<commit_before>#include "stdafx.h"
#include "extension.h"
#include "iarchive.h"
#include "oarchive.h"
#include "iobject.h"
#include "oobject.h"
#include "iproperty.h"
#include "oproperty.h"
#include "icompoundproperty.h"
#include "ocompoundproperty.h"
#include "ixformproperty.h"
#include "oxformproperty.h"
#include "itimesampling.h"
#include "otimesampling.h"

std::string resolvePath_Internal(std::string path)
{
	return path;
}

static PyObject * extension_error = NULL;
PyObject * getError() { return extension_error; }

static PyObject* extension_getVersion(PyObject* self, PyObject* args)
{
   return Py_BuildValue("i", ABCPY_VERSION_CURRENT);
}

static PyObject* extension_getAlembicVersion(PyObject* self, PyObject* args)
{
   return Py_BuildValue("i", ALEMBIC_VERSION);
}

static const char* OBJ_TYPES[] =
{
   "AbcGeom_Xform_v1",
   "AbcGeom_Camera_v1",
   "AbcGeom_PolyMesh_v3",
   "AbcGeom_SubD_v3",
   "AbcGeom_Curve_v1",
   "AbcGeom_Points_v1",
   "AbcGeom_FaceSet_v1",

   0
};

static PyObject* extension_getObjectTypes(PyObject *self)
{
   PyObject *_list = PyList_New(0);
   const char **types = OBJ_TYPES;
   while (*types)
   {
      PyList_Append(_list, Py_BuildValue("s", *types));
      ++types;
   }
   return _list;
}

static const char* PRO_TYPES[] =
{
   "bool",
   "uchar",   "char",
   "uint16",   "int16",
   "uint32",   "int32",
   "uint64",   "int64",
   "half",
   "float",
   "double",
   "string",   "wstring",
   "vector2s", "vector2i", "vector2f", "vector2d", "vector3s", "vector3i", "vector3f", "vector3d",
   "point2s",  "point2i",  "point2f",  "point2d",  "point3s",  "point3i",  "point3f",  "point3d",
   "box2s",    "box2i",    "box2f",    "box2d",    "box3s",    "box3i",    "box3f",    "box3d",
   "matrix3f", "matrix3d", "matrix4f", "matrix4d",
   "color3h",  "color3f",  "color3c",  "color4h",  "color4f",  "color4c",
   "normal2f", "normal2d", "normal3f", "normal3d",

   0
};

static PyObject* extension_getPropertyTypes(PyObject *self)
{
   PyObject *_list = PyList_New(0);
   const char **types = PRO_TYPES;
   while (*types)
   {
      PyList_Append(_list, Py_BuildValue("s", *types));
      ++types;
   }
   return _list;
}

static PyMethodDef extension_methods[] =
{
   {"getVersion", (PyCFunction)extension_getVersion, METH_NOARGS, "Returns the version number of the alembic extension"},
   {"getAlembicVersion", (PyCFunction)extension_getVersion, METH_NOARGS, "Returns the Alembic.IO version number used for the extension"},
   {"getIArchive", (PyCFunction)iArchive_new, METH_VARARGS, "Takes in a filename to an Alembic file, and returns an iArchive linked to that file."},
   {"getOArchive", (PyCFunction)oArchive_new, METH_VARARGS, "Takes in a filename to create an Alembic file at, and return an oArchive linked to that file."},

   {"getObjectTypes", (PyCFunction)extension_getObjectTypes, METH_NOARGS, "Returns a list of all valid object types. The same one listed in Appendix A."},
   {"getPropertyTypes", (PyCFunction)extension_getPropertyTypes, METH_NOARGS, "Returns a list of all valid property types. The same one listed in Appendix B."},
   {NULL, NULL}
};

static PyMethodDef unlicensed_extension_methods[] = {
   {NULL, NULL}
};

bool register_object(PyObject *module, PyTypeObject &type_object, const char *object_name)
{
  if (PyType_Ready(&type_object) < 0)
    return false;

  Py_INCREF(&type_object);
  PyModule_AddObject(module, object_name, (PyObject*)&type_object);
  Py_DECREF(&type_object);
  return true;
}

EXTENSION_CALLBACK init_ExocortexAlembicPython(void)
{
   PyObject * m = Py_InitModule3("_ExocortexAlembicPython", extension_methods, "This is the core extension module. It provides access to input as well as output archive objects.");
   PyObject * d = PyModule_GetDict(m);

   register_object_iArchive(m);
   register_object_iObject(m);
   register_object_iProperty(m);
   register_object_iCompoundProperty(m);
   register_object_iXformProperty(m);
   register_object_iTimeSampling(m);

   register_object_oArchive(m);
   register_object_oObject(m);
   register_object_oProperty(m);
   register_object_oCompoundProperty(m);
   register_object_oXformProperty(m);
   register_object_oTimeSampling(m);

   extension_error = PyErr_NewException("ExocortexAlembicPython.error", NULL, NULL);
   PyDict_SetItemString(d, "error", extension_error);
}

<commit_msg>resolvePath_Internal<commit_after>#include "stdafx.h"
#include "extension.h"
#include "iarchive.h"
#include "oarchive.h"
#include "iobject.h"
#include "oobject.h"
#include "iproperty.h"
#include "oproperty.h"
#include "icompoundproperty.h"
#include "ocompoundproperty.h"
#include "ixformproperty.h"
#include "oxformproperty.h"
#include "itimesampling.h"
#include "otimesampling.h"

std::string resolvePath_Internal(std::string const& path)
{
	return path;
}

static PyObject * extension_error = NULL;
PyObject * getError() { return extension_error; }

static PyObject* extension_getVersion(PyObject* self, PyObject* args)
{
   return Py_BuildValue("i", ABCPY_VERSION_CURRENT);
}

static PyObject* extension_getAlembicVersion(PyObject* self, PyObject* args)
{
   return Py_BuildValue("i", ALEMBIC_VERSION);
}

static const char* OBJ_TYPES[] =
{
   "AbcGeom_Xform_v1",
   "AbcGeom_Camera_v1",
   "AbcGeom_PolyMesh_v3",
   "AbcGeom_SubD_v3",
   "AbcGeom_Curve_v1",
   "AbcGeom_Points_v1",
   "AbcGeom_FaceSet_v1",

   0
};

static PyObject* extension_getObjectTypes(PyObject *self)
{
   PyObject *_list = PyList_New(0);
   const char **types = OBJ_TYPES;
   while (*types)
   {
      PyList_Append(_list, Py_BuildValue("s", *types));
      ++types;
   }
   return _list;
}

static const char* PRO_TYPES[] =
{
   "bool",
   "uchar",   "char",
   "uint16",   "int16",
   "uint32",   "int32",
   "uint64",   "int64",
   "half",
   "float",
   "double",
   "string",   "wstring",
   "vector2s", "vector2i", "vector2f", "vector2d", "vector3s", "vector3i", "vector3f", "vector3d",
   "point2s",  "point2i",  "point2f",  "point2d",  "point3s",  "point3i",  "point3f",  "point3d",
   "box2s",    "box2i",    "box2f",    "box2d",    "box3s",    "box3i",    "box3f",    "box3d",
   "matrix3f", "matrix3d", "matrix4f", "matrix4d",
   "color3h",  "color3f",  "color3c",  "color4h",  "color4f",  "color4c",
   "normal2f", "normal2d", "normal3f", "normal3d",

   0
};

static PyObject* extension_getPropertyTypes(PyObject *self)
{
   PyObject *_list = PyList_New(0);
   const char **types = PRO_TYPES;
   while (*types)
   {
      PyList_Append(_list, Py_BuildValue("s", *types));
      ++types;
   }
   return _list;
}

static PyMethodDef extension_methods[] =
{
   {"getVersion", (PyCFunction)extension_getVersion, METH_NOARGS, "Returns the version number of the alembic extension"},
   {"getAlembicVersion", (PyCFunction)extension_getVersion, METH_NOARGS, "Returns the Alembic.IO version number used for the extension"},
   {"getIArchive", (PyCFunction)iArchive_new, METH_VARARGS, "Takes in a filename to an Alembic file, and returns an iArchive linked to that file."},
   {"getOArchive", (PyCFunction)oArchive_new, METH_VARARGS, "Takes in a filename to create an Alembic file at, and return an oArchive linked to that file."},

   {"getObjectTypes", (PyCFunction)extension_getObjectTypes, METH_NOARGS, "Returns a list of all valid object types. The same one listed in Appendix A."},
   {"getPropertyTypes", (PyCFunction)extension_getPropertyTypes, METH_NOARGS, "Returns a list of all valid property types. The same one listed in Appendix B."},
   {NULL, NULL}
};

static PyMethodDef unlicensed_extension_methods[] = {
   {NULL, NULL}
};

bool register_object(PyObject *module, PyTypeObject &type_object, const char *object_name)
{
  if (PyType_Ready(&type_object) < 0)
    return false;

  Py_INCREF(&type_object);
  PyModule_AddObject(module, object_name, (PyObject*)&type_object);
  Py_DECREF(&type_object);
  return true;
}

EXTENSION_CALLBACK init_ExocortexAlembicPython(void)
{
   PyObject * m = Py_InitModule3("_ExocortexAlembicPython", extension_methods, "This is the core extension module. It provides access to input as well as output archive objects.");
   PyObject * d = PyModule_GetDict(m);

   register_object_iArchive(m);
   register_object_iObject(m);
   register_object_iProperty(m);
   register_object_iCompoundProperty(m);
   register_object_iXformProperty(m);
   register_object_iTimeSampling(m);

   register_object_oArchive(m);
   register_object_oObject(m);
   register_object_oProperty(m);
   register_object_oCompoundProperty(m);
   register_object_oXformProperty(m);
   register_object_oTimeSampling(m);

   extension_error = PyErr_NewException("ExocortexAlembicPython.error", NULL, NULL);
   PyDict_SetItemString(d, "error", extension_error);
}

<|endoftext|>


<commit_before>#include <stdexcept>
#include <vector>
#include <windows.h>
#include <string>
#include <algorithm>

#include "Main.h"
#include "GestureClass.h"
#include "Gesture.h"
#include "Frame.h"
#include "Keypress.h"
#include "Console.h"
#include "Filewriter.h"
#include "Filereader.h"
#include "Model.h"

void Model::updateCountDown()
{
	if (!countDownInitiated)
	{
		countDownInitiated = true;
		countDownRef = Clock::now();
		//printf("Get ready to record\n");
		countDown = 4;
		updateUI = true;
	}
	else
	{
		auto t2 = Clock::now();
		long time = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - countDownRef).count();

		if (time >= 1000 && countDown > 3)
		{
			//printf("3 after %ld \n", time);
			--countDown;
			updateUI = true;				//the UI will update it's state based on the countDown parameter
		}
		else if (time >= 2000 && countDown > 2)
		{
			//printf("2 after %ld \n", time);
			--countDown;
			updateUI = true;				//the UI will update it's state based on the countDown parameter
		}
		else if (time >= 3000 && countDown > 1)
		{
			//printf("1 after %ld \n", time);
			--countDown;
			updateUI = true;				//the UI will update it's state based on the countDown parameter
		}
		else if ((time >= 4000 && countDown > 0))
		{

			//printf("GO after %ld \n", time);
			--countDown;
			framesBuffer.clear();
			recording = true;
			//refresh = false;
			updateUI = true;				//the UI will update it's state based on the countDown parameter
											//countDownInitiated = false;

		}
		else if (recording == false && countDown == 0)
		{
			//printf(" recording is done \n");
			--countDown;

			countDownRef = Clock::now();

			updateUI = true;				//the UI will update it's state based on the countDown parameter
		}
		else if (time >= 500 && countDown == -1)
		{
			//printf(" delete screen \n");
			--countDown;

			refresh = false;
			countDownInitiated = false;
			updateUI = true;
		}

	}
}

Model::Model()
{
	Filereader::loadAllData(&projects, &gestureClasses);
	if (projects.empty())		//If no project is loaded, else do nothing.
	{
		projects.push_back(std::make_shared<Project>());
	}
	activeProject = projects.back();
}

Model::~Model()
{
}

void Model::setView(std::shared_ptr<UI> v)
{
	view = v;
}

std::shared_ptr<Project> Model::getProject()
{
	return activeProject;
}

