<commit_before>#include "plotwidget.h"
#include "plot.h"
#include "signalhandler.h"
#include "signaldata.h"
#include "setscaledialog.h"
#include "selectsignaldialog.h"
#include "signaldescription.h"
#include "pythonchannelsubscribercollection.h"

#include <qwt_scale_engine.h>
#include <qlabel.h>
#include <qlayout.h>
#include <QDoubleSpinBox>
#include <QMenu>
#include <QAction>
#include <QLabel>
#include <QInputDialog>
#include <QDialogButtonBox>
#include <QListWidget>
#include <QTimer>
#include <QPushButton>
#include <QColorDialog>

PlotWidget::PlotWidget(PythonChannelSubscriberCollection* subscribers, QWidget *parent):
    QWidget(parent),
    mSubscribers(subscribers)
{

  d_plot = new Plot(this);

  mColors << Qt::green
          << Qt::red
          << Qt::blue
          << Qt::cyan
          << Qt::magenta
          << Qt::darkYellow
          << QColor(139, 69, 19) // brown
          << Qt::darkCyan
          << Qt::darkGreen
          << Qt::darkMagenta
          << Qt::black;

  mTimeWindowSpin = new QDoubleSpinBox;
  mTimeWindowSpin->setSingleStep(0.1);

  QDoubleSpinBox* yScaleSpin = new QDoubleSpinBox;
  yScaleSpin->setSingleStep(0.1);

  QVBoxLayout* vLayout1 = new QVBoxLayout();

  //QPushButton* resetYScaleButton = new QPushButton("Reset Y scale");
  //vLayout1->addWidget(resetYScaleButton);

  QWidget* frameWidget = new QWidget;
  QHBoxLayout* frameLayout = new QHBoxLayout(frameWidget);
  frameWidget->setContentsMargins(0, 0, 0, 0);
  frameLayout->addWidget(new QLabel("Time Window [s]:"));
  frameLayout->addWidget(mTimeWindowSpin);
  vLayout1->addWidget(frameWidget);

  mSignalListWidget = new QListWidget(this);
  vLayout1->addWidget(mSignalListWidget);

  mSignalInfoLabel = new QLabel(this);
  vLayout1->addWidget(mSignalInfoLabel);
  vLayout1->addStretch(10);

  QHBoxLayout *layout = new QHBoxLayout(this);
  layout->addWidget(d_plot, 10);
  layout->addLayout(vLayout1);

  mTimeWindowSpin->setValue(d_plot->timeWindow());

  connect(mTimeWindowSpin, SIGNAL(valueChanged(double)),
          d_plot, SLOT(setTimeWindow(double)));

  connect(d_plot, SIGNAL(syncXAxisScale(double, double)),
          this, SIGNAL(syncXAxisScale(double, double)));

  //connect(yScaleSpin, SIGNAL(valueChanged(double)),
  //        d_plot, SLOT(setYScale(double)));
  //yScaleSpin->setValue(10.0);

  this->setContextMenuPolicy(Qt::CustomContextMenu);
  this->connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
      SLOT(onShowContextMenu(const QPoint&)));

  //mSignalListWidget->setDragDropMode(QAbstractItemView::DragDrop);
  //mSignalListWidget->setDragEnabled(true);
  //mSignalListWidget->setDefaultDropAction(Qt::MoveAction);
  mSignalListWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);

  mSignalListWidget->setContextMenuPolicy(Qt::CustomContextMenu);
  this->connect(mSignalListWidget, SIGNAL(customContextMenuRequested(const QPoint&)),
      SLOT(onShowSignalContextMenu(const QPoint&)));

  this->connect(mSignalListWidget, SIGNAL(itemChanged(QListWidgetItem *)), SLOT(onSignalListItemChanged(QListWidgetItem*)));

  QTimer* labelUpdateTimer = new QTimer(this);
  this->connect(labelUpdateTimer, SIGNAL(timeout()), SLOT(updateSignalInfoLabel()));
  labelUpdateTimer->start(100);
}

void PlotWidget::onShowContextMenu(const QPoint& pos)
{

  QPoint globalPos = this->mapToGlobal(pos);
  // for QAbstractScrollArea and derived classes you would use:
  // QPoint globalPos = myWidget->viewport()->mapToGlobal(pos);

  QMenu myMenu;
  myMenu.addAction("Add signal");
  myMenu.addSeparator();
  myMenu.addAction("Reset Y axis scale");
  myMenu.addAction("Set Y axis scale");
  myMenu.addSeparator();
  myMenu.addAction("Remove plot");

  QAction* selectedItem = myMenu.exec(globalPos);
  if (!selectedItem)
  {
    return;
  }

  QString selectedAction = selectedItem->text();

  if (selectedAction == "Remove plot")
  {
    emit this->removePlotRequested(this);
  }
  else if (selectedAction == "Add signal")
  {
    emit this->addSignalRequested(this);
  }
  else if (selectedAction == "Reset Y axis scale")
  {
    this->onResetYAxisScale();
  }
  else if (selectedAction == "Set Y axis scale")
  {

    SetScaleDialog dialog(this);
    QwtInterval axisInterval = d_plot->axisInterval(QwtPlot::yLeft);
    dialog.setUpper(axisInterval.maxValue());
    dialog.setLower(axisInterval.minValue());

    int result = dialog.exec();
    if (result == QDialog::Accepted)
    {
      d_plot->setAxisScale(QwtPlot::yLeft, dialog.lower(), dialog.upper());
    }
  }
}

QList<SignalHandler*> PlotWidget::signalHandlers()
{
  QList<SignalHandler*> handlers;
  for (int i = 0; i < mSignalListWidget->count(); ++i)
  {
    handlers.append(mSignals[mSignalListWidget->item(i)]);
  }

  return handlers;
}

void PlotWidget::onShowSignalContextMenu(const QPoint& pos)
{

  if (mSignals.empty())
  {
    return;
  }

  QPoint globalPos = mSignalListWidget->mapToGlobal(pos);
  // for QAbstractScrollArea and derived classes you would use:
  // QPoint globalPos = myWidget->viewport()->mapToGlobal(pos);

  QMenu myMenu;
  if (mSignalListWidget->selectedItems().size() == 1)
    {
    myMenu.addAction("Change color");
    myMenu.addSeparator();
    }

  myMenu.addAction("Remove signal");

  QAction* selectedItem = myMenu.exec(globalPos);
  if (!selectedItem)
  {
    return;
  }

  QString selectedAction = selectedItem->text();

  if (selectedAction == "Change color")
  {
    QListWidgetItem* signalItem = mSignalListWidget->currentItem();
    SignalHandler* signalHandler = signalItem->data(Qt::UserRole).value<SignalHandler*>();
    QColor initialColor = signalHandler->signalDescription()->mColor;
    QColor newColor = QColorDialog::getColor(initialColor, this, "Choose signal color");

    if (newColor.isValid())
    {
      signalHandler->signalDescription()->mColor = newColor;
      QPixmap pixmap(24, 24);
      pixmap.fill(newColor);
      signalItem->setIcon(QIcon(pixmap));
      d_plot->setSignalColor(signalHandler->signalData(), newColor);
    }

  }
  else if (selectedAction == "Remove signal")
  {

    QList<QListWidgetItem*> selectedItems = mSignalListWidget->selectedItems();
    foreach (QListWidgetItem*	selectedItem, selectedItems)
    {
      QListWidgetItem* signalItem = mSignalListWidget->currentItem();
      SignalHandler* signalHandler = this->signalForItem(signalItem);

      mSubscribers->removeSignalHandler(signalHandler);

      d_plot->removeSignal(signalHandler->signalData());
      mSignals.remove(signalItem);

      delete signalItem;
      delete signalHandler;
    }
  }

}

void PlotWidget::updateSignalInfoLabel()
{
  mSignalInfoLabel->setText(QString());

  QListWidgetItem* selectedItem = mSignalListWidget->currentItem();
  if (!selectedItem)
  {
    return;
  }

  SignalHandler* signalHandler = selectedItem->data(Qt::UserRole).value<SignalHandler*>();
  SignalData* signalData = signalHandler->signalData();

  QString signalValue = "No data";
  int numberOfValues = signalData->size();
  if (numberOfValues)
  {
    signalValue = QString::number(signalData->value(numberOfValues-1).y(), 'g', 6);
  }

  QString signalInfoText = QString("Freq:  %1  Val: %2").arg(QString::number(signalData->messageFrequency(), 'f', 1)).arg(signalValue);

  mSignalInfoLabel->setText(signalInfoText);
}

void PlotWidget::setEndTime(double endTime)
{
  d_plot->setEndTime(endTime);
}

void PlotWidget::setXAxisScale(double x0, double x1)
{
  d_plot->setAxisScale(QwtPlot::xBottom, x0, x1);
}

void PlotWidget::replot()
{
  d_plot->replot();
}

void PlotWidget::onResetYAxisScale()
{

}

void PlotWidget::onSignalListItemChanged(QListWidgetItem* item)
{
  SignalHandler* signalHandler = this->signalForItem(item);
  Qt::CheckState checkState = item->checkState();

  if (!item->isSelected())
  {
    mSignalListWidget->clearSelection();
    item->setSelected(true);
  }

  QList<QListWidgetItem*> selectedItems = mSignalListWidget->selectedItems();
  foreach (QListWidgetItem*	selectedItem, selectedItems)
  {
    SignalHandler* signalHandler = this->signalForItem(selectedItem);
    selectedItem->setCheckState(checkState);
    d_plot->setSignalVisible(signalHandler->signalData(), checkState == Qt::Checked);
  }
}

QListWidgetItem* PlotWidget::itemForSignal(SignalHandler* signalHandler)
{
  return mSignals.key(signalHandler);
}

SignalHandler* PlotWidget::signalForItem(QListWidgetItem* item)
{
  return mSignals.value(item);
}

bool PlotWidget::signalIsVisible(SignalHandler* signalHandler)
{
  if (!signalHandler)
  {
    return false;
  }

  return (this->itemForSignal(signalHandler)->checkState() == Qt::Checked);
}

void PlotWidget::setSignalVisibility(SignalHandler* signalHandler, bool visible)
{
  QListWidgetItem* item = this->itemForSignal(signalHandler);
  if (item)
  {
    item->setCheckState(visible ? Qt::Checked : Qt::Unchecked);
  }
}

void PlotWidget::start()
{
  d_plot->start();
}

void PlotWidget::stop()
{
  d_plot->stop();
}

void PlotWidget::clearHistory()
{
  foreach (SignalHandler* handler, this->signalHandlers())
  {
    handler->signalData()->clear();
  }

  d_plot->replot();
}

void PlotWidget::setBackgroundColor(QString color)
{
  d_plot->setBackgroundColor(color);
}

void PlotWidget::setPointSize(double pointSize)
{
  d_plot->setPointSize(pointSize);
}

void PlotWidget::setCurveStyle(QwtPlotCurve::CurveStyle style)
{
  d_plot->setCurveStyle(style);
}

void PlotWidget::addSignal(const QMap<QString, QVariant>& signalSettings)
{
  SignalDescription desc;
  desc.mChannel = signalSettings.value("channel").toString();
  desc.mMessageType = signalSettings.value("messageType").toString();
  desc.mFieldName = signalSettings.value("fieldName").toString();
  desc.mArrayKeys = signalSettings.value("arrayKeys").toStringList();

  QList<QVariant> color = signalSettings.value("color").toList();
  if (color.size() == 3)
  {
    desc.mColor = QColor::fromRgb(color[0].toInt(), color[1].toInt(), color[2].toInt());
  }

  bool visible = signalSettings.value("visible", true).toBool();

  SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&desc);

  if (signalHandler)
  {
    //printf("adding signal: %s\n", qPrintable(signalHandler->description()));
  }
  else
  {
    printf("failed to create signal from signal settings.\n");
  }

  this->addSignal(signalHandler);
  this->setSignalVisibility(signalHandler, visible);
}

Q_DECLARE_METATYPE(SignalHandler*);

void PlotWidget::addSignal(SignalHandler* signalHandler)
{
  if (!signalHandler)
  {
    return;
  }

  QColor color = signalHandler->signalDescription()->mColor;
  if (!color.isValid())
  {
    int signalColorIndex = mSignals.size() % mColors.size();
    color = mColors[signalColorIndex];
    signalHandler->signalDescription()->mColor = color;
  }

  QString signalDescription = QString("%2 [%1]").arg(signalHandler->channel()).arg(signalHandler->description().split(".").back());
  QListWidgetItem* signalItem = new QListWidgetItem(signalDescription);
  mSignalListWidget->addItem(signalItem);
  mSignals[signalItem] = signalHandler;

  mSubscribers->addSignalHandler(signalHandler);

  d_plot->addSignal(signalHandler->signalData(), color);

  QPixmap pixmap(24, 24);
  pixmap.fill(color);
  signalItem->setIcon(QIcon(pixmap));

  signalItem->setData(Qt::UserRole, qVariantFromValue(signalHandler));
  signalItem->setData(Qt::CheckStateRole, Qt::Checked);
}

