<commit_before>#include "./object_manager.h"
#include <QLoggingCategory>
#include <vector>
#include <map>
#include <algorithm>
#include "./gl.h"
#include "./buffer_manager.h"
#include "./texture_manager.h"
#include "./shader_manager.h"

namespace Graphics
{

QLoggingCategory omChan("Graphics.ObjectManager");

ObjectManager::ObjectManager(std::shared_ptr<TextureManager> textureManager,
                             std::shared_ptr<ShaderManager> shaderManager)
  : bufferManager(std::make_shared<BufferManager>()),
    textureManager(textureManager), shaderManager(shaderManager),
    transformBuffer(GL_SHADER_STORAGE_BUFFER),
    customBuffer(GL_SHADER_STORAGE_BUFFER),
    commandsBuffer(GL_DRAW_INDIRECT_BUFFER)

{
}

ObjectManager::~ObjectManager()
{
}

void ObjectManager::initialize(Gl *gl, uint maxObjectCount, uint bufferSize)
{
  this->gl = gl;

  bufferManager->initialize(gl, maxObjectCount, bufferSize);

  commandsBuffer.initialize(gl, 3 * maxObjectCount, CREATE_FLAGS, MAP_FLAGS);
  transformBuffer.initialize(gl, 3 * maxObjectCount, CREATE_FLAGS, MAP_FLAGS);
  customBuffer.initialize(gl, 12 * maxObjectCount, CREATE_FLAGS, MAP_FLAGS);
}

ObjectData ObjectManager::addObject(const std::vector<float> &vertices,
                                    const std::vector<float> &normals,
                                    const std::vector<float> &colors,
                                    const std::vector<float> &texCoords,
                                    const std::vector<uint> &indices,
                                    int shaderProgramId, int primitiveType)
{
  auto bufferInformation =
      bufferManager->addObject(vertices, normals, colors, texCoords, indices);

  ObjectData object;
  object.vertexOffset = bufferInformation.vertexBufferOffset;
  object.vertexSize = bufferInformation.vertexCount;
  object.indexOffset = bufferInformation.indexBufferOffset;
  object.indexSize = indices.size();
  object.customBufferSize = 0;
  object.setBuffer = nullptr;
  object.transform = Eigen::Matrix4f::Identity();
  object.shaderProgramId = shaderProgramId;
  object.primitiveType = primitiveType;

  return object;
}

int ObjectManager::addShader(std::string vertexShaderPath,
                             std::string fragmentShaderPath)
{
  auto id = shaderManager->addShader(vertexShaderPath, fragmentShaderPath);

  qCDebug(omChan) << "Added" << vertexShaderPath.c_str() << "|"
                  << fragmentShaderPath.c_str() << "which got id" << id;

  return id;
}

int ObjectManager::addTexture(std::string path)
{
  return textureManager->addTexture(path);
}

TextureAddress ObjectManager::getAddressFor(int textureId)
{
  return textureManager->getAddressFor(textureId);
}

void ObjectManager::render(const RenderData &renderData)
{
  std::map<int, std::vector<ObjectData>> objectsByShader;
  for (auto &object : objectsForFrame)
  {
    objectsByShader[object.shaderProgramId].push_back(object);
  }

  for (auto &shaderObjectPair : objectsByShader)
  {
    qCDebug(omChan) << "Render objects with shader" << shaderObjectPair.first
                    << "with" << shaderObjectPair.second.size() << "objects";

    shaderManager->bind(shaderObjectPair.first, renderData);

    std::map<int, std::vector<ObjectData>> objectsByPrimitiveType;
    for (auto &object : shaderObjectPair.second)
    {
      objectsByPrimitiveType[object.primitiveType].push_back(object);
    }

    for (auto pair : objectsByPrimitiveType)
    {
      renderObjects(objectsByPrimitiveType[pair.first]);
    }
  }

  objectsForFrame.clear();
}

void ObjectManager::renderImmediately(ObjectData objectData)
{
  std::vector<ObjectData> objs = { objectData };

  renderObjects(objs);
}

void ObjectManager::renderLater(ObjectData object)
{
  objectsForFrame.push_back(object);
}

void ObjectManager::renderObjects(std::vector<ObjectData> objects)
{
  bufferManager->bind();

  // prepare per object buffers
  uint objectCount = objects.size();
  DrawElementsIndirectCommand *commands = commandsBuffer.reserve(objectCount);
  auto *matrices = transformBuffer.reserve(objectCount);
  int customBufferSize = objects[0].customBufferSize * objectCount;

  void *custom = nullptr;
  if (customBufferSize)
    custom = customBuffer.reserve(customBufferSize);

  qCDebug(omChan) << "customBufferSize" << customBufferSize << "custom"
                  << custom << "matrices" << matrices;

  int counter = 0;
  for (auto &objectData : objects)
  {
    commands[counter] = createDrawCommand(objectData, counter);

    auto *transform = &matrices[counter];
    memcpy(transform, objectData.transform.data(), sizeof(float[16]));

    if (objectData.setBuffer && customBufferSize)
    {
      objectData.setBuffer(static_cast<char *>(custom) +
                           counter * objectData.customBufferSize);
    }

    ++counter;
  }

  qCDebug(omChan, "objectcount: %u/%ld", objectCount, commandsBuffer.size());

  int mapRange = ((objectCount / 4) + 1) * 4;
  transformBuffer.bindBufferRange(0, mapRange);
  int customMapRange = ((customBufferSize / 16) + 1) * 16;
  if (customBufferSize)
    customBuffer.bindBufferRange(1, customMapRange);

  // We didn't use MAP_COHERENT here - make sure data is on the gpu
  // glAssert(gl->glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT));
  glAssert(gl->glMemoryBarrier(GL_ALL_BARRIER_BITS));

  // draw
  qCDebug(omChan, "head: %ld headoffset %p objectcount: %un",
          commandsBuffer.getHead(), commandsBuffer.headOffset(), objectCount);

  glAssert(gl->glMultiDrawElementsIndirect(
      objects[0].primitiveType, GL_UNSIGNED_INT, commandsBuffer.headOffset(),
      objectCount, 0));

  bufferManager->unbind();

  commandsBuffer.onUsageComplete(mapRange);
  transformBuffer.onUsageComplete(mapRange);
  if (customBufferSize)
    customBuffer.onUsageComplete(customMapRange);
}

DrawElementsIndirectCommand
ObjectManager::createDrawCommand(const ObjectData &objectData, int counter)
{
  DrawElementsIndirectCommand command;

  command.count = objectData.indexSize;
  command.instanceCount = 1;
  command.firstIndex = objectData.indexOffset;
  command.baseVertex = objectData.vertexOffset;
  command.baseInstance = counter;

  qCDebug(omChan, "counter: %d count: %u firstIndex: %u baseVertex: %u",
          counter, command.count, command.firstIndex, command.baseVertex);

  return command;
}

}  // namespace Graphics
<commit_msg>Remove buffer range alignment from ObjectManager.<commit_after>#include "./object_manager.h"
#include <QLoggingCategory>
#include <vector>
#include <map>
#include <algorithm>
#include "./gl.h"
#include "./buffer_manager.h"
#include "./texture_manager.h"
#include "./shader_manager.h"

namespace Graphics
{

QLoggingCategory omChan("Graphics.ObjectManager");

ObjectManager::ObjectManager(std::shared_ptr<TextureManager> textureManager,
                             std::shared_ptr<ShaderManager> shaderManager)
  : bufferManager(std::make_shared<BufferManager>()),
    textureManager(textureManager), shaderManager(shaderManager),
    transformBuffer(GL_SHADER_STORAGE_BUFFER),
    customBuffer(GL_SHADER_STORAGE_BUFFER),
    commandsBuffer(GL_DRAW_INDIRECT_BUFFER)
{
}

ObjectManager::~ObjectManager()
{
}

void ObjectManager::initialize(Gl *gl, uint maxObjectCount, uint bufferSize)
{
  this->gl = gl;

  bufferManager->initialize(gl, maxObjectCount, bufferSize);

  commandsBuffer.initialize(gl, 3 * maxObjectCount, CREATE_FLAGS, MAP_FLAGS);
  transformBuffer.initialize(gl, 3 * maxObjectCount, CREATE_FLAGS, MAP_FLAGS);
  customBuffer.initialize(gl, 12 * maxObjectCount, CREATE_FLAGS, MAP_FLAGS);
}

ObjectData ObjectManager::addObject(const std::vector<float> &vertices,
                                    const std::vector<float> &normals,
                                    const std::vector<float> &colors,
                                    const std::vector<float> &texCoords,
                                    const std::vector<uint> &indices,
                                    int shaderProgramId, int primitiveType)
{
  auto bufferInformation =
      bufferManager->addObject(vertices, normals, colors, texCoords, indices);

  ObjectData object;
  object.vertexOffset = bufferInformation.vertexBufferOffset;
  object.vertexSize = bufferInformation.vertexCount;
  object.indexOffset = bufferInformation.indexBufferOffset;
  object.indexSize = indices.size();
  object.customBufferSize = 0;
  object.setBuffer = nullptr;
  object.transform = Eigen::Matrix4f::Identity();
  object.shaderProgramId = shaderProgramId;
  object.primitiveType = primitiveType;

  return object;
}

int ObjectManager::addShader(std::string vertexShaderPath,
                             std::string fragmentShaderPath)
{
  auto id = shaderManager->addShader(vertexShaderPath, fragmentShaderPath);

  qCDebug(omChan) << "Added" << vertexShaderPath.c_str() << "|"
                  << fragmentShaderPath.c_str() << "which got id" << id;

  return id;
}

int ObjectManager::addTexture(std::string path)
{
  return textureManager->addTexture(path);
}

TextureAddress ObjectManager::getAddressFor(int textureId)
{
  return textureManager->getAddressFor(textureId);
}

void ObjectManager::render(const RenderData &renderData)
{
  std::map<int, std::vector<ObjectData>> objectsByShader;
  for (auto &object : objectsForFrame)
  {
    objectsByShader[object.shaderProgramId].push_back(object);
  }

  for (auto &shaderObjectPair : objectsByShader)
  {
    qCDebug(omChan) << "Render objects with shader" << shaderObjectPair.first
                    << "with" << shaderObjectPair.second.size() << "objects";

    shaderManager->bind(shaderObjectPair.first, renderData);

    std::map<int, std::vector<ObjectData>> objectsByPrimitiveType;
    for (auto &object : shaderObjectPair.second)
    {
      objectsByPrimitiveType[object.primitiveType].push_back(object);
    }

    for (auto pair : objectsByPrimitiveType)
    {
      renderObjects(objectsByPrimitiveType[pair.first]);
    }
  }

  objectsForFrame.clear();
}

void ObjectManager::renderImmediately(ObjectData objectData)
{
  std::vector<ObjectData> objs = { objectData };

  renderObjects(objs);
}

void ObjectManager::renderLater(ObjectData object)
{
  objectsForFrame.push_back(object);
}

void ObjectManager::renderObjects(std::vector<ObjectData> objects)
{
  bufferManager->bind();

  // prepare per object buffers
  uint objectCount = objects.size();
  DrawElementsIndirectCommand *commands = commandsBuffer.reserve(objectCount);
  auto *matrices = transformBuffer.reserve(objectCount);
  int customBufferSize = objects[0].customBufferSize * objectCount;

  void *custom = nullptr;
  if (customBufferSize)
    custom = customBuffer.reserve(customBufferSize);

  qCDebug(omChan) << "customBufferSize" << customBufferSize << "custom"
                  << custom << "matrices" << matrices;

  int counter = 0;
  for (auto &objectData : objects)
  {
    commands[counter] = createDrawCommand(objectData, counter);

    auto *transform = &matrices[counter];
    memcpy(transform, objectData.transform.data(), sizeof(float[16]));

    if (objectData.setBuffer && customBufferSize)
    {
      objectData.setBuffer(static_cast<char *>(custom) +
                           counter * objectData.customBufferSize);
    }

    ++counter;
  }

  qCDebug(omChan, "objectcount: %u/%ld", objectCount, commandsBuffer.size());
  transformBuffer.bindBufferRange(0, objectCount);
  if (customBufferSize)
    customBuffer.bindBufferRange(1, customBufferSize);

  // We didn't use MAP_COHERENT here - make sure data is on the gpu
  // glAssert(gl->glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT));
  glAssert(gl->glMemoryBarrier(GL_ALL_BARRIER_BITS));

  // draw
  qCDebug(omChan, "head: %ld headoffset %p objectcount: %un",
          commandsBuffer.getHead(), commandsBuffer.headOffset(), objectCount);

  glAssert(gl->glMultiDrawElementsIndirect(
      objects[0].primitiveType, GL_UNSIGNED_INT, commandsBuffer.headOffset(),
      objectCount, 0));

  bufferManager->unbind();

  commandsBuffer.onUsageComplete(objectCount);
  transformBuffer.onUsageComplete(objectCount);
  if (customBufferSize)
    customBuffer.onUsageComplete(customBufferSize);
}

DrawElementsIndirectCommand
ObjectManager::createDrawCommand(const ObjectData &objectData, int counter)
{
  DrawElementsIndirectCommand command;

  command.count = objectData.indexSize;
  command.instanceCount = 1;
  command.firstIndex = objectData.indexOffset;
  command.baseVertex = objectData.vertexOffset;
  command.baseInstance = counter;

  qCDebug(omChan, "counter: %d count: %u firstIndex: %u baseVertex: %u",
          counter, command.count, command.firstIndex, command.baseVertex);

  return command;
}

}  // namespace Graphics
<|endoftext|>


