<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include "RenderWindow.h"
#include "ui_RenderWindow.h"
#include "Core/Datatypes/DenseMatrix.h"

#include <QVTKWidget.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkPolyDataMapper.h>
#include <vtkArrowSource.h>
#include <vtkVector.h>
#include <vtkMatrix3x3.h>
#include <vtkMatrix4x4.h>
#include <vtkTransform.h>
#include <vtkTextActor.h>
#include <vtkTextProperty.h>

using namespace SCIRun::Domain::Datatypes;

//-----------------------------------------------------------------------------
RenderWindow::RenderWindow(QWidget *parent) :
  QDialog(parent),
  ui(new Ui::RenderWindow),
  mVtkWidget(new QVTKWidget(this, QFlag(0)))
{
  ui->setupUi(this);

  // Add VTK widget to vertical layout.
  ui->verticalLayout->addWidget(mVtkWidget);
  ui->verticalLayout->update();

  // Create renderer
  mRen = vtkSmartPointer<vtkRenderer>::New();
  mVtkWidget->GetRenderWindow()->AddRenderer(mRen);
  mVtkWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
  //mRen->SetBackground(1.0,0.0,0.0);

  // Create arrow poly data
  mArrowSource = vtkSmartPointer<vtkArrowSource>::New();
  //arrowSource->SetShaftRadius(1.0);
  //arrowSource->SetTipLength(1.0);
  mArrowSource->Update();

  // Create data mapper (from visualization system to graphics system).
  mArrowMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  mArrowMapper->SetInputConnection(mArrowSource->GetOutputPort());

  //setupDefaultVectorField();
  setupHelixVectorField();

  setText("This is a vector field!");
}

//-----------------------------------------------------------------------------
RenderWindow::~RenderWindow()
{
  delete mVtkWidget;
  delete ui;
}

//-----------------------------------------------------------------------------
void RenderWindow::setupDefaultVectorField()
{
  // Read matrix and build scene with appropriate actors.
  const int numVecs = 6;
  double vpd[3][numVecs] = { // Vector position data
    { 0.0, 0.0, 0.0, 0.0, 1.0, 1.0 },
    { 0.0, 1.0, 0.0, 1.0, 1.0, 0.0 },
    { 0.0, 0.0, 1.0, 1.0, 0.0, 1.0 }
  };
  double vod[3][numVecs] = { // Vector orientation data
    { 1.0, 0.0, 0.0, 0.0, 1.0, 1.0 },
    { 0.0, 1.0, 0.0, 1.0, 1.0, 0.0 },
    { 0.0, 0.0, 1.0, 1.0, 0.0, 1.0 }
  };

  // Setup actors for each of the vectors...
  // There are better ways of representing vectors fields in VTK.

  // Need to construct 3x3 rotation matrices from orientation vector.
  for (int i = 0; i < numVecs; i++)
  {
    vtkSmartPointer<vtkTransform> orient = matFromVec(
        vtkVector3d(vod[0][i], vod[1][i], vod[2][i]),
        vtkVector3d(vpd[0][i], vpd[1][i], vpd[2][i]));

    vtkSmartPointer<vtkMatrix4x4> m = vtkSmartPointer<vtkMatrix4x4>::New();
    orient->GetMatrix(m);
    //m->Print(std::cout);

    // Now we have appropriate transformation data, build actor.
    vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
    actor->SetMapper(mArrowMapper);
    actor->SetUserTransform(orient);
    //actor->SetPosition(vpd[0][i], vpd[1][i], vpd[2][i]);
    mRen->AddActor(actor);
  }
}

//-----------------------------------------------------------------------------
void RenderWindow::setupHelixVectorField()
{
  double t = 0.0;
  const double dt = 0.4;
  const double p2Off = 3.14159265 / 2.0f;
  vtkVector3d p1;
  vtkVector3d p2;
  vtkVector3d dp1;
  vtkVector3d dp2;
  const double heightMult = 2.0;
  const double r = 2.0; // Radius
  const int steps = 40;

  DenseMatrixGeneric<double> m(6, steps * 2);

  for (int i = 0; i < steps; i++)
  {
    p1.Set(cos(t) * r, t * heightMult, sin(t) * r);
    dp1.Set(-sin(t) * r, heightMult, cos(t) * r);
    p2.Set(cos(t + p2Off) * r, t * heightMult, sin(t + p2Off) * r);
    dp2.Set(-sin(t + p2Off) * r, heightMult, cos(t + p2Off) * r);

    int off = i * 2;

    m(0,off) = dp1.X();
    m(1,off) = dp1.Y();
    m(2,off) = dp1.Z();
    m(3,off) = p1.X();
    m(4,off) = p1.Y();
    m(5,off) = p1.Z();

    m(0,off+1) = dp2.X();
    m(1,off+1) = dp2.Y();
    m(2,off+1) = dp2.Z();
    m(3,off+1) = p2.X();
    m(4,off+1) = p2.Y();
    m(5,off+1) = p2.Z();

    t += dt;
  }

  setVectorField(m);
}

//-----------------------------------------------------------------------------
void RenderWindow::setText(const char* output)
{
  vtkSmartPointer<vtkTextActor> txt = vtkSmartPointer<vtkTextActor>::New();
  txt->SetDisplayPosition(90, 50);
  txt->SetInput(output);

  vtkTextProperty* txtProp = txt->GetTextProperty();
  txtProp->SetFontSize(18);
  txtProp->BoldOn();

  mRen->AddActor2D(txt);
}

//-----------------------------------------------------------------------------
void RenderWindow::setVectorField(const DenseMatrixGeneric<double>& m)
{
  if (m.nrows() != 6)
    throw std::runtime_error("Expecting a 6xn matrix.");

  for (int i = 0; i < m.ncols(); i++)
  {
    // Extract direction/position
    vtkVector3d dir(m(0,i), m(1,i), m(2,i));
    vtkVector3d pos(m(3,i), m(4,i), m(5,i));

    vtkSmartPointer<vtkTransform> orient = matFromVecR(dir, pos);

    //vtkSmartPointer<vtkMatrix4x4> m = vtkSmartPointer<vtkMatrix4x4>::New();
    //orient->GetMatrix(m);
    //m->Print(std::cout);

    // Now we have appropriate transformation data, build actor.
    vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
    actor->SetMapper(mArrowMapper);
    actor->SetUserTransform(orient);
    //actor->SetPosition(pos.X(), pos.Y(), pos.Z());
    mRen->AddActor(actor);
  }
}

//-----------------------------------------------------------------------------
vtkSmartPointer<vtkTransform> RenderWindow::matFromVec(const vtkVector3d& v,
                                                       const vtkVector3d& pos)
{
  // Find the maximal component in the vector. The construct a normal vector
  // which has a zero for the maximal component.
  float absX = fabs(v.GetX());
  float absY = fabs(v.GetY());
  float absZ = fabs(v.GetZ());

  vtkVector3d gen;
  if (absX > absY)
  {
    if (absZ > absX)
    {
      gen = vtkVector3d(1.0, 1.0, 0.0);
    }
    else
    {
      gen = vtkVector3d(0.0, 1.0, 1.0);
    }
  }
  else
  {
    if (absZ > absY)
    {
      gen = vtkVector3d(1.0, 1.0, 0.0);
    }
    else
    {
      gen = vtkVector3d(1.0, 0.0, 1.0);
    }
  }

  gen.Normalize();

  vtkVector3d at = v;
  at.Normalize();

  // Cross generated vector with 'at' vector.
  vtkVector3d right = gen.Cross(at);
  right.Normalize();
  vtkVector3d up = at.Cross(right);
  up.Normalize();

  double m[16];

  /// @todo Combine two matrices below.
  // Assuming the matrix is row major. Although, this doesn't matter for
  // the identity (I^T = I)
  m[0 ] = 1.0; m[1 ] = 0.0; m[2 ] = 0.0; m[3 ] = 0.0;
  m[4 ] = 0.0; m[5 ] = 1.0; m[6 ] = 0.0; m[7 ] = 0.0;
  m[8 ] = 0.0; m[9 ] = 0.0; m[10] = 1.0; m[11] = 0.0;
  m[12] = 0.0; m[13] = 0.0; m[14] = 0.0; m[15] = 1.0;

  // Populate rotation.
  m[0 ] = right[0]; m[1 ] = up[0]; m[2 ] = at[0]; m[3 ] = pos.X();
  m[4 ] = right[1]; m[5 ] = up[1]; m[6 ] = at[1]; m[7 ] = pos.Y();
  m[8 ] = right[2]; m[9 ] = up[2]; m[10] = at[2]; m[11] = pos.Z();

  vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New();
  t->SetMatrix(m);
  //t->Inverse();

  return t;
}

//-----------------------------------------------------------------------------
vtkSmartPointer<vtkTransform> RenderWindow::matFromVecR(const vtkVector3d& x,
                                                        const vtkVector3d& pos)
{
  // Find the maximal component in the vector. The construct a normal vector
  // which has a zero for the maximal component.
  float absX = fabs(x.GetX());
  float absY = fabs(x.GetY());
  float absZ = fabs(x.GetZ());

  vtkVector3d gen;
  if (absX > absY)
  {
    if (absZ > absX)
    {
      gen = vtkVector3d(1.0, 1.0, 0.0);
    }
    else
    {
      gen = vtkVector3d(0.0, 1.0, 1.0);
    }
  }
  else
  {
    if (absZ > absY)
    {
      gen = vtkVector3d(1.0, 1.0, 0.0);
    }
    else
    {
      gen = vtkVector3d(1.0, 0.0, 1.0);
    }
  }

  gen.Normalize();

  vtkVector3d right = x;
  right.Normalize();

  // Cross generated vector with 'at' vector.
  vtkVector3d at = gen.Cross(right);
  at.Normalize();
  vtkVector3d up = at.Cross(right);
  up.Normalize();

  double m[16];

  /// @todo Combine two matrices below.
  // Assuming the matrix is row major. Although, this doesn't matter for
  // the identity (I^T = I)
  m[0 ] = 1.0; m[1 ] = 0.0; m[2 ] = 0.0; m[3 ] = 0.0;
  m[4 ] = 0.0; m[5 ] = 1.0; m[6 ] = 0.0; m[7 ] = 0.0;
  m[8 ] = 0.0; m[9 ] = 0.0; m[10] = 1.0; m[11] = 0.0;
  m[12] = 0.0; m[13] = 0.0; m[14] = 0.0; m[15] = 1.0;

  // Populate rotation.
  m[0 ] = right[0]; m[1 ] = up[0]; m[2 ] = at[0]; m[3 ] = pos.X();
  m[4 ] = right[1]; m[5 ] = up[1]; m[6 ] = at[1]; m[7 ] = pos.Y();
  m[8 ] = right[2]; m[9 ] = up[2]; m[10] = at[2]; m[11] = pos.Z();

  vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New();
  t->SetMatrix(m);
  //t->Inverse();

  return t;
}

