<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.

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

#include "QmitkOverlayController.h"

#include "QmitkRenderWindow.h"
#include "QmitkOverlay.h"

#include <QHBoxLayout>
#include <QVBoxLayout>

#include <algorithm>

QmitkOverlayController::QmitkOverlayController( QmitkRenderWindow* rw, mitk::PropertyList* pl )
: QObject(), m_RenderWindow( rw ), m_PropertyList( pl )
{
  if ( m_RenderWindow == NULL )
  {
    MITK_ERROR << "invalid QmitkRenderWindow";
    return;
  }

  connect( rw, SIGNAL( moved() ), this, SLOT( AdjustOverlayPosition() ) );

  this->InitializeOverlayLayout();
  this->AdjustOverlayPosition();
  this->SetOverlayVisibility( true );

  if ( m_PropertyList.IsNull() )
    m_PropertyList = mitk::PropertyList::New();

}

QmitkOverlayController::~QmitkOverlayController()
{
}

void QmitkOverlayController::InitializeOverlayLayout()
{
  // setup widget for each position
  this->InitializeWidget( QmitkOverlay::top_Left );
  this->InitializeWidget( QmitkOverlay::top_Center );
  this->InitializeWidget( QmitkOverlay::top_Right );
  this->InitializeWidget( QmitkOverlay::middle_Left );
  this->InitializeWidget( QmitkOverlay::middle_Right );
  this->InitializeWidget( QmitkOverlay::bottom_Left );
  this->InitializeWidget( QmitkOverlay::bottom_Center );
  this->InitializeWidget( QmitkOverlay::bottom_Right );

}

void QmitkOverlayController::InitializeWidget( QmitkOverlay::DisplayPosition pos )
{
  // create a new QWidget as Tool & FramelessWindowHint
  m_PositionedOverlays[ pos ] = new QWidget( m_RenderWindow, Qt::Tool | Qt::FramelessWindowHint );

  // autoFillBackGround(false) and WA_TranslucentBackground = true are needed to have a translucent background
  // transparency does NOT work under Win-XP 32-Bit --> paint black background

#if !defined(_WIN32) || defined(_WIN64)
  m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_TranslucentBackground, true );
#else
  m_PositionedOverlays[ pos ]->setStyleSheet( "QWidget { background: black }" );
  m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_TranslucentBackground, false );
#endif

  // X11 specific attributes
  m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_X11NetWmWindowTypeUtility, true );

  // mac-specific attributes:
  // making sure overlays are even visible if RenderWindow does not have the focus (not default for Qt::Tool on mac)
  m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_MacAlwaysShowToolWindow, true );
  // testing something
  m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_MacShowFocusRect, false );

  // overlays should not get the focus
  m_PositionedOverlays[ pos ]->setFocusPolicy( Qt::NoFocus );

  // setting the color of the background to transparent - not sure it's needed after the attributes have been set above
  QPalette p = QPalette();
  p.setColor( QPalette::Window, Qt::transparent );
  m_PositionedOverlays[ pos ]->setPalette( p );

  // setting position-specific properties
  switch ( pos )
  {
  case QmitkOverlay::top_Left :
    {
      // adding left-aligned top-to-bottom layout
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::TopToBottom );
      layout->setAlignment( Qt::AlignLeft );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  case QmitkOverlay::top_Center :
    {
      // adding center-aligned top-to-bottom layout
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::TopToBottom );
      layout->setAlignment( Qt::AlignCenter );
      layout->setAlignment( Qt::AlignLeft );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  case QmitkOverlay::top_Right :
    {
      // adding right-aligned top-to-bottom layout
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::TopToBottom );
      layout->setAlignment( Qt::AlignRight );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  case QmitkOverlay::middle_Left :
    {
      // adding left-aligned left-to-right layout
      QHBoxLayout* layout = new QHBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::LeftToRight );
      layout->setAlignment( Qt::AlignLeft );
      layout->setSpacing( 3 );
      break;

    }
  case QmitkOverlay::middle_Right :
    {
      // adding right-aligned right-to-left layout
      QHBoxLayout* layout = new QHBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::RightToLeft );
      layout->setAlignment( Qt::AlignRight );
      layout->setSpacing( 3 );
      break;
    }
  case QmitkOverlay::bottom_Left :
    {
      // adding left-aligned bottom-to-top layout
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::BottomToTop );
      layout->setAlignment( Qt::AlignLeft );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  case QmitkOverlay::bottom_Center :
    {
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::BottomToTop );
      layout->setAlignment( Qt::AlignCenter );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  case QmitkOverlay::bottom_Right :
    {
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::BottomToTop );
      layout->setAlignment( Qt::AlignRight );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  }
}

void QmitkOverlayController::AdjustOverlayPosition()
{
  QWidget* widget;
  QPoint pos;

  // setting position of top-left overlay-container
  pos = m_RenderWindow->mapToGlobal( QPoint(0,0) );
  m_PositionedOverlays[ QmitkOverlay::top_Left ]->move( pos.x(), pos.y() );

  // setting position of top-center overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::top_Center ];
  pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width()/2, 0 ) ) ;
  widget->move( pos.x() - widget->size().width()/2, pos.y() );

  // setting position of top-right overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::top_Right ];
  pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), 0 ) ) ;
  widget->move( pos.x() - widget->size().width(), pos.y() );

  // setting position of middle-left overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::middle_Left ];
  pos = m_RenderWindow->mapToGlobal( QPoint( 0, m_RenderWindow->size().height()/2 ) ) ;
  widget->move( pos.x(), pos.y() - widget->size().height()/2 );

  // setting position of middle-right overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::middle_Right ];
  pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), m_RenderWindow->size().height()/2 ) ) ;
  widget->move( pos.x() - widget->size().width(), pos.y() - widget->size().height()/2 );

  // setting position of bottom-left overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::bottom_Left ];
  pos = m_RenderWindow->mapToGlobal( QPoint( 0, m_RenderWindow->size().height() ) ) ;
  widget->move( pos.x(), pos.y() - widget->size().height() );

  // setting position of bottom-center overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::bottom_Center ];
  pos = m_RenderWindow->mapToGlobal( QPoint(  m_RenderWindow->size().width()/2, m_RenderWindow->size().height() ) ) ;
  widget->move( pos.x() - widget->size().width()/2, pos.y() - widget->size().height() );

  // setting position of bottom-right overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::bottom_Right ];
  pos = m_RenderWindow->mapToGlobal( QPoint(  m_RenderWindow->size().width(), m_RenderWindow->size().height() ) ) ;
  widget->move( pos.x() - widget->size().width(), pos.y() - widget->size().height() );
}

void QmitkOverlayController::SetOverlayVisibility( bool visible )
{
  OverlayPositionMap::iterator overlayIter;
  for ( overlayIter=m_PositionedOverlays.begin(); overlayIter!=m_PositionedOverlays.end(); overlayIter++ )
  {
    if ( visible )
    {
      (overlayIter->second)->show();
    }
    else
    {
      (overlayIter->second)->hide();
    }
  }
}

void QmitkOverlayController::AddOverlay( QmitkOverlay* overlay )
{
  // if no renderwindow has been set, it's not possible to add overlays...
  if ( m_RenderWindow == NULL )
  {
    MITK_ERROR << "invalid QmitkRenderWindow";
    return;
  }

  if ( overlay != NULL )
  {
    // get desired position and layer of the overlay
    QmitkOverlay::DisplayPosition pos = overlay->GetPosition();

    // concatenate local propertyList and propertyList of the RenderingManager
    // local properties have priority as they are not overwritten if preset in both
    m_PropertyList->ConcatenatePropertyList( m_RenderWindow->GetRenderer()->GetRenderingManager()->GetPropertyList(), false );

    // add the overlay to the OverlayContainer in the RenderWindow ...
    overlay->GetWidget()->setParent( m_PositionedOverlays[ pos ] );

    // ... and set it up with the correct properties
    this->UpdateOverlayData( overlay );

    // add overlay to list of all overlays and correctly put it into the layering
    m_AllOverlays.push_back( overlay );
    this->RestackOverlays( pos );

    // make sure the widget containing the added overlay is shown ...
    m_PositionedOverlays[ pos ]->show();
    // ... and reset the position of the widgets
    this->AdjustOverlayPosition();
  }
}

void QmitkOverlayController::UpdateOverlayData( QmitkOverlay* overlay )
{
  overlay->GenerateData( m_PropertyList );
}

void QmitkOverlayController::RemoveOverlay( QmitkOverlay* overlay )
{
  if ( overlay != NULL )
  {
    // get desired position and layer of the overlay
    QmitkOverlay::DisplayPosition pos = overlay->GetPosition();

    OverlayVector::iterator iter = std::find( m_AllOverlays.begin(), m_AllOverlays.end(), overlay );

    if ( iter != m_AllOverlays.end() )
    {
      m_AllOverlays.erase( iter );
      overlay->GetWidget()->setParent( NULL );
      overlay->GetWidget()->hide();

      if ( m_PositionedOverlays[ pos ]->layout()->isEmpty() )
      {
        m_PositionedOverlays[ pos ]->hide();
      }
      else
      {
        this->RestackOverlays( pos );
        // reset the position of the widgets
        this->AdjustOverlayPosition();
      }
    }

    overlay->deleteLater();
  }
}

void QmitkOverlayController::AlignOverlays()
{
  //OverlayVector::iterator overlayIter;

  //for ( overlayIter=m_AllOverlays.begin(); overlayIter!=m_AllOverlays.end(); overlayIter++ )
  //{
  //  int stackLayer = dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ (*overlayIter)->GetPosition() ]->layout() )->isEmpty() ? 0 : layer;
  //  dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ (*overlayIter)->GetPosition() ]->layout() )->addWidget( (*overlayIter)->GetWidget(), stackLayer, Qt::AlignLeft );
  //}
}

void QmitkOverlayController::RestackOverlays( QmitkOverlay::DisplayPosition pos )
{
  OverlayVector::iterator overlayIter;
  QBoxLayout* layout = dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ pos ]->layout() );

  std::sort( m_AllOverlays.begin(), m_AllOverlays.end() );

  for ( overlayIter=m_AllOverlays.begin(); overlayIter!=m_AllOverlays.end(); overlayIter++ )
  {
    // do nothing if the overlay is not in the right position
    if ( (*overlayIter)->GetPosition() != pos )
    {
      continue;
    }

    // determine the desired stacking layer
    // if the overlay-container is empty, simply append the overlay to the list
    // if it's not empty, use the layer of the overlay
    unsigned int layer = (*overlayIter)->GetLayer();
    int stackLayer = 0;
    if ( !layout->isEmpty() )
    {
      stackLayer = layer;
    }

    switch ( pos )
    {
      // same alignment for all lefts, ...
    case QmitkOverlay::top_Left : {}
    case QmitkOverlay::middle_Left : {}
    case QmitkOverlay::bottom_Left :
      {
        layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignLeft );
        break;
      }
      // ... for all centers, ...
    case QmitkOverlay::top_Center : {}
    case QmitkOverlay::bottom_Center :
      {
        layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignCenter );
        break;
      }
      // ... and for all rights
    case QmitkOverlay::top_Right : {}
    case QmitkOverlay::middle_Right : {}
    case QmitkOverlay::bottom_Right :
      {
        layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignRight );
        break;
      }
    }
  }

}

