<commit_before>/**
 * @file vcs_species_thermo.cpp
 *   Implementation for the VCS_SPECIES_THERMO object.
 */
/*
 * $Id: vcs_species_thermo.cpp,v 1.18 2008/12/17 16:34:18 hkmoffa Exp $
 */
/*
 * Copywrite (2005) Sandia Corporation. Under the terms of
 * Contract DE-AC04-94AL85000 with Sandia Corporation, the
 * U.S. Government retains certain rights in this software.
 */

#include "vcs_solve.h"
#include "vcs_species_thermo.h"
#include "vcs_defs.h"
#include "vcs_VolPhase.h"

#include "vcs_Exception.h"
#include "vcs_internal.h"

#include <cstdio>
#include <cstdlib>
#include <cmath>

using namespace std;

namespace VCSnonideal {

VCS_SPECIES_THERMO::VCS_SPECIES_THERMO(int indexPhase,
				       int indexSpeciesPhase) :

  IndexPhase(indexPhase),
  IndexSpeciesPhase(indexSpeciesPhase),
  OwningPhase(0),
  SS0_Model(VCS_SS0_CONSTANT),
  SS0_feSave(0.0),
  SS0_TSave(-90.0),
  SS0_T0(273.15),
  SS0_H0(0.0),
  SS0_S0(0.0),
  SS0_Cp0(0.0),
  SS0_Pref(1.01325E5),
  SS0_Params(0),
  SSStar_Model(VCS_SSSTAR_CONSTANT),
  SSStar_Params(0),
  Activity_Coeff_Model(VCS_AC_CONSTANT),
  Activity_Coeff_Params(0),
  SSStar_Vol_Model(VCS_SSVOL_IDEALGAS),
  SSStar_Vol_Params(0),
  SSStar_Vol0(-1.0),
  UseCanteraCalls(false),
  m_VCS_UnitsFormat(VCS_UNITS_UNITLESS)
{
  SS0_Pref = 1.01325E5;
}

/******************************************************************************
 *
 * destructor
 */
VCS_SPECIES_THERMO::~VCS_SPECIES_THERMO()
{
}

/*****************************************************************************
 *
 * Copy Constructor VCS_SPECIES_THERMO
 */
VCS_SPECIES_THERMO::VCS_SPECIES_THERMO(const VCS_SPECIES_THERMO& b) :
  IndexPhase(b.IndexPhase),
  IndexSpeciesPhase(b.IndexSpeciesPhase),
  OwningPhase(b.OwningPhase),
  SS0_Model(b.SS0_Model),
  SS0_feSave(b.SS0_feSave),
  SS0_TSave(b.SS0_TSave),
  SS0_T0(b.SS0_T0),
  SS0_H0(b.SS0_H0),
  SS0_S0(b.SS0_S0),
  SS0_Cp0(b.SS0_Cp0),
  SS0_Pref(b.SS0_Pref),
  SS0_Params(0),
  SSStar_Model(b.SSStar_Model),
  SSStar_Params(0),
  Activity_Coeff_Model(b.Activity_Coeff_Model),
  Activity_Coeff_Params(0),
  SSStar_Vol_Model(b.SSStar_Vol_Model),
  SSStar_Vol_Params(0),
  SSStar_Vol0(b.SSStar_Vol0),
  UseCanteraCalls(b.UseCanteraCalls),
  m_VCS_UnitsFormat(b.m_VCS_UnitsFormat)
{

  switch (SS0_Model) {

  default:

    SS0_Params = 0;
    break;
  }
}

/*****************************************************************************
 *
 * Assignment operator for VCS_SPECIES_THERMO
 */
VCS_SPECIES_THERMO&
VCS_SPECIES_THERMO::operator=(const VCS_SPECIES_THERMO& b)
{
  if (&b != this) {
    IndexPhase            = b.IndexPhase;
    IndexSpeciesPhase     = b.IndexSpeciesPhase;
    OwningPhase           = b.OwningPhase;
    SS0_Model             = b.SS0_Model;
    SS0_feSave            = b.SS0_feSave;
    SS0_TSave             = b.SS0_TSave;
    SS0_T0                = b.SS0_T0;
    SS0_H0                = b.SS0_H0;
    SS0_S0                = b.SS0_S0;
    SS0_Cp0               = b.SS0_Cp0;
    SS0_Pref              = b.SS0_Pref;
    SSStar_Model          = b.SSStar_Model;
    /*
     * shallow copy because function is undeveloped.
     */
    SSStar_Params         = b.SSStar_Params;
    Activity_Coeff_Model  = b.Activity_Coeff_Model;
    /*
     * shallow copy because function is undeveloped.
     */
    Activity_Coeff_Params = b.Activity_Coeff_Params;
    SSStar_Vol_Model      = b.SSStar_Vol_Model;
    /*
     * shallow copy because function is undeveloped.
     */
    SSStar_Vol_Params     = b.SSStar_Vol_Params;
    SSStar_Vol0           = b.SSStar_Vol0;
    UseCanteraCalls       = b.UseCanteraCalls;
    m_VCS_UnitsFormat     = b.m_VCS_UnitsFormat;
  }
  return *this;
}

/******************************************************************************
 *
 * duplMyselfAsVCS_SPECIES_THERMO():                (virtual)
 *
 *    This routine can duplicate inherited objects given a base class
 *    pointer. It relies on valid copy constructors.
 */

VCS_SPECIES_THERMO* VCS_SPECIES_THERMO::duplMyselfAsVCS_SPECIES_THERMO() {
  VCS_SPECIES_THERMO* ptr = new VCS_SPECIES_THERMO(*this);
  return  ptr;
}

/**************************************************************************
 *
 * GStar_R_calc();
 *
 *  This function calculates the standard state Gibbs free energy
 *  for species, kspec, at the solution temperature TKelvin and
 *  solution pressure, Pres.
 *
 *
 *  Input
 *   kglob = species global index.
 *   TKelvin = Temperature in Kelvin
 *   pres = pressure is given in units specified by if__ variable.
 *
 *
 * Output
 *    return value = standard state free energy in units of Kelvin.
 */
double VCS_SPECIES_THERMO::GStar_R_calc(int kglob, double TKelvin,
					double pres)
{
  char yo[] = "VCS_SPECIES_THERMO::GStar_R_calc ";
  double fe, T;
  fe = G0_R_calc(kglob, TKelvin);
  T = TKelvin;
  if (UseCanteraCalls) {
    AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, "Possible inconsistency");
    int kspec = IndexSpeciesPhase;
    OwningPhase->setState_TP(TKelvin, pres);
    fe = OwningPhase->GStar_calc_one(kspec);
    double R = vcsUtil_gasConstant(m_VCS_UnitsFormat);
    fe /= R;
  } else {
    double pref = SS0_Pref;
    switch(SSStar_Model) {
    case VCS_SSSTAR_CONSTANT:
      break;
    case VCS_SSSTAR_IDEAL_GAS:
      fe += T * log( pres/ pref );
      break;
    default:
      plogf("%sERROR: unknown SSStar model\n", yo);
      exit(EXIT_FAILURE);
    }
  }
  return fe;
}

/**************************************************************************
 *
 * VolStar_calc:
 *
 *  This function calculates the standard state molar volume
 *  for species, kspec, at the temperature TKelvin and pressure, Pres,
 *
 *  Input
 *
 * Output
 *    return value = standard state volume in    m**3 per kmol.
 *                   (VCS_UNITS_MKS)
 */
double VCS_SPECIES_THERMO::
VolStar_calc(int kglob, double TKelvin, double presPA)
{
  char yo[] = "VCS_SPECIES_THERMO::VStar_calc ";
  double vol, T;

  T = TKelvin;
  if (UseCanteraCalls) {
    AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, "Possible inconsistency");
    int kspec = IndexSpeciesPhase;
    OwningPhase->setState_TP(TKelvin, presPA);
    vol = OwningPhase->VolStar_calc_one(kspec);
  } else {
    switch(SSStar_Vol_Model) {
    case VCS_SSVOL_CONSTANT:
      vol = SSStar_Vol0;
      break;
    case VCS_SSVOL_IDEALGAS:
      // R J/kmol/K (2006 CODATA value)
      vol= 8314.47215  * T / presPA;
      break;
    default:
      plogf("%sERROR: unknown SSVol model\n", yo);
      exit(EXIT_FAILURE);
    }
  }
  return vol;
}

/**************************************************************************
 *
 * G0_R_calc:
 *
 *  This function calculates the naught state Gibbs free energy
 *  for species, kspec, at the temperature TKelvin
 *
 *  Input
 *   kglob = species global index.
 *   TKelvin = Temperature in Kelvin
 *
 * Output
 *    return value = naught state free energy in Kelvin.
 */
double VCS_SPECIES_THERMO::G0_R_calc(int kglob, double TKelvin)
{
#ifdef DEBUG_MODE
  char yo[] = "VS_SPECIES_THERMO::G0_R_calc ";
#endif
  double fe, H, S;
  if (SS0_Model == VCS_SS0_CONSTANT) {
    fe = SS0_feSave;
    return fe;
  }
  if (TKelvin == SS0_TSave) {
    fe = SS0_feSave;
    return fe;
  }
  if (UseCanteraCalls) {
    AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, "Possible inconsistency");
    int kspec = IndexSpeciesPhase;
    OwningPhase->setState_T(TKelvin);
    fe = OwningPhase->G0_calc_one(kspec);
    double R = vcsUtil_gasConstant(m_VCS_UnitsFormat);
    fe /= R;
  } else {
    switch (SS0_Model) {
    case VCS_SS0_CONSTANT:
      fe = SS0_feSave;
      break;
    case VCS_SS0_CONSTANT_CP:
      H  = SS0_H0 + (TKelvin - SS0_T0) * SS0_Cp0;
      S  = SS0_Cp0 + SS0_Cp0 * log((TKelvin / SS0_T0));
      fe = H - TKelvin * S;
      break;
    default:
#ifdef DEBUG_MODE
      plogf("%sERROR: unknown model\n", yo);
#endif
      exit(EXIT_FAILURE);
    }
  }
  SS0_feSave = fe;
  SS0_TSave = TKelvin;
  return fe;
}