<commit_msg>Added math.h header file for 'fabs', 'sin', and 'cos'.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include "RenderWindow.h"
#include "ui_RenderWindow.h"
#include "Core/Datatypes/DenseMatrix.h"

#include <QVTKWidget.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkPolyDataMapper.h>
#include <vtkArrowSource.h>
#include <vtkVector.h>
#include <vtkMatrix3x3.h>
#include <vtkMatrix4x4.h>
#include <vtkTransform.h>
#include <vtkTextActor.h>
#include <vtkTextProperty.h>
#include <math.h>

using namespace SCIRun::Domain::Datatypes;

//-----------------------------------------------------------------------------
RenderWindow::RenderWindow(QWidget *parent) :
  QDialog(parent),
  ui(new Ui::RenderWindow),
  mVtkWidget(new QVTKWidget(this, QFlag(0)))
{
  ui->setupUi(this);

  // Add VTK widget to vertical layout.
  ui->verticalLayout->addWidget(mVtkWidget);
  ui->verticalLayout->update();

  // Create renderer
  mRen = vtkSmartPointer<vtkRenderer>::New();
  mVtkWidget->GetRenderWindow()->AddRenderer(mRen);
  mVtkWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
  //mRen->SetBackground(1.0,0.0,0.0);

  // Create arrow poly data
  mArrowSource = vtkSmartPointer<vtkArrowSource>::New();
  //arrowSource->SetShaftRadius(1.0);
  //arrowSource->SetTipLength(1.0);
  mArrowSource->Update();

  // Create data mapper (from visualization system to graphics system).
  mArrowMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  mArrowMapper->SetInputConnection(mArrowSource->GetOutputPort());

  //setupDefaultVectorField();
  setupHelixVectorField();

  setText("This is a vector field!");
}

//-----------------------------------------------------------------------------
RenderWindow::~RenderWindow()
{
  delete mVtkWidget;
  delete ui;
}

//-----------------------------------------------------------------------------
void RenderWindow::setupDefaultVectorField()
{
  // Read matrix and build scene with appropriate actors.
  const int numVecs = 6;
  double vpd[3][numVecs] = { // Vector position data
    { 0.0, 0.0, 0.0, 0.0, 1.0, 1.0 },
    { 0.0, 1.0, 0.0, 1.0, 1.0, 0.0 },
    { 0.0, 0.0, 1.0, 1.0, 0.0, 1.0 }
  };
  double vod[3][numVecs] = { // Vector orientation data
    { 1.0, 0.0, 0.0, 0.0, 1.0, 1.0 },
    { 0.0, 1.0, 0.0, 1.0, 1.0, 0.0 },
    { 0.0, 0.0, 1.0, 1.0, 0.0, 1.0 }
  };

  // Setup actors for each of the vectors...
  // There are better ways of representing vectors fields in VTK.

  // Need to construct 3x3 rotation matrices from orientation vector.
  for (int i = 0; i < numVecs; i++)
  {
    vtkSmartPointer<vtkTransform> orient = matFromVec(
        vtkVector3d(vod[0][i], vod[1][i], vod[2][i]),
        vtkVector3d(vpd[0][i], vpd[1][i], vpd[2][i]));

    vtkSmartPointer<vtkMatrix4x4> m = vtkSmartPointer<vtkMatrix4x4>::New();
    orient->GetMatrix(m);
    //m->Print(std::cout);

    // Now we have appropriate transformation data, build actor.
    vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
    actor->SetMapper(mArrowMapper);
    actor->SetUserTransform(orient);
    //actor->SetPosition(vpd[0][i], vpd[1][i], vpd[2][i]);
    mRen->AddActor(actor);
  }
}

//-----------------------------------------------------------------------------
void RenderWindow::setupHelixVectorField()
{
  double t = 0.0;
  const double dt = 0.4;
  const double p2Off = 3.14159265 / 2.0f;
  vtkVector3d p1;
  vtkVector3d p2;
  vtkVector3d dp1;
  vtkVector3d dp2;
  const double heightMult = 2.0;
  const double r = 2.0; // Radius
  const int steps = 40;

  DenseMatrixGeneric<double> m(6, steps * 2);

  for (int i = 0; i < steps; i++)
  {
    p1.Set(cos(t) * r, t * heightMult, sin(t) * r);
    dp1.Set(-sin(t) * r, heightMult, cos(t) * r);
    p2.Set(cos(t + p2Off) * r, t * heightMult, sin(t + p2Off) * r);
    dp2.Set(-sin(t + p2Off) * r, heightMult, cos(t + p2Off) * r);

    int off = i * 2;

    m(0,off) = dp1.X();
    m(1,off) = dp1.Y();
    m(2,off) = dp1.Z();
    m(3,off) = p1.X();
    m(4,off) = p1.Y();
    m(5,off) = p1.Z();

    m(0,off+1) = dp2.X();
    m(1,off+1) = dp2.Y();
    m(2,off+1) = dp2.Z();
    m(3,off+1) = p2.X();
    m(4,off+1) = p2.Y();
    m(5,off+1) = p2.Z();

    t += dt;
  }

  setVectorField(m);
}

//-----------------------------------------------------------------------------
void RenderWindow::setText(const char* output)
{
  vtkSmartPointer<vtkTextActor> txt = vtkSmartPointer<vtkTextActor>::New();
  txt->SetDisplayPosition(90, 50);
  txt->SetInput(output);

  vtkTextProperty* txtProp = txt->GetTextProperty();
  txtProp->SetFontSize(18);
  txtProp->BoldOn();

  mRen->AddActor2D(txt);
}

//-----------------------------------------------------------------------------
void RenderWindow::setVectorField(const DenseMatrixGeneric<double>& m)
{
  if (m.nrows() != 6)
    throw std::runtime_error("Expecting a 6xn matrix.");

  for (int i = 0; i < m.ncols(); i++)
  {
    // Extract direction/position
    vtkVector3d dir(m(0,i), m(1,i), m(2,i));
    vtkVector3d pos(m(3,i), m(4,i), m(5,i));

    vtkSmartPointer<vtkTransform> orient = matFromVecR(dir, pos);

    //vtkSmartPointer<vtkMatrix4x4> m = vtkSmartPointer<vtkMatrix4x4>::New();
    //orient->GetMatrix(m);
    //m->Print(std::cout);

    // Now we have appropriate transformation data, build actor.
    vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
    actor->SetMapper(mArrowMapper);
    actor->SetUserTransform(orient);
    //actor->SetPosition(pos.X(), pos.Y(), pos.Z());
    mRen->AddActor(actor);
  }
}

//-----------------------------------------------------------------------------
vtkSmartPointer<vtkTransform> RenderWindow::matFromVec(const vtkVector3d& v,
                                                       const vtkVector3d& pos)
{
  // Find the maximal component in the vector. The construct a normal vector
  // which has a zero for the maximal component.
  float absX = fabs(v.GetX());
  float absY = fabs(v.GetY());
  float absZ = fabs(v.GetZ());

  vtkVector3d gen;
  if (absX > absY)
  {
    if (absZ > absX)
    {
      gen = vtkVector3d(1.0, 1.0, 0.0);
    }
    else
    {
      gen = vtkVector3d(0.0, 1.0, 1.0);
    }
  }
  else
  {
    if (absZ > absY)
    {
      gen = vtkVector3d(1.0, 1.0, 0.0);
    }
    else
    {
      gen = vtkVector3d(1.0, 0.0, 1.0);
    }
  }

  gen.Normalize();

  vtkVector3d at = v;
  at.Normalize();

  // Cross generated vector with 'at' vector.
  vtkVector3d right = gen.Cross(at);
  right.Normalize();
  vtkVector3d up = at.Cross(right);
  up.Normalize();

  double m[16];

  /// @todo Combine two matrices below.
  // Assuming the matrix is row major. Although, this doesn't matter for
  // the identity (I^T = I)
  m[0 ] = 1.0; m[1 ] = 0.0; m[2 ] = 0.0; m[3 ] = 0.0;
  m[4 ] = 0.0; m[5 ] = 1.0; m[6 ] = 0.0; m[7 ] = 0.0;
  m[8 ] = 0.0; m[9 ] = 0.0; m[10] = 1.0; m[11] = 0.0;
  m[12] = 0.0; m[13] = 0.0; m[14] = 0.0; m[15] = 1.0;

  // Populate rotation.
  m[0 ] = right[0]; m[1 ] = up[0]; m[2 ] = at[0]; m[3 ] = pos.X();
  m[4 ] = right[1]; m[5 ] = up[1]; m[6 ] = at[1]; m[7 ] = pos.Y();
  m[8 ] = right[2]; m[9 ] = up[2]; m[10] = at[2]; m[11] = pos.Z();

  vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New();
  t->SetMatrix(m);
  //t->Inverse();

  return t;
}

//-----------------------------------------------------------------------------
vtkSmartPointer<vtkTransform> RenderWindow::matFromVecR(const vtkVector3d& x,
                                                        const vtkVector3d& pos)
{
  // Find the maximal component in the vector. The construct a normal vector
  // which has a zero for the maximal component.
  float absX = fabs(x.GetX());
  float absY = fabs(x.GetY());
  float absZ = fabs(x.GetZ());

  vtkVector3d gen;
  if (absX > absY)
  {
    if (absZ > absX)
    {
      gen = vtkVector3d(1.0, 1.0, 0.0);
    }
    else
    {
      gen = vtkVector3d(0.0, 1.0, 1.0);
    }
  }
  else
  {
    if (absZ > absY)
    {
      gen = vtkVector3d(1.0, 1.0, 0.0);
    }
    else
    {
      gen = vtkVector3d(1.0, 0.0, 1.0);
    }
  }

  gen.Normalize();

  vtkVector3d right = x;
  right.Normalize();

  // Cross generated vector with 'at' vector.
  vtkVector3d at = gen.Cross(right);
  at.Normalize();
  vtkVector3d up = at.Cross(right);
  up.Normalize();

  double m[16];

  /// @todo Combine two matrices below.
  // Assuming the matrix is row major. Although, this doesn't matter for
  // the identity (I^T = I)
  m[0 ] = 1.0; m[1 ] = 0.0; m[2 ] = 0.0; m[3 ] = 0.0;
  m[4 ] = 0.0; m[5 ] = 1.0; m[6 ] = 0.0; m[7 ] = 0.0;
  m[8 ] = 0.0; m[9 ] = 0.0; m[10] = 1.0; m[11] = 0.0;
  m[12] = 0.0; m[13] = 0.0; m[14] = 0.0; m[15] = 1.0;

  // Populate rotation.
  m[0 ] = right[0]; m[1 ] = up[0]; m[2 ] = at[0]; m[3 ] = pos.X();
  m[4 ] = right[1]; m[5 ] = up[1]; m[6 ] = at[1]; m[7 ] = pos.Y();
  m[8 ] = right[2]; m[9 ] = up[2]; m[10] = at[2]; m[11] = pos.Z();

  vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New();
  t->SetMatrix(m);
  //t->Inverse();

  return t;
}

