<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

// No circular dependencies between gl.h and glew.h
#ifndef GLEW_INCLUDED
#include <GL/glew.h>
#define GLEW_INCLUDED
#endif

#include "vvbrick.h"
#include "vvtexrend.h"

#include <math.h>

void vvBrick::render(vvTexRend* renderer, const vvVector3& normal,
                     const vvVector3& farthest, const vvVector3& delta,
                     const vvVector3& probeMin, const vvVector3& probeMax,
                     GLuint*& texNames, vvShaderManager* isectShader, const bool setupEdges) const
{
  const vvVector3 dist = max - min;

  // Clip probe object to brick extends.
  vvVector3 minClipped;
  vvVector3 maxClipped;
  vvVector3 texRange;
  vvVector3 texMin;
  for (int i = 0; i < 3; ++i)
  {
    if (min[i] < probeMin[i])
    {
      minClipped[i] = probeMin[i];
    }
    else
    {
      minClipped[i] = min[i];
    }

    if (max[i] > probeMax[i])
    {
      maxClipped[i] = probeMax[i];
    }
    else
    {
      maxClipped[i] = max[i];
    }
    const float overlapNorm = (float)(brickTexelOverlap[i]) / (float)texels[i];
    texRange[i] = (1.0f - overlapNorm);
    texMin[i] = (1.0f / (2.0f * (float)(renderer->_renderState._brickTexelOverlap) * (float)texels[i]));
  }

  const vvVector3 (&verts)[8] = vvAABB(minClipped, maxClipped).calcVertices();

  float minDot;
  float maxDot;
  const ushort idx = getFrontIndex(verts, farthest, normal, minDot, maxDot);

  const float deltaInv = 1.0f / delta.length();

  const int startSlices = (int)ceilf(minDot * deltaInv);
  const int endSlices = (int)floorf(maxDot * deltaInv);

  glBindTexture(GL_TEXTURE_3D_EXT, texNames[index]);
  if (renderer->_proxyGeometryOnGpu)
  {
    isectShader->setArrayParameter3f(0, "vertices", 0, verts[0].e[0], verts[0].e[1], verts[0].e[2]);
    if (setupEdges)
    {
      for (int i = 1; i < 8; ++i)
      {
        isectShader->setArrayParameter3f(0, "vertices", i, verts[i].e[0]-verts[0].e[0],
                                                           verts[i].e[1]-verts[0].e[1],
                                                           verts[i].e[2]-verts[0].e[2]);
      }
    }

    // Pass planeStart along with brickMin and spare one setParameter call.
    isectShader->setParameter4f(0, "brickMin", min[0], min[1], min[2], -farthest.length());
    // Pass front index along with brickDimInv and spare one setParameter call.
    isectShader->setParameter4f(0, "brickDimInv", 1.0f/dist[0], 1.0f/dist[1], 1.0f/dist[2], idx);
    // Mind that textures overlap a little bit for correct interpolation at the borders.
    // Thus add that little difference.
    isectShader->setParameter3f(0, "texRange", texRange[0], texRange[1], texRange[2]);
    isectShader->setParameter3f(0, "texMin", texMin[0], texMin[1], texMin[2]);

    const int primCount = (endSlices - startSlices) + 1;

    glVertexPointer(2, GL_INT, 0, &renderer->_vertArray[startSlices*12]);
    glMultiDrawElements(GL_POLYGON, &renderer->_elemCounts[0], GL_UNSIGNED_INT, (const GLvoid**)&renderer->_vertIndices[0], primCount);
  }
  else // render proxy geometry on gpu? else then:
  {
    vvVector3 startPoint = farthest + delta * startSlices;

    for (int i = startSlices; i <= endSlices; ++i)
    {
      vvVector3 isect[6];
      const int isectCnt = isect->isectPlaneCuboid(&normal, &startPoint, &minClipped, &maxClipped);
      startPoint.add(&delta);

      if (isectCnt < 3) continue;                 // at least 3 intersections needed for drawing

      // Check volume section mode:
      if (renderer->minSlice != -1 && i < renderer->minSlice) continue;
      if (renderer->maxSlice != -1 && i > renderer->maxSlice) continue;

      // Put the intersecting 3 to 6 vertices in cyclic order to draw adjacent
      // and non-overlapping triangles:
      isect->cyclicSort(isectCnt, &normal);

      // Generate vertices in texture coordinates:
      vvVector3 texcoord[6];
      for (int j = 0; j < isectCnt; ++j)
      {
        for (int k = 0; k < 3; ++k)
        {
          texcoord[j][k] = (isect[j][k] - min.e[k]) / dist[k];
          texcoord[j][k] = texcoord[j][k] * texRange[k] + texMin[k];
        }
      }

      glBegin(GL_TRIANGLE_FAN);
      glColor4f(1.0, 1.0, 1.0, 1.0);
      glNormal3f(normal[0], normal[1], normal[2]);
      for (int j = 0; j < isectCnt; ++j)
      {
        // The following lines are the bottleneck of this method:
        glTexCoord3f(texcoord[j][0], texcoord[j][1], texcoord[j][2]);
        glVertex3f(isect[j][0], isect[j][1], isect[j][2]);
      }
      glEnd();
    }
  }
}

void vvBrick::renderOutlines(const vvVector3& probeMin, const vvVector3& probeMax) const
{
  vvVector3 minClipped;
  vvVector3 maxClipped;
  for (int i = 0; i < 3; i++)
  {
    if (min.e[i] < probeMin.e[i])
    {
      minClipped.e[i] = probeMin.e[i];
    }
    else
    {
      minClipped.e[i] = min.e[i];
    }

    if (max.e[i] > probeMax.e[i])
    {
      maxClipped.e[i] = probeMax.e[i];
    }
    else
    {
      maxClipped.e[i] = max.e[i];
    }
  }
  glBegin(GL_LINES);
    glColor3f(1.0f, 1.0f, 1.0f);
    glVertex3f(minClipped[0], minClipped[1], minClipped[2]);
    glVertex3f(maxClipped[0], minClipped[1], minClipped[2]);

    glVertex3f(minClipped[0], minClipped[1], minClipped[2]);
    glVertex3f(minClipped[0], maxClipped[1], minClipped[2]);

    glVertex3f(minClipped[0], minClipped[1], minClipped[2]);
    glVertex3f(minClipped[0], minClipped[1], maxClipped[2]);

    glVertex3f(maxClipped[0], maxClipped[1], maxClipped[2]);
    glVertex3f(minClipped[0], maxClipped[1], maxClipped[2]);

    glVertex3f(maxClipped[0], maxClipped[1], maxClipped[2]);
    glVertex3f(maxClipped[0], minClipped[1], maxClipped[2]);

    glVertex3f(maxClipped[0], maxClipped[1], maxClipped[2]);
    glVertex3f(maxClipped[0], maxClipped[1], minClipped[2]);

    glVertex3f(maxClipped[0], minClipped[1], minClipped[2]);
    glVertex3f(maxClipped[0], maxClipped[1], minClipped[2]);

    glVertex3f(maxClipped[0], minClipped[1], minClipped[2]);
    glVertex3f(maxClipped[0], minClipped[1], maxClipped[2]);

    glVertex3f(minClipped[0], maxClipped[1], minClipped[2]);
    glVertex3f(maxClipped[0], maxClipped[1], minClipped[2]);

    glVertex3f(minClipped[0], maxClipped[1], minClipped[2]);
    glVertex3f(minClipped[0], maxClipped[1], maxClipped[2]);

    glVertex3f(minClipped[0], minClipped[1], maxClipped[2]);
    glVertex3f(maxClipped[0], minClipped[1], maxClipped[2]);

    glVertex3f(minClipped[0], minClipped[1], maxClipped[2]);
    glVertex3f(minClipped[0], maxClipped[1], maxClipped[2]);
  glEnd();
}

bool vvBrick::upload3DTexture(GLuint& texName, uchar* texData,
                              const GLenum texFormat, const GLint internalTexFormat,
                              const bool interpolation)
{
  glBindTexture(GL_TEXTURE_3D_EXT, texName);

  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_MAG_FILTER, (interpolation) ? GL_LINEAR : GL_NEAREST);
  glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_MIN_FILTER, (interpolation) ? GL_LINEAR : GL_NEAREST);
  glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_R_EXT, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_S, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_T, GL_CLAMP);

  glTexImage3D(GL_PROXY_TEXTURE_3D_EXT, 0, internalTexFormat,
    texels[0], texels[1], texels[2], 0, texFormat, GL_UNSIGNED_BYTE, NULL);

  GLint glWidth;
  glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D_EXT, 0, GL_TEXTURE_WIDTH, &glWidth);
  if (glWidth != 0)
  {
    glTexImage3D(GL_TEXTURE_3D_EXT, 0, internalTexFormat, texels[0], texels[1], texels[2], 0,
      texFormat, GL_UNSIGNED_BYTE, texData);
    return true;
  }
  else
  {
    return false;
  }
}

/** Get front index of the brick based upon the current modelview matrix.
  @param vertices  NOTE THE FOLLOWING: albeit vertices are constituents of
                   bricks, these are passed along with the function call in
                   order not to recalculate them. This is due to the fact that
                   AABBs actually don't store pointers to their eight verts,
                   but only to two corners.
  @param point     The point to calc the distance from. The distance of interest
                   is the one from point to the first and last vertex along
                   normal
  @param normal    The normal to calc the distance along.
  @param minDot    The minimum dot product of vector point-vertex and normal,
                   passed along for later calculations.
  @param maxDot    The maximum dot product of vector point-vertex and normal,
                   passed along for later calculations.
*/
ushort vvBrick::getFrontIndex(const vvVector3* vertices,
                              const vvVector3& point,
                              const vvVector3& normal,
                              float& minDot,
                              float& maxDot) const
{

  // Get vertices with max and min distance to point along normal.
  maxDot = -FLT_MAX;
  minDot = FLT_MAX;
  ushort frontIndex;

  for (int i=0; i<8; i++)
  {
    const vvVector3 v = vertices[i] - point;
    const float dot = v.dot(&normal);
    if (dot > maxDot)
    {
      maxDot = dot;
      frontIndex = i;
    }

    if (dot < minDot)
    {
      minDot = dot;
    }
  }
  return frontIndex;
}

void vvBrick::sortByCenter(vvBrick** bricks, const int numBricks, const vvVector3& axis)
{
  const vvVector3 axisGetter(0, 1, 2);
  const int a = axis.dot(&axisGetter);

  // Selection sort.
  for (int i = 0; i < numBricks; ++i)
  {
    for (int j = i; j < numBricks; ++j)
    {
      vvBrick* tmp = bricks[j];
      for (int k = i + 1; k < numBricks; ++k)
      {
        vvBrick* tmp2 = bricks[k];
        if (tmp->getAABB().calcCenter().e[a] > tmp2->getAABB().calcCenter().e[a])
        {
          vvBrick* tmp3 = bricks[j];
          bricks[j] = bricks[k];
          bricks[k] = tmp3;
        }
      }
    }
  }
}
<commit_msg>Fix windows compiler warnings<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

// No circular dependencies between gl.h and glew.h
#ifndef GLEW_INCLUDED
#include <GL/glew.h>
#define GLEW_INCLUDED
#endif

#include "vvbrick.h"
#include "vvtexrend.h"

#include <math.h>

