<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/utils/simple_delegate.h"

#include <limits>
#include <memory>
#include <vector>

#include "tensorflow/lite/builtin_ops.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/context_util.h"
#include "tensorflow/lite/delegates/utils.h"
#include "tensorflow/lite/kernels/internal/compatibility.h"
#include "tensorflow/lite/minimal_logging.h"

namespace tflite {
namespace {
TfLiteRegistration GetDelegateKernelRegistration(
    SimpleDelegateInterface* delegate) {
  TfLiteRegistration kernel_registration;
  kernel_registration.profiling_string = nullptr;
  kernel_registration.builtin_code = kTfLiteBuiltinDelegate;
  kernel_registration.custom_name = delegate->Name();
  kernel_registration.version = 1;
  kernel_registration.free = [](TfLiteContext* context, void* buffer) -> void {
    delete reinterpret_cast<SimpleDelegateKernelInterface*>(buffer);
  };
  kernel_registration.init = [](TfLiteContext* context, const char* buffer,
                                size_t length) -> void* {
    const TfLiteDelegateParams* params =
        reinterpret_cast<const TfLiteDelegateParams*>(buffer);
    if (params == nullptr) {
      TF_LITE_KERNEL_LOG(context, "NULL TfLiteDelegateParams passed.");
      return nullptr;
    }
    auto* delegate =
        reinterpret_cast<SimpleDelegateInterface*>(params->delegate->data_);
    std::unique_ptr<SimpleDelegateKernelInterface> delegate_kernel(
        delegate->CreateDelegateKernelInterface());
    if (delegate_kernel->Init(context, params) != kTfLiteOk) {
      return nullptr;
    }
    return delegate_kernel.release();
  };
  kernel_registration.prepare = [](TfLiteContext* context,
                                   TfLiteNode* node) -> TfLiteStatus {
    if (node->user_data == nullptr) {
      TF_LITE_KERNEL_LOG(context, "Delegate kernel was not initialized");
      return kTfLiteError;
    }
    SimpleDelegateKernelInterface* delegate_kernel =
        reinterpret_cast<SimpleDelegateKernelInterface*>(node->user_data);
    return delegate_kernel->Prepare(context, node);
  };
  kernel_registration.invoke = [](TfLiteContext* context,
                                  TfLiteNode* node) -> TfLiteStatus {
    SimpleDelegateKernelInterface* delegate_kernel =
        reinterpret_cast<SimpleDelegateKernelInterface*>(node->user_data);
    TFLITE_DCHECK(delegate_kernel != nullptr);
    return delegate_kernel->Eval(context, node);
  };

  return kernel_registration;
}

TfLiteStatus DelegatePrepare(TfLiteContext* context,
                             TfLiteDelegate* base_delegate) {
  auto* delegate =
      reinterpret_cast<SimpleDelegateInterface*>(base_delegate->data_);
  auto delegate_options = delegate->DelegateOptions();
  if (delegate_options.max_delegated_partitions <= 0)
    delegate_options.max_delegated_partitions = std::numeric_limits<int>::max();

  TF_LITE_ENSURE_STATUS(delegate->Initialize(context));
  delegates::IsNodeSupportedFn node_supported_fn =
      [=](TfLiteContext* context, TfLiteNode* node,
          TfLiteRegistration* registration,
          std::string* unsupported_details) -> bool {
    return delegate->IsNodeSupportedByDelegate(registration, node, context);
  };
  // TODO(b/149484598): Update to have method that gets all supported nodes.
  delegates::GraphPartitionHelper helper(context, node_supported_fn);
  TF_LITE_ENSURE_STATUS(helper.Partition(nullptr));

  std::vector<int> supported_nodes = helper.GetNodesOfFirstNLargestPartitions(
      delegate_options.max_delegated_partitions,
      delegate_options.min_nodes_per_partition);

  TFLITE_LOG_PROD(tflite::TFLITE_LOG_INFO,
                  "%s delegate: %d nodes delegated out of %d nodes with "
                  "%d partitions.\n",
                  delegate->Name(), supported_nodes.size(),
                  helper.num_total_nodes(), helper.num_partitions());
  TfLiteRegistration delegate_kernel_registration =
      GetDelegateKernelRegistration(delegate);

  return context->ReplaceNodeSubsetsWithDelegateKernels(
      context, delegate_kernel_registration,
      BuildTfLiteIntArray(supported_nodes).get(), base_delegate);
}
}  // namespace

TfLiteDelegate* TfLiteDelegateFactory::CreateSimpleDelegate(
    std::unique_ptr<SimpleDelegateInterface> simple_delegate, int64_t flag) {
  if (simple_delegate == nullptr) {
    return nullptr;
  }
  auto delegate = new TfLiteDelegate();
  delegate->Prepare = &DelegatePrepare;
  delegate->flags = flag;
  delegate->CopyFromBufferHandle = nullptr;
  delegate->CopyToBufferHandle = nullptr;
  delegate->FreeBufferHandle = nullptr;
  delegate->data_ = simple_delegate.release();
  return delegate;
}

void TfLiteDelegateFactory::DeleteSimpleDelegate(TfLiteDelegate* delegate) {
  if (!delegate) return;
  SimpleDelegateInterface* simple_delegate =
      reinterpret_cast<SimpleDelegateInterface*>(delegate->data_);
  delete simple_delegate;
  delete delegate;
}
}  // namespace tflite
<commit_msg>Downgrade logging from `TFLITE_LOG_PROD` to `TFLITE_LOG_PROD_ONCE`.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/utils/simple_delegate.h"

#include <limits>
#include <memory>
#include <vector>

#include "tensorflow/lite/builtin_ops.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/context_util.h"
#include "tensorflow/lite/delegates/utils.h"
#include "tensorflow/lite/kernels/internal/compatibility.h"
#include "tensorflow/lite/minimal_logging.h"

namespace tflite {
namespace {
TfLiteRegistration GetDelegateKernelRegistration(
    SimpleDelegateInterface* delegate) {
  TfLiteRegistration kernel_registration;
  kernel_registration.profiling_string = nullptr;
  kernel_registration.builtin_code = kTfLiteBuiltinDelegate;
  kernel_registration.custom_name = delegate->Name();
  kernel_registration.version = 1;
  kernel_registration.free = [](TfLiteContext* context, void* buffer) -> void {
    delete reinterpret_cast<SimpleDelegateKernelInterface*>(buffer);
  };
  kernel_registration.init = [](TfLiteContext* context, const char* buffer,
                                size_t length) -> void* {
    const TfLiteDelegateParams* params =
        reinterpret_cast<const TfLiteDelegateParams*>(buffer);
    if (params == nullptr) {
      TF_LITE_KERNEL_LOG(context, "NULL TfLiteDelegateParams passed.");
      return nullptr;
    }
    auto* delegate =
        reinterpret_cast<SimpleDelegateInterface*>(params->delegate->data_);
    std::unique_ptr<SimpleDelegateKernelInterface> delegate_kernel(
        delegate->CreateDelegateKernelInterface());
    if (delegate_kernel->Init(context, params) != kTfLiteOk) {
      return nullptr;
    }
    return delegate_kernel.release();
  };
  kernel_registration.prepare = [](TfLiteContext* context,
                                   TfLiteNode* node) -> TfLiteStatus {
    if (node->user_data == nullptr) {
      TF_LITE_KERNEL_LOG(context, "Delegate kernel was not initialized");
      return kTfLiteError;
    }
    SimpleDelegateKernelInterface* delegate_kernel =
        reinterpret_cast<SimpleDelegateKernelInterface*>(node->user_data);
    return delegate_kernel->Prepare(context, node);
  };
  kernel_registration.invoke = [](TfLiteContext* context,
                                  TfLiteNode* node) -> TfLiteStatus {
    SimpleDelegateKernelInterface* delegate_kernel =
        reinterpret_cast<SimpleDelegateKernelInterface*>(node->user_data);
    TFLITE_DCHECK(delegate_kernel != nullptr);
    return delegate_kernel->Eval(context, node);
  };

  return kernel_registration;
}

TfLiteStatus DelegatePrepare(TfLiteContext* context,
                             TfLiteDelegate* base_delegate) {
  auto* delegate =
      reinterpret_cast<SimpleDelegateInterface*>(base_delegate->data_);
  auto delegate_options = delegate->DelegateOptions();
  if (delegate_options.max_delegated_partitions <= 0)
    delegate_options.max_delegated_partitions = std::numeric_limits<int>::max();

  TF_LITE_ENSURE_STATUS(delegate->Initialize(context));
  delegates::IsNodeSupportedFn node_supported_fn =
      [=](TfLiteContext* context, TfLiteNode* node,
          TfLiteRegistration* registration,
          std::string* unsupported_details) -> bool {
    return delegate->IsNodeSupportedByDelegate(registration, node, context);
  };
  // TODO(b/149484598): Update to have method that gets all supported nodes.
  delegates::GraphPartitionHelper helper(context, node_supported_fn);
  TF_LITE_ENSURE_STATUS(helper.Partition(nullptr));

  std::vector<int> supported_nodes = helper.GetNodesOfFirstNLargestPartitions(
      delegate_options.max_delegated_partitions,
      delegate_options.min_nodes_per_partition);

  TFLITE_LOG_PROD_ONCE(tflite::TFLITE_LOG_INFO,
                       "%s delegate: %d nodes delegated out of %d nodes with "
                       "%d partitions.\n",
                       delegate->Name(), supported_nodes.size(),
                       helper.num_total_nodes(), helper.num_partitions());
  TfLiteRegistration delegate_kernel_registration =
      GetDelegateKernelRegistration(delegate);

  return context->ReplaceNodeSubsetsWithDelegateKernels(
      context, delegate_kernel_registration,
      BuildTfLiteIntArray(supported_nodes).get(), base_delegate);
}
}  // namespace

TfLiteDelegate* TfLiteDelegateFactory::CreateSimpleDelegate(
    std::unique_ptr<SimpleDelegateInterface> simple_delegate, int64_t flag) {
  if (simple_delegate == nullptr) {
    return nullptr;
  }
  auto delegate = new TfLiteDelegate();
  delegate->Prepare = &DelegatePrepare;
  delegate->flags = flag;
  delegate->CopyFromBufferHandle = nullptr;
  delegate->CopyToBufferHandle = nullptr;
  delegate->FreeBufferHandle = nullptr;
  delegate->data_ = simple_delegate.release();
  return delegate;
}

void TfLiteDelegateFactory::DeleteSimpleDelegate(TfLiteDelegate* delegate) {
  if (!delegate) return;
  SimpleDelegateInterface* simple_delegate =
      reinterpret_cast<SimpleDelegateInterface*>(delegate->data_);
  delete simple_delegate;
  delete delegate;
}
}  // namespace tflite
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgeomapobject.h"
#include "qgeomapobject_p.h"
#include "qgeomapdata.h"
#include "qgeomapdata_p.h"
#include "qgeoboundingbox.h"
#include "qgeocoordinate.h"
#include "projwrapper_p.h"