<|endoftext|>


<commit_before>#include "random_graph.hpp"

namespace vg {
namespace unittest {

VG randomGraph(int64_t seqSize, int64_t variantLen,
                    int64_t variantCount){
    //Create a random graph for a sequence of length seqSize
    //variantLen is the mean length of a larger variation and variationCount
    //is the number of variations in the graph

    VG graph;
    map<size_t, id_t> indexToNode;
                  //Index of original sequence to node that starts at that index

    string seq(seqSize, 'A');//TODO: The graph is all As
    Node* n = graph.create_node(seq);
    indexToNode.insert(make_pair(0, n->id()));

    //Get random number generator for lengths and variation types
    poisson_distribution<size_t> lengthDistribution(variantLen);
    uniform_int_distribution<int> variantDistribution(0, 4);
    uniform_int_distribution<int> indexDistribution(0, seqSize-1);
    random_device seed_source;
    default_random_engine generator(seed_source());

    auto splitNode = [&] (size_t index) -> pair<Node, Node> {
        //Split graph at index. Split the node with the original sequence into
        //the original node and a new node and connect the two

        auto n = --indexToNode.upper_bound(index);//orig node containing pos
        size_t firstIndex = n->first;           //Index of first node
        size_t firstNodeID = n->second;         //Node ID of first node

        Node* firstNode = graph.get_node(firstNodeID);
        string origSeq = firstNode->sequence();
        if (index > firstIndex) {
            size_t nodeLength = index - firstIndex;

            firstNode->set_sequence(origSeq.substr(0, nodeLength));//replace seq
            Node* newNode = graph.create_node(origSeq.substr(nodeLength));
            indexToNode.insert(make_pair(index, newNode->id()));

            //Transfer outgoing edges from fist node to second node

            handle_t startFd = graph.get_handle(firstNodeID, false);
            handle_t endFd = graph.get_handle(newNode->id(), false);

            unordered_set<handle_t> nextHandles;
            auto addHandle = [&](const handle_t& h) ->bool {
                nextHandles.insert(h);
                return true;
            };
            graph.follow_edges(startFd, false, addHandle);

            for (handle_t h : nextHandles) {
                //for each edge from start node, delete and add to new node
                graph.destroy_edge(startFd, h);
                graph.create_edge(endFd, h);
            }
            graph.create_edge(firstNode, newNode);
            return make_pair(*firstNode, *newNode);
        } else {

            auto n = --indexToNode.lower_bound(index);
            Node* prevNode = graph.get_node(n->second);
            return make_pair(*prevNode, *firstNode);
        }

    };

    enum VariationType {SNP = 0, POINT_INDEL = 1, STRUCTURAL_INDEL = 2,
                        CNV = 3, INVERSION = 4};

    for (int j = 0; j < variantCount; j++) {
        //add variants
        int startIndex = indexDistribution(generator);
        VariationType variationType =
                                 (VariationType) variantDistribution(generator);

        if (variationType == SNP) {

            if (startIndex == 0) {

                pair<Node, Node> endNodes = splitNode(startIndex+1);
                Node end = endNodes.second;
                Node* newNode = graph.create_node("G");//TODO: snp are all Gs
                graph.create_edge(newNode, &end);

            } else if (startIndex < seqSize-2) {

                pair<Node, Node> startNodes = splitNode(startIndex);
                pair<Node, Node> endNodes = splitNode(startIndex+1);

                Node start = startNodes.first;
                Node end = endNodes.second;
                Node* newNode = graph.create_node("G");
                graph.create_edge(&start, newNode);
                graph.create_edge(newNode, &end);

            } else if (startIndex == seqSize -2) {

                pair<Node, Node> startNodes = splitNode(startIndex);

                Node start = startNodes.first;
                Node* newNode = graph.create_node("G");
                graph.create_edge(&start, newNode);

            }
        } else if (variationType == POINT_INDEL) {
            //Short indel - deletion of original

            if (startIndex > 0 && startIndex < seqSize-1) {
                pair<Node, Node> startNodes = splitNode(startIndex);
                pair<Node, Node> endNodes = splitNode(startIndex+1);

                Node start = startNodes.first;
                Node end = endNodes.second;
                graph.create_edge(&start, &end);

            }
        } else if (variationType == STRUCTURAL_INDEL) {
            //long indel
            size_t length = lengthDistribution(generator);

            if (length > 0 && startIndex > 0 &&
               length + startIndex < seqSize-1) {

                pair<Node, Node> startNodes = splitNode(startIndex);
                pair<Node, Node> endNodes = splitNode(startIndex+length);

                Node start = startNodes.first;
                Node end = endNodes.second;
                graph.create_edge(&start, &end);

            }
        } else if (variationType == CNV) {
            //Copy number variation
            size_t length = lengthDistribution(generator);

            if (length > 0 ) {
                if (startIndex == 0) {
                    pair<Node, Node> endNodes = splitNode(startIndex+length);
                    Node n = endNodes.first;

                    auto nodePair = --indexToNode.upper_bound(0);//first node
                    size_t firstNodeID = nodePair->second;

                    Node* firstNode = graph.get_node(firstNodeID);

                    graph.create_edge(&n, firstNode);

                } else if ( length + startIndex < seqSize-1) {

                    pair<Node, Node> startNodes = splitNode(startIndex);
                    pair<Node, Node> endNodes = splitNode(startIndex+length);

                    Node n1 = startNodes.second;
                    Node n2 = endNodes.first;
                    graph.create_edge(&n2, &n1);

                } else  if ( length + startIndex == seqSize -1) {
                    pair<Node, Node> startNodes = splitNode(startIndex);

                    auto nodePair = --indexToNode.upper_bound(seqSize);
                        //last node
                    size_t lastNodeID = nodePair->second;

                    Node* lastNode = graph.get_node(lastNodeID);

                    Node n = startNodes.second;
                    graph.create_edge(lastNode, &n);
                }
            }
        } else if (variationType == INVERSION){
            //Inversion
            size_t length = lengthDistribution(generator);
            if (length > 0) {
                if (startIndex == 0) {

                    pair<Node, Node> endNodes = splitNode(startIndex+length);

                    Node end = endNodes.second;
                    Node n = endNodes.first;
                    graph.create_edge(&n, &end, true, false);

                } else if ( length + startIndex < seqSize-1) {
                    pair<Node, Node> startNodes = splitNode(startIndex);
                    pair<Node, Node> endNodes = splitNode(startIndex+length);

                    Node start = startNodes.first;
                    Node end = endNodes.second;
                    Node n1 = startNodes.second;
                    Node n2 = endNodes.first;
                    graph.create_edge(&start, &n2, false, true);
                    graph.create_edge(&n1, &end, true, false);

               } else if (length + startIndex == seqSize - 1) {

                    pair<Node, Node> startNodes = splitNode(startIndex);

                    Node start = startNodes.first;
                    Node n = startNodes.second;
                    graph.create_edge(&start, &n, false, true);

               }
           }
        }
    }
    return graph;
};

}
}
<commit_msg>add random sequence to random graph<commit_after>#include "random_graph.hpp"

namespace vg {
namespace unittest {

VG randomGraph(int64_t seqSize, int64_t variantLen,
                    int64_t variantCount){
    //Create a random graph for a sequence of length seqSize
    //variantLen is the mean length of a larger variation and variationCount
    //is the number of variations in the graph

    VG graph;
    map<size_t, id_t> indexToNode;
                  //Index of original sequence to node that starts at that index

    random_device seed_source;
    default_random_engine generator(seed_source());

    uniform_int_distribution<int> baseDistribution(0, 3);
    poisson_distribution<size_t> lengthDistribution(variantLen);
    uniform_int_distribution<int> variantDistribution(0, 4);
    uniform_int_distribution<int> indexDistribution(0, seqSize-1);

    // Init the string with placeholder bases
    string seq(seqSize, 'A');
    // Set the string to random bases
    string alphabet = "ACGT";
    for (size_t i = 0; i < seq.size(); i++) {
        seq[i] = alphabet[baseDistribution(generator)];
    }

    Node* n = graph.create_node(seq);
    indexToNode.insert(make_pair(0, n->id()));

    //Get random number generator for lengths and variation types

    auto splitNode = [&] (size_t index) -> pair<Node, Node> {
        //Split graph at index. Split the node with the original sequence into
        //the original node and a new node and connect the two

        auto n = --indexToNode.upper_bound(index);//orig node containing pos
        size_t firstIndex = n->first;           //Index of first node
        size_t firstNodeID = n->second;         //Node ID of first node

        Node* firstNode = graph.get_node(firstNodeID);
        string origSeq = firstNode->sequence();
        if (index > firstIndex) {
            size_t nodeLength = index - firstIndex;

            firstNode->set_sequence(origSeq.substr(0, nodeLength));//replace seq
            Node* newNode = graph.create_node(origSeq.substr(nodeLength));
            indexToNode.insert(make_pair(index, newNode->id()));

            //Transfer outgoing edges from fist node to second node

            handle_t startFd = graph.get_handle(firstNodeID, false);
            handle_t endFd = graph.get_handle(newNode->id(), false);

            unordered_set<handle_t> nextHandles;
            auto addHandle = [&](const handle_t& h) ->bool {
                nextHandles.insert(h);
                return true;
            };
            graph.follow_edges(startFd, false, addHandle);

            for (handle_t h : nextHandles) {
                //for each edge from start node, delete and add to new node
                graph.destroy_edge(startFd, h);
                graph.create_edge(endFd, h);
            }
            graph.create_edge(firstNode, newNode);
            return make_pair(*firstNode, *newNode);
        } else {

            auto n = --indexToNode.lower_bound(index);
            Node* prevNode = graph.get_node(n->second);
            return make_pair(*prevNode, *firstNode);
        }

    };

    enum VariationType {SNP = 0, POINT_INDEL = 1, STRUCTURAL_INDEL = 2,
                        CNV = 3, INVERSION = 4};

    for (int j = 0; j < variantCount; j++) {
        //add variants
        int startIndex = indexDistribution(generator);
        VariationType variationType =
                                 (VariationType) variantDistribution(generator);

        if (variationType == SNP) {

            if (startIndex == 0) {

                pair<Node, Node> endNodes = splitNode(startIndex+1);
                Node end = endNodes.second;
                Node* newNode = graph.create_node(string(1, alphabet[baseDistribution(generator)]));
                graph.create_edge(newNode, &end);

            } else if (startIndex < seqSize-2) {

                pair<Node, Node> startNodes = splitNode(startIndex);
                pair<Node, Node> endNodes = splitNode(startIndex+1);

                Node start = startNodes.first;
                Node end = endNodes.second;
                Node* newNode = graph.create_node(string(1, alphabet[baseDistribution(generator)]));
                graph.create_edge(&start, newNode);
                graph.create_edge(newNode, &end);

            } else if (startIndex == seqSize -2) {

                pair<Node, Node> startNodes = splitNode(startIndex);

                Node start = startNodes.first;
                Node* newNode = graph.create_node(string(1, alphabet[baseDistribution(generator)]));
                graph.create_edge(&start, newNode);

            }
        } else if (variationType == POINT_INDEL) {
            //Short indel - deletion of original

            if (startIndex > 0 && startIndex < seqSize-1) {
                pair<Node, Node> startNodes = splitNode(startIndex);
                pair<Node, Node> endNodes = splitNode(startIndex+1);

                Node start = startNodes.first;
                Node end = endNodes.second;
                graph.create_edge(&start, &end);

            }
        } else if (variationType == STRUCTURAL_INDEL) {
            //long indel
            size_t length = lengthDistribution(generator);

            if (length > 0 && startIndex > 0 &&
               length + startIndex < seqSize-1) {

                pair<Node, Node> startNodes = splitNode(startIndex);
                pair<Node, Node> endNodes = splitNode(startIndex+length);

                Node start = startNodes.first;
                Node end = endNodes.second;
                graph.create_edge(&start, &end);

            }
        } else if (variationType == CNV) {
            //Copy number variation
            size_t length = lengthDistribution(generator);

            if (length > 0 ) {
                if (startIndex == 0) {
                    pair<Node, Node> endNodes = splitNode(startIndex+length);
                    Node n = endNodes.first;

                    auto nodePair = --indexToNode.upper_bound(0);//first node
                    size_t firstNodeID = nodePair->second;

                    Node* firstNode = graph.get_node(firstNodeID);

                    graph.create_edge(&n, firstNode);

                } else if ( length + startIndex < seqSize-1) {

                    pair<Node, Node> startNodes = splitNode(startIndex);
                    pair<Node, Node> endNodes = splitNode(startIndex+length);

                    Node n1 = startNodes.second;
                    Node n2 = endNodes.first;
                    graph.create_edge(&n2, &n1);

                } else  if ( length + startIndex == seqSize -1) {
                    pair<Node, Node> startNodes = splitNode(startIndex);

                    auto nodePair = --indexToNode.upper_bound(seqSize);
                        //last node
                    size_t lastNodeID = nodePair->second;

                    Node* lastNode = graph.get_node(lastNodeID);

                    Node n = startNodes.second;
                    graph.create_edge(lastNode, &n);
                }
            }
        } else if (variationType == INVERSION){
            //Inversion
            size_t length = lengthDistribution(generator);
            if (length > 0) {
                if (startIndex == 0) {

                    pair<Node, Node> endNodes = splitNode(startIndex+length);

                    Node end = endNodes.second;
                    Node n = endNodes.first;
                    graph.create_edge(&n, &end, true, false);

                } else if ( length + startIndex < seqSize-1) {
                    pair<Node, Node> startNodes = splitNode(startIndex);
                    pair<Node, Node> endNodes = splitNode(startIndex+length);

                    Node start = startNodes.first;
                    Node end = endNodes.second;
                    Node n1 = startNodes.second;
                    Node n2 = endNodes.first;
                    graph.create_edge(&start, &n2, false, true);
                    graph.create_edge(&n1, &end, true, false);

               } else if (length + startIndex == seqSize - 1) {

                    pair<Node, Node> startNodes = splitNode(startIndex);

                    Node start = startNodes.first;
                    Node n = startNodes.second;
                    graph.create_edge(&start, &n, false, true);

               }
           }
        }
    }
    return graph;
};

}
}
<|endoftext|>


