<commit_before>#include <babylon/materialslibrary/simple/simple_material.h>

#include <nlohmann/json.hpp>

#include <babylon/cameras/camera.h>
#include <babylon/engines/engine.h>
#include <babylon/engines/scene.h>
#include <babylon/materials/effect.h>
#include <babylon/materials/effect_creation_options.h>
#include <babylon/materials/effect_fallbacks.h>
#include <babylon/materials/material_helper.h>
#include <babylon/materials/standard_material.h>
#include <babylon/materials/textures/texture.h>
#include <babylon/materialslibrary/simple/simple_fragment_fx.h>
#include <babylon/materialslibrary/simple/simple_vertex_fx.h>
#include <babylon/meshes/abstract_mesh.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/sub_mesh.h>
#include <babylon/meshes/vertex_buffer.h>

namespace BABYLON {
namespace MaterialsLibrary {

SimpleMaterial::SimpleMaterial(const std::string& iName, Scene* scene)
    : PushMaterial{iName, scene}
    , diffuseTexture{this, &SimpleMaterial::get_diffuseTexture,
                     &SimpleMaterial::set_diffuseTexture}
    , diffuseColor{Color3(1.f, 1.f, 1.f)}
    , disableLighting{this, &SimpleMaterial::get_disableLighting,
                      &SimpleMaterial::set_disableLighting}
    , maxSimultaneousLights{this, &SimpleMaterial::get_maxSimultaneousLights,
                            &SimpleMaterial::set_maxSimultaneousLights}
    , _diffuseTexture{nullptr}
    , _disableLighting{false}
    , _maxSimultaneousLights{4}
    , _renderId{-1}
{
  // Vertex shader
  Effect::ShadersStore()["simpleVertexShader"] = simpleVertexShader;

  // Fragment shader
  Effect::ShadersStore()["simplePixelShader"] = simplePixelShader;
}

SimpleMaterial::~SimpleMaterial() = default;

TexturePtr& SimpleMaterial::get_diffuseTexture()
{
  return _diffuseTexture;
}

void SimpleMaterial::set_diffuseTexture(const TexturePtr& value)
{
  if (_diffuseTexture != value) {
    _diffuseTexture = value;
    _markAllSubMeshesAsTexturesDirty();
  }
}

bool SimpleMaterial::get_disableLighting() const
{
  return _disableLighting;
}

void SimpleMaterial::set_disableLighting(bool value)
{
  if (_disableLighting != value) {
    _disableLighting = value;
    _markAllSubMeshesAsLightsDirty();
  }
}

unsigned int SimpleMaterial::get_maxSimultaneousLights() const
{
  return _maxSimultaneousLights;
}

void SimpleMaterial::set_maxSimultaneousLights(unsigned int value)
{
  if (_maxSimultaneousLights != value) {
    _maxSimultaneousLights = value;
    _markAllSubMeshesAsLightsDirty();
  }
}

bool SimpleMaterial::needAlphaBlending() const
{
  return (alpha < 1.f);
}

bool SimpleMaterial::needAlphaTesting() const
{
  return false;
}

BaseTexturePtr SimpleMaterial::getAlphaTestTexture()
{
  return nullptr;
}

bool SimpleMaterial::isReadyForSubMesh(AbstractMesh* mesh, BaseSubMesh* subMesh,
                                       bool useInstances)
{
  if (isFrozen()) {
    if (_wasPreviouslyReady && subMesh->effect()) {
      return true;
    }
  }

  if (!subMesh->_materialDefines) {
    subMesh->_materialDefines = std::make_shared<SimpleMaterialDefines>();
  }

  auto definesPtr = std::static_pointer_cast<SimpleMaterialDefines>(
    subMesh->_materialDefines);
  auto& defines = *definesPtr.get();
  auto scene    = getScene();

  if (!checkReadyOnEveryCall && subMesh->effect()) {
    if (_renderId == scene->getRenderId()) {
      return true;
    }
  }

  auto engine = scene->getEngine();

  // Textures
  if (defines._areTexturesDirty) {
    defines._needUVs = false;
    if (scene->texturesEnabled()) {
      if (_diffuseTexture && StandardMaterial::DiffuseTextureEnabled()) {
        if (!_diffuseTexture->isReady()) {
          return false;
        }
        else {
          defines._needUVs           = true;
          defines.boolDef["DIFFUSE"] = true;
        }
      }
    }
  }

  // Misc.
  MaterialHelper::PrepareDefinesForMisc(mesh, scene, false, pointsCloud(),
                                        fogEnabled(),
                                        _shouldTurnAlphaTestOn(mesh), defines);

  // Lights
  defines._needNormals = MaterialHelper::PrepareDefinesForLights(
    scene, mesh, defines, false, _maxSimultaneousLights, _disableLighting);

  // Values that need to be evaluated on every frame
  MaterialHelper::PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);

  // Attribs
  MaterialHelper::PrepareDefinesForAttributes(mesh, defines, true, true);

  // Get correct effect
  if (defines.isDirty()) {
    defines.markAsProcessed();
    scene->resetCachedMaterial();

    // Fallbacks
    auto fallbacks = std::make_unique<EffectFallbacks>();
    if (defines["FOG"]) {
      fallbacks->addFallback(1, "FOG");
    }

    MaterialHelper::HandleFallbacksForShadows(defines, *fallbacks,
                                              maxSimultaneousLights());

    if (defines.intDef["NUM_BONE_INFLUENCERS"] > 0) {
      fallbacks->addCPUSkinningFallback(0, mesh);
    }

    // Attributes
    std::vector<std::string> attribs{VertexBuffer::PositionKind};

    if (defines["NORMAL"]) {
      attribs.emplace_back(VertexBuffer::NormalKind);
    }

    if (defines["UV1"]) {
      attribs.emplace_back(VertexBuffer::UVKind);
    }

    if (defines["UV2"]) {
      attribs.emplace_back(VertexBuffer::UV2Kind);
    }

    if (defines["VERTEXCOLOR"]) {
      attribs.emplace_back(VertexBuffer::ColorKind);
    }

    MaterialHelper::PrepareAttributesForBones(attribs, mesh, defines,
                                              *fallbacks);
    MaterialHelper::PrepareAttributesForInstances(attribs, defines);

    const std::string shaderName{"simple"};
    auto join = defines.toString();
    const std::vector<std::string> uniforms{
      "world",       "view",          "viewProjection", "vEyePosition",
      "vLightsType", "vDiffuseColor", "vFogInfos",      "vFogColor",
      "pointSize",   "vDiffuseInfos", "mBones",         "vClipPlane",
      "vClipPlane2", "vClipPlane3",   "vClipPlane4",    "diffuseMatrix"};
    const std::vector<std::string> samplers{"diffuseSampler"};
    const std::vector<std::string> uniformBuffers{};

    EffectCreationOptions options;
    options.attributes            = std::move(attribs);
    options.uniformsNames         = std::move(uniforms);
    options.uniformBuffersNames   = std::move(uniformBuffers);
    options.samplers              = std::move(samplers);
    options.materialDefines       = &defines;
    options.defines               = std::move(join);
    options.maxSimultaneousLights = maxSimultaneousLights();
    options.fallbacks             = std::move(fallbacks);
    options.onCompiled            = onCompiled;
    options.onError               = onError;
    options.indexParameters
      = {{"maxSimultaneousLights", maxSimultaneousLights()}};

    MaterialHelper::PrepareUniformsAndSamplersList(options);
    subMesh->setEffect(
      scene->getEngine()->createEffect(shaderName, options, engine),
      definesPtr);
  }

  if (!subMesh->effect() || !subMesh->effect()->isReady()) {
    return false;
  }

  _renderId           = scene->getRenderId();
  _wasPreviouslyReady = true;

  return true;
}

void SimpleMaterial::bindForSubMesh(Matrix& world, Mesh* mesh, SubMesh* subMesh)
{
  auto scene = getScene();

  auto defines
    = static_cast<SimpleMaterialDefines*>(subMesh->_materialDefines.get());
  if (!defines) {
    return;
  }

  auto effect = subMesh->effect();
  if (!effect) {
    return;
  }
  _activeEffect = effect;

  // Matrices
  bindOnlyWorldMatrix(world);
  _activeEffect->setMatrix("viewProjection", scene->getTransformMatrix());

  // Bones
  MaterialHelper::BindBonesParameters(mesh, _activeEffect);

  if (_mustRebind(scene, effect)) {
    // Textures
    if (_diffuseTexture && StandardMaterial::DiffuseTextureEnabled()) {
      _activeEffect->setTexture("diffuseSampler", _diffuseTexture);

      _activeEffect->setFloat2(
        "vDiffuseInfos", static_cast<float>(_diffuseTexture->coordinatesIndex),
        _diffuseTexture->level);
      _activeEffect->setMatrix("diffuseMatrix",
                               *_diffuseTexture->getTextureMatrix());
    }

    // Clip plane
    MaterialHelper::BindClipPlane(_activeEffect, scene);

    // Point size
    if (pointsCloud()) {
      _activeEffect->setFloat("pointSize", pointSize);
    }

    MaterialHelper::BindEyePosition(effect, scene);
  }

  _activeEffect->setColor4("vDiffuseColor", diffuseColor,
                           alpha * mesh->visibility);

  // Lights
  if (scene->lightsEnabled() && !_disableLighting) {
    MaterialHelper::BindLights(scene, mesh, _activeEffect, *defines,
                               maxSimultaneousLights());
  }

  // View
  if (scene->fogEnabled() && mesh->applyFog()
      && scene->fogMode() != Scene::FOGMODE_NONE) {
    _activeEffect->setMatrix("view", scene->getViewMatrix());
  }

  // Fog
  MaterialHelper::BindFogParameters(scene, mesh, _activeEffect);

  _afterBind(mesh, _activeEffect);
}

std::vector<IAnimatablePtr> SimpleMaterial::getAnimatables()
{
  std::vector<IAnimatablePtr> results;

  if (_diffuseTexture && _diffuseTexture->animations.size() > 0) {
    results.emplace_back(_diffuseTexture);
  }

  return results;
}

std::vector<BaseTexturePtr> SimpleMaterial::getActiveTextures() const
{
  auto activeTextures = PushMaterial::getActiveTextures();

  if (_diffuseTexture) {
    activeTextures.emplace_back(_diffuseTexture);
  }

  return activeTextures;
}

bool SimpleMaterial::hasTexture(const BaseTexturePtr& texture) const
{
  if (PushMaterial::hasTexture(texture)) {
    return true;
  }

  if (_diffuseTexture == texture) {
    return true;
  }

  return false;
}

void SimpleMaterial::dispose(bool forceDisposeEffect, bool forceDisposeTextures,
                             bool /*notBoundToMesh*/)
{
  if (_diffuseTexture) {
    _diffuseTexture->dispose();
  }

  PushMaterial::dispose(forceDisposeEffect, forceDisposeTextures);
}

MaterialPtr SimpleMaterial::clone(const std::string& /*name*/,
                                  bool /*cloneChildren*/) const
{
  return nullptr;
}

json SimpleMaterial::serialize() const
{
  return nullptr;
}

std::string SimpleMaterial::getClassName() const
{
  return "SimpleMaterial";
}

SimpleMaterial* SimpleMaterial::Parse(const json& /*source*/, Scene* /*scene*/,
                                      const std::string& /*rootUrl*/)
{
  return nullptr;
}

} // end of namespace MaterialsLibrary
} // end of namespace BABYLON
<commit_msg>Updated Simple Material to v4.1.0-alpha.17<commit_after>#include <babylon/materialslibrary/simple/simple_material.h>