/**************************************************************************
 *
 * eval_ac:
 *
 *  This function evaluates the activity coefficient
 *  for species, kspec
 *
 *  Input
 *      kglob -> integer value of the species in the global
 *            species list within VCS_GLOB. Phase and local species id
 *             can be looked up within object.
 *
 *   Note, T, P and mole fractions are obtained from the
 *   single private instance of VCS_GLOB
 *
 *
 * Output
 *    return value = activity coefficient for species kspec
 */
double VCS_SPECIES_THERMO::eval_ac(int kglob)
{
#ifdef DEBUG_MODE
  char yo[] = "VCS_SPECIES_THERMO::eval_ac ";
#endif
  double ac;
  /*
   *  Activity coefficients are frequently evaluated on a per phase
   *  basis. If they are, then the currPhAC[] boolean may be used
   *  to reduce repeated work. Just set currPhAC[iph], when the
   *  activity coefficients for all species in the phase are reevaluated.
   */
  if (UseCanteraCalls) {
    int kspec = IndexSpeciesPhase;
    ac = OwningPhase->AC_calc_one(kspec);
  } else {
    switch (Activity_Coeff_Model) {
    case VCS_AC_CONSTANT:
      ac = 1.0;
      break;
    default:
#ifdef DEBUG_MODE
      plogf("%sERROR: unknown model\n", yo);
#endif
      exit(EXIT_FAILURE);
    }
  }
  return ac;
}

/*****************************************************************************/
}
<commit_msg>Took out a warning message on vc++<commit_after>/**
 * @file vcs_species_thermo.cpp
 *   Implementation for the VCS_SPECIES_THERMO object.
 */
/*
 * $Id: vcs_species_thermo.cpp,v 1.18 2008/12/17 16:34:18 hkmoffa Exp $
 */
/*
 * Copywrite (2005) Sandia Corporation. Under the terms of
 * Contract DE-AC04-94AL85000 with Sandia Corporation, the
 * U.S. Government retains certain rights in this software.
 */

#include "vcs_solve.h"
#include "vcs_species_thermo.h"
#include "vcs_defs.h"
#include "vcs_VolPhase.h"

#include "vcs_Exception.h"
#include "vcs_internal.h"

#include <cstdio>
#include <cstdlib>
#include <cmath>

using namespace std;

namespace VCSnonideal {

VCS_SPECIES_THERMO::VCS_SPECIES_THERMO(int indexPhase,
				       int indexSpeciesPhase) :

  IndexPhase(indexPhase),
  IndexSpeciesPhase(indexSpeciesPhase),
  OwningPhase(0),
  SS0_Model(VCS_SS0_CONSTANT),
  SS0_feSave(0.0),
  SS0_TSave(-90.0),
  SS0_T0(273.15),
  SS0_H0(0.0),
  SS0_S0(0.0),
  SS0_Cp0(0.0),
  SS0_Pref(1.01325E5),
  SS0_Params(0),
  SSStar_Model(VCS_SSSTAR_CONSTANT),
  SSStar_Params(0),
  Activity_Coeff_Model(VCS_AC_CONSTANT),
  Activity_Coeff_Params(0),
  SSStar_Vol_Model(VCS_SSVOL_IDEALGAS),
  SSStar_Vol_Params(0),
  SSStar_Vol0(-1.0),
  UseCanteraCalls(false),
  m_VCS_UnitsFormat(VCS_UNITS_UNITLESS)
{
  SS0_Pref = 1.01325E5;
}

/******************************************************************************
 *
 * destructor
 */
VCS_SPECIES_THERMO::~VCS_SPECIES_THERMO()
{
}

/*****************************************************************************
 *
 * Copy Constructor VCS_SPECIES_THERMO
 */
VCS_SPECIES_THERMO::VCS_SPECIES_THERMO(const VCS_SPECIES_THERMO& b) :
  IndexPhase(b.IndexPhase),
  IndexSpeciesPhase(b.IndexSpeciesPhase),
  OwningPhase(b.OwningPhase),
  SS0_Model(b.SS0_Model),
  SS0_feSave(b.SS0_feSave),
  SS0_TSave(b.SS0_TSave),
  SS0_T0(b.SS0_T0),
  SS0_H0(b.SS0_H0),
  SS0_S0(b.SS0_S0),
  SS0_Cp0(b.SS0_Cp0),
  SS0_Pref(b.SS0_Pref),
  SS0_Params(0),
  SSStar_Model(b.SSStar_Model),
  SSStar_Params(0),
  Activity_Coeff_Model(b.Activity_Coeff_Model),
  Activity_Coeff_Params(0),
  SSStar_Vol_Model(b.SSStar_Vol_Model),
  SSStar_Vol_Params(0),
  SSStar_Vol0(b.SSStar_Vol0),
  UseCanteraCalls(b.UseCanteraCalls),
  m_VCS_UnitsFormat(b.m_VCS_UnitsFormat)
{

   SS0_Params = 0;
}

/*****************************************************************************
 *
 * Assignment operator for VCS_SPECIES_THERMO
 */
VCS_SPECIES_THERMO&
VCS_SPECIES_THERMO::operator=(const VCS_SPECIES_THERMO& b)
{
  if (&b != this) {
    IndexPhase            = b.IndexPhase;
    IndexSpeciesPhase     = b.IndexSpeciesPhase;
    OwningPhase           = b.OwningPhase;
    SS0_Model             = b.SS0_Model;
    SS0_feSave            = b.SS0_feSave;
    SS0_TSave             = b.SS0_TSave;
    SS0_T0                = b.SS0_T0;
    SS0_H0                = b.SS0_H0;
    SS0_S0                = b.SS0_S0;
    SS0_Cp0               = b.SS0_Cp0;
    SS0_Pref              = b.SS0_Pref;
    SSStar_Model          = b.SSStar_Model;
    /*
     * shallow copy because function is undeveloped.
     */
    SSStar_Params         = b.SSStar_Params;
    Activity_Coeff_Model  = b.Activity_Coeff_Model;
    /*
     * shallow copy because function is undeveloped.
     */
    Activity_Coeff_Params = b.Activity_Coeff_Params;
    SSStar_Vol_Model      = b.SSStar_Vol_Model;
    /*
     * shallow copy because function is undeveloped.
     */
    SSStar_Vol_Params     = b.SSStar_Vol_Params;
    SSStar_Vol0           = b.SSStar_Vol0;
    UseCanteraCalls       = b.UseCanteraCalls;
    m_VCS_UnitsFormat     = b.m_VCS_UnitsFormat;
  }
  return *this;
}

/******************************************************************************
 *
 * duplMyselfAsVCS_SPECIES_THERMO():                (virtual)
 *
 *    This routine can duplicate inherited objects given a base class
 *    pointer. It relies on valid copy constructors.
 */

VCS_SPECIES_THERMO* VCS_SPECIES_THERMO::duplMyselfAsVCS_SPECIES_THERMO() {
  VCS_SPECIES_THERMO* ptr = new VCS_SPECIES_THERMO(*this);
  return  ptr;
}

/**************************************************************************
 *
 * GStar_R_calc();
 *
 *  This function calculates the standard state Gibbs free energy
 *  for species, kspec, at the solution temperature TKelvin and
 *  solution pressure, Pres.
 *
 *
 *  Input
 *   kglob = species global index.
 *   TKelvin = Temperature in Kelvin
 *   pres = pressure is given in units specified by if__ variable.
 *
 *
 * Output
 *    return value = standard state free energy in units of Kelvin.
 */
double VCS_SPECIES_THERMO::GStar_R_calc(int kglob, double TKelvin,
					double pres)
{
  char yo[] = "VCS_SPECIES_THERMO::GStar_R_calc ";
  double fe, T;
  fe = G0_R_calc(kglob, TKelvin);
  T = TKelvin;
  if (UseCanteraCalls) {
    AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, "Possible inconsistency");
    int kspec = IndexSpeciesPhase;
    OwningPhase->setState_TP(TKelvin, pres);
    fe = OwningPhase->GStar_calc_one(kspec);
    double R = vcsUtil_gasConstant(m_VCS_UnitsFormat);
    fe /= R;
  } else {
    double pref = SS0_Pref;
    switch(SSStar_Model) {
    case VCS_SSSTAR_CONSTANT:
      break;
    case VCS_SSSTAR_IDEAL_GAS:
      fe += T * log( pres/ pref );
      break;
    default:
      plogf("%sERROR: unknown SSStar model\n", yo);
      exit(EXIT_FAILURE);
    }
  }
  return fe;
}

/**************************************************************************
 *
 * VolStar_calc:
 *
 *  This function calculates the standard state molar volume
 *  for species, kspec, at the temperature TKelvin and pressure, Pres,
 *
 *  Input
 *
 * Output
 *    return value = standard state volume in    m**3 per kmol.
 *                   (VCS_UNITS_MKS)
 */
double VCS_SPECIES_THERMO::
VolStar_calc(int kglob, double TKelvin, double presPA)
{
  char yo[] = "VCS_SPECIES_THERMO::VStar_calc ";
  double vol, T;

  T = TKelvin;
  if (UseCanteraCalls) {
    AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, "Possible inconsistency");
    int kspec = IndexSpeciesPhase;
    OwningPhase->setState_TP(TKelvin, presPA);
    vol = OwningPhase->VolStar_calc_one(kspec);
  } else {
    switch(SSStar_Vol_Model) {
    case VCS_SSVOL_CONSTANT:
      vol = SSStar_Vol0;
      break;
    case VCS_SSVOL_IDEALGAS:
      // R J/kmol/K (2006 CODATA value)
      vol= 8314.47215  * T / presPA;
      break;
    default:
      plogf("%sERROR: unknown SSVol model\n", yo);
      exit(EXIT_FAILURE);
    }
  }
  return vol;
}