void Model::train()
{
	activeProject->setSVMModel(*(SVMInterface::train(activeProject->getProjectMap())));
	Console::print("SVM trained");
	Filewriter::save(activeProject);
	Console::printsl(" -- Project saved");
	activeProject->setLongestGestureSize();
}

int Model::test(Frame & frame)
{
	return SVMInterface::test(activeProject->getSVMModel(), frame);
}

void Model::setActiveLabel(int label)
{
	activeGestureClassLabel = label;
}

void Model::setRefresh(bool refresh)
{
	this->refresh = refresh;
}

bool Model::getRefresh()
{
	return refresh;
}

void Model::setPredict(bool refresh)
{
	this->predict = refresh;
}

void Model::setTrained(bool train)
{
	trained = train;
}

void Model::setRecording(bool record)
{
	recording = record;
}

bool Model::getRecording()
{
	return recording;
}

void Model::addActionToActive(WORD keycode, bool hold)
{
	activeProject->addAction(activeGestureClassLabel, keycode, hold);
}

void Model::addGesture(int label, std::shared_ptr<Gesture> gesture)
{
	if (activeProject->containsLabel(label))
	{
		activeProject->addGesture(label, gesture);
	}
	else
	{
		gestureClasses.push_back(std::make_shared<GestureClass>(gesture));
		activeProject->addNew(label, gestureClasses.back());
	}
	updateUI = true;
}

std::vector<Frame> Model::getRelevantFramesFromBuffer(int offset)
{
	return std::vector<Frame>(framesBuffer.begin(), framesBuffer.end() - offset);
}

void Model::addToLabelsBuffer(int label)
{
	labelsBuffer.push_back(label);

	if (labelsBuffer.size() > activeProject->getLongestGestureSize())
	{
		resizeLabelsBuffer();
	}
}

void Model::resizeLabelsBuffer()
{
	labelsBuffer = std::vector<int>(labelsBuffer.end() - activeProject->getLongestGestureSize(), labelsBuffer.end());
}

bool Model::isGestureExecuted(std::shared_ptr<Gesture> & gesture, int posInBuffer, int recursiveCounter)
{
	int labelOrderPosition = SVMInterface::NB_OF_LABEL_DIVISIONS - recursiveCounter;
	int labelToCheck = gesture->getLabelOrder().at(labelOrderPosition);

	for (int i = posInBuffer; i >= 0; i--)
	{
		if (labelsBuffer.at(i) == labelToCheck)
		{
			if (labelOrderPosition <= 0)
			{
				return true;
			}
			return isGestureExecuted(gesture, i - 1, recursiveCounter + 1);
		}
	}

	return false;
}

void Model::predictAndExecute(int label)
{
	/*
	//Find out what base label the given label belongs to.
	int baseLabel = -1;
	if (activeProject->containsLabel(label))
	{
		baseLabel = label;
	}
	else
	{
		for (int i = SVMInterface::NB_OF_LABEL_DIVISIONS; i > 0; i--)
		{
			if (activeProject->containsLabel(label - i))
			{
				baseLabel = label - i;
				break;
			}
		}
	}

	if (isGestureExecuted(label, labelsBuffer.size() - 1, 1, 0))
	{
		previousPredictedLabel = predictedLabel;
		predictedLabel = baseLabel;

		Console::print("Predicted label: ");
		Console::printsl(predictedLabel);
		labelsBuffer.clear();

		if (previousPredictedLabel < 0)
		{
			activeProject->activate(predictedLabel);
		}
		else if (previousPredictedLabel != predictedLabel)
		{
			activeProject->deactivate(previousPredictedLabel);
			activeProject->activate(predictedLabel);
		}
		else if (previousPredictedLabel == predictedLabel)
		{
			activeProject->activate(predictedLabel);
		}
	}
	*/

	int executedLabel = -1;
	for (const auto & keyValue : activeProject->getProjectMap())
	{
		for (std::shared_ptr<Gesture> gesture : keyValue.second.first->getGestures())
		{
			if (isGestureExecuted(gesture, labelsBuffer.size() - 1, 1))
			{
				executedLabel = keyValue.first;
			}
		}
	}

	if (executedLabel != -1)
	{
		previousPredictedLabel = predictedLabel;
		predictedLabel = executedLabel;

		Console::print("Predicted label: ");
		Console::printsl(predictedLabel);

		labelsBuffer.clear();
		labelsBuffer.push_back(activeProject->getProjectMap().find(1)->second.first->getGestures().front()->getLabelOrder().front());
		Console::print("Added label: ");
		Console::print(activeProject->getProjectMap().find(1)->second.first->getGestures().front()->getLabelOrder().front());

		if (previousPredictedLabel < 0)
		{
			activeProject->activate(predictedLabel);
		}
		else if (previousPredictedLabel != predictedLabel)
		{
			activeProject->deactivate(previousPredictedLabel);
			activeProject->activate(predictedLabel);
		}
		else if (previousPredictedLabel == predictedLabel)
		{
			activeProject->activate(predictedLabel);
		}
	}
}

std::shared_ptr<GestureClass> Model::getGestureClassByID(const int & ID)
{
	for (int i = 0; i < gestureClasses.size(); ++i)
	{
		if (gestureClasses[i] != nullptr)
		{
			if (gestureClasses[i]->getGestureClassID() == ID)
				return gestureClasses[i];
		}
	}

	//give the last gestureClass back
	//return gestureClasses[gestureClasses.size()-1];
	return nullptr;
}

void Model::displayFrames()
{
	if (view->checkResource())
	{
		view->drawFrames(relFrames, absFrames);
	}

	relFrames.clear();
	absFrames.clear();
}

void Model::processBody(INT64 nTime, int nBodyCount, IBody ** ppBodies)
{
	//Go through all the bodies that are being seen now. If a body is tracked, its frame is made and added to the frames vector
	for (int i = 0; i < nBodyCount; ++i)
	{
		pBody = ppBodies[i];
		if (pBody)
		{
			BOOLEAN bTracked = false;
			HRESULT hr = pBody->get_IsTracked(&bTracked);

			if (currentActiveBody == -1 && SUCCEEDED(hr) && bTracked)	//No body is tracked at the moment
			{
				currentActiveBody = i;
			}

			if (SUCCEEDED(hr) && bTracked && i == currentActiveBody)
			{
				Frame relFrame(pBody);					//Create a frame of every tracked body
				Frame absFrame(pBody, false);

				relFrames.push_back(relFrame);
				absFrames.push_back(absFrame);

				if (recording)
				{
					recordGesture(relFrame);
					break;
				}

				framesBuffer.push_back(relFrame);

				if (refresh && !predict)				//The measure button was pressed last
				{
					updateCountDown();
				}

				if (predict)
				{
					if (!trained)						//If the model is not yet trained, train it
					{
						train();
						trained = true;
					}
					int label = SVMInterface::test(activeProject->getSVMModel(), relFrame);
					addToLabelsBuffer(label);
					predictAndExecute(label);
					view->setPredictedLabel(label);
				}
			}
			else if (i == currentActiveBody)			//If the current tracked body is lost for this frame
			{
				bodyLostCounter++;						//Increment the lostBodyCounter
				if (bodyLostCounter > BODY_LOST_LIMIT)	//If the limit is reached, reset the currentActiveBody
				{
					currentActiveBody = -1;
					bodyLostCounter = 0;
				}
			}
		}
	}

	if (updateUI)
	{
		view->updateHitboxes();
		updateUI = false;
	}

	displayFrames();
}

void Model::recordGesture(Frame & frame)
{
	if (!initialized)
	{
		frameNeutral.setFrame(frame);
		initialized = true;
		Console::print("Initialized recording");
	}

	//relFrames.push_back(frame);
	framesBuffer.push_back(frame);

	if (!startedMoving)
	{
		if (! frame.equals(frameNeutral))
		{
			Console::print("Motion detected -- start recording frames");
			startedMoving = true;
			if (framesBuffer.size() > 20)
			{
				std::vector<Frame> latestFrames = getRelevantFramesFromBuffer(10);
				framesBuffer.clear();
				for (Frame frame : latestFrames)
				{
					framesBuffer.push_back(frame);
				}
			}
		}
		else if (framesBuffer.size() > NOT_MOVING_FRAME_DELAY)
		{
			Console::print("Standing still -- posture recorded");
			addRecordedGesture();
		}
		else
		{
			return;
		}
	}

	if (framesBuffer.size() > NOT_MOVING_FRAME_DELAY &&
		framesBuffer.back().equals(framesBuffer.at(framesBuffer.size() - NOT_MOVING_FRAME_DELAY)) &&
		framesBuffer.back().equals(framesBuffer.at(framesBuffer.size() - NOT_MOVING_FRAME_DELAY/2)))
	{
		addRecordedGesture();
	}
}

bool Model::getCountDownInit()
{
	return countDownInitiated;
}

int Model::getCountDown()
{
	return countDown;
}

void Model::setUpdatUI(bool update)
{
	updateUI = update;
}

bool Model::getUpdateUI()
{
	return updateUI;
}

void Model::addRecordedGesture()
{
	std::shared_ptr<Gesture> gesture = std::make_shared<Gesture>( getRelevantFramesFromBuffer(NOT_MOVING_FRAME_DELAY-20) );
	addGesture(activeGestureClassLabel, gesture);
	recording = false;
	initialized = false;
	startedMoving = false;
	framesBuffer.clear();
	Console::print("Recording stopped");
}
<commit_msg>mdoel<commit_after>#include <stdexcept>
#include <vector>
#include <windows.h>
#include <string>
#include <algorithm>

#include "Main.h"
#include "GestureClass.h"
#include "Gesture.h"
#include "Frame.h"
#include "Keypress.h"
#include "Console.h"
#include "Filewriter.h"
#include "Filereader.h"
#include "Model.h"

void Model::updateCountDown()
{
	if (!countDownInitiated)
	{
		countDownInitiated = true;
		countDownRef = Clock::now();
		//printf("Get ready to record\n");
		countDown = 4;
		updateUI = true;
	}
	else
	{
		auto t2 = Clock::now();
		long time = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - countDownRef).count();

		if (time >= 1000 && countDown > 3)
		{
			//printf("3 after %ld \n", time);
			--countDown;
			updateUI = true;				//the UI will update it's state based on the countDown parameter
		}
		else if (time >= 2000 && countDown > 2)
		{
			//printf("2 after %ld \n", time);
			--countDown;
			updateUI = true;				//the UI will update it's state based on the countDown parameter
		}
		else if (time >= 3000 && countDown > 1)
		{
			//printf("1 after %ld \n", time);
			--countDown;
			updateUI = true;				//the UI will update it's state based on the countDown parameter
		}
		else if ((time >= 4000 && countDown > 0))
		{

			//printf("GO after %ld \n", time);
			--countDown;
			framesBuffer.clear();
			recording = true;
			//refresh = false;
			updateUI = true;				//the UI will update it's state based on the countDown parameter
											//countDownInitiated = false;

		}
		else if (recording == false && countDown == 0)
		{
			//printf(" recording is done \n");
			--countDown;

			countDownRef = Clock::now();

			updateUI = true;				//the UI will update it's state based on the countDown parameter
		}
		else if (time >= 500 && countDown == -1)
		{
			//printf(" delete screen \n");
			--countDown;

			refresh = false;
			countDownInitiated = false;
			updateUI = true;
		}

	}
}

Model::Model()
{
	Filereader::loadAllData(&projects, &gestureClasses);
	if (projects.empty())		//If no project is loaded, else do nothing.
	{
		projects.push_back(std::make_shared<Project>());
	}
	activeProject = projects.back();
}

Model::~Model()
{
}

void Model::setView(std::shared_ptr<UI> v)
{
	view = v;
}

std::shared_ptr<Project> Model::getProject()
{
	return activeProject;
}

void Model::train()
{
	activeProject->setSVMModel(*(SVMInterface::train(activeProject->getProjectMap())));
	Console::print("SVM trained");
	Filewriter::save(activeProject);
	Console::printsl(" -- Project saved");
	activeProject->setLongestGestureSize();
}

int Model::test(Frame & frame)
{
	return SVMInterface::test(activeProject->getSVMModel(), frame);
}

void Model::setActiveLabel(int label)
{
	activeGestureClassLabel = label;
}