#include <QtAlgorithms>

QTM_BEGIN_NAMESPACE

/*!
    \class QGeoMapObject
    \brief The QGeoMapObject class is graphical item for display in
    QGraphicsGeoMap instances, that is specified in terms of coordinates and
    distances.

    \inmodule QtLocation

    \ingroup maps-mapping-objects

    QGeoMapObject itself can be used to facilitate the display of any
    arbitrary QGraphicsItem on a map. To this end, it supports different
    coordinate systems and the concept of an "origin point" for translation
    into map coordinates.

    For example, the following code creates a QGraphicsEllipseItem and a
    QGeoMapObject to display it. The EllipseItem extends from the origin point,
    out 20 meters to the east and 30 metres south.

    \code
    QGraphicsEllipseItem *ellipseItem = new QGraphicsEllipseItem;
    ellipseItem->setRect(0, 0, 20, 30);

    QGeoMapObject *mapObject = new QGeoMapObject;
    mapObject->setGraphicsItem(ellipseItem);
    mapObject->setUnits(QGeoMapObject::MeterUnit);
    mapObject->setOrigin(QGeoCoordinate(-27.5796, 153.1));
    \endcode

    By default, the GraphicsItem will be transformed into map coordinates using
    a bilinear interpolation. Another option is the ExactTransform, which
    converts the GraphicsItem exactly into map coordinates, but is only available
    for certain subclasses. Other interpolation methods may be provided in
    future for greater accuracy near poles and in different map projections,
    without the limitations of ExactTransform.

    QGeoMapObject instances can also be grouped into heirarchies in order to
    simplify the process of creating compound objects and managing groups of
    objects.
*/

/*!
    \enum QGeoMapObject::Type

    Describes the type of a map object.

    \value NullType
        An empty QGeoMapObject.
    \value GroupType
        A QGeoMapObject used to organize other map objects into groups.
    \value RectangleType
        A QGeoMapObject used to display a rectangular region.
    \value CircleType
        A QGeoMapObject used to display a circular region.
    \value PolylineType
        A QGeoMapObject used to display a multi-segment line.
    \value PolygonType
        A QGeoMapObject used to display a polygonal region.
    \value PixmapType
        A QGeoMapObject used to display a pixmap on a map.
    \value TextType
        A QGeoMapObject used to display text on a map
    \value RouteType
        A QGeoMapObject used to display a route.
*/

/*!
    \enum QGeoMapObject::CoordinateUnit

    Describes the units of measurement used for a map object's
    graphics item.

    \value PixelUnit
        Units are in pixels on the screen. Pixel coordinate (0,0) is
        translated to the origin coordinate.
    \value MeterUnit
        Units are in meters on the ground -- a local Transverse Mercator
        coordinate system (on the WGS84 ellipsoid) is used for translation,
        centered on the origin coordinate.
    \value RelativeArcSecondUnit
        Units are in arc seconds relative to the origin coordinate (along the
        WGS84 ellipsoid).
    \value AbsoluteArcSecondUnit
        Units are in arc seconds on WGS84, origin ignored.
*/

/*!
    \enum QGeoMapObject::TransformType

    Describes the type of transformation applied to change this object's
    coordinate system into screen coordinates.

    \value BilinearTransform
        This object's bounding box is taken, and transformed at each of its
        corners into screen coordinates. A bilinear interpolation is then used
        to draw the rest of the object's GraphicsItem.
    \value ExactTransform
        Individual key points on the object are transformed and the GraphicsItem
        is constructed in direct pixel coordinates. This is only available for
        certain subclasses, depending on the implementation of QGeoMapData used.
*/

/*!
    Constructs a new map object associated with \a mapData.
*/
QGeoMapObject::QGeoMapObject(QGeoMapData *mapData)
    : d_ptr(new QGeoMapObjectPrivate())
{
    setMapData(mapData);

    connect(this, SIGNAL(originChanged(QGeoCoordinate)),
            this, SIGNAL(mapNeedsUpdate()));
    connect(this, SIGNAL(selectedChanged(bool)),
            this, SIGNAL(mapNeedsUpdate()));
    connect(this, SIGNAL(visibleChanged(bool)),
            this, SIGNAL(mapNeedsUpdate()));
    connect(this, SIGNAL(zValueChanged(int)),
            this, SIGNAL(mapNeedsUpdate()));
    connect(this, SIGNAL(graphicsItemChanged(QGraphicsItem*)),
            this, SIGNAL(mapNeedsUpdate()));
}

/*!
    Destroys this map object.
*/
QGeoMapObject::~QGeoMapObject()
{
    setMapData(0);
    delete d_ptr;
}

/*!
    Causes the QGeoMapData containing this object to be updated.
*/
void QGeoMapObject::update()
{
    emit mapNeedsUpdate();
}

/*!
    Returns the type of this map object.
*/
QGeoMapObject::Type QGeoMapObject::type() const
{
    if (d_ptr->graphicsItem)
        return QGeoMapObject::CustomType;
    else
        return QGeoMapObject::NullType;
}

/*!
    \property QGeoMapObject::zValue
    \brief This property holds the z-value of the map object.

    The z-value determines the order in which the objects are drawn on the
    screen.  Objects with the same value will be drawn in the order that
    they were added to the map or map object.

    This is the same behaviour as QGraphicsItem.
*/
void QGeoMapObject::setZValue(int zValue)
{
    if (d_ptr->zValue != zValue) {
        d_ptr->zValue = zValue;
        if (d_ptr->graphicsItem)
            d_ptr->graphicsItem->setZValue(zValue);
        emit zValueChanged(d_ptr->zValue);
    }
}

int QGeoMapObject::zValue() const
{
    return d_ptr->zValue;
}

/*!
    \property QGeoMapObject::visible
    \brief This property holds whether the map object is visible.

    If this map object is not visible then none of the childObjects() will
    be displayed either.
*/
void QGeoMapObject::setVisible(bool visible)
{
    if (d_ptr->isVisible != visible) {
        d_ptr->isVisible = visible;
        if (d_ptr->graphicsItem)
            d_ptr->graphicsItem->setVisible(visible);
        emit visibleChanged(d_ptr->isVisible);
    }
}

bool QGeoMapObject::isVisible() const
{
    return d_ptr->isVisible;
}

/*!
    \property QGeoMapObject::selected
    \brief This property holds whether the map object is selected.
*/
void QGeoMapObject::setSelected(bool selected)
{
    if (d_ptr->isSelected != selected) {
        d_ptr->isSelected = selected;
        emit selectedChanged(d_ptr->isSelected);
    }
}

bool QGeoMapObject::isSelected() const
{
    return d_ptr->isSelected;
}

/*!
    Returns a bounding box which contains this map object.
*/
QGeoBoundingBox QGeoMapObject::boundingBox() const
{
    if (!d_ptr->graphicsItem || !d_ptr->mapData)
        return QGeoBoundingBox();

    d_ptr->mapData->d_ptr->updateTransforms();
    QTransform trans = d_ptr->mapData->d_ptr->latLonTrans.value(this);

    QRectF bounds = d_ptr->graphicsItem->boundingRect();
    QPolygonF poly = bounds * trans;

    QRectF latLonBounds = poly.boundingRect();
    QPointF topLeft = latLonBounds.bottomLeft();
    if (topLeft.x() > 180.0 * 3600.0)
        topLeft.setX(topLeft.x() - 360.0 * 3600.0);
    if (topLeft.x() < -180.0 * 3600.0)
        topLeft.setX(topLeft.x() + 360.0 * 3600.0);

    QPointF bottomRight = latLonBounds.topRight();
    if (bottomRight.x() > 180.0 * 3600.0)
        bottomRight.setX(bottomRight.x() - 360.0 * 3600.0);
    if (bottomRight.x() < -180.0 * 3600.0)
        bottomRight.setX(bottomRight.x() + 360.0 * 3600.0);

    QGeoCoordinate tlc(topLeft.y() / 3600.0, topLeft.x() / 3600.0);
    QGeoCoordinate brc(bottomRight.y() / 3600.0, bottomRight.x() / 3600.0);

    return QGeoBoundingBox(tlc, brc);
}

/*!
    Returns whether \a coordinate is contained with the boundary of this
    map object.
*/
bool QGeoMapObject::contains(const QGeoCoordinate &coordinate) const
{
    if (!d_ptr->graphicsItem || !d_ptr->mapData)
        return false;

    d_ptr->mapData->d_ptr->updateTransforms();
    QPointF latLonPoint(coordinate.longitude(), coordinate.latitude());

    QList<QTransform> transList = d_ptr->mapData->d_ptr->latLonTrans.values(this);
    foreach (QTransform trans, transList) {
        bool ok;
        QTransform inv = trans.inverted(&ok);
        if (!ok)
            continue;

        QPointF localPoint = latLonPoint * inv;

        if (d_ptr->graphicsItem->contains(localPoint))
            return true;
    }
    return false;
}

/*!
    \internal
*/
bool QGeoMapObject::operator<(const QGeoMapObject &other) const
{
    return d_ptr->zValue < other.d_ptr->zValue;
}

/*!
    \internal
*/
bool QGeoMapObject::operator>(const QGeoMapObject &other) const
{
    return d_ptr->zValue > other.d_ptr->zValue;
}

/*!
    Associates the QGeoMapData instance \a mapData with this map object.

    This will create an appropriate QGeoMapObjectInfo instance for
    this QGeoMapObject and will connect the appropriate signals to it
    so that it can be kept up to date.
*/
void QGeoMapObject::setMapData(QGeoMapData *mapData)
{
    if (d_ptr->mapData == mapData)
        return;

    if (d_ptr->mapData) {
        disconnect(this, SIGNAL(mapNeedsUpdate()),
                   d_ptr->mapData->d_ptr, SLOT(updateSender()));
    }

    d_ptr->mapData = mapData;
    if (!d_ptr->mapData)
        return;

    connect(this, SIGNAL(mapNeedsUpdate()),
            d_ptr->mapData->d_ptr, SLOT(updateSender()));
}

/*!
    Returns the QGeoMapData instance associated with this object.

    Will return 0 if not QGeoMapData instance has been set.
*/
QGeoMapData* QGeoMapObject::mapData() const
{
    return d_ptr->mapData;
}