<commit_before><commit_msg>Quick 'low-risk-for-the-next-release' fix to increase theme install/load perf (should be a 2-4x speedup). Bug should remain open until a better approach (background threads, perhaps) is used.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/gtk/browser_window_gtk.h"

#include "base/logging.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/gtk/browser_toolbar_view_gtk.h"
#include "chrome/browser/renderer_host/render_widget_host_view_gtk.h"
#include "chrome/browser/tab_contents/web_contents.h"

namespace {

gboolean MainWindowDestroyed(GtkWindow* window, BrowserWindowGtk* browser_win) {
  delete browser_win;
  return FALSE;  // Don't stop this message.
}

gboolean MainWindowConfigured(GtkWindow* window, GdkEventConfigure* event,
                              BrowserWindowGtk* browser_win) {
  gfx::Rect bounds = gfx::Rect(event->x, event->y, event->width, event->height);
  browser_win->OnBoundsChanged(bounds);
  return FALSE;
}

gboolean MainWindowStateChanged(GtkWindow* window, GdkEventWindowState* event,
                                BrowserWindowGtk* browser_win) {
  browser_win->OnStateChanged(event->new_window_state);
  return FALSE;
}

// Using gtk_window_get_position/size creates a race condition, so only use
// this to get the initial bounds.  After window creation, we pick up the
// normal bounds by connecting to the configure-event signal.
gfx::Rect GetInitialWindowBounds(GtkWindow* window) {
  gint x, y, width, height;
  gtk_window_get_position(window, &x, &y);
  gtk_window_get_size(window, &width, &height);
  return gfx::Rect(x, y, width, height);
}

gboolean FalseMachine(GtkWindow* window, GdkEventWindowState* event,
                                BrowserWindowGtk* browser_win) {
  return FALSE;
}

}  // namespace

BrowserWindowGtk::BrowserWindowGtk(Browser* browser) : browser_(browser) {
  Init();
}

BrowserWindowGtk::~BrowserWindowGtk() {
  Close();
}

void BrowserWindowGtk::Init() {
  window_ = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
  gtk_window_set_title(window_, "Chromium");
  gtk_window_set_default_size(window_, 640, 480);
  g_signal_connect(G_OBJECT(window_), "destroy",
                   G_CALLBACK(MainWindowDestroyed), this);
  g_signal_connect(G_OBJECT(window_), "configure-event",
                   G_CALLBACK(MainWindowConfigured), this);
  g_signal_connect(G_OBJECT(window_), "expose-event",
                   G_CALLBACK(FalseMachine), this);
  g_signal_connect(G_OBJECT(window_), "window-state-event",
                   G_CALLBACK(MainWindowStateChanged), this);
  bounds_ = GetInitialWindowBounds(window_);

  vbox_ = gtk_vbox_new(FALSE, 0);

  toolbar_.reset(new BrowserToolbarGtk(browser_.get()));
  toolbar_->Init(browser_->profile());
  toolbar_->AddToolbarToBox(vbox_);

  gtk_container_add(GTK_CONTAINER(window_), vbox_);
}

void BrowserWindowGtk::Show() {
  // TODO(estade): fix this block. As it stands, it is a temporary hack to get
  // the browser displaying something.
  if (content_area_ == NULL) {
    WebContents* contents = (WebContents*)(browser_->GetTabContentsAt(0));
    content_area_ = ((RenderWidgetHostViewGtk*)contents->
        render_view_host()->view())->native_view();
    gtk_box_pack_start(GTK_BOX(vbox_), content_area_, TRUE, TRUE, 0);
    contents->NavigateToPendingEntry(false);
  }

  gtk_widget_show_all(GTK_WIDGET(window_));
}

void BrowserWindowGtk::SetBounds(const gfx::Rect& bounds) {
  gint x = static_cast<gint>(bounds.x());
  gint y = static_cast<gint>(bounds.y());
  gint width = static_cast<gint>(bounds.width());
  gint height = static_cast<gint>(bounds.height());

  gtk_window_move(window_, x, y);
  gtk_window_resize(window_, width, height);
}

void BrowserWindowGtk::Close() {
  if (!window_)
    return;

  gtk_widget_destroy(GTK_WIDGET(window_));
  window_ = NULL;
}

void BrowserWindowGtk::Activate() {
  gtk_window_present(window_);
}

void BrowserWindowGtk::FlashFrame() {
  // May not be respected by all window managers.
  gtk_window_set_urgency_hint(window_, TRUE);
}

void* BrowserWindowGtk::GetNativeHandle() {
  return window_;
}

BrowserWindowTesting* BrowserWindowGtk::GetBrowserWindowTesting() {
  NOTIMPLEMENTED();
  return NULL;
}

StatusBubble* BrowserWindowGtk::GetStatusBubble() {
  NOTIMPLEMENTED();
  return NULL;
}

void BrowserWindowGtk::SelectedTabToolbarSizeChanged(bool is_animating) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::UpdateTitleBar() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::UpdateLoadingAnimations(bool should_animate) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::SetStarredState(bool is_starred) {
  NOTIMPLEMENTED();
}

gfx::Rect BrowserWindowGtk::GetNormalBounds() const {
  return bounds_;
}

bool BrowserWindowGtk::IsMaximized() {
  return (state_ & GDK_WINDOW_STATE_MAXIMIZED);
}

LocationBar* BrowserWindowGtk::GetLocationBar() const {
  NOTIMPLEMENTED();
  return NULL;
}

void BrowserWindowGtk::UpdateStopGoState(bool is_loading) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::UpdateToolbar(TabContents* contents,
                                     bool should_restore_state) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::FocusToolbar() {
  NOTIMPLEMENTED();
}

bool BrowserWindowGtk::IsBookmarkBarVisible() const {
  NOTIMPLEMENTED();
  return false;
}

void BrowserWindowGtk::ToggleBookmarkBar() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowAboutChromeDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowBookmarkManager() {
  NOTIMPLEMENTED();
}

bool BrowserWindowGtk::IsBookmarkBubbleVisible() const {
  NOTIMPLEMENTED();
  return false;
}

void BrowserWindowGtk::ShowBookmarkBubble(const GURL& url,
                                          bool already_bookmarked) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowReportBugDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowClearBrowsingDataDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowImportDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowSearchEnginesDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowPasswordManager() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowSelectProfileDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowNewProfileDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowHTMLDialog(HtmlDialogContentsDelegate* delegate,
                                      void* parent_window) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::DestroyBrowser() {
  browser_.reset();
}

void BrowserWindowGtk::OnBoundsChanged(const gfx::Rect& bounds) {
  bounds_ = bounds;
}

void BrowserWindowGtk::OnStateChanged(GdkWindowState state) {
  state_ = state;
}
<commit_msg>Remove dead code from last commit.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/gtk/browser_window_gtk.h"

#include "base/logging.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/gtk/browser_toolbar_view_gtk.h"
#include "chrome/browser/renderer_host/render_widget_host_view_gtk.h"
#include "chrome/browser/tab_contents/web_contents.h"