void Model::setRefresh(bool refresh)
{
	this->refresh = refresh;
}

bool Model::getRefresh()
{
	return refresh;
}

void Model::setPredict(bool refresh)
{
	this->predict = refresh;
}

void Model::setTrained(bool train)
{
	trained = train;
}

void Model::setRecording(bool record)
{
	recording = record;
}

bool Model::getRecording()
{
	return recording;
}

void Model::addActionToActive(WORD keycode, bool hold)
{
	activeProject->addAction(activeGestureClassLabel, keycode, hold);
}

void Model::addGesture(int label, std::shared_ptr<Gesture> gesture)
{
	if (activeProject->containsLabel(label))
	{
		activeProject->addGesture(label, gesture);
	}
	else
	{
		gestureClasses.push_back(std::make_shared<GestureClass>(gesture));
		activeProject->addNew(label, gestureClasses.back());
	}
	updateUI = true;
}

std::vector<Frame> Model::getRelevantFramesFromBuffer(int offset)
{
	return std::vector<Frame>(framesBuffer.begin(), framesBuffer.end() - offset);
}

void Model::addToLabelsBuffer(int label)
{
	labelsBuffer.push_back(label);

	if (labelsBuffer.size() > activeProject->getLongestGestureSize())
	{
		resizeLabelsBuffer();
	}
}

void Model::resizeLabelsBuffer()
{
	labelsBuffer = std::vector<int>(labelsBuffer.end() - activeProject->getLongestGestureSize(), labelsBuffer.end());
}

bool Model::isGestureExecuted(std::shared_ptr<Gesture> & gesture, int posInBuffer, int recursiveCounter)
{
	int labelOrderPosition = SVMInterface::NB_OF_LABEL_DIVISIONS - recursiveCounter;
	int labelToCheck = gesture->getLabelOrder().at(labelOrderPosition);

	for (int i = posInBuffer; i >= 0; i--)
	{
		if (labelsBuffer.at(i) == labelToCheck)
		{
			if (labelOrderPosition <= 0)
			{
				return true;
			}
			return isGestureExecuted(gesture, i - 1, recursiveCounter + 1);
		}
	}

	return false;
}

void Model::predictAndExecute(int label)
{
	/*
	//Find out what base label the given label belongs to.
	int baseLabel = -1;
	if (activeProject->containsLabel(label))
	{
		baseLabel = label;
	}
	else
	{
		for (int i = SVMInterface::NB_OF_LABEL_DIVISIONS; i > 0; i--)
		{
			if (activeProject->containsLabel(label - i))
			{
				baseLabel = label - i;
				break;
			}
		}
	}

	if (isGestureExecuted(label, labelsBuffer.size() - 1, 1, 0))
	{
		previousPredictedLabel = predictedLabel;
		predictedLabel = baseLabel;

		Console::print("Predicted label: ");
		Console::printsl(predictedLabel);
		labelsBuffer.clear();

		if (previousPredictedLabel < 0)
		{
			activeProject->activate(predictedLabel);
		}
		else if (previousPredictedLabel != predictedLabel)
		{
			activeProject->deactivate(previousPredictedLabel);
			activeProject->activate(predictedLabel);
		}
		else if (previousPredictedLabel == predictedLabel)
		{
			activeProject->activate(predictedLabel);
		}
	}
	*/

	int executedLabel = -1;
	for (const auto & keyValue : activeProject->getProjectMap())
	{
		for (std::shared_ptr<Gesture> gesture : keyValue.second.first->getGestures())
		{
			if (isGestureExecuted(gesture, labelsBuffer.size() - 1, 1))
			{
				executedLabel = keyValue.first;
			}
		}
	}

	if (executedLabel != -1)
	{
		previousPredictedLabel = predictedLabel;
		predictedLabel = executedLabel;

		Console::print("Predicted label: ");
		Console::printsl(predictedLabel);

		labelsBuffer.clear();
		labelsBuffer.push_back(activeProject->getProjectMap().find(10)->second.first->getGestures().front()->getLabelOrder().front());
		printf("Added label: ");
		printf("%d",activeProject->getProjectMap().find(10)->second.first->getGestures().front()->getLabelOrder().front());

		if (previousPredictedLabel < 0)
		{
			activeProject->activate(predictedLabel);
		}
		else if (previousPredictedLabel != predictedLabel)
		{
			activeProject->deactivate(previousPredictedLabel);
			activeProject->activate(predictedLabel);
		}
		else if (previousPredictedLabel == predictedLabel)
		{
			activeProject->activate(predictedLabel);
		}
	}
}

std::shared_ptr<GestureClass> Model::getGestureClassByID(const int & ID)
{
	for (int i = 0; i < gestureClasses.size(); ++i)
	{
		if (gestureClasses[i] != nullptr)
		{
			if (gestureClasses[i]->getGestureClassID() == ID)
				return gestureClasses[i];
		}
	}

	//give the last gestureClass back
	//return gestureClasses[gestureClasses.size()-1];
	return nullptr;
}

void Model::displayFrames()
{
	if (view->checkResource())
	{
		view->drawFrames(relFrames, absFrames);
	}

	relFrames.clear();
	absFrames.clear();
}

void Model::processBody(INT64 nTime, int nBodyCount, IBody ** ppBodies)
{
	//Go through all the bodies that are being seen now. If a body is tracked, its frame is made and added to the frames vector
	for (int i = 0; i < nBodyCount; ++i)
	{
		pBody = ppBodies[i];
		if (pBody)
		{
			BOOLEAN bTracked = false;
			HRESULT hr = pBody->get_IsTracked(&bTracked);

			if (currentActiveBody == -1 && SUCCEEDED(hr) && bTracked)	//No body is tracked at the moment
			{
				currentActiveBody = i;
			}

			if (SUCCEEDED(hr) && bTracked && i == currentActiveBody)
			{
				Frame relFrame(pBody);					//Create a frame of every tracked body
				Frame absFrame(pBody, false);

				relFrames.push_back(relFrame);
				absFrames.push_back(absFrame);

				if (recording)
				{
					recordGesture(relFrame);
					break;
				}

				framesBuffer.push_back(relFrame);

				if (refresh && !predict)				//The measure button was pressed last
				{
					updateCountDown();
				}

				if (predict)
				{
					if (!trained)						//If the model is not yet trained, train it
					{
						train();
						trained = true;
					}
					int label = SVMInterface::test(activeProject->getSVMModel(), relFrame);
					addToLabelsBuffer(label);
					predictAndExecute(label);
					view->setPredictedLabel(label);
				}
			}
			else if (i == currentActiveBody)			//If the current tracked body is lost for this frame
			{
				bodyLostCounter++;						//Increment the lostBodyCounter
				if (bodyLostCounter > BODY_LOST_LIMIT)	//If the limit is reached, reset the currentActiveBody
				{
					currentActiveBody = -1;
					bodyLostCounter = 0;
				}
			}
		}
	}

	if (updateUI)
	{
		view->updateHitboxes();
		updateUI = false;
	}

	displayFrames();
}

void Model::recordGesture(Frame & frame)
{
	if (!initialized)
	{
		frameNeutral.setFrame(frame);
		initialized = true;
		Console::print("Initialized recording");
	}

	//relFrames.push_back(frame);
	framesBuffer.push_back(frame);

	if (!startedMoving)
	{
		if (! frame.equals(frameNeutral))
		{
			Console::print("Motion detected -- start recording frames");
			startedMoving = true;
			if (framesBuffer.size() > 20)
			{
				std::vector<Frame> latestFrames = getRelevantFramesFromBuffer(10);
				framesBuffer.clear();
				for (Frame frame : latestFrames)
				{
					framesBuffer.push_back(frame);
				}
			}
		}
		else if (framesBuffer.size() > NOT_MOVING_FRAME_DELAY)
		{
			Console::print("Standing still -- posture recorded");
			addRecordedGesture();
		}
		else
		{
			return;
		}
	}

	if (framesBuffer.size() > NOT_MOVING_FRAME_DELAY &&
		framesBuffer.back().equals(framesBuffer.at(framesBuffer.size() - NOT_MOVING_FRAME_DELAY)) &&
		framesBuffer.back().equals(framesBuffer.at(framesBuffer.size() - NOT_MOVING_FRAME_DELAY/2)))
	{
		addRecordedGesture();
	}
}

bool Model::getCountDownInit()
{
	return countDownInitiated;
}

int Model::getCountDown()
{
	return countDown;
}

void Model::setUpdatUI(bool update)
{
	updateUI = update;
}

bool Model::getUpdateUI()
{
	return updateUI;
}

void Model::addRecordedGesture()
{
	std::shared_ptr<Gesture> gesture = std::make_shared<Gesture>( getRelevantFramesFromBuffer(NOT_MOVING_FRAME_DELAY-20) );
	addGesture(activeGestureClassLabel, gesture);
	recording = false;
	initialized = false;
	startedMoving = false;
	framesBuffer.clear();
	Console::print("Recording stopped");
}
<|endoftext|>


<commit_before><commit_msg>Create Minimum Expression.cpp<commit_after><|endoftext|>


<commit_before>// source changed by mrn@paus.ch/ max rheiner
// original source: henryj@paradise.net.nz

#include <iostream>
#include <stdlib.h> // exit()

#include <GL/glut.h>

#ifdef USE_STD_NAMESPACE
using namespace std;
#endif

#include "FTGLOutlineFont.h"
#include "FTGLPolygonFont.h"
#include "FTGLBitmapFont.h"
#ifndef FTGL_NO_TEXTURE_FONTS
#include "FTGLTextureFont.h"
#endif
#include "FTGLPixmapFont.h"

static FTFont* fonts[5];
static int width;
static int height;

#ifdef __linux__
const char* DEFAULT_FONT = "/usr/share/fonts/truetype/arial.ttf";
#else
#ifdef __APPLE_CC__
const char* DEFAULT_FONT = "/Users/henry/Development/PROJECTS/FTGL/ftglcvs/FTGL/demo/arial.ttf";
#else
#ifdef WIN32
const char* DEFAULT_FONT = "C:\\WINNT\\Fonts\\arial.ttf";
#else
const char* DEFAULT_FONT = "arial.ttf";
#endif
#endif
#endif

int file_exists( const char * filename );

void
my_init( const char* font_filename )
{
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    fonts[0] = new FTGLOutlineFont;
    fonts[1] = new FTGLPolygonFont;
#ifndef FTGL_NO_TEXTURE_FONTS
    fonts[2] = new FTGLTextureFont;
#endif
    fonts[3] = new FTGLBitmapFont;
    fonts[4] = new FTGLPixmapFont;
    for (int i=0; i< 5; i++) {
#ifdef FTGL_NO_TEXTURE_FONTS
    if (i == 2) continue;
#endif
        if (!fonts[i]->Open(font_filename)) {
            cerr << "ERROR: Unable to open file " << font_filename << "\n";
        }
        else {
			cout << "Reading font " << i << " from " << font_filename << endl;

            int point_size = 24;
            if (!fonts[i]->FaceSize(point_size)) {
                cerr << "ERROR: Unable to set font face size " << point_size << "\n";
            }

            // Try to load AFM font metrics
            const char* ext = strrchr(font_filename, '.');
            if (ext && !strcmp(ext, ".pfb"))
            {
            char *metrics = new char[strlen(font_filename)];
            strncpy(metrics, font_filename, ext - font_filename);
            strcpy(metrics + (ext - font_filename), ".afm");
            if (file_exists(metrics))
              {
              cout << "Attaching font metrics from " << metrics << endl;
              fonts[i]->Attach(metrics);
              }
            }
        }
    }
}

static void
do_ortho()
{
  int w;
  int h;
  GLdouble size;
  GLdouble aspect;

  w = width;
  h = height;
  aspect = (GLdouble)w / (GLdouble)h;

  // Use the whole window.
  glViewport(0, 0, w, h);

  // We are going to do some 2-D orthographic drawing.
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  size = (GLdouble)((w >= h) ? w : h) / 2.0;
  if (w <= h) {
    aspect = (GLdouble)h/(GLdouble)w;
    glOrtho(-size, size, -size*aspect, size*aspect,
            -100000.0, 100000.0);
  }
  else {
    aspect = (GLdouble)w/(GLdouble)h;
    glOrtho(-size*aspect, size*aspect, -size, size,
            -100000.0, 100000.0);
  }

  // Make the world and window coordinates coincide so that 1.0 in
  // model space equals one pixel in window space.
  glScaled(aspect, aspect, 1.0);

   // Now determine where to draw things.
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
}