/*!
    \property QGeoMapObject::graphicsItem
    \brief This property holds the GraphicsItem that will be drawn on the map.

    The GraphicsItem's coordinates are in the units specified by the
    QGeoMapObject::units property.

    To offset the coordinates of the GraphicsItem (for items that can only
    be constructed about their parent position), use the QGraphicsItem::setTransform
    method with a QTransform containing the desired translation.
*/
QGraphicsItem * const QGeoMapObject::graphicsItem() const
{
    return d_ptr->graphicsItem;
}

void QGeoMapObject::setGraphicsItem(QGraphicsItem *item)
{
    if (item == d_ptr->graphicsItem)
        return;

    d_ptr->graphicsItem = item;
    item->setZValue(this->zValue());
    emit graphicsItemChanged(item);
}

/*!
    \property QGeoMapObject::transformType
    \brief This property holds the transformation type used to draw the object.

    \sa QGeoMapObject::TransformType
*/
QGeoMapObject::TransformType QGeoMapObject::transformType() const
{
    return d_ptr->transType;
}

void QGeoMapObject::setTransformType(const TransformType &type)
{
    d_ptr->transType = type;
    emit mapNeedsUpdate();
}

/*!
    \property QGeoMapObject::origin
    \brief This property holds the origin of the object's coordinate system.

    How the origin coordinate is used depends on the selected coordinate
    system, see QGeoMapObject::TransformType for more details.
*/
QGeoCoordinate QGeoMapObject::origin() const
{
    return d_ptr->origin;
}

void QGeoMapObject::setOrigin(const QGeoCoordinate &origin)
{
    if (origin == d_ptr->origin)
        return;

    d_ptr->origin = origin;
    emit originChanged(origin);
}

/*!
    \property QGeoMapObject::units
    \brief This property holds the units of measurement for the object.

    Note that setting the units to PixelUnit will result in the transformType
    property being set to ExactTransform automatically.
*/
QGeoMapObject::CoordinateUnit QGeoMapObject::units() const
{
    return d_ptr->units;
}

void QGeoMapObject::setUnits(const CoordinateUnit &unit)
{
    d_ptr->units = unit;

    if (unit == QGeoMapObject::PixelUnit)
        setTransformType(QGeoMapObject::ExactTransform);
    else
        setTransformType(QGeoMapObject::BilinearTransform);

    emit mapNeedsUpdate();
}

/*!
\fn void QGeoMapObject::zValueChanged(int zValue)

    This signal is emitted when the z value of the map object
    has changed.

    The new value is \a zValue.
*/

/*!
\fn void QGeoMapObject::visibleChanged(bool visible)

    This signal is emitted when the visible state of the map object
    has changed.

    The new value is \a visible.
*/

/*!
\fn void QGeoMapObject::selectedChanged(bool selected)

    This signal is emitted when the selected state of the map object
    has changed.

    The new vlaue is \a selected.
*/

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

QGeoMapObjectPrivate::QGeoMapObjectPrivate()
    : zValue(0),
      isVisible(true),
      isSelected(false),
      mapData(0),
      units(QGeoMapObject::PixelUnit),
      transType(QGeoMapObject::ExactTransform),
      graphicsItem(0) {}

QGeoMapObjectPrivate::~QGeoMapObjectPrivate()
{
}

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

#include "moc_qgeomapobject.cpp"

QTM_END_NAMESPACE
<commit_msg>Updating documentation to reflect new default behaviour<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgeomapobject.h"
#include "qgeomapobject_p.h"
#include "qgeomapdata.h"
#include "qgeomapdata_p.h"
#include "qgeoboundingbox.h"
#include "qgeocoordinate.h"
#include "projwrapper_p.h"

#include <QtAlgorithms>

QTM_BEGIN_NAMESPACE

/*!
    \class QGeoMapObject
    \brief The QGeoMapObject class is graphical item for display in
    QGraphicsGeoMap instances, that is specified in terms of coordinates and
    distances.

    \inmodule QtLocation

    \ingroup maps-mapping-objects

    QGeoMapObject itself can be used to facilitate the display of any
    arbitrary QGraphicsItem on a map. To this end, it supports different
    coordinate systems and the concept of an "origin point" for translation
    into map coordinates.

    For example, the following code creates a QGraphicsEllipseItem and a
    QGeoMapObject to display it. The EllipseItem extends from the origin point,
    out 20 meters to the east and 30 metres south.

    \code
    QGraphicsEllipseItem *ellipseItem = new QGraphicsEllipseItem;
    ellipseItem->setRect(0, 0, 20, 30);

    QGeoMapObject *mapObject = new QGeoMapObject;
    mapObject->setGraphicsItem(ellipseItem);
    mapObject->setUnits(QGeoMapObject::MeterUnit);
    mapObject->setOrigin(QGeoCoordinate(-27.5796, 153.1));
    \endcode

    Normally, the GraphicsItem will be transformed into map coordinates using
    a bilinear interpolation. Another option is the ExactTransform, which
    converts the GraphicsItem exactly into map coordinates, but is only available
    for certain subclasses. Other interpolation methods may be provided in
    future for greater accuracy near poles and in different map projections,
    without the limitations of ExactTransform.

    Calling setUnits() or setting the units property will result in the
    default value of transformType being restored. See QGeoMapObject::transformType
    for more details.

    QGeoMapObject instances can also be grouped into heirarchies in order to
    simplify the process of creating compound objects and managing groups of
    objects.
*/

/*!
    \enum QGeoMapObject::Type

    Describes the type of a map object.

    \value NullType
        An empty QGeoMapObject.
    \value GroupType
        A QGeoMapObject used to organize other map objects into groups.
    \value RectangleType
        A QGeoMapObject used to display a rectangular region.
    \value CircleType
        A QGeoMapObject used to display a circular region.
    \value PolylineType
        A QGeoMapObject used to display a multi-segment line.
    \value PolygonType
        A QGeoMapObject used to display a polygonal region.
    \value PixmapType
        A QGeoMapObject used to display a pixmap on a map.
    \value TextType
        A QGeoMapObject used to display text on a map
    \value RouteType
        A QGeoMapObject used to display a route.
*/

/*!
    \enum QGeoMapObject::CoordinateUnit

    Describes the units of measurement used for a map object's
    graphics item.

    \value PixelUnit
        Units are in pixels on the screen. Pixel coordinate (0,0) is
        translated to the origin coordinate.
    \value MeterUnit
        Units are in meters on the ground -- a local Transverse Mercator
        coordinate system (on the WGS84 ellipsoid) is used for translation,
        centered on the origin coordinate.
    \value RelativeArcSecondUnit
        Units are in arc seconds relative to the origin coordinate (along the
        WGS84 ellipsoid).
    \value AbsoluteArcSecondUnit
        Units are in arc seconds on WGS84, origin ignored.
*/

/*!
    \enum QGeoMapObject::TransformType

    Describes the type of transformation applied to change this object's
    coordinate system into screen coordinates.

    \value BilinearTransform
        This object's bounding box is taken, and transformed at each of its
        corners into screen coordinates. A bilinear interpolation is then used
        to draw the rest of the object's GraphicsItem.
    \value ExactTransform
        Individual key points on the object are transformed and the GraphicsItem
        is constructed in direct pixel coordinates. This is only available for
        certain subclasses, depending on the implementation of QGeoMapData used.
*/

/*!
    Constructs a new map object associated with \a mapData.

    The object will be in pixel coordinates, with exact transform.
*/
QGeoMapObject::QGeoMapObject(QGeoMapData *mapData)
    : d_ptr(new QGeoMapObjectPrivate())
{
    setMapData(mapData);

    connect(this, SIGNAL(originChanged(QGeoCoordinate)),
            this, SIGNAL(mapNeedsUpdate()));
    connect(this, SIGNAL(selectedChanged(bool)),
            this, SIGNAL(mapNeedsUpdate()));
    connect(this, SIGNAL(visibleChanged(bool)),
            this, SIGNAL(mapNeedsUpdate()));
    connect(this, SIGNAL(zValueChanged(int)),
            this, SIGNAL(mapNeedsUpdate()));
    connect(this, SIGNAL(graphicsItemChanged(QGraphicsItem*)),
            this, SIGNAL(mapNeedsUpdate()));
}

/*!
    Destroys this map object.
*/
QGeoMapObject::~QGeoMapObject()
{
    setMapData(0);
    delete d_ptr;
}

/*!
    Causes the QGeoMapData containing this object to be updated.
*/
void QGeoMapObject::update()
{
    emit mapNeedsUpdate();
}

/*!
    Returns the type of this map object.
*/
QGeoMapObject::Type QGeoMapObject::type() const
{
    if (d_ptr->graphicsItem)
        return QGeoMapObject::CustomType;
    else
        return QGeoMapObject::NullType;
}

/*!
    \property QGeoMapObject::zValue
    \brief This property holds the z-value of the map object.

    The z-value determines the order in which the objects are drawn on the
    screen.  Objects with the same value will be drawn in the order that
    they were added to the map or map object.

    This is the same behaviour as QGraphicsItem.
*/
void QGeoMapObject::setZValue(int zValue)
{
    if (d_ptr->zValue != zValue) {
        d_ptr->zValue = zValue;
        if (d_ptr->graphicsItem)
            d_ptr->graphicsItem->setZValue(zValue);
        emit zValueChanged(d_ptr->zValue);
    }
}

int QGeoMapObject::zValue() const
{
    return d_ptr->zValue;
}

/*!
    \property QGeoMapObject::visible
    \brief This property holds whether the map object is visible.

    If this map object is not visible then none of the childObjects() will
    be displayed either.
*/
void QGeoMapObject::setVisible(bool visible)
{
    if (d_ptr->isVisible != visible) {
        d_ptr->isVisible = visible;
        if (d_ptr->graphicsItem)
            d_ptr->graphicsItem->setVisible(visible);
        emit visibleChanged(d_ptr->isVisible);
    }
}

bool QGeoMapObject::isVisible() const
{
    return d_ptr->isVisible;
}

/*!
    \property QGeoMapObject::selected
    \brief This property holds whether the map object is selected.
*/
void QGeoMapObject::setSelected(bool selected)
{
    if (d_ptr->isSelected != selected) {
        d_ptr->isSelected = selected;
        emit selectedChanged(d_ptr->isSelected);
    }
}

bool QGeoMapObject::isSelected() const
{
    return d_ptr->isSelected;
}