void PlotWidget::loadSettings(const QMap<QString, QVariant>& plotSettings)
{
  QList<QVariant> signalList = plotSettings.value("signals").toList();
  foreach (const QVariant& signalVariant, signalList)
  {
    this->addSignal(signalVariant.toMap());
  }

  double timeWindow = plotSettings.value("timeWindow", QVariant(10.0)).toDouble();
  double ymin = plotSettings.value("ymin", QVariant(-10.0)).toDouble();
  double ymax = plotSettings.value("ymax", QVariant(10.0)).toDouble();
  d_plot->setAxisScale(QwtPlot::yLeft, ymin, ymax);
  mTimeWindowSpin->setValue(timeWindow);

  if (plotSettings.value("curveStyle", "dots") == "lines")
  {
    d_plot->setCurveStyle(QwtPlotCurve::Lines);
  }
}

QMap<QString, QVariant> PlotWidget::saveSettings()
{
  QMap<QString, QVariant> settings;

  settings["ymin"] = d_plot->axisInterval(QwtPlot::yLeft).minValue();
  settings["ymax"] = d_plot->axisInterval(QwtPlot::yLeft).maxValue();
  settings["timeWindow"] = d_plot->timeWindow();

  QList<QVariant> signalSettings;
  foreach (SignalHandler* signalHandler, this->signalHandlers())
  {
    signalSettings.append(this->saveSignalSettings(signalHandler));
  }

  settings["signals"] = signalSettings;
  return settings;
}

QMap<QString, QVariant> PlotWidget::saveSignalSettings(SignalHandler* signalHandler)
{
  QMap<QString, QVariant> settings;

  SignalDescription* signalDescription = signalHandler->signalDescription();

  settings["channel"] = signalDescription->mChannel;
  settings["messageType"] = signalDescription->mMessageType;
  settings["fieldName"] = signalDescription->mFieldName;
  settings["arrayKeys"] = QVariant(signalDescription->mArrayKeys);
  settings["visible"] = QVariant(this->itemForSignal(signalHandler)->checkState() == Qt::Checked);

  QList<QVariant> color;
  color << signalDescription->mColor.red() << signalDescription->mColor.green() << signalDescription->mColor.blue();
  settings["color"] = color;

  return settings;
}

<commit_msg>fix bug in multiselect + remove signal<commit_after>#include "plotwidget.h"
#include "plot.h"
#include "signalhandler.h"
#include "signaldata.h"
#include "setscaledialog.h"
#include "selectsignaldialog.h"
#include "signaldescription.h"
#include "pythonchannelsubscribercollection.h"

#include <qwt_scale_engine.h>
#include <qlabel.h>
#include <qlayout.h>
#include <QDoubleSpinBox>
#include <QMenu>
#include <QAction>
#include <QLabel>
#include <QInputDialog>
#include <QDialogButtonBox>
#include <QListWidget>
#include <QTimer>
#include <QPushButton>
#include <QColorDialog>

PlotWidget::PlotWidget(PythonChannelSubscriberCollection* subscribers, QWidget *parent):
    QWidget(parent),
    mSubscribers(subscribers)
{

  d_plot = new Plot(this);

  mColors << Qt::green
          << Qt::red
          << Qt::blue
          << Qt::cyan
          << Qt::magenta
          << Qt::darkYellow
          << QColor(139, 69, 19) // brown
          << Qt::darkCyan
          << Qt::darkGreen
          << Qt::darkMagenta
          << Qt::black;

  mTimeWindowSpin = new QDoubleSpinBox;
  mTimeWindowSpin->setSingleStep(0.1);

  QDoubleSpinBox* yScaleSpin = new QDoubleSpinBox;
  yScaleSpin->setSingleStep(0.1);

  QVBoxLayout* vLayout1 = new QVBoxLayout();

  //QPushButton* resetYScaleButton = new QPushButton("Reset Y scale");
  //vLayout1->addWidget(resetYScaleButton);

  QWidget* frameWidget = new QWidget;
  QHBoxLayout* frameLayout = new QHBoxLayout(frameWidget);
  frameWidget->setContentsMargins(0, 0, 0, 0);
  frameLayout->addWidget(new QLabel("Time Window [s]:"));
  frameLayout->addWidget(mTimeWindowSpin);
  vLayout1->addWidget(frameWidget);

  mSignalListWidget = new QListWidget(this);
  vLayout1->addWidget(mSignalListWidget);

  mSignalInfoLabel = new QLabel(this);
  vLayout1->addWidget(mSignalInfoLabel);
  vLayout1->addStretch(10);

  QHBoxLayout *layout = new QHBoxLayout(this);
  layout->addWidget(d_plot, 10);
  layout->addLayout(vLayout1);

  mTimeWindowSpin->setValue(d_plot->timeWindow());

  connect(mTimeWindowSpin, SIGNAL(valueChanged(double)),
          d_plot, SLOT(setTimeWindow(double)));

  connect(d_plot, SIGNAL(syncXAxisScale(double, double)),
          this, SIGNAL(syncXAxisScale(double, double)));

  //connect(yScaleSpin, SIGNAL(valueChanged(double)),
  //        d_plot, SLOT(setYScale(double)));
  //yScaleSpin->setValue(10.0);

  this->setContextMenuPolicy(Qt::CustomContextMenu);
  this->connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
      SLOT(onShowContextMenu(const QPoint&)));

  //mSignalListWidget->setDragDropMode(QAbstractItemView::DragDrop);
  //mSignalListWidget->setDragEnabled(true);
  //mSignalListWidget->setDefaultDropAction(Qt::MoveAction);
  mSignalListWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);

  mSignalListWidget->setContextMenuPolicy(Qt::CustomContextMenu);
  this->connect(mSignalListWidget, SIGNAL(customContextMenuRequested(const QPoint&)),
      SLOT(onShowSignalContextMenu(const QPoint&)));

  this->connect(mSignalListWidget, SIGNAL(itemChanged(QListWidgetItem *)), SLOT(onSignalListItemChanged(QListWidgetItem*)));

  QTimer* labelUpdateTimer = new QTimer(this);
  this->connect(labelUpdateTimer, SIGNAL(timeout()), SLOT(updateSignalInfoLabel()));
  labelUpdateTimer->start(100);
}

void PlotWidget::onShowContextMenu(const QPoint& pos)
{

  QPoint globalPos = this->mapToGlobal(pos);
  // for QAbstractScrollArea and derived classes you would use:
  // QPoint globalPos = myWidget->viewport()->mapToGlobal(pos);

  QMenu myMenu;
  myMenu.addAction("Add signal");
  myMenu.addSeparator();
  myMenu.addAction("Reset Y axis scale");
  myMenu.addAction("Set Y axis scale");
  myMenu.addSeparator();
  myMenu.addAction("Remove plot");

  QAction* selectedItem = myMenu.exec(globalPos);
  if (!selectedItem)
  {
    return;
  }

  QString selectedAction = selectedItem->text();

  if (selectedAction == "Remove plot")
  {
    emit this->removePlotRequested(this);
  }
  else if (selectedAction == "Add signal")
  {
    emit this->addSignalRequested(this);
  }
  else if (selectedAction == "Reset Y axis scale")
  {
    this->onResetYAxisScale();
  }
  else if (selectedAction == "Set Y axis scale")
  {

    SetScaleDialog dialog(this);
    QwtInterval axisInterval = d_plot->axisInterval(QwtPlot::yLeft);
    dialog.setUpper(axisInterval.maxValue());
    dialog.setLower(axisInterval.minValue());

    int result = dialog.exec();
    if (result == QDialog::Accepted)
    {
      d_plot->setAxisScale(QwtPlot::yLeft, dialog.lower(), dialog.upper());
    }
  }
}

QList<SignalHandler*> PlotWidget::signalHandlers()
{
  QList<SignalHandler*> handlers;
  for (int i = 0; i < mSignalListWidget->count(); ++i)
  {
    handlers.append(mSignals[mSignalListWidget->item(i)]);
  }

  return handlers;
}

void PlotWidget::onShowSignalContextMenu(const QPoint& pos)
{

  if (mSignals.empty())
  {
    return;
  }

  QPoint globalPos = mSignalListWidget->mapToGlobal(pos);
  // for QAbstractScrollArea and derived classes you would use:
  // QPoint globalPos = myWidget->viewport()->mapToGlobal(pos);

  QMenu myMenu;
  if (mSignalListWidget->selectedItems().size() == 1)
    {
    myMenu.addAction("Change color");
    myMenu.addSeparator();
    }

  myMenu.addAction("Remove signal");

  QAction* selectedItem = myMenu.exec(globalPos);
  if (!selectedItem)
  {
    return;
  }

  QString selectedAction = selectedItem->text();

  if (selectedAction == "Change color")
  {
    QListWidgetItem* signalItem = mSignalListWidget->currentItem();
    SignalHandler* signalHandler = signalItem->data(Qt::UserRole).value<SignalHandler*>();
    QColor initialColor = signalHandler->signalDescription()->mColor;
    QColor newColor = QColorDialog::getColor(initialColor, this, "Choose signal color");

    if (newColor.isValid())
    {
      signalHandler->signalDescription()->mColor = newColor;
      QPixmap pixmap(24, 24);
      pixmap.fill(newColor);
      signalItem->setIcon(QIcon(pixmap));
      d_plot->setSignalColor(signalHandler->signalData(), newColor);
    }

  }
  else if (selectedAction == "Remove signal")
  {

    QList<QListWidgetItem*> selectedItems = mSignalListWidget->selectedItems();
    foreach (QListWidgetItem*	selectedItem, selectedItems)
    {
      SignalHandler* signalHandler = this->signalForItem(selectedItem);

      mSubscribers->removeSignalHandler(signalHandler);

      d_plot->removeSignal(signalHandler->signalData());
      mSignals.remove(selectedItem);

      delete selectedItem;
      delete signalHandler;
    }
  }

}

void PlotWidget::updateSignalInfoLabel()
{
  mSignalInfoLabel->setText(QString());

  QListWidgetItem* selectedItem = mSignalListWidget->currentItem();
  if (!selectedItem)
  {
    return;
  }

  SignalHandler* signalHandler = selectedItem->data(Qt::UserRole).value<SignalHandler*>();
  SignalData* signalData = signalHandler->signalData();

  QString signalValue = "No data";
  int numberOfValues = signalData->size();
  if (numberOfValues)
  {
    signalValue = QString::number(signalData->value(numberOfValues-1).y(), 'g', 6);
  }

  QString signalInfoText = QString("Freq:  %1  Val: %2").arg(QString::number(signalData->messageFrequency(), 'f', 1)).arg(signalValue);

  mSignalInfoLabel->setText(signalInfoText);
}

void PlotWidget::setEndTime(double endTime)
{
  d_plot->setEndTime(endTime);
}

void PlotWidget::setXAxisScale(double x0, double x1)
{
  d_plot->setAxisScale(QwtPlot::xBottom, x0, x1);
}

void PlotWidget::replot()
{
  d_plot->replot();
}

void PlotWidget::onResetYAxisScale()
{

}

void PlotWidget::onSignalListItemChanged(QListWidgetItem* item)
{
  SignalHandler* signalHandler = this->signalForItem(item);
  Qt::CheckState checkState = item->checkState();

  if (!item->isSelected())
  {
    mSignalListWidget->clearSelection();
    item->setSelected(true);
  }

  QList<QListWidgetItem*> selectedItems = mSignalListWidget->selectedItems();
  foreach (QListWidgetItem*	selectedItem, selectedItems)
  {
    SignalHandler* signalHandler = this->signalForItem(selectedItem);
    selectedItem->setCheckState(checkState);
    d_plot->setSignalVisible(signalHandler->signalData(), checkState == Qt::Checked);
  }
}

QListWidgetItem* PlotWidget::itemForSignal(SignalHandler* signalHandler)
{
  return mSignals.key(signalHandler);
}

SignalHandler* PlotWidget::signalForItem(QListWidgetItem* item)
{
  return mSignals.value(item);
}

bool PlotWidget::signalIsVisible(SignalHandler* signalHandler)
{
  if (!signalHandler)
  {
    return false;
  }

  return (this->itemForSignal(signalHandler)->checkState() == Qt::Checked);
}

void PlotWidget::setSignalVisibility(SignalHandler* signalHandler, bool visible)
{
  QListWidgetItem* item = this->itemForSignal(signalHandler);
  if (item)
  {
    item->setCheckState(visible ? Qt::Checked : Qt::Unchecked);
  }
}

void PlotWidget::start()
{
  d_plot->start();
}