void
my_reshape(int w, int h)
{
  width = w;
  height = h;

  do_ortho( );
}

void
my_handle_key(unsigned char key, int x, int y)
{
   switch (key) {

	   //!!ELLERS
   case 'q':   // Esc or 'q' Quits the program.
   case 27:
	   {
       for (int i=0; i<5; i++) {
#ifdef FTGL_NO_TEXTURE_FONTS
       if (i == 2) continue;
#endif
           if (fonts[i]) {
               delete fonts[i];
               fonts[i] = 0;
           }
       }
      exit(1);
	   }
      break;

   default:
      break;
   }
}

void
draw_scene()
{
   /* Set up some strings with the characters to draw. */
   unsigned int count = 0;
   char string[8][256];
   int i;
   for (i=1; i < 32; i++) { /* Skip zero - it's the null terminator! */
      string[0][count] = i;
      count++;
   }
   string[0][count] = '\0';

   count = 0;
   for (i=32; i < 64; i++) {
      string[1][count] = i;
      count++;
   }
   string[1][count] = '\0';

   count = 0;
   for (i=64; i < 96; i++) {
      string[2][count] = i;
      count++;
   }
   string[2][count] = '\0';

   count = 0;
   for (i=96; i < 128; i++) {
      string[3][count] = i;
      count++;
   }
   string[3][count] = '\0';

   count = 0;
   for (i=128; i < 160; i++) {
      string[4][count] = i;
      count++;
   }
   string[4][count] = '\0';

   count = 0;
   for (i=160; i < 192; i++) {
      string[5][count] = i;
      count++;
   }
   string[5][count] = '\0';

   count = 0;
   for (i=192; i < 224; i++) {
      string[6][count] = i;
      count++;
   }
   string[6][count] = '\0';

   count = 0;
   for (i=224; i < 256; i++) {
      string[7][count] = i;
      count++;
   }
   string[7][count] = '\0';

   glColor3f(1.0, 1.0, 1.0);

   for (int font = 0; font < 5; font++) {
       GLfloat x = -250.0;
       GLfloat y;
       GLfloat yild = 20.0;
       for (int j=0; j<4; j++) {
           y = 275.0-font*120.0-j*yild;
           if (font >= 3) {
               glRasterPos2f(x, y);
               fonts[font]->render(string[j]);
           }
           else {
#ifdef FTGL_NO_TEXTURE_FONTS
           if (font == 2) continue;
#endif
               if (font == 2) {
                   glEnable(GL_TEXTURE_2D);
                   glEnable(GL_BLEND);
                   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
               }
               glPushMatrix(); {
                   glTranslatef(x, y, 0.0);
                   fonts[font]->render(string[j]);
               } glPopMatrix();
               if (font == 2) {
                   glDisable(GL_TEXTURE_2D);
                   glDisable(GL_BLEND);
               }
           }
       }
   }
}

void
my_display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);

    draw_scene();

    glutSwapBuffers();
}

int
file_exists( const char * filename )
{
	FILE * fp = fopen( filename, "r" );

	if ( fp == NULL )
	{
		// That fopen failed does _not_ definitely mean the file isn't there
		// but for now this is ok
		return 0;
	}
	fclose( fp );
	return 1;
}

void
usage( const char * program )
{
	cerr << "Usage: " << program << " <filename.ttf>\n" << endl;
}

int
main(int argc, char **argv)
{
	//!!ELLERS  -- cleaned up
	const char * filename;

	glutInitWindowSize(600, 600);
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE);

	glutCreateWindow("FTGL demo");

	if ( argc >= 2 )
	{
		if ( !file_exists( argv[ 1 ] ))
		{
			usage( argv[ 0 ]);
			cerr << "Couldn't open file '" << argv[ 1 ] << "'" << endl;
			exit( -1 );
		}
		filename = argv[ 1 ];
	}
	else
	{
		// try a default font
		filename = DEFAULT_FONT;

		if ( !file_exists( filename ))
		{
			usage( argv[ 0 ]);
			cerr << "Couldn't open default file '" << filename << "'" << endl;
			exit( -1 );
		}
	}

	my_init( filename );

	glutDisplayFunc(my_display);
	glutReshapeFunc(my_reshape);
	glutKeyboardFunc(my_handle_key);

	glutMainLoop();
	return 0;
}

<commit_msg>FIX: fix for include glut on Apple (seb's commit)<commit_after>// source changed by mrn@paus.ch/ max rheiner
// original source: henryj@paradise.net.nz

#include <iostream>
#include <stdlib.h> // exit()

#ifdef __APPLE_CC__
  #include <GLUT/glut.h>
#else
  #include <GL/glut.h>
#endif

#ifdef USE_STD_NAMESPACE
using namespace std;
#endif

#include "FTGLOutlineFont.h"
#include "FTGLPolygonFont.h"
#include "FTGLBitmapFont.h"
#ifndef FTGL_NO_TEXTURE_FONTS
#include "FTGLTextureFont.h"
#endif
#include "FTGLPixmapFont.h"

static FTFont* fonts[5];
static int width;
static int height;

#ifdef __linux__
const char* DEFAULT_FONT = "/usr/share/fonts/truetype/arial.ttf";
#else
#ifdef __APPLE_CC__
const char* DEFAULT_FONT = "/Users/henry/Development/PROJECTS/FTGL/ftglcvs/FTGL/demo/arial.ttf";
#else
#ifdef WIN32
const char* DEFAULT_FONT = "C:\\WINNT\\Fonts\\arial.ttf";
#else
const char* DEFAULT_FONT = "arial.ttf";
#endif
#endif
#endif

int file_exists( const char * filename );

void
my_init( const char* font_filename )
{
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    fonts[0] = new FTGLOutlineFont;
    fonts[1] = new FTGLPolygonFont;
#ifndef FTGL_NO_TEXTURE_FONTS
    fonts[2] = new FTGLTextureFont;
#endif
    fonts[3] = new FTGLBitmapFont;
    fonts[4] = new FTGLPixmapFont;
    for (int i=0; i< 5; i++) {
#ifdef FTGL_NO_TEXTURE_FONTS
    if (i == 2) continue;
#endif
        if (!fonts[i]->Open(font_filename)) {
            cerr << "ERROR: Unable to open file " << font_filename << "\n";
        }
        else {
			cout << "Reading font " << i << " from " << font_filename << endl;

            int point_size = 24;
            if (!fonts[i]->FaceSize(point_size)) {
                cerr << "ERROR: Unable to set font face size " << point_size << "\n";
            }

            // Try to load AFM font metrics
            const char* ext = strrchr(font_filename, '.');
            if (ext && !strcmp(ext, ".pfb"))
            {
            char *metrics = new char[strlen(font_filename)];
            strncpy(metrics, font_filename, ext - font_filename);
            strcpy(metrics + (ext - font_filename), ".afm");
            if (file_exists(metrics))
              {
              cout << "Attaching font metrics from " << metrics << endl;
              fonts[i]->Attach(metrics);
              }
            }
        }
    }
}

static void
do_ortho()
{
  int w;
  int h;
  GLdouble size;
  GLdouble aspect;

  w = width;
  h = height;
  aspect = (GLdouble)w / (GLdouble)h;

  // Use the whole window.
  glViewport(0, 0, w, h);

  // We are going to do some 2-D orthographic drawing.
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  size = (GLdouble)((w >= h) ? w : h) / 2.0;
  if (w <= h) {
    aspect = (GLdouble)h/(GLdouble)w;
    glOrtho(-size, size, -size*aspect, size*aspect,
            -100000.0, 100000.0);
  }
  else {
    aspect = (GLdouble)w/(GLdouble)h;
    glOrtho(-size*aspect, size*aspect, -size, size,
            -100000.0, 100000.0);
  }

  // Make the world and window coordinates coincide so that 1.0 in
  // model space equals one pixel in window space.
  glScaled(aspect, aspect, 1.0);

   // Now determine where to draw things.
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
}

void
my_reshape(int w, int h)
{
  width = w;
  height = h;

  do_ortho( );
}

void
my_handle_key(unsigned char key, int x, int y)
{
   switch (key) {

	   //!!ELLERS
   case 'q':   // Esc or 'q' Quits the program.
   case 27:
	   {
       for (int i=0; i<5; i++) {
#ifdef FTGL_NO_TEXTURE_FONTS
       if (i == 2) continue;
#endif
           if (fonts[i]) {
               delete fonts[i];
               fonts[i] = 0;
           }
       }
      exit(1);
	   }
      break;

   default:
      break;
   }
}

void
draw_scene()
{
   /* Set up some strings with the characters to draw. */
   unsigned int count = 0;
   char string[8][256];
   int i;
   for (i=1; i < 32; i++) { /* Skip zero - it's the null terminator! */
      string[0][count] = i;
      count++;
   }
   string[0][count] = '\0';

   count = 0;
   for (i=32; i < 64; i++) {
      string[1][count] = i;
      count++;
   }
   string[1][count] = '\0';

   count = 0;
   for (i=64; i < 96; i++) {
      string[2][count] = i;
      count++;
   }
   string[2][count] = '\0';

   count = 0;
   for (i=96; i < 128; i++) {
      string[3][count] = i;
      count++;
   }
   string[3][count] = '\0';

   count = 0;
   for (i=128; i < 160; i++) {
      string[4][count] = i;
      count++;
   }
   string[4][count] = '\0';

   count = 0;
   for (i=160; i < 192; i++) {
      string[5][count] = i;
      count++;
   }
   string[5][count] = '\0';

   count = 0;
   for (i=192; i < 224; i++) {
      string[6][count] = i;
      count++;
   }
   string[6][count] = '\0';

   count = 0;
   for (i=224; i < 256; i++) {
      string[7][count] = i;
      count++;
   }
   string[7][count] = '\0';

   glColor3f(1.0, 1.0, 1.0);

   for (int font = 0; font < 5; font++) {
       GLfloat x = -250.0;
       GLfloat y;
       GLfloat yild = 20.0;
       for (int j=0; j<4; j++) {
           y = 275.0-font*120.0-j*yild;
           if (font >= 3) {
               glRasterPos2f(x, y);
               fonts[font]->render(string[j]);
           }
           else {
#ifdef FTGL_NO_TEXTURE_FONTS
           if (font == 2) continue;
#endif
               if (font == 2) {
                   glEnable(GL_TEXTURE_2D);
                   glEnable(GL_BLEND);
                   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
               }
               glPushMatrix(); {
                   glTranslatef(x, y, 0.0);
                   fonts[font]->render(string[j]);
               } glPopMatrix();
               if (font == 2) {
                   glDisable(GL_TEXTURE_2D);
                   glDisable(GL_BLEND);
               }
           }
       }
   }
}

void
my_display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);

    draw_scene();

    glutSwapBuffers();
}

int
file_exists( const char * filename )
{
	FILE * fp = fopen( filename, "r" );

	if ( fp == NULL )
	{
		// That fopen failed does _not_ definitely mean the file isn't there
		// but for now this is ok
		return 0;
	}
	fclose( fp );
	return 1;
}

void
usage( const char * program )
{
	cerr << "Usage: " << program << " <filename.ttf>\n" << endl;
}

int
main(int argc, char **argv)
{
	//!!ELLERS  -- cleaned up
	const char * filename;

	glutInitWindowSize(600, 600);
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE);

	glutCreateWindow("FTGL demo");

	if ( argc >= 2 )
	{
		if ( !file_exists( argv[ 1 ] ))
		{
			usage( argv[ 0 ]);
			cerr << "Couldn't open file '" << argv[ 1 ] << "'" << endl;
			exit( -1 );
		}
		filename = argv[ 1 ];
	}
	else
	{
		// try a default font
		filename = DEFAULT_FONT;

		if ( !file_exists( filename ))
		{
			usage( argv[ 0 ]);
			cerr << "Couldn't open default file '" << filename << "'" << endl;
			exit( -1 );
		}
	}

	my_init( filename );

	glutDisplayFunc(my_display);
	glutReshapeFunc(my_reshape);
	glutKeyboardFunc(my_handle_key);

	glutMainLoop();
	return 0;
}