/**************************************************************************
 *
 * G0_R_calc:
 *
 *  This function calculates the naught state Gibbs free energy
 *  for species, kspec, at the temperature TKelvin
 *
 *  Input
 *   kglob = species global index.
 *   TKelvin = Temperature in Kelvin
 *
 * Output
 *    return value = naught state free energy in Kelvin.
 */
double VCS_SPECIES_THERMO::G0_R_calc(int kglob, double TKelvin)
{
#ifdef DEBUG_MODE
  char yo[] = "VS_SPECIES_THERMO::G0_R_calc ";
#endif
  double fe, H, S;
  if (SS0_Model == VCS_SS0_CONSTANT) {
    fe = SS0_feSave;
    return fe;
  }
  if (TKelvin == SS0_TSave) {
    fe = SS0_feSave;
    return fe;
  }
  if (UseCanteraCalls) {
    AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, "Possible inconsistency");
    int kspec = IndexSpeciesPhase;
    OwningPhase->setState_T(TKelvin);
    fe = OwningPhase->G0_calc_one(kspec);
    double R = vcsUtil_gasConstant(m_VCS_UnitsFormat);
    fe /= R;
  } else {
    switch (SS0_Model) {
    case VCS_SS0_CONSTANT:
      fe = SS0_feSave;
      break;
    case VCS_SS0_CONSTANT_CP:
      H  = SS0_H0 + (TKelvin - SS0_T0) * SS0_Cp0;
      S  = SS0_Cp0 + SS0_Cp0 * log((TKelvin / SS0_T0));
      fe = H - TKelvin * S;
      break;
    default:
#ifdef DEBUG_MODE
      plogf("%sERROR: unknown model\n", yo);
#endif
      exit(EXIT_FAILURE);
    }
  }
  SS0_feSave = fe;
  SS0_TSave = TKelvin;
  return fe;
}

/**************************************************************************
 *
 * eval_ac:
 *
 *  This function evaluates the activity coefficient
 *  for species, kspec
 *
 *  Input
 *      kglob -> integer value of the species in the global
 *            species list within VCS_GLOB. Phase and local species id
 *             can be looked up within object.
 *
 *   Note, T, P and mole fractions are obtained from the
 *   single private instance of VCS_GLOB
 *
 *
 * Output
 *    return value = activity coefficient for species kspec
 */
double VCS_SPECIES_THERMO::eval_ac(int kglob)
{
#ifdef DEBUG_MODE
  char yo[] = "VCS_SPECIES_THERMO::eval_ac ";
#endif
  double ac;
  /*
   *  Activity coefficients are frequently evaluated on a per phase
   *  basis. If they are, then the currPhAC[] boolean may be used
   *  to reduce repeated work. Just set currPhAC[iph], when the
   *  activity coefficients for all species in the phase are reevaluated.
   */
  if (UseCanteraCalls) {
    int kspec = IndexSpeciesPhase;
    ac = OwningPhase->AC_calc_one(kspec);
  } else {
    switch (Activity_Coeff_Model) {
    case VCS_AC_CONSTANT:
      ac = 1.0;
      break;
    default:
#ifdef DEBUG_MODE
      plogf("%sERROR: unknown model\n", yo);
#endif
      exit(EXIT_FAILURE);
    }
  }
  return ac;
}

/*****************************************************************************/
}
<|endoftext|>


<commit_before>// Copyright © 2010-2015 The CefSharp 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 "Stdafx.h"
#include "Internals/CefRequestWrapper.h"
#include "Internals/CefResponseWrapper.h"
#include "Internals/CefCallbackWrapper.h"
#include "ResourceHandlerWrapper.h"
#include "Internals/TypeConversion.h"

using namespace System::Runtime::InteropServices;
using namespace System::IO;

namespace CefSharp
{
    bool ResourceHandlerWrapper::ProcessRequest(CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> callback)
    {
        _callbackWrapper = gcnew CefCallbackWrapper(callback);

        // If we already have a non-null _request
        // dispose it via delete before using the parameter for the rest
        // of this object's lifetime. This ought to be sensible to do
        // because the contained data ought to be nearly identical.
        delete _request;

        _request = gcnew CefRequestWrapper(request);

        AutoLock lock_scope(_syncRoot);

        return _handler->ProcessRequestAsync(_request, _callbackWrapper);
    }

    void ResourceHandlerWrapper::GetResponseHeaders(CefRefPtr<CefResponse> response, int64& response_length, CefString& redirectUrl)
    {
        String^ newRedistUrl;

        CefResponseWrapper responseWrapper(response);

        _stream = _handler->GetResponse(%responseWrapper, response_length, newRedistUrl);

        redirectUrl = StringUtils::ToNative(newRedistUrl);
    }

    bool ResourceHandlerWrapper::ReadResponse(void* data_out, int bytes_to_read, int& bytes_read, CefRefPtr<CefCallback> callback)
    {
        bool hasData = false;

        AutoLock lock_scope(_syncRoot);

        if (static_cast<Stream^>(_stream) == nullptr)
        {
            bytes_read = 0;
        }
        else
        {
            array<Byte>^ buffer = gcnew array<Byte>(bytes_to_read);
            bytes_read = _stream->Read(buffer, 0, bytes_to_read);
            pin_ptr<Byte> src = &buffer[0];
            memcpy(data_out, static_cast<void*>(src), bytes_read);
            // must return false when the response is complete
            hasData = bytes_read > 0;
            //TODO: Fix this
            /*if (!hasData && _closeStream)
            {
                _stream->Close();
            }*/
        }

        return hasData;
    }

    bool ResourceHandlerWrapper::CanGetCookie(const CefCookie& cookie)
    {
        //Default value is true
        return true;
    }

    bool ResourceHandlerWrapper::CanSetCookie(const CefCookie& cookie)
    {
        //Default value is true
        return true;
    }

    void ResourceHandlerWrapper::Cancel()
    {
        //TODO: Fix this
        /*if (static_cast<Stream^>(_stream) != nullptr && _closeStream)
        {
            _stream->Close();
        }*/
        _stream = nullptr;

        // Do not dispose here; since CEF 2537 the ResourceHandlerWrapper pointer is
        // referenced after Cancel and disposal would cause an access violation.
        //delete this;
    }

    int64 ResourceHandlerWrapper::SizeFromStream()
    {
        if (static_cast<Stream^>(_stream) == nullptr)
        {
            return 0;
        }

        if (_stream->CanSeek)
        {
            _stream->Seek(0, System::IO::SeekOrigin::End);
            int64 length = static_cast<int>(_stream->Position);
            _stream->Seek(0, System::IO::SeekOrigin::Begin);
            return length;
        }
        return -1;
    }
}<commit_msg>Fix typo - newRedirectUrl<commit_after>// Copyright © 2010-2015 The CefSharp 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 "Stdafx.h"
#include "Internals/CefRequestWrapper.h"
#include "Internals/CefResponseWrapper.h"
#include "Internals/CefCallbackWrapper.h"
#include "ResourceHandlerWrapper.h"
#include "Internals/TypeConversion.h"

using namespace System::Runtime::InteropServices;
using namespace System::IO;

namespace CefSharp
{
    bool ResourceHandlerWrapper::ProcessRequest(CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> callback)
    {
        _callbackWrapper = gcnew CefCallbackWrapper(callback);

        // If we already have a non-null _request
        // dispose it via delete before using the parameter for the rest
        // of this object's lifetime. This ought to be sensible to do
        // because the contained data ought to be nearly identical.
        delete _request;

        _request = gcnew CefRequestWrapper(request);

        AutoLock lock_scope(_syncRoot);

        return _handler->ProcessRequestAsync(_request, _callbackWrapper);
    }

    void ResourceHandlerWrapper::GetResponseHeaders(CefRefPtr<CefResponse> response, int64& response_length, CefString& redirectUrl)
    {
        String^ newRedirectUrl;

        CefResponseWrapper responseWrapper(response);

        _stream = _handler->GetResponse(%responseWrapper, response_length, newRedirectUrl);

        redirectUrl = StringUtils::ToNative(newRedirectUrl);
    }

    bool ResourceHandlerWrapper::ReadResponse(void* data_out, int bytes_to_read, int& bytes_read, CefRefPtr<CefCallback> callback)
    {
        bool hasData = false;

        AutoLock lock_scope(_syncRoot);

        if (static_cast<Stream^>(_stream) == nullptr)
        {
            bytes_read = 0;
        }
        else
        {
            array<Byte>^ buffer = gcnew array<Byte>(bytes_to_read);
            bytes_read = _stream->Read(buffer, 0, bytes_to_read);
            pin_ptr<Byte> src = &buffer[0];
            memcpy(data_out, static_cast<void*>(src), bytes_read);
            // must return false when the response is complete
            hasData = bytes_read > 0;
            //TODO: Fix this
            /*if (!hasData && _closeStream)
            {
                _stream->Close();
            }*/
        }

        return hasData;
    }

    bool ResourceHandlerWrapper::CanGetCookie(const CefCookie& cookie)
    {
        //Default value is true
        return true;
    }

    bool ResourceHandlerWrapper::CanSetCookie(const CefCookie& cookie)
    {
        //Default value is true
        return true;
    }

    void ResourceHandlerWrapper::Cancel()
    {
        //TODO: Fix this
        /*if (static_cast<Stream^>(_stream) != nullptr && _closeStream)
        {
            _stream->Close();
        }*/
        _stream = nullptr;

        // Do not dispose here; since CEF 2537 the ResourceHandlerWrapper pointer is
        // referenced after Cancel and disposal would cause an access violation.
        //delete this;
    }

    int64 ResourceHandlerWrapper::SizeFromStream()
    {
        if (static_cast<Stream^>(_stream) == nullptr)
        {
            return 0;
        }

        if (_stream->CanSeek)
        {
            _stream->Seek(0, System::IO::SeekOrigin::End);
            int64 length = static_cast<int>(_stream->Position);
            _stream->Seek(0, System::IO::SeekOrigin::Begin);
            return length;
        }
        return -1;
    }
}<|endoftext|>