#include <nlohmann/json.hpp>

#include <babylon/cameras/camera.h>
#include <babylon/engines/engine.h>
#include <babylon/engines/scene.h>
#include <babylon/materials/effect.h>
#include <babylon/materials/effect_creation_options.h>
#include <babylon/materials/effect_fallbacks.h>
#include <babylon/materials/material_flags.h>
#include <babylon/materials/material_helper.h>
#include <babylon/materials/textures/texture.h>
#include <babylon/materialslibrary/simple/simple_fragment_fx.h>
#include <babylon/materialslibrary/simple/simple_vertex_fx.h>
#include <babylon/meshes/abstract_mesh.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/sub_mesh.h>
#include <babylon/meshes/vertex_buffer.h>

namespace BABYLON {
namespace MaterialsLibrary {

SimpleMaterial::SimpleMaterial(const std::string& iName, Scene* scene)
    : PushMaterial{iName, scene}
    , diffuseTexture{this, &SimpleMaterial::get_diffuseTexture, &SimpleMaterial::set_diffuseTexture}
    , diffuseColor{Color3(1.f, 1.f, 1.f)}
    , disableLighting{this, &SimpleMaterial::get_disableLighting,
                      &SimpleMaterial::set_disableLighting}
    , maxSimultaneousLights{this, &SimpleMaterial::get_maxSimultaneousLights,
                            &SimpleMaterial::set_maxSimultaneousLights}
    , _diffuseTexture{nullptr}
    , _disableLighting{false}
    , _maxSimultaneousLights{4}
    , _renderId{-1}
{
  // Vertex shader
  Effect::ShadersStore()["simpleVertexShader"] = simpleVertexShader;

  // Fragment shader
  Effect::ShadersStore()["simplePixelShader"] = simplePixelShader;
}

SimpleMaterial::~SimpleMaterial() = default;

TexturePtr& SimpleMaterial::get_diffuseTexture()
{
  return _diffuseTexture;
}

void SimpleMaterial::set_diffuseTexture(const TexturePtr& value)
{
  if (_diffuseTexture != value) {
    _diffuseTexture = value;
    _markAllSubMeshesAsTexturesDirty();
  }
}

bool SimpleMaterial::get_disableLighting() const
{
  return _disableLighting;
}

void SimpleMaterial::set_disableLighting(bool value)
{
  if (_disableLighting != value) {
    _disableLighting = value;
    _markAllSubMeshesAsLightsDirty();
  }
}

unsigned int SimpleMaterial::get_maxSimultaneousLights() const
{
  return _maxSimultaneousLights;
}

void SimpleMaterial::set_maxSimultaneousLights(unsigned int value)
{
  if (_maxSimultaneousLights != value) {
    _maxSimultaneousLights = value;
    _markAllSubMeshesAsLightsDirty();
  }
}

bool SimpleMaterial::needAlphaBlending() const
{
  return (alpha < 1.f);
}

bool SimpleMaterial::needAlphaTesting() const
{
  return false;
}

BaseTexturePtr SimpleMaterial::getAlphaTestTexture()
{
  return nullptr;
}

bool SimpleMaterial::isReadyForSubMesh(AbstractMesh* mesh, BaseSubMesh* subMesh, bool useInstances)
{
  if (isFrozen()) {
    if (_wasPreviouslyReady && subMesh->effect()) {
      return true;
    }
  }

  if (!subMesh->_materialDefines) {
    subMesh->_materialDefines = std::make_shared<SimpleMaterialDefines>();
  }

  auto definesPtr = std::static_pointer_cast<SimpleMaterialDefines>(subMesh->_materialDefines);
  auto& defines   = *definesPtr.get();
  auto scene      = getScene();

  if (!checkReadyOnEveryCall && subMesh->effect()) {
    if (_renderId == scene->getRenderId()) {
      return true;
    }
  }

  auto engine = scene->getEngine();

  // Textures
  if (defines._areTexturesDirty) {
    defines._needUVs = false;
    if (scene->texturesEnabled()) {
      if (_diffuseTexture && MaterialFlags::DiffuseTextureEnabled()) {
        if (!_diffuseTexture->isReady()) {
          return false;
        }
        else {
          defines._needUVs           = true;
          defines.boolDef["DIFFUSE"] = true;
        }
      }
    }
  }

  // Misc.
  MaterialHelper::PrepareDefinesForMisc(mesh, scene, false, pointsCloud(), fogEnabled(),
                                        _shouldTurnAlphaTestOn(mesh), defines);

  // Lights
  defines._needNormals = MaterialHelper::PrepareDefinesForLights(
    scene, mesh, defines, false, _maxSimultaneousLights, _disableLighting);

  // Values that need to be evaluated on every frame
  MaterialHelper::PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);

  // Attribs
  MaterialHelper::PrepareDefinesForAttributes(mesh, defines, true, true);

  // Get correct effect
  if (defines.isDirty()) {
    defines.markAsProcessed();
    scene->resetCachedMaterial();

    // Fallbacks
    auto fallbacks = std::make_unique<EffectFallbacks>();
    if (defines["FOG"]) {
      fallbacks->addFallback(1, "FOG");
    }

    MaterialHelper::HandleFallbacksForShadows(defines, *fallbacks, maxSimultaneousLights());

    if (defines.intDef["NUM_BONE_INFLUENCERS"] > 0) {
      fallbacks->addCPUSkinningFallback(0, mesh);
    }

    // Attributes
    std::vector<std::string> attribs{VertexBuffer::PositionKind};

    if (defines["NORMAL"]) {
      attribs.emplace_back(VertexBuffer::NormalKind);
    }

    if (defines["UV1"]) {
      attribs.emplace_back(VertexBuffer::UVKind);
    }

    if (defines["UV2"]) {
      attribs.emplace_back(VertexBuffer::UV2Kind);
    }

    if (defines["VERTEXCOLOR"]) {
      attribs.emplace_back(VertexBuffer::ColorKind);
    }

    MaterialHelper::PrepareAttributesForBones(attribs, mesh, defines, *fallbacks);
    MaterialHelper::PrepareAttributesForInstances(attribs, defines);

    const std::string shaderName{"simple"};
    auto join = defines.toString();
    const std::vector<std::string> uniforms{
      "world",       "view",          "viewProjection", "vEyePosition",
      "vLightsType", "vDiffuseColor", "vFogInfos",      "vFogColor",
      "pointSize",   "vDiffuseInfos", "mBones",         "vClipPlane",
      "vClipPlane2", "vClipPlane3",   "vClipPlane4",    "diffuseMatrix"};
    const std::vector<std::string> samplers{"diffuseSampler"};
    const std::vector<std::string> uniformBuffers{};

    EffectCreationOptions options;
    options.attributes            = std::move(attribs);
    options.uniformsNames         = std::move(uniforms);
    options.uniformBuffersNames   = std::move(uniformBuffers);
    options.samplers              = std::move(samplers);
    options.materialDefines       = &defines;
    options.defines               = std::move(join);
    options.maxSimultaneousLights = maxSimultaneousLights();
    options.fallbacks             = std::move(fallbacks);
    options.onCompiled            = onCompiled;
    options.onError               = onError;
    options.indexParameters       = {{"maxSimultaneousLights", maxSimultaneousLights()}};

    MaterialHelper::PrepareUniformsAndSamplersList(options);
    subMesh->setEffect(scene->getEngine()->createEffect(shaderName, options, engine), definesPtr);
  }

  if (!subMesh->effect() || !subMesh->effect()->isReady()) {
    return false;
  }

  _renderId           = scene->getRenderId();
  _wasPreviouslyReady = true;