void QmitkOverlayController::UpdateAllOverlays()
{
  foreach( QmitkOverlay* overlay, m_AllOverlays )
  {
    this->UpdateOverlayData( overlay );
  }
}<commit_msg>no longer call show in the AddOverlay method<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.

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

#include "QmitkOverlayController.h"

#include "QmitkRenderWindow.h"
#include "QmitkOverlay.h"

#include <QHBoxLayout>
#include <QVBoxLayout>

#include <algorithm>

QmitkOverlayController::QmitkOverlayController( QmitkRenderWindow* rw, mitk::PropertyList* pl )
: QObject(), m_RenderWindow( rw ), m_PropertyList( pl )
{
  if ( m_RenderWindow == NULL )
  {
    MITK_ERROR << "invalid QmitkRenderWindow";
    return;
  }

  connect( rw, SIGNAL( moved() ), this, SLOT( AdjustOverlayPosition() ) );

  this->InitializeOverlayLayout();
  this->AdjustOverlayPosition();
  this->SetOverlayVisibility( true );

  if ( m_PropertyList.IsNull() )
    m_PropertyList = mitk::PropertyList::New();

}

QmitkOverlayController::~QmitkOverlayController()
{
}

void QmitkOverlayController::InitializeOverlayLayout()
{
  // setup widget for each position
  this->InitializeWidget( QmitkOverlay::top_Left );
  this->InitializeWidget( QmitkOverlay::top_Center );
  this->InitializeWidget( QmitkOverlay::top_Right );
  this->InitializeWidget( QmitkOverlay::middle_Left );
  this->InitializeWidget( QmitkOverlay::middle_Right );
  this->InitializeWidget( QmitkOverlay::bottom_Left );
  this->InitializeWidget( QmitkOverlay::bottom_Center );
  this->InitializeWidget( QmitkOverlay::bottom_Right );

}

void QmitkOverlayController::InitializeWidget( QmitkOverlay::DisplayPosition pos )
{
  // create a new QWidget as Tool & FramelessWindowHint
  m_PositionedOverlays[ pos ] = new QWidget( m_RenderWindow, Qt::Tool | Qt::FramelessWindowHint );

  // autoFillBackGround(false) and WA_TranslucentBackground = true are needed to have a translucent background
  // transparency does NOT work under Win-XP 32-Bit --> paint black background

#if !defined(_WIN32) || defined(_WIN64)
  m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_TranslucentBackground, true );
#else
  m_PositionedOverlays[ pos ]->setStyleSheet( "QWidget { background: black }" );
  m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_TranslucentBackground, false );
#endif

  // X11 specific attributes
  m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_X11NetWmWindowTypeUtility, true );

  // mac-specific attributes:
  // making sure overlays are even visible if RenderWindow does not have the focus (not default for Qt::Tool on mac)
  m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_MacAlwaysShowToolWindow, true );
  // testing something
  m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_MacShowFocusRect, false );

  // overlays should not get the focus
  m_PositionedOverlays[ pos ]->setFocusPolicy( Qt::NoFocus );

  // setting the color of the background to transparent - not sure it's needed after the attributes have been set above
  QPalette p = QPalette();
  p.setColor( QPalette::Window, Qt::transparent );
  m_PositionedOverlays[ pos ]->setPalette( p );

  // setting position-specific properties
  switch ( pos )
  {
  case QmitkOverlay::top_Left :
    {
      // adding left-aligned top-to-bottom layout
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::TopToBottom );
      layout->setAlignment( Qt::AlignLeft );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  case QmitkOverlay::top_Center :
    {
      // adding center-aligned top-to-bottom layout
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::TopToBottom );
      layout->setAlignment( Qt::AlignCenter );
      layout->setAlignment( Qt::AlignLeft );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  case QmitkOverlay::top_Right :
    {
      // adding right-aligned top-to-bottom layout
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::TopToBottom );
      layout->setAlignment( Qt::AlignRight );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  case QmitkOverlay::middle_Left :
    {
      // adding left-aligned left-to-right layout
      QHBoxLayout* layout = new QHBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::LeftToRight );
      layout->setAlignment( Qt::AlignLeft );
      layout->setSpacing( 3 );
      break;

    }
  case QmitkOverlay::middle_Right :
    {
      // adding right-aligned right-to-left layout
      QHBoxLayout* layout = new QHBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::RightToLeft );
      layout->setAlignment( Qt::AlignRight );
      layout->setSpacing( 3 );
      break;
    }
  case QmitkOverlay::bottom_Left :
    {
      // adding left-aligned bottom-to-top layout
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::BottomToTop );
      layout->setAlignment( Qt::AlignLeft );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  case QmitkOverlay::bottom_Center :
    {
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::BottomToTop );
      layout->setAlignment( Qt::AlignCenter );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  case QmitkOverlay::bottom_Right :
    {
      QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] );
      layout->setDirection( QBoxLayout::BottomToTop );
      layout->setAlignment( Qt::AlignRight );
      m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 );
      break;
    }
  }
}

void QmitkOverlayController::AdjustOverlayPosition()
{
  QWidget* widget;
  QPoint pos;

  // setting position of top-left overlay-container
  pos = m_RenderWindow->mapToGlobal( QPoint(0,0) );
  m_PositionedOverlays[ QmitkOverlay::top_Left ]->move( pos.x(), pos.y() );

  // setting position of top-center overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::top_Center ];
  pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width()/2, 0 ) ) ;
  widget->move( pos.x() - widget->size().width()/2, pos.y() );

  // setting position of top-right overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::top_Right ];
  pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), 0 ) ) ;
  widget->move( pos.x() - widget->size().width(), pos.y() );

  // setting position of middle-left overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::middle_Left ];
  pos = m_RenderWindow->mapToGlobal( QPoint( 0, m_RenderWindow->size().height()/2 ) ) ;
  widget->move( pos.x(), pos.y() - widget->size().height()/2 );

  // setting position of middle-right overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::middle_Right ];
  pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), m_RenderWindow->size().height()/2 ) ) ;
  widget->move( pos.x() - widget->size().width(), pos.y() - widget->size().height()/2 );

  // setting position of bottom-left overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::bottom_Left ];
  pos = m_RenderWindow->mapToGlobal( QPoint( 0, m_RenderWindow->size().height() ) ) ;
  widget->move( pos.x(), pos.y() - widget->size().height() );

  // setting position of bottom-center overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::bottom_Center ];
  pos = m_RenderWindow->mapToGlobal( QPoint(  m_RenderWindow->size().width()/2, m_RenderWindow->size().height() ) ) ;
  widget->move( pos.x() - widget->size().width()/2, pos.y() - widget->size().height() );

  // setting position of bottom-right overlay-container
  widget = m_PositionedOverlays[ QmitkOverlay::bottom_Right ];
  pos = m_RenderWindow->mapToGlobal( QPoint(  m_RenderWindow->size().width(), m_RenderWindow->size().height() ) ) ;
  widget->move( pos.x() - widget->size().width(), pos.y() - widget->size().height() );
}

void QmitkOverlayController::SetOverlayVisibility( bool visible )
{
  OverlayPositionMap::iterator overlayIter;
  for ( overlayIter=m_PositionedOverlays.begin(); overlayIter!=m_PositionedOverlays.end(); overlayIter++ )
  {
    if ( visible )
    {
      (overlayIter->second)->show();
    }
    else
    {
      (overlayIter->second)->hide();
    }
  }
}

void QmitkOverlayController::AddOverlay( QmitkOverlay* overlay )
{
  // if no renderwindow has been set, it's not possible to add overlays...
  if ( m_RenderWindow == NULL )
  {
    MITK_ERROR << "invalid QmitkRenderWindow";
    return;
  }

  if ( overlay != NULL )
  {
    // get desired position and layer of the overlay
    QmitkOverlay::DisplayPosition pos = overlay->GetPosition();

    // concatenate local propertyList and propertyList of the RenderingManager
    // local properties have priority as they are not overwritten if preset in both
    m_PropertyList->ConcatenatePropertyList( m_RenderWindow->GetRenderer()->GetRenderingManager()->GetPropertyList(), false );

    // add the overlay to the OverlayContainer in the RenderWindow ...
    overlay->GetWidget()->setParent( m_PositionedOverlays[ pos ] );

    // ... and set it up with the correct properties
    this->UpdateOverlayData( overlay );

    // add overlay to list of all overlays and correctly put it into the layering
    m_AllOverlays.push_back( overlay );
    this->RestackOverlays( pos );

    // ... and reset the position of the widgets
    this->AdjustOverlayPosition();
  }
}

void QmitkOverlayController::UpdateOverlayData( QmitkOverlay* overlay )
{
  overlay->GenerateData( m_PropertyList );
}

void QmitkOverlayController::RemoveOverlay( QmitkOverlay* overlay )
{
  if ( overlay != NULL )
  {
    // get desired position and layer of the overlay
    QmitkOverlay::DisplayPosition pos = overlay->GetPosition();

    OverlayVector::iterator iter = std::find( m_AllOverlays.begin(), m_AllOverlays.end(), overlay );

    if ( iter != m_AllOverlays.end() )
    {
      m_AllOverlays.erase( iter );
      overlay->GetWidget()->setParent( NULL );
      overlay->GetWidget()->hide();

      if ( m_PositionedOverlays[ pos ]->layout()->isEmpty() )
      {
        m_PositionedOverlays[ pos ]->hide();
      }
      else
      {
        this->RestackOverlays( pos );
        // reset the position of the widgets
        this->AdjustOverlayPosition();
      }
    }

    overlay->deleteLater();
  }
}

void QmitkOverlayController::AlignOverlays()
{
  //OverlayVector::iterator overlayIter;

  //for ( overlayIter=m_AllOverlays.begin(); overlayIter!=m_AllOverlays.end(); overlayIter++ )
  //{
  //  int stackLayer = dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ (*overlayIter)->GetPosition() ]->layout() )->isEmpty() ? 0 : layer;
  //  dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ (*overlayIter)->GetPosition() ]->layout() )->addWidget( (*overlayIter)->GetWidget(), stackLayer, Qt::AlignLeft );
  //}
}