/*!
    Returns a bounding box which contains this map object.
*/
QGeoBoundingBox QGeoMapObject::boundingBox() const
{
    if (!d_ptr->graphicsItem || !d_ptr->mapData)
        return QGeoBoundingBox();

    d_ptr->mapData->d_ptr->updateTransforms();
    QTransform trans = d_ptr->mapData->d_ptr->latLonTrans.value(this);

    QRectF bounds = d_ptr->graphicsItem->boundingRect();
    QPolygonF poly = bounds * trans;

    QRectF latLonBounds = poly.boundingRect();
    QPointF topLeft = latLonBounds.bottomLeft();
    if (topLeft.x() > 180.0 * 3600.0)
        topLeft.setX(topLeft.x() - 360.0 * 3600.0);
    if (topLeft.x() < -180.0 * 3600.0)
        topLeft.setX(topLeft.x() + 360.0 * 3600.0);

    QPointF bottomRight = latLonBounds.topRight();
    if (bottomRight.x() > 180.0 * 3600.0)
        bottomRight.setX(bottomRight.x() - 360.0 * 3600.0);
    if (bottomRight.x() < -180.0 * 3600.0)
        bottomRight.setX(bottomRight.x() + 360.0 * 3600.0);

    QGeoCoordinate tlc(topLeft.y() / 3600.0, topLeft.x() / 3600.0);
    QGeoCoordinate brc(bottomRight.y() / 3600.0, bottomRight.x() / 3600.0);

    return QGeoBoundingBox(tlc, brc);
}

/*!
    Returns whether \a coordinate is contained with the boundary of this
    map object.
*/
bool QGeoMapObject::contains(const QGeoCoordinate &coordinate) const
{
    if (!d_ptr->graphicsItem || !d_ptr->mapData)
        return false;

    d_ptr->mapData->d_ptr->updateTransforms();
    QPointF latLonPoint(coordinate.longitude(), coordinate.latitude());

    QList<QTransform> transList = d_ptr->mapData->d_ptr->latLonTrans.values(this);
    foreach (QTransform trans, transList) {
        bool ok;
        QTransform inv = trans.inverted(&ok);
        if (!ok)
            continue;

        QPointF localPoint = latLonPoint * inv;

        if (d_ptr->graphicsItem->contains(localPoint))
            return true;
    }
    return false;
}

/*!
    \internal
*/
bool QGeoMapObject::operator<(const QGeoMapObject &other) const
{
    return d_ptr->zValue < other.d_ptr->zValue;
}

/*!
    \internal
*/
bool QGeoMapObject::operator>(const QGeoMapObject &other) const
{
    return d_ptr->zValue > other.d_ptr->zValue;
}

/*!
    Associates the QGeoMapData instance \a mapData with this map object.

    This will create an appropriate QGeoMapObjectInfo instance for
    this QGeoMapObject and will connect the appropriate signals to it
    so that it can be kept up to date.
*/
void QGeoMapObject::setMapData(QGeoMapData *mapData)
{
    if (d_ptr->mapData == mapData)
        return;

    if (d_ptr->mapData) {
        disconnect(this, SIGNAL(mapNeedsUpdate()),
                   d_ptr->mapData->d_ptr, SLOT(updateSender()));
    }

    d_ptr->mapData = mapData;
    if (!d_ptr->mapData)
        return;

    connect(this, SIGNAL(mapNeedsUpdate()),
            d_ptr->mapData->d_ptr, SLOT(updateSender()));
}

/*!
    Returns the QGeoMapData instance associated with this object.

    Will return 0 if not QGeoMapData instance has been set.
*/
QGeoMapData* QGeoMapObject::mapData() const
{
    return d_ptr->mapData;
}

/*!
    \property QGeoMapObject::graphicsItem
    \brief This property holds the GraphicsItem that will be drawn on the map.

    The GraphicsItem's coordinates are in the units specified by the
    QGeoMapObject::units property.

    To offset the coordinates of the GraphicsItem (for items that can only
    be constructed about their parent position), use the QGraphicsItem::setTransform
    method with a QTransform containing the desired translation.
*/
QGraphicsItem * const QGeoMapObject::graphicsItem() const
{
    return d_ptr->graphicsItem;
}

void QGeoMapObject::setGraphicsItem(QGraphicsItem *item)
{
    if (item == d_ptr->graphicsItem)
        return;

    d_ptr->graphicsItem = item;
    item->setZValue(this->zValue());
    emit graphicsItemChanged(item);
}

/*!
    \property QGeoMapObject::transformType
    \brief This property holds the transformation type used to draw the object.

    \sa QGeoMapObject::TransformType
*/
QGeoMapObject::TransformType QGeoMapObject::transformType() const
{
    return d_ptr->transType;
}

void QGeoMapObject::setTransformType(const TransformType &type)
{
    d_ptr->transType = type;
    emit mapNeedsUpdate();
}

/*!
    \property QGeoMapObject::origin
    \brief This property holds the origin of the object's coordinate system.

    How the origin coordinate is used depends on the selected coordinate
    system, see QGeoMapObject::TransformType for more details.
*/
QGeoCoordinate QGeoMapObject::origin() const
{
    return d_ptr->origin;
}

void QGeoMapObject::setOrigin(const QGeoCoordinate &origin)
{
    if (origin == d_ptr->origin)
        return;

    d_ptr->origin = origin;
    emit originChanged(origin);
}

/*!
    \property QGeoMapObject::units
    \brief This property holds the units of measurement for the object.

    Note that setting this property will reset the transformType property to
    the default for the units given. For PixelUnit, this is ExactTransform,
    and for all others, BilinearTransform.

    \sa QGeoMapObject::CoordinateUnit
*/
QGeoMapObject::CoordinateUnit QGeoMapObject::units() const
{
    return d_ptr->units;
}

void QGeoMapObject::setUnits(const CoordinateUnit &unit)
{
    d_ptr->units = unit;

    if (unit == QGeoMapObject::PixelUnit)
        setTransformType(QGeoMapObject::ExactTransform);
    else
        setTransformType(QGeoMapObject::BilinearTransform);

    emit mapNeedsUpdate();
}

/*!
\fn void QGeoMapObject::zValueChanged(int zValue)

    This signal is emitted when the z value of the map object
    has changed.

    The new value is \a zValue.
*/

/*!
\fn void QGeoMapObject::visibleChanged(bool visible)

    This signal is emitted when the visible state of the map object
    has changed.

    The new value is \a visible.
*/

/*!
\fn void QGeoMapObject::selectedChanged(bool selected)

    This signal is emitted when the selected state of the map object
    has changed.

    The new vlaue is \a selected.
*/

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

QGeoMapObjectPrivate::QGeoMapObjectPrivate()
    : zValue(0),
      isVisible(true),
      isSelected(false),
      mapData(0),
      units(QGeoMapObject::PixelUnit),
      transType(QGeoMapObject::ExactTransform),
      graphicsItem(0) {}

QGeoMapObjectPrivate::~QGeoMapObjectPrivate()
{
}

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

#include "moc_qgeomapobject.cpp"

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>#pragma once

#include <boost/filesystem.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/trivial.hpp>
#include <cstdint>
#include <nano/lib/errors.hpp>
#include <nano/lib/jsonconfig.hpp>

#define FATAL_LOG_PREFIX "FATAL ERROR: "

using namespace std::chrono;

namespace nano
{
// A wrapper around a boost logger object to allow
// minimum time spaced output to prevent logging happening
// too quickly.
class logger_mt
{
private:
	void add_to_stream (boost::log::record_ostream & stream)
	{
	}

	template <typename LogItem, typename... LogItems>
	void add_to_stream (boost::log::record_ostream & stream, const LogItem & first_log_item, LogItems &&... remainder_log_items)
	{
		stream << first_log_item;
		add_to_stream (stream, remainder_log_items...);
	}

	template <typename... LogItems>
	void output (LogItems &&... log_items)
	{
		boost::log::record rec = boost_logger_mt.open_record ();
		if (rec)
		{
			boost::log::record_ostream strm (rec);
			add_to_stream (strm, std::forward<LogItems> (log_items)...);
			strm.flush ();
			boost_logger_mt.push_record (std::move (rec));
		}
	}

public:
	/**
	 * @param min_log_delta_a The minimum time between successive output
	 */
	explicit logger_mt (std::chrono::milliseconds const & min_log_delta_a) :
	min_log_delta (min_log_delta_a)
	{
	}

	/*
	 * @param log_items A collection of objects with overloaded operator<< to be output to the log file
	 */
	template <typename... LogItems>
	void always_log (LogItems &&... log_items)
	{
		output (std::forward<LogItems> (log_items)...);
	}

	/*
	 * @param log_items A collection of objects with overloaded operator<< to be output to the log file
	 *					if the last time an item was logged was over min_log_delta time ago.
	 * @return true if the log was successful
	 */
	template <typename... LogItems>
	bool try_log (LogItems &&... log_items)
	{
		auto error (true);
		auto time_now = steady_clock::now ();
		if (((time_now - last_log_time) > min_log_delta) || last_log_time == steady_clock::time_point{})
		{
			output (std::forward<LogItems> (log_items)...);
			last_log_time = time_now;
			error = false;
		}
		return error;
	}

private:
	milliseconds const & min_log_delta;
	steady_clock::time_point last_log_time;
	boost::log::sources::logger_mt boost_logger_mt;
};

class logging
{
public:
	nano::error serialize_json (nano::jsonconfig &) const;
	nano::error deserialize_json (bool &, nano::jsonconfig &);
	bool upgrade_json (unsigned, nano::jsonconfig &);
	bool ledger_logging () const;
	bool ledger_duplicate_logging () const;
	bool vote_logging () const;
	bool network_logging () const;
	bool network_message_logging () const;
	bool network_publish_logging () const;
	bool network_packet_logging () const;
	bool network_keepalive_logging () const;
	bool network_node_id_handshake_logging () const;
	bool node_lifetime_tracing () const;
	bool insufficient_work_logging () const;
	bool upnp_details_logging () const;
	bool timing_logging () const;
	bool log_rpc () const;
	bool log_ipc () const;
	bool bulk_pull_logging () const;
	bool callback_logging () const;
	bool work_generation_time () const;
	bool log_to_cerr () const;
	void init (boost::filesystem::path const &);

	bool ledger_logging_value{ false };
	bool ledger_duplicate_logging_value{ false };
	bool vote_logging_value{ false };
	bool network_logging_value{ true };
	bool network_message_logging_value{ false };
	bool network_publish_logging_value{ false };
	bool network_packet_logging_value{ false };
	bool network_keepalive_logging_value{ false };
	bool network_node_id_handshake_logging_value{ false };
	bool node_lifetime_tracing_value{ false };
	bool insufficient_work_logging_value{ true };
	bool log_rpc_value{ true };
	bool log_ipc_value{ true };
	bool bulk_pull_logging_value{ false };
	bool work_generation_time_value{ true };
	bool upnp_details_logging_value{ false };
	bool timing_logging_value{ false };
	bool log_to_cerr_value{ false };
	bool flush{ true };
	uintmax_t max_size{ 128 * 1024 * 1024 };
	uintmax_t rotation_size{ 4 * 1024 * 1024 };
	milliseconds min_time_between_log_output{ 5 };
	nano::logger_mt logger{ min_time_between_log_output };
	int json_version () const
	{
		return 7;
	}
};
}
<commit_msg>Fix comment formatting in parameter<commit_after>#pragma once