void vvBrick::render(vvTexRend* renderer, const vvVector3& normal,
                     const vvVector3& farthest, const vvVector3& delta,
                     const vvVector3& probeMin, const vvVector3& probeMax,
                     GLuint*& texNames, vvShaderManager* isectShader, const bool setupEdges) const
{
  const vvVector3 dist = max - min;

  // Clip probe object to brick extends.
  vvVector3 minClipped;
  vvVector3 maxClipped;
  vvVector3 texRange;
  vvVector3 texMin;
  for (int i = 0; i < 3; ++i)
  {
    if (min[i] < probeMin[i])
    {
      minClipped[i] = probeMin[i];
    }
    else
    {
      minClipped[i] = min[i];
    }

    if (max[i] > probeMax[i])
    {
      maxClipped[i] = probeMax[i];
    }
    else
    {
      maxClipped[i] = max[i];
    }
    const float overlapNorm = (float)(brickTexelOverlap[i]) / (float)texels[i];
    texRange[i] = (1.0f - overlapNorm);
    texMin[i] = (1.0f / (2.0f * (float)(renderer->_renderState._brickTexelOverlap) * (float)texels[i]));
  }

  const vvVector3 (&verts)[8] = vvAABB(minClipped, maxClipped).calcVertices();

  float minDot;
  float maxDot;
  const ushort idx = getFrontIndex(verts, farthest, normal, minDot, maxDot);

  const float deltaInv = 1.0f / delta.length();

  const int startSlices = (int)ceilf(minDot * deltaInv);
  const int endSlices = (int)floorf(maxDot * deltaInv);

  glBindTexture(GL_TEXTURE_3D_EXT, texNames[index]);
  if (renderer->_proxyGeometryOnGpu)
  {
    isectShader->setArrayParameter3f(0, "vertices", 0, verts[0].e[0], verts[0].e[1], verts[0].e[2]);
    if (setupEdges)
    {
      for (int i = 1; i < 8; ++i)
      {
        isectShader->setArrayParameter3f(0, "vertices", i, verts[i].e[0]-verts[0].e[0],
                                                           verts[i].e[1]-verts[0].e[1],
                                                           verts[i].e[2]-verts[0].e[2]);
      }
    }

    // Pass planeStart along with brickMin and spare one setParameter call.
    isectShader->setParameter4f(0, "brickMin", min[0], min[1], min[2], -farthest.length());
    // Pass front index along with brickDimInv and spare one setParameter call.
    isectShader->setParameter4f(0, "brickDimInv", 1.0f/dist[0], 1.0f/dist[1], 1.0f/dist[2], idx);
    // Mind that textures overlap a little bit for correct interpolation at the borders.
    // Thus add that little difference.
    isectShader->setParameter3f(0, "texRange", texRange[0], texRange[1], texRange[2]);
    isectShader->setParameter3f(0, "texMin", texMin[0], texMin[1], texMin[2]);

    const int primCount = (endSlices - startSlices) + 1;

    glVertexPointer(2, GL_INT, 0, &renderer->_vertArray[startSlices*12]);
    glMultiDrawElements(GL_POLYGON, &renderer->_elemCounts[0], GL_UNSIGNED_INT, (const GLvoid**)&renderer->_vertIndices[0], primCount);
  }
  else // render proxy geometry on gpu? else then:
  {
    vvVector3 startPoint = farthest + delta * static_cast<float>(startSlices);

    for (int i = startSlices; i <= endSlices; ++i)
    {
      vvVector3 isect[6];
      const int isectCnt = isect->isectPlaneCuboid(&normal, &startPoint, &minClipped, &maxClipped);
      startPoint.add(&delta);

      if (isectCnt < 3) continue;                 // at least 3 intersections needed for drawing

      // Check volume section mode:
      if (renderer->minSlice != -1 && i < renderer->minSlice) continue;
      if (renderer->maxSlice != -1 && i > renderer->maxSlice) continue;

      // Put the intersecting 3 to 6 vertices in cyclic order to draw adjacent
      // and non-overlapping triangles:
      isect->cyclicSort(isectCnt, &normal);

      // Generate vertices in texture coordinates:
      vvVector3 texcoord[6];
      for (int j = 0; j < isectCnt; ++j)
      {
        for (int k = 0; k < 3; ++k)
        {
          texcoord[j][k] = (isect[j][k] - min.e[k]) / dist[k];
          texcoord[j][k] = texcoord[j][k] * texRange[k] + texMin[k];
        }
      }

      glBegin(GL_TRIANGLE_FAN);
      glColor4f(1.0, 1.0, 1.0, 1.0);
      glNormal3f(normal[0], normal[1], normal[2]);
      for (int j = 0; j < isectCnt; ++j)
      {
        // The following lines are the bottleneck of this method:
        glTexCoord3f(texcoord[j][0], texcoord[j][1], texcoord[j][2]);
        glVertex3f(isect[j][0], isect[j][1], isect[j][2]);
      }
      glEnd();
    }
  }
}

void vvBrick::renderOutlines(const vvVector3& probeMin, const vvVector3& probeMax) const
{
  vvVector3 minClipped;
  vvVector3 maxClipped;
  for (int i = 0; i < 3; i++)
  {
    if (min.e[i] < probeMin.e[i])
    {
      minClipped.e[i] = probeMin.e[i];
    }
    else
    {
      minClipped.e[i] = min.e[i];
    }

    if (max.e[i] > probeMax.e[i])
    {
      maxClipped.e[i] = probeMax.e[i];
    }
    else
    {
      maxClipped.e[i] = max.e[i];
    }
  }
  glBegin(GL_LINES);
    glColor3f(1.0f, 1.0f, 1.0f);
    glVertex3f(minClipped[0], minClipped[1], minClipped[2]);
    glVertex3f(maxClipped[0], minClipped[1], minClipped[2]);

    glVertex3f(minClipped[0], minClipped[1], minClipped[2]);
    glVertex3f(minClipped[0], maxClipped[1], minClipped[2]);

    glVertex3f(minClipped[0], minClipped[1], minClipped[2]);
    glVertex3f(minClipped[0], minClipped[1], maxClipped[2]);

    glVertex3f(maxClipped[0], maxClipped[1], maxClipped[2]);
    glVertex3f(minClipped[0], maxClipped[1], maxClipped[2]);

    glVertex3f(maxClipped[0], maxClipped[1], maxClipped[2]);
    glVertex3f(maxClipped[0], minClipped[1], maxClipped[2]);

    glVertex3f(maxClipped[0], maxClipped[1], maxClipped[2]);
    glVertex3f(maxClipped[0], maxClipped[1], minClipped[2]);

    glVertex3f(maxClipped[0], minClipped[1], minClipped[2]);
    glVertex3f(maxClipped[0], maxClipped[1], minClipped[2]);

    glVertex3f(maxClipped[0], minClipped[1], minClipped[2]);
    glVertex3f(maxClipped[0], minClipped[1], maxClipped[2]);

    glVertex3f(minClipped[0], maxClipped[1], minClipped[2]);
    glVertex3f(maxClipped[0], maxClipped[1], minClipped[2]);

    glVertex3f(minClipped[0], maxClipped[1], minClipped[2]);
    glVertex3f(minClipped[0], maxClipped[1], maxClipped[2]);

    glVertex3f(minClipped[0], minClipped[1], maxClipped[2]);
    glVertex3f(maxClipped[0], minClipped[1], maxClipped[2]);

    glVertex3f(minClipped[0], minClipped[1], maxClipped[2]);
    glVertex3f(minClipped[0], maxClipped[1], maxClipped[2]);
  glEnd();
}

bool vvBrick::upload3DTexture(GLuint& texName, uchar* texData,
                              const GLenum texFormat, const GLint internalTexFormat,
                              const bool interpolation)
{
  glBindTexture(GL_TEXTURE_3D_EXT, texName);

  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_MAG_FILTER, (interpolation) ? GL_LINEAR : GL_NEAREST);
  glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_MIN_FILTER, (interpolation) ? GL_LINEAR : GL_NEAREST);
  glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_R_EXT, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_S, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_T, GL_CLAMP);

  glTexImage3D(GL_PROXY_TEXTURE_3D_EXT, 0, internalTexFormat,
    texels[0], texels[1], texels[2], 0, texFormat, GL_UNSIGNED_BYTE, NULL);

  GLint glWidth;
  glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D_EXT, 0, GL_TEXTURE_WIDTH, &glWidth);
  if (glWidth != 0)
  {
    glTexImage3D(GL_TEXTURE_3D_EXT, 0, internalTexFormat, texels[0], texels[1], texels[2], 0,
      texFormat, GL_UNSIGNED_BYTE, texData);
    return true;
  }
  else
  {
    return false;
  }
}

/** Get front index of the brick based upon the current modelview matrix.
  @param vertices  NOTE THE FOLLOWING: albeit vertices are constituents of
                   bricks, these are passed along with the function call in
                   order not to recalculate them. This is due to the fact that
                   AABBs actually don't store pointers to their eight verts,
                   but only to two corners.
  @param point     The point to calc the distance from. The distance of interest
                   is the one from point to the first and last vertex along
                   normal
  @param normal    The normal to calc the distance along.
  @param minDot    The minimum dot product of vector point-vertex and normal,
                   passed along for later calculations.
  @param maxDot    The maximum dot product of vector point-vertex and normal,
                   passed along for later calculations.
*/
ushort vvBrick::getFrontIndex(const vvVector3* vertices,
                              const vvVector3& point,
                              const vvVector3& normal,
                              float& minDot,
                              float& maxDot) const
{

  // Get vertices with max and min distance to point along normal.
  maxDot = -FLT_MAX;
  minDot = FLT_MAX;
  ushort frontIndex;

  for (int i=0; i<8; i++)
  {
    const vvVector3 v = vertices[i] - point;
    const float dot = v.dot(&normal);
    if (dot > maxDot)
    {
      maxDot = dot;
      frontIndex = i;
    }

    if (dot < minDot)
    {
      minDot = dot;
    }
  }
  return frontIndex;
}