void PlotWidget::stop()
{
  d_plot->stop();
}

void PlotWidget::clearHistory()
{
  foreach (SignalHandler* handler, this->signalHandlers())
  {
    handler->signalData()->clear();
  }

  d_plot->replot();
}

void PlotWidget::setBackgroundColor(QString color)
{
  d_plot->setBackgroundColor(color);
}

void PlotWidget::setPointSize(double pointSize)
{
  d_plot->setPointSize(pointSize);
}

void PlotWidget::setCurveStyle(QwtPlotCurve::CurveStyle style)
{
  d_plot->setCurveStyle(style);
}

void PlotWidget::addSignal(const QMap<QString, QVariant>& signalSettings)
{
  SignalDescription desc;
  desc.mChannel = signalSettings.value("channel").toString();
  desc.mMessageType = signalSettings.value("messageType").toString();
  desc.mFieldName = signalSettings.value("fieldName").toString();
  desc.mArrayKeys = signalSettings.value("arrayKeys").toStringList();

  QList<QVariant> color = signalSettings.value("color").toList();
  if (color.size() == 3)
  {
    desc.mColor = QColor::fromRgb(color[0].toInt(), color[1].toInt(), color[2].toInt());
  }

  bool visible = signalSettings.value("visible", true).toBool();

  SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&desc);

  if (signalHandler)
  {
    //printf("adding signal: %s\n", qPrintable(signalHandler->description()));
  }
  else
  {
    printf("failed to create signal from signal settings.\n");
  }

  this->addSignal(signalHandler);
  this->setSignalVisibility(signalHandler, visible);
}

Q_DECLARE_METATYPE(SignalHandler*);

void PlotWidget::addSignal(SignalHandler* signalHandler)
{
  if (!signalHandler)
  {
    return;
  }

  QColor color = signalHandler->signalDescription()->mColor;
  if (!color.isValid())
  {
    int signalColorIndex = mSignals.size() % mColors.size();
    color = mColors[signalColorIndex];
    signalHandler->signalDescription()->mColor = color;
  }

  QString signalDescription = QString("%2 [%1]").arg(signalHandler->channel()).arg(signalHandler->description().split(".").back());
  QListWidgetItem* signalItem = new QListWidgetItem(signalDescription);
  mSignalListWidget->addItem(signalItem);
  mSignals[signalItem] = signalHandler;

  mSubscribers->addSignalHandler(signalHandler);

  d_plot->addSignal(signalHandler->signalData(), color);

  QPixmap pixmap(24, 24);
  pixmap.fill(color);
  signalItem->setIcon(QIcon(pixmap));

  signalItem->setData(Qt::UserRole, qVariantFromValue(signalHandler));
  signalItem->setData(Qt::CheckStateRole, Qt::Checked);
}

void PlotWidget::loadSettings(const QMap<QString, QVariant>& plotSettings)
{
  QList<QVariant> signalList = plotSettings.value("signals").toList();
  foreach (const QVariant& signalVariant, signalList)
  {
    this->addSignal(signalVariant.toMap());
  }

  double timeWindow = plotSettings.value("timeWindow", QVariant(10.0)).toDouble();
  double ymin = plotSettings.value("ymin", QVariant(-10.0)).toDouble();
  double ymax = plotSettings.value("ymax", QVariant(10.0)).toDouble();
  d_plot->setAxisScale(QwtPlot::yLeft, ymin, ymax);
  mTimeWindowSpin->setValue(timeWindow);

  if (plotSettings.value("curveStyle", "dots") == "lines")
  {
    d_plot->setCurveStyle(QwtPlotCurve::Lines);
  }
}

QMap<QString, QVariant> PlotWidget::saveSettings()
{
  QMap<QString, QVariant> settings;

  settings["ymin"] = d_plot->axisInterval(QwtPlot::yLeft).minValue();
  settings["ymax"] = d_plot->axisInterval(QwtPlot::yLeft).maxValue();
  settings["timeWindow"] = d_plot->timeWindow();

  QList<QVariant> signalSettings;
  foreach (SignalHandler* signalHandler, this->signalHandlers())
  {
    signalSettings.append(this->saveSignalSettings(signalHandler));
  }

  settings["signals"] = signalSettings;
  return settings;
}