<commit_before>/** \copyright
 * Copyright (c) 2015, Balazs Racz
 * 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.
 *
 * 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 HOLDER 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.
 *
 * \file ConfiguredConsumer.hxx
 *
 * Consumer class that uses CDI configuration and a GPIO template structure to
 * export a single bit as two event consumers to OpenLCB.
 *
 * @author Balazs Racz
 * @date 13 June 2015
 */

#ifndef _NMRANET_CONFIGUREDCONSUMER_HXX_
#define _NMRANET_CONFIGUREDCONSUMER_HXX_

#include "nmranet/SimpleStack.hxx"
#include "nmranet/EventHandlerTemplates.hxx"
#include "nmranet/ConfigRepresentation.hxx"
#include "utils/ConfigUpdateListener.hxx"

namespace nmranet
{

BEGIN_GROUP(ConsumerConfig, base);
EXTEND_GROUP(ConsumerConfig, base, event_on, EventConfigEntry, Name("Event On"),
    Description("Receiving this event ID will turn the output on."));
EXTEND_GROUP(ConsumerConfig, event_on, event_off, EventConfigEntry,
    Name("Event Off"),
    Description("Receiving this event ID will turn the output off."));
END_GROUP(ConsumerConfig, event_off);

class ConfiguredConsumer : public ConfigUpdateListener
{
public:
    using Impl = GPIOBit;

    template <class HW>
    ConfiguredConsumer(Node *node, const ConsumerConfig &cfg, const HW &)
        : impl_(node, 0, 0, &HW::get, &HW::set)
        , consumer_(&impl_)
        , cfg_(cfg)
    {
        ConfigUpdateService::instance()->register_update_listener(this);
    }

    UpdateAction apply_configuration(
        int fd, bool initial_load, BarrierNotifiable *done)
    {
        AutoNotify n(done);
        EventId cfg_event_on = cfg_.event_on().read(fd);
        EventId cfg_event_off = cfg_.event_off().read(fd);
        if (cfg_event_off != impl_.event_off() ||
            cfg_event_on != impl_.event_on())
        {
            auto saved_setter = impl_.setter_;
            auto saved_getter = impl_.getter_;
            auto saved_node = impl_.node();
            // Need to reinitialize the consumer. We do this with in-place
            // destruction and construction.
            consumer_.~BitEventConsumer();
            impl_.~Impl();
            new (&impl_) Impl(saved_node, cfg_event_on, cfg_event_off,
                saved_getter, saved_setter);
            new (&consumer_) BitEventConsumer(&impl_);
            return REINIT_NEEDED; // Causes events identify.
        }
        return UPDATED;
    }

    ///@TODO(balazs.racz): implement
    void factory_reset(int fd) OVERRIDE
    {
    }

private:
    Impl impl_;
    BitEventConsumer consumer_;
    const ConsumerConfig cfg_;
};

} // namespace nmranet

#endif // _NMRANET_CONFIGUREDCONSUMER_HXX_
<commit_msg>Fixes formatting.<commit_after>/** \copyright
 * Copyright (c) 2015, Balazs Racz
 * 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.
 *
 * 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 HOLDER 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.
 *
 * \file ConfiguredConsumer.hxx
 *
 * Consumer class that uses CDI configuration and a GPIO template structure to
 * export a single bit as two event consumers to OpenLCB.
 *
 * @author Balazs Racz
 * @date 13 June 2015
 */

#ifndef _NMRANET_CONFIGUREDCONSUMER_HXX_
#define _NMRANET_CONFIGUREDCONSUMER_HXX_

#include "nmranet/EventHandlerTemplates.hxx"
#include "nmranet/ConfigRepresentation.hxx"
#include "utils/ConfigUpdateListener.hxx"
#include "utils/ConfigUpdateService.hxx"

namespace nmranet
{

BEGIN_GROUP(ConsumerConfig, base);
EXTEND_GROUP(ConsumerConfig, base, event_on, EventConfigEntry, //
    Name("Event On"),
    Description("Receiving this event ID will turn the output on."));
EXTEND_GROUP(ConsumerConfig, event_on, event_off, EventConfigEntry, //
    Name("Event Off"),
    Description("Receiving this event ID will turn the output off."));
END_GROUP(ConsumerConfig, event_off);

class ConfiguredConsumer : public ConfigUpdateListener
{
public:
    using Impl = GPIOBit;

    template <class HW>
    ConfiguredConsumer(Node *node, const ConsumerConfig &cfg, const HW &)
        : impl_(node, 0, 0, &HW::get, &HW::set)
        , consumer_(&impl_)
        , cfg_(cfg)
    {
        ConfigUpdateService::instance()->register_update_listener(this);
    }

    UpdateAction apply_configuration(
        int fd, bool initial_load, BarrierNotifiable *done)
    {
        AutoNotify n(done);
        EventId cfg_event_on = cfg_.event_on().read(fd);
        EventId cfg_event_off = cfg_.event_off().read(fd);
        if (cfg_event_off != impl_.event_off() ||
            cfg_event_on != impl_.event_on())
        {
            auto saved_setter = impl_.setter_;
            auto saved_getter = impl_.getter_;
            auto saved_node = impl_.node();
            // Need to reinitialize the consumer. We do this with in-place
            // destruction and construction.
            consumer_.~BitEventConsumer();
            impl_.~Impl();
            new (&impl_) Impl(saved_node, cfg_event_on, cfg_event_off,
                saved_getter, saved_setter);
            new (&consumer_) BitEventConsumer(&impl_);
            return REINIT_NEEDED; // Causes events identify.
        }
        return UPDATED;
    }

    ///@TODO(balazs.racz): implement
    void factory_reset(int fd) OVERRIDE
    {
    }

private:
    Impl impl_;
    BitEventConsumer consumer_;
    const ConsumerConfig cfg_;
};

} // namespace nmranet

#endif // _NMRANET_CONFIGUREDCONSUMER_HXX_
<|endoftext|>


<commit_before><commit_msg>moved memleak into projectm-test<commit_after><|endoftext|>


<commit_before>// Copyright 2012 Luis Pedro Coelho <luis@luispedro.org>
// License: MIT (see COPYING.MIT file)

#include "base.h"
#include "_png.h"
#include "tools.h"

#include <png.h>

#include <cstring>
#include <vector>

namespace {

void throw_error(png_structp png_ptr, png_const_charp error_msg) {
    throw CannotReadError(error_msg);
}

class png_holder {
    public:
        png_holder(int m)
            :png_ptr((m == write_mode ? png_create_write_struct : png_create_read_struct)(PNG_LIBPNG_VER_STRING, 0, throw_error, 0))
            ,png_info(0)
            ,mode(holder_mode(m))
            { }
        ~png_holder() {
            png_infopp pp = (png_info ? &png_info : 0);
            if (mode == read_mode) png_destroy_read_struct(&png_ptr, pp, 0);
            else png_destroy_write_struct(&png_ptr, pp);
        }
        void create_info() {
            png_info = png_create_info_struct(png_ptr);
            if (!png_info) throw "error";
        }

        png_structp png_ptr;
        png_infop png_info;
        enum holder_mode { read_mode, write_mode } mode;
};

void read_from_source(png_structp png_ptr, png_byte* buffer, size_t n) {
    byte_source* s = static_cast<byte_source*>(png_get_io_ptr(png_ptr));
    const size_t actual = s->read(reinterpret_cast<byte*>(buffer), n);
    if (actual != n) {
        throw CannotReadError();
    }
}

void write_to_source(png_structp png_ptr, png_byte* buffer, size_t n) {
    byte_sink* s = static_cast<byte_sink*>(png_get_io_ptr(png_ptr));
    const size_t actual = s->write(reinterpret_cast<byte*>(buffer), n);
    if (actual != n) {
        throw CannotReadError();
    }
}
void flush_source(png_structp png_ptr) {
    byte_sink* s = static_cast<byte_sink*>(png_get_io_ptr(png_ptr));
    s->flush();
}

int color_type_of(Image* im) {
    if (im->ndims() == 2) return PNG_COLOR_TYPE_GRAY;
    if (im->ndims() != 3) throw CannotWriteError();
    if (im->dim(2) == 3) return PNG_COLOR_TYPE_RGB;
    if (im->dim(2) == 4) return PNG_COLOR_TYPE_RGBA;
    throw CannotWriteError();
}
}
std::auto_ptr<Image> PNGFormat::read(byte_source* src, ImageFactory* factory) {
    png_holder p(png_holder::read_mode);
    png_set_read_fn(p.png_ptr, src, read_from_source);
    p.create_info();
    png_read_info(p.png_ptr, p.png_info);

    const int w = png_get_image_width (p.png_ptr, p.png_info);
    const int h = png_get_image_height(p.png_ptr, p.png_info);
    int bit_depth = png_get_bit_depth(p.png_ptr, p.png_info);
    if (bit_depth != 8 && bit_depth != 16) {
        throw CannotReadError("Cannot read this bit depth and color combination");
    }
    int d = -1;
    switch (png_get_color_type(p.png_ptr, p.png_info)) {
        case PNG_COLOR_TYPE_PALETTE:
        png_set_palette_to_rgb(p.png_ptr);
        case PNG_COLOR_TYPE_RGB:
            d = 3;
            break;
        case PNG_COLOR_TYPE_RGB_ALPHA:
            d = 4;
            break;
        case PNG_COLOR_TYPE_GRAY:
            if (bit_depth < 8) {
                png_set_expand_gray_1_2_4_to_8(p.png_ptr);
                bit_depth = 8;
            }
            d = -1;
            break;
        default:
            throw CannotReadError("Unhandled color type");
    }

    std::auto_ptr<Image> output(factory->create(bit_depth, h, w, d));
    std::vector<png_bytep> rowps = allrows<png_byte>(*output);
    png_read_image(p.png_ptr, &rowps[0]);

    return output;
}