void vvBrick::sortByCenter(vvBrick** bricks, const int numBricks, const vvVector3& axis)
{
  const vvVector3 axisGetter(0, 1, 2);
  const int a = static_cast<const int>(axis.dot(&axisGetter));

  // Selection sort.
  for (int i = 0; i < numBricks; ++i)
  {
    for (int j = i; j < numBricks; ++j)
    {
      vvBrick* tmp = bricks[j];
      for (int k = i + 1; k < numBricks; ++k)
      {
        vvBrick* tmp2 = bricks[k];
        if (tmp->getAABB().calcCenter().e[a] > tmp2->getAABB().calcCenter().e[a])
        {
          vvBrick* tmp3 = bricks[j];
          bricks[j] = bricks[k];
          bricks[k] = tmp3;
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
//
//             ------------------------------------------------
//             Toroid Miniapp:  Generate simple toroidal meshes
//             ------------------------------------------------
//
// This miniapp generates two types of Toroidal meshes; one with triangular
// cross sections and one with square cross sections.  It works by defining a
// stack of individual elements and bending them so that the bottom and top of
// the stack can be joined to form a torus.  The stack can also be twisted so
// that the vertices of the bottom and top can be joined with any integer
// offset.
//
// Compile with: make toroid
//
// Sample runs:  toroid
//               toroid -nphi 6
//               toroid -ns 1
//               toroid -ns 0 -t0 -30
//               toroid -R 2 -r 1 -ns 3
//               toroid -R 2 -r 1 -ns -3
//               toroid -R 2 -r 1 -ns 3 -e 1
//               toroid -R 2 -r 1 -ns 3 -e 1 -rs 1
//               toroid -nphi 2 -ns 10 -e 1 -o 4

#include "mfem.hpp"
#include <fstream>
#include <iostream>

using namespace std;
using namespace mfem;

static Element::Type el_type_ = Element::WEDGE;
static int    order_  = 3;
static int    nphi_   = 8;
static int    ns_     = 0;
static double R_      = 1.0;
static double r_      = 0.2;
static double theta0_ = 0.0;

void pts(int iphi, int t, double x[]);
void trans(const Vector &x, Vector &p);

int main(int argc, char *argv[])
{
   int ser_ref_levels = 0;
   int el_type = 0;
   bool dg_mesh = false;
   bool visualization = true;

   OptionsParser args(argc, argv);
   args.AddOption(&nphi_, "-nphi", "--num-elements-phi",
                  "Number of elements in phi-direction.");
   args.AddOption(&ns_, "-ns", "--num-shifts",
                  "Number of shifts.");
   args.AddOption(&order_, "-o", "--mesh-order",
                  "Order (polynomial degree) of the mesh elements.");
   args.AddOption(&ser_ref_levels, "-rs", "--refine-serial",
                  "Number of times to refine the mesh uniformly in serial.");
   args.AddOption(&R_, "-R", "--major-radius",
                  "Major radius of the torus.");
   args.AddOption(&r_, "-r", "--minor-radius",
                  "Minor radius of the torus.");
   args.AddOption(&theta0_, "-t0", "--initial-angle",
                  "Starting angle of the cross section (in degrees).");
   args.AddOption(&el_type, "-e", "--element-type",
                  "Element type: 0 - Wedge, 1 - Hexahedron.");
   args.AddOption(&dg_mesh, "-dm", "--discont-mesh", "-cm", "--cont-mesh",
                  "Use discontinuous or continuous space for the mesh nodes.");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");
   args.Parse();
   if (!args.Good())
   {
      args.PrintUsage(cout);
      return 1;
   }
   args.PrintOptions(cout);

   // The output mesh could be hexahedra or prisms
   el_type_ = (el_type == 0) ? Element::WEDGE : Element::HEXAHEDRON;
   if (el_type_ != Element::WEDGE && el_type_ != Element::HEXAHEDRON)
   {
      cout << "Unsupported element type" << endl;
      exit(1);
   }

   // Determine the number of nodes in the cross section
   int nnode = (el_type_ == Element::WEDGE)? 3:4;
   int nshift = (ns_ >= 0) ? 0 : (nnode * (1 - ns_ / nnode));

   // Convert initial angle from degrees to radians
   theta0_ *= M_PI / 180.0;

   // Define an empty mesh
   Mesh *mesh;
   mesh = new Mesh(3, nnode * (nphi_+1), nphi_);

   // Add vertices for a stack of elements
   double c[3];
   for (int i=0; i<=nphi_; i++)
   {
      c[0] = 0.0; c[1] = 0.0; c[2] = i;
      mesh->AddVertex(c);

      c[0] = 1.0;
      mesh->AddVertex(c);

      if (el_type_ == Element::HEXAHEDRON)
      {
         c[0] = 1.0; c[1] = 1.0;
         mesh->AddVertex(c);
      }

      c[0] = 0.0; c[1] = 1.0;
      mesh->AddVertex(c);
   }

   // Add Elements of the desired type
   int v[8];
   for (int i=0; i < nphi_; i++)
   {
      if (el_type_ == Element::WEDGE)
      {
         for (int j = 0; j < 6; j++) { v[j] = 3*i+j; }
         mesh->AddPri(v);
      }
      else
      {
         for (int j = 0; j < 8; j++) { v[j] = 4*i+j; }
         mesh->AddHex(v);
      }
   }
   mesh->FinalizeTopology();

   // Promote to high order mesh and transform into a torus shape
   if (order_ > 1)
   {
      mesh->SetCurvature(order_, true, 3, Ordering::byVDIM);
      mesh->Transform(trans);
   }

   // Stitch the ends of the stack together
   {
      Array<int> v2v(mesh->GetNV());
      for (int i = 0; i < v2v.Size() - nnode; i++)
      {
         v2v[i] = i;
      }
      // identify vertices at the extremes of the stack of prisms
      for (int i=0; i<nnode; i++)
      {
         v2v[v2v.Size() - nnode + i] = (nshift + ns_ + i) % nnode;
      }
      // renumber elements
      for (int i = 0; i < mesh->GetNE(); i++)
      {
         Element *el = mesh->GetElement(i);
         int *v = el->GetVertices();
         int nv = el->GetNVertices();
         for (int j = 0; j < nv; j++)
         {
            v[j] = v2v[v[j]];
         }
      }
      // renumber boundary elements
      for (int i = 0; i < mesh->GetNBE(); i++)
      {
         Element *el = mesh->GetBdrElement(i);
         int *v = el->GetVertices();
         int nv = el->GetNVertices();
         for (int j = 0; j < nv; j++)
         {
            v[j] = v2v[v[j]];
         }
      }
      mesh->RemoveUnusedVertices();
      mesh->RemoveInternalBoundaries();
   }
   if (order_ > 1)
   {
      mesh->SetCurvature(order_, dg_mesh, 3, Ordering::byVDIM);
   }

   // Refine the mesh if desired
   for (int lev = 0; lev < ser_ref_levels; lev++)
   {
      mesh->UniformRefinement();
   }

   // Output the resulting mesh to a file
   {
      ostringstream oss;
      if (el_type_ == Element::WEDGE)
      {
         oss << "toroid-wedge";
      }
      else
      {
         oss << "toroid-hex";
      }
      oss << "-o" << order_ << "-s" << ns_;
      if (ser_ref_levels > 0)
      {
         oss << "-r" << ser_ref_levels;
      }
      oss << ".mesh";
      ofstream ofs(oss.str().c_str());
      ofs.precision(8);
      mesh->Print(ofs);
      ofs.close();
   }

   // Output the resulting mesh to GLVis
   if (visualization)
   {
      char vishost[] = "localhost";
      int  visport   = 19916;
      socketstream sol_sock(vishost, visport);
      sol_sock.precision(8);
      sol_sock << "mesh\n" << *mesh << flush;
   }

   // Clean up and exit
   delete mesh;
   return 0;
}

void trans(const Vector &x, Vector &p)
{
   int nnode = (el_type_ == Element::WEDGE)? 3:4;

   double phi = 2.0 * M_PI * x[2] / nphi_;
   double theta = theta0_ + phi * ns_ / nnode;

   double u = (1.5 * (x[0] + x[1]) - 1.0) * r_;
   double v = sqrt(0.75) * (x[0] - x[1]) * r_;

   if (el_type_ == Element::WEDGE)
   {
      u = (1.5 * (x[0] + x[1]) - 1.0) * r_;
      v = sqrt(0.75) * (x[0] - x[1]) * r_;
   }
   else
   {
      u = M_SQRT2 * (x[1] - 0.5) * r_;
      v = M_SQRT2 * (x[0] - 0.5) * r_;
   }

   p[0] = ( R_ + u * cos(theta) + v * sin(theta)) * cos(phi);
   p[1] = ( R_ + u * cos(theta) + v * sin(theta)) * sin(phi);
   p[2] = v * cos(theta) - u * sin(theta);
}
<commit_msg>Changing one last occurrence of AddPri to AddWedge<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
//
//             ------------------------------------------------
//             Toroid Miniapp:  Generate simple toroidal meshes
//             ------------------------------------------------
//
// This miniapp generates two types of Toroidal meshes; one with triangular
// cross sections and one with square cross sections.  It works by defining a
// stack of individual elements and bending them so that the bottom and top of
// the stack can be joined to form a torus.  The stack can also be twisted so
// that the vertices of the bottom and top can be joined with any integer
// offset.
//
// Compile with: make toroid
//
// Sample runs:  toroid
//               toroid -nphi 6
//               toroid -ns 1
//               toroid -ns 0 -t0 -30
//               toroid -R 2 -r 1 -ns 3
//               toroid -R 2 -r 1 -ns -3
//               toroid -R 2 -r 1 -ns 3 -e 1
//               toroid -R 2 -r 1 -ns 3 -e 1 -rs 1
//               toroid -nphi 2 -ns 10 -e 1 -o 4

#include "mfem.hpp"
#include <fstream>
#include <iostream>

using namespace std;
using namespace mfem;

static Element::Type el_type_ = Element::WEDGE;
static int    order_  = 3;
static int    nphi_   = 8;
static int    ns_     = 0;
static double R_      = 1.0;
static double r_      = 0.2;
static double theta0_ = 0.0;

void pts(int iphi, int t, double x[]);
void trans(const Vector &x, Vector &p);

int main(int argc, char *argv[])
{
   int ser_ref_levels = 0;
   int el_type = 0;
   bool dg_mesh = false;
   bool visualization = true;

   OptionsParser args(argc, argv);
   args.AddOption(&nphi_, "-nphi", "--num-elements-phi",
                  "Number of elements in phi-direction.");
   args.AddOption(&ns_, "-ns", "--num-shifts",
                  "Number of shifts.");
   args.AddOption(&order_, "-o", "--mesh-order",
                  "Order (polynomial degree) of the mesh elements.");
   args.AddOption(&ser_ref_levels, "-rs", "--refine-serial",
                  "Number of times to refine the mesh uniformly in serial.");
   args.AddOption(&R_, "-R", "--major-radius",
                  "Major radius of the torus.");
   args.AddOption(&r_, "-r", "--minor-radius",
                  "Minor radius of the torus.");
   args.AddOption(&theta0_, "-t0", "--initial-angle",
                  "Starting angle of the cross section (in degrees).");
   args.AddOption(&el_type, "-e", "--element-type",
                  "Element type: 0 - Wedge, 1 - Hexahedron.");
   args.AddOption(&dg_mesh, "-dm", "--discont-mesh", "-cm", "--cont-mesh",
                  "Use discontinuous or continuous space for the mesh nodes.");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");
   args.Parse();
   if (!args.Good())
   {
      args.PrintUsage(cout);
      return 1;
   }
   args.PrintOptions(cout);

   // The output mesh could be hexahedra or prisms
   el_type_ = (el_type == 0) ? Element::WEDGE : Element::HEXAHEDRON;
   if (el_type_ != Element::WEDGE && el_type_ != Element::HEXAHEDRON)
   {
      cout << "Unsupported element type" << endl;
      exit(1);
   }

   // Determine the number of nodes in the cross section
   int nnode = (el_type_ == Element::WEDGE)? 3:4;
   int nshift = (ns_ >= 0) ? 0 : (nnode * (1 - ns_ / nnode));

   // Convert initial angle from degrees to radians
   theta0_ *= M_PI / 180.0;

   // Define an empty mesh
   Mesh *mesh;
   mesh = new Mesh(3, nnode * (nphi_+1), nphi_);

   // Add vertices for a stack of elements
   double c[3];
   for (int i=0; i<=nphi_; i++)
   {
      c[0] = 0.0; c[1] = 0.0; c[2] = i;
      mesh->AddVertex(c);

      c[0] = 1.0;
      mesh->AddVertex(c);

      if (el_type_ == Element::HEXAHEDRON)
      {
         c[0] = 1.0; c[1] = 1.0;
         mesh->AddVertex(c);
      }

      c[0] = 0.0; c[1] = 1.0;
      mesh->AddVertex(c);
   }

   // Add Elements of the desired type
   int v[8];
   for (int i=0; i < nphi_; i++)
   {
      if (el_type_ == Element::WEDGE)
      {
         for (int j = 0; j < 6; j++) { v[j] = 3*i+j; }
         mesh->AddWedge(v);
      }
      else
      {
         for (int j = 0; j < 8; j++) { v[j] = 4*i+j; }
         mesh->AddHex(v);
      }
   }
   mesh->FinalizeTopology();

   // Promote to high order mesh and transform into a torus shape
   if (order_ > 1)
   {
      mesh->SetCurvature(order_, true, 3, Ordering::byVDIM);
      mesh->Transform(trans);
   }

   // Stitch the ends of the stack together
   {
      Array<int> v2v(mesh->GetNV());
      for (int i = 0; i < v2v.Size() - nnode; i++)
      {
         v2v[i] = i;
      }
      // identify vertices at the extremes of the stack of prisms
      for (int i=0; i<nnode; i++)
      {
         v2v[v2v.Size() - nnode + i] = (nshift + ns_ + i) % nnode;
      }
      // renumber elements
      for (int i = 0; i < mesh->GetNE(); i++)
      {
         Element *el = mesh->GetElement(i);
         int *v = el->GetVertices();
         int nv = el->GetNVertices();
         for (int j = 0; j < nv; j++)
         {
            v[j] = v2v[v[j]];
         }
      }
      // renumber boundary elements
      for (int i = 0; i < mesh->GetNBE(); i++)
      {
         Element *el = mesh->GetBdrElement(i);
         int *v = el->GetVertices();
         int nv = el->GetNVertices();
         for (int j = 0; j < nv; j++)
         {
            v[j] = v2v[v[j]];
         }
      }
      mesh->RemoveUnusedVertices();
      mesh->RemoveInternalBoundaries();
   }
   if (order_ > 1)
   {
      mesh->SetCurvature(order_, dg_mesh, 3, Ordering::byVDIM);
   }

   // Refine the mesh if desired
   for (int lev = 0; lev < ser_ref_levels; lev++)
   {
      mesh->UniformRefinement();
   }

   // Output the resulting mesh to a file
   {
      ostringstream oss;
      if (el_type_ == Element::WEDGE)
      {
         oss << "toroid-wedge";
      }
      else
      {
         oss << "toroid-hex";
      }
      oss << "-o" << order_ << "-s" << ns_;
      if (ser_ref_levels > 0)
      {
         oss << "-r" << ser_ref_levels;
      }
      oss << ".mesh";
      ofstream ofs(oss.str().c_str());
      ofs.precision(8);
      mesh->Print(ofs);
      ofs.close();
   }

   // Output the resulting mesh to GLVis
   if (visualization)
   {
      char vishost[] = "localhost";
      int  visport   = 19916;
      socketstream sol_sock(vishost, visport);
      sol_sock.precision(8);
      sol_sock << "mesh\n" << *mesh << flush;
   }

   // Clean up and exit
   delete mesh;
   return 0;
}

void trans(const Vector &x, Vector &p)
{
   int nnode = (el_type_ == Element::WEDGE)? 3:4;

   double phi = 2.0 * M_PI * x[2] / nphi_;
   double theta = theta0_ + phi * ns_ / nnode;

   double u = (1.5 * (x[0] + x[1]) - 1.0) * r_;
   double v = sqrt(0.75) * (x[0] - x[1]) * r_;

   if (el_type_ == Element::WEDGE)
   {
      u = (1.5 * (x[0] + x[1]) - 1.0) * r_;
      v = sqrt(0.75) * (x[0] - x[1]) * r_;
   }
   else
   {
      u = M_SQRT2 * (x[1] - 0.5) * r_;
      v = M_SQRT2 * (x[0] - 0.5) * r_;
   }

   p[0] = ( R_ + u * cos(theta) + v * sin(theta)) * cos(phi);
   p[1] = ( R_ + u * cos(theta) + v * sin(theta)) * sin(phi);
   p[2] = v * cos(theta) - u * sin(theta);
}
<|endoftext|>


<commit_before>/*  -*- mode: C++; c-file-style: "gnu" -*-
    cryptplugfactory.cpp

    This file is part of libkleopatra, the KDE key management library
    Copyright (c) 2001,2004 Klarlvdalens Datakonsult AB

    Libkleopatra is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2, as published by the Free Software Foundation.

    Libkleopatra 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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.
*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "cryptplugfactory.h"
#include "cryptplugwrapperlist.h"

#include <kconfig.h>
#include <klocale.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kapplication.h>

Kleo::CryptPlugFactory * Kleo::CryptPlugFactory::mSelf = 0;

Kleo::CryptPlugFactory::CryptPlugFactory()
  : QObject( qApp, "CryptPlugFactory::instance()" ),
    mCryptPlugWrapperList( 0 )
{
  mSelf = this;
  mCryptPlugWrapperList = new CryptPlugWrapperList();
  loadFromConfig( kapp->config() );
  mCryptPlugWrapperList->setAutoDelete( true );
}

Kleo::CryptPlugFactory::~CryptPlugFactory() {
  mSelf = 0;

  delete mCryptPlugWrapperList;
  mCryptPlugWrapperList = 0;
}

Kleo::CryptPlugFactory * Kleo::CryptPlugFactory::instance() {
  if ( !mSelf )
    mSelf = new CryptPlugFactory();
  return mSelf;
}

CryptPlugWrapper * Kleo::CryptPlugFactory::active() const {
  if ( smime() && smime()->active() )
    return smime();
  if ( openpgp() && openpgp()->active() )
    return openpgp();
  return 0;
}

CryptPlugWrapper * Kleo::CryptPlugFactory::createForProtocol( const QString & proto ) const {
  QString p = proto.lower();
  if ( p == "application/pkcs7-signature" )
    return smime();
  if ( p == "application/pgp-signature" )
    return openpgp();
  return 0;
}

CryptPlugWrapper * Kleo::CryptPlugFactory::smime() const {
  return mCryptPlugWrapperList->findForLibName( "smime" );
}

CryptPlugWrapper * Kleo::CryptPlugFactory::openpgp() const {
  return mCryptPlugWrapperList->findForLibName( "openpgp" );
}

bool Kleo::CryptPlugFactory::hasBackends() const {
  return mCryptPlugWrapperList && !mCryptPlugWrapperList->isEmpty();
}

void Kleo::CryptPlugFactory::scanForBackends() {
  mCryptPlugWrapperList->clear();

  static const struct {
    const char * displayName;
    const char * libName;
    const char * errorMsg;
    bool active;
  } cryptPlugs[] = {
    { "S/MIME", "smime",
      I18N_NOOP("GpgSM not found. "
		"S/MIME cryptographic backend has beed disabled."),
      true
    },
    { "OpenPGP", "openpgp",
      I18N_NOOP("GnuPG not found. "
		"OpenPGP/MIME cryptographic backend has beed disabled."),
      false
    }
  };
  static const int numCryptPlugs = sizeof cryptPlugs / sizeof *cryptPlugs ;

  for ( int i = 0 ; i < numCryptPlugs ; ++i ) {
    CryptPlugWrapper * w =
      new CryptPlugWrapper( cryptPlugs[i].displayName, cryptPlugs[i].libName,
			    QString::null, cryptPlugs[i].active );

    CryptPlugWrapper::InitStatus initStatus;
    QString errorMsg;
    if ( !w->initialize( &initStatus, &errorMsg ) ) {
      KMessageBox::queuedMessageBox( 0, KMessageBox::Error, i18n( cryptPlugs[i].errorMsg ) );
      delete w; w = 0;
    } else
      mCryptPlugWrapperList->append( w );
  }
}

static void showPluginInitError( const CryptPlugWrapper* wrapper,
				 CryptPlugWrapper::InitStatus initStatus,
				 const QString & errorMsg )
{
    QString msg;
    switch ( initStatus ) {
    case CryptPlugWrapper::InitStatus_undef:
        msg = i18n( "Error loading plug-in \"%1\"!\n(code: InitStatus_undef)")
            .arg( wrapper->displayName() );
        break;
    case CryptPlugWrapper::InitStatus_NoLibName:
        msg = i18n("Please specify the LOCATION of plug-in \"%1\"!\n"
                "(complete path/filename of the respective library file)")
            .arg( wrapper->displayName() );
        break;
    case CryptPlugWrapper::InitStatus_LoadError:
        msg = i18n( "Error loading plug-in library file \"%1\"!\n"
                    "(code: \"%2\")").arg( wrapper->libName() )
            .arg( errorMsg );
        break;
    case CryptPlugWrapper::InitStatus_InitError: {
            msg = i18n( "Error: Plug-in \"%1\" initialization unsuccessful.\n"
                        "library: %2\n"
                        "version: %3\n"
                        "Plug-in is out-dated or not installed properly.\n" )
                .arg( wrapper->displayName() )
                .arg( wrapper->libName() )
                .arg( wrapper->libVersion() );
        }
        break;
    default:
        msg = i18n( "Cannot load/initialize plug-in library \"%1\"!\n"
                    "(unknown error)").arg( wrapper->libName() );
    }
    // Use a queued message box because a normal message box would block
    // this initialization "thread" and this would lead to a crash in
    // code called by the event loop due to incomplete initialization.
    KMessageBox::queuedMessageBox( 0, KMessageBox::Error, msg );
}

void Kleo::CryptPlugFactory::loadFromConfig( KConfig * config ) {
  mCryptPlugWrapperList->clear();

  KConfigGroupSaver saver( config, "General" );

  if ( !config->hasKey( "crypt-plug-count" ) ) {
    scanForBackends();
    return;
  }

  const int numPlugins = config->readNumEntry( "crypt-plug-count", 0 );

  for( int i = 0; i < numPlugins; ++i ) {
    // load the initial config data for one plugin
    config->setGroup( QString( "CryptPlug #%1" ).arg( i ) );

    const QString name = config->readEntry( "name" );
    const QString location = config->readPathEntry( "location" );
    const QString updateURL = config->readPathEntry( "updates" );
    const bool active = config->readBoolEntry( "active", false );

    // Try to initialize that plugin
    CryptPlugWrapper::InitStatus initStatus;
    QString errorMsg;
    CryptPlugWrapper* newWrapper =
      new CryptPlugWrapper( name, location, updateURL, active );
    if( !newWrapper->initialize( &initStatus, &errorMsg ) ) {
      showPluginInitError( newWrapper, initStatus, errorMsg );
      continue;
    }

    kdDebug( 5150 ) << "Loaded crypto plugin " << name
		    << " at location " << location << endl;
    mCryptPlugWrapperList->append( newWrapper );

    // Configure the current plugin by means of the wrapper. If
    // the plugin was not initialized successfully, these calls
    // will end in Nirvana.

    // Signature configuration
    const int sigAlgo = config->readNumEntry( "SigAlgo", SignAlg_SHA1 );
    newWrapper->setSignatureAlgorithm( static_cast<SignatureAlgorithm>( sigAlgo ) );

    const int compoundMode = config->readNumEntry( "SignatureCompoundMode",
						   SignatureCompoundMode_Detached );
    newWrapper->setSignatureCompoundMode( static_cast<SignatureCompoundMode>( compoundMode ) );

    const int sendCerts = config->readNumEntry( "SendCerts",
						SendCert_SendOwn );
    newWrapper->setSendCertificates( static_cast<SendCertificates>( sendCerts ) );

    const int signEmail = config->readNumEntry( "SignEmail",
					  SignEmail_SignAll );
    newWrapper->setSignEmail( static_cast<SignEmail>( signEmail ) );

    const bool warnSendUnsigned = config->readBoolEntry( "WarnSendUnsigned",
							 true );
    newWrapper->setWarnSendUnsigned( warnSendUnsigned );

    const bool saveSentSigs = config->readBoolEntry( "SaveSentSigs", true );
    newWrapper->setSaveSentSignatures( saveSentSigs );

    const bool warnNoCert = config->readBoolEntry( "WarnNoCert", true );
    newWrapper->setWarnNoCertificate( warnNoCert );

    const int pinRequests = config->readNumEntry( "NumPINRequests",
						  PinRequest_Always );
    newWrapper->setNumPINRequests( static_cast<PinRequests>( pinRequests ) );

    const int pinRequestsInt = config->readNumEntry( "NumPINRequestsInt",
							   10 );
    newWrapper->setNumPINRequestsInterval( pinRequestsInt );

    const bool checkSigToRoot = config->readNumEntry( "CheckSigCertToRoot",
						      true );
    newWrapper->setCheckSignatureCertificatePathToRoot( checkSigToRoot );

    const bool sigUseCRLs = config->readBoolEntry( "SigUseCRLs", true );
    newWrapper->setSignatureUseCRLs( sigUseCRLs );

    const bool sigCertWarnNearExpire = config->readBoolEntry( "SigCertWarnNearExpire", true );
    newWrapper->setSignatureCertificateExpiryNearWarning( sigCertWarnNearExpire );

    const int sigCertWarnNearExpireInt = config->readNumEntry( "SigCertWarnNearExpireInt", 14 );
    newWrapper->setSignatureCertificateExpiryNearInterval( sigCertWarnNearExpireInt );

    const bool caCertWarnNearExpire = config->readBoolEntry( "CACertWarnNearExpire", true );
    newWrapper->setCACertificateExpiryNearWarning( caCertWarnNearExpire );

    const int caCertWarnNearExpireInt = config->readNumEntry( "CACertWarnNearExpireInt", 14 );
    newWrapper->setCACertificateExpiryNearInterval( caCertWarnNearExpireInt );

    const bool rootCertWarnNearExpire = config->readBoolEntry( "RootCertWarnNearExpire", true );
    newWrapper->setRootCertificateExpiryNearWarning( rootCertWarnNearExpire );

    const int rootCertWarnNearExpireInt = config->readNumEntry( "RootCertWarnNearExpireInt", 14 );
    newWrapper->setRootCertificateExpiryNearInterval( rootCertWarnNearExpireInt );

    const bool warnEmailNotInCert = config->readBoolEntry( "WarnEmailNotInCert", true );
    newWrapper->setWarnNoCertificate( warnEmailNotInCert );

    // Encryption configuration
    const int encryptAlgo = config->readNumEntry( "EncryptAlgo", EncryptAlg_RSA );
    newWrapper->setEncryptionAlgorithm( static_cast<EncryptionAlgorithm>( encryptAlgo ) );

    const int encryptEmail = config->readNumEntry( "EncryptEmail",
						   EncryptEmail_EncryptAll );
    newWrapper->setEncryptEmail( static_cast<EncryptEmail>( encryptEmail ) );

    const bool warnSendUnencrypted = config->readBoolEntry( "WarnSendUnencrypted",
							    true );
    newWrapper->setWarnSendUnencrypted( warnSendUnencrypted );

    const bool alwaysEncryptToSelf = config->readBoolEntry( "AlwaysEncryptToSelf",
							    true );
    newWrapper->setAlwaysEncryptToSelf( alwaysEncryptToSelf );

    const bool warnRecvCertNearExpire = config->readBoolEntry( "WarnRecvCertNearExpire",
							       true );
    newWrapper->setReceiverCertificateExpiryNearWarning( warnRecvCertNearExpire );

    const int warnRecvCertNearExpireInt = config->readNumEntry( "WarnRecvCertNearExpireInt",
								14 );
    newWrapper->setReceiverCertificateExpiryNearWarningInterval( warnRecvCertNearExpireInt );

    const bool warnCertInChainNearExpire = config->readBoolEntry( "WarnCertInChainNearExpire",
								  true );
    newWrapper->setCertificateInChainExpiryNearWarning( warnCertInChainNearExpire );

    const int warnCertInChainNearExpireInt = config->readNumEntry( "WarnCertInChainNearExpireInt",
								   14 );
    newWrapper->setCertificateInChainExpiryNearWarningInterval( warnCertInChainNearExpireInt );

    const bool warnRecvAddrNotInCert = config->readBoolEntry( "WarnRecvAddrNotInCert" );
    newWrapper->setReceiverEmailAddressNotInCertificateWarning( warnRecvAddrNotInCert );

    const bool saveMsgEncrypted = config->readBoolEntry( "SaveMsgsEncrypted", false );
    newWrapper->setSaveMessagesEncrypted( saveMsgEncrypted );

    const bool checkCertPath = config->readBoolEntry( "CheckCertPath", true );
    newWrapper->setCheckCertificatePath( checkCertPath );

    const bool checkEncryptToRoot = config->readBoolEntry( "CheckEncryptCertToRoot",
							   true );
    newWrapper->setCheckEncryptionCertificatePathToRoot( checkEncryptToRoot );

    const bool encryptUseCRLs = config->readBoolEntry( "EncryptUseCRLs", true );
    newWrapper->setEncryptionUseCRLs( encryptUseCRLs );

    const bool encryptCRLWarnNearExpire = config->readBoolEntry( "EncryptCRLWarnNearExpire", true );
    newWrapper->setEncryptionCRLExpiryNearWarning( encryptCRLWarnNearExpire );

    const int encryptCRLWarnNearExpireInt = config->readNumEntry( "EncryptCRLWarnNearExpireInt", 14 );
    newWrapper->setEncryptionCRLNearExpiryInterval( encryptCRLWarnNearExpireInt );

    const int certSource = config->readNumEntry( "CertSource", CertSrc_ServerLocal );
    newWrapper->setCertificateSource( static_cast<CertificateSource>( certSource ) );

    const int crlSource = config->readNumEntry( "CRLSource", CertSrc_ServerLocal );
    newWrapper->setCRLSource( static_cast<CertificateSource>( crlSource ) );
  }
}

#include "cryptplugfactory.moc"
<commit_msg>Fix typos. Pity it can't find my GnuPG.<commit_after>/*  -*- mode: C++; c-file-style: "gnu" -*-
    cryptplugfactory.cpp

    This file is part of libkleopatra, the KDE key management library
    Copyright (c) 2001,2004 Klarlvdalens Datakonsult AB

    Libkleopatra is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2, as published by the Free Software Foundation.

    Libkleopatra 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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.
*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "cryptplugfactory.h"
#include "cryptplugwrapperlist.h"

#include <kconfig.h>
#include <klocale.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kapplication.h>

Kleo::CryptPlugFactory * Kleo::CryptPlugFactory::mSelf = 0;

Kleo::CryptPlugFactory::CryptPlugFactory()
  : QObject( qApp, "CryptPlugFactory::instance()" ),
    mCryptPlugWrapperList( 0 )
{
  mSelf = this;
  mCryptPlugWrapperList = new CryptPlugWrapperList();
  loadFromConfig( kapp->config() );
  mCryptPlugWrapperList->setAutoDelete( true );
}

Kleo::CryptPlugFactory::~CryptPlugFactory() {
  mSelf = 0;

  delete mCryptPlugWrapperList;
  mCryptPlugWrapperList = 0;
}

Kleo::CryptPlugFactory * Kleo::CryptPlugFactory::instance() {
  if ( !mSelf )
    mSelf = new CryptPlugFactory();
  return mSelf;
}

CryptPlugWrapper * Kleo::CryptPlugFactory::active() const {
  if ( smime() && smime()->active() )
    return smime();
  if ( openpgp() && openpgp()->active() )
    return openpgp();
  return 0;
}

CryptPlugWrapper * Kleo::CryptPlugFactory::createForProtocol( const QString & proto ) const {
  QString p = proto.lower();
  if ( p == "application/pkcs7-signature" )
    return smime();
  if ( p == "application/pgp-signature" )
    return openpgp();
  return 0;
}

CryptPlugWrapper * Kleo::CryptPlugFactory::smime() const {
  return mCryptPlugWrapperList->findForLibName( "smime" );
}

CryptPlugWrapper * Kleo::CryptPlugFactory::openpgp() const {
  return mCryptPlugWrapperList->findForLibName( "openpgp" );
}

bool Kleo::CryptPlugFactory::hasBackends() const {
  return mCryptPlugWrapperList && !mCryptPlugWrapperList->isEmpty();
}

void Kleo::CryptPlugFactory::scanForBackends() {
  mCryptPlugWrapperList->clear();

  static const struct {
    const char * displayName;
    const char * libName;
    const char * errorMsg;
    bool active;
  } cryptPlugs[] = {
    { "S/MIME", "smime",
      I18N_NOOP("GpgSM not found. "
		"S/MIME cryptographic backend has been disabled."),
      true
    },
    { "OpenPGP", "openpgp",
      I18N_NOOP("GnuPG not found. "
		"OpenPGP/MIME cryptographic backend has been disabled."),
      false
    }
  };
  static const int numCryptPlugs = sizeof cryptPlugs / sizeof *cryptPlugs ;

  for ( int i = 0 ; i < numCryptPlugs ; ++i ) {
    CryptPlugWrapper * w =
      new CryptPlugWrapper( cryptPlugs[i].displayName, cryptPlugs[i].libName,
			    QString::null, cryptPlugs[i].active );

    CryptPlugWrapper::InitStatus initStatus;
    QString errorMsg;
    if ( !w->initialize( &initStatus, &errorMsg ) ) {
      KMessageBox::queuedMessageBox( 0, KMessageBox::Error, i18n( cryptPlugs[i].errorMsg ) );
      delete w; w = 0;
    } else
      mCryptPlugWrapperList->append( w );
  }
}

static void showPluginInitError( const CryptPlugWrapper* wrapper,
				 CryptPlugWrapper::InitStatus initStatus,
				 const QString & errorMsg )
{
    QString msg;
    switch ( initStatus ) {
    case CryptPlugWrapper::InitStatus_undef:
        msg = i18n( "Error loading plug-in \"%1\"!\n(code: InitStatus_undef)")
            .arg( wrapper->displayName() );
        break;
    case CryptPlugWrapper::InitStatus_NoLibName:
        msg = i18n("Please specify the LOCATION of plug-in \"%1\"!\n"
                "(complete path/filename of the respective library file)")
            .arg( wrapper->displayName() );
        break;
    case CryptPlugWrapper::InitStatus_LoadError:
        msg = i18n( "Error loading plug-in library file \"%1\"!\n"
                    "(code: \"%2\")").arg( wrapper->libName() )
            .arg( errorMsg );
        break;
    case CryptPlugWrapper::InitStatus_InitError: {
            msg = i18n( "Error: Plug-in \"%1\" initialization unsuccessful.\n"
                        "library: %2\n"
                        "version: %3\n"
                        "Plug-in is out-dated or not installed properly.\n" )
                .arg( wrapper->displayName() )
                .arg( wrapper->libName() )
                .arg( wrapper->libVersion() );
        }
        break;
    default:
        msg = i18n( "Cannot load/initialize plug-in library \"%1\"!\n"
                    "(unknown error)").arg( wrapper->libName() );
    }
    // Use a queued message box because a normal message box would block
    // this initialization "thread" and this would lead to a crash in
    // code called by the event loop due to incomplete initialization.
    KMessageBox::queuedMessageBox( 0, KMessageBox::Error, msg );
}

void Kleo::CryptPlugFactory::loadFromConfig( KConfig * config ) {
  mCryptPlugWrapperList->clear();

  KConfigGroupSaver saver( config, "General" );

  if ( !config->hasKey( "crypt-plug-count" ) ) {
    scanForBackends();
    return;
  }

  const int numPlugins = config->readNumEntry( "crypt-plug-count", 0 );

  for( int i = 0; i < numPlugins; ++i ) {
    // load the initial config data for one plugin
    config->setGroup( QString( "CryptPlug #%1" ).arg( i ) );

    const QString name = config->readEntry( "name" );
    const QString location = config->readPathEntry( "location" );
    const QString updateURL = config->readPathEntry( "updates" );
    const bool active = config->readBoolEntry( "active", false );

    // Try to initialize that plugin
    CryptPlugWrapper::InitStatus initStatus;
    QString errorMsg;
    CryptPlugWrapper* newWrapper =
      new CryptPlugWrapper( name, location, updateURL, active );
    if( !newWrapper->initialize( &initStatus, &errorMsg ) ) {
      showPluginInitError( newWrapper, initStatus, errorMsg );
      continue;
    }

    kdDebug( 5150 ) << "Loaded crypto plugin " << name
		    << " at location " << location << endl;
    mCryptPlugWrapperList->append( newWrapper );

    // Configure the current plugin by means of the wrapper. If
    // the plugin was not initialized successfully, these calls
    // will end in Nirvana.

    // Signature configuration
    const int sigAlgo = config->readNumEntry( "SigAlgo", SignAlg_SHA1 );
    newWrapper->setSignatureAlgorithm( static_cast<SignatureAlgorithm>( sigAlgo ) );

    const int compoundMode = config->readNumEntry( "SignatureCompoundMode",
						   SignatureCompoundMode_Detached );
    newWrapper->setSignatureCompoundMode( static_cast<SignatureCompoundMode>( compoundMode ) );

    const int sendCerts = config->readNumEntry( "SendCerts",
						SendCert_SendOwn );
    newWrapper->setSendCertificates( static_cast<SendCertificates>( sendCerts ) );

    const int signEmail = config->readNumEntry( "SignEmail",
					  SignEmail_SignAll );
    newWrapper->setSignEmail( static_cast<SignEmail>( signEmail ) );

    const bool warnSendUnsigned = config->readBoolEntry( "WarnSendUnsigned",
							 true );
    newWrapper->setWarnSendUnsigned( warnSendUnsigned );

    const bool saveSentSigs = config->readBoolEntry( "SaveSentSigs", true );
    newWrapper->setSaveSentSignatures( saveSentSigs );

    const bool warnNoCert = config->readBoolEntry( "WarnNoCert", true );
    newWrapper->setWarnNoCertificate( warnNoCert );

    const int pinRequests = config->readNumEntry( "NumPINRequests",
						  PinRequest_Always );
    newWrapper->setNumPINRequests( static_cast<PinRequests>( pinRequests ) );

    const int pinRequestsInt = config->readNumEntry( "NumPINRequestsInt",
							   10 );
    newWrapper->setNumPINRequestsInterval( pinRequestsInt );

    const bool checkSigToRoot = config->readNumEntry( "CheckSigCertToRoot",
						      true );
    newWrapper->setCheckSignatureCertificatePathToRoot( checkSigToRoot );

    const bool sigUseCRLs = config->readBoolEntry( "SigUseCRLs", true );
    newWrapper->setSignatureUseCRLs( sigUseCRLs );

    const bool sigCertWarnNearExpire = config->readBoolEntry( "SigCertWarnNearExpire", true );
    newWrapper->setSignatureCertificateExpiryNearWarning( sigCertWarnNearExpire );

    const int sigCertWarnNearExpireInt = config->readNumEntry( "SigCertWarnNearExpireInt", 14 );
    newWrapper->setSignatureCertificateExpiryNearInterval( sigCertWarnNearExpireInt );

    const bool caCertWarnNearExpire = config->readBoolEntry( "CACertWarnNearExpire", true );
    newWrapper->setCACertificateExpiryNearWarning( caCertWarnNearExpire );

    const int caCertWarnNearExpireInt = config->readNumEntry( "CACertWarnNearExpireInt", 14 );
    newWrapper->setCACertificateExpiryNearInterval( caCertWarnNearExpireInt );

    const bool rootCertWarnNearExpire = config->readBoolEntry( "RootCertWarnNearExpire", true );
    newWrapper->setRootCertificateExpiryNearWarning( rootCertWarnNearExpire );

    const int rootCertWarnNearExpireInt = config->readNumEntry( "RootCertWarnNearExpireInt", 14 );
    newWrapper->setRootCertificateExpiryNearInterval( rootCertWarnNearExpireInt );

    const bool warnEmailNotInCert = config->readBoolEntry( "WarnEmailNotInCert", true );
    newWrapper->setWarnNoCertificate( warnEmailNotInCert );

    // Encryption configuration
    const int encryptAlgo = config->readNumEntry( "EncryptAlgo", EncryptAlg_RSA );
    newWrapper->setEncryptionAlgorithm( static_cast<EncryptionAlgorithm>( encryptAlgo ) );

    const int encryptEmail = config->readNumEntry( "EncryptEmail",
						   EncryptEmail_EncryptAll );
    newWrapper->setEncryptEmail( static_cast<EncryptEmail>( encryptEmail ) );

    const bool warnSendUnencrypted = config->readBoolEntry( "WarnSendUnencrypted",
							    true );
    newWrapper->setWarnSendUnencrypted( warnSendUnencrypted );

    const bool alwaysEncryptToSelf = config->readBoolEntry( "AlwaysEncryptToSelf",
							    true );
    newWrapper->setAlwaysEncryptToSelf( alwaysEncryptToSelf );

    const bool warnRecvCertNearExpire = config->readBoolEntry( "WarnRecvCertNearExpire",
							       true );
    newWrapper->setReceiverCertificateExpiryNearWarning( warnRecvCertNearExpire );

    const int warnRecvCertNearExpireInt = config->readNumEntry( "WarnRecvCertNearExpireInt",
								14 );
    newWrapper->setReceiverCertificateExpiryNearWarningInterval( warnRecvCertNearExpireInt );

    const bool warnCertInChainNearExpire = config->readBoolEntry( "WarnCertInChainNearExpire",
								  true );
    newWrapper->setCertificateInChainExpiryNearWarning( warnCertInChainNearExpire );

    const int warnCertInChainNearExpireInt = config->readNumEntry( "WarnCertInChainNearExpireInt",
								   14 );
    newWrapper->setCertificateInChainExpiryNearWarningInterval( warnCertInChainNearExpireInt );

    const bool warnRecvAddrNotInCert = config->readBoolEntry( "WarnRecvAddrNotInCert" );
    newWrapper->setReceiverEmailAddressNotInCertificateWarning( warnRecvAddrNotInCert );

    const bool saveMsgEncrypted = config->readBoolEntry( "SaveMsgsEncrypted", false );
    newWrapper->setSaveMessagesEncrypted( saveMsgEncrypted );

    const bool checkCertPath = config->readBoolEntry( "CheckCertPath", true );
    newWrapper->setCheckCertificatePath( checkCertPath );

    const bool checkEncryptToRoot = config->readBoolEntry( "CheckEncryptCertToRoot",
							   true );
    newWrapper->setCheckEncryptionCertificatePathToRoot( checkEncryptToRoot );

    const bool encryptUseCRLs = config->readBoolEntry( "EncryptUseCRLs", true );
    newWrapper->setEncryptionUseCRLs( encryptUseCRLs );

    const bool encryptCRLWarnNearExpire = config->readBoolEntry( "EncryptCRLWarnNearExpire", true );
    newWrapper->setEncryptionCRLExpiryNearWarning( encryptCRLWarnNearExpire );

    const int encryptCRLWarnNearExpireInt = config->readNumEntry( "EncryptCRLWarnNearExpireInt", 14 );
    newWrapper->setEncryptionCRLNearExpiryInterval( encryptCRLWarnNearExpireInt );

    const int certSource = config->readNumEntry( "CertSource", CertSrc_ServerLocal );
    newWrapper->setCertificateSource( static_cast<CertificateSource>( certSource ) );

    const int crlSource = config->readNumEntry( "CRLSource", CertSrc_ServerLocal );
    newWrapper->setCRLSource( static_cast<CertificateSource>( crlSource ) );
  }
}

#include "cryptplugfactory.moc"
<|endoftext|>


<commit_before>///
/// [EntityFu](https://github.com/NatWeiss/EntityFu)
/// A simple, fast entity component system written in C++.
/// Under the MIT license.
///

#include "EntityFu.h"
using namespace std;

/// Turn this on to have a faster yet riskier ECS.
#define kTrustPointers 0

/// Auto-define a log method.
#ifndef Log
	#include <stdio.h>
	#define Log(...) {printf(__VA_ARGS__); printf("\n");}
#endif

/// Auto-define an assert method.
#ifndef Assert
	#define Assert(condition, format, ...) {if(!condition) throw format;}
#endif

/// Turn this to 1 or 2 to debug the ECS.
/// 1 == log creation, 2 == log creation and deletion.
static int verbosity = 0;

bool* Entity::entities = nullptr;
Entity::Component*** Entity::components = nullptr;
vector<Eid>* Entity::componentEids = nullptr;

void Entity::alloc()
{
	if (components != nullptr)
		return;
	if (verbosity > 0)
		{Log("Allocing entities");}

	// allocate entities
	entities = new bool[kMaxEntities];
	for (Eid eid = 0; eid < kMaxEntities; ++eid)
		entities[eid] = false;

	// allocate components
	auto max = Component::numCids;
	components = new Component**[max];
	componentEids = new vector<Eid>[Component::numCids];
	for (Cid cid = 0; cid < max; cid++)
	{
		// allocate component array
		components[cid] = new Component*[kMaxEntities];

		// zero component pointers
		for (Eid eid = 0; eid < kMaxEntities; eid++)
			components[cid][eid] = nullptr;
	}
}

void Entity::dealloc()
{
	if (verbosity > 0)
		{Log("Deallocing entities");}

	if (components != nullptr)
	{
		Entity::destroyAll();
		for (Cid cid = 0; cid < Component::numCids; cid++)
			if (components[cid] != nullptr)
				delete [] components[cid];
		delete [] components;
	}

	if (componentEids != nullptr)
		delete [] componentEids;

	if (entities != nullptr)
		delete [] entities;

	entities = nullptr;
	components = nullptr;
	componentEids = nullptr;
}

Eid Entity::create()
{
	// auto allocate
	Entity::alloc();

	Eid eid = 1;
	for (; eid < kMaxEntities && entities[eid]; ++eid)
	{
	}

	if (eid < 1 || eid >= kMaxEntities)
	{
		Assert(false, "Maximum number of entities reached!");
		eid = 0;
	}
	else
	{
		entities[eid] = true;
		if (verbosity > 0)
			{Log("Entity %u created", eid);}
	}

	return eid;
}

void Entity::destroyNow(Eid eid)
{
	if (eid == 0)
		return;
	if (verbosity > 0)
		{Log("Entity %u being destroyed", eid);}

	for (Cid cid = 0; cid < Component::numCids; cid++)
		Entity::removeComponent(cid, eid);
	entities[eid] = false;
}

void Entity::destroyAll()
{
	for (Eid eid = 1; eid < kMaxEntities; ++eid)
		if (entities[eid])
			Entity::destroyNow(eid);
}

void Entity::addComponent(Cid cid, Eid eid, Component* c)
{
	if (c == nullptr)
		return;
	if (eid >= kMaxEntities || !entities[eid] || cid >= Component::numCids)
	{
		Assert(false, "Invalid eid %u or cid %u", eid, cid);
		return;
	}
	if (verbosity > 0)
	{
		Log("");
		Entity::log(cid);
		Log("Adding component cid %u eid %u (%x)", cid, eid, (int)(long)c);
	}

	// if component already added, delete old one
	if (components[cid][eid] != nullptr)
		Entity::removeComponent(cid, eid);

	// pointers to components are stored in the map
	// (components must be allocated with new, not stack objects)
	components[cid][eid] = c;

	// store component eids
	componentEids[cid].push_back(eid);

	if (verbosity > 0)
		Entity::log(cid);
}

void Entity::removeComponent(Cid cid, Eid eid)
{
	if (eid >= kMaxEntities || !entities[eid] || cid >= Component::numCids)
	{
		Assert(false, "Invalid eid %u or cid %u", eid, cid);
		return;
	}

	// get pointer
	auto ptr = components[cid][eid];
	if (ptr == nullptr)
		return;

	if (verbosity > 1)
	{
		Log("");
		Entity::log(cid);
		Log("Removing component cid %u eid %u (%x)", cid, eid, (int)(long)ptr);
	}

	// pointers to components are deleted
	delete ptr;

	// erase the component pointer
	components[cid][eid] = nullptr;

	// update component eids
	auto& eids = componentEids[cid];
	auto it = find(eids.begin(), eids.end(), eid);
	if (it != eids.end())
		it = eids.erase(it);

	if (verbosity > 1)
		Entity::log(cid);
}

Entity::Component* Entity::getComponent(Cid cid, Eid eid)
{
#if (kTrustPointers == 0)
	if (eid < kMaxEntities && cid < Component::numCids)
	{
#endif
		return components[cid][eid];

#if (kTrustPointers == 0)
	}
	return nullptr;
#endif
}

const vector<Eid>& Entity::getAll(Cid cid)
{
	if (cid < Component::numCids)
		return componentEids[cid];
	static vector<Eid> blankEids;
	return blankEids;
}

unsigned Entity::count()
{
	int ret = 0;
	for (Eid eid = 1; eid < kMaxEntities; ++eid)
		if (entities[eid])
			++ret;
	return ret;
}

unsigned Entity::count(Cid cid)
{
	return (unsigned)Entity::getAll(cid).size();
}

void Entity::log(Cid cid)
{
	auto n = Entity::count(cid);
	auto& eids = Entity::getAll(cid);
	if (eids.size() > 0)
		{Log("Cid %u has %d entities ranging from %u to %u", cid, n, eids.front(), eids.back());}
}

void Entity::logAll()
{
	for (Cid cid = 0, max = Component::numCids; cid < max; cid++)
		Entity::log(cid);
}

<commit_msg>Check if the entities are allocated before counting<commit_after>///
/// [EntityFu](https://github.com/NatWeiss/EntityFu)
/// A simple, fast entity component system written in C++.
/// Under the MIT license.
///

#include "EntityFu.h"
using namespace std;

/// Turn this on to have a faster yet riskier ECS.
#define kTrustPointers 0

/// Auto-define a log method.
#ifndef Log
	#include <stdio.h>
	#define Log(...) {printf(__VA_ARGS__); printf("\n");}
#endif

/// Auto-define an assert method.
#ifndef Assert
	#define Assert(condition, format, ...) {if(!condition) throw format;}
#endif

/// Turn this to 1 or 2 to debug the ECS.
/// 1 == log creation, 2 == log creation and deletion.
static int verbosity = 0;

bool* Entity::entities = nullptr;
Entity::Component*** Entity::components = nullptr;
vector<Eid>* Entity::componentEids = nullptr;

void Entity::alloc()
{
	if (components != nullptr)
		return;
	if (verbosity > 0)
		{Log("Allocing entities");}

	// allocate entities
	entities = new bool[kMaxEntities];
	for (Eid eid = 0; eid < kMaxEntities; ++eid)
		entities[eid] = false;

	// allocate components
	auto max = Component::numCids;
	components = new Component**[max];
	componentEids = new vector<Eid>[Component::numCids];
	for (Cid cid = 0; cid < max; cid++)
	{
		// allocate component array
		components[cid] = new Component*[kMaxEntities];

		// zero component pointers
		for (Eid eid = 0; eid < kMaxEntities; eid++)
			components[cid][eid] = nullptr;
	}
}

void Entity::dealloc()
{
	if (verbosity > 0)
		{Log("Deallocing entities");}

	if (components != nullptr)
	{
		Entity::destroyAll();
		for (Cid cid = 0; cid < Component::numCids; cid++)
			if (components[cid] != nullptr)
				delete [] components[cid];
		delete [] components;
	}

	if (componentEids != nullptr)
		delete [] componentEids;

	if (entities != nullptr)
		delete [] entities;

	entities = nullptr;
	components = nullptr;
	componentEids = nullptr;
}

Eid Entity::create()
{
	// auto allocate
	Entity::alloc();

	Eid eid = 1;
	for (; eid < kMaxEntities && entities[eid]; ++eid)
	{
	}

	if (eid < 1 || eid >= kMaxEntities)
	{
		Assert(false, "Maximum number of entities reached!");
		eid = 0;
	}
	else
	{
		entities[eid] = true;
		if (verbosity > 0)
			{Log("Entity %u created", eid);}
	}

	return eid;
}

void Entity::destroyNow(Eid eid)
{
	if (eid == 0)
		return;
	if (verbosity > 0)
		{Log("Entity %u being destroyed", eid);}

	for (Cid cid = 0; cid < Component::numCids; cid++)
		Entity::removeComponent(cid, eid);
	entities[eid] = false;
}

void Entity::destroyAll()
{
	for (Eid eid = 1; eid < kMaxEntities; ++eid)
		if (entities[eid])
			Entity::destroyNow(eid);
}

void Entity::addComponent(Cid cid, Eid eid, Component* c)
{
	if (c == nullptr)
		return;
	if (eid >= kMaxEntities || !entities[eid] || cid >= Component::numCids)
	{
		Assert(false, "Invalid eid %u or cid %u", eid, cid);
		return;
	}
	if (verbosity > 0)
	{
		Log("");
		Entity::log(cid);
		Log("Adding component cid %u eid %u (%x)", cid, eid, (int)(long)c);
	}

	// if component already added, delete old one
	if (components[cid][eid] != nullptr)
		Entity::removeComponent(cid, eid);

	// pointers to components are stored in the map
	// (components must be allocated with new, not stack objects)
	components[cid][eid] = c;

	// store component eids
	componentEids[cid].push_back(eid);

	if (verbosity > 0)
		Entity::log(cid);
}

void Entity::removeComponent(Cid cid, Eid eid)
{
	if (eid >= kMaxEntities || !entities[eid] || cid >= Component::numCids)
	{
		Assert(false, "Invalid eid %u or cid %u", eid, cid);
		return;
	}

	// get pointer
	auto ptr = components[cid][eid];
	if (ptr == nullptr)
		return;

	if (verbosity > 1)
	{
		Log("");
		Entity::log(cid);
		Log("Removing component cid %u eid %u (%x)", cid, eid, (int)(long)ptr);
	}

	// pointers to components are deleted
	delete ptr;

	// erase the component pointer
	components[cid][eid] = nullptr;

	// update component eids
	auto& eids = componentEids[cid];
	auto it = find(eids.begin(), eids.end(), eid);
	if (it != eids.end())
		it = eids.erase(it);

	if (verbosity > 1)
		Entity::log(cid);
}

Entity::Component* Entity::getComponent(Cid cid, Eid eid)
{
#if (kTrustPointers == 0)
	if (eid < kMaxEntities && cid < Component::numCids)
	{
#endif
		return components[cid][eid];

#if (kTrustPointers == 0)
	}
	return nullptr;
#endif
}

const vector<Eid>& Entity::getAll(Cid cid)
{
	if (cid < Component::numCids)
		return componentEids[cid];
	static vector<Eid> blankEids;
	return blankEids;
}

unsigned Entity::count()
{
	int ret = 0;
	if(entities != nullptr)
	{
		for (Eid eid = 1; eid < kMaxEntities; ++eid)
			if (entities[eid])
				++ret;
	}
	return ret;
}

unsigned Entity::count(Cid cid)
{
	return (unsigned)Entity::getAll(cid).size();
}

void Entity::log(Cid cid)
{
	auto n = Entity::count(cid);
	auto& eids = Entity::getAll(cid);
	if (eids.size() > 0)
		{Log("Cid %u has %d entities ranging from %u to %u", cid, n, eids.front(), eids.back());}
}

void Entity::logAll()
{
	for (Cid cid = 0, max = Component::numCids; cid < max; cid++)
		Entity::log(cid);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: docsh.hxx,v $
 *
 *  $Revision: 1.35 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 15:20:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SWDOCSH_HXX
#define _SWDOCSH_HXX

#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#ifndef _SHELLID_HXX
#include <shellid.hxx>
#endif

#include <svtools/lstner.hxx>

class SwDoc;
class SfxDocumentInfoDialog;
class SfxStyleSheetBasePool;
class FontList;
class SwView;
class SwWrtShell;
class SwFEShell;
class Reader;
class SwReader;
class SwCrsrShell;
class SwSrcView;
class SwPaM;
class SwgReaderOption;
class SwOLEObj;
class IDocumentDeviceAccess;
class IDocumentSettingAccess;

class SW_DLLPUBLIC SwDocShell: public SfxObjectShell, public SfxListener
{
    SwDoc*                  pDoc;           // Document
    SfxStyleSheetBasePool*  pBasePool;      // Durchreiche fuer Formate
    FontList*               pFontList;      // aktuelle FontListe

    // Nix geht ohne die WrtShell (historische Gruende)
    // RuekwaertsPointer auf die View (historische Gruende)
    // Dieser gilt solange bis im Activate ein neuer gesetzt wird
    // oder dieser im Dtor der View geloescht wird
    //
    SwView*                 pView;
    SwWrtShell*             pWrtShell;

    Timer                   aFinishedTimer; // Timer fuers ueberpriefen der
                                            // Grafik-Links. Sind alle da,
                                            // dann ist Doc voll. geladen

    //SvPersistRef            xOLEChildList;  // fuers RemoveOLEObjects
    comphelper::EmbeddedObjectContainer*    pOLEChildList;
    sal_Int16               nUpdateDocMode; // contains the com::sun::star::document::UpdateDocMode
    bool                    bInUpdateFontList; //prevent nested calls of UpdateFontList
    // Methoden fuer den Zugriff aufs Doc
    SW_DLLPRIVATE void                  AddLink();
    SW_DLLPRIVATE void                  RemoveLink();

    // Hint abfangen fuer DocInfo
    SW_DLLPRIVATE virtual void          Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    // FileIO
    SW_DLLPRIVATE virtual sal_Bool InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    SW_DLLPRIVATE virtual sal_Bool Load( SfxMedium& rMedium );
    SW_DLLPRIVATE virtual sal_Bool LoadFrom( SfxMedium& rMedium );
    SW_DLLPRIVATE virtual sal_Bool            ConvertFrom( SfxMedium &rMedium );
    SW_DLLPRIVATE virtual sal_Bool            ConvertTo( SfxMedium &rMedium );
    SW_DLLPRIVATE virtual sal_Bool SaveAs( SfxMedium& rMedium );
    SW_DLLPRIVATE virtual sal_Bool SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );

    SW_DLLPRIVATE virtual USHORT            PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );

    // DocInfo dem Doc melden
    //
    SW_DLLPRIVATE virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog(
                                    Window *pParent, const SfxItemSet &);
    // OLE-Geraffel
    SW_DLLPRIVATE virtual void          Draw( OutputDevice*, const JobSetup&, USHORT);

    // Methoden fuer StyleSheets
    SW_DLLPRIVATE USHORT                    Edit( const String &rName, const String& rParent, USHORT nFamily,
                                    USHORT nMask, BOOL bNew,
                                    BOOL bColumn = FALSE,
                                    SwWrtShell* pActShell = 0,
                                    BOOL bBasic = FALSE );
    SW_DLLPRIVATE USHORT                    Delete(const String &rName, USHORT nFamily);
    SW_DLLPRIVATE USHORT                    ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0,
                                        USHORT nMode = 0 );
    SW_DLLPRIVATE USHORT                    DoWaterCan( const String &rName, USHORT nFamily);
    SW_DLLPRIVATE USHORT                    UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0);
    SW_DLLPRIVATE USHORT                    MakeByExample(const String &rName,
                                            USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0);

    SW_DLLPRIVATE void                  InitDraw();
    SW_DLLPRIVATE void                  SubInitNew();   // fuer InitNew und HtmlSourceModus

    SW_DLLPRIVATE void                  RemoveOLEObjects();
    SW_DLLPRIVATE void                  CalcLayoutForOLEObjects();

    SW_DLLPRIVATE void                    Init_Impl();
    SW_DLLPRIVATE DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* );

public:

    // aber selbst implementieren
    SFX_DECL_INTERFACE(SW_DOCSHELL)
    SFX_DECL_OBJECTFACTORY()
    TYPEINFO();

    static SfxInterface *_GetInterface() { return GetStaticInterface(); }

    //Das Doc wird fuer SO-Datenaustausch benoetigt!
    SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );
    ~SwDocShell();

    // OLE 2.0-Benachrichtigung
    DECL_LINK( Ole2ModifiedHdl, void * );

    // OLE-Geraffel
    virtual void      SetVisArea( const Rectangle &rRect );
    virtual Rectangle GetVisArea( USHORT nAspect ) const;
    virtual Printer  *GetDocumentPrinter();
    virtual OutputDevice* GetDocumentRefDev();
    virtual void      OnDocumentPrinterChanged( Printer * pNewPrinter );
    virtual ULONG     GetMiscStatus() const;

    virtual void            PrepareReload();
    virtual void            SetModified( BOOL = TRUE );

    // Dispatcher
    void                    Execute(SfxRequest &);
    void                    ExecStyleSheet(SfxRequest&);
    void                    ExecDB(SfxRequest&);

    void                    GetState(SfxItemSet &);
    void                    StateAlways(SfxItemSet &);
    void                    StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 );

    // Doc rausreichen aber VORSICHT
    inline SwDoc*                   GetDoc() { return pDoc; }
    IDocumentDeviceAccess*          getIDocumentDeviceAccess();
    const IDocumentSettingAccess*   getIDocumentSettingAccess() const;

    void                    UpdateFontList();
    void                    UpdateChildWindows();

    // DocumentInfo neu setzen
    BOOL                    SetDocumentInfo(const SfxDocumentInfo& rInfo);

    // globaler IO
    virtual BOOL            Save();

    // fuer VorlagenPI
    virtual SfxStyleSheetBasePool*  GetStyleSheetPool();

    // Fuer Organizer
    virtual BOOL Insert(SfxObjectShell &rSource,
                        USHORT  nSourceIdx1,
                        USHORT  nSourceIdx2,
                        USHORT  nSourceIdx3,
                        USHORT& nIdx1,
                        USHORT& nIdx2,
                        USHORT& nIdx3,
                        USHORT& nRemovedIdx);

    virtual BOOL Remove(USHORT nIdx1,
                        USHORT nIdx2 = INDEX_IGNORE,
                        USHORT nIdx3 = INDEX_IGNORE);

    virtual Bitmap      GetStyleFamilyBitmap( SfxStyleFamily eFamily, BmpColorMode eColorMode );

    // View setzen fuer Aktionen ueber Shell
    void          SetView(SwView* pVw);
    const SwView *GetView() const { return pView; }
    SwView       *GetView()       { return pView; }

    // Zugriff auf die zur SwView gehoerige SwWrtShell
          SwWrtShell *GetWrtShell()       { return pWrtShell; }
    const SwWrtShell *GetWrtShell() const { return pWrtShell; }

    // fuer die Core - die kennt die DocShell aber keine WrtShell!
          SwFEShell *GetFEShell();
    const SwFEShell *GetFEShell() const
                { return ((SwDocShell*)this)->GetFEShell(); }

    // Fuer Einfuegen Dokument
    Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr,
                            SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0);

    virtual long DdeGetData( const String& rItem, const String& rMimeType,
                             ::com::sun::star::uno::Any & rValue );
    virtual long DdeSetData( const String& rItem, const String& rMimeType,
                                const ::com::sun::star::uno::Any & rValue );
    virtual ::sfx2::SvLinkSource* DdeCreateLinkSource( const String& rItem );
    virtual void FillClass( SvGlobalName * pClassName,
                                   sal_uInt32 * pClipFormat,
                                   String * pAppName,
                                   String * pLongUserName,
                                   String * pUserName,
                                   sal_Int32 nFileFormat ) const;

    virtual void LoadStyles( SfxObjectShell& rSource );

    void _LoadStyles( SfxObjectShell& rSource, BOOL bPreserveCurrentDocument );

    // Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage
    void FormatPage( const String& rPage,
                        BOOL bColumn = FALSE,
                        SwWrtShell*     pActShell = 0 );

    // Timer starten fuers ueberpruefen der Grafik-Links. Sind alle
    // vollstaendig geladen, dann ist das Doc fertig
    void StartLoadFinishedTimer();

    // eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen)
    virtual void CancelTransfers();

    // Doc aus Html-Source neu laden
    void    ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView );

    sal_Int16   GetUpdateDocMode() const {return nUpdateDocMode;}

    //Activate wait cursor for all windows of this document
    //Optionally all dispatcher could be Locked
    //Usually locking should be done using the class: SwWaitObject!
    void EnterWait( BOOL bLockDispatcher );
    void LeaveWait( BOOL bLockDispatcher );

    void ToggleBrowserMode(BOOL bOn, SwView* pView = 0);

    ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt,
                                BOOL bUnoCall );
    void InvalidateModel();
    void ReactivateModel();

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >  GetEventNames();

    // --> FME 2004-08-05 #i20883# Digital Signatures and Encryption
    virtual sal_uInt16 GetHiddenInformationState( sal_uInt16 nStates );
    // <--

    // --> FME 2005-02-25 #i42634# Overwrites SfxObjectShell::UpdateLinks
    // This new function is necessary to trigger update of links in docs
    // read by the binary filter:
    virtual void UpdateLinks();
    // <--

    SW_DLLPRIVATE void  CalcAndSetScaleOfOLEObj( SwOLEObj& rOLEObject );
};

#endif
<commit_msg>INTEGRATION: CWS swstability06 (1.35.22); FILE MERGED 2006/09/01 12:10:30 ama 1.35.22.1: #i68827#: CleanUp for timer access<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: docsh.hxx,v $
 *
 *  $Revision: 1.36 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-11 08:47:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SWDOCSH_HXX
#define _SWDOCSH_HXX

#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#ifndef _SHELLID_HXX
#include <shellid.hxx>
#endif

#include <svtools/lstner.hxx>

class SwDoc;
class SfxDocumentInfoDialog;
class SfxStyleSheetBasePool;
class FontList;
class SwView;
class SwWrtShell;
class SwFEShell;
class Reader;
class SwReader;
class SwCrsrShell;
class SwSrcView;
class SwPaM;
class SwgReaderOption;
class SwOLEObj;
class IDocumentDeviceAccess;
class IDocumentSettingAccess;
class IDocumentTimerAccess;

class SW_DLLPUBLIC SwDocShell: public SfxObjectShell, public SfxListener
{
    SwDoc*                  pDoc;           // Document
    SfxStyleSheetBasePool*  pBasePool;      // Durchreiche fuer Formate
    FontList*               pFontList;      // aktuelle FontListe

    // Nix geht ohne die WrtShell (historische Gruende)
    // RuekwaertsPointer auf die View (historische Gruende)
    // Dieser gilt solange bis im Activate ein neuer gesetzt wird
    // oder dieser im Dtor der View geloescht wird
    //
    SwView*                 pView;
    SwWrtShell*             pWrtShell;

    Timer                   aFinishedTimer; // Timer fuers ueberpriefen der
                                            // Grafik-Links. Sind alle da,
                                            // dann ist Doc voll. geladen

    //SvPersistRef            xOLEChildList;  // fuers RemoveOLEObjects
    comphelper::EmbeddedObjectContainer*    pOLEChildList;
    sal_Int16               nUpdateDocMode; // contains the com::sun::star::document::UpdateDocMode
    bool                    bInUpdateFontList; //prevent nested calls of UpdateFontList
    // Methoden fuer den Zugriff aufs Doc
    SW_DLLPRIVATE void                  AddLink();
    SW_DLLPRIVATE void                  RemoveLink();

    // Hint abfangen fuer DocInfo
    SW_DLLPRIVATE virtual void          Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    // FileIO
    SW_DLLPRIVATE virtual sal_Bool InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    SW_DLLPRIVATE virtual sal_Bool Load( SfxMedium& rMedium );
    SW_DLLPRIVATE virtual sal_Bool LoadFrom( SfxMedium& rMedium );
    SW_DLLPRIVATE virtual sal_Bool            ConvertFrom( SfxMedium &rMedium );
    SW_DLLPRIVATE virtual sal_Bool            ConvertTo( SfxMedium &rMedium );
    SW_DLLPRIVATE virtual sal_Bool SaveAs( SfxMedium& rMedium );
    SW_DLLPRIVATE virtual sal_Bool SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );

    SW_DLLPRIVATE virtual USHORT            PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );

    // DocInfo dem Doc melden
    //
    SW_DLLPRIVATE virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog(
                                    Window *pParent, const SfxItemSet &);
    // OLE-Geraffel
    SW_DLLPRIVATE virtual void          Draw( OutputDevice*, const JobSetup&, USHORT);

    // Methoden fuer StyleSheets
    SW_DLLPRIVATE USHORT                    Edit( const String &rName, const String& rParent, USHORT nFamily,
                                    USHORT nMask, BOOL bNew,
                                    BOOL bColumn = FALSE,
                                    SwWrtShell* pActShell = 0,
                                    BOOL bBasic = FALSE );
    SW_DLLPRIVATE USHORT                    Delete(const String &rName, USHORT nFamily);
    SW_DLLPRIVATE USHORT                    ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0,
                                        USHORT nMode = 0 );
    SW_DLLPRIVATE USHORT                    DoWaterCan( const String &rName, USHORT nFamily);
    SW_DLLPRIVATE USHORT                    UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0);
    SW_DLLPRIVATE USHORT                    MakeByExample(const String &rName,
                                            USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0);

    SW_DLLPRIVATE void                  InitDraw();
    SW_DLLPRIVATE void                  SubInitNew();   // fuer InitNew und HtmlSourceModus

    SW_DLLPRIVATE void                  RemoveOLEObjects();
    SW_DLLPRIVATE void                  CalcLayoutForOLEObjects();

    SW_DLLPRIVATE void                    Init_Impl();
    SW_DLLPRIVATE DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* );

public:

    // aber selbst implementieren
    SFX_DECL_INTERFACE(SW_DOCSHELL)
    SFX_DECL_OBJECTFACTORY()
    TYPEINFO();

    static SfxInterface *_GetInterface() { return GetStaticInterface(); }

    //Das Doc wird fuer SO-Datenaustausch benoetigt!
    SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );
    ~SwDocShell();

    // OLE 2.0-Benachrichtigung
    DECL_LINK( Ole2ModifiedHdl, void * );

    // OLE-Geraffel
    virtual void      SetVisArea( const Rectangle &rRect );
    virtual Rectangle GetVisArea( USHORT nAspect ) const;
    virtual Printer  *GetDocumentPrinter();
    virtual OutputDevice* GetDocumentRefDev();
    virtual void      OnDocumentPrinterChanged( Printer * pNewPrinter );
    virtual ULONG     GetMiscStatus() const;

    virtual void            PrepareReload();
    virtual void            SetModified( BOOL = TRUE );

    // Dispatcher
    void                    Execute(SfxRequest &);
    void                    ExecStyleSheet(SfxRequest&);
    void                    ExecDB(SfxRequest&);

    void                    GetState(SfxItemSet &);
    void                    StateAlways(SfxItemSet &);
    void                    StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 );

    // Doc rausreichen aber VORSICHT
    inline SwDoc*                   GetDoc() { return pDoc; }
    IDocumentDeviceAccess*          getIDocumentDeviceAccess();
    const IDocumentSettingAccess*   getIDocumentSettingAccess() const;
    IDocumentTimerAccess*           getIDocumentTimerAccess();

    void                    UpdateFontList();
    void                    UpdateChildWindows();

    // DocumentInfo neu setzen
    BOOL                    SetDocumentInfo(const SfxDocumentInfo& rInfo);

    // globaler IO
    virtual BOOL            Save();

    // fuer VorlagenPI
    virtual SfxStyleSheetBasePool*  GetStyleSheetPool();

    // Fuer Organizer
    virtual BOOL Insert(SfxObjectShell &rSource,
                        USHORT  nSourceIdx1,
                        USHORT  nSourceIdx2,
                        USHORT  nSourceIdx3,
                        USHORT& nIdx1,
                        USHORT& nIdx2,
                        USHORT& nIdx3,
                        USHORT& nRemovedIdx);

    virtual BOOL Remove(USHORT nIdx1,
                        USHORT nIdx2 = INDEX_IGNORE,
                        USHORT nIdx3 = INDEX_IGNORE);

    virtual Bitmap      GetStyleFamilyBitmap( SfxStyleFamily eFamily, BmpColorMode eColorMode );

    // View setzen fuer Aktionen ueber Shell
    void          SetView(SwView* pVw);
    const SwView *GetView() const { return pView; }
    SwView       *GetView()       { return pView; }

    // Zugriff auf die zur SwView gehoerige SwWrtShell
          SwWrtShell *GetWrtShell()       { return pWrtShell; }
    const SwWrtShell *GetWrtShell() const { return pWrtShell; }

    // fuer die Core - die kennt die DocShell aber keine WrtShell!
          SwFEShell *GetFEShell();
    const SwFEShell *GetFEShell() const
                { return ((SwDocShell*)this)->GetFEShell(); }

    // Fuer Einfuegen Dokument
    Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr,
                            SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0);

    virtual long DdeGetData( const String& rItem, const String& rMimeType,
                             ::com::sun::star::uno::Any & rValue );
    virtual long DdeSetData( const String& rItem, const String& rMimeType,
                                const ::com::sun::star::uno::Any & rValue );
    virtual ::sfx2::SvLinkSource* DdeCreateLinkSource( const String& rItem );
    virtual void FillClass( SvGlobalName * pClassName,
                                   sal_uInt32 * pClipFormat,
                                   String * pAppName,
                                   String * pLongUserName,
                                   String * pUserName,
                                   sal_Int32 nFileFormat ) const;

    virtual void LoadStyles( SfxObjectShell& rSource );

    void _LoadStyles( SfxObjectShell& rSource, BOOL bPreserveCurrentDocument );

    // Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage
    void FormatPage( const String& rPage,
                        BOOL bColumn = FALSE,
                        SwWrtShell*     pActShell = 0 );

    // Timer starten fuers ueberpruefen der Grafik-Links. Sind alle
    // vollstaendig geladen, dann ist das Doc fertig
    void StartLoadFinishedTimer();

    // eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen)
    virtual void CancelTransfers();

    // Doc aus Html-Source neu laden
    void    ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView );

    sal_Int16   GetUpdateDocMode() const {return nUpdateDocMode;}

    //Activate wait cursor for all windows of this document
    //Optionally all dispatcher could be Locked
    //Usually locking should be done using the class: SwWaitObject!
    void EnterWait( BOOL bLockDispatcher );
    void LeaveWait( BOOL bLockDispatcher );

    void ToggleBrowserMode(BOOL bOn, SwView* pView = 0);

    ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt,
                                BOOL bUnoCall );
    void InvalidateModel();
    void ReactivateModel();

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >  GetEventNames();

    // --> FME 2004-08-05 #i20883# Digital Signatures and Encryption
    virtual sal_uInt16 GetHiddenInformationState( sal_uInt16 nStates );
    // <--

    // --> FME 2005-02-25 #i42634# Overwrites SfxObjectShell::UpdateLinks
    // This new function is necessary to trigger update of links in docs
    // read by the binary filter:
    virtual void UpdateLinks();
    // <--

    SW_DLLPRIVATE void  CalcAndSetScaleOfOLEObj( SwOLEObj& rOLEObject );
};

#endif
<|endoftext|>