void QmitkOverlayController::RestackOverlays( QmitkOverlay::DisplayPosition pos )
{
  OverlayVector::iterator overlayIter;
  QBoxLayout* layout = dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ pos ]->layout() );

  std::sort( m_AllOverlays.begin(), m_AllOverlays.end() );

  for ( overlayIter=m_AllOverlays.begin(); overlayIter!=m_AllOverlays.end(); overlayIter++ )
  {
    // do nothing if the overlay is not in the right position
    if ( (*overlayIter)->GetPosition() != pos )
    {
      continue;
    }

    // determine the desired stacking layer
    // if the overlay-container is empty, simply append the overlay to the list
    // if it's not empty, use the layer of the overlay
    unsigned int layer = (*overlayIter)->GetLayer();
    int stackLayer = 0;
    if ( !layout->isEmpty() )
    {
      stackLayer = layer;
    }

    switch ( pos )
    {
      // same alignment for all lefts, ...
    case QmitkOverlay::top_Left : {}
    case QmitkOverlay::middle_Left : {}
    case QmitkOverlay::bottom_Left :
      {
        layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignLeft );
        break;
      }
      // ... for all centers, ...
    case QmitkOverlay::top_Center : {}
    case QmitkOverlay::bottom_Center :
      {
        layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignCenter );
        break;
      }
      // ... and for all rights
    case QmitkOverlay::top_Right : {}
    case QmitkOverlay::middle_Right : {}
    case QmitkOverlay::bottom_Right :
      {
        layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignRight );
        break;
      }
    }
  }

}

void QmitkOverlayController::UpdateAllOverlays()
{
  foreach( QmitkOverlay* overlay, m_AllOverlays )
  {
    this->UpdateOverlayData( overlay );
  }
}<|endoftext|>


<commit_before>// Copyright 2014 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 "content/browser/android/system_ui_resource_manager_impl.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/debug/trace_event.h"
#include "base/location.h"
#include "base/observer_list.h"
#include "base/threading/worker_pool.h"
#include "cc/resources/ui_resource_bitmap.h"
#include "content/public/browser/android/ui_resource_client_android.h"
#include "content/public/browser/android/ui_resource_provider.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/effects/SkPorterDuff.h"
#include "ui/gfx/android/java_bitmap.h"
#include "ui/gfx/screen.h"

namespace content {
namespace {

SkBitmap CreateOverscrollGlowLBitmap(const gfx::Size& screen_size) {
  const float kSin = 0.5f;    // sin(PI / 6)
  const float kCos = 0.866f;  // cos(PI / 6);

  SkPaint paint;
  paint.setAntiAlias(true);
  paint.setAlpha(0x33);
  paint.setStyle(SkPaint::kFill_Style);

  const float arc_width =
      std::min(screen_size.width(), screen_size.height()) * 0.5f / kSin;
  const float y = kCos * arc_width;
  const float height = arc_width - y;
  gfx::Size bounds(arc_width, height);
  SkRect arc_rect = SkRect::MakeXYWH(
      -arc_width / 2.f, -arc_width - y, arc_width * 2.f, arc_width * 2.f);
  SkBitmap glow_bitmap;
  if (!glow_bitmap.allocPixels(
          SkImageInfo::MakeA8(bounds.width(), bounds.height()))) {
    LOG(FATAL) << " Failed to allocate bitmap of size " << bounds.width() << "x"
               << bounds.height();
  }

  SkCanvas canvas(glow_bitmap);
  canvas.clipRect(SkRect::MakeXYWH(0, 0, bounds.width(), bounds.height()));
  canvas.drawArc(arc_rect, 45, 90, true, paint);
  return glow_bitmap;
}

void LoadBitmap(ui::SystemUIResourceManager::ResourceType type,
                SkBitmap* bitmap_holder,
                const gfx::Size& screen_size) {
  TRACE_EVENT1(
      "browser", "SystemUIResourceManagerImpl::LoadBitmap", "type", type);
  SkBitmap bitmap;
  switch (type) {
    case ui::SystemUIResourceManager::OVERSCROLL_EDGE:
      bitmap = gfx::CreateSkBitmapFromAndroidResource(
          "android:drawable/overscroll_edge", gfx::Size(128, 12));
      break;
    case ui::SystemUIResourceManager::OVERSCROLL_GLOW:
      bitmap = gfx::CreateSkBitmapFromAndroidResource(
          "android:drawable/overscroll_glow", gfx::Size(128, 64));
      break;
    case ui::SystemUIResourceManager::OVERSCROLL_GLOW_L:
      bitmap = CreateOverscrollGlowLBitmap(screen_size);
      break;
  }
  bitmap.setImmutable();
  *bitmap_holder = bitmap;
}

}  // namespace

class SystemUIResourceManagerImpl::Entry
    : public content::UIResourceClientAndroid {
 public:
  explicit Entry(UIResourceProvider* provider) : id_(0), provider_(provider) {
    DCHECK(provider);
  }

  virtual ~Entry() {
    if (id_)
      provider_->DeleteUIResource(id_);
    id_ = 0;
  }

  void SetBitmap(const SkBitmap& bitmap) {
    DCHECK(!bitmap.empty());
    DCHECK(bitmap_.empty());
    DCHECK(!id_);
    bitmap_ = bitmap;
  }

  cc::UIResourceId GetUIResourceId() {
    if (bitmap_.empty())
      return 0;
    if (!id_)
      id_ = provider_->CreateUIResource(this);
    return id_;
  }

  // content::UIResourceClient implementation.
  virtual cc::UIResourceBitmap GetBitmap(cc::UIResourceId uid,
                                         bool resource_lost) OVERRIDE {
    DCHECK(!bitmap_.empty());
    return cc::UIResourceBitmap(bitmap_);
  }

  // content::UIResourceClientAndroid implementation.
  virtual void UIResourceIsInvalid() OVERRIDE { id_ = 0; }

  const SkBitmap& bitmap() const { return bitmap_; }

 private:
  SkBitmap bitmap_;
  cc::UIResourceId id_;
  UIResourceProvider* provider_;

  DISALLOW_COPY_AND_ASSIGN(Entry);
};

SystemUIResourceManagerImpl::SystemUIResourceManagerImpl(
    UIResourceProvider* ui_resource_provider)
    : ui_resource_provider_(ui_resource_provider), weak_factory_(this) {
}

SystemUIResourceManagerImpl::~SystemUIResourceManagerImpl() {
}

void SystemUIResourceManagerImpl::PreloadResource(ResourceType type) {
  GetEntry(type);
}

cc::UIResourceId SystemUIResourceManagerImpl::GetUIResourceId(
    ResourceType type) {
  return GetEntry(type)->GetUIResourceId();
}

SystemUIResourceManagerImpl::Entry* SystemUIResourceManagerImpl::GetEntry(
    ResourceType type) {
  DCHECK_GE(type, RESOURCE_TYPE_FIRST);
  DCHECK_LE(type, RESOURCE_TYPE_LAST);
  if (!resource_map_[type]) {
    resource_map_[type].reset(new Entry(ui_resource_provider_));
    // Lazily build the resource.
    BuildResource(type);
  }
  return resource_map_[type].get();
}

void SystemUIResourceManagerImpl::BuildResource(ResourceType type) {
  DCHECK(GetEntry(type)->bitmap().empty());

  // Instead of blocking the main thread, we post a task to load the bitmap.
  SkBitmap* bitmap = new SkBitmap();
  gfx::Size screen_size =
      gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().GetSizeInPixel();
  base::Closure load_bitmap =
      base::Bind(&LoadBitmap, type, bitmap, screen_size);
  base::Closure finished_load =
      base::Bind(&SystemUIResourceManagerImpl::OnFinishedLoadBitmap,
                 weak_factory_.GetWeakPtr(),
                 type,
                 base::Owned(bitmap));
  base::WorkerPool::PostTaskAndReply(
      FROM_HERE, load_bitmap, finished_load, true);
}

void SystemUIResourceManagerImpl::OnFinishedLoadBitmap(
    ResourceType type,
    SkBitmap* bitmap_holder) {
  DCHECK(bitmap_holder);
  GetEntry(type)->SetBitmap(*bitmap_holder);
}

}  // namespace content
<commit_msg>[Android] Clear backing SkBitmap before rendering the overscroll effect<commit_after>// Copyright 2014 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 "content/browser/android/system_ui_resource_manager_impl.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/debug/trace_event.h"
#include "base/location.h"
#include "base/observer_list.h"
#include "base/threading/worker_pool.h"
#include "cc/resources/ui_resource_bitmap.h"
#include "content/public/browser/android/ui_resource_client_android.h"
#include "content/public/browser/android/ui_resource_provider.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/effects/SkPorterDuff.h"
#include "ui/gfx/android/java_bitmap.h"
#include "ui/gfx/screen.h"