#include <boost/filesystem.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/trivial.hpp>
#include <cstdint>
#include <nano/lib/errors.hpp>
#include <nano/lib/jsonconfig.hpp>

#define FATAL_LOG_PREFIX "FATAL ERROR: "

using namespace std::chrono;

namespace nano
{
// A wrapper around a boost logger object to allow
// minimum time spaced output to prevent logging happening
// too quickly.
class logger_mt
{
private:
	void add_to_stream (boost::log::record_ostream & stream)
	{
	}

	template <typename LogItem, typename... LogItems>
	void add_to_stream (boost::log::record_ostream & stream, const LogItem & first_log_item, LogItems &&... remainder_log_items)
	{
		stream << first_log_item;
		add_to_stream (stream, remainder_log_items...);
	}

	template <typename... LogItems>
	void output (LogItems &&... log_items)
	{
		boost::log::record rec = boost_logger_mt.open_record ();
		if (rec)
		{
			boost::log::record_ostream strm (rec);
			add_to_stream (strm, std::forward<LogItems> (log_items)...);
			strm.flush ();
			boost_logger_mt.push_record (std::move (rec));
		}
	}

public:
	/**
	 * @param min_log_delta_a The minimum time between successive output
	 */
	explicit logger_mt (std::chrono::milliseconds const & min_log_delta_a) :
	min_log_delta (min_log_delta_a)
	{
	}

	/*
	 * @param log_items A collection of objects with overloaded operator<< to be output to the log file
	 */
	template <typename... LogItems>
	void always_log (LogItems &&... log_items)
	{
		output (std::forward<LogItems> (log_items)...);
	}

	/*
	 * @param log_items Output to the log file if the last write was over min_log_delta time ago.
	 * @return true if the log was successful
	 */
	template <typename... LogItems>
	bool try_log (LogItems &&... log_items)
	{
		auto error (true);
		auto time_now = steady_clock::now ();
		if (((time_now - last_log_time) > min_log_delta) || last_log_time == steady_clock::time_point{})
		{
			output (std::forward<LogItems> (log_items)...);
			last_log_time = time_now;
			error = false;
		}
		return error;
	}

private:
	milliseconds const & min_log_delta;
	steady_clock::time_point last_log_time;
	boost::log::sources::logger_mt boost_logger_mt;
};

class logging
{
public:
	nano::error serialize_json (nano::jsonconfig &) const;
	nano::error deserialize_json (bool &, nano::jsonconfig &);
	bool upgrade_json (unsigned, nano::jsonconfig &);
	bool ledger_logging () const;
	bool ledger_duplicate_logging () const;
	bool vote_logging () const;
	bool network_logging () const;
	bool network_message_logging () const;
	bool network_publish_logging () const;
	bool network_packet_logging () const;
	bool network_keepalive_logging () const;
	bool network_node_id_handshake_logging () const;
	bool node_lifetime_tracing () const;
	bool insufficient_work_logging () const;
	bool upnp_details_logging () const;
	bool timing_logging () const;
	bool log_rpc () const;
	bool log_ipc () const;
	bool bulk_pull_logging () const;
	bool callback_logging () const;
	bool work_generation_time () const;
	bool log_to_cerr () const;
	void init (boost::filesystem::path const &);

	bool ledger_logging_value{ false };
	bool ledger_duplicate_logging_value{ false };
	bool vote_logging_value{ false };
	bool network_logging_value{ true };
	bool network_message_logging_value{ false };
	bool network_publish_logging_value{ false };
	bool network_packet_logging_value{ false };
	bool network_keepalive_logging_value{ false };
	bool network_node_id_handshake_logging_value{ false };
	bool node_lifetime_tracing_value{ false };
	bool insufficient_work_logging_value{ true };
	bool log_rpc_value{ true };
	bool log_ipc_value{ true };
	bool bulk_pull_logging_value{ false };
	bool work_generation_time_value{ true };
	bool upnp_details_logging_value{ false };
	bool timing_logging_value{ false };
	bool log_to_cerr_value{ false };
	bool flush{ true };
	uintmax_t max_size{ 128 * 1024 * 1024 };
	uintmax_t rotation_size{ 4 * 1024 * 1024 };
	milliseconds min_time_between_log_output{ 5 };
	nano::logger_mt logger{ min_time_between_log_output };
	int json_version () const
	{
		return 7;
	}
};
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QtDeclarative/qmlengine.h>
#include <QtDeclarative/qmlcomponent.h>
#include <QtDeclarative/qmlview.h>
#include <private/qmlgraphicsrectangle_p.h>
#include <private/qmlbehavior_p.h>
#include <private/qmlanimation_p.h>

class tst_behaviors : public QObject
{
    Q_OBJECT
public:
    tst_behaviors() {}

private slots:
    void simpleBehavior();
    void scriptTriggered();
    void cppTriggered();
    void loop();
    void colorBehavior();
    void replaceBinding();
    //void transitionOverrides();
    void group();
    void emptyBehavior();
    void nonSelectingBehavior();
    void reassignedAnimation();
};

void tst_behaviors::simpleBehavior()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/simple.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);
    QVERIFY(qobject_cast<QmlBehavior*>(rect->findChild<QmlBehavior*>("MyBehavior"))->animation());

    rect->setState("moved");
    QTest::qWait(100);
    qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
    QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
}

void tst_behaviors::scriptTriggered()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/scripttrigger.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setColor(QColor("red"));
    QTest::qWait(100);
    qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
    QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
}

void tst_behaviors::cppTriggered()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/cpptrigger.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    QmlGraphicsRectangle *innerRect = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"));
    QVERIFY(innerRect);

    innerRect->setProperty("x", 200);
    QTest::qWait(100);
    qreal x = innerRect->x();
    QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
}

void tst_behaviors::loop()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/loop.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    //don't crash
    rect->setState("moved");
}

void tst_behaviors::colorBehavior()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/color.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setState("red");
    QTest::qWait(100);
    QColor color = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->color();
    QVERIFY(color != QColor("red") && color != QColor("green"));  //i.e. the behavior has been triggered
}

void tst_behaviors::replaceBinding()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/binding.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setState("moved");
    QTest::qWait(100);
    QmlGraphicsRectangle *innerRect = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"));
    QVERIFY(innerRect);
    qreal x = innerRect->x();
    QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
    QTest::qWait(300);
    QCOMPARE(innerRect->x(), (qreal)200);
    rect->setProperty("basex", 10);
    QCOMPARE(innerRect->x(), (qreal)200);
    rect->setProperty("movedx", 210);
    QTest::qWait(300);
    QCOMPARE(innerRect->x(), (qreal)210);

    rect->setState("");
    QTest::qWait(100);
    x = innerRect->x();
    QVERIFY(x > 10 && x < 210);  //i.e. the behavior has been triggered
    QTest::qWait(300);
    QCOMPARE(innerRect->x(), (qreal)10);
    rect->setProperty("movedx", 200);
    QCOMPARE(innerRect->x(), (qreal)10);
    rect->setProperty("basex", 20);
    QTest::qWait(300);
    QCOMPARE(innerRect->x(), (qreal)20);
}

void tst_behaviors::group()
{
    {
        QmlEngine engine;
        QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/groupProperty.qml"));
        QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
        QVERIFY(rect);

        rect->setState("moved");
        QTest::qWait(100);
        qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
        QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
    }

    {
        QmlEngine engine;
        QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/groupProperty2.qml"));
        QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
        QVERIFY(rect);

        rect->setState("moved");
        QTest::qWait(100);
        qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
        QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
    }
}

void tst_behaviors::emptyBehavior()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/empty.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setState("moved");
    qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
    QCOMPARE(x, qreal(200));    //should change immediately
}

void tst_behaviors::nonSelectingBehavior()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/nonSelecting.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setState("moved");
    qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
    QCOMPARE(x, qreal(200));    //should change immediately
}

void tst_behaviors::reassignedAnimation()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/reassignedAnimation.qml"));
    QTest::ignoreMessage(QtWarningMsg, "QML QmlBehavior (file://" SRCDIR "/data/reassignedAnimation.qml:9:12) Can't change the animation assigned to a Behavior.");
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setState("moved");
    QTest::qWait(200 + 100);
    qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
    QVERIFY(x > 0 && x < 200);  //i.e. the right behavior has been triggered
}

QTEST_MAIN(tst_behaviors)

#include "tst_behaviors.moc"
<commit_msg>Fix test.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QtDeclarative/qmlengine.h>
#include <QtDeclarative/qmlcomponent.h>
#include <QtDeclarative/qmlview.h>
#include <private/qmlgraphicsrectangle_p.h>
#include <private/qmlbehavior_p.h>
#include <private/qmlanimation_p.h>

class tst_behaviors : public QObject
{
    Q_OBJECT
public:
    tst_behaviors() {}

private slots:
    void simpleBehavior();
    void scriptTriggered();
    void cppTriggered();
    void loop();
    void colorBehavior();
    void replaceBinding();
    //void transitionOverrides();
    void group();
    void emptyBehavior();
    void nonSelectingBehavior();
    void reassignedAnimation();
};

void tst_behaviors::simpleBehavior()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/simple.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);
    QVERIFY(qobject_cast<QmlBehavior*>(rect->findChild<QmlBehavior*>("MyBehavior"))->animation());

    rect->setState("moved");
    QTest::qWait(100);
    qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
    QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
}

void tst_behaviors::scriptTriggered()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/scripttrigger.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setColor(QColor("red"));
    QTest::qWait(100);
    qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
    QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
}

void tst_behaviors::cppTriggered()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/cpptrigger.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    QmlGraphicsRectangle *innerRect = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"));
    QVERIFY(innerRect);

    innerRect->setProperty("x", 200);
    QTest::qWait(100);
    qreal x = innerRect->x();
    QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
}

void tst_behaviors::loop()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/loop.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    //don't crash
    rect->setState("moved");
}

void tst_behaviors::colorBehavior()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/color.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setState("red");
    QTest::qWait(100);
    QColor color = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->color();
    QVERIFY(color != QColor("red") && color != QColor("green"));  //i.e. the behavior has been triggered
}

