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

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// CTK includes
#include "ctkMatrixWidget.h"
#include "ctkDoubleSpinBox.h"
#include "ctkUtils.h"

// Qt includes
#include <QDebug>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QItemEditorFactory>
#include <QResizeEvent>
#include <QStyledItemDelegate>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QVariant>
#include <Qt>

//-----------------------------------------------------------------------------
// Custom item editors

namespace
{
//-----------------------------------------------------------------------------
  class ctkMatrixDoubleSpinBox : public ctkDoubleSpinBox
  {
  public:
    ctkMatrixDoubleSpinBox(QWidget * parentWidget)
      : ctkDoubleSpinBox(parentWidget)
    {
      // We know that the parentWidget() of parentWidget will be a
      // ctkMatrixWidget because this object is
      // created by the QItemEditorFactory
      ctkMatrixWidget* matrixWidget =
        qobject_cast<ctkMatrixWidget*>(parentWidget->parentWidget()->parent());
      Q_ASSERT(matrixWidget);
      this->setMinimum(matrixWidget->minimum());
      this->setMaximum(matrixWidget->maximum());
      this->setDecimals(matrixWidget->decimals());
      this->setDecimalsOption(matrixWidget->decimalsOption());
      this->setSingleStep(matrixWidget->singleStep());

      this->connect(this, SIGNAL(decimalsChanged(int)),
        matrixWidget, SLOT(setDecimals(int)));
    }
  };

//-----------------------------------------------------------------------------
// Reimplemented to display the numbers with the matrix decimals.
class ctkMatrixItemDelegate : public QStyledItemDelegate
{
public:
  ctkMatrixItemDelegate(ctkMatrixWidget* matrixWidget)
    : QStyledItemDelegate(matrixWidget)
  {
  }
  virtual QString	displayText ( const QVariant & value, const QLocale & locale ) const
  {
    ctkMatrixWidget* matrix = qobject_cast<ctkMatrixWidget*>(this->parent());
    Q_ASSERT(matrix);
    switch(value.type())
      {
      case QVariant::Double:
        return locale.toString(value.toDouble(), 'f', matrix->decimals());
      default:
        return this->QStyledItemDelegate::displayText(value, locale);
      }
  }
};

}

//-----------------------------------------------------------------------------
class ctkMatrixWidgetPrivate
{
  Q_DECLARE_PUBLIC(ctkMatrixWidget);
protected:
  ctkMatrixWidget* const q_ptr;
public:
  ctkMatrixWidgetPrivate(ctkMatrixWidget& object, int rows = 4, int columns = 4);

  void init();
  void validateItems();
  void updateGeometries();
  void setIdentityItem(int i, int j);

  QTableWidget* Table;

  // Parameters for the spinbox used to change the value of matrix elements
  double Minimum;
  double Maximum;
  int    Decimals;
  ctkDoubleSpinBox::DecimalsOptions DecimalsOption;
  double SingleStep;
};

//-----------------------------------------------------------------------------
ctkMatrixWidgetPrivate::ctkMatrixWidgetPrivate(ctkMatrixWidget& object, int rows, int columns)
  :q_ptr(&object)
{
  this->Table = new QTableWidget(rows, columns);
}

//-----------------------------------------------------------------------------
void ctkMatrixWidgetPrivate::init()
{
  Q_Q(ctkMatrixWidget);
  this->Table->setItemDelegate(new ctkMatrixItemDelegate(q));

  this->Table->setParent(q);
  QHBoxLayout* layout = new QHBoxLayout(q);
  layout->addWidget(this->Table);
  layout->setContentsMargins(0,0,0,0);
  q->setLayout(layout);

  // Set parameters for the spinbox
  // TODO: not sure [-100. 100.] is the right default range
  this->Minimum = -100;
  this->Maximum = 100;
  this->Decimals = 2;
  this->SingleStep = 0.01;

  // Don't select the items
  this->Table->setSelectionMode(QAbstractItemView::NoSelection);

  // Hide headers
  this->Table->verticalHeader()->hide();
  this->Table->horizontalHeader()->hide();

  // Disable scrollBars
  this->Table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  this->Table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

  // Don't expand for no reason
  q->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

  // Disable the frame by default
  this->Table->setFrameStyle(QFrame::NoFrame);

  // Register custom editors
  QItemEditorFactory *editorFactory = new QItemEditorFactory;
  editorFactory->registerEditor(QVariant::Double, new QStandardItemEditorCreator<ctkMatrixDoubleSpinBox>);

  QStyledItemDelegate* defaultItemDelegate =
    qobject_cast<QStyledItemDelegate*>(this->Table->itemDelegate());
  Q_ASSERT(defaultItemDelegate);
  defaultItemDelegate->setItemEditorFactory(editorFactory);

  // Define prototype item
  QTableWidgetItem* _item = new QTableWidgetItem;
  _item->setData(Qt::DisplayRole, QVariant(0.0));
  _item->setTextAlignment(Qt::AlignCenter);

  // The table takes ownership of the prototype.
  this->Table->setItemPrototype(_item);

  QObject::connect(this->Table, SIGNAL(cellChanged(int,int)),
                   q, SIGNAL(matrixChanged()));
  /// \todo Wrap model signals to emit signals when the matrix is changed.
/// Right now you can connect to the signal:
/// matrixWidget->model()->dataChanged(...)

  // Set Read-only
  q->setEditable(true);

  // Initialize
  this->validateItems();

  this->updateGeometries();
}

// --------------------------------------------------------------------------
void ctkMatrixWidgetPrivate::validateItems()
{
  Q_Q(ctkMatrixWidget);
  for (int i=0; i < q->rowCount(); ++i)
    {
    for (int j=0; j < q->columnCount(); ++j)
      {
      QTableWidgetItem* item = this->Table->item(i, j);
      if (!item)
        {
        this->Table->setItem(i, j , this->Table->itemPrototype()->clone());
        this->setIdentityItem(i, j);
        }
      else
        {
        double value = item->data(Qt::DisplayRole).toDouble();
        item->setData(Qt::DisplayRole,
                      qBound(this->Minimum, value, this->Maximum));
        }
      }
    }
}

// --------------------------------------------------------------------------
void ctkMatrixWidgetPrivate::setIdentityItem(int i, int j)
{
  Q_Q(ctkMatrixWidget);
  // the item must exist first
  Q_ASSERT(this->Table->item(i, j));
  // identity matrix has 1 on the diagonal, 0 everywhere else
  double value = (i == j ? 1. : 0.);
  // set the value to the table
  q->setValue(i, j, value);
}

// --------------------------------------------------------------------------
void ctkMatrixWidgetPrivate::updateGeometries()
{
  Q_Q(ctkMatrixWidget);
  QSize viewportSize = q->size();
  // columns
  const int ccount = q->columnCount();
  int colWidth = viewportSize.width() / ccount;
  int lastColWidth = colWidth
    + (viewportSize.width() - colWidth * ccount);
  for (int j=0; j < ccount; j++)
    {
    bool lastColumn = (j==(ccount-1));
    int newWidth = lastColumn ? lastColWidth : colWidth;
    this->Table->setColumnWidth(j, newWidth);
    CTK_SOFT_ASSERT(this->Table->columnWidth(j) == newWidth);
    }
  // rows
  const int rcount = q->rowCount();
  int rowHeight = viewportSize.height() / rcount;
  int lastRowHeight = rowHeight + (viewportSize.height() - rowHeight * rcount);
  for (int i=0; i < rcount; i++)
    {
    bool lastRow = (i==(rcount-1));
    int newHeight = lastRow ? lastRowHeight : rowHeight;
    this->Table->setRowHeight(i, newHeight);
    CTK_SOFT_ASSERT(this->Table->rowHeight(i) == newHeight);
    }
  this->Table->updateGeometry();
}

// --------------------------------------------------------------------------
ctkMatrixWidget::ctkMatrixWidget(QWidget* _parent)
  :Superclass(_parent)
  ,d_ptr(new ctkMatrixWidgetPrivate(*this))
{
  Q_D(ctkMatrixWidget);
  d->init();
}

// --------------------------------------------------------------------------
ctkMatrixWidget::ctkMatrixWidget(int rows, int columns, QWidget* _parent)
  : QWidget(_parent)
  , d_ptr(new ctkMatrixWidgetPrivate(*this, rows, columns))
{
  Q_D(ctkMatrixWidget);
  d->init();
}

// --------------------------------------------------------------------------
ctkMatrixWidget::ctkMatrixWidget(ctkMatrixWidgetPrivate& pvt,
                                 QWidget* _parent)
  : Superclass(_parent)
  ,d_ptr(&pvt)
{
  Q_D(ctkMatrixWidget);
  d->init();
}

// --------------------------------------------------------------------------
ctkMatrixWidget::~ctkMatrixWidget()
{
}