void PNGFormat::write(Image* input, byte_sink* output) {
    png_holder p(png_holder::write_mode);
    p.create_info();
    png_set_write_fn(p.png_ptr, output, write_to_source, flush_source);
    const int height = input->dim(0);
    const int width = input->dim(1);
    const int bit_depth = 8;
    const int color_type = color_type_of(input);

    png_set_IHDR(p.png_ptr, p.png_info, width, height,
                     bit_depth, color_type, PNG_INTERLACE_NONE,
                     PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
    png_write_info(p.png_ptr, p.png_info);

    std::vector<png_bytep> rowps = allrows<png_byte>(*input);
    png_write_image(p.png_ptr, &rowps[0]);
    png_write_end(p.png_ptr, p.png_info);
}

<commit_msg>ENH More checks and error messages<commit_after>// Copyright 2012 Luis Pedro Coelho <luis@luispedro.org>
// License: MIT (see COPYING.MIT file)

#include "base.h"
#include "_png.h"
#include "tools.h"

#include <png.h>

#include <cstring>
#include <vector>

namespace {

void throw_error(png_structp png_ptr, png_const_charp error_msg) {
    throw CannotReadError(error_msg);
}

class png_holder {
    public:
        png_holder(int m)
            :png_ptr((m == write_mode ? png_create_write_struct : png_create_read_struct)(PNG_LIBPNG_VER_STRING, 0, throw_error, 0))
            ,png_info(0)
            ,mode(holder_mode(m))
            { }
        ~png_holder() {
            png_infopp pp = (png_info ? &png_info : 0);
            if (mode == read_mode) png_destroy_read_struct(&png_ptr, pp, 0);
            else png_destroy_write_struct(&png_ptr, pp);
        }
        void create_info() {
            png_info = png_create_info_struct(png_ptr);
            if (!png_info) throw "error";
        }

        png_structp png_ptr;
        png_infop png_info;
        enum holder_mode { read_mode, write_mode } mode;
};

void read_from_source(png_structp png_ptr, png_byte* buffer, size_t n) {
    byte_source* s = static_cast<byte_source*>(png_get_io_ptr(png_ptr));
    const size_t actual = s->read(reinterpret_cast<byte*>(buffer), n);
    if (actual != n) {
        throw CannotReadError();
    }
}

void write_to_source(png_structp png_ptr, png_byte* buffer, size_t n) {
    byte_sink* s = static_cast<byte_sink*>(png_get_io_ptr(png_ptr));
    const size_t actual = s->write(reinterpret_cast<byte*>(buffer), n);
    if (actual != n) {
        throw CannotReadError();
    }
}
void flush_source(png_structp png_ptr) {
    byte_sink* s = static_cast<byte_sink*>(png_get_io_ptr(png_ptr));
    s->flush();
}

int color_type_of(Image* im) {
    if (im->nbits() != 8) throw CannotWriteError("Image must be 8 bits for PNG saving");
    if (im->ndims() == 2) return PNG_COLOR_TYPE_GRAY;
    if (im->ndims() != 3) throw CannotWriteError("Image must be either 2 or 3 dimensional");
    if (im->dim(2) == 3) return PNG_COLOR_TYPE_RGB;
    if (im->dim(2) == 4) return PNG_COLOR_TYPE_RGBA;
    throw CannotWriteError();
}
}
std::auto_ptr<Image> PNGFormat::read(byte_source* src, ImageFactory* factory) {
    png_holder p(png_holder::read_mode);
    png_set_read_fn(p.png_ptr, src, read_from_source);
    p.create_info();
    png_read_info(p.png_ptr, p.png_info);

    const int w = png_get_image_width (p.png_ptr, p.png_info);
    const int h = png_get_image_height(p.png_ptr, p.png_info);
    int bit_depth = png_get_bit_depth(p.png_ptr, p.png_info);
    if (bit_depth != 8 && bit_depth != 16) {
        throw CannotReadError("Cannot read this bit depth and color combination");
    }
    int d = -1;
    switch (png_get_color_type(p.png_ptr, p.png_info)) {
        case PNG_COLOR_TYPE_PALETTE:
        png_set_palette_to_rgb(p.png_ptr);
        case PNG_COLOR_TYPE_RGB:
            d = 3;
            break;
        case PNG_COLOR_TYPE_RGB_ALPHA:
            d = 4;
            break;
        case PNG_COLOR_TYPE_GRAY:
            if (bit_depth < 8) {
                png_set_expand_gray_1_2_4_to_8(p.png_ptr);
                bit_depth = 8;
            }
            d = -1;
            break;
        default:
            throw CannotReadError("Unhandled color type");
    }

    std::auto_ptr<Image> output(factory->create(bit_depth, h, w, d));
    std::vector<png_bytep> rowps = allrows<png_byte>(*output);
    png_read_image(p.png_ptr, &rowps[0]);

    return output;
}

void PNGFormat::write(Image* input, byte_sink* output) {
    png_holder p(png_holder::write_mode);
    p.create_info();
    png_set_write_fn(p.png_ptr, output, write_to_source, flush_source);
    const int height = input->dim(0);
    const int width = input->dim(1);
    const int bit_depth = 8;
    const int color_type = color_type_of(input);

    png_set_IHDR(p.png_ptr, p.png_info, width, height,
                     bit_depth, color_type, PNG_INTERLACE_NONE,
                     PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
    png_write_info(p.png_ptr, p.png_info);

    std::vector<png_bytep> rowps = allrows<png_byte>(*input);
    png_write_image(p.png_ptr, &rowps[0]);
    png_write_end(p.png_ptr, p.png_info);
}

<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

  Some parts of this code are derived from ITK. See ITKCopyright.txt
  for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbStandardFilterWatcher.h"

namespace otb
{

StandardFilterWatcher
::StandardFilterWatcher(itk::ProcessObject* process,
                        const char *comment)
    : FilterWatcherBase(process, comment)
{
  m_StarsCount = 50;
}

StandardFilterWatcher
::StandardFilterWatcher( const StandardFilterWatcher& watch)
{
  // Initialize state
  m_StarsCount = watch.m_StarsCount;
}

void
StandardFilterWatcher
::operator=(const StandardFilterWatcher &watch)
{
  // Initialize state
  m_StarsCount = watch.m_StarsCount;
}

void
StandardFilterWatcher
::ShowProgress()
{
  if (m_Process)
  {
    int progressPercent = static_cast<int>(m_Process->GetProgress()*100);
    std::string stars(static_cast<int>(m_Process->GetProgress()*m_StarsCount),'*');
    std::string blanks(static_cast<int>(m_StarsCount - m_Process->GetProgress()*m_StarsCount),' ');
    std::cout << "\rProcessing progress:" << progressPercent << "% [" << stars << blanks << "]" << std::flush;
  }
}

void
StandardFilterWatcher
::StartFilter()
{
  m_TimeProbe.Start();
  std::cout << (m_Process.GetPointer() ? m_Process->GetNameOfClass() : "None")
            << " \"" << m_Comment << "\" " << std::endl;
}

void
StandardFilterWatcher
::EndFilter()
{
  m_TimeProbe.Stop();
  std::cout << std::endl << "Filter took "
            << m_TimeProbe.GetMeanTime()
            << " seconds." << std::endl;
}

} // end namespace otb
<commit_msg>BUG: Fixed a bug on string creation for standard filter watcher<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

  Some parts of this code are derived from ITK. See ITKCopyright.txt
  for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbStandardFilterWatcher.h"

namespace otb
{

StandardFilterWatcher
::StandardFilterWatcher(itk::ProcessObject* process,
                        const char *comment)
    : FilterWatcherBase(process, comment)
{
  m_StarsCount = 50;
}

StandardFilterWatcher
::StandardFilterWatcher( const StandardFilterWatcher& watch)
{
  // Initialize state
  m_StarsCount = watch.m_StarsCount;
}

void
StandardFilterWatcher
::operator=(const StandardFilterWatcher &watch)
{
  // Initialize state
  m_StarsCount = watch.m_StarsCount;
}

void
StandardFilterWatcher
::ShowProgress()
{
  if (m_Process)
  {
     int progressPercent = static_cast<int>(m_Process->GetProgress()*100);
     int nbStars = static_cast<int>(m_Process->GetProgress()*m_StarsCount);
     int nbBlanks = m_StarsCount - nbStars;

     if(nbBlanks < 0)
       {
       nbBlanks = 0;
       }

     if(nbStars > m_StarsCount)
       {
       nbStars = m_StarsCount;
       }

     if(progressPercent > 100)
       {
       progressPercent = 100;
       }

     std::string stars(nbStars,'*');
     std::string blanks(nbBlanks,' ');
     std::cout << "\rProcessing progress: " << progressPercent << "% [" << stars << blanks<< "]" << std::flush;
  }
}

void
StandardFilterWatcher
::StartFilter()
{
  m_TimeProbe.Start();
  std::cout << (m_Process.GetPointer() ? m_Process->GetNameOfClass() : "None")
            << " \"" << m_Comment << "\" " << std::endl;
}

void
StandardFilterWatcher
::EndFilter()
{
   m_TimeProbe.Stop();
   std::cout << std::endl << "Filter took "
             << m_TimeProbe.GetMeanTime()
             << " seconds." << std::endl;
}
} // end namespace otb
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pages.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 18:49:10 $
 *
 *  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 _PAGES_HXX_
#define _PAGES_HXX_

#include <vcl/tabpage.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/dialog.hxx>
#include <vcl/scrbar.hxx>
#include <svtools/wizardmachine.hxx>
#include <svtools/svmedit.hxx>
#include <svtools/lstner.hxx>
#include <svtools/xtextedt.hxx>

namespace desktop
{
class WelcomePage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    svt::OWizardMachine *m_pParent;
    sal_Bool m_bLicenseNeedsAcceptance;
    enum OEMType
    {
        OEM_NONE, OEM_NORMAL, OEM_EXTENDED
    };
    OEMType checkOEM();
    bool bIsEvalVersion;
    bool bNoEvalText;
    void checkEval();

public:
    WelcomePage( svt::OWizardMachine* parent, const ResId& resid, sal_Bool bLicenseNeedsAcceptance );
protected:
    virtual void ActivatePage();
};

class LicenseView : public MultiLineEdit, public SfxListener
{
    BOOL            mbEndReached;
    Link            maEndReachedHdl;
    Link            maScrolledHdl;

public:
    LicenseView( Window* pParent, const ResId& rResId );
    ~LicenseView();

    void ScrollDown( ScrollType eScroll );

    BOOL IsEndReached() const;
    BOOL EndReached() const { return mbEndReached; }
    void SetEndReached( BOOL bEnd ) { mbEndReached = bEnd; }

    void SetEndReachedHdl( const Link& rHdl )  { maEndReachedHdl = rHdl; }
    const Link& GetAutocompleteHdl() const { return maEndReachedHdl; }

    void SetScrolledHdl( const Link& rHdl )  { maScrolledHdl = rHdl; }
    const Link& GetScrolledHdl() const { return maScrolledHdl; }

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

protected:
    using MultiLineEdit::Notify;
};

class LicensePage : public svt::OWizardPage
{
private:
    svt::OWizardMachine *m_pParent;
    FixedText m_ftHead;
    FixedText m_ftBody1;
    FixedText m_ftBody1Txt;
    FixedText m_ftBody2;
    FixedText m_ftBody2Txt;
    LicenseView m_mlLicense;
    PushButton m_pbDown;
    sal_Bool m_bLicenseRead;
public:
    LicensePage( svt::OWizardMachine* parent, const ResId& resid, const rtl::OUString &rLicensePath );
private:
    DECL_LINK(PageDownHdl, PushButton*);
    DECL_LINK(EndReachedHdl, LicenseView*);
    DECL_LINK(ScrolledHdl, LicenseView*);
protected:
    virtual bool canAdvance() const;
    virtual void ActivatePage();
};

class MigrationPage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    CheckBox m_cbMigration;
    sal_Bool m_bMigrationDone;
public:
    MigrationPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage( CommitPageReason _eReason );

protected:
    virtual void ActivatePage();
};

class UserPage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    FixedText m_ftFirst;
    Edit m_edFirst;
    FixedText m_ftLast;
    Edit m_edLast;
    FixedText m_ftInitials;
    Edit m_edInitials;
    FixedText m_ftFather;
    Edit m_edFather;
    LanguageType m_lang;

public:
    UserPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage( CommitPageReason _eReason );
protected:
    virtual void ActivatePage();
};

