<commit_before>/*
 * Copyright (c) 2006, 2007, 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 "config.h"
#include "public/platform/Platform.h"

#include "SkTypeface.h"
#include "platform/LayoutTestSupport.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/fonts/harfbuzz/FontPlatformDataHarfBuzz.h"
#include "public/platform/linux/WebFontInfo.h"
#include "public/platform/linux/WebFontRenderStyle.h"
#include "public/platform/linux/WebSandboxSupport.h"

namespace WebCore {

static SkPaint::Hinting skiaHinting = SkPaint::kNormal_Hinting;
static bool useSkiaAutoHint = true;
static bool useSkiaBitmaps = true;
static bool useSkiaAntiAlias = true;
static bool useSkiaSubpixelRendering = false;

void FontPlatformData::setHinting(SkPaint::Hinting hinting)
{
    skiaHinting = hinting;
}

void FontPlatformData::setAutoHint(bool useAutoHint)
{
    useSkiaAutoHint = useAutoHint;
}

void FontPlatformData::setUseBitmaps(bool useBitmaps)
{
    useSkiaBitmaps = useBitmaps;
}

void FontPlatformData::setAntiAlias(bool useAntiAlias)
{
    useSkiaAntiAlias = useAntiAlias;
}

void FontPlatformData::setSubpixelRendering(bool useSubpixelRendering)
{
    useSkiaSubpixelRendering = useSubpixelRendering;
}

void FontPlatformData::setupPaint(SkPaint* paint, GraphicsContext*) const
{
    paint->setAntiAlias(m_style.useAntiAlias);
    paint->setHinting(static_cast<SkPaint::Hinting>(m_style.hintStyle));
    paint->setEmbeddedBitmapText(m_style.useBitmaps);
    paint->setAutohinted(m_style.useAutoHint);
    if (m_style.useAntiAlias)
        paint->setLCDRenderText(m_style.useSubpixelRendering);

    // TestRunner specifically toggles the subpixel positioning flag.
    if (RuntimeEnabledFeatures::subpixelFontScalingEnabled() && !isRunningLayoutTest())
        paint->setSubpixelText(true);
    else
        paint->setSubpixelText(m_style.useSubpixelPositioning);

    const float ts = m_textSize >= 0 ? m_textSize : 12;
    paint->setTextSize(SkFloatToScalar(ts));
    paint->setTypeface(m_typeface.get());
    paint->setFakeBoldText(m_syntheticBold);
    paint->setTextSkewX(m_syntheticItalic ? -SK_Scalar1 / 4 : 0);
}

static inline void getRenderStyleForStrike(FontRenderStyle& fontRenderStyle, const char* font, int sizeAndStyle)
{
    blink::WebFontRenderStyle style;

#if OS(ANDROID)
    style.setDefaults();
#else
    if (!font || !*font)
        style.setDefaults(); // It's probably a webfont. Take the system defaults.
    else if (blink::Platform::current()->sandboxSupport())
        blink::Platform::current()->sandboxSupport()->getRenderStyleForStrike(font, sizeAndStyle, &style);
    else
        blink::WebFontInfo::renderStyleForStrike(font, sizeAndStyle, &style);
#endif

    style.toFontRenderStyle(&fontRenderStyle);
}

void FontPlatformData::querySystemForRenderStyle(bool useSkiaSubpixelPositioning)
{
    getRenderStyleForStrike(m_style, m_family.data(), (((int)m_textSize) << 2) | (m_typeface->style() & 3));

    // Fix FontRenderStyle::NoPreference to actual styles.
    if (m_style.useAntiAlias == FontRenderStyle::NoPreference)
        m_style.useAntiAlias = useSkiaAntiAlias;

    if (!m_style.useHinting)
        m_style.hintStyle = SkPaint::kNo_Hinting;
    else if (m_style.useHinting == FontRenderStyle::NoPreference)
        m_style.hintStyle = skiaHinting;

    if (m_style.useBitmaps == FontRenderStyle::NoPreference)
        m_style.useBitmaps = useSkiaBitmaps;
    if (m_style.useAutoHint == FontRenderStyle::NoPreference)
        m_style.useAutoHint = useSkiaAutoHint;
    if (m_style.useAntiAlias == FontRenderStyle::NoPreference)
        m_style.useAntiAlias = useSkiaAntiAlias;
    if (m_style.useSubpixelRendering == FontRenderStyle::NoPreference)
        m_style.useSubpixelRendering = useSkiaSubpixelRendering;

    // TestRunner specifically toggles the subpixel positioning flag.
    if (m_style.useSubpixelPositioning == FontRenderStyle::NoPreference
        || isRunningLayoutTest())
        m_style.useSubpixelPositioning = useSkiaSubpixelPositioning;
}

bool FontPlatformData::defaultUseSubpixelPositioning()
{
    return FontDescription::subpixelPositioning();
}

} // namespace WebCore
<commit_msg>Disable subpixel text on linux systems with full_hinting<commit_after>/*
 * Copyright (c) 2006, 2007, 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 "config.h"
#include "public/platform/Platform.h"

#include "SkTypeface.h"
#include "platform/LayoutTestSupport.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/fonts/harfbuzz/FontPlatformDataHarfBuzz.h"
#include "public/platform/linux/WebFontInfo.h"
#include "public/platform/linux/WebFontRenderStyle.h"
#include "public/platform/linux/WebSandboxSupport.h"

namespace WebCore {

static SkPaint::Hinting skiaHinting = SkPaint::kNormal_Hinting;
static bool useSkiaAutoHint = true;
static bool useSkiaBitmaps = true;
static bool useSkiaAntiAlias = true;
static bool useSkiaSubpixelRendering = false;

void FontPlatformData::setHinting(SkPaint::Hinting hinting)
{
    skiaHinting = hinting;
}

void FontPlatformData::setAutoHint(bool useAutoHint)
{
    useSkiaAutoHint = useAutoHint;
}

void FontPlatformData::setUseBitmaps(bool useBitmaps)
{
    useSkiaBitmaps = useBitmaps;
}

void FontPlatformData::setAntiAlias(bool useAntiAlias)
{
    useSkiaAntiAlias = useAntiAlias;
}

void FontPlatformData::setSubpixelRendering(bool useSubpixelRendering)
{
    useSkiaSubpixelRendering = useSubpixelRendering;
}

void FontPlatformData::setupPaint(SkPaint* paint, GraphicsContext*) const
{
    paint->setAntiAlias(m_style.useAntiAlias);
    paint->setHinting(static_cast<SkPaint::Hinting>(m_style.hintStyle));
    paint->setEmbeddedBitmapText(m_style.useBitmaps);
    paint->setAutohinted(m_style.useAutoHint);
    if (m_style.useAntiAlias)
        paint->setLCDRenderText(m_style.useSubpixelRendering);

    // TestRunner specifically toggles the subpixel positioning flag.
    if (RuntimeEnabledFeatures::subpixelFontScalingEnabled()
        && paint->getHinting() != SkPaint::kFull_Hinting
        && !isRunningLayoutTest())
        paint->setSubpixelText(true);
    else
        paint->setSubpixelText(m_style.useSubpixelPositioning);

    const float ts = m_textSize >= 0 ? m_textSize : 12;
    paint->setTextSize(SkFloatToScalar(ts));
    paint->setTypeface(m_typeface.get());
    paint->setFakeBoldText(m_syntheticBold);
    paint->setTextSkewX(m_syntheticItalic ? -SK_Scalar1 / 4 : 0);
}

static inline void getRenderStyleForStrike(FontRenderStyle& fontRenderStyle, const char* font, int sizeAndStyle)
{
    blink::WebFontRenderStyle style;

#if OS(ANDROID)
    style.setDefaults();
#else
    if (!font || !*font)
        style.setDefaults(); // It's probably a webfont. Take the system defaults.
    else if (blink::Platform::current()->sandboxSupport())
        blink::Platform::current()->sandboxSupport()->getRenderStyleForStrike(font, sizeAndStyle, &style);
    else
        blink::WebFontInfo::renderStyleForStrike(font, sizeAndStyle, &style);
#endif

    style.toFontRenderStyle(&fontRenderStyle);
}

void FontPlatformData::querySystemForRenderStyle(bool useSkiaSubpixelPositioning)
{
    getRenderStyleForStrike(m_style, m_family.data(), (((int)m_textSize) << 2) | (m_typeface->style() & 3));

    // Fix FontRenderStyle::NoPreference to actual styles.
    if (m_style.useAntiAlias == FontRenderStyle::NoPreference)
        m_style.useAntiAlias = useSkiaAntiAlias;

    if (!m_style.useHinting)
        m_style.hintStyle = SkPaint::kNo_Hinting;
    else if (m_style.useHinting == FontRenderStyle::NoPreference)
        m_style.hintStyle = skiaHinting;

    if (m_style.useBitmaps == FontRenderStyle::NoPreference)
        m_style.useBitmaps = useSkiaBitmaps;
    if (m_style.useAutoHint == FontRenderStyle::NoPreference)
        m_style.useAutoHint = useSkiaAutoHint;
    if (m_style.useAntiAlias == FontRenderStyle::NoPreference)
        m_style.useAntiAlias = useSkiaAntiAlias;
    if (m_style.useSubpixelRendering == FontRenderStyle::NoPreference)
        m_style.useSubpixelRendering = useSkiaSubpixelRendering;

    // TestRunner specifically toggles the subpixel positioning flag.
    if (m_style.useSubpixelPositioning == FontRenderStyle::NoPreference
        || isRunningLayoutTest())
        m_style.useSubpixelPositioning = useSkiaSubpixelPositioning;
}

bool FontPlatformData::defaultUseSubpixelPositioning()
{
    return FontDescription::subpixelPositioning();
}

} // namespace WebCore
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2011 - 2017)
//   Kirsten Weber   (2013)
//   Rene Milk       (2014 - 2018)
//   Tobias Leibner  (2014, 2016 - 2017)

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <dune/xt/common/memory.hh>

#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/la/container/vector-interface.hh>

#include <dune/xt/functions/interfaces/localizable-function.hh>

#include <dune/gdt/local/discretefunction.hh>
#include <dune/gdt/discretefunction/dof-vector.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {

template <class Vector, class GridView, size_t range_dim = 1, size_t range_dim_cols = 1, class RangeField = double>
class ConstDiscreteFunction
    : public XT::Functions::
          LocalizableFunctionInterface<XT::Grid::extract_entity_t<GridView>, range_dim, range_dim_cols, RangeField>
{
  static_assert(XT::LA::is_vector<Vector>::value, "");

  using BaseType = XT::Functions::
      LocalizableFunctionInterface<XT::Grid::extract_entity_t<GridView>, range_dim, range_dim_cols, RangeField>;
  using ThisType = ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

public:
  using ConstDofVectorType = ConstDofVector<Vector, GridView>;
  using SpaceType = SpaceInterface<GridView, range_dim, range_dim_cols, RangeField>;
  using VectorType = Vector;
  using ConstLocalDiscreteFunctionType =
      ConstLocalDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

  using typename BaseType::LocalFunctionType;
  using typename BaseType::EntityType;

  ConstDiscreteFunction(const SpaceType& spc,
                        const VectorType& vector,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(spc)
    , dofs_(space_.mapper(), vector)
    , name_(nm)
  {
  }

  ConstDiscreteFunction(const ThisType&) = default;
  ConstDiscreteFunction(ThisType&&) = default;

  ThisType& operator=(const ThisType&) = delete;
  ThisType& operator=(ThisType&&) = delete;

  const SpaceType& space() const
  {
    return space_;
  }

  const ConstDofVectorType& dofs() const
  {
    return dofs_;
  }

  std::unique_ptr<ConstLocalDiscreteFunctionType> local_discrete_function() const
  {
    return std::make_unique<ConstLocalDiscreteFunctionType>(space_, dofs_);
  }

  std::unique_ptr<ConstLocalDiscreteFunctionType> local_discrete_function(const EntityType& element) const
  {
    return std::make_unique<ConstLocalDiscreteFunctionType>(space_, dofs_, element);
  }

  /**
   * \name ``These methods are required by XT::Functions::LocalizableFunctionInterface.''
   * \{
   */
  std::string type() const override
  {
    return "dune.gdt.constdiscretefunction";
  }

  std::string name() const override final
  {
    return name_;
  }

  virtual std::unique_ptr<LocalFunctionType> local_function() const
  {
    return local_discrete_function();
  }

  virtual std::unique_ptr<LocalFunctionType> local_function(const EntityType& element) const
  {
    return local_discrete_function(element);
  }

  /**
   * \}
   */

  using BaseType::visualize;

  /**
   * \brief Visualizes the function using Dune::XT::Functions::LocalizableFunctionInterface::visualize on the grid view
   *        associated with the space.
   * \sa    Dune::XT::Functions::LocalizableFunctionInterface::visualize
   * \note  Subsampling is enabled by default for functions of order greater than one.
   */
  void visualize(const std::string filename,
                 const VTK::OutputType vtk_output_type = VTK::appendedraw,
                 const XT::Common::Parameter& param = {}) const
  {
    this->visualize(space_.grid_view(), filename, space_.max_polorder() > 1, vtk_output_type, param);
  }