void tst_behaviors::replaceBinding()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/binding.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setState("moved");
    QTest::qWait(100);
    QmlGraphicsRectangle *innerRect = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"));
    QVERIFY(innerRect);
    qreal x = innerRect->x();
    QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
    QTest::qWait(300);
    QCOMPARE(innerRect->x(), (qreal)200);
    rect->setProperty("basex", 10);
    QCOMPARE(innerRect->x(), (qreal)200);
    rect->setProperty("movedx", 210);
    QTest::qWait(300);
    QCOMPARE(innerRect->x(), (qreal)210);

    rect->setState("");
    QTest::qWait(100);
    x = innerRect->x();
    QVERIFY(x > 10 && x < 210);  //i.e. the behavior has been triggered
    QTest::qWait(300);
    QCOMPARE(innerRect->x(), (qreal)10);
    rect->setProperty("movedx", 200);
    QCOMPARE(innerRect->x(), (qreal)10);
    rect->setProperty("basex", 20);
    QTest::qWait(300);
    QCOMPARE(innerRect->x(), (qreal)20);
}

void tst_behaviors::group()
{
    {
        QmlEngine engine;
        QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/groupProperty.qml"));
        QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
        QVERIFY(rect);

        rect->setState("moved");
        QTest::qWait(100);
        qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
        QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
    }

    {
        QmlEngine engine;
        QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/groupProperty2.qml"));
        QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
        QVERIFY(rect);

        rect->setState("moved");
        QTest::qWait(100);
        qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
        QVERIFY(x > 0 && x < 200);  //i.e. the behavior has been triggered
    }
}

void tst_behaviors::emptyBehavior()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/empty.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setState("moved");
    qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
    QCOMPARE(x, qreal(200));    //should change immediately
}

void tst_behaviors::nonSelectingBehavior()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/nonSelecting.qml"));
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setState("moved");
    qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
    QCOMPARE(x, qreal(200));    //should change immediately
}

void tst_behaviors::reassignedAnimation()
{
    QmlEngine engine;
    QmlComponent c(&engine, QUrl("file://" SRCDIR "/data/reassignedAnimation.qml"));
    QTest::ignoreMessage(QtWarningMsg, "QML QmlBehavior (file://" SRCDIR "/data/reassignedAnimation.qml:9:12) Can't change the animation assigned to a Behavior.");
    QmlGraphicsRectangle *rect = qobject_cast<QmlGraphicsRectangle*>(c.create());
    QVERIFY(rect);

    rect->setState("moved");
    QTest::qWait(200 + 100);
    qreal x = qobject_cast<QmlGraphicsRectangle*>(rect->findChild<QmlGraphicsRectangle*>("MyRect"))->x();
    QCOMPARE(x, qreal(200));  //i.e. the right behavior has been triggered
}

QTEST_MAIN(tst_behaviors)

#include "tst_behaviors.moc"
<|endoftext|>


<commit_before>/**
 * @copyright
 * ====================================================================
 *    Licensed to the Apache Software Foundation (ASF) under one
 *    or more contributor license agreements.  See the NOTICE file
 *    distributed with this work for additional information
 *    regarding copyright ownership.  The ASF licenses this file
 *    to you under the Apache License, Version 2.0 (the
 *    "License"); you may not use this file except in compliance
 *    with the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing,
 *    software distributed under the License is distributed on an
 *    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *    KIND, either express or implied.  See the License for the
 *    specific language governing permissions and limitations
 *    under the License.
 * ====================================================================
 * @endcopyright
 *
 * @file LogMessageCallback.cpp
 * @brief Implementation of the class LogMessageCallback
 */

#include "LogMessageCallback.h"
#include "CreateJ.h"
#include "EnumMapper.h"
#include "JNIUtil.h"
#include "svn_time.h"
#include "svn_sorts.h"
#include "svn_compat.h"

/**
 * Create a LogMessageCallback object
 * @param jcallback the Java callback object.
 */
LogMessageCallback::LogMessageCallback(jobject jcallback)
{
  m_callback = jcallback;
}

/**
 * Destroy a LogMessageCallback object
 */
LogMessageCallback::~LogMessageCallback()
{
  // The m_callback does not need to be destroyed because it is the
  // passed in parameter to the Java SVNClientInterface.logMessages
  // method.
}

svn_error_t *
LogMessageCallback::callback(void *baton,
                             svn_log_entry_t *log_entry,
                             apr_pool_t *pool)
{
  if (baton)
    return ((LogMessageCallback *)baton)->singleMessage(log_entry, pool);

  return SVN_NO_ERROR;
}

/**
 * Callback called for a single log message
 */
svn_error_t *
LogMessageCallback::singleMessage(svn_log_entry_t *log_entry, apr_pool_t *pool)
{
  JNIEnv *env = JNIUtil::getEnv();

  // The method id will not change during the time this library is
  // loaded, so it can be cached.
  static jmethodID sm_mid = 0;
  if (sm_mid == 0)
    {
      jclass clazz = env->FindClass(JAVA_PACKAGE"/callback/LogMessageCallback");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;

      sm_mid = env->GetMethodID(clazz,
                                "singleMessage",
                                "(Ljava/util/Set;JLjava/util/Map;Z)V");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;

      env->DeleteLocalRef(clazz);
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;
    }

  jclass clazzCP = env->FindClass(JAVA_PACKAGE"/ChangePath");
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  static jmethodID midCP = 0;
  if (midCP == 0)
    {
      midCP = env->GetMethodID(clazzCP,
                               "<init>",
                               "(Ljava/lang/String;JLjava/lang/String;CIII)V");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;
    }

  jobject jChangedPaths = NULL;
  if (log_entry->changed_paths)
    {
      apr_hash_index_t *hi;
      std::vector<jobject> jcps;

      for (hi = apr_hash_first(pool, log_entry->changed_paths);
           hi;
           hi = apr_hash_next(hi))
        {
          const char *path = (const char *) svn_apr_hash_index_key(hi);
          svn_log_changed_path2_t *log_item =
                    (svn_log_changed_path2_t *) svn_apr_hash_index_val(hi);

          jstring jpath = JNIUtil::makeJString(path);
          if (JNIUtil::isJavaExceptionThrown())
            return SVN_NO_ERROR;

          jstring jcopyFromPath =
            JNIUtil::makeJString(log_item->copyfrom_path);
          if (JNIUtil::isJavaExceptionThrown())
            return SVN_NO_ERROR;

          jlong jcopyFromRev = log_item->copyfrom_rev;
          jchar jaction = log_item->action;

          jobject cp = env->NewObject(clazzCP, midCP, jpath, jcopyFromRev,
                              jcopyFromPath, jaction,
                              EnumMapper::mapNodeKind(log_item->node_kind),
                              EnumMapper::mapTristate(log_item->text_modified),
                              EnumMapper::mapTristate(log_item->props_modified));
          if (JNIUtil::isJavaExceptionThrown())
            return SVN_NO_ERROR;

          jcps.push_back(cp);

          env->DeleteLocalRef(jpath);
          if (JNIUtil::isJavaExceptionThrown())
            return SVN_NO_ERROR;

          env->DeleteLocalRef(jcopyFromPath);
          if (JNIUtil::isJavaExceptionThrown())
            return SVN_NO_ERROR;
        }

      jChangedPaths = CreateJ::Set(jcps);
    }

  jobject jrevprops = NULL;
  if (log_entry->revprops != NULL && apr_hash_count(log_entry->revprops) > 0)
    jrevprops = CreateJ::PropertyMap(log_entry->revprops, pool);

  env->CallVoidMethod(m_callback,
                      sm_mid,
                      jChangedPaths,
                      (jlong)log_entry->revision,
                      jrevprops,
                      (jboolean)log_entry->has_children);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  env->DeleteLocalRef(jChangedPaths);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  env->DeleteLocalRef(jrevprops);
  // No need to check for an exception here, because we return anyway.

  return SVN_NO_ERROR;
}
<commit_msg>JavaHL: Fix build errors introduced by r922003.<commit_after>/**
 * @copyright
 * ====================================================================
 *    Licensed to the Apache Software Foundation (ASF) under one
 *    or more contributor license agreements.  See the NOTICE file
 *    distributed with this work for additional information
 *    regarding copyright ownership.  The ASF licenses this file
 *    to you under the Apache License, Version 2.0 (the
 *    "License"); you may not use this file except in compliance
 *    with the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing,
 *    software distributed under the License is distributed on an
 *    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *    KIND, either express or implied.  See the License for the
 *    specific language governing permissions and limitations
 *    under the License.
 * ====================================================================
 * @endcopyright
 *
 * @file LogMessageCallback.cpp
 * @brief Implementation of the class LogMessageCallback
 */

#include "LogMessageCallback.h"
#include "CreateJ.h"
#include "EnumMapper.h"
#include "JNIUtil.h"
#include "svn_time.h"
#include "svn_sorts.h"
#include "svn_compat.h"

/**
 * Create a LogMessageCallback object
 * @param jcallback the Java callback object.
 */
LogMessageCallback::LogMessageCallback(jobject jcallback)
{
  m_callback = jcallback;
}

/**
 * Destroy a LogMessageCallback object
 */
LogMessageCallback::~LogMessageCallback()
{
  // The m_callback does not need to be destroyed because it is the
  // passed in parameter to the Java SVNClientInterface.logMessages
  // method.
}

svn_error_t *
LogMessageCallback::callback(void *baton,
                             svn_log_entry_t *log_entry,
                             apr_pool_t *pool)
{
  if (baton)
    return ((LogMessageCallback *)baton)->singleMessage(log_entry, pool);

  return SVN_NO_ERROR;
}

/**
 * Callback called for a single log message
 */