  return true;
}

void SimpleMaterial::bindForSubMesh(Matrix& world, Mesh* mesh, SubMesh* subMesh)
{
  auto scene = getScene();

  auto defines = static_cast<SimpleMaterialDefines*>(subMesh->_materialDefines.get());
  if (!defines) {
    return;
  }

  auto effect = subMesh->effect();
  if (!effect) {
    return;
  }
  _activeEffect = effect;

  // Matrices
  bindOnlyWorldMatrix(world);
  _activeEffect->setMatrix("viewProjection", scene->getTransformMatrix());

  // Bones
  MaterialHelper::BindBonesParameters(mesh, _activeEffect);

  if (_mustRebind(scene, effect)) {
    // Textures
    if (_diffuseTexture && MaterialFlags::DiffuseTextureEnabled()) {
      _activeEffect->setTexture("diffuseSampler", _diffuseTexture);

      _activeEffect->setFloat2("vDiffuseInfos",
                               static_cast<float>(_diffuseTexture->coordinatesIndex),
                               _diffuseTexture->level);
      _activeEffect->setMatrix("diffuseMatrix", *_diffuseTexture->getTextureMatrix());
    }

    // Clip plane
    MaterialHelper::BindClipPlane(_activeEffect, scene);

    // Point size
    if (pointsCloud()) {
      _activeEffect->setFloat("pointSize", pointSize);
    }

    MaterialHelper::BindEyePosition(effect, scene);
  }

  _activeEffect->setColor4("vDiffuseColor", diffuseColor, alpha * mesh->visibility);

  // Lights
  if (scene->lightsEnabled() && !_disableLighting) {
    MaterialHelper::BindLights(scene, mesh, _activeEffect, *defines, maxSimultaneousLights());
  }

  // View
  if (scene->fogEnabled() && mesh->applyFog() && scene->fogMode() != Scene::FOGMODE_NONE) {
    _activeEffect->setMatrix("view", scene->getViewMatrix());
  }

  // Fog
  MaterialHelper::BindFogParameters(scene, mesh, _activeEffect);

  _afterBind(mesh, _activeEffect);
}

std::vector<IAnimatablePtr> SimpleMaterial::getAnimatables()
{
  std::vector<IAnimatablePtr> results;

  if (_diffuseTexture && _diffuseTexture->animations.size() > 0) {
    results.emplace_back(_diffuseTexture);
  }

  return results;
}

std::vector<BaseTexturePtr> SimpleMaterial::getActiveTextures() const
{
  auto activeTextures = PushMaterial::getActiveTextures();

  if (_diffuseTexture) {
    activeTextures.emplace_back(_diffuseTexture);
  }

  return activeTextures;
}

bool SimpleMaterial::hasTexture(const BaseTexturePtr& texture) const
{
  if (PushMaterial::hasTexture(texture)) {
    return true;
  }

  if (_diffuseTexture == texture) {
    return true;
  }

  return false;
}

void SimpleMaterial::dispose(bool forceDisposeEffect, bool forceDisposeTextures,
                             bool /*notBoundToMesh*/)
{
  if (_diffuseTexture) {
    _diffuseTexture->dispose();
  }

  PushMaterial::dispose(forceDisposeEffect, forceDisposeTextures);
}

MaterialPtr SimpleMaterial::clone(const std::string& /*name*/, bool /*cloneChildren*/) const
{
  return nullptr;
}

json SimpleMaterial::serialize() const
{
  return nullptr;
}

std::string SimpleMaterial::getClassName() const
{
  return "SimpleMaterial";
}

SimpleMaterial* SimpleMaterial::Parse(const json& /*source*/, Scene* /*scene*/,
                                      const std::string& /*rootUrl*/)
{
  return nullptr;
}

} // end of namespace MaterialsLibrary
} // end of namespace BABYLON
<|endoftext|>


<commit_before>#include <iostream>
#include <list>
#include <limits>
#include <algorithm>
#include "EnPhrasalVerb.h"
#include "moses/Util.h"

using namespace std;

void EnPhrasalVerb(const Phrase &source, ostream &out)
{
  typedef pair<int,int> Range;
  typedef list<Range> Ranges;
  Ranges ranges;

  // find ranges to label
  for (int start = 0; start < source.size(); ++start) {
	size_t end = std::numeric_limits<size_t>::max();

	if (IsA(source, start, 0, 0, "ask asked asking")) {
		end = Found(source, start, 0, "out");
    }
	else if (IsA(source, start, 0, 0, "back backed backing")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "blow blown blew")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "break broke broken")) {
		end = Found(source, start, 0, "down up in");
	}
	else if (IsA(source, start, 0, 0, "bring brought bringing")) {
		end = Found(source, start, 0, "down up in");
	}
	else if (IsA(source, start, 0, 0, "call called calling")) {
		end = Found(source, start, 0, "back up off");
	}
	else if (IsA(source, start, 0, 0, "check checked checking")) {
		end = Found(source, start, 0, "out in");
	}
	else if (IsA(source, start, 0, 0, "cheer cheered cheering")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "clean cleaned cleaning")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "cross crossed crossing")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "cut cutting")) {
		end = Found(source, start, 0, "down off out");
	}
	else if (IsA(source, start, 0, 0, "do did done")) {
		end = Found(source, start, 0, "over up");
	}
	else if (IsA(source, start, 0, 0, "drop dropped dropping")) {
		end = Found(source, start, 0, "off");
	}
	else if (IsA(source, start, 0, 0, "figure figured figuring")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "fill filled filling")) {
		end = Found(source, start, 0, "in out up");
	}
	else if (IsA(source, start, 0, 0, "find found finding")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "get got getting gotten")) {
		end = Found(source, start, 0, "across over back");
	}
	else if (IsA(source, start, 0, 0, "give given gave giving")) {
		end = Found(source, start, 0, "away back out up");
	}
	else if (IsA(source, start, 0, 0, "hand handed handing")) {
		end = Found(source, start, 0, "down in over");
	}
	else if (IsA(source, start, 0, 0, "hold held holding")) {
		end = Found(source, start, 0, "back up");
	}
	else if (IsA(source, start, 0, 0, "keep kept keeping")) {
		end = Found(source, start, 0, "from up");
	}
	else if (IsA(source, start, 0, 0, "let letting")) {
		end = Found(source, start, 0, "down in");
	}
	else if (IsA(source, start, 0, 0, "look looked looking")) {
		end = Found(source, start, 0, "over up");
	}
	else if (IsA(source, start, 0, 0, "make made making")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "mix mixed mixing")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "pass passed passing")) {
		end = Found(source, start, 0, "out up");
	}
	else if (IsA(source, start, 0, 0, "pay payed paying")) {
		end = Found(source, start, 0, "back");
	}
	else if (IsA(source, start, 0, 0, "pick picked picking")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "point pointed pointing")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "put putting")) {
		end = Found(source, start, 0, "down off out together on");
	}
	else if (IsA(source, start, 0, 0, "send sending")) {
		end = Found(source, start, 0, "back");
	}
	else if (IsA(source, start, 0, 0, "set setting")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "sort sorted sorting")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "switch switched switching")) {
		end = Found(source, start, 0, "off on");
	}
	else if (IsA(source, start, 0, 0, "take took taking")) {
		end = Found(source, start, 0, "apart back off out");
	}
	else if (IsA(source, start, 0, 0, "tear torn tearing")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "think thought thinking")) {
		end = Found(source, start, 0, "over");
	}
	else if (IsA(source, start, 0, 0, "thrown threw thrown throwing")) {
		end = Found(source, start, 0, "away");
	}
	else if (IsA(source, start, 0, 0, "turn turned turning")) {
		end = Found(source, start, 0, "down off on");
	}
	else if (IsA(source, start, 0, 0, "try tried trying")) {
		end = Found(source, start, 0, "on out");
	}
	else if (IsA(source, start, 0, 0, "use used using")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "warm warmed warming")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "work worked working")) {
		end = Found(source, start, 0, "out");
	}

	// found range to label
	if (end == std::numeric_limits<size_t>::max() &&
			end > start + 1) {
        Range range(start, end);
        ranges.push_back(range);
	}
  }

  OutputWithLabels(source, ranges, out);
}

size_t Found(const Phrase &source, int pos, int factor, const std::string &str)
{
  const size_t MAX_RANGE = 10;

  vector<string> soughts = Moses::Tokenize(str, " ");
  vector<string> puncts = Moses::Tokenize(str, ". : , ;");

  size_t maxEnd = std::min(source.size(), (size_t) pos + MAX_RANGE);
  for (size_t i = pos + 1; i < maxEnd; ++i) {
	const Word &word = source[i];
	bool found;

	found = Found(word, factor, puncts);
	if (found) {
		return std::numeric_limits<size_t>::max();
	}

	found = Found(word, factor, soughts);
	if (found) {
		return i;
	}
  }

  return std::numeric_limits<size_t>::max();
}

bool Found(const Word &word, int factor, const vector<string> &soughts)
{
  const string &element = word[factor];
  for (size_t i = 0; i < soughts.size(); ++i) {
	const string &sought = soughts[i];
	bool found = (element == sought);
	if (found) {
	  return true;
	}
  }
  return false;
}

<commit_msg>label the intervening span, don't include the phrasal verbs itself<commit_after>#include <iostream>
#include <list>
#include <limits>
#include <algorithm>
#include "EnPhrasalVerb.h"
#include "moses/Util.h"

using namespace std;

void EnPhrasalVerb(const Phrase &source, ostream &out)
{
  typedef pair<int,int> Range;
  typedef list<Range> Ranges;
  Ranges ranges;

  // find ranges to label
  for (int start = 0; start < source.size(); ++start) {
	size_t end = std::numeric_limits<size_t>::max();

	if (IsA(source, start, 0, 0, "ask asked asking")) {
		end = Found(source, start, 0, "out");
    }
	else if (IsA(source, start, 0, 0, "back backed backing")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "blow blown blew")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "break broke broken")) {
		end = Found(source, start, 0, "down up in");
	}
	else if (IsA(source, start, 0, 0, "bring brought bringing")) {
		end = Found(source, start, 0, "down up in");
	}
	else if (IsA(source, start, 0, 0, "call called calling")) {
		end = Found(source, start, 0, "back up off");
	}
	else if (IsA(source, start, 0, 0, "check checked checking")) {
		end = Found(source, start, 0, "out in");
	}
	else if (IsA(source, start, 0, 0, "cheer cheered cheering")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "clean cleaned cleaning")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "cross crossed crossing")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "cut cutting")) {
		end = Found(source, start, 0, "down off out");
	}
	else if (IsA(source, start, 0, 0, "do did done")) {
		end = Found(source, start, 0, "over up");
	}
	else if (IsA(source, start, 0, 0, "drop dropped dropping")) {
		end = Found(source, start, 0, "off");
	}
	else if (IsA(source, start, 0, 0, "figure figured figuring")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "fill filled filling")) {
		end = Found(source, start, 0, "in out up");
	}
	else if (IsA(source, start, 0, 0, "find found finding")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "get got getting gotten")) {
		end = Found(source, start, 0, "across over back");
	}
	else if (IsA(source, start, 0, 0, "give given gave giving")) {
		end = Found(source, start, 0, "away back out up");
	}
	else if (IsA(source, start, 0, 0, "hand handed handing")) {
		end = Found(source, start, 0, "down in over");
	}
	else if (IsA(source, start, 0, 0, "hold held holding")) {
		end = Found(source, start, 0, "back up");
	}
	else if (IsA(source, start, 0, 0, "keep kept keeping")) {
		end = Found(source, start, 0, "from up");
	}
	else if (IsA(source, start, 0, 0, "let letting")) {
		end = Found(source, start, 0, "down in");
	}
	else if (IsA(source, start, 0, 0, "look looked looking")) {
		end = Found(source, start, 0, "over up");
	}
	else if (IsA(source, start, 0, 0, "make made making")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "mix mixed mixing")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "pass passed passing")) {
		end = Found(source, start, 0, "out up");
	}
	else if (IsA(source, start, 0, 0, "pay payed paying")) {
		end = Found(source, start, 0, "back");
	}
	else if (IsA(source, start, 0, 0, "pick picked picking")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "point pointed pointing")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "put putting")) {
		end = Found(source, start, 0, "down off out together on");
	}
	else if (IsA(source, start, 0, 0, "send sending")) {
		end = Found(source, start, 0, "back");
	}
	else if (IsA(source, start, 0, 0, "set setting")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "sort sorted sorting")) {
		end = Found(source, start, 0, "out");
	}
	else if (IsA(source, start, 0, 0, "switch switched switching")) {
		end = Found(source, start, 0, "off on");
	}
	else if (IsA(source, start, 0, 0, "take took taking")) {
		end = Found(source, start, 0, "apart back off out");
	}
	else if (IsA(source, start, 0, 0, "tear torn tearing")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "think thought thinking")) {
		end = Found(source, start, 0, "over");
	}
	else if (IsA(source, start, 0, 0, "thrown threw thrown throwing")) {
		end = Found(source, start, 0, "away");
	}
	else if (IsA(source, start, 0, 0, "turn turned turning")) {
		end = Found(source, start, 0, "down off on");
	}
	else if (IsA(source, start, 0, 0, "try tried trying")) {
		end = Found(source, start, 0, "on out");
	}
	else if (IsA(source, start, 0, 0, "use used using")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "warm warmed warming")) {
		end = Found(source, start, 0, "up");
	}
	else if (IsA(source, start, 0, 0, "work worked working")) {
		end = Found(source, start, 0, "out");
	}

	// found range to label
	if (end == std::numeric_limits<size_t>::max() &&
			end > start + 1) {
        Range range(start + 1, end - 1);
        ranges.push_back(range);
	}
  }

  OutputWithLabels(source, ranges, out);
}