// --------------------------------------------------------------------------
int ctkMatrixWidget::columnCount()const
{
  Q_D(const ctkMatrixWidget);
  return d->Table->columnCount();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setColumnCount(int rc)
{
  Q_D(ctkMatrixWidget);
  d->Table->setColumnCount(rc);
  d->validateItems();
  d->updateGeometries();
}

// --------------------------------------------------------------------------
int ctkMatrixWidget::rowCount()const
{
  Q_D(const ctkMatrixWidget);
  return d->Table->rowCount();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setRowCount(int rc)
{
  Q_D(ctkMatrixWidget);
  d->Table->setRowCount(rc);
  d->validateItems();
  d->updateGeometries();
}

// --------------------------------------------------------------------------
bool ctkMatrixWidget::isEditable()const
{
  Q_D(const ctkMatrixWidget);
  return d->Table->editTriggers();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setEditable(bool newEditable)
{
  Q_D(ctkMatrixWidget);
  d->Table->setEditTriggers(
    newEditable ? QTableWidget::DoubleClicked : QTableWidget::NoEditTriggers);
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkMatrixWidget, double, minimum, Minimum);
CTK_GET_CPP(ctkMatrixWidget, double, maximum, Maximum);
CTK_GET_CPP(ctkMatrixWidget, double, singleStep, SingleStep);
CTK_SET_CPP(ctkMatrixWidget, double, setSingleStep, SingleStep);
CTK_GET_CPP(ctkMatrixWidget, int, decimals, Decimals);

// --------------------------------------------------------------------------
void ctkMatrixWidget::setMinimum(double newMinimum)
{
  Q_D(ctkMatrixWidget);
  d->Minimum = newMinimum;
  d->Maximum = qMax(newMinimum, d->Maximum);
  d->validateItems();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setMaximum(double newMaximum)
{
  Q_D(ctkMatrixWidget);
  d->Minimum = qMin(d->Minimum, newMaximum);
  d->Maximum = newMaximum;
  d->validateItems();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setRange(double newMinimum, double newMaximum)
{
  Q_D(ctkMatrixWidget);
  d->Minimum = qMin(newMinimum, newMaximum);
  d->Maximum = qMax(newMinimum, newMaximum);
  d->validateItems();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setDecimals(int decimals)
{
  Q_D(ctkMatrixWidget);
  if (d->Decimals == decimals)
    {
    return;
    }
  d->Decimals = qMax(0, decimals);
  this->update();
  this->emit decimalsChanged(d->Decimals);
}

// --------------------------------------------------------------------------
ctkDoubleSpinBox::DecimalsOptions ctkMatrixWidget::decimalsOption()const
{
  Q_D(const ctkMatrixWidget);
  return d->DecimalsOption;
}

// --------------------------------------------------------------------------
void ctkMatrixWidget
::setDecimalsOption(ctkDoubleSpinBox::DecimalsOptions newDecimalsOption)
{
  Q_D(ctkMatrixWidget);
  d->DecimalsOption = newDecimalsOption;
}

// --------------------------------------------------------------------------
QSize ctkMatrixWidget::minimumSizeHint() const
{
  Q_D(const ctkMatrixWidget);
  int maxWidth = d->Table->horizontalHeader()->sectionSizeHint(0);
  for (int j = 1; j < this->columnCount(); ++j)
    {
    maxWidth = qMax(maxWidth, d->Table->horizontalHeader()->sectionSizeHint(j));
    }
  int maxHeight = d->Table->verticalHeader()->sectionSizeHint(0);
  for (int i = 1; i < this->rowCount(); ++i)
    {
    maxHeight = qMax(maxHeight, d->Table->verticalHeader()->sectionSizeHint(i));
    }
  return QSize(maxWidth*this->columnCount(), maxHeight*this->rowCount());
}

// --------------------------------------------------------------------------
QSize ctkMatrixWidget::sizeHint() const
{
  return this->minimumSizeHint();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::resizeEvent(QResizeEvent* event)
{
  Q_D(ctkMatrixWidget);
  this->Superclass::resizeEvent(event);
  d->updateGeometries();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::identity()
{
  Q_D(ctkMatrixWidget);
  // Initialize 4x4 matrix
  for (int i=0; i < this->rowCount(); i++)
    {
    for (int j=0; j < this->columnCount(); j++)
      {
      d->setIdentityItem(i,j);
      }
    }
}

// --------------------------------------------------------------------------
double ctkMatrixWidget::value(int i, int j)const
{
  Q_D(const ctkMatrixWidget);
  Q_ASSERT( i>=0 && i<this->rowCount() &&
            j>=0 && j<this->columnCount());

  return d->Table->item(i, j)->data(Qt::DisplayRole).toDouble();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setValue(int i, int j, double newValue)
{
  Q_D(ctkMatrixWidget);
  Q_ASSERT( i>=0 && i<this->rowCount() &&
            j>=0 && j<this->columnCount());

  newValue = qBound(d->Minimum, newValue, d->Maximum);
  d->Table->item(i, j)->setData(Qt::DisplayRole, QVariant(newValue));
}

// --------------------------------------------------------------------------
QVector<double> ctkMatrixWidget::values()const
{
  QVector<double> values;

  for (int i=0; i < this->rowCount(); i++)
    {
    for (int j=0; j < this->columnCount(); j++)
      {
      values.push_back(this->value(i,j));
      }
    }

  return values;
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setValues(const QVector<double> & vector)
{
  Q_D(ctkMatrixWidget);
  Q_ASSERT(vector.size() == this->rowCount() * this->columnCount());
  // As we are potentially making a lot of changes, just fire a unique
  // signal at the end if at least one matrix value has been changed.
  bool blocked = this->blockSignals(true);
  bool modified = false;
  for (int row=0; row < this->rowCount(); ++row)
    {
    for (int column=0; column < this->columnCount(); ++column)
      {
      double newValue = vector.at(row * this->columnCount() + column);
      newValue = qBound(d->Minimum, newValue, d->Maximum);
      if (newValue != this->value(row, column))
        {
        this->setValue(row, column, newValue);
        modified = true;
        }
      }
    }
  this->blockSignals(blocked);
  if (modified)
    {
    this->emit matrixChanged();
    }
}

// --------------------------------------------------------------------------
QTableWidgetItem* ctkMatrixWidget::widgetItem(int i, int j)
{
  Q_D(ctkMatrixWidget);
  QTableWidgetItem* item = d->Table->item(i, j);
  return item;
}
<commit_msg>BUG: Remove assert from matrix widget that flooded application log<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// CTK includes
#include "ctkMatrixWidget.h"
#include "ctkDoubleSpinBox.h"
#include "ctkUtils.h"

// Qt includes
#include <QDebug>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QItemEditorFactory>
#include <QResizeEvent>
#include <QStyledItemDelegate>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QVariant>
#include <Qt>

//-----------------------------------------------------------------------------
// Custom item editors

namespace
{
//-----------------------------------------------------------------------------
  class ctkMatrixDoubleSpinBox : public ctkDoubleSpinBox
  {
  public:
    ctkMatrixDoubleSpinBox(QWidget * parentWidget)
      : ctkDoubleSpinBox(parentWidget)
    {
      // We know that the parentWidget() of parentWidget will be a
      // ctkMatrixWidget because this object is
      // created by the QItemEditorFactory
      ctkMatrixWidget* matrixWidget =
        qobject_cast<ctkMatrixWidget*>(parentWidget->parentWidget()->parent());
      Q_ASSERT(matrixWidget);
      this->setMinimum(matrixWidget->minimum());
      this->setMaximum(matrixWidget->maximum());
      this->setDecimals(matrixWidget->decimals());
      this->setDecimalsOption(matrixWidget->decimalsOption());
      this->setSingleStep(matrixWidget->singleStep());

      this->connect(this, SIGNAL(decimalsChanged(int)),
        matrixWidget, SLOT(setDecimals(int)));
    }
  };

//-----------------------------------------------------------------------------
// Reimplemented to display the numbers with the matrix decimals.
class ctkMatrixItemDelegate : public QStyledItemDelegate
{
public:
  ctkMatrixItemDelegate(ctkMatrixWidget* matrixWidget)
    : QStyledItemDelegate(matrixWidget)
  {
  }
  virtual QString	displayText ( const QVariant & value, const QLocale & locale ) const
  {
    ctkMatrixWidget* matrix = qobject_cast<ctkMatrixWidget*>(this->parent());
    Q_ASSERT(matrix);
    switch(value.type())
      {
      case QVariant::Double:
        return locale.toString(value.toDouble(), 'f', matrix->decimals());
      default:
        return this->QStyledItemDelegate::displayText(value, locale);
      }
  }
};

}

//-----------------------------------------------------------------------------
class ctkMatrixWidgetPrivate
{
  Q_DECLARE_PUBLIC(ctkMatrixWidget);
protected:
  ctkMatrixWidget* const q_ptr;
public:
  ctkMatrixWidgetPrivate(ctkMatrixWidget& object, int rows = 4, int columns = 4);

  void init();
  void validateItems();
  void updateGeometries();
  void setIdentityItem(int i, int j);

  QTableWidget* Table;

  // Parameters for the spinbox used to change the value of matrix elements
  double Minimum;
  double Maximum;
  int    Decimals;
  ctkDoubleSpinBox::DecimalsOptions DecimalsOption;
  double SingleStep;
};

//-----------------------------------------------------------------------------
ctkMatrixWidgetPrivate::ctkMatrixWidgetPrivate(ctkMatrixWidget& object, int rows, int columns)
  :q_ptr(&object)
{
  this->Table = new QTableWidget(rows, columns);
}

//-----------------------------------------------------------------------------
void ctkMatrixWidgetPrivate::init()
{
  Q_Q(ctkMatrixWidget);
  this->Table->setItemDelegate(new ctkMatrixItemDelegate(q));

  this->Table->setParent(q);
  QHBoxLayout* layout = new QHBoxLayout(q);
  layout->addWidget(this->Table);
  layout->setContentsMargins(0,0,0,0);
  q->setLayout(layout);

  // Set parameters for the spinbox
  // TODO: not sure [-100. 100.] is the right default range
  this->Minimum = -100;
  this->Maximum = 100;
  this->Decimals = 2;
  this->SingleStep = 0.01;

  // Don't select the items
  this->Table->setSelectionMode(QAbstractItemView::NoSelection);

  // Hide headers
  this->Table->verticalHeader()->hide();
  this->Table->horizontalHeader()->hide();

  // Disable scrollBars
  this->Table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  this->Table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

  // Don't expand for no reason
  q->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

  // Disable the frame by default
  this->Table->setFrameStyle(QFrame::NoFrame);

  // Register custom editors
  QItemEditorFactory *editorFactory = new QItemEditorFactory;
  editorFactory->registerEditor(QVariant::Double, new QStandardItemEditorCreator<ctkMatrixDoubleSpinBox>);

  QStyledItemDelegate* defaultItemDelegate =
    qobject_cast<QStyledItemDelegate*>(this->Table->itemDelegate());
  Q_ASSERT(defaultItemDelegate);
  defaultItemDelegate->setItemEditorFactory(editorFactory);

  // Define prototype item
  QTableWidgetItem* _item = new QTableWidgetItem;
  _item->setData(Qt::DisplayRole, QVariant(0.0));
  _item->setTextAlignment(Qt::AlignCenter);

  // The table takes ownership of the prototype.
  this->Table->setItemPrototype(_item);

  QObject::connect(this->Table, SIGNAL(cellChanged(int,int)),
                   q, SIGNAL(matrixChanged()));
  /// \todo Wrap model signals to emit signals when the matrix is changed.
/// Right now you can connect to the signal:
/// matrixWidget->model()->dataChanged(...)

  // Set Read-only
  q->setEditable(true);

  // Initialize
  this->validateItems();

  this->updateGeometries();
}

// --------------------------------------------------------------------------
void ctkMatrixWidgetPrivate::validateItems()
{
  Q_Q(ctkMatrixWidget);
  for (int i=0; i < q->rowCount(); ++i)
    {
    for (int j=0; j < q->columnCount(); ++j)
      {
      QTableWidgetItem* item = this->Table->item(i, j);
      if (!item)
        {
        this->Table->setItem(i, j , this->Table->itemPrototype()->clone());
        this->setIdentityItem(i, j);
        }
      else
        {
        double value = item->data(Qt::DisplayRole).toDouble();
        item->setData(Qt::DisplayRole,
                      qBound(this->Minimum, value, this->Maximum));
        }
      }
    }
}

// --------------------------------------------------------------------------
void ctkMatrixWidgetPrivate::setIdentityItem(int i, int j)
{
  Q_Q(ctkMatrixWidget);
  // the item must exist first
  Q_ASSERT(this->Table->item(i, j));
  // identity matrix has 1 on the diagonal, 0 everywhere else
  double value = (i == j ? 1. : 0.);
  // set the value to the table
  q->setValue(i, j, value);
}

// --------------------------------------------------------------------------
void ctkMatrixWidgetPrivate::updateGeometries()
{
  Q_Q(ctkMatrixWidget);
  QSize viewportSize = q->size();
  // columns
  const int ccount = q->columnCount();
  int colWidth = viewportSize.width() / ccount;
  int lastColWidth = colWidth
    + (viewportSize.width() - colWidth * ccount);
  for (int j=0; j < ccount; j++)
    {
    bool lastColumn = (j==(ccount-1));
    int newWidth = lastColumn ? lastColWidth : colWidth;
    this->Table->setColumnWidth(j, newWidth);
    }
  // rows
  const int rcount = q->rowCount();
  int rowHeight = viewportSize.height() / rcount;
  int lastRowHeight = rowHeight + (viewportSize.height() - rowHeight * rcount);
  for (int i=0; i < rcount; i++)
    {
    bool lastRow = (i==(rcount-1));
    int newHeight = lastRow ? lastRowHeight : rowHeight;
    this->Table->setRowHeight(i, newHeight);
    }
  this->Table->updateGeometry();
}

// --------------------------------------------------------------------------
ctkMatrixWidget::ctkMatrixWidget(QWidget* _parent)
  :Superclass(_parent)
  ,d_ptr(new ctkMatrixWidgetPrivate(*this))
{
  Q_D(ctkMatrixWidget);
  d->init();
}

// --------------------------------------------------------------------------
ctkMatrixWidget::ctkMatrixWidget(int rows, int columns, QWidget* _parent)
  : QWidget(_parent)
  , d_ptr(new ctkMatrixWidgetPrivate(*this, rows, columns))
{
  Q_D(ctkMatrixWidget);
  d->init();
}

// --------------------------------------------------------------------------
ctkMatrixWidget::ctkMatrixWidget(ctkMatrixWidgetPrivate& pvt,
                                 QWidget* _parent)
  : Superclass(_parent)
  ,d_ptr(&pvt)
{
  Q_D(ctkMatrixWidget);
  d->init();
}

// --------------------------------------------------------------------------
ctkMatrixWidget::~ctkMatrixWidget()
{
}

// --------------------------------------------------------------------------
int ctkMatrixWidget::columnCount()const
{
  Q_D(const ctkMatrixWidget);
  return d->Table->columnCount();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setColumnCount(int rc)
{
  Q_D(ctkMatrixWidget);
  d->Table->setColumnCount(rc);
  d->validateItems();
  d->updateGeometries();
}

// --------------------------------------------------------------------------
int ctkMatrixWidget::rowCount()const
{
  Q_D(const ctkMatrixWidget);
  return d->Table->rowCount();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setRowCount(int rc)
{
  Q_D(ctkMatrixWidget);
  d->Table->setRowCount(rc);
  d->validateItems();
  d->updateGeometries();
}

// --------------------------------------------------------------------------
bool ctkMatrixWidget::isEditable()const
{
  Q_D(const ctkMatrixWidget);
  return d->Table->editTriggers();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setEditable(bool newEditable)
{
  Q_D(ctkMatrixWidget);
  d->Table->setEditTriggers(
    newEditable ? QTableWidget::DoubleClicked : QTableWidget::NoEditTriggers);
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkMatrixWidget, double, minimum, Minimum);
CTK_GET_CPP(ctkMatrixWidget, double, maximum, Maximum);
CTK_GET_CPP(ctkMatrixWidget, double, singleStep, SingleStep);
CTK_SET_CPP(ctkMatrixWidget, double, setSingleStep, SingleStep);
CTK_GET_CPP(ctkMatrixWidget, int, decimals, Decimals);

// --------------------------------------------------------------------------
void ctkMatrixWidget::setMinimum(double newMinimum)
{
  Q_D(ctkMatrixWidget);
  d->Minimum = newMinimum;
  d->Maximum = qMax(newMinimum, d->Maximum);
  d->validateItems();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setMaximum(double newMaximum)
{
  Q_D(ctkMatrixWidget);
  d->Minimum = qMin(d->Minimum, newMaximum);
  d->Maximum = newMaximum;
  d->validateItems();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setRange(double newMinimum, double newMaximum)
{
  Q_D(ctkMatrixWidget);
  d->Minimum = qMin(newMinimum, newMaximum);
  d->Maximum = qMax(newMinimum, newMaximum);
  d->validateItems();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setDecimals(int decimals)
{
  Q_D(ctkMatrixWidget);
  if (d->Decimals == decimals)
    {
    return;
    }
  d->Decimals = qMax(0, decimals);
  this->update();
  this->emit decimalsChanged(d->Decimals);
}

// --------------------------------------------------------------------------
ctkDoubleSpinBox::DecimalsOptions ctkMatrixWidget::decimalsOption()const
{
  Q_D(const ctkMatrixWidget);
  return d->DecimalsOption;
}

// --------------------------------------------------------------------------
void ctkMatrixWidget
::setDecimalsOption(ctkDoubleSpinBox::DecimalsOptions newDecimalsOption)
{
  Q_D(ctkMatrixWidget);
  d->DecimalsOption = newDecimalsOption;
}

// --------------------------------------------------------------------------
QSize ctkMatrixWidget::minimumSizeHint() const
{
  Q_D(const ctkMatrixWidget);
  int maxWidth = d->Table->horizontalHeader()->sectionSizeHint(0);
  for (int j = 1; j < this->columnCount(); ++j)
    {
    maxWidth = qMax(maxWidth, d->Table->horizontalHeader()->sectionSizeHint(j));
    }
  int maxHeight = d->Table->verticalHeader()->sectionSizeHint(0);
  for (int i = 1; i < this->rowCount(); ++i)
    {
    maxHeight = qMax(maxHeight, d->Table->verticalHeader()->sectionSizeHint(i));
    }
  return QSize(maxWidth*this->columnCount(), maxHeight*this->rowCount());
}

// --------------------------------------------------------------------------
QSize ctkMatrixWidget::sizeHint() const
{
  return this->minimumSizeHint();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::resizeEvent(QResizeEvent* event)
{
  Q_D(ctkMatrixWidget);
  this->Superclass::resizeEvent(event);
  d->updateGeometries();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::identity()
{
  Q_D(ctkMatrixWidget);
  // Initialize 4x4 matrix
  for (int i=0; i < this->rowCount(); i++)
    {
    for (int j=0; j < this->columnCount(); j++)
      {
      d->setIdentityItem(i,j);
      }
    }
}

// --------------------------------------------------------------------------
double ctkMatrixWidget::value(int i, int j)const
{
  Q_D(const ctkMatrixWidget);
  Q_ASSERT( i>=0 && i<this->rowCount() &&
            j>=0 && j<this->columnCount());

  return d->Table->item(i, j)->data(Qt::DisplayRole).toDouble();
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setValue(int i, int j, double newValue)
{
  Q_D(ctkMatrixWidget);
  Q_ASSERT( i>=0 && i<this->rowCount() &&
            j>=0 && j<this->columnCount());

  newValue = qBound(d->Minimum, newValue, d->Maximum);
  d->Table->item(i, j)->setData(Qt::DisplayRole, QVariant(newValue));
}

// --------------------------------------------------------------------------
QVector<double> ctkMatrixWidget::values()const
{
  QVector<double> values;

  for (int i=0; i < this->rowCount(); i++)
    {
    for (int j=0; j < this->columnCount(); j++)
      {
      values.push_back(this->value(i,j));
      }
    }

  return values;
}

// --------------------------------------------------------------------------
void ctkMatrixWidget::setValues(const QVector<double> & vector)
{
  Q_D(ctkMatrixWidget);
  Q_ASSERT(vector.size() == this->rowCount() * this->columnCount());
  // As we are potentially making a lot of changes, just fire a unique
  // signal at the end if at least one matrix value has been changed.
  bool blocked = this->blockSignals(true);
  bool modified = false;
  for (int row=0; row < this->rowCount(); ++row)
    {
    for (int column=0; column < this->columnCount(); ++column)
      {
      double newValue = vector.at(row * this->columnCount() + column);
      newValue = qBound(d->Minimum, newValue, d->Maximum);
      if (newValue != this->value(row, column))
        {
        this->setValue(row, column, newValue);
        modified = true;
        }
      }
    }
  this->blockSignals(blocked);
  if (modified)
    {
    this->emit matrixChanged();
    }
}

// --------------------------------------------------------------------------
QTableWidgetItem* ctkMatrixWidget::widgetItem(int i, int j)
{
  Q_D(ctkMatrixWidget);
  QTableWidgetItem* item = d->Table->item(i, j);
  return item;
}
<|endoftext|>


<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Authors:
//   Eugen Wintersberger <eugen.wintersberger@desy.de>
//   Martin Shetty <martin.shetty@esss.se>
// Created on: Aug 25, 2017
//

#include <gtest/gtest.h>
#include <h5cpp/dataspace/simple.hpp>

using namespace hdf5;

TEST(SelectionManager, test_nothing_and_all_selected) {
  dataspace::Simple space({10, 1024});
  EXPECT_EQ(space.size(), 10l * 1024l);
  EXPECT_EQ(space.selection.size(), 10ul * 1024ul);

  space.selection.none();
  EXPECT_EQ(space.size(), 10l * 1024l);
  EXPECT_EQ(space.selection.size(), 0ul);

  space.selection.all();
  EXPECT_EQ(space.size(), 10l * 1024l);
  EXPECT_EQ(space.selection.size(), 10ul * 1024ul);

  ObjectHandle(static_cast<hid_t>(space)).close();
  EXPECT_THROW(space.selection.size(), std::runtime_error);
  EXPECT_THROW(space.selection.none(), std::runtime_error);
  EXPECT_THROW(space.selection.all(), std::runtime_error);
}
<commit_msg>Just added a few more tests for the selection manager class<commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Authors:
//   Eugen Wintersberger <eugen.wintersberger@desy.de>
//   Martin Shetty <martin.shetty@esss.se>
// Created on: Aug 25, 2017
//

#include <gtest/gtest.h>
#include <h5cpp/dataspace/simple.hpp>

using namespace hdf5;

TEST(SelectionManager, test_nothing_and_all_selected) {
  dataspace::Simple space({10, 1024});
  EXPECT_EQ(space.size(), 10l * 1024l);
  EXPECT_EQ(space.selection.size(), 10ul * 1024ul);
  EXPECT_EQ(space.selection.type(),dataspace::SelectionType::ALL);

  space.selection.none();
  EXPECT_EQ(space.size(), 10l * 1024l);
  EXPECT_EQ(space.selection.size(), 0ul);
  EXPECT_EQ(space.selection.type(),dataspace::SelectionType::NONE);

  space.selection.all();
  EXPECT_EQ(space.size(), 10l * 1024l);
  EXPECT_EQ(space.selection.size(), 10ul * 1024ul);
  EXPECT_EQ(space.selection.type(),dataspace::SelectionType::ALL);

  ObjectHandle(static_cast<hid_t>(space)).close();
  EXPECT_THROW(space.selection.size(), std::runtime_error);
  EXPECT_THROW(space.selection.none(), std::runtime_error);
  EXPECT_THROW(space.selection.all(), std::runtime_error);
}
<|endoftext|>


<commit_before>/*
 * gVirtuS -- A GPGPU transparent virtualization component.
 *
 * Copyright (C) 2009-2010  The University of Napoli Parthenope at Naples.
 *
 * This file is part of gVirtuS.
 *
 * gVirtuS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * gVirtuS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gVirtuS; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Written by: Flora Giannone <flora.giannone@studenti.uniparthenope.it>,
 *             Department of Applied Science
 */

#include <cstring>
#include "CudaDrFrontend.h"
#include "CudaUtil.h"
#include "CudaDr.h"
#include <cuda.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>

using namespace std;

void listFiles( const char* path )
{
   DIR* dirFile = opendir( path );
   if ( dirFile )
   {
      struct dirent* hFile;
      errno = 0;
      while (( hFile = readdir( dirFile )) != NULL )
      {
         if ( !strcmp( hFile->d_name, "."  )) continue;
         if ( !strcmp( hFile->d_name, ".." )) continue;
         if ( strstr( hFile->d_name, ".ptx" ))
            printf( "found an .ptx file: %s", hFile->d_name );
      }
      closedir( dirFile );
   }
}
/*Sets the parameter size for the function.*/
extern CUresult cuParamSetSize(CUfunction hfunc, unsigned int numbytes) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(numbytes);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuParamSetSize");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Sets the block-dimensions for the function.*/
extern CUresult cuFuncSetBlockShape(CUfunction hfunc, int x, int y, int z) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(x);
    CudaDrFrontend::AddVariableForArguments(y);
    CudaDrFrontend::AddVariableForArguments(z);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuFuncSetBlockShape");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Launches a CUDA function.*/
extern CUresult cuLaunchGrid(CUfunction f, int grid_width, int grid_height) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(grid_width);
    CudaDrFrontend::AddVariableForArguments(grid_height);
    CudaDrFrontend::AddDevicePointerForArguments((void*) f);
    CudaDrFrontend::Execute("cuLaunchGrid");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Returns information about a function.*/
extern CUresult cuFuncGetAttribute(int *pi, CUfunction_attribute attrib, CUfunction hfunc) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddHostPointerForArguments(pi);
    CudaDrFrontend::AddVariableForArguments(attrib);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuFuncGetAttribute");
    if (CudaDrFrontend::Success())
        *pi = *(CudaDrFrontend::GetOutputHostPointer<int>());
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

/*Sets the dynamic shared-memory size for the function.*/
extern CUresult cuFuncSetSharedSize(CUfunction hfunc, unsigned int bytes) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(bytes);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuFuncSetSharedSize");
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

/*Launches a CUDA function.*/
extern CUresult cuLaunch(CUfunction f) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddDevicePointerForArguments((void*) f);
    CudaDrFrontend::Execute("cuLaunch");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Launches a CUDA function.*/
extern CUresult cuLaunchGridAsync(CUfunction f, int grid_width, int grid_height, CUstream hStream) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(grid_width);
    CudaDrFrontend::AddVariableForArguments(grid_height);
    CudaDrFrontend::AddDevicePointerForArguments((void*) f);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hStream);
    CudaDrFrontend::Execute("cuLaunchGridAsync");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Adds a floating-point parameter to the function's argument list.*/
extern CUresult cuParamSetf(CUfunction hfunc, int offset, float value) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(offset);
    CudaDrFrontend::AddVariableForArguments(value);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuParamSetf");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Adds an integer parameter to the function's argument list.*/
extern CUresult cuParamSeti(CUfunction hfunc, int offset, unsigned int value) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(offset);
    CudaDrFrontend::AddVariableForArguments(value);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuParamSeti");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Adds a texture-reference to the function's argument list.*/
extern CUresult cuParamSetTexRef(CUfunction hfunc, int texunit, CUtexref hTexRef) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::AddVariableForArguments(texunit);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hTexRef);
    CudaDrFrontend::Execute("cuParamSetTexRef");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Adds arbitrary data to the function's argument list.*/
extern CUresult cuParamSetv(CUfunction hfunc, int offset, void *ptr, unsigned int numbytes) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(offset);
    CudaDrFrontend::AddVariableForArguments(numbytes);
    CudaDrFrontend::AddHostPointerForArguments((char *) ptr, numbytes);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuParamSetv");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Sets the preferred cache configuration for a device function. */
extern CUresult cuFuncSetCacheConfig(CUfunction hfunc, CUfunc_cache config) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(config);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuFuncSetCacheConfig");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

// new Cuda 4.0 functions
extern CUresult cuLaunchKernel(CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hstream , void** kernelParams, void** extra){
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddDevicePointerForArguments((void*) f);
    CudaDrFrontend::AddVariableForArguments(gridDimX);
    CudaDrFrontend::AddVariableForArguments(gridDimY);
    CudaDrFrontend::AddVariableForArguments(gridDimZ);
    CudaDrFrontend::AddVariableForArguments(blockDimX);
    CudaDrFrontend::AddVariableForArguments(blockDimY);
    CudaDrFrontend::AddVariableForArguments(blockDimZ);
    CudaDrFrontend::AddVariableForArguments(sharedMemBytes);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hstream);
    int link[2];
    int size;
    pid_t pid;
    char foo[1024];
    pipe(link);
    pid=fork();
    if (pid == 0){
        dup2(link[1],STDOUT_FILENO);
        close(link[0]);
        close(link[1]);
        char cwd[1024];
        getcwd(cwd,sizeof(cwd));
        listFiles(cwd);
        fprintf(stderr,"pwd: %s\n",cwd);
        system("grep -rnw 'vectorAdd_kernel64.ptx' -e '.param' -c");
    } else {
        close(link[1]);
        read(link[0],foo,sizeof(foo));
        size = atoi(foo);
    }
    for (unsigned int i = 0; i < size; i++) {
        CudaDrFrontend::AddDevicePointerForArguments(kernelParams+i);
    }
    CudaDrFrontend::AddHostPointerForArguments(&extra);
    CudaDrFrontend::Execute("cuLaunchKernel");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

<commit_msg>Work in progress on cuLaunchKernel<commit_after>/*
 * gVirtuS -- A GPGPU transparent virtualization component.
 *
 * Copyright (C) 2009-2010  The University of Napoli Parthenope at Naples.
 *
 * This file is part of gVirtuS.
 *
 * gVirtuS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * gVirtuS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gVirtuS; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Written by: Flora Giannone <flora.giannone@studenti.uniparthenope.it>,
 *             Department of Applied Science
 */

#include <cstring>
#include "CudaDrFrontend.h"
#include "CudaUtil.h"
#include "CudaDr.h"
#include <cuda.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>

using namespace std;

void listFiles( const char* path )
{
   DIR* dirFile = opendir( path );
   if ( dirFile )
   {
      struct dirent* hFile;
      errno = 0;
      while (( hFile = readdir( dirFile )) != NULL )
      {
         if ( !strcmp( hFile->d_name, "."  )) continue;
         if ( !strcmp( hFile->d_name, ".." )) continue;
         if ( strstr( hFile->d_name, ".ptx" ))
            printf( "found an .ptx file: %s", hFile->d_name );
      }
      closedir( dirFile );
   }
}
/*Sets the parameter size for the function.*/
extern CUresult cuParamSetSize(CUfunction hfunc, unsigned int numbytes) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(numbytes);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuParamSetSize");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Sets the block-dimensions for the function.*/
extern CUresult cuFuncSetBlockShape(CUfunction hfunc, int x, int y, int z) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(x);
    CudaDrFrontend::AddVariableForArguments(y);
    CudaDrFrontend::AddVariableForArguments(z);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuFuncSetBlockShape");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Launches a CUDA function.*/
extern CUresult cuLaunchGrid(CUfunction f, int grid_width, int grid_height) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(grid_width);
    CudaDrFrontend::AddVariableForArguments(grid_height);
    CudaDrFrontend::AddDevicePointerForArguments((void*) f);
    CudaDrFrontend::Execute("cuLaunchGrid");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Returns information about a function.*/
extern CUresult cuFuncGetAttribute(int *pi, CUfunction_attribute attrib, CUfunction hfunc) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddHostPointerForArguments(pi);
    CudaDrFrontend::AddVariableForArguments(attrib);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuFuncGetAttribute");
    if (CudaDrFrontend::Success())
        *pi = *(CudaDrFrontend::GetOutputHostPointer<int>());
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

/*Sets the dynamic shared-memory size for the function.*/
extern CUresult cuFuncSetSharedSize(CUfunction hfunc, unsigned int bytes) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(bytes);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuFuncSetSharedSize");
    return (CUresult) (CudaDrFrontend::GetExitCode());
}

/*Launches a CUDA function.*/
extern CUresult cuLaunch(CUfunction f) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddDevicePointerForArguments((void*) f);
    CudaDrFrontend::Execute("cuLaunch");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Launches a CUDA function.*/
extern CUresult cuLaunchGridAsync(CUfunction f, int grid_width, int grid_height, CUstream hStream) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(grid_width);
    CudaDrFrontend::AddVariableForArguments(grid_height);
    CudaDrFrontend::AddDevicePointerForArguments((void*) f);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hStream);
    CudaDrFrontend::Execute("cuLaunchGridAsync");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Adds a floating-point parameter to the function's argument list.*/
extern CUresult cuParamSetf(CUfunction hfunc, int offset, float value) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(offset);
    CudaDrFrontend::AddVariableForArguments(value);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuParamSetf");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Adds an integer parameter to the function's argument list.*/
extern CUresult cuParamSeti(CUfunction hfunc, int offset, unsigned int value) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(offset);
    CudaDrFrontend::AddVariableForArguments(value);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuParamSeti");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Adds a texture-reference to the function's argument list.*/
extern CUresult cuParamSetTexRef(CUfunction hfunc, int texunit, CUtexref hTexRef) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::AddVariableForArguments(texunit);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hTexRef);
    CudaDrFrontend::Execute("cuParamSetTexRef");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Adds arbitrary data to the function's argument list.*/
extern CUresult cuParamSetv(CUfunction hfunc, int offset, void *ptr, unsigned int numbytes) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(offset);
    CudaDrFrontend::AddVariableForArguments(numbytes);
    CudaDrFrontend::AddHostPointerForArguments((char *) ptr, numbytes);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuParamSetv");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

/*Sets the preferred cache configuration for a device function. */
extern CUresult cuFuncSetCacheConfig(CUfunction hfunc, CUfunc_cache config) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddVariableForArguments(config);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hfunc);
    CudaDrFrontend::Execute("cuFuncSetCacheConfig");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

// new Cuda 4.0 functions
extern CUresult cuLaunchKernel(CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hstream , void** kernelParams, void** extra){
    cout << "cuLaunchKernel\n";

    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddDevicePointerForArguments((void*) f);
    CudaDrFrontend::AddVariableForArguments(gridDimX);
    CudaDrFrontend::AddVariableForArguments(gridDimY);
    CudaDrFrontend::AddVariableForArguments(gridDimZ);
    CudaDrFrontend::AddVariableForArguments(blockDimX);
    CudaDrFrontend::AddVariableForArguments(blockDimY);
    CudaDrFrontend::AddVariableForArguments(blockDimZ);
    CudaDrFrontend::AddVariableForArguments(sharedMemBytes);
    CudaDrFrontend::AddDevicePointerForArguments((void*) hstream);
    CudaDrFrontend::AddDevicePointerForArguments(kernelParams);
    CudaDrFrontend::AddHostPointerForArguments(&extra);
    CudaDrFrontend::Execute("cuLaunchKernel");
    return (CUresult) CudaDrFrontend::GetExitCode();
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////

#pragma once

#include "node_types.hpp"
#include "napi.h"

namespace realm {
namespace js {

template<>
inline const char* node::Value::typeof(Napi::Env env, const Napi::Value& value) {
	if (value.IsNull()) { return "null"; }
	if (value.IsNumber()) { return "number"; }
	if (value.IsString()) { return "string"; }
	if (value.IsBoolean()) { return "boolean"; }
	if (value.IsUndefined()) { return "undefined"; }
	if (value.IsObject()) { return "object"; }
	return "unknown";
}

template<>
inline bool node::Value::is_array(Napi::Env env, const Napi::Value& value) {
	return value.IsArray();
}

template<>
inline bool node::Value::is_array_buffer(Napi::Env env, const Napi::Value& value) {
	return value.IsArrayBuffer();
}

template<>
inline bool node::Value::is_array_buffer_view(Napi::Env env, const Napi::Value& value) {
	return value.IsTypedArray() || value.IsDataView();
}

template<>
inline bool node::Value::is_date(Napi::Env env, const Napi::Value& value) {
	return value.IsObject() && value.As<Napi::Object>().InstanceOf(env.Global().Get("Date").As<Napi::Function>());
}

template<>
inline bool node::Value::is_boolean(Napi::Env env, const Napi::Value& value) {
    return value.IsBoolean();
}

template<>
inline bool node::Value::is_constructor(Napi::Env env, const Napi::Value& value) {
	return value.IsFunction();
}

template<>
inline bool node::Value::is_function(Napi::Env env, const Napi::Value& value) {
	return value.IsFunction();
}

template<>
inline bool node::Value::is_null(Napi::Env env, const Napi::Value& value) {
	return value.IsNull();
}

template<>
inline bool node::Value::is_number(Napi::Env env, const Napi::Value& value) {
	return value.IsNumber();
}

template<>
inline bool node::Value::is_decimal128(Napi::Env env, const Napi::Value& value) {
	return value.IsObject();  // FIXME: can we do better?
}

template<>
inline bool node::Value::is_object_id(Napi::Env env, const Napi::Value& value) {
	return value.IsObject(); // FIXME: can we do better?
}

template<>
inline bool node::Value::is_object(Napi::Env env, const Napi::Value& value) {
	return value.IsObject();
}

template<>
inline bool node::Value::is_string(Napi::Env env, const Napi::Value& value) {
	return value.IsString();
}

template<>
inline bool node::Value::is_undefined(Napi::Env env, const Napi::Value& value) {
	return value.IsUndefined();
}

template<>
inline bool node::Value::is_binary(Napi::Env env, const Napi::Value& value) {
	return Value::is_array_buffer(env, value) || Value::is_array_buffer_view(env, value);
}

template<>
inline bool node::Value::is_valid(const Napi::Value& value) {
	return !value.IsEmpty();
}

template<>
inline Napi::Value node::Value::from_boolean(Napi::Env env, bool boolean) {
	return Napi::Boolean::New(env, boolean);
}

template<>
inline Napi::Value node::Value::from_null(Napi::Env env) {
	return Napi::Value(env, env.Null());
}

template<>
inline Napi::Value node::Value::from_number(Napi::Env env, double number) {
	return Napi::Number::New(env, number);
}

template<>
inline Napi::Value node::Value::from_nonnull_string(Napi::Env env, const node::String& string) {
	return Napi::String::New(env, string);
}

template<>
inline Napi::Value node::Value::from_nonnull_binary(Napi::Env env, BinaryData data) {
	Napi::EscapableHandleScope scope(env);

	Napi::ArrayBuffer buffer = Napi::ArrayBuffer::New(env, data.size());

	if (data.size()) {
		memcpy(buffer.Data(), data.data(), data.size());
	}

	return scope.Escape(buffer);
}

template<>
inline Napi::Value node::Value::from_undefined(Napi::Env env) {
	return Napi::Value(env, env.Undefined());
}

template<>
inline bool node::Value::to_boolean(Napi::Env env, const Napi::Value& value) {
	return value.ToBoolean();
}

template<>
inline node::String node::Value::to_string(Napi::Env env, const Napi::Value& value) {
	return value.ToString();
}

template<>
inline double node::Value::to_number(Napi::Env env, const Napi::Value& value) {
	double number = value.ToNumber();
	if (std::isnan(number)) {
		throw std::invalid_argument(util::format("Value '%1' not convertible to a number.", (std::string)to_string(env, value)));
	}

	return number;
}

template<>
inline OwnedBinaryData node::Value::to_binary(Napi::Env env, const Napi::Value value) {
	// Make a non-null OwnedBinaryData, even when `data` is nullptr.
	auto make_owned_binary_data = [](const char* data, size_t length) {
		REALM_ASSERT(data || length == 0);
		char placeholder;
		return OwnedBinaryData(data ? data : &placeholder, length);
	};

	if (Value::is_array_buffer(env, value)) {
		auto arrayBuffer = value.As<Napi::ArrayBuffer>();
		return make_owned_binary_data(static_cast<char*>(arrayBuffer.Data()), arrayBuffer.ByteLength());
	}
	else if (Value::is_array_buffer_view(env, value)) {
		int64_t byteLength = value.As<Napi::Object>().Get("byteLength").As<Napi::Number>();
		int64_t byteOffset = value.As<Napi::Object>().Get("byteOffset").As<Napi::Number>();
		Napi::ArrayBuffer arrayBuffer = value.As<Napi::Object>().Get("buffer").As<Napi::ArrayBuffer>();
		return make_owned_binary_data(static_cast<char*>(arrayBuffer.Data()) + byteOffset, byteLength);
	}
	else {
		throw std::runtime_error("Can only convert Buffer, ArrayBuffer, and ArrayBufferView objects to binary");
	}
}

template<>
inline Napi::Object node::Value::to_object(Napi::Env env, const Napi::Value& value) {
	return value.ToObject();
}

template<>
inline Napi::Object node::Value::to_array(Napi::Env env, const Napi::Value& value) {
	return to_object(env, value);
}

template<>
inline Napi::Function node::Value::to_function(Napi::Env env, const Napi::Value& value) {
	return value.IsFunction() ? value.As<Napi::Function>() : Napi::Function();
}

template<>
inline Napi::Function node::Value::to_constructor(Napi::Env env, const Napi::Value& value) {
	return to_function(env, value);
}

template<>
inline Napi::Object node::Value::to_date(Napi::Env env, const Napi::Value& value) {
	if (value.IsString()) {
		Napi::Function date_constructor = to_constructor(env, env.Global().Get("Date"));
		std::array<Napi::Value, 1 > args{ {value} };
		return node::Function::construct(env, date_constructor, args.size(), args.data());
	}

	return to_object(env, value);
}

template<>
inline Napi::Value node::Value::from_decimal128(Napi::Env env, const Decimal128& number) {
	Napi::EscapableHandleScope scope(env);

	Napi::Function realm_constructor = node::RealmClassConstructor.Value();
	Napi::Object decimal_constructor = realm_constructor.Get("_Decimal128").As<Napi::Object>();
	Napi::Function fromStringFunc = decimal_constructor.Get("fromString").As<Napi::Function>();
	Napi::String numberAsString = Napi::String::New(env, number.to_string());
	Napi::Value result = fromStringFunc.Call({ numberAsString });

	return scope.Escape(result);
}

template<>
inline Decimal128 node::Value::to_decimal128(Napi::Env env, const Napi::Value& value) {
	Napi::HandleScope scope(env);

	Napi::Object decimal128 = value.As<Napi::Object>();
	Napi::Function toStringFunc = decimal128.Get("toString").As<Napi::Function>();
	node::String string = toStringFunc.Call(value, {}).As<Napi::String>();
	std::string decimal128AsString = string;
	Decimal128 result(decimal128AsString);
	return result;
}

template<>
inline Napi::Value node::Value::from_object_id(Napi::Env env, const ObjectId& objectId) {
	Napi::EscapableHandleScope scope(env);

	Napi::Function realm_constructor = node::RealmClassConstructor.Value();
	Napi::Function object_id_constructor = realm_constructor.Get("_ObjectId").As<Napi::Function>();
	napi_value args[] = { Napi::String::New(env, objectId.to_string()) };
	Napi::Value result = object_id_constructor.New(1, args);
	return scope.Escape(result);
}

template<>
inline ObjectId node::Value::to_object_id(Napi::Env env, const Napi::Value& value) {
	Napi::HandleScope scope(env);

	Napi::Object objectId = value.As<Napi::Object>();
	Napi::Function toHexStringFunc = objectId.Get("toHexString").As<Napi::Function>();
	node::String string = toHexStringFunc.Call(value, {}).As<Napi::String>();
	std::string objectIdAsString = string;
	ObjectId result(objectIdAsString.c_str());
	return result;
}

} // js
} // realm
<commit_msg>Fix ObjectId and Decimal128<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////

#pragma once

#include <iostream>
#include "node_types.hpp"
#include "napi.h"

namespace realm {
namespace js {

template<>
inline const char* node::Value::typeof(Napi::Env env, const Napi::Value& value) {
	if (value.IsNull()) { return "null"; }
	if (value.IsNumber()) { return "number"; }
	if (value.IsString()) { return "string"; }
	if (value.IsBoolean()) { return "boolean"; }
	if (value.IsUndefined()) { return "undefined"; }
	if (value.IsObject()) { return "object"; }
	return "unknown";
}

template<>
inline bool node::Value::is_array(Napi::Env env, const Napi::Value& value) {
	return value.IsArray();
}

template<>
inline bool node::Value::is_array_buffer(Napi::Env env, const Napi::Value& value) {
	return value.IsArrayBuffer();
}

template<>
inline bool node::Value::is_array_buffer_view(Napi::Env env, const Napi::Value& value) {
	return value.IsTypedArray() || value.IsDataView();
}

template<>
inline bool node::Value::is_date(Napi::Env env, const Napi::Value& value) {
	return value.IsObject() && value.As<Napi::Object>().InstanceOf(env.Global().Get("Date").As<Napi::Function>());
}

template<>
inline bool node::Value::is_boolean(Napi::Env env, const Napi::Value& value) {
    return value.IsBoolean();
}

template<>
inline bool node::Value::is_constructor(Napi::Env env, const Napi::Value& value) {
	return value.IsFunction();
}

template<>
inline bool node::Value::is_function(Napi::Env env, const Napi::Value& value) {
	return value.IsFunction();
}

template<>
inline bool node::Value::is_null(Napi::Env env, const Napi::Value& value) {
	return value.IsNull();
}

template<>
inline bool node::Value::is_number(Napi::Env env, const Napi::Value& value) {
	return value.IsNumber();
}

template<>
inline bool node::Value::is_decimal128(Napi::Env env, const Napi::Value& value) {
	return value.IsObject();  // FIXME: can we do better?
}

template<>
inline bool node::Value::is_object_id(Napi::Env env, const Napi::Value& value) {
	return value.IsObject(); // FIXME: can we do better?
}

template<>
inline bool node::Value::is_object(Napi::Env env, const Napi::Value& value) {
	return value.IsObject();
}

template<>
inline bool node::Value::is_string(Napi::Env env, const Napi::Value& value) {
	return value.IsString();
}

template<>
inline bool node::Value::is_undefined(Napi::Env env, const Napi::Value& value) {
	return value.IsUndefined();
}

template<>
inline bool node::Value::is_binary(Napi::Env env, const Napi::Value& value) {
	return Value::is_array_buffer(env, value) || Value::is_array_buffer_view(env, value);
}

template<>
inline bool node::Value::is_valid(const Napi::Value& value) {
	return !value.IsEmpty();
}

template<>
inline Napi::Value node::Value::from_boolean(Napi::Env env, bool boolean) {
	return Napi::Boolean::New(env, boolean);
}

template<>
inline Napi::Value node::Value::from_null(Napi::Env env) {
	return Napi::Value(env, env.Null());
}

template<>
inline Napi::Value node::Value::from_number(Napi::Env env, double number) {
	return Napi::Number::New(env, number);
}

template<>
inline Napi::Value node::Value::from_nonnull_string(Napi::Env env, const node::String& string) {
	return Napi::String::New(env, string);
}

template<>
inline Napi::Value node::Value::from_nonnull_binary(Napi::Env env, BinaryData data) {
	Napi::EscapableHandleScope scope(env);

	Napi::ArrayBuffer buffer = Napi::ArrayBuffer::New(env, data.size());

	if (data.size()) {
		memcpy(buffer.Data(), data.data(), data.size());
	}

	return scope.Escape(buffer);
}

template<>
inline Napi::Value node::Value::from_undefined(Napi::Env env) {
	return Napi::Value(env, env.Undefined());
}

template<>
inline bool node::Value::to_boolean(Napi::Env env, const Napi::Value& value) {
	return value.ToBoolean();
}

template<>
inline node::String node::Value::to_string(Napi::Env env, const Napi::Value& value) {
	return value.ToString();
}

template<>
inline double node::Value::to_number(Napi::Env env, const Napi::Value& value) {
	double number = value.ToNumber();
	if (std::isnan(number)) {
		throw std::invalid_argument(util::format("Value '%1' not convertible to a number.", (std::string)to_string(env, value)));
	}

	return number;
}

template<>
inline OwnedBinaryData node::Value::to_binary(Napi::Env env, const Napi::Value value) {
	// Make a non-null OwnedBinaryData, even when `data` is nullptr.
	auto make_owned_binary_data = [](const char* data, size_t length) {
		REALM_ASSERT(data || length == 0);
		char placeholder;
		return OwnedBinaryData(data ? data : &placeholder, length);
	};

	if (Value::is_array_buffer(env, value)) {
		auto arrayBuffer = value.As<Napi::ArrayBuffer>();
		return make_owned_binary_data(static_cast<char*>(arrayBuffer.Data()), arrayBuffer.ByteLength());
	}
	else if (Value::is_array_buffer_view(env, value)) {
		int64_t byteLength = value.As<Napi::Object>().Get("byteLength").As<Napi::Number>();
		int64_t byteOffset = value.As<Napi::Object>().Get("byteOffset").As<Napi::Number>();
		Napi::ArrayBuffer arrayBuffer = value.As<Napi::Object>().Get("buffer").As<Napi::ArrayBuffer>();
		return make_owned_binary_data(static_cast<char*>(arrayBuffer.Data()) + byteOffset, byteLength);
	}
	else {
		throw std::runtime_error("Can only convert Buffer, ArrayBuffer, and ArrayBufferView objects to binary");
	}
}

template<>
inline Napi::Object node::Value::to_object(Napi::Env env, const Napi::Value& value) {
	return value.ToObject();
}

template<>
inline Napi::Object node::Value::to_array(Napi::Env env, const Napi::Value& value) {
	return to_object(env, value);
}

template<>
inline Napi::Function node::Value::to_function(Napi::Env env, const Napi::Value& value) {
	return value.IsFunction() ? value.As<Napi::Function>() : Napi::Function();
}

template<>
inline Napi::Function node::Value::to_constructor(Napi::Env env, const Napi::Value& value) {
	return to_function(env, value);
}

template<>
inline Napi::Object node::Value::to_date(Napi::Env env, const Napi::Value& value) {
	if (value.IsString()) {
		Napi::Function date_constructor = to_constructor(env, env.Global().Get("Date"));
		std::array<Napi::Value, 1 > args{ {value} };
		return node::Function::construct(env, date_constructor, args.size(), args.data());
	}

	return to_object(env, value);
}

template<>
inline Napi::Value node::Value::from_decimal128(Napi::Env env, const Decimal128& number) {
	Napi::EscapableHandleScope scope(env);

	Napi::Function realm_constructor = node::RealmClassConstructor.Value();
	Napi::Object decimal_constructor = realm_constructor.Get("_Decimal128").As<Napi::Object>();
	Napi::Function fromStringFunc = decimal_constructor.Get("fromString").As<Napi::Function>();
	Napi::String numberAsString = Napi::String::New(env, number.to_string());
	Napi::Value result = fromStringFunc.Call({ numberAsString });

	return scope.Escape(result);
}

template<>
inline Decimal128 node::Value::to_decimal128(Napi::Env env, const Napi::Value& value) {
	Napi::HandleScope scope(env);

	Napi::Object decimal128 = value.As<Napi::Object>();
	Napi::Function toStringFunc = decimal128.Get("toString").As<Napi::Function>();
	node::String string = toStringFunc.Call(value, {}).As<Napi::String>();
	std::string decimal128AsString = string;
	Decimal128 result(decimal128AsString);
	return result;
}

template<>
inline Napi::Value node::Value::from_object_id(Napi::Env env, const ObjectId& objectId) {
	Napi::EscapableHandleScope scope(env);

	Napi::Function realm_constructor = node::RealmClassConstructor.Value();
	Napi::Function object_id_constructor = realm_constructor.Get("_ObjectId").As<Napi::Function>();
	napi_value args[] = { Napi::String::New(env, objectId.to_string()) };
	Napi::Value result = object_id_constructor.New(1, args);
	return scope.Escape(result);
}

template<>
inline ObjectId node::Value::to_object_id(Napi::Env env, const Napi::Value& value) {
	Napi::HandleScope scope(env);

	Napi::Object objectId = value.As<Napi::Object>();
	Napi::Function toHexStringFunc = objectId.Get("toHexString").As<Napi::Function>();
	node::String string = toHexStringFunc.Call(value, {}).As<Napi::String>();
	std::string objectIdAsString = string;
	ObjectId result(objectIdAsString.c_str());
	return result;
}

} // js
} // realm
<|endoftext|>


<commit_before>/*
 * C S O U N D
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include "MusicModel.hpp"
#include "Exception.hpp"
#include "Composition.hpp"
#include "System.hpp"
#include <cstdio>
#include <cstdlib>
#include <cstdint>

namespace csound
{
  MusicModel::MusicModel() :
    cppSound(&cppSound_),
    threadCount(1)
  {
  }

  MusicModel::~MusicModel()
  {
    //clear();
  }

  void MusicModel::initialize()
  {
  }

  int MusicModel::generate()
  {
    int errorStatus = 0;
    cppSound->removeScore();
    if (children.size()) {
      score.clear();
    }
    traverse(getLocalCoordinates(), score);
    System::message("Generated %d events.\n", score.size());
    return errorStatus;
  }

  int MusicModel::render()
  {
    int errorStatus = generate();
    if (errorStatus) {
      return errorStatus;
    }
    errorStatus = perform();
    return errorStatus;
  }

  void MusicModel::createCsoundScore(std::string addToScore, double extendSeconds)
  {
    System::inform("addToScore.length(): %d\n", addToScore.length());
    if (addToScore.length() > 2) {
      cppSound->removeScore();
      cppSound->addScoreLine(addToScore);
    }
    cppSound->addScoreLine(score.getCsoundScore(tonesPerOctave, conformPitches));
    char buffer[0x100];
    //std::sprintf(buffer, "\ns %9.3f", extendSeconds);
    //cppSound->addScoreLine(buffer);
    std::sprintf(buffer, "\ne %9.3f\n", extendSeconds);
    cppSound->addScoreLine(buffer);
    //cppSound->exportForPerformance();
  }

  int MusicModel::perform()
  {
    int errorStatus = 0;
    cppSound->setCommand(getCsoundCommand());
    createCsoundScore(csoundScoreHeader);
    errorStatus = cppSound->perform();
    if (errorStatus == 1) {
      errorStatus = 0;
    }
    // The Csound command is managed from MusicModel,
    // not from CppSound. So we clear out what we set.
    cppSound->setCommand("");
    return errorStatus;
  }

  void MusicModel::clear()
  {
    Node::clear();
    Composition::clear();
    cppSound->removeScore();
  }

  void MusicModel::setCppSound(CppSound *cppSound)
  {
    if(!cppSound)
      {
        this->cppSound = &cppSound_;
      }
    else
      {
        this->cppSound = cppSound;
      }
  }

  CppSound *MusicModel::getCppSound()
  {
    return cppSound;
  }

  void MusicModel::setCsoundOrchestra(std::string orchestra)
  {
    cppSound->setOrchestra(orchestra);
  }

  std::string MusicModel::getCsoundOrchestra() const
  {
    return cppSound->getOrchestra();
  }

  void MusicModel::setCsoundScoreHeader(std::string header)
  {
    csoundScoreHeader = header;
  }

  std::string MusicModel::getCsoundScoreHeader() const
  {
    return csoundScoreHeader;
  }

  void MusicModel::arrange(int oldInstrumentNumber, int newInstrumentNumber)
  {
    score.arrange(oldInstrumentNumber, newInstrumentNumber);
  }

  void MusicModel::arrange(int oldInstrumentNumber,
                           int newInstrumentNumber,
                           double gain)
  {
    score.arrange(oldInstrumentNumber, newInstrumentNumber, gain);
  }

  void MusicModel::arrange(int oldInstrumentNumber,
                           int newInstrumentNumber,
                           double gain,
                           double pan)
  {
    score.arrange(oldInstrumentNumber, newInstrumentNumber, gain, pan);
  }

  void MusicModel::arrange(int silenceInstrumentNumber,
                           std::string csoundInstrumentName)
  {
    int csoundInstrumentNumber =
      cppSound->getInstrumentNumber(csoundInstrumentName);
    arrange(silenceInstrumentNumber, csoundInstrumentNumber);
  }

  void MusicModel::arrange(int silenceInstrumentNumber,
                           std::string csoundInstrumentName, double gain)
  {
    int csoundInstrumentNumber =
      cppSound->getInstrumentNumber(csoundInstrumentName);
    arrange(silenceInstrumentNumber, csoundInstrumentNumber, gain);
  }

  void MusicModel::arrange(int silenceInstrumentNumber,
                           std::string csoundInstrumentName, double gain, double pan)
  {
    int csoundInstrumentNumber =
      cppSound->getInstrumentNumber(csoundInstrumentName);
    arrange(silenceInstrumentNumber, csoundInstrumentNumber, gain, pan);
  }

  void MusicModel::removeArrangement()
  {
    score.removeArrangement();
  }

  void MusicModel::setCsoundCommand(std::string command)
  {
    cppSound->setCommand(command);
  }

  std::string MusicModel::getCsoundCommand() const
  {
    std::string command_ = cppSound->getCommand();
    if (command_.size() == 0) {
      char buffer[0x200];
      std::sprintf(buffer,
                   "csound --midi-key=4 --midi-velocity=5 -m195 -j%d -RWdfo %s",
           threadCount,
                   getOutputSoundfileName().c_str());
      command_ = buffer;
    }
    return command_;
  }

  intptr_t MusicModel::getThis()
  {
    return (intptr_t) this;
  }

  Node *MusicModel::getThisNode()
  {
    return (Node *)this;
  }

  int MusicModel::processArgs(const std::vector<std::string> &args)
  {
    System::inform("BEGAN MusicModel::processArgv()...\n");
    std::map<std::string, std::string> argsmap;
    std::string key;
    for (size_t i = 0, n = args.size(); i < n; ++i) {
      const std::string token = args[i];
      std::string value = "";
      if (token.find("--") == 0) {
        key = token;
        System::inform("argument[%2d]: %s\n", i, key.c_str());
      } else {
        value = token;
        System::inform("argument[%2d]: %s =  %s\n", i, key.c_str(), value.c_str());
      }
      argsmap[key] = value;
    }
    char command[0x200];
    int errorStatus = 0;
    bool postPossible = false;
    std::string playSoundfileName = getOutputSoundfileName();
    if ((argsmap.find("--dir") != argsmap.end()) && !errorStatus) {
      setOutputDirectory(argsmap["--dir"]);
    }
    if ((argsmap.find("--midi") != argsmap.end()) && !errorStatus) {
      errorStatus = generate();
      if (errorStatus) {
        return errorStatus;
      }
      getScore().save(getMidiFilename().c_str());
    }
    if ((argsmap.find("--notation") != argsmap.end()) && !errorStatus) {
        translateToNotation();
    }
    if ((argsmap.find("--audio") != argsmap.end()) && !errorStatus) {
      postPossible = false;
      const char *audiosystem = argsmap["--audio"].c_str();
      const char *devicename = argsmap["--device"].c_str();
      std::sprintf(command,
                   "csound --midi-key=4 --midi-velocity=5 -m195 -+rtaudio=%s -o %s",
                   audiosystem, devicename);
      System::inform("Csound command: %s\n", command);
      setCsoundCommand(command);
      errorStatus = render();
    }
    if ((argsmap.find("--csound") != argsmap.end()) && !errorStatus) {
      postPossible = true;
      errorStatus = render();
    }
    if ((argsmap.find("--pianoteq") != argsmap.end()) && !errorStatus) {
      std::sprintf(command, "Pianoteq --midi=%s\n", getMidiFilename().c_str());
      System::inform("Executing command: %s\n", command);
      errorStatus = std::system(command);
    }
    if ((argsmap.find("--pianoteq-wav") != argsmap.end()) && !errorStatus) {
      postPossible = true;
      std::sprintf(command, "Pianoteq --headless --midi %s --rate 48000 --wav %s\n", getMidiFilename().c_str(), getOutputSoundfileName().c_str());
      System::inform("Executing command: %s\n", command);
      errorStatus = std::system(command);
    }
    if ((argsmap.find("--playmidi") != argsmap.end()) && !errorStatus) {
      std::sprintf(command, "%s %s\n", argsmap["--playmidi"].c_str(), getMidiFilename().c_str());
      System::inform("Executing command: %s\n", command);
      errorStatus = std::system(command);
    }
    if ((argsmap.find("--post") != argsmap.end()) && !errorStatus && postPossible) {
      errorStatus = translateMaster();
      playSoundfileName = getNormalizedSoundfileName();
    }
    if ((argsmap.find("--playwav") != argsmap.end()) && !errorStatus) {
      std::sprintf(command, "%s %s\n", argsmap["--playwav"].c_str(), playSoundfileName.c_str());
      System::inform("Csound command: %s\n", command);
      errorStatus = std::system(command);
    }
    System::inform("ENDED MusicModel::processArgv().\n");
    return errorStatus;
  }

  void MusicModel::stop()
  {
    std::cout << "MusicModel::stop()..." << std::endl;
    cppSound->stop();
  }
}
<commit_msg>added header to make it compile again<commit_after>/*
 * C S O U N D
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include "MusicModel.hpp"
#include "Exception.hpp"
#include "Composition.hpp"
#include "System.hpp"
#include <cstdio>
#include <cstdlib>
#include <stdint.h>

namespace csound
{
  MusicModel::MusicModel() :
    cppSound(&cppSound_),
    threadCount(1)
  {
  }

  MusicModel::~MusicModel()
  {
    //clear();
  }

  void MusicModel::initialize()
  {
  }

  int MusicModel::generate()
  {
    int errorStatus = 0;
    cppSound->removeScore();
    if (children.size()) {
      score.clear();
    }
    traverse(getLocalCoordinates(), score);
    System::message("Generated %d events.\n", score.size());
    return errorStatus;
  }

  int MusicModel::render()
  {
    int errorStatus = generate();
    if (errorStatus) {
      return errorStatus;
    }
    errorStatus = perform();
    return errorStatus;
  }

  void MusicModel::createCsoundScore(std::string addToScore, double extendSeconds)
  {
    System::inform("addToScore.length(): %d\n", addToScore.length());
    if (addToScore.length() > 2) {
      cppSound->removeScore();
      cppSound->addScoreLine(addToScore);
    }
    cppSound->addScoreLine(score.getCsoundScore(tonesPerOctave, conformPitches));
    char buffer[0x100];
    //std::sprintf(buffer, "\ns %9.3f", extendSeconds);
    //cppSound->addScoreLine(buffer);
    std::sprintf(buffer, "\ne %9.3f\n", extendSeconds);
    cppSound->addScoreLine(buffer);
    //cppSound->exportForPerformance();
  }

  int MusicModel::perform()
  {
    int errorStatus = 0;
    cppSound->setCommand(getCsoundCommand());
    createCsoundScore(csoundScoreHeader);
    errorStatus = cppSound->perform();
    if (errorStatus == 1) {
      errorStatus = 0;
    }
    // The Csound command is managed from MusicModel,
    // not from CppSound. So we clear out what we set.
    cppSound->setCommand("");
    return errorStatus;
  }

  void MusicModel::clear()
  {
    Node::clear();
    Composition::clear();
    cppSound->removeScore();
  }

  void MusicModel::setCppSound(CppSound *cppSound)
  {
    if(!cppSound)
      {
        this->cppSound = &cppSound_;
      }
    else
      {
        this->cppSound = cppSound;
      }
  }

  CppSound *MusicModel::getCppSound()
  {
    return cppSound;
  }

  void MusicModel::setCsoundOrchestra(std::string orchestra)
  {
    cppSound->setOrchestra(orchestra);
  }

  std::string MusicModel::getCsoundOrchestra() const
  {
    return cppSound->getOrchestra();
  }

  void MusicModel::setCsoundScoreHeader(std::string header)
  {
    csoundScoreHeader = header;
  }

  std::string MusicModel::getCsoundScoreHeader() const
  {
    return csoundScoreHeader;
  }

  void MusicModel::arrange(int oldInstrumentNumber, int newInstrumentNumber)
  {
    score.arrange(oldInstrumentNumber, newInstrumentNumber);
  }

  void MusicModel::arrange(int oldInstrumentNumber,
                           int newInstrumentNumber,
                           double gain)
  {
    score.arrange(oldInstrumentNumber, newInstrumentNumber, gain);
  }

  void MusicModel::arrange(int oldInstrumentNumber,
                           int newInstrumentNumber,
                           double gain,
                           double pan)
  {
    score.arrange(oldInstrumentNumber, newInstrumentNumber, gain, pan);
  }

  void MusicModel::arrange(int silenceInstrumentNumber,
                           std::string csoundInstrumentName)
  {
    int csoundInstrumentNumber =
      cppSound->getInstrumentNumber(csoundInstrumentName);
    arrange(silenceInstrumentNumber, csoundInstrumentNumber);
  }

  void MusicModel::arrange(int silenceInstrumentNumber,
                           std::string csoundInstrumentName, double gain)
  {
    int csoundInstrumentNumber =
      cppSound->getInstrumentNumber(csoundInstrumentName);
    arrange(silenceInstrumentNumber, csoundInstrumentNumber, gain);
  }

  void MusicModel::arrange(int silenceInstrumentNumber,
                           std::string csoundInstrumentName, double gain, double pan)
  {
    int csoundInstrumentNumber =
      cppSound->getInstrumentNumber(csoundInstrumentName);
    arrange(silenceInstrumentNumber, csoundInstrumentNumber, gain, pan);
  }

  void MusicModel::removeArrangement()
  {
    score.removeArrangement();
  }

  void MusicModel::setCsoundCommand(std::string command)
  {
    cppSound->setCommand(command);
  }

  std::string MusicModel::getCsoundCommand() const
  {
    std::string command_ = cppSound->getCommand();
    if (command_.size() == 0) {
      char buffer[0x200];
      std::sprintf(buffer,
                   "csound --midi-key=4 --midi-velocity=5 -m195 -j%d -RWdfo %s",
           threadCount,
                   getOutputSoundfileName().c_str());
      command_ = buffer;
    }
    return command_;
  }

  intptr_t MusicModel::getThis()
  {
    return (intptr_t) this;
  }

  Node *MusicModel::getThisNode()
  {
    return (Node *)this;
  }

  int MusicModel::processArgs(const std::vector<std::string> &args)
  {
    System::inform("BEGAN MusicModel::processArgv()...\n");
    std::map<std::string, std::string> argsmap;
    std::string key;
    for (size_t i = 0, n = args.size(); i < n; ++i) {
      const std::string token = args[i];
      std::string value = "";
      if (token.find("--") == 0) {
        key = token;
        System::inform("argument[%2d]: %s\n", i, key.c_str());
      } else {
        value = token;
        System::inform("argument[%2d]: %s =  %s\n", i, key.c_str(), value.c_str());
      }
      argsmap[key] = value;
    }
    char command[0x200];
    int errorStatus = 0;
    bool postPossible = false;
    std::string playSoundfileName = getOutputSoundfileName();
    if ((argsmap.find("--dir") != argsmap.end()) && !errorStatus) {
      setOutputDirectory(argsmap["--dir"]);
    }
    if ((argsmap.find("--midi") != argsmap.end()) && !errorStatus) {
      errorStatus = generate();
      if (errorStatus) {
        return errorStatus;
      }
      getScore().save(getMidiFilename().c_str());
    }
    if ((argsmap.find("--notation") != argsmap.end()) && !errorStatus) {
        translateToNotation();
    }
    if ((argsmap.find("--audio") != argsmap.end()) && !errorStatus) {
      postPossible = false;
      const char *audiosystem = argsmap["--audio"].c_str();
      const char *devicename = argsmap["--device"].c_str();
      std::sprintf(command,
                   "csound --midi-key=4 --midi-velocity=5 -m195 -+rtaudio=%s -o %s",
                   audiosystem, devicename);
      System::inform("Csound command: %s\n", command);
      setCsoundCommand(command);
      errorStatus = render();
    }
    if ((argsmap.find("--csound") != argsmap.end()) && !errorStatus) {
      postPossible = true;
      errorStatus = render();
    }
    if ((argsmap.find("--pianoteq") != argsmap.end()) && !errorStatus) {
      std::sprintf(command, "Pianoteq --midi=%s\n", getMidiFilename().c_str());
      System::inform("Executing command: %s\n", command);
      errorStatus = std::system(command);
    }
    if ((argsmap.find("--pianoteq-wav") != argsmap.end()) && !errorStatus) {
      postPossible = true;
      std::sprintf(command, "Pianoteq --headless --midi %s --rate 48000 --wav %s\n", getMidiFilename().c_str(), getOutputSoundfileName().c_str());
      System::inform("Executing command: %s\n", command);
      errorStatus = std::system(command);
    }
    if ((argsmap.find("--playmidi") != argsmap.end()) && !errorStatus) {
      std::sprintf(command, "%s %s\n", argsmap["--playmidi"].c_str(), getMidiFilename().c_str());
      System::inform("Executing command: %s\n", command);
      errorStatus = std::system(command);
    }
    if ((argsmap.find("--post") != argsmap.end()) && !errorStatus && postPossible) {
      errorStatus = translateMaster();
      playSoundfileName = getNormalizedSoundfileName();
    }
    if ((argsmap.find("--playwav") != argsmap.end()) && !errorStatus) {
      std::sprintf(command, "%s %s\n", argsmap["--playwav"].c_str(), playSoundfileName.c_str());
      System::inform("Csound command: %s\n", command);
      errorStatus = std::system(command);
    }
    System::inform("ENDED MusicModel::processArgv().\n");
    return errorStatus;
  }

  void MusicModel::stop()
  {
    std::cout << "MusicModel::stop()..." << std::endl;
    cppSound->stop();
  }
}
<|endoftext|>