<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////

#include "tink/integration/awskms/aws_kms_aead.h"

#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "aws/core/auth/AWSCredentialsProvider.h"
#include "aws/core/client/AWSClient.h"
#include "aws/core/utils/Outcome.h"
#include "aws/core/utils/memory/AWSMemory.h"
#include "aws/kms/KMSClient.h"
#include "aws/kms/KMSErrors.h"
#include "aws/kms/model/DecryptRequest.h"
#include "aws/kms/model/DecryptResult.h"
#include "aws/kms/model/EncryptRequest.h"
#include "aws/kms/model/EncryptResult.h"
#include "tink/aead.h"
#include "tink/util/errors.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"

namespace crypto {
namespace tink {
namespace integration {
namespace awskms {

using crypto::tink::util::Status;
using crypto::tink::util::StatusOr;

namespace {

// TODO: pull out hex-helpers from test_util and remove the copy below.
std::string HexEncode(absl::string_view bytes) {
  std::string hexchars = "0123456789abcdef";
  std::string res(bytes.size() * 2, static_cast<char>(255));
  for (size_t i = 0; i < bytes.size(); ++i) {
    uint8_t c = static_cast<uint8_t>(bytes[i]);
    res[2 * i] = hexchars[c / 16];
    res[2 * i + 1] = hexchars[c % 16];
  }
  return res;
}

std::string AwsErrorToString(Aws::Client::AWSError<Aws::KMS::KMSErrors> err) {
  return absl::StrCat("AWS error code: ", err.GetErrorType(), ", ",
                      err.GetExceptionName(), ": ", err.GetMessage());
}

}  // namespace

AwsKmsAead::AwsKmsAead(absl::string_view key_arn,
                       std::shared_ptr<Aws::KMS::KMSClient> aws_client) :
    key_arn_(key_arn), aws_client_(aws_client) {
}

// static
StatusOr<std::unique_ptr<Aead>>
AwsKmsAead::New(absl::string_view key_arn,
                std::shared_ptr<Aws::KMS::KMSClient> aws_client) {
  if (key_arn.empty()) {
    return Status(util::error::INVALID_ARGUMENT,
                  "Key ARN cannot be empty.");
  }
  if (aws_client == nullptr) {
    return Status(util::error::INVALID_ARGUMENT,
                  "AWS KMS client cannot be null.");
  }
  std::unique_ptr<Aead> aead(new AwsKmsAead(key_arn, aws_client));
  return std::move(aead);
}

StatusOr<std::string> AwsKmsAead::Encrypt(
    absl::string_view plaintext, absl::string_view associated_data) const {
  Aws::KMS::Model::EncryptRequest req;
  req.SetKeyId(key_arn_.c_str());
  Aws::Utils::ByteBuffer plaintext_buffer(
      reinterpret_cast<const unsigned char*>(plaintext.data()),
      plaintext.length());
  req.SetPlaintext(plaintext_buffer);
  if (!associated_data.empty()) {
    req.AddEncryptionContext("associatedData",
                             HexEncode(associated_data).c_str());
  }
  auto outcome = aws_client_->Encrypt(req);
  if (outcome.IsSuccess()) {
    auto& blob = outcome.GetResult().GetCiphertextBlob();
    std::string ciphertext(
        reinterpret_cast<const char*>(blob.GetUnderlyingData()),
        blob.GetLength());
    return ciphertext;
  }
  auto& err = outcome.GetError();
  return ToStatusF(util::error::INVALID_ARGUMENT,
                   "AWS KMS encryption failed with error: %s",
                   AwsErrorToString(err));
}

StatusOr<std::string> AwsKmsAead::Decrypt(
    absl::string_view ciphertext, absl::string_view associated_data) const {
  Aws::KMS::Model::DecryptRequest req;
  Aws::Utils::ByteBuffer ciphertext_buffer(
      reinterpret_cast<const unsigned char*>(ciphertext.data()),
      ciphertext.length());
  req.SetCiphertextBlob(ciphertext_buffer);
  if (!associated_data.empty()) {
    req.AddEncryptionContext("associatedData",
                             HexEncode(associated_data).c_str());
  }
  auto outcome = aws_client_->Decrypt(req);
  if (outcome.IsSuccess()) {
    if (outcome.GetResult().GetKeyId() != Aws::String(key_arn_.c_str())) {
      return util::Status(util::error::INVALID_ARGUMENT,
                          "AWS KMS decryption failed: wrong key ARN.");
    }
    auto& buffer = outcome.GetResult().GetPlaintext();
    std::string plaintext(
        reinterpret_cast<const char*>(buffer.GetUnderlyingData()),
        buffer.GetLength());
    return plaintext;
  }
  auto& err = outcome.GetError();
  return ToStatusF(util::error::INVALID_ARGUMENT,
                   "AWS KMS decryption failed with error: %s",
                   AwsErrorToString(err));
}

}  // namespace awskms
}  // namespace integration
}  // namespace tink
}  // namespace crypto
<commit_msg>C++: mitigate the AWS KMS security issues disclosed in https://github.com/google/security-research/security/advisories/GHSA-wqgp-vphw-hphf.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////

#include "tink/integration/awskms/aws_kms_aead.h"

#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "aws/core/auth/AWSCredentialsProvider.h"
#include "aws/core/client/AWSClient.h"
#include "aws/core/utils/Outcome.h"
#include "aws/core/utils/memory/AWSMemory.h"
#include "aws/kms/KMSClient.h"
#include "aws/kms/KMSErrors.h"
#include "aws/kms/model/DecryptRequest.h"
#include "aws/kms/model/DecryptResult.h"
#include "aws/kms/model/EncryptRequest.h"
#include "aws/kms/model/EncryptResult.h"
#include "tink/aead.h"
#include "tink/util/errors.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"

namespace crypto {
namespace tink {
namespace integration {
namespace awskms {

using crypto::tink::util::Status;
using crypto::tink::util::StatusOr;

namespace {

// TODO: pull out hex-helpers from test_util and remove the copy below.
std::string HexEncode(absl::string_view bytes) {
  std::string hexchars = "0123456789abcdef";
  std::string res(bytes.size() * 2, static_cast<char>(255));
  for (size_t i = 0; i < bytes.size(); ++i) {
    uint8_t c = static_cast<uint8_t>(bytes[i]);
    res[2 * i] = hexchars[c / 16];
    res[2 * i + 1] = hexchars[c % 16];
  }
  return res;
}

std::string AwsErrorToString(Aws::Client::AWSError<Aws::KMS::KMSErrors> err) {
  return absl::StrCat("AWS error code: ", err.GetErrorType(), ", ",
                      err.GetExceptionName(), ": ", err.GetMessage());
}

}  // namespace

AwsKmsAead::AwsKmsAead(absl::string_view key_arn,
                       std::shared_ptr<Aws::KMS::KMSClient> aws_client) :
    key_arn_(key_arn), aws_client_(aws_client) {
}

// static
StatusOr<std::unique_ptr<Aead>>
AwsKmsAead::New(absl::string_view key_arn,
                std::shared_ptr<Aws::KMS::KMSClient> aws_client) {
  if (key_arn.empty()) {
    return Status(util::error::INVALID_ARGUMENT,
                  "Key ARN cannot be empty.");
  }
  if (aws_client == nullptr) {
    return Status(util::error::INVALID_ARGUMENT,
                  "AWS KMS client cannot be null.");
  }
  std::unique_ptr<Aead> aead(new AwsKmsAead(key_arn, aws_client));
  return std::move(aead);
}

StatusOr<std::string> AwsKmsAead::Encrypt(
    absl::string_view plaintext, absl::string_view associated_data) const {
  Aws::KMS::Model::EncryptRequest req;
  req.SetKeyId(key_arn_.c_str());
  Aws::Utils::ByteBuffer plaintext_buffer(
      reinterpret_cast<const unsigned char*>(plaintext.data()),
      plaintext.length());
  req.SetPlaintext(plaintext_buffer);
  if (!associated_data.empty()) {
    req.AddEncryptionContext("associatedData",
                             HexEncode(associated_data).c_str());
  }
  auto outcome = aws_client_->Encrypt(req);
  if (outcome.IsSuccess()) {
    auto& blob = outcome.GetResult().GetCiphertextBlob();
    std::string ciphertext(
        reinterpret_cast<const char*>(blob.GetUnderlyingData()),
        blob.GetLength());
    return ciphertext;
  }
  auto& err = outcome.GetError();
  return ToStatusF(util::error::INVALID_ARGUMENT,
                   "AWS KMS encryption failed with error: %s",
                   AwsErrorToString(err));
}

StatusOr<std::string> AwsKmsAead::Decrypt(
    absl::string_view ciphertext, absl::string_view associated_data) const {
  Aws::KMS::Model::DecryptRequest req;
  req.SetKeyId(key_arn_.c_str());
  Aws::Utils::ByteBuffer ciphertext_buffer(
      reinterpret_cast<const unsigned char*>(ciphertext.data()),
      ciphertext.length());
  req.SetCiphertextBlob(ciphertext_buffer);
  if (!associated_data.empty()) {
    req.AddEncryptionContext("associatedData",
                             HexEncode(associated_data).c_str());
  }
  auto outcome = aws_client_->Decrypt(req);
  if (outcome.IsSuccess()) {
    if (outcome.GetResult().GetKeyId() != Aws::String(key_arn_.c_str())) {
      return util::Status(util::error::INVALID_ARGUMENT,
                          "AWS KMS decryption failed: wrong key ARN.");
    }
    auto& buffer = outcome.GetResult().GetPlaintext();
    std::string plaintext(
        reinterpret_cast<const char*>(buffer.GetUnderlyingData()),
        buffer.GetLength());
    return plaintext;
  }
  auto& err = outcome.GetError();
  return ToStatusF(util::error::INVALID_ARGUMENT,
                   "AWS KMS decryption failed with error: %s",
                   AwsErrorToString(err));
}

}  // namespace awskms
}  // namespace integration
}  // namespace tink
}  // namespace crypto
<|endoftext|>


<commit_before><commit_msg>Fixed licence text<commit_after><|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015
              Vladimír Vondruš <mosra@centrum.cz>

    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 "Animable.h"

namespace Magnum { namespace SceneGraph {

Debug operator<<(Debug debug, AnimationState value) {
    switch(value) {
        #define _c(value) case AnimationState::value: return debug << "SceneGraph::AnimationState::" #value;
        _c(Stopped)
        _c(Paused)
        _c(Running)
        #undef _c
    }

    return debug << "SceneGraph::AnimationState::(invalid)";
}

}}
<commit_msg>Attempt to fix build without assertions no. 5.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015
              Vladimír Vondruš <mosra@centrum.cz>

    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 "Animable.h"

#include <Corrade/Utility/Debug.h>

namespace Magnum { namespace SceneGraph {

Debug operator<<(Debug debug, AnimationState value) {
    switch(value) {
        #define _c(value) case AnimationState::value: return debug << "SceneGraph::AnimationState::" #value;
        _c(Stopped)
        _c(Paused)
        _c(Running)
        #undef _c
    }

    return debug << "SceneGraph::AnimationState::(invalid)";
}

}}
<|endoftext|>


<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Core/Win32/FileImpl.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Win32/Time.hpp>
#include <memory>
#include <Nazara/Core/Debug.hpp>

namespace Nz
{
	FileImpl::FileImpl(const File* parent) :
	m_endOfFile(false),
	m_endOfFileUpdated(true)
	{
		NazaraUnused(parent);
	}

	void FileImpl::Close()
	{
		CloseHandle(m_handle);
	}

	bool FileImpl::EndOfFile() const
	{
		if (!m_endOfFileUpdated)
		{
			LARGE_INTEGER fileSize;
			if (!GetFileSizeEx(m_handle, &fileSize))
				fileSize.QuadPart = 0;

			m_endOfFile = (GetCursorPos() >= static_cast<UInt64>(fileSize.QuadPart));
			m_endOfFileUpdated = true;
		}

		return m_endOfFile;
	}

	void FileImpl::Flush()
	{
		if (!FlushFileBuffers(m_handle))
			NazaraError("Unable to flush file: " + Error::GetLastSystemError());
	}