namespace content {
namespace {

SkBitmap CreateOverscrollGlowLBitmap(const gfx::Size& screen_size) {
  const float kSin = 0.5f;    // sin(PI / 6)
  const float kCos = 0.866f;  // cos(PI / 6);

  SkPaint paint;
  paint.setAntiAlias(true);
  paint.setAlpha(0x33);
  paint.setStyle(SkPaint::kFill_Style);

  const float arc_width =
      std::min(screen_size.width(), screen_size.height()) * 0.5f / kSin;
  const float y = kCos * arc_width;
  const float height = arc_width - y;
  gfx::Size bounds(arc_width, height);
  SkRect arc_rect = SkRect::MakeXYWH(
      -arc_width / 2.f, -arc_width - y, arc_width * 2.f, arc_width * 2.f);
  SkBitmap glow_bitmap;
  if (!glow_bitmap.allocPixels(
          SkImageInfo::MakeA8(bounds.width(), bounds.height()))) {
    LOG(FATAL) << " Failed to allocate bitmap of size " << bounds.width() << "x"
               << bounds.height();
  }
  glow_bitmap.eraseColor(SK_ColorTRANSPARENT);

  SkCanvas canvas(glow_bitmap);
  canvas.clipRect(SkRect::MakeXYWH(0, 0, bounds.width(), bounds.height()));
  canvas.drawArc(arc_rect, 45, 90, true, paint);
  return glow_bitmap;
}

void LoadBitmap(ui::SystemUIResourceManager::ResourceType type,
                SkBitmap* bitmap_holder,
                const gfx::Size& screen_size) {
  TRACE_EVENT1(
      "browser", "SystemUIResourceManagerImpl::LoadBitmap", "type", type);
  SkBitmap bitmap;
  switch (type) {
    case ui::SystemUIResourceManager::OVERSCROLL_EDGE:
      bitmap = gfx::CreateSkBitmapFromAndroidResource(
          "android:drawable/overscroll_edge", gfx::Size(128, 12));
      break;
    case ui::SystemUIResourceManager::OVERSCROLL_GLOW:
      bitmap = gfx::CreateSkBitmapFromAndroidResource(
          "android:drawable/overscroll_glow", gfx::Size(128, 64));
      break;
    case ui::SystemUIResourceManager::OVERSCROLL_GLOW_L:
      bitmap = CreateOverscrollGlowLBitmap(screen_size);
      break;
  }
  bitmap.setImmutable();
  *bitmap_holder = bitmap;
}

}  // namespace

class SystemUIResourceManagerImpl::Entry
    : public content::UIResourceClientAndroid {
 public:
  explicit Entry(UIResourceProvider* provider) : id_(0), provider_(provider) {
    DCHECK(provider);
  }

  virtual ~Entry() {
    if (id_)
      provider_->DeleteUIResource(id_);
    id_ = 0;
  }

  void SetBitmap(const SkBitmap& bitmap) {
    DCHECK(!bitmap.empty());
    DCHECK(bitmap_.empty());
    DCHECK(!id_);
    bitmap_ = bitmap;
  }

  cc::UIResourceId GetUIResourceId() {
    if (bitmap_.empty())
      return 0;
    if (!id_)
      id_ = provider_->CreateUIResource(this);
    return id_;
  }

  // content::UIResourceClient implementation.
  virtual cc::UIResourceBitmap GetBitmap(cc::UIResourceId uid,
                                         bool resource_lost) OVERRIDE {
    DCHECK(!bitmap_.empty());
    return cc::UIResourceBitmap(bitmap_);
  }

  // content::UIResourceClientAndroid implementation.
  virtual void UIResourceIsInvalid() OVERRIDE { id_ = 0; }

  const SkBitmap& bitmap() const { return bitmap_; }

 private:
  SkBitmap bitmap_;
  cc::UIResourceId id_;
  UIResourceProvider* provider_;

  DISALLOW_COPY_AND_ASSIGN(Entry);
};

SystemUIResourceManagerImpl::SystemUIResourceManagerImpl(
    UIResourceProvider* ui_resource_provider)
    : ui_resource_provider_(ui_resource_provider), weak_factory_(this) {
}

SystemUIResourceManagerImpl::~SystemUIResourceManagerImpl() {
}

void SystemUIResourceManagerImpl::PreloadResource(ResourceType type) {
  GetEntry(type);
}

cc::UIResourceId SystemUIResourceManagerImpl::GetUIResourceId(
    ResourceType type) {
  return GetEntry(type)->GetUIResourceId();
}

SystemUIResourceManagerImpl::Entry* SystemUIResourceManagerImpl::GetEntry(
    ResourceType type) {
  DCHECK_GE(type, RESOURCE_TYPE_FIRST);
  DCHECK_LE(type, RESOURCE_TYPE_LAST);
  if (!resource_map_[type]) {
    resource_map_[type].reset(new Entry(ui_resource_provider_));
    // Lazily build the resource.
    BuildResource(type);
  }
  return resource_map_[type].get();
}

void SystemUIResourceManagerImpl::BuildResource(ResourceType type) {
  DCHECK(GetEntry(type)->bitmap().empty());

  // Instead of blocking the main thread, we post a task to load the bitmap.
  SkBitmap* bitmap = new SkBitmap();
  gfx::Size screen_size =
      gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().GetSizeInPixel();
  base::Closure load_bitmap =
      base::Bind(&LoadBitmap, type, bitmap, screen_size);
  base::Closure finished_load =
      base::Bind(&SystemUIResourceManagerImpl::OnFinishedLoadBitmap,
                 weak_factory_.GetWeakPtr(),
                 type,
                 base::Owned(bitmap));
  base::WorkerPool::PostTaskAndReply(
      FROM_HERE, load_bitmap, finished_load, true);
}

void SystemUIResourceManagerImpl::OnFinishedLoadBitmap(
    ResourceType type,
    SkBitmap* bitmap_holder) {
  DCHECK(bitmap_holder);
  GetEntry(type)->SetBitmap(*bitmap_holder);
}

}  // namespace content
<|endoftext|>


<commit_before>#include "generated/cpp/RhoFileBase.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "common/RhoFile.h"
#include "common/RhoFilePath.h"
#include "logging/RhoLog.h"

namespace rho {

using namespace apiGenerator;
using namespace common;

class CFileSingletonImpl: public CRhoFileSingletonBase
{
public:

    CFileSingletonImpl(): CRhoFileSingletonBase(){}

    virtual void copy( const rho::String& from,  const rho::String& to, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::copyFile(from.c_str(),to.c_str()) );
    }

    virtual void rename( const rho::String& from,  const rho::String& to, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::renameFile(from.c_str(), to.c_str() ) );
    }

    virtual void makeDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::createFolder( path.c_str() ) );
    }

    virtual void exists( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( CRhoFile::isFileExist( path.c_str() ) );
    }

    virtual void getFileSize( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::getFileSize( path.c_str() ) );
    }

    virtual void isDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( CRhoFile::isDirectory( path.c_str() ) );
    }

    virtual void isFile( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( CRhoFile::isFile( path.c_str() ) );
    }

    virtual void deleteFile( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::deleteFile( path.c_str() ) );
    }

    virtual void deleteDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::deleteEmptyFolder( path.c_str() ) );
    }

    virtual void makeDirs( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        CRhoFile::recursiveCreateDir( path.c_str(), "" );
    }

    virtual void deleteRecursive( const rho::String& path,  bool leaveRoot, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::deleteFolder( path.c_str() ) );
    }

    virtual void listDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        Vector<String> entries;
        if (CRhoFile::listFolderEntries(path,entries)) {
            oResult.set(entries);
        }
    }

    virtual void basename( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        CFilePath oPath(path);
        oResult.set( oPath.getBaseName() );
    }

    virtual void dirname( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        CFilePath oPath(path);
        oResult.set( oPath.getFolderName() );

    }

    virtual void join( const rho::String& p1,  const rho::String& p2, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( CFilePath::join(p1,p2) );
    }

    virtual void read( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        String data;
        CRhoFile::loadTextFile( path.c_str(), data );
        oResult.set(data);
    }
};

class CRhoFileImpl : public CRhoFileBase
{
    CRhoFile m_oFile;
public:
    virtual ~CRhoFileImpl() {}

    virtual void open( const rho::String& path,  int mode, rho::apiGenerator::CMethodResult& oResult) {
        m_oFile.open(path.c_str(), (CRhoFile::EOpenModes)mode);
    }

    virtual void close(rho::apiGenerator::CMethodResult& oResult) {
        m_oFile.close();
    }

    virtual void isOpened(rho::apiGenerator::CMethodResult& oResult) {
        oResult.set(m_oFile.isOpened());
    }

    virtual void read( int size, rho::apiGenerator::CMethodResult& oResult) {
        char* buf = 0;
        if ( size > 0 ) {
            buf = new char[size + 1];

            m_oFile.readData((void*)buf,0,size);
            buf[size] = 0;

            String data(buf);
            oResult.set(data);
        } else {
            oResult.set("");
        }
    }

    virtual void readAll(rho::apiGenerator::CMethodResult& oResult) {
        String data;
        m_oFile.readString(data);
        oResult.set(data);

    }

    virtual void write( const rho::String& val, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)m_oFile.write((void*)val.c_str(),val.size()) );
    }

    virtual void flush(rho::apiGenerator::CMethodResult& oResult) {
        m_oFile.flush();
    }

    virtual void seek( int pos, rho::apiGenerator::CMethodResult& oResult) {
        m_oFile.setPosTo(pos);
    }

    virtual void size(rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)m_oFile.size() );
    }

};

////////////////////////////////////////////////////////////////////////

class CRhoFileFactory: public CRhoFileFactoryBase
{
public:
    CRhoFileFactory(){}

    IRhoFileSingleton* createModuleSingleton()
    {
        return new CFileSingletonImpl();
    }

    virtual IRhoFile* createModuleByID(const rho::String& strID){ return new CRhoFileImpl(); };

};

}

extern "C" void Init_RhoFile()
{
    rho::CRhoFileFactory::setInstance( new rho::CRhoFileFactory() );
    rho::Init_RhoFile_API();
}
<commit_msg>coreAPI: create new folder after it was deleted if leaveRoot is set to true; set \0 symbol at actual read position, delete allocated array after read.<commit_after>#include "generated/cpp/RhoFileBase.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "common/RhoFile.h"
#include "common/RhoFilePath.h"
#include "logging/RhoLog.h"

namespace rho {

using namespace apiGenerator;
using namespace common;

class CFileSingletonImpl: public CRhoFileSingletonBase
{
public:

    CFileSingletonImpl(): CRhoFileSingletonBase(){}

    virtual void copy( const rho::String& from,  const rho::String& to, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::copyFile(from.c_str(),to.c_str()) );
    }

    virtual void rename( const rho::String& from,  const rho::String& to, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::renameFile(from.c_str(), to.c_str() ) );
    }

    virtual void makeDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::createFolder( path.c_str() ) );
    }

    virtual void exists( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( CRhoFile::isFileExist( path.c_str() ) );
    }

    virtual void getFileSize( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::getFileSize( path.c_str() ) );
    }

    virtual void isDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( CRhoFile::isDirectory( path.c_str() ) );
    }

    virtual void isFile( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( CRhoFile::isFile( path.c_str() ) );
    }

    virtual void deleteFile( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::deleteFile( path.c_str() ) );
    }

    virtual void deleteDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)CRhoFile::deleteEmptyFolder( path.c_str() ) );
    }

    virtual void makeDirs( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        CRhoFile::recursiveCreateDir( path.c_str(), "" );
    }

    virtual void deleteRecursive( const rho::String& path,  bool leaveRoot, rho::apiGenerator::CMethodResult& oResult) {
        int result = (int)CRhoFile::deleteFolder( path.c_str() );
        if (leaveRoot && result == 0 )
        {
            result = (int)CRhoFile::createFolder( path.c_str() );
        }
        oResult.set( result );
    }

    virtual void listDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        Vector<String> entries;
        if (CRhoFile::listFolderEntries(path,entries)) {
            oResult.set(entries);
        }
    }

    virtual void basename( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        CFilePath oPath(path);
        oResult.set( oPath.getBaseName() );
    }

    virtual void dirname( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        CFilePath oPath(path);
        oResult.set( oPath.getFolderName() );

    }

    virtual void join( const rho::String& p1,  const rho::String& p2, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( CFilePath::join(p1,p2) );
    }

    virtual void read( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) {
        String data;
        CRhoFile::loadTextFile( path.c_str(), data );
        oResult.set(data);
    }
};

class CRhoFileImpl : public CRhoFileBase
{
    CRhoFile m_oFile;
public:
    virtual ~CRhoFileImpl() {}

    virtual void open( const rho::String& path,  int mode, rho::apiGenerator::CMethodResult& oResult) {
        m_oFile.open(path.c_str(), (CRhoFile::EOpenModes)mode);
    }

    virtual void close(rho::apiGenerator::CMethodResult& oResult) {
        m_oFile.close();
    }

    virtual void isOpened(rho::apiGenerator::CMethodResult& oResult) {
        oResult.set(m_oFile.isOpened());
    }

    virtual void read( int size, rho::apiGenerator::CMethodResult& oResult) {
        char* buf = 0;
        if ( size > 0 ) {
            buf = new char[size + 1];
        }
        if (buf)
        {
            int actualsize = m_oFile.readData((void*)buf,0,size);
            buf[actualsize] = 0;

            String data(buf);
            oResult.set(data);
            delete[] buf;
        }
        else {
            oResult.set("");
        }
    }