protected:
  const SpaceType& space_;

private:
  const ConstDofVectorType dofs_;
  const std::string name_;
}; // class ConstDiscreteFunction

template <class V, class GV, size_t r, size_t rC, class R>
ConstDiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_const_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                             const XT::LA::VectorInterface<V>& vector,
                             const std::string nm = "dune.gdt.constdiscretefunction")
{
  return ConstDiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(
      space, vector.as_imp(), nm);
}

template <class Vector, class GridView, size_t range_dim = 1, size_t range_dim_cols = 1, class RangeField = double>
class DiscreteFunction : XT::Common::StorageProvider<Vector>,
                         public ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>
{
  using ThisType = DiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;
  using VectorStorage = XT::Common::StorageProvider<Vector>;
  using BaseType = ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

public:
  using typename BaseType::EntityType;
  using typename BaseType::SpaceType;
  using typename BaseType::VectorType;

  using DofVectorType = DofVector<Vector, GridView>;
  using LocalDiscreteFunctionType = LocalDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

  DiscreteFunction(const SpaceType& spc, VectorType& vector, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(vector)
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const SpaceType& spc, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(new VectorType(spc.mapper().size(), 0))
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const ThisType&) = default;
  DiscreteFunction(ThisType&&) = default;

  ThisType& operator=(const ThisType&) = delete;
  ThisType& operator=(ThisType&&) = delete;

  using BaseType::dofs;

  DofVectorType& dofs()
  {
    return dofs_;
  }

  using BaseType::local_discrete_function;

  std::unique_ptr<LocalDiscreteFunctionType> local_discrete_function()
  {
    return std::make_unique<LocalDiscreteFunctionType>(space_, dofs_);
  }

  std::unique_ptr<LocalDiscreteFunctionType> local_discrete_function(const EntityType& element)
  {
    return std::make_unique<LocalDiscreteFunctionType>(space_, dofs_, element);
  }

  /**
   * \name ``These methods are required by XT::Functions::LocalizableFunctionInterface.''
   * \{
   */

  std::string type() const override final
  {
    return "dune.gdt.discretefunction";
  }

  /**
   * \}
   */

private:
  using BaseType::space_;
  DofVectorType dofs_;
}; // class DiscreteFunction

template <class V, class GV, size_t r, size_t rC, class R>
DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                       XT::LA::VectorInterface<V>& vector,
                       const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(space, vector.as_imp(), nm);
}

template <class VectorType, class GV, size_t r, size_t rC, class R>
DiscreteFunction<VectorType, GV, r, rC, R> make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                                                                  const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<VectorType, GV, r, rC, R>(space, nm);
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<commit_msg>[discretefunction.default] add a ctor which moves in a given vector<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2011 - 2017)
//   Kirsten Weber   (2013)
//   Rene Milk       (2014 - 2018)
//   Tobias Leibner  (2014, 2016 - 2017)

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <dune/xt/common/memory.hh>

#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/la/container/vector-interface.hh>

#include <dune/xt/functions/interfaces/localizable-function.hh>

#include <dune/gdt/local/discretefunction.hh>
#include <dune/gdt/discretefunction/dof-vector.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {

template <class Vector, class GridView, size_t range_dim = 1, size_t range_dim_cols = 1, class RangeField = double>
class ConstDiscreteFunction
    : public XT::Functions::
          LocalizableFunctionInterface<XT::Grid::extract_entity_t<GridView>, range_dim, range_dim_cols, RangeField>
{
  static_assert(XT::LA::is_vector<Vector>::value, "");

  using BaseType = XT::Functions::
      LocalizableFunctionInterface<XT::Grid::extract_entity_t<GridView>, range_dim, range_dim_cols, RangeField>;
  using ThisType = ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

public:
  using ConstDofVectorType = ConstDofVector<Vector, GridView>;
  using SpaceType = SpaceInterface<GridView, range_dim, range_dim_cols, RangeField>;
  using VectorType = Vector;
  using ConstLocalDiscreteFunctionType =
      ConstLocalDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

  using typename BaseType::LocalFunctionType;
  using typename BaseType::EntityType;

  ConstDiscreteFunction(const SpaceType& spc,
                        const VectorType& vector,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(spc)
    , dofs_(space_.mapper(), vector)
    , name_(nm)
  {
  }

  ConstDiscreteFunction(const ThisType&) = default;
  ConstDiscreteFunction(ThisType&&) = default;

  ThisType& operator=(const ThisType&) = delete;
  ThisType& operator=(ThisType&&) = delete;

  const SpaceType& space() const
  {
    return space_;
  }

  const ConstDofVectorType& dofs() const
  {
    return dofs_;
  }

  std::unique_ptr<ConstLocalDiscreteFunctionType> local_discrete_function() const
  {
    return std::make_unique<ConstLocalDiscreteFunctionType>(space_, dofs_);
  }

  std::unique_ptr<ConstLocalDiscreteFunctionType> local_discrete_function(const EntityType& element) const
  {
    return std::make_unique<ConstLocalDiscreteFunctionType>(space_, dofs_, element);
  }

  /**
   * \name ``These methods are required by XT::Functions::LocalizableFunctionInterface.''
   * \{
   */
  std::string type() const override
  {
    return "dune.gdt.constdiscretefunction";
  }

  std::string name() const override final
  {
    return name_;
  }

  virtual std::unique_ptr<LocalFunctionType> local_function() const
  {
    return local_discrete_function();
  }

  virtual std::unique_ptr<LocalFunctionType> local_function(const EntityType& element) const
  {
    return local_discrete_function(element);
  }

  /**
   * \}
   */

  using BaseType::visualize;

  /**
   * \brief Visualizes the function using Dune::XT::Functions::LocalizableFunctionInterface::visualize on the grid view
   *        associated with the space.
   * \sa    Dune::XT::Functions::LocalizableFunctionInterface::visualize
   * \note  Subsampling is enabled by default for functions of order greater than one.
   */
  void visualize(const std::string filename,
                 const VTK::OutputType vtk_output_type = VTK::appendedraw,
                 const XT::Common::Parameter& param = {}) const
  {
    this->visualize(space_.grid_view(), filename, space_.max_polorder() > 1, vtk_output_type, param);
  }

protected:
  const SpaceType& space_;

private:
  const ConstDofVectorType dofs_;
  const std::string name_;
}; // class ConstDiscreteFunction

template <class V, class GV, size_t r, size_t rC, class R>
ConstDiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_const_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                             const XT::LA::VectorInterface<V>& vector,
                             const std::string nm = "dune.gdt.constdiscretefunction")
{
  return ConstDiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(
      space, vector.as_imp(), nm);
}

template <class Vector, class GridView, size_t range_dim = 1, size_t range_dim_cols = 1, class RangeField = double>
class DiscreteFunction : XT::Common::StorageProvider<Vector>,
                         public ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>
{
  using ThisType = DiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;
  using VectorStorage = XT::Common::StorageProvider<Vector>;
  using BaseType = ConstDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

public:
  using typename BaseType::EntityType;
  using typename BaseType::SpaceType;
  using typename BaseType::VectorType;

  using DofVectorType = DofVector<Vector, GridView>;
  using LocalDiscreteFunctionType = LocalDiscreteFunction<Vector, GridView, range_dim, range_dim_cols, RangeField>;

  DiscreteFunction(const SpaceType& spc, VectorType& vector, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(vector)
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const SpaceType& spc, VectorType&& vector, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(new VectorType(std::move(vector)))
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const SpaceType& spc, const std::string nm = "dune.gdt.discretefunction")
    : VectorStorage(new VectorType(spc.mapper().size(), 0))
    , BaseType(spc, VectorStorage::access(), nm)
    , dofs_(space_.mapper(), VectorStorage::access())
  {
  }

  DiscreteFunction(const ThisType&) = default;
  DiscreteFunction(ThisType&&) = default;

  ThisType& operator=(const ThisType&) = delete;
  ThisType& operator=(ThisType&&) = delete;

  using BaseType::dofs;

  DofVectorType& dofs()
  {
    return dofs_;
  }

  using BaseType::local_discrete_function;

  std::unique_ptr<LocalDiscreteFunctionType> local_discrete_function()
  {
    return std::make_unique<LocalDiscreteFunctionType>(space_, dofs_);
  }

  std::unique_ptr<LocalDiscreteFunctionType> local_discrete_function(const EntityType& element)
  {
    return std::make_unique<LocalDiscreteFunctionType>(space_, dofs_, element);
  }

  /**
   * \name ``These methods are required by XT::Functions::LocalizableFunctionInterface.''
   * \{
   */

  std::string type() const override final
  {
    return "dune.gdt.discretefunction";
  }

  /**
   * \}
   */

private:
  using BaseType::space_;
  DofVectorType dofs_;
}; // class DiscreteFunction