namespace {

gboolean MainWindowDestroyed(GtkWindow* window, BrowserWindowGtk* browser_win) {
  delete browser_win;
  return FALSE;  // Don't stop this message.
}

gboolean MainWindowConfigured(GtkWindow* window, GdkEventConfigure* event,
                              BrowserWindowGtk* browser_win) {
  gfx::Rect bounds = gfx::Rect(event->x, event->y, event->width, event->height);
  browser_win->OnBoundsChanged(bounds);
  return FALSE;
}

gboolean MainWindowStateChanged(GtkWindow* window, GdkEventWindowState* event,
                                BrowserWindowGtk* browser_win) {
  browser_win->OnStateChanged(event->new_window_state);
  return FALSE;
}

// Using gtk_window_get_position/size creates a race condition, so only use
// this to get the initial bounds.  After window creation, we pick up the
// normal bounds by connecting to the configure-event signal.
gfx::Rect GetInitialWindowBounds(GtkWindow* window) {
  gint x, y, width, height;
  gtk_window_get_position(window, &x, &y);
  gtk_window_get_size(window, &width, &height);
  return gfx::Rect(x, y, width, height);
}

}  // namespace

BrowserWindowGtk::BrowserWindowGtk(Browser* browser) : browser_(browser) {
  Init();
}

BrowserWindowGtk::~BrowserWindowGtk() {
  Close();
}

void BrowserWindowGtk::Init() {
  window_ = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
  gtk_window_set_title(window_, "Chromium");
  gtk_window_set_default_size(window_, 640, 480);
  g_signal_connect(G_OBJECT(window_), "destroy",
                   G_CALLBACK(MainWindowDestroyed), this);
  g_signal_connect(G_OBJECT(window_), "configure-event",
                   G_CALLBACK(MainWindowConfigured), this);
  g_signal_connect(G_OBJECT(window_), "window-state-event",
                   G_CALLBACK(MainWindowStateChanged), this);
  bounds_ = GetInitialWindowBounds(window_);

  vbox_ = gtk_vbox_new(FALSE, 0);

  toolbar_.reset(new BrowserToolbarGtk(browser_.get()));
  toolbar_->Init(browser_->profile());
  toolbar_->AddToolbarToBox(vbox_);

  gtk_container_add(GTK_CONTAINER(window_), vbox_);
}

void BrowserWindowGtk::Show() {
  // TODO(estade): fix this block. As it stands, it is a temporary hack to get
  // the browser displaying something.
  if (content_area_ == NULL) {
    WebContents* contents = (WebContents*)(browser_->GetTabContentsAt(0));
    content_area_ = ((RenderWidgetHostViewGtk*)contents->
        render_view_host()->view())->native_view();
    gtk_box_pack_start(GTK_BOX(vbox_), content_area_, TRUE, TRUE, 0);
    contents->NavigateToPendingEntry(false);
  }

  gtk_widget_show_all(GTK_WIDGET(window_));
}

void BrowserWindowGtk::SetBounds(const gfx::Rect& bounds) {
  gint x = static_cast<gint>(bounds.x());
  gint y = static_cast<gint>(bounds.y());
  gint width = static_cast<gint>(bounds.width());
  gint height = static_cast<gint>(bounds.height());

  gtk_window_move(window_, x, y);
  gtk_window_resize(window_, width, height);
}

void BrowserWindowGtk::Close() {
  if (!window_)
    return;

  gtk_widget_destroy(GTK_WIDGET(window_));
  window_ = NULL;
}

void BrowserWindowGtk::Activate() {
  gtk_window_present(window_);
}

void BrowserWindowGtk::FlashFrame() {
  // May not be respected by all window managers.
  gtk_window_set_urgency_hint(window_, TRUE);
}

void* BrowserWindowGtk::GetNativeHandle() {
  return window_;
}

BrowserWindowTesting* BrowserWindowGtk::GetBrowserWindowTesting() {
  NOTIMPLEMENTED();
  return NULL;
}

StatusBubble* BrowserWindowGtk::GetStatusBubble() {
  NOTIMPLEMENTED();
  return NULL;
}

void BrowserWindowGtk::SelectedTabToolbarSizeChanged(bool is_animating) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::UpdateTitleBar() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::UpdateLoadingAnimations(bool should_animate) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::SetStarredState(bool is_starred) {
  NOTIMPLEMENTED();
}

gfx::Rect BrowserWindowGtk::GetNormalBounds() const {
  return bounds_;
}

bool BrowserWindowGtk::IsMaximized() {
  return (state_ & GDK_WINDOW_STATE_MAXIMIZED);
}

LocationBar* BrowserWindowGtk::GetLocationBar() const {
  NOTIMPLEMENTED();
  return NULL;
}

void BrowserWindowGtk::UpdateStopGoState(bool is_loading) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::UpdateToolbar(TabContents* contents,
                                     bool should_restore_state) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::FocusToolbar() {
  NOTIMPLEMENTED();
}

bool BrowserWindowGtk::IsBookmarkBarVisible() const {
  NOTIMPLEMENTED();
  return false;
}

void BrowserWindowGtk::ToggleBookmarkBar() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowAboutChromeDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowBookmarkManager() {
  NOTIMPLEMENTED();
}

bool BrowserWindowGtk::IsBookmarkBubbleVisible() const {
  NOTIMPLEMENTED();
  return false;
}

void BrowserWindowGtk::ShowBookmarkBubble(const GURL& url,
                                          bool already_bookmarked) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowReportBugDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowClearBrowsingDataDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowImportDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowSearchEnginesDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowPasswordManager() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowSelectProfileDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowNewProfileDialog() {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::ShowHTMLDialog(HtmlDialogContentsDelegate* delegate,
                                      void* parent_window) {
  NOTIMPLEMENTED();
}

void BrowserWindowGtk::DestroyBrowser() {
  browser_.reset();
}

void BrowserWindowGtk::OnBoundsChanged(const gfx::Rect& bounds) {
  bounds_ = bounds;
}

void BrowserWindowGtk::OnStateChanged(GdkWindowState state) {
  state_ = state;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/atom_bindings.h"

#include <algorithm>
#include <iostream>
#include <string>

#include "atom/common/atom_version.h"
#include "atom/common/chrome_version.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "base/logging.h"
#include "base/sys_info.h"
#include "native_mate/dictionary.h"

namespace atom {

namespace {

// Dummy class type that used for crashing the program.
struct DummyClass { bool crash; };

// Called when there is a fatal error in V8, we just crash the process here so
// we can get the stack trace.
void FatalErrorCallback(const char* location, const char* message) {
  LOG(ERROR) << "Fatal error in V8: " << location << " " << message;
  AtomBindings::Crash();
}

}  // namespace

AtomBindings::AtomBindings(uv_loop_t* loop) {
  uv_async_init(loop, &call_next_tick_async_, OnCallNextTick);
  call_next_tick_async_.data = this;
  metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics();
}

AtomBindings::~AtomBindings() {
  uv_close(reinterpret_cast<uv_handle_t*>(&call_next_tick_async_), nullptr);
}

void AtomBindings::BindTo(v8::Isolate* isolate,
                          v8::Local<v8::Object> process) {
  v8::V8::SetFatalErrorHandler(FatalErrorCallback);

  mate::Dictionary dict(isolate, process);
  dict.SetMethod("crash", &AtomBindings::Crash);
  dict.SetMethod("hang", &Hang);
  dict.SetMethod("log", &Log);
  dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo);
  dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo);
  dict.SetMethod("getCPUUsage",
      base::Bind(&AtomBindings::GetCPUUsage, base::Unretained(this)));
  dict.SetMethod("getIOCounters", &GetIOCounters);
#if defined(OS_POSIX)
  dict.SetMethod("setFdLimit", &base::SetFdLimit);
#endif
  dict.SetMethod("activateUvLoop",
      base::Bind(&AtomBindings::ActivateUVLoop, base::Unretained(this)));

#if defined(MAS_BUILD)
  dict.Set("mas", true);
#endif

  mate::Dictionary versions;
  if (dict.Get("versions", &versions)) {
    // TODO(kevinsawicki): Make read-only in 2.0 to match node
    versions.Set(ATOM_PROJECT_NAME, ATOM_VERSION_STRING);
    versions.Set("chrome", CHROME_VERSION_STRING);

    // TODO(kevinsawicki): Remove in 2.0
    versions.Set("atom-shell", ATOM_VERSION_STRING);
  }
}

void AtomBindings::EnvironmentDestroyed(node::Environment* env) {
  auto it = std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(),
                      env);
  if (it != pending_next_ticks_.end())
    pending_next_ticks_.erase(it);
}

void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) {
  node::Environment* env = node::Environment::GetCurrent(isolate);
  if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) !=
      pending_next_ticks_.end())
    return;

  pending_next_ticks_.push_back(env);
  uv_async_send(&call_next_tick_async_);
}

// static
void AtomBindings::OnCallNextTick(uv_async_t* handle) {
  AtomBindings* self = static_cast<AtomBindings*>(handle->data);
  for (std::list<node::Environment*>::const_iterator it =
           self->pending_next_ticks_.begin();
       it != self->pending_next_ticks_.end(); ++it) {
    node::Environment* env = *it;
    // KickNextTick, copied from node.cc:
    node::Environment::AsyncCallbackScope callback_scope(env);
    if (callback_scope.in_makecallback())
      continue;
    node::Environment::TickInfo* tick_info = env->tick_info();
    if (tick_info->length() == 0)
      env->isolate()->RunMicrotasks();
    v8::Local<v8::Object> process = env->process_object();
    if (tick_info->length() == 0)
      tick_info->set_index(0);
    env->tick_callback_function()->Call(process, 0, nullptr).IsEmpty();
  }

  self->pending_next_ticks_.clear();
}

// static
void AtomBindings::Log(const base::string16& message) {
  std::cout << message << std::flush;
}

// static
void AtomBindings::Crash() {
  static_cast<DummyClass*>(nullptr)->crash = true;
}

// static
void AtomBindings::Hang() {
  for (;;)
    base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
}

// static
v8::Local<v8::Value> AtomBindings::GetProcessMemoryInfo(v8::Isolate* isolate) {
  std::unique_ptr<base::ProcessMetrics> metrics(
      base::ProcessMetrics::CreateCurrentProcessMetrics());

  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("workingSetSize",
           static_cast<double>(metrics->GetWorkingSetSize() >> 10));
  dict.Set("peakWorkingSetSize",
           static_cast<double>(metrics->GetPeakWorkingSetSize() >> 10));

  size_t private_bytes, shared_bytes;
  if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) {
    dict.Set("privateBytes", static_cast<double>(private_bytes >> 10));
    dict.Set("sharedBytes", static_cast<double>(shared_bytes >> 10));
  }

  return dict.GetHandle();
}

// static
v8::Local<v8::Value> AtomBindings::GetSystemMemoryInfo(v8::Isolate* isolate,
    mate::Arguments* args) {
  base::SystemMemoryInfoKB mem_info;
  if (!base::GetSystemMemoryInfo(&mem_info)) {
    args->ThrowError("Unable to retrieve system memory information");
    return v8::Undefined(isolate);
  }

  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("total", mem_info.total);
  dict.Set("free", mem_info.free);

  // NB: These return bogus values on macOS
#if !defined(OS_MACOSX)
  dict.Set("swapTotal", mem_info.swap_total);
  dict.Set("swapFree", mem_info.swap_free);
#endif

  return dict.GetHandle();
}

