<commit_before>#ifndef ASSOCATION_H
#define ASSOCATION_H

#include <list>

enum Multiplicity {One, Many, Some};

template <typename T>
class Association
{

public:

    Association(Multiplicity multiplicity_): multiplicity(multiplicity_) {}

    void addAssoc(T* o)
    {
        if (multiplicity != Multiplicity::One || (linkedObjects.size() == 0))
        {
            linkedObjects.push_back(o);
        }
    }

    void removeAssoc(T* o)
    {
        linkedObjects.remove(o);
    }

    T* getOne(bool cond(T*) = []{return true;})
    {
        T* object = nullptr;
        for(T* o : linkedObjects)
        {
            if(cond(o))
            {
                object = o;
            }
        }

        if(object == nullptr)
        {
            //TODO sign error
        }
        return object;
    }

    std::list<T*> getAll()
    {
        return linkedObjects;
    }

private:

    std::list<T*> linkedObjects;
    Multiplicity multiplicity;
};

#endif // ASSOCATION_H
<commit_msg>Created a function to link objects to each other<commit_after>#ifndef ASSOCATION_H
#define ASSOCATION_H

#include <list>

namespace action
{
    template<typename E1, typename E2>
    void link(E1* e1, E2* e2)
    {
        e1->link<E2>(e2);
        e2->link<E1>(e1);
    }
}

enum Multiplicity {One, Many, Some};

template <typename T>
class Association
{

public:

    Association(Multiplicity multiplicity_): multiplicity(multiplicity_) {}

    void addAssoc(T* o)
    {
        if (multiplicity != Multiplicity::One || (linkedObjects.size() == 0))
        {
            linkedObjects.push_back(o);
        }
    }

    void removeAssoc(T* o)
    {
        linkedObjects.remove(o);
    }

    T* getOne(bool cond(T*) = []{return true;})
    {
        T* object = nullptr;
        for(T* o : linkedObjects)
        {
            if(cond(o))
            {
                object = o;
            }
        }

        if(object == nullptr)
        {
            //TODO sign error
        }
        return object;
    }

    std::list<T*> getAll()
    {
        return linkedObjects;
    }

private:

    std::list<T*> linkedObjects;
    Multiplicity multiplicity;
};

#endif // ASSOCATION_H
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

// Qmitk related includes
#include "QmitkPointSetInteractionView.h"
#include "ui_QmitkPointSetInteractionViewControls.h"

#include <berryIWorkbenchWindow.h>
#include <berryISelectionService.h>
#include <QInputDialog>
#include <QLineEdit>
#include <mitkProperties.h>
#include <QmitkPointListWidget.h>
#include <mitkDataNodeObject.h>
#include <mitkDataNodeSelection.h>

QmitkPointSetInteractionView::QmitkPointSetInteractionView( QObject* /*parent*/ )
: m_Controls(0)
{

}

QmitkPointSetInteractionView::~QmitkPointSetInteractionView()
{
}

void QmitkPointSetInteractionView::CreateQtPartControl( QWidget *parent )
{
  m_Controls = new Ui::QmitkPointSetInteractionControls;
  m_Controls->setupUi(parent);
  m_Controls->m_PbAddPointSet->connect( m_Controls->m_PbAddPointSet, SIGNAL( clicked() )
    , this, SLOT( OnAddPointSetClicked() ) );
}

void QmitkPointSetInteractionView::Activated()
{
  // emulate datamanager selection
  std::vector<mitk::DataNode*> selection = this->GetDataManagerSelection();
  this->OnSelectionChanged( selection );
}

void QmitkPointSetInteractionView::Deactivated()
{
  // emulate empty selection
  std::vector<mitk::DataNode*> selection;
  this->OnSelectionChanged( selection );
  m_Controls->m_PointListWidget->DeactivateInteractor(true);
}

void QmitkPointSetInteractionView::OnAddPointSetClicked()
{
  //Ask for the name of the point set
  bool ok = false;
  QString name = QInputDialog::getText( QApplication::activeWindow()
    , "Add point set...", "Enter name for the new point set", QLineEdit::Normal, "PointSet", &ok );
  if ( ! ok || name.isEmpty() )
    return;

  //
  //Create a new empty pointset
  //
  mitk::PointSet::Pointer pointSet = mitk::PointSet::New();
  //
  // Create a new data tree node
  //
  mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New();
  //
  // fill the data tree node with the appropriate information
  //
  pointSetNode->SetData( pointSet );
  pointSetNode->SetProperty( "name", mitk::StringProperty::New( name.toStdString() ) );
  pointSetNode->SetProperty( "opacity", mitk::FloatProperty::New( 1 ) );
  pointSetNode->SetColor( 1.0, 1.0, 0.0 );
  //
  // add the node to the ds
  //
  this->GetDefaultDataStorage()->Add(pointSetNode);

  // make new selection and emulate selection for this
  std::vector<mitk::DataNode*> selection;
  selection.push_back( pointSetNode );
  this->FireNodesSelected( selection );
  this->OnSelectionChanged( selection );
}

void QmitkPointSetInteractionView::OnSelectionChanged(std::vector<mitk::DataNode*> nodes)
{
  mitk::DataNode* selectedNode = 0;
  if(nodes.size() > 0)
    selectedNode = nodes.front();

  mitk::PointSet* pointSet = 0;
  if(selectedNode)
    pointSet = dynamic_cast<mitk::PointSet*> ( selectedNode->GetData() );

  if (pointSet)
  {
    m_SelectedPointSetNode = selectedNode;
    m_Controls->m_CurrentPointSetLabel->setText(QString::fromStdString(selectedNode->GetName()));
    m_Controls->m_PointListWidget->SetPointSetNode(selectedNode);
  }
  else
  {
    m_Controls->m_CurrentPointSetLabel->setText("None");
    m_Controls->m_PointListWidget->SetPointSetNode(0);
  }

}

bool QmitkPointSetInteractionView::IsExclusiveFunctionality() const
{
  return true;
}

void QmitkPointSetInteractionView::NodeChanged( const mitk::DataNode* node )
{
  if(node == m_SelectedPointSetNode && m_Controls->m_CurrentPointSetLabel->text().toStdString() != node->GetName())
  {
    m_Controls->m_CurrentPointSetLabel->setText(QString::fromStdString(node->GetName()));
  }
}

void QmitkPointSetInteractionView::StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget )
{
    if(m_Controls)
      m_Controls->m_PointListWidget->SetMultiWidget( &stdMultiWidget );
}

void QmitkPointSetInteractionView::StdMultiWidgetClosed( QmitkStdMultiWidget& /*stdMultiWidget*/ )
{
   if(m_Controls)
      m_Controls->m_PointListWidget->SetMultiWidget( 0 );
}
<commit_msg>update current selection to nullptr if nothing is selected<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

// Qmitk related includes
#include "QmitkPointSetInteractionView.h"
#include "ui_QmitkPointSetInteractionViewControls.h"

#include <berryIWorkbenchWindow.h>
#include <berryISelectionService.h>
#include <QInputDialog>
#include <QLineEdit>
#include <mitkProperties.h>
#include <QmitkPointListWidget.h>
#include <mitkDataNodeObject.h>
#include <mitkDataNodeSelection.h>

QmitkPointSetInteractionView::QmitkPointSetInteractionView( QObject* /*parent*/ )
: m_Controls(0)
{

}

QmitkPointSetInteractionView::~QmitkPointSetInteractionView()
{
}

void QmitkPointSetInteractionView::CreateQtPartControl( QWidget *parent )
{
  m_Controls = new Ui::QmitkPointSetInteractionControls;
  m_Controls->setupUi(parent);
  m_Controls->m_PbAddPointSet->connect( m_Controls->m_PbAddPointSet, SIGNAL( clicked() )
    , this, SLOT( OnAddPointSetClicked() ) );
}

void QmitkPointSetInteractionView::Activated()
{
  // emulate datamanager selection
  std::vector<mitk::DataNode*> selection = this->GetDataManagerSelection();
  this->OnSelectionChanged( selection );
}

void QmitkPointSetInteractionView::Deactivated()
{
  // emulate empty selection
  std::vector<mitk::DataNode*> selection;
  this->OnSelectionChanged( selection );
  m_Controls->m_PointListWidget->DeactivateInteractor(true);
}

void QmitkPointSetInteractionView::OnAddPointSetClicked()
{
  //Ask for the name of the point set
  bool ok = false;
  QString name = QInputDialog::getText( QApplication::activeWindow()
    , "Add point set...", "Enter name for the new point set", QLineEdit::Normal, "PointSet", &ok );
  if ( ! ok || name.isEmpty() )
    return;

  //
  //Create a new empty pointset
  //
  mitk::PointSet::Pointer pointSet = mitk::PointSet::New();
  //
  // Create a new data tree node
  //
  mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New();
  //
  // fill the data tree node with the appropriate information
  //
  pointSetNode->SetData( pointSet );
  pointSetNode->SetProperty( "name", mitk::StringProperty::New( name.toStdString() ) );
  pointSetNode->SetProperty( "opacity", mitk::FloatProperty::New( 1 ) );
  pointSetNode->SetColor( 1.0, 1.0, 0.0 );
  //
  // add the node to the ds
  //
  this->GetDefaultDataStorage()->Add(pointSetNode);

  // make new selection and emulate selection for this
  std::vector<mitk::DataNode*> selection;
  selection.push_back( pointSetNode );
  this->FireNodesSelected( selection );
  this->OnSelectionChanged( selection );
}

void QmitkPointSetInteractionView::OnSelectionChanged(std::vector<mitk::DataNode*> nodes)
{
  mitk::DataNode* selectedNode = 0;
  if(nodes.size() > 0)
    selectedNode = nodes.front();

  mitk::PointSet* pointSet = 0;
  if(selectedNode)
    pointSet = dynamic_cast<mitk::PointSet*> ( selectedNode->GetData() );

  if (pointSet)
  {
    m_SelectedPointSetNode = selectedNode;
    m_Controls->m_CurrentPointSetLabel->setText(QString::fromStdString(selectedNode->GetName()));
    m_Controls->m_PointListWidget->SetPointSetNode(selectedNode);
  }
  else
  {
    m_Controls->m_CurrentPointSetLabel->setText("None");
    m_Controls->m_PointListWidget->SetPointSetNode(nullptr);
    std::vector<mitk::DataNode*> emptyList;
    emptyList.push_back(nullptr);
    this->FireNodesSelected( emptyList );
  }

}

