<commit_before>// Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <QtGui/QImage>
#include <QtGui/QFrame>
#include <QtCore/QtDebug>

#include <algorithm>

#include "SensitivitiesWidget.h"
#include "DataModelGUI.h"
#include "qtUtilities.h"
#include "CQTaskBtnWidget.h"
#include "CQTaskHeaderWidget.h"
#include "CQTaskMethodWidget.h"
#include "CCopasiSelectionDialog.h"
#include "resourcesUI/CQIconResource.h"

#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "sensitivities/CSensTask.h"
#include "sensitivities/CSensProblem.h"
#include "sensitivities/CSensMethod.h"
#include "model/CModel.h"
#include "utilities/CCopasiException.h"
#include "report/CKeyFactory.h"
#include "CQSensResultWidget.h"

/**
 *  Constructs a SensitivitiesWidget which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 */
SensitivitiesWidget::SensitivitiesWidget(QWidget* parent, const char* name, Qt::WFlags fl)
  : TaskWidget(parent, name, fl),
    mpSingleFunction(NULL),
    mpSingleVariable(NULL),
    mpSingleVariable2(NULL)
{
  setupUi(this);

  init();
  retranslateUi(this);
}

/*
 *  Destroys the object and frees any allocated resources
 */
SensitivitiesWidget::~SensitivitiesWidget()
{}

void SensitivitiesWidget::init()
{
  mpHeaderWidget->setTaskName("Sensitivities");

  verticalLayout->insertWidget(0, mpHeaderWidget);  // header
  // verticalLayout->insertSpacing(1, 14);      // space between header and body

  mpMethodWidget->showMethodParameters(true);
  verticalLayout->addWidget(mpMethodWidget);

  verticalLayout->addWidget(mpBtnWidget);     // 'footer'

  // icons
  SingleFunctionChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));
  SingleVariableChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));
  SingleVariable2Chooser->setIcon(CQIconResource::icon(CQIconResource::copasi));

  // initialization
  initCombos();
}

bool SensitivitiesWidget::saveTask()
{
  saveCommon();
  saveMethod();

  CSensTask* sensTask =
    dynamic_cast<CSensTask *>(CCopasiRootContainer::getKeyFactory()->get(mKey));

  if (sensTask == NULL)
    return false;

  CSensProblem* problem =
    dynamic_cast<CSensProblem *>(sensTask->getProblem());

  if (problem == NULL)
    return false;

  CSensMethod* method =
    dynamic_cast<CSensMethod *>(sensTask->getMethod());

  if (method == NULL)
    return false;

  // subtask
  problem->setSubTaskType((CSensProblem::SubTaskType)SubTaskChooser->currentIndex());

  CSensItem tmp;

  // target function
  if (FunctionChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
    {
      if (mpSingleFunction)
        tmp.setSingleObjectCN(mpSingleFunction->getCN());
    }
  else
    tmp.setListType(FunctionChooser->getCurrentObjectList());

  problem->changeTargetFunctions(tmp);

  // variables 1
  if (VariableChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
    {
      if (mpSingleVariable)
        tmp.setSingleObjectCN(mpSingleVariable->getCN());
    }
  else
    tmp.setListType(VariableChooser->getCurrentObjectList());

  problem->removeVariables();

  if (tmp.getListType() != CObjectLists::EMPTY_LIST)
    problem->addVariables(tmp);
  else
    return true;

  //variables 2
  CSensItem tmp2;

  if (Variable2Chooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
    {
      if (mpSingleVariable2)
        tmp2.setSingleObjectCN(mpSingleVariable2->getCN());
    }
  else
    tmp2.setListType(Variable2Chooser->getCurrentObjectList());

  // write variables to problem
  problem->removeVariables();

  if (tmp.getListType() != CObjectLists::EMPTY_LIST)
    {
      problem->addVariables(tmp);

      if (tmp2.getListType() != CObjectLists::EMPTY_LIST)
        problem->addVariables(tmp2);
    }

  // :TODO Bug 322: This should only be called when actual changes have been saved.
  // However we do not track the changes for the variables we just delete them and add them again.
  if (true)
    {
      if (mpDataModel != NULL)
        {
          mpDataModel->changed();
        }

      mChanged = false;
    }

  return true;
}

CCopasiMethod * SensitivitiesWidget::createMethod(const CCopasiMethod::SubType & type)
{return CSensMethod::createMethod(type);}

bool SensitivitiesWidget::runTask()
{
  if (FunctionChooser->getCurrentObjectList() != CObjectLists::SINGLE_OBJECT)
    FunctionLineEdit->setText(QApplication::translate("SensitivitiesWidget", "[Please Choose Object.] --->", 0, QApplication::UnicodeUTF8));

  if (!commonBeforeRunTask()) return false;

  bool success = true;

  if (!commonRunTask()) success = false;

  return success;
}

bool SensitivitiesWidget::taskFinishedEvent()
{
  bool success = true;
  //setup the result widget
  CQSensResultWidget *pResult =
    dynamic_cast<CQSensResultWidget*>(mpListView->findWidgetFromId(341));

  if (pResult) pResult->newResult();

  if (success && isVisible()) mpListView->switchToOtherWidget(341, ""); //change to the results window

  return success;
}

bool SensitivitiesWidget::loadTask()
{
  loadCommon();
  loadMethod();

  CSensTask* sensTask =
    dynamic_cast<CSensTask *>(CCopasiRootContainer::getKeyFactory()->get(mKey));
  assert(sensTask);

  CSensProblem* problem =
    dynamic_cast<CSensProblem *>(sensTask->getProblem());
  assert(problem);

  //CSensMethod* method =
  //  dynamic_cast<CSensMethod *>(sensTask->getMethod());
  //assert(method);

  //mSubTaskType = problem->getSubTaskType();
  SubTaskChooser->setCurrentIndex((int)problem->getSubTaskType());
  updateComboBoxes(problem->getSubTaskType());

  CSensItem tmp = problem->getTargetFunctions();

  //target function
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);

  if (tmp.isSingleObject())
    {
      FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
      mpSingleFunction = pDataModel->getDataObject(tmp.getSingleObjectCN());

      if (mpSingleFunction)
        FunctionLineEdit->setText(FROM_UTF8(mpSingleFunction->getObjectDisplayName()));
    }
  else
    {
      mpSingleFunction = NULL;
      FunctionChooser->setCurrentObjectList(tmp.getListType());
    }

  //variables 1
  if (problem->getNumberOfVariables() > 0)
    {
      tmp = problem->getVariables(0);

      if (tmp.isSingleObject())
        {
          VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
          mpSingleVariable = pDataModel->getDataObject(tmp.getSingleObjectCN());

          if (mpSingleVariable)
            VariableLineEdit->setText(FROM_UTF8(mpSingleVariable->getObjectDisplayName()));
        }
      else
        VariableChooser->setCurrentObjectList(tmp.getListType());
    }
  else
    {
      VariableChooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);
      mpSingleVariable = NULL;
    }

  //variables 2
  if (problem->getNumberOfVariables() > 1)
    {
      tmp = problem->getVariables(1);

      if (tmp.isSingleObject())
        {
          Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
          mpSingleVariable2 = pDataModel->getDataObject(tmp.getSingleObjectCN());

          if (mpSingleVariable2)
            Variable2LineEdit->setText(FROM_UTF8(mpSingleVariable2->getObjectDisplayName()));
        }
      else
        Variable2Chooser->setCurrentObjectList(tmp.getListType());
    }
  else
    {
      Variable2Chooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);
      mpSingleVariable2 = NULL;
    }

  //  initCombos(problem);

  mChanged = false;

  updateAllLineditEnable();
  return true;
}

//**************************************************************************

void SensitivitiesWidget::updateLineeditEnable(const SensWidgetComboBox* box, QWidget* w1, QWidget* w2)
{
  if (!box) return;

  bool enable = false;

  if (box->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
    enable = true;

  if (w1) w1->setVisible(enable);

  if (w2) w2->setVisible(enable);
}

void SensitivitiesWidget::updateAllLineditEnable()
{
  /*
    updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooserButton);
    updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooserButton);
    updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2ChooserButton);
  */
  updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooser);
  updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooser);
  updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2Chooser);
}

void
SensitivitiesWidget::initCombos()
{
  QStringList StringList;
  //std::vector<int> mFunctionIndexTable, mVariableIndexTable;

  // SubTaskChooser combo
  int i = 0;

  while (CSensProblem::SubTaskName[i].length() > 0)
    {
      StringList.append(FROM_UTF8(CSensProblem::SubTaskName[i]));
      ++i;
    }

  SubTaskChooser->insertItems(SubTaskChooser->count(), StringList);
  SubTaskChooser->setCurrentIndex(0);
  updateComboBoxes((CSensProblem::SubTaskType)0);
}

void SensitivitiesWidget::updateComboBoxes(CSensProblem::SubTaskType type)
{
  FunctionChooser->fillFromList(CSensProblem::getPossibleTargetFunctions(type));
  VariableChooser->fillFromList(CSensProblem::getPossibleVariables(type));
  Variable2Chooser->fillFromList(CSensProblem::getPossibleVariables(type));
}

// ******************* SLOTs *******************************+

void
//SensitivitiesWidget::on_SubTaskChooser_activated(int)
SensitivitiesWidget::slotChooseSubTask(int)
{
  CSensProblem::SubTaskType subTaskType = (CSensProblem::SubTaskType)SubTaskChooser->currentIndex();
  updateComboBoxes(subTaskType);

  updateAllLineditEnable();
}

void
//SensitivitiesWidget::on_FunctionChooser_activated(int a)
SensitivitiesWidget::slotChooseFunction(int)
{
  updateAllLineditEnable();
}

void
//SensitivitiesWidget::on_VariableChooser_activated(int)
SensitivitiesWidget::slotChooseVariable(int)
{
  updateAllLineditEnable();
}

void
//SensitivitiesWidget::on_Variable2Chooser_activated(int)
SensitivitiesWidget::slotChooseVariable2(int)
{
  updateAllLineditEnable();
}

void
//SensitivitiesWidget::on_SingleFunctionChooser_clicked()
SensitivitiesWidget::slotChooseSingleFunction()
{
  const CCopasiObject * pObject =
    CCopasiSelectionDialog::getObjectSingle(this,
        CQSimpleSelectionTree::Variables |
        CQSimpleSelectionTree::ObservedValues |
        CQSimpleSelectionTree::ObservedConstants);

  if (pObject)
    {
      FunctionLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
      mpSingleFunction = pObject;
      FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
    }
}

void
//SensitivitiesWidget::on_SingleVariableChooser_clicked()
SensitivitiesWidget::slotChooseSingleVariable()
{
  const CCopasiObject * pObject =
    CCopasiSelectionDialog::getObjectSingle(this,
        CQSimpleSelectionTree::InitialTime |
        CQSimpleSelectionTree::Parameters);

  if (pObject)
    {
      VariableLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
      mpSingleVariable = pObject;
      VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
    }
}

void
//SensitivitiesWidget::on_SingleVariable2Chooser_clicked()
SensitivitiesWidget::slotChooseSingleVariable2()
{
  const CCopasiObject * pObject =
    CCopasiSelectionDialog::getObjectSingle(this,
        CQSimpleSelectionTree::InitialTime |
        CQSimpleSelectionTree::Parameters);

  if (pObject)
    {
      Variable2LineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
      mpSingleVariable2 = pObject;
      Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
    }
}
<commit_msg>Fixed Bug 2097. The constant are no longer shown in the object browser.<commit_after>// Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <QtGui/QImage>
#include <QtGui/QFrame>
#include <QtCore/QtDebug>

#include <algorithm>

#include "SensitivitiesWidget.h"
#include "DataModelGUI.h"
#include "qtUtilities.h"
#include "CQTaskBtnWidget.h"
#include "CQTaskHeaderWidget.h"
#include "CQTaskMethodWidget.h"
#include "CCopasiSelectionDialog.h"
#include "resourcesUI/CQIconResource.h"

#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "sensitivities/CSensTask.h"
#include "sensitivities/CSensProblem.h"
#include "sensitivities/CSensMethod.h"
#include "model/CModel.h"
#include "utilities/CCopasiException.h"
#include "report/CKeyFactory.h"
#include "CQSensResultWidget.h"

/**
 *  Constructs a SensitivitiesWidget which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 */