QMap<QString, QVariant> PlotWidget::saveSignalSettings(SignalHandler* signalHandler)
{
  QMap<QString, QVariant> settings;

  SignalDescription* signalDescription = signalHandler->signalDescription();

  settings["channel"] = signalDescription->mChannel;
  settings["messageType"] = signalDescription->mMessageType;
  settings["fieldName"] = signalDescription->mFieldName;
  settings["arrayKeys"] = QVariant(signalDescription->mArrayKeys);
  settings["visible"] = QVariant(this->itemForSignal(signalHandler)->checkState() == Qt::Checked);

  QList<QVariant> color;
  color << signalDescription->mColor.red() << signalDescription->mColor.green() << signalDescription->mColor.blue();
  settings["color"] = color;

  return settings;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xiroot.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2003-09-16 08:19:54 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// ============================================================================

#ifndef SC_XIROOT_HXX
#define SC_XIROOT_HXX

#ifndef SC_XLROOT_HXX
#include "xlroot.hxx"
#endif

// Global data ================================================================

class XclImpSst;
class XclImpPalette;
class XclImpFontBuffer;
class XclImpNumFmtBuffer;
class XclImpXFBuffer;
class XclImpXFIndexBuffer;
class XclImpTabIdBuffer;
class XclImpLinkManager;
class XclImpObjectManager;
class XclImpCondFormatManager;
class XclImpWebQueryBuffer;

/** Stores global buffers and data needed for Excel import filter. */
struct XclImpRootData : public XclRootData
{
    typedef ::std::auto_ptr< XclImpSst >                XclImpSstPtr;
    typedef ::std::auto_ptr< XclImpPalette >            XclImpPalettePtr;
    typedef ::std::auto_ptr< XclImpFontBuffer >         XclImpFontBufferPtr;
    typedef ::std::auto_ptr< XclImpNumFmtBuffer >       XclImpNumFmtBufferPtr;
    typedef ::std::auto_ptr< XclImpXFBuffer >           XclImpXFBufferPtr;
    typedef ::std::auto_ptr< XclImpXFIndexBuffer >      XclImpXFIndexBufferPtr;
    typedef ::std::auto_ptr< XclImpTabIdBuffer >        XclImpTabIdBufferPtr;
    typedef ::std::auto_ptr< XclImpLinkManager >        XclImpLinkManagerPtr;
    typedef ::std::auto_ptr< XclImpObjectManager >      XclImpObjectManagerPtr;
    typedef ::std::auto_ptr< XclImpCondFormatManager >  XclImpCondFormatManagerPtr;
    typedef ::std::auto_ptr< XclImpWebQueryBuffer >     XclImpWebQueryBufferPtr;

    XclImpSstPtr                mpSst;              /// The shared string table.

    XclImpPalettePtr            mpPalette;          /// The color buffer.
    XclImpFontBufferPtr         mpFontBuffer;       /// All fonts in the file.
    XclImpNumFmtBufferPtr       mpNumFmtBuffer;     /// All number formats in the file.
    XclImpXFBufferPtr           mpXFBuffer;         /// All XF record data in the file.
    XclImpXFIndexBufferPtr      mpXFIndexBuffer;    /// Buffer of XF indexes in a sheet.

    XclImpTabIdBufferPtr        mpTabIdBuffer;      /// Sheet creation order list.
    XclImpLinkManagerPtr        mpLinkManager;      /// Manager for internal/external links.

    XclImpObjectManagerPtr      mpObjManager;       /// All drawing objects.
    XclImpCondFormatManagerPtr  mpCondFmtManager;   /// Conditional formattings.
    XclImpWebQueryBufferPtr     mpWebQBuffer;       /// All web queries.

    explicit                    XclImpRootData(
                                    XclBiff eBiff,
                                    ScDocument& rDocument,
                                    const String& rDocUrl,
                                    CharSet eCharSet );
    virtual                     ~XclImpRootData();
};

// ----------------------------------------------------------------------------

class ExcelToSc;

/** Access to global data from other classes. */
class XclImpRoot : public XclRoot
{
private:
    mutable XclImpRootData&     mrImpData;      /// Reference to the global import data struct.

public:
                                XclImpRoot( const XclImpRoot& rRoot );

    XclImpRoot&                 operator=( const XclImpRoot& rRoot );

    /** Returns this root instance - for code readability in derived classes. */
    inline const XclImpRoot&    GetRoot() const { return *this; }

    /** Returns the shared string table. */
    XclImpSst&                  GetSst() const;

    /** Returns the color buffer. */
    XclImpPalette&              GetPalette() const;
    /** Returns the font buffer. */
    XclImpFontBuffer&           GetFontBuffer() const;
    /** Returns the number format buffer. */
    XclImpNumFmtBuffer&         GetNumFmtBuffer() const;
    /** Returns the cell formatting attributes buffer. */
    XclImpXFBuffer&             GetXFBuffer() const;
    /** Returns the buffer of XF indexes for a sheet. */
    XclImpXFIndexBuffer&        GetXFIndexBuffer() const;

    /** Returns the buffer that contains the sheet creation order. */
    XclImpTabIdBuffer&          GetTabIdBuffer() const;
    /** Returns the link manager. */
    XclImpLinkManager&          GetLinkManager() const;

    /** Returns the drawing object manager. */
    XclImpObjectManager&        GetObjectManager() const;
    /** Returns the conditional formattings manager. */
    XclImpCondFormatManager&    GetCondFormatManager() const;
    /** Returns the web query buffer. */
    XclImpWebQueryBuffer&       GetWebQueryBuffer() const;

    /** Returns the formula converter. */
    ExcelToSc&                  GetFmlaConverter() const;

    /** Returns the Calc add-in function name for an Excel function name. */
    String                      GetScAddInName( const String& rXclName ) const;

    /** Checks if the passed cell address is a valid Calc cell position.
        @descr  See XclRoot::CheckCellAddress for details. */
    bool                        CheckCellAddress( const ScAddress& rPos ) const;
    /** Checks and eventually crops the cell range to valid Calc dimensions.
        @descr  See XclRoot::CheckCellRange for details. */
    bool                        CheckCellRange( ScRange& rRange ) const;
    /** Checks and eventually crops the cell ranges to valid Calc dimensions.
        @descr  See XclRoot::CheckCellRangeList for details. */
    void                        CheckCellRangeList( ScRangeList& rRanges ) const;

protected:
    explicit                    XclImpRoot( XclImpRootData& rImpRootData );

    /** Sets the BIFF version and BOF/EOF block type. */
    void                        SetBiff( XclBiff eBiff );
};

// ============================================================================

#endif

<commit_msg>INTEGRATION: CWS calc17 (1.5.2); FILE MERGED 2003/10/02 13:06:15 dr 1.5.2.3: #101529# new NAME import, update of imp/exp link managers 2003/09/18 06:58:09 dr 1.5.2.2: RESYNC: (1.5-1.6); FILE MERGED 2003/08/18 14:14:36 dr 1.5.2.1: #111865# page settings reimplemented<commit_after>/*************************************************************************
 *
 *  $RCSfile: xiroot.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2003-11-05 13:42:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// ============================================================================

#ifndef SC_XIROOT_HXX
#define SC_XIROOT_HXX

#ifndef SC_XLROOT_HXX
#include "xlroot.hxx"
#endif

// Global data ================================================================

class XclImpSst;
class XclImpPalette;
class XclImpFontBuffer;
class XclImpNumFmtBuffer;
class XclImpXFBuffer;
class XclImpXFIndexBuffer;
class XclImpPageSettings;
class _ScRangeListTabs;
class XclImpTabIdBuffer;
class XclImpNameBuffer;
class XclImpLinkManager;
class XclImpObjectManager;
class XclImpCondFormatManager;
class XclImpAutoFilterBuffer;
class XclImpWebQueryBuffer;

/** Stores global buffers and data needed for Excel import filter. */
struct XclImpRootData : public XclRootData
{
    typedef ::std::auto_ptr< XclImpSst >                XclImpSstPtr;
    typedef ::std::auto_ptr< XclImpPalette >            XclImpPalettePtr;
    typedef ::std::auto_ptr< XclImpFontBuffer >         XclImpFontBufferPtr;
    typedef ::std::auto_ptr< XclImpNumFmtBuffer >       XclImpNumFmtBufferPtr;
    typedef ::std::auto_ptr< XclImpXFBuffer >           XclImpXFBufferPtr;
    typedef ::std::auto_ptr< XclImpXFIndexBuffer >      XclImpXFIndexBufferPtr;
    typedef ::std::auto_ptr< XclImpPageSettings >       XclImpPageSettingsPtr;
    typedef ::std::auto_ptr< XclImpTabIdBuffer >        XclImpTabIdBufferPtr;
    typedef ::std::auto_ptr< XclImpNameBuffer >         XclImpNameBufferPtr;
    typedef ::std::auto_ptr< XclImpLinkManager >        XclImpLinkManagerPtr;
    typedef ::std::auto_ptr< XclImpObjectManager >      XclImpObjectManagerPtr;
    typedef ::std::auto_ptr< XclImpCondFormatManager >  XclImpCondFormatManagerPtr;
    typedef ::std::auto_ptr< XclImpWebQueryBuffer >     XclImpWebQueryBufferPtr;

    XclImpSstPtr                mpSst;              /// The shared string table.

    XclImpPalettePtr            mpPalette;          /// The color buffer.
    XclImpFontBufferPtr         mpFontBuffer;       /// All fonts in the file.
    XclImpNumFmtBufferPtr       mpNumFmtBuffer;     /// All number formats in the file.
    XclImpXFBufferPtr           mpXFBuffer;         /// All XF record data in the file.
    XclImpXFIndexBufferPtr      mpXFIndexBuffer;    /// Buffer of XF indexes in a sheet.

    XclImpPageSettingsPtr       mpPageSettings;     /// Page settings for current sheet.

    XclImpTabIdBufferPtr        mpTabIdBuffer;      /// Sheet creation order list.
    XclImpNameBufferPtr         mpNameBuffer;       /// Internal defined names.
    XclImpLinkManagerPtr        mpLinkManager;      /// Manager for internal/external links.

    XclImpObjectManagerPtr      mpObjManager;       /// All drawing objects.
    XclImpCondFormatManagerPtr  mpCondFmtManager;   /// Conditional formattings.
    XclImpWebQueryBufferPtr     mpWebQBuffer;       /// All web queries.

    explicit                    XclImpRootData(
                                    XclBiff eBiff,
                                    ScDocument& rDocument,
                                    const String& rDocUrl,
                                    CharSet eCharSet );
    virtual                     ~XclImpRootData();
};

// ----------------------------------------------------------------------------

class ExcelToSc;

/** Access to global data from other classes. */
class XclImpRoot : public XclRoot
{
private:
    mutable XclImpRootData&     mrImpData;      /// Reference to the global import data struct.

public:
    /** Returns this root instance - for code readability in derived classes. */
    inline const XclImpRoot&    GetRoot() const { return *this; }

    /** Returns the shared string table. */
    XclImpSst&                  GetSst() const;

    /** Returns the color buffer. */
    XclImpPalette&              GetPalette() const;
    /** Returns the font buffer. */
    XclImpFontBuffer&           GetFontBuffer() const;
    /** Returns the number format buffer. */
    XclImpNumFmtBuffer&         GetNumFmtBuffer() const;
    /** Returns the cell formatting attributes buffer. */
    XclImpXFBuffer&             GetXFBuffer() const;
    /** Returns the buffer of XF indexes for a sheet. */
    XclImpXFIndexBuffer&        GetXFIndexBuffer() const;

    /** Returns the page settings of the current sheet. */
    XclImpPageSettings&         GetPageSettings() const;
    /** Returns the buffer that contains all print areas in the document. */
    _ScRangeListTabs&           GetPrintAreaBuffer() const;
    /** Returns the buffer that contains all print areas in the document. */
    _ScRangeListTabs&           GetTitleAreaBuffer() const;

    /** Returns the buffer that contains the sheet creation order. */
    XclImpTabIdBuffer&          GetTabIdBuffer() const;
    /** Returns the buffer that contains internal defined names. */
    XclImpNameBuffer&           GetNameBuffer() const;
    /** Returns the link manager. */
    XclImpLinkManager&          GetLinkManager() const;

    /** Returns the drawing object manager. */
    XclImpObjectManager&        GetObjectManager() const;
    /** Returns the conditional formattings manager. */
    XclImpCondFormatManager&    GetCondFormatManager() const;
    /** Returns the filter manager. */
    XclImpAutoFilterBuffer&     GetFilterManager() const;
    /** Returns the web query buffer. */
    XclImpWebQueryBuffer&       GetWebQueryBuffer() const;

    /** Returns the formula converter. */
    ExcelToSc&                  GetFmlaConverter() const;

    /** Returns the Calc add-in function name for an Excel function name. */
    String                      GetScAddInName( const String& rXclName ) const;

    /** Checks if the passed cell address is a valid Calc cell position.
        @descr  See XclRoot::CheckCellAddress for details. */
    bool                        CheckCellAddress( const ScAddress& rPos ) const;
    /** Checks and eventually crops the cell range to valid Calc dimensions.
        @descr  See XclRoot::CheckCellRange for details. */
    bool                        CheckCellRange( ScRange& rRange ) const;
    /** Checks and eventually crops the cell ranges to valid Calc dimensions.
        @descr  See XclRoot::CheckCellRangeList for details. */
    void                        CheckCellRangeList( ScRangeList& rRanges ) const;

protected:
    explicit                    XclImpRoot( XclImpRootData& rImpRootData );

    /** Sets the BIFF version and BOF/EOF block type. */
    void                        SetBiff( XclBiff eBiff );
};

// ============================================================================

#endif

<|endoftext|>


<commit_before>
#include <Match.h>

#include <Estimator/estimator.h>
#include <iostream>

#include <FeatureMatcher/featurematcher.h>

#include <opencv2/highgui.hpp>

namespace vrlt
{
    MatchThread::MatchThread( FeatureMatcher *_fm, Node *_node1, Node *_node2, double _threshold, bool _upright, bool _deleteFM )
    : fm( _fm ), node1( _node1 ), node2( _node2 ), threshold( _threshold ), upright( _upright ), deleteFM( _deleteFM )
    {

    }

    MatchThread::~MatchThread()
    {
		if ( deleteFM ) delete fm;
    }

    void MatchThread::run()
    {
        std::vector<Feature*> fm2_features;
        addFeatures( node2, false, fm2_features );

        if ( fm->features.empty() || fm2_features.empty() ) {
            return;
        }

//        findMatches( (*fm), fm2_features, matches );
        findUniqueMatches( (*fm), fm2_features, 0.8, matches );

        for ( int i = 0; i < matches.size(); i++ ) {
            PointPair point_pair;

            Feature *feature1 = matches[i]->feature1;
            Feature *feature2 = matches[i]->feature2;

            Eigen::Vector3d pt1 = feature1->unproject();
            Eigen::Vector3d pt2 = feature2->unproject();

            pt1 = feature1->camera->node->globalPose().inverse() * pt1;
            pt2 = feature2->camera->node->globalPose().inverse() * pt2;

            point_pair.first = pt1;
            point_pair.second = pt2;

            point_pairs.push_back( point_pair );
        }

        PROSAC prosac;
        prosac.num_trials = 100;
        prosac.inlier_threshold = threshold;
        prosac.min_num_inliers = point_pairs.size();

        if ( upright )
        {
            estimator = new UprightEssential;
        }
        else
        {
            estimator = new FivePointEssential;
        }

        ninliers = prosac.compute( point_pairs.begin(), point_pairs.end(), (*estimator), inliers );
    }

    void MatchThread::finish( Reconstruction &r )
    {
        std::cout << node1->name << "\t" << node2->name << "\t" << ninliers << " / " << point_pairs.size() << "\n";

        if ( ninliers < 50 ) {
            for ( int i = 0; i < inliers.size(); i++ ) {
                delete matches[i];
            }
            return;
        }

        PointPairList inlier_point_pairs;

        for ( int i = 0; i < inliers.size(); i++ ) {
            if ( inliers[i] == false ) {
                delete matches[i];
                continue;
            }
            inlier_point_pairs.push_back( point_pairs[i] );
            char name[256];
            sprintf( name, "match.%s.%s.%d", node1->name.c_str(), node2->name.c_str(), i );
            matches[i]->name = std::string(name);
            r.matches[ matches[i]->name ] = matches[i];
        }

        Pair *nodepair = new Pair;
        char name[256];
        sprintf( name, "pair.%s.%s", node1->name.c_str(), node2->name.c_str() );
        nodepair->name = name;
        nodepair->node1 = node1;
        nodepair->node2 = node2;
        if ( upright )
        {
            nodepair->pose = ((UprightEssential*)estimator)->getPose( inlier_point_pairs.begin(), inlier_point_pairs.end() );
        }
        else
        {
            nodepair->pose = ((FivePointEssential*)estimator)->getPose( inlier_point_pairs.begin(), inlier_point_pairs.end() );
        }

        nodepair->nmatches = (int)inlier_point_pairs.size();

        r.pairs[nodepair->name] = nodepair;

        delete estimator;
    }
}
<commit_msg>Fixed typo in match.cpp<commit_after>
#include <match.h>

#include <Estimator/estimator.h>
#include <iostream>

#include <FeatureMatcher/featurematcher.h>

#include <opencv2/highgui.hpp>

namespace vrlt
{
    MatchThread::MatchThread( FeatureMatcher *_fm, Node *_node1, Node *_node2, double _threshold, bool _upright, bool _deleteFM )
    : fm( _fm ), node1( _node1 ), node2( _node2 ), threshold( _threshold ), upright( _upright ), deleteFM( _deleteFM )
    {

    }

    MatchThread::~MatchThread()
    {
		if ( deleteFM ) delete fm;
    }

    void MatchThread::run()
    {
        std::vector<Feature*> fm2_features;
        addFeatures( node2, false, fm2_features );

        if ( fm->features.empty() || fm2_features.empty() ) {
            return;
        }

//        findMatches( (*fm), fm2_features, matches );
        findUniqueMatches( (*fm), fm2_features, 0.8, matches );

        for ( int i = 0; i < matches.size(); i++ ) {
            PointPair point_pair;

            Feature *feature1 = matches[i]->feature1;
            Feature *feature2 = matches[i]->feature2;

            Eigen::Vector3d pt1 = feature1->unproject();
            Eigen::Vector3d pt2 = feature2->unproject();

            pt1 = feature1->camera->node->globalPose().inverse() * pt1;
            pt2 = feature2->camera->node->globalPose().inverse() * pt2;

            point_pair.first = pt1;
            point_pair.second = pt2;

            point_pairs.push_back( point_pair );
        }

        PROSAC prosac;
        prosac.num_trials = 100;
        prosac.inlier_threshold = threshold;
        prosac.min_num_inliers = point_pairs.size();

        if ( upright )
        {
            estimator = new UprightEssential;
        }
        else
        {
            estimator = new FivePointEssential;
        }

        ninliers = prosac.compute( point_pairs.begin(), point_pairs.end(), (*estimator), inliers );
    }

    void MatchThread::finish( Reconstruction &r )
    {
        std::cout << node1->name << "\t" << node2->name << "\t" << ninliers << " / " << point_pairs.size() << "\n";

        if ( ninliers < 50 ) {
            for ( int i = 0; i < inliers.size(); i++ ) {
                delete matches[i];
            }
            return;
        }

        PointPairList inlier_point_pairs;

        for ( int i = 0; i < inliers.size(); i++ ) {
            if ( inliers[i] == false ) {
                delete matches[i];
                continue;
            }
            inlier_point_pairs.push_back( point_pairs[i] );
            char name[256];
            sprintf( name, "match.%s.%s.%d", node1->name.c_str(), node2->name.c_str(), i );
            matches[i]->name = std::string(name);
            r.matches[ matches[i]->name ] = matches[i];
        }

        Pair *nodepair = new Pair;
        char name[256];
        sprintf( name, "pair.%s.%s", node1->name.c_str(), node2->name.c_str() );
        nodepair->name = name;
        nodepair->node1 = node1;
        nodepair->node2 = node2;
        if ( upright )
        {
            nodepair->pose = ((UprightEssential*)estimator)->getPose( inlier_point_pairs.begin(), inlier_point_pairs.end() );
        }
        else
        {
            nodepair->pose = ((FivePointEssential*)estimator)->getPose( inlier_point_pairs.begin(), inlier_point_pairs.end() );
        }

        nodepair->nmatches = (int)inlier_point_pairs.size();

        r.pairs[nodepair->name] = nodepair;

        delete estimator;
    }
}
<|endoftext|>


<commit_before>/*
* Copyright (c) 2008, AMT – The Association For Manufacturing Technology (“AMT”)
* 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.
*     * Neither the name of the AMT nor the
*       names of its contributors may be used to endorse or promote products
*       derived from this software without specific prior written permission.
*
* DISCLAIMER OF WARRANTY. ALL MTCONNECT MATERIALS AND SPECIFICATIONS PROVIDED
* BY AMT, MTCONNECT OR ANY PARTICIPANT TO YOU OR ANY PARTY ARE PROVIDED "AS IS"
* AND WITHOUT ANY WARRANTY OF ANY KIND. AMT, MTCONNECT, AND EACH OF THEIR
* RESPECTIVE MEMBERS, OFFICERS, DIRECTORS, AFFILIATES, SPONSORS, AND AGENTS
* (COLLECTIVELY, THE "AMT PARTIES") AND PARTICIPANTS MAKE NO REPRESENTATION OR
* WARRANTY OF ANY KIND WHATSOEVER RELATING TO THESE MATERIALS, INCLUDING, WITHOUT
* LIMITATION, ANY EXPRESS OR IMPLIED WARRANTY OF NONINFRINGEMENT,
* MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

* LIMITATION OF LIABILITY. IN NO EVENT SHALL AMT, MTCONNECT, ANY OTHER AMT
* PARTY, OR ANY PARTICIPANT BE LIABLE FOR THE COST OF PROCURING SUBSTITUTE GOODS
* OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA OR ANY INCIDENTAL,
* CONSEQUENTIAL, INDIRECT, SPECIAL OR PUNITIVE DAMAGES OR OTHER DIRECT DAMAGES,
* WHETHER UNDER CONTRACT, TORT, WARRANTY OR OTHERWISE, ARISING IN ANY WAY OUT OF
* THIS AGREEMENT, USE OR INABILITY TO USE MTCONNECT MATERIALS, WHETHER OR NOT
* SUCH PARTY HAD ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
*/

#include "component_event.hpp"

using namespace std;

/* ComponentEvent public methods */
ComponentEvent::ComponentEvent(
    DataItem& dataItem,
    unsigned int sequence,
    const string& time,
    const string& value
  )
{
  mDataItem = &dataItem;
  mSequence = sequence;
  mTime = time;

  fValue = 0.0f;
  convertValue(value);
}

ComponentEvent::ComponentEvent(ComponentEvent& ce)
{
  std::map<string, string> attributes = ce.getAttributes();

  mDataItem = ce.getDataItem();

  mTime = attributes["timestamp"];
  mSequence = atoi(attributes["sequence"].c_str());

  mAlarmData = attributes["code"] + "|" + attributes["nativeCode"] + "|" +
    attributes["severity"] + "|" + attributes["state"];

  fValue = ce.getFValue();
  sValue = ce.getSValue();
}

ComponentEvent::~ComponentEvent()
{
}

std::map<string, string> ComponentEvent::getAttributes()
{
  std::map<string, string> attributes;

  attributes["dataItemId"] = mDataItem->getId();
  attributes["timestamp"] = mTime;
  if (!mDataItem->getSubType().empty())
  {
    attributes["subType"] = mDataItem->getSubType();
  }

  attributes["name"] = mDataItem->getName();
  attributes["sequence"] = intToString(mSequence);

  if (getDataItem()->getType() == "ALARM")
  {
    // Format to parse: CODE|NATIVECODE|SEVERITY|STATE
    istringstream toParse(mAlarmData);
    string token;

    getline(toParse, token, '|');
    attributes["code"] = token;

    getline(toParse, token, '|');
    attributes["nativeCode"] = token;

    getline(toParse, token, '|');
    attributes["severity"] = token;

    getline(toParse, token, '|');
    attributes["state"] = token;
  }

  return attributes;
}

/* ComponentEvent protected methods */
void ComponentEvent::convertValue(const string& value)
{
  // Check if the type is an alarm or if it doesn't have units
  if (mDataItem->getType() == "ALARM")
  {
    string::size_type lastPipe = value.rfind('|');

    // Alarm data = CODE|NATIVECODE|SEVERITY|STATE
    mAlarmData = value.substr(0, lastPipe);

    // sValue = DESCRIPTION
    sValue = value.substr(lastPipe+1);
  }
  else if (mDataItem->conversionRequired())
  {
    fValue = mDataItem->convertValue(value);
  }
  else
  {
    sValue = value;
  }
}

<commit_msg>Removed unessary parsing from copy constructure.<commit_after>/*
* Copyright (c) 2008, AMT – The Association For Manufacturing Technology (“AMT”)
* 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.
*     * Neither the name of the AMT nor the
*       names of its contributors may be used to endorse or promote products
*       derived from this software without specific prior written permission.
*
* DISCLAIMER OF WARRANTY. ALL MTCONNECT MATERIALS AND SPECIFICATIONS PROVIDED
* BY AMT, MTCONNECT OR ANY PARTICIPANT TO YOU OR ANY PARTY ARE PROVIDED "AS IS"
* AND WITHOUT ANY WARRANTY OF ANY KIND. AMT, MTCONNECT, AND EACH OF THEIR
* RESPECTIVE MEMBERS, OFFICERS, DIRECTORS, AFFILIATES, SPONSORS, AND AGENTS
* (COLLECTIVELY, THE "AMT PARTIES") AND PARTICIPANTS MAKE NO REPRESENTATION OR
* WARRANTY OF ANY KIND WHATSOEVER RELATING TO THESE MATERIALS, INCLUDING, WITHOUT
* LIMITATION, ANY EXPRESS OR IMPLIED WARRANTY OF NONINFRINGEMENT,
* MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

* LIMITATION OF LIABILITY. IN NO EVENT SHALL AMT, MTCONNECT, ANY OTHER AMT
* PARTY, OR ANY PARTICIPANT BE LIABLE FOR THE COST OF PROCURING SUBSTITUTE GOODS
* OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA OR ANY INCIDENTAL,
* CONSEQUENTIAL, INDIRECT, SPECIAL OR PUNITIVE DAMAGES OR OTHER DIRECT DAMAGES,
* WHETHER UNDER CONTRACT, TORT, WARRANTY OR OTHERWISE, ARISING IN ANY WAY OUT OF
* THIS AGREEMENT, USE OR INABILITY TO USE MTCONNECT MATERIALS, WHETHER OR NOT
* SUCH PARTY HAD ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
*/

#include "component_event.hpp"

using namespace std;

/* ComponentEvent public methods */
ComponentEvent::ComponentEvent(
    DataItem& dataItem,
    unsigned int sequence,
    const string& time,
    const string& value
  )
{
  mDataItem = &dataItem;
  mSequence = sequence;
  mTime = time;

  fValue = 0.0f;
  convertValue(value);
}

ComponentEvent::ComponentEvent(ComponentEvent& ce)
{
  mDataItem = ce.getDataItem();
  mTime = ce.mTime;
  mSequence = ce.mSequence;
  mAlarmData = ce.mAlarmData;
  fValue = ce.fValue;
  sValue = ce.sValue;
}

ComponentEvent::~ComponentEvent()
{
}

std::map<string, string> ComponentEvent::getAttributes()
{
  std::map<string, string> attributes;

  attributes["dataItemId"] = mDataItem->getId();
  attributes["timestamp"] = mTime;
  if (!mDataItem->getSubType().empty())
  {
    attributes["subType"] = mDataItem->getSubType();
  }

  attributes["name"] = mDataItem->getName();
  attributes["sequence"] = intToString(mSequence);

  if (getDataItem()->getType() == "ALARM")
  {
    // Format to parse: CODE|NATIVECODE|SEVERITY|STATE
    istringstream toParse(mAlarmData);
    string token;

    getline(toParse, token, '|');
    attributes["code"] = token;

    getline(toParse, token, '|');
    attributes["nativeCode"] = token;

    getline(toParse, token, '|');
    attributes["severity"] = token;

    getline(toParse, token, '|');
    attributes["state"] = token;
  }

  return attributes;
}

/* ComponentEvent protected methods */
void ComponentEvent::convertValue(const string& value)
{
  // Check if the type is an alarm or if it doesn't have units
  if (mDataItem->getType() == "ALARM")
  {
    string::size_type lastPipe = value.rfind('|');

    // Alarm data = CODE|NATIVECODE|SEVERITY|STATE
    mAlarmData = value.substr(0, lastPipe);

    // sValue = DESCRIPTION
    sValue = value.substr(lastPipe+1);
  }
  else if (mDataItem->conversionRequired())
  {
    fValue = mDataItem->convertValue(value);
  }
  else
  {
    sValue = value;
  }
}

<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_toolkit.hxx"

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

#include <toolkit/helper/servicenames.hxx>

const sal_Char __FAR_DATA szServiceName_Toolkit[] = "stardiv.vcl.VclToolkit", szServiceName2_Toolkit[] = "com.sun.star.awt.Toolkit";
const sal_Char __FAR_DATA szServiceName_PopupMenu[] = "stardiv.vcl.PopupMenu", szServiceName2_PopupMenu[] = "com.sun.star.awt.PopupMenu";
const sal_Char __FAR_DATA szServiceName_MenuBar[] = "stardiv.vcl.MenuBar", szServiceName2_MenuBar[] = "com.sun.star.awt.MenuBar";
const sal_Char __FAR_DATA szServiceName_Pointer[] = "stardiv.vcl.Pointer", szServiceName2_Pointer[] = "com.sun.star.awt.Pointer";
const sal_Char __FAR_DATA szServiceName_UnoControlContainer[] = "stardiv.vcl.control.ControlContainer", szServiceName2_UnoControlContainer[] = "com.sun.star.awt.UnoControlContainer";
const sal_Char __FAR_DATA szServiceName_UnoControlContainerModel[] = "stardiv.vcl.controlmodel.ControlContainer", szServiceName2_UnoControlContainerModel[] = "com.sun.star.awt.UnoControlContainerModel";
const sal_Char __FAR_DATA szServiceName_TabController[] = "stardiv.vcl.control.TabController", szServiceName2_TabController[] = "com.sun.star.awt.TabController";
const sal_Char __FAR_DATA szServiceName_TabControllerModel[] = "stardiv.vcl.controlmodel.TabController", szServiceName2_TabControllerModel[] = "com.sun.star.awt.TabControllerModel";
const sal_Char __FAR_DATA szServiceName_UnoControlDialog[] = "stardiv.vcl.control.Dialog", szServiceName2_UnoControlDialog[] = "com.sun.star.awt.UnoControlDialog";
const sal_Char __FAR_DATA szServiceName_UnoControlDialogModel[] = "stardiv.vcl.controlmodel.Dialog", szServiceName2_UnoControlDialogModel[] = "com.sun.star.awt.UnoControlDialogModel";
const sal_Char __FAR_DATA szServiceName_UnoControlEdit[] = "stardiv.vcl.control.Edit", szServiceName2_UnoControlEdit[] = "com.sun.star.awt.UnoControlEdit";
const sal_Char __FAR_DATA szServiceName_UnoControlEditModel[] = "stardiv.vcl.controlmodel.Edit", szServiceName2_UnoControlEditModel[] = "com.sun.star.awt.UnoControlEditModel";
const sal_Char __FAR_DATA szServiceName_UnoControlFileControl[] = "stardiv.vcl.control.FileControl", szServiceName2_UnoControlFileControl[] = "com.sun.star.awt.UnoControlFileControl";
const sal_Char __FAR_DATA szServiceName_UnoControlFileControlModel[] = "stardiv.vcl.controlmodel.FileControl", szServiceName2_UnoControlFileControlModel[] = "com.sun.star.awt.UnoControlFileControlModel";
const sal_Char __FAR_DATA szServiceName_UnoControlButton[] = "stardiv.vcl.control.Button", szServiceName2_UnoControlButton[] = "com.sun.star.awt.UnoControlButton";
const sal_Char __FAR_DATA szServiceName_UnoControlButtonModel[] = "stardiv.vcl.controlmodel.Button", szServiceName2_UnoControlButtonModel[] = "com.sun.star.awt.UnoControlButtonModel";
const sal_Char __FAR_DATA szServiceName_UnoControlImageButton[] = "stardiv.vcl.control.ImageButton", szServiceName2_UnoControlImageButton[] = "com.sun.star.awt.UnoControlImageButton";
const sal_Char __FAR_DATA szServiceName_UnoControlImageButtonModel[] = "stardiv.vcl.controlmodel.ImageButton", szServiceName2_UnoControlImageButtonModel[] = "com.sun.star.awt.UnoControlImageButtonModel";
const sal_Char __FAR_DATA szServiceName_UnoControlImageControl[] = "stardiv.vcl.control.ImageControl", szServiceName2_UnoControlImageControl[] = "com.sun.star.awt.UnoControlImageControl";
const sal_Char __FAR_DATA szServiceName_UnoControlImageControlModel[] = "stardiv.vcl.controlmodel.ImageControl", szServiceName2_UnoControlImageControlModel[] = "com.sun.star.awt.UnoControlImageControlModel";
const sal_Char __FAR_DATA szServiceName_UnoControlRadioButton[] = "stardiv.vcl.control.RadioButton", szServiceName2_UnoControlRadioButton[] = "com.sun.star.awt.UnoControlRadioButton";
const sal_Char __FAR_DATA szServiceName_UnoControlRadioButtonModel[] = "stardiv.vcl.controlmodel.RadioButton", szServiceName2_UnoControlRadioButtonModel[] = "com.sun.star.awt.UnoControlRadioButtonModel";
const sal_Char __FAR_DATA szServiceName_UnoControlCheckBox[] = "stardiv.vcl.control.CheckBox", szServiceName2_UnoControlCheckBox[] = "com.sun.star.awt.UnoControlCheckBox";
const sal_Char __FAR_DATA szServiceName_UnoControlCheckBoxModel[] = "stardiv.vcl.controlmodel.CheckBox", szServiceName2_UnoControlCheckBoxModel[] = "com.sun.star.awt.UnoControlCheckBoxModel";
const sal_Char __FAR_DATA szServiceName_UnoControlListBox[] = "stardiv.vcl.control.ListBox", szServiceName2_UnoControlListBox[] = "com.sun.star.awt.UnoControlListBox";
const sal_Char __FAR_DATA szServiceName_UnoControlListBoxModel[] = "stardiv.vcl.controlmodel.ListBox", szServiceName2_UnoControlListBoxModel[] = "com.sun.star.awt.UnoControlListBoxModel";
const sal_Char __FAR_DATA szServiceName_UnoControlComboBox[] = "stardiv.vcl.control.ComboBox", szServiceName2_UnoControlComboBox[] = "com.sun.star.awt.UnoControlComboBox";
const sal_Char __FAR_DATA szServiceName_UnoControlComboBoxModel[] = "stardiv.vcl.controlmodel.ComboBox", szServiceName2_UnoControlComboBoxModel[] = "com.sun.star.awt.UnoControlComboBoxModel";
const sal_Char __FAR_DATA szServiceName_UnoControlFixedText[] = "stardiv.vcl.control.FixedText", szServiceName2_UnoControlFixedText[] = "com.sun.star.awt.UnoControlFixedText";
const sal_Char __FAR_DATA szServiceName_UnoControlFixedTextModel[] = "stardiv.vcl.controlmodel.FixedText", szServiceName2_UnoControlFixedTextModel[] = "com.sun.star.awt.UnoControlFixedTextModel";
const sal_Char __FAR_DATA szServiceName_UnoControlGroupBox[] = "stardiv.vcl.control.GroupBox", szServiceName2_UnoControlGroupBox[] = "com.sun.star.awt.UnoControlGroupBox";
const sal_Char __FAR_DATA szServiceName_UnoControlGroupBoxModel[] = "stardiv.vcl.controlmodel.GroupBox", szServiceName2_UnoControlGroupBoxModel[] = "com.sun.star.awt.UnoControlGroupBoxModel";
const sal_Char __FAR_DATA szServiceName_UnoControlDateField[] = "stardiv.vcl.control.DateField", szServiceName2_UnoControlDateField[] = "com.sun.star.awt.UnoControlDateField";
const sal_Char __FAR_DATA szServiceName_UnoControlDateFieldModel[] = "stardiv.vcl.controlmodel.DateField", szServiceName2_UnoControlDateFieldModel[] = "com.sun.star.awt.UnoControlDateFieldModel";
const sal_Char __FAR_DATA szServiceName_UnoControlTimeField[] = "stardiv.vcl.control.TimeField", szServiceName2_UnoControlTimeField[] = "com.sun.star.awt.UnoControlTimeField";
const sal_Char __FAR_DATA szServiceName_UnoControlTimeFieldModel[] = "stardiv.vcl.controlmodel.TimeField", szServiceName2_UnoControlTimeFieldModel[] = "com.sun.star.awt.UnoControlTimeFieldModel";
const sal_Char __FAR_DATA szServiceName_UnoControlNumericField[] = "stardiv.vcl.control.NumericField", szServiceName2_UnoControlNumericField[] = "com.sun.star.awt.UnoControlNumericField";
const sal_Char __FAR_DATA szServiceName_UnoControlNumericFieldModel[] = "stardiv.vcl.controlmodel.NumericField", szServiceName2_UnoControlNumericFieldModel[] = "com.sun.star.awt.UnoControlNumericFieldModel";
const sal_Char __FAR_DATA szServiceName_UnoControlCurrencyField[] = "stardiv.vcl.control.CurrencyField", szServiceName2_UnoControlCurrencyField[] = "com.sun.star.awt.UnoControlCurrencyField";
const sal_Char __FAR_DATA szServiceName_UnoControlCurrencyFieldModel[] = "stardiv.vcl.controlmodel.CurrencyField", szServiceName2_UnoControlCurrencyFieldModel[] = "com.sun.star.awt.UnoControlCurrencyFieldModel";
const sal_Char __FAR_DATA szServiceName_UnoControlPatternField[] = "stardiv.vcl.control.PatternField", szServiceName2_UnoControlPatternField[] = "com.sun.star.awt.UnoControlPatternField";
const sal_Char __FAR_DATA szServiceName_UnoControlPatternFieldModel[] = "stardiv.vcl.controlmodel.PatternField", szServiceName2_UnoControlPatternFieldModel[] = "com.sun.star.awt.UnoControlPatternFieldModel";
const sal_Char __FAR_DATA szServiceName_UnoControlFormattedField[] = "stardiv.vcl.control.FormattedField", szServiceName2_UnoControlFormattedField[] = "com.sun.star.awt.UnoControlFormattedField";
const sal_Char __FAR_DATA szServiceName_UnoControlFormattedFieldModel[] = "stardiv.vcl.controlmodel.FormattedField", szServiceName2_UnoControlFormattedFieldModel[] = "com.sun.star.awt.UnoControlFormattedFieldModel";
const sal_Char __FAR_DATA szServiceName_MVCIntrospection[] = "stardiv.vcl.MVCIntrospection", szServiceName2_MVCIntrospection[] = "com.sun.star.awt.MVCIntrospection";
const sal_Char __FAR_DATA szServiceName_ImageProducer[] = "stardiv.vcl.ImageProducer", szServiceName2_ImageProducer[] = "com.sun.star.awt.ImageProducer";
const sal_Char __FAR_DATA szServiceName_PrinterServer[] = "stardiv.vcl.PrinterServer", szServiceName2_PrinterServer[] = "com.sun.star.awt.PrinterServer";
const sal_Char __FAR_DATA szServiceName_UnoControlProgressBar[] = "stardiv.vcl.control.ProgressBar", szServiceName2_UnoControlProgressBar[] = "com.sun.star.awt.UnoControlProgressBar";
const sal_Char __FAR_DATA szServiceName_UnoControlProgressBarModel[] = "stardiv.vcl.controlmodel.ProgressBar", szServiceName2_UnoControlProgressBarModel[] = "com.sun.star.awt.UnoControlProgressBarModel";
const sal_Char __FAR_DATA szServiceName_UnoControlScrollBar[] = "stardiv.vcl.control.ScrollBar", szServiceName2_UnoControlScrollBar[] = "com.sun.star.awt.UnoControlScrollBar";
const sal_Char __FAR_DATA szServiceName_UnoControlScrollBarModel[] = "stardiv.vcl.controlmodel.ScrollBar", szServiceName2_UnoControlScrollBarModel[] = "com.sun.star.awt.UnoControlScrollBarModel";
const sal_Char __FAR_DATA szServiceName_UnoControlFixedLine[] = "stardiv.vcl.control.FixedLine", szServiceName2_UnoControlFixedLine[] = "com.sun.star.awt.UnoControlFixedLine";
const sal_Char __FAR_DATA szServiceName_UnoControlFixedLineModel[] = "stardiv.vcl.controlmodel.FixedLine", szServiceName2_UnoControlFixedLineModel[] = "com.sun.star.awt.UnoControlFixedLineModel";
const sal_Char __FAR_DATA szServiceName_UnoControlRoadmap[] = "stardiv.vcl.control.Roadmap", szServiceName2_UnoControlRoadmap[] = "com.sun.star.awt.UnoControlRoadmap";
const sal_Char __FAR_DATA szServiceName_UnoControlRoadmapModel[] = "stardiv.vcl.controlmodel.Roadmap", szServiceName2_UnoControlRoadmapModel[] = "com.sun.star.awt.UnoControlRoadmapModel";
const sal_Char __FAR_DATA szServiceName_UnoSpinButtonControl[] = "com.sun.star.awt.UnoControlSpinButton";
const sal_Char __FAR_DATA szServiceName_UnoSpinButtonModel[] = "com.sun.star.awt.UnoControlSpinButtonModel";
const sal_Char __FAR_DATA szServiceName_UnoSimpleAnimationControlModel[] = "com.sun.star.awt.UnoSimpleAnimationControlModel";
const sal_Char __FAR_DATA szServiceName_UnoSimpleAnimationControl[] = "com.sun.star.awt.UnoSimpleAnimationControl";
const sal_Char __FAR_DATA szServiceName_UnoThrobberControlModel[] = "com.sun.star.awt.UnoThrobberControlModel";
const sal_Char __FAR_DATA szServiceName_UnoThrobberControl[] = "com.sun.star.awt.UnoThrobberControl";

<commit_msg>INTEGRATION: CWS awttree01 (1.9.8); FILE MERGED 2007/03/11 14:42:58 cl 1.9.8.4: RESYNC: (1.9-1.10); FILE MERGED 2006/12/01 06:19:33 cl 1.9.8.3: implement a tree control api 2006/10/13 13:52:42 cl 1.9.8.2: added primilary awt tree control api 2006/09/28 13:57:48 cl 1.9.8.1: added primilary awt tree control api<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: servicenames.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 12:23:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_toolkit.hxx"

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

#include <toolkit/helper/servicenames.hxx>

const sal_Char __FAR_DATA szServiceName_Toolkit[] = "stardiv.vcl.VclToolkit", szServiceName2_Toolkit[] = "com.sun.star.awt.Toolkit";
const sal_Char __FAR_DATA szServiceName_PopupMenu[] = "stardiv.vcl.PopupMenu", szServiceName2_PopupMenu[] = "com.sun.star.awt.PopupMenu";
const sal_Char __FAR_DATA szServiceName_MenuBar[] = "stardiv.vcl.MenuBar", szServiceName2_MenuBar[] = "com.sun.star.awt.MenuBar";
const sal_Char __FAR_DATA szServiceName_Pointer[] = "stardiv.vcl.Pointer", szServiceName2_Pointer[] = "com.sun.star.awt.Pointer";
const sal_Char __FAR_DATA szServiceName_UnoControlContainer[] = "stardiv.vcl.control.ControlContainer", szServiceName2_UnoControlContainer[] = "com.sun.star.awt.UnoControlContainer";
const sal_Char __FAR_DATA szServiceName_UnoControlContainerModel[] = "stardiv.vcl.controlmodel.ControlContainer", szServiceName2_UnoControlContainerModel[] = "com.sun.star.awt.UnoControlContainerModel";
const sal_Char __FAR_DATA szServiceName_TabController[] = "stardiv.vcl.control.TabController", szServiceName2_TabController[] = "com.sun.star.awt.TabController";
const sal_Char __FAR_DATA szServiceName_TabControllerModel[] = "stardiv.vcl.controlmodel.TabController", szServiceName2_TabControllerModel[] = "com.sun.star.awt.TabControllerModel";
const sal_Char __FAR_DATA szServiceName_UnoControlDialog[] = "stardiv.vcl.control.Dialog", szServiceName2_UnoControlDialog[] = "com.sun.star.awt.UnoControlDialog";
const sal_Char __FAR_DATA szServiceName_UnoControlDialogModel[] = "stardiv.vcl.controlmodel.Dialog", szServiceName2_UnoControlDialogModel[] = "com.sun.star.awt.UnoControlDialogModel";
const sal_Char __FAR_DATA szServiceName_UnoControlEdit[] = "stardiv.vcl.control.Edit", szServiceName2_UnoControlEdit[] = "com.sun.star.awt.UnoControlEdit";
const sal_Char __FAR_DATA szServiceName_UnoControlEditModel[] = "stardiv.vcl.controlmodel.Edit", szServiceName2_UnoControlEditModel[] = "com.sun.star.awt.UnoControlEditModel";
const sal_Char __FAR_DATA szServiceName_UnoControlFileControl[] = "stardiv.vcl.control.FileControl", szServiceName2_UnoControlFileControl[] = "com.sun.star.awt.UnoControlFileControl";
const sal_Char __FAR_DATA szServiceName_UnoControlFileControlModel[] = "stardiv.vcl.controlmodel.FileControl", szServiceName2_UnoControlFileControlModel[] = "com.sun.star.awt.UnoControlFileControlModel";
const sal_Char __FAR_DATA szServiceName_UnoControlButton[] = "stardiv.vcl.control.Button", szServiceName2_UnoControlButton[] = "com.sun.star.awt.UnoControlButton";
const sal_Char __FAR_DATA szServiceName_UnoControlButtonModel[] = "stardiv.vcl.controlmodel.Button", szServiceName2_UnoControlButtonModel[] = "com.sun.star.awt.UnoControlButtonModel";
const sal_Char __FAR_DATA szServiceName_UnoControlImageButton[] = "stardiv.vcl.control.ImageButton", szServiceName2_UnoControlImageButton[] = "com.sun.star.awt.UnoControlImageButton";
const sal_Char __FAR_DATA szServiceName_UnoControlImageButtonModel[] = "stardiv.vcl.controlmodel.ImageButton", szServiceName2_UnoControlImageButtonModel[] = "com.sun.star.awt.UnoControlImageButtonModel";
const sal_Char __FAR_DATA szServiceName_UnoControlImageControl[] = "stardiv.vcl.control.ImageControl", szServiceName2_UnoControlImageControl[] = "com.sun.star.awt.UnoControlImageControl";
const sal_Char __FAR_DATA szServiceName_UnoControlImageControlModel[] = "stardiv.vcl.controlmodel.ImageControl", szServiceName2_UnoControlImageControlModel[] = "com.sun.star.awt.UnoControlImageControlModel";
const sal_Char __FAR_DATA szServiceName_UnoControlRadioButton[] = "stardiv.vcl.control.RadioButton", szServiceName2_UnoControlRadioButton[] = "com.sun.star.awt.UnoControlRadioButton";
const sal_Char __FAR_DATA szServiceName_UnoControlRadioButtonModel[] = "stardiv.vcl.controlmodel.RadioButton", szServiceName2_UnoControlRadioButtonModel[] = "com.sun.star.awt.UnoControlRadioButtonModel";
const sal_Char __FAR_DATA szServiceName_UnoControlCheckBox[] = "stardiv.vcl.control.CheckBox", szServiceName2_UnoControlCheckBox[] = "com.sun.star.awt.UnoControlCheckBox";
const sal_Char __FAR_DATA szServiceName_UnoControlCheckBoxModel[] = "stardiv.vcl.controlmodel.CheckBox", szServiceName2_UnoControlCheckBoxModel[] = "com.sun.star.awt.UnoControlCheckBoxModel";
const sal_Char __FAR_DATA szServiceName_UnoControlListBox[] = "stardiv.vcl.control.ListBox", szServiceName2_UnoControlListBox[] = "com.sun.star.awt.UnoControlListBox";
const sal_Char __FAR_DATA szServiceName_UnoControlListBoxModel[] = "stardiv.vcl.controlmodel.ListBox", szServiceName2_UnoControlListBoxModel[] = "com.sun.star.awt.UnoControlListBoxModel";
const sal_Char __FAR_DATA szServiceName_UnoControlComboBox[] = "stardiv.vcl.control.ComboBox", szServiceName2_UnoControlComboBox[] = "com.sun.star.awt.UnoControlComboBox";
const sal_Char __FAR_DATA szServiceName_UnoControlComboBoxModel[] = "stardiv.vcl.controlmodel.ComboBox", szServiceName2_UnoControlComboBoxModel[] = "com.sun.star.awt.UnoControlComboBoxModel";
const sal_Char __FAR_DATA szServiceName_UnoControlFixedText[] = "stardiv.vcl.control.FixedText", szServiceName2_UnoControlFixedText[] = "com.sun.star.awt.UnoControlFixedText";
const sal_Char __FAR_DATA szServiceName_UnoControlFixedTextModel[] = "stardiv.vcl.controlmodel.FixedText", szServiceName2_UnoControlFixedTextModel[] = "com.sun.star.awt.UnoControlFixedTextModel";
const sal_Char __FAR_DATA szServiceName_UnoControlGroupBox[] = "stardiv.vcl.control.GroupBox", szServiceName2_UnoControlGroupBox[] = "com.sun.star.awt.UnoControlGroupBox";
const sal_Char __FAR_DATA szServiceName_UnoControlGroupBoxModel[] = "stardiv.vcl.controlmodel.GroupBox", szServiceName2_UnoControlGroupBoxModel[] = "com.sun.star.awt.UnoControlGroupBoxModel";
const sal_Char __FAR_DATA szServiceName_UnoControlDateField[] = "stardiv.vcl.control.DateField", szServiceName2_UnoControlDateField[] = "com.sun.star.awt.UnoControlDateField";
const sal_Char __FAR_DATA szServiceName_UnoControlDateFieldModel[] = "stardiv.vcl.controlmodel.DateField", szServiceName2_UnoControlDateFieldModel[] = "com.sun.star.awt.UnoControlDateFieldModel";
const sal_Char __FAR_DATA szServiceName_UnoControlTimeField[] = "stardiv.vcl.control.TimeField", szServiceName2_UnoControlTimeField[] = "com.sun.star.awt.UnoControlTimeField";
const sal_Char __FAR_DATA szServiceName_UnoControlTimeFieldModel[] = "stardiv.vcl.controlmodel.TimeField", szServiceName2_UnoControlTimeFieldModel[] = "com.sun.star.awt.UnoControlTimeFieldModel";
const sal_Char __FAR_DATA szServiceName_UnoControlNumericField[] = "stardiv.vcl.control.NumericField", szServiceName2_UnoControlNumericField[] = "com.sun.star.awt.UnoControlNumericField";
const sal_Char __FAR_DATA szServiceName_UnoControlNumericFieldModel[] = "stardiv.vcl.controlmodel.NumericField", szServiceName2_UnoControlNumericFieldModel[] = "com.sun.star.awt.UnoControlNumericFieldModel";
const sal_Char __FAR_DATA szServiceName_UnoControlCurrencyField[] = "stardiv.vcl.control.CurrencyField", szServiceName2_UnoControlCurrencyField[] = "com.sun.star.awt.UnoControlCurrencyField";
const sal_Char __FAR_DATA szServiceName_UnoControlCurrencyFieldModel[] = "stardiv.vcl.controlmodel.CurrencyField", szServiceName2_UnoControlCurrencyFieldModel[] = "com.sun.star.awt.UnoControlCurrencyFieldModel";
const sal_Char __FAR_DATA szServiceName_UnoControlPatternField[] = "stardiv.vcl.control.PatternField", szServiceName2_UnoControlPatternField[] = "com.sun.star.awt.UnoControlPatternField";
const sal_Char __FAR_DATA szServiceName_UnoControlPatternFieldModel[] = "stardiv.vcl.controlmodel.PatternField", szServiceName2_UnoControlPatternFieldModel[] = "com.sun.star.awt.UnoControlPatternFieldModel";
const sal_Char __FAR_DATA szServiceName_UnoControlFormattedField[] = "stardiv.vcl.control.FormattedField", szServiceName2_UnoControlFormattedField[] = "com.sun.star.awt.UnoControlFormattedField";
const sal_Char __FAR_DATA szServiceName_UnoControlFormattedFieldModel[] = "stardiv.vcl.controlmodel.FormattedField", szServiceName2_UnoControlFormattedFieldModel[] = "com.sun.star.awt.UnoControlFormattedFieldModel";
const sal_Char __FAR_DATA szServiceName_MVCIntrospection[] = "stardiv.vcl.MVCIntrospection", szServiceName2_MVCIntrospection[] = "com.sun.star.awt.MVCIntrospection";
const sal_Char __FAR_DATA szServiceName_ImageProducer[] = "stardiv.vcl.ImageProducer", szServiceName2_ImageProducer[] = "com.sun.star.awt.ImageProducer";
const sal_Char __FAR_DATA szServiceName_PrinterServer[] = "stardiv.vcl.PrinterServer", szServiceName2_PrinterServer[] = "com.sun.star.awt.PrinterServer";
const sal_Char __FAR_DATA szServiceName_UnoControlProgressBar[] = "stardiv.vcl.control.ProgressBar", szServiceName2_UnoControlProgressBar[] = "com.sun.star.awt.UnoControlProgressBar";
const sal_Char __FAR_DATA szServiceName_UnoControlProgressBarModel[] = "stardiv.vcl.controlmodel.ProgressBar", szServiceName2_UnoControlProgressBarModel[] = "com.sun.star.awt.UnoControlProgressBarModel";
const sal_Char __FAR_DATA szServiceName_UnoControlScrollBar[] = "stardiv.vcl.control.ScrollBar", szServiceName2_UnoControlScrollBar[] = "com.sun.star.awt.UnoControlScrollBar";
const sal_Char __FAR_DATA szServiceName_UnoControlScrollBarModel[] = "stardiv.vcl.controlmodel.ScrollBar", szServiceName2_UnoControlScrollBarModel[] = "com.sun.star.awt.UnoControlScrollBarModel";
const sal_Char __FAR_DATA szServiceName_UnoControlFixedLine[] = "stardiv.vcl.control.FixedLine", szServiceName2_UnoControlFixedLine[] = "com.sun.star.awt.UnoControlFixedLine";
const sal_Char __FAR_DATA szServiceName_UnoControlFixedLineModel[] = "stardiv.vcl.controlmodel.FixedLine", szServiceName2_UnoControlFixedLineModel[] = "com.sun.star.awt.UnoControlFixedLineModel";
const sal_Char __FAR_DATA szServiceName_UnoControlRoadmap[] = "stardiv.vcl.control.Roadmap", szServiceName2_UnoControlRoadmap[] = "com.sun.star.awt.UnoControlRoadmap";
const sal_Char __FAR_DATA szServiceName_UnoControlRoadmapModel[] = "stardiv.vcl.controlmodel.Roadmap", szServiceName2_UnoControlRoadmapModel[] = "com.sun.star.awt.UnoControlRoadmapModel";
const sal_Char __FAR_DATA szServiceName_UnoSpinButtonControl[] = "com.sun.star.awt.UnoControlSpinButton";
const sal_Char __FAR_DATA szServiceName_UnoSpinButtonModel[] = "com.sun.star.awt.UnoControlSpinButtonModel";
const sal_Char __FAR_DATA szServiceName_TreeControl[] = "com.sun.star.awt.tree.TreeControl";
const sal_Char __FAR_DATA szServiceName_TreeControlModel[] = "com.sun.star.awt.tree.TreeControlModel";
const sal_Char __FAR_DATA szServiceName_MutableTreeDataModel[] = "com.sun.star.awt.tree.MutableTreeDataModel";
const sal_Char __FAR_DATA szServiceName_UnoSimpleAnimationControlModel[] = "com.sun.star.awt.UnoSimpleAnimationControlModel";
const sal_Char __FAR_DATA szServiceName_UnoSimpleAnimationControl[] = "com.sun.star.awt.UnoSimpleAnimationControl";
const sal_Char __FAR_DATA szServiceName_UnoThrobberControlModel[] = "com.sun.star.awt.UnoThrobberControlModel";
const sal_Char __FAR_DATA szServiceName_UnoThrobberControl[] = "com.sun.star.awt.UnoThrobberControl";
<|endoftext|>


<commit_before>#include "BasicBlock.h"
#include "MemStream.h"
#include "offsetof_def.h"
#include "MipsJitter.h"
#include "Jitter_CodeGenFactory.h"

#if defined(AOT_BUILD_CACHE) || defined(AOT_USE_CACHE)
#define AOT_ENABLED
#endif

#ifdef AOT_ENABLED

#include <zlib.h>
#include "StdStream.h"
#include "StdStreamUtils.h"

#endif

#ifdef VTUNE_ENABLED
#include <jitprofiling.h>
#include "string_format.h"
#endif

#ifdef AOT_USE_CACHE

struct AOT_BLOCK
{
	AOT_BLOCK_KEY	key;
	void*			fct;
};

extern "C" AOT_BLOCK	_aot_firstBlock;
extern "C" uint32		_aot_blockCount;

#endif

CBasicBlock::CBasicBlock(CMIPS& context, uint32 begin, uint32 end)
: m_begin(begin)
, m_end(end)
, m_context(context)
, m_selfLoopCount(0)
#ifdef AOT_USE_CACHE
, m_function(nullptr)
#endif
{
	assert(m_end >= m_begin);
}

CBasicBlock::~CBasicBlock()
{

}

#ifdef AOT_BUILD_CACHE

Framework::CStdStream*	CBasicBlock::m_aotBlockOutputStream(nullptr);
std::mutex				CBasicBlock::m_aotBlockOutputStreamMutex;

void CBasicBlock::SetAotBlockOutputStream(Framework::CStdStream* outputStream)
{
	assert(m_aotBlockOutputStream == nullptr || outputStream == nullptr);
	m_aotBlockOutputStream = outputStream;
}

#endif

void CBasicBlock::Compile()
{
#ifndef AOT_USE_CACHE

	Framework::CMemStream stream;
	{
		static __declspec(thread) CMipsJitter* jitter = NULL;
		if(jitter == NULL)
		{
			Jitter::CCodeGen* codeGen = Jitter::CreateCodeGen();
			jitter = new CMipsJitter(codeGen);

			for(unsigned int i = 0; i < 4; i++)
			{
				jitter->SetVariableAsConstant(
					offsetof(CMIPS, m_State.nGPR[CMIPS::R0].nV[i]),
					0
					);
			}
		}

		jitter->SetStream(&stream);
		jitter->Begin();
		CompileRange(jitter);
//		codeGen.DumpVariables(0);
//		codeGen.EndQuota();
		jitter->End();
	}

	m_function = CMemoryFunction(stream.GetBuffer(), stream.GetSize());

#ifdef VTUNE_ENABLED
	if(iJIT_IsProfilingActive() == iJIT_SAMPLING_ON)
	{
		iJIT_Method_Load jmethod = {};
		jmethod.method_id = iJIT_GetNewMethodID();
		jmethod.class_file_name = "";
		jmethod.source_file_name = __FILE__;

		jmethod.method_load_address = m_function.GetCode();
		jmethod.method_size = m_function.GetSize();
		jmethod.line_number_size = 0;

		auto functionName = string_format("BasicBlock_0x%0.8X_0x%0.8X", m_begin, m_end);

		jmethod.method_name = const_cast<char*>(functionName.c_str());
		iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED, reinterpret_cast<void*>(&jmethod));
	}
#endif

#endif

#ifdef AOT_ENABLED

	size_t blockSize = ((m_end - m_begin) / 4) + 1;
	auto blockData = new uint32[blockSize];

	for(uint32 i = 0; i < blockSize; i++)
	{
		blockData[i] = m_context.m_pMemoryMap->GetWord(m_begin + (i * 4));
	}

	uint32 blockChecksum = crc32(0, reinterpret_cast<Bytef*>(blockData), blockSize * 4);

#endif

#ifdef AOT_USE_CACHE

	AOT_BLOCK* blocksBegin = &_aot_firstBlock;
	AOT_BLOCK* blocksEnd = blocksBegin + _aot_blockCount;

	AOT_BLOCK blockRef = { blockChecksum, m_begin, m_end, nullptr };

	static const auto blockComparer =
		[] (const AOT_BLOCK& item1, const AOT_BLOCK& item2)
		{
			return item1.key < item2.key;
		};

//	assert(std::is_sorted(blocksBegin, blocksEnd, blockComparer));

	bool blockExists = std::binary_search(blocksBegin, blocksEnd, blockRef, blockComparer);
	auto blockIterator = std::lower_bound(blocksBegin, blocksEnd, blockRef, blockComparer);

	assert(blockExists);
	assert(blockIterator != blocksEnd);
	assert(blockIterator->key.crc == blockChecksum);
	assert(blockIterator->key.begin == m_begin);
	assert(blockIterator->key.end == m_end);

	m_function = reinterpret_cast<void (*)(void*)>(blockIterator->fct);

#endif

#ifdef AOT_BUILD_CACHE
	{
		std::lock_guard<std::mutex> lock(m_aotBlockOutputStreamMutex);

		m_aotBlockOutputStream->Write32(blockChecksum);
		m_aotBlockOutputStream->Write32(m_begin);
		m_aotBlockOutputStream->Write32(m_end);
		m_aotBlockOutputStream->Write(blockData, blockSize * 4);
	}
#endif
}