size_t Found(const Phrase &source, int pos, int factor, const std::string &str)
{
  const size_t MAX_RANGE = 10;

  vector<string> soughts = Moses::Tokenize(str, " ");
  vector<string> puncts = Moses::Tokenize(str, ". : , ;");

  size_t maxEnd = std::min(source.size(), (size_t) pos + MAX_RANGE);
  for (size_t i = pos + 1; i < maxEnd; ++i) {
	const Word &word = source[i];
	bool found;

	found = Found(word, factor, puncts);
	if (found) {
		return std::numeric_limits<size_t>::max();
	}

	found = Found(word, factor, soughts);
	if (found) {
		return i;
	}
  }

  return std::numeric_limits<size_t>::max();
}

bool Found(const Word &word, int factor, const vector<string> &soughts)
{
  const string &element = word[factor];
  for (size_t i = 0; i < soughts.size(); ++i) {
	const string &sought = soughts[i];
	bool found = (element == sought);
	if (found) {
	  return true;
	}
  }
  return false;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 The University of Texas at Austin and the
 * Institute of Human Machine Cognition. All rights reserved.
 *
 * 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. See
 * <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>
 *
 * 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, see
 * <http://www.gnu.org/licenses/>
 */

#ifndef __CONTROLIT_CORE_RT_CONTROL_MODEL_HPP__
#define __CONTROLIT_CORE_RT_CONTROL_MODEL_HPP__

#include <mutex>
#include <thread>
#include <condition_variable>
#include <chrono>

#include <ros/ros.h>

#include <controlit/ControlModel.hpp>
#include <controlit/Constraint.hpp>
#include <controlit/BindingManager.hpp>

#include <controlit/addons/ros/RealTimePublisher.hpp>

// Messages
#include <std_msgs/Float64.h>
#include <controlit_core/HolonomicConstraint.h>
#include "controlit_core/get_constraint_set_jacobians.h"

namespace controlit {

/*!
 * Instantiates two ControlModel objects and manages which
 * one is active.  The active ControlModel is used by the
 * main servo thread to compute the next command.  The inactive
 * ControlModel is used by a child thread to update the model
 * based on the current joint state.  The active and inactive
 * models are swapped when the child thread is done updating
 * the inactive model.
 */
class RTControlModel
{
public:
    /*!
     * The constructor.
     */
    RTControlModel();

    /*!
     * The destructor.
     */
    virtual ~RTControlModel();

    /*!
     * Whether this RTControlModel is initialized.
     */
    bool isInitialized() {return initialized;}

    /*!
     * Sets the robot control models to be stale.  This is to prevent
     * stale models from being used when the controller begins to run.
     */
    void setStale();

    /*!
     * Initialize this RTControlModel.
     *
     * \param[in] nh the ROS node handle.
     * \param[in] robotState A pointer to the latest robot state information.  This is
     * passed to the internal Control Model objects used within this object.
     * \param[in] parameterBindingManager The parameterBindingManager.
     * \param[out] params A pointer to the WBC parameters.  This is necessary to save the
     * joint limit information when the URDF is parsed.
     */
    bool init(ros::NodeHandle & nh, RobotState * robotState,
        BindingManager * parameterBindingManager,
        controlit::utility::ControlItParameters * params);

    /*!
     * Sets the gravity vector of all control models used internally
     * within this class.
     *
     * \param[in] gravityVector The gravity vector
     */
    virtual void setGravityVector(const Vector & gravityVector);

    /*!
     * Sets the A matrix mask of all control models used internally within this class.
     *
     * \param mask The A matrix mask.
     */
    virtual void setAMask(const std::vector<std::vector<std::string>> & mask);

    /*!
     * Sets the gravity mask of all control models used internally within this class.
     *
     * \param mask The gravity vector mask.
     */
    virtual void setGravMask(const std::vector<std::string> & mask);

    /*!
     * Adds a listener to the constraint set of every control model
     * used internally within this class.
     *
     * \param listener The listener.
     */
    virtual void addListenerToConstraintSet(boost::function<void(std::string const &)> listener);

    /*!
     * Starts the child thread that updates the inactive control model.
     */
    virtual void startThread();

    /*!
     * Stops the child thread that updates the inactive control model.
     */
    virtual void stopThread();

    /*!
     * Grabs the swap lock.  This prevents the active control model from being
     * swapped.  Note that this is a blocking operation and should *not*
     * be called by the RT thread!.
     */
    virtual void getSwapLock();

    /*!
     * Releases the swap lock.  This should only be called after calling getLock().
     * After calling it, the active control model may be swapped with the inactive
     * one.
     */
    virtual void releaseSwapLock();

    /*!
     * Attempt to grab the lock.  A pointer to the inactive ControlModel
     * will be returned if (1) the lock is successfully obtained,
     * (2) turn_ = REALTIME, and (3) newUpdateAvailable != true.
     *
     * \return A pointer to the inactive model if the lock is successfully
     * obtained, or nullptr otherwise.
     */
    virtual ControlModel * trylock();

    /*!
     * Releases the lock that protects the inactive model.
     */
    virtual void unlockAndUpdate();

    /*!
     * Check if an updated ControlModel is available.  If so upgrade
     * to it by swapping it and the currently-active ControlModel.
     *
     * \return true if a swap occurred.
     */
    virtual bool checkUpdate();

    /*!
     * Gets the active control model.
     *
     * \return A pointer to the active control model.
     */
    ControlModel* get();

    /*!
     * Returns the number of times the control model was updated.
     */
    // int getNumUpdates() {return numUpdates;}

protected:

    /*!
     * Define the possible states of the ModelUpdate thread.
     */
    enum class State : int {IDLE, UPDATING_MODEL, UPDATED_MODEL_READY};

    /*!
     * This is the state of the ModelUpdate thread.
     */
    State state;

    /*!
     * This is executed by the child thread that updates the inactive
     * control model.
     */
    void updateLoop();

    /*!
     * Swaps the inactive and active control models.
     */
    void swap();

    bool getConstraintJacobiansHandler(
        controlit_core::get_constraint_set_jacobians::Request  &req,
        controlit_core::get_constraint_set_jacobians::Response &res);

    /*!
     * Returns a string representation of the state.
     *
     * \param state The state.
     * \return A string description of the state.
     */
    std::string stateToString(State state) const;

    /*!
     * Whether the model update thread is running.
     */
    bool isRunning;

    /*!
     * Whether the model update thread should continue to run.
     */
    bool keepRunning;

    /*!
     * Whether init() was called.
     */
    bool initialized;

    /*!
     * The active control model.  This is used by the main servo thread
     * to compute the next command.
     */
    ControlModel * activeModel;

    /*!
     * The inactive control model.  This is used by a child thread to
     * update the model in parallel with the main servo thread.
     */
    ControlModel * inactiveModel;

    /*!
     * The parameter binding manager is used to create and destroy bindings.
     */
    BindingManager * parameterBindingManager;

    /*!
     * Notification of when it is OK to proceed with doing an update because state
     * information has been updated.
     */
    std::condition_variable cv;

    /*!
     * This mutex controls when the inactive control model can be updated.
     */
    std::mutex mutex;

    /*!
     * This mutex controls when the active ControlModel can be swapped with
     * the inactive one.
     */
    std::mutex swapMutex;

    /*!
     * This is the child thread that updates the inactive ControlModel.
     */
    std::thread thread;

    /*!
     * For publishing the model staleness information.
     */
    controlit::addons::ros::RealtimePublisher<std_msgs::Float64>
        modelUpdateLatencyPublisher;

    /*!
     * For publishing the gravity vector (diagnostics).
     */
    controlit::addons::ros::RealtimePublisher<std_msgs::Float64MultiArray>
        gravityPublisher;

    /*!
     * The service that provides the constraint jacobian matrices.
     */
    ros::ServiceServer constraintJacobianService;

    /*!
     * A holonomic constraint.  This is used by method getConstraintJacobiansHandler().
     */
    controlit_core::HolonomicConstraint hc;

    /*!
     * The model update end time.
     */
    high_resolution_clock::time_point modelUpdateStartTime;

    /*!
     * The model update end time.
     */
    high_resolution_clock::time_point modelUpdateEndTime;
};

} // namespace controlit

#endif<commit_msg>Updated doc.<commit_after>/*
 * Copyright (C) 2015 The University of Texas at Austin and the
 * Institute of Human Machine Cognition. All rights reserved.
 *
 * 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. See
 * <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>
 *
 * 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, see
 * <http://www.gnu.org/licenses/>
 */

#ifndef __CONTROLIT_CORE_RT_CONTROL_MODEL_HPP__
#define __CONTROLIT_CORE_RT_CONTROL_MODEL_HPP__

#include <mutex>
#include <thread>
#include <condition_variable>
#include <chrono>

#include <ros/ros.h>

#include <controlit/ControlModel.hpp>
#include <controlit/Constraint.hpp>
#include <controlit/BindingManager.hpp>

#include <controlit/addons/ros/RealTimePublisher.hpp>

// Messages
#include <std_msgs/Float64.h>
#include <controlit_core/HolonomicConstraint.h>
#include "controlit_core/get_constraint_set_jacobians.h"

namespace controlit {

/*!
 * Instantiates two ControlModel objects and manages which
 * one is active.  The active ControlModel is used by the
 * main servo thread to compute the next command.  The inactive
 * ControlModel is used by a child thread to update the model
 * based on the current joint state.  The active and inactive
 * models are swapped when the child thread is done updating
 * the inactive model.
 */
class RTControlModel
{
public:
    /*!
     * The constructor.
     */
    RTControlModel();

    /*!
     * The destructor.
     */
    virtual ~RTControlModel();

    /*!
     * Whether this RTControlModel is initialized.
     */
    bool isInitialized() {return initialized;}

    /*!
     * Sets the robot control models to be stale.  This is to prevent
     * stale models from being used when the controller begins to run.
     */
    void setStale();

    /*!
     * Initialize this RTControlModel.
     *
     * \param[in] nh the ROS node handle.
     * \param[in] robotState A pointer to the latest robot state information.  This is
     * passed to the internal Control Model objects used within this object.
     * \param[in] parameterBindingManager The parameterBindingManager.
     * \param[out] params A pointer to the WBC parameters.  This is necessary to save the
     * joint limit information when the URDF is parsed.
     */
    bool init(ros::NodeHandle & nh, RobotState * robotState,
        BindingManager * parameterBindingManager,
        controlit::utility::ControlItParameters * params);

    /*!
     * Sets the gravity vector of all control models used internally
     * within this class.
     *
     * \param[in] gravityVector The gravity vector
     */
    virtual void setGravityVector(const Vector & gravityVector);

    /*!
     * Sets the A matrix mask of all control models used internally within this class.
     *
     * \param mask The A matrix mask.
     */
    virtual void setAMask(const std::vector<std::vector<std::string>> & mask);

    /*!
     * Sets the gravity mask of all control models used internally within this class.
     *
     * \param mask The gravity vector mask.
     */
    virtual void setGravMask(const std::vector<std::string> & mask);

    /*!
     * Adds a listener to the constraint set of every control model
     * used internally within this class.
     *
     * \param listener The listener.
     */
    virtual void addListenerToConstraintSet(boost::function<void(std::string const &)> listener);

    /*!
     * Starts the child thread that updates the inactive control model.
     */
    virtual void startThread();

    /*!
     * Stops the child thread that updates the inactive control model.
     */
    virtual void stopThread();

    /*!
     * Grabs the swap lock.  This prevents the active control model from being
     * swapped.  Note that this is a blocking operation and should *not*
     * be called by the RT thread!.
     */
    virtual void getSwapLock();

    /*!
     * Releases the swap lock.  This should only be called after calling getLock().
     * After calling it, the active control model may be swapped with the inactive
     * one.
     */
    virtual void releaseSwapLock();

    /*!
     * Attempt to grab the lock.  A pointer to the inactive ControlModel
     * will be returned if (1) the lock is successfully obtained,
     * (2) turn_ = REALTIME, and (3) newUpdateAvailable != true.
     *
     * \return A pointer to the inactive model if the lock is successfully
     * obtained, or nullptr otherwise.
     */
    virtual ControlModel * trylock();

    /*!
     * Releases the lock that protects the inactive model.
     */
    virtual void unlockAndUpdate();

    /*!
     * Check if an updated ControlModel is available.  If so upgrade
     * to it by swapping it and the currently-active ControlModel.
     *
     * \return true if a swap occurred.
     */
    virtual bool checkUpdate();

    /*!
     * Gets the active control model.
     *
     * \return A pointer to the active control model.
     */
    ControlModel* get();

    /*!
     * Returns the number of times the control model was updated.
     */
    // int getNumUpdates() {return numUpdates;}

protected:

    /*!
     * Define the possible states of the ModelUpdate thread.
     */
    enum class State : int {IDLE, UPDATING_MODEL, UPDATED_MODEL_READY};

    /*!
     * This is the state of the ModelUpdate thread.
     */
    State state;

    /*!
     * This is executed by the child thread that updates the inactive
     * control model.
     */
    void updateLoop();

    /*!
     * Swaps the inactive and active control models.
     */
    void swap();

    bool getConstraintJacobiansHandler(
        controlit_core::get_constraint_set_jacobians::Request  &req,
        controlit_core::get_constraint_set_jacobians::Response &res);

    /*!
     * Returns a string representation of the state.
     *
     * \param state The state.
     * \return A string description of the state.
     */
    std::string stateToString(State state) const;

    /*!
     * Whether the model update thread is running.
     */
    bool isRunning;

    /*!
     * Whether the model update thread should continue to run.
     */
    bool keepRunning;

    /*!
     * Whether init() was called.
     */
    bool initialized;

    /*!
     * The active control model.  This is used by the main servo thread
     * to compute the next command.
     */
    ControlModel * activeModel;

    /*!
     * The inactive control model.  This is used by a child thread to
     * update the model in parallel with the main servo thread.
     */
    ControlModel * inactiveModel;

    /*!
     * The parameter binding manager is used to create and destroy bindings.
     */
    BindingManager * parameterBindingManager;

    /*!
     * Notification of when it is OK to proceed with doing an update because state
     * information has been updated.
     */
    std::condition_variable cv;

    /*!
     * This mutex controls when the inactive control model can be updated.
     */
    std::mutex mutex;

    /*!
     * This mutex controls when the active ControlModel can be swapped with
     * the inactive one.
     */
    std::mutex swapMutex;

    /*!
     * The thread that updates the inactive ControlModel.
     */
    std::thread thread;

    /*!
     * For publishing the model staleness information.
     */
    controlit::addons::ros::RealtimePublisher<std_msgs::Float64>
        modelUpdateLatencyPublisher;

    /*!
     * For publishing the gravity vector (diagnostics).
     */
    controlit::addons::ros::RealtimePublisher<std_msgs::Float64MultiArray>
        gravityPublisher;

    /*!
     * The service that provides the constraint jacobian matrices.
     */
    ros::ServiceServer constraintJacobianService;

    /*!
     * A holonomic constraint.  This is used by method getConstraintJacobiansHandler().
     */
    controlit_core::HolonomicConstraint hc;

    /*!
     * The model update end time.
     */
    high_resolution_clock::time_point modelUpdateStartTime;

    /*!
     * The model update end time.
     */
    high_resolution_clock::time_point modelUpdateEndTime;
};

} // namespace controlit

#endif<|endoftext|>


<commit_before>#pragma once
/*
 * Copyright (c) 2012, 2014 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#ifndef _QI_PATH_HPP_
# define _QI_PATH_HPP_

# include <string>
# include <vector>
# include <locale>
# include <iosfwd>
# include <boost/scoped_ptr.hpp>
# include <qi/api.hpp>

namespace boost { namespace filesystem {
  class path;
}}

namespace qi
{

  class PrivatePath;
  class Path;
  typedef std::vector<Path> PathVector;

  /**
   * \brief The Path class allow handling path in a cross-platform maner.
   * \includename{qi/path.hpp}
   * The class assume that all string are encoded in UTF-8.
   */
  class QI_API Path {
  public:
    /// Default Constructor
    /// \param unicodePath Path
    Path(const std::string& unicodePath = std::string());

    /// \param unicodePath Path
    Path(const char* unicodePath);

    /// Copy Constructor
    Path(const Path& path);

    /// Copy Constructor from boost filesystem.
    Path(const boost::filesystem::path& path);

    /// Default destructor
    ~Path();

    /// is the path empty?
    bool isEmpty() const;

    /// does this file exist?
    bool exists() const;

    /// is the path a directory?
    bool isDir() const;

    /// is the path a regular file?
    bool isRegularFile() const;

    /// is the path a symlink?
    bool isSymlink() const;

    /// get the name of the current file of folder
    std::string filename() const;

    /// get the extension of the current file
    std::string extension() const;

    /// return a Path to the parent
    Path parent() const;

    /// return an absolute Path of the current path
    Path absolute() const;

    /// return a vector of files contained in the current path
    PathVector files() const;

    /// return a vector of absolute path to files contained recursively in the current path
    PathVector recursiveFiles() const;

    /// return a vector of dirs contained in the current path
    PathVector dirs() const;

    /// return the path as a string
    operator std::string() const;

    /// return the path as a string
    std::string str() const;

    /// return the path as a boost path representation
    const boost::filesystem::path& bfsPath() const;

    /// concat two paths adding a directory separator between them
    Path operator/(const qi::Path& rhs) const;

    /// concat two paths adding a directory separator between them
    const Path& operator/=(const qi::Path& rhs) const;

    /// copy operator
    const Path& operator=(const qi::Path& rhs) const;

    /// Standard output stream operator for logging.
    friend std::ostream& operator<<(std::ostream& output, const qi::Path& path)
    {
      output << path.str();
      return output;
    }

  private:
    Path(PrivatePath* p);
    boost::scoped_ptr<PrivatePath> _p;
  };

  /// Set of tools to handle SDK layouts.
  namespace path
  {
    /// Create a temporary directory that will be removed
    /// once you quit the scope
    class QI_API ScopedDir
    {
    public:
      /// Give a path to the constructor to specifed
      /// where you want the directory to be created
      /// Otherwise qi::os::mktmpdir will be used to
      /// create the directory
      ScopedDir(qi::Path path = qi::Path());
      /// Remove the directory
      ~ScopedDir();

      /// Get the full path to the directory created
      const qi::Path& path() const;

    private:
      /// Remove current scoped directory
      /// retry is the number of try before quiting if the directory
      /// cannot be removed.
      void removeAll(int retry);

      qi::Path _path;
    };

    /// Create a temporary path to a file that will be removed
    /// once you quit the scope.
    /// Becareful it's only a path it's your call to open it to create it
    class QI_API ScopedFile
    {
    public:
      /// Give a path to the constructor to specifed
      /// where you want the file to be created.
      /// Otherwise the path to the file is construct with
      /// qi::os::mktmpdir / "tmpfile"
      /// If it already exists it will be remove.
      ScopedFile(qi::Path filePath = qi::Path());
      ~ScopedFile();

      /// Get the full path to the directory created
      const qi::Path& path() const;

    private:
      qi::path::ScopedDir _dir;
      qi::Path _path;
    };

    /**
     * \brief Return the default SDK prefix path.
     * \return The SDK prefix path.
     * It's always a complete, native path.
     */
    QI_API std::string sdkPrefix();

    /// \brief Implementation details
    ///
    /// not thread-safe, must be kept internal
    namespace detail {

      /**
       * \brief Return the SDK prefixes list.
       * It's always complete, native paths.
       */
      QI_API std::vector<std::string> getSdkPrefixes();

      /**
       * \brief Add a new SDK prefix to the list of searchable prefixes.
       *
       * A default SDK prefix is computed using argc, argv when calling
       * qi::Application app(argc, argv).
       *
       * After calling this function, the new SDK prefix will be taken
       * into account by the other methods.
       * \param prefix The new prefix to add (in UTF-8).
       */
      QI_API void addOptionalSdkPrefix(const char* prefix);

      /**
       * \brief Reset the list of additional SDK prefixes.
       *
       * Reset all the SDK added with qi::path::addOptionalSdkPrefix.
       * The list of SDK prefixes will only contain the default SDK
       * prefix.
       */
      QI_API void clearOptionalSdkPrefix();

      /**
       * \brief Set the writable files path for users.
       * \param path Path to the new writable data path
       */
      QI_API void setWritablePath(const std::string &path);
    }

    /**
     * \brief Look for a binary.
     * \param name The full name of the binary, or just the name.
     * \return The complete, native path to the file found,
     * an empty string otherwise.
     *
     * \verbatim
     * This will search in all SDK prefixes for a file named 'name'.
     * It will then add '.exe' suffix if needed.
     * (without '.exe') (in UTF-8).
     * \endverbatim
     */
    QI_API std::string findBin(const std::string& name, bool searchInPath=false);

    /**
     * \brief Look for a library.
     * \param name The full name of the library, or just the name.
     * \return The complete, native path to the file found,
     * an empty string otherwise.
     *
     * \verbatim
     * This will search in all SDK prefixes for a file named 'name'.
     * It will then add 'lib' prefix, and appropriated suffixes
     * ('.dll' on windows, '.so' on linux, '.dylib' on mac).
     * (without '.dll', '.so') (in UTF-8).
     *
     * You can specify subdirectories using "/" as directory separator
     * (in UTF-8).
     * \endverbatim
     */
    QI_API std::string findLib(const std::string& name);

    /**
     * \brief Look for a configuration file.
     * \param applicationName Name of the application.
     * \param filename Name of the file to look for.
     * You can specify subdirectories using "/" as directory separator.
     * \return The complete, native path of the file if it was found,
     * an empty string otherwise.
     *
     * \verbatim
     * The file is searched in a list of possible directories,
     * the first match is returned.
     *
     * The list of paths is constructed like this:
     *
     * - first, a standard path in the home directory (like
     *   ~/.config/<applicationName>/<filename>)
     * - then: <sdk_prefix>/etc/<applicationName>/<filename> for each known SDK
     *   prefix.
     * - then a standard path in the system. (like
     *   /etc/<applicationName>/<filename>)
     * \endverbatim
     */
    QI_API std::string findConf(const std::string& applicationName,
                                const std::string& filename);

    /**
     * \brief Look for a file in all dataPaths(applicationName) directories,
     * return the first match.
     * \param applicationName Name of the application.
     * \param filename Name of the file to look for.
     * You can specify subdirectories using "/" as directory separator.
     * \return The complete, native path of the file if it was found,
     * an empty string otherwise.
     *
     * \verbatim
     * The file is searched in a list of possible directories, provided by the
     * :cpp:func:`qi::path::dataPaths(const std::string&)`.
     * The first match is returned.
     *
     * For instance if you have the following files on a unix system
     *
     * - ~/.local/share/foo/models/nao.xml
     * - /usr/share/foo/models/nao.xml
     *
     * then listData("foo", "models/nao.xml") will return
     *
     * - ~/.local/share/foo/models/nao.xml
     * \endverbatim
     */
    QI_API std::string findData(const std::string& applicationName,
                                const std::string& filename);

    /**
     * \brief List data files matching the given pattern in all dataPaths(applicationName)
     * directories. For each match, return the occurence from the first dataPaths prefix.
     * Directories are discarded.
     * \param applicationName Name of the application.
     * \param pattern wilcard pattern of the files to look for.
     * You can specify subdirectories using "/" as directory separator.
     * \return An std::vector of the complete, native paths of the files that matched.
     *
     * \verbatim
     * Matches are searched in a list of possible directories, provided by the
     * :cpp:func:`qi::path::dataPaths(const std::string&)`.
     * When several matches collide, the first one is
     * returned.
     *
     * For instance if you have the following files on a unix system
     *
     * - ~/.local/share/foo/models/mynao.xml
     * - ~/.local/share/foo/models/myromeo_with_laser_head.xml
     * - /usr/share/foo/models/mynao.xml
     * - /usr/share/foo/models/myromeo.xml
     *
     * then listData("foo", "models/my*.xml") will return
     *
     * - ~/.local/share/foo/models/mynao.xml
     * - ~/.local/share/foo/models/myromeo_with_laser_head.xml
     * - /usr/share/foo/models/myromeo.xml
     *
     * note that /usr/share/foo/models/mynao.xml is not returned because a nao.xml file is already matched.
     * \endverbatim
     */
    QI_API std::vector<std::string> listData(const std::string& applicationName,
                                             const std::string& pattern="*");

    /** same as listData but for libraries
     */
    QI_API std::vector<std::string> listLib(const std::string& subfolder,
                                            const std::string& pattern="*");

    /**
     * \brief Get the list of directories used when searching for configuration files for the given application name.
     * \param applicationName Name of the application.
     * \return List of configuration directories.
     *
     * \verbatim
     * This is used by the :cpp:func:`qi::path::findConf(const std::string&, const std::string&)`.
     *
     * .. warning:: You should not assume those directories exist, nor
     *    that they are writeable.
     * \endverbatim
     */
    QI_API std::vector<std::string> confPaths(const std::string& applicationName="");

    /**
     * \brief Get the list of directories used when searching for data files for the given application name.
     * \param applicationName Name of the application.
     * \return A list of directories.
     *
     * \verbatim
     * This is used by the :cpp:func:`qi::path::findData(const std::string&, const std::string&)`
     * and the :cpp:func:`qi::path::listData(const std::string&, const std::string&)`.
     *
     * The list of paths is constructed like this:
     *
     * - first, a standard path in the home directory (like
     *   ~/.local/share/<applicationName>/<filename>)
     * - then <sdk_prefix>/share/<applicationName>/<filename> for each known SDK
     *   prefix.
     *
     * .. warning:: You should not assume those directories exist,
     *    nor that they are writeable.
     * \endverbatim
     */
    QI_API std::vector<std::string> dataPaths(const std::string& applicationName="");

    /**
     * \brief Get the list of directories used when searching for binaries.
     * \return A list of directories.
     *
     * \verbatim
     * This is used by the :cpp:func:`qi::path::findBin(const std::string&)`.
     *
     * .. warning:: You should not assume those directories exist, nor that they are
     *    writeable.
     * \endverbatim
     */
    QI_API std::vector<std::string> binPaths();

    /**
     * \brief Get the list of directories used when searching for libraries.
     * \return A list of directories.
     *
     * \verbatim
     * This is used by the :cpp:func:`qi::path::findLib(const std::string&)`.
     *
     * .. warning:: You should not assume those directories exist, nor that they are
     *    writeable.
     * \endverbatim
     */
    QI_API std::vector<std::string> libPaths();

    /**
     * \brief Get the writable data files path for users.
     * \param applicationName The name of the application.
     * \param filename The filename.
     * \return The directory or the file.
     *
     * \verbatim
     * If filename is empty, return the directory in which to write.
     * Otherwise the path is constructed like this:
     *
     * Linux
     *    <home>/.local/share/<applicationName>/<filename>
     *
     * Windows
     *    %AppData%\<applicatioName>\<filename>
     *
     * You can specify subdirectories using "/" as directory separator.
     * \endverbatim
     */
    QI_API std::string userWritableDataPath(const std::string& applicationName,
                                            const std::string& filename);

    /**
     * \brief Get the writable configuration files path for users.
     * \param applicationName The name of the application.
     * \param filename The filename.
     * \return The directory or the file.
     *
     * \verbatim
     * If filename is empty, return the directory
     * in which to write. Otherwise the path is constructed like this:
     *
     * Linux
     *    <home>/.config/<applicatioName>/<filename>
     *
     * Windows
     *    %AppData%\<applicatioName>\<filename>
     *
     * You can specify subdirectories using "/" as directory separator.
     * \endverbatim
     */
    QI_API std::string userWritableConfPath(const std::string& applicationName,
                                            const std::string& filename="");

    /**
     * \brief Convert given path into DOS 8.3 path if it exists, else returns empty string (Windows only).
     *
     * To use some API that doesn't support unicode on Windows, it is
     * possible to convert a unicode path to an existing file into a DOS
     * path without any accentuated characters.
     * (for ex. "C:\test àé\" becomes "C:\TEST~1\" if it already exists)
     *
     * On other platforms, simply return pathString.
     */
    QI_API std::string convertToDosPath(const std::string &pathString);

    /**
     * \brief Set the writable files path for users.
     * \param path Path to the new writable data path
     * \deprecated since 2.2 Use qi::path::detail::setWritablePath instead
     */
    QI_API QI_API_DEPRECATED void setWritablePath(const std::string &path);
  }

  /**
   * \brief Standard std::codecvt type accepted by STL and boost.
   *
   * Typedef for std::codecvt<wchar_t, char, std::mbstate_t> that can be used
   * with boost::filesystem::path and std::locale.
   */
  typedef std::codecvt<wchar_t, char, std::mbstate_t> codecvt_type;

  /**
   * \brief UTF-8 facet object getter.
   * \return UTF-8 implementation for std::codecvt<wchar_t, char, std::mbstate_t>
   *
   * Return a facet object that can be used by stl (iostream, locale, ...)
   * and std::locale compliant library like boost::filesystem.
   *
   * This class allow conversion between UTF-8 (char) and UTF-16/UTF-32 (wchar).
   */
  QI_API codecvt_type &unicodeFacet();
}