bool QmitkPointSetInteractionView::IsExclusiveFunctionality() const
{
  return true;
}

void QmitkPointSetInteractionView::NodeChanged( const mitk::DataNode* node )
{
  if(node == m_SelectedPointSetNode && m_Controls->m_CurrentPointSetLabel->text().toStdString() != node->GetName())
  {
    m_Controls->m_CurrentPointSetLabel->setText(QString::fromStdString(node->GetName()));
  }
}

void QmitkPointSetInteractionView::StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget )
{
    if(m_Controls)
      m_Controls->m_PointListWidget->SetMultiWidget( &stdMultiWidget );
}

void QmitkPointSetInteractionView::StdMultiWidgetClosed( QmitkStdMultiWidget& /*stdMultiWidget*/ )
{
   if(m_Controls)
      m_Controls->m_PointListWidget->SetMultiWidget( 0 );
}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

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

#include "QmitkVolumeVisualizationView.h"

#include <vtkSmartVolumeMapper.h>

#include <mitkImage.h>

#include <mitkTransferFunction.h>
#include <mitkTransferFunctionInitializer.h>
#include <mitkTransferFunctionProperty.h>

#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateDimension.h>
#include <mitkNodePredicateAnd.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateOr.h>
#include <mitkNodePredicateProperty.h>

#include <mitkProperties.h>

const std::string QmitkVolumeVisualizationView::VIEW_ID = "org.mitk.views.volumevisualization";

enum
{
  DEFAULT_RENDERMODE = 0,
  RAYCAST_RENDERMODE = 1,
  GPU_RENDERMODE = 2
};

QmitkVolumeVisualizationView::QmitkVolumeVisualizationView()
  : QmitkAbstractView()
  , m_Controls(nullptr)
{
}

void QmitkVolumeVisualizationView::SetFocus()
{
  UpdateInterface();
}

void QmitkVolumeVisualizationView::CreateQtPartControl(QWidget* parent)
{
  m_Controls = new Ui::QmitkVolumeVisualizationViewControls;
  m_Controls->setupUi(parent);

  m_Controls->volumeSelectionWidget->SetDataStorage(GetDataStorage());
  m_Controls->volumeSelectionWidget->SetNodePredicate(mitk::NodePredicateAnd::New(
    mitk::TNodePredicateDataType<mitk::Image>::New(),
    mitk::NodePredicateOr::New(mitk::NodePredicateDimension::New(3), mitk::NodePredicateDimension::New(4)),
    mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))));
  m_Controls->volumeSelectionWidget->SetSelectionIsOptional(true);
  m_Controls->volumeSelectionWidget->SetEmptyInfo(QString("Please select a 3D / 4D image volume"));
  m_Controls->volumeSelectionWidget->SetPopUpTitel(QString("Select image volume"));

  // Fill the transfer function presets in the generator widget
  std::vector<std::string> names;
  mitk::TransferFunctionInitializer::GetPresetNames(names);
  for (const auto& name : names)
  {
    m_Controls->transferFunctionGeneratorWidget->AddPreset(QString::fromStdString(name));
  }

  // see enum in vtkSmartVolumeMapper
  m_Controls->renderMode->addItem("Default");
  m_Controls->renderMode->addItem("RayCast");
  m_Controls->renderMode->addItem("GPU");

  // see vtkVolumeMapper::BlendModes
  m_Controls->blendMode->addItem("Comp");
  m_Controls->blendMode->addItem("Max");
  m_Controls->blendMode->addItem("Min");
  m_Controls->blendMode->addItem("Avg");
  m_Controls->blendMode->addItem("Add");

  connect(m_Controls->volumeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged,
    this, &QmitkVolumeVisualizationView::OnCurrentSelectionChanged);
  connect(m_Controls->enableRenderingCB, SIGNAL(toggled(bool)), this, SLOT(OnEnableRendering(bool)));
  connect(m_Controls->renderMode, SIGNAL(activated(int)), this, SLOT(OnRenderMode(int)));
  connect(m_Controls->blendMode, SIGNAL(activated(int)), this, SLOT(OnBlendMode(int)));

  connect(m_Controls->transferFunctionGeneratorWidget, SIGNAL(SignalUpdateCanvas()),
          m_Controls->transferFunctionWidget, SLOT(OnUpdateCanvas()));
  connect(m_Controls->transferFunctionGeneratorWidget, SIGNAL(SignalTransferFunctionModeChanged(int)),
          SLOT(OnMitkInternalPreset(int)));

  m_Controls->enableRenderingCB->setEnabled(false);
  m_Controls->blendMode->setEnabled(false);
  m_Controls->renderMode->setEnabled(false);
  m_Controls->transferFunctionWidget->setEnabled(false);
  m_Controls->transferFunctionGeneratorWidget->setEnabled(false);

  m_Controls->volumeSelectionWidget->SetAutoSelectNewNodes(true);

  this->m_TimePointChangeListener.RenderWindowPartActivated(this->GetRenderWindowPart());
  connect(&m_TimePointChangeListener,
          &QmitkSliceNavigationListener::SelectedTimePointChanged,
          this,
          &QmitkVolumeVisualizationView::OnSelectedTimePointChanged);
}

void QmitkVolumeVisualizationView::RenderWindowPartActivated(mitk::IRenderWindowPart *renderWindowPart)
{
  this->m_TimePointChangeListener.RenderWindowPartActivated(renderWindowPart);
}

void QmitkVolumeVisualizationView::RenderWindowPartDeactivated(mitk::IRenderWindowPart *renderWindowPart)
{
  this->m_TimePointChangeListener.RenderWindowPartDeactivated(renderWindowPart);
}

void QmitkVolumeVisualizationView::OnMitkInternalPreset(int mode)
{
  if (m_SelectedNode.IsExpired())
  {
    return;
  }

  auto node = m_SelectedNode.Lock();
  mitk::TransferFunctionProperty::Pointer transferFuncProp;
  if (node->GetProperty(transferFuncProp, "TransferFunction"))
  {
    // first item is only information
    if (--mode == -1)
      return;

    // -- Creat new TransferFunction
    mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(transferFuncProp->GetValue());
    tfInit->SetTransferFunctionMode(mode);
    RequestRenderWindowUpdate();
    m_Controls->transferFunctionWidget->OnUpdateCanvas();
  }
}

void QmitkVolumeVisualizationView::OnCurrentSelectionChanged(QList<mitk::DataNode::Pointer> nodes)
{
  m_SelectedNode = nullptr;

  if (nodes.empty() || nodes.front().IsNull())
  {
    UpdateInterface();
    return;
  }

  auto selectedNode = nodes.front();
  auto image = dynamic_cast<mitk::Image*>(selectedNode->GetData());
  if (nullptr != image)
  {
    m_SelectedNode = selectedNode;
  }

  UpdateInterface();
}

void QmitkVolumeVisualizationView::OnEnableRendering(bool state)
{
  if (m_SelectedNode.IsExpired())
  {
    return;
  }

  m_SelectedNode.Lock()->SetProperty("volumerendering", mitk::BoolProperty::New(state));
  UpdateInterface();
  RequestRenderWindowUpdate();
}

void QmitkVolumeVisualizationView::OnRenderMode(int mode)
{
  if (m_SelectedNode.IsExpired())
  {
    return;
  }

  auto selectedNode = m_SelectedNode.Lock();

  bool usegpu = false;
  bool useray = false;
  if (DEFAULT_RENDERMODE == mode)
  {
    useray = true;
    usegpu = true;
  }
  else if (GPU_RENDERMODE == mode)
  {
    usegpu = true;
  }
  else if (RAYCAST_RENDERMODE == mode)
  {
    useray = true;
  }

  selectedNode->SetProperty("volumerendering.usegpu", mitk::BoolProperty::New(usegpu));
  selectedNode->SetProperty("volumerendering.useray", mitk::BoolProperty::New(useray));

  RequestRenderWindowUpdate();
}

void QmitkVolumeVisualizationView::OnBlendMode(int mode)
{
  if (m_SelectedNode.IsExpired())
  {
    return;
  }

  auto selectedNode = m_SelectedNode.Lock();

  bool usemip = false;
  if (vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND == mode)
  {
    usemip = true;
  }

  selectedNode->SetProperty("volumerendering.usemip", mitk::BoolProperty::New(usemip));
  selectedNode->SetProperty("volumerendering.blendmode", mitk::IntProperty::New(mode));

  RequestRenderWindowUpdate();
}

void QmitkVolumeVisualizationView::OnSelectedTimePointChanged(const mitk::TimePointType & /*newTimePoint*/)
{
  this->UpdateInterface();
}

void QmitkVolumeVisualizationView::UpdateInterface()
{
  if (m_SelectedNode.IsExpired())
  {
    // turnoff all
    m_Controls->enableRenderingCB->setChecked(false);
    m_Controls->enableRenderingCB->setEnabled(false);

    m_Controls->blendMode->setCurrentIndex(0);
    m_Controls->blendMode->setEnabled(false);

    m_Controls->renderMode->setCurrentIndex(0);
    m_Controls->renderMode->setEnabled(false);

    m_Controls->transferFunctionWidget->SetDataNode(nullptr);
    m_Controls->transferFunctionWidget->setEnabled(false);

    m_Controls->transferFunctionGeneratorWidget->SetDataNode(nullptr);
    m_Controls->transferFunctionGeneratorWidget->setEnabled(false);
    return;
  }

  bool enabled = false;
  auto selectedNode = m_SelectedNode.Lock();

  selectedNode->GetBoolProperty("volumerendering", enabled);
  m_Controls->enableRenderingCB->setEnabled(true);
  m_Controls->enableRenderingCB->setChecked(enabled);

  if (!enabled)
  {
    // turnoff all except volumerendering checkbox
    m_Controls->blendMode->setCurrentIndex(0);
    m_Controls->blendMode->setEnabled(false);

    m_Controls->renderMode->setCurrentIndex(0);
    m_Controls->renderMode->setEnabled(false);

    m_Controls->transferFunctionWidget->SetDataNode(nullptr);
    m_Controls->transferFunctionWidget->setEnabled(false);

    m_Controls->transferFunctionGeneratorWidget->SetDataNode(nullptr);
    m_Controls->transferFunctionGeneratorWidget->setEnabled(false);
    return;
  }

  // otherwise we can activate em all
  m_Controls->blendMode->setEnabled(true);
  m_Controls->renderMode->setEnabled(true);

  // Determine Combo Box mode
  {
    bool usegpu = false;
    bool useray = false;
    bool usemip = false;
    selectedNode->GetBoolProperty("volumerendering.usegpu", usegpu);
    selectedNode->GetBoolProperty("volumerendering.useray", useray);
    selectedNode->GetBoolProperty("volumerendering.usemip", usemip);

    int blendMode;
    if (selectedNode->GetIntProperty("volumerendering.blendmode", blendMode))
      m_Controls->blendMode->setCurrentIndex(blendMode);

    if (usemip)
      m_Controls->blendMode->setCurrentIndex(vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND);

    int mode = DEFAULT_RENDERMODE;

    if (useray)
      mode = RAYCAST_RENDERMODE;
    else if (usegpu)
      mode = GPU_RENDERMODE;

    m_Controls->renderMode->setCurrentIndex(mode);
  }
  auto time = this->GetRenderWindowPart()->GetTimeNavigationController()->GetSelectedTimeStep();
  m_Controls->transferFunctionWidget->SetDataNode(selectedNode, time);
  m_Controls->transferFunctionWidget->setEnabled(true);
  m_Controls->transferFunctionGeneratorWidget->SetDataNode(selectedNode, time);
  m_Controls->transferFunctionGeneratorWidget->setEnabled(true);
}
<commit_msg>undo useless Update call from D564<commit_after>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

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