void CBasicBlock::CompileRange(CMipsJitter* jitter)
{
	for(uint32 address = m_begin; address <= m_end; address += 4)
	{
		m_context.m_pArch->CompileInstruction(
			address,
			jitter,
			&m_context);
		//Sanity check
		assert(jitter->IsStackEmpty());
	}
}

unsigned int CBasicBlock::Execute()
{
	m_function(&m_context);

	if(m_context.m_State.nDelayedJumpAddr != MIPS_INVALID_PC)
	{
		m_context.m_State.nPC = m_context.m_State.nDelayedJumpAddr;
		m_context.m_State.nDelayedJumpAddr = MIPS_INVALID_PC;
	}
	else
	{
		m_context.m_State.nPC = m_end + 4;
	}

	assert(m_context.m_State.nGPR[0].nV0 == 0);
	assert(m_context.m_State.nGPR[0].nV1 == 0);
	assert(m_context.m_State.nGPR[0].nV2 == 0);
	assert(m_context.m_State.nGPR[0].nV3 == 0);
	assert((m_context.m_State.nGPR[CMIPS::RA].nV0 & 3) == 0);
	assert(m_context.m_State.nCOP2[0].nV0 == 0x00000000);
	assert(m_context.m_State.nCOP2[0].nV1 == 0x00000000);
	assert(m_context.m_State.nCOP2[0].nV2 == 0x00000000);
	assert(m_context.m_State.nCOP2[0].nV3 == 0x3F800000);

	return ((m_end - m_begin) / 4) + 1;
}