    virtual void readAll(rho::apiGenerator::CMethodResult& oResult) {
        String data;
        m_oFile.readString(data);
        oResult.set(data);

    }

    virtual void write( const rho::String& val, rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)m_oFile.write((void*)val.c_str(),val.size()) );
    }

    virtual void flush(rho::apiGenerator::CMethodResult& oResult) {
        m_oFile.flush();
    }

    virtual void seek( int pos, rho::apiGenerator::CMethodResult& oResult) {
        m_oFile.setPosTo(pos);
    }

    virtual void size(rho::apiGenerator::CMethodResult& oResult) {
        oResult.set( (int)m_oFile.size() );
    }

};

////////////////////////////////////////////////////////////////////////

class CRhoFileFactory: public CRhoFileFactoryBase
{
public:
    CRhoFileFactory(){}

    IRhoFileSingleton* createModuleSingleton()
    {
        return new CFileSingletonImpl();
    }

    virtual IRhoFile* createModuleByID(const rho::String& strID){ return new CRhoFileImpl(); };

};

}

extern "C" void Init_RhoFile()
{
    rho::CRhoFileFactory::setInstance( new rho::CRhoFileFactory() );
    rho::Init_RhoFile_API();
}
<|endoftext|>


<commit_before><commit_msg>Cleanups<commit_after><|endoftext|>


<commit_before>// Copyright 2008, 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 <windows.h>
#include <string>

#include "base/icu_util.h"

#include "base/logging.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "unicode/udata.h"

namespace icu_util {

bool Initialize() {
  // Assert that we are not called more than once.  Even though calling this
  // function isn't harmful (ICU can handle it), being called twice probably
  // indicates a programming error.
#ifndef DEBUG
  static bool called_once = false;
  DCHECK(!called_once);
  called_once = true;
#endif

  // We expect to find the ICU data module alongside the current module.
  std::wstring data_path;
  PathService::Get(base::DIR_MODULE, &data_path);
  file_util::AppendToPath(&data_path, L"icudt38.dll");

  HMODULE module = LoadLibrary(data_path.c_str());
  if (!module)
    return false;

  FARPROC addr = GetProcAddress(module, "icudt38_dat");
  if (!addr)
    return false;

  UErrorCode err = U_ZERO_ERROR;
  udata_setCommonData(reinterpret_cast<void*>(addr), &err);
  return err == U_ZERO_ERROR;
}

}  // namespace icu_util
<commit_msg>ICU isn't packaged on the Mac as it is on Windows. Review URL: http://chrome-reviews.prom.corp.google.com/1092<commit_after>// Copyright 2008, 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 "build/build_config.h"

#ifdef OS_WIN
#include <windows.h>
#endif

#include <string>

#include "base/icu_util.h"

#include "base/logging.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "unicode/udata.h"

namespace icu_util {

bool Initialize() {
#ifdef OS_WIN
  // Assert that we are not called more than once.  Even though calling this
  // function isn't harmful (ICU can handle it), being called twice probably
  // indicates a programming error.
#ifndef NDEBUG
  static bool called_once = false;
  DCHECK(!called_once);
  called_once = true;
#endif

  // We expect to find the ICU data module alongside the current module.
  std::wstring data_path;
  PathService::Get(base::DIR_MODULE, &data_path);
  file_util::AppendToPath(&data_path, L"icudt38.dll");

  HMODULE module = LoadLibrary(data_path.c_str());
  if (!module)
    return false;

  FARPROC addr = GetProcAddress(module, "icudt38_dat");
  if (!addr)
    return false;

  UErrorCode err = U_ZERO_ERROR;
  udata_setCommonData(reinterpret_cast<void*>(addr), &err);
  return err == U_ZERO_ERROR;
#else
  // Windows ships ICU's data separate, so it needs to link the code to data
  // here. Other platforms don't need this.
  return true;
#endif  // OS_WIN
}

}  // namespace icu_util
<|endoftext|>