#include "QmitkVolumeVisualizationView.h"

#include <vtkSmartVolumeMapper.h>

#include <mitkImage.h>

#include <mitkTransferFunction.h>
#include <mitkTransferFunctionInitializer.h>
#include <mitkTransferFunctionProperty.h>

#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateDimension.h>
#include <mitkNodePredicateAnd.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateOr.h>
#include <mitkNodePredicateProperty.h>

#include <mitkProperties.h>

const std::string QmitkVolumeVisualizationView::VIEW_ID = "org.mitk.views.volumevisualization";

enum
{
  DEFAULT_RENDERMODE = 0,
  RAYCAST_RENDERMODE = 1,
  GPU_RENDERMODE = 2
};

QmitkVolumeVisualizationView::QmitkVolumeVisualizationView()
  : QmitkAbstractView()
  , m_Controls(nullptr)
{
}

void QmitkVolumeVisualizationView::SetFocus()
{
}

void QmitkVolumeVisualizationView::CreateQtPartControl(QWidget* parent)
{
  m_Controls = new Ui::QmitkVolumeVisualizationViewControls;
  m_Controls->setupUi(parent);

  m_Controls->volumeSelectionWidget->SetDataStorage(GetDataStorage());
  m_Controls->volumeSelectionWidget->SetNodePredicate(mitk::NodePredicateAnd::New(
    mitk::TNodePredicateDataType<mitk::Image>::New(),
    mitk::NodePredicateOr::New(mitk::NodePredicateDimension::New(3), mitk::NodePredicateDimension::New(4)),
    mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))));
  m_Controls->volumeSelectionWidget->SetSelectionIsOptional(true);
  m_Controls->volumeSelectionWidget->SetEmptyInfo(QString("Please select a 3D / 4D image volume"));
  m_Controls->volumeSelectionWidget->SetPopUpTitel(QString("Select image volume"));

  // Fill the transfer function presets in the generator widget
  std::vector<std::string> names;
  mitk::TransferFunctionInitializer::GetPresetNames(names);
  for (const auto& name : names)
  {
    m_Controls->transferFunctionGeneratorWidget->AddPreset(QString::fromStdString(name));
  }

  // see enum in vtkSmartVolumeMapper
  m_Controls->renderMode->addItem("Default");
  m_Controls->renderMode->addItem("RayCast");
  m_Controls->renderMode->addItem("GPU");

  // see vtkVolumeMapper::BlendModes
  m_Controls->blendMode->addItem("Comp");
  m_Controls->blendMode->addItem("Max");
  m_Controls->blendMode->addItem("Min");
  m_Controls->blendMode->addItem("Avg");
  m_Controls->blendMode->addItem("Add");

  connect(m_Controls->volumeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged,
    this, &QmitkVolumeVisualizationView::OnCurrentSelectionChanged);
  connect(m_Controls->enableRenderingCB, SIGNAL(toggled(bool)), this, SLOT(OnEnableRendering(bool)));
  connect(m_Controls->renderMode, SIGNAL(activated(int)), this, SLOT(OnRenderMode(int)));
  connect(m_Controls->blendMode, SIGNAL(activated(int)), this, SLOT(OnBlendMode(int)));

  connect(m_Controls->transferFunctionGeneratorWidget, SIGNAL(SignalUpdateCanvas()),
          m_Controls->transferFunctionWidget, SLOT(OnUpdateCanvas()));
  connect(m_Controls->transferFunctionGeneratorWidget, SIGNAL(SignalTransferFunctionModeChanged(int)),
          SLOT(OnMitkInternalPreset(int)));

  m_Controls->enableRenderingCB->setEnabled(false);
  m_Controls->blendMode->setEnabled(false);
  m_Controls->renderMode->setEnabled(false);
  m_Controls->transferFunctionWidget->setEnabled(false);
  m_Controls->transferFunctionGeneratorWidget->setEnabled(false);

  m_Controls->volumeSelectionWidget->SetAutoSelectNewNodes(true);

  this->m_TimePointChangeListener.RenderWindowPartActivated(this->GetRenderWindowPart());
  connect(&m_TimePointChangeListener,
          &QmitkSliceNavigationListener::SelectedTimePointChanged,
          this,
          &QmitkVolumeVisualizationView::OnSelectedTimePointChanged);
}

void QmitkVolumeVisualizationView::RenderWindowPartActivated(mitk::IRenderWindowPart *renderWindowPart)
{
  this->m_TimePointChangeListener.RenderWindowPartActivated(renderWindowPart);
}

void QmitkVolumeVisualizationView::RenderWindowPartDeactivated(mitk::IRenderWindowPart *renderWindowPart)
{
  this->m_TimePointChangeListener.RenderWindowPartDeactivated(renderWindowPart);
}

void QmitkVolumeVisualizationView::OnMitkInternalPreset(int mode)
{
  if (m_SelectedNode.IsExpired())
  {
    return;
  }

  auto node = m_SelectedNode.Lock();
  mitk::TransferFunctionProperty::Pointer transferFuncProp;
  if (node->GetProperty(transferFuncProp, "TransferFunction"))
  {
    // first item is only information
    if (--mode == -1)
      return;

    // -- Creat new TransferFunction
    mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(transferFuncProp->GetValue());
    tfInit->SetTransferFunctionMode(mode);
    RequestRenderWindowUpdate();
    m_Controls->transferFunctionWidget->OnUpdateCanvas();
  }
}

void QmitkVolumeVisualizationView::OnCurrentSelectionChanged(QList<mitk::DataNode::Pointer> nodes)
{
  m_SelectedNode = nullptr;

  if (nodes.empty() || nodes.front().IsNull())
  {
    UpdateInterface();
    return;
  }

  auto selectedNode = nodes.front();
  auto image = dynamic_cast<mitk::Image*>(selectedNode->GetData());
  if (nullptr != image)
  {
    m_SelectedNode = selectedNode;
  }

  UpdateInterface();
}

void QmitkVolumeVisualizationView::OnEnableRendering(bool state)
{
  if (m_SelectedNode.IsExpired())
  {
    return;
  }

  m_SelectedNode.Lock()->SetProperty("volumerendering", mitk::BoolProperty::New(state));
  UpdateInterface();
  RequestRenderWindowUpdate();
}

void QmitkVolumeVisualizationView::OnRenderMode(int mode)
{
  if (m_SelectedNode.IsExpired())
  {
    return;
  }

  auto selectedNode = m_SelectedNode.Lock();

  bool usegpu = false;
  bool useray = false;
  if (DEFAULT_RENDERMODE == mode)
  {
    useray = true;
    usegpu = true;
  }
  else if (GPU_RENDERMODE == mode)
  {
    usegpu = true;
  }
  else if (RAYCAST_RENDERMODE == mode)
  {
    useray = true;
  }

  selectedNode->SetProperty("volumerendering.usegpu", mitk::BoolProperty::New(usegpu));
  selectedNode->SetProperty("volumerendering.useray", mitk::BoolProperty::New(useray));

  RequestRenderWindowUpdate();
}

void QmitkVolumeVisualizationView::OnBlendMode(int mode)
{
  if (m_SelectedNode.IsExpired())
  {
    return;
  }

  auto selectedNode = m_SelectedNode.Lock();

  bool usemip = false;
  if (vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND == mode)
  {
    usemip = true;
  }

  selectedNode->SetProperty("volumerendering.usemip", mitk::BoolProperty::New(usemip));
  selectedNode->SetProperty("volumerendering.blendmode", mitk::IntProperty::New(mode));

  RequestRenderWindowUpdate();
}

void QmitkVolumeVisualizationView::OnSelectedTimePointChanged(const mitk::TimePointType & /*newTimePoint*/)
{
  this->UpdateInterface();
}

void QmitkVolumeVisualizationView::UpdateInterface()
{
  if (m_SelectedNode.IsExpired())
  {
    // turnoff all
    m_Controls->enableRenderingCB->setChecked(false);
    m_Controls->enableRenderingCB->setEnabled(false);

    m_Controls->blendMode->setCurrentIndex(0);
    m_Controls->blendMode->setEnabled(false);

    m_Controls->renderMode->setCurrentIndex(0);
    m_Controls->renderMode->setEnabled(false);

    m_Controls->transferFunctionWidget->SetDataNode(nullptr);
    m_Controls->transferFunctionWidget->setEnabled(false);

    m_Controls->transferFunctionGeneratorWidget->SetDataNode(nullptr);
    m_Controls->transferFunctionGeneratorWidget->setEnabled(false);
    return;
  }

  bool enabled = false;
  auto selectedNode = m_SelectedNode.Lock();

  selectedNode->GetBoolProperty("volumerendering", enabled);
  m_Controls->enableRenderingCB->setEnabled(true);
  m_Controls->enableRenderingCB->setChecked(enabled);

  if (!enabled)
  {
    // turnoff all except volumerendering checkbox
    m_Controls->blendMode->setCurrentIndex(0);
    m_Controls->blendMode->setEnabled(false);

    m_Controls->renderMode->setCurrentIndex(0);
    m_Controls->renderMode->setEnabled(false);

    m_Controls->transferFunctionWidget->SetDataNode(nullptr);
    m_Controls->transferFunctionWidget->setEnabled(false);

    m_Controls->transferFunctionGeneratorWidget->SetDataNode(nullptr);
    m_Controls->transferFunctionGeneratorWidget->setEnabled(false);
    return;
  }

  // otherwise we can activate em all
  m_Controls->blendMode->setEnabled(true);
  m_Controls->renderMode->setEnabled(true);

  // Determine Combo Box mode
  {
    bool usegpu = false;
    bool useray = false;
    bool usemip = false;
    selectedNode->GetBoolProperty("volumerendering.usegpu", usegpu);
    selectedNode->GetBoolProperty("volumerendering.useray", useray);
    selectedNode->GetBoolProperty("volumerendering.usemip", usemip);

    int blendMode;
    if (selectedNode->GetIntProperty("volumerendering.blendmode", blendMode))
      m_Controls->blendMode->setCurrentIndex(blendMode);

    if (usemip)
      m_Controls->blendMode->setCurrentIndex(vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND);

    int mode = DEFAULT_RENDERMODE;

    if (useray)
      mode = RAYCAST_RENDERMODE;
    else if (usegpu)
      mode = GPU_RENDERMODE;

    m_Controls->renderMode->setCurrentIndex(mode);
  }
  auto time = this->GetRenderWindowPart()->GetTimeNavigationController()->GetSelectedTimeStep();
  m_Controls->transferFunctionWidget->SetDataNode(selectedNode, time);
  m_Controls->transferFunctionWidget->setEnabled(true);
  m_Controls->transferFunctionGeneratorWidget->SetDataNode(selectedNode, time);
  m_Controls->transferFunctionGeneratorWidget->setEnabled(true);
}
<|endoftext|>