<commit_before>#include "gui/controls/scrollable.h"
#include "core/crc32.h"
#include "core/iserializer.h"
#include "gui/controls/scrollbar.h"

namespace Lux
{
namespace UI
{

Scrollable::Scrollable(Gui& gui, Block* parent)
	: Block(gui, parent, "_box")
{
	setArea(0, 0, 0, 0, 1, 0, 1, 0);
	m_container = new Lux::UI::Block(gui, this, NULL);
	m_container->setIsClipping(true);
	m_container->setArea(0, 0, 0, 0, 1, 0, 1, 0);

	m_vertical_scrollbar = new Scrollbar(gui, this);
	m_vertical_scrollbar->setArea(1, -20, 0, 0, 1, 0, 1, 0);
	m_vertical_scrollbar->hide();
	m_vertical_scrollbar->setScrollbarType(Scrollbar::VERTICAL);
	m_vertical_scrollbar->getCallback("value_changed").bind<Scrollable, &Scrollable::scrollbarValueChanged>(this);

	m_horizontal_scrollbar = new Scrollbar(gui, this);
	m_horizontal_scrollbar->setArea(0, 0, 1, -20, 1, 0, 1, 0);
	m_horizontal_scrollbar->hide();
	m_horizontal_scrollbar->getCallback("value_changed").bind<Scrollable, &Scrollable::scrollbarValueChanged>(this);
}

Scrollable::~Scrollable()
{
}

uint32_t Scrollable::getType() const
{
	static const uint32_t hash = crc32("scrollable");
	return hash;
}

void Scrollable::scrollbarValueChanged(Block& block, void*)
{
	layout();
}

void Scrollable::serialize(ISerializer& serializer)
{
	Block::serialize(serializer);
}

void Scrollable::deserialize(ISerializer& serializer)
{
	Block::deserialize(serializer);
}

void Scrollable::layout()
{
	Block::layout();
	if(m_container->getChildCount() > 0)
	{
		Area content_size = m_container->getChild(m_container->getChildCount()-1)->getGlobalArea();
		for(int i = m_container->getChildCount() - 2; i >= 0; --i)
		{
			content_size.merge(m_container->getChild(i)->getGlobalArea());
		}
		float container_delta_w = 0;
		float container_delta_h = 0;
		bool both_visible = true;
		if(m_container->getGlobalWidth() < content_size.right)
		{
			m_horizontal_scrollbar->show();
			container_delta_h = -m_horizontal_scrollbar->getGlobalHeight();
		}
		else
		{
			both_visible = false;
			m_horizontal_scrollbar->hide();
		}
		if(m_container->getGlobalHeight() < content_size.bottom)
		{
			m_vertical_scrollbar->show();
			container_delta_w = -m_vertical_scrollbar->getGlobalWidth();
		}
		else
		{
			both_visible = false;
			m_vertical_scrollbar->hide();
		}
		if(both_visible)
		{
			m_vertical_scrollbar->setArea(1, -20, 0, 0, 1, 0, 1, -20);
			m_horizontal_scrollbar->setArea(0, 0, 1, -20, 1, -20, 1, 0);
		}
		else
		{
			m_vertical_scrollbar->setArea(1, -20, 0, 0, 1, 0, 1, 0);
			m_horizontal_scrollbar->setArea(0, 0, 1, -20, 1, 0, 1, 0);
		}
		m_container->setArea(0, 0, 0, 0, 1, container_delta_w, 1, container_delta_h);
		m_container->layout();
		float dx = m_horizontal_scrollbar->isShown() ? m_horizontal_scrollbar->getRelativeValue() : 0;
		float dy = m_vertical_scrollbar->isShown() ? m_vertical_scrollbar->getRelativeValue() : 0;
		dx *= content_size.right - m_container->getGlobalRight();
		dy *= content_size.bottom - m_container->getGlobalBottom();
		dx = (float)(int)dx;
		dy = (float)(int)dy;
		for(int i = m_container->getChildCount() - 1; i >= 0; --i)
		{
			Area& area = m_container->getChild(i)->getGlobalArea();
			area.left -= dx;
			area.right -= dx;
			area.top -= dy;
			area.bottom -= dy;
		}
		m_vertical_scrollbar->layout();
		m_horizontal_scrollbar->layout();
	}
	else
	{
		m_vertical_scrollbar->hide();
		m_horizontal_scrollbar->hide();
	}
}

} // ~namespace UI
} // ~namespace Lux<commit_msg>scrollbars in a scrollable are properly shown / hidden<commit_after>#include "gui/controls/scrollable.h"
#include "core/crc32.h"
#include "core/iserializer.h"
#include "gui/controls/scrollbar.h"

namespace Lux
{
namespace UI
{

Scrollable::Scrollable(Gui& gui, Block* parent)
	: Block(gui, parent, "_box")
{
	setArea(0, 0, 0, 0, 1, 0, 1, 0);
	m_container = new Lux::UI::Block(gui, this, NULL);
	m_container->setIsClipping(true);
	m_container->setArea(0, 0, 0, 0, 1, 0, 1, 0);

	m_vertical_scrollbar = new Scrollbar(gui, this);
	m_vertical_scrollbar->setArea(1, -20, 0, 0, 1, 0, 1, 0);
	m_vertical_scrollbar->hide();
	m_vertical_scrollbar->setScrollbarType(Scrollbar::VERTICAL);
	m_vertical_scrollbar->getCallback("value_changed").bind<Scrollable, &Scrollable::scrollbarValueChanged>(this);

	m_horizontal_scrollbar = new Scrollbar(gui, this);
	m_horizontal_scrollbar->setArea(0, 0, 1, -20, 1, 0, 1, 0);
	m_horizontal_scrollbar->hide();
	m_horizontal_scrollbar->getCallback("value_changed").bind<Scrollable, &Scrollable::scrollbarValueChanged>(this);
}

Scrollable::~Scrollable()
{
}

uint32_t Scrollable::getType() const
{
	static const uint32_t hash = crc32("scrollable");
	return hash;
}

void Scrollable::scrollbarValueChanged(Block& block, void*)
{
	layout();
}

void Scrollable::serialize(ISerializer& serializer)
{
	Block::serialize(serializer);
}

void Scrollable::deserialize(ISerializer& serializer)
{
	Block::deserialize(serializer);
}

void Scrollable::layout()
{
	Block::layout();
	if(m_container->getChildCount() > 0)
	{
		Area content_size = m_container->getChild(m_container->getChildCount()-1)->getGlobalArea();
		for(int i = m_container->getChildCount() - 2; i >= 0; --i)
		{
			content_size.merge(m_container->getChild(i)->getGlobalArea());
		}
		float container_delta_w = 0;
		float container_delta_h = 0;
		bool both_visible = true;
		if(m_container->getGlobalWidth() < content_size.right - content_size.left)
		{
			m_horizontal_scrollbar->show();
			container_delta_h = -m_horizontal_scrollbar->getGlobalHeight();
		}
		else
		{
			both_visible = false;
			m_horizontal_scrollbar->hide();
		}
		if(m_container->getGlobalHeight() < content_size.bottom - content_size.top)
		{
			m_vertical_scrollbar->show();
			container_delta_w = -m_vertical_scrollbar->getGlobalWidth();
		}
		else
		{
			both_visible = false;
			m_vertical_scrollbar->hide();
		}
		if(both_visible)
		{
			m_vertical_scrollbar->setArea(1, -20, 0, 0, 1, 0, 1, -20);
			m_horizontal_scrollbar->setArea(0, 0, 1, -20, 1, -20, 1, 0);
		}
		else
		{
			m_vertical_scrollbar->setArea(1, -20, 0, 0, 1, 0, 1, 0);
			m_horizontal_scrollbar->setArea(0, 0, 1, -20, 1, 0, 1, 0);
		}
		m_container->setArea(0, 0, 0, 0, 1, container_delta_w, 1, container_delta_h);
		m_container->layout();
		float dx = m_horizontal_scrollbar->isShown() ? m_horizontal_scrollbar->getRelativeValue() : 0;
		float dy = m_vertical_scrollbar->isShown() ? m_vertical_scrollbar->getRelativeValue() : 0;
		dx *= content_size.right - m_container->getGlobalRight();
		dy *= content_size.bottom - m_container->getGlobalBottom();
		dx = (float)(int)dx;
		dy = (float)(int)dy;
		for(int i = m_container->getChildCount() - 1; i >= 0; --i)
		{
			Area& area = m_container->getChild(i)->getGlobalArea();
			area.left -= dx;
			area.right -= dx;
			area.top -= dy;
			area.bottom -= dy;
		}
		m_vertical_scrollbar->layout();
		m_horizontal_scrollbar->layout();
	}
	else
	{
		m_vertical_scrollbar->hide();
		m_horizontal_scrollbar->hide();
	}
}

} // ~namespace UI
} // ~namespace Lux<|endoftext|>