SensitivitiesWidget::SensitivitiesWidget(QWidget* parent, const char* name, Qt::WFlags fl)
  : TaskWidget(parent, name, fl),
    mpSingleFunction(NULL),
    mpSingleVariable(NULL),
    mpSingleVariable2(NULL)
{
  setupUi(this);

  init();
  retranslateUi(this);
}

/*
 *  Destroys the object and frees any allocated resources
 */
SensitivitiesWidget::~SensitivitiesWidget()
{}

void SensitivitiesWidget::init()
{
  mpHeaderWidget->setTaskName("Sensitivities");

  verticalLayout->insertWidget(0, mpHeaderWidget);  // header
  // verticalLayout->insertSpacing(1, 14);      // space between header and body

  mpMethodWidget->showMethodParameters(true);
  verticalLayout->addWidget(mpMethodWidget);

  verticalLayout->addWidget(mpBtnWidget);     // 'footer'

  // icons
  SingleFunctionChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));
  SingleVariableChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));
  SingleVariable2Chooser->setIcon(CQIconResource::icon(CQIconResource::copasi));

  // initialization
  initCombos();
}

bool SensitivitiesWidget::saveTask()
{
  saveCommon();
  saveMethod();

  CSensTask* sensTask =
    dynamic_cast<CSensTask *>(CCopasiRootContainer::getKeyFactory()->get(mKey));

  if (sensTask == NULL)
    return false;

  CSensProblem* problem =
    dynamic_cast<CSensProblem *>(sensTask->getProblem());

  if (problem == NULL)
    return false;

  CSensMethod* method =
    dynamic_cast<CSensMethod *>(sensTask->getMethod());

  if (method == NULL)
    return false;

  // subtask
  problem->setSubTaskType((CSensProblem::SubTaskType)SubTaskChooser->currentIndex());

  CSensItem tmp;

  // target function
  if (FunctionChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
    {
      if (mpSingleFunction)
        tmp.setSingleObjectCN(mpSingleFunction->getCN());
    }
  else
    tmp.setListType(FunctionChooser->getCurrentObjectList());

  problem->changeTargetFunctions(tmp);

  // variables 1
  if (VariableChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
    {
      if (mpSingleVariable)
        tmp.setSingleObjectCN(mpSingleVariable->getCN());
    }
  else
    tmp.setListType(VariableChooser->getCurrentObjectList());

  problem->removeVariables();

  if (tmp.getListType() != CObjectLists::EMPTY_LIST)
    problem->addVariables(tmp);
  else
    return true;

  //variables 2
  CSensItem tmp2;

  if (Variable2Chooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
    {
      if (mpSingleVariable2)
        tmp2.setSingleObjectCN(mpSingleVariable2->getCN());
    }
  else
    tmp2.setListType(Variable2Chooser->getCurrentObjectList());

  // write variables to problem
  problem->removeVariables();

  if (tmp.getListType() != CObjectLists::EMPTY_LIST)
    {
      problem->addVariables(tmp);

      if (tmp2.getListType() != CObjectLists::EMPTY_LIST)
        problem->addVariables(tmp2);
    }

  // :TODO Bug 322: This should only be called when actual changes have been saved.
  // However we do not track the changes for the variables we just delete them and add them again.
  if (true)
    {
      if (mpDataModel != NULL)
        {
          mpDataModel->changed();
        }

      mChanged = false;
    }

  return true;
}

CCopasiMethod * SensitivitiesWidget::createMethod(const CCopasiMethod::SubType & type)
{return CSensMethod::createMethod(type);}

bool SensitivitiesWidget::runTask()
{
  if (FunctionChooser->getCurrentObjectList() != CObjectLists::SINGLE_OBJECT)
    FunctionLineEdit->setText(QApplication::translate("SensitivitiesWidget", "[Please Choose Object.] --->", 0, QApplication::UnicodeUTF8));

  if (!commonBeforeRunTask()) return false;

  bool success = true;

  if (!commonRunTask()) success = false;

  return success;
}

bool SensitivitiesWidget::taskFinishedEvent()
{
  bool success = true;
  //setup the result widget
  CQSensResultWidget *pResult =
    dynamic_cast<CQSensResultWidget*>(mpListView->findWidgetFromId(341));

  if (pResult) pResult->newResult();

  if (success && isVisible()) mpListView->switchToOtherWidget(341, ""); //change to the results window

  return success;
}

bool SensitivitiesWidget::loadTask()
{
  loadCommon();
  loadMethod();

  CSensTask* sensTask =
    dynamic_cast<CSensTask *>(CCopasiRootContainer::getKeyFactory()->get(mKey));
  assert(sensTask);

  CSensProblem* problem =
    dynamic_cast<CSensProblem *>(sensTask->getProblem());
  assert(problem);

  //CSensMethod* method =
  //  dynamic_cast<CSensMethod *>(sensTask->getMethod());
  //assert(method);

  //mSubTaskType = problem->getSubTaskType();
  SubTaskChooser->setCurrentIndex((int)problem->getSubTaskType());
  updateComboBoxes(problem->getSubTaskType());

  CSensItem tmp = problem->getTargetFunctions();

  //target function
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);

  if (tmp.isSingleObject())
    {
      FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
      mpSingleFunction = pDataModel->getDataObject(tmp.getSingleObjectCN());

      if (mpSingleFunction)
        FunctionLineEdit->setText(FROM_UTF8(mpSingleFunction->getObjectDisplayName()));
    }
  else
    {
      mpSingleFunction = NULL;
      FunctionChooser->setCurrentObjectList(tmp.getListType());
    }

  //variables 1
  if (problem->getNumberOfVariables() > 0)
    {
      tmp = problem->getVariables(0);

      if (tmp.isSingleObject())
        {
          VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
          mpSingleVariable = pDataModel->getDataObject(tmp.getSingleObjectCN());

          if (mpSingleVariable)
            VariableLineEdit->setText(FROM_UTF8(mpSingleVariable->getObjectDisplayName()));
        }
      else
        VariableChooser->setCurrentObjectList(tmp.getListType());
    }
  else
    {
      VariableChooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);
      mpSingleVariable = NULL;
    }

  //variables 2
  if (problem->getNumberOfVariables() > 1)
    {
      tmp = problem->getVariables(1);

      if (tmp.isSingleObject())
        {
          Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
          mpSingleVariable2 = pDataModel->getDataObject(tmp.getSingleObjectCN());

          if (mpSingleVariable2)
            Variable2LineEdit->setText(FROM_UTF8(mpSingleVariable2->getObjectDisplayName()));
        }
      else
        Variable2Chooser->setCurrentObjectList(tmp.getListType());
    }
  else
    {
      Variable2Chooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);
      mpSingleVariable2 = NULL;
    }

  //  initCombos(problem);

  mChanged = false;

  updateAllLineditEnable();
  return true;
}

//**************************************************************************

void SensitivitiesWidget::updateLineeditEnable(const SensWidgetComboBox* box, QWidget* w1, QWidget* w2)
{
  if (!box) return;

  bool enable = false;

  if (box->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)
    enable = true;

  if (w1) w1->setVisible(enable);

  if (w2) w2->setVisible(enable);
}

void SensitivitiesWidget::updateAllLineditEnable()
{
  /*
    updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooserButton);
    updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooserButton);
    updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2ChooserButton);
  */
  updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooser);
  updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooser);
  updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2Chooser);
}

void
SensitivitiesWidget::initCombos()
{
  QStringList StringList;
  //std::vector<int> mFunctionIndexTable, mVariableIndexTable;

  // SubTaskChooser combo
  int i = 0;

  while (CSensProblem::SubTaskName[i].length() > 0)
    {
      StringList.append(FROM_UTF8(CSensProblem::SubTaskName[i]));
      ++i;
    }

  SubTaskChooser->insertItems(SubTaskChooser->count(), StringList);
  SubTaskChooser->setCurrentIndex(0);
  updateComboBoxes((CSensProblem::SubTaskType)0);
}

void SensitivitiesWidget::updateComboBoxes(CSensProblem::SubTaskType type)
{
  FunctionChooser->fillFromList(CSensProblem::getPossibleTargetFunctions(type));
  VariableChooser->fillFromList(CSensProblem::getPossibleVariables(type));
  Variable2Chooser->fillFromList(CSensProblem::getPossibleVariables(type));
}

// ******************* SLOTs *******************************+

void
//SensitivitiesWidget::on_SubTaskChooser_activated(int)
SensitivitiesWidget::slotChooseSubTask(int)
{
  CSensProblem::SubTaskType subTaskType = (CSensProblem::SubTaskType)SubTaskChooser->currentIndex();
  updateComboBoxes(subTaskType);

  updateAllLineditEnable();
}

void
//SensitivitiesWidget::on_FunctionChooser_activated(int a)
SensitivitiesWidget::slotChooseFunction(int)
{
  updateAllLineditEnable();
}

void
//SensitivitiesWidget::on_VariableChooser_activated(int)
SensitivitiesWidget::slotChooseVariable(int)
{
  updateAllLineditEnable();
}

void
//SensitivitiesWidget::on_Variable2Chooser_activated(int)
SensitivitiesWidget::slotChooseVariable2(int)
{
  updateAllLineditEnable();
}

void
//SensitivitiesWidget::on_SingleFunctionChooser_clicked()
SensitivitiesWidget::slotChooseSingleFunction()
{
  const CCopasiObject * pObject =
    CCopasiSelectionDialog::getObjectSingle(this,
        CQSimpleSelectionTree::Variables |
        CQSimpleSelectionTree::ObservedValues);

  if (pObject)
    {
      FunctionLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
      mpSingleFunction = pObject;
      FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
    }
}

void
//SensitivitiesWidget::on_SingleVariableChooser_clicked()
SensitivitiesWidget::slotChooseSingleVariable()
{
  const CCopasiObject * pObject =
    CCopasiSelectionDialog::getObjectSingle(this,
        CQSimpleSelectionTree::InitialTime |
        CQSimpleSelectionTree::Parameters);

  if (pObject)
    {
      VariableLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
      mpSingleVariable = pObject;
      VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
    }
}

void
//SensitivitiesWidget::on_SingleVariable2Chooser_clicked()
SensitivitiesWidget::slotChooseSingleVariable2()
{
  const CCopasiObject * pObject =
    CCopasiSelectionDialog::getObjectSingle(this,
        CQSimpleSelectionTree::InitialTime |
        CQSimpleSelectionTree::Parameters);

  if (pObject)
    {
      Variable2LineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));
      mpSingleVariable2 = pObject;
      Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);
    }
}
<|endoftext|>


<commit_before>/*
 *  qiunwrap.cpp
 *
 *  Created by Tobias Wood on 11/06/2015.
 *  Copyright (c) 2015 Tobias Wood.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include "Eigen/Dense"

#include "itkImageSource.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkMultiplyImageFilter.h"
#include "itkForwardFFTImageFilter.h"
#include "itkInverseFFTImageFilter.h"
#include "itkFFTPadImageFilter.h"
#include "Types.h"
#include "Util.h"

using namespace std;
using namespace Eigen;

namespace itk {

class DiscreteLaplacePhaseFilter : public ImageToImageFilter<QI::ImageF, QI::ImageF> {
protected:

public:
	/** Standard class typedefs. */
	typedef QI::ImageF     TImage;

	typedef DiscreteLaplacePhaseFilter         Self;
	typedef ImageToImageFilter<TImage, TImage> Superclass;
	typedef SmartPointer<Self>                 Pointer;
	typedef typename TImage::RegionType        RegionType;

	itkNewMacro(Self);
	itkTypeMacro(DiscreteLaplacePhaseFilter, DiscreteLaplacePhaseFilter);

    void SetInput(const TImage *img) override      { this->SetNthInput(0, const_cast<TImage*>(img)); }
    void SetMask(const TImage *img)                { this->SetNthInput(1, const_cast<TImage*>(img)); }
	typename TImage::ConstPointer GetInput() const { return static_cast<const TImage *>(this->ProcessObject::GetInput(0)); }
	typename TImage::ConstPointer GetMask() const  { return static_cast<const TImage *>(this->ProcessObject::GetInput(1)); }

	virtual void GenerateOutputInformation() override {
		Superclass::GenerateOutputInformation();
		auto op = this->GetOutput();
		op->SetRegions(this->GetInput()->GetLargestPossibleRegion());
		op->Allocate();
	}