uint32 CBasicBlock::GetBeginAddress() const
{
	return m_begin;
}

uint32 CBasicBlock::GetEndAddress() const
{
	return m_end;
}

bool CBasicBlock::IsCompiled() const
{
#ifndef AOT_USE_CACHE
	return !m_function.IsEmpty();
#else
	return (m_function != nullptr);
#endif
}

unsigned int CBasicBlock::GetSelfLoopCount() const
{
	return m_selfLoopCount;
}

void CBasicBlock::SetSelfLoopCount(unsigned int selfLoopCount)
{
	m_selfLoopCount = selfLoopCount;
}
<commit_msg>Added check to make sure VI0 isn't trashed.<commit_after>#include "BasicBlock.h"
#include "MemStream.h"
#include "offsetof_def.h"
#include "MipsJitter.h"
#include "Jitter_CodeGenFactory.h"

#if defined(AOT_BUILD_CACHE) || defined(AOT_USE_CACHE)
#define AOT_ENABLED
#endif

#ifdef AOT_ENABLED

#include <zlib.h>
#include "StdStream.h"
#include "StdStreamUtils.h"

#endif

#ifdef VTUNE_ENABLED
#include <jitprofiling.h>
#include "string_format.h"
#endif

#ifdef AOT_USE_CACHE