#endif  // _QI_PATH_HPP_
<commit_msg>path: add warning on setWritablePath<commit_after>#pragma once
/*
 * Copyright (c) 2012, 2014 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#ifndef _QI_PATH_HPP_
# define _QI_PATH_HPP_

# include <string>
# include <vector>
# include <locale>
# include <iosfwd>
# include <boost/scoped_ptr.hpp>
# include <qi/api.hpp>

namespace boost { namespace filesystem {
  class path;
}}

namespace qi
{

  class PrivatePath;
  class Path;
  typedef std::vector<Path> PathVector;

  /**
   * \brief The Path class allow handling path in a cross-platform maner.
   * \includename{qi/path.hpp}
   * The class assume that all string are encoded in UTF-8.
   */
  class QI_API Path {
  public:
    /// Default Constructor
    /// \param unicodePath Path
    Path(const std::string& unicodePath = std::string());

    /// \param unicodePath Path
    Path(const char* unicodePath);

    /// Copy Constructor
    Path(const Path& path);

    /// Copy Constructor from boost filesystem.
    Path(const boost::filesystem::path& path);

    /// Default destructor
    ~Path();

    /// is the path empty?
    bool isEmpty() const;

    /// does this file exist?
    bool exists() const;

    /// is the path a directory?
    bool isDir() const;

    /// is the path a regular file?
    bool isRegularFile() const;

    /// is the path a symlink?
    bool isSymlink() const;

    /// get the name of the current file of folder
    std::string filename() const;

    /// get the extension of the current file
    std::string extension() const;

    /// return a Path to the parent
    Path parent() const;

    /// return an absolute Path of the current path
    Path absolute() const;

    /// return a vector of files contained in the current path
    PathVector files() const;

    /// return a vector of absolute path to files contained recursively in the current path
    PathVector recursiveFiles() const;

    /// return a vector of dirs contained in the current path
    PathVector dirs() const;

    /// return the path as a string
    operator std::string() const;

    /// return the path as a string
    std::string str() const;

    /// return the path as a boost path representation
    const boost::filesystem::path& bfsPath() const;

    /// concat two paths adding a directory separator between them
    Path operator/(const qi::Path& rhs) const;

    /// concat two paths adding a directory separator between them
    const Path& operator/=(const qi::Path& rhs) const;

    /// copy operator
    const Path& operator=(const qi::Path& rhs) const;

    /// Standard output stream operator for logging.
    friend std::ostream& operator<<(std::ostream& output, const qi::Path& path)
    {
      output << path.str();
      return output;
    }

  private:
    Path(PrivatePath* p);
    boost::scoped_ptr<PrivatePath> _p;
  };

  /// Set of tools to handle SDK layouts.
  namespace path
  {
    /// Create a temporary directory that will be removed
    /// once you quit the scope
    class QI_API ScopedDir
    {
    public:
      /// Give a path to the constructor to specifed
      /// where you want the directory to be created
      /// Otherwise qi::os::mktmpdir will be used to
      /// create the directory
      ScopedDir(qi::Path path = qi::Path());
      /// Remove the directory
      ~ScopedDir();

      /// Get the full path to the directory created
      const qi::Path& path() const;

    private:
      /// Remove current scoped directory
      /// retry is the number of try before quiting if the directory
      /// cannot be removed.
      void removeAll(int retry);

      qi::Path _path;
    };

    /// Create a temporary path to a file that will be removed
    /// once you quit the scope.
    /// Becareful it's only a path it's your call to open it to create it
    class QI_API ScopedFile
    {
    public:
      /// Give a path to the constructor to specifed
      /// where you want the file to be created.
      /// Otherwise the path to the file is construct with
      /// qi::os::mktmpdir / "tmpfile"
      /// If it already exists it will be remove.
      ScopedFile(qi::Path filePath = qi::Path());
      ~ScopedFile();

      /// Get the full path to the directory created
      const qi::Path& path() const;

    private:
      qi::path::ScopedDir _dir;
      qi::Path _path;
    };

    /**
     * \brief Return the default SDK prefix path.
     * \return The SDK prefix path.
     * It's always a complete, native path.
     */
    QI_API std::string sdkPrefix();

    /// \brief Implementation details
    ///
    /// not thread-safe, must be kept internal
    namespace detail {

      /**
       * \brief Return the SDK prefixes list.
       * It's always complete, native paths.
       */
      QI_API std::vector<std::string> getSdkPrefixes();

      /**
       * \brief Add a new SDK prefix to the list of searchable prefixes.
       *
       * A default SDK prefix is computed using argc, argv when calling
       * qi::Application app(argc, argv).
       *
       * After calling this function, the new SDK prefix will be taken
       * into account by the other methods.
       * \param prefix The new prefix to add (in UTF-8).
       */
      QI_API void addOptionalSdkPrefix(const char* prefix);

      /**
       * \brief Reset the list of additional SDK prefixes.
       *
       * Reset all the SDK added with qi::path::addOptionalSdkPrefix.
       * The list of SDK prefixes will only contain the default SDK
       * prefix.
       */
      QI_API void clearOptionalSdkPrefix();

      /**
       * \brief Set the writable files path for users.
       * \param path Path to the new writable data path
       * \warning This method is only meant to be used in tests.
       */
      QI_API void setWritablePath(const std::string &path);
    }

    /**
     * \brief Look for a binary.
     * \param name The full name of the binary, or just the name.
     * \return The complete, native path to the file found,
     * an empty string otherwise.
     *
     * \verbatim
     * This will search in all SDK prefixes for a file named 'name'.
     * It will then add '.exe' suffix if needed.
     * (without '.exe') (in UTF-8).
     * \endverbatim
     */
    QI_API std::string findBin(const std::string& name, bool searchInPath=false);

    /**
     * \brief Look for a library.
     * \param name The full name of the library, or just the name.
     * \return The complete, native path to the file found,
     * an empty string otherwise.
     *
     * \verbatim
     * This will search in all SDK prefixes for a file named 'name'.
     * It will then add 'lib' prefix, and appropriated suffixes
     * ('.dll' on windows, '.so' on linux, '.dylib' on mac).
     * (without '.dll', '.so') (in UTF-8).
     *
     * You can specify subdirectories using "/" as directory separator
     * (in UTF-8).
     * \endverbatim
     */
    QI_API std::string findLib(const std::string& name);

    /**
     * \brief Look for a configuration file.
     * \param applicationName Name of the application.
     * \param filename Name of the file to look for.
     * You can specify subdirectories using "/" as directory separator.
     * \return The complete, native path of the file if it was found,
     * an empty string otherwise.
     *
     * \verbatim
     * The file is searched in a list of possible directories,
     * the first match is returned.
     *
     * The list of paths is constructed like this:
     *
     * - first, a standard path in the home directory (like
     *   ~/.config/<applicationName>/<filename>)
     * - then: <sdk_prefix>/etc/<applicationName>/<filename> for each known SDK
     *   prefix.
     * - then a standard path in the system. (like
     *   /etc/<applicationName>/<filename>)
     * \endverbatim
     */
    QI_API std::string findConf(const std::string& applicationName,
                                const std::string& filename);

    /**
     * \brief Look for a file in all dataPaths(applicationName) directories,
     * return the first match.
     * \param applicationName Name of the application.
     * \param filename Name of the file to look for.
     * You can specify subdirectories using "/" as directory separator.
     * \return The complete, native path of the file if it was found,
     * an empty string otherwise.
     *
     * \verbatim
     * The file is searched in a list of possible directories, provided by the
     * :cpp:func:`qi::path::dataPaths(const std::string&)`.
     * The first match is returned.
     *
     * For instance if you have the following files on a unix system
     *
     * - ~/.local/share/foo/models/nao.xml
     * - /usr/share/foo/models/nao.xml
     *
     * then listData("foo", "models/nao.xml") will return
     *
     * - ~/.local/share/foo/models/nao.xml
     * \endverbatim
     */
    QI_API std::string findData(const std::string& applicationName,
                                const std::string& filename);

    /**
     * \brief List data files matching the given pattern in all dataPaths(applicationName)
     * directories. For each match, return the occurence from the first dataPaths prefix.
     * Directories are discarded.
     * \param applicationName Name of the application.
     * \param pattern wilcard pattern of the files to look for.
     * You can specify subdirectories using "/" as directory separator.
     * \return An std::vector of the complete, native paths of the files that matched.
     *
     * \verbatim
     * Matches are searched in a list of possible directories, provided by the
     * :cpp:func:`qi::path::dataPaths(const std::string&)`.
     * When several matches collide, the first one is
     * returned.
     *
     * For instance if you have the following files on a unix system
     *
     * - ~/.local/share/foo/models/mynao.xml
     * - ~/.local/share/foo/models/myromeo_with_laser_head.xml
     * - /usr/share/foo/models/mynao.xml
     * - /usr/share/foo/models/myromeo.xml
     *
     * then listData("foo", "models/my*.xml") will return
     *
     * - ~/.local/share/foo/models/mynao.xml
     * - ~/.local/share/foo/models/myromeo_with_laser_head.xml
     * - /usr/share/foo/models/myromeo.xml
     *
     * note that /usr/share/foo/models/mynao.xml is not returned because a nao.xml file is already matched.
     * \endverbatim
     */
    QI_API std::vector<std::string> listData(const std::string& applicationName,
                                             const std::string& pattern="*");

    /** same as listData but for libraries
     */
    QI_API std::vector<std::string> listLib(const std::string& subfolder,
                                            const std::string& pattern="*");

    /**
     * \brief Get the list of directories used when searching for configuration files for the given application name.
     * \param applicationName Name of the application.
     * \return List of configuration directories.
     *
     * \verbatim
     * This is used by the :cpp:func:`qi::path::findConf(const std::string&, const std::string&)`.
     *
     * .. warning:: You should not assume those directories exist, nor
     *    that they are writeable.
     * \endverbatim
     */
    QI_API std::vector<std::string> confPaths(const std::string& applicationName="");

    /**
     * \brief Get the list of directories used when searching for data files for the given application name.
     * \param applicationName Name of the application.
     * \return A list of directories.
     *
     * \verbatim
     * This is used by the :cpp:func:`qi::path::findData(const std::string&, const std::string&)`
     * and the :cpp:func:`qi::path::listData(const std::string&, const std::string&)`.
     *
     * The list of paths is constructed like this:
     *
     * - first, a standard path in the home directory (like
     *   ~/.local/share/<applicationName>/<filename>)
     * - then <sdk_prefix>/share/<applicationName>/<filename> for each known SDK
     *   prefix.
     *
     * .. warning:: You should not assume those directories exist,
     *    nor that they are writeable.
     * \endverbatim
     */
    QI_API std::vector<std::string> dataPaths(const std::string& applicationName="");

    /**
     * \brief Get the list of directories used when searching for binaries.
     * \return A list of directories.
     *
     * \verbatim
     * This is used by the :cpp:func:`qi::path::findBin(const std::string&)`.
     *
     * .. warning:: You should not assume those directories exist, nor that they are
     *    writeable.
     * \endverbatim
     */
    QI_API std::vector<std::string> binPaths();

    /**
     * \brief Get the list of directories used when searching for libraries.
     * \return A list of directories.
     *
     * \verbatim
     * This is used by the :cpp:func:`qi::path::findLib(const std::string&)`.
     *
     * .. warning:: You should not assume those directories exist, nor that they are
     *    writeable.
     * \endverbatim
     */
    QI_API std::vector<std::string> libPaths();

    /**
     * \brief Get the writable data files path for users.
     * \param applicationName The name of the application.
     * \param filename The filename.
     * \return The directory or the file.
     *
     * \verbatim
     * If filename is empty, return the directory in which to write.
     * Otherwise the path is constructed like this:
     *
     * Linux
     *    <home>/.local/share/<applicationName>/<filename>
     *
     * Windows
     *    %AppData%\<applicatioName>\<filename>
     *
     * You can specify subdirectories using "/" as directory separator.
     * \endverbatim
     */
    QI_API std::string userWritableDataPath(const std::string& applicationName,
                                            const std::string& filename);

    /**
     * \brief Get the writable configuration files path for users.
     * \param applicationName The name of the application.
     * \param filename The filename.
     * \return The directory or the file.
     *
     * \verbatim
     * If filename is empty, return the directory
     * in which to write. Otherwise the path is constructed like this:
     *
     * Linux
     *    <home>/.config/<applicatioName>/<filename>
     *
     * Windows
     *    %AppData%\<applicatioName>\<filename>
     *
     * You can specify subdirectories using "/" as directory separator.
     * \endverbatim
     */
    QI_API std::string userWritableConfPath(const std::string& applicationName,
                                            const std::string& filename="");

    /**
     * \brief Convert given path into DOS 8.3 path if it exists, else returns empty string (Windows only).
     *
     * To use some API that doesn't support unicode on Windows, it is
     * possible to convert a unicode path to an existing file into a DOS
     * path without any accentuated characters.
     * (for ex. "C:\test àé\" becomes "C:\TEST~1\" if it already exists)
     *
     * On other platforms, simply return pathString.
     */
    QI_API std::string convertToDosPath(const std::string &pathString);

    /**
     * \brief Set the writable files path for users.
     * \param path Path to the new writable data path
     * \deprecated since 2.2 Use qi::path::detail::setWritablePath instead
     * \warning This method is only meant to be used in tests.
     */
    QI_API QI_API_DEPRECATED void setWritablePath(const std::string &path);
  }

  /**
   * \brief Standard std::codecvt type accepted by STL and boost.
   *
   * Typedef for std::codecvt<wchar_t, char, std::mbstate_t> that can be used
   * with boost::filesystem::path and std::locale.
   */
  typedef std::codecvt<wchar_t, char, std::mbstate_t> codecvt_type;

  /**
   * \brief UTF-8 facet object getter.
   * \return UTF-8 implementation for std::codecvt<wchar_t, char, std::mbstate_t>
   *
   * Return a facet object that can be used by stl (iostream, locale, ...)
   * and std::locale compliant library like boost::filesystem.
   *
   * This class allow conversion between UTF-8 (char) and UTF-16/UTF-32 (wchar).
   */
  QI_API codecvt_type &unicodeFacet();
}