protected:
	DiscreteLaplacePhaseFilter() {
		this->SetNumberOfRequiredInputs(1);
		this->SetNumberOfRequiredOutputs(1);
		this->SetNthOutput(0, this->MakeOutput(0));
	}
	~DiscreteLaplacePhaseFilter() {}

	DataObject::Pointer MakeOutput(unsigned int idx) {
		//std::cout <<  __PRETTY_FUNCTION__ << endl;
		if (idx == 0) {
			DataObject::Pointer output = (TImage::New()).GetPointer();
			return output.GetPointer();
		} else {
			std::cerr << "No output " << idx << std::endl;
			return NULL;
		}
	}

    virtual void ThreadedGenerateData(const RegionType &region, ThreadIdType threadId) override {
		//std::cout <<  __PRETTY_FUNCTION__ << endl;
		ConstNeighborhoodIterator<TImage>::RadiusType radius;
		radius.Fill(1);
		ConstNeighborhoodIterator<TImage> inputIter(radius, this->GetInput(), region);
		ImageRegionIterator<TImage> outputIter(this->GetOutput(), region);

		ImageRegionConstIterator<TImage> maskIter;
		const auto mask = this->GetMask();
		if (mask) {
			maskIter = ImageRegionConstIterator<TImage>(mask, region);
		}

		vector<ConstNeighborhoodIterator<TImage>::OffsetType> back, fwrd;
		back.push_back({{-1, 0, 0}});
		fwrd.push_back({{ 1, 0, 0}});
		back.push_back({{ 0,-1, 0}});
		fwrd.push_back({{ 0, 1, 0}});
		back.push_back({{ 0, 0,-1}});
		fwrd.push_back({{ 0, 0, 1}});

		TImage::SpacingType spacing = this->GetInput()->GetSpacing();
		TImage::SpacingType s_sqr = spacing * spacing;
		while(!inputIter.IsAtEnd()) {
			double sum = 0;
			if (!mask || maskIter.Get()) {
				double cphase = inputIter.GetCenterPixel();
				complex<double> c = std::polar(1., cphase);
				for (int i = 0; i < fwrd.size(); ++i) {
					double bphase = inputIter.GetPixel(back[i]);
					double fphase = inputIter.GetPixel(fwrd[i]);
					complex<double> b = std::polar(1., bphase);
					complex<double> f = std::polar(1., fphase);
					sum += std::arg((f*b)/(c*c)) / s_sqr[i];
				}
			}
			outputIter.Set(sum / 7.);
			++inputIter;
			++outputIter;
			if (mask)
				++maskIter;
		}
	}

private:
	DiscreteLaplacePhaseFilter(const Self &); //purposely not implemented
	void operator=(const Self &);  //purposely not implemented
};

class DiscreteInverseLaplace : public ImageSource<QI::ImageF> {
public:
	typedef QI::ImageF             TImage;
	typedef DiscreteInverseLaplace Self;
	typedef ImageSource<TImage>    Superclass;
	typedef SmartPointer<Self>     Pointer;

	itkNewMacro(Self);
	itkTypeMacro(DiscreteInverseLaplace, ImageSource);

    void SetImageProperties(const TImage *img) {
        m_region = img->GetLargestPossibleRegion();
		m_spacing = img->GetSpacing();
		m_direction = img->GetDirection();
		m_origin = img->GetOrigin();
	}

protected:
    typename TImage::RegionType    m_region;
	typename TImage::SpacingType   m_spacing;
	typename TImage::DirectionType m_direction;
	typename TImage::PointType     m_origin;

	DiscreteInverseLaplace(){}
	~DiscreteInverseLaplace(){}
    virtual void GenerateData() override {
		typename TImage::Pointer output = this->GetOutput();
        output->SetRegions(m_region);
		output->Allocate();
		output->SetSpacing(m_spacing);
		output->SetDirection(m_direction);
		output->SetOrigin(m_origin);
		itk::ImageRegionIteratorWithIndex<TImage> imageIt(output,output->GetLargestPossibleRegion());
		imageIt.GoToBegin();
		imageIt.Set(0.); // There is a pole here
		++imageIt;
		while(!imageIt.IsAtEnd()) {
			auto index = imageIt.GetIndex();
			double val = 0;
			for (int i = 0; i < 3; i++) {
                val += 2. - 2. * cos(index[i] * 2. * M_PI / m_region.GetSize()[i]);
			}
			val /= 7.;
			imageIt.Set(1./val);
			++imageIt;
		}
	}

private:
	DiscreteInverseLaplace(const Self &);
	void operator=(const Self &);
};

} // End namespace itk

//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: qiunwrap [options] input \n\
\n\
Input is a single wrapped phase volume\n\
\n\
Options:\n\
	--help, -h        : Print this message.\n\
	--verbose, -v     : Print more information.\n\
	--out, -o path    : Specify an output filename (default image base).\n\
	--mask, -m file   : Mask input with specified file.\n\
	--threads, -T N   : Use N threads (default=hardware limit).\n\
	--lop, -l C       : Use Continuous Laplacian operators.\n\
	          D         Use Discrete Laplacian operators (default).\n"
};

const struct option long_options[] = {
	{"help", no_argument, 0, 'h'},
	{"verbose", no_argument, 0, 'v'},
	{"out", required_argument, 0, 'o'},
	{"mask", required_argument, 0, 'm'},
	{"threads", required_argument, 0, 'T'},
	{"lop", required_argument, 0, 'l'},
	{0, 0, 0, 0}
};
const char *short_options = "hvo:m:T:l:";

//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
	Eigen::initParallel();

	bool verbose = false;
	string prefix;
	itk::ImageFileReader<itk::Image<float, 3>>::Pointer mask = ITK_NULLPTR;
	int indexptr = 0, c;
	while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {
		switch (c) {
			case 'v': verbose = true; break;
			case 'm':
				if (verbose) cout << "Reading mask file " << optarg << endl;
				mask = itk::ImageFileReader<itk::Image<float, 3>>::New();
				mask->SetFileName(optarg);
				break;
			case 'o':
				prefix = optarg;
				cout << "Output prefix will be: " << prefix << endl;
				break;
			case 'l':
				break;
			case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break;
			case 'h':
				cout << usage << endl;
				return EXIT_SUCCESS;
			case '?': // getopt will print an error message
				return EXIT_FAILURE;
			default:
				cout << "Unhandled option " << string(1, c) << endl;
				return EXIT_FAILURE;
		}
	}
	if ((argc - optind) != 1) {
		cout << "Incorrect number of arguments." << endl << usage << endl;
		return EXIT_FAILURE;
	}
	if (verbose) cout << "Opening input file: " << argv[optind] << endl;
	string fname(argv[optind++]);
	if (prefix == "")
		prefix = fname.substr(0, fname.find(".nii"));
	string outname = prefix + "_unwrap" + QI::OutExt();
	if (verbose) cout << "Output filename: " << outname << endl;

	auto inFile = QI::ReadImageF::New();
	auto calcLaplace = itk::DiscreteLaplacePhaseFilter::New();
	inFile->SetFileName(fname);
	inFile->Update(); // Need the size info
	calcLaplace->SetInput(inFile->GetOutput());
	if (mask)
		calcLaplace->SetMask(mask->GetOutput());
    if (verbose) cout << "Padding image to valid FFT size." << endl;
    typedef itk::FFTPadImageFilter<QI::ImageF> PadFFTType;
    auto padFFT = PadFFTType::New();
    padFFT->SetInput(calcLaplace->GetOutput());
    padFFT->Update();
	if (verbose) cout << "Calculating Forward FFT." << endl;
	typedef itk::ForwardFFTImageFilter<QI::ImageF> FFFTType;
	auto forwardFFT = FFFTType::New();
    forwardFFT->SetInput(padFFT->GetOutput());
    forwardFFT->Update();
	if (verbose) cout << "Generating Inverse Laplace Kernel." << endl;
	auto inverseLaplace = itk::DiscreteInverseLaplace::New();
    inverseLaplace->SetImageProperties(padFFT->GetOutput());
    inverseLaplace->Update();
	if (verbose) cout << "Multiplying." << endl;
	auto mult = itk::MultiplyImageFilter<QI::ImageXF, QI::ImageF, QI::ImageXF>::New();
	mult->SetInput1(forwardFFT->GetOutput());
	mult->SetInput2(inverseLaplace->GetOutput());

	if (verbose) cout << "Inverse FFT." << endl;
    auto inverseFFT = itk::InverseFFTImageFilter<QI::ImageXF, QI::ImageF>::New();
	inverseFFT->SetInput(mult->GetOutput());

    auto outFile = QI::WriteImageF::New();
    outFile->SetInput(inverseFFT->GetOutput());
	outFile->SetFileName(outname);
	if (verbose) cout << "Writing output." << endl;
	outFile->Update();
	if (verbose) cout << "Finished." << endl;
	return EXIT_SUCCESS;
}
<commit_msg>Added a step to extract the original size image (to remove FFT padding)<commit_after>/*
 *  qiunwrap.cpp
 *
 *  Created by Tobias Wood on 11/06/2015.
 *  Copyright (c) 2015 Tobias Wood.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include <time.h>
#include <getopt.h>
#include <iostream>
#include <atomic>
#include "Eigen/Dense"

#include "itkImageSource.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkMultiplyImageFilter.h"
#include "itkForwardFFTImageFilter.h"
#include "itkInverseFFTImageFilter.h"
#include "itkFFTPadImageFilter.h"
#include "Types.h"
#include "Util.h"

using namespace std;
using namespace Eigen;

namespace itk {

class DiscreteLaplacePhaseFilter : public ImageToImageFilter<QI::ImageF, QI::ImageF> {
protected:

public:
	/** Standard class typedefs. */
	typedef QI::ImageF     TImage;

	typedef DiscreteLaplacePhaseFilter         Self;
	typedef ImageToImageFilter<TImage, TImage> Superclass;
	typedef SmartPointer<Self>                 Pointer;
	typedef typename TImage::RegionType        RegionType;

	itkNewMacro(Self);
	itkTypeMacro(DiscreteLaplacePhaseFilter, DiscreteLaplacePhaseFilter);

    void SetInput(const TImage *img) override      { this->SetNthInput(0, const_cast<TImage*>(img)); }
    void SetMask(const TImage *img)                { this->SetNthInput(1, const_cast<TImage*>(img)); }
	typename TImage::ConstPointer GetInput() const { return static_cast<const TImage *>(this->ProcessObject::GetInput(0)); }
	typename TImage::ConstPointer GetMask() const  { return static_cast<const TImage *>(this->ProcessObject::GetInput(1)); }

	virtual void GenerateOutputInformation() override {
		Superclass::GenerateOutputInformation();
		auto op = this->GetOutput();
		op->SetRegions(this->GetInput()->GetLargestPossibleRegion());
		op->Allocate();
	}

protected:
	DiscreteLaplacePhaseFilter() {
		this->SetNumberOfRequiredInputs(1);
		this->SetNumberOfRequiredOutputs(1);
		this->SetNthOutput(0, this->MakeOutput(0));
	}
	~DiscreteLaplacePhaseFilter() {}

	DataObject::Pointer MakeOutput(unsigned int idx) {
		//std::cout <<  __PRETTY_FUNCTION__ << endl;
		if (idx == 0) {
			DataObject::Pointer output = (TImage::New()).GetPointer();
			return output.GetPointer();
		} else {
			std::cerr << "No output " << idx << std::endl;
			return NULL;
		}
	}

    virtual void ThreadedGenerateData(const RegionType &region, ThreadIdType threadId) override {
		//std::cout <<  __PRETTY_FUNCTION__ << endl;
		ConstNeighborhoodIterator<TImage>::RadiusType radius;
		radius.Fill(1);
		ConstNeighborhoodIterator<TImage> inputIter(radius, this->GetInput(), region);
		ImageRegionIterator<TImage> outputIter(this->GetOutput(), region);

		ImageRegionConstIterator<TImage> maskIter;
		const auto mask = this->GetMask();
		if (mask) {
			maskIter = ImageRegionConstIterator<TImage>(mask, region);
		}

		vector<ConstNeighborhoodIterator<TImage>::OffsetType> back, fwrd;
		back.push_back({{-1, 0, 0}});
		fwrd.push_back({{ 1, 0, 0}});
		back.push_back({{ 0,-1, 0}});
		fwrd.push_back({{ 0, 1, 0}});
		back.push_back({{ 0, 0,-1}});
		fwrd.push_back({{ 0, 0, 1}});

		TImage::SpacingType spacing = this->GetInput()->GetSpacing();
		TImage::SpacingType s_sqr = spacing * spacing;
		while(!inputIter.IsAtEnd()) {
			double sum = 0;
			if (!mask || maskIter.Get()) {
				double cphase = inputIter.GetCenterPixel();
				complex<double> c = std::polar(1., cphase);
				for (int i = 0; i < fwrd.size(); ++i) {
					double bphase = inputIter.GetPixel(back[i]);
					double fphase = inputIter.GetPixel(fwrd[i]);
					complex<double> b = std::polar(1., bphase);
					complex<double> f = std::polar(1., fphase);
					sum += std::arg((f*b)/(c*c)) / s_sqr[i];
				}
			}
			outputIter.Set(sum / 7.);
			++inputIter;
			++outputIter;
			if (mask)
				++maskIter;
		}
	}