	UInt64 FileImpl::GetCursorPos() const
	{
		LARGE_INTEGER zero;
		zero.QuadPart = 0;

		LARGE_INTEGER position;
		SetFilePointerEx(m_handle, zero, &position, FILE_CURRENT);

		return position.QuadPart;
	}

	bool FileImpl::Open(const String& filePath, UInt32 mode)
	{
		DWORD access;
		DWORD shareMode = FILE_SHARE_READ;
		DWORD openMode;
		if (mode & OpenMode_ReadOnly)
		{
			access = GENERIC_READ;
			openMode = OPEN_EXISTING;
		}
		else if (mode & OpenMode_ReadWrite)
		{
			if (mode & OpenMode_Append)
				access = FILE_APPEND_DATA;
			else
				access = GENERIC_READ | GENERIC_WRITE;

			if (mode & OpenMode_Truncate)
				openMode = CREATE_ALWAYS;
			else
				openMode = OPEN_ALWAYS;
		}
		else if (mode & OpenMode_WriteOnly)
		{
			if (mode & OpenMode_Append)
				access = FILE_APPEND_DATA;
			else
				access = GENERIC_WRITE;

			if (mode & OpenMode_Truncate)
				openMode = CREATE_ALWAYS;
			else
				openMode = OPEN_ALWAYS;
		}
		else
			return false;

		if ((mode & OpenMode_Lock) == 0)
			shareMode |= FILE_SHARE_WRITE;

		m_handle = CreateFileW(filePath.GetWideString().data(), access, shareMode, nullptr, openMode, 0, nullptr);
		return m_handle != INVALID_HANDLE_VALUE;
	}

	std::size_t FileImpl::Read(void* buffer, std::size_t size)
	{
		//UInt64 oldCursorPos = GetCursorPos();

		DWORD read = 0;
		if (ReadFile(m_handle, buffer, size, &read, nullptr))
		{
			m_endOfFile = (read != size);
			m_endOfFileUpdated = true;

			return read;
			///FIXME: D'après la documentation, read vaut 0 si ReadFile atteint la fin du fichier
			///       D'après les tests, ce n'est pas le cas, la taille lue est inférieure à la taille en argument, mais pas nulle
			///       Peut-être ais-je mal compris la documentation
			///       Le correctif (dans le cas où la doc serait vraie) est commenté en début de fonction et après ce commentaire
			///       Il est cependant plus lourd, et ne fonctionne pas avec le comportement observé de la fonction
			/*
			if (read == 0)
			{
				// Si nous atteignons la fin du fichier, la taille lue vaut 0
				// pour renvoyer le nombre d'octets lus nous comparons la position du curseur
				// http://msdn.microsoft.com/en-us/library/windows/desktop/aa365690(v=vs.85).aspx
				m_endOfFile = true;
				m_endOfFileUpdated = true;

				return GetCursorPos()-oldCursorPos;
			}
			else
			{
				m_endOfFileUpdated = false;
				return read;
			}
			*/
		}
		else
			return 0;
	}

	bool FileImpl::SetCursorPos(CursorPosition pos, Int64 offset)
	{
		DWORD moveMethod;
		switch (pos)
		{
			case CursorPosition_AtBegin:
				moveMethod = FILE_BEGIN;
				break;

			case CursorPosition_AtCurrent:
				moveMethod = FILE_CURRENT;
				break;

			case CursorPosition_AtEnd:
				moveMethod = FILE_END;
				break;

			default:
				NazaraInternalError("Cursor position not handled (0x" + String::Number(pos, 16) + ')');
				return false;
		}

		LARGE_INTEGER distance;
		distance.QuadPart = offset;

		m_endOfFileUpdated = false;

		return SetFilePointerEx(m_handle, distance, nullptr, moveMethod) != 0;
	}

	std::size_t FileImpl::Write(const void* buffer, std::size_t size)
	{
		DWORD written = 0;

		LARGE_INTEGER cursorPos;
		cursorPos.QuadPart = GetCursorPos();

		LockFile(m_handle, cursorPos.LowPart, cursorPos.HighPart, size, 0);
		WriteFile(m_handle, buffer, size, &written, nullptr);
		UnlockFile(m_handle, cursorPos.LowPart, cursorPos.HighPart, size, 0);

		m_endOfFileUpdated = false;

		return written;
	}

	bool FileImpl::Copy(const String& sourcePath, const String& targetPath)
	{
		if (CopyFileW(sourcePath.GetWideString().data(), targetPath.GetWideString().data(), false))
			return true;
		else
		{
			NazaraError("Failed to copy file: " + Error::GetLastSystemError());
			return false;
		}
	}

	bool FileImpl::Delete(const String& filePath)
	{
		if (DeleteFileW(filePath.GetWideString().data()))
			return true;
		else
		{
			NazaraError("Failed to delete file (" + filePath + "): " + Error::GetLastSystemError());
			return false;
		}
	}

	bool FileImpl::Exists(const String& filePath)
	{
		HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
		if (handle == INVALID_HANDLE_VALUE)
			return false;

		CloseHandle(handle);
		return true;
	}

	time_t FileImpl::GetCreationTime(const String& filePath)
	{
		HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
		if (handle == INVALID_HANDLE_VALUE)
			return 0;

		FILETIME creationTime;
		if (!GetFileTime(handle, &creationTime, nullptr, nullptr))
		{
			CloseHandle(handle);

			NazaraError("Unable to get creation time: " + Error::GetLastSystemError());
			return 0;
		}

		CloseHandle(handle);
		return FileTimeToTime(&creationTime);
	}

	time_t FileImpl::GetLastAccessTime(const String& filePath)
	{
		HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
		if (handle == INVALID_HANDLE_VALUE)
			return 0;

		FILETIME accessTime;
		if (!GetFileTime(handle, nullptr, &accessTime, nullptr))
		{
			CloseHandle(handle);

			NazaraError("Unable to get last access time: " + Error::GetLastSystemError());
			return 0;
		}

		CloseHandle(handle);
		return FileTimeToTime(&accessTime);
	}

	time_t FileImpl::GetLastWriteTime(const String& filePath)
	{
		HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
		if (handle == INVALID_HANDLE_VALUE)
			return 0;

		FILETIME writeTime;
		if (!GetFileTime(handle, nullptr, nullptr, &writeTime))
		{
			CloseHandle(handle);

			NazaraError("Unable to get last write time: " + Error::GetLastSystemError());
			return 0;
		}

		CloseHandle(handle);
		return FileTimeToTime(&writeTime);
	}

	UInt64 FileImpl::GetSize(const String& filePath)
	{
		HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
		if (handle == INVALID_HANDLE_VALUE)
			return 0;

		LARGE_INTEGER fileSize;
		if (!GetFileSizeEx(handle, &fileSize))
			fileSize.QuadPart = 0;

		CloseHandle(handle);
		return fileSize.QuadPart;
	}

	bool FileImpl::Rename(const String& sourcePath, const String& targetPath)
	{
		if (MoveFileExW(sourcePath.GetWideString().data(), targetPath.GetWideString().data(), MOVEFILE_COPY_ALLOWED))
			return true;
		else
		{
			NazaraError("Unable to rename file: " + Error::GetLastSystemError());
			return false;
		}
	}
}
<commit_msg>Core/Win32: Fix file opening in ReadWrite mode<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Core/Win32/FileImpl.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Win32/Time.hpp>
#include <memory>
#include <Nazara/Core/Debug.hpp>

namespace Nz
{
	FileImpl::FileImpl(const File* parent) :
	m_endOfFile(false),
	m_endOfFileUpdated(true)
	{
		NazaraUnused(parent);
	}

	void FileImpl::Close()
	{
		CloseHandle(m_handle);
	}

	bool FileImpl::EndOfFile() const
	{
		if (!m_endOfFileUpdated)
		{
			LARGE_INTEGER fileSize;
			if (!GetFileSizeEx(m_handle, &fileSize))
				fileSize.QuadPart = 0;

			m_endOfFile = (GetCursorPos() >= static_cast<UInt64>(fileSize.QuadPart));
			m_endOfFileUpdated = true;
		}

		return m_endOfFile;
	}

	void FileImpl::Flush()
	{
		if (!FlushFileBuffers(m_handle))
			NazaraError("Unable to flush file: " + Error::GetLastSystemError());
	}

	UInt64 FileImpl::GetCursorPos() const
	{
		LARGE_INTEGER zero;
		zero.QuadPart = 0;

		LARGE_INTEGER position;
		SetFilePointerEx(m_handle, zero, &position, FILE_CURRENT);

		return position.QuadPart;
	}

	bool FileImpl::Open(const String& filePath, UInt32 mode)
	{
		DWORD access = 0;
		DWORD shareMode = FILE_SHARE_READ;
		DWORD openMode = 0;

		if (mode & OpenMode_ReadOnly)
		{
			access |= GENERIC_READ;

			if ((mode & OpenMode_WriteOnly) == 0)
				openMode |= OPEN_EXISTING;
		}

		if (mode & OpenMode_WriteOnly)
		{
			if (mode & OpenMode_Append)
				access |= FILE_APPEND_DATA;
			else
				access |= GENERIC_WRITE;

			if (mode & OpenMode_Truncate)
				openMode |= CREATE_ALWAYS;
			else
				openMode |= OPEN_ALWAYS;
		}

		if ((mode & OpenMode_Lock) == 0)
			shareMode |= FILE_SHARE_WRITE;

		m_handle = CreateFileW(filePath.GetWideString().data(), access, shareMode, nullptr, openMode, 0, nullptr);
		return m_handle != INVALID_HANDLE_VALUE;
	}

	std::size_t FileImpl::Read(void* buffer, std::size_t size)
	{
		//UInt64 oldCursorPos = GetCursorPos();

		DWORD read = 0;
		if (ReadFile(m_handle, buffer, size, &read, nullptr))
		{
			m_endOfFile = (read != size);
			m_endOfFileUpdated = true;

			return read;
			///FIXME: D'après la documentation, read vaut 0 si ReadFile atteint la fin du fichier
			///       D'après les tests, ce n'est pas le cas, la taille lue est inférieure à la taille en argument, mais pas nulle
			///       Peut-être ais-je mal compris la documentation
			///       Le correctif (dans le cas où la doc serait vraie) est commenté en début de fonction et après ce commentaire
			///       Il est cependant plus lourd, et ne fonctionne pas avec le comportement observé de la fonction
			/*
			if (read == 0)
			{
				// Si nous atteignons la fin du fichier, la taille lue vaut 0
				// pour renvoyer le nombre d'octets lus nous comparons la position du curseur
				// http://msdn.microsoft.com/en-us/library/windows/desktop/aa365690(v=vs.85).aspx
				m_endOfFile = true;
				m_endOfFileUpdated = true;

				return GetCursorPos()-oldCursorPos;
			}
			else
			{
				m_endOfFileUpdated = false;
				return read;
			}
			*/
		}
		else
			return 0;
	}

	bool FileImpl::SetCursorPos(CursorPosition pos, Int64 offset)
	{
		DWORD moveMethod;
		switch (pos)
		{
			case CursorPosition_AtBegin:
				moveMethod = FILE_BEGIN;
				break;

			case CursorPosition_AtCurrent:
				moveMethod = FILE_CURRENT;
				break;

			case CursorPosition_AtEnd:
				moveMethod = FILE_END;
				break;

			default:
				NazaraInternalError("Cursor position not handled (0x" + String::Number(pos, 16) + ')');
				return false;
		}

		LARGE_INTEGER distance;
		distance.QuadPart = offset;

		m_endOfFileUpdated = false;

		return SetFilePointerEx(m_handle, distance, nullptr, moveMethod) != 0;
	}

	std::size_t FileImpl::Write(const void* buffer, std::size_t size)
	{
		DWORD written = 0;

		LARGE_INTEGER cursorPos;
		cursorPos.QuadPart = GetCursorPos();

		LockFile(m_handle, cursorPos.LowPart, cursorPos.HighPart, size, 0);
		WriteFile(m_handle, buffer, size, &written, nullptr);
		UnlockFile(m_handle, cursorPos.LowPart, cursorPos.HighPart, size, 0);

		m_endOfFileUpdated = false;

		return written;
	}