struct AOT_BLOCK
{
	AOT_BLOCK_KEY	key;
	void*			fct;
};

extern "C" AOT_BLOCK	_aot_firstBlock;
extern "C" uint32		_aot_blockCount;

#endif

CBasicBlock::CBasicBlock(CMIPS& context, uint32 begin, uint32 end)
: m_begin(begin)
, m_end(end)
, m_context(context)
, m_selfLoopCount(0)
#ifdef AOT_USE_CACHE
, m_function(nullptr)
#endif
{
	assert(m_end >= m_begin);
}

CBasicBlock::~CBasicBlock()
{

}

#ifdef AOT_BUILD_CACHE

Framework::CStdStream*	CBasicBlock::m_aotBlockOutputStream(nullptr);
std::mutex				CBasicBlock::m_aotBlockOutputStreamMutex;

void CBasicBlock::SetAotBlockOutputStream(Framework::CStdStream* outputStream)
{
	assert(m_aotBlockOutputStream == nullptr || outputStream == nullptr);
	m_aotBlockOutputStream = outputStream;
}

#endif

void CBasicBlock::Compile()
{
#ifndef AOT_USE_CACHE

	Framework::CMemStream stream;
	{
		static __declspec(thread) CMipsJitter* jitter = NULL;
		if(jitter == NULL)
		{
			Jitter::CCodeGen* codeGen = Jitter::CreateCodeGen();
			jitter = new CMipsJitter(codeGen);

			for(unsigned int i = 0; i < 4; i++)
			{
				jitter->SetVariableAsConstant(
					offsetof(CMIPS, m_State.nGPR[CMIPS::R0].nV[i]),
					0
					);
			}
		}

		jitter->SetStream(&stream);
		jitter->Begin();
		CompileRange(jitter);
//		codeGen.DumpVariables(0);
//		codeGen.EndQuota();
		jitter->End();
	}

	m_function = CMemoryFunction(stream.GetBuffer(), stream.GetSize());

#ifdef VTUNE_ENABLED
	if(iJIT_IsProfilingActive() == iJIT_SAMPLING_ON)
	{
		iJIT_Method_Load jmethod = {};
		jmethod.method_id = iJIT_GetNewMethodID();
		jmethod.class_file_name = "";
		jmethod.source_file_name = __FILE__;

		jmethod.method_load_address = m_function.GetCode();
		jmethod.method_size = m_function.GetSize();
		jmethod.line_number_size = 0;

		auto functionName = string_format("BasicBlock_0x%0.8X_0x%0.8X", m_begin, m_end);

		jmethod.method_name = const_cast<char*>(functionName.c_str());
		iJIT_NotifyEvent(iJVM_EVENT_TYPE_METHOD_LOAD_FINISHED, reinterpret_cast<void*>(&jmethod));
	}
#endif

#endif

#ifdef AOT_ENABLED

	size_t blockSize = ((m_end - m_begin) / 4) + 1;
	auto blockData = new uint32[blockSize];

	for(uint32 i = 0; i < blockSize; i++)
	{
		blockData[i] = m_context.m_pMemoryMap->GetWord(m_begin + (i * 4));
	}

	uint32 blockChecksum = crc32(0, reinterpret_cast<Bytef*>(blockData), blockSize * 4);

#endif

#ifdef AOT_USE_CACHE

	AOT_BLOCK* blocksBegin = &_aot_firstBlock;
	AOT_BLOCK* blocksEnd = blocksBegin + _aot_blockCount;

	AOT_BLOCK blockRef = { blockChecksum, m_begin, m_end, nullptr };

	static const auto blockComparer =
		[] (const AOT_BLOCK& item1, const AOT_BLOCK& item2)
		{
			return item1.key < item2.key;
		};

//	assert(std::is_sorted(blocksBegin, blocksEnd, blockComparer));

	bool blockExists = std::binary_search(blocksBegin, blocksEnd, blockRef, blockComparer);
	auto blockIterator = std::lower_bound(blocksBegin, blocksEnd, blockRef, blockComparer);

	assert(blockExists);
	assert(blockIterator != blocksEnd);
	assert(blockIterator->key.crc == blockChecksum);
	assert(blockIterator->key.begin == m_begin);
	assert(blockIterator->key.end == m_end);

	m_function = reinterpret_cast<void (*)(void*)>(blockIterator->fct);

#endif

#ifdef AOT_BUILD_CACHE
	{
		std::lock_guard<std::mutex> lock(m_aotBlockOutputStreamMutex);

		m_aotBlockOutputStream->Write32(blockChecksum);
		m_aotBlockOutputStream->Write32(m_begin);
		m_aotBlockOutputStream->Write32(m_end);
		m_aotBlockOutputStream->Write(blockData, blockSize * 4);
	}
#endif
}