v8::Local<v8::Value> AtomBindings::GetCPUUsage(v8::Isolate* isolate) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  int processor_count = base::SysInfo::NumberOfProcessors();
  dict.Set("percentCPUUsage",
           metrics_->GetPlatformIndependentCPUUsage() / processor_count);
  dict.Set("idleWakeupsPerSecond", metrics_->GetIdleWakeupsPerSecond());

  return dict.GetHandle();
}

// static
v8::Local<v8::Value> AtomBindings::GetIOCounters(v8::Isolate* isolate) {
  std::unique_ptr<base::ProcessMetrics> metrics(
      base::ProcessMetrics::CreateCurrentProcessMetrics());
  base::IoCounters io_counters;
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);

  if (metrics->GetIOCounters(&io_counters)) {
    dict.Set("readOperationCount", io_counters.ReadOperationCount);
    dict.Set("writeOperationCount", io_counters.WriteOperationCount);
    dict.Set("otherOperationCount", io_counters.OtherOperationCount);
    dict.Set("readTransferCount", io_counters.ReadTransferCount);
    dict.Set("writeTransferCount", io_counters.WriteTransferCount);
    dict.Set("otherTransferCount", io_counters.OtherTransferCount);
  }

  return dict.GetHandle();
}

}  // namespace atom
<commit_msg>Fix free memory calculation.<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/atom_bindings.h"

#include <algorithm>
#include <iostream>
#include <string>

#include "atom/common/atom_version.h"
#include "atom/common/chrome_version.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "base/logging.h"
#include "base/sys_info.h"
#include "native_mate/dictionary.h"

namespace atom {

namespace {

// Dummy class type that used for crashing the program.
struct DummyClass { bool crash; };

// Called when there is a fatal error in V8, we just crash the process here so
// we can get the stack trace.
void FatalErrorCallback(const char* location, const char* message) {
  LOG(ERROR) << "Fatal error in V8: " << location << " " << message;
  AtomBindings::Crash();
}

}  // namespace

AtomBindings::AtomBindings(uv_loop_t* loop) {
  uv_async_init(loop, &call_next_tick_async_, OnCallNextTick);
  call_next_tick_async_.data = this;
  metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics();
}

AtomBindings::~AtomBindings() {
  uv_close(reinterpret_cast<uv_handle_t*>(&call_next_tick_async_), nullptr);
}

void AtomBindings::BindTo(v8::Isolate* isolate,
                          v8::Local<v8::Object> process) {
  v8::V8::SetFatalErrorHandler(FatalErrorCallback);

  mate::Dictionary dict(isolate, process);
  dict.SetMethod("crash", &AtomBindings::Crash);
  dict.SetMethod("hang", &Hang);
  dict.SetMethod("log", &Log);
  dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo);
  dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo);
  dict.SetMethod("getCPUUsage",
      base::Bind(&AtomBindings::GetCPUUsage, base::Unretained(this)));
  dict.SetMethod("getIOCounters", &GetIOCounters);
#if defined(OS_POSIX)
  dict.SetMethod("setFdLimit", &base::SetFdLimit);
#endif
  dict.SetMethod("activateUvLoop",
      base::Bind(&AtomBindings::ActivateUVLoop, base::Unretained(this)));

#if defined(MAS_BUILD)
  dict.Set("mas", true);
#endif

  mate::Dictionary versions;
  if (dict.Get("versions", &versions)) {
    // TODO(kevinsawicki): Make read-only in 2.0 to match node
    versions.Set(ATOM_PROJECT_NAME, ATOM_VERSION_STRING);
    versions.Set("chrome", CHROME_VERSION_STRING);

    // TODO(kevinsawicki): Remove in 2.0
    versions.Set("atom-shell", ATOM_VERSION_STRING);
  }
}

void AtomBindings::EnvironmentDestroyed(node::Environment* env) {
  auto it = std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(),
                      env);
  if (it != pending_next_ticks_.end())
    pending_next_ticks_.erase(it);
}

void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) {
  node::Environment* env = node::Environment::GetCurrent(isolate);
  if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) !=
      pending_next_ticks_.end())
    return;

  pending_next_ticks_.push_back(env);
  uv_async_send(&call_next_tick_async_);
}

// static
void AtomBindings::OnCallNextTick(uv_async_t* handle) {
  AtomBindings* self = static_cast<AtomBindings*>(handle->data);
  for (std::list<node::Environment*>::const_iterator it =
           self->pending_next_ticks_.begin();
       it != self->pending_next_ticks_.end(); ++it) {
    node::Environment* env = *it;
    // KickNextTick, copied from node.cc:
    node::Environment::AsyncCallbackScope callback_scope(env);
    if (callback_scope.in_makecallback())
      continue;
    node::Environment::TickInfo* tick_info = env->tick_info();
    if (tick_info->length() == 0)
      env->isolate()->RunMicrotasks();
    v8::Local<v8::Object> process = env->process_object();
    if (tick_info->length() == 0)
      tick_info->set_index(0);
    env->tick_callback_function()->Call(process, 0, nullptr).IsEmpty();
  }

  self->pending_next_ticks_.clear();
}

// static
void AtomBindings::Log(const base::string16& message) {
  std::cout << message << std::flush;
}

// static
void AtomBindings::Crash() {
  static_cast<DummyClass*>(nullptr)->crash = true;
}

// static
void AtomBindings::Hang() {
  for (;;)
    base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
}

// static
v8::Local<v8::Value> AtomBindings::GetProcessMemoryInfo(v8::Isolate* isolate) {
  std::unique_ptr<base::ProcessMetrics> metrics(
      base::ProcessMetrics::CreateCurrentProcessMetrics());

  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("workingSetSize",
           static_cast<double>(metrics->GetWorkingSetSize() >> 10));
  dict.Set("peakWorkingSetSize",
           static_cast<double>(metrics->GetPeakWorkingSetSize() >> 10));

  size_t private_bytes, shared_bytes;
  if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) {
    dict.Set("privateBytes", static_cast<double>(private_bytes >> 10));
    dict.Set("sharedBytes", static_cast<double>(shared_bytes >> 10));
  }

  return dict.GetHandle();
}

// static
v8::Local<v8::Value> AtomBindings::GetSystemMemoryInfo(v8::Isolate* isolate,
    mate::Arguments* args) {
  base::SystemMemoryInfoKB mem_info;
  if (!base::GetSystemMemoryInfo(&mem_info)) {
    args->ThrowError("Unable to retrieve system memory information");
    return v8::Undefined(isolate);
  }

  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("total", mem_info.total);

  // See Chromium's "base/process/process_metrics.h" for an explanation.
  int free =
#if defined(OS_WIN)
      mem_info.avail_phys;
#else
      mem_info.free;
#endif
  dict.Set("free", free);

  // NB: These return bogus values on macOS
#if !defined(OS_MACOSX)
  dict.Set("swapTotal", mem_info.swap_total);
  dict.Set("swapFree", mem_info.swap_free);
#endif

  return dict.GetHandle();
}

v8::Local<v8::Value> AtomBindings::GetCPUUsage(v8::Isolate* isolate) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  int processor_count = base::SysInfo::NumberOfProcessors();
  dict.Set("percentCPUUsage",
           metrics_->GetPlatformIndependentCPUUsage() / processor_count);
  dict.Set("idleWakeupsPerSecond", metrics_->GetIdleWakeupsPerSecond());

  return dict.GetHandle();
}

// static
v8::Local<v8::Value> AtomBindings::GetIOCounters(v8::Isolate* isolate) {
  std::unique_ptr<base::ProcessMetrics> metrics(
      base::ProcessMetrics::CreateCurrentProcessMetrics());
  base::IoCounters io_counters;
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);

  if (metrics->GetIOCounters(&io_counters)) {
    dict.Set("readOperationCount", io_counters.ReadOperationCount);
    dict.Set("writeOperationCount", io_counters.WriteOperationCount);
    dict.Set("otherOperationCount", io_counters.OtherOperationCount);
    dict.Set("readTransferCount", io_counters.ReadTransferCount);
    dict.Set("writeTransferCount", io_counters.WriteTransferCount);
    dict.Set("otherTransferCount", io_counters.OtherTransferCount);
  }

  return dict.GetHandle();
}

}  // namespace atom
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2020 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Modules/Factory/ModuleDescriptionLookup.h>
#include <Modules/Fields/InterfaceWithCleaver.h>
#include <Modules/Fields/RefineTetMeshLocally.h>
#include <Modules/Legacy/Fields/MapFieldDataFromElemToNode.h>
#include <Modules/Legacy/Fields/MapFieldDataFromNodeToElem.h>
#include <Modules/Legacy/Fields/CalculateVectorMagnitudes.h>
#include <Modules/Legacy/Fields/CalculateGradients.h>
#include <Modules/Legacy/Fields/ConvertFieldBasis.h>
#include <Modules/Legacy/Fields/GetFieldData.h>
#include <Modules/Legacy/Fields/SetFieldData.h>
#include <Modules/Legacy/Fields/ApplyMappingMatrix.h>
#include <Modules/Legacy/Fields/SplitFieldByConnectedRegion.h>
#include <Modules/Legacy/Math/SelectSubMatrix.h>
#include <Modules/Legacy/Math/ConvertMatrixType.h>
#include <Modules/BrainStimulator/ElectrodeCoilSetup.h>
#include <Modules/BrainStimulator/SetConductivitiesToTetMesh.h>
#include <Modules/BrainStimulator/SetupRHSforTDCSandTMS.h>
#include <Modules/BrainStimulator/GenerateROIStatistics.h>
#include <Modules/BrainStimulator/SimulateForwardMagneticField.h>
#include <Modules/Legacy/Math/AddKnownsToLinearSystem.h>
#include <Modules/Legacy/FiniteElements/BuildTDCSMatrix.h>
#include <Modules/Legacy/FiniteElements/BuildFEVolRHS.h>
#include <Modules/Legacy/Visualization/GenerateStreamLines.h>
#include <Modules/Legacy/Inverse/BuildSurfaceLaplacianMatrix.h>
#include <Modules/Legacy/Fields/ConvertHexVolToTetVol.h>
#include <Modules/Legacy/Fields/ExtractSimpleIsosurface.h>
#include <Modules/Legacy/Fields/ClipVolumeByIsovalue.h>
#include <Modules/Math/ComputePCA.h>
#include <Modules/Visualization/ShowString.h>

using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules;
using namespace SCIRun::Modules::Factory;
using namespace SCIRun::Modules::Math;
using namespace SCIRun::Modules::Fields;
using namespace SCIRun::Modules::FiniteElements;
using namespace SCIRun::Modules::BrainStimulator;
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Modules::Inverse;