template <class V, class GV, size_t r, size_t rC, class R>
DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                       XT::LA::VectorInterface<V>& vector,
                       const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(space, vector.as_imp(), nm);
}

template <class V, class GV, size_t r, size_t rC, class R>
DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>
make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                       XT::LA::VectorInterface<V>&& vector,
                       const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<typename XT::LA::VectorInterface<V>::derived_type, GV, r, rC, R>(
      space, std::move(vector.as_imp()), nm);
}

template <class VectorType, class GV, size_t r, size_t rC, class R>
DiscreteFunction<VectorType, GV, r, rC, R> make_discrete_function(const SpaceInterface<GV, r, rC, R>& space,
                                                                  const std::string nm = "dune.gdt.discretefunction")
{
  return DiscreteFunction<VectorType, GV, r, rC, R>(space, nm);
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <memory>
#include <type_traits>

#include <dune/common/exceptions.hh>
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/common/fvector.hh>

#include <dune/grid/io/file/vtk.hh>
#include <dune/stuff/common/reenable_warnings.hh>

#include <dune/stuff/la/container/interfaces.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/common/memory.hh>

#include <dune/gdt/spaces/interface.hh>

#include "local.hh"

namespace Dune {
namespace GDT {

template <class SpaceImp, class VectorImp>
class ConstDiscreteFunction
    : public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                                 SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                                 SpaceImp::dimRange, SpaceImp::dimRangeCols>
{
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits,
                                                                 typename VectorImp::Traits::ScalarType>,
                                VectorImp>::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
                "Types do not match!");
  typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                              SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                              SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType;
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  static const unsigned int dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainFieldType DomainFieldType;
  typedef typename BaseType::DomainType DomainType;

  static const unsigned int dimRange     = BaseType::dimRange;
  static const unsigned int dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeFieldType RangeFieldType;
  typedef typename BaseType::RangeType RangeType;
  typedef typename BaseType::JacobianRangeType JacobianRangeType;

  typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType;

  ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(sp)
    , vector_(vec)
    , name_(nm)
  {
    assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
  }

  ConstDiscreteFunction(const ThisType& other) = default;

  ConstDiscreteFunction(ThisType&& source) = delete;

  virtual ~ConstDiscreteFunction()
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const override
  {
    return new ThisType(*this);
  }

  virtual std::string name() const override
  {
    return name_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const VectorType& vector() const
  {
    return vector_;
  }

  ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const
  {
    assert(space_.grid_view().indexSet().contains(entity));
    return ConstLocalDiscreteFunctionType(space_, vector_, entity);
  }

  virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const override
  {
    return DSC::make_unique<ConstLocalDiscreteFunctionType>(local_discrete_function(entity));
  }

  void visualize(const std::string filename, const bool subsampling = (SpaceType::polOrder > 1),
                 VTK::OutputType vtk_output_type = VTK::appendedraw) const
  {
    BaseType::template visualize<typename SpaceType::GridViewType>(
        space().grid_view(), filename, subsampling, vtk_output_type);
  }

  bool dofs_valid() const
  {
    return vector().valid();
  }

protected:
  const SpaceType& space_;

private:
  const VectorType& vector_;
  const std::string name_;
}; // class ConstDiscreteFunction

template <class SpaceImp, class VectorImp>
class DiscreteFunction : Stuff::Common::StorageProvider<VectorImp>, public ConstDiscreteFunction<SpaceImp, VectorImp>
{
  typedef Stuff::Common::StorageProvider<VectorImp> VectorProviderBaseType;
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef DiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;

  DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction")
    : VectorProviderBaseType(vec)
    , BaseType(sp, VectorProviderBaseType::storage_access(), nm)
  {
  }

  DiscreteFunction(const SpaceType& sp, const std::string nm = "dune.gdt.discretefunction")
    : VectorProviderBaseType(new VectorType(sp.mapper().size()))
    , BaseType(sp, VectorProviderBaseType::storage_access(), nm)
  {
  }

  DiscreteFunction(const ThisType& other)
    : VectorProviderBaseType(new VectorType(other.vector()))
    , BaseType(other.space(), VectorProviderBaseType::storage_access(), other.name())
  {
  }

  //! \todo is this intentionally c&p of the copy ctor?
  DiscreteFunction(ThisType&& source)
    : VectorProviderBaseType(new VectorType(source.vector()))
    , BaseType(source.space(), VectorProviderBaseType::storage_access(), source.name())
  {
  }

  ~DiscreteFunction()
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const override
  {
    return new ThisType(*this);
  }

  using BaseType::vector;

  VectorType& vector()
  {
    return this->storage_access();
  }

  using BaseType::local_discrete_function;

  LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
  {
    assert(space_.grid_view().indexSet().contains(entity));
    return LocalDiscreteFunctionType(space_, this->storage_access(), entity);
  }

private:
  using BaseType::space_;
}; // class DiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<commit_msg>[discretefunction.default] let local_discrete_function return a unique_ptr<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <memory>
#include <type_traits>

#include <dune/common/exceptions.hh>
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/common/fvector.hh>

#include <dune/grid/io/file/vtk.hh>
#include <dune/stuff/common/reenable_warnings.hh>

#include <dune/stuff/la/container/interfaces.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/common/memory.hh>

#include <dune/gdt/spaces/interface.hh>

#include "local.hh"

namespace Dune {
namespace GDT {

template <class SpaceImp, class VectorImp>
class ConstDiscreteFunction
    : public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                                 SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                                 SpaceImp::dimRange, SpaceImp::dimRangeCols>
{
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits,
                                                                 typename VectorImp::Traits::ScalarType>,
                                VectorImp>::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
                "Types do not match!");
  typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                              SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                              SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType;
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  static const unsigned int dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainFieldType DomainFieldType;
  typedef typename BaseType::DomainType DomainType;

  static const unsigned int dimRange     = BaseType::dimRange;
  static const unsigned int dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeFieldType RangeFieldType;
  typedef typename BaseType::RangeType RangeType;
  typedef typename BaseType::JacobianRangeType JacobianRangeType;

  typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType;

  ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(sp)
    , vector_(vec)
    , name_(nm)
  {
    assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
  }

  ConstDiscreteFunction(const ThisType& other) = default;

  ConstDiscreteFunction(ThisType&& source) = delete;

  virtual ~ConstDiscreteFunction()
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const override
  {
    return new ThisType(*this);
  }

  virtual std::string name() const override
  {
    return name_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const VectorType& vector() const
  {
    return vector_;
  }

  std::unique_ptr<ConstLocalDiscreteFunctionType> local_discrete_function(const EntityType& entity) const
  {
    assert(space_.grid_view().indexSet().contains(entity));
    return DSC::make_unique<ConstLocalDiscreteFunctionType>(space_, vector_, entity);
  }

  virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const override
  {
    return local_discrete_function(entity);
  }

  void visualize(const std::string filename, const bool subsampling = (SpaceType::polOrder > 1),
                 VTK::OutputType vtk_output_type = VTK::appendedraw) const
  {
    BaseType::template visualize<typename SpaceType::GridViewType>(
        space().grid_view(), filename, subsampling, vtk_output_type);
  }

  bool dofs_valid() const
  {
    return vector().valid();
  }

protected:
  const SpaceType& space_;

private:
  const VectorType& vector_;
  const std::string name_;
}; // class ConstDiscreteFunction

template <class SpaceImp, class VectorImp>
class DiscreteFunction : Stuff::Common::StorageProvider<VectorImp>, public ConstDiscreteFunction<SpaceImp, VectorImp>
{
  typedef Stuff::Common::StorageProvider<VectorImp> VectorProviderBaseType;
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef DiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;

  DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction")
    : VectorProviderBaseType(vec)
    , BaseType(sp, VectorProviderBaseType::storage_access(), nm)
  {
  }

  DiscreteFunction(const SpaceType& sp, const std::string nm = "dune.gdt.discretefunction")
    : VectorProviderBaseType(new VectorType(sp.mapper().size()))
    , BaseType(sp, VectorProviderBaseType::storage_access(), nm)
  {
  }

  DiscreteFunction(const ThisType& other)
    : VectorProviderBaseType(new VectorType(other.vector()))
    , BaseType(other.space(), VectorProviderBaseType::storage_access(), other.name())
  {
  }

  //! \todo is this intentionally c&p of the copy ctor?
  DiscreteFunction(ThisType&& source)
    : VectorProviderBaseType(new VectorType(source.vector()))
    , BaseType(source.space(), VectorProviderBaseType::storage_access(), source.name())
  {
  }

  ~DiscreteFunction()
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  virtual ThisType* copy() const override
  {
    return new ThisType(*this);
  }

  using BaseType::vector;

  VectorType& vector()
  {
    return this->storage_access();
  }

  using BaseType::local_discrete_function;

  std::unique_ptr<LocalDiscreteFunctionType> local_discrete_function(const EntityType& entity)
  {
    assert(space_.grid_view().indexSet().contains(entity));
    return DSC::make_unique<LocalDiscreteFunctionType>(space_, this->storage_access(), entity);
  }

private:
  using BaseType::space_;
}; // class DiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          process.cpp
* Purpose:       Implementation of class 'wxExProcess'
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/regex.h>
#include <wx/tokenzr.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/extension/configdlg.h>
#include <wx/extension/log.h>
#include <wx/extension/util.h> // for wxExConfigFirstOf
#include <wx/extension/report/process.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/frame.h>
#include <wx/extension/report/listitem.h>
#include <wx/extension/report/listview.h>

BEGIN_EVENT_TABLE(wxExProcess, wxProcess)
  EVT_TIMER(-1, wxExProcess::OnTimer)
END_EVENT_TABLE()

wxString wxExProcess::m_Command;
wxString wxExProcess::m_WorkingDirKey = _("Process folder");

wxExProcess::wxExProcess(
  wxExFrameWithHistory* frame,
  const wxString& command)
  : wxProcess(NULL, -1)
  , m_Frame(frame)
  , m_ListView(NULL)
  , m_Timer(this)
{
  if (!command.empty())
  {
    m_Command = command;
  }

  Redirect();
}

bool wxExProcess::CheckInput()
{
  if (m_ListView == NULL)
  {
    return false;
  }

  bool hasInput = false;

  // This assumes that the output is always line buffered.
  wxString line;

  if (IsInputAvailable())
  {
    wxTextInputStream tis(*GetInputStream());
    line << tis.ReadLine();
    hasInput = true;
  }
  else if (IsErrorAvailable())
  {
    wxTextInputStream tis(*GetErrorStream());
    line << tis.ReadLine();
    hasInput = true;
  }

  if (hasInput && !line.empty())
  {
    wxString lineno;
    wxString path;

    // Check on error in php script output.
    const wxRegEx regex(".*in \\(.*\\) on line \\(.*\\)", wxRE_ADVANCED);

    if (regex.Matches(line))
    {
      size_t start, len;

      if (regex.GetMatch(&start, &len, 1))
      {
        path = line.substr(start, len);
      }

      if (regex.GetMatch(&start, &len, 2))
      {
        lineno = line.substr(start, len);
      }
    }
    else
    {
      // Check on error in gcc output (and some others).
      wxStringTokenizer tkz(line, ':');
      path = tkz.GetNextToken();

      if (tkz.HasMoreTokens())
      {
        const wxString number = tkz.GetNextToken();
        if (atoi(number.c_str()) != 0) lineno = number;
      }
    }

    wxFileName fn(path);

    fn.Normalize();

    if (fn.FileExists())
    {
      wxExListItem item(m_ListView, fn);
      item.Insert();
      item.SetItem(_("Line"), line);
      item.SetItem(_("Line No"), lineno);
    }
    else
    {
      m_ListView->InsertItem(m_ListView->GetItemCount(), line, -1);
    }

    // If nothing selected, then ensure last line is visible.
    // Otherwise you are busy inspecting some line, and
    // it would be irritating to get it out of view.
    if (m_ListView->GetSelectedItemCount() == 0)
    {
      m_ListView->EnsureVisible(m_ListView->GetItemCount() - 1);
    }

#if wxUSE_STATUSBAR
    m_ListView->UpdateStatusBar();
#endif
  }

  return hasInput;
}

int wxExProcess::ConfigDialog(
  wxWindow* parent,
  const wxString& title)
{
  std::vector<wxExConfigItem> v;

  v.push_back(wxExConfigItem(
    _("Process"),
    CONFIG_COMBOBOX,
    wxEmptyString));

  v.push_back(wxExConfigItem(
    m_WorkingDirKey,
    CONFIG_COMBOBOXDIR,
    wxEmptyString,
    true,
    1000));

  const auto result = wxExConfigDialog(parent,
    v,
    title).ShowModal();

  if (result == wxID_OK)
  {
    m_Command = wxExConfigFirstOf(_("Process"));
  }

  return result;
}

long wxExProcess::Execute()
{
  if (m_Command.empty())
  {
    if (ConfigDialog(m_ListView) == wxID_CANCEL)
    {
      return 0;
    }
  }

  wxString cwd;
  const wxString dir = wxExConfigFirstOf(m_WorkingDirKey);

  if (!dir.empty())
  {
    cwd = wxGetCwd();
    if (!wxSetWorkingDirectory(dir))
    {
      wxLogError(_("Cannot set working directory"));
      return 0;
    }
  }

  m_ListView = m_Frame->Activate(wxExListViewStandard::LIST_PROCESS);

  if (m_ListView == NULL)
  {
    // Only show a message, and continue,
    // easier for testing.
    wxLogMessage(_("No listview to collect output"));
  }

  const long pid = wxExecute(m_Command, wxEXEC_ASYNC, this);

  if (pid > 0)
  {
    SetPid(pid);

#if wxUSE_STATUSBAR
    wxExFrame::StatusText(m_Command);
#endif
    wxExLog::Get()->Log(m_Command);

    m_Timer.Start(1000); // each 1000 milliseconds
  }
  else
  {
    wxLogError(_("Cannot execute") + ": " + m_Command);
  }

  if (!cwd.empty())
  {
    wxSetWorkingDirectory(cwd);
  }

  return pid;
}

bool wxExProcess::IsRunning() const
{
  if (GetPid() < 0)
  {
    return false;
  }

  return Exists(GetPid());
}

wxKillError wxExProcess::Kill(wxSignal sig)
{
  if (!IsRunning())
  {
    return wxKILL_NO_PROCESS;
  }

  m_Timer.Stop();

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(_("Stopped"));
#endif

  DeletePendingEvents();

  return wxProcess::Kill(GetPid(), sig);
}

void wxExProcess::OnTerminate(
  int WXUNUSED(pid),
  int WXUNUSED(status))
{
  m_Timer.Stop();

  // Collect remaining input.
  while (CheckInput())
  {
    // Do nothing.
  }

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(_("Ready"));
#endif

  wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);
  wxPostEvent(wxTheApp->GetTopWindow(), event);
}

void wxExProcess::OnTimer(wxTimerEvent& event)
{
  while (CheckInput())
  {
    // Do nothing.
  }
}
<commit_msg>removed SetPid, is already done by wxExecute itself<commit_after>/******************************************************************************\
* File:          process.cpp
* Purpose:       Implementation of class 'wxExProcess'
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/regex.h>
#include <wx/tokenzr.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/extension/configdlg.h>
#include <wx/extension/log.h>
#include <wx/extension/util.h> // for wxExConfigFirstOf
#include <wx/extension/report/process.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/frame.h>
#include <wx/extension/report/listitem.h>
#include <wx/extension/report/listview.h>

BEGIN_EVENT_TABLE(wxExProcess, wxProcess)
  EVT_TIMER(-1, wxExProcess::OnTimer)
END_EVENT_TABLE()

wxString wxExProcess::m_Command;
wxString wxExProcess::m_WorkingDirKey = _("Process folder");

wxExProcess::wxExProcess(
  wxExFrameWithHistory* frame,
  const wxString& command)
  : wxProcess(NULL, -1)
  , m_Frame(frame)
  , m_ListView(NULL)
  , m_Timer(this)
{
  if (!command.empty())
  {
    m_Command = command;
  }

  Redirect();
}

bool wxExProcess::CheckInput()
{
  if (m_ListView == NULL)
  {
    return false;
  }

  bool hasInput = false;

  // This assumes that the output is always line buffered.
  wxString line;

  if (IsInputAvailable())
  {
    wxTextInputStream tis(*GetInputStream());
    line << tis.ReadLine();
    hasInput = true;
  }
  else if (IsErrorAvailable())
  {
    wxTextInputStream tis(*GetErrorStream());
    line << tis.ReadLine();
    hasInput = true;
  }

  if (hasInput && !line.empty())
  {
    wxString lineno;
    wxString path;

    // Check on error in php script output.
    const wxRegEx regex(".*in \\(.*\\) on line \\(.*\\)", wxRE_ADVANCED);

    if (regex.Matches(line))
    {
      size_t start, len;

      if (regex.GetMatch(&start, &len, 1))
      {
        path = line.substr(start, len);
      }

      if (regex.GetMatch(&start, &len, 2))
      {
        lineno = line.substr(start, len);
      }
    }
    else
    {
      // Check on error in gcc output (and some others).
      wxStringTokenizer tkz(line, ':');
      path = tkz.GetNextToken();

      if (tkz.HasMoreTokens())
      {
        const wxString number = tkz.GetNextToken();
        if (atoi(number.c_str()) != 0) lineno = number;
      }
    }

    wxFileName fn(path);

    fn.Normalize();

    if (fn.FileExists())
    {
      wxExListItem item(m_ListView, fn);
      item.Insert();
      item.SetItem(_("Line"), line);
      item.SetItem(_("Line No"), lineno);
    }
    else
    {
      m_ListView->InsertItem(m_ListView->GetItemCount(), line, -1);
    }

    // If nothing selected, then ensure last line is visible.
    // Otherwise you are busy inspecting some line, and
    // it would be irritating to get it out of view.
    if (m_ListView->GetSelectedItemCount() == 0)
    {
      m_ListView->EnsureVisible(m_ListView->GetItemCount() - 1);
    }

#if wxUSE_STATUSBAR
    m_ListView->UpdateStatusBar();
#endif
  }

  return hasInput;
}

int wxExProcess::ConfigDialog(
  wxWindow* parent,
  const wxString& title)
{
  std::vector<wxExConfigItem> v;

  v.push_back(wxExConfigItem(
    _("Process"),
    CONFIG_COMBOBOX,
    wxEmptyString));

  v.push_back(wxExConfigItem(
    m_WorkingDirKey,
    CONFIG_COMBOBOXDIR,
    wxEmptyString,
    true,
    1000));

  const auto result = wxExConfigDialog(parent,
    v,
    title).ShowModal();

  if (result == wxID_OK)
  {
    m_Command = wxExConfigFirstOf(_("Process"));
  }

  return result;
}

long wxExProcess::Execute()
{
  if (m_Command.empty())
  {
    if (ConfigDialog(m_ListView) == wxID_CANCEL)
    {
      return 0;
    }
  }

  wxString cwd;
  const wxString dir = wxExConfigFirstOf(m_WorkingDirKey);

  if (!dir.empty())
  {
    cwd = wxGetCwd();
    if (!wxSetWorkingDirectory(dir))
    {
      wxLogError(_("Cannot set working directory"));
      return 0;
    }
  }

  m_ListView = m_Frame->Activate(wxExListViewStandard::LIST_PROCESS);

  if (m_ListView == NULL)
  {
    // Only show a message, and continue,
    // easier for testing.
    wxLogMessage(_("No listview to collect output"));
  }

  const long pid = wxExecute(m_Command, wxEXEC_ASYNC, this);

  if (pid > 0)
  {
#if wxUSE_STATUSBAR
    wxExFrame::StatusText(m_Command);
#endif
    wxExLog::Get()->Log(m_Command);

    m_Timer.Start(1000); // each 1000 milliseconds
  }
  else
  {
    wxLogError(_("Cannot execute") + ": " + m_Command);
  }

  if (!cwd.empty())
  {
    wxSetWorkingDirectory(cwd);
  }

  return pid;
}

bool wxExProcess::IsRunning() const
{
  if (GetPid() < 0)
  {
    return false;
  }

  return Exists(GetPid());
}

wxKillError wxExProcess::Kill(wxSignal sig)
{
  if (!IsRunning())
  {
    return wxKILL_NO_PROCESS;
  }

  m_Timer.Stop();

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(_("Stopped"));
#endif

  DeletePendingEvents();

  return wxProcess::Kill(GetPid(), sig);
}

void wxExProcess::OnTerminate(
  int WXUNUSED(pid),
  int WXUNUSED(status))
{
  m_Timer.Stop();

  // Collect remaining input.
  while (CheckInput())
  {
    // Do nothing.
  }

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(_("Ready"));
#endif

  wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);
  wxPostEvent(wxTheApp->GetTopWindow(), event);
}

void wxExProcess::OnTimer(wxTimerEvent& event)
{
  while (CheckInput())
  {
    // Do nothing.
  }
}
<|endoftext|>


<commit_before>/*
 * StructureMaintenanceTask.cpp
 *
 *  Created on: Aug 1, 2012
 *      Author: swgemu
 */

#include "StructureMaintenanceTask.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/managers/structure/StructureManager.h"
#include "server/chat/ChatManager.h"
#include "server/zone/objects/building/BuildingObject.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/Zone.h"
#include "server/zone/templates/tangible/SharedStructureObjectTemplate.h"
#include "server/zone/objects/region/CityRegion.h"

void StructureMaintenanceTask::run() {
	ManagedReference<StructureObject*> strongRef = structureObject.get();

	if (strongRef == NULL)
		return;

	ZoneServer* zoneServer = strongRef->getZoneServer();

	if (zoneServer != NULL && zoneServer->isServerLoading()) {
		schedule(1000);

		return;
	}

	ManagedReference<CreatureObject*> owner = strongRef->getOwnerCreatureObject();

	if (owner == NULL || !owner->isPlayerCreature()) {
		info("Player structure has NULL owner, destroying.", true);
		StructureManager::instance()->destroyStructure(strongRef);
		return;
	}

	ManagedReference<PlayerObject*> ghost = owner->getPlayerObject();

	if (!ghost->isOwnedStructure(strongRef)) {
		info("Removing orphaned structure.", true);
		StructureManager::instance()->destroyStructure(strongRef);
		return;
	}

	if (strongRef->getSurplusMaintenance() > 0) {
		//Incorrect scheduling, reschedule.
		Locker locker(strongRef);

		strongRef->scheduleMaintenanceExpirationEvent();
		return;
	}

	//Structure is out of maintenance. Start the decaying process...
	strongRef->updateStructureStatus();

	//Calculate one week of maintenance +- any existing maintenance/decay.
	int oneWeekMaintenance = 7 * 24 * strongRef->getMaintenanceRate() - strongRef->getSurplusMaintenance();

	// add city tax to the week maintenance
	ManagedReference<CityRegion*> city = strongRef->getCityRegion();
	if(strongRef->isBuildingObject() && city != NULL){
		oneWeekMaintenance += city->getPropertyTax() / 100.0f * oneWeekMaintenance;
	}

	Locker _ownerLock(owner);
	Locker _lock(strongRef, owner);

	//Check if owner got money in the bank and structure not decaying.
	if (owner->getBankCredits() >= oneWeekMaintenance && !strongRef->isDecaying()) {
		//Withdraw 1 week maintenance from owner bank account and add to the structure
		//maintenance pool.
		strongRef->payMaintenance(oneWeekMaintenance, owner, false);

		//Send email notification to owner.
		sendMailMaintenanceWithdrawnFromBank(owner, strongRef);

		//Reschedule task in 1 week.
		strongRef->scheduleMaintenanceExpirationEvent();
	} else {
		//Start decay process.

		//Notify owner about decay.
		sendMailDecay(owner, strongRef);

		if (!strongRef->isDecayed()) {
			//Reschedule task in 1 day.
			reschedule(oneDayTime);
		} else {
			if (strongRef->isBuildingObject() && !shouldBuildingBeDestroyed(strongRef)) {
				BuildingObject* building = strongRef.castTo<BuildingObject*>();

				//Building is condemned since it has decayed.
				sendMailCondemned(owner, strongRef);

				strongRef->info("Structure decayed, it is now condemned.");

				building->updateSignName(true);
			} else {
				strongRef->info("Structure decayed, destroying it.");

				StructureManager::instance()->destroyStructure(strongRef);
			}
		}
	}
}

void StructureMaintenanceTask::sendMailMaintenanceWithdrawnFromBank(CreatureObject* owner, StructureObject* structure) {
	ManagedReference<ChatManager*> chatManager = structure->getZoneServer()->getChatManager();

	if (chatManager != NULL) {
		UnicodeString subject = "@player_structure:structure_maintenance_empty_subject";

		String zoneName = "the void";
		if (structure->getZone() != NULL) {
			zoneName = structure->getZone()->getZoneName();
		}

		//Your %TT %TO has an empty maintenance pool. It will start deducting from your bank account automatically.
		StringIdChatParameter emailBody("@player_structure:structure_maintenance_empty_body");
		emailBody.setTT(structure->getObjectName());
		emailBody.setTO("(" + String::valueOf((int)structure->getPositionX()) + ", " + String::valueOf((int)structure->getPositionY()) + " on " + zoneName + ")");

		chatManager->sendMail("@player_structure:your_structure_prefix", subject, emailBody, owner->getFirstName());
	}
}

void StructureMaintenanceTask::sendMailDecay(CreatureObject* owner, StructureObject* structure) {
	ManagedReference<ChatManager*> chatManager = structure->getZoneServer()->getChatManager();

	if (chatManager != NULL) {
		UnicodeString subject = "@player_structure:mail_structure_damage_sub";

		//Your %TT %TO is currently at %DI percent condition. It will be destroyed if it reaches 0. If you wish to keep this structure, you should immediately add maintenance.
		String bodyName = "mail_structure_damage";
		if (structure->isBuildingObject()) {
			//Your %TT %TO is currently at %DI percent condition. It will be condemned if it reaches 0. If you wish to keep this structure, you should immediately add maintenance.
			bodyName = "mail_structure_damage_condemn";
		}

		String zoneName = "the void";
		if (structure->getZone() != NULL) {
			zoneName = structure->getZone()->getZoneName();
		}

		StringIdChatParameter emailBody("@player_structure:" + bodyName);
		emailBody.setTT(structure->getObjectName());
		emailBody.setTO("(" + String::valueOf((int)structure->getPositionX()) + ", " + String::valueOf((int)structure->getPositionY()) + " on " + zoneName + ")");
		emailBody.setDI(structure->getDecayPercentage());

		chatManager->sendMail("@player_structure:your_structure_prefix", subject, emailBody, owner->getFirstName());
	}
}

void StructureMaintenanceTask::sendMailCondemned(CreatureObject* owner, StructureObject* structure) {
	//Create an email.
	ManagedReference<ChatManager*> chatManager = structure->getZoneServer()->getChatManager();

	if (chatManager != NULL) {
		UnicodeString subject = "@player_structure:structure_condemned_subject";

		String zoneName = "the void";
		if (structure->getZone() != NULL) {
			zoneName = structure->getZone()->getZoneName();
		}

		//Your %TT %TO has been condemned by the order of the Empire due to lack of maintenance. You must pay %DI credits to uncondemn this structure.
		StringIdChatParameter emailBody("@player_structure:structure_condemned_body");
		emailBody.setTT(structure->getObjectName());
		emailBody.setTO("(" + String::valueOf((int)structure->getPositionX()) + ", " + String::valueOf((int)structure->getPositionY()) + " on " + zoneName + ")");
		emailBody.setDI(-structure->getSurplusMaintenance());
		chatManager->sendMail("@player_structure:your_structure_prefix", subject, emailBody, owner->getFirstName());
	}
}

bool StructureMaintenanceTask::shouldBuildingBeDestroyed(StructureObject* structure) {
	int threeMonthsOfMaintenance = 30 * 24 * structure->getMaintenanceRate();

	if (threeMonthsOfMaintenance + structure->getSurplusMaintenance() < 0) {
		return true;
	} else {
		return false;
	}
}
<commit_msg>[Fixed] structures to deduct maintenance from their owners bank when they run out - mantis 5352<commit_after>/*
 * StructureMaintenanceTask.cpp
 *
 *  Created on: Aug 1, 2012
 *      Author: swgemu
 */

#include "StructureMaintenanceTask.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/managers/structure/StructureManager.h"
#include "server/chat/ChatManager.h"
#include "server/zone/objects/building/BuildingObject.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/Zone.h"
#include "server/zone/templates/tangible/SharedStructureObjectTemplate.h"
#include "server/zone/objects/region/CityRegion.h"

void StructureMaintenanceTask::run() {
	ManagedReference<StructureObject*> strongRef = structureObject.get();

	if (strongRef == NULL)
		return;

	ZoneServer* zoneServer = strongRef->getZoneServer();

	if (zoneServer != NULL && zoneServer->isServerLoading()) {
		schedule(1000);

		return;
	}

	ManagedReference<CreatureObject*> owner = strongRef->getOwnerCreatureObject();

	if (owner == NULL || !owner->isPlayerCreature()) {
		info("Player structure has NULL owner, destroying.", true);
		StructureManager::instance()->destroyStructure(strongRef);
		return;
	}

	ManagedReference<PlayerObject*> ghost = owner->getPlayerObject();

	if (!ghost->isOwnedStructure(strongRef)) {
		info("Removing orphaned structure.", true);
		StructureManager::instance()->destroyStructure(strongRef);
		return;
	}

	if (strongRef->getSurplusMaintenance() > 0) {
		//Incorrect scheduling, reschedule.
		Locker locker(strongRef);

		strongRef->scheduleMaintenanceExpirationEvent();
		return;
	}

	//Structure is out of maintenance. Start the decaying process...
	strongRef->updateStructureStatus();

	//Calculate one week of maintenance +- any existing maintenance/decay.
	int oneWeekMaintenance = 7 * 24 * strongRef->getMaintenanceRate() - strongRef->getSurplusMaintenance();

	// add city tax to the week maintenance
	ManagedReference<CityRegion*> city = strongRef->getCityRegion();
	if(strongRef->isBuildingObject() && city != NULL){
		oneWeekMaintenance += city->getPropertyTax() / 100.0f * oneWeekMaintenance;
	}

	Locker _ownerLock(owner);
	Locker _lock(strongRef, owner);

	//Check if owner got money in the bank and structure not decaying.
	if (owner->getBankCredits() >= oneWeekMaintenance) {
		//Withdraw 1 week maintenance from owner bank account and add to the structure
		//maintenance pool.
		strongRef->payMaintenance(oneWeekMaintenance, owner, false);

		//Send email notification to owner.
		sendMailMaintenanceWithdrawnFromBank(owner, strongRef);

		//Reschedule task in 1 week.
		strongRef->scheduleMaintenanceExpirationEvent();
	} else {
		//Start decay process.

		//Notify owner about decay.
		sendMailDecay(owner, strongRef);

		if (!strongRef->isDecayed()) {
			//Reschedule task in 1 day.
			reschedule(oneDayTime);
		} else {
			if (strongRef->isBuildingObject() && !shouldBuildingBeDestroyed(strongRef)) {
				BuildingObject* building = strongRef.castTo<BuildingObject*>();

				//Building is condemned since it has decayed.
				sendMailCondemned(owner, strongRef);

				strongRef->info("Structure decayed, it is now condemned.");

				building->updateSignName(true);
			} else {
				strongRef->info("Structure decayed, destroying it.");

				StructureManager::instance()->destroyStructure(strongRef);
			}
		}
	}
}

void StructureMaintenanceTask::sendMailMaintenanceWithdrawnFromBank(CreatureObject* owner, StructureObject* structure) {
	ManagedReference<ChatManager*> chatManager = structure->getZoneServer()->getChatManager();

	if (chatManager != NULL) {
		UnicodeString subject = "@player_structure:structure_maintenance_empty_subject";

		String zoneName = "the void";
		if (structure->getZone() != NULL) {
			zoneName = structure->getZone()->getZoneName();
		}

		//Your %TT %TO has an empty maintenance pool. It will start deducting from your bank account automatically.
		StringIdChatParameter emailBody("@player_structure:structure_maintenance_empty_body");
		emailBody.setTT(structure->getObjectName());
		emailBody.setTO("(" + String::valueOf((int)structure->getPositionX()) + ", " + String::valueOf((int)structure->getPositionY()) + " on " + zoneName + ")");

		chatManager->sendMail("@player_structure:your_structure_prefix", subject, emailBody, owner->getFirstName());
	}
}

void StructureMaintenanceTask::sendMailDecay(CreatureObject* owner, StructureObject* structure) {
	ManagedReference<ChatManager*> chatManager = structure->getZoneServer()->getChatManager();

	if (chatManager != NULL) {
		UnicodeString subject = "@player_structure:mail_structure_damage_sub";

		//Your %TT %TO is currently at %DI percent condition. It will be destroyed if it reaches 0. If you wish to keep this structure, you should immediately add maintenance.
		String bodyName = "mail_structure_damage";
		if (structure->isBuildingObject()) {
			//Your %TT %TO is currently at %DI percent condition. It will be condemned if it reaches 0. If you wish to keep this structure, you should immediately add maintenance.
			bodyName = "mail_structure_damage_condemn";
		}

		String zoneName = "the void";
		if (structure->getZone() != NULL) {
			zoneName = structure->getZone()->getZoneName();
		}

		StringIdChatParameter emailBody("@player_structure:" + bodyName);
		emailBody.setTT(structure->getObjectName());
		emailBody.setTO("(" + String::valueOf((int)structure->getPositionX()) + ", " + String::valueOf((int)structure->getPositionY()) + " on " + zoneName + ")");
		emailBody.setDI(structure->getDecayPercentage());

		chatManager->sendMail("@player_structure:your_structure_prefix", subject, emailBody, owner->getFirstName());
	}
}

void StructureMaintenanceTask::sendMailCondemned(CreatureObject* owner, StructureObject* structure) {
	//Create an email.
	ManagedReference<ChatManager*> chatManager = structure->getZoneServer()->getChatManager();

	if (chatManager != NULL) {
		UnicodeString subject = "@player_structure:structure_condemned_subject";

		String zoneName = "the void";
		if (structure->getZone() != NULL) {
			zoneName = structure->getZone()->getZoneName();
		}

		//Your %TT %TO has been condemned by the order of the Empire due to lack of maintenance. You must pay %DI credits to uncondemn this structure.
		StringIdChatParameter emailBody("@player_structure:structure_condemned_body");
		emailBody.setTT(structure->getObjectName());
		emailBody.setTO("(" + String::valueOf((int)structure->getPositionX()) + ", " + String::valueOf((int)structure->getPositionY()) + " on " + zoneName + ")");
		emailBody.setDI(-structure->getSurplusMaintenance());
		chatManager->sendMail("@player_structure:your_structure_prefix", subject, emailBody, owner->getFirstName());
	}
}

bool StructureMaintenanceTask::shouldBuildingBeDestroyed(StructureObject* structure) {
	int threeMonthsOfMaintenance = 30 * 24 * structure->getMaintenanceRate();

	if (threeMonthsOfMaintenance + structure->getSurplusMaintenance() < 0) {
		return true;
	} else {
		return false;
	}
}
<|endoftext|>


<commit_before>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

#include "outprocessapplication.h"

#include "SRWExclusiveLock.h"
#include "exceptions.h"

OUT_OF_PROCESS_APPLICATION::OUT_OF_PROCESS_APPLICATION(
    IHttpApplication& pApplication,
    std::unique_ptr<REQUESTHANDLER_CONFIG> pConfig) :
    AppOfflineTrackingApplication(pApplication),
    m_fWebSocketSupported(WEBSOCKET_STATUS::WEBSOCKET_UNKNOWN),
    m_pConfig(std::move(pConfig))
{
    m_pProcessManager = NULL;
}

OUT_OF_PROCESS_APPLICATION::~OUT_OF_PROCESS_APPLICATION()
{
    SRWExclusiveLock lock(m_stateLock);
    if (m_pProcessManager != NULL)
    {
        m_pProcessManager->Shutdown();
        m_pProcessManager->DereferenceProcessManager();
        m_pProcessManager = NULL;
    }
}

HRESULT
OUT_OF_PROCESS_APPLICATION::Initialize(
)
{
    if (m_pProcessManager == NULL)
    {
        m_pProcessManager = new PROCESS_MANAGER();
        RETURN_IF_FAILED(m_pProcessManager->Initialize());
    }
    return S_OK;
}

HRESULT
OUT_OF_PROCESS_APPLICATION::GetProcess(
    _Out_   SERVER_PROCESS       **ppServerProcess
)
{
    return m_pProcessManager->GetProcess(m_pConfig.get(), QueryWebsocketStatus(), ppServerProcess);
}

__override
VOID
OUT_OF_PROCESS_APPLICATION::StopInternal(bool fServerInitiated)
{
    AppOfflineTrackingApplication::StopInternal(fServerInitiated);

    if (m_pProcessManager != NULL)
    {
        m_pProcessManager->Shutdown();
    }
}

HRESULT
OUT_OF_PROCESS_APPLICATION::CreateHandler(
    _In_  IHttpContext       *pHttpContext,
    _Out_ IREQUEST_HANDLER  **pRequestHandler)
{
    IREQUEST_HANDLER* pHandler = NULL;

    //add websocket check here
    if (m_fWebSocketSupported == WEBSOCKET_STATUS::WEBSOCKET_UNKNOWN)
    {
        SetWebsocketStatus(pHttpContext);
    }

    pHandler = new FORWARDING_HANDLER(pHttpContext, ::ReferenceApplication(this));
    *pRequestHandler = pHandler;
    return S_OK;
}

VOID
OUT_OF_PROCESS_APPLICATION::SetWebsocketStatus(
    IHttpContext* pHttpContext
)
{
    // Even though the applicationhost.config file contains the websocket element,
    // the websocket module may still not be enabled.
    PCWSTR pszTempWebsocketValue;
    DWORD cbLength;

    if (FAILED_LOG(pHttpContext->GetServerVariable("WEBSOCKET_VERSION", &pszTempWebsocketValue, &cbLength)))
    {
        m_fWebSocketSupported = WEBSOCKET_STATUS::WEBSOCKET_NOT_SUPPORTED;
    }
    else
    {
        m_fWebSocketSupported = WEBSOCKET_STATUS::WEBSOCKET_SUPPORTED;
    }
}

BOOL
OUT_OF_PROCESS_APPLICATION::QueryWebsocketStatus() const
{
    return m_fWebSocketSupported == WEBSOCKET_STATUS::WEBSOCKET_SUPPORTED;
}
<commit_msg>Remove misleading websocket error log (#7249)<commit_after>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

#include "outprocessapplication.h"

#include "SRWExclusiveLock.h"
#include "exceptions.h"

OUT_OF_PROCESS_APPLICATION::OUT_OF_PROCESS_APPLICATION(
    IHttpApplication& pApplication,
    std::unique_ptr<REQUESTHANDLER_CONFIG> pConfig) :
    AppOfflineTrackingApplication(pApplication),
    m_fWebSocketSupported(WEBSOCKET_STATUS::WEBSOCKET_UNKNOWN),
    m_pConfig(std::move(pConfig))
{
    m_pProcessManager = NULL;
}

OUT_OF_PROCESS_APPLICATION::~OUT_OF_PROCESS_APPLICATION()
{
    SRWExclusiveLock lock(m_stateLock);
    if (m_pProcessManager != NULL)
    {
        m_pProcessManager->Shutdown();
        m_pProcessManager->DereferenceProcessManager();
        m_pProcessManager = NULL;
    }
}

HRESULT
OUT_OF_PROCESS_APPLICATION::Initialize(
)
{
    if (m_pProcessManager == NULL)
    {
        m_pProcessManager = new PROCESS_MANAGER();
        RETURN_IF_FAILED(m_pProcessManager->Initialize());
    }
    return S_OK;
}

HRESULT
OUT_OF_PROCESS_APPLICATION::GetProcess(
    _Out_   SERVER_PROCESS       **ppServerProcess
)
{
    return m_pProcessManager->GetProcess(m_pConfig.get(), QueryWebsocketStatus(), ppServerProcess);
}

__override
VOID
OUT_OF_PROCESS_APPLICATION::StopInternal(bool fServerInitiated)
{
    AppOfflineTrackingApplication::StopInternal(fServerInitiated);

    if (m_pProcessManager != NULL)
    {
        m_pProcessManager->Shutdown();
    }
}

HRESULT
OUT_OF_PROCESS_APPLICATION::CreateHandler(
    _In_  IHttpContext       *pHttpContext,
    _Out_ IREQUEST_HANDLER  **pRequestHandler)
{
    IREQUEST_HANDLER* pHandler = NULL;

    //add websocket check here
    if (m_fWebSocketSupported == WEBSOCKET_STATUS::WEBSOCKET_UNKNOWN)
    {
        SetWebsocketStatus(pHttpContext);
    }

    pHandler = new FORWARDING_HANDLER(pHttpContext, ::ReferenceApplication(this));
    *pRequestHandler = pHandler;
    return S_OK;
}

VOID
OUT_OF_PROCESS_APPLICATION::SetWebsocketStatus(
    IHttpContext* pHttpContext
)
{
    // Even though the applicationhost.config file contains the websocket element,
    // the websocket module may still not be enabled.
    PCWSTR pszTempWebsocketValue;
    DWORD cbLength;
    HRESULT hr = pHttpContext->GetServerVariable("WEBSOCKET_VERSION", &pszTempWebsocketValue, &cbLength);
    if (SUCCEEDED(hr))
    {
        m_fWebSocketSupported = WEBSOCKET_STATUS::WEBSOCKET_SUPPORTED;
    }
    else
    {
        m_fWebSocketSupported = WEBSOCKET_STATUS::WEBSOCKET_NOT_SUPPORTED;
        if (hr != HRESULT_FROM_WIN32(ERROR_INVALID_INDEX))
        {
            LOG_IF_FAILED(hr);
        }
    }
}

BOOL
OUT_OF_PROCESS_APPLICATION::QueryWebsocketStatus() const
{
    return m_fWebSocketSupported == WEBSOCKET_STATUS::WEBSOCKET_SUPPORTED;
}
<|endoftext|>


<commit_before>#include "AndroidMessageProcessor.h"
#include "AndroidServiceHandler.h"

#include "log.h"

AndroidMessageProcessor::AndroidMessageProcessor(AndroidServiceHandler *serviceHandler) :
closed(false),
closeMutex(),
newMessageMutex(),
newMessageAvailable(newMessageMutex),
commsHandler(serviceHandler),
gatewayConnector(NULL)
{
  //need to initialize GatewayConnector in the main thread; the constructor always
  //happens in the main thread
  gatewayConnector = new GatewayConnector(this);
}

AndroidMessageProcessor::~AndroidMessageProcessor() {
  LOG_TRACE("In ~AndroidMessageProcessor()");
  if(gatewayConnector) {
    delete gatewayConnector;
  }
}

int AndroidMessageProcessor::open(void *args) {
  closed = false;
  return 0;
}

int AndroidMessageProcessor::close(unsigned long flags) {
  LOG_TRACE("Closing MessageProcessor (in AndroidMessageProcessor.close())");
  closeMutex.acquire();
  closed = true;
  closeMutex.release();

  signalNewMessageAvailable();
  return 0;
}

bool AndroidMessageProcessor::isClosed() {
  volatile bool ret; //does this need to be volatile to keep the compiler from optimizing it out?

  closeMutex.acquire();
  ret = closed;
  closeMutex.release();

  return ret;
}

int AndroidMessageProcessor::svc() {
  while(!isClosed()) {
    newMessageMutex.acquire();
    newMessageAvailable.wait();
    newMessageMutex.release();

    ammo::protocol::MessageWrapper *msg = NULL;

    do {
      msg = commsHandler->getNextReceivedMessage();
      if(msg) {
        processMessage(*msg);
        delete msg;
      }
    } while (msg != NULL);
  }
  return 0;
}

void AndroidMessageProcessor::signalNewMessageAvailable() {
  newMessageMutex.acquire();
  newMessageAvailable.signal();
  newMessageMutex.release();
}

void AndroidMessageProcessor::processMessage(ammo::protocol::MessageWrapper &msg) {
  LOG_TRACE("Message Received: " << msg.DebugString());

  if(msg.type() == ammo::protocol::MessageWrapper_MessageType_AUTHENTICATION_MESSAGE) {
    LOG_DEBUG("Received Authentication Message...");
    if(gatewayConnector != NULL) {
      ammo::protocol::AuthenticationMessage authMessage = msg.authentication_message();
      gatewayConnector->associateDevice(authMessage.device_id(), authMessage.user_id(), authMessage.user_key());
      //deviceId = authMessage.device_id();
    }
  } else if(msg.type() == ammo::protocol::MessageWrapper_MessageType_DATA_MESSAGE) {
    LOG_DEBUG("Received Data Message...");
    if(gatewayConnector != NULL) {
      ammo::protocol::DataMessage dataMessage = msg.data_message();
      gatewayConnector->pushData(dataMessage.uri(), dataMessage.mime_type(), dataMessage.data());
      ammo::protocol::MessageWrapper *ackMsg = new ammo::protocol::MessageWrapper();
      ammo::protocol::PushAcknowledgement *ack = ackMsg->mutable_push_acknowledgement();
      ack->set_uri(dataMessage.uri());
      ackMsg->set_type(ammo::protocol::MessageWrapper_MessageType_PUSH_ACKNOWLEDGEMENT);
      LOG_DEBUG("Sending push acknowledgement to connected device...");
      commsHandler->sendMessage(ackMsg);

    }
  } else if(msg.type() == ammo::protocol::MessageWrapper_MessageType_SUBSCRIBE_MESSAGE) {
    LOG_DEBUG("Received Subscribe Message...");
    if(gatewayConnector != NULL) {
      ammo::protocol::SubscribeMessage subscribeMessage = msg.subscribe_message();
      gatewayConnector->registerDataInterest(subscribeMessage.mime_type(), this);
    }
  } else if(msg.type() == ammo::protocol::MessageWrapper_MessageType_PULL_REQUEST) {
    LOG_DEBUG("Received Pull Request Message...");
    if(gatewayConnector != NULL) {
      ammo::protocol::PullRequest pullRequest = msg.pull_request();
      // register for pull response -
      gatewayConnector->registerPullResponseInterest(pullRequest.mime_type(), this);
      // now send request
      gatewayConnector->pullRequest( pullRequest.request_uid(), pullRequest.plugin_id(), pullRequest.mime_type(), pullRequest.query(),
				     pullRequest.projection(), pullRequest.max_results(), pullRequest.start_from_count(), pullRequest.live_query() );

    }
  }
}

void AndroidMessageProcessor::onConnect(GatewayConnector *sender) {
}

void AndroidMessageProcessor::onDisconnect(GatewayConnector *sender) {

}

void AndroidMessageProcessor::onDataReceived(GatewayConnector *sender, std::string uri, std::string mimeType, std::vector<char> &data, std::string originUser) {
  LOG_DEBUG("Sending subscribed data to device...");
  LOG_DEBUG("   URI: " << uri << ", Type: " << mimeType);

  std::string dataString(data.begin(), data.end());
  ammo::protocol::MessageWrapper *msg = new ammo::protocol::MessageWrapper;
  ammo::protocol::DataMessage *dataMsg = msg->mutable_data_message();
  dataMsg->set_uri(uri);
  dataMsg->set_mime_type(mimeType);
  dataMsg->set_data(dataString);

  msg->set_type(ammo::protocol::MessageWrapper_MessageType_DATA_MESSAGE);

  LOG_DEBUG("Sending Data Push message to connected device");
  commsHandler->sendMessage(msg);
}

void AndroidMessageProcessor::onDataReceived(GatewayConnector *sender, std::string requestUid, std::string pluginId, std::string mimeType, std::string uri, std::vector<char> &data) {
  LOG_DEBUG("Sending pull response to device...");
  LOG_DEBUG("   URI: " << uri << ", Type: " << mimeType);

  std::string dataString(data.begin(), data.end());
  ammo::protocol::MessageWrapper *msg = new ammo::protocol::MessageWrapper();
  ammo::protocol::PullResponse *pullMsg = msg->mutable_pull_response();

  pullMsg->set_request_uid(requestUid);
  pullMsg->set_plugin_id(pluginId);
  pullMsg->set_mime_type(mimeType);
  pullMsg->set_uri(uri);
  pullMsg->set_data(dataString);

  msg->set_type(ammo::protocol::MessageWrapper_MessageType_PULL_RESPONSE);

  LOG_DEBUG("Sending Pull Response message to connected device");
  commsHandler->sendMessage(msg);
}

void AndroidMessageProcessor::onAuthenticationResponse(GatewayConnector *sender, bool result) {
  LOG_DEBUG("Delegate: onAuthenticationResponse");
  ammo::protocol::MessageWrapper *newMsg = new ammo::protocol::MessageWrapper();
  newMsg->set_type(ammo::protocol::MessageWrapper_MessageType_AUTHENTICATION_RESULT);
  newMsg->mutable_authentication_result()->set_result(result ? ammo::protocol::AuthenticationResult_Status_SUCCESS : ammo::protocol::AuthenticationResult_Status_SUCCESS);
  commsHandler->sendMessage(newMsg);
}
<commit_msg>Fixed timing bug<commit_after>#include "AndroidMessageProcessor.h"
#include "AndroidServiceHandler.h"

#include "log.h"

AndroidMessageProcessor::AndroidMessageProcessor(AndroidServiceHandler *serviceHandler) :
closed(false),
closeMutex(),
newMessageMutex(),
newMessageAvailable(newMessageMutex),
commsHandler(serviceHandler),
gatewayConnector(NULL)
{
  //need to initialize GatewayConnector in the main thread; the constructor always
  //happens in the main thread
  gatewayConnector = new GatewayConnector(this);
}

AndroidMessageProcessor::~AndroidMessageProcessor() {
  LOG_TRACE("In ~AndroidMessageProcessor()");
  if(gatewayConnector) {
    delete gatewayConnector;
  }
}

int AndroidMessageProcessor::open(void *args) {
  closed = false;
  return 0;
}

int AndroidMessageProcessor::close(unsigned long flags) {
  LOG_TRACE("Closing MessageProcessor (in AndroidMessageProcessor.close())");
  closeMutex.acquire();
  closed = true;
  closeMutex.release();

  signalNewMessageAvailable();
  return 0;
}

bool AndroidMessageProcessor::isClosed() {
  volatile bool ret; //does this need to be volatile to keep the compiler from optimizing it out?

  closeMutex.acquire();
  ret = closed;
  closeMutex.release();

  return ret;
}

int AndroidMessageProcessor::svc() {
  while(!isClosed()) {
    ammo::protocol::MessageWrapper *msg = NULL;

    do {
      msg = commsHandler->getNextReceivedMessage();
      if(msg) {
        processMessage(*msg);
        delete msg;
      }
    } while (msg != NULL);
    newMessageMutex.acquire();
    newMessageAvailable.wait();
    newMessageMutex.release();
  }
  return 0;
}

void AndroidMessageProcessor::signalNewMessageAvailable() {
  newMessageMutex.acquire();
  newMessageAvailable.signal();
  newMessageMutex.release();
}

void AndroidMessageProcessor::processMessage(ammo::protocol::MessageWrapper &msg) {
  LOG_TRACE("Message Received: " << msg.DebugString());

  if(msg.type() == ammo::protocol::MessageWrapper_MessageType_AUTHENTICATION_MESSAGE) {
    LOG_DEBUG("Received Authentication Message...");
    if(gatewayConnector != NULL) {
      ammo::protocol::AuthenticationMessage authMessage = msg.authentication_message();
      gatewayConnector->associateDevice(authMessage.device_id(), authMessage.user_id(), authMessage.user_key());
      //deviceId = authMessage.device_id();
    }
  } else if(msg.type() == ammo::protocol::MessageWrapper_MessageType_DATA_MESSAGE) {
    LOG_DEBUG("Received Data Message...");
    if(gatewayConnector != NULL) {
      ammo::protocol::DataMessage dataMessage = msg.data_message();
      gatewayConnector->pushData(dataMessage.uri(), dataMessage.mime_type(), dataMessage.data());
      ammo::protocol::MessageWrapper *ackMsg = new ammo::protocol::MessageWrapper();
      ammo::protocol::PushAcknowledgement *ack = ackMsg->mutable_push_acknowledgement();
      ack->set_uri(dataMessage.uri());
      ackMsg->set_type(ammo::protocol::MessageWrapper_MessageType_PUSH_ACKNOWLEDGEMENT);
      LOG_DEBUG("Sending push acknowledgement to connected device...");
      commsHandler->sendMessage(ackMsg);

    }
  } else if(msg.type() == ammo::protocol::MessageWrapper_MessageType_SUBSCRIBE_MESSAGE) {
    LOG_DEBUG("Received Subscribe Message...");
    if(gatewayConnector != NULL) {
      ammo::protocol::SubscribeMessage subscribeMessage = msg.subscribe_message();
      gatewayConnector->registerDataInterest(subscribeMessage.mime_type(), this);
    }
  } else if(msg.type() == ammo::protocol::MessageWrapper_MessageType_PULL_REQUEST) {
    LOG_DEBUG("Received Pull Request Message...");
    if(gatewayConnector != NULL) {
      ammo::protocol::PullRequest pullRequest = msg.pull_request();
      // register for pull response -
      gatewayConnector->registerPullResponseInterest(pullRequest.mime_type(), this);
      // now send request
      gatewayConnector->pullRequest( pullRequest.request_uid(), pullRequest.plugin_id(), pullRequest.mime_type(), pullRequest.query(),
				     pullRequest.projection(), pullRequest.max_results(), pullRequest.start_from_count(), pullRequest.live_query() );

    }
  }
}

void AndroidMessageProcessor::onConnect(GatewayConnector *sender) {
}

void AndroidMessageProcessor::onDisconnect(GatewayConnector *sender) {

}

void AndroidMessageProcessor::onDataReceived(GatewayConnector *sender, std::string uri, std::string mimeType, std::vector<char> &data, std::string originUser) {
  LOG_DEBUG("Sending subscribed data to device...");
  LOG_DEBUG("   URI: " << uri << ", Type: " << mimeType);

  std::string dataString(data.begin(), data.end());
  ammo::protocol::MessageWrapper *msg = new ammo::protocol::MessageWrapper;
  ammo::protocol::DataMessage *dataMsg = msg->mutable_data_message();
  dataMsg->set_uri(uri);
  dataMsg->set_mime_type(mimeType);
  dataMsg->set_data(dataString);

  msg->set_type(ammo::protocol::MessageWrapper_MessageType_DATA_MESSAGE);

  LOG_DEBUG("Sending Data Push message to connected device");
  commsHandler->sendMessage(msg);
}

void AndroidMessageProcessor::onDataReceived(GatewayConnector *sender, std::string requestUid, std::string pluginId, std::string mimeType, std::string uri, std::vector<char> &data) {
  LOG_DEBUG("Sending pull response to device...");
  LOG_DEBUG("   URI: " << uri << ", Type: " << mimeType);

  std::string dataString(data.begin(), data.end());
  ammo::protocol::MessageWrapper *msg = new ammo::protocol::MessageWrapper();
  ammo::protocol::PullResponse *pullMsg = msg->mutable_pull_response();

  pullMsg->set_request_uid(requestUid);
  pullMsg->set_plugin_id(pluginId);
  pullMsg->set_mime_type(mimeType);
  pullMsg->set_uri(uri);
  pullMsg->set_data(dataString);

  msg->set_type(ammo::protocol::MessageWrapper_MessageType_PULL_RESPONSE);

  LOG_DEBUG("Sending Pull Response message to connected device");
  commsHandler->sendMessage(msg);
}

void AndroidMessageProcessor::onAuthenticationResponse(GatewayConnector *sender, bool result) {
  LOG_DEBUG("Delegate: onAuthenticationResponse");
  ammo::protocol::MessageWrapper *newMsg = new ammo::protocol::MessageWrapper();
  newMsg->set_type(ammo::protocol::MessageWrapper_MessageType_AUTHENTICATION_RESULT);
  newMsg->mutable_authentication_result()->set_result(result ? ammo::protocol::AuthenticationResult_Status_SUCCESS : ammo::protocol::AuthenticationResult_Status_SUCCESS);
  commsHandler->sendMessage(newMsg);
}
<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CMassAction.cpp,v $
   $Revision: 1.29 $
   $Name:  $
   $Author: shoops $
   $Date: 2005/07/13 17:24:16 $
   End CVS Header */

/**
 * CMassAction
 *
 * Created for Copasi by Stefan Hoops
 * (C) Stefan Hoops 2001
 */

#include "copasi.h"
#include "CMassAction.h"
#include "utilities/utility.h"

#define COPASI_TRACE_CONSTRUCTION
CMassAction::CMassAction(const std::string & name,
                         const CCopasiContainer * pParent):
    CFunction(name, pParent)
{
  CONSTRUCTOR_TRACE;
  setType(CFunction::MassAction);
}

CMassAction::CMassAction(const CFunction & src,
                         const CCopasiContainer * pParent):
    CFunction(src, pParent)
{CONSTRUCTOR_TRACE;}

CMassAction::CMassAction(const TriLogic & reversible,
                         const CCopasiContainer * pParent):
    CFunction((reversible == TriTrue) ?
              "Mass action (reversible)" :
              "Mass action (irreversible)",
              pParent,
              CFunction::MassAction)
{
  CONSTRUCTOR_TRACE;
  if (reversible != TriFalse && reversible != TriTrue)
    CCopasiMessage(CCopasiMessage::ERROR, MCMassAction + 1);

  setType(CFunction::MassAction);
  setReversible(reversible);

  getVariables().add("k1",
                     CFunctionParameter::FLOAT64,
                     "PARAMETER");
  getVariables().add("substrate",
                     CFunctionParameter::VFLOAT64,
                     "SUBSTRATE");
  addUsage("SUBSTRATE", 1, CRange::Infinity);

  if (isReversible() == TriTrue)
    {
      // setName("Mass action (reversible)");
      setInfix("k1 * PRODUCT <substrate_i> "
               "- k2 * PRODUCT <product_j>");
      getVariables().add("k2",
                         CFunctionParameter::FLOAT64,
                         "PARAMETER");
      getVariables().add("product",
                         CFunctionParameter::VFLOAT64,
                         "PRODUCT");
      addUsage("PRODUCT", 1, CRange::Infinity);
    }
  else
    {
      // setName("Mass action (irreversible)");
      setInfix("k1 * PRODUCT <substrate_i>");
    }
}
CMassAction::~CMassAction(){DESTRUCTOR_TRACE;}

const C_FLOAT64 & CMassAction::calcValue(const CCallParameters<C_FLOAT64> & callParameters)
{
  unsigned C_INT32 i, imax;
  CCallParameters<C_FLOAT64>::const_iterator Factor;
  //  std::vector<const C_FLOAT64 *>::const_iterator Factor;

  mValue = 0.0;
  C_FLOAT64 Products = 0.0;

  imax = callParameters[1].vector->size();   // NoSubstrates
  if (imax)
    {
      mValue = * callParameters[0].value;           // k1
      Factor = callParameters[1].vector->begin();   // first substr.

      for (i = 0; i < imax; i++)
        mValue *= *(Factor++)->value;
    }

  if (isReversible() == TriFalse)
    return mValue;

  imax = callParameters[3].vector->size();   // NoProducts
  if (imax)
    {
      Products = * callParameters[2].value;             // k2
      Factor = callParameters[3].vector->begin();   // first product

      for (i = 0; i < imax; i++)
        Products *= *(Factor++)->value;
    }

  return mValue -= Products;
}

bool CMassAction::dependsOn(const C_FLOAT64 * parameter,
                            const CCallParameters<C_FLOAT64> & callParameters) const
  {
    if (parameter == callParameters[0].value) return true;

    CCallParameters<C_FLOAT64>::const_iterator it;
    CCallParameters<C_FLOAT64>::const_iterator end;

    it = callParameters[1].vector->begin();
    end = callParameters[1].vector->end();

    for (; it != end; it++) if (parameter == it->value) return true;

    if (isReversible() != TriTrue) return false;

    if (parameter == callParameters[2].value) return true;

    it = callParameters[3].vector->begin();
    end = callParameters[3].vector->end();

    for (; it != end; it++) if (parameter == it->value) return true;

    return false;
  }

bool CMassAction::compile() {return true;}
<commit_msg>Enhanced calculate to only use iterators in the loops.<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CMassAction.cpp,v $
   $Revision: 1.30 $
   $Name:  $
   $Author: shoops $
   $Date: 2005/07/21 15:57:35 $
   End CVS Header */

/**
 * CMassAction
 *
 * Created for Copasi by Stefan Hoops
 * (C) Stefan Hoops 2001
 */

#include "copasi.h"
#include "CMassAction.h"
#include "utilities/utility.h"

#define COPASI_TRACE_CONSTRUCTION
CMassAction::CMassAction(const std::string & name,
                         const CCopasiContainer * pParent):
    CFunction(name, pParent)
{
  CONSTRUCTOR_TRACE;
  setType(CFunction::MassAction);
}

CMassAction::CMassAction(const CFunction & src,
                         const CCopasiContainer * pParent):
    CFunction(src, pParent)
{CONSTRUCTOR_TRACE;}

CMassAction::CMassAction(const TriLogic & reversible,
                         const CCopasiContainer * pParent):
    CFunction((reversible == TriTrue) ?
              "Mass action (reversible)" :
              "Mass action (irreversible)",
              pParent,
              CFunction::MassAction)
{
  CONSTRUCTOR_TRACE;
  if (reversible != TriFalse && reversible != TriTrue)
    CCopasiMessage(CCopasiMessage::ERROR, MCMassAction + 1);

  setType(CFunction::MassAction);
  setReversible(reversible);

  getVariables().add("k1",
                     CFunctionParameter::FLOAT64,
                     "PARAMETER");
  getVariables().add("substrate",
                     CFunctionParameter::VFLOAT64,
                     "SUBSTRATE");
  addUsage("SUBSTRATE", 1, CRange::Infinity);

  if (isReversible() == TriTrue)
    {
      // setName("Mass action (reversible)");
      setInfix("k1 * PRODUCT <substrate_i> "
               "- k2 * PRODUCT <product_j>");
      getVariables().add("k2",
                         CFunctionParameter::FLOAT64,
                         "PARAMETER");
      getVariables().add("product",
                         CFunctionParameter::VFLOAT64,
                         "PRODUCT");
      addUsage("PRODUCT", 1, CRange::Infinity);
    }
  else
    {
      // setName("Mass action (irreversible)");
      setInfix("k1 * PRODUCT <substrate_i>");
    }
}
CMassAction::~CMassAction(){DESTRUCTOR_TRACE;}

const C_FLOAT64 & CMassAction::calcValue(const CCallParameters<C_FLOAT64> & callParameters)
{
  CCallParameters<C_FLOAT64>::const_iterator Factor;
  CCallParameters<C_FLOAT64>::const_iterator End;

  mValue = 0.0;

  Factor = callParameters[1].vector->begin();
  End = callParameters[1].vector->end();
  if (Factor != End)
    {
      mValue = *callParameters[0].value   // k1
               * *(Factor++)->value;      // first substrate.

      while (Factor != End)
        mValue *= *(Factor++)->value;
    }

  if (isReversible() == TriFalse)
    return mValue;

  C_FLOAT64 Products = 0.0;

  Factor = callParameters[3].vector->begin();
  End = callParameters[3].vector->end();
  if (Factor != End)
    {
      Products = *callParameters[2].value // k2
                 * *(Factor++)->value;    // first product.

      while (Factor != End)
        Products *= *(Factor++)->value;
    }

  return mValue -= Products;
}

bool CMassAction::dependsOn(const C_FLOAT64 * parameter,
                            const CCallParameters<C_FLOAT64> & callParameters) const
  {
    if (parameter == callParameters[0].value) return true;

    CCallParameters<C_FLOAT64>::const_iterator it;
    CCallParameters<C_FLOAT64>::const_iterator end;

    it = callParameters[1].vector->begin();
    end = callParameters[1].vector->end();

    for (; it != end; it++) if (parameter == it->value) return true;

    if (isReversible() != TriTrue) return false;

    if (parameter == callParameters[2].value) return true;

    it = callParameters[3].vector->begin();
    end = callParameters[3].vector->end();

    for (; it != end; it++) if (parameter == it->value) return true;

    return false;
  }

bool CMassAction::compile() {return true;}
<|endoftext|>