private:
	DiscreteLaplacePhaseFilter(const Self &); //purposely not implemented
	void operator=(const Self &);  //purposely not implemented
};

class DiscreteInverseLaplace : public ImageSource<QI::ImageF> {
public:
	typedef QI::ImageF             TImage;
	typedef DiscreteInverseLaplace Self;
	typedef ImageSource<TImage>    Superclass;
	typedef SmartPointer<Self>     Pointer;

	itkNewMacro(Self);
	itkTypeMacro(DiscreteInverseLaplace, ImageSource);

    void SetImageProperties(const TImage *img) {
        m_region = img->GetLargestPossibleRegion();
		m_spacing = img->GetSpacing();
		m_direction = img->GetDirection();
		m_origin = img->GetOrigin();
	}

protected:
    typename TImage::RegionType    m_region;
	typename TImage::SpacingType   m_spacing;
	typename TImage::DirectionType m_direction;
	typename TImage::PointType     m_origin;

	DiscreteInverseLaplace(){}
	~DiscreteInverseLaplace(){}
    virtual void GenerateData() override {
		typename TImage::Pointer output = this->GetOutput();
        output->SetRegions(m_region);
		output->Allocate();
		output->SetSpacing(m_spacing);
		output->SetDirection(m_direction);
		output->SetOrigin(m_origin);
		itk::ImageRegionIteratorWithIndex<TImage> imageIt(output,output->GetLargestPossibleRegion());
		imageIt.GoToBegin();
		imageIt.Set(0.); // There is a pole here
		++imageIt;
		while(!imageIt.IsAtEnd()) {
			auto index = imageIt.GetIndex();
			double val = 0;
			for (int i = 0; i < 3; i++) {
                val += 2. - 2. * cos(index[i] * 2. * M_PI / m_region.GetSize()[i]);
			}
			val /= 7.;
			imageIt.Set(1./val);
			++imageIt;
		}
	}

private:
	DiscreteInverseLaplace(const Self &);
	void operator=(const Self &);
};

} // End namespace itk

//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: qiunwrap [options] input \n\
\n\
Input is a single wrapped phase volume\n\
\n\
Options:\n\
	--help, -h        : Print this message.\n\
	--verbose, -v     : Print more information.\n\
	--out, -o path    : Specify an output filename (default image base).\n\
	--mask, -m file   : Mask input with specified file.\n\
	--threads, -T N   : Use N threads (default=hardware limit).\n\
	--lop, -l C       : Use Continuous Laplacian operators.\n\
	          D         Use Discrete Laplacian operators (default).\n"
};

const struct option long_options[] = {
	{"help", no_argument, 0, 'h'},
	{"verbose", no_argument, 0, 'v'},
	{"out", required_argument, 0, 'o'},
	{"mask", required_argument, 0, 'm'},
	{"threads", required_argument, 0, 'T'},
	{"lop", required_argument, 0, 'l'},
	{0, 0, 0, 0}
};
const char *short_options = "hvo:m:T:l:";

//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
	Eigen::initParallel();

	bool verbose = false;
	string prefix;
	itk::ImageFileReader<itk::Image<float, 3>>::Pointer mask = ITK_NULLPTR;
	int indexptr = 0, c;
	while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {
		switch (c) {
			case 'v': verbose = true; break;
			case 'm':
				if (verbose) cout << "Reading mask file " << optarg << endl;
				mask = itk::ImageFileReader<itk::Image<float, 3>>::New();
				mask->SetFileName(optarg);
				break;
			case 'o':
				prefix = optarg;
				cout << "Output prefix will be: " << prefix << endl;
				break;
			case 'l':
				break;
			case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break;
			case 'h':
				cout << usage << endl;
				return EXIT_SUCCESS;
			case '?': // getopt will print an error message
				return EXIT_FAILURE;
			default:
				cout << "Unhandled option " << string(1, c) << endl;
				return EXIT_FAILURE;
		}
	}
	if ((argc - optind) != 1) {
		cout << "Incorrect number of arguments." << endl << usage << endl;
		return EXIT_FAILURE;
	}
	if (verbose) cout << "Opening input file: " << argv[optind] << endl;
	string fname(argv[optind++]);
	if (prefix == "")
		prefix = fname.substr(0, fname.find(".nii"));
	string outname = prefix + "_unwrap" + QI::OutExt();
	if (verbose) cout << "Output filename: " << outname << endl;

	auto inFile = QI::ReadImageF::New();
	auto calcLaplace = itk::DiscreteLaplacePhaseFilter::New();
	inFile->SetFileName(fname);
	inFile->Update(); // Need the size info
	calcLaplace->SetInput(inFile->GetOutput());
	if (mask)
        calcLaplace->SetMask(mask->GetOutput());

    if (verbose) cout << "Padding image to valid FFT size." << endl;
    typedef itk::FFTPadImageFilter<QI::ImageF> PadFFTType;
    auto padFFT = PadFFTType::New();
    padFFT->SetInput(calcLaplace->GetOutput());
    padFFT->Update();

	if (verbose) cout << "Calculating Forward FFT." << endl;
	typedef itk::ForwardFFTImageFilter<QI::ImageF> FFFTType;
	auto forwardFFT = FFFTType::New();
    forwardFFT->SetInput(padFFT->GetOutput());
    forwardFFT->Update();

	if (verbose) cout << "Generating Inverse Laplace Kernel." << endl;
	auto inverseLaplace = itk::DiscreteInverseLaplace::New();
    inverseLaplace->SetImageProperties(padFFT->GetOutput());
    inverseLaplace->Update();

    if (verbose) cout << "Multiplying." << endl;
	auto mult = itk::MultiplyImageFilter<QI::ImageXF, QI::ImageF, QI::ImageXF>::New();
	mult->SetInput1(forwardFFT->GetOutput());
	mult->SetInput2(inverseLaplace->GetOutput());

	if (verbose) cout << "Inverse FFT." << endl;
    auto inverseFFT = itk::InverseFFTImageFilter<QI::ImageXF, QI::ImageF>::New();
	inverseFFT->SetInput(mult->GetOutput());

    if (verbose) cout << "Extracting original size image" << endl;
    auto extract = itk::ExtractImageFilter<QI::ImageF, QI::ImageF>::New();
    extract->SetInput(inverseFFT->GetOutput());
    extract->SetDirectionCollapseToSubmatrix();
    extract->SetExtractionRegion(calcLaplace->GetOutput()->GetLargestPossibleRegion());
    extract->Update();

    auto outFile = QI::WriteImageF::New();
    outFile->SetInput(extract->GetOutput());
	outFile->SetFileName(outname);
    if (verbose) cout << "Writing output." << endl;
	outFile->Update();
	if (verbose) cout << "Finished." << endl;
	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>//
//  SpcFileGenerate.cpp
//  C700
//
//  Created by osoumen on 2017/01/30.
//
//

#include "SpcFileGenerate.h"

SpcFileGenerate::SpcFileGenerate(int allocSize)
: PlayingFileGenerateBase(allocSize)
{
    //SetSpcPlayCode( spcplayercode, sizeof(spcplayercode) );
    strncpy(mSongTitle, "Song title", 32);
    strncpy(mGameTitle, "Game title", 32);
    strncpy(mNameOfDumper, "dumper", 16);
    strncpy(mArtistOfSong, "Artist of song", 32);
    strncpy(mSongComments, "Comments", 32);
    mPlaySec = 120;
    mFadeMs = 5000;

}

SpcFileGenerate::~SpcFileGenerate()
{

}

void SpcFileGenerate::SetSpcPlayCode( const void *code, int size, const void *smccode, int smcsize )
{
    m_pSpcPlayCode = (unsigned char*)code;
    mSpcPlayCodeSize = size;
	mSpcPlayCodeSize2 = findDspregAccCode( smccode, smcsize, &m_pSpcPlayCode2 );
}

bool SpcFileGenerate::WriteToFile( const char *path, const RegisterLogger &reglog, double tickPerSec )
{
    DataBuffer  spcFile(0x10200);

    // レジスタログの生成
    unsigned char *reglogData = new unsigned char [4 * 1024 * 1024];
    int loopPoint;
    int reglogSize = convertLogData( reglog, tickPerSec, reglogData, 4 * 1024 * 1024, &loopPoint, true );

	const int echoSize = reglog.getDspRegionData()[0x7d] << 11;
	int logAddr = 0x600 + echoSize;
	int brrAddr = reglog.getBrrRegionLocateAddr();
	bool outputScript700 = false;
	if (reglogSize > (brrAddr - logAddr))
	{
		// 64kに収まらない場合、700ファイルの形式で書き出す
		char script700path[PATH_LEN_MAX];
		get700FileName(path, script700path, PATH_LEN_MAX);
		exportScript700(script700path, reglog);
		outputScript700 = true;
	}

    // SPCヘッダの書き出し
    spcFile.writeData("SNES-SPC700 Sound File Data v0.30", 33);
    spcFile.writeByte(26, 3);
    spcFile.writeByte(30);      // Version minor
	if (outputScript700) {
		spcFile.writeU16(0x31);    // PC
	}
	else {
		spcFile.writeU16(0x100);    // PC
	}
    spcFile.writeByte(0);       // A
    spcFile.writeByte(0);       // X
    spcFile.writeByte(0);       // Y
    spcFile.writeByte(0x02);    // PSW
    spcFile.writeByte(0xff);    // SP
    spcFile.writeByte(0, 2);    // reserved

    spcFile.writeData(mSongTitle, 32);      // Song title
    spcFile.writeData(mGameTitle, 32);      // Game title
    spcFile.writeData(mNameOfDumper, 16);   // Name of dumper
    spcFile.writeData(mSongComments, 32);   // Comments
    {
        time_t timer;
        struct tm *local;
        timer = time(NULL);
        local = localtime(&timer);
        char dateStr[16];
        sprintf(dateStr, "%02d/%02d/%04d", local->tm_mon + 1, local->tm_mday, local->tm_year + 1900);
        spcFile.writeData(dateStr, 11);    // Date SPC was dumped (MM/DD/YYYY)
    }
    {
        char str[4] = {0,0,0,0};
        sprintf(str, "%d", mPlaySec);
        spcFile.writeData(str, 3);            // Number of seconds to play song before fading out
    }
    {
        char str[6] = {0,0,0,0,0,0};
        sprintf(str, "%d", mFadeMs);
        spcFile.writeData(str, 5);          // Length of fade in milliseconds
    }
    spcFile.writeData(mArtistOfSong, 32);   // Artist of song
    spcFile.writeByte(0);       // Default channel disables (0 = enable, 1 = disable)
    spcFile.writeByte(0);       // Emulator used to dump SPC: 0 = unknown, 1 = ZSNES, 2 = Snes9x
    spcFile.writeByte(0, 45);   // reserved (set to all 0's)

    // WaitTableの書き出し
	if (!outputScript700) {
		spcFile.setPos(0x130);
		writeWaitTable(spcFile, reglog);
	}

    // 実行コードの書き出し
	if (outputScript700) {
		spcFile.setPos(0x110);
		spcFile.writeData(m_pSpcPlayCode2, mSpcPlayCodeSize2);
	}
	else {
		spcFile.setPos(0x170);
		spcFile.writeData(m_pSpcPlayCode, mSpcPlayCodeSize);
	}

    // DIR領域の書き出し
    spcFile.setPos(0x300);
    spcFile.writeData(reglog.getDirRegionData(), reglog.getDirRegionSize());

    // レジスタログの書き出し
	if (!outputScript700) {
		// エコー領域の後に演奏データを入れる
		spcFile.setPos(0x700 + echoSize);    // DSP_EDL
		spcFile.writeData(reglogData, reglogSize);
	}

    // BRR領域の書き出し
    spcFile.setPos(0x100 + brrAddr);
    spcFile.writeData(reglog.getBrrRegionData(), reglog.getBrrRegionSize());

    // 初期変数の設定
	if (!outputScript700) {
		spcFile.setPos(0x102);                  // 変数領域へ移動
		spcFile.writeU16(logAddr & 0xffff);     // 演奏データ開始アドレス
		spcFile.writeU16(loopPoint & 0xffff);   // ループポイント
		spcFile.writeByte(0xff);                // _INITIAL_WAIT_FRAMES
	}

    // DSP領域の書き出し
    spcFile.setPos(0x10100);
    writeDspRegion(spcFile, reglog);

	// KON,KOFフラグをクリアする
	spcFile.setPos(0x1014c);
	spcFile.writeByte(0x00);
	spcFile.setPos(0x1015c);
	spcFile.writeByte(0x00);

    spcFile.WriteToFile(path);

    delete [] reglogData;

    return true;
}