<commit_before>// Copyright 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <stdio.h>
#include "gtest/gtest.h"

GTEST_API_ int main(int argc, char **argv) {
  printf("Running main() from %s\n", __FILE__);
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>supporting MPI tests<commit_after>// Copyright 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <stdio.h>
#include "gtest/gtest.h"
#include <stan/math/prim/arr/functor/mpi_cluster.hpp>

GTEST_API_ int main(int argc, char **argv) {
#ifdef STAN_MPI
   // for MPI testing we test with all workers in listen mode. No
  // output is generated from the workers.
  stan::math::mpi_cluster cluster;
  cluster.listen();
  if (cluster.rank_ != 0)
    return 0;
#endif
  printf("Running main() from %s\n", __FILE__);
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#pragma once

namespace oh {
  namespace helper {

template<typename T>
void Swap(T& a, T& b);
template<typename T>
void ExclusiveAssign(T& a, T expr_a, T& b, T expr_b);

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

template<typename T>
void Swap(T& a, T& b)
{
  ExclusiveAssign(a, b, b, a);
}

/*
 * Evaluate expr_x and assign it to x variable (x is a and b)
 *
 * !Remark: arguments passed to function are eagerly evaluated
 */
template<typename T>
void ExclusiveAssign(T& a, T expr_a, T& b, T expr_b)
{
  a = expr_a;
  b = expr_b;
}

}}
// ~~ oh::helper::
<commit_msg>Adding non-invasive NextToTop for stack function.<commit_after>#pragma once

#include <stack>

namespace oh {
  namespace helper {

template<typename T>
void Swap(T& a, T& b);
template<typename T>
void ExclusiveAssign(T& a, T expr_a, T& b, T expr_b);
template<typename T>
T NextToTop(std::stack<T> stack);

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

template<typename T>
void Swap(T& a, T& b)
{
  ExclusiveAssign(a, b, b, a);
}

/*
 * Evaluate expr_x and assign it to x variable (x is a and b)
 *
 * !Remark: arguments passed to function are eagerly evaluated
 */
template<typename T>
void ExclusiveAssign(T& a, T expr_a, T& b, T expr_b)
{
  a = expr_a;
  b = expr_b;
}

template<typename T>
T NextToTop(std::stack<T> stack) {
  stack.pop();
  return stack.top();
}

}}
// ~~ oh::helper::
<|endoftext|>


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

#include "ChartTypeTemplate.hxx"
#include "StackMode.hxx"

#include "OPropertySet.hxx"
#include "MutexContainer.hxx"

#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif

namespace chart
{

class AreaChartTypeTemplate :
        public MutexContainer,
        public ChartTypeTemplate,
        public ::property::OPropertySet
{
public:
    explicit AreaChartTypeTemplate(
        ::com::sun::star::uno::Reference<
            ::com::sun::star::uno::XComponentContext > const & xContext,
        const ::rtl::OUString & rServiceName,
        StackMode eStackMode,
        sal_Int32 nDim = 2 );
    virtual ~AreaChartTypeTemplate();

    /// XServiceInfo declarations
    APPHELPER_XSERVICEINFO_DECL()

    /// merge XInterface implementations
     DECLARE_XINTERFACE()
    /// merge XTypeProvider implementations
     DECLARE_XTYPEPROVIDER()

protected:
    // ____ OPropertySet ____
    virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const
        throw(::com::sun::star::beans::UnknownPropertyException);
    virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

    // ____ XPropertySet ____
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL
        getPropertySetInfo()
        throw (::com::sun::star::uno::RuntimeException);

    // ____ XChartTypeTemplate ____
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > SAL_CALL
        getChartTypeForNewSeries( const ::com::sun::star::uno::Sequence<
            ::com::sun::star::uno::Reference<
                ::com::sun::star::chart2::XChartType > >& aFormerlyUsedChartTypes )
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL applyStyle(
        const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries,
        ::sal_Int32 nChartTypeGroupIndex,
        ::sal_Int32 nSeriesIndex,
        ::sal_Int32 nSeriesCount )
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL resetStyles(
        const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& xDiagram )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ ChartTypeTemplate ____
    virtual sal_Int32 getDimension() const;
    virtual StackMode getStackMode( sal_Int32 nChartTypeIndex ) const;

private:
    StackMode          m_eStackMode;
    sal_Int32          m_nDim;
};

} //  namespace chart

// CHART_AREACHARTTYPETEMPLATE_HXX
#endif
<commit_msg>INTEGRATION: CWS chart17 (1.6.66); FILE MERGED 2007/11/05 14:02:15 iha 1.6.66.1: #i63857#, #i4039# more flexible placement of data point labels, best fit for pie labels<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AreaChartTypeTemplate.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-23 11:59:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART_AREACHARTTYPETEMPLATE_HXX
#define CHART_AREACHARTTYPETEMPLATE_HXX

#include "ChartTypeTemplate.hxx"
#include "StackMode.hxx"

#include "OPropertySet.hxx"
#include "MutexContainer.hxx"

#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif

namespace chart
{

class AreaChartTypeTemplate :
        public MutexContainer,
        public ChartTypeTemplate,
        public ::property::OPropertySet
{
public:
    explicit AreaChartTypeTemplate(
        ::com::sun::star::uno::Reference<
            ::com::sun::star::uno::XComponentContext > const & xContext,
        const ::rtl::OUString & rServiceName,
        StackMode eStackMode,
        sal_Int32 nDim = 2 );
    virtual ~AreaChartTypeTemplate();

    /// XServiceInfo declarations
    APPHELPER_XSERVICEINFO_DECL()

    /// merge XInterface implementations
     DECLARE_XINTERFACE()
    /// merge XTypeProvider implementations
     DECLARE_XTYPEPROVIDER()

protected:
    // ____ OPropertySet ____
    virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const
        throw(::com::sun::star::beans::UnknownPropertyException);
    virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

    // ____ XPropertySet ____
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL
        getPropertySetInfo()
        throw (::com::sun::star::uno::RuntimeException);

    // ____ XChartTypeTemplate ____
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > SAL_CALL
        getChartTypeForNewSeries( const ::com::sun::star::uno::Sequence<
            ::com::sun::star::uno::Reference<
                ::com::sun::star::chart2::XChartType > >& aFormerlyUsedChartTypes )
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL applyStyle(
        const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries,
        ::sal_Int32 nChartTypeGroupIndex,
        ::sal_Int32 nSeriesIndex,
        ::sal_Int32 nSeriesCount )
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL resetStyles(
        const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& xDiagram )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ ChartTypeTemplate ____
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >
                getChartTypeForIndex( sal_Int32 nChartTypeIndex );
    virtual sal_Int32 getDimension() const;
    virtual StackMode getStackMode( sal_Int32 nChartTypeIndex ) const;

private:
    StackMode          m_eStackMode;
    sal_Int32          m_nDim;
};

} //  namespace chart

// CHART_AREACHARTTYPETEMPLATE_HXX
#endif
<|endoftext|>


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

#include "chrome/browser/chromeos/login/signed_settings_cache.h"

#include <string>

#include "base/base64.h"
#include "base/bind.h"
#include "chrome/browser/chromeos/cros_settings.h"
#include "chrome/browser/chromeos/login/ownership_service.h"
#include "chrome/browser/chromeos/login/ownership_status_checker.h"
#include "chrome/browser/chromeos/login/signed_settings_helper.h"
#include "chrome/browser/policy/proto/device_management_backend.pb.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/pref_names.h"

using content::BrowserThread;

namespace em = enterprise_management;

namespace chromeos {

namespace {

void OnStorePolicyCompleted(SignedSettings::ReturnCode code) {
  if (code != SignedSettings::SUCCESS)
    LOG(ERROR) << "Couldn't save temp store to the policy blob. code: " << code;
  else
    CrosSettings::Get()->ReloadProviders();
}

void FinishFinalize(PrefService* local_state,
                    SignedSettings::ReturnCode code,
                    const em::PolicyFetchResponse& policy) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (code != SignedSettings::SUCCESS) {
    LOG(ERROR) << "Can't finalize temp store error code:" << code;
    return;
  }

  if (local_state) {
    std::string encoded =
        local_state->GetString(prefs::kSignedSettingsCache);
    std::string policy_string;
    if (!base::Base64Decode(encoded, &policy_string)) {
      LOG(WARNING) << "Can't decode policy from base64 on finalizing.";
      return;
    }

    em::PolicyData merging_policy_data;
    if (!merging_policy_data.ParseFromString(policy_string)) {
      LOG(WARNING) << "Can't decode policy from string on finalizing.";
      return;
    }

    em::PolicyFetchResponse policy_envelope = policy;
    DCHECK(policy_envelope.has_policy_data());
    em::PolicyData base_policy_data;
    base_policy_data.ParseFromString(policy_envelope.policy_data());
    // Merge only the policy value as we should never ever rewrite the other
    // fields of the PolicyData protobuf.
    base_policy_data.set_policy_value(merging_policy_data.policy_value());
    policy_envelope.set_policy_data(base_policy_data.SerializeAsString());
    DCHECK(base_policy_data.has_username());
    policy_envelope.clear_policy_data_signature();
    SignedSettingsHelper::Get()->StartStorePolicyOp(
        policy_envelope, base::Bind(&OnStorePolicyCompleted));
  }
}

// Reload the initial policy blob, and if successful apply the settings from
// temp storage, and write them back the blob in FinishFinalize.
void ReloadSignedSettingsAndFinalize(
    PrefService* local_state,
    OwnershipStatusChecker* ownership_checker,
    OwnershipService::Status status,
    bool current_user_is_owner) {
  if (current_user_is_owner) {
    SignedSettingsHelper::Get()->StartRetrievePolicyOp(
        base::Bind(FinishFinalize, local_state));
  }
  delete ownership_checker;
}

}  // namespace

namespace signed_settings_cache {

void RegisterPrefs(PrefService* local_state) {
  local_state->RegisterStringPref(prefs::kSignedSettingsCache,
                                  "invalid",
                                  PrefService::UNSYNCABLE_PREF);
}

bool Store(const em::PolicyData& policy, PrefService* local_state) {
  if (local_state) {
    std::string policy_string = policy.SerializeAsString();
    std::string encoded;
    if (!base::Base64Encode(policy_string, &encoded)) {
      LOG(WARNING) << "Can't encode policy in base64.";
      return false;
    }
    local_state->SetString(prefs::kSignedSettingsCache, encoded);
    return true;
  }
  return false;
}

bool Retrieve(em::PolicyData *policy, PrefService* local_state) {
  if (local_state) {
    std::string encoded =
        local_state->GetString(prefs::kSignedSettingsCache);
    std::string policy_string;
    if (!base::Base64Decode(encoded, &policy_string)) {
      LOG(WARNING) << "Can't decode policy from base64.";
      return false;
    }
    return policy->ParseFromString(policy_string);
  }
  return false;
}

void Finalize(PrefService* local_state) {
  // First we have to make sure the owner is really logged in because the key
  // notification is generated on every cloud policy key rotation too.
  OwnershipStatusChecker* ownership_checker = new OwnershipStatusChecker();
  ownership_checker->Check(base::Bind(&ReloadSignedSettingsAndFinalize,
                                      local_state, ownership_checker));
}

}  // namespace signed_settings_cache

}  // namespace chromeos
<commit_msg>Change the levels of the debug output of the SignedSettingsCache.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/signed_settings_cache.h"

#include <string>

#include "base/base64.h"
#include "base/bind.h"
#include "chrome/browser/chromeos/cros_settings.h"
#include "chrome/browser/chromeos/login/ownership_service.h"
#include "chrome/browser/chromeos/login/ownership_status_checker.h"
#include "chrome/browser/chromeos/login/signed_settings_helper.h"
#include "chrome/browser/policy/proto/device_management_backend.pb.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/pref_names.h"

using content::BrowserThread;

namespace em = enterprise_management;

namespace chromeos {

namespace {

void OnStorePolicyCompleted(SignedSettings::ReturnCode code) {
  if (code != SignedSettings::SUCCESS)
    LOG(ERROR) << "Couldn't save temp store to the policy blob. code: " << code;
  else
    CrosSettings::Get()->ReloadProviders();
}

void FinishFinalize(PrefService* local_state,
                    SignedSettings::ReturnCode code,
                    const em::PolicyFetchResponse& policy) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (code != SignedSettings::SUCCESS) {
    LOG(ERROR) << "Can't finalize temp store error code:" << code;
    return;
  }

  if (local_state) {
    std::string encoded =
        local_state->GetString(prefs::kSignedSettingsCache);
    std::string policy_string;
    if (!base::Base64Decode(encoded, &policy_string)) {
      LOG(ERROR) << "Can't decode policy from base64 on finalizing.";
      return;
    }

    em::PolicyData merging_policy_data;
    if (!merging_policy_data.ParseFromString(policy_string)) {
      LOG(ERROR) << "Can't decode policy from string on finalizing.";
      return;
    }

    em::PolicyFetchResponse policy_envelope = policy;
    DCHECK(policy_envelope.has_policy_data());
    em::PolicyData base_policy_data;
    base_policy_data.ParseFromString(policy_envelope.policy_data());
    // Merge only the policy value as we should never ever rewrite the other
    // fields of the PolicyData protobuf.
    base_policy_data.set_policy_value(merging_policy_data.policy_value());
    policy_envelope.set_policy_data(base_policy_data.SerializeAsString());
    DCHECK(base_policy_data.has_username());
    policy_envelope.clear_policy_data_signature();
    SignedSettingsHelper::Get()->StartStorePolicyOp(
        policy_envelope, base::Bind(&OnStorePolicyCompleted));
  }
}

// Reload the initial policy blob, and if successful apply the settings from
// temp storage, and write them back the blob in FinishFinalize.
void ReloadSignedSettingsAndFinalize(
    PrefService* local_state,
    OwnershipStatusChecker* ownership_checker,
    OwnershipService::Status status,
    bool current_user_is_owner) {
  if (current_user_is_owner) {
    SignedSettingsHelper::Get()->StartRetrievePolicyOp(
        base::Bind(FinishFinalize, local_state));
  }
  delete ownership_checker;
}

}  // namespace

namespace signed_settings_cache {

void RegisterPrefs(PrefService* local_state) {
  local_state->RegisterStringPref(prefs::kSignedSettingsCache,
                                  "invalid",
                                  PrefService::UNSYNCABLE_PREF);
}

bool Store(const em::PolicyData& policy, PrefService* local_state) {
  if (local_state) {
    std::string policy_string = policy.SerializeAsString();
    std::string encoded;
    if (!base::Base64Encode(policy_string, &encoded)) {
      LOG(ERROR) << "Can't encode policy in base64.";
      return false;
    }
    local_state->SetString(prefs::kSignedSettingsCache, encoded);
    return true;
  }
  return false;
}

bool Retrieve(em::PolicyData *policy, PrefService* local_state) {
  if (local_state) {
    std::string encoded =
        local_state->GetString(prefs::kSignedSettingsCache);
    std::string policy_string;
    if (!base::Base64Decode(encoded, &policy_string)) {
      // This is normal and happens on first boot.
      VLOG(1) << "Can't decode policy from base64.";
      return false;
    }
    return policy->ParseFromString(policy_string);
  }
  return false;
}

void Finalize(PrefService* local_state) {
  // First we have to make sure the owner is really logged in because the key
  // notification is generated on every cloud policy key rotation too.
  OwnershipStatusChecker* ownership_checker = new OwnershipStatusChecker();
  ownership_checker->Check(base::Bind(&ReloadSignedSettingsAndFinalize,
                                      local_state, ownership_checker));
}

}  // namespace signed_settings_cache

}  // namespace chromeos
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// CoinVault
//
// signaturedialog.cpp
//
// Copyright (c) 2013-2014 Eric Lombrozo
//
// All Rights Reserved.