<commit_before>#ifndef __ENVIRE_CORE_ENVIRE_GRAPH__
#define __ENVIRE_CORE_ENVIRE_GRAPH__

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/labeled_graph.hpp>
#include <boost/graph/properties.hpp>
#include <boost/pending/property.hpp>
#include <boost/property_map/transform_value_property_map.hpp>
#include <boost/type_traits.hpp>
#include <boost/mpl/if.hpp>

namespace boost
{

    struct EnvireGraphTag { };

    /**
     * The EnvireGraph class template is a simplified version of the BGL
     * adjacency list. This class is provided for ease of use, but may not
     * perform as well as custom-defined adjacency list classes. Instances of
     * this template model the BidirectionalGraph, VertexIndexGraph, and
     * EdgeIndexGraph concepts. The graph is also fully mutable, supporting
     * both insertions and removals of vertices and edges.
     *
     * @note Special care must be taken when removing vertices or edges since
     * those operations can invalidate the numbering of vertices.
     */
    template <
        typename VertexProp = no_property,
        typename EdgeProp = no_property,
        typename GraphProp = no_property>
    class EnvireGraph
    {
    public:
        typedef GraphProp graph_property_type;
        typedef VertexProp vertex_property_type;
        typedef EdgeProp edge_property_type;
        typedef typename lookup_one_property<GraphProp, graph_bundle_t>::type graph_bundled;
        typedef typename lookup_one_property<VertexProp, vertex_bundle_t>::type vertex_bundled;
        typedef typename lookup_one_property<EdgeProp, edge_bundle_t>::type edge_bundled;

    public:
        // Embed indices into the vertex type.
        typedef property<vertex_index_t, unsigned, vertex_property_type> internal_vertex_property;
        typedef property<edge_index_t, unsigned, edge_property_type> internal_edge_property;
    public:
        typedef boost::labeled_graph<
            boost::adjacency_list<
            listS, listS, bidirectionalS,
            internal_vertex_property, internal_edge_property, GraphProp,
            listS>, std::string> graph_type;

    private:
        // storage selectors
        typedef typename graph_type::vertex_list_selector vertex_list_selector;
        typedef typename graph_type::edge_list_selector edge_list_selector;
        typedef typename graph_type::out_edge_list_selector out_edge_list_selector;
        typedef typename graph_type::directed_selector directed_selector;

    public:
        // more commonly used graph types
        typedef typename graph_type::stored_vertex stored_vertex;
        typedef typename graph_type::vertices_size_type vertices_size_type;
        typedef typename graph_type::edges_size_type edges_size_type;
        typedef typename graph_type::degree_size_type degree_size_type;
        typedef typename graph_type::vertex_descriptor vertex_descriptor;
        typedef typename graph_type::edge_descriptor edge_descriptor;

        // iterator types
        typedef typename graph_type::vertex_iterator vertex_iterator;
        typedef typename graph_type::edge_iterator edge_iterator;
        typedef typename graph_type::out_edge_iterator out_edge_iterator;
        typedef typename graph_type::in_edge_iterator in_edge_iterator;
        typedef typename graph_type::adjacency_iterator adjacency_iterator;

        // miscellaneous types
        typedef EnvireGraphTag graph_tag;
        typedef typename graph_type::directed_category directed_category;
        typedef typename graph_type::edge_parallel_category edge_parallel_category;
        typedef typename graph_type::traversal_category traversal_category;

        typedef std::size_t vertex_index_type;
        typedef std::size_t edge_index_type;

        EnvireGraph(GraphProp const& p = GraphProp())
            : m_graph(p), m_num_vertices(0), m_num_edges(0), m_max_vertex_index(0)
            , m_max_edge_index(0)
        { }

        EnvireGraph(EnvireGraph const& x)
            : m_graph(x), m_num_vertices(x.m_num_vertices), m_num_edges(x.m_num_edges)
            , m_max_vertex_index(x.m_max_vertex_index), m_max_edge_index(x.m_max_edge_index)
        { }

        EnvireGraph(vertices_size_type n, GraphProp const& p = GraphProp())
            : m_graph(n, p), m_num_vertices(n), m_num_edges(0), m_max_vertex_index(n)
            , m_max_edge_index(0)
        { renumber_vertex_indices(); }

        template <typename EdgeIterator>
        EnvireGraph(EdgeIterator f,
                       EdgeIterator l,
                       vertices_size_type n,
                       edges_size_type m = 0,
                       GraphProp const& p = GraphProp())
            : m_graph(f, l, n, m, p), m_num_vertices(n), m_num_edges(0)
            , m_max_vertex_index(n), m_max_edge_index(0)
        {
            // Unfortunately, we have to renumber the entire graph.
            renumber_indices();

            // Can't always guarantee that the number of edges is actually
            // m if distance(f, l) != m (or is undefined).
            m_num_edges = m_max_edge_index = boost::num_edges(m_graph);
        }

        EnvireGraph& operator=(EnvireGraph const& g) {
            if(&g != this) {
                m_graph = g.m_graph;
                m_num_vertices = g.m_num_vertices;
                m_num_edges = g.m_num_edges;
                m_max_vertex_index = g.m_max_vertex_index;
                m_max_edge_index = g.m_max_edge_index;
            }
            return *this;
        }

        // The impl_() methods are not part of the public interface.
        graph_type& impl()
        { return m_graph; }

        graph_type const& impl() const
        { return m_graph; }

        // The following methods are not part of the public interface
        vertices_size_type num_vertices() const
        { return m_num_vertices; }

    private:
        // This helper function manages the attribution of vertex indices.
        vertex_descriptor make_index(vertex_descriptor v) {
            boost::put(vertex_index, m_graph, v, m_max_vertex_index);
            m_num_vertices++;
            m_max_vertex_index++;
            return v;
        }
    public:
        vertex_descriptor add_vertex()
        { return make_index(boost::add_vertex(m_graph)); }

        vertex_descriptor add_vertex(vertex_property_type const& p)
        { return make_index(boost::add_vertex(internal_vertex_property(0u, p), m_graph)); }

        void clear_vertex(vertex_descriptor v)
        {
            m_num_edges -= boost::degree(v, m_graph);
            boost::clear_vertex(v, m_graph);
        }

        void remove_vertex(vertex_descriptor v)
        {
            boost::remove_vertex(v, m_graph);
            --m_num_vertices;
        }

        edges_size_type num_edges() const
        { return m_num_edges; }

    private:
        // A helper fucntion for managing edge index attributes.
        std::pair<edge_descriptor, bool> const&
        make_index(std::pair<edge_descriptor, bool> const& x)
        {
            if(x.second) {
                boost::put(edge_index, m_graph, x.first, m_max_edge_index);
                ++m_num_edges;
                ++m_max_edge_index;
            }
            return x;
        }
    public:
        std::pair<edge_descriptor, bool>
        add_edge(vertex_descriptor u, vertex_descriptor v)
        { return make_index(boost::add_edge(u, v, m_graph)); }

        std::pair<edge_descriptor, bool>
        add_edge(vertex_descriptor u, vertex_descriptor v, edge_property_type const& p)
        { return make_index(boost::add_edge(u, v, internal_edge_property(0u, p), m_graph)); }

        void remove_edge(vertex_descriptor u, vertex_descriptor v)
        {
            // find all edges, (u, v)
            std::vector<edge_descriptor> edges;
            out_edge_iterator i, i_end;
            for(boost::tie(i, i_end) = boost::out_edges(u, m_graph); i != i_end; ++i) {
                if(boost::target(*i, m_graph) == v) {
                    edges.push_back(*i);
                }
            }
            // remove all edges, (u, v)
            typename std::vector<edge_descriptor>::iterator
            j = edges.begin(), j_end = edges.end();
            for( ; j != j_end; ++j) {
                remove_edge(*j);
            }
        }

        void remove_edge(edge_iterator i)
        {
            remove_edge(*i);
        }

        void remove_edge(edge_descriptor e)
        {
            boost::remove_edge(e, m_graph);
            --m_num_edges;
        }

        vertex_index_type max_vertex_index() const
        { return m_max_vertex_index; }

        void
        renumber_vertex_indices()
        {
            vertex_iterator i, end;
            boost::tie(i, end) = vertices(m_graph);
            m_max_vertex_index = renumber_vertex_indices(i, end, 0);
        }

        void
        remove_vertex_and_renumber_indices(vertex_iterator i)
        {
            vertex_iterator j = next(i), end = vertices(m_graph).second;
            vertex_index_type n = get(vertex_index, m_graph, *i);

            // remove the offending vertex and renumber everything after
            remove_vertex(*i);
            m_max_vertex_index = renumber_vertex_indices(j, end, n);
        }

        edge_index_type
        max_edge_index() const
        { return m_max_edge_index; }

        void
        renumber_edge_indices()
        {
            edge_iterator i, end;
            boost::tie(i, end) = edges(m_graph);
            m_max_edge_index = renumber_edge_indices(i, end, 0);
        }

        void
        remove_edge_and_renumber_indices(edge_iterator i)
        {
            edge_iterator j = next(i), end = edges(m_graph).second;
            edge_index_type n = get(edge_index, m_graph, *i);

            // remove the offending edge and renumber everything after
            remove_edge(*i);
            m_max_edge_index = renumber_edge_indices(j, end, n);
        }