class UpdateCheckPage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    CheckBox m_cbUpdateCheck;
public:
    UpdateCheckPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage( CommitPageReason _eReason );

protected:
    virtual void ActivatePage();
};

class RegistrationPage : public svt::OWizardPage
{
private:
    FixedText   m_ftHeader;
    FixedText   m_ftBody;
    FixedImage  m_fiImage;
    RadioButton m_rbNow;
    RadioButton m_rbLater;
    RadioButton m_rbNever;
    RadioButton m_rbReg;
    FixedLine   m_flSeparator;
    FixedText   m_ftEnd;

    sal_Bool    m_bNeverVisible;

    void updateButtonStates();
    void impl_retrieveConfigurationData();

protected:
    virtual bool canAdvance() const;
    virtual void ActivatePage();

    virtual sal_Bool commitPage( CommitPageReason _eReason );

public:
    RegistrationPage( Window* parent, const ResId& resid);

    enum RegistrationMode
    {
        rmNow,      // register now
        rmLater,    // register later
        rmNever,    // register never
        rmAlready   // already registered
    };

    RegistrationMode    getRegistrationMode() const;
    void                prepareSingleMode();
    inline String       getSingleModeTitle() const { return m_ftHeader.GetText(); }

    static bool         hasReminderDateCome();
    static void         executeSingleMode();
};

} // namespace desktop

#endif // #ifndef _PAGES_HXX_

<commit_msg>INTEGRATION: CWS newregdlg (1.11.20); FILE MERGED 2008/03/05 13:34:10 pb 1.11.20.2: fix: #i86683# syntax error fixed 2008/03/05 13:22:25 pb 1.11.20.1: fix: #i86683# Registration tabpage changed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pages.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 08:46:31 $
 *
 *  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 _PAGES_HXX_
#define _PAGES_HXX_

#include <vcl/tabpage.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/dialog.hxx>
#include <vcl/scrbar.hxx>
#include <svtools/wizardmachine.hxx>
#include <svtools/svmedit.hxx>
#include <svtools/lstner.hxx>
#include <svtools/xtextedt.hxx>

namespace desktop
{
class WelcomePage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    svt::OWizardMachine *m_pParent;
    sal_Bool m_bLicenseNeedsAcceptance;
    enum OEMType
    {
        OEM_NONE, OEM_NORMAL, OEM_EXTENDED
    };
    OEMType checkOEM();
    bool bIsEvalVersion;
    bool bNoEvalText;
    void checkEval();

public:
    WelcomePage( svt::OWizardMachine* parent, const ResId& resid, sal_Bool bLicenseNeedsAcceptance );
protected:
    virtual void ActivatePage();
};

class LicenseView : public MultiLineEdit, public SfxListener
{
    BOOL            mbEndReached;
    Link            maEndReachedHdl;
    Link            maScrolledHdl;

public:
    LicenseView( Window* pParent, const ResId& rResId );
    ~LicenseView();

    void ScrollDown( ScrollType eScroll );

    BOOL IsEndReached() const;
    BOOL EndReached() const { return mbEndReached; }
    void SetEndReached( BOOL bEnd ) { mbEndReached = bEnd; }

    void SetEndReachedHdl( const Link& rHdl )  { maEndReachedHdl = rHdl; }
    const Link& GetAutocompleteHdl() const { return maEndReachedHdl; }

    void SetScrolledHdl( const Link& rHdl )  { maScrolledHdl = rHdl; }
    const Link& GetScrolledHdl() const { return maScrolledHdl; }

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

protected:
    using MultiLineEdit::Notify;
};

class LicensePage : public svt::OWizardPage
{
private:
    svt::OWizardMachine *m_pParent;
    FixedText m_ftHead;
    FixedText m_ftBody1;
    FixedText m_ftBody1Txt;
    FixedText m_ftBody2;
    FixedText m_ftBody2Txt;
    LicenseView m_mlLicense;
    PushButton m_pbDown;
    sal_Bool m_bLicenseRead;
public:
    LicensePage( svt::OWizardMachine* parent, const ResId& resid, const rtl::OUString &rLicensePath );
private:
    DECL_LINK(PageDownHdl, PushButton*);
    DECL_LINK(EndReachedHdl, LicenseView*);
    DECL_LINK(ScrolledHdl, LicenseView*);
protected:
    virtual bool canAdvance() const;
    virtual void ActivatePage();
};

class MigrationPage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    CheckBox m_cbMigration;
    sal_Bool m_bMigrationDone;
public:
    MigrationPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage( CommitPageReason _eReason );

protected:
    virtual void ActivatePage();
};

class UserPage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    FixedText m_ftFirst;
    Edit m_edFirst;
    FixedText m_ftLast;
    Edit m_edLast;
    FixedText m_ftInitials;
    Edit m_edInitials;
    FixedText m_ftFather;
    Edit m_edFather;
    LanguageType m_lang;

public:
    UserPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage( CommitPageReason _eReason );
protected:
    virtual void ActivatePage();
};

class UpdateCheckPage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    CheckBox m_cbUpdateCheck;
public:
    UpdateCheckPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage( CommitPageReason _eReason );

protected:
    virtual void ActivatePage();
};

class RegistrationPage : public svt::OWizardPage
{
private:
    FixedText   m_ftHeader;
    FixedText   m_ftBody;
    RadioButton m_rbNow;
    RadioButton m_rbLater;
    RadioButton m_rbNever;
    FixedLine   m_flSeparator;
    FixedText   m_ftEnd;

    sal_Bool    m_bNeverVisible;

    void updateButtonStates();
    void impl_retrieveConfigurationData();

protected:
    virtual bool canAdvance() const;
    virtual void ActivatePage();

    virtual sal_Bool commitPage( CommitPageReason _eReason );

public:
    RegistrationPage( Window* parent, const ResId& resid);

    enum RegistrationMode
    {
        rmNow,      // register now
        rmLater,    // register later
        rmNever     // register never
    };

    RegistrationMode    getRegistrationMode() const;
    void                prepareSingleMode();
    inline String       getSingleModeTitle() const { return m_ftHeader.GetText(); }

    static bool         hasReminderDateCome();
    static void         executeSingleMode();
};

} // namespace desktop

#endif // #ifndef _PAGES_HXX_

<|endoftext|>