void CBasicBlock::CompileRange(CMipsJitter* jitter)
{
	for(uint32 address = m_begin; address <= m_end; address += 4)
	{
		m_context.m_pArch->CompileInstruction(
			address,
			jitter,
			&m_context);
		//Sanity check
		assert(jitter->IsStackEmpty());
	}
}

unsigned int CBasicBlock::Execute()
{
	m_function(&m_context);

	if(m_context.m_State.nDelayedJumpAddr != MIPS_INVALID_PC)
	{
		m_context.m_State.nPC = m_context.m_State.nDelayedJumpAddr;
		m_context.m_State.nDelayedJumpAddr = MIPS_INVALID_PC;
	}
	else
	{
		m_context.m_State.nPC = m_end + 4;
	}

	assert(m_context.m_State.nGPR[0].nV0 == 0);
	assert(m_context.m_State.nGPR[0].nV1 == 0);
	assert(m_context.m_State.nGPR[0].nV2 == 0);
	assert(m_context.m_State.nGPR[0].nV3 == 0);
	assert((m_context.m_State.nGPR[CMIPS::RA].nV0 & 3) == 0);
	assert(m_context.m_State.nCOP2[0].nV0 == 0x00000000);
	assert(m_context.m_State.nCOP2[0].nV1 == 0x00000000);
	assert(m_context.m_State.nCOP2[0].nV2 == 0x00000000);
	assert(m_context.m_State.nCOP2[0].nV3 == 0x3F800000);
	assert(m_context.m_State.nCOP2VI[0] == 0);

	return ((m_end - m_begin) / 4) + 1;
}

uint32 CBasicBlock::GetBeginAddress() const
{
	return m_begin;
}

uint32 CBasicBlock::GetEndAddress() const
{
	return m_end;
}

bool CBasicBlock::IsCompiled() const
{
#ifndef AOT_USE_CACHE
	return !m_function.IsEmpty();
#else
	return (m_function != nullptr);
#endif
}

unsigned int CBasicBlock::GetSelfLoopCount() const
{
	return m_selfLoopCount;
}

void CBasicBlock::SetSelfLoopCount(unsigned int selfLoopCount)
{
	m_selfLoopCount = selfLoopCount;
}
<|endoftext|>