<commit_before>/*	libscratch - Multipurpose objective C++ library.

		Copyright (c) 2013 - 2016 Angelo Geels <spansjh@gmail.com>

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

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

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

#pragma once

#include "Common.h"

SCRATCH_NAMESPACE_BEGIN;

namespace Internal
{
	template<typename Result, typename ...Args>
	struct abstract_function
	{
		virtual Result operator()(Args... args) = 0;
		virtual abstract_function *clone() const = 0;
		virtual ~abstract_function() {}
	};

	template<typename Func, typename Result, typename ...Args>
	class concrete_function : public abstract_function<Result, Args...>
	{
	private:
		Func m_func;

	public:
		concrete_function(const Func &x)
			: m_func(x)
		{
		}

		virtual Result operator()(Args... args)
		{
			return m_func(args...);
		}

		virtual concrete_function* clone() const
		{
			return new concrete_function(m_func);
		}
	};

	template<typename Func>
	struct func_filter
	{
		typedef Func type;
	};

	template<typename Result, typename ...Args>
	struct func_filter<Result(Args...)>
	{
		typedef Result(*type)(Args...);
	};
}

template<typename signature>
class Function;

template<typename Result, typename ...Args>
class Function<Result(Args...)>
{
private:
	Internal::abstract_function<Result, Args...>* m_func;

public:
	Function()
	{
		m_func = nullptr;
	}

	template<typename Func>
	Function(const Func &x)
	{
		m_func = new Internal::concrete_function<typename Internal::func_filter<Func>::type, Result, Args...>(x);
	}

	Function(const Function &rhs)
	{
		m_func = nullptr;
		if (rhs.m_func != nullptr) {
			m_func = rhs.m_func->clone();
		}
	}

	Function(decltype(nullptr))
	{
		m_func = nullptr;
	}

	~Function()
	{
		if (m_func != nullptr) {
			delete m_func;
		}
	}

	Function &operator=(const Function &rhs)
	{
		if (&rhs != this && rhs.m_func != nullptr)
		{
			auto temp = rhs.m_func->clone();
			if (m_func != nullptr) {
				delete m_func;
			}
			m_func = temp;
		}
		return *this;
	}

	Function &operator=(decltype(nullptr))
	{
		m_func = nullptr;
		return *this;
	}

	template<typename Func>
	Function &operator=(const Func &x)
	{
		auto temp = new Internal::concrete_function<typename Internal::func_filter<Func>::type, Result, Args...>(x);
		if (m_func != nullptr) {
			delete m_func;
		}
		m_func = temp;
		return *this;
	}

	bool operator==(decltype(nullptr))
	{
		return m_func == nullptr;
	}

	bool operator!=(decltype(nullptr))
	{
		return m_func != nullptr;
	}

	Result operator()(Args... args) const
	{
		if (m_func == nullptr) {
			return Result();
		}
		return (*m_func)(args...);
	}
};

SCRATCH_NAMESPACE_END;
<commit_msg>Fuction nullptr check can be on const object<commit_after>/*	libscratch - Multipurpose objective C++ library.

		Copyright (c) 2013 - 2016 Angelo Geels <spansjh@gmail.com>

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

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

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

#pragma once

#include "Common.h"

SCRATCH_NAMESPACE_BEGIN;

namespace Internal
{
	template<typename Result, typename ...Args>
	struct abstract_function
	{
		virtual Result operator()(Args... args) = 0;
		virtual abstract_function *clone() const = 0;
		virtual ~abstract_function() {}
	};

	template<typename Func, typename Result, typename ...Args>
	class concrete_function : public abstract_function<Result, Args...>
	{
	private:
		Func m_func;

	public:
		concrete_function(const Func &x)
			: m_func(x)
		{
		}

		virtual Result operator()(Args... args)
		{
			return m_func(args...);
		}

		virtual concrete_function* clone() const
		{
			return new concrete_function(m_func);
		}
	};

	template<typename Func>
	struct func_filter
	{
		typedef Func type;
	};

	template<typename Result, typename ...Args>
	struct func_filter<Result(Args...)>
	{
		typedef Result(*type)(Args...);
	};
}

template<typename signature>
class Function;

template<typename Result, typename ...Args>
class Function<Result(Args...)>
{
private:
	Internal::abstract_function<Result, Args...>* m_func;

public:
	Function()
	{
		m_func = nullptr;
	}

	template<typename Func>
	Function(const Func &x)
	{
		m_func = new Internal::concrete_function<typename Internal::func_filter<Func>::type, Result, Args...>(x);
	}

	Function(const Function &rhs)
	{
		m_func = nullptr;
		if (rhs.m_func != nullptr) {
			m_func = rhs.m_func->clone();
		}
	}

	Function(decltype(nullptr))
	{
		m_func = nullptr;
	}

	~Function()
	{
		if (m_func != nullptr) {
			delete m_func;
		}
	}

	Function &operator=(const Function &rhs)
	{
		if (&rhs != this && rhs.m_func != nullptr)
		{
			auto temp = rhs.m_func->clone();
			if (m_func != nullptr) {
				delete m_func;
			}
			m_func = temp;
		}
		return *this;
	}

	Function &operator=(decltype(nullptr))
	{
		m_func = nullptr;
		return *this;
	}

	template<typename Func>
	Function &operator=(const Func &x)
	{
		auto temp = new Internal::concrete_function<typename Internal::func_filter<Func>::type, Result, Args...>(x);
		if (m_func != nullptr) {
			delete m_func;
		}
		m_func = temp;
		return *this;
	}

	bool operator==(decltype(nullptr)) const
	{
		return m_func == nullptr;
	}

	bool operator!=(decltype(nullptr)) const
	{
		return m_func != nullptr;
	}

	Result operator()(Args... args) const
	{
		if (m_func == nullptr) {
			return Result();
		}
		return (*m_func)(args...);
	}
};

SCRATCH_NAMESPACE_END;
<|endoftext|>


<commit_before>// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2005 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>

#include <cstring>
#include <string>

#include "GNURegex.h"

#include "Array.h"
#include "Int16.h"
#include "Str.h"
#include "Structure.h"

#include "debug.h"
#include "GetOpt.h"

using namespace CppUnit;
using namespace std;

static bool debug = false;

namespace libdap {

class ArrayTest: public TestFixture {
private:
    Array *d_cardinal, *d_string, *d_structure;
    Int16 *d_int16;
    Str *d_str;
    Structure *d_struct;

    string svalues[4];
public:
    ArrayTest()
    {
        svalues[0] = "0 String";
        svalues[1] = "1 String";
        svalues[2] = "2 String";
        svalues[3] = "3 String";
    }

    ~ArrayTest()
    {
    }

    void setUp()
    {
        d_int16 = new Int16("Int16");
        DBG(cerr << "d_int16: " << d_int16 << endl);
        d_cardinal = new Array("Array_of_Int16", d_int16);
        d_cardinal->append_dim(4, "dimension");
        dods_int16 buffer[4] = { 0, 1, 2, 3 };
        d_cardinal->val2buf(buffer);
#ifdef DODS_DEBUG
        for (int i = 0; i < 4; ++i)
        cerr << "buffer[" << i << "]: " << buffer[i] << endl;
#endif

        d_str = new Str("Str");
        d_string = new Array("Array_of_String", d_str);
        d_string->append_dim(4, "dimension");
        string sbuffer[4] = { "0 String", "1 String", "2 String", "3 String" };
        d_string->val2buf(sbuffer);
#ifdef DODS_DEBUG
        for (int i = 0; i < 4; ++i)
        cerr << "sbuffer[" << i << "]: " << sbuffer[i] << endl;
#endif

        d_struct = new Structure("Structure");
        d_struct->add_var(d_int16);
        d_structure = new Array("Array_of_Strctures", d_struct);
        d_structure->append_dim(4, "dimension");
        ostringstream oss;
        for (int i = 0; i < 4; ++i) {
            oss.str("");
            oss << "field" << i;
            Int16 *n = new Int16(oss.str());
            DBG(cerr << "n " << i << ": " << n << endl);
            oss.str("");
            oss << "element" << i;
            Structure *s = new Structure(oss.str());
            s->add_var(n);
            d_structure->set_vec(i, s);
            delete n;
            n = 0;
            delete s;
            s = 0;
        }

        delete d_int16;
        d_int16 = 0;
        delete d_str;
        d_str = 0;
        delete d_struct;
        d_struct = 0;
    }

    void tearDown()
    {
        delete d_cardinal;
        delete d_string;
        delete d_structure;
    }

    bool re_match(Regex &r, const char *s)
    {
        int match_position = r.match(s, strlen(s));
        DBG(cerr << "match position: " << match_position
            << " string length: " << (int)strlen(s) << endl);
        return match_position == (int) strlen(s);
    }

    CPPUNIT_TEST_SUITE (ArrayTest);

    CPPUNIT_TEST (duplicate_cardinal_test);
    CPPUNIT_TEST (duplicate_string_test);
    CPPUNIT_TEST (duplicate_structure_test);

    CPPUNIT_TEST_SUITE_END();

    void duplicate_structure_test()
    {
        Array::Dim_iter i = d_structure->dim_begin();
        CPPUNIT_ASSERT(d_structure->dimension_size(i) == 4);
#ifdef DODS_DEBUG
        for (int i = 0; i < 4; ++i) {
            Structure *s = dynamic_cast<Structure*>(d_structure->var(i));
            DBG(cerr << "s: " << s << endl);
            if (s)
            s->print_decl(cerr);
        }
#endif

        Array *a = new Array(*d_structure);
        // a = *d_structure; I test operator= in duplicate_cardinal_test().
        i = a->dim_begin();
        CPPUNIT_ASSERT(a->dimension_size(i) == 4);
        for (int i = 0; i < 4; ++i) {
            // The point of this test is to ensure that the const ctor
            // performs a deep copy; first test to make sure the pointers
            // to BaseType instnaces are different in the two objects.
            Structure *src = dynamic_cast<Structure*>(d_structure->var(i));
            Structure *dest = dynamic_cast<Structure*>(a->var(i));
            CPPUNIT_ASSERT(src != dest);

            // However, for the deep copy to be correct, the two arrays must
            // have equivalent elements. We know there's only one field...
            CPPUNIT_ASSERT(src->type() == dods_structure_c && dest->type() == dods_structure_c);
            Constructor::Vars_iter s = src->var_begin();
            Constructor::Vars_iter d = dest->var_begin();
            CPPUNIT_ASSERT((*s)->type() == dods_int16_c && (*d)->type() == dods_int16_c);
            CPPUNIT_ASSERT((*s)->name() == (*d)->name());
        }
        delete a;
        a = 0;
    }

    void duplicate_string_test()
    {
        Array::Dim_iter i = d_string->dim_begin();
        CPPUNIT_ASSERT(d_string->dimension_size(i) == 4);
        string *s = new string[4];
        d_string->buf2val((void**) &s);
        for (int i = 0; i < 4; ++i) {
            CPPUNIT_ASSERT(s[i] == svalues[i]);
            DBG(cerr << "s[" << i << "]: " << s[i] << endl);
        }

        Array a = *d_string;
        i = a.dim_begin();
        CPPUNIT_ASSERT(a.dimension_size(i) == 4);

        string *s2 = new string[4];
        d_string->buf2val((void**) &s2);
        for (int i = 0; i < 4; ++i) {
            CPPUNIT_ASSERT(s2[i] == svalues[i]);
            DBG(cerr << "s2[" << i << "]: " << s2[i] << endl);
        }

        delete[] s;
        s = 0;
        delete[] s2;
        s2 = 0;
    }

    void duplicate_cardinal_test()
    {
        Array::Dim_iter i = d_cardinal->dim_begin();
        CPPUNIT_ASSERT(d_cardinal->dimension_size(i) == 4);
        dods_int16 *b = new dods_int16[4];
        d_cardinal->buf2val((void**) &b);
        for (int i = 0; i < 4; ++i) {
            CPPUNIT_ASSERT(b[i] == i);
            DBG(cerr << "b[" << i << "]: " << b[i] << endl);
        }
        delete[] b;
        b = 0;

        Array a = *d_cardinal;
        i = a.dim_begin();
        CPPUNIT_ASSERT(a.dimension_size(i) == 4);

        dods_int16 *b2 = new dods_int16[4];
        d_cardinal->buf2val((void**) &b2);
        for (int i = 0; i < 4; ++i) {
            CPPUNIT_ASSERT(b2[i] == i);
            DBG(cerr << "b2[" << i << "]: " << b2[i] << endl);
        }
        delete[] b2;
        b2 = 0;
    }

};

CPPUNIT_TEST_SUITE_REGISTRATION (ArrayTest);

} // namespace libdap

int main(int argc, char *argv[])
{
    GetOpt getopt(argc, argv, "dh");
    int option_char;

    while ((option_char = getopt()) != -1)
        switch (option_char) {
        case 'd':
            debug = 1;  // debug is a static global
            break;

        case 'h': {     // help - show test names
            cerr << "Usage: ArrayTest has the following tests:" << endl;
            const std::vector<Test*> &tests = libdap::ArrayTest::suite()->getTests();
            unsigned int prefix_len = libdap::ArrayTest::suite()->getName().append("::").length();
            for (std::vector<Test*>::const_iterator i = tests.begin(), e = tests.end(); i != e; ++i) {
                cerr << (*i)->getName().replace(0, prefix_len, "") << endl;
            }
            break;
        }

        default:
            break;
        }

    CppUnit::TextTestRunner runner;
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());

    bool wasSuccessful = true;
    string test = "";
    int i = getopt.optind;
    if (i == argc) {
        // run them all
        wasSuccessful = runner.run("");
    }
    else {
        for (; i < argc; ++i) {
            if (debug) cerr << "Running " << argv[i] << endl;
            test = libdap::ArrayTest::suite()->getName().append("::").append(argv[i]);
            wasSuccessful = wasSuccessful && runner.run(test);
        }
    }

    return wasSuccessful ? 0 : 1;
}
<commit_msg>more testing<commit_after>// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2005,2018 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>

#include <cstring>
#include <string>

#include "GNURegex.h"

#include "Array.h"
#include "Int16.h"
#include "Str.h"
#include "Structure.h"
#include "D4Dimensions.h"

#include "debug.h"
#include "GetOpt.h"

using namespace CppUnit;
using namespace std;

static bool debug = false;

namespace libdap {

class ArrayTest: public TestFixture {
private:
    Array *d_cardinal, *d_string, *d_structure;
    Int16 *d_int16;
    Str *d_str;
    Structure *d_struct;

    string svalues[4];
    char a[1024];

public:
    ArrayTest()
    {
        svalues[0] = "0 String";
        svalues[1] = "1 String";
        svalues[2] = "2 String";
        svalues[3] = "3 String";
    }

    ~ArrayTest()
    {
    }

    void setUp()
    {
        d_int16 = new Int16("Int16");
        DBG(cerr << "d_int16: " << d_int16 << endl);
        d_cardinal = new Array("Array_of_Int16", d_int16);
        d_cardinal->append_dim(4, "dimension");
        dods_int16 buffer[4] = { 0, 1, 2, 3 };
        d_cardinal->val2buf(buffer);
#ifdef DODS_DEBUG
        for (int i = 0; i < 4; ++i)
        cerr << "buffer[" << i << "]: " << buffer[i] << endl;
#endif

        d_str = new Str("Str");
        d_string = new Array("Array_of_String", d_str);
        d_string->append_dim(4, "dimension");
        string sbuffer[4] = { "0 String", "1 String", "2 String", "3 String" };
        d_string->val2buf(sbuffer);
#ifdef DODS_DEBUG
        for (int i = 0; i < 4; ++i)
        cerr << "sbuffer[" << i << "]: " << sbuffer[i] << endl;
#endif

        d_struct = new Structure("Structure");
        d_struct->add_var(d_int16);
        d_structure = new Array("Array_of_Strctures", d_struct);
        d_structure->append_dim(4, "dimension");
        ostringstream oss;
        for (int i = 0; i < 4; ++i) {
            oss.str("");
            oss << "field" << i;
            Int16 *n = new Int16(oss.str());
            DBG(cerr << "n " << i << ": " << n << endl);
            oss.str("");
            oss << "element" << i;
            Structure *s = new Structure(oss.str());
            s->add_var(n);
            d_structure->set_vec(i, s);
            delete n;
            n = 0;
            delete s;
            s = 0;
        }

        delete d_int16;
        d_int16 = 0;
        delete d_str;
        d_str = 0;
        delete d_struct;
        d_struct = 0;
    }

    void tearDown()
    {
        delete d_cardinal;
        delete d_string;
        delete d_structure;
    }

    bool re_match(Regex &r, const char *s)
    {
        int match_position = r.match(s, strlen(s));
        DBG(cerr << "match position: " << match_position
            << " string length: " << (int)strlen(s) << endl);
        return match_position == (int) strlen(s);
    }

    CPPUNIT_TEST_SUITE (ArrayTest);

    CPPUNIT_TEST (cons_test);
    CPPUNIT_TEST (equals_test);
    CPPUNIT_TEST (prepend_dim_test);
    CPPUNIT_TEST (prepend_dim_2_test);
    CPPUNIT_TEST (clear_dims_test);
    CPPUNIT_TEST (error_handling_test);
    CPPUNIT_TEST (error_handling_2_test);
    CPPUNIT_TEST (print_test);
    CPPUNIT_TEST (duplicate_cardinal_test);
    CPPUNIT_TEST (duplicate_string_test);
    CPPUNIT_TEST (duplicate_structure_test);

    CPPUNIT_TEST_SUITE_END();

    void cons_test()
    {
        Array a1 = Array("a", "b", d_int16, true);
        CPPUNIT_ASSERT(a1.name() == "a");
    }

    void equals_test()
    {
        Array a1 = Array("a", d_int16);
        a1 = *d_cardinal;
        Array::Dim_iter i = a1.dim_begin();
        CPPUNIT_ASSERT(a1.dimension_size(i) == 4);
        a1 = a1;
        i = a1.dim_begin();
        CPPUNIT_ASSERT(a1.dimension_size(i) == 4);
    }

    void prepend_dim_test()
    {
        Array a1 = Array("a", d_int16);
        Array::Dim_iter i = a1.dim_begin();
        CPPUNIT_ASSERT(a1.dimension_size(i) == 0);
        a1.prepend_dim(2, "dim_a");
        i = a1.dim_begin();
        CPPUNIT_ASSERT(a1.dimension_size(i) == 2);
        a1.prepend_dim(3, "dim_b");
    }

    void prepend_dim_2_test()
    {
        Array a1 = Array("a", d_int16);
        string expected_name[2] = {"dim_b", "dim_a"};
        int j = 0;
        D4Dimensions *dims = new D4Dimensions();
        D4Dimension *d = new D4Dimension("dim_b", 2, dims);
        a1.prepend_dim(2, "dim_a");
        a1.prepend_dim(d);
        for (Array::Dim_iter i = a1.dim_begin(); i != a1.dim_end(); i++, j++) {
            CPPUNIT_ASSERT(a1.dimension_name(i) == expected_name[j]);
        }
    }

    void clear_dims_test()
    {
        Array a1 = Array("a", d_int16);
        a1.prepend_dim(2, "dim_a");
        a1.prepend_dim(3, "dim_b");
        a1.clear_all_dims();
        Array::Dim_iter i = a1.dim_begin();
        CPPUNIT_ASSERT(a1.dimension_size(i) == 0);
    }

    void error_handling_test()
    {
        Array a1 = Array("a", d_int16);
        Array::Dim_iter i = a1.dim_begin();
        string msg;
        CPPUNIT_ASSERT_THROW(a1.dimension_name(i), InternalErr);
        CPPUNIT_ASSERT(!a1.check_semantics(msg));
    }

    void error_handling_2_test()
    {
        Array a1 = Array("a", d_int16);
        a1.append_dim(2, "dim_a");
        Array::Dim_iter i = a1.dim_begin();
        CPPUNIT_ASSERT(a1.dimension_size(i) == 2);
        CPPUNIT_ASSERT_THROW(a1.add_constraint(i, 2, 1, 1), Error);
        CPPUNIT_ASSERT_THROW(a1.add_constraint(i, 0, 1, 2), Error);
        CPPUNIT_ASSERT_THROW(a1.add_constraint(i, 0, 3, 1), Error);
    }

    void print_test()
    {
        Array a1 = Array("a", d_int16);
        FILE *fp;
        a1.append_dim(2, "dim_a");
        CPPUNIT_ASSERT(fp = fopen("ArrayTest.output", "w"));
        a1.print_xml(fp, " ", true);
        fclose(fp);
        ifstream ifs("ArrayTest.output");
        while(!ifs.eof())
            ifs >> a;
        ifs.close();
        cout<<a;
        CPPUNIT_ASSERT(!strcmp(a, "22;"));
    }

    void duplicate_structure_test()
    {
        Array::Dim_iter i = d_structure->dim_begin();
        CPPUNIT_ASSERT(d_structure->dimension_size(i) == 4);
#ifdef DODS_DEBUG
        for (int i = 0; i < 4; ++i) {
            Structure *s = dynamic_cast<Structure*>(d_structure->var(i));
            DBG(cerr << "s: " << s << endl);
            if (s)
            s->print_decl(cerr);
        }
#endif

        Array *a = new Array(*d_structure);
        // a = *d_structure; I test operator= in duplicate_cardinal_test().
        i = a->dim_begin();
        CPPUNIT_ASSERT(a->dimension_size(i) == 4);
        for (int i = 0; i < 4; ++i) {
            // The point of this test is to ensure that the const ctor
            // performs a deep copy; first test to make sure the pointers
            // to BaseType instnaces are different in the two objects.
            Structure *src = dynamic_cast<Structure*>(d_structure->var(i));
            Structure *dest = dynamic_cast<Structure*>(a->var(i));
            CPPUNIT_ASSERT(src != dest);

            // However, for the deep copy to be correct, the two arrays must
            // have equivalent elements. We know there's only one field...
            CPPUNIT_ASSERT(src->type() == dods_structure_c && dest->type() == dods_structure_c);
            Constructor::Vars_iter s = src->var_begin();
            Constructor::Vars_iter d = dest->var_begin();
            CPPUNIT_ASSERT((*s)->type() == dods_int16_c && (*d)->type() == dods_int16_c);
            CPPUNIT_ASSERT((*s)->name() == (*d)->name());
        }
        delete a;
        a = 0;
    }

    void duplicate_string_test()
    {
        Array::Dim_iter i = d_string->dim_begin();
        CPPUNIT_ASSERT(d_string->dimension_size(i) == 4);
        string *s = new string[4];
        d_string->buf2val((void**) &s);
        for (int i = 0; i < 4; ++i) {
            CPPUNIT_ASSERT(s[i] == svalues[i]);
            DBG(cerr << "s[" << i << "]: " << s[i] << endl);
        }

        Array a = *d_string;
        i = a.dim_begin();
        CPPUNIT_ASSERT(a.dimension_size(i) == 4);

        string *s2 = new string[4];
        d_string->buf2val((void**) &s2);
        for (int i = 0; i < 4; ++i) {
            CPPUNIT_ASSERT(s2[i] == svalues[i]);
            DBG(cerr << "s2[" << i << "]: " << s2[i] << endl);
        }

        delete[] s;
        s = 0;
        delete[] s2;
        s2 = 0;
    }

    void duplicate_cardinal_test()
    {
        Array::Dim_iter i = d_cardinal->dim_begin();
        CPPUNIT_ASSERT(d_cardinal->dimension_size(i) == 4);
        dods_int16 *b = new dods_int16[4];
        d_cardinal->buf2val((void**) &b);
        for (int i = 0; i < 4; ++i) {
            CPPUNIT_ASSERT(b[i] == i);
            DBG(cerr << "b[" << i << "]: " << b[i] << endl);
        }
        delete[] b;
        b = 0;

        Array a = *d_cardinal;
        i = a.dim_begin();
        CPPUNIT_ASSERT(a.dimension_size(i) == 4);

        dods_int16 *b2 = new dods_int16[4];
        d_cardinal->buf2val((void**) &b2);
        for (int i = 0; i < 4; ++i) {
            CPPUNIT_ASSERT(b2[i] == i);
            DBG(cerr << "b2[" << i << "]: " << b2[i] << endl);
        }
        delete[] b2;
        b2 = 0;
    }

};

CPPUNIT_TEST_SUITE_REGISTRATION (ArrayTest);

} // namespace libdap

int main(int argc, char *argv[])
{
    GetOpt getopt(argc, argv, "dh");
    int option_char;

    while ((option_char = getopt()) != -1)
        switch (option_char) {
        case 'd':
            debug = 1;  // debug is a static global
            break;

        case 'h': {     // help - show test names
            cerr << "Usage: ArrayTest has the following tests:" << endl;
            const std::vector<Test*> &tests = libdap::ArrayTest::suite()->getTests();
            unsigned int prefix_len = libdap::ArrayTest::suite()->getName().append("::").length();
            for (std::vector<Test*>::const_iterator i = tests.begin(), e = tests.end(); i != e; ++i) {
                cerr << (*i)->getName().replace(0, prefix_len, "") << endl;
            }
            break;
        }

        default:
            break;
        }

    CppUnit::TextTestRunner runner;
    runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());

    bool wasSuccessful = true;
    string test = "";
    int i = getopt.optind;
    if (i == argc) {
        // run them all
        wasSuccessful = runner.run("");
    }
    else {
        for (; i < argc; ++i) {
            if (debug) cerr << "Running " << argv[i] << endl;
            test = libdap::ArrayTest::suite()->getName().append("::").append(argv[i]);
            wasSuccessful = wasSuccessful && runner.run(test);
        }
    }

    return wasSuccessful ? 0 : 1;
}
<|endoftext|>


<commit_before><commit_msg>Initialize NSS with databases.<commit_after><|endoftext|>


<commit_before>// $Id: sample.cpp 793 2008-08-17 14:33:30Z glandrum $
//
//  Copyright (C) 2009 Greg Landrum
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//

#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/Depictor/RDDepictor.h>
#include <Demos/RDKit/Draw/MolDrawing.h>

#include <RDGeneral/RDLog.h>
#include <vector>

using namespace RDKit;
void DrawDemo(){
  RWMol *mol=SmilesToMol("Clc1c(C#N)cc(C(=O)NCc2sccc2)cc1");
  //RWMol *mol=SmilesToMol("c1ncncn1");
  RDKit::MolOps::Kekulize(*mol);

  // generate the 2D coordinates:
  RDDepict::compute2DCoords(*mol);
  std::vector<int> drawing=RDKit::Drawing::DrawMol(*mol);

  std::cout<<"var codes=[";
  std::copy(drawing.begin(),drawing.end(),std::ostream_iterator<int>(std::cout,","));
  std::cout<<"];"<<std::endl;

  delete mol;
}

int
main(int argc, char *argv[])
{
  RDLog::InitLogs();
  DrawDemo();
}
<commit_msg>initial pass at very crude svg translation<commit_after>// $Id: sample.cpp 793 2008-08-17 14:33:30Z glandrum $
//
//  Copyright (C) 2009 Greg Landrum
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//

#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/Depictor/RDDepictor.h>
#include <Demos/RDKit/Draw/MolDrawing.h>

#include <RDGeneral/RDLog.h>
#include <vector>
#include <sstream>

using namespace RDKit;

std::string getColor(int atNum){
  static std::map<int,std::string> colors;
  if(colors.empty()){
    colors[7]="#0000FF";
    colors[8]="#FF0000";
    colors[9]="#33CCCC";
    colors[15]="#FF7F00";
    colors[16]="#CCCC00";
    colors[16]="#00CC00";
    colors[35]="#7F4C19";
    colors[0]="#7F7F7F";
  }
  std::string res="#000000";
  if(colors.find(atNum)!=colors.end()) res= colors[atNum];
  return res;
}
void drawLine(std::vector<int>::const_iterator &pos,std::ostringstream &sstr){
      pos+=4;
      sstr<<"<svg:path ";
      sstr<<"d='M "<<*pos<<","<<*(pos+1)<<" "<<*(pos+2)<<","<<*(pos+3)<<"' ";
      pos+=4;
      sstr<<"style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1'";
      sstr<<" />\n";
}
void drawAtom(std::vector<int>::const_iterator &pos,std::ostringstream &sstr){
  int atNum=*pos++;
  int xp=*pos++;
  int yp=*pos++;
  int slen=*pos++;
  std::string label="";
  for(unsigned int i=0;i<slen;++i){
    label+=(char)*pos++;
  }
  sstr<<"<svg:text x='"<<xp<<"' y='"<<yp<<"'";
  sstr<<" style='font-size:40px;font-style:normal;font-weight:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill-opacity:1;stroke:none;font-family:Sans;text-anchor:middle;baseline-shift:sub"<<";fill:"<<getColor(atNum)<<"'";
  sstr<<">";
  sstr<<"<svg:tspan x='"<<xp<<"' y='"<<yp<<"'>";
  sstr<<label<<"</svg:tspan>";
  sstr<<"</svg:text>\n";
}

std::string ToSVG(const std::vector<int> &drawing){
  std::ostringstream sstr;
  sstr<<"<?xml version='1.0' encoding='iso-8859-1'?>\n";
  int width=300,height=300;
  std::vector<int>::const_iterator pos=drawing.begin()+2;
  TEST_ASSERT(*pos==Drawing::BOUNDS);
  pos+=3;
  width = *pos++;
  height = *pos++;
  sstr << "<svg:svg version='1.1' baseProfile='full'\n      \
        xmlns:svg='http://www.w3.org/2000/svg'\n                \
        xmlns:xlink='http://www.w3.org/1999/xlink'\n          \
        xml:space='preserve'\n";
  sstr<<"width='"<<width<<"px' height='"<<height<<"px' >\n";
  sstr<<"<svg:g transform='translate("<<width*.05<<","<<height*.05<<") scale(.9,.9)'>";
  while(pos!=drawing.end()){
    int token=*pos++;
    switch(token){
    case Drawing::LINE:
      drawLine(pos,sstr);
      break;
    case Drawing::ATOM:
      drawAtom(pos,sstr);
      break;
    default:
      std::cerr<<"unrecognized token: "<<token<<std::endl;
    }
  }

  sstr<<"</svg:g></svg:svg>";
  return sstr.str();
}

void DrawDemo(){
  RWMol *mol=SmilesToMol("Clc1c(C#N)cc(C(=O)NCc2sccc2)cc1");
  //RWMol *mol=SmilesToMol("c1ncncn1");
  RDKit::MolOps::Kekulize(*mol);

  // generate the 2D coordinates:
  RDDepict::compute2DCoords(*mol);
  std::vector<int> drawing=RDKit::Drawing::DrawMol(*mol);

  std::cerr<<"var codes=[";
  std::copy(drawing.begin(),drawing.end(),std::ostream_iterator<int>(std::cerr,","));
  std::cerr<<"];"<<std::endl;

  std::string svg=ToSVG(drawing);
  std::cout<<svg<<std::endl;

  delete mol;
}

int
main(int argc, char *argv[])
{
  RDLog::InitLogs();
  DrawDemo();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sb.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 14:10:46 $
 *
 *  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 _SB_HXX
#define _SB_HXX

#ifndef _SBERRORS_HXX
 #include <basic/sberrors.hxx>
#endif

#include <basic/sbdef.hxx>
#include <basic/sbmeth.hxx>
#include <basic/sbmod.hxx>
#include <basic/sbprop.hxx>
#include <basic/sbstar.hxx>

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.88); FILE MERGED 2008/03/28 16:06:55 rt 1.3.88.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: sb.hxx,v $
 * $Revision: 1.4 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef _SB_HXX
#define _SB_HXX

#ifndef _SBERRORS_HXX
 #include <basic/sberrors.hxx>
#endif

#include <basic/sbdef.hxx>
#include <basic/sbmeth.hxx>
#include <basic/sbmod.hxx>
#include <basic/sbprop.hxx>
#include <basic/sbstar.hxx>

#endif
<|endoftext|>


<commit_before>//
// Copyright (C) 2013-2018 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program.  If not, see
// <http://www.gnu.org/licenses/>.
//

#include "rowcontrols.h"
#include "analysis/analysisform.h"
#include "analysis/jaspcontrol.h"
#include "jasplistcontrol.h"

#include "log.h"

#include <QQmlContext>

RowControls::RowControls(ListModel* parent
						 , QQmlComponent* component
						 , const QMap<QString, Json::Value>& rowValues)
 : QObject(parent), _parentModel(parent), _rowComponent(component), _rowValues(rowValues)
{
}

// Cannot do this code in the constructor: the Component create function (comp->create(context)) will call the addJASPControl method in JASPControl (or ListView),
// So this RowControls instance needs to exist already.
void RowControls::init(int row, const Term& key, bool isNew)
{
	JASPListControl* listView = _parentModel->listView();

	QQmlContext* context = new QQmlContext(qmlContext(listView), listView);
	context->setContextProperty("isDynamic", true);
	context->setContextProperty("form", listView->form());
	context->setContextProperty("listView", listView);
	context->setContextProperty("isNew", isNew);
	context->setContextProperty("rowIndex",	row);
	context->setContextProperty("rowValue", key.asQString());

	_rowObject = qobject_cast<QQuickItem*>(_rowComponent->create(context));
	_context = context;

	if (_rowObject)	_setupControls();
	else			Log::log() << "Could not create control in ListView " << listView->name() << std::endl;
}

void RowControls::_setupControls(bool reuseBoundValue)
{
	// The controls (when created or reused) may need to be bound with some values:
	// either with the initial values (in _rowValues), new values (by calling createJson)
	// And if a control depends on a source, its values must be refreshed by this source.
	QList<JASPControl*> controls = _rowJASPControlMap.values();
	AnalysisForm* form = _parentModel->listView()->form();

	if (form)
	{
		form->sortControls(controls);
		form->blockValueChangeSignal(true);
	}

	for (JASPControl* control : controls)
	{
		bool hasInitialValues = _rowValues.contains(control->name());
		BoundControl* boundItem = control->boundControl();

		if (boundItem)
		{
			if (!reuseBoundValue || boundItem->boundValue().isNull())
				boundItem->bindTo(hasInitialValues ? (_rowValues[control->name()]) : boundItem->createJson());
		}

		if (!boundItem || !hasInitialValues || reuseBoundValue)
		{
			JASPListControl* listView = dynamic_cast<JASPListControl*>(control);
			// If a ListView depends on a source, it has to be initialized by this source
			// For this just call the sourceTermsChanged handler.
			if (listView && listView->hasSource())
				listView->model()->sourceTermsReset();
		}
	}

	if (form)
		form->blockValueChangeSignal(false, false);
}

void RowControls::setContext(int row, const QString &key)
{
	// Cannot use qmlContext(item) : setContextProperty would generate: 'Cannot set property on internal context.' error
	_context->setContextProperty("rowIndex", row);
	_context->setContextProperty("rowValue", key);
	_context->setContextProperty("isNew", false);
	_rowObject->setParentItem(nullptr);

	_setupControls(true);
}

bool RowControls::addJASPControl(JASPControl *control)
{
	bool success = false;
	JASPListControl* listView = _parentModel->listView();

	if (control->isBound() && control->name().isEmpty())
		listView->addControlError(tr("A row component in %1 does not have a name").arg(listView->name()));
	else if (_rowJASPControlMap.contains(control->name()))
		listView->addControlError(tr("2 row components in %1 have the same name").arg(listView->name()).arg(control->name()));
	else
		success = true;

	if (!control->name().isEmpty() && success)
		_rowJASPControlMap[control->name()] = control;

	return success;
}
<commit_msg>Adding a row in a ComponentList does not signal a analysis change<commit_after>//
// Copyright (C) 2013-2018 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program.  If not, see
// <http://www.gnu.org/licenses/>.
//

#include "rowcontrols.h"
#include "analysis/analysisform.h"
#include "analysis/jaspcontrol.h"
#include "jasplistcontrol.h"

#include "log.h"

#include <QQmlContext>

RowControls::RowControls(ListModel* parent
						 , QQmlComponent* component
						 , const QMap<QString, Json::Value>& rowValues)
 : QObject(parent), _parentModel(parent), _rowComponent(component), _rowValues(rowValues)
{
}

// Cannot do this code in the constructor: the Component create function (comp->create(context)) will call the addJASPControl method in JASPControl (or ListView),
// So this RowControls instance needs to exist already.
void RowControls::init(int row, const Term& key, bool isNew)
{
	JASPListControl* listView = _parentModel->listView();

	QQmlContext* context = new QQmlContext(qmlContext(listView), listView);
	context->setContextProperty("isDynamic", true);
	context->setContextProperty("form", listView->form());
	context->setContextProperty("listView", listView);
	context->setContextProperty("isNew", isNew);
	context->setContextProperty("rowIndex",	row);
	context->setContextProperty("rowValue", key.asQString());

	_rowObject = qobject_cast<QQuickItem*>(_rowComponent->create(context));
	_context = context;

	if (_rowObject)	_setupControls();
	else			Log::log() << "Could not create control in ListView " << listView->name() << std::endl;
}

void RowControls::_setupControls(bool reuseBoundValue)
{
	// The controls (when created or reused) may need to be bound with some values:
	// either with the initial values (in _rowValues), new values (by calling createJson)
	// And if a control depends on a source, its values must be refreshed by this source.
	QList<JASPControl*> controls = _rowJASPControlMap.values();
	AnalysisForm* form = _parentModel->listView()->form();

	if (form)
	{
		form->sortControls(controls);
		form->blockValueChangeSignal(true);
	}

	for (JASPControl* control : controls)
	{
		bool hasInitialValues = _rowValues.contains(control->name());
		BoundControl* boundItem = control->boundControl();

		if (boundItem)
		{
			if (!reuseBoundValue || boundItem->boundValue().isNull())
				boundItem->bindTo(hasInitialValues ? (_rowValues[control->name()]) : boundItem->createJson());
		}

		if (!boundItem || !hasInitialValues || reuseBoundValue)
		{
			JASPListControl* listView = dynamic_cast<JASPListControl*>(control);
			// If a ListView depends on a source, it has to be initialized by this source
			// For this just call the sourceTermsChanged handler.
			if (listView && listView->hasSource())
				listView->model()->sourceTermsReset();
		}
	}

	if (form)
		form->blockValueChangeSignal(false);
}

void RowControls::setContext(int row, const QString &key)
{
	// Cannot use qmlContext(item) : setContextProperty would generate: 'Cannot set property on internal context.' error
	_context->setContextProperty("rowIndex", row);
	_context->setContextProperty("rowValue", key);
	_context->setContextProperty("isNew", false);
	_rowObject->setParentItem(nullptr);

	_setupControls(true);
}

bool RowControls::addJASPControl(JASPControl *control)
{
	bool success = false;
	JASPListControl* listView = _parentModel->listView();

	if (control->isBound() && control->name().isEmpty())
		listView->addControlError(tr("A row component in %1 does not have a name").arg(listView->name()));
	else if (_rowJASPControlMap.contains(control->name()))
		listView->addControlError(tr("2 row components in %1 have the same name").arg(listView->name()).arg(control->name()));
	else
		success = true;

	if (!control->name().isEmpty() && success)
		_rowJASPControlMap[control->name()] = control;

	return success;
}
<|endoftext|>