void SpcFileGenerate::SetGameTitle(const char *title)
{
    setHeaderString(mGameTitle, title, 32);
}

void SpcFileGenerate::SetSongTitle(const char *title)
{
    setHeaderString(mSongTitle, title, 32);
}

void SpcFileGenerate::SetNameOfDumper(const char *dumper)
{
    setHeaderString(mNameOfDumper, dumper, 16);
}

void SpcFileGenerate::SetArtistOfSong(const char *artist)
{
    setHeaderString(mArtistOfSong, artist, 32);
}

void SpcFileGenerate::SetSongComments(const char *comments)
{
    setHeaderString(mSongComments, comments, 32);
}

void SpcFileGenerate::setHeaderString(char *dst, const char *src, int len)
{
    if (src[0] == 0) {
        return;
    }
    memset(dst, 0x20, len);
    for (int i=0; (i<len) && (src[i]!=0); i++) {
        dst[i] = src[i];
    }
}

void SpcFileGenerate::SetPlaySeconds(int sec)
{
    mPlaySec = sec;
    if (mPlaySec > 999) {
        mPlaySec = 999;
    }
    if (mPlaySec < 0) {
        mPlaySec = 0;
    }
}

void SpcFileGenerate::SetFadeMs(int ms)
{
    mFadeMs = ms;
    if (mFadeMs > 99999) {
        mFadeMs = 99999;
    }
    if (mFadeMs < 0) {
        mFadeMs = 0;
    }
}

//-----------------------------------------------------------------------------
void SpcFileGenerate::get700FileName( const char *path, char *out, int maxLen )
{
#if MAC
	CFURLRef	url = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8*)path, strlen(path), false);
	CFURLRef	extlesspath=CFURLCreateCopyDeletingPathExtension(NULL, url);
	CFStringRef	filename = CFURLCopyFileSystemPath(extlesspath,kCFURLPOSIXPathStyle);
	CFStringGetCString(filename, out, maxLen-1, kCFStringEncodingUTF8);
	strcat(out, ".700");
	CFRelease(filename);
	CFRelease(extlesspath);
	CFRelease(url);
#else
	int	len = static_cast<int>(strlen(path));
	int extPos = len;
	for ( int i=len-1; i>=0; i-- ) {
		if ( path[i] == '.' ) {
			extPos = i;
			break;
		}
	}
	strncpy(out, path, extPos);
	out[extPos] = 0;
	strcat(out, ".700");
#endif
}

//-----------------------------------------------------------------------------
int SpcFileGenerate::findDspregAccCode( const void *code, int size, const unsigned char **outCode )
{
	const unsigned char *p_code = (unsigned char*)code;
	for (int i=0; i<(size-3); ++i) {
		if (p_code[i] == 0x8f && p_code[i+1] == 0x00 && p_code[i+2] == 0xf1) {
			*outCode = &p_code[i];
			return size - i;
		}
	}
	return 0;
}
<commit_msg>SpcPlayCodeSizeに応じてspcファイルのDIR,ESAの位置を移動させる処理<commit_after>//
//  SpcFileGenerate.cpp
//  C700
//
//  Created by osoumen on 2017/01/30.
//
//

#include "SpcFileGenerate.h"

SpcFileGenerate::SpcFileGenerate(int allocSize)
: PlayingFileGenerateBase(allocSize)
{
    //SetSpcPlayCode( spcplayercode, sizeof(spcplayercode) );
    strncpy(mSongTitle, "Song title", 32);
    strncpy(mGameTitle, "Game title", 32);
    strncpy(mNameOfDumper, "dumper", 16);
    strncpy(mArtistOfSong, "Artist of song", 32);
    strncpy(mSongComments, "Comments", 32);
    mPlaySec = 120;
    mFadeMs = 5000;

}

SpcFileGenerate::~SpcFileGenerate()
{

}

void SpcFileGenerate::SetSpcPlayCode( const void *code, int size, const void *smccode, int smcsize )
{
    m_pSpcPlayCode = (unsigned char*)code;
    mSpcPlayCodeSize = size;
	mSpcPlayCodeSize2 = findDspregAccCode( smccode, smcsize, &m_pSpcPlayCode2 );
}

bool SpcFileGenerate::WriteToFile( const char *path, const RegisterLogger &reglog, double tickPerSec )
{
    DataBuffer  spcFile(0x10200);

    // レジスタログの生成
    unsigned char *reglogData = new unsigned char [4 * 1024 * 1024];
    int loopPoint;
    int reglogSize = convertLogData( reglog, tickPerSec, reglogData, 4 * 1024 * 1024, &loopPoint, true );

	const int echoSize = reglog.getDspRegionData()[0x7d] << 11;
	int brrAddr = reglog.getBrrRegionLocateAddr();
	bool outputScript700 = false;
	int dirPos = (0x200 + mSpcPlayCodeSize + 0xff) & 0xff00;
	int esaPos = dirPos + 0x400;
	int logAddr = esaPos + echoSize;

	if (reglogSize > (brrAddr - logAddr))
	{
		// 64kに収まらない場合、700ファイルの形式で書き出す
		char script700path[PATH_LEN_MAX];
		get700FileName(path, script700path, PATH_LEN_MAX);
		exportScript700(script700path, reglog);
		outputScript700 = true;
		dirPos = 0x200;
		esaPos = dirPos + 0x400;
	}

    // SPCヘッダの書き出し
    spcFile.writeData("SNES-SPC700 Sound File Data v0.30", 33);
    spcFile.writeByte(26, 3);
    spcFile.writeByte(30);      // Version minor
	if (outputScript700) {
		spcFile.writeU16(0x31);    // PC
	}
	else {
		spcFile.writeU16(0x100);    // PC
	}
    spcFile.writeByte(0);       // A
    spcFile.writeByte(0);       // X
    spcFile.writeByte(0);       // Y
    spcFile.writeByte(0x02);    // PSW
    spcFile.writeByte(0xff);    // SP
    spcFile.writeByte(0, 2);    // reserved

    spcFile.writeData(mSongTitle, 32);      // Song title
    spcFile.writeData(mGameTitle, 32);      // Game title
    spcFile.writeData(mNameOfDumper, 16);   // Name of dumper
    spcFile.writeData(mSongComments, 32);   // Comments
    {
        time_t timer;
        struct tm *local;
        timer = time(NULL);
        local = localtime(&timer);
        char dateStr[16];
        sprintf(dateStr, "%02d/%02d/%04d", local->tm_mon + 1, local->tm_mday, local->tm_year + 1900);
        spcFile.writeData(dateStr, 11);    // Date SPC was dumped (MM/DD/YYYY)
    }
    {
        char str[4] = {0,0,0,0};
        sprintf(str, "%d", mPlaySec);
        spcFile.writeData(str, 3);            // Number of seconds to play song before fading out
    }
    {
        char str[6] = {0,0,0,0,0,0};
        sprintf(str, "%d", mFadeMs);
        spcFile.writeData(str, 5);          // Length of fade in milliseconds
    }
    spcFile.writeData(mArtistOfSong, 32);   // Artist of song
    spcFile.writeByte(0);       // Default channel disables (0 = enable, 1 = disable)
    spcFile.writeByte(0);       // Emulator used to dump SPC: 0 = unknown, 1 = ZSNES, 2 = Snes9x
    spcFile.writeByte(0, 45);   // reserved (set to all 0's)

    // WaitTableの書き出し
	if (!outputScript700) {
		spcFile.setPos(0x130);
		writeWaitTable(spcFile, reglog);
	}

    // 実行コードの書き出し
	if (outputScript700) {
		spcFile.setPos(0x110);
		spcFile.writeData(m_pSpcPlayCode2, mSpcPlayCodeSize2);
	}
	else {
		spcFile.setPos(0x170);
		spcFile.writeData(m_pSpcPlayCode, mSpcPlayCodeSize);
	}

    // DIR領域の書き出し
    spcFile.setPos(0x100 + dirPos);
    spcFile.writeData(reglog.getDirRegionData(), reglog.getDirRegionSize());

    // レジスタログの書き出し
	if (!outputScript700) {
		// エコー領域の後に演奏データを入れる
		spcFile.setPos(0x100 + esaPos + echoSize);    // DSP_EDL
		spcFile.writeData(reglogData, reglogSize);
	}

    // BRR領域の書き出し
    spcFile.setPos(0x100 + brrAddr);
    spcFile.writeData(reglog.getBrrRegionData(), reglog.getBrrRegionSize());

    // 初期変数の設定
	if (!outputScript700) {
		spcFile.setPos(0x102);                  // 変数領域へ移動
		spcFile.writeU16(logAddr & 0xffff);     // 演奏データ開始アドレス
		spcFile.writeU16(loopPoint & 0xffff);   // ループポイント
		spcFile.writeByte(0xff);                // _INITIAL_WAIT_FRAMES
	}

    // DSP領域の書き出し
    spcFile.setPos(0x10100);
    writeDspRegion(spcFile, reglog);

	// DIR,ESAの書き換え
	spcFile.setPos(0x1015d);	// DIR
	spcFile.writeByte(dirPos >> 8);
	spcFile.setPos(0x1016d);	// ESA
	spcFile.writeByte(esaPos >> 8);

	// KON,KOFフラグをクリアする
	spcFile.setPos(0x1014c);
	spcFile.writeByte(0x00);
	spcFile.setPos(0x1015c);
	spcFile.writeByte(0x00);

    spcFile.WriteToFile(path);

    delete [] reglogData;

    return true;
}

void SpcFileGenerate::SetGameTitle(const char *title)
{
    setHeaderString(mGameTitle, title, 32);
}

void SpcFileGenerate::SetSongTitle(const char *title)
{
    setHeaderString(mSongTitle, title, 32);
}

void SpcFileGenerate::SetNameOfDumper(const char *dumper)
{
    setHeaderString(mNameOfDumper, dumper, 16);
}

void SpcFileGenerate::SetArtistOfSong(const char *artist)
{
    setHeaderString(mArtistOfSong, artist, 32);
}

void SpcFileGenerate::SetSongComments(const char *comments)
{
    setHeaderString(mSongComments, comments, 32);
}

void SpcFileGenerate::setHeaderString(char *dst, const char *src, int len)
{
    if (src[0] == 0) {
        return;
    }
    memset(dst, 0x20, len);
    for (int i=0; (i<len) && (src[i]!=0); i++) {
        dst[i] = src[i];
    }
}

void SpcFileGenerate::SetPlaySeconds(int sec)
{
    mPlaySec = sec;
    if (mPlaySec > 999) {
        mPlaySec = 999;
    }
    if (mPlaySec < 0) {
        mPlaySec = 0;
    }
}

void SpcFileGenerate::SetFadeMs(int ms)
{
    mFadeMs = ms;
    if (mFadeMs > 99999) {
        mFadeMs = 99999;
    }
    if (mFadeMs < 0) {
        mFadeMs = 0;
    }
}

//-----------------------------------------------------------------------------
void SpcFileGenerate::get700FileName( const char *path, char *out, int maxLen )
{
#if MAC
	CFURLRef	url = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8*)path, strlen(path), false);
	CFURLRef	extlesspath=CFURLCreateCopyDeletingPathExtension(NULL, url);
	CFStringRef	filename = CFURLCopyFileSystemPath(extlesspath,kCFURLPOSIXPathStyle);
	CFStringGetCString(filename, out, maxLen-1, kCFStringEncodingUTF8);
	strcat(out, ".700");
	CFRelease(filename);
	CFRelease(extlesspath);
	CFRelease(url);
