<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkInteractiveChartXYZ.h

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkInteractiveChartXYZ.h"

#include "vtkAnnotationLink.h"
#include "vtkAxis.h"
#include "vtkCommand.h"
#include "vtkContext2D.h"
#include "vtkContext3D.h"
#include "vtkContextMouseEvent.h"
#include "vtkContextScene.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkLookupTable.h"
#include "vtkMath.h"
#include "vtkTable.h"
#include "vtkTransform.h"
#include "vtkUnsignedCharArray.h"
#include "vtkVector.h"
#include "vtkVectorOperators.h"

#include "vtkPen.h"
#include "vtkAnnotationLink.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"

#include "vtkObjectFactory.h"

#include <vector>
#include <cassert>

using std::vector;

vtkStandardNewMacro(vtkInteractiveChartXYZ)

void vtkInteractiveChartXYZ::PrintSelf(ostream &os, vtkIndent indent)
{
  Superclass::PrintSelf(os, indent);
}

void vtkInteractiveChartXYZ::Update()
{
  if (this->Link)
    {
    // Copy the row numbers so that we can do the highlight...
    if (!this->points.empty())
      {
      vtkSelection *selection =
          vtkSelection::SafeDownCast(this->Link->GetOutputDataObject(2));
      if (selection->GetNumberOfNodes())
        {
        vtkSelectionNode *node = selection->GetNode(0);
        vtkIdTypeArray *idArray =
            vtkIdTypeArray::SafeDownCast(node->GetSelectionList());
        if (this->selectedPointsBuidTime > idArray->GetMTime() ||
            this->GetMTime() > this->selectedPointsBuidTime)
          {
          this->selectedPoints.resize(idArray->GetNumberOfTuples());
          for (vtkIdType i = 0; i < idArray->GetNumberOfTuples(); ++i)
            {
            this->selectedPoints[i] = this->points[idArray->GetValue(i)];
            }
          this->selectedPointsBuidTime.Modified();
          }
        }
      }
    }
}

bool vtkInteractiveChartXYZ::Paint(vtkContext2D *painter)
{
  if (!this->Visible || this->points.size() == 0)
    return false;

  // Get the 3D context.
  vtkContext3D *context = painter->GetContext3D();

  if (!context)
    return false;

  this->Update();

  // Calculate the transforms required for the current rotation.
  this->CalculateTransforms();

  context->PushMatrix();
  context->AppendTransform(this->ContextTransform.GetPointer());

  // First lets draw the points in 3d.
  context->ApplyPen(this->Pen.GetPointer());
  if (this->NumberOfComponents == 0)
    {
    context->DrawPoints(this->points[0].GetData(), this->points.size());
    }
  else
    {
    context->DrawPoints(this->points[0].GetData(), this->points.size(),
                        this->Colors, this->NumberOfComponents);
    }

  // Now to render the selected points.
  if (!this->selectedPoints.empty())
    {
    context->ApplyPen(this->SelectedPen.GetPointer());
    context->DrawPoints(this->selectedPoints[0].GetData(), this->selectedPoints.size());
    }

  context->PopMatrix();

  // Now to draw the axes - pretty basic for now but could be extended.
  context->PushMatrix();
  context->AppendTransform(this->Box.GetPointer());
  context->ApplyPen(this->AxisPen.GetPointer());

  vtkVector3f box[4];
  box[0] = vtkVector3f(0, 0, 0);
  box[1] = vtkVector3f(0, 1, 0);
  box[2] = vtkVector3f(1, 1, 0);
  box[3] = vtkVector3f(1, 0, 0);
  context->DrawLine(box[0], box[1]);
  context->DrawLine(box[1], box[2]);
  context->DrawLine(box[2], box[3]);
  context->DrawLine(box[3], box[0]);
  for (int i = 0; i < 4; ++i)
    {
    box[i].SetZ(1);
    }
  context->DrawLine(box[0], box[1]);
  context->DrawLine(box[1], box[2]);
  context->DrawLine(box[2], box[3]);
  context->DrawLine(box[3], box[0]);
  context->DrawLine(vtkVector3f(0, 0, 0), vtkVector3f(0, 0, 1));
  context->DrawLine(vtkVector3f(1, 0, 0), vtkVector3f(1, 0, 1));
  context->DrawLine(vtkVector3f(0, 1, 0), vtkVector3f(0, 1, 1));
  context->DrawLine(vtkVector3f(1, 1, 0), vtkVector3f(1, 1, 1));
  context->PopMatrix();

  return true;
}

void vtkInteractiveChartXYZ::SetInput(vtkTable *input, const vtkStdString &xName,
                           const vtkStdString &yName, const vtkStdString &zName)
{
  this->Superclass::SetInput(input, xName, yName, zName);
}

void vtkInteractiveChartXYZ::SetInput(vtkTable *input, const vtkStdString &xName,
                           const vtkStdString &yName, const vtkStdString &zName,
                           const vtkStdString &colorName)
{
  this->Superclass::SetInput(input, xName, yName, zName);

  vtkDataArray *colorArr =
      vtkDataArray::SafeDownCast(input->GetColumnByName(colorName.c_str()));

  assert(colorArr);
  assert(colorArr->GetNumberOfTuples() == this->points.size());

  this->NumberOfComponents = 3;

  //generate a color lookup table
  vtkNew<vtkLookupTable> lookupTable;
  double min = DBL_MAX;
  double max = DBL_MIN;
  for (int i = 0; i < this->points.size(); ++i)
    {
    double value = colorArr->GetComponent(i, 0);
    if (value > max)
      {
      max = value;
      }
    else if (value < min)
      {
      min = value;
      }
    }

  lookupTable->SetNumberOfTableValues(256);
  lookupTable->SetRange(min, max);
  lookupTable->Build();

  double color[3];
  this->Colors =
    new unsigned char[this->points.size() * this->NumberOfComponents];

  for (int i = 0; i < this->points.size(); ++i)
    {
    double value = colorArr->GetComponent(i, 0);
    unsigned char *rgb = lookupTable->MapValue(value);
    this->Colors[i * this->NumberOfComponents] = rgb[0];
    this->Colors[i * this->NumberOfComponents + 1] = rgb[1];
    this->Colors[i * this->NumberOfComponents + 2] = rgb[2];
    }
}

vtkInteractiveChartXYZ::vtkInteractiveChartXYZ()
{
  this->Translation->Identity();
  this->Translation->PostMultiply();
  this->Scale->Identity();
  this->Scale->PostMultiply();
  this->Interactive = true;
  this->Colors = NULL;
  this->NumberOfComponents = 0;
}