<commit_before>/*
Copyright (C) 2011 by Ivan Safrin

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

#include "PolyGLSLProgram.h"
#include "PolyVector3.h"
#include "PolyVector2.h"
#include "PolyColor.h"
#include "PolyLogger.h"
#include "PolyCoreServices.h"
#include "PolyLogger.h"

#ifdef _WINDOWS
#include <windows.h>

// Some shader functions that aren't defined in glext/wglext
extern PFNGLGETSHADERIVPROC glGetShaderiv;
extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;

#endif

#include "PolyGLHeaders.h"

using std::vector;

#ifdef _WINDOWS
extern PFNGLUSEPROGRAMPROC glUseProgram;
extern PFNGLUNIFORM1IPROC glUniform1i;
extern PFNGLACTIVETEXTUREPROC glActiveTexture;
extern PFNGLCREATESHADERPROC glCreateShader;
extern PFNGLSHADERSOURCEPROC glShaderSource;
extern PFNGLCOMPILESHADERPROC glCompileShader;
extern PFNGLCREATEPROGRAMPROC glCreateProgram;
extern PFNGLATTACHSHADERPROC glAttachShader;
extern PFNGLLINKPROGRAMPROC glLinkProgram;
extern PFNGLDETACHSHADERPROC glDetachShader;
extern PFNGLDELETESHADERPROC glDeleteShader;
extern PFNGLDELETEPROGRAMPROC glDeleteProgram;
#ifndef _MINGW
extern PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocation;
#endif
#endif

using namespace Polycode;

GLSLProgram::GLSLProgram(String fileName, int type) : ShaderProgram(type) {
	program = -1;
	this->fileName = fileName;
	reloadProgram();
}

GLSLProgram::~GLSLProgram() {
	glDeleteShader(program);
}

void GLSLProgram::reloadProgram() {
	if(program != -1)
		glDeleteShader(program);

	OSFILE *file = OSBasics::open(fileName, "r");
	OSBasics::seek(file, 0, SEEK_END);
	long progsize = OSBasics::tell(file);
	OSBasics::seek(file, 0, SEEK_SET);
	char *buffer = (char*)malloc(progsize+1);
	memset(buffer, 0, progsize+1);
	OSBasics::read(buffer, progsize, 1, file);
	OSBasics::close(file);

	if(type == GLSLProgram::TYPE_VERT) {
		program =  glCreateShader(GL_VERTEX_SHADER);
	} else {
		program =  glCreateShader(GL_FRAGMENT_SHADER);
	}

	glShaderSource(program, 1, (const GLchar**)&buffer, 0);
	glCompileShader(program);

	GLint compiled = true;
    glGetShaderiv(program, GL_COMPILE_STATUS, &compiled);
    if(!compiled) {
        GLint length;
        GLchar* log;
        glGetShaderiv(program, GL_INFO_LOG_LENGTH, &length);
        log = (GLchar*)malloc(length);
        glGetShaderInfoLog(program, length, &length, log);
		printf("GLSL ERROR: %s\n", log);
		CoreServices::getInstance()->getLogger()->logBroadcast("GLSL ERROR:" + String(log));
        free(log);
    }
	free(buffer);
}<commit_msg>Fixed a missing header.<commit_after>/*
Copyright (C) 2011 by Ivan Safrin

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

#include "PolyGLSLProgram.h"
#include "PolyVector3.h"
#include "PolyVector2.h"
#include "PolyColor.h"
#include "PolyLogger.h"
#include "PolyCoreServices.h"
#include "PolyLogger.h"
#include "PolyGLHeaders.h"

#ifdef _WINDOWS
#include <windows.h>

// Some shader functions that aren't defined in glext/wglext
extern PFNGLGETSHADERIVPROC glGetShaderiv;
extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;

#endif

#include "PolyGLHeaders.h"

using std::vector;

#ifdef _WINDOWS
extern PFNGLUSEPROGRAMPROC glUseProgram;
extern PFNGLUNIFORM1IPROC glUniform1i;
extern PFNGLACTIVETEXTUREPROC glActiveTexture;
extern PFNGLCREATESHADERPROC glCreateShader;
extern PFNGLSHADERSOURCEPROC glShaderSource;
extern PFNGLCOMPILESHADERPROC glCompileShader;
extern PFNGLCREATEPROGRAMPROC glCreateProgram;
extern PFNGLATTACHSHADERPROC glAttachShader;
extern PFNGLLINKPROGRAMPROC glLinkProgram;
extern PFNGLDETACHSHADERPROC glDetachShader;
extern PFNGLDELETESHADERPROC glDeleteShader;
extern PFNGLDELETEPROGRAMPROC glDeleteProgram;
#ifndef _MINGW
extern PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocation;
#endif
#endif

using namespace Polycode;

GLSLProgram::GLSLProgram(String fileName, int type) : ShaderProgram(type) {
	program = -1;
	this->fileName = fileName;
	reloadProgram();
}

GLSLProgram::~GLSLProgram() {
	glDeleteShader(program);
}

void GLSLProgram::reloadProgram() {
	if(program != -1)
		glDeleteShader(program);

	OSFILE *file = OSBasics::open(fileName, "r");
	OSBasics::seek(file, 0, SEEK_END);
	long progsize = OSBasics::tell(file);
	OSBasics::seek(file, 0, SEEK_SET);
	char *buffer = (char*)malloc(progsize+1);
	memset(buffer, 0, progsize+1);
	OSBasics::read(buffer, progsize, 1, file);
	OSBasics::close(file);

	if(type == GLSLProgram::TYPE_VERT) {
		program =  glCreateShader(GL_VERTEX_SHADER);
	} else {
		program =  glCreateShader(GL_FRAGMENT_SHADER);
	}

	glShaderSource(program, 1, (const GLchar**)&buffer, 0);
	glCompileShader(program);

	GLint compiled = true;
    glGetShaderiv(program, GL_COMPILE_STATUS, &compiled);
    if(!compiled) {
        GLint length;
        GLchar* log;
        glGetShaderiv(program, GL_INFO_LOG_LENGTH, &length);
        log = (GLchar*)malloc(length);
        glGetShaderInfoLog(program, length, &length, log);
		printf("GLSL ERROR: %s\n", log);
		CoreServices::getInstance()->getLogger()->logBroadcast("GLSL ERROR:" + String(log));
        free(log);
    }
	free(buffer);
}<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

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

#include "mitkSplineVtkMapper3D.h"
#include <vtkProp.h>
#include <vtkPropAssembly.h>
#include <vtkCardinalSpline.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkCellArray.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkProperty.h>
#include <vtkTubeFilter.h>
#include <vtkPropCollection.h>
#include <mitkProperties.h>
#include <mitkPointSet.h>

mitk::SplineVtkMapper3D::SplineVtkMapper3D()
: m_SplinesAvailable (false), m_SplinesAddedToAssembly(false)
{
  m_SplinesActor = vtkActor::New();
  m_SplineAssembly = vtkPropAssembly::New();
  m_SplineResolution = 500;
}

mitk::SplineVtkMapper3D::~SplineVtkMapper3D()
{
  m_SplinesActor->Delete();
  m_SplineAssembly->Delete();
}

vtkProp*
mitk::SplineVtkMapper3D::GetProp()
{
  if (GetDataTreeNode() == NULL)
    return NULL;

  //to assign User Transforms in superclass
  Superclass::GetProp();

  m_SplinesActor->SetUserTransform( GetDataTreeNode()->GetVtkTransform() );

  return m_SplineAssembly;
}

void
mitk::SplineVtkMapper3D::GenerateData()
{
  Superclass::GenerateData();

  // only update spline if UpdateSpline has not been called from
  // external, e.g. by the SplineMapper2D.
  if ( m_SplineUpdateTime < m_LastUpdateTime )
  {
    UpdateSpline();
    this->ApplyProperties();
  }

  if ( m_SplinesAvailable )
  {
    if ( ! m_SplinesAddedToAssembly )
    {
      m_SplineAssembly->AddPart( m_SplinesActor );
      m_SplinesAddedToAssembly = true;
    }
  }
  else
  {
    if ( m_SplinesAddedToAssembly )
    {
      m_SplineAssembly->RemovePart( m_SplinesActor );
      m_SplinesAddedToAssembly = false;
    }
  }
}

void mitk::SplineVtkMapper3D::GenerateData( mitk::BaseRenderer* renderer )
{
  if ( IsVisible( renderer ) == false )
  {
    m_SplinesActor->VisibilityOff();
    m_SplineAssembly->VisibilityOff();
  }
  else
  {
    m_SplinesActor->VisibilityOn();
    m_SplineAssembly->VisibilityOn();

    //remove the PointsAssembly if it was added insuperclass. No need to display points and spline!
    if(m_SplineAssembly->GetParts()->IsItemPresent(m_PointsAssembly))
      m_SplineAssembly->RemovePart(m_PointsAssembly);
    this->ApplyProperties();

  }
}

void mitk::SplineVtkMapper3D::ApplyProperties()
{
//todo: only call if needed and properties have been changed!!!

  //vtk changed the type of rgba during releases. Due to that, the following convert is done
  vtkFloatingPointType rgba[ 4 ] = {1.0f, 1.0f, 1.0f, 1.0f};//white

  //getting the color from DataTreeNode
  float temprgba[4];
  this->GetDataTreeNode()->GetColor( &temprgba[0], NULL );
  //convert to rgba, what ever type it has!
  rgba[0] = temprgba[0];    rgba[1] = temprgba[1];    rgba[2] = temprgba[2];    rgba[3] = temprgba[3];
  //finaly set the color inside the actor
  m_SplinesActor->GetProperty()->SetColor( rgba );

  float lineWidth;
  if (dynamic_cast<mitk::FloatProperty *>(this->GetDataTreeNode()->GetProperty("linewidth").GetPointer()) == NULL)
    lineWidth = 1.0;
  else
    lineWidth = dynamic_cast<mitk::FloatProperty *>(this->GetDataTreeNode()->GetProperty("linewidth").GetPointer())->GetValue();
  m_SplinesActor->GetProperty()->SetLineWidth(lineWidth);
}

bool mitk::SplineVtkMapper3D::SplinesAreAvailable()
{
  return m_SplinesAvailable;
}

vtkPolyData* mitk::SplineVtkMapper3D::GetSplinesPolyData()
{
  Mapper::Update(NULL);
  if ( m_SplinesAvailable )
    return ( dynamic_cast<vtkPolyDataMapper*>( m_SplinesActor->GetMapper() ) )->GetInput();
  else
    return NULL;
}

vtkActor* mitk::SplineVtkMapper3D::GetSplinesActor()
{
  Mapper::Update(NULL);
  if ( m_SplinesAvailable )
    return m_SplinesActor;
  else
    return vtkActor::New();
}

unsigned long mitk::SplineVtkMapper3D::GetLastUpdateTime() const
{
  return m_LastUpdateTime.GetMTime();
}

void mitk::SplineVtkMapper3D::UpdateSpline()
{
  mitk::PointSet::Pointer input = const_cast<mitk::PointSet*>( this->GetInput( ) );
//  input->Update();//already done in superclass

  // Number of points on the spline
  unsigned int numberOfOutputPoints = m_SplineResolution;
  unsigned int numberOfInputPoints = input->GetSize();

  if ( numberOfInputPoints >= 2 )
  {
    m_SplinesAvailable = true;
    vtkCardinalSpline* splineX = vtkCardinalSpline::New();
    vtkCardinalSpline* splineY = vtkCardinalSpline::New();
    vtkCardinalSpline* splineZ = vtkCardinalSpline::New();
    unsigned int index = 0;
    mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = input->GetPointSet()->GetPoints();
    for ( mitk::PointSet::DataType::PointsContainer::Iterator it = pointsContainer->Begin(); it != pointsContainer->End(); ++it, ++index )
    //for ( unsigned int i = 0 ; i < numberOfInputPoints; ++i )
    {
      mitk::PointSet::PointType point = it->Value();
      splineX->AddPoint( index, point[ 0 ] );
      splineY->AddPoint( index, point[ 1 ] );
      splineZ->AddPoint( index, point[ 2 ] );
    }
    vtkPoints* points = vtkPoints::New();
    vtkPolyData* profileData = vtkPolyData::New();

    // Interpolate x, y and z by using the three spline filters and
    // create new points
    double t = 0.0f;
    for ( unsigned int i = 0; i < numberOfOutputPoints; ++i )
    {
      t = ( ( ( ( double ) numberOfInputPoints ) - 1.0f ) / ( ( ( double ) numberOfOutputPoints ) - 1.0f ) ) * ( ( double ) i );
      points->InsertPoint( i, splineX->Evaluate( t ), splineY->Evaluate( t ), splineZ->Evaluate( t ) ) ;
    }

    // Create the polyline.
    vtkCellArray* lines = vtkCellArray::New();
    lines->InsertNextCell( numberOfOutputPoints );
    for ( unsigned int i = 0; i < numberOfOutputPoints; ++i )
      lines->InsertCellPoint( i );

    profileData->SetPoints( points );
    profileData->SetLines( lines );

    // Add thickness to the resulting line.
    //vtkTubeFilter* profileTubes = vtkTubeFilter::New();
    //profileTubes->SetNumberOfSides(8);
    //profileTubes->SetInput(profileData);
    //profileTubes->SetRadius(.005);

    vtkPolyDataMapper* profileMapper = vtkPolyDataMapper::New();
    profileMapper->SetInput( profileData );

    m_SplinesActor->SetMapper( profileMapper );
  }
  else
  {
    m_SplinesAvailable = false;
  }
  m_SplineUpdateTime.Modified();
}

<commit_msg>FIX: removed problematic call to Mapper::Update(NULL) leading to spurious segmentation faults.<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

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

#include "mitkSplineVtkMapper3D.h"
#include <vtkProp.h>
#include <vtkPropAssembly.h>
#include <vtkCardinalSpline.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkCellArray.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkProperty.h>
#include <vtkTubeFilter.h>
#include <vtkPropCollection.h>
#include <mitkProperties.h>
#include <mitkPointSet.h>

mitk::SplineVtkMapper3D::SplineVtkMapper3D()
: m_SplinesAvailable (false), m_SplinesAddedToAssembly(false)
{
  m_SplinesActor = vtkActor::New();
  m_SplineAssembly = vtkPropAssembly::New();
  m_SplineResolution = 500;
}

mitk::SplineVtkMapper3D::~SplineVtkMapper3D()
{
  m_SplinesActor->Delete();
  m_SplineAssembly->Delete();
}

vtkProp*
mitk::SplineVtkMapper3D::GetProp()
{
  if (GetDataTreeNode() == NULL)
    return NULL;

  //to assign User Transforms in superclass
  Superclass::GetProp();

  m_SplinesActor->SetUserTransform( GetDataTreeNode()->GetVtkTransform() );

  return m_SplineAssembly;
}

void
mitk::SplineVtkMapper3D::GenerateData()
{
  Superclass::GenerateData();

  // only update spline if UpdateSpline has not been called from
  // external, e.g. by the SplineMapper2D.
  if ( m_SplineUpdateTime < m_LastUpdateTime )
  {
    UpdateSpline();
    this->ApplyProperties();
  }

  if ( m_SplinesAvailable )
  {
    if ( ! m_SplinesAddedToAssembly )
    {
      m_SplineAssembly->AddPart( m_SplinesActor );
      m_SplinesAddedToAssembly = true;
    }
  }
  else
  {
    if ( m_SplinesAddedToAssembly )
    {
      m_SplineAssembly->RemovePart( m_SplinesActor );
      m_SplinesAddedToAssembly = false;
    }
  }
}

void mitk::SplineVtkMapper3D::GenerateData( mitk::BaseRenderer* renderer )
{
  if ( IsVisible( renderer ) == false )
  {
    m_SplinesActor->VisibilityOff();
    m_SplineAssembly->VisibilityOff();
  }
  else
  {
    m_SplinesActor->VisibilityOn();
    m_SplineAssembly->VisibilityOn();

    //remove the PointsAssembly if it was added insuperclass. No need to display points and spline!
    if(m_SplineAssembly->GetParts()->IsItemPresent(m_PointsAssembly))
      m_SplineAssembly->RemovePart(m_PointsAssembly);
    this->ApplyProperties();

  }
}

void mitk::SplineVtkMapper3D::ApplyProperties()
{
//todo: only call if needed and properties have been changed!!!

  //vtk changed the type of rgba during releases. Due to that, the following convert is done
  vtkFloatingPointType rgba[ 4 ] = {1.0f, 1.0f, 1.0f, 1.0f};//white

  //getting the color from DataTreeNode
  float temprgba[4];
  this->GetDataTreeNode()->GetColor( &temprgba[0], NULL );
  //convert to rgba, what ever type it has!
  rgba[0] = temprgba[0];    rgba[1] = temprgba[1];    rgba[2] = temprgba[2];    rgba[3] = temprgba[3];
  //finaly set the color inside the actor
  m_SplinesActor->GetProperty()->SetColor( rgba );

  float lineWidth;
  if (dynamic_cast<mitk::FloatProperty *>(this->GetDataTreeNode()->GetProperty("linewidth").GetPointer()) == NULL)
    lineWidth = 1.0;
  else
    lineWidth = dynamic_cast<mitk::FloatProperty *>(this->GetDataTreeNode()->GetProperty("linewidth").GetPointer())->GetValue();
  m_SplinesActor->GetProperty()->SetLineWidth(lineWidth);
}

bool mitk::SplineVtkMapper3D::SplinesAreAvailable()
{
  return m_SplinesAvailable;
}

vtkPolyData* mitk::SplineVtkMapper3D::GetSplinesPolyData()
{
  if ( m_SplinesAvailable )
    return ( dynamic_cast<vtkPolyDataMapper*>( m_SplinesActor->GetMapper() ) )->GetInput();
  else
    return NULL;
}

vtkActor* mitk::SplineVtkMapper3D::GetSplinesActor()
{
  if ( m_SplinesAvailable )
    return m_SplinesActor;
  else
    return vtkActor::New();
}

unsigned long mitk::SplineVtkMapper3D::GetLastUpdateTime() const
{
  return m_LastUpdateTime.GetMTime();
}

void mitk::SplineVtkMapper3D::UpdateSpline()
{
  mitk::PointSet::Pointer input = const_cast<mitk::PointSet*>( this->GetInput( ) );
//  input->Update();//already done in superclass

  // Number of points on the spline
  unsigned int numberOfOutputPoints = m_SplineResolution;
  unsigned int numberOfInputPoints = input->GetSize();

  if ( numberOfInputPoints >= 2 )
  {
    m_SplinesAvailable = true;
    vtkCardinalSpline* splineX = vtkCardinalSpline::New();
    vtkCardinalSpline* splineY = vtkCardinalSpline::New();
    vtkCardinalSpline* splineZ = vtkCardinalSpline::New();
    unsigned int index = 0;
    mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = input->GetPointSet()->GetPoints();
    for ( mitk::PointSet::DataType::PointsContainer::Iterator it = pointsContainer->Begin(); it != pointsContainer->End(); ++it, ++index )
    //for ( unsigned int i = 0 ; i < numberOfInputPoints; ++i )
    {
      mitk::PointSet::PointType point = it->Value();
      splineX->AddPoint( index, point[ 0 ] );
      splineY->AddPoint( index, point[ 1 ] );
      splineZ->AddPoint( index, point[ 2 ] );
    }
    vtkPoints* points = vtkPoints::New();
    vtkPolyData* profileData = vtkPolyData::New();

    // Interpolate x, y and z by using the three spline filters and
    // create new points
    double t = 0.0f;
    for ( unsigned int i = 0; i < numberOfOutputPoints; ++i )
    {
      t = ( ( ( ( double ) numberOfInputPoints ) - 1.0f ) / ( ( ( double ) numberOfOutputPoints ) - 1.0f ) ) * ( ( double ) i );
      points->InsertPoint( i, splineX->Evaluate( t ), splineY->Evaluate( t ), splineZ->Evaluate( t ) ) ;
    }

    // Create the polyline.
    vtkCellArray* lines = vtkCellArray::New();
    lines->InsertNextCell( numberOfOutputPoints );
    for ( unsigned int i = 0; i < numberOfOutputPoints; ++i )
      lines->InsertCellPoint( i );

    profileData->SetPoints( points );
    profileData->SetLines( lines );

    // Add thickness to the resulting line.
    //vtkTubeFilter* profileTubes = vtkTubeFilter::New();
    //profileTubes->SetNumberOfSides(8);
    //profileTubes->SetInput(profileData);
    //profileTubes->SetRadius(.005);

    vtkPolyDataMapper* profileMapper = vtkPolyDataMapper::New();
    profileMapper->SetInput( profileData );

    m_SplinesActor->SetMapper( profileMapper );
  }
  else
  {
    m_SplinesAvailable = false;
  }
  m_SplineUpdateTime.Modified();
}

<|endoftext|>