#else
	int	len = static_cast<int>(strlen(path));
	int extPos = len;
	for ( int i=len-1; i>=0; i-- ) {
		if ( path[i] == '.' ) {
			extPos = i;
			break;
		}
	}
	strncpy(out, path, extPos);
	out[extPos] = 0;
	strcat(out, ".700");
#endif
}

//-----------------------------------------------------------------------------
int SpcFileGenerate::findDspregAccCode( const void *code, int size, const unsigned char **outCode )
{
	const unsigned char *p_code = (unsigned char*)code;
	for (int i=0; i<(size-3); ++i) {
		if (p_code[i] == 0x8f && p_code[i+1] == 0x00 && p_code[i+2] == 0xf1) {
			*outCode = &p_code[i];
			return size - i;
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>/*
T0 DA for online calibration
Contact: AllaMaevskaya@cern.ch
Run Type: PHYSICS
DA Type: MON
Number of events needed: 10000
Input Files: inPhys.dat, external parameters, T0/Calib/Slewing_Walk
Output Files: daPhys.root, to be exported to the DAQ FXS
Trigger types used: PHYSICS_EVENT

*/

#define FILE_OUT "daPhys.root"
#define FILE_IN "inPhys.dat"
#include <daqDA.h>
#include <event.h>
#include <monitor.h>

#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>

//AliRoot
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliT0RawReader.h>
#include <AliT0CalibWalk.h>
#include <AliCDBManager.h>
#include <AliCDBEntry.h>
//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include "TFile.h"
#include "TKey.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TString.h"
#include "TH1.h"
#include "TMath.h"

/* Main routine
      Arguments:
      1- monitoring data source
*/
int main(int argc, char **argv) {
//int main(){
  int status;

  /* magic line */
  gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
                                        "*",
                                        "TStreamerInfo",
                                        "RIO",
                                        "TStreamerInfo()");

  if(daqDA_DB_getFile(FILE_IN, FILE_IN)){
    printf("Couldn't get input file >>inPhys.dat<< from DAQ_DB !!!\n");
    return -1;
  }

  FILE *inp;
  char c;
  inp = fopen(FILE_IN, "r");
  if(!inp){
    printf("Input file >>inPhys.dat<< not found !!!\n");
    return -1;
  }
  int  kcbx, kt0bx, knpmtA, knpmtC,kcfdbx;
  float kclx,kcmx, kt0lx, kt0hx, kcfdlx, kcfdhx;

  while((c=getc(inp))!=EOF) {
    switch(c) {
    case 'a': {fscanf(inp, "%d", &kcbx ); break;} //N of X bins hCFD1minCFD
    case 'b': {fscanf(inp, "%f", &kclx ); break;} //Low x hCFD1minCFD
    case 'c': {fscanf(inp, "%f", &kcmx ); break;} //High x hCFD1minCFD
    case 'd': {fscanf(inp, "%d", &knpmtC ); break;} //number of reference PMTC
    case 'e': {fscanf(inp, "%d", &knpmtA ); break;} //number of reference PMTA
    case 'f': {fscanf(inp, "%d", &kcfdbx ); break;} //N of X bins hCFD&OR
    case 'g': {fscanf(inp, "%f", &kcfdlx ); break;} //Low x  hCFD&OR
    case 'k': {fscanf(inp, "%f", &kcfdhx ); break;} //High x  hCFD&OR
    case 'm': {fscanf(inp, "%d", &kt0bx ); break;} //N of X bins TVDC
    case 'n': {fscanf(inp, "%f", &kt0lx ); break;} //Low x  TVDC
    case 'q': {fscanf(inp, "%f", &kt0hx ); break;} //High x  TVDC
    }
  }
  fclose(inp);

  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
    printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  /* log start of process */
  printf("T0 monitoring program started\n");

  // Get run number
  if (getenv("DATE_RUN_NUMBER")==0) {
    printf("DATE_RUN_NUMBER not properly set.\n");
    return -1;
  }
  int runNr = atoi(getenv("DATE_RUN_NUMBER"));

 // Get the necessary OCDB files from the DAQ detector DB
  if (gSystem->AccessPathName("localOCDB/T0/Calib/Slewing_Walk/",kFileExists)) {
    if (gSystem->mkdir("localOCDB/T0/Calib/Slewing_Walk/",kTRUE) != 0) {
      printf("Failed to create directory: localOCDB/T0/Calib/Slewing_Walk/");
      return -1;
    }
  }
  status = daqDA_DB_getFile("T0/Calib/Slewing_Walk/Run0_999999999_v0_s0.root","localOCDB/T0/Calib/Slewing_Walk/Run0_999999999_v0_s0.root");
  if (status) {
    printf("Failed to get  file T0/Calib/Slewing_Walk() from DAQdetDB, status=%d\n", status);
    return -1;
  }

  TGraph *gr[24]; TGraph *gramp[24];
  AliCDBManager *man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://localOCDB");
  man->SetRun(runNr);
  cout<<" run number "<<runNr<<endl;
  AliCDBEntry *entry = AliCDBManager::Instance()->Get("T0/Calib/Slewing_Walk");
  if(entry) {
    AliT0CalibWalk *fParam = (AliT0CalibWalk*)entry->GetObject();
    for (Int_t i=0; i<24; i++) {
      gr[i] = fParam->GetWalk(i);
      gramp[i] = fParam->GetQTC(i);
    }
  }
  Int_t chargeQT0[24], chargeQT1[24];
  Float_t adc ,walk, amp;

  // Allocation of histograms - start

  TH1F *hCFD1minCFD[24];
  TH1F *hCFD[24], *hQT1[24], *hPed[24];

  for(Int_t ic=0; ic<24; ic++) {
    hCFD1minCFD[ic] = new TH1F(Form("CFD1minCFD%d",ic+1),"CFD-CFD",kcbx,kclx,kcmx);
    hCFD[ic] = new TH1F(Form("CFD%d",ic+1),"CFD",kcfdbx,kcfdlx,kcfdhx);
    hQT1[ic] = new TH1F(Form("QT1%d",ic+1),"QT1",kt0bx,kt0lx,kt0hx);
    hPed[ic] = new TH1F(Form("hPed%d",ic+1),"pedestal",500,500,2000);
  }
  TH1F *hVertex = new TH1F("hVertex","TVDC",kt0bx,kt0lx,kt0hx);
  TH1F *hOrA = new TH1F("hOrA","OrA",kcfdbx,kcfdlx,kcfdhx);
  TH1F *hOrC = new TH1F("hOrC","OrC",kcfdbx,kcfdlx,kcfdhx);

   // Allocation of histograms - end

 Int_t iev=0;
  /* main loop (infinite) */
  for(;;) {
    struct eventHeaderStruct *event;
    eventTypeType eventT;

    /* check shutdown condition */
    if (daqDA_checkShutdown()) {break;}

    /* get next event (blocking call until timeout) */
    status=monitorGetEventDynamic((void **)&event);
     if (status==(int)MON_ERR_EOF) {
      printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
    }

    if (status!=0) {
      printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
    }

    /* retry if got no event */
    if (event==NULL) {
      continue;
    }

    /* use event - here, just write event id to result file */
    eventT=event->eventType;

    switch (event->eventType){

    case START_OF_RUN:
      break;

    case END_OF_RUN:
      break;

  case PHYSICS_EVENT:
      //	 	 case CALIBRATION_EVENT: for test
      iev++;

      if(iev==1){
	printf("First event - %i\n",iev);
      }

      // Initalize raw-data reading and decoding
      AliRawReader *reader = new AliRawReaderDate((void*)event);

      // Enable the following two lines in case of real-data
      reader->RequireHeader(kTRUE);
      AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);
      // start->SetPrintout(kFALSE);
      // Read raw data
      Int_t allData[220][5];
      for(Int_t i0=0;i0<220;i0++)
      	for(Int_t j0=0;j0<5;j0++)
	  allData[i0][j0] = 0;

      if(start->Next()){
	for (Int_t i=0; i<211; i++) {
	  for(Int_t iHit=0;iHit<5;iHit++){
	    allData[i][iHit]= start->GetData(i,iHit);
	  }
	}
      }
      if (allData[50][0] == 0)     continue;
      hVertex->Fill(allData[50][0]);
      hOrA->Fill(allData[51][0]);
      hOrC->Fill(allData[52][0]);
      // Fill the histograms
      walk = adc = amp = -999;
      for (Int_t in=0; in<12;  in++)
	{
	  chargeQT0[in]=allData[2*in+25][0];
	  chargeQT1[in]=allData[2*in+26][0];
	}
      for (Int_t in=12; in<24;  in++)
	{
	  chargeQT0[in]=allData[2*in+57][0];
	  chargeQT1[in]=allData[2*in+58][0];
	}
      Float_t time[24];
      Float_t meanShift[24];
      for (Int_t ik = 0; ik<24; ik++)
	{
	  if( ( chargeQT0[ik] - chargeQT1[ik])>0)  {
	    adc = chargeQT0[ik] - chargeQT1[ik];
	    //	cout<<ik <<"  "<<adc<<endl;
	  }
	  if(gr[ik] && adc>0)
	    walk = Int_t(gr[ik]->Eval(Double_t(adc) ) );
	  //	  cout<<ik<<" walk "<<walk<<" "<<allData[ik+1][0]<<endl;
	  if(ik<12 && allData[ik+1][0]>0  ){
	    if( walk >-100) hCFD[ik]->Fill(allData[ik+1][0] - walk);
	    hQT1[ik]->Fill(chargeQT1[ik]);
	    if ( allData[knpmtC][0]>0 )
	      hCFD1minCFD[ik]->Fill(allData[ik+1][0]-allData[knpmtC][0]);
	  }

	  if(ik>11 && allData[ik+45][0]>0 )
	    {
	      if( walk >-100) hCFD[ik]->Fill(allData[ik+45][0] - walk);
	      hQT1[ik]->Fill(chargeQT1[ik]);
	       if (allData[56+knpmtA][0]>0)
		 hCFD1minCFD[ik]->Fill(allData[ik+45][0]-allData[56+knpmtA][0]);
	    }
	  if(ik<12 && allData[ik+1][0]==0 && adc>0 ) hPed[ik]->Fill(adc);
	  if(ik>11 && allData[ik+45][0]==0 && adc>0 ) hPed[ik]->Fill(adc);

	}

     delete start;
     start = 0x0;
     delete reader;
     reader= 0x0;
      // End of fill histograms

    }

    /* free resources */
    free(event);

    /* exit when last event received, no need to wait for TERM signal */
    if (eventT==END_OF_RUN) {
      printf("EOR event detected\n");
      printf("Number of events processed - %i\n ",iev);
      break;
    }
  }
  printf("After loop, before writing histos\n");
  // write a file with the histograms

  TFile hist(FILE_OUT,"RECREATE");

  for(Int_t j=0;j<24;j++){
    hCFD1minCFD[j]->SetDirectory(&hist);
    hCFD1minCFD[j]->Write();
    hCFD[j]->Write();
    hQT1[j]->Write();
    hPed[j]->Write();
  }
  hVertex->Write();
  hOrA->Write();
  hOrC->Write();
  hist.Close();
  //delete hist;

  status=0;

  /* export file to FXS */
  if (daqDA_FES_storeFile(FILE_OUT, "PHYSICS")) {
    status=-2;
  }

  return status;
}

<commit_msg>T00Physda read full 226 channels<commit_after>/*
T0 DA for online calibration
Contact: AllaMaevskaya@cern.ch
Run Type: PHYSICS
DA Type: MON
Number of events needed: 10000
Input Files: inPhys.dat, external parameters, T0/Calib/Slewing_Walk
Output Files: daPhys.root, to be exported to the DAQ FXS
Trigger types used: PHYSICS_EVENT

*/

#define FILE_OUT "daPhys.root"
#define FILE_IN "inPhys.dat"
#include <daqDA.h>
#include <event.h>
#include <monitor.h>

#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>

//AliRoot
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliT0RawReader.h>
#include <AliT0CalibWalk.h>
#include <AliCDBManager.h>
#include <AliCDBEntry.h>
//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include "TFile.h"
#include "TKey.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TString.h"
#include "TH1.h"
#include "TMath.h"

/* Main routine
      Arguments:
      1- monitoring data source
*/
int main(int argc, char **argv) {
//int main(){
  int status;

  /* magic line */
  gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
                                        "*",
                                        "TStreamerInfo",
                                        "RIO",
                                        "TStreamerInfo()");

  if(daqDA_DB_getFile(FILE_IN, FILE_IN)){
    printf("Couldn't get input file >>inPhys.dat<< from DAQ_DB !!!\n");
    return -1;
  }

  FILE *inp;
  char c;
  inp = fopen(FILE_IN, "r");
  if(!inp){
    printf("Input file >>inPhys.dat<< not found !!!\n");
    return -1;
  }
  int  kcbx, kt0bx, knpmtA, knpmtC,kcfdbx;
  float kclx,kcmx, kt0lx, kt0hx, kcfdlx, kcfdhx;

  while((c=getc(inp))!=EOF) {
    switch(c) {
    case 'a': {fscanf(inp, "%d", &kcbx ); break;} //N of X bins hCFD1minCFD
    case 'b': {fscanf(inp, "%f", &kclx ); break;} //Low x hCFD1minCFD
    case 'c': {fscanf(inp, "%f", &kcmx ); break;} //High x hCFD1minCFD
    case 'd': {fscanf(inp, "%d", &knpmtC ); break;} //number of reference PMTC
    case 'e': {fscanf(inp, "%d", &knpmtA ); break;} //number of reference PMTA
    case 'f': {fscanf(inp, "%d", &kcfdbx ); break;} //N of X bins hCFD&OR
    case 'g': {fscanf(inp, "%f", &kcfdlx ); break;} //Low x  hCFD&OR
    case 'k': {fscanf(inp, "%f", &kcfdhx ); break;} //High x  hCFD&OR
    case 'm': {fscanf(inp, "%d", &kt0bx ); break;} //N of X bins TVDC
    case 'n': {fscanf(inp, "%f", &kt0lx ); break;} //Low x  TVDC
    case 'q': {fscanf(inp, "%f", &kt0hx ); break;} //High x  TVDC
    }
  }
  fclose(inp);

  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
    printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  /* log start of process */
  printf("T0 monitoring program started\n");

  // Get run number
  if (getenv("DATE_RUN_NUMBER")==0) {
    printf("DATE_RUN_NUMBER not properly set.\n");
    return -1;
  }
  int runNr = atoi(getenv("DATE_RUN_NUMBER"));

 // Get the necessary OCDB files from the DAQ detector DB
  if (gSystem->AccessPathName("localOCDB/T0/Calib/Slewing_Walk/",kFileExists)) {
    if (gSystem->mkdir("localOCDB/T0/Calib/Slewing_Walk/",kTRUE) != 0) {
      printf("Failed to create directory: localOCDB/T0/Calib/Slewing_Walk/");
      return -1;
    }
  }
  status = daqDA_DB_getFile("T0/Calib/Slewing_Walk/Run0_999999999_v0_s0.root","localOCDB/T0/Calib/Slewing_Walk/Run0_999999999_v0_s0.root");
  if (status) {
    printf("Failed to get  file T0/Calib/Slewing_Walk() from DAQdetDB, status=%d\n", status);
    return -1;
  }

  TGraph *gr[24]; TGraph *gramp[24];
  AliCDBManager *man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://localOCDB");
  man->SetRun(runNr);
  cout<<" run number "<<runNr<<endl;
  AliCDBEntry *entry = AliCDBManager::Instance()->Get("T0/Calib/Slewing_Walk");
  if(entry) {
    AliT0CalibWalk *fParam = (AliT0CalibWalk*)entry->GetObject();
    for (Int_t i=0; i<24; i++) {
      gr[i] = fParam->GetWalk(i);
      gramp[i] = fParam->GetQTC(i);
    }
  }
  Int_t chargeQT0[24], chargeQT1[24];
  Float_t adc ,walk, amp;

  // Allocation of histograms - start

  TH1F *hCFD1minCFD[24];
  TH1F *hCFD[24], *hQT1[24], *hPed[24];

  for(Int_t ic=0; ic<24; ic++) {
    hCFD1minCFD[ic] = new TH1F(Form("CFD1minCFD%d",ic+1),"CFD-CFD",kcbx,kclx,kcmx);
    hCFD[ic] = new TH1F(Form("CFD%d",ic+1),"CFD",kcfdbx,kcfdlx,kcfdhx);
    hQT1[ic] = new TH1F(Form("QT1%d",ic+1),"QT1",kt0bx,kt0lx,kt0hx);
    hPed[ic] = new TH1F(Form("hPed%d",ic+1),"pedestal",500,500,2000);
  }
  TH1F *hVertex = new TH1F("hVertex","TVDC",kt0bx,kt0lx,kt0hx);
  TH1F *hOrA = new TH1F("hOrA","OrA",kcfdbx,kcfdlx,kcfdhx);
  TH1F *hOrC = new TH1F("hOrC","OrC",kcfdbx,kcfdlx,kcfdhx);

   // Allocation of histograms - end

 Int_t iev=0;
  /* main loop (infinite) */
  for(;;) {
    struct eventHeaderStruct *event;
    eventTypeType eventT;

    /* check shutdown condition */
    if (daqDA_checkShutdown()) {break;}

    /* get next event (blocking call until timeout) */
    status=monitorGetEventDynamic((void **)&event);
     if (status==(int)MON_ERR_EOF) {
      printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
    }

    if (status!=0) {
      printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
    }

    /* retry if got no event */
    if (event==NULL) {
      continue;
    }

    /* use event - here, just write event id to result file */
    eventT=event->eventType;

    switch (event->eventType){

    case START_OF_RUN:
      break;

    case END_OF_RUN:
      break;

  case PHYSICS_EVENT:
      //	 	 case CALIBRATION_EVENT: for test
      iev++;

      if(iev==1){
	printf("First event - %i\n",iev);
      }

      // Initalize raw-data reading and decoding
      AliRawReader *reader = new AliRawReaderDate((void*)event);

      // Enable the following two lines in case of real-data
      reader->RequireHeader(kTRUE);
      AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);
      // start->SetPrintout(kFALSE);
      // Read raw data
      Int_t allData[250][5];
      for(Int_t i0=0;i0<250;i0++)
      	for(Int_t j0=0;j0<5;j0++)
	  allData[i0][j0] = 0;

      if(start->Next()){
	for (Int_t i=0; i<226; i++) {
	  for(Int_t iHit=0;iHit<5;iHit++){
	    allData[i][iHit]= start->GetData(i,iHit);
	  }
	}
      }
      if (allData[50][0] == 0)     continue;
      hVertex->Fill(allData[50][0]);
      hOrA->Fill(allData[51][0]);
      hOrC->Fill(allData[52][0]);
      // Fill the histograms
      walk = adc = amp = -999;
      for (Int_t in=0; in<12;  in++)
	{
	  chargeQT0[in]=allData[2*in+25][0];
	  chargeQT1[in]=allData[2*in+26][0];
	}
      for (Int_t in=12; in<24;  in++)
	{
	  chargeQT0[in]=allData[2*in+57][0];
	  chargeQT1[in]=allData[2*in+58][0];
	}
      Float_t time[24];
      Float_t meanShift[24];
      for (Int_t ik = 0; ik<24; ik++)
	{
	  if( ( chargeQT0[ik] - chargeQT1[ik])>0)  {
	    adc = chargeQT0[ik] - chargeQT1[ik];
	    //	cout<<ik <<"  "<<adc<<endl;
	  }
	  if(gr[ik] && adc>0)
	    walk = Int_t(gr[ik]->Eval(Double_t(adc) ) );
	  //	  cout<<ik<<" walk "<<walk<<" "<<allData[ik+1][0]<<endl;
	  if(ik<12 && allData[ik+1][0]>0  ){
	    if( walk >-100) hCFD[ik]->Fill(allData[ik+1][0] - walk);
	    hQT1[ik]->Fill(chargeQT1[ik]);
	    if ( allData[knpmtC][0]>0 )
	      hCFD1minCFD[ik]->Fill(allData[ik+1][0]-allData[knpmtC][0]);
	  }

	  if(ik>11 && allData[ik+45][0]>0 )
	    {
	      if( walk >-100) hCFD[ik]->Fill(allData[ik+45][0] - walk);
	      hQT1[ik]->Fill(chargeQT1[ik]);
	       if (allData[56+knpmtA][0]>0)
		 hCFD1minCFD[ik]->Fill(allData[ik+45][0]-allData[56+knpmtA][0]);
	    }
	  if(ik<12 && allData[ik+1][0]==0 && adc>0 ) hPed[ik]->Fill(adc);
	  if(ik>11 && allData[ik+45][0]==0 && adc>0 ) hPed[ik]->Fill(adc);

	}

     delete start;
     start = 0x0;
     delete reader;
     reader= 0x0;
      // End of fill histograms

    }

    /* free resources */
    free(event);

    /* exit when last event received, no need to wait for TERM signal */
    if (eventT==END_OF_RUN) {
      printf("EOR event detected\n");
      printf("Number of events processed - %i\n ",iev);
      break;
    }
  }
  printf("After loop, before writing histos\n");
  // write a file with the histograms

  TFile hist(FILE_OUT,"RECREATE");

  for(Int_t j=0;j<24;j++){
    hCFD1minCFD[j]->SetDirectory(&hist);
    hCFD1minCFD[j]->Write();
    hCFD[j]->Write();
    hQT1[j]->Write();
    hPed[j]->Write();
  }
  hVertex->Write();
  hOrA->Write();
  hOrC->Write();
  hist.Close();
  //delete hist;

  status=0;

  /* export file to FXS */
  if (daqDA_FES_storeFile(FILE_OUT, "PHYSICS")) {
    status=-2;
  }

  return status;
}