        void
        renumber_indices()
        {
            renumber_vertex_indices();
            renumber_edge_indices();
        }

        // bundled property support
        #ifndef BOOST_GRAPH_NO_BUNDLED_PROPERTIES
        vertex_bundled& operator[](vertex_descriptor v)
        { return m_graph[v]; }

        vertex_bundled const& operator[](vertex_descriptor v) const
        { return m_graph[v]; }

        edge_bundled& operator[](edge_descriptor e)
        { return m_graph[e]; }

        edge_bundled const& operator[](edge_descriptor e) const
        { return m_graph[e]; }

        graph_bundled& operator[](graph_bundle_t)
        { return get_property(*this); }

        graph_bundled const& operator[](graph_bundle_t) const
        { return get_property(*this); }
        #endif

        // Graph concepts
        static vertex_descriptor null_vertex()
        { return graph_type::null_vertex(); }

        void clear()
        {
            m_graph.clear();
            m_num_vertices = m_max_vertex_index = 0;
            m_num_edges = m_max_edge_index = 0;
        }

        void swap(EnvireGraph& g)
        {
            m_graph.swap(g.m_graph);
            std::swap(m_num_vertices, g.m_num_vertices);
            std::swap(m_max_vertex_index, g.m_max_vertex_index);
            std::swap(m_num_edges, g.m_num_edges);
            std::swap(m_max_edge_index, g.m_max_edge_index);
        }

    private:
        vertices_size_type
        renumber_vertex_indices(vertex_iterator i,
                                vertex_iterator end,
                                vertices_size_type n)
        {
            typedef typename property_map<graph_type, vertex_index_t>::type IndexMap;
            IndexMap indices = get(vertex_index, m_graph);
            for( ; i != end; ++i) {
                indices[*i] = n++;
            }
            return n;
        }

        vertices_size_type
        renumber_edge_indices(edge_iterator i,
                            edge_iterator end,
                            vertices_size_type n)
        {
            typedef typename property_map<graph_type, edge_index_t>::type IndexMap;
            IndexMap indices = get(edge_index, m_graph);
            for( ; i != end; ++i) {
                indices[*i] = n++;
            }
            return n;
        }

        graph_type m_graph;
        vertices_size_type m_num_vertices;
        edges_size_type m_num_edges;
        vertex_index_type m_max_vertex_index;
        edge_index_type m_max_edge_index;
    };

    #define ENVIRE_GRAPH_PARAMS typename VP, typename EP, typename GP
    #define ENVIRE_GRAPH EnvireGraph<VP,EP,GP>