#include "signaturedialog.h"

// Models/Views
#include "signaturemodel.h"
#include "signatureview.h"

#include <QLabel>
#include <QVBoxLayout>

SignatureDialog::SignatureDialog(CoinDB::Vault* vault, const bytes_t& txHash, QWidget* parent)
    : QDialog(parent)
{
    resize(QSize(800, 400));

    m_model = new SignatureModel(vault, txHash, this);
    m_model->update();

    m_view = new SignatureView(this);
    m_view->setModel(m_model);
    m_view->update();

    QString sigsNeededCaption = tr("Additional signatures required: ") + QString::number(m_model->getSigsNeeded());
    m_sigsNeededLabel = new QLabel(sigsNeededCaption);

    QVBoxLayout* mainLayout = new QVBoxLayout();
    mainLayout->addWidget(m_sigsNeededLabel);
    mainLayout->addWidget(m_view);
    setLayout(mainLayout);
    setWindowTitle(QString::fromStdString(uchar_vector(txHash).getHex()));
}
<commit_msg>Smaller SignatureDialog<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// CoinVault
//
// signaturedialog.cpp
//
// Copyright (c) 2013-2014 Eric Lombrozo
//
// All Rights Reserved.

#include "signaturedialog.h"

// Models/Views
#include "signaturemodel.h"
#include "signatureview.h"

#include <QLabel>
#include <QVBoxLayout>

SignatureDialog::SignatureDialog(CoinDB::Vault* vault, const bytes_t& txHash, QWidget* parent)
    : QDialog(parent)
{
    resize(QSize(600, 200));

    m_model = new SignatureModel(vault, txHash, this);
    m_model->update();

    m_view = new SignatureView(this);
    m_view->setModel(m_model);
    m_view->update();

    QString sigsNeededCaption = tr("Additional signatures required: ") + QString::number(m_model->getSigsNeeded());
    m_sigsNeededLabel = new QLabel(sigsNeededCaption);

    QVBoxLayout* mainLayout = new QVBoxLayout();
    mainLayout->addWidget(m_sigsNeededLabel);
    mainLayout->addWidget(m_view);
    setLayout(mainLayout);
    setWindowTitle(QString::fromStdString(uchar_vector(txHash).getHex()));
}
<|endoftext|>


<commit_before>#include "limiter.hpp"

Limiter::Limiter(int attack, float release) {
    this->attack = attack;
    this->release = release;

    // set up the attack curve
    attackCurve = new float[attack];
    for (int i=0; i<attack; i++) {
        float fade = 1.0 - ((float)i / (float)attack);
        // apply a power curve to the fade?
        //fade = std::pow(fade, 0.5);
        attackCurve[i] = fade;
    }

    gain = 0.0;
    limitedFrames = 0;
    totalFrames = 0;
}

Limiter::~Limiter() {
    delete[] attackCurve;
}