<|endoftext|>


<commit_before>//
//  MSXDSK.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 07/01/2018.
//  Copyright © 2018 Thomas Harte. All rights reserved.
//

#include "MSXDSK.hpp"

#include "Utility/ImplicitSectors.hpp"

namespace {
	static const int sectors_per_track = 9;
	static const int sector_size = 2;
}

using namespace Storage::Disk;

MSXDSK::MSXDSK(const char *file_name) :
	MFMSectorDump(file_name) {
	// The only sanity check here is whether a sensible
	// geometry can be guessed.
	off_t file_size = file_.stats().st_size;
	const off_t track_size = 512*9;

	// Throw if there would seemingly be an incomplete track.
	if(file_size % track_size) throw ErrorNotMSXDSK;

	track_count_ = static_cast<int>(file_size / track_size);
	head_count_ = 1;

	// Throw if too large or too small or too large for single sided and
	// clearly not double sided.
	if(track_count_ < 40) throw ErrorNotMSXDSK;
	if(track_count_ > 82*2) throw ErrorNotMSXDSK;
	if(track_count_ > 82 && track_count_&1) throw ErrorNotMSXDSK;

	// The below effectively prefers the idea of a single-sided 80-track disk
	// to a double-sided 40-track disk. Emulators have to guess.
	if(track_count_ > 82) {
		track_count_ /= 2;
		head_count_ = 2;
	}

	set_geometry(sectors_per_track, sector_size, 1, true);
}

int MSXDSK::get_head_position_count() {
	return track_count_;
}

int MSXDSK::get_head_count() {
	return head_count_;
}

long MSXDSK::get_file_offset_for_position(Track::Address address) {
	return (address.position*2 + address.head) * 512 * 9;
}
<commit_msg>Corrects assumption of double sidedness.<commit_after>//
//  MSXDSK.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 07/01/2018.
//  Copyright © 2018 Thomas Harte. All rights reserved.
//

#include "MSXDSK.hpp"

#include "Utility/ImplicitSectors.hpp"

namespace {
	static const int sectors_per_track = 9;
	static const int sector_size = 2;
}

using namespace Storage::Disk;