    // IncidenceGraph concepts
    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::vertex_descriptor
    source(typename ENVIRE_GRAPH::edge_descriptor e, ENVIRE_GRAPH const& g)
    { return source(e, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::vertex_descriptor
    target(typename ENVIRE_GRAPH::edge_descriptor e, ENVIRE_GRAPH const& g)
    { return target(e, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::degree_size_type
    out_degree(typename ENVIRE_GRAPH::vertex_descriptor v, ENVIRE_GRAPH const& g)
    { return out_degree(v, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS>
    inline std::pair<
        typename ENVIRE_GRAPH::out_edge_iterator,
        typename ENVIRE_GRAPH::out_edge_iterator
    >
    out_edges(typename ENVIRE_GRAPH::vertex_descriptor v,
            ENVIRE_GRAPH const& g)
    { return out_edges(v, g.impl()); }

    // BidirectionalGraph concepts
    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::degree_size_type
    in_degree(typename ENVIRE_GRAPH::vertex_descriptor v, ENVIRE_GRAPH const& g)
    { return in_degree(v, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS>
    inline std::pair<
        typename ENVIRE_GRAPH::in_edge_iterator,
        typename ENVIRE_GRAPH::in_edge_iterator
    >
    in_edges(typename ENVIRE_GRAPH::vertex_descriptor v,
            ENVIRE_GRAPH const& g)
    { return in_edges(v, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::degree_size_type
    degree(typename ENVIRE_GRAPH::vertex_descriptor v, ENVIRE_GRAPH const& g)
    { return degree(v, g.impl()); }

    // AdjacencyGraph concepts
    template <ENVIRE_GRAPH_PARAMS>
    inline std::pair<
        typename ENVIRE_GRAPH::adjacency_iterator,
        typename ENVIRE_GRAPH::adjacency_iterator
        >
    adjacent_vertices(typename ENVIRE_GRAPH::vertex_descriptor v,
                      ENVIRE_GRAPH const& g)
    { return adjacent_vertices(v, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS>
    typename ENVIRE_GRAPH::vertex_descriptor
    vertex(typename ENVIRE_GRAPH::vertices_size_type n,
           ENVIRE_GRAPH const& g)
    { return vertex(n, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS>
    std::pair<typename ENVIRE_GRAPH::edge_descriptor, bool>
    edge(typename ENVIRE_GRAPH::vertex_descriptor u,
         typename ENVIRE_GRAPH::vertex_descriptor v,
         ENVIRE_GRAPH const& g)
    { return edge(u, v, g.impl()); }

    // VertexListGraph concepts
    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::vertices_size_type
    num_vertices(ENVIRE_GRAPH const& g)
    { return g.num_vertices(); }

    template <ENVIRE_GRAPH_PARAMS>
    inline std::pair<
        typename ENVIRE_GRAPH::vertex_iterator,
        typename ENVIRE_GRAPH::vertex_iterator
    >
    vertices(ENVIRE_GRAPH const& g)
    { return vertices(g.impl()); }

    // EdgeListGraph concepts
    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::edges_size_type
    num_edges(ENVIRE_GRAPH const& g)
    { return g.num_edges(); }

    template <ENVIRE_GRAPH_PARAMS>
    inline std::pair<
        typename ENVIRE_GRAPH::edge_iterator,
        typename ENVIRE_GRAPH::edge_iterator
    >
    edges(ENVIRE_GRAPH const& g)
    { return edges(g.impl()); }

    // MutableGraph concepts
    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::vertex_descriptor
    add_vertex(ENVIRE_GRAPH& g)
    { return g.add_vertex(); }

    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::vertex_descriptor
    add_vertex(typename ENVIRE_GRAPH::vertex_property_type const& p,
               ENVIRE_GRAPH& g)
    { return g.add_vertex(p); }

    template <ENVIRE_GRAPH_PARAMS>
    inline void
    clear_vertex(typename ENVIRE_GRAPH::vertex_descriptor v,
    ENVIRE_GRAPH& g)
    { return g.clear_vertex(v); }

    template <ENVIRE_GRAPH_PARAMS>
    inline void
    remove_vertex(typename ENVIRE_GRAPH::vertex_descriptor v,
                  ENVIRE_GRAPH& g)
    { return g.remove_vertex(v); }

    template <ENVIRE_GRAPH_PARAMS>
    inline std::pair<typename ENVIRE_GRAPH::edge_descriptor, bool>
    add_edge(typename ENVIRE_GRAPH::vertex_descriptor u,
             typename ENVIRE_GRAPH::vertex_descriptor v,
             ENVIRE_GRAPH& g)
    { return g.add_edge(u, v); }

    template <ENVIRE_GRAPH_PARAMS>
    inline std::pair<typename ENVIRE_GRAPH::edge_descriptor, bool>
    add_edge(typename ENVIRE_GRAPH::vertex_descriptor u,
             typename ENVIRE_GRAPH::vertex_descriptor v,
             typename ENVIRE_GRAPH::edge_property_type const& p,
             ENVIRE_GRAPH& g)
    { return g.add_edge(u, v, p); }

    template <ENVIRE_GRAPH_PARAMS>
    inline void remove_edge(typename ENVIRE_GRAPH::vertex_descriptor u,
                            typename ENVIRE_GRAPH::vertex_descriptor v,
                            ENVIRE_GRAPH& g)
    { return g.remove_edge(u, v); }

    template <ENVIRE_GRAPH_PARAMS>
    inline void remove_edge(typename ENVIRE_GRAPH::edge_descriptor e, ENVIRE_GRAPH& g)
    { return g.remove_edge(e); }

    template <ENVIRE_GRAPH_PARAMS>
    inline void remove_edge(typename ENVIRE_GRAPH::edge_iterator i, ENVIRE_GRAPH& g)
    { return g.remove_edge(i); }

    template <ENVIRE_GRAPH_PARAMS, class Predicate>
    inline void remove_edge_if(Predicate pred, ENVIRE_GRAPH& g)
    { return remove_edge_if(pred, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS, class Predicate>
    inline void
    remove_out_edge_if(typename ENVIRE_GRAPH::vertex_descriptor v,
                       Predicate pred,
                       ENVIRE_GRAPH& g)
    { return remove_out_edge_if(v, pred, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS, class Predicate>
    inline void
    remove_in_edge_if(typename ENVIRE_GRAPH::vertex_descriptor v,
                    Predicate pred,
                    ENVIRE_GRAPH& g)
    { return remove_in_edge_if(v, pred, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS, typename Property>
    struct property_map<ENVIRE_GRAPH, Property>: property_map<typename ENVIRE_GRAPH::graph_type, Property> {};

    template <ENVIRE_GRAPH_PARAMS>
    struct property_map<ENVIRE_GRAPH, vertex_all_t> {
      typedef transform_value_property_map<
                detail::remove_first_property,
                typename property_map<typename ENVIRE_GRAPH::graph_type, vertex_all_t>::const_type>
        const_type;
      typedef transform_value_property_map<
                detail::remove_first_property,
                typename property_map<typename ENVIRE_GRAPH::graph_type, vertex_all_t>::type>
        type;
    };

    template <ENVIRE_GRAPH_PARAMS>
    struct property_map<ENVIRE_GRAPH, edge_all_t> {
      typedef transform_value_property_map<
                detail::remove_first_property,
                typename property_map<typename ENVIRE_GRAPH::graph_type, edge_all_t>::const_type>
        const_type;
      typedef transform_value_property_map<
                detail::remove_first_property,
                typename property_map<typename ENVIRE_GRAPH::graph_type, edge_all_t>::type>
        type;
    };

    // PropertyGraph concepts
    template <ENVIRE_GRAPH_PARAMS, typename Property>
    inline typename property_map<ENVIRE_GRAPH, Property>::type
    get(Property p, ENVIRE_GRAPH& g)
    { return get(p, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS, typename Property>
    inline typename property_map<ENVIRE_GRAPH, Property>::const_type
    get(Property p, ENVIRE_GRAPH const& g)
    { return get(p, g.impl()); }

    template <ENVIRE_GRAPH_PARAMS>
    inline typename property_map<ENVIRE_GRAPH, vertex_all_t>::type
    get(vertex_all_t, ENVIRE_GRAPH& g)
    { return typename property_map<ENVIRE_GRAPH, vertex_all_t>::type(detail::remove_first_property(), get(vertex_all, g.impl())); }

    template <ENVIRE_GRAPH_PARAMS>
    inline typename property_map<ENVIRE_GRAPH, vertex_all_t>::const_type
    get(vertex_all_t, ENVIRE_GRAPH const& g)
    { return typename property_map<ENVIRE_GRAPH, vertex_all_t>::const_type(detail::remove_first_property(), get(vertex_all, g.impl())); }

    template <ENVIRE_GRAPH_PARAMS>
    inline typename property_map<ENVIRE_GRAPH, edge_all_t>::type
    get(edge_all_t, ENVIRE_GRAPH& g)
    { return typename property_map<ENVIRE_GRAPH, edge_all_t>::type(detail::remove_first_property(), get(edge_all, g.impl())); }

    template <ENVIRE_GRAPH_PARAMS>
    inline typename property_map<ENVIRE_GRAPH, edge_all_t>::const_type
    get(edge_all_t, ENVIRE_GRAPH const& g)
    { return typename property_map<ENVIRE_GRAPH, edge_all_t>::const_type(detail::remove_first_property(), get(edge_all, g.impl())); }

    template <ENVIRE_GRAPH_PARAMS, typename Property, typename Key>
    inline typename property_traits<
        typename property_map<
            typename ENVIRE_GRAPH::graph_type, Property
        >::const_type
    >::value_type
    get(Property p, ENVIRE_GRAPH const& g, Key const& k)
    { return get(p, g.impl(), k); }

    template <ENVIRE_GRAPH_PARAMS, typename Key>
    inline typename property_traits<
        typename property_map<
            typename ENVIRE_GRAPH::graph_type, vertex_all_t
        >::const_type
    >::value_type
    get(vertex_all_t, ENVIRE_GRAPH const& g, Key const& k)
    { return get(vertex_all, g.impl(), k).m_base; }

    template <ENVIRE_GRAPH_PARAMS, typename Key>
    inline typename property_traits<
        typename property_map<
            typename ENVIRE_GRAPH::graph_type, edge_all_t
        >::const_type
    >::value_type
    get(edge_all_t, ENVIRE_GRAPH const& g, Key const& k)
    { return get(edge_all, g.impl(), k).m_base; }

    template <ENVIRE_GRAPH_PARAMS, typename Property, typename Key, typename Value>
    inline void put(Property p, ENVIRE_GRAPH& g, Key const& k, Value const& v)
    { put(p, g.impl(), k, v); }

    template <ENVIRE_GRAPH_PARAMS, typename Key, typename Value>
    inline void put(vertex_all_t, ENVIRE_GRAPH& g, Key const& k, Value const& v)
    { put(vertex_all, g.impl(), k,
          typename ENVIRE_GRAPH::internal_vertex_property(get(vertex_index, g.impl(), k), v));
    }

    template <ENVIRE_GRAPH_PARAMS, typename Key, typename Value>
    inline void put(edge_all_t, ENVIRE_GRAPH& g, Key const& k, Value const& v)
    { put(edge_all, g.impl(), k,
          typename ENVIRE_GRAPH::internal_vertex_property(get(edge_index, g.impl(), k), v));
    }

    template <ENVIRE_GRAPH_PARAMS, class Property>
    typename graph_property<ENVIRE_GRAPH, Property>::type&
    get_property(ENVIRE_GRAPH& g, Property p)
    { return get_property(g.impl(), p); }

    template <ENVIRE_GRAPH_PARAMS, class Property>
    typename graph_property<ENVIRE_GRAPH, Property>::type const&
    get_property(ENVIRE_GRAPH const& g, Property p)
    { return get_property(g.impl(), p); }

    template <ENVIRE_GRAPH_PARAMS, class Property, class Value>
    void
    set_property(ENVIRE_GRAPH& g, Property p, Value v)
    { return set_property(g.impl(), p, v); }

    // Vertex index management

    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::vertex_index_type
    get_vertex_index(typename ENVIRE_GRAPH::vertex_descriptor v,
                    ENVIRE_GRAPH const& g)
    { return get(vertex_index, g, v); }

    template <ENVIRE_GRAPH_PARAMS>
    typename ENVIRE_GRAPH::vertex_index_type
    max_vertex_index(ENVIRE_GRAPH const& g)
    { return g.max_vertex_index(); }

    template <ENVIRE_GRAPH_PARAMS>
    inline void
    renumber_vertex_indices(ENVIRE_GRAPH& g)
    { g.renumber_vertex_indices(); }

    template <ENVIRE_GRAPH_PARAMS>
    inline void
    remove_vertex_and_renumber_indices(typename ENVIRE_GRAPH::vertex_iterator i,
                                    ENVIRE_GRAPH& g)
    { g.remove_vertex_and_renumber_indices(i); }

    // Edge index management
    template <ENVIRE_GRAPH_PARAMS>
    inline typename ENVIRE_GRAPH::edge_index_type
    get_edge_index(typename ENVIRE_GRAPH::edge_descriptor v, ENVIRE_GRAPH const& g)
    { return get(edge_index, g, v); }

    template <ENVIRE_GRAPH_PARAMS>
    typename ENVIRE_GRAPH::edge_index_type
    max_edge_index(ENVIRE_GRAPH const& g)
    { return g.max_edge_index(); }

    template <ENVIRE_GRAPH_PARAMS>
    inline void renumber_edge_indices(ENVIRE_GRAPH& g)
    { g.renumber_edge_indices(); }

    template <ENVIRE_GRAPH_PARAMS>
    inline void
    remove_edge_and_renumber_indices(typename ENVIRE_GRAPH::edge_iterator i,
                                     ENVIRE_GRAPH& g)
    { g.remove_edge_and_renumber_indices(i); }

    // Index management
    template <ENVIRE_GRAPH_PARAMS>
    inline void
    renumber_indices(ENVIRE_GRAPH& g)
    { g.renumber_indices(); }

    // Mutability Traits
    template <ENVIRE_GRAPH_PARAMS>
    struct graph_mutability_traits<ENVIRE_GRAPH> {
        typedef mutable_property_graph_tag category;
    };

    #undef ENVIRE_GRAPH_PARAMS
    #undef ENVIRE_GRAPH

} /* namespace envire */

#endif

<commit_msg>removed EnvireGraph.hpp. It was used for testing and is no longer needed<commit_after><|endoftext|>


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

    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <interfaces/bodypartformatter.h>
#include <interfaces/bodypart.h>
#include <interfaces/bodyparturlhandler.h>
#include <khtmlparthtmlwriter.h>

#include <kcal/calendarlocal.h>
#include <kcal/icalformat.h>
#include <kcal/attendee.h>
#include <kcal/incidence.h>
#include <kcal/incidenceformatter.h>

#include <kpimprefs.h> // for the timezone

#include <kmail/callback.h>
#include <kmail/kmmessage.h>
#include <kmail/kmcommands.h>

#include <email.h>

#include <kglobal.h>
#include <klocale.h>
#include <kstringhandler.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kdcopservicestarter.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <ktempfile.h>

#include <QUrl>
#include <QDir>
#include <QTextStream>

#include <kdepimmacros.h>

#include <dcopclient.h>
#include <dcopref.h>

using namespace KCal;

namespace {

class KMInvitationFormatterHelper : public KCal::InvitationFormatterHelper
{
  public:
    KMInvitationFormatterHelper( KMail::Interface::BodyPart *bodyPart ) : mBodyPart( bodyPart ) {}
    virtual QString generateLinkURL( const QString &id ) { return mBodyPart->makeLink( id ); }
  private:
    KMail::Interface::BodyPart *mBodyPart;
};

class Formatter : public KMail::Interface::BodyPartFormatter
{
  public:
    Result format( KMail::Interface::BodyPart *bodyPart,
                   KMail::HtmlWriter *writer ) const
    {
      if ( !writer )
        // Guard against crashes in createReply()
        return Ok;
      CalendarLocal cl( KPimPrefs::timezone() );
      KMInvitationFormatterHelper helper( bodyPart );
      QString source;
      /* If the bodypart does not have a charset specified, we need to fall
         back to utf8, not the KMail fallback encoding, so get the contents
         as binary and decode explicitly. */
      if ( bodyPart->contentTypeParameter( "charset").isEmpty() ) {
        const QByteArray &ba = bodyPart->asBinary();
        source = QString::fromUtf8(ba);
      } else {
        source = bodyPart->asText();
      }
      QString html = IncidenceFormatter::formatICalInvitation( source, &cl, &helper );

      if ( html.isEmpty() ) return AsIcon;
      writer->queue( html );

      return Ok;
    }
};

class UrlHandler : public KMail::Interface::BodyPartURLHandler
{
  public:
    UrlHandler()
    {
      kDebug() << "UrlHandler() (iCalendar)" << endl;
    }

    Incidence* icalToString( const QString& iCal ) const
    {
      CalendarLocal calendar( KPimPrefs::timezone() ) ;
      ICalFormat format;
      ScheduleMessage *message =
        format.parseScheduleMessage( &calendar, iCal );
      if ( !message )
        //TODO: Error message?
        return 0;
      return dynamic_cast<Incidence*>( message->event() );
    }

    Attendee *findMyself( Incidence* incidence, const QString& receiver ) const
    {
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      Attendee* myself = 0;
      // Find myself. There will always be all attendees listed, even if
      // only I need to answer it.
      if ( attendees.count() == 1 )
        // Only one attendee, that must be me
        myself = *attendees.begin();
      else {
        for ( it = attendees.begin(); it != attendees.end(); ++it ) {
          // match only the email part, not the name
          if( EmailAddressTools::compareEmail( (*it)->email(), receiver, false ) ) {
            // We are the current one, and even the receiver, note
            // this and quit searching.
            myself = (*it);
            break;
          }
        }
      }
      return myself;
    }

    static bool heuristicalRSVP( Incidence *incidence )
    {
      bool rsvp = true; // better send superfluously than not at all
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      for ( it = attendees.begin(); it != attendees.end(); ++it ) {
        if ( it == attendees.begin() ) {
          rsvp = (*it)->RSVP(); // use what the first one has
        } else {
          if ( (*it)->RSVP() != rsvp ) {
            rsvp = true; // they differ, default
            break;
          }
        }
      }
      return rsvp;
    }

    static Attendee::Role heuristicalRole( Incidence *incidence )
    {
      Attendee::Role role = Attendee::OptParticipant;
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      for ( it = attendees.begin(); it != attendees.end(); ++it ) {
        if ( it == attendees.begin() ) {
          role = (*it)->role(); // use what the first one has
        } else {
          if ( (*it)->role() != role ) {
            role = Attendee::OptParticipant; // they differ, default
            break;
          }
        }
      }
      return role;

    }

    void setStatusOnMyself( Incidence* incidence, Attendee* myself,
                            Attendee::PartStat status, const QString &receiver ) const
    {
      Attendee* newMyself = 0;
      QString name;
      QString email;
      EmailAddressTools::extractEmailAddressAndName( receiver, email, name );
      if ( name.isEmpty() && myself ) name = myself->name();
      if ( email.isEmpty()&& myself ) email = myself->email();
      Q_ASSERT( !email.isEmpty() ); // delivery must be possible
      newMyself = new Attendee( name,
                                email,
                                true, // RSVP, otherwise we would not be here
                                status,
                                myself ? myself->role() : heuristicalRole( incidence ),
                                myself ? myself->uid() : QString::null );

      // Make sure only ourselves is in the event
      incidence->clearAttendees();
      if( newMyself )
        incidence->addAttendee( newMyself );
    }

    bool mail( Incidence* incidence, KMail::Callback& callback ) const
    {
      ICalFormat format;
      format.setTimeZone( KPimPrefs::timezone(), false );
      QString msg = format.createScheduleMessage( incidence,
                                                  Scheduler::Reply );
      QString subject;
      if ( !incidence->summary().isEmpty() )
        subject = i18n( "Answer: %1", incidence->summary() );
      else
        subject = i18n( "Answer: Incidence with no summary" );
      return callback.mailICal( incidence->organizer().fullName(), msg, subject );
    }

    bool saveFile( const QString& receiver, const QString& iCal,
                   const QString& type ) const
    {
      KTempFile file( KStandardDirs::locateLocal( "data", "korganizer/income." + type + '/',
                                   true ) );
      QTextStream* ts = file.textStream();
      if ( !ts ) {
        KMessageBox::error( 0, i18n("Could not save file to KOrganizer") );
        return false;
      }
      ts->setCodec("UTF-8");
      (*ts) << receiver << '\n' << iCal;
      file.close();

      // Now ensure that korganizer is running; otherwise start it, to prevent surprises
      // (https://intevation.de/roundup/kolab/issue758)
      QString error;
      DCOPCString dcopService;
      int result = KDCOPServiceStarter::self()->findServiceFor( "DCOP/Organizer", QString::null, &error, &dcopService );
      if ( result == 0 ) {
        // OK, so korganizer (or kontact) is running. Now ensure the object we want is available
        // [that's not the case when kontact was already running, but korganizer not loaded into it...]
        static const char* const dcopObjectId = "KOrganizerIface";
        DCOPCString dummy;
        if ( !kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ) {
          DCOPRef ref( dcopService, dcopService ); // talk to the KUniqueApplication or its kontact wrapper
          DCOPReply reply = ref.call( "load()" );
          if ( reply.isValid() && (bool)reply ) {
            kDebug() << "Loaded " << dcopService << " successfully" << endl;
            Q_ASSERT( kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) );
          } else
            kWarning() << "Error loading " << dcopService << endl;
        }

        // We don't do anything with it, we just need it to be running so that it handles
        // the incoming directory.
      }
      else
        kWarning() << "Couldn't start DCOP/Organizer: " << dcopService << " " << error << endl;

      return true;
    }

    bool handleInvitation( const QString& iCal, Attendee::PartStat status,
                           KMail::Callback &callback ) const
    {
      bool ok = true;
      const QString receiver = callback.receiver();
      if ( receiver.isEmpty() )
        // Must be some error. Still return true though, since we did handle it
        return true;

      // First, save it for KOrganizer to handle
      QString dir;
      if ( status == Attendee::Accepted ) dir = "accepted";
      else if ( status == Attendee::Tentative  ) dir = "tentative";
      else if ( status == Attendee::Declined ) dir = "cancel";
      else return true; // unknown status

      saveFile( receiver, iCal, dir );

      // Now produce the return message
      Incidence* incidence = icalToString( iCal );

      if( !incidence ) return false;
      Attendee *myself = findMyself( incidence, receiver );
      if ( ( myself && myself->RSVP() ) || heuristicalRSVP( incidence ) ) {
        setStatusOnMyself( incidence, myself, status, receiver );
        ok =  mail( incidence, callback );
      } else {
        ( new KMDeleteMsgCommand( callback.getMsg()->getMsgSerNum() ) )->start();
      }
      delete incidence;
      return ok;
    }

    bool handleIgnore( const QString&, KMail::Callback& c ) const
    {
      // simply move the message to trash
      ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start();
      return true;
    }

    bool handleClick( KMail::Interface::BodyPart *part,
                      const QString &path, KMail::Callback& c ) const
    {
      QString iCal = part->asText();
      bool result = false;
      if ( path == "accept" )
        result = handleInvitation( iCal, Attendee::Accepted, c );
      if ( path == "accept_conditionally" )
        result = handleInvitation( iCal, Attendee::Tentative, c );
      if ( path == "ignore" )
        result = handleIgnore( iCal, c );
      if ( path == "decline" )
        result = handleInvitation( iCal, Attendee::Declined, c );
      if ( path == "reply" || path == "cancel" ) {
        // These should just be saved with their type as the dir
        if ( saveFile( "Receiver Not Searched", iCal, path ) ) {
          ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start();
          result = true;
        }
      }
      if ( result )
        c.closeIfSecondaryWindow();
      return result;
    }

    bool handleContextMenuRequest( KMail::Interface::BodyPart *,
                                   const QString &,
                                   const QPoint & ) const
    {
      return false;
    }

    QString statusBarMessage( KMail::Interface::BodyPart *,
                              const QString &path ) const
    {
      if ( !path.isEmpty() ) {
        if ( path == "accept" )
          return i18n("Accept incidence");
        if ( path == "accept_conditionally" )
          return i18n( "Accept incidence conditionally" );
        if ( path == "ignore" )
          return i18n( "Throw mail away" );
        if ( path == "decline" )
          return i18n( "Decline incidence" );
        if ( path == "check_calendar" )
          return i18n("Check my calendar..." );
        if ( path == "reply" )
          return i18n( "Enter incidence into my calendar" );
        if ( path == "cancel" )
          return i18n( "Remove incidence from my calendar" );
      }

      return QString::null;
    }
};

class Plugin : public KMail::Interface::BodyPartFormatterPlugin
{
  public:
    const KMail::Interface::BodyPartFormatter *bodyPartFormatter( int idx ) const
    {
      if ( idx == 0 ) return new Formatter();
      else return 0;
    }

    const char *type( int idx ) const
    {
      if ( idx == 0 ) return "text";
      else return 0;
    }

    const char *subtype( int idx ) const
    {
      if ( idx == 0 ) return "calendar";
      else return 0;
    }

    const KMail::Interface::BodyPartURLHandler * urlHandler( int idx ) const
    {
      if ( idx == 0 ) return new UrlHandler();
      else return 0;
    }
};

}

extern "C"
KDE_EXPORT KMail::Interface::BodyPartFormatterPlugin *
libkmail_bodypartformatter_text_calendar_create_bodypart_formatter_plugin()
{
  KGlobal::locale()->insertCatalog( "kmail_text_calendar_plugin" );
  return new Plugin();
}
<commit_msg>compile<commit_after>/*
    This file is part of kdepim.

    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <interfaces/bodypartformatter.h>
#include <interfaces/bodypart.h>
#include <interfaces/bodyparturlhandler.h>
#include <khtmlparthtmlwriter.h>

#include <kcal/calendarlocal.h>
#include <kcal/icalformat.h>
#include <kcal/attendee.h>
#include <kcal/incidence.h>
#include <kcal/incidenceformatter.h>

#include <kpimprefs.h> // for the timezone

#include <kmail/callback.h>
#include <kmail/kmmessage.h>
#include <kmail/kmcommands.h>

#include <emailfunctions/email.h>

#include <kglobal.h>
#include <klocale.h>
#include <kstringhandler.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kdbusservicestarter.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <ktempfile.h>

#include <QUrl>
#include <QDir>
#include <QTextStream>

#include <kdepimmacros.h>

using namespace KCal;

namespace {

class KMInvitationFormatterHelper : public KCal::InvitationFormatterHelper
{
  public:
    KMInvitationFormatterHelper( KMail::Interface::BodyPart *bodyPart ) : mBodyPart( bodyPart ) {}
    virtual QString generateLinkURL( const QString &id ) { return mBodyPart->makeLink( id ); }
  private:
    KMail::Interface::BodyPart *mBodyPart;
};

class Formatter : public KMail::Interface::BodyPartFormatter
{
  public:
    Result format( KMail::Interface::BodyPart *bodyPart,
                   KMail::HtmlWriter *writer ) const
    {
      if ( !writer )
        // Guard against crashes in createReply()
        return Ok;
      CalendarLocal cl( KPimPrefs::timezone() );
      KMInvitationFormatterHelper helper( bodyPart );
      QString source;
      /* If the bodypart does not have a charset specified, we need to fall
         back to utf8, not the KMail fallback encoding, so get the contents
         as binary and decode explicitly. */
      if ( bodyPart->contentTypeParameter( "charset").isEmpty() ) {
        const QByteArray &ba = bodyPart->asBinary();
        source = QString::fromUtf8(ba);
      } else {
        source = bodyPart->asText();
      }
      QString html = IncidenceFormatter::formatICalInvitation( source, &cl, &helper );

      if ( html.isEmpty() ) return AsIcon;
      writer->queue( html );

      return Ok;
    }
};

class UrlHandler : public KMail::Interface::BodyPartURLHandler
{
  public:
    UrlHandler()
    {
      kDebug() << "UrlHandler() (iCalendar)" << endl;
    }

    Incidence* icalToString( const QString& iCal ) const
    {
      CalendarLocal calendar( KPimPrefs::timezone() ) ;
      ICalFormat format;
      ScheduleMessage *message =
        format.parseScheduleMessage( &calendar, iCal );
      if ( !message )
        //TODO: Error message?
        return 0;
      return dynamic_cast<Incidence*>( message->event() );
    }

    Attendee *findMyself( Incidence* incidence, const QString& receiver ) const
    {
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      Attendee* myself = 0;
      // Find myself. There will always be all attendees listed, even if
      // only I need to answer it.
      if ( attendees.count() == 1 )
        // Only one attendee, that must be me
        myself = *attendees.begin();
      else {
        for ( it = attendees.begin(); it != attendees.end(); ++it ) {
          // match only the email part, not the name
          if( EmailAddressTools::compareEmail( (*it)->email(), receiver, false ) ) {
            // We are the current one, and even the receiver, note
            // this and quit searching.
            myself = (*it);
            break;
          }
        }
      }
      return myself;
    }

    static bool heuristicalRSVP( Incidence *incidence )
    {
      bool rsvp = true; // better send superfluously than not at all
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      for ( it = attendees.begin(); it != attendees.end(); ++it ) {
        if ( it == attendees.begin() ) {
          rsvp = (*it)->RSVP(); // use what the first one has
        } else {
          if ( (*it)->RSVP() != rsvp ) {
            rsvp = true; // they differ, default
            break;
          }
        }
      }
      return rsvp;
    }

    static Attendee::Role heuristicalRole( Incidence *incidence )
    {
      Attendee::Role role = Attendee::OptParticipant;
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      for ( it = attendees.begin(); it != attendees.end(); ++it ) {
        if ( it == attendees.begin() ) {
          role = (*it)->role(); // use what the first one has
        } else {
          if ( (*it)->role() != role ) {
            role = Attendee::OptParticipant; // they differ, default
            break;
          }
        }
      }
      return role;

    }

    void setStatusOnMyself( Incidence* incidence, Attendee* myself,
                            Attendee::PartStat status, const QString &receiver ) const
    {
      Attendee* newMyself = 0;
      QString name;
      QString email;
      EmailAddressTools::extractEmailAddressAndName( receiver, email, name );
      if ( name.isEmpty() && myself ) name = myself->name();
      if ( email.isEmpty()&& myself ) email = myself->email();
      Q_ASSERT( !email.isEmpty() ); // delivery must be possible
      newMyself = new Attendee( name,
                                email,
                                true, // RSVP, otherwise we would not be here
                                status,
                                myself ? myself->role() : heuristicalRole( incidence ),
                                myself ? myself->uid() : QString::null );

      // Make sure only ourselves is in the event
      incidence->clearAttendees();
      if( newMyself )
        incidence->addAttendee( newMyself );
    }

    bool mail( Incidence* incidence, KMail::Callback& callback ) const
    {
      ICalFormat format;
      format.setTimeZone( KPimPrefs::timezone(), false );
      QString msg = format.createScheduleMessage( incidence,
                                                  Scheduler::Reply );
      QString subject;
      if ( !incidence->summary().isEmpty() )
        subject = i18n( "Answer: %1", incidence->summary() );
      else
        subject = i18n( "Answer: Incidence with no summary" );
      return callback.mailICal( incidence->organizer().fullName(), msg, subject );
    }

    bool saveFile( const QString& receiver, const QString& iCal,
                   const QString& type ) const
    {
      KTempFile file( KStandardDirs::locateLocal( "data", "korganizer/income." + type + '/',
                                   true ) );
      QTextStream* ts = file.textStream();
      if ( !ts ) {
        KMessageBox::error( 0, i18n("Could not save file to KOrganizer") );
        return false;
      }
      ts->setCodec("UTF-8");
      (*ts) << receiver << '\n' << iCal;
      file.close();

      // Now ensure that korganizer is running; otherwise start it, to prevent surprises
      // (https://intevation.de/roundup/kolab/issue758)
      QString error;
      QString dcopService;
      int result = KDBusServiceStarter::self()->findServiceFor( "DCOP/Organizer", QString::null, &error, &dcopService );
      if ( result == 0 ) {
        // OK, so korganizer (or kontact) is running. Now ensure the object we want is available
        // [that's not the case when kontact was already running, but korganizer not loaded into it...]
#warning Port me to DBus!
/*        static const char* const dcopObjectId = "KOrganizerIface";
        DCOPCString dummy;
        if ( !kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ) {
          DCOPRef ref( dcopService, dcopService ); // talk to the KUniqueApplication or its kontact wrapper
          DCOPReply reply = ref.call( "load()" );
          if ( reply.isValid() && (bool)reply ) {
            kDebug() << "Loaded " << dcopService << " successfully" << endl;
            Q_ASSERT( kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) );
          } else
            kWarning() << "Error loading " << dcopService << endl;
        }*/

        // We don't do anything with it, we just need it to be running so that it handles
        // the incoming directory.
      }
      else
        kWarning() << "Couldn't start DCOP/Organizer: " << dcopService << " " << error << endl;

      return true;
    }

    bool handleInvitation( const QString& iCal, Attendee::PartStat status,
                           KMail::Callback &callback ) const
    {
      bool ok = true;
      const QString receiver = callback.receiver();
      if ( receiver.isEmpty() )
        // Must be some error. Still return true though, since we did handle it
        return true;

      // First, save it for KOrganizer to handle
      QString dir;
      if ( status == Attendee::Accepted ) dir = "accepted";
      else if ( status == Attendee::Tentative  ) dir = "tentative";
      else if ( status == Attendee::Declined ) dir = "cancel";
      else return true; // unknown status

      saveFile( receiver, iCal, dir );

      // Now produce the return message
      Incidence* incidence = icalToString( iCal );

      if( !incidence ) return false;
      Attendee *myself = findMyself( incidence, receiver );
      if ( ( myself && myself->RSVP() ) || heuristicalRSVP( incidence ) ) {
        setStatusOnMyself( incidence, myself, status, receiver );
        ok =  mail( incidence, callback );
      } else {
        ( new KMDeleteMsgCommand( callback.getMsg()->getMsgSerNum() ) )->start();
      }
      delete incidence;
      return ok;
    }

    bool handleIgnore( const QString&, KMail::Callback& c ) const
    {
      // simply move the message to trash
      ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start();
      return true;
    }

    bool handleClick( KMail::Interface::BodyPart *part,
                      const QString &path, KMail::Callback& c ) const
    {
      QString iCal = part->asText();
      bool result = false;
      if ( path == "accept" )
        result = handleInvitation( iCal, Attendee::Accepted, c );
      if ( path == "accept_conditionally" )
        result = handleInvitation( iCal, Attendee::Tentative, c );
      if ( path == "ignore" )
        result = handleIgnore( iCal, c );
      if ( path == "decline" )
        result = handleInvitation( iCal, Attendee::Declined, c );
      if ( path == "reply" || path == "cancel" ) {
        // These should just be saved with their type as the dir
        if ( saveFile( "Receiver Not Searched", iCal, path ) ) {
          ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start();
          result = true;
        }
      }
      if ( result )
        c.closeIfSecondaryWindow();
      return result;
    }

    bool handleContextMenuRequest( KMail::Interface::BodyPart *,
                                   const QString &,
                                   const QPoint & ) const
    {
      return false;
    }

    QString statusBarMessage( KMail::Interface::BodyPart *,
                              const QString &path ) const
    {
      if ( !path.isEmpty() ) {
        if ( path == "accept" )
          return i18n("Accept incidence");
        if ( path == "accept_conditionally" )
          return i18n( "Accept incidence conditionally" );
        if ( path == "ignore" )
          return i18n( "Throw mail away" );
        if ( path == "decline" )
          return i18n( "Decline incidence" );
        if ( path == "check_calendar" )
          return i18n("Check my calendar..." );
        if ( path == "reply" )
          return i18n( "Enter incidence into my calendar" );
        if ( path == "cancel" )
          return i18n( "Remove incidence from my calendar" );
      }

      return QString::null;
    }
};

class Plugin : public KMail::Interface::BodyPartFormatterPlugin
{
  public:
    const KMail::Interface::BodyPartFormatter *bodyPartFormatter( int idx ) const
    {
      if ( idx == 0 ) return new Formatter();
      else return 0;
    }

    const char *type( int idx ) const
    {
      if ( idx == 0 ) return "text";
      else return 0;
    }

    const char *subtype( int idx ) const
    {
      if ( idx == 0 ) return "calendar";
      else return 0;
    }

    const KMail::Interface::BodyPartURLHandler * urlHandler( int idx ) const
    {
      if ( idx == 0 ) return new UrlHandler();
      else return 0;
    }
};

}

extern "C"
KDE_EXPORT KMail::Interface::BodyPartFormatterPlugin *
libkmail_bodypartformatter_text_calendar_create_bodypart_formatter_plugin()
{
  KGlobal::locale()->insertCatalog( "kmail_text_calendar_plugin" );
  return new Plugin();
}
<|endoftext|>


<commit_before>// playHistoryTracker.cpp : Defines the entry point for the DLL application.
//

#include "bzfsAPI.h"
#include <string>
#include <map>

BZ_GET_PLUGIN_VERSION

// event handler callback

class PlayHistoryTracker : public bz_EventHandler
{
public:
	PlayHistoryTracker();
	virtual ~PlayHistoryTracker();

	virtual void process ( bz_EventData *eventData );

	virtual bool autoDelete ( void ) { return false;} // this will be used for more then one event
protected:

	typedef struct
	{
		int playerID;
		std::string callsign;
		double		startTime;
		double		lastUpdateTime;
		int			spreeTotal;
	}trPlayerHistoryRecord;

	std::map<int, trPlayerHistoryRecord > playerList;
};

PlayHistoryTracker	historyTracker;

BZF_PLUGIN_CALL int bz_Load ( const char* commandLine )
{
	bz_debugMessage(4,"PlayHistoryTracker plugin loaded");

	bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);
	bz_registerEvent(bz_ePlayerPartEvent,BZ_ALL_USERS,&historyTracker);
	bz_registerEvent(bz_ePlayerSpawnEvent,BZ_ALL_USERS,&historyTracker);
	bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);

	return 0;
}

BZF_PLUGIN_CALL int bz_Unload ( void )
{
	bz_removeEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);
	bz_removeEvent(bz_ePlayerPartEvent,BZ_ALL_USERS,&historyTracker);
	bz_removeEvent(bz_ePlayerSpawnEvent,BZ_ALL_USERS,&historyTracker);
	bz_removeEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);

	bz_debugMessage(4,"PlayHistoryTracker plugin unloaded");
	return 0;
}

// ----------------- SpreeTracker-----------------

/*typedef struct
{
int playerID;
std::string callsign;
double		startTime;
double		lastUpdateTime;
int			spreeTotal;
}trPlayerHistoryRecord;

std::map<int, trPlayerHistoryRecord > playerList; */

PlayHistoryTracker::PlayHistoryTracker()
{
}

PlayHistoryTracker::~PlayHistoryTracker()
{
}

void PlayHistoryTracker::process ( bz_EventData *eventData )
{
	switch (eventData->eventType)
	{
	default:
		// really WTF!!!!
		break;

	case bz_ePlayerDieEvent:
		{
			 bz_PlayerDieEventData	*deathRecord = ( bz_PlayerDieEventData*)eventData;

			 bz_PlayerRecord	killerData;

			 bz_getPlayerByIndex(deathRecord->killerID,&killerData);

		//	GameKeeper::Player *killerData = GameKeeper::Player::getPlayerByIndex(deathRecord->killerID);
			//GameKeeper::Player *victimData = GameKeeper::Player::getPlayerByIndex(deathRecord->playerID);

			 std::string soundToPlay;

			// clear out the dude who got shot, since he won't be having any SPREEs
			if (playerList.find(deathRecord->playerID) != playerList.end())
			{
				trPlayerHistoryRecord	&record = playerList.find(deathRecord->playerID)->second;
				std::string message;
				if ( record.spreeTotal >= 5 && record.spreeTotal < 10 )
					message = record.callsign + std::string("'s rampage was stoped by ") + killerData.callsign;
				if ( record.spreeTotal >= 10 && record.spreeTotal < 20 )
					message = record.callsign + std::string("'s killing spree was halted by ") + killerData.callsign;
				if ( record.spreeTotal >= 20 )
					message = std::string("The unstopable reign of ") + record.callsign + std::string(" was ended by ") + killerData.callsign;

				if (message.size())
				{
					 bz_sendTextMessage(BZ_SERVER, BZ_ALL_USERS, message.c_str());
					 soundToPlay = "spree4";
				}

				record.spreeTotal = 0;
				record.startTime = deathRecord->time;
				record.lastUpdateTime = deathRecord->time;

			}

			// chock up another win for our killer
			// if they weren't the same as the killer ( suicide ).
			if ( (deathRecord->playerID != deathRecord->killerID) && playerList.find(deathRecord->killerID) != playerList.end())
			{
				trPlayerHistoryRecord	&record = playerList.find(deathRecord->killerID)->second;
				record.spreeTotal++;
				record.lastUpdateTime = deathRecord->time;

				std::string message;

				if ( record.spreeTotal == 5 )
				{
					message = record.callsign + std::string(" is on a Rampage!");
					if (!soundToPlay.size())
						soundToPlay = "spree1";
				}
				if ( record.spreeTotal == 10 )
				{
					message = record.callsign + std::string(" is on a Killing Spree!");
					if (!soundToPlay.size())
						soundToPlay = "spree2";
				}
				if ( record.spreeTotal == 20 )
				{
					message = record.callsign + std::string(" is Unstoppable!!");
					if (!soundToPlay.size())
						soundToPlay = "spree3";
				}
				if ( record.spreeTotal > 20 && record.spreeTotal%5 == 0 )
				{
					message = record.callsign + std::string("'s continues to rage on");
					if (!soundToPlay.size())
						soundToPlay = "spree4";
				}

				if (message.size())
				{
					bz_sendTextMessage(BZ_SERVER, BZ_ALL_USERS, message.c_str());
				}

			}

		//	if (soundToPlay.size())
		//	bz_sendPlayCustomLocalSound(BZ_ALL_USERS,soundToPlay.c_str());

		}
		break;

	case  bz_ePlayerSpawnEvent:
		// really WTF!!!!
		break;

	case  bz_ePlayerJoinEvent:
		{
			trPlayerHistoryRecord	playerRecord;

			playerRecord.playerID = (( bz_PlayerJoinPartEventData*)eventData)->playerID;
			playerRecord.callsign = (( bz_PlayerJoinPartEventData*)eventData)->callsign;
			playerRecord.spreeTotal = 0;
			playerRecord.lastUpdateTime = (( bz_PlayerJoinPartEventData*)eventData)->time;
			playerRecord.startTime = playerRecord.lastUpdateTime;

			playerList[(( bz_PlayerJoinPartEventData*)eventData)->playerID] = playerRecord;
		}
		break;
	case  bz_ePlayerPartEvent:
		{
			std::map<int, trPlayerHistoryRecord >::iterator	itr = playerList.find( (( bz_PlayerJoinPartEventData*)eventData)->playerID );
			if (itr != playerList.end())
				playerList.erase(itr);
		}
		break;
	}
}

<commit_msg>make compatable with new API version<commit_after>// playHistoryTracker.cpp : Defines the entry point for the DLL application.
//

#include "bzfsAPI.h"
#include <string>
#include <map>

BZ_GET_PLUGIN_VERSION

// event handler callback

class PlayHistoryTracker : public bz_EventHandler
{
public:
	PlayHistoryTracker();
	virtual ~PlayHistoryTracker();

	virtual void process ( bz_EventData *eventData );

	virtual bool autoDelete ( void ) { return false;} // this will be used for more then one event
protected:

	typedef struct
	{
		int playerID;
		std::string callsign;
		double		startTime;
		double		lastUpdateTime;
		int			spreeTotal;
	}trPlayerHistoryRecord;

	std::map<int, trPlayerHistoryRecord > playerList;
};

PlayHistoryTracker	historyTracker;

BZF_PLUGIN_CALL int bz_Load ( const char* commandLine )
{
	bz_debugMessage(4,"PlayHistoryTracker plugin loaded");

	bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);
	bz_registerEvent(bz_ePlayerPartEvent,BZ_ALL_USERS,&historyTracker);
	bz_registerEvent(bz_ePlayerSpawnEvent,BZ_ALL_USERS,&historyTracker);
	bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);

	return 0;
}

BZF_PLUGIN_CALL int bz_Unload ( void )
{
	bz_removeEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);
	bz_removeEvent(bz_ePlayerPartEvent,BZ_ALL_USERS,&historyTracker);
	bz_removeEvent(bz_ePlayerSpawnEvent,BZ_ALL_USERS,&historyTracker);
	bz_removeEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);

	bz_debugMessage(4,"PlayHistoryTracker plugin unloaded");
	return 0;
}

// ----------------- SpreeTracker-----------------

/*typedef struct
{
int playerID;
std::string callsign;
double		startTime;
double		lastUpdateTime;
int			spreeTotal;
}trPlayerHistoryRecord;

std::map<int, trPlayerHistoryRecord > playerList; */

PlayHistoryTracker::PlayHistoryTracker()
{
}

PlayHistoryTracker::~PlayHistoryTracker()
{
}

void PlayHistoryTracker::process ( bz_EventData *eventData )
{
	switch (eventData->eventType)
	{
	default:
		// really WTF!!!!
		break;

	case bz_ePlayerDieEvent:
		{
			 bz_PlayerDieEventData	*deathRecord = ( bz_PlayerDieEventData*)eventData;

			 bz_PlayerRecord	killerData;

			 bz_getPlayerByIndex(deathRecord->killerID,&killerData);

		//	GameKeeper::Player *killerData = GameKeeper::Player::getPlayerByIndex(deathRecord->killerID);
			//GameKeeper::Player *victimData = GameKeeper::Player::getPlayerByIndex(deathRecord->playerID);

			 std::string soundToPlay;

			// clear out the dude who got shot, since he won't be having any SPREEs
			if (playerList.find(deathRecord->playerID) != playerList.end())
			{
				trPlayerHistoryRecord	&record = playerList.find(deathRecord->playerID)->second;
				std::string message;
				if ( record.spreeTotal >= 5 && record.spreeTotal < 10 )
					message = record.callsign + std::string("'s rampage was stoped by ") + killerData.callsign.c_str();
				if ( record.spreeTotal >= 10 && record.spreeTotal < 20 )
					message = record.callsign + std::string("'s killing spree was halted by ") + killerData.callsign.c_str();
				if ( record.spreeTotal >= 20 )
					message = std::string("The unstopable reign of ") + record.callsign + std::string(" was ended by ") + killerData.callsign.c_str();

				if (message.size())
				{
					 bz_sendTextMessage(BZ_SERVER, BZ_ALL_USERS, message.c_str());
					 soundToPlay = "spree4";
				}

				record.spreeTotal = 0;
				record.startTime = deathRecord->time;
				record.lastUpdateTime = deathRecord->time;

			}

			// chock up another win for our killer
			// if they weren't the same as the killer ( suicide ).
			if ( (deathRecord->playerID != deathRecord->killerID) && playerList.find(deathRecord->killerID) != playerList.end())
			{
				trPlayerHistoryRecord	&record = playerList.find(deathRecord->killerID)->second;
				record.spreeTotal++;
				record.lastUpdateTime = deathRecord->time;

				std::string message;

				if ( record.spreeTotal == 5 )
				{
					message = record.callsign + std::string(" is on a Rampage!");
					if (!soundToPlay.size())
						soundToPlay = "spree1";
				}
				if ( record.spreeTotal == 10 )
				{
					message = record.callsign + std::string(" is on a Killing Spree!");
					if (!soundToPlay.size())
						soundToPlay = "spree2";
				}
				if ( record.spreeTotal == 20 )
				{
					message = record.callsign + std::string(" is Unstoppable!!");
					if (!soundToPlay.size())
						soundToPlay = "spree3";
				}
				if ( record.spreeTotal > 20 && record.spreeTotal%5 == 0 )
				{
					message = record.callsign + std::string("'s continues to rage on");
					if (!soundToPlay.size())
						soundToPlay = "spree4";
				}

				if (message.size())
				{
					bz_sendTextMessage(BZ_SERVER, BZ_ALL_USERS, message.c_str());
				}

			}

		//	if (soundToPlay.size())
		//	bz_sendPlayCustomLocalSound(BZ_ALL_USERS,soundToPlay.c_str());

		}
		break;

	case  bz_ePlayerSpawnEvent:
		// really WTF!!!!
		break;

	case  bz_ePlayerJoinEvent:
		{
			trPlayerHistoryRecord	playerRecord;

			playerRecord.playerID = (( bz_PlayerJoinPartEventData*)eventData)->playerID;
			playerRecord.callsign = (( bz_PlayerJoinPartEventData*)eventData)->callsign.c_str();
			playerRecord.spreeTotal = 0;
			playerRecord.lastUpdateTime = (( bz_PlayerJoinPartEventData*)eventData)->time;
			playerRecord.startTime = playerRecord.lastUpdateTime;

			playerList[(( bz_PlayerJoinPartEventData*)eventData)->playerID] = playerRecord;
		}
		break;
	case  bz_ePlayerPartEvent:
		{
			std::map<int, trPlayerHistoryRecord >::iterator	itr = playerList.find( (( bz_PlayerJoinPartEventData*)eventData)->playerID );
			if (itr != playerList.end())
				playerList.erase(itr);
		}
		break;
	}
}

<|endoftext|>