void Limiter::process(float *data, int64_t frames, int channels, float *lookaheadData, int64_t lookaheadFrames) {
    for (int64_t frame = 0; frame < frames; frame++) {
        totalFrames++;
        // calculate attack
        float max = 0.0;
        for (int64_t ahead = 0; ahead < attack; ahead++) {
            float sample;
            int64_t aheadFrame = frame + ahead;
            if (aheadFrame < frames) {
                for (int channel = 0; channel < channels; channel++) {
                    sample = data[aheadFrame * channels + channel];
                    sample = std::abs(sample * attackCurve[ahead]);
                    if (sample > max) max = sample;
                }
            } else if (lookaheadData && (aheadFrame - frames) < lookaheadFrames) {
                aheadFrame = aheadFrame - frames;
                for (int channel = 0; channel < channels; channel++) {
                    sample = lookaheadData[aheadFrame * channels + channel];
                    sample = std::abs(sample * attackCurve[ahead]);
                    if (sample > max) max = sample;
                }
            }
        }
        float neededGain = -(VtoDB(max) + 0.01);
        if (neededGain < gain) {
            gain = neededGain;
        }
        // apply the gain
        float mult = DBtoV(gain);
        for (int channel = 0; channel < channels; channel++) {
            data[frame * channels + channel] *= mult;
        }
        if (mult < 1.0) limitedFrames++;
        // release
        gain += release;
        if (gain > 0) gain = 0.0;
    }
}
<commit_msg>changed limiter max value<commit_after>#include "limiter.hpp"

Limiter::Limiter(int attack, float release) {
    this->attack = attack;
    this->release = release;

    // set up the attack curve
    attackCurve = new float[attack];
    for (int i=0; i<attack; i++) {
        float fade = 1.0 - ((float)i / (float)attack);
        // apply a power curve to the fade?
        //fade = std::pow(fade, 0.5);
        attackCurve[i] = fade;
    }

    gain = 0.0;
    limitedFrames = 0;
    totalFrames = 0;
}

Limiter::~Limiter() {
    delete[] attackCurve;
}

void Limiter::process(float *data, int64_t frames, int channels, float *lookaheadData, int64_t lookaheadFrames) {
    for (int64_t frame = 0; frame < frames; frame++) {
        totalFrames++;
        // calculate attack
        float max = 0.0;
        for (int64_t ahead = 0; ahead < attack; ahead++) {
            float sample;
            int64_t aheadFrame = frame + ahead;
            if (aheadFrame < frames) {
                for (int channel = 0; channel < channels; channel++) {
                    sample = data[aheadFrame * channels + channel];
                    sample = std::abs(sample * attackCurve[ahead]);
                    if (sample > max) max = sample;
                }
            } else if (lookaheadData && (aheadFrame - frames) < lookaheadFrames) {
                aheadFrame = aheadFrame - frames;
                for (int channel = 0; channel < channels; channel++) {
                    sample = lookaheadData[aheadFrame * channels + channel];
                    sample = std::abs(sample * attackCurve[ahead]);
                    if (sample > max) max = sample;
                }
            }
        }
        float neededGain = -(VtoDB(max) + 0.001);
        if (neededGain < gain) {
            gain = neededGain;
        }
        // apply the gain
        float mult = DBtoV(gain);
        for (int channel = 0; channel < channels; channel++) {
            data[frame * channels + channel] *= mult;
        }
        if (mult < 1.0) limitedFrames++;
        // release
        gain += release;
        if (gain > 0) gain = 0.0;
    }
}
<|endoftext|>


<commit_before>#include "logging.h"

#include "util.h"

#include <fstream>
#include <cstdlib>
#include <stdexcept>
#include <cassert>

namespace logging {

const Level Level::Dbg = Level(1u);
const Level Level::Info = Level(1u << 1);
const Level Level::Warn = Level(1u << 2);
const Level Level::Panic = Level(1u << 3);

//TODO: Should we just coarsely lock every function or do we want to
//device something smart? Probably doesn't matter too much if we do
//the coarse thing?
LogPtr Log::sub(std::string const& name) {
        lock();
        subLoggers[name] = std::make_shared<SubLog>(name, *this);
        subLoggerStates[name] = true;
        unlock();
        return subLoggers[name];
}

bool Log::changeState(std::string const& name, bool val) {
        auto it = subLoggerStates.find(name);
        bool found = it != subLoggerStates.end();
        if (found) {
                it->second = false;
        }
        return found;
}

bool Log::changeState(std::vector<std::string> path, bool val) {
        assert(path.size() > 0);
        if (path.size() == 1) {
                return changeState(path[0], val);
        } else if (path.size() == 2) {
                return changeState(path[1], val);
        } else {
                auto it = subLoggers.find(path.at(1));
                if (it != subLoggers.end()) {
                        auto v = std::vector<std::string>(path.begin() + 1, path.end());
                        return it->second->changeState(v, val);
                }
        }
        return false;
}

bool Log::disable(std::vector<std::string> path) {
        return changeState(path, false);
}

bool Log::enable(std::vector<std::string> path) {
        return changeState(path, true);
}

bool Log::disable(std::string const& name) {
        return changeState(name, false);
}

bool Log::enable(std::string const& name) {
        return changeState(name, true);
}

SubLog::SubLog(std::string name, Log& parent)
        : Log{name}, parent{parent} {}

void SubLog::dbg(int line, std::string file, std::string msg) {
        parent.dbgInternal(line, file, name, msg);
}

void SubLog::info(int line, std::string file, std::string msg) {
        parent.infoInternal(line, file, name, msg);
}

void SubLog::warn(int line, std::string file, std::string msg) {
        parent.warnInternal(line, file, name, msg);
}

void SubLog::panic(int line, std::string file, std::string msg) {
        parent.panicInternal(line, file, name, msg);
}

void SubLog::dbgInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                parent.dbgInternal(line, file, this->name + "/" + name, msg);
        }
}

void SubLog::infoInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                parent.infoInternal(line, file, this->name + "/" + name, msg);
        }
}

void SubLog::warnInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                parent.warnInternal(line, file, this->name + "/" + name, msg);
        }
}

void SubLog::panicInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                parent.panicInternal(line, file, this->name + "/" + name, msg);
        }
}

bool Log::enabled(std::string const& name) {
        auto it = subLoggerStates.find(name);
        if (it != subLoggerStates.end()) {
                return it->second;
        }
        return false;
}

Log::Log(std::string name, std::unique_ptr<Dest>&& dest, Level level /* = Level::Info | Level::Warn | Level::Panic */, bool threaded /* = true */)
        : name{name}, dest{std::move(dest)}, level{level},
          format{"[{severity} ({name})]: {msg}\n"} {}

Log::Log(std::string name, Level level /* = Level::Info | Level::Warn | Level::Panic */, bool threaded /* = true */)
        : Log{name, util::make_unique<StdOutDest>(), level} {}

void Log::setFormat(std::string newFormat) {
        lock();
        format = newFormat;
        unlock();
}

void Log::setLevel(Level newLevel) {
        lock();
        level = newLevel;
        unlock();
}

void Log::dbgInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                doLogInternal(Level::Dbg, line, file, this->name + "/" + name, msg);
        }
}

void Log::infoInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                doLogInternal(Level::Info, line, file, this->name + "/" + name, msg);
        }
}

void Log::warnInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                doLogInternal(Level::Warn, line, file, this->name + "/" + name, msg);
        }
}

void Log::panicInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                doLogInternal(Level::Panic, line, file, this->name + "/" + name, msg);
        }
}

void Log::doLogInternal(Level level, int line, std::string file, std::string name, std::string msg) {
        lock();
        if (dest) {
                dest->write(formatMsg(levelToString(level), name, line, file, msg));
        } else {
                throw Error{"There is no destination available for logging"};
        }
        unlock();
}

std::string Log::levelToString(Level level) {
        if (level.hasLevel(Level::Dbg))   { return "DEBUG  "; }
        if (level.hasLevel(Level::Info))  { return "INFO   "; }
        if (level.hasLevel(Level::Warn))  { return "WARNING"; }
        if (level.hasLevel(Level::Panic)) { return "PANIC  "; }
        throw std::runtime_error{"Unreachable code in Log::levelToString()"};
}

std::string Log::replace(std::string needle, std::string haystack, std::string replacement) {
        std::string res{};
        auto pos = haystack.find(needle);
        if (pos == std::string::npos) {
                return haystack;
        }
        res = haystack.substr(0, pos);
        res += replacement;
        res += haystack.substr(pos + needle.length());
        return res;
}

std::string Log::formatMsg(std::string level, std::string fullName, int line, std::string file, std::string message) {
        std::string res{format};
        res = replace("{file}", res, file);
        res = replace("{line}", res, util::format(line));
        res = replace("{name}", res, fullName);
        res = replace("{severity}", res, level);
        res = replace("{msg}", res, message);
        return res;
}

void Log::dbg(int line, std::string file, std::string msg) {
        doLogInternal(Level::Dbg, line, file, name, msg);
}

void Log::info(int line, std::string file, std::string msg) {
        doLogInternal(Level::Info, line, file, name, msg);
}

void Log::warn(int line, std::string file, std::string msg) {
        doLogInternal(Level::Warn, line, file, name, msg);
}

void Log::panic(int line, std::string file, std::string msg) {
        doLogInternal(Level::Panic, line, file, name, msg);
}

void Log::setDest(std::unique_ptr<Dest>&& newDest) {
        lock();
        dest = std::move(newDest);
        unlock();
}

void Log::lock() {
        if (threaded) {
                mutex.lock();
        }
}

void Log::unlock() {
        if (threaded) {
                mutex.unlock();
        }
}

FileDest::FileDest(std::string fileName) {
        file.open(fileName, std::ios::out | std::ios::app);
        if (!file.is_open()) {
                throw Error{util::format("Can't open `", fileName, "' for writing")};
        }
}

void FileDest::write(std::string message) {
        file << message;
}

// If i've understood https://stackoverflow.com/a/11667596 correctly
// this should be thread safe
Log& Log::root() {
        static Log root{"root"};
        return root;
}

} /* namespace logging */
<commit_msg>Fix compilation error when crosscompiling<commit_after>#include "logging.h"

#include "util.h"

#include <fstream>
#include <cstdlib>
#include <stdexcept>
#include <cassert>