MSXDSK::MSXDSK(const char *file_name) :
	MFMSectorDump(file_name) {
	// The only sanity check here is whether a sensible
	// geometry can be guessed.
	off_t file_size = file_.stats().st_size;
	const off_t track_size = 512*9;

	// Throw if there would seemingly be an incomplete track.
	if(file_size % track_size) throw ErrorNotMSXDSK;

	track_count_ = static_cast<int>(file_size / track_size);
	head_count_ = 1;

	// Throw if too large or too small or too large for single sided and
	// clearly not double sided.
	if(track_count_ < 40) throw ErrorNotMSXDSK;
	if(track_count_ > 82*2) throw ErrorNotMSXDSK;
	if(track_count_ > 82 && track_count_&1) throw ErrorNotMSXDSK;

	// The below effectively prefers the idea of a single-sided 80-track disk
	// to a double-sided 40-track disk. Emulators have to guess.
	if(track_count_ > 82) {
		track_count_ /= 2;
		head_count_ = 2;
	}

	set_geometry(sectors_per_track, sector_size, 1, true);
}

int MSXDSK::get_head_position_count() {
	return track_count_;
}

int MSXDSK::get_head_count() {
	return head_count_;
}

long MSXDSK::get_file_offset_for_position(Track::Address address) {
	return (address.position*head_count_ + address.head) * 512 * 9;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <com/sun/star/oooimprovement/XCore.hpp>

#include "oooimprovecore_module.hxx"
#include <com/sun/star/frame/XTerminateListener.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/oooimprovement/XCoreController.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <comphelper/componentmodule.hxx>
#include <comphelper/configurationhelper.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/uieventslogger.hxx>
#include <cppuhelper/implbase3.hxx>
#include <svx/svxdlg.hxx>
#include <vcl/svapp.hxx>
#include <osl/mutex.hxx>
#include <svl/itemset.hxx>
#include <svl/stritem.hxx>
#include <sfx2/app.hxx>
#include <svx/dialogs.hrc>
#include <sfx2/sfxsids.hrc>

using namespace ::com::sun::star::oooimprovement;
using ::com::sun::star::frame::XTerminateListener;
using ::com::sun::star::lang::EventObject;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::lang::XServiceInfo;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::XComponentContext;
using ::com::sun::star::uno::XInterface;
using ::comphelper::UiEventsLogger;
using ::rtl::OUString;

// declaration
namespace oooimprovecore
{
    class Core : public ::cppu::WeakImplHelper3<XCore,XServiceInfo,XTerminateListener>
    {
        public:
            // XServiceInfo - static version
            static OUString SAL_CALL getImplementationName_static();
            static Sequence<OUString> SAL_CALL getSupportedServiceNames_static();
            static Reference<XInterface> Create(const Reference<XComponentContext>& context );

        protected:
            Core(const Reference<XComponentContext>&);
            virtual ~Core();

            // XCore
            virtual sal_Int32 SAL_CALL getSessionLogEventCount() throw(RuntimeException);
            virtual sal_Bool SAL_CALL getUiEventsLoggerEnabled() throw(RuntimeException);
            virtual void SAL_CALL inviteUser() throw(RuntimeException);

            // XServiceInfo
            virtual OUString SAL_CALL getImplementationName() throw(RuntimeException);
            virtual sal_Bool SAL_CALL supportsService(const OUString& service_name) throw(RuntimeException);
            virtual Sequence<OUString> SAL_CALL getSupportedServiceNames() throw(RuntimeException);

            // XTerminateListener
            virtual void SAL_CALL queryTermination(const EventObject&) throw(RuntimeException);
            virtual void SAL_CALL notifyTermination(const EventObject&) throw(RuntimeException);

            // XEventListener
            virtual void SAL_CALL disposing(const EventObject&) throw(RuntimeException);
    };
}

// implementation
namespace oooimprovecore
{

    Core::Core(const Reference<XComponentContext>&)
    { }

    Core::~Core()
    { }

    sal_Int32 SAL_CALL Core::getSessionLogEventCount() throw(RuntimeException)
    { return UiEventsLogger::getSessionLogEventCount(); }

    sal_Bool SAL_CALL Core::getUiEventsLoggerEnabled() throw(RuntimeException)
    { return UiEventsLogger::isEnabled(); }

    void SAL_CALL Core::inviteUser() throw(RuntimeException)
    {
        Reference<XMultiServiceFactory> xServiceFactory = ::comphelper::getProcessServiceFactory();

        OUString help_url;
        Reference<XCoreController> core_c(
            xServiceFactory->createInstance(OUString::createFromAscii("com.sun.star.oooimprovement.CoreController")),
            UNO_QUERY);
        if(core_c.is())
            ::comphelper::ConfigurationHelper::readDirectKey(
                xServiceFactory,
                OUString::createFromAscii("/org.openoffice.Office.OOoImprovement.Settings"),
                OUString::createFromAscii("Participation"),
                OUString::createFromAscii("HelpUrl"),
                ::comphelper::ConfigurationHelper::E_READONLY) >>= help_url;
        else
            help_url = OUString::createFromAscii("http://www.openoffice.org");
        {
            SolarMutexGuard aGuard;
            SfxAllItemSet aSet( SFX_APP()->GetPool() );
            aSet.Put( SfxStringItem( SID_CURRENT_URL, help_url ) );
            SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
            if ( pFact )
            {
                SfxAbstractDialog *pDlg = pFact->CreateSfxDialog( NULL, aSet, 0, RID_SVXPAGE_IMPROVEMENT );
                pDlg->Execute();
                delete pDlg;
            }
        }
    }

    sal_Bool SAL_CALL Core::supportsService(const OUString& service_name) throw(RuntimeException)
    {
        const Sequence<OUString> service_names(getSupportedServiceNames());
        for (sal_Int32 idx = service_names.getLength()-1; idx>=0; --idx)
            if(service_name == service_names[idx]) return sal_True;
        return sal_False;
    }

    OUString SAL_CALL Core::getImplementationName() throw(RuntimeException)
    { return getImplementationName_static(); }

    Sequence<OUString> SAL_CALL Core::getSupportedServiceNames() throw(RuntimeException)
    { return getSupportedServiceNames_static(); }

    OUString SAL_CALL Core::getImplementationName_static()
    { return OUString::createFromAscii("com.sun.star.comp.extensions.oooimprovecore.Core"); }

    Sequence<OUString> SAL_CALL Core::getSupportedServiceNames_static()
    {
        Sequence<OUString> aServiceNames(1);
        aServiceNames[0] = OUString::createFromAscii("com.sun.star.oooimprovement.Core");
        return aServiceNames;
    }

    void Core::queryTermination(const EventObject&) throw(RuntimeException)
    { }

    void Core::notifyTermination(const EventObject&) throw(RuntimeException)
    {
        UiEventsLogger::disposing();
    }

    void Core::disposing(const EventObject&) throw(RuntimeException)
    { }

    Reference<XInterface> Core::Create(const Reference<XComponentContext>& context)
    { return *(new Core(context)); }

    void createRegistryInfo_Core()
    {
        static OAutoRegistration<Core> auto_reg;
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Changing a few more strings to read "LibreOffice" (cherry picked from commit da9762a0da84a061fd2adadfdb51295357d5e270)<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <com/sun/star/oooimprovement/XCore.hpp>

#include "oooimprovecore_module.hxx"
#include <com/sun/star/frame/XTerminateListener.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/oooimprovement/XCoreController.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <comphelper/componentmodule.hxx>
#include <comphelper/configurationhelper.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/uieventslogger.hxx>
#include <cppuhelper/implbase3.hxx>
#include <svx/svxdlg.hxx>
#include <vcl/svapp.hxx>
#include <osl/mutex.hxx>
#include <svl/itemset.hxx>
#include <svl/stritem.hxx>
#include <sfx2/app.hxx>
#include <svx/dialogs.hrc>
#include <sfx2/sfxsids.hrc>

using namespace ::com::sun::star::oooimprovement;
using ::com::sun::star::frame::XTerminateListener;
using ::com::sun::star::lang::EventObject;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::lang::XServiceInfo;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::XComponentContext;
using ::com::sun::star::uno::XInterface;
using ::comphelper::UiEventsLogger;
using ::rtl::OUString;

// declaration
namespace oooimprovecore
{
    class Core : public ::cppu::WeakImplHelper3<XCore,XServiceInfo,XTerminateListener>
    {
        public:
            // XServiceInfo - static version
            static OUString SAL_CALL getImplementationName_static();
            static Sequence<OUString> SAL_CALL getSupportedServiceNames_static();
            static Reference<XInterface> Create(const Reference<XComponentContext>& context );

        protected:
            Core(const Reference<XComponentContext>&);
            virtual ~Core();

            // XCore
            virtual sal_Int32 SAL_CALL getSessionLogEventCount() throw(RuntimeException);
            virtual sal_Bool SAL_CALL getUiEventsLoggerEnabled() throw(RuntimeException);
            virtual void SAL_CALL inviteUser() throw(RuntimeException);

            // XServiceInfo
            virtual OUString SAL_CALL getImplementationName() throw(RuntimeException);
            virtual sal_Bool SAL_CALL supportsService(const OUString& service_name) throw(RuntimeException);
            virtual Sequence<OUString> SAL_CALL getSupportedServiceNames() throw(RuntimeException);

            // XTerminateListener
            virtual void SAL_CALL queryTermination(const EventObject&) throw(RuntimeException);
            virtual void SAL_CALL notifyTermination(const EventObject&) throw(RuntimeException);

            // XEventListener
            virtual void SAL_CALL disposing(const EventObject&) throw(RuntimeException);
    };
}

// implementation
namespace oooimprovecore
{

    Core::Core(const Reference<XComponentContext>&)
    { }

    Core::~Core()
    { }

    sal_Int32 SAL_CALL Core::getSessionLogEventCount() throw(RuntimeException)
    { return UiEventsLogger::getSessionLogEventCount(); }

    sal_Bool SAL_CALL Core::getUiEventsLoggerEnabled() throw(RuntimeException)
    { return UiEventsLogger::isEnabled(); }

    void SAL_CALL Core::inviteUser() throw(RuntimeException)
    {
        Reference<XMultiServiceFactory> xServiceFactory = ::comphelper::getProcessServiceFactory();

        OUString help_url;
        Reference<XCoreController> core_c(
            xServiceFactory->createInstance(OUString::createFromAscii("com.sun.star.oooimprovement.CoreController")),
            UNO_QUERY);
        if(core_c.is())
            ::comphelper::ConfigurationHelper::readDirectKey(
                xServiceFactory,
                OUString::createFromAscii("/org.openoffice.Office.OOoImprovement.Settings"),
                OUString::createFromAscii("Participation"),
                OUString::createFromAscii("HelpUrl"),
                ::comphelper::ConfigurationHelper::E_READONLY) >>= help_url;
        else
            help_url = OUString::createFromAscii("http://www.libreoffice.org");
        {
            SolarMutexGuard aGuard;
            SfxAllItemSet aSet( SFX_APP()->GetPool() );
            aSet.Put( SfxStringItem( SID_CURRENT_URL, help_url ) );
            SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
            if ( pFact )
            {
                SfxAbstractDialog *pDlg = pFact->CreateSfxDialog( NULL, aSet, 0, RID_SVXPAGE_IMPROVEMENT );
                pDlg->Execute();
                delete pDlg;
            }
        }
    }

    sal_Bool SAL_CALL Core::supportsService(const OUString& service_name) throw(RuntimeException)
    {
        const Sequence<OUString> service_names(getSupportedServiceNames());
        for (sal_Int32 idx = service_names.getLength()-1; idx>=0; --idx)
            if(service_name == service_names[idx]) return sal_True;
        return sal_False;
    }

    OUString SAL_CALL Core::getImplementationName() throw(RuntimeException)
    { return getImplementationName_static(); }

    Sequence<OUString> SAL_CALL Core::getSupportedServiceNames() throw(RuntimeException)
    { return getSupportedServiceNames_static(); }

    OUString SAL_CALL Core::getImplementationName_static()
    { return OUString::createFromAscii("com.sun.star.comp.extensions.oooimprovecore.Core"); }

    Sequence<OUString> SAL_CALL Core::getSupportedServiceNames_static()
    {
        Sequence<OUString> aServiceNames(1);
        aServiceNames[0] = OUString::createFromAscii("com.sun.star.oooimprovement.Core");
        return aServiceNames;
    }

    void Core::queryTermination(const EventObject&) throw(RuntimeException)
    { }

    void Core::notifyTermination(const EventObject&) throw(RuntimeException)
    {
        UiEventsLogger::disposing();
    }

    void Core::disposing(const EventObject&) throw(RuntimeException)
    { }

    Reference<XInterface> Core::Create(const Reference<XComponentContext>& context)
    { return *(new Core(context)); }

    void createRegistryInfo_Core()
    {
        static OAutoRegistration<Core> auto_reg;
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>