#endif  // _QI_PATH_HPP_
<|endoftext|>


<commit_before>#ifndef DOMErrorHandler_HEADER_GUARD_
#define DOMErrorHandler_HEADER_GUARD_

/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.3  2002/06/06 20:53:06  tng
 * Documentation Fix: Update the API Documentation for DOM headers
 *
 * Revision 1.2  2002/05/30 19:24:48  knoaman
 * documentation update
 *
 * Revision 1.1  2002/05/23 15:47:24  knoaman
 * DOM L3 core - support for DOMError, DOMErrorHandler and DOMLocator
 *
 */

#include <xercesc/util/XercesDefs.hpp>

class DOMError;

/**
  * Basic interface for DOM error handlers.
  *
  *
DOMErrorHandler is a callback interface that the DOM implementation
  * can call when reporting errors that happens while processing XML data, or
  * when doing some other processing (e.g. validating a document).

  *
  *
The application that is using the DOM implementation is expected to
  * implement this interface.

  *
  * @see DOMBuilder#setErrorHandler
  * @since DOM Level 3
  */

class CDOM_EXPORT DOMErrorHandler
{
protected:
    // -----------------------------------------------------------------------
    //  Hidden constructors
    // -----------------------------------------------------------------------
    /** @name Hidden constructors */
    //@{
    DOMErrorHandler() {};
    DOMErrorHandler(const DOMErrorHandler &other) {};
    DOMErrorHandler & operator = (const DOMErrorHandler &other) {return *this;};
    //@}

public:
    // -----------------------------------------------------------------------
    //  All constructors are hidden, just the destructor is available
    // -----------------------------------------------------------------------
    /** @name Destructor */
    //@{
    /**
     * Destructor
     *
     */
    virtual ~DOMErrorHandler() {};
    //@}