namespace logging {

const Level Level::Dbg = Level(1u);
const Level Level::Info = Level(1u << 1);
const Level Level::Warn = Level(1u << 2);
const Level Level::Panic = Level(1u << 3);

//TODO: Should we just coarsely lock every function or do we want to
//device something smart? Probably doesn't matter too much if we do
//the coarse thing?
LogPtr Log::sub(std::string const& name) {
        lock();
        subLoggers[name] = std::make_shared<SubLog>(name, *this);
        subLoggerStates[name] = true;
        unlock();
        return subLoggers[name];
}

bool Log::changeState(std::string const& name, bool val) {
        auto it = subLoggerStates.find(name);
        bool found = it != subLoggerStates.end();
        if (found) {
                it->second = false;
        }
        return found;
}

bool Log::changeState(std::vector<std::string> path, bool val) {
        assert(path.size() > 0);
        if (path.size() == 1) {
                return changeState(path[0], val);
        } else if (path.size() == 2) {
                return changeState(path[1], val);
        } else {
                auto it = subLoggers.find(path.at(1));
                if (it != subLoggers.end()) {
                        auto v = std::vector<std::string>(path.begin() + 1, path.end());
                        return it->second->changeState(v, val);
                }
        }
        return false;
}

bool Log::disable(std::vector<std::string> path) {
        return changeState(path, false);
}

bool Log::enable(std::vector<std::string> path) {
        return changeState(path, true);
}

bool Log::disable(std::string const& name) {
        return changeState(name, false);
}

bool Log::enable(std::string const& name) {
        return changeState(name, true);
}

SubLog::SubLog(std::string name, Log& parent)
        : Log{name}, parent(parent) {}

void SubLog::dbg(int line, std::string file, std::string msg) {
        parent.dbgInternal(line, file, name, msg);
}

void SubLog::info(int line, std::string file, std::string msg) {
        parent.infoInternal(line, file, name, msg);
}

void SubLog::warn(int line, std::string file, std::string msg) {
        parent.warnInternal(line, file, name, msg);
}

void SubLog::panic(int line, std::string file, std::string msg) {
        parent.panicInternal(line, file, name, msg);
}

void SubLog::dbgInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                parent.dbgInternal(line, file, this->name + "/" + name, msg);
        }
}

void SubLog::infoInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                parent.infoInternal(line, file, this->name + "/" + name, msg);
        }
}

void SubLog::warnInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                parent.warnInternal(line, file, this->name + "/" + name, msg);
        }
}

void SubLog::panicInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                parent.panicInternal(line, file, this->name + "/" + name, msg);
        }
}

bool Log::enabled(std::string const& name) {
        auto it = subLoggerStates.find(name);
        if (it != subLoggerStates.end()) {
                return it->second;
        }
        return false;
}

Log::Log(std::string name, std::unique_ptr<Dest>&& dest, Level level /* = Level::Info | Level::Warn | Level::Panic */, bool threaded /* = true */)
        : name{name}, dest{std::move(dest)}, level{level},
          format{"[{severity} ({name})]: {msg}\n"} {}

Log::Log(std::string name, Level level /* = Level::Info | Level::Warn | Level::Panic */, bool threaded /* = true */)
        : Log{name, util::make_unique<StdOutDest>(), level} {}

void Log::setFormat(std::string newFormat) {
        lock();
        format = newFormat;
        unlock();
}

void Log::setLevel(Level newLevel) {
        lock();
        level = newLevel;
        unlock();
}

void Log::dbgInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                doLogInternal(Level::Dbg, line, file, this->name + "/" + name, msg);
        }
}

void Log::infoInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                doLogInternal(Level::Info, line, file, this->name + "/" + name, msg);
        }
}

void Log::warnInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                doLogInternal(Level::Warn, line, file, this->name + "/" + name, msg);
        }
}

void Log::panicInternal(int line, std::string file, std::string name, std::string msg) {
        if (enabled(name)) {
                doLogInternal(Level::Panic, line, file, this->name + "/" + name, msg);
        }
}

void Log::doLogInternal(Level level, int line, std::string file, std::string name, std::string msg) {
        lock();
        if (dest) {
                dest->write(formatMsg(levelToString(level), name, line, file, msg));
        } else {
                throw Error{"There is no destination available for logging"};
        }
        unlock();
}

std::string Log::levelToString(Level level) {
        if (level.hasLevel(Level::Dbg))   { return "DEBUG  "; }
        if (level.hasLevel(Level::Info))  { return "INFO   "; }
        if (level.hasLevel(Level::Warn))  { return "WARNING"; }
        if (level.hasLevel(Level::Panic)) { return "PANIC  "; }
        throw std::runtime_error{"Unreachable code in Log::levelToString()"};
}

std::string Log::replace(std::string needle, std::string haystack, std::string replacement) {
        std::string res{};
        auto pos = haystack.find(needle);
        if (pos == std::string::npos) {
                return haystack;
        }
        res = haystack.substr(0, pos);
        res += replacement;
        res += haystack.substr(pos + needle.length());
        return res;
}

std::string Log::formatMsg(std::string level, std::string fullName, int line, std::string file, std::string message) {
        std::string res{format};
        res = replace("{file}", res, file);
        res = replace("{line}", res, util::format(line));
        res = replace("{name}", res, fullName);
        res = replace("{severity}", res, level);
        res = replace("{msg}", res, message);
        return res;
}

void Log::dbg(int line, std::string file, std::string msg) {
        doLogInternal(Level::Dbg, line, file, name, msg);
}

void Log::info(int line, std::string file, std::string msg) {
        doLogInternal(Level::Info, line, file, name, msg);
}

void Log::warn(int line, std::string file, std::string msg) {
        doLogInternal(Level::Warn, line, file, name, msg);
}

void Log::panic(int line, std::string file, std::string msg) {
        doLogInternal(Level::Panic, line, file, name, msg);
}

void Log::setDest(std::unique_ptr<Dest>&& newDest) {
        lock();
        dest = std::move(newDest);
        unlock();
}

void Log::lock() {
        if (threaded) {
                mutex.lock();
        }
}

void Log::unlock() {
        if (threaded) {
                mutex.unlock();
        }
}

FileDest::FileDest(std::string fileName) {
        file.open(fileName, std::ios::out | std::ios::app);
        if (!file.is_open()) {
                throw Error{util::format("Can't open `", fileName, "' for writing")};
        }
}

void FileDest::write(std::string message) {
        file << message;
}

// If i've understood https://stackoverflow.com/a/11667596 correctly
// this should be thread safe
Log& Log::root() {
        static Log root{"root"};
        return root;
}

} /* namespace logging */
<|endoftext|>


<commit_before>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*++

Module Name:

    cruntime/misc.cpp

Abstract:

    Implementation of C runtime functions that don't fit anywhere else.

--*/

#include "pal/thread.hpp"
#include "pal/threadsusp.hpp"
#include "pal/palinternal.h"
#include "pal/dbgmsg.h"
#include "pal/misc.h"

#include <errno.h>
/* <stdarg.h> needs to be included after "palinternal.h" to avoid name
   collision for va_start and va_end */
#include <stdarg.h>
#include <time.h>
#include <limits.h>

#if defined(_AMD64_) || defined(_x86_)
#include <xmmintrin.h>
#endif // defined(_AMD64_) || defined(_x86_)
#if defined(_DEBUG)
#include <assert.h>
#endif //defined(_DEBUG)

SET_DEFAULT_DEBUG_CHANNEL(CRT);

using namespace CorUnix;

/*++
Function:
  _gcvt_s

See MSDN doc.
--*/
char *
__cdecl
_gcvt_s( char * buffer, int iSize, double value, int digits )
{
    PERF_ENTRY(_gcvt);
    ENTRY( "_gcvt( value:%f digits=%d, buffer=%p )\n", value, digits, buffer );

    if ( !buffer )
    {
        ERROR( "buffer was an invalid pointer.\n" );
    }

    switch ( digits )
    {
    case 7 :
        /* Fall through */
    case 8 :
        /* Fall through */
    case 15 :
        /* Fall through */
    case 17 :

        sprintf_s( buffer, iSize, "%.*g", digits, value );
        break;

    default :
        ASSERT( "Only the digits 7, 8, 15, and 17 are valid.\n" );
        *buffer = '\0';
    }

    LOGEXIT( "_gcvt returns %p (%s)\n", buffer , buffer );
    PERF_EXIT(_gcvt);
    return buffer;
}

/*++
Function :

    __iscsym

See MSDN for more details.
--*/
int
__cdecl
__iscsym( int c )
{
    PERF_ENTRY(__iscsym);
    ENTRY( "__iscsym( c=%d )\n", c );

    if ( isalnum( c ) || c == '_'  )
    {
        LOGEXIT( "__iscsym returning 1\n" );
        PERF_EXIT(__iscsym);
        return 1;
    }

    LOGEXIT( "__iscsym returning 0\n" );
    PERF_EXIT(__iscsym);
    return 0;
}

/*++

Function :

    PAL_errno

    Returns the address of the errno.

--*/
int * __cdecl PAL_errno( int caller )
{
    int *retval;
    PERF_ENTRY(errno);
    ENTRY( "PAL_errno( void )\n" );
    retval = (INT*)(&errno);
    LOGEXIT("PAL_errno returns %p\n",retval);
    PERF_EXIT(errno);
    return retval;
}

/*++
Function:

    mktime

See MSDN for more details.
--*/

PAL_time_t
__cdecl
PAL_mktime(struct PAL_tm *tm)
{
    time_t result;
    struct tm tmpTm;

    PERF_ENTRY(mktime);
    ENTRY( "mktime( tm=%p )\n",tm );

    /*copy the value of Windows struct into BSD struct*/
    tmpTm.tm_sec = tm->tm_sec;
    tmpTm.tm_min = tm->tm_min;
    tmpTm.tm_hour = tm->tm_hour;
    tmpTm.tm_mday = tm->tm_mday;
    tmpTm.tm_mon  = tm->tm_mon;
    tmpTm.tm_year = tm->tm_year;
    tmpTm.tm_wday = tm->tm_wday;
    tmpTm.tm_yday = tm->tm_yday;
    tmpTm.tm_isdst = tm->tm_isdst;

    result = mktime(&tmpTm);

    LOGEXIT( "mktime returned %#lx\n",result );
    PERF_EXIT(mktime);
    return result;
}

/*++
Function:

   rand

   The difference between the FreeBSD and Windows implementations is the max
   of the return value. in FreeBSD, RAND_MAX is 0x7fffffff and in Windows
   it's 0x7fff.

See MSDN for more details.
--*/
int
__cdecl
PAL_rand(void)
{
    int ret;
    PERF_ENTRY(rand);
    ENTRY("rand(void)\n");

    ret = (rand() % (PAL_RAND_MAX + 1));

    LOGEXIT("rand() returning %d\n", ret);
    PERF_EXIT(rand);
    return ret;
}

/*++
Function:

   time

See MSDN for more details.
--*/
PAL_time_t
__cdecl
PAL_time(PAL_time_t *tloc)
{
    time_t result;

    PERF_ENTRY(time);
    ENTRY( "time( tloc=%p )\n",tloc );

    result = time(tloc);

    LOGEXIT( "time returning %#lx\n",result );
    PERF_EXIT(time);
    return result;
}