svn_error_t *
LogMessageCallback::singleMessage(svn_log_entry_t *log_entry, apr_pool_t *pool)
{
  JNIEnv *env = JNIUtil::getEnv();

  // The method id will not change during the time this library is
  // loaded, so it can be cached.
  static jmethodID sm_mid = 0;
  if (sm_mid == 0)
    {
      jclass clazz = env->FindClass(JAVA_PACKAGE"/callback/LogMessageCallback");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;

      sm_mid = env->GetMethodID(clazz,
                                "singleMessage",
                                "(Ljava/util/Set;JLjava/util/Map;Z)V");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;

      env->DeleteLocalRef(clazz);
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;
    }

  jclass clazzCP = env->FindClass(JAVA_PACKAGE"/ChangePath");
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  static jmethodID midCP = 0;
  if (midCP == 0)
    {
      midCP = env->GetMethodID(clazzCP,
                               "<init>",
                               "(Ljava/lang/String;JLjava/lang/String;CIII)V");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;
    }

  jobject jChangedPaths = NULL;
  if (log_entry->changed_paths)
    {
      apr_hash_index_t *hi;
      std::vector<jobject> jcps;

      for (hi = apr_hash_first(pool, log_entry->changed_paths);
           hi;
           hi = apr_hash_next(hi))
        {
          const char *path = (const char *) svn__apr_hash_index_key(hi);
          svn_log_changed_path2_t *log_item =
                    (svn_log_changed_path2_t *) svn__apr_hash_index_val(hi);

          jstring jpath = JNIUtil::makeJString(path);
          if (JNIUtil::isJavaExceptionThrown())
            return SVN_NO_ERROR;

          jstring jcopyFromPath =
            JNIUtil::makeJString(log_item->copyfrom_path);
          if (JNIUtil::isJavaExceptionThrown())
            return SVN_NO_ERROR;

          jlong jcopyFromRev = log_item->copyfrom_rev;
          jchar jaction = log_item->action;

          jobject cp = env->NewObject(clazzCP, midCP, jpath, jcopyFromRev,
                              jcopyFromPath, jaction,
                              EnumMapper::mapNodeKind(log_item->node_kind),
                              EnumMapper::mapTristate(log_item->text_modified),
                              EnumMapper::mapTristate(log_item->props_modified));
          if (JNIUtil::isJavaExceptionThrown())
            return SVN_NO_ERROR;

          jcps.push_back(cp);

          env->DeleteLocalRef(jpath);
          if (JNIUtil::isJavaExceptionThrown())
            return SVN_NO_ERROR;

          env->DeleteLocalRef(jcopyFromPath);
          if (JNIUtil::isJavaExceptionThrown())
            return SVN_NO_ERROR;
        }

      jChangedPaths = CreateJ::Set(jcps);
    }

  jobject jrevprops = NULL;
  if (log_entry->revprops != NULL && apr_hash_count(log_entry->revprops) > 0)
    jrevprops = CreateJ::PropertyMap(log_entry->revprops, pool);

  env->CallVoidMethod(m_callback,
                      sm_mid,
                      jChangedPaths,
                      (jlong)log_entry->revision,
                      jrevprops,
                      (jboolean)log_entry->has_children);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  env->DeleteLocalRef(jChangedPaths);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  env->DeleteLocalRef(jrevprops);
  // No need to check for an exception here, because we return anyway.

  return SVN_NO_ERROR;
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2010 Daisuke Okanohara
 *
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 *
 *   1. Redistributions of source code must retain the above Copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *   2. 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.
 *
 *   3. Neither the name of the authors nor the names of its contributors
 *      may be used to endorse or promote products derived from this
 *      software without specific prior written permission.
 */

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

#include "redsvdFile.hpp"
#include "redsvd.hpp"
#include "redsvdIncr.hpp"

using namespace std;
using namespace Eigen;

namespace REDSVD{

namespace {

void writeMatrix_(const string& fn, const MatrixXf& M){
  cout << "write " << fn << endl;
  FILE* outfp = fopen(fn.c_str(), "wb");
  if (outfp == NULL){
    throw string("cannot open ") + fn;
  }

  for (int i = 0; i < M.rows(); ++i){
    for (int j = 0; j < M.cols(); ++j){
      fprintf(outfp, "%+f ",  M(i, j));
    }
    fprintf(outfp, "\n");
  }

  fclose(outfp);
}

void writeVector_(const string& fn, const VectorXf& V){
  cout << "write " << fn << endl;
  FILE* outfp = fopen(fn.c_str(), "wb");
  if (outfp == NULL){
    throw string("cannot open ") + fn;
  }

  for (int i = 0; i < V.rows(); ++i){
    fprintf(outfp, "%+f\n", V(i));
  }

  fclose(outfp);
}

void readLine(const string& line,
	      fv_t& fv){
  istringstream is(line);

  int id;
  char sep;
  float val;
  while (is >> id >> sep >> val){
    fv.push_back(make_pair(id, val));
  }
  sort(fv.begin(), fv.end());
  fv.erase(unique(fv.begin(), fv.end()), fv.end());
}

}

void readMatrix(const std::string& fn, SMatrixXf& A){
  vector<fv_t> fvs;
  ifstream ifs(fn.c_str());
  if (!ifs){
    throw string("failed to open") + fn;
  }

  for (string line; getline(ifs, line); ){
    fv_t fv;
    readLine(line, fv);
    //if (fv.size() == 0) continue;
    fvs.push_back(fv);
  }
  Util::convertFV2Mat(fvs, A);
}

void readMatrix(const std::string& fn, MatrixXf& A){
  ifstream ifs(fn.c_str());
  if (!ifs){
    throw string("failed to open " ) + fn;
  }

  vector< vector<float> > vs;
  for (string line; getline(ifs, line); ){
    istringstream is(line);
    vector<float> v;
    float val;
    while (is >> val){
      v.push_back(val);
    }
    vs.push_back(v);
  }

  size_t rowN = vs.size();
  if (rowN == 0) return;
  size_t colN = vs[0].size();
  A.resize(rowN, colN);

  for (size_t i = 0; i < rowN; ++i){
    if (colN != vs[i].size()){
      cerr << "warning: " << i+1 << "-th row has " << vs[i].size() << " entries. "
	   << colN << " entries are expected" << endl;
    }
    size_t colNmin = min(colN, vs[i].size());
    for (size_t j = 0; j < colNmin; ++j){
      A(i, j) = vs[i][j];
    }
  }
}

void writeMatrix(const string& fn, const REDSVD::RedSVD& A){
  writeMatrix_(fn + ".U", A.matrixU());
  writeVector_(fn + ".S", A.singularValues());
  writeMatrix_(fn + ".V", A.matrixV());
}

void writeMatrix(const string& fn, const REDSVD::RedSVDIncr& A){
  writeMatrix_(fn + ".U", A.matrixU());
  writeVector_(fn + ".S", A.singularValues());
  writeMatrix_(fn + ".V", A.matrixV());
}

void writeMatrix(const string& fn, const REDSVD::RedPCA& A){
  writeMatrix_(fn + ".pc",    A.principalComponents());
  writeMatrix_(fn + ".score", A.scores());
}

void writeMatrix(const string& fn, const REDSVD::RedSymEigen& A){
  writeMatrix_(fn + ".evec", A.eigenVectors());
  writeVector_(fn + ".eval", A.eigenValues());
}

}
<commit_msg>Remove trailing whitespace in matrix output<commit_after>/*
 *  Copyright (c) 2010 Daisuke Okanohara
 *
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 *
 *   1. Redistributions of source code must retain the above Copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *   2. 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.
 *
 *   3. Neither the name of the authors nor the names of its contributors
 *      may be used to endorse or promote products derived from this
 *      software without specific prior written permission.
 */

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

#include "redsvdFile.hpp"
#include "redsvd.hpp"
#include "redsvdIncr.hpp"

using namespace std;
using namespace Eigen;

namespace REDSVD{

namespace {

void writeMatrix_(const string& fn, const MatrixXf& M){
  cout << "write " << fn << endl;
  FILE* outfp = fopen(fn.c_str(), "wb");
  if (outfp == NULL){
    throw string("cannot open ") + fn;
  }

  for (int i = 0; i < M.rows(); ++i){
    /* print first element of the line */
    fprintf(outfp, "%+f",  M(i, 0));

    for (int j = 1; j < M.cols(); ++j){
      fprintf(outfp, " %+f",  M(i, j));
    }
    fprintf(outfp, "\n");
  }

  fclose(outfp);
}

void writeVector_(const string& fn, const VectorXf& V){
  cout << "write " << fn << endl;
  FILE* outfp = fopen(fn.c_str(), "wb");
  if (outfp == NULL){
    throw string("cannot open ") + fn;
  }

  for (int i = 0; i < V.rows(); ++i){
    fprintf(outfp, "%+f\n", V(i));
  }

  fclose(outfp);
}

void readLine(const string& line,
	      fv_t& fv){
  istringstream is(line);

  int id;
  char sep;
  float val;
  while (is >> id >> sep >> val){
    fv.push_back(make_pair(id, val));
  }
  sort(fv.begin(), fv.end());
  fv.erase(unique(fv.begin(), fv.end()), fv.end());
}

}

void readMatrix(const std::string& fn, SMatrixXf& A){
  vector<fv_t> fvs;
  ifstream ifs(fn.c_str());
  if (!ifs){
    throw string("failed to open") + fn;
  }

  for (string line; getline(ifs, line); ){
    fv_t fv;
    readLine(line, fv);
    //if (fv.size() == 0) continue;
    fvs.push_back(fv);
  }
  Util::convertFV2Mat(fvs, A);
}

void readMatrix(const std::string& fn, MatrixXf& A){
  ifstream ifs(fn.c_str());
  if (!ifs){
    throw string("failed to open " ) + fn;
  }

  vector< vector<float> > vs;
  for (string line; getline(ifs, line); ){
    istringstream is(line);
    vector<float> v;
    float val;
    while (is >> val){
      v.push_back(val);
    }
    vs.push_back(v);
  }

  size_t rowN = vs.size();
  if (rowN == 0) return;
  size_t colN = vs[0].size();
  A.resize(rowN, colN);

  for (size_t i = 0; i < rowN; ++i){
    if (colN != vs[i].size()){
      cerr << "warning: " << i+1 << "-th row has " << vs[i].size() << " entries. "
	   << colN << " entries are expected" << endl;
    }
    size_t colNmin = min(colN, vs[i].size());
    for (size_t j = 0; j < colNmin; ++j){
      A(i, j) = vs[i][j];
    }
  }
}

void writeMatrix(const string& fn, const REDSVD::RedSVD& A){
  writeMatrix_(fn + ".U", A.matrixU());
  writeVector_(fn + ".S", A.singularValues());
  writeMatrix_(fn + ".V", A.matrixV());
}

void writeMatrix(const string& fn, const REDSVD::RedSVDIncr& A){
  writeMatrix_(fn + ".U", A.matrixU());
  writeVector_(fn + ".S", A.singularValues());
  writeMatrix_(fn + ".V", A.matrixV());
}

void writeMatrix(const string& fn, const REDSVD::RedPCA& A){
  writeMatrix_(fn + ".pc",    A.principalComponents());
  writeMatrix_(fn + ".score", A.scores());
}

void writeMatrix(const string& fn, const REDSVD::RedSymEigen& A){
  writeMatrix_(fn + ".evec", A.eigenVectors());
  writeVector_(fn + ".eval", A.eigenValues());
}

}
<|endoftext|>


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

#include "chromecast/media/cma/test/media_component_device_feeder_for_test.h"

#include <list>
#include <vector>

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "chromecast/media/base/decrypt_context.h"
#include "chromecast/media/cma/backend/audio_pipeline_device.h"
#include "chromecast/media/cma/backend/media_clock_device.h"
#include "chromecast/media/cma/backend/media_pipeline_device.h"
#include "chromecast/media/cma/backend/video_pipeline_device.h"
#include "chromecast/media/cma/base/decoder_buffer_adapter.h"
#include "chromecast/media/cma/base/decoder_buffer_base.h"
#include "chromecast/media/cma/test/frame_segmenter_for_test.h"
#include "media/base/audio_decoder_config.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/buffers.h"
#include "media/base/decoder_buffer.h"
#include "media/base/video_decoder_config.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace chromecast {
namespace media {

MediaComponentDeviceFeederForTest::MediaComponentDeviceFeederForTest(
    MediaComponentDevice *device,
    const BufferList& frames)
    : media_component_device_(device),
      rendering_frame_idx_(1),
      clock_frame_idx_(1),
      feeding_completed_(false) {
  frames_ = frames;
}

MediaComponentDeviceFeederForTest::~MediaComponentDeviceFeederForTest() {
}

void MediaComponentDeviceFeederForTest::Initialize(
    const base::Closure& eos_cb) {
  eos_cb_ = eos_cb;

  MediaComponentDevice::Client client;
  client.eos_cb =
      base::Bind(&MediaComponentDeviceFeederForTest::OnEos,
                 base::Unretained(this));
  media_component_device_->SetClient(client);

  bool success =
      media_component_device_->SetState(MediaComponentDevice::kStateIdle);
  ASSERT_TRUE(success);
  success = media_component_device_->SetStartPts(base::TimeDelta());
  ASSERT_TRUE(success);
  success =
      media_component_device_->SetState(MediaComponentDevice::kStatePaused);
  ASSERT_TRUE(success);
}

void MediaComponentDeviceFeederForTest::Feed() {
  // Start rendering if needed.
  if (rendering_frame_idx_ == 0) {
    media_component_device_->SetState(MediaComponentDevice::kStateRunning);
  } else {
    rendering_frame_idx_--;
  }

  // Possibly feed one frame
  DCHECK(!frames_.empty());
  scoped_refptr<DecoderBufferBase> buffer = frames_.front();

  MediaComponentDevice::FrameStatus status = media_component_device_->PushFrame(
      scoped_refptr<DecryptContext>(), buffer,
      ::media::BindToCurrentLoop(
          base::Bind(&MediaComponentDeviceFeederForTest::OnFramePushed,
                     base::Unretained(this))));
  EXPECT_NE(status, MediaComponentDevice::kFrameFailed);
  frames_.pop_front();

  // Feeding is done, just wait for the end of stream callback.
  if (buffer->end_of_stream() || frames_.empty()) {
    if (frames_.empty() && !buffer->end_of_stream()) {
      LOG(WARNING) << "Stream emptied without feeding EOS frame";
    }

    feeding_completed_ = true;
    return;
  }

  if (status == MediaComponentDevice::kFramePending)
    return;

  OnFramePushed(MediaComponentDevice::kFrameSuccess);
}

void MediaComponentDeviceFeederForTest::OnFramePushed(
    MediaComponentDevice::FrameStatus status) {
  EXPECT_NE(status, MediaComponentDevice::kFrameFailed);
  if (feeding_completed_)
    return;

  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::Bind(&MediaComponentDeviceFeederForTest::Feed,
                            base::Unretained(this)));
}

void MediaComponentDeviceFeederForTest::OnEos() {
  bool success = media_component_device_->SetState(
      MediaComponentDevice::kStateIdle);
  ASSERT_TRUE(success);
  success = media_component_device_->SetState(
      MediaComponentDevice::kStateUninitialized);
  ASSERT_TRUE(success);

  if (!eos_cb_.is_null()) {
    eos_cb_.Run();
  }
}

}  // namespace media
}  // namespace chromecast
<commit_msg>Revert of [Chromecast] Add explicit task_runner in CMA test (patchset #4 id:60001 of https://codereview.chromium.org/1267563003/)<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromecast/media/cma/test/media_component_device_feeder_for_test.h"

#include <list>
#include <vector>

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "chromecast/media/base/decrypt_context.h"
#include "chromecast/media/cma/backend/audio_pipeline_device.h"
#include "chromecast/media/cma/backend/media_clock_device.h"
#include "chromecast/media/cma/backend/media_pipeline_device.h"
#include "chromecast/media/cma/backend/video_pipeline_device.h"
#include "chromecast/media/cma/base/decoder_buffer_adapter.h"
#include "chromecast/media/cma/base/decoder_buffer_base.h"
#include "chromecast/media/cma/test/frame_segmenter_for_test.h"
#include "media/base/audio_decoder_config.h"
#include "media/base/buffers.h"
#include "media/base/decoder_buffer.h"
#include "media/base/video_decoder_config.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace chromecast {
namespace media {

MediaComponentDeviceFeederForTest::MediaComponentDeviceFeederForTest(
    MediaComponentDevice *device,
    const BufferList& frames)
    : media_component_device_(device),
      rendering_frame_idx_(1),
      clock_frame_idx_(1),
      feeding_completed_(false) {
  frames_ = frames;
}

MediaComponentDeviceFeederForTest::~MediaComponentDeviceFeederForTest() {
}

void MediaComponentDeviceFeederForTest::Initialize(
    const base::Closure& eos_cb) {
  eos_cb_ = eos_cb;

  MediaComponentDevice::Client client;
  client.eos_cb =
      base::Bind(&MediaComponentDeviceFeederForTest::OnEos,
                 base::Unretained(this));
  media_component_device_->SetClient(client);

  bool success =
      media_component_device_->SetState(MediaComponentDevice::kStateIdle);
  ASSERT_TRUE(success);
  success = media_component_device_->SetStartPts(base::TimeDelta());
  ASSERT_TRUE(success);
  success =
      media_component_device_->SetState(MediaComponentDevice::kStatePaused);
  ASSERT_TRUE(success);
}

void MediaComponentDeviceFeederForTest::Feed() {
  // Start rendering if needed.
  if (rendering_frame_idx_ == 0) {
    media_component_device_->SetState(MediaComponentDevice::kStateRunning);
  } else {
    rendering_frame_idx_--;
  }

  // Possibly feed one frame
  DCHECK(!frames_.empty());
  scoped_refptr<DecoderBufferBase> buffer = frames_.front();

  MediaComponentDevice::FrameStatus status =
      media_component_device_->PushFrame(
          scoped_refptr<DecryptContext>(),
          buffer,
          base::Bind(&MediaComponentDeviceFeederForTest::OnFramePushed,
                     base::Unretained(this)));
  EXPECT_NE(status, MediaComponentDevice::kFrameFailed);
  frames_.pop_front();

  // Feeding is done, just wait for the end of stream callback.
  if (buffer->end_of_stream() || frames_.empty()) {
    if (frames_.empty() && !buffer->end_of_stream()) {
      LOG(WARNING) << "Stream emptied without feeding EOS frame";
    }

    feeding_completed_ = true;
    return;
  }

  if (status == MediaComponentDevice::kFramePending)
    return;

  OnFramePushed(MediaComponentDevice::kFrameSuccess);
}

void MediaComponentDeviceFeederForTest::OnFramePushed(
    MediaComponentDevice::FrameStatus status) {
  EXPECT_NE(status, MediaComponentDevice::kFrameFailed);
  if (feeding_completed_)
    return;

  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::Bind(&MediaComponentDeviceFeederForTest::Feed,
                            base::Unretained(this)));
}

void MediaComponentDeviceFeederForTest::OnEos() {
  bool success = media_component_device_->SetState(
      MediaComponentDevice::kStateIdle);
  ASSERT_TRUE(success);
  success = media_component_device_->SetState(
      MediaComponentDevice::kStateUninitialized);
  ASSERT_TRUE(success);

  if (!eos_cb_.is_null()) {
    eos_cb_.Run();
  }
}

}  // namespace media
}  // namespace chromecast
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// Copyright (c) 2017 John D. Haughton
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//------------------------------------------------------------------------------