    // -----------------------------------------------------------------------
    //  Virtual DOMErrorHandler interface
    // -----------------------------------------------------------------------
    /** @name Functions introduced in DOM Level 3 */
    //@{
    /**
     * This method is called on the error handler when an error occures.
     *
     *
"Experimental - subject to change"

     *
     * @param domError The error object that describes the error, this object
     *                 may be reused by the DOM implementation across multiple
     *                 calls to the handleEvent method.
     * @return If the handleError method returns true the DOM
     *         implementation should continue as if the error didn't happen
     *         when possible, if the method returns false then the
     *         DOM implementation should stop the current processing when
     *         possible.
     *
     * @since DOM Level 3
     */
    virtual bool handleError(const DOMError& domError) = 0;

    /**
     * Reset the Error handler object on its reuse
     *
     *
This method helps in reseting the Error handler object
     * implementational defaults each time the Error handler is begun.

     *
     *
"Experimental - subject to change"

     *
     * @since DOM Level 3
     */
     virtual void resetErrors() = 0;

    //@}
};

#endif
<commit_msg>DOM L3: remove non standard resetErrors<commit_after>#ifndef DOMErrorHandler_HEADER_GUARD_
#define DOMErrorHandler_HEADER_GUARD_

/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.4  2002/07/15 19:26:34  tng
 * DOM L3: remove non standard resetErrors
 *
 * Revision 1.3  2002/06/06 20:53:06  tng
 * Documentation Fix: Update the API Documentation for DOM headers
 *
 * Revision 1.2  2002/05/30 19:24:48  knoaman
 * documentation update
 *
 * Revision 1.1  2002/05/23 15:47:24  knoaman
 * DOM L3 core - support for DOMError, DOMErrorHandler and DOMLocator
 *
 */