PALIMPORT
void __cdecl
PAL_qsort(void *base, size_t nmemb, size_t size,
          int (__cdecl *compar )(const void *, const void *))
{
    PERF_ENTRY(qsort);
    ENTRY("qsort(base=%p, nmemb=%lu, size=%lu, compar=%p\n",
          base,(unsigned long) nmemb,(unsigned long) size, compar);

/* reset ENTRY nesting level back to zero, qsort will invoke app-defined
   callbacks and we want their entry traces... */
#if _ENABLE_DEBUG_MESSAGES_
{
    int old_level;
    old_level = DBG_change_entrylevel(0);
#endif /* _ENABLE_DEBUG_MESSAGES_ */

    qsort(base,nmemb,size,compar);

/* ...and set nesting level back to what it was */
#if _ENABLE_DEBUG_MESSAGES_
    DBG_change_entrylevel(old_level);
}
#endif /* _ENABLE_DEBUG_MESSAGES_ */

    LOGEXIT("qsort returns\n");
    PERF_EXIT(qsort);
}

PALIMPORT
void * __cdecl
PAL_bsearch(const void *key, const void *base, size_t nmemb, size_t size,
            int (__cdecl *compar)(const void *, const void *))
{
    void *retval;

    PERF_ENTRY(bsearch);
    ENTRY("bsearch(key=%p, base=%p, nmemb=%lu, size=%lu, compar=%p\n",
          key, base, (unsigned long) nmemb, (unsigned long) size, compar);

/* reset ENTRY nesting level back to zero, bsearch will invoke app-defined
   callbacks and we want their entry traces... */
#if _ENABLE_DEBUG_MESSAGES_
{
    int old_level;
    old_level = DBG_change_entrylevel(0);
#endif /* _ENABLE_DEBUG_MESSAGES_ */

    retval = bsearch(key,base,nmemb,size,compar);

/* ...and set nesting level back to what it was */
#if _ENABLE_DEBUG_MESSAGES_
    DBG_change_entrylevel(old_level);
}
#endif /* _ENABLE_DEBUG_MESSAGES_ */

    LOGEXIT("bsearch returns %p\n",retval);
    PERF_EXIT(bsearch);
    return retval;
}

#ifdef _AMD64_

PALIMPORT
unsigned int PAL__mm_getcsr(void)
{
    return _mm_getcsr();
}

PALIMPORT
void PAL__mm_setcsr(unsigned int i)
{
    _mm_setcsr(i);
}

#endif // _AMD64_

#if defined(_DEBUG)

/*++
Function:
PAL_memcpy

Overlapping buffer-safe version of memcpy.
See MSDN doc for memcpy
--*/
void *PAL_memcpy (void *dest, const void *src, size_t count)
{
    UINT_PTR x = (UINT_PTR)dest, y = (UINT_PTR)src;
    assert((x + count <= y) || (y + count <= x));

    void *ret;
    #undef memcpy
    ret = memcpy(dest, src, count);
    return ret;
}
#endif //DEBUG
<commit_msg>The RAND_MAX value can vary by platform<commit_after>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*++

Module Name:

    cruntime/misc.cpp

Abstract:

    Implementation of C runtime functions that don't fit anywhere else.

--*/

#include "pal/thread.hpp"
#include "pal/threadsusp.hpp"
#include "pal/palinternal.h"
#include "pal/dbgmsg.h"
#include "pal/misc.h"

#include <errno.h>
/* <stdarg.h> needs to be included after "palinternal.h" to avoid name
   collision for va_start and va_end */
#include <stdarg.h>
#include <time.h>
#include <limits.h>

#if defined(_AMD64_) || defined(_x86_)
#include <xmmintrin.h>
#endif // defined(_AMD64_) || defined(_x86_)
#if defined(_DEBUG)
#include <assert.h>
#endif //defined(_DEBUG)

SET_DEFAULT_DEBUG_CHANNEL(CRT);

using namespace CorUnix;

/*++
Function:
  _gcvt_s

See MSDN doc.
--*/
char *
__cdecl
_gcvt_s( char * buffer, int iSize, double value, int digits )
{
    PERF_ENTRY(_gcvt);
    ENTRY( "_gcvt( value:%f digits=%d, buffer=%p )\n", value, digits, buffer );

    if ( !buffer )
    {
        ERROR( "buffer was an invalid pointer.\n" );
    }

    switch ( digits )
    {
    case 7 :
        /* Fall through */
    case 8 :
        /* Fall through */
    case 15 :
        /* Fall through */
    case 17 :

        sprintf_s( buffer, iSize, "%.*g", digits, value );
        break;

    default :
        ASSERT( "Only the digits 7, 8, 15, and 17 are valid.\n" );
        *buffer = '\0';
    }

    LOGEXIT( "_gcvt returns %p (%s)\n", buffer , buffer );
    PERF_EXIT(_gcvt);
    return buffer;
}

/*++
Function :

    __iscsym

See MSDN for more details.
--*/
int
__cdecl
__iscsym( int c )
{
    PERF_ENTRY(__iscsym);
    ENTRY( "__iscsym( c=%d )\n", c );

    if ( isalnum( c ) || c == '_'  )
    {
        LOGEXIT( "__iscsym returning 1\n" );
        PERF_EXIT(__iscsym);
        return 1;
    }

    LOGEXIT( "__iscsym returning 0\n" );
    PERF_EXIT(__iscsym);
    return 0;
}

/*++

Function :

    PAL_errno

    Returns the address of the errno.

--*/
int * __cdecl PAL_errno( int caller )
{
    int *retval;
    PERF_ENTRY(errno);
    ENTRY( "PAL_errno( void )\n" );
    retval = (INT*)(&errno);
    LOGEXIT("PAL_errno returns %p\n",retval);
    PERF_EXIT(errno);
    return retval;
}

/*++
Function:

    mktime

See MSDN for more details.
--*/

PAL_time_t
__cdecl
PAL_mktime(struct PAL_tm *tm)
{
    time_t result;
    struct tm tmpTm;

    PERF_ENTRY(mktime);
    ENTRY( "mktime( tm=%p )\n",tm );

    /*copy the value of Windows struct into BSD struct*/
    tmpTm.tm_sec = tm->tm_sec;
    tmpTm.tm_min = tm->tm_min;
    tmpTm.tm_hour = tm->tm_hour;
    tmpTm.tm_mday = tm->tm_mday;
    tmpTm.tm_mon  = tm->tm_mon;
    tmpTm.tm_year = tm->tm_year;
    tmpTm.tm_wday = tm->tm_wday;
    tmpTm.tm_yday = tm->tm_yday;
    tmpTm.tm_isdst = tm->tm_isdst;

    result = mktime(&tmpTm);

    LOGEXIT( "mktime returned %#lx\n",result );
    PERF_EXIT(mktime);
    return result;
}

/*++
Function:

   rand

   The RAND_MAX value can vary by platform.

See MSDN for more details.
--*/
int
__cdecl
PAL_rand(void)
{
    int ret;
    PERF_ENTRY(rand);
    ENTRY("rand(void)\n");

    ret = (rand() % (PAL_RAND_MAX + 1));

    LOGEXIT("rand() returning %d\n", ret);
    PERF_EXIT(rand);
    return ret;
}

/*++
Function:

   time

See MSDN for more details.
--*/
PAL_time_t
__cdecl
PAL_time(PAL_time_t *tloc)
{
    time_t result;

    PERF_ENTRY(time);
    ENTRY( "time( tloc=%p )\n",tloc );

    result = time(tloc);

    LOGEXIT( "time returning %#lx\n",result );
    PERF_EXIT(time);
    return result;
}

PALIMPORT
void __cdecl
PAL_qsort(void *base, size_t nmemb, size_t size,
          int (__cdecl *compar )(const void *, const void *))
{
    PERF_ENTRY(qsort);
    ENTRY("qsort(base=%p, nmemb=%lu, size=%lu, compar=%p\n",
          base,(unsigned long) nmemb,(unsigned long) size, compar);

/* reset ENTRY nesting level back to zero, qsort will invoke app-defined
   callbacks and we want their entry traces... */
#if _ENABLE_DEBUG_MESSAGES_
{
    int old_level;
    old_level = DBG_change_entrylevel(0);
#endif /* _ENABLE_DEBUG_MESSAGES_ */

    qsort(base,nmemb,size,compar);

/* ...and set nesting level back to what it was */
#if _ENABLE_DEBUG_MESSAGES_
    DBG_change_entrylevel(old_level);
}
#endif /* _ENABLE_DEBUG_MESSAGES_ */

    LOGEXIT("qsort returns\n");
    PERF_EXIT(qsort);
}

PALIMPORT
void * __cdecl
PAL_bsearch(const void *key, const void *base, size_t nmemb, size_t size,
            int (__cdecl *compar)(const void *, const void *))
{
    void *retval;

    PERF_ENTRY(bsearch);
    ENTRY("bsearch(key=%p, base=%p, nmemb=%lu, size=%lu, compar=%p\n",
          key, base, (unsigned long) nmemb, (unsigned long) size, compar);

/* reset ENTRY nesting level back to zero, bsearch will invoke app-defined
   callbacks and we want their entry traces... */
#if _ENABLE_DEBUG_MESSAGES_
{
    int old_level;
    old_level = DBG_change_entrylevel(0);
#endif /* _ENABLE_DEBUG_MESSAGES_ */

    retval = bsearch(key,base,nmemb,size,compar);

/* ...and set nesting level back to what it was */
#if _ENABLE_DEBUG_MESSAGES_
    DBG_change_entrylevel(old_level);
}
#endif /* _ENABLE_DEBUG_MESSAGES_ */

    LOGEXIT("bsearch returns %p\n",retval);
    PERF_EXIT(bsearch);
    return retval;
}

#ifdef _AMD64_

PALIMPORT
unsigned int PAL__mm_getcsr(void)
{
    return _mm_getcsr();
}

PALIMPORT
void PAL__mm_setcsr(unsigned int i)
{
    _mm_setcsr(i);
}

#endif // _AMD64_

#if defined(_DEBUG)

/*++
Function:
PAL_memcpy

Overlapping buffer-safe version of memcpy.
See MSDN doc for memcpy
--*/
void *PAL_memcpy (void *dest, const void *src, size_t count)
{
    UINT_PTR x = (UINT_PTR)dest, y = (UINT_PTR)src;
    assert((x + count <= y) || (y + count <= x));

    void *ret;
    #undef memcpy
    ret = memcpy(dest, src, count);
    return ret;
}
#endif //DEBUG
<|endoftext|>