// Stub Sounder implementation using PLT::Audio

#include "PLT/Sounder.h"
#include "PLT/Audio.h"
#include "STB/Waveform.h"

class Beep : public PLT::Audio::Out
{
public:
   Beep()
      : PLT::Audio::Out(SAMPLE_FREQUENCY, FORMAT, CHANNELS)
   {}

   void control(unsigned gain_8, unsigned freq)
   {
      if (gain_8 == 0)
      {
         setEnable(false);
      }
      else
      {
         delta = double(freq) / SAMPLE_FREQUENCY;
         gain  = gain_8 * 0x80;

         setEnable(true);
      }
   }

private:
   static const unsigned           SAMPLE_FREQUENCY = 44100; // 44.1 KHz
   static const PLT::Audio::Format FORMAT           = PLT::Audio::Format::SINT16;
   static const unsigned           CHANNELS         = 1;

   double   phase{0.0};
   double   delta;
   unsigned gain{0};

   virtual void getSamples(int16_t* buffer, unsigned n) override
   {
      for(unsigned i = 0; i < n; ++i)
      {
         buffer[i] = STB::Waveform::sine(phase) * gain;
         phase += delta;
      }
   }
};

void PLT::Sounder::setEnable(bool enable)
{
   control(enable ? 0xFF : 0x00, 440);
}

void PLT::Sounder::control(unsigned gain_8, unsigned freq)
{
   static Beep beep;

   beep.control(gain_8, freq);
}
<commit_msg>Extend PLt::Sounder API for basic gain and frequency control<commit_after>//------------------------------------------------------------------------------
// Copyright (c) 2017 John D. Haughton
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//------------------------------------------------------------------------------

// Stub Sounder implementation using PLT::Audio

#include "PLT/Sounder.h"
#include "PLT/Audio.h"
#include "STB/Waveform.h"

class Beep : public PLT::Audio::Out
{
public:
   Beep()
      : PLT::Audio::Out(SAMPLE_FREQUENCY, FORMAT, CHANNELS)
   {}

   void control(unsigned gain_8, unsigned freq)
   {
      if (gain_8 == 0)
      {
         setEnable(false);
      }
      else
      {
         delta = double(freq) / SAMPLE_FREQUENCY;
         gain  = gain_8 * 0x80;

         setEnable(true);
      }
   }

private:
   static const unsigned           SAMPLE_FREQUENCY = 44100; // 44.1 KHz
   static const PLT::Audio::Format FORMAT           = PLT::Audio::Format::SINT16;
   static const unsigned           CHANNELS         = 1;

   double   phase{0.0};
   double   delta;
   unsigned gain{0};

   virtual void getSamples(int16_t* buffer, unsigned n) override
   {
      // XXX isn't phase going to run out of precision?
      for(unsigned i = 0; i < n; ++i)
      {
         buffer[i] = STB::Waveform::sine(phase) * gain;
         phase += delta;
      }
   }
};

void PLT::Sounder::setEnable(bool enable)
{
   control(enable ? 0xFF : 0x00, 440);
}

void PLT::Sounder::control(unsigned gain_8, unsigned freq)
{
   static Beep beep;

   beep.control(gain_8, freq);
}
<|endoftext|>