	bool FileImpl::Copy(const String& sourcePath, const String& targetPath)
	{
		if (CopyFileW(sourcePath.GetWideString().data(), targetPath.GetWideString().data(), false))
			return true;
		else
		{
			NazaraError("Failed to copy file: " + Error::GetLastSystemError());
			return false;
		}
	}

	bool FileImpl::Delete(const String& filePath)
	{
		if (DeleteFileW(filePath.GetWideString().data()))
			return true;
		else
		{
			NazaraError("Failed to delete file (" + filePath + "): " + Error::GetLastSystemError());
			return false;
		}
	}

	bool FileImpl::Exists(const String& filePath)
	{
		HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
		if (handle == INVALID_HANDLE_VALUE)
			return false;

		CloseHandle(handle);
		return true;
	}

	time_t FileImpl::GetCreationTime(const String& filePath)
	{
		HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
		if (handle == INVALID_HANDLE_VALUE)
			return 0;

		FILETIME creationTime;
		if (!GetFileTime(handle, &creationTime, nullptr, nullptr))
		{
			CloseHandle(handle);

			NazaraError("Unable to get creation time: " + Error::GetLastSystemError());
			return 0;
		}

		CloseHandle(handle);
		return FileTimeToTime(&creationTime);
	}

	time_t FileImpl::GetLastAccessTime(const String& filePath)
	{
		HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
		if (handle == INVALID_HANDLE_VALUE)
			return 0;

		FILETIME accessTime;
		if (!GetFileTime(handle, nullptr, &accessTime, nullptr))
		{
			CloseHandle(handle);

			NazaraError("Unable to get last access time: " + Error::GetLastSystemError());
			return 0;
		}

		CloseHandle(handle);
		return FileTimeToTime(&accessTime);
	}

	time_t FileImpl::GetLastWriteTime(const String& filePath)
	{
		HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
		if (handle == INVALID_HANDLE_VALUE)
			return 0;

		FILETIME writeTime;
		if (!GetFileTime(handle, nullptr, nullptr, &writeTime))
		{
			CloseHandle(handle);

			NazaraError("Unable to get last write time: " + Error::GetLastSystemError());
			return 0;
		}

		CloseHandle(handle);
		return FileTimeToTime(&writeTime);
	}

	UInt64 FileImpl::GetSize(const String& filePath)
	{
		HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
		if (handle == INVALID_HANDLE_VALUE)
			return 0;

		LARGE_INTEGER fileSize;
		if (!GetFileSizeEx(handle, &fileSize))
			fileSize.QuadPart = 0;

		CloseHandle(handle);
		return fileSize.QuadPart;
	}

	bool FileImpl::Rename(const String& sourcePath, const String& targetPath)
	{
		if (MoveFileExW(sourcePath.GetWideString().data(), targetPath.GetWideString().data(), MOVEFILE_COPY_ALLOWED))
			return true;
		else
		{
			NazaraError("Unable to rename file: " + Error::GetLastSystemError());
			return false;
		}
	}
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * Copyright � 2002-2011 VideoLAN and VLC authors
 * $Id$
 *
 * Authors: Sergey Radionov <rsatom_gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "vlc_player.h"

////////////////////////////////////////////////////////////////////////////////
vlc_player::vlc_player()
    :_libvlc_instance(0), _mp(0), _ml(0), _ml_p(0)
{
}

vlc_player::~vlc_player(void)
{
    close();
}

bool vlc_player::open(libvlc_instance_t* inst)
{
    if( !inst )
        return false;

    if( is_open() )
        close();

    _libvlc_instance = inst;

    _mp   = libvlc_media_player_new(inst);
    _ml   = libvlc_media_list_new(inst);
    _ml_p = libvlc_media_list_player_new(inst);

    if( _mp && _ml && _ml_p ) {
        libvlc_media_list_player_set_media_list(_ml_p, _ml);
        libvlc_media_list_player_set_media_player(_ml_p, _mp);
    }
    else{
        close();
        return false;
    }

    return true;
}

bool vlc_player::is_playing()
{
    return _ml_p && libvlc_media_list_player_is_playing(_ml_p) != 0;
}

libvlc_state_t vlc_player::get_state()
{
    if( !is_open() )
        return libvlc_NothingSpecial;

    return libvlc_media_list_player_get_state(_ml_p);
}

void vlc_player::close()
{
    if(_ml_p) {
        libvlc_media_list_player_release(_ml_p);
        _ml_p = 0;
    }

    if(_ml) {
        libvlc_media_list_release(_ml);
        _ml = 0;
    }

    if(_mp) {
        libvlc_media_player_release(_mp);
        _mp = 0;
    }

    _libvlc_instance = 0;
}

int vlc_player::add_item(const char * mrl_or_path,
                         unsigned int optc, const char **optv,
                         unsigned int trusted_optc, const char **trusted_optv,
                         bool is_path /*= false*/)
{
    if( !is_open() )
        return -1;

    int item = -1;

    libvlc_media_t* media = is_path ?
                            libvlc_media_new_path(_libvlc_instance, mrl_or_path) :
                            libvlc_media_new_location(_libvlc_instance, mrl_or_path);

    if( !media )
        return -1;

    unsigned int i;
    for( i = 0; i < optc; ++i )
        libvlc_media_add_option_flag(media, optv[i], libvlc_media_option_unique);

    for( i = 0; i < trusted_optc; ++i )
        libvlc_media_add_option_flag(media, trusted_optv[i], libvlc_media_option_unique | libvlc_media_option_trusted);

    libvlc_media_list_lock(_ml);
    if( 0 == libvlc_media_list_add_media(_ml, media) )
         item = libvlc_media_list_count(_ml) - 1;
    libvlc_media_list_unlock(_ml);

    libvlc_media_release(media);

    return item;
}

int vlc_player::current_item()
{
    if( !is_open() )
        return -1;

    libvlc_media_t* media = libvlc_media_player_get_media(_mp);

    if( !media )
        return -1;

    return libvlc_media_list_index_of_item(_ml, media);
}

int vlc_player::items_count()
{
    if( !is_open() )
        return 0;

    libvlc_media_list_lock(_ml);
    int icnt = libvlc_media_list_count(_ml);
    libvlc_media_list_unlock(_ml);
    return icnt;
}

bool vlc_player::delete_item(unsigned int idx)
{
    if( !is_open() )
        return false;

    libvlc_media_list_lock(_ml);
    bool ret = libvlc_media_list_remove_index(_ml, idx) == 0;
    libvlc_media_list_unlock(_ml);

    return ret;
}

void vlc_player::clear_items()
{
    if( !is_open() )
        return;

    libvlc_media_list_lock(_ml);
    for( int i = libvlc_media_list_count(_ml); i > 0; --i) {
        libvlc_media_list_remove_index(_ml, i - 1);
    }
    libvlc_media_list_unlock(_ml);
}

void vlc_player::play()
{
    if( !is_open() )
        return;

    if( 0 == items_count() )
        return;
    else if( -1 == current_item() ) {
        play(0);
    }
    else {
        libvlc_media_list_player_play(_ml_p);
        on_player_action(pa_play);
    }
}

bool vlc_player::play(unsigned int idx)
{
    if( !is_open() )
        return false;

    const int r = libvlc_media_list_player_play_item_at_index(_ml_p, idx);
    if( 0 == r ) {
        on_player_action(pa_play);
        return true;
    }

    return false;
}

void vlc_player::pause()
{
    if( is_open() ) {
        libvlc_media_list_player_pause(_ml_p);
        on_player_action(pa_pause);
    }
}

void vlc_player::stop()
{
    if( is_open() ){
        libvlc_media_list_player_stop(_ml_p);
        on_player_action(pa_stop);
    }
}

bool vlc_player::next()
{
    if( !is_open() )
        return false;

    const int r = libvlc_media_list_player_next(_ml_p);
    if( 0 == r ) {
        on_player_action(pa_next);
        return true;
    }

    return false;
}

bool vlc_player::prev()
{
    if( !is_open() )
        return false;

    const int r = libvlc_media_list_player_previous(_ml_p);
    if( 0 == r ) {
        on_player_action(pa_prev);
        return true;
    }

    return false;
}

float vlc_player::get_rate()
{
    if( !is_open() )
        return 1.f;

    return libvlc_media_player_get_rate(_mp);
}

void vlc_player::set_rate(float rate)
{
    if( !is_open() )
        return;

    libvlc_media_player_set_rate(_mp, rate);
}

float vlc_player::get_fps()
{
    if( !is_open() )
        return 0;

    return libvlc_media_player_get_fps(_mp);
}

bool vlc_player::has_vout()
{
    if( !is_open() )
        return false;

    return libvlc_media_player_has_vout(_mp) > 0;
}

float vlc_player::get_position()
{
    if( !is_open() )
        return 0.f;

    float p = libvlc_media_player_get_position(_mp);

    return p<0 ? 0 : p;
}

void vlc_player::set_position(float p)
{
    if( !is_open() )
        return;

    libvlc_media_player_set_position(_mp, p);
}

libvlc_time_t vlc_player::get_time()
{
    if( !is_open() )
        return 0;

    libvlc_time_t t = libvlc_media_player_get_time(_mp);

    return t<0 ? 0 : t ;
}

void vlc_player::set_time(libvlc_time_t t)
{
    if( !is_open() )
        return;

    libvlc_media_player_set_time(_mp, t);
}

libvlc_time_t vlc_player::get_length()
{
    if( !is_open() )
        return 0;

    libvlc_time_t t = libvlc_media_player_get_length(_mp);

    return t<0 ? 0 : t ;
}

void vlc_player::set_mode(libvlc_playback_mode_t mode)
{
    if( is_open() )
        libvlc_media_list_player_set_playback_mode(_ml_p, mode);
}

bool vlc_player::is_muted()
{
    if( !is_open() )
        return false;

    return libvlc_audio_get_mute(_mp) != 0;
}

void vlc_player::toggle_mute()
{
    if( is_open() )
        libvlc_audio_toggle_mute(_mp);
}

void vlc_player::set_mute(bool mute)
{
    if( is_open() )
        libvlc_audio_set_mute(_mp, mute);
}

unsigned int vlc_player::get_volume()
{
    if( !is_open() )
        return 0;

    int v = libvlc_audio_get_volume(_mp);

    return v<0 ? 0 : v;
}

void vlc_player::set_volume(unsigned int volume)
{
    if( is_open() )
        libvlc_audio_set_volume(_mp, volume);
}

unsigned int vlc_player::track_count()
{
    if( !is_open() )
        return 0;

    int tc = libvlc_audio_get_track_count(_mp);

    return tc<0 ? 0 : tc ;
}

unsigned int vlc_player::get_track()
{
    if( !is_open() )
        return 0;

    int t = libvlc_audio_get_track(_mp);

    return t<0 ? 0 : t ;
}

void vlc_player::set_track(unsigned int track)
{
    if( is_open() )
        libvlc_audio_set_track(_mp, track);
}

libvlc_audio_output_channel_t vlc_player::get_channel()
{
    if( !is_open() )
        return libvlc_AudioChannel_Error;

    return (libvlc_audio_output_channel_t) libvlc_audio_get_channel(_mp);
}

void vlc_player::set_channel(libvlc_audio_output_channel_t channel)
{
    if( is_open() )
        libvlc_audio_set_channel(_mp, channel);
}

////////////////////////////////////////////////////////////////////////////////
float vlc_player_video::get_ajust_filter_var( libvlc_video_adjust_option_t option,
                                              float def_v )
{
    if( m_vp->is_open() ) {
        return libvlc_video_get_adjust_float( m_vp->get_mp(), option );
    }
    else return def_v;
}

void vlc_player_video::set_ajust_filter_var( libvlc_video_adjust_option_t option,
                                             float val )
{
    if( m_vp->is_open() ) {
        libvlc_video_set_adjust_float( m_vp->get_mp(), option, val );
    }
}
<commit_msg>added necessary locking of media list<commit_after>/*****************************************************************************
 * Copyright � 2002-2011 VideoLAN and VLC authors
 * $Id$
 *
 * Authors: Sergey Radionov <rsatom_gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "vlc_player.h"

////////////////////////////////////////////////////////////////////////////////
vlc_player::vlc_player()
    :_libvlc_instance(0), _mp(0), _ml(0), _ml_p(0)
{
}

vlc_player::~vlc_player(void)
{
    close();
}

bool vlc_player::open(libvlc_instance_t* inst)
{
    if( !inst )
        return false;

    if( is_open() )
        close();

    _libvlc_instance = inst;

    _mp   = libvlc_media_player_new(inst);
    _ml   = libvlc_media_list_new(inst);
    _ml_p = libvlc_media_list_player_new(inst);

    if( _mp && _ml && _ml_p ) {
        libvlc_media_list_player_set_media_list(_ml_p, _ml);
        libvlc_media_list_player_set_media_player(_ml_p, _mp);
    }
    else{
        close();
        return false;
    }

    return true;
}

bool vlc_player::is_playing()
{
    return _ml_p && libvlc_media_list_player_is_playing(_ml_p) != 0;
}

libvlc_state_t vlc_player::get_state()
{
    if( !is_open() )
        return libvlc_NothingSpecial;

    return libvlc_media_list_player_get_state(_ml_p);
}

void vlc_player::close()
{
    if(_ml_p) {
        libvlc_media_list_player_release(_ml_p);
        _ml_p = 0;
    }

    if(_ml) {
        libvlc_media_list_release(_ml);
        _ml = 0;
    }

    if(_mp) {
        libvlc_media_player_release(_mp);
        _mp = 0;
    }

    _libvlc_instance = 0;
}

int vlc_player::add_item(const char * mrl_or_path,
                         unsigned int optc, const char **optv,
                         unsigned int trusted_optc, const char **trusted_optv,
                         bool is_path /*= false*/)
{
    if( !is_open() )
        return -1;

    int item = -1;

    libvlc_media_t* media = is_path ?
                            libvlc_media_new_path(_libvlc_instance, mrl_or_path) :
                            libvlc_media_new_location(_libvlc_instance, mrl_or_path);

    if( !media )
        return -1;

    unsigned int i;
    for( i = 0; i < optc; ++i )
        libvlc_media_add_option_flag(media, optv[i], libvlc_media_option_unique);

    for( i = 0; i < trusted_optc; ++i )
        libvlc_media_add_option_flag(media, trusted_optv[i], libvlc_media_option_unique | libvlc_media_option_trusted);

    libvlc_media_list_lock(_ml);
    if( 0 == libvlc_media_list_add_media(_ml, media) )
         item = libvlc_media_list_count(_ml) - 1;
    libvlc_media_list_unlock(_ml);

    libvlc_media_release(media);

    return item;
}