void ModuleDescriptionLookup::addBrainSpecificModules()
{
  addModuleDesc<ElectrodeCoilSetup>("ElectrodeCoilSetup", "BrainStimulator", "SCIRun", " in progress ", " Place tDCS electrodes and TMS coils ");
  addModuleDesc<SetConductivitiesToMesh>("SetConductivitiesToMesh", "BrainStimulator", "SCIRun", "New module", " Sets conveniently conductivity profile for tetrahedral mesh ");
  addModuleDesc<GenerateROIStatistics>("GenerateROIStatistics", "BrainStimulator", "SCIRun", " in progress ", " Roi statistics ");
  addModuleDesc<SetupTDCS>("SetupTDCS", "BrainStimulator", "SCIRun", " in progress ", " set RHS for tDCS and TMS ");
}

void ModuleDescriptionLookup::addMoreModules()
{
  addModuleDesc<AddKnownsToLinearSystem>("AddKnownsToLinearSystem", "Math", "SCIRun", "Real ported module", "...");
  addModuleDesc<CalculateVectorMagnitudes>("CalculateVectorMagnitudes", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<CalculateGradients >("CalculateGradients", "ChangeFieldData", "SCIRun", "Real ported module", "...");
	addModuleDesc<ConvertFieldBasis>("ConvertFieldBasis", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<GetFieldData>("GetFieldData", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<InterfaceWithCleaver>("InterfaceWithCleaver", "NewField", "SCIRun", "New module", "...");
  addModuleDesc<SetFieldData>("SetFieldData", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<SelectSubMatrix>("SelectSubMatrix", "Math", "SCIRun", "Real ported module", "...");
  addModuleDesc<MapFieldDataFromElemToNode>("MapFieldDataFromElemToNode", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<ApplyMappingMatrix>("ApplyMappingMatrix", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<ConvertMatrixType>("ConvertMatrixType", "Math", "SCIRun", "Real ported module", "...");
  addModuleDesc<MapFieldDataFromNodeToElem>("MapFieldDataFromNodeToElem", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<BuildFEVolRHS>("BuildFEVolRHS", "FiniteElements", "SCIRun", "Real ported module", "...");
  addModuleDesc<GenerateStreamLines>("in progress--needs testing", "...");
  addModuleDesc<ConvertHexVolToTetVol>("ConvertHexVolToTetVol", "ChangeMesh", "SCIRun", "Real ported module", "...");
  addModuleDesc<BuildSurfaceLaplacianMatrix>("BuildSurfaceLaplacianMatrix","Inverse","SCIRun","...","...");
  addModuleDesc<ExtractIsosurface>("...","...");
  addModuleDesc<ExtractIsosurface>("ExtractSimpleIsosurface", "NewField", "SCIRun", "...", "...");
  addModuleDesc<ComputePCA>("ComputePCA","Math","SCIRun","...","...");
  addModuleDesc<ClipVolumeByIsovalue>("ClipVolumeByIsovalue","NewField","SCIRun","...","...");
  addModuleDesc<RefineTetMeshLocally>("RefineTetMeshLocally","ChangeMesh","SCIRun","...","...");
  addModuleDesc<ShowString>("in progress--needs testing", "...");
}
<commit_msg>Duplicate module in factory<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2020 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Modules/Factory/ModuleDescriptionLookup.h>
#include <Modules/Fields/InterfaceWithCleaver.h>
#include <Modules/Fields/RefineTetMeshLocally.h>
#include <Modules/Legacy/Fields/MapFieldDataFromElemToNode.h>
#include <Modules/Legacy/Fields/MapFieldDataFromNodeToElem.h>
#include <Modules/Legacy/Fields/CalculateVectorMagnitudes.h>
#include <Modules/Legacy/Fields/ConvertFieldBasis.h>
#include <Modules/Legacy/Fields/GetFieldData.h>
#include <Modules/Legacy/Fields/SetFieldData.h>
#include <Modules/Legacy/Fields/ApplyMappingMatrix.h>
#include <Modules/Legacy/Fields/SplitFieldByConnectedRegion.h>
#include <Modules/Legacy/Math/SelectSubMatrix.h>
#include <Modules/Legacy/Math/ConvertMatrixType.h>
#include <Modules/BrainStimulator/ElectrodeCoilSetup.h>
#include <Modules/BrainStimulator/SetConductivitiesToTetMesh.h>
#include <Modules/BrainStimulator/SetupRHSforTDCSandTMS.h>
#include <Modules/BrainStimulator/GenerateROIStatistics.h>
#include <Modules/BrainStimulator/SimulateForwardMagneticField.h>
#include <Modules/Legacy/Math/AddKnownsToLinearSystem.h>
#include <Modules/Legacy/FiniteElements/BuildTDCSMatrix.h>
#include <Modules/Legacy/FiniteElements/BuildFEVolRHS.h>
#include <Modules/Legacy/Visualization/GenerateStreamLines.h>
#include <Modules/Legacy/Inverse/BuildSurfaceLaplacianMatrix.h>
#include <Modules/Legacy/Fields/ConvertHexVolToTetVol.h>
#include <Modules/Legacy/Fields/ExtractSimpleIsosurface.h>
#include <Modules/Legacy/Fields/ClipVolumeByIsovalue.h>
#include <Modules/Math/ComputePCA.h>
#include <Modules/Visualization/ShowString.h>

using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules;
using namespace SCIRun::Modules::Factory;
using namespace SCIRun::Modules::Math;
using namespace SCIRun::Modules::Fields;
using namespace SCIRun::Modules::FiniteElements;
using namespace SCIRun::Modules::BrainStimulator;
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Modules::Inverse;

void ModuleDescriptionLookup::addBrainSpecificModules()
{
  addModuleDesc<ElectrodeCoilSetup>("ElectrodeCoilSetup", "BrainStimulator", "SCIRun", " in progress ", " Place tDCS electrodes and TMS coils ");
  addModuleDesc<SetConductivitiesToMesh>("SetConductivitiesToMesh", "BrainStimulator", "SCIRun", "New module", " Sets conveniently conductivity profile for tetrahedral mesh ");
  addModuleDesc<GenerateROIStatistics>("GenerateROIStatistics", "BrainStimulator", "SCIRun", " in progress ", " Roi statistics ");
  addModuleDesc<SetupTDCS>("SetupTDCS", "BrainStimulator", "SCIRun", " in progress ", " set RHS for tDCS and TMS ");
}

void ModuleDescriptionLookup::addMoreModules()
{
  addModuleDesc<AddKnownsToLinearSystem>("AddKnownsToLinearSystem", "Math", "SCIRun", "Real ported module", "...");
  addModuleDesc<CalculateVectorMagnitudes>("CalculateVectorMagnitudes", "ChangeFieldData", "SCIRun", "Real ported module", "...");
	addModuleDesc<ConvertFieldBasis>("ConvertFieldBasis", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<GetFieldData>("GetFieldData", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<InterfaceWithCleaver>("InterfaceWithCleaver", "NewField", "SCIRun", "New module", "...");
  addModuleDesc<SetFieldData>("SetFieldData", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<SelectSubMatrix>("SelectSubMatrix", "Math", "SCIRun", "Real ported module", "...");
  addModuleDesc<MapFieldDataFromElemToNode>("MapFieldDataFromElemToNode", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<ApplyMappingMatrix>("ApplyMappingMatrix", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<ConvertMatrixType>("ConvertMatrixType", "Math", "SCIRun", "Real ported module", "...");
  addModuleDesc<MapFieldDataFromNodeToElem>("MapFieldDataFromNodeToElem", "ChangeFieldData", "SCIRun", "Real ported module", "...");
  addModuleDesc<BuildFEVolRHS>("BuildFEVolRHS", "FiniteElements", "SCIRun", "Real ported module", "...");
  addModuleDesc<GenerateStreamLines>("in progress--needs testing", "...");
  addModuleDesc<ConvertHexVolToTetVol>("ConvertHexVolToTetVol", "ChangeMesh", "SCIRun", "Real ported module", "...");
  addModuleDesc<BuildSurfaceLaplacianMatrix>("BuildSurfaceLaplacianMatrix","Inverse","SCIRun","...","...");
  addModuleDesc<ExtractIsosurface>("...","...");
  addModuleDesc<ExtractIsosurface>("ExtractSimpleIsosurface", "NewField", "SCIRun", "...", "...");
  addModuleDesc<ComputePCA>("ComputePCA","Math","SCIRun","...","...");
  addModuleDesc<ClipVolumeByIsovalue>("ClipVolumeByIsovalue","NewField","SCIRun","...","...");
  addModuleDesc<RefineTetMeshLocally>("RefineTetMeshLocally","ChangeMesh","SCIRun","...","...");
  addModuleDesc<ShowString>("in progress--needs testing", "...");
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "PolylineCompressor.h"
#include "../DataStructures/SegmentInformation.h"

#include <osrm/Coordinate.h>

void PolylineCompressor::encodeVectorSignedNumber(std::vector<int> &numbers, std::string &output)
    const
{
    const unsigned end = static_cast<unsigned>(numbers.size());
    for (unsigned i = 0; i < end; ++i)
    {
        numbers[i] <<= 1;
        if (numbers[i] < 0)
        {
            numbers[i] = ~(numbers[i]);
        }
    }
    for (const int number: numbers)
    {
        encodeNumber(number, output);
    }
}

void PolylineCompressor::encodeNumber(int number_to_encode, std::string &output) const
{
    while (number_to_encode >= 0x20)
    {
        const int next_value = (0x20 | (number_to_encode & 0x1f)) + 63;
        output += static_cast<char>(next_value);
        if (92 == next_value)
        {
            output += static_cast<char>(next_value);
        }
        number_to_encode >>= 5;
    }

    number_to_encode += 63;
    output += static_cast<char>(number_to_encode);
    if (92 == number_to_encode)
    {
        output += static_cast<char>(number_to_encode);
    }
}

JSON::String PolylineCompressor::printEncodedString(const std::vector<SegmentInformation> &polyline) const
{
    std::string output;
    std::vector<int> delta_numbers;
    if (!polyline.empty())
    {
        FixedPointCoordinate last_coordinate = polyline[0].location;
        delta_numbers.emplace_back(last_coordinate.lat);
        delta_numbers.emplace_back(last_coordinate.lon);
        for (const auto & segment : polyline)
        {
            if (segment.necessary)
            {
                int lat_diff = segment.location.lat - last_coordinate.lat;
                int lon_diff = segment.location.lon - last_coordinate.lon;
                delta_numbers.emplace_back(lat_diff);
                delta_numbers.emplace_back(lon_diff);
                last_coordinate = segment.location;
            }
        }
        encodeVectorSignedNumber(delta_numbers, output);
    }
    JSON::String return_value(output);
    return return_value;
}

JSON::Array PolylineCompressor::printUnencodedString(const std::vector<SegmentInformation> &polyline) const
{
    JSON::Array json_geometry_array;
    for( const auto & segment : polyline)
    {
        if (segment.necessary)
        {
            std::string tmp, output;
            FixedPointCoordinate::convertInternalLatLonToString(segment.location.lat, tmp);
            output += (tmp + ",");
            FixedPointCoordinate::convertInternalLatLonToString(segment.location.lon, tmp);
            output += tmp;
            json_geometry_array.values.push_back(output);
        }
    }
    return json_geometry_array;
}
<commit_msg>reformat to cut long line<commit_after>/*

Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "PolylineCompressor.h"
#include "../DataStructures/SegmentInformation.h"

#include <osrm/Coordinate.h>

void PolylineCompressor::encodeVectorSignedNumber(std::vector<int> &numbers, std::string &output)
    const
{
    const unsigned end = static_cast<unsigned>(numbers.size());
    for (unsigned i = 0; i < end; ++i)
    {
        numbers[i] <<= 1;
        if (numbers[i] < 0)
        {
            numbers[i] = ~(numbers[i]);
        }
    }
    for (const int number : numbers)
    {
        encodeNumber(number, output);
    }
}

void PolylineCompressor::encodeNumber(int number_to_encode, std::string &output) const
{
    while (number_to_encode >= 0x20)
    {
        const int next_value = (0x20 | (number_to_encode & 0x1f)) + 63;
        output += static_cast<char>(next_value);
        if (92 == next_value)
        {
            output += static_cast<char>(next_value);
        }
        number_to_encode >>= 5;
    }

    number_to_encode += 63;
    output += static_cast<char>(number_to_encode);
    if (92 == number_to_encode)
    {
        output += static_cast<char>(number_to_encode);
    }
}

JSON::String PolylineCompressor::printEncodedString(const std::vector<SegmentInformation> &polyline)
    const
{
    std::string output;
    std::vector<int> delta_numbers;
    if (!polyline.empty())
    {
        FixedPointCoordinate last_coordinate = polyline[0].location;
        delta_numbers.emplace_back(last_coordinate.lat);
        delta_numbers.emplace_back(last_coordinate.lon);
        for (const auto &segment : polyline)
        {
            if (segment.necessary)
            {
                int lat_diff = segment.location.lat - last_coordinate.lat;
                int lon_diff = segment.location.lon - last_coordinate.lon;
                delta_numbers.emplace_back(lat_diff);
                delta_numbers.emplace_back(lon_diff);
                last_coordinate = segment.location;
            }
        }
        encodeVectorSignedNumber(delta_numbers, output);
    }
    JSON::String return_value(output);
    return return_value;
}

JSON::Array
PolylineCompressor::printUnencodedString(const std::vector<SegmentInformation> &polyline) const
{
    JSON::Array json_geometry_array;
    for (const auto &segment : polyline)
    {
        if (segment.necessary)
        {
            std::string tmp, output;
            FixedPointCoordinate::convertInternalLatLonToString(segment.location.lat, tmp);
            output += (tmp + ",");
            FixedPointCoordinate::convertInternalLatLonToString(segment.location.lon, tmp);
            output += tmp;
            json_geometry_array.values.push_back(output);
        }
    }
    return json_geometry_array;
}
<|endoftext|>


<commit_before>#include <ORM/backends/Sqlite3/Sqlite3Query.hpp>
#include <ORM/backends/Sqlite3/Sqlite3Bdd.hpp>

namespace orm
{
    Sqlite3Query::Sqlite3Query(Bdd& bdd,const std::string& query) : Query(bdd,query), statement(0)
    {
        int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd&>(bdd).dbConn,query.c_str(),query.size()+1, &statement, NULL);

        #if ORM_VERBOSITY & ORM_ERROR
        if (result != SQLITE_OK)
        {
            ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&) Failed to make the statment : "<<sqlite3_errstr(result));
        }
        #endif
    };

    Sqlite3Query::Sqlite3Query(Bdd& bdd,std::string&& query) : Query(bdd,query), statement(0)
    {
        int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd&>(bdd).dbConn,query.c_str(),query.size()+1, &statement, NULL);

        #if ORM_VERBOSITY & ORM_ERROR
        if (result != SQLITE_OK)
        {
            ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&&) Failed to make the statment")
            /// \todo <<sqlite3_errstr(result)<<std::endl;
        }
        #endif
    };

    Sqlite3Query::~Sqlite3Query()
    {
        if(statement)
        {
            int result = sqlite3_finalize(statement);

            #if ORM_VERBOSITY & ORM_ERROR
            if(result != SQLITE_OK)
            {
                ORM_PRINT_ERROR("Sqlite3Query::~Sqlite3Query() Failed to close the statement")
                /// \todo <<sqlite3_errstr(result)<<std::endl;
            }
            #endif
        }
    };

    int Sqlite3Query::count()const
    {
        return sqlite3_data_count(statement);
    };

    bool Sqlite3Query::get(bool& value,const int& column)const
    {
        value = (bool)sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::get(int& value,const int& column)const
    {
        value = sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::getPk(int& value, const int& colum)const
    {
        if(sqlite3_column_type(statement,colum) == SQLITE_NULL)
        {
            value = -1;
            return false;
        }
        value = sqlite3_column_int(statement,colum);
        return true;
    }

    bool Sqlite3Query::get(unsigned int& value,const int& column)const
    {
        value = (unsigned int)sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long long int& value,const int& column)const
    {
        value = (long long int)sqlite3_column_int64(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long long unsigned int& value,const int& column)const
    {
        value = (unsigned long long int)sqlite3_column_int64(statement,column);

        return true;
    };

    bool Sqlite3Query::get(float& value,const int& column)const
    {
        value = (float)sqlite3_column_double(statement,column);
        return true;
    };

    bool Sqlite3Query::get(double& value,const int& column)const
    {
        value = (double)sqlite3_column_double(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long double& value,const int& column)const
    {
        value = (long double)sqlite3_column_double(statement,column);
        return true;
    };

    bool Sqlite3Query::get(std::string& value,const int& column)const
    {
        const unsigned char* res = sqlite3_column_text(statement,column);

        if (res)
            value = (const char*)res;
        else
            value = "";

        return true;
    };

    bool Sqlite3Query::next()
    {
        int result = sqlite3_step(statement);
        if(result == SQLITE_ROW)
            return true;

        ORM_PRINT_WARNING("Sqlite3Query::next() imposible to get next row")
        ///\ todo sqlite3_errstr(result)<<std::endl;

        return false;

    }

    bool Sqlite3Query::set(const bool& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const unsigned int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long long int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long long unsigned int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const float& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const double& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long double& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const std::string& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_text(statement,(int)column,value.c_str(),-1,SQLITE_TRANSIENT)== SQLITE_OK);
    };

    bool Sqlite3Query::setNull(const int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_null(statement,(int)column)== SQLITE_OK);
    };

    void Sqlite3Query::executeQuery()
    {
    };

};
<commit_msg>remove sqlite3 error<commit_after>#include <ORM/backends/Sqlite3/Sqlite3Query.hpp>
#include <ORM/backends/Sqlite3/Sqlite3Bdd.hpp>

namespace orm
{
    Sqlite3Query::Sqlite3Query(Bdd& bdd,const std::string& query) : Query(bdd,query), statement(0)
    {
        int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd&>(bdd).dbConn,query.c_str(),query.size()+1, &statement, NULL);

        #if ORM_VERBOSITY & ORM_ERROR
        if (result != SQLITE_OK)
        {
            ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&) Failed to make the statment");
            //\todo: "<<sqlite3_errstr(result));
        }
        #endif
    };

    Sqlite3Query::Sqlite3Query(Bdd& bdd,std::string&& query) : Query(bdd,query), statement(0)
    {
        int result = sqlite3_prepare_v2(static_cast<Sqlite3Bdd&>(bdd).dbConn,query.c_str(),query.size()+1, &statement, NULL);

        #if ORM_VERBOSITY & ORM_ERROR
        if (result != SQLITE_OK)
        {
            ORM_PRINT_ERROR("Sqlite3Query::Sqlite3Query(bdd,string&&) Failed to make the statment")
            /// \todo <<sqlite3_errstr(result)<<std::endl;
        }
        #endif
    };

    Sqlite3Query::~Sqlite3Query()
    {
        if(statement)
        {
            int result = sqlite3_finalize(statement);

            #if ORM_VERBOSITY & ORM_ERROR
            if(result != SQLITE_OK)
            {
                ORM_PRINT_ERROR("Sqlite3Query::~Sqlite3Query() Failed to close the statement")
                /// \todo <<sqlite3_errstr(result)<<std::endl;
            }
            #endif
        }
    };

    int Sqlite3Query::count()const
    {
        return sqlite3_data_count(statement);
    };

    bool Sqlite3Query::get(bool& value,const int& column)const
    {
        value = (bool)sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::get(int& value,const int& column)const
    {
        value = sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::getPk(int& value, const int& colum)const
    {
        if(sqlite3_column_type(statement,colum) == SQLITE_NULL)
        {
            value = -1;
            return false;
        }
        value = sqlite3_column_int(statement,colum);
        return true;
    }

    bool Sqlite3Query::get(unsigned int& value,const int& column)const
    {
        value = (unsigned int)sqlite3_column_int(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long long int& value,const int& column)const
    {
        value = (long long int)sqlite3_column_int64(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long long unsigned int& value,const int& column)const
    {
        value = (unsigned long long int)sqlite3_column_int64(statement,column);

        return true;
    };

    bool Sqlite3Query::get(float& value,const int& column)const
    {
        value = (float)sqlite3_column_double(statement,column);
        return true;
    };

    bool Sqlite3Query::get(double& value,const int& column)const
    {
        value = (double)sqlite3_column_double(statement,column);
        return true;
    };

    bool Sqlite3Query::get(long double& value,const int& column)const
    {
        value = (long double)sqlite3_column_double(statement,column);
        return true;
    };

    bool Sqlite3Query::get(std::string& value,const int& column)const
    {
        const unsigned char* res = sqlite3_column_text(statement,column);

        if (res)
            value = (const char*)res;
        else
            value = "";

        return true;
    };

    bool Sqlite3Query::next()
    {
        int result = sqlite3_step(statement);
        if(result == SQLITE_ROW)
            return true;

        ORM_PRINT_WARNING("Sqlite3Query::next() imposible to get next row")
        ///\ todo sqlite3_errstr(result)<<std::endl;

        return false;

    }

    bool Sqlite3Query::set(const bool& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const unsigned int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int(statement,(int)column,(int)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long long int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long long unsigned int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_int64(statement,(int)column,(sqlite3_int64)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const float& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const double& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const long double& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_double(statement,(int)column,(double)value)== SQLITE_OK);
    };

    bool Sqlite3Query::set(const std::string& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_text(statement,(int)column,value.c_str(),-1,SQLITE_TRANSIENT)== SQLITE_OK);
    };

    bool Sqlite3Query::setNull(const int& value,const unsigned int& column)
    {
        if(not prepared)
            return false;
        return (sqlite3_bind_null(statement,(int)column)== SQLITE_OK);
    };

    void Sqlite3Query::executeQuery()
    {
    };

};
<|endoftext|>