#include <xercesc/util/XercesDefs.hpp>

class DOMError;

/**
  * Basic interface for DOM error handlers.
  *
  *
DOMErrorHandler is a callback interface that the DOM implementation
  * can call when reporting errors that happens while processing XML data, or
  * when doing some other processing (e.g. validating a document).

  *
  *
The application that is using the DOM implementation is expected to
  * implement this interface.

  *
  * @see DOMBuilder#setErrorHandler
  * @since DOM Level 3
  */

class CDOM_EXPORT DOMErrorHandler
{
protected:
    // -----------------------------------------------------------------------
    //  Hidden constructors
    // -----------------------------------------------------------------------
    /** @name Hidden constructors */
    //@{
    DOMErrorHandler() {};
    DOMErrorHandler(const DOMErrorHandler &other) {};
    DOMErrorHandler & operator = (const DOMErrorHandler &other) {return *this;};
    //@}

public:
    // -----------------------------------------------------------------------
    //  All constructors are hidden, just the destructor is available
    // -----------------------------------------------------------------------
    /** @name Destructor */
    //@{
    /**
     * Destructor
     *
     */
    virtual ~DOMErrorHandler() {};
    //@}

    // -----------------------------------------------------------------------
    //  Virtual DOMErrorHandler interface
    // -----------------------------------------------------------------------
    /** @name Functions introduced in DOM Level 3 */
    //@{
    /**
     * This method is called on the error handler when an error occures.
     *
     *
"Experimental - subject to change"

     *
     * @param domError The error object that describes the error, this object
     *                 may be reused by the DOM implementation across multiple
     *                 calls to the handleEvent method.
     * @return If the handleError method returns true the DOM
     *         implementation should continue as if the error didn't happen
     *         when possible, if the method returns false then the
     *         DOM implementation should stop the current processing when
     *         possible.
     *
     * @since DOM Level 3
     */
    virtual bool handleError(const DOMError& domError) = 0;
    //@}

};

#endif
<|endoftext|>