int vlc_player::current_item()
{
    if( !is_open() )
        return -1;

    libvlc_media_t* media = libvlc_media_player_get_media(_mp);
    if( !media )
        return -1;

    libvlc_media_list_lock(_ml);
    int idx = libvlc_media_list_index_of_item(_ml, media);
    libvlc_media_list_unlock(_ml);

    return idx;
}

int vlc_player::items_count()
{
    if( !is_open() )
        return 0;

    libvlc_media_list_lock(_ml);
    int icnt = libvlc_media_list_count(_ml);
    libvlc_media_list_unlock(_ml);
    return icnt;
}

bool vlc_player::delete_item(unsigned int idx)
{
    if( !is_open() )
        return false;

    libvlc_media_list_lock(_ml);
    bool ret = libvlc_media_list_remove_index(_ml, idx) == 0;
    libvlc_media_list_unlock(_ml);

    return ret;
}

void vlc_player::clear_items()
{
    if( !is_open() )
        return;

    libvlc_media_list_lock(_ml);
    for( int i = libvlc_media_list_count(_ml); i > 0; --i) {
        libvlc_media_list_remove_index(_ml, i - 1);
    }
    libvlc_media_list_unlock(_ml);
}

void vlc_player::play()
{
    if( !is_open() )
        return;

    if( 0 == items_count() )
        return;
    else if( -1 == current_item() ) {
        play(0);
    }
    else {
        libvlc_media_list_player_play(_ml_p);
        on_player_action(pa_play);
    }
}

bool vlc_player::play(unsigned int idx)
{
    if( !is_open() )
        return false;

    const int r = libvlc_media_list_player_play_item_at_index(_ml_p, idx);
    if( 0 == r ) {
        on_player_action(pa_play);
        return true;
    }

    return false;
}

void vlc_player::pause()
{
    if( is_open() ) {
        libvlc_media_list_player_pause(_ml_p);
        on_player_action(pa_pause);
    }
}

void vlc_player::stop()
{
    if( is_open() ){
        libvlc_media_list_player_stop(_ml_p);
        on_player_action(pa_stop);
    }
}

bool vlc_player::next()
{
    if( !is_open() )
        return false;

    const int r = libvlc_media_list_player_next(_ml_p);
    if( 0 == r ) {
        on_player_action(pa_next);
        return true;
    }

    return false;
}

bool vlc_player::prev()
{
    if( !is_open() )
        return false;

    const int r = libvlc_media_list_player_previous(_ml_p);
    if( 0 == r ) {
        on_player_action(pa_prev);
        return true;
    }

    return false;
}

float vlc_player::get_rate()
{
    if( !is_open() )
        return 1.f;

    return libvlc_media_player_get_rate(_mp);
}

void vlc_player::set_rate(float rate)
{
    if( !is_open() )
        return;

    libvlc_media_player_set_rate(_mp, rate);
}

float vlc_player::get_fps()
{
    if( !is_open() )
        return 0;

    return libvlc_media_player_get_fps(_mp);
}

bool vlc_player::has_vout()
{
    if( !is_open() )
        return false;

    return libvlc_media_player_has_vout(_mp) > 0;
}

float vlc_player::get_position()
{
    if( !is_open() )
        return 0.f;

    float p = libvlc_media_player_get_position(_mp);

    return p<0 ? 0 : p;
}

void vlc_player::set_position(float p)
{
    if( !is_open() )
        return;

    libvlc_media_player_set_position(_mp, p);
}

libvlc_time_t vlc_player::get_time()
{
    if( !is_open() )
        return 0;

    libvlc_time_t t = libvlc_media_player_get_time(_mp);

    return t<0 ? 0 : t ;
}

void vlc_player::set_time(libvlc_time_t t)
{
    if( !is_open() )
        return;

    libvlc_media_player_set_time(_mp, t);
}

libvlc_time_t vlc_player::get_length()
{
    if( !is_open() )
        return 0;

    libvlc_time_t t = libvlc_media_player_get_length(_mp);

    return t<0 ? 0 : t ;
}

void vlc_player::set_mode(libvlc_playback_mode_t mode)
{
    if( is_open() )
        libvlc_media_list_player_set_playback_mode(_ml_p, mode);
}

bool vlc_player::is_muted()
{
    if( !is_open() )
        return false;

    return libvlc_audio_get_mute(_mp) != 0;
}

void vlc_player::toggle_mute()
{
    if( is_open() )
        libvlc_audio_toggle_mute(_mp);
}

void vlc_player::set_mute(bool mute)
{
    if( is_open() )
        libvlc_audio_set_mute(_mp, mute);
}

unsigned int vlc_player::get_volume()
{
    if( !is_open() )
        return 0;

    int v = libvlc_audio_get_volume(_mp);

    return v<0 ? 0 : v;
}

void vlc_player::set_volume(unsigned int volume)
{
    if( is_open() )
        libvlc_audio_set_volume(_mp, volume);
}

unsigned int vlc_player::track_count()
{
    if( !is_open() )
        return 0;

    int tc = libvlc_audio_get_track_count(_mp);

    return tc<0 ? 0 : tc ;
}

unsigned int vlc_player::get_track()
{
    if( !is_open() )
        return 0;

    int t = libvlc_audio_get_track(_mp);

    return t<0 ? 0 : t ;
}

void vlc_player::set_track(unsigned int track)
{
    if( is_open() )
        libvlc_audio_set_track(_mp, track);
}

libvlc_audio_output_channel_t vlc_player::get_channel()
{
    if( !is_open() )
        return libvlc_AudioChannel_Error;

    return (libvlc_audio_output_channel_t) libvlc_audio_get_channel(_mp);
}

void vlc_player::set_channel(libvlc_audio_output_channel_t channel)
{
    if( is_open() )
        libvlc_audio_set_channel(_mp, channel);
}

////////////////////////////////////////////////////////////////////////////////
float vlc_player_video::get_ajust_filter_var( libvlc_video_adjust_option_t option,
                                              float def_v )
{
    if( m_vp->is_open() ) {
        return libvlc_video_get_adjust_float( m_vp->get_mp(), option );
    }
    else return def_v;
}

void vlc_player_video::set_ajust_filter_var( libvlc_video_adjust_option_t option,
                                             float val )
{
    if( m_vp->is_open() ) {
        libvlc_video_set_adjust_float( m_vp->get_mp(), option, val );
    }
}
<|endoftext|>


<commit_before>#include "domain.h"
#include "person.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include "data.h"
#include "console.h"

using namespace std;

Domain::Domain()
{
asdf
}

bool agePerson (const Person& lsh, const Person& rhs) // sort by birthyear
{
    return (lsh.getBirth() < rhs.getBirth());
}

void Domain::ageSorting(vector<Person>& ageSort) //sort by birthyear
{
    std::sort(ageSort.begin(), ageSort.end(), agePerson);
}

bool nameAlpha(const Person& lhs, const Person& rhs)
{
    return (lhs.getName() < rhs.getName());
}

void Domain::alphabeticSort(vector<Person>& alphaSort)
{
    std::sort(alphaSort.begin(), alphaSort.end(), nameAlpha);
}

int Domain::findAge(Person& sciAge) const
{
    int x;
    int y;
    int resultDead;
    int resultAlive;
    const int currentYear = 2016;
    x = sciAge.getDeath();
    y = sciAge.getBirth();

    if(x == 0)
    {
        resultAlive = currentYear - y;
        return resultAlive;
    }
    else
    {
        resultDead = x - y;
        return resultDead;
    }
}

vector<Person> Domain::search(vector<Person>& p, string name)
{
    vector<Person> results;
//Search function, we search from out vector and then put the results in another vector so it shows us all results
    for(unsigned int i = 0; i < p.size(); i++)
    {
        string nameFind;
        char genderFind;
        int birthFind;
        int deathFind;
        nameFind = p[i].getName();
        std::size_t found = nameFind.find(name);

        if (found!=std::string::npos)
        {
            p[i].getName();
            genderFind = p[i].getGender();
            birthFind = p[i].getBirth();
            deathFind = p[i].getDeath();
            Person p2(nameFind, genderFind, birthFind, deathFind);
            results.push_back(p2);
        }
    }
    return results;
}
<commit_msg>testa email<commit_after>#include "domain.h"
#include "person.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include "data.h"
#include "console.h"

using namespace std;

Domain::Domain()
{

}

bool agePerson (const Person& lsh, const Person& rhs) // sort by birthyear
{
    return (lsh.getBirth() < rhs.getBirth());
}

void Domain::ageSorting(vector<Person>& ageSort) //sort by birthyear
{
    std::sort(ageSort.begin(), ageSort.end(), agePerson);
}

bool nameAlpha(const Person& lhs, const Person& rhs)
{
    return (lhs.getName() < rhs.getName());
}

void Domain::alphabeticSort(vector<Person>& alphaSort)
{
    std::sort(alphaSort.begin(), alphaSort.end(), nameAlpha);
}

int Domain::findAge(Person& sciAge) const
{
    int x;
    int y;
    int resultDead;
    int resultAlive;
    const int currentYear = 2016;
    x = sciAge.getDeath();
    y = sciAge.getBirth();

    if(x == 0)
    {
        resultAlive = currentYear - y;
        return resultAlive;
    }
    else
    {
        resultDead = x - y;
        return resultDead;
    }
}

vector<Person> Domain::search(vector<Person>& p, string name)
{
    vector<Person> results;
//Search function, we search from out vector and then put the results in another vector so it shows us all results
    for(unsigned int i = 0; i < p.size(); i++)
    {
        string nameFind;
        char genderFind;
        int birthFind;
        int deathFind;
        nameFind = p[i].getName();
        std::size_t found = nameFind.find(name);

        if (found!=std::string::npos)
        {
            p[i].getName();
            genderFind = p[i].getGender();
            birthFind = p[i].getBirth();
            deathFind = p[i].getDeath();
            Person p2(nameFind, genderFind, birthFind, deathFind);
            results.push_back(p2);
        }
    }
    return results;
}
<|endoftext|>