vtkInteractiveChartXYZ::~vtkInteractiveChartXYZ()
{
  if(this->Colors != NULL)
    {
    delete [] this->Colors;
    this->Colors = NULL;
    }
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::Hit(const vtkContextMouseEvent &vtkNotUsed(mouse))
{
  // If we are interactive, we want to catch anything that propagates to the
  // background, otherwise we do not want any mouse events.
  return this->Interactive;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::MouseButtonPressEvent(const vtkContextMouseEvent &mouse)
{
  if (mouse.GetButton() == vtkContextMouseEvent::LEFT_BUTTON)
    {
    return true;
    }
  return false;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::MouseMoveEvent(const vtkContextMouseEvent &mouse)
{
  if (mouse.GetButton() == vtkContextMouseEvent::LEFT_BUTTON)
    {
    if (mouse.GetModifiers() == vtkContextMouseEvent::SHIFT_MODIFIER)
      {
      return this->Spin(mouse);
      }
    else
      {
      return this->Rotate(mouse);
      }
    }
  if (mouse.GetButton() == vtkContextMouseEvent::RIGHT_BUTTON)
    {
    if (mouse.GetModifiers() == vtkContextMouseEvent::SHIFT_MODIFIER)
      {
      return this->Pan(mouse);
      }
    else
      {
      return this->Zoom(mouse);
      }
    }
/*
    // Figure out how much the mouse has moved and scale accordingly
    float delta = 0.0f;
    if (this->Scene->GetSceneHeight() > 0)
      {
      delta = static_cast<float>(mouse.GetLastScreenPos()[1] - mouse.GetScreenPos()[1])/this->Scene->GetSceneHeight();
      }

    // Dragging full screen height zooms 4x.
    float scaling = pow(4.0f, delta);

    // Mark the scene as dirty
    this->Scene->SetDirty(true);

    this->InvokeEvent(vtkCommand::InteractionEvent);
    return true;
*/
  return false;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::MouseWheelEvent(const vtkContextMouseEvent &mouse, int delta)
{
  // Determine current position to zoom in on
  /*
  vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData());
  vtkVector2d pos(0.0, 0.0);
  vtkTransform2D *transform = this->GetTransform();
  transform->InverseTransformPoints(screenPos.GetData(), pos.GetData(), 1);
  vtkVector2f zoomAnchor = vtkVector2f(pos.Cast<float>().GetData());
  */

  // Ten "wheels" to double/halve zoom level
  float scaling = pow(2.0f, delta/10.0f);

  // Zoom in on current position
  /*
  this->Translate(zoomAnchor[0], zoomAnchor[1]);
  this->Scale(scaling, scaling);
  this->Translate(-zoomAnchor[0], -zoomAnchor[1]);
  */

  // Mark the scene as dirty
  this->Scene->SetDirty(true);

  this->InvokeEvent(vtkCommand::InteractionEvent);
  return true;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::Rotate(const vtkContextMouseEvent &mouse)
{
  // Figure out how much the mouse has moved in plot coordinates
  vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData());
  vtkVector2d lastScreenPos(mouse.GetLastScreenPos().Cast<double>().GetData());

  double dx = screenPos[0] - lastScreenPos[0];
  double dy = screenPos[1] - lastScreenPos[1];

  double delta_elevation = -20.0 / this->Scene->GetSceneHeight();
  double delta_azimuth = -20.0 / this->Scene->GetSceneWidth();

  double rxf = dx * delta_azimuth * 10.0;
  double ryf = dy * delta_elevation * 10.0;

  this->Rotation->RotateY(-rxf);
  this->Rotation->RotateX(ryf);

  // Mark the scene as dirty
  this->Scene->SetDirty(true);

  this->InvokeEvent(vtkCommand::InteractionEvent);
  return true;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::Pan(const vtkContextMouseEvent &mouse)
{
  // Figure out how much the mouse has moved in plot coordinates
  vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData());
  vtkVector2d lastScreenPos(mouse.GetLastScreenPos().Cast<double>().GetData());

  double dx = (screenPos[0] - lastScreenPos[0]);
  double dy = (screenPos[1] - lastScreenPos[1]);

  this->Translation->Translate(dx, dy, 0.0);

  // Mark the scene as dirty
  this->Scene->SetDirty(true);

  this->InvokeEvent(vtkCommand::InteractionEvent);
  return true;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::Zoom(const vtkContextMouseEvent &mouse)
{
  // Figure out how much the mouse has moved in plot coordinates
  vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData());
  vtkVector2d lastScreenPos(mouse.GetLastScreenPos().Cast<double>().GetData());

  double dz = 1.0 -
    (screenPos[1] - lastScreenPos[1]) / this->Scene->GetSceneHeight();
  this->Scale->Scale(dz, dz, 0.0);

  // Mark the scene as dirty
  this->Scene->SetDirty(true);

  this->InvokeEvent(vtkCommand::InteractionEvent);
  return true;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::Spin(const vtkContextMouseEvent &mouse)
{
  // Figure out how much the mouse has moved in plot coordinates
  vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData());
  vtkVector2d lastScreenPos(mouse.GetLastScreenPos().Cast<double>().GetData());

  double newAngle =
    vtkMath::DegreesFromRadians(atan2(screenPos[1], screenPos[0]));
  double oldAngle =
    vtkMath::DegreesFromRadians(atan2(lastScreenPos[1], lastScreenPos[0]));

  this->Rotation->RotateZ(-(newAngle - oldAngle));

  // Mark the scene as dirty
  this->Scene->SetDirty(true);

  this->InvokeEvent(vtkCommand::InteractionEvent);
  return true;
}

void vtkInteractiveChartXYZ::CalculateTransforms()
{
  // First the rotation transform...
  // Calculate the correct translation vector before the rotation is applied
  vtkVector3f translation(
        (axes[0]->GetPosition2()[0] - axes[0]->GetPosition1()[0]) / 2.0
        + axes[0]->GetPosition1()[0],
        (axes[1]->GetPosition2()[1] - axes[1]->GetPosition1()[1]) / 2.0
        + axes[1]->GetPosition1()[1],
        (axes[2]->GetPosition2()[1] - axes[2]->GetPosition1()[1]) / 2.0
        + axes[2]->GetPosition1()[1]);
  vtkVector3f mtranslation = -1.0 * translation;

  this->ContextTransform->Identity();
  this->ContextTransform->Concatenate(this->Translation.GetPointer());
  this->ContextTransform->Translate(translation.GetData());
  this->ContextTransform->Concatenate(this->Rotation.GetPointer());
  this->ContextTransform->Concatenate(this->Scale.GetPointer());
  this->ContextTransform->Translate(mtranslation.GetData());
  this->ContextTransform->Concatenate(this->Transform.GetPointer());

  // Next the box rotation transform.
  double scale[3] = { 300, 300, 300 };
  for (int i = 0; i < 3; ++i)
    {
    if (i == 0)
      scale[i] = axes[i]->GetPosition2()[0] - axes[i]->GetPosition1()[0];
    else
      scale[i] = axes[i]->GetPosition2()[1] - axes[i]->GetPosition1()[1];
    }

  this->Box->Identity();
  this->Box->PostMultiply();
  this->Box->Translate(-0.5, -0.5, -0.5);
  this->Box->Concatenate(this->Rotation.GetPointer());
  this->Box->Concatenate(this->Scale.GetPointer());
  this->Box->Translate(0.5, 0.5, 0.5);
  this->Box->Scale(scale);
  this->Box->Translate(axes[0]->GetPosition1()[0],
                       axes[1]->GetPosition1()[1],
                       axes[2]->GetPosition1()[1]);
  this->Box->Concatenate(this->Translation.GetPointer());
}
<commit_msg>implement mouse wheel zoom for vtkInteractiveChartXYZ<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkInteractiveChartXYZ.h

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkInteractiveChartXYZ.h"

#include "vtkAnnotationLink.h"
#include "vtkAxis.h"
#include "vtkCommand.h"
#include "vtkContext2D.h"
#include "vtkContext3D.h"
#include "vtkContextMouseEvent.h"
#include "vtkContextScene.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkLookupTable.h"
#include "vtkMath.h"
#include "vtkTable.h"
#include "vtkTransform.h"
#include "vtkUnsignedCharArray.h"
#include "vtkVector.h"
#include "vtkVectorOperators.h"

#include "vtkPen.h"
#include "vtkAnnotationLink.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"

#include "vtkObjectFactory.h"

#include <vector>
#include <cassert>

using std::vector;

vtkStandardNewMacro(vtkInteractiveChartXYZ)

void vtkInteractiveChartXYZ::PrintSelf(ostream &os, vtkIndent indent)
{
  Superclass::PrintSelf(os, indent);
}

void vtkInteractiveChartXYZ::Update()
{
  if (this->Link)
    {
    // Copy the row numbers so that we can do the highlight...
    if (!this->points.empty())
      {
      vtkSelection *selection =
          vtkSelection::SafeDownCast(this->Link->GetOutputDataObject(2));
      if (selection->GetNumberOfNodes())
        {
        vtkSelectionNode *node = selection->GetNode(0);
        vtkIdTypeArray *idArray =
            vtkIdTypeArray::SafeDownCast(node->GetSelectionList());
        if (this->selectedPointsBuidTime > idArray->GetMTime() ||
            this->GetMTime() > this->selectedPointsBuidTime)
          {
          this->selectedPoints.resize(idArray->GetNumberOfTuples());
          for (vtkIdType i = 0; i < idArray->GetNumberOfTuples(); ++i)
            {
            this->selectedPoints[i] = this->points[idArray->GetValue(i)];
            }
          this->selectedPointsBuidTime.Modified();
          }
        }
      }
    }
}

bool vtkInteractiveChartXYZ::Paint(vtkContext2D *painter)
{
  if (!this->Visible || this->points.size() == 0)
    return false;

  // Get the 3D context.
  vtkContext3D *context = painter->GetContext3D();

  if (!context)
    return false;

  this->Update();

  // Calculate the transforms required for the current rotation.
  this->CalculateTransforms();

  context->PushMatrix();
  context->AppendTransform(this->ContextTransform.GetPointer());

  // First lets draw the points in 3d.
  context->ApplyPen(this->Pen.GetPointer());
  if (this->NumberOfComponents == 0)
    {
    context->DrawPoints(this->points[0].GetData(), this->points.size());
    }
  else
    {
    context->DrawPoints(this->points[0].GetData(), this->points.size(),
                        this->Colors, this->NumberOfComponents);
    }

  // Now to render the selected points.
  if (!this->selectedPoints.empty())
    {
    context->ApplyPen(this->SelectedPen.GetPointer());
    context->DrawPoints(this->selectedPoints[0].GetData(), this->selectedPoints.size());
    }

  context->PopMatrix();

  // Now to draw the axes - pretty basic for now but could be extended.
  context->PushMatrix();
  context->AppendTransform(this->Box.GetPointer());
  context->ApplyPen(this->AxisPen.GetPointer());

  vtkVector3f box[4];
  box[0] = vtkVector3f(0, 0, 0);
  box[1] = vtkVector3f(0, 1, 0);
  box[2] = vtkVector3f(1, 1, 0);
  box[3] = vtkVector3f(1, 0, 0);
  context->DrawLine(box[0], box[1]);
  context->DrawLine(box[1], box[2]);
  context->DrawLine(box[2], box[3]);
  context->DrawLine(box[3], box[0]);
  for (int i = 0; i < 4; ++i)
    {
    box[i].SetZ(1);
    }
  context->DrawLine(box[0], box[1]);
  context->DrawLine(box[1], box[2]);
  context->DrawLine(box[2], box[3]);
  context->DrawLine(box[3], box[0]);
  context->DrawLine(vtkVector3f(0, 0, 0), vtkVector3f(0, 0, 1));
  context->DrawLine(vtkVector3f(1, 0, 0), vtkVector3f(1, 0, 1));
  context->DrawLine(vtkVector3f(0, 1, 0), vtkVector3f(0, 1, 1));
  context->DrawLine(vtkVector3f(1, 1, 0), vtkVector3f(1, 1, 1));
  context->PopMatrix();

  return true;
}

void vtkInteractiveChartXYZ::SetInput(vtkTable *input, const vtkStdString &xName,
                           const vtkStdString &yName, const vtkStdString &zName)
{
  this->Superclass::SetInput(input, xName, yName, zName);
}

void vtkInteractiveChartXYZ::SetInput(vtkTable *input, const vtkStdString &xName,
                           const vtkStdString &yName, const vtkStdString &zName,
                           const vtkStdString &colorName)
{
  this->Superclass::SetInput(input, xName, yName, zName);

  vtkDataArray *colorArr =
      vtkDataArray::SafeDownCast(input->GetColumnByName(colorName.c_str()));

  assert(colorArr);
  assert(colorArr->GetNumberOfTuples() == this->points.size());

  this->NumberOfComponents = 3;

  //generate a color lookup table
  vtkNew<vtkLookupTable> lookupTable;
  double min = DBL_MAX;
  double max = DBL_MIN;
  for (int i = 0; i < this->points.size(); ++i)
    {
    double value = colorArr->GetComponent(i, 0);
    if (value > max)
      {
      max = value;
      }
    else if (value < min)
      {
      min = value;
      }
    }

  lookupTable->SetNumberOfTableValues(256);
  lookupTable->SetRange(min, max);
  lookupTable->Build();

  double color[3];
  this->Colors =
    new unsigned char[this->points.size() * this->NumberOfComponents];

  for (int i = 0; i < this->points.size(); ++i)
    {
    double value = colorArr->GetComponent(i, 0);
    unsigned char *rgb = lookupTable->MapValue(value);
    this->Colors[i * this->NumberOfComponents] = rgb[0];
    this->Colors[i * this->NumberOfComponents + 1] = rgb[1];
    this->Colors[i * this->NumberOfComponents + 2] = rgb[2];
    }
}

vtkInteractiveChartXYZ::vtkInteractiveChartXYZ()
{
  this->Translation->Identity();
  this->Translation->PostMultiply();
  this->Scale->Identity();
  this->Scale->PostMultiply();
  this->Interactive = true;
  this->Colors = NULL;
  this->NumberOfComponents = 0;
}

vtkInteractiveChartXYZ::~vtkInteractiveChartXYZ()
{
  if(this->Colors != NULL)
    {
    delete [] this->Colors;
    this->Colors = NULL;
    }
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::Hit(const vtkContextMouseEvent &vtkNotUsed(mouse))
{
  // If we are interactive, we want to catch anything that propagates to the
  // background, otherwise we do not want any mouse events.
  return this->Interactive;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::MouseButtonPressEvent(const vtkContextMouseEvent &mouse)
{
  if (mouse.GetButton() == vtkContextMouseEvent::LEFT_BUTTON)
    {
    return true;
    }
  return false;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::MouseMoveEvent(const vtkContextMouseEvent &mouse)
{
  if (mouse.GetButton() == vtkContextMouseEvent::LEFT_BUTTON)
    {
    if (mouse.GetModifiers() == vtkContextMouseEvent::SHIFT_MODIFIER)
      {
      return this->Spin(mouse);
      }
    else
      {
      return this->Rotate(mouse);
      }
    }
  if (mouse.GetButton() == vtkContextMouseEvent::RIGHT_BUTTON)
    {
    if (mouse.GetModifiers() == vtkContextMouseEvent::SHIFT_MODIFIER)
      {
      return this->Pan(mouse);
      }
    else
      {
      return this->Zoom(mouse);
      }
    }
  return false;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::MouseWheelEvent(const vtkContextMouseEvent &mouse, int delta)
{
  // Ten "wheels" to double/halve zoom level
  float scaling = pow(2.0f, delta/10.0f);
  this->Scale->Scale(scaling, scaling, 0.0);

  // Mark the scene as dirty
  this->Scene->SetDirty(true);

  this->InvokeEvent(vtkCommand::InteractionEvent);
  return true;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::Rotate(const vtkContextMouseEvent &mouse)
{
  // Figure out how much the mouse has moved in plot coordinates
  vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData());
  vtkVector2d lastScreenPos(mouse.GetLastScreenPos().Cast<double>().GetData());

  double dx = screenPos[0] - lastScreenPos[0];
  double dy = screenPos[1] - lastScreenPos[1];

  double delta_elevation = -20.0 / this->Scene->GetSceneHeight();
  double delta_azimuth = -20.0 / this->Scene->GetSceneWidth();

  double rxf = dx * delta_azimuth * 10.0;
  double ryf = dy * delta_elevation * 10.0;

  this->Rotation->RotateY(-rxf);
  this->Rotation->RotateX(ryf);

  // Mark the scene as dirty
  this->Scene->SetDirty(true);

  this->InvokeEvent(vtkCommand::InteractionEvent);
  return true;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::Pan(const vtkContextMouseEvent &mouse)
{
  // Figure out how much the mouse has moved in plot coordinates
  vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData());
  vtkVector2d lastScreenPos(mouse.GetLastScreenPos().Cast<double>().GetData());

  double dx = (screenPos[0] - lastScreenPos[0]);
  double dy = (screenPos[1] - lastScreenPos[1]);

  this->Translation->Translate(dx, dy, 0.0);

  // Mark the scene as dirty
  this->Scene->SetDirty(true);

  this->InvokeEvent(vtkCommand::InteractionEvent);
  return true;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::Zoom(const vtkContextMouseEvent &mouse)
{
  // Figure out how much the mouse has moved and scale accordingly
  vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData());
  vtkVector2d lastScreenPos(mouse.GetLastScreenPos().Cast<double>().GetData());

  float delta = 0.0f;
  if (this->Scene->GetSceneHeight() > 0)
    {
    delta = static_cast<float>(mouse.GetLastScreenPos()[1] - mouse.GetScreenPos()[1])/this->Scene->GetSceneHeight();
    }

  // Dragging full screen height zooms 4x.
  float scaling = pow(4.0f, delta);
  this->Scale->Scale(scaling, scaling, 0.0);

  // Mark the scene as dirty
  this->Scene->SetDirty(true);

  this->InvokeEvent(vtkCommand::InteractionEvent);
  return true;
}

//-----------------------------------------------------------------------------
bool vtkInteractiveChartXYZ::Spin(const vtkContextMouseEvent &mouse)
{
  // Figure out how much the mouse has moved in plot coordinates
  vtkVector2d screenPos(mouse.GetScreenPos().Cast<double>().GetData());
  vtkVector2d lastScreenPos(mouse.GetLastScreenPos().Cast<double>().GetData());

  double newAngle =
    vtkMath::DegreesFromRadians(atan2(screenPos[1], screenPos[0]));
  double oldAngle =
    vtkMath::DegreesFromRadians(atan2(lastScreenPos[1], lastScreenPos[0]));

  this->Rotation->RotateZ(-(newAngle - oldAngle));

  // Mark the scene as dirty
  this->Scene->SetDirty(true);

  this->InvokeEvent(vtkCommand::InteractionEvent);
  return true;
}

void vtkInteractiveChartXYZ::CalculateTransforms()
{
  // First the rotation transform...
  // Calculate the correct translation vector before the rotation is applied
  vtkVector3f translation(
        (axes[0]->GetPosition2()[0] - axes[0]->GetPosition1()[0]) / 2.0
        + axes[0]->GetPosition1()[0],
        (axes[1]->GetPosition2()[1] - axes[1]->GetPosition1()[1]) / 2.0
        + axes[1]->GetPosition1()[1],
        (axes[2]->GetPosition2()[1] - axes[2]->GetPosition1()[1]) / 2.0
        + axes[2]->GetPosition1()[1]);
  vtkVector3f mtranslation = -1.0 * translation;

  this->ContextTransform->Identity();
  this->ContextTransform->Concatenate(this->Translation.GetPointer());
  this->ContextTransform->Translate(translation.GetData());
  this->ContextTransform->Concatenate(this->Rotation.GetPointer());
  this->ContextTransform->Concatenate(this->Scale.GetPointer());
  this->ContextTransform->Translate(mtranslation.GetData());
  this->ContextTransform->Concatenate(this->Transform.GetPointer());

  // Next the box rotation transform.
  double scale[3] = { 300, 300, 300 };
  for (int i = 0; i < 3; ++i)
    {
    if (i == 0)
      scale[i] = axes[i]->GetPosition2()[0] - axes[i]->GetPosition1()[0];
    else
      scale[i] = axes[i]->GetPosition2()[1] - axes[i]->GetPosition1()[1];
    }

  this->Box->Identity();
  this->Box->PostMultiply();
  this->Box->Translate(-0.5, -0.5, -0.5);
  this->Box->Concatenate(this->Rotation.GetPointer());
  this->Box->Concatenate(this->Scale.GetPointer());
  this->Box->Translate(0.5, 0.5, 0.5);
  this->Box->Scale(scale);
  this->Box->Translate(axes[0]->GetPosition1()[0],
                       axes[1]->GetPosition1()[1],
                       axes[2]->GetPosition1()[1]);
  this->Box->Concatenate(this->Translation.GetPointer());
}
<|endoftext|>


<commit_before>#include <iostream>

#include "Table.h"
#include "Logger.h"

// MJG FLAG Indexing not currently supported

// -----------------------------------------------------------------------
// constructors
Table::Table(table_name name)
{
  name_ = name;
  defined_ = false;
};

// -----------------------------------------------------------------------
// setter functions
void Table::setPrimaryKey(column const col)
{
  setPrimaryKey(col.first);
}

void Table::setPrimaryKey(std::string const pk_string)
{
  primary_key pk;
  pk.push_back(pk_string);
  this->setPrimaryKey(pk);
}

void Table::tableDefined()
{
  defined_ = true;
  std::cout << "Table " << name_ << " is defined." << std::endl;
  LOG(LEV_DEBUG5,"table") << "Table is defined with creation command: "
			  << this->create();
}
// -----------------------------------------------------------------------
// table creation functions
void Table::addForeignKey(foreign_key const fk){
  int key_size = fk.first.size();
  int ref_size = fk.second.second.size();
  if (key_size != ref_size){
    // throw error
    std::cout << "foreign key sizes don't match" << std::endl;
  }
  foreign_keys_.push_back(fk);
}

// add and insert row command
void Table::addRow(row const r){
  command *cmd = new command(""), *cols = new command(""), *values = new command("");
  int nEntries = r.size();
  for (int j = 0; j < nEntries; j++){
    (*cols) << r.at(j).first;
    (*values) << stringifyData(r.at(j).second);
    if (j < nEntries-1){
      (*cols) << ", ", (*values) << ", ";
    }
  }
  (*cmd) << "INSERT INTO " << this->name() << " (" << cols->str() << ") "
         << "VALUES (" << values->str() << ");";
  row_commands_.push_back(cmd);
  LOG(LEV_DEBUG5,"table") << "Added command to row commands: " << cmd->str();
}

// update rows
void Table::updateRow(primary_key_ref const pkref, entry const e){
  command *cmd = new command("");
  command data("");
  (*cmd) << "UPDATE " << this->name() << " ";
  (*cmd) << "SET " << e.first << "=" << stringifyData(e.second) << " ";
  (*cmd) << "WHERE " << updateRowPK(pkref) << ";";
  row_commands_.push_back(cmd);
  LOG(LEV_DEBUG5, "table") << "Added command to row commands: " << cmd->str();
}
void Table::updateRow(primary_key_ref const pkref, row const r){
  int nEntries = r.size();
  for (int i = 0; i < nEntries; i++){
    this->updateRow(pkref,r.at(i));
  }
}
std::string Table::updateRowPK(primary_key_ref const pkref){
  command cmd("");
  int nRefs = pkref.size();
  if (nRefs > 0){
    for (int i = 0; i < nRefs; i++){
      cmd << pkref.at(i).first << "=" << stringifyData(pkref.at(i).second);
      if (i < nRefs-1)
        cmd << " AND ";
    }
  }
  return cmd.str();
}

// -----------------------------------------------------------------------
// table query strings

// foreign keys
std::string Table::f_keys(){
  // create a the foreign keys statement
  command final_cmd("");
  int nKeys = foreign_keys_.size();
  // if there are no foreign keys, return an empty command
  if (nKeys > 0){
    for (int i = 0; i < nKeys; i++){
      // get key and reference information
      foreign_key fKey = foreign_keys_.at(i);
      foreign_key_ref fKey_ref = fKey.second;
      table_name refTable = fKey_ref.first;

      // construct the foreign key command
      command fKey_cmd("");
      command keys("");      // column names from this table
      command refKeys("");   // column names from the reference table

      // collect the column names for this table and the ref table
      int nKey_Cols = fKey.first.size();
      for (int j = 0; j < nKey_Cols; j++){
	col_name key = fKey.first.at(j);
	col_name refKey = fKey_ref.second.at(j);
	keys << key;
	refKeys << refKey;
	// comma deliminate until last entry
	if (j < nKey_Cols-1){
	  keys << ", ";
	  refKeys << ", ";
	}
      }

      // construct the foreign key command
      fKey_cmd << "FOREIGN KEY (" << keys.str() << ") REFERENCES "
	       << refTable << "(" << refKeys.str() << ")";
      // comma deliminate until last entry
      if (i < nKeys -1) {
	fKey_cmd << ", ";
      }
      final_cmd << fKey_cmd.str();
    }
  }
  return final_cmd.str();
}

// primary key
std::string Table::p_key(){
  // create a the primary key statement
  command cmd("");
  int nCols = primary_key_.size();
  // if there is no primary key, return an empty command
  if (nCols > 0){
    cmd << "PRIMARY KEY (";
    // for each column, add the column name to the key
    // and comma separate entries
    for(std::vector<col_name>::iterator name = primary_key_.begin();
	name != primary_key_.end();
	++name) {
      cmd << *name;
      // if this is the last entry, do not comma separate
      if (name != primary_key_.end() - 1)
	cmd << ", ";
    }
    // close the primary key command
    cmd << ")";
  }
  return cmd.str();
}

// create table
std::string Table::create(){
  // create a table using this table's name
  command cmd("");
  cmd << "CREATE TABLE " << this->name() <<" (";
  // for each entry, add the column name and data type
  // and comma separate entries
  for(std::vector<column>::iterator col = columns_.begin();
      col != columns_.end();
      ++col) {
    // add the column and data type to the command
    cmd << col->first << " " << col->second;
    // if this is the last entry, do not comma separate
    if (col != columns_.end() - 1)
      cmd << ", ";
  }
  // add primary keys
  if (primary_key_.size() > 0)
    cmd << ", " << this->p_key();
  // add foreign keys
  if (foreign_keys_.size() > 0)
    cmd << ", " << this->f_keys();
  // close the create table command
  cmd << ");";

  // return a stringified version of the command
  //std::cout << "Command to execute: \n     " << cmd.str() << std::endl;
  return cmd.str();
}

// write rows
std::string Table::writeRows(){
  // compile all row commands into a single command
  command cmd("");
  int nCmds = row_commands_.size();
  for (int i = 0; i < nCmds; i++){
    cmd << row_commands_.at(i)->str();
    if (i < nCmds-1)
      cmd << " ";
  }
  // return a stringified version of the command
  //std::cout << "Command to execute: \n     " << cmd.str() << std::endl;
  return cmd.str();
}

// some private utility functions
std::string Table::stringifyData(data const d){
  command data("");
  data << d;
  return data.str();
}
<commit_msg>cout statement taken out<commit_after>#include <iostream>

#include "Table.h"
#include "Logger.h"

// MJG FLAG Indexing not currently supported

// -----------------------------------------------------------------------
// constructors
Table::Table(table_name name)
{
  name_ = name;
  defined_ = false;
};

// -----------------------------------------------------------------------
// setter functions
void Table::setPrimaryKey(column const col)
{
  setPrimaryKey(col.first);
}

void Table::setPrimaryKey(std::string const pk_string)
{
  primary_key pk;
  pk.push_back(pk_string);
  this->setPrimaryKey(pk);
}

void Table::tableDefined()
{
  defined_ = true;
  LOG(LEV_DEBUG5,"table") << "Table is defined with creation command: "
			  << this->create();
}
// -----------------------------------------------------------------------
// table creation functions
void Table::addForeignKey(foreign_key const fk){
  int key_size = fk.first.size();
  int ref_size = fk.second.second.size();
  if (key_size != ref_size){
    // throw error
    std::cout << "foreign key sizes don't match" << std::endl;
  }
  foreign_keys_.push_back(fk);
}

// add and insert row command
void Table::addRow(row const r){
  command *cmd = new command(""), *cols = new command(""), *values = new command("");
  int nEntries = r.size();
  for (int j = 0; j < nEntries; j++){
    (*cols) << r.at(j).first;
    (*values) << stringifyData(r.at(j).second);
    if (j < nEntries-1){
      (*cols) << ", ", (*values) << ", ";
    }
  }
  (*cmd) << "INSERT INTO " << this->name() << " (" << cols->str() << ") "
         << "VALUES (" << values->str() << ");";
  row_commands_.push_back(cmd);
  LOG(LEV_DEBUG5,"table") << "Added command to row commands: " << cmd->str();
}

// update rows
void Table::updateRow(primary_key_ref const pkref, entry const e){
  command *cmd = new command("");
  command data("");
  (*cmd) << "UPDATE " << this->name() << " ";
  (*cmd) << "SET " << e.first << "=" << stringifyData(e.second) << " ";
  (*cmd) << "WHERE " << updateRowPK(pkref) << ";";
  row_commands_.push_back(cmd);
  LOG(LEV_DEBUG5, "table") << "Added command to row commands: " << cmd->str();
}
void Table::updateRow(primary_key_ref const pkref, row const r){
  int nEntries = r.size();
  for (int i = 0; i < nEntries; i++){
    this->updateRow(pkref,r.at(i));
  }
}
std::string Table::updateRowPK(primary_key_ref const pkref){
  command cmd("");
  int nRefs = pkref.size();
  if (nRefs > 0){
    for (int i = 0; i < nRefs; i++){
      cmd << pkref.at(i).first << "=" << stringifyData(pkref.at(i).second);
      if (i < nRefs-1)
        cmd << " AND ";
    }
  }
  return cmd.str();
}

// -----------------------------------------------------------------------
// table query strings

// foreign keys
std::string Table::f_keys(){
  // create a the foreign keys statement
  command final_cmd("");
  int nKeys = foreign_keys_.size();
  // if there are no foreign keys, return an empty command
  if (nKeys > 0){
    for (int i = 0; i < nKeys; i++){
      // get key and reference information
      foreign_key fKey = foreign_keys_.at(i);
      foreign_key_ref fKey_ref = fKey.second;
      table_name refTable = fKey_ref.first;

      // construct the foreign key command
      command fKey_cmd("");
      command keys("");      // column names from this table
      command refKeys("");   // column names from the reference table

      // collect the column names for this table and the ref table
      int nKey_Cols = fKey.first.size();
      for (int j = 0; j < nKey_Cols; j++){
	col_name key = fKey.first.at(j);
	col_name refKey = fKey_ref.second.at(j);
	keys << key;
	refKeys << refKey;
	// comma deliminate until last entry
	if (j < nKey_Cols-1){
	  keys << ", ";
	  refKeys << ", ";
	}
      }

      // construct the foreign key command
      fKey_cmd << "FOREIGN KEY (" << keys.str() << ") REFERENCES "
	       << refTable << "(" << refKeys.str() << ")";
      // comma deliminate until last entry
      if (i < nKeys -1) {
	fKey_cmd << ", ";
      }
      final_cmd << fKey_cmd.str();
    }
  }
  return final_cmd.str();
}

// primary key
std::string Table::p_key(){
  // create a the primary key statement
  command cmd("");
  int nCols = primary_key_.size();
  // if there is no primary key, return an empty command
  if (nCols > 0){
    cmd << "PRIMARY KEY (";
    // for each column, add the column name to the key
    // and comma separate entries
    for(std::vector<col_name>::iterator name = primary_key_.begin();
	name != primary_key_.end();
	++name) {
      cmd << *name;
      // if this is the last entry, do not comma separate
      if (name != primary_key_.end() - 1)
	cmd << ", ";
    }
    // close the primary key command
    cmd << ")";
  }
  return cmd.str();
}

// create table
std::string Table::create(){
  // create a table using this table's name
  command cmd("");
  cmd << "CREATE TABLE " << this->name() <<" (";
  // for each entry, add the column name and data type
  // and comma separate entries
  for(std::vector<column>::iterator col = columns_.begin();
      col != columns_.end();
      ++col) {
    // add the column and data type to the command
    cmd << col->first << " " << col->second;
    // if this is the last entry, do not comma separate
    if (col != columns_.end() - 1)
      cmd << ", ";
  }
  // add primary keys
  if (primary_key_.size() > 0)
    cmd << ", " << this->p_key();
  // add foreign keys
  if (foreign_keys_.size() > 0)
    cmd << ", " << this->f_keys();
  // close the create table command
  cmd << ");";

  // return a stringified version of the command
  //std::cout << "Command to execute: \n     " << cmd.str() << std::endl;
  return cmd.str();
}

// write rows
std::string Table::writeRows(){
  // compile all row commands into a single command
  command cmd("");
  int nCmds = row_commands_.size();
  for (int i = 0; i < nCmds; i++){
    cmd << row_commands_.at(i)->str();
    if (i < nCmds-1)
      cmd << " ";
  }
  // return a stringified version of the command
  //std::cout << "Command to execute: \n     " << cmd.str() << std::endl;
  return cmd.str();
}

// some private utility functions
std::string Table::stringifyData(data const d){
  command data("");
  data << d;
  return data.str();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: global.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-26 14:28:43 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _RTL_OSTRINGBUFFER_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef     _OSL_THREAD_H_
#include    <osl/thread.h>
#endif
#ifndef     _OSL_FILE_HXX_
#include    <osl/file.hxx>
#endif

#include <stdlib.h>
#include <stdio.h>
#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif

#ifdef UNX
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#endif

#ifndef _CODEMAKER_GLOBAL_HXX_
#include    <codemaker/global.hxx>
#endif

#ifdef SAL_UNX
#define SEPARATOR '/'
#else
#define SEPARATOR '\\'
#endif

using namespace ::rtl;
using namespace ::osl;

OString makeTempName(sal_Char* prefix)
{
    static OUString uTMP( RTL_CONSTASCII_USTRINGPARAM("TMP") );
    static OUString uTEMP( RTL_CONSTASCII_USTRINGPARAM("TEMP") );
    OUString        uPrefix( RTL_CONSTASCII_USTRINGPARAM("cmk_") );
    OUString        uPattern;

    sal_Char*   pPrefix = "cmk_";
    sal_Char    tmpPattern[512];
    sal_Char    *pTmpName = NULL;

    if (prefix)
        pPrefix = prefix;

    if ( osl_getEnvironment(uTMP.pData, &uPattern.pData) != osl_Process_E_None )
    {
        if ( osl_getEnvironment(uTEMP.pData, &uPattern.pData) != osl_Process_E_None )
        {
#if defined(SAL_W32) || defined(SAL_OS2)
            OSL_ASSERT( sizeof(tmpPattern) > RTL_CONSTASCII_LENGTH( "." ) );
            strncpy(tmpPattern, ".", sizeof(tmpPattern)-1);
#else
            OSL_ASSERT( sizeof(tmpPattern) > RTL_CONSTASCII_LENGTH( "/tmp" ) );
            strncpy(tmpPattern, "/tmp", sizeof(tmpPattern)-1);
#endif
        }
    }

    if (uPattern.getLength())
    {
        OString aOStr( OUStringToOString(uPattern, RTL_TEXTENCODING_UTF8) );
        OSL_ASSERT( sizeof(tmpPattern) > aOStr.getLength() );
        strncpy(tmpPattern, aOStr.getStr(), sizeof(tmpPattern)-1);
    }

#ifdef SAL_W32
    OSL_ASSERT( sizeof(tmpPattern) > ( strlen(tmpPattern)
                                       + RTL_CONSTASCII_LENGTH("\\")
                                       + strlen(pPrefix)
                                       + RTL_CONSTASCII_LENGTH("XXXXXX") ) );
    strncat(tmpPattern, "\\", sizeof(tmpPattern)-1-strlen(tmpPattern));
    strncat(tmpPattern, pPrefix, sizeof(tmpPattern)-1-strlen(tmpPattern));
    strncat(tmpPattern, "XXXXXX", sizeof(tmpPattern)-1-strlen(tmpPattern));
    pTmpName = mktemp(tmpPattern);
#endif

#ifdef SAL_OS2
    char* tmpname = tempnam(NULL, prefix);
    OSL_ASSERT( sizeof(tmpPattern) > strlen(tmpname) );
    strncpy(tmpPattern, tmpname, sizeof(tmpPattern)-1);
    pTmpName = tmpPattern;
#endif

#ifdef SAL_UNX
    OSL_ASSERT( sizeof(tmpPattern) > ( strlen(tmpPattern)
                                       + RTL_CONSTASCII_LENGTH("/")
                                       + strlen(pPrefix)
                                       + RTL_CONSTASCII_LENGTH("XXXXXX") ) );
    strncat(tmpPattern, "/", sizeof(tmpPattern)-1-strlen(tmpPattern));
    strncat(tmpPattern, pPrefix, sizeof(tmpPattern)-1-strlen(tmpPattern));
    strncat(tmpPattern, "XXXXXX", sizeof(tmpPattern)-1-strlen(tmpPattern));
    pTmpName = mktemp(tmpPattern);
#endif

    return OString(pTmpName);
}

OString createFileNameFromType( const OString& destination,
                                const OString typeName,
                                const OString postfix,
                                sal_Bool bLowerCase,
                                const OString prefix )
{
    OString type(typeName);

    if (bLowerCase)
    {
        type = typeName.toAsciiLowerCase();
    }

    sal_uInt32 length = destination.getLength();

    sal_Bool withPoint = sal_False;
    if (length == 0)
    {
        length++;
        withPoint = sal_True;
    }

    length += prefix.getLength() + type.getLength() + postfix.getLength();

    sal_Bool withSeperator = sal_False;
    if (destination.getStr()[destination.getLength()] != '\\' &&
        destination.getStr()[destination.getLength()] != '/' &&
        type.getStr()[0] != '\\' &&
        type.getStr()[0] != '/')
    {
        length++;
        withSeperator = sal_True;
    }

    OStringBuffer nameBuffer(length);

    if (withPoint)
        nameBuffer.append('.');
    else
        nameBuffer.append(destination.getStr(), destination.getLength());

    if (withSeperator)
        nameBuffer.append("/", 1);

    OString tmpStr(type);
    if (prefix.getLength() > 0)
    {
        tmpStr = type.replaceAt(type.lastIndexOf('/')+1, 0, prefix);
    }

    nameBuffer.append(tmpStr.getStr(), tmpStr.getLength());
    nameBuffer.append(postfix.getStr(), postfix.getLength());

    OString fileName(nameBuffer);

    sal_Char token;
#ifdef SAL_UNX
    fileName = fileName.replace('\\', '/');
    token = '/';
#else
    fileName = fileName.replace('/', '\\');
    token = '\\';
#endif

    nameBuffer = OStringBuffer(length);

    sal_Int32 nIndex = 0;
    do
    {
        nameBuffer.append(fileName.getToken( 0, token, nIndex ).getStr());

        if (nameBuffer.getLength() == 0 || OString(".") == nameBuffer.getStr())
        {
            nameBuffer.append(token);
            continue;
        }

#ifdef SAL_UNX
        if (mkdir((char*)nameBuffer.getStr(), 0777) == -1)
#else
           if (mkdir((char*)nameBuffer.getStr()) == -1)
#endif
        {
            if ( errno == ENOENT )
                return OString();
        }

        nameBuffer.append(token);
    }
    while ( nIndex >= 0 );

    return fileName;
}

sal_Bool fileExists(const OString& fileName)
{
    FILE  *f= fopen(fileName.getStr(), "r");

    if (f != NULL)
    {
        fclose(f);
        return sal_True;
    }

    return sal_False;
}

sal_Bool checkFileContent(const OString& targetFileName, const OString& tmpFileName)
{
    FILE  *target = fopen(targetFileName.getStr(), "r");
    FILE  *tmp = fopen(tmpFileName.getStr(), "r");
    sal_Bool ret = sal_False;

    if (target != NULL && tmp != NULL)
    {
        sal_Bool    bFindChanges = sal_False;
        sal_Char    buffer1[1024+1];
        sal_Char    buffer2[1024+1];
        sal_Int32   n1 = 0;
        sal_Int32   n2 = 0;

        while ( !bFindChanges && !feof(target) && !feof(tmp))
        {
            n1 = fread(buffer1, sizeof(sal_Char), 1024, target);
            n2 = fread(buffer2, sizeof(sal_Char), 1024, tmp);

            if ( n1 != n2 )
            {
                bFindChanges = sal_True;
            }
            else
            {
                if ( rtl_compareMemory(buffer1, buffer2, n2) != 0 )
                    bFindChanges =  sal_True;
            }
        }

        fclose(target);
        fclose(tmp);

        if ( bFindChanges )
        {
            if ( !unlink(targetFileName.getStr()) )
                if ( !rename(tmpFileName.getStr(), targetFileName.getStr()) )
                    ret = sal_True;
        }
        else
        {
            if ( !unlink(tmpFileName.getStr()) )
                ret = sal_True;
        }
    }

    return ret;
}

const OString inGlobalSet(const OUString & rValue)
{
    OString sValue( OUStringToOString(rValue, RTL_TEXTENCODING_UTF8) );
    static StringSet aGlobalMap;
    StringSet::iterator iter = aGlobalMap.find( sValue );
    if( iter != aGlobalMap.end() )
        return *iter;
    return *(aGlobalMap.insert( sValue ).first);
}

static sal_Bool isFileUrl(const OString& fileName)
{
    if (fileName.indexOf("file://") == 0 )
        return sal_True;
    return sal_False;
}

OUString convertToFileUrl(const OString& fileName)
{
    if ( isFileUrl(fileName) )
    {
        return OStringToOUString(fileName, osl_getThreadTextEncoding());
    }

    OUString uUrlFileName;
    OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
    if ( fileName.indexOf('.') == 0 || fileName.indexOf(SEPARATOR) < 0 )
    {
        OUString uWorkingDir;
        OSL_VERIFY( osl_getProcessWorkingDir(&uWorkingDir.pData) == osl_Process_E_None );
        OSL_VERIFY( FileBase::getAbsoluteFileURL(uWorkingDir, uFileName, uUrlFileName) == FileBase::E_None );
    } else
    {
        OSL_VERIFY( FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName) == FileBase::E_None );
    }

    return uUrlFileName;
}

//*************************************************************************
// FileStream
//*************************************************************************
FileStream::FileStream()
{
}

FileStream::FileStream(const OString& name, FileAccessMode mode)
    : m_pFile(NULL)
{
    if ( name.getLength() > 0 )
    {
        m_name = name;
        m_pFile = fopen(m_name, checkAccessMode(mode));
    }
}

FileStream::~FileStream()
{
    if ( isValid() )
    {
        fflush(m_pFile);
        fclose(m_pFile);
    }
}

sal_Bool FileStream::isValid()
{
    if ( m_pFile )
        return sal_True;

    return sal_False;
}

void FileStream::open(const OString& name, FileAccessMode mode)
{
    if ( name.getLength() > 0 )
    {
        m_name = name;
        m_pFile = fopen(m_name, checkAccessMode(mode));
    }
}

void FileStream::close()
{
    if ( isValid() )
    {
        fflush(m_pFile);
        fclose(m_pFile);
        m_pFile = NULL;
        m_name = OString();
    }
}

sal_Int32 FileStream::getSize()
{
    sal_Int32 pos = 0;
    sal_Int32 size = 0;
    if ( isValid() )
    {
        fflush(m_pFile);
        pos = ftell(m_pFile);
        if (!fseek(m_pFile, 0, SEEK_END))
            size = ftell(m_pFile);
        fseek(m_pFile, pos, SEEK_SET);
    }
    return size;
}

const sal_Char* FileStream::checkAccessMode(FileAccessMode mode)
{
    switch( mode )
    {
    case FAM_READ:
        return "r";
    case FAM_WRITE:
        return "w";
    case FAM_APPEND:
        return "a";
    case FAM_READWRITE_EXIST:
        return "r+";
    case FAM_READWRITE:
        return "w+";
    case FAM_READAPPEND:
        return "a+";
    }
    return "w+";
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.9.78); FILE MERGED 2005/09/05 17:42:12 rt 1.9.78.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: global.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:03:57 $
 *
 *  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 _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _RTL_OSTRINGBUFFER_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef     _OSL_THREAD_H_
#include    <osl/thread.h>
#endif
#ifndef     _OSL_FILE_HXX_
#include    <osl/file.hxx>
#endif

#include <stdlib.h>
#include <stdio.h>
#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif

#ifdef UNX
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#endif

#ifndef _CODEMAKER_GLOBAL_HXX_
#include    <codemaker/global.hxx>
#endif

#ifdef SAL_UNX
#define SEPARATOR '/'
#else
#define SEPARATOR '\\'
#endif

using namespace ::rtl;
using namespace ::osl;

OString makeTempName(sal_Char* prefix)
{
    static OUString uTMP( RTL_CONSTASCII_USTRINGPARAM("TMP") );
    static OUString uTEMP( RTL_CONSTASCII_USTRINGPARAM("TEMP") );
    OUString        uPrefix( RTL_CONSTASCII_USTRINGPARAM("cmk_") );
    OUString        uPattern;

    sal_Char*   pPrefix = "cmk_";
    sal_Char    tmpPattern[512];
    sal_Char    *pTmpName = NULL;

    if (prefix)
        pPrefix = prefix;

    if ( osl_getEnvironment(uTMP.pData, &uPattern.pData) != osl_Process_E_None )
    {
        if ( osl_getEnvironment(uTEMP.pData, &uPattern.pData) != osl_Process_E_None )
        {
#if defined(SAL_W32) || defined(SAL_OS2)
            OSL_ASSERT( sizeof(tmpPattern) > RTL_CONSTASCII_LENGTH( "." ) );
            strncpy(tmpPattern, ".", sizeof(tmpPattern)-1);
#else
            OSL_ASSERT( sizeof(tmpPattern) > RTL_CONSTASCII_LENGTH( "/tmp" ) );
            strncpy(tmpPattern, "/tmp", sizeof(tmpPattern)-1);
#endif
        }
    }

    if (uPattern.getLength())
    {
        OString aOStr( OUStringToOString(uPattern, RTL_TEXTENCODING_UTF8) );
        OSL_ASSERT( sizeof(tmpPattern) > aOStr.getLength() );
        strncpy(tmpPattern, aOStr.getStr(), sizeof(tmpPattern)-1);
    }

#ifdef SAL_W32
    OSL_ASSERT( sizeof(tmpPattern) > ( strlen(tmpPattern)
                                       + RTL_CONSTASCII_LENGTH("\\")
                                       + strlen(pPrefix)
                                       + RTL_CONSTASCII_LENGTH("XXXXXX") ) );
    strncat(tmpPattern, "\\", sizeof(tmpPattern)-1-strlen(tmpPattern));
    strncat(tmpPattern, pPrefix, sizeof(tmpPattern)-1-strlen(tmpPattern));
    strncat(tmpPattern, "XXXXXX", sizeof(tmpPattern)-1-strlen(tmpPattern));
    pTmpName = mktemp(tmpPattern);
#endif

#ifdef SAL_OS2
    char* tmpname = tempnam(NULL, prefix);
    OSL_ASSERT( sizeof(tmpPattern) > strlen(tmpname) );
    strncpy(tmpPattern, tmpname, sizeof(tmpPattern)-1);
    pTmpName = tmpPattern;
#endif

#ifdef SAL_UNX
    OSL_ASSERT( sizeof(tmpPattern) > ( strlen(tmpPattern)
                                       + RTL_CONSTASCII_LENGTH("/")
                                       + strlen(pPrefix)
                                       + RTL_CONSTASCII_LENGTH("XXXXXX") ) );
    strncat(tmpPattern, "/", sizeof(tmpPattern)-1-strlen(tmpPattern));
    strncat(tmpPattern, pPrefix, sizeof(tmpPattern)-1-strlen(tmpPattern));
    strncat(tmpPattern, "XXXXXX", sizeof(tmpPattern)-1-strlen(tmpPattern));
    pTmpName = mktemp(tmpPattern);
#endif

    return OString(pTmpName);
}

OString createFileNameFromType( const OString& destination,
                                const OString typeName,
                                const OString postfix,
                                sal_Bool bLowerCase,
                                const OString prefix )
{
    OString type(typeName);

    if (bLowerCase)
    {
        type = typeName.toAsciiLowerCase();
    }

    sal_uInt32 length = destination.getLength();

    sal_Bool withPoint = sal_False;
    if (length == 0)
    {
        length++;
        withPoint = sal_True;
    }

    length += prefix.getLength() + type.getLength() + postfix.getLength();

    sal_Bool withSeperator = sal_False;
    if (destination.getStr()[destination.getLength()] != '\\' &&
        destination.getStr()[destination.getLength()] != '/' &&
        type.getStr()[0] != '\\' &&
        type.getStr()[0] != '/')
    {
        length++;
        withSeperator = sal_True;
    }

    OStringBuffer nameBuffer(length);

    if (withPoint)
        nameBuffer.append('.');
    else
        nameBuffer.append(destination.getStr(), destination.getLength());

    if (withSeperator)
        nameBuffer.append("/", 1);

    OString tmpStr(type);
    if (prefix.getLength() > 0)
    {
        tmpStr = type.replaceAt(type.lastIndexOf('/')+1, 0, prefix);
    }

    nameBuffer.append(tmpStr.getStr(), tmpStr.getLength());
    nameBuffer.append(postfix.getStr(), postfix.getLength());

    OString fileName(nameBuffer);

    sal_Char token;
#ifdef SAL_UNX
    fileName = fileName.replace('\\', '/');
    token = '/';
#else
    fileName = fileName.replace('/', '\\');
    token = '\\';
#endif

    nameBuffer = OStringBuffer(length);

    sal_Int32 nIndex = 0;
    do
    {
        nameBuffer.append(fileName.getToken( 0, token, nIndex ).getStr());

        if (nameBuffer.getLength() == 0 || OString(".") == nameBuffer.getStr())
        {
            nameBuffer.append(token);
            continue;
        }

#ifdef SAL_UNX
        if (mkdir((char*)nameBuffer.getStr(), 0777) == -1)
#else
           if (mkdir((char*)nameBuffer.getStr()) == -1)
#endif
        {
            if ( errno == ENOENT )
                return OString();
        }

        nameBuffer.append(token);
    }
    while ( nIndex >= 0 );

    return fileName;
}

sal_Bool fileExists(const OString& fileName)
{
    FILE  *f= fopen(fileName.getStr(), "r");

    if (f != NULL)
    {
        fclose(f);
        return sal_True;
    }

    return sal_False;
}

sal_Bool checkFileContent(const OString& targetFileName, const OString& tmpFileName)
{
    FILE  *target = fopen(targetFileName.getStr(), "r");
    FILE  *tmp = fopen(tmpFileName.getStr(), "r");
    sal_Bool ret = sal_False;

    if (target != NULL && tmp != NULL)
    {
        sal_Bool    bFindChanges = sal_False;
        sal_Char    buffer1[1024+1];
        sal_Char    buffer2[1024+1];
        sal_Int32   n1 = 0;
        sal_Int32   n2 = 0;

        while ( !bFindChanges && !feof(target) && !feof(tmp))
        {
            n1 = fread(buffer1, sizeof(sal_Char), 1024, target);
            n2 = fread(buffer2, sizeof(sal_Char), 1024, tmp);

            if ( n1 != n2 )
            {
                bFindChanges = sal_True;
            }
            else
            {
                if ( rtl_compareMemory(buffer1, buffer2, n2) != 0 )
                    bFindChanges =  sal_True;
            }
        }

        fclose(target);
        fclose(tmp);

        if ( bFindChanges )
        {
            if ( !unlink(targetFileName.getStr()) )
                if ( !rename(tmpFileName.getStr(), targetFileName.getStr()) )
                    ret = sal_True;
        }
        else
        {
            if ( !unlink(tmpFileName.getStr()) )
                ret = sal_True;
        }
    }

    return ret;
}

const OString inGlobalSet(const OUString & rValue)
{
    OString sValue( OUStringToOString(rValue, RTL_TEXTENCODING_UTF8) );
    static StringSet aGlobalMap;
    StringSet::iterator iter = aGlobalMap.find( sValue );
    if( iter != aGlobalMap.end() )
        return *iter;
    return *(aGlobalMap.insert( sValue ).first);
}

static sal_Bool isFileUrl(const OString& fileName)
{
    if (fileName.indexOf("file://") == 0 )
        return sal_True;
    return sal_False;
}

OUString convertToFileUrl(const OString& fileName)
{
    if ( isFileUrl(fileName) )
    {
        return OStringToOUString(fileName, osl_getThreadTextEncoding());
    }

    OUString uUrlFileName;
    OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
    if ( fileName.indexOf('.') == 0 || fileName.indexOf(SEPARATOR) < 0 )
    {
        OUString uWorkingDir;
        OSL_VERIFY( osl_getProcessWorkingDir(&uWorkingDir.pData) == osl_Process_E_None );
        OSL_VERIFY( FileBase::getAbsoluteFileURL(uWorkingDir, uFileName, uUrlFileName) == FileBase::E_None );
    } else
    {
        OSL_VERIFY( FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName) == FileBase::E_None );
    }

    return uUrlFileName;
}

//*************************************************************************
// FileStream
//*************************************************************************
FileStream::FileStream()
{
}

FileStream::FileStream(const OString& name, FileAccessMode mode)
    : m_pFile(NULL)
{
    if ( name.getLength() > 0 )
    {
        m_name = name;
        m_pFile = fopen(m_name, checkAccessMode(mode));
    }
}

FileStream::~FileStream()
{
    if ( isValid() )
    {
        fflush(m_pFile);
        fclose(m_pFile);
    }
}

sal_Bool FileStream::isValid()
{
    if ( m_pFile )
        return sal_True;

    return sal_False;
}

void FileStream::open(const OString& name, FileAccessMode mode)
{
    if ( name.getLength() > 0 )
    {
        m_name = name;
        m_pFile = fopen(m_name, checkAccessMode(mode));
    }
}

void FileStream::close()
{
    if ( isValid() )
    {
        fflush(m_pFile);
        fclose(m_pFile);
        m_pFile = NULL;
        m_name = OString();
    }
}

sal_Int32 FileStream::getSize()
{
    sal_Int32 pos = 0;
    sal_Int32 size = 0;
    if ( isValid() )
    {
        fflush(m_pFile);
        pos = ftell(m_pFile);
        if (!fseek(m_pFile, 0, SEEK_END))
            size = ftell(m_pFile);
        fseek(m_pFile, pos, SEEK_SET);
    }
    return size;
}

const sal_Char* FileStream::checkAccessMode(FileAccessMode mode)
{
    switch( mode )
    {
    case FAM_READ:
        return "r";
    case FAM_WRITE:
        return "w";
    case FAM_APPEND:
        return "a";
    case FAM_READWRITE_EXIST:
        return "r+";
    case FAM_READWRITE:
        return "w+";
    case FAM_READAPPEND:
        return "a+";
    }
    return "w+";
}

<|endoftext|>


<commit_before>#include <stdio.h>

#include <Arduino.h>
#include "mode.h"
#include "main.h"
#include "res.h"

namespace {

JeopardyMode jeopardyMode;
BrainMode brainMode;

const int MODE_COUNT = 3;
Mode* modes[] = {&jeopardyMode, &brainMode};
const char* ids[] = {jeopardyLabel, brainLabel};
int selectedMode;

}  // namespace

void SelectMode::init() {
    selectedMode = 0;
}

bool SelectMode::getLedState(int playerId) {
    return false;
}

void SelectMode::getCaption(char* buffer, size_t bufferSize) {
    snprintf(buffer, bufferSize, modeLabel, ids[selectedMode]);
}

void SelectMode::getScore(char* buffer, size_t bufferSize) {
    buffer[0] = 0;
}

void SelectMode::getInfo(char* buffer, size_t bufferSize) {
    buffer[0] = 0;
}

bool SelectMode::preferShowScore() {
    return false;
}

const char* SelectMode::getLabel(int buttonId) {
    if (buttonId == BUTTON_RESET) {
        return leftLabel;
    } else if (buttonId == BUTTON_START)  {
        return rightLabel;
    } else if (buttonId == BUTTON_CONTROL_2) {
        return selectLabel;
    }
    return "";
}

void SelectMode::update() {
    if (isControlPressed(BUTTON_RESET)) {
        selectedMode--;
        if (selectedMode == -1) {
            selectedMode = MODE_COUNT - 1;
        }
    } else if (isControlPressed(BUTTON_CONTROL_2)) {
        setMode(modes[selectedMode]);
    } else if (isControlPressed(BUTTON_START)) {
        selectedMode++;
        if (selectedMode == MODE_COUNT) {
            selectedMode = 0;
        }
    }
}
<commit_msg>Bug fix<commit_after>#include <stdio.h>

#include <Arduino.h>
#include "mode.h"
#include "main.h"
#include "res.h"

namespace {

JeopardyMode jeopardyMode;
BrainMode brainMode;

const int MODE_COUNT = 2;
Mode* modes[] = {&jeopardyMode, &brainMode};
const char* ids[] = {jeopardyLabel, brainLabel};
int selectedMode;

}  // namespace

void SelectMode::init() {
    selectedMode = 0;
}

bool SelectMode::getLedState(int playerId) {
    return false;
}

void SelectMode::getCaption(char* buffer, size_t bufferSize) {
    snprintf(buffer, bufferSize, modeLabel, ids[selectedMode]);
}

void SelectMode::getScore(char* buffer, size_t bufferSize) {
    buffer[0] = 0;
}

void SelectMode::getInfo(char* buffer, size_t bufferSize) {
    buffer[0] = 0;
}

bool SelectMode::preferShowScore() {
    return false;
}

const char* SelectMode::getLabel(int buttonId) {
    if (buttonId == BUTTON_RESET) {
        return leftLabel;
    } else if (buttonId == BUTTON_START)  {
        return rightLabel;
    } else if (buttonId == BUTTON_CONTROL_2) {
        return selectLabel;
    }
    return "";
}

void SelectMode::update() {
    if (isControlPressed(BUTTON_RESET)) {
        selectedMode--;
        if (selectedMode == -1) {
            selectedMode = MODE_COUNT - 1;
        }
    } else if (isControlPressed(BUTTON_CONTROL_2)) {
        setMode(modes[selectedMode]);
    } else if (isControlPressed(BUTTON_START)) {
        selectedMode++;
        if (selectedMode == MODE_COUNT) {
            selectedMode = 0;
        }
    }
}
<|endoftext|>


<commit_before>#include <getopt.h>
#include <string>
#include <iostream>
#include "gfakluge.hpp"

using namespace std;
using namespace gfak;

void extract_help(char** argv){
    cout << "gfa_extract: extract a FASTA file from GFA" << endl
        << "Usage: gfa_extract [ -p ] <GFA_FILE> > file.fa " << endl
            << "-p / --include-paths  include paths in output (might be contigs?? We nevr know)" << endl
        << endl;
}

int main(int argc, char** argv){
    string gfa_file = "";
    bool include_paths = false;

    if (argc < 2){
        extract_help(argv);
        exit(0);
    }

    int c;
    optind = 1;
    while (true){
        static struct option long_options[] =
        {
            {"help", no_argument, 0, 'h'},
            {"inlude-paths", no_argument, 0, 'p'},
            {0,0,0,0}
        };

        int option_index = 0;
        c = getopt_long(argc, argv, "hp", long_options, &option_index);
        if (c == -1){
            break;
        }

        switch (c){
            case 'i':
                gfa_file = optarg;
                break;

            case '?':
            case 'h':
                extract_help(argv);
                exit(0);
            case 'p':
                include_paths= true;
                break;
            default:
                abort();
        }
    }
    gfa_file = argv[optind];

    GFAKluge gg;
    gg.parse_gfa_file(gfa_file);

    map<string, sequence_elem, custom_key> seqs = gg.get_name_to_seq();

    for (auto name_seq : seqs){
        cout << ">" << name_seq.second.name << endl
            << name_seq.second.sequence << endl
            << endl;
    }
    // Do the same for groups/walks/paths, as the concated
    // sequences of the oriented seq_elems create a path (e.g. a chromosome or contig)
    if (include_paths){
        for (auto p : gg.get_groups()){
            stringstream pstr;
            if (p.second.ordered){

                pstr << ">" << p.second.id << endl;
                for (int i = 0; i < p.second.items.size(); i++){
                    string seqname = p.second.items[i];
                    bool ori = p.second.orientations[i];
                    pstr << ( ori ? seqs[seqname].sequence : string((seqs[seqname]).sequence.rbegin(), (seqs[seqname]).sequence.rend()));
                }
                pstr << endl;
                cout << pstr.str() << endl;
                pstr.str("");
            }
        }
    }

	return 0;
}
<commit_msg>Remove external extract_main file<commit_after><|endoftext|>


<commit_before>
#include "client_base.hpp"
#include "server_base.hpp"
#include "broker.hpp"
#include "worker.hpp"
#include "util.hpp"
#include <string>
#include <thread> // std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
#include <mutex>
#include <future>

// this is the callback function of server
// typedef std::function<void(const char *, size_t, void *)> SERVER_CB_FUNC;
// this is the callback function of client
// typedef void USR_CB_FUNC(char *msg, size_t len, void *usr_data);
server_base st1;
worker_base wk1;
worker_base wk2;
worker_base wk3;
worker_base wk4;
std::mutex mtx;
int message_count;
int message_count_recv;
int64_t last_time;
int64_t total_msg;

size_t time_str(uint32_t secs, uint32_t msec, char *out_ptr, size_t sz)
{
    size_t len;           // String length
    time_t lsecs;         // Local secs value
    struct tm local_time; // Local timestamp

    // Convert seconds to a time value
    // Convert secs to the 32/64 bit format for this client
    lsecs = (time_t)secs;
    (void)localtime_r(&lsecs, &local_time);
    len = snprintf(out_ptr, sz, "%4u/%02u/%02u %02u:%02u:%02u.%03u",
                   local_time.tm_year + 1900,
                   local_time.tm_mon + 1,
                   local_time.tm_mday,
                   local_time.tm_hour,
                   local_time.tm_min,
                   local_time.tm_sec,
                   msec);

    if (len >= sz)
    {
        *(out_ptr + sz - 1) = '\0';
        len = sz;
    }

    return (len);
}

void logging_cb(const char *file_ptr, int line, const char *func_ptr, Logger::Level lev, const char *msg)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);

    char str_buff[256 + 1] = "";
    time_str(tv.tv_sec, tv.tv_usec, (char *)(&str_buff), 256);

    std::cout << std::dec << "+++ " << str_buff << " [" << Logger::logLevelString(lev) << "]: file: " << file_ptr << ", line: "
              << line << ", func: " << func_ptr << "\n"
              << msg << std::endl;
    return;
}

//std::lock_guard<std::mutex> lock(mtx);
void client_cb_001(const char *msg, size_t len, void *usr_data)
{
    #if 0
    message_count_recv++;
    total_msg += len;
 //   std::cout << std::dec <<"s_clock() is : "<<s_clock()<<" last_time is : " << last_time<< " s_clock() -last_time is : "<< s_clock() -last_time<<std::endl;

    if (last_time - s_clock() <= 10)
    {
        std::cout << std::dec << "\[ " << message_count_recv << " \] message per second, message rate " << (total_msg / 1000) << "kbps\r";

        last_time = s_clock() + 1000;
        total_msg = 0;
        message_count_recv = 0;
    }

#endif
    //std::cout << std::dec << "receive message form server : \"" << (std::string(msg, len)) << " \", len is : " << len << " , with user data : " << usr_data << " total message: " << message_count_recv++ << "\r"<<std::flush;
std::cout << std::dec <<" total message: " << message_count_recv++ << "\r"<<std::flush;
}
void server_cb_001(const char *data, size_t len, void *ID)
{
    //std::cout<<std::dec<< "receive message form client : " << (std::string(data, len)) << " total message: " << message_count++ << std::endl;
    st1.send(data, len, ID);
}

void worker_cb_001(const char *data, size_t len, void *ID)
{
    std::cout << std::dec << "receive message form client : " << (std::string(data, len)) << " total message: " << message_count++ << std::endl;
    wk1.send(data, len, ID);
}

void worker_cb_002(const char *data, size_t len, void *ID)
{
    std::cout << std::dec << "receive message form client : " << (std::string(data, len)) << " total message: " << message_count++ << std::endl;
    wk2.send(data, len, ID);
}

void worker_cb_003(const char *data, size_t len, void *ID)
{
    std::cout << std::dec << "receive message form client : " << (std::string(data, len)) << " total message: " << message_count++ << std::endl;
    wk3.send(data, len, ID);
}
void client_monitor_func(int event, int value, std::string &address)
{
    std::cout << std::dec << "receive event form client monitor task, the event is " << event << ". Value is : " << value << ". string is : " << address << "string length is : " << address.size() << std::endl;
}
void server_monitor_func(int event, int value, std::string &address)
{
    std::cout << std::dec << "receive event form server monitor task, the event is " << event << ". Value is : " << value << ". string is : " << address << std::endl;
}
int main(void)
{

    LogManager::getLogger(logging_cb)->setLevel(Logger::WARN); //ALL);
                                                               //LogManager::getLogger(logging_cb)->setLevel(Logger::ALL);

    //    logger->error(ZMQ_LOG, "hello world\n");
    /************this is DEALER <->ROUTER MODE ************/
#if 0
    {
        logger->error(ZMQ_LOG, " ************   this is DEALER<->ROUTER MODE************\n");
        last_time = s_clock() + 1000;
        st1.setIPPort("127.0.0.1:5571");
        st1.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        st1.set_cb(server_cb_001);
        st1.run();

        std::string test_str = "this is for test!";
        void *user_data = (void *)28;

        std::vector<client_base *> client_vector;
        for (int num = 0; num < 50; num++)
        {
            client_vector.emplace_back(new client_base());
        }
        for (auto tmp_client : client_vector)
        {
            tmp_client->set_monitor_cb(client_monitor_func);
            tmp_client->setIPPort("127.0.0.1:5571");
            tmp_client->run();
            //tmp_client->send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
        }
        while (1)
        {
            //getchar();
            std::this_thread::sleep_for(std::chrono::milliseconds(1));

            for (int i = 0; i < 10; i++)
            {
                for (auto tmp_client : client_vector)
                {
                    tmp_client->send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
                }
            }
        }
#if 0
        client_base ct1;
        ct1.set_monitor_cb(client_monitor_func);
        ct1.setIPPort("127.0.0.1:5571");
        //ct1.setIPPortSource("127.0.0.1:5578");

        client_base ct2;
        ct2.set_monitor_cb(client_monitor_func);
        ct2.setIPPort("127.0.0.1:5571");
        //    ct1.setIPPortSource("127.0.0.1:5577");

        st1.setIPPort("127.0.0.1:5571");
        st1.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        st1.set_cb(server_cb_001);

        ct1.run();
        ct2.run();

        st1.run();

        std::string test_str = "this is for test!";
        void *user_data = (void *)28;
        std::cout<<std::dec<< "send message : \"" << test_str << "\"  with usr data : " << user_data << std::endl;
        while (1)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
            for (int i = 0; i < 100; i++)
            {
                ct1.send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
                ct2.send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
            }
        }
#endif
        //std::this_thread::sleep_for(std::chrono::milliseconds(4000));
        //ct2.send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
        //ct1.stop();
    }

#endif
    /************   this is DEALER<->(RTOUTER<->DEALER)<->DEALER  mode************/
    {
        logger->error(ZMQ_LOG, " ************   this is DEALER<->(RTOUTER<->RTOUTER)<->DEALER  mode************\n");
        // test if the API is binary safe
        char tmp_str[20] = "this is for test!";
        tmp_str[2] = 0;
        std::string test_str(tmp_str, 20);
        void *user_data = (void *)28;
        // there will be three part
        // 1. client part
        // 2. broker part
        // 3. worker part

        // 1. client part
        logger->debug(ZMQ_LOG, "start client part now\n");
        client_base ct1;
        ct1.set_monitor_cb(client_monitor_func);
        ct1.setIPPort("127.0.0.1:5561");
        ct1.run();
        logger->debug(ZMQ_LOG, "start broker part now\n");
        // 2. broker part
        broker_base bk1;
        bk1.set_backtend_protocol("ipc://");
        bk1.set_backtend_IPPort("abcdefg");
        auto broker_fun = std::bind(&broker_base::run, &bk1);
        std::thread broker_t(broker_fun);
        //broker_t.detach();
        logger->debug(ZMQ_LOG, "start worker part now\n");
        // 3. worker part
        // "inproc://abcdefg"
        // for broker
        //void set_backtend_protocol(std::string protocol)
        //set_backtend_IPPort(std::string IPPort)
        // for worker
        //    void set_protocol(std::string protocol_)
        //    void setIPPort(std::string ipport)
        //wk1.setIPPort("127.0.0.1:5560");
        wk1.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        wk1.set_cb(worker_cb_001);

        wk1.set_protocol("ipc://");
        wk1.setIPPort("abcdefg");
        wk1.run();
        //std::this_thread::sleep_for(std::chrono::milliseconds(400));
        /*
        wk2.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        wk2.set_cb(worker_cb_002);
        wk2.run();
        //std::this_thread::sleep_for(std::chrono::milliseconds(400));

        wk3.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        wk3.set_cb(worker_cb_003);
        wk3.run();
        //std::this_thread::sleep_for(std::chrono::milliseconds(400));
*/
        for (int i = 0; i < 10; i++)
        {
            logger->debug(ZMQ_LOG, "send message now\n");
            std::this_thread::sleep_for(std::chrono::milliseconds(400));

            ct1.send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
        }
        while (1)
        {
            getchar();
            ct1.send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
        }
    }

#if 0
    {
        /************  test worker recovery  ************/
        logger->error(ZMQ_LOG, " ************   test worker recovery************\n");
        wk4.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        wk4.set_cb(worker_cb_001);
        // invalid IP Port
        wk4.setIPPort("127.0.0.1:12341");
        wk4.run();
        getchar();
    }
#endif
    return 0;
}
<commit_msg>new branch<commit_after>
#include "client_base.hpp"
#include "server_base.hpp"
#include "broker.hpp"
#include "worker.hpp"
#include "util.hpp"
#include <string>
#include <thread> // std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
#include <mutex>
#include <future>

// this is the callback function of server
// typedef std::function<void(const char *, size_t, void *)> SERVER_CB_FUNC;
// this is the callback function of client
// typedef void USR_CB_FUNC(char *msg, size_t len, void *usr_data);
server_base st1;
worker_base wk1;
worker_base wk2;
worker_base wk3;
worker_base wk4;
std::mutex mtx;
int message_count;
int message_count_recv;
int64_t last_time;
int64_t total_msg;

size_t time_str(uint32_t secs, uint32_t msec, char *out_ptr, size_t sz)
{
    size_t len;           // String length
    time_t lsecs;         // Local secs value
    struct tm local_time; // Local timestamp

    // Convert seconds to a time value
    // Convert secs to the 32/64 bit format for this client
    lsecs = (time_t)secs;
    (void)localtime_r(&lsecs, &local_time);
    len = snprintf(out_ptr, sz, "%4u/%02u/%02u %02u:%02u:%02u.%03u",
                   local_time.tm_year + 1900,
                   local_time.tm_mon + 1,
                   local_time.tm_mday,
                   local_time.tm_hour,
                   local_time.tm_min,
                   local_time.tm_sec,
                   msec);

    if (len >= sz)
    {
        *(out_ptr + sz - 1) = '\0';
        len = sz;
    }

    return (len);
}

void logging_cb(const char *file_ptr, int line, const char *func_ptr, Logger::Level lev, const char *msg)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);

    char str_buff[256 + 1] = "";
    time_str(tv.tv_sec, tv.tv_usec, (char *)(&str_buff), 256);

    std::cout << std::dec << "+++ " << str_buff << " [" << Logger::logLevelString(lev) << "]: file: " << file_ptr << ", line: "
              << line << ", func: " << func_ptr << "\n"
              << msg << std::endl;
    return;
}

//std::lock_guard<std::mutex> lock(mtx);
void client_cb_001(const char *msg, size_t len, void *usr_data)
{
#if 0
    message_count_recv++;
    total_msg += len;
 //   std::cout << std::dec <<"s_clock() is : "<<s_clock()<<" last_time is : " << last_time<< " s_clock() -last_time is : "<< s_clock() -last_time<<std::endl;

    if (last_time - s_clock() <= 10)
    {
        std::cout << std::dec << "\[ " << message_count_recv << " \] message per second, message rate " << (total_msg / 1000) << "kbps\r";

        last_time = s_clock() + 1000;
        total_msg = 0;
        message_count_recv = 0;
    }

#endif
    //std::cout << std::dec << "receive message form server : \"" << (std::string(msg, len)) << " \", len is : " << len << " , with user data : " << usr_data << " total message: " << message_count_recv++ << "\r"<<std::flush;
    std::cout << std::dec << " total message: " << message_count_recv++ << "\r" << std::flush;
}
void server_cb_001(const char *data, size_t len, void *ID)
{
    //std::cout<<std::dec<< "receive message form client : " << (std::string(data, len)) << " total message: " << message_count++ << std::endl;
    st1.send(data, len, ID);
}

void worker_cb_001(const char *data, size_t len, void *ID)
{
    std::cout << std::dec << "receive message form client : " << (std::string(data, len)) << " total message: " << message_count++ << std::endl;
    wk1.send(data, len, ID);
}

void worker_cb_002(const char *data, size_t len, void *ID)
{
    std::cout << std::dec << "receive message form client : " << (std::string(data, len)) << " total message: " << message_count++ << std::endl;
    wk2.send(data, len, ID);
}

void worker_cb_003(const char *data, size_t len, void *ID)
{
    std::cout << std::dec << "receive message form client : " << (std::string(data, len)) << " total message: " << message_count++ << std::endl;
    wk3.send(data, len, ID);
}
void client_monitor_func(int event, int value, std::string &address)
{
    std::cout << std::dec << "receive event form client monitor task, the event is " << event << ". Value is : " << value << ". string is : " << address << "string length is : " << address.size() << std::endl;
}
void server_monitor_func(int event, int value, std::string &address)
{
    std::cout << std::dec << "receive event form server monitor task, the event is " << event << ". Value is : " << value << ". string is : " << address << std::endl;
}
int main(void)
{

    LogManager::getLogger(logging_cb)->setLevel(Logger::WARN); //ALL);
                                                               //LogManager::getLogger(logging_cb)->setLevel(Logger::ALL);

//    logger->error(ZMQ_LOG, "hello world\n");
/************this is DEALER <->ROUTER MODE ************/
#if 0
    {
        logger->error(ZMQ_LOG, " ************   this is DEALER<->ROUTER MODE************\n");
        last_time = s_clock() + 1000;
        st1.setIPPort("127.0.0.1:5571");
        st1.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        st1.set_cb(server_cb_001);
        st1.run();

        std::string test_str = "this is for test!";
        void *user_data = (void *)28;

        std::vector<client_base *> client_vector;
        for (int num = 0; num < 50; num++)
        {
            client_vector.emplace_back(new client_base());
        }
        for (auto tmp_client : client_vector)
        {
            tmp_client->set_monitor_cb(client_monitor_func);
            tmp_client->setIPPort("127.0.0.1:5571");
            tmp_client->run();
            //tmp_client->send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
        }
        while (1)
        {
            //getchar();
            std::this_thread::sleep_for(std::chrono::milliseconds(1));

            for (int i = 0; i < 10; i++)
            {
                for (auto tmp_client : client_vector)
                {
                    tmp_client->send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
                }
            }
        }
#if 0
        client_base ct1;
        ct1.set_monitor_cb(client_monitor_func);
        ct1.setIPPort("127.0.0.1:5571");
        //ct1.setIPPortSource("127.0.0.1:5578");

        client_base ct2;
        ct2.set_monitor_cb(client_monitor_func);
        ct2.setIPPort("127.0.0.1:5571");
        //    ct1.setIPPortSource("127.0.0.1:5577");

        st1.setIPPort("127.0.0.1:5571");
        st1.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        st1.set_cb(server_cb_001);

        ct1.run();
        ct2.run();

        st1.run();

        std::string test_str = "this is for test!";
        void *user_data = (void *)28;
        std::cout<<std::dec<< "send message : \"" << test_str << "\"  with usr data : " << user_data << std::endl;
        while (1)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
            for (int i = 0; i < 100; i++)
            {
                ct1.send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
                ct2.send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
            }
        }
#endif
        //std::this_thread::sleep_for(std::chrono::milliseconds(4000));
        //ct2.send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
        //ct1.stop();
    }

#endif
    /************   this is DEALER<->(RTOUTER<->DEALER)<->DEALER  mode************/
    {
        logger->error(ZMQ_LOG, " ************   this is DEALER<->(RTOUTER<->RTOUTER)<->DEALER  mode************\n");
        // test if the API is binary safe
        char tmp_str[20] = "this is for test!";
        tmp_str[2] = 0;
        std::string test_str(tmp_str, 20);
        void *user_data = (void *)28;
        // there will be three part
        // 1. client part
        // 2. broker part
        // 3. worker part

        // 1. client part
        logger->debug(ZMQ_LOG, "start client part now\n");
        client_base ct1;
        ct1.set_monitor_cb(client_monitor_func);
        ct1.setIPPort("127.0.0.1:5561");
        ct1.run();
        logger->debug(ZMQ_LOG, "start broker part now\n");
        // 2. broker part
        broker_base bk1;
        bk1.set_backtend_protocol("ipc://");
        bk1.set_backtend_IPPort("abcdefg");
        auto broker_fun = std::bind(&broker_base::run, &bk1);
        std::thread broker_t(broker_fun);
        //broker_t.detach();
        logger->debug(ZMQ_LOG, "start worker part now\n");
        // 3. worker part
        // "inproc://abcdefg"
        // for broker
        //void set_backtend_protocol(std::string protocol)
        //set_backtend_IPPort(std::string IPPort)
        // for worker
        //    void set_protocol(std::string protocol_)
        //    void setIPPort(std::string ipport)
        //wk1.setIPPort("127.0.0.1:5560");
        wk1.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        wk1.set_cb(worker_cb_001);

        wk1.set_protocol("ipc://");
        wk1.setIPPort("abcdefg");
        wk1.run();
        //std::this_thread::sleep_for(std::chrono::milliseconds(400));
        /*
        wk2.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        wk2.set_cb(worker_cb_002);
        wk2.run();
        //std::this_thread::sleep_for(std::chrono::milliseconds(400));

        wk3.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        wk3.set_cb(worker_cb_003);
        wk3.run();
        //std::this_thread::sleep_for(std::chrono::milliseconds(400));
*/
        for (int i = 0; i < 10; i++)
        {
            logger->debug(ZMQ_LOG, "send message now\n");
            std::this_thread::sleep_for(std::chrono::milliseconds(400));

            ct1.send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
        }
        while (1)
        {
            getchar();
            ct1.send(user_data, client_cb_001, test_str.c_str(), size_t(test_str.size()));
        }
    }

#if 0
    {
        /************  test worker recovery  ************/
        logger->error(ZMQ_LOG, " ************   test worker recovery************\n");
        wk4.set_monitor_cb(server_monitor_func);
        // for server, you need to set callback function first
        wk4.set_cb(worker_cb_001);
        // invalid IP Port
        wk4.setIPPort("127.0.0.1:12341");
        wk4.run();
        getchar();
    }
#endif
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>delete old sample<commit_after><|endoftext|>