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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "XMLChartStyleContext.hxx"

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLNUMFI_HXX
#include "xmlnumfi.hxx"
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include "families.hxx"
#endif

#include "XMLChartPropertyContext.hxx"

using namespace com::sun::star;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_DATA_STYLE_NAME;
using ::xmloff::token::XML_TEXT_PROPERTIES;
using ::xmloff::token::XML_PARAGRAPH_PROPERTIES;
using ::xmloff::token::XML_GRAPHIC_PROPERTIES;
using ::xmloff::token::XML_CHART_PROPERTIES;

TYPEINIT1( XMLChartStyleContext, XMLPropStyleContext );

// protected

void XMLChartStyleContext::SetAttribute(
    sal_uInt16 nPrefixKey,
    const ::rtl::OUString& rLocalName,
    const ::rtl::OUString& rValue )
{
    if( IsXMLToken( rLocalName, XML_DATA_STYLE_NAME ) )
    {
        msDataStyleName =rValue;
    }
    else
    {
        XMLShapeStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue );
    }
}

//public

// CTOR
XMLChartStyleContext::XMLChartStyleContext(
    SvXMLImport& rImport, sal_uInt16 nPrfx,
    const ::rtl::OUString& rLName,
    const uno::Reference< xml::sax::XAttributeList > & xAttrList,
    SvXMLStylesContext& rStyles, sal_uInt16 nFamily ) :

        XMLShapeStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, nFamily ),
        mrStyles( rStyles )
{}

// DTOR
XMLChartStyleContext::~XMLChartStyleContext()
{}

void XMLChartStyleContext::FillPropertySet(
    const uno::Reference< beans::XPropertySet > & rPropSet )
{
    XMLShapeStyleContext::FillPropertySet( rPropSet );
    if( msDataStyleName.getLength())
    {
        SvXMLNumFormatContext* pStyle = (SvXMLNumFormatContext *)mrStyles.FindStyleChildContext(
            XML_STYLE_FAMILY_DATA_STYLE, msDataStyleName, sal_True );
        if( pStyle )
        {
            uno::Any aNumberFormat;
            sal_Int32 nNumberFormat = pStyle->GetKey();
            aNumberFormat <<= nNumberFormat;
            rPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NumberFormat" )),
                                        aNumberFormat );
        }
    }
}

SvXMLImportContext *XMLChartStyleContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const ::rtl::OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext* pContext = NULL;

    if( XML_NAMESPACE_STYLE == nPrefix )
    {
        sal_uInt32 nFamily = 0;
        if( IsXMLToken( rLocalName, XML_TEXT_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_TEXT;
        else if( IsXMLToken( rLocalName, XML_PARAGRAPH_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_PARAGRAPH;
        else if( IsXMLToken( rLocalName, XML_GRAPHIC_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_GRAPHIC;
        else if( IsXMLToken( rLocalName, XML_CHART_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_CHART;
        if( nFamily )
        {
            UniReference < SvXMLImportPropertyMapper > xImpPrMap =
                GetStyles()->GetImportPropertyMapper( GetFamily() );
            if( xImpPrMap.is() )
                pContext = new XMLChartPropertyContext(
                    GetImport(), nPrefix, rLocalName, xAttrList, nFamily,
                    GetProperties(), xImpPrMap );
        }
    }

    if( !pContext )
        pContext = XMLShapeStyleContext::CreateChildContext( nPrefix, rLocalName,
                                                             xAttrList );

    return pContext;
}
<commit_msg>INTEGRATION: CWS chart2mst3 (1.7.6); FILE MERGED 2006/10/20 09:50:41 bm 1.7.6.4: warnings removed 2006/10/19 10:00:19 bm 1.7.6.3: RESYNC: (1.8-1.9); FILE MERGED 2005/10/09 08:08:07 bm 1.7.6.2: RESYNC: (1.7-1.8); FILE MERGED 2005/04/19 17:52:04 iha 1.7.6.1: assert exception<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLChartStyleContext.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 16:08:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "XMLChartStyleContext.hxx"

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLNUMFI_HXX
#include "xmlnumfi.hxx"
#endif
#ifndef _XMLOFF_FAMILIES_HXX_
#include "families.hxx"
#endif

#include "XMLChartPropertyContext.hxx"

using namespace com::sun::star;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_DATA_STYLE_NAME;
using ::xmloff::token::XML_TEXT_PROPERTIES;
using ::xmloff::token::XML_PARAGRAPH_PROPERTIES;
using ::xmloff::token::XML_GRAPHIC_PROPERTIES;
using ::xmloff::token::XML_CHART_PROPERTIES;

TYPEINIT1( XMLChartStyleContext, XMLPropStyleContext );

// protected

void XMLChartStyleContext::SetAttribute(
    sal_uInt16 nPrefixKey,
    const ::rtl::OUString& rLocalName,
    const ::rtl::OUString& rValue )
{
    if( IsXMLToken( rLocalName, XML_DATA_STYLE_NAME ) )
    {
        msDataStyleName =rValue;
    }
    else
    {
        XMLShapeStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue );
    }
}

//public

// CTOR
XMLChartStyleContext::XMLChartStyleContext(
    SvXMLImport& rImport, sal_uInt16 nPrfx,
    const ::rtl::OUString& rLName,
    const uno::Reference< xml::sax::XAttributeList > & xAttrList,
    SvXMLStylesContext& rStyles, sal_uInt16 nFamily ) :

        XMLShapeStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, nFamily ),
        mrStyles( rStyles )
{}

// DTOR
XMLChartStyleContext::~XMLChartStyleContext()
{}

void XMLChartStyleContext::FillPropertySet(
    const uno::Reference< beans::XPropertySet > & rPropSet )
{
    try
    {
        XMLShapeStyleContext::FillPropertySet( rPropSet );
    }
    catch( beans::UnknownPropertyException&  )
    {
        DBG_ASSERT( false, "unknown property exception -> shape style not completly imported for chart style" );
    }
    if( msDataStyleName.getLength())
    {
        SvXMLNumFormatContext* pStyle = (SvXMLNumFormatContext *)mrStyles.FindStyleChildContext(
            XML_STYLE_FAMILY_DATA_STYLE, msDataStyleName, sal_True );
        if( pStyle )
        {
            uno::Any aNumberFormat;
            sal_Int32 nNumberFormat = pStyle->GetKey();
            aNumberFormat <<= nNumberFormat;
            rPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "NumberFormat" )),
                                        aNumberFormat );
        }
    }
}

SvXMLImportContext *XMLChartStyleContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const ::rtl::OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext* pContext = NULL;

    if( XML_NAMESPACE_STYLE == nPrefix )
    {
        sal_uInt32 nFamily = 0;
        if( IsXMLToken( rLocalName, XML_TEXT_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_TEXT;
        else if( IsXMLToken( rLocalName, XML_PARAGRAPH_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_PARAGRAPH;
        else if( IsXMLToken( rLocalName, XML_GRAPHIC_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_GRAPHIC;
        else if( IsXMLToken( rLocalName, XML_CHART_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_CHART;
        if( nFamily )
        {
            UniReference < SvXMLImportPropertyMapper > xImpPrMap =
                GetStyles()->GetImportPropertyMapper( GetFamily() );
            if( xImpPrMap.is() )
                pContext = new XMLChartPropertyContext(
                    GetImport(), nPrefix, rLocalName, xAttrList, nFamily,
                    GetProperties(), xImpPrMap );
        }
    }

    if( !pContext )
        pContext = XMLShapeStyleContext::CreateChildContext( nPrefix, rLocalName,
                                                             xAttrList );

    return pContext;
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "futureprogress.h"
#include "progressbar.h"

#include <QtCore/QFutureWatcher>
#include <QtCore/QTimer>
#include <QtCore/QCoreApplication>
#include <QtCore/QPropertyAnimation>
#include <QtCore/QSequentialAnimationGroup>

#include <QtGui/QColor>
#include <QtGui/QVBoxLayout>
#include <QtGui/QMenu>
#include <QtGui/QProgressBar>
#include <QtGui/QHBoxLayout>
#include <QtGui/QPainter>
#include <QtGui/QMouseEvent>
#include <utils/stylehelper.h>

const int notificationTimeout = 8000;
const int shortNotificationTimeout = 1000;

namespace Core {
namespace Internal {

class FadeWidgetHack : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(float opacity READ opacity WRITE setOpacity)
public:
    FadeWidgetHack(QWidget *parent):QWidget(parent), m_opacity(0){
        setAttribute(Qt::WA_TransparentForMouseEvents);
    }
    void paintEvent(QPaintEvent *);

    void setOpacity(float o) { m_opacity = o; update(); }
    float opacity() const { return m_opacity; }

private:
    float m_opacity;
};

void FadeWidgetHack::paintEvent(QPaintEvent *)
{
    if (m_opacity == 0)
        return;

    QPainter p(this);
    p.setOpacity(m_opacity);
    if (m_opacity > 0)
        Utils::StyleHelper::verticalGradient(&p, rect(), rect());
}

} // namespace Internal

struct FutureProgressPrivate {
    explicit FutureProgressPrivate(FutureProgress *q);

    void tryToFadeAway();

    QFutureWatcher<void> m_watcher;
    Internal::ProgressBar *m_progress;
    QWidget *m_widget;
    QHBoxLayout *m_widgetLayout;
    QString m_type;
    FutureProgress::KeepOnFinishType m_keep;
    bool m_waitingForUserInteraction;
    Internal::FadeWidgetHack *m_faderWidget;
    FutureProgress *m_q;
    bool m_isFading;
};

FutureProgressPrivate::FutureProgressPrivate(FutureProgress *q) :
    m_progress(new Internal::ProgressBar), m_widget(0), m_widgetLayout(new QHBoxLayout),
    m_keep(FutureProgress::DontKeepOnFinish), m_waitingForUserInteraction(false),
    m_faderWidget(new Internal::FadeWidgetHack(q)), m_q(q), m_isFading(false)
{
}

/*!
    \mainclass
    \class Core::FutureProgress
    \brief The FutureProgress class is used to adapt the appearance of
    progress indicators that were created through the ProgressManager class.

    Use the instance of this class that was returned by
    ProgressManager::addTask() to define a widget that
    should be shown below the progress bar, or to change the
    progress title.
    Also use it to react on the event that the user clicks on
    the progress indicator (which can be used to e.g. open a more detailed
    view, or the results of the task).
*/

/*!
    \fn void FutureProgress::clicked()
    Connect to this signal to get informed when the user clicks on the
    progress indicator.
*/

/*!
    \fn void FutureProgress::finished()
    Another way to get informed when the task has finished.
*/

/*!
    \fn QWidget FutureProgress::widget() const
    Returns the custom widget that is shown below the progress indicator.
*/

/*!
    \fn FutureProgress::FutureProgress(QWidget *parent)
    \internal
*/
FutureProgress::FutureProgress(QWidget *parent) :
    QWidget(parent), d(new FutureProgressPrivate(this))
{
    QVBoxLayout *layout = new QVBoxLayout;
    setLayout(layout);
    layout->addWidget(d->m_progress);
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->addLayout(d->m_widgetLayout);
    d->m_widgetLayout->setContentsMargins(7, 0, 7, 2);
    d->m_widgetLayout->setSpacing(0);

    connect(&d->m_watcher, SIGNAL(started()), this, SLOT(setStarted()));
    connect(&d->m_watcher, SIGNAL(finished()), this, SLOT(setFinished()));
    connect(&d->m_watcher, SIGNAL(progressRangeChanged(int,int)), this, SLOT(setProgressRange(int,int)));
    connect(&d->m_watcher, SIGNAL(progressValueChanged(int)), this, SLOT(setProgressValue(int)));
    connect(&d->m_watcher, SIGNAL(progressTextChanged(const QString&)),
            this, SLOT(setProgressText(const QString&)));
    connect(d->m_progress, SIGNAL(clicked()), this, SLOT(cancel()));
}

/*!
    \fn FutureProgress::~FutureProgress()
    \internal
*/
FutureProgress::~FutureProgress()
{
    if (d->m_widget)
        delete d->m_widget;
}

/*!
    \fn void FutureProgress::setWidget(QWidget *widget)
    Sets the \a widget to show below the progress bar.
    This will be destroyed when the progress indicator is destroyed.
    Default is to show no widget below the progress indicator.
*/
void FutureProgress::setWidget(QWidget *widget)
{
    if (d->m_widget)
        delete d->m_widget;
    QSizePolicy sp = widget->sizePolicy();
    sp.setHorizontalPolicy(QSizePolicy::Ignored);
    widget->setSizePolicy(sp);
    d->m_widget = widget;
    if (d->m_widget)
        d->m_widgetLayout->addWidget(d->m_widget);
}

/*!
    \fn void FutureProgress::setTitle(const QString &title)
    Changes the \a title of the progress indicator.
*/
void FutureProgress::setTitle(const QString &title)
{
    d->m_progress->setTitle(title);
}

/*!
    \fn QString FutureProgress::title() const
    Returns the title of the progress indicator.
*/
QString FutureProgress::title() const
{
    return d->m_progress->title();
}

void FutureProgress::cancel()
{
    d->m_watcher.future().cancel();
}

void FutureProgress::updateToolTip(const QString &text)
{
    setToolTip("" + title() + "
" + text);
}

void FutureProgress::setStarted()
{
    d->m_progress->reset();
    d->m_progress->setError(false);
    d->m_progress->setRange(d->m_watcher.progressMinimum(), d->m_watcher.progressMaximum());
    d->m_progress->setValue(d->m_watcher.progressValue());
}

bool FutureProgress::eventFilter(QObject *, QEvent *e)
{
    if (d->m_keep != KeepOnFinish && d->m_waitingForUserInteraction
        && (e->type() == QEvent::MouseMove || e->type() == QEvent::KeyPress)) {
        qApp->removeEventFilter(this);
        QTimer::singleShot(notificationTimeout, this, SLOT(fadeAway()));
    }
    return false;
}

void FutureProgress::setFinished()
{
    updateToolTip(d->m_watcher.future().progressText());

    d->m_progress->setFinished(true);

    if (d->m_watcher.future().isCanceled()) {
        d->m_progress->setError(true);
    } else {
        d->m_progress->setError(false);
    }
    emit finished();
    d->tryToFadeAway();
}

void FutureProgressPrivate::tryToFadeAway()
{
    if (m_isFading)
        return;
    if (m_keep == FutureProgress::KeepOnFinishTillUserInteraction) {
        m_waitingForUserInteraction = true;
        //eventfilter is needed to get user interaction
        //events to start QTimer::singleShot later
        qApp->installEventFilter(m_q);
        m_isFading = true;
    } else if (m_keep == FutureProgress::DontKeepOnFinish && !m_progress->hasError()) {
        QTimer::singleShot(shortNotificationTimeout, m_q, SLOT(fadeAway()));
        m_isFading = true;
    }
}

void FutureProgress::setProgressRange(int min, int max)
{
    d->m_progress->setRange(min, max);
}

void FutureProgress::setProgressValue(int val)
{
    d->m_progress->setValue(val);
}

void FutureProgress::setProgressText(const QString &text)
{
    updateToolTip(text);
}

/*!
    \fn void FutureProgress::setFuture(const QFuture<void> &future)
    \internal
*/
void FutureProgress::setFuture(const QFuture<void> &future)
{
    d->m_watcher.setFuture(future);
}

/*!
    \fn QFuture<void> FutureProgress::future() const
    Returns a QFuture object that represents this running task.
*/
QFuture<void> FutureProgress::future() const
{
    return d->m_watcher.future();
}

/*!
    \fn void FutureProgress::mousePressEvent(QMouseEvent *event)
    \internal
*/
void FutureProgress::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
        emit clicked();
    QWidget::mousePressEvent(event);
}

void FutureProgress::resizeEvent(QResizeEvent *)
{
    d->m_faderWidget->setGeometry(rect());
}

/*!
    \fn bool FutureProgress::hasError() const
    Returns the error state of this progress indicator.
*/
bool FutureProgress::hasError() const
{
    return d->m_progress->hasError();
}

void FutureProgress::fadeAway()
{
    d->m_faderWidget->raise();
    QSequentialAnimationGroup *group = new QSequentialAnimationGroup(this);
    QPropertyAnimation *animation = new QPropertyAnimation(d->m_faderWidget, "opacity");
    animation->setDuration(600);
    animation->setEndValue(1.0);
    group->addAnimation(animation);
    animation = new QPropertyAnimation(this, "maximumHeight");
    animation->setDuration(120);
    animation->setEasingCurve(QEasingCurve::InCurve);
    animation->setStartValue(sizeHint().height());
    animation->setEndValue(0.0);
    group->addAnimation(animation);
    group->start(QAbstractAnimation::DeleteWhenStopped);

    connect(group, SIGNAL(finished()), this, SIGNAL(removeMe()));
}

void FutureProgress::setType(const QString &type)
{
    d->m_type = type;
}

QString FutureProgress::type() const
{
    return d->m_type;
}

void FutureProgress::setKeepOnFinish(KeepOnFinishType keepType)
{
    if (d->m_keep == keepType) {
        return;
    }
    d->m_keep = keepType;

    //if it is not finished tryToFadeAway is called by setFinished at the end
    if (d->m_watcher.isFinished()) {
        d->tryToFadeAway();
    }
}

bool FutureProgress::keepOnFinish() const
{
    return d->m_keep;
}

QWidget *FutureProgress::widget() const
{
    return d->m_widget;
}

} // namespace Core

#include "futureprogress.moc"
<commit_msg>Don't keep canceled tasks forever.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "futureprogress.h"
#include "progressbar.h"

#include <QtCore/QFutureWatcher>
#include <QtCore/QTimer>
#include <QtCore/QCoreApplication>
#include <QtCore/QPropertyAnimation>
#include <QtCore/QSequentialAnimationGroup>

#include <QtGui/QColor>
#include <QtGui/QVBoxLayout>
#include <QtGui/QMenu>
#include <QtGui/QProgressBar>
#include <QtGui/QHBoxLayout>
#include <QtGui/QPainter>
#include <QtGui/QMouseEvent>
#include <utils/stylehelper.h>

const int notificationTimeout = 8000;
const int shortNotificationTimeout = 1000;

namespace Core {
namespace Internal {

class FadeWidgetHack : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(float opacity READ opacity WRITE setOpacity)
public:
    FadeWidgetHack(QWidget *parent):QWidget(parent), m_opacity(0){
        setAttribute(Qt::WA_TransparentForMouseEvents);
    }
    void paintEvent(QPaintEvent *);

    void setOpacity(float o) { m_opacity = o; update(); }
    float opacity() const { return m_opacity; }

private:
    float m_opacity;
};

void FadeWidgetHack::paintEvent(QPaintEvent *)
{
    if (m_opacity == 0)
        return;

    QPainter p(this);
    p.setOpacity(m_opacity);
    if (m_opacity > 0)
        Utils::StyleHelper::verticalGradient(&p, rect(), rect());
}

} // namespace Internal

struct FutureProgressPrivate {
    explicit FutureProgressPrivate(FutureProgress *q);

    void tryToFadeAway();

    QFutureWatcher<void> m_watcher;
    Internal::ProgressBar *m_progress;
    QWidget *m_widget;
    QHBoxLayout *m_widgetLayout;
    QString m_type;
    FutureProgress::KeepOnFinishType m_keep;
    bool m_waitingForUserInteraction;
    Internal::FadeWidgetHack *m_faderWidget;
    FutureProgress *m_q;
    bool m_isFading;
};

FutureProgressPrivate::FutureProgressPrivate(FutureProgress *q) :
    m_progress(new Internal::ProgressBar), m_widget(0), m_widgetLayout(new QHBoxLayout),
    m_keep(FutureProgress::DontKeepOnFinish), m_waitingForUserInteraction(false),
    m_faderWidget(new Internal::FadeWidgetHack(q)), m_q(q), m_isFading(false)
{
}

/*!
    \mainclass
    \class Core::FutureProgress
    \brief The FutureProgress class is used to adapt the appearance of
    progress indicators that were created through the ProgressManager class.

    Use the instance of this class that was returned by
    ProgressManager::addTask() to define a widget that
    should be shown below the progress bar, or to change the
    progress title.
    Also use it to react on the event that the user clicks on
    the progress indicator (which can be used to e.g. open a more detailed
    view, or the results of the task).
*/

/*!
    \fn void FutureProgress::clicked()
    Connect to this signal to get informed when the user clicks on the
    progress indicator.
*/

/*!
    \fn void FutureProgress::finished()
    Another way to get informed when the task has finished.
*/

/*!
    \fn QWidget FutureProgress::widget() const
    Returns the custom widget that is shown below the progress indicator.
*/

/*!
    \fn FutureProgress::FutureProgress(QWidget *parent)
    \internal
*/
FutureProgress::FutureProgress(QWidget *parent) :
    QWidget(parent), d(new FutureProgressPrivate(this))
{
    QVBoxLayout *layout = new QVBoxLayout;
    setLayout(layout);
    layout->addWidget(d->m_progress);
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->addLayout(d->m_widgetLayout);
    d->m_widgetLayout->setContentsMargins(7, 0, 7, 2);
    d->m_widgetLayout->setSpacing(0);

    connect(&d->m_watcher, SIGNAL(started()), this, SLOT(setStarted()));
    connect(&d->m_watcher, SIGNAL(finished()), this, SLOT(setFinished()));
    connect(&d->m_watcher, SIGNAL(progressRangeChanged(int,int)), this, SLOT(setProgressRange(int,int)));
    connect(&d->m_watcher, SIGNAL(progressValueChanged(int)), this, SLOT(setProgressValue(int)));
    connect(&d->m_watcher, SIGNAL(progressTextChanged(const QString&)),
            this, SLOT(setProgressText(const QString&)));
    connect(d->m_progress, SIGNAL(clicked()), this, SLOT(cancel()));
}

/*!
    \fn FutureProgress::~FutureProgress()
    \internal
*/
FutureProgress::~FutureProgress()
{
    if (d->m_widget)
        delete d->m_widget;
}

/*!
    \fn void FutureProgress::setWidget(QWidget *widget)
    Sets the \a widget to show below the progress bar.
    This will be destroyed when the progress indicator is destroyed.
    Default is to show no widget below the progress indicator.
*/
void FutureProgress::setWidget(QWidget *widget)
{
    if (d->m_widget)
        delete d->m_widget;
    QSizePolicy sp = widget->sizePolicy();
    sp.setHorizontalPolicy(QSizePolicy::Ignored);
    widget->setSizePolicy(sp);
    d->m_widget = widget;
    if (d->m_widget)
        d->m_widgetLayout->addWidget(d->m_widget);
}

/*!
    \fn void FutureProgress::setTitle(const QString &title)
    Changes the \a title of the progress indicator.
*/
void FutureProgress::setTitle(const QString &title)
{
    d->m_progress->setTitle(title);
}

/*!
    \fn QString FutureProgress::title() const
    Returns the title of the progress indicator.
*/
QString FutureProgress::title() const
{
    return d->m_progress->title();
}

void FutureProgress::cancel()
{
    d->m_watcher.future().cancel();
}

void FutureProgress::updateToolTip(const QString &text)
{
    setToolTip("" + title() + "
" + text);
}

void FutureProgress::setStarted()
{
    d->m_progress->reset();
    d->m_progress->setError(false);
    d->m_progress->setRange(d->m_watcher.progressMinimum(), d->m_watcher.progressMaximum());
    d->m_progress->setValue(d->m_watcher.progressValue());
}

bool FutureProgress::eventFilter(QObject *, QEvent *e)
{
    if (d->m_keep != KeepOnFinish && d->m_waitingForUserInteraction
        && (e->type() == QEvent::MouseMove || e->type() == QEvent::KeyPress)) {
        qApp->removeEventFilter(this);
        QTimer::singleShot(notificationTimeout, this, SLOT(fadeAway()));
    }
    return false;
}

void FutureProgress::setFinished()
{
    updateToolTip(d->m_watcher.future().progressText());

    d->m_progress->setFinished(true);

    if (d->m_watcher.future().isCanceled()) {
        d->m_progress->setError(true);
    } else {
        d->m_progress->setError(false);
    }
    emit finished();
    d->tryToFadeAway();
}

void FutureProgressPrivate::tryToFadeAway()
{
    if (m_isFading)
        return;
    if (m_keep == FutureProgress::KeepOnFinishTillUserInteraction
            || (m_keep == FutureProgress::DontKeepOnFinish && m_progress->hasError())) {
        m_waitingForUserInteraction = true;
        //eventfilter is needed to get user interaction
        //events to start QTimer::singleShot later
        qApp->installEventFilter(m_q);
        m_isFading = true;
    } else if (m_keep == FutureProgress::DontKeepOnFinish) {
        QTimer::singleShot(shortNotificationTimeout, m_q, SLOT(fadeAway()));
        m_isFading = true;
    }
}

void FutureProgress::setProgressRange(int min, int max)
{
    d->m_progress->setRange(min, max);
}

void FutureProgress::setProgressValue(int val)
{
    d->m_progress->setValue(val);
}

void FutureProgress::setProgressText(const QString &text)
{
    updateToolTip(text);
}

/*!
    \fn void FutureProgress::setFuture(const QFuture<void> &future)
    \internal
*/
void FutureProgress::setFuture(const QFuture<void> &future)
{
    d->m_watcher.setFuture(future);
}

/*!
    \fn QFuture<void> FutureProgress::future() const
    Returns a QFuture object that represents this running task.
*/
QFuture<void> FutureProgress::future() const
{
    return d->m_watcher.future();
}

/*!
    \fn void FutureProgress::mousePressEvent(QMouseEvent *event)
    \internal
*/
void FutureProgress::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
        emit clicked();
    QWidget::mousePressEvent(event);
}

void FutureProgress::resizeEvent(QResizeEvent *)
{
    d->m_faderWidget->setGeometry(rect());
}

/*!
    \fn bool FutureProgress::hasError() const
    Returns the error state of this progress indicator.
*/
bool FutureProgress::hasError() const
{
    return d->m_progress->hasError();
}

void FutureProgress::fadeAway()
{
    d->m_faderWidget->raise();
    QSequentialAnimationGroup *group = new QSequentialAnimationGroup(this);
    QPropertyAnimation *animation = new QPropertyAnimation(d->m_faderWidget, "opacity");
    animation->setDuration(600);
    animation->setEndValue(1.0);
    group->addAnimation(animation);
    animation = new QPropertyAnimation(this, "maximumHeight");
    animation->setDuration(120);
    animation->setEasingCurve(QEasingCurve::InCurve);
    animation->setStartValue(sizeHint().height());
    animation->setEndValue(0.0);
    group->addAnimation(animation);
    group->start(QAbstractAnimation::DeleteWhenStopped);

    connect(group, SIGNAL(finished()), this, SIGNAL(removeMe()));
}

void FutureProgress::setType(const QString &type)
{
    d->m_type = type;
}

QString FutureProgress::type() const
{
    return d->m_type;
}

void FutureProgress::setKeepOnFinish(KeepOnFinishType keepType)
{
    if (d->m_keep == keepType) {
        return;
    }
    d->m_keep = keepType;

    //if it is not finished tryToFadeAway is called by setFinished at the end
    if (d->m_watcher.isFinished()) {
        d->tryToFadeAway();
    }
}

bool FutureProgress::keepOnFinish() const
{
    return d->m_keep;
}

QWidget *FutureProgress::widget() const
{
    return d->m_widget;
}

} // namespace Core

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


<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_support/cc/port/default/tflite_wrapper.h"

#include "absl/status/status.h"
#include "absl/strings/str_format.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/delegates/interpreter_utils.h"
#include "tensorflow/lite/experimental/acceleration/configuration/proto_to_flatbuffer.h"
#include "tensorflow_lite_support/cc/port/status_macros.h"

namespace tflite {
namespace support {

namespace {
using tflite::delegates::DelegatePluginRegistry;
using tflite::delegates::InterpreterUtils;
using tflite::proto::ComputeSettings;
using tflite::proto::Delegate;

// The constant names for initializing delegates from the `DelegateRegistry`.
constexpr char kGpuPluginName[] = "GpuPlugin";
constexpr char kHexagonPluginName[] = "HexagonPlugin";
constexpr char kNnApiPluginName[] = "NnapiPlugin";
}  // namespace

/* static */
absl::Status TfLiteInterpreterWrapper::SanityCheckComputeSettings(
    const ComputeSettings& compute_settings) {
  Delegate delegate = compute_settings.tflite_settings().delegate();
  if (delegate != Delegate::NONE && delegate != Delegate::GPU &&
      delegate != Delegate::HEXAGON && delegate != Delegate::NNAPI) {
    return absl::UnimplementedError(absl::StrFormat(
        "Using delegate '%s' is not supported.", Delegate_Name(delegate)));
  }
  return absl::OkStatus();
}

TfLiteInterpreterWrapper::TfLiteInterpreterWrapper()
    : delegate_(nullptr, nullptr), got_error_do_not_delegate_anymore_(false) {}

absl::Status TfLiteInterpreterWrapper::InitializeWithFallback(
    std::function<absl::Status(std::unique_ptr<tflite::Interpreter>*)>
        interpreter_initializer,
    const ComputeSettings& compute_settings) {
  return InitializeWithFallback(
      [interpreter_initializer](
          const InterpreterCreationResources& /*resources*/,
          std::unique_ptr<tflite::Interpreter>* interpreter_out)
          -> absl::Status { return interpreter_initializer(interpreter_out); },
      compute_settings);
}

absl::Status TfLiteInterpreterWrapper::InitializeWithFallback(
    std::function<absl::Status(const InterpreterCreationResources&,
                               std::unique_ptr<tflite::Interpreter>*)>
        interpreter_initializer,
    const ComputeSettings& compute_settings) {
  // Store interpreter initializer if not already here.
  if (interpreter_initializer_) {
    return absl::FailedPreconditionError(
        "InitializeWithFallback already called.");
  }
  interpreter_initializer_ = std::move(interpreter_initializer);

  // Sanity check and copy ComputeSettings.
  RETURN_IF_ERROR(SanityCheckComputeSettings(compute_settings));
  compute_settings_ = compute_settings;

  // Initialize fallback behavior.
  fallback_on_compilation_error_ =
      compute_settings_.tflite_settings()
          .fallback_settings()
          .allow_automatic_fallback_on_compilation_error() ||
      // Deprecated, keep supporting for backward compatibility.
      compute_settings_.tflite_settings()
          .nnapi_settings()
          .fallback_settings()
          .allow_automatic_fallback_on_compilation_error();
  fallback_on_execution_error_ =
      compute_settings_.tflite_settings()
          .fallback_settings()
          .allow_automatic_fallback_on_execution_error() ||
      // Deprecated, keep supporting for backward compatibility.
      compute_settings_.tflite_settings()
          .nnapi_settings()
          .fallback_settings()
          .allow_automatic_fallback_on_execution_error();

  return InitializeWithFallbackAndResize();
}

absl::Status TfLiteInterpreterWrapper::AllocateTensors() {
  if (interpreter_->AllocateTensors() != kTfLiteOk) {
    return absl::InternalError("AllocateTensors() failed.");
  }
  return absl::OkStatus();
}

// TODO(b/173406463): the `resize` parameter is going to be used by
// ResizeAndAllocateTensors functions, coming soon.
absl::Status TfLiteInterpreterWrapper::InitializeWithFallbackAndResize(
    std::function<absl::Status(Interpreter* interpreter)> resize) {
  RETURN_IF_ERROR(
      interpreter_initializer_(InterpreterCreationResources(), &interpreter_));
  RETURN_IF_ERROR(resize(interpreter_.get()));
  SetTfLiteCancellation();

  if (got_error_do_not_delegate_anymore_ ||
      compute_settings_.tflite_settings().delegate() == Delegate::NONE) {
    // Just allocate tensors and return.
    delegate_.reset(nullptr);
    return AllocateTensors();
  }

  // Initialize delegate and modify graph.
  RETURN_IF_ERROR(InitializeDelegate());
  if (interpreter_->ModifyGraphWithDelegate(delegate_.get()) != kTfLiteOk) {
    // If a compilation error occurs, stop delegation from happening in the
    // future.
    got_error_do_not_delegate_anymore_ = true;
    delegate_.reset(nullptr);
    if (!fallback_on_compilation_error_) {
      // If instructed not to fallback, return error.
      return absl::InternalError(absl::StrFormat(
          "ModifyGraphWithDelegate() failed for delegate '%s'.",
          Delegate_Name(compute_settings_.tflite_settings().delegate())));
    }
  }

  // The call to ModifyGraphWithDelegate() leaves the interpreter in a usable
  // state in case of failure: calling AllocateTensors() will silently fallback
  // on CPU in such a situation.
  return AllocateTensors();
}

absl::Status TfLiteInterpreterWrapper::InitializeDelegate() {
  if (delegate_ != nullptr) {
    // Nothing to do.
    return absl::OkStatus();
  }

  // Delegates are initialized from the FlatBuffer counterpart of the
  // `ComputeSettings` proto.
  const tflite::ComputeSettings* compute_settings =
      tflite::ConvertFromProto(compute_settings_, &flatbuffers_builder_);
  switch (compute_settings_.tflite_settings().delegate()) {
    case Delegate::NNAPI:
      delegate_plugin_ = DelegatePluginRegistry::CreateByName(
          kNnApiPluginName, *compute_settings->tflite_settings());
      if (!delegate_plugin_) {
        return absl::NotFoundError(
            "Unable to find NNAPI delegate plugin. Have you linked in the "
            "`nnapi_plugin` target?");
      }
      delegate_ = delegate_plugin_->Create();
      break;
    case Delegate::GPU:
      delegate_plugin_ = DelegatePluginRegistry::CreateByName(
          kGpuPluginName, *compute_settings->tflite_settings());
      if (!delegate_plugin_) {
        return absl::NotFoundError(
            "Unable to find GPU delegate plugin. Have you linked in the "
            "`gpu_plugin` target?");
      }
      delegate_ = delegate_plugin_->Create();
      break;
    case Delegate::HEXAGON:
      delegate_plugin_ = DelegatePluginRegistry::CreateByName(
          kHexagonPluginName, *compute_settings->tflite_settings());
      if (!delegate_plugin_) {
        return absl::NotFoundError(
            "Unable to find HEXAGON delegate plugin. Have you linked in the "
            "`hexagon_plugin` target?");
      }
      delegate_ = delegate_plugin_->Create();
      break;
    default:
      // Nothing to do: this should be caught by sanity checks beforehand, and
      // will anyway cause the code below to throw an InternalError.
      break;
  }

  if (!delegate_) {
    return absl::InternalError(absl::StrFormat(
        "Unable to create '%s' delegate.",
        Delegate_Name(compute_settings_.tflite_settings().delegate())));
  }
  return absl::OkStatus();
}

absl::Status TfLiteInterpreterWrapper::InvokeWithFallback(
    const std::function<absl::Status(tflite::Interpreter* interpreter)>&
        set_inputs) {
  RETURN_IF_ERROR(set_inputs(interpreter_.get()));
  // Reset cancel flag before calling `Invoke()`.
  cancel_flag_.Set(false);
  TfLiteStatus status = kTfLiteError;
  if (fallback_on_execution_error_) {
    status = InterpreterUtils::InvokeWithCPUFallback(interpreter_.get());
  } else {
    status = interpreter_->Invoke();
  }
  if (status == kTfLiteOk) {
    return absl::OkStatus();
  }
  // Assume InvokeWithoutFallback() is guarded under caller's synchronization.
  // Assume the inference is cancelled successfully if Invoke() returns
  // kTfLiteError and the cancel flag is `true`.
  if (status == kTfLiteError && cancel_flag_.Get()) {
    return absl::CancelledError("Invoke() cancelled.");
  }
  if (delegate_) {
    // Mark that an error occurred so that later invocations immediately
    // fallback to CPU.
    got_error_do_not_delegate_anymore_ = true;
    // InvokeWithCPUFallback returns `kTfLiteDelegateError` in case of
    // *successful* fallback: convert it to an OK status.
    if (status == kTfLiteDelegateError) {
      return absl::OkStatus();
    }
  }
  return absl::InternalError("Invoke() failed.");
}

absl::Status TfLiteInterpreterWrapper::InvokeWithoutFallback() {
  // Reset cancel flag before calling `Invoke()`.
  cancel_flag_.Set(false);
  TfLiteStatus status = interpreter_->Invoke();
  if (status != kTfLiteOk) {
    // Assume InvokeWithoutFallback() is guarded under caller's synchronization.
    // Assume the inference is cancelled successfully if Invoke() returns
    // kTfLiteError and the cancel flag is `true`.
    if (status == kTfLiteError && cancel_flag_.Get()) {
      return absl::CancelledError("Invoke() cancelled.");
    }
    return absl::InternalError("Invoke() failed.");
  }
  return absl::OkStatus();
}

void TfLiteInterpreterWrapper::Cancel() { cancel_flag_.Set(true); }

void TfLiteInterpreterWrapper::SetTfLiteCancellation() {
  // Create a cancellation check function and set to the TFLite interpreter.
  auto check_cancel_flag = [](void* data) {
    auto* cancel_flag = reinterpret_cast<CancelFlag*>(data);
    return cancel_flag->Get();
  };
  interpreter_->SetCancellationFunction(reinterpret_cast<void*>(&cancel_flag_),
                                        check_cancel_flag);
}

}  // namespace support
}  // namespace tflite
<commit_msg>Add XNNPack delegate plugin for acceleration configuration.<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_support/cc/port/default/tflite_wrapper.h"

#include "absl/status/status.h"
#include "absl/strings/str_format.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/delegates/interpreter_utils.h"
#include "tensorflow/lite/experimental/acceleration/configuration/proto_to_flatbuffer.h"
#include "tensorflow_lite_support/cc/port/status_macros.h"

namespace tflite {
namespace support {

namespace {
using tflite::delegates::DelegatePluginRegistry;
using tflite::delegates::InterpreterUtils;
using tflite::proto::ComputeSettings;
using tflite::proto::Delegate;

// The constant names for initializing delegates from the `DelegateRegistry`.
constexpr char kGpuPluginName[] = "GpuPlugin";
constexpr char kHexagonPluginName[] = "HexagonPlugin";
constexpr char kNnApiPluginName[] = "NnapiPlugin";
constexpr char kXnnPackPluginName[] = "XNNPackPlugin";
}  // namespace

/* static */
absl::Status TfLiteInterpreterWrapper::SanityCheckComputeSettings(
    const ComputeSettings& compute_settings) {
  Delegate delegate = compute_settings.tflite_settings().delegate();
  if (delegate != Delegate::NONE && delegate != Delegate::GPU &&
      delegate != Delegate::HEXAGON && delegate != Delegate::NNAPI &&
      delegate != Delegate::XNNPACK) {
    return absl::UnimplementedError(absl::StrFormat(
        "Using delegate '%s' is not supported.", Delegate_Name(delegate)));
  }
  return absl::OkStatus();
}

TfLiteInterpreterWrapper::TfLiteInterpreterWrapper()
    : delegate_(nullptr, nullptr), got_error_do_not_delegate_anymore_(false) {}

absl::Status TfLiteInterpreterWrapper::InitializeWithFallback(
    std::function<absl::Status(std::unique_ptr<tflite::Interpreter>*)>
        interpreter_initializer,
    const ComputeSettings& compute_settings) {
  return InitializeWithFallback(
      [interpreter_initializer](
          const InterpreterCreationResources& /*resources*/,
          std::unique_ptr<tflite::Interpreter>* interpreter_out)
          -> absl::Status { return interpreter_initializer(interpreter_out); },
      compute_settings);
}

absl::Status TfLiteInterpreterWrapper::InitializeWithFallback(
    std::function<absl::Status(const InterpreterCreationResources&,
                               std::unique_ptr<tflite::Interpreter>*)>
        interpreter_initializer,
    const ComputeSettings& compute_settings) {
  // Store interpreter initializer if not already here.
  if (interpreter_initializer_) {
    return absl::FailedPreconditionError(
        "InitializeWithFallback already called.");
  }
  interpreter_initializer_ = std::move(interpreter_initializer);

  // Sanity check and copy ComputeSettings.
  RETURN_IF_ERROR(SanityCheckComputeSettings(compute_settings));
  compute_settings_ = compute_settings;

  // Initialize fallback behavior.
  fallback_on_compilation_error_ =
      compute_settings_.tflite_settings()
          .fallback_settings()
          .allow_automatic_fallback_on_compilation_error() ||
      // Deprecated, keep supporting for backward compatibility.
      compute_settings_.tflite_settings()
          .nnapi_settings()
          .fallback_settings()
          .allow_automatic_fallback_on_compilation_error();
  fallback_on_execution_error_ =
      compute_settings_.tflite_settings()
          .fallback_settings()
          .allow_automatic_fallback_on_execution_error() ||
      // Deprecated, keep supporting for backward compatibility.
      compute_settings_.tflite_settings()
          .nnapi_settings()
          .fallback_settings()
          .allow_automatic_fallback_on_execution_error();

  return InitializeWithFallbackAndResize();
}

absl::Status TfLiteInterpreterWrapper::AllocateTensors() {
  if (interpreter_->AllocateTensors() != kTfLiteOk) {
    return absl::InternalError("AllocateTensors() failed.");
  }
  return absl::OkStatus();
}

// TODO(b/173406463): the `resize` parameter is going to be used by
// ResizeAndAllocateTensors functions, coming soon.
absl::Status TfLiteInterpreterWrapper::InitializeWithFallbackAndResize(
    std::function<absl::Status(Interpreter* interpreter)> resize) {
  RETURN_IF_ERROR(
      interpreter_initializer_(InterpreterCreationResources(), &interpreter_));
  RETURN_IF_ERROR(resize(interpreter_.get()));
  SetTfLiteCancellation();

  if (got_error_do_not_delegate_anymore_ ||
      compute_settings_.tflite_settings().delegate() == Delegate::NONE) {
    // Just allocate tensors and return.
    delegate_.reset(nullptr);
    return AllocateTensors();
  }

  // Initialize delegate and modify graph.
  RETURN_IF_ERROR(InitializeDelegate());
  if (interpreter_->ModifyGraphWithDelegate(delegate_.get()) != kTfLiteOk) {
    // If a compilation error occurs, stop delegation from happening in the
    // future.
    got_error_do_not_delegate_anymore_ = true;
    delegate_.reset(nullptr);
    if (!fallback_on_compilation_error_) {
      // If instructed not to fallback, return error.
      return absl::InternalError(absl::StrFormat(
          "ModifyGraphWithDelegate() failed for delegate '%s'.",
          Delegate_Name(compute_settings_.tflite_settings().delegate())));
    }
  }

  // The call to ModifyGraphWithDelegate() leaves the interpreter in a usable
  // state in case of failure: calling AllocateTensors() will silently fallback
  // on CPU in such a situation.
  return AllocateTensors();
}

absl::Status TfLiteInterpreterWrapper::InitializeDelegate() {
  if (delegate_ != nullptr) {
    // Nothing to do.
    return absl::OkStatus();
  }

  // Delegates are initialized from the FlatBuffer counterpart of the
  // `ComputeSettings` proto.
  const tflite::ComputeSettings* compute_settings =
      tflite::ConvertFromProto(compute_settings_, &flatbuffers_builder_);
  switch (compute_settings_.tflite_settings().delegate()) {
    case Delegate::NNAPI:
      delegate_plugin_ = DelegatePluginRegistry::CreateByName(
          kNnApiPluginName, *compute_settings->tflite_settings());
      if (!delegate_plugin_) {
        return absl::NotFoundError(
            "Unable to find NNAPI delegate plugin. Have you linked in the "
            "`nnapi_plugin` target?");
      }
      delegate_ = delegate_plugin_->Create();
      break;
    case Delegate::GPU:
      delegate_plugin_ = DelegatePluginRegistry::CreateByName(
          kGpuPluginName, *compute_settings->tflite_settings());
      if (!delegate_plugin_) {
        return absl::NotFoundError(
            "Unable to find GPU delegate plugin. Have you linked in the "
            "`gpu_plugin` target?");
      }
      delegate_ = delegate_plugin_->Create();
      break;
    case Delegate::HEXAGON:
      delegate_plugin_ = DelegatePluginRegistry::CreateByName(
          kHexagonPluginName, *compute_settings->tflite_settings());
      if (!delegate_plugin_) {
        return absl::NotFoundError(
            "Unable to find HEXAGON delegate plugin. Have you linked in the "
            "`hexagon_plugin` target?");
      }
      delegate_ = delegate_plugin_->Create();
      break;
    case Delegate::XNNPACK:
      delegate_plugin_ = DelegatePluginRegistry::CreateByName(
          kXnnPackPluginName, *compute_settings->tflite_settings());
      if (!delegate_plugin_) {
        return absl::NotFoundError(
            "Unable to find XNNPACK delegate plugin. Have you linked in the "
            "`xnnpack_plugin` target?");
      }
      delegate_ = delegate_plugin_->Create();
      break;
    default:
      // Nothing to do: this should be caught by sanity checks beforehand, and
      // will anyway cause the code below to throw an InternalError.
      break;
  }

  if (!delegate_) {
    return absl::InternalError(absl::StrFormat(
        "Unable to create '%s' delegate.",
        Delegate_Name(compute_settings_.tflite_settings().delegate())));
  }
  return absl::OkStatus();
}

absl::Status TfLiteInterpreterWrapper::InvokeWithFallback(
    const std::function<absl::Status(tflite::Interpreter* interpreter)>&
        set_inputs) {
  RETURN_IF_ERROR(set_inputs(interpreter_.get()));
  // Reset cancel flag before calling `Invoke()`.
  cancel_flag_.Set(false);
  TfLiteStatus status = kTfLiteError;
  if (fallback_on_execution_error_) {
    status = InterpreterUtils::InvokeWithCPUFallback(interpreter_.get());
  } else {
    status = interpreter_->Invoke();
  }
  if (status == kTfLiteOk) {
    return absl::OkStatus();
  }
  // Assume InvokeWithoutFallback() is guarded under caller's synchronization.
  // Assume the inference is cancelled successfully if Invoke() returns
  // kTfLiteError and the cancel flag is `true`.
  if (status == kTfLiteError && cancel_flag_.Get()) {
    return absl::CancelledError("Invoke() cancelled.");
  }
  if (delegate_) {
    // Mark that an error occurred so that later invocations immediately
    // fallback to CPU.
    got_error_do_not_delegate_anymore_ = true;
    // InvokeWithCPUFallback returns `kTfLiteDelegateError` in case of
    // *successful* fallback: convert it to an OK status.
    if (status == kTfLiteDelegateError) {
      return absl::OkStatus();
    }
  }
  return absl::InternalError("Invoke() failed.");
}

absl::Status TfLiteInterpreterWrapper::InvokeWithoutFallback() {
  // Reset cancel flag before calling `Invoke()`.
  cancel_flag_.Set(false);
  TfLiteStatus status = interpreter_->Invoke();
  if (status != kTfLiteOk) {
    // Assume InvokeWithoutFallback() is guarded under caller's synchronization.
    // Assume the inference is cancelled successfully if Invoke() returns
    // kTfLiteError and the cancel flag is `true`.
    if (status == kTfLiteError && cancel_flag_.Get()) {
      return absl::CancelledError("Invoke() cancelled.");
    }
    return absl::InternalError("Invoke() failed.");
  }
  return absl::OkStatus();
}

void TfLiteInterpreterWrapper::Cancel() { cancel_flag_.Set(true); }

void TfLiteInterpreterWrapper::SetTfLiteCancellation() {
  // Create a cancellation check function and set to the TFLite interpreter.
  auto check_cancel_flag = [](void* data) {
    auto* cancel_flag = reinterpret_cast<CancelFlag*>(data);
    return cancel_flag->Get();
  };
  interpreter_->SetCancellationFunction(reinterpret_cast<void*>(&cancel_flag_),
                                        check_cancel_flag);
}

}  // namespace support
}  // namespace tflite
<|endoftext|>


<commit_before>#include "rpc/utils.h"

using namespace rpc;
using namespace std;

class ShortLockCounter: public NoCopy {
    i64 next_;
    ShortLock l_;
public:
    ShortLockCounter(i64 start = 0) : next_(start) { }
    i64 peek_next() {
        l_.lock();
        i64 r = next_;
        l_.unlock();
        return r;
    }
    i64 next(i64 step = 1) {
        l_.lock();
        i64 r = next_++;
        l_.unlock();
        return r;
    }
    void reset(i64 start = 0) {
        l_.lock();
        next_ = start;
        l_.unlock();
    }
};

class LongLockCounter: public NoCopy {
    i64 next_;
    LongLock l_;
public:
    LongLockCounter(i64 start = 0) : next_(start) { }
    i64 peek_next() {
        l_.lock();
        i64 r = next_;
        l_.unlock();
        return r;
    }
    i64 next(i64 step = 1) {
        l_.lock();
        i64 r = next_++;
        l_.unlock();
        return r;
    }
    void reset(i64 start = 0) {
        l_.lock();
        next_ = start;
        l_.unlock();
    }
};

static void* worker_thread(void* f) {
    function<void()>* func = (function<void()> *) f;
    (*func)();
    pthread_exit(nullptr);
    return nullptr;
}

int main(int argc, char* argv[]) {
    Log::info("This shall be done!");
    Timer tm;
    volatile int j = 0;
    int n = 1000 * 1000;
    int t = 64;
    tm.start();
    for (volatile int i = 0; i < n; i++) {
        j++;
    }
    tm.end();
    double base = n / tm.elapsed();
    Log::info("i++ 1 thread: %.2lf/s", base);
    Counter ctr;
    tm.reset();
    tm.start();
    for (int i = 0; i < n; i++) {
        ctr.next();
    }
    tm.end();
    Log::info("Counter 1 thread: %.2lf/s (%.4lf)", n / tm.elapsed(), n / tm.elapsed() / base);
    ShortLockCounter s_ctr;
    tm.reset();
    tm.start();
    for (int i = 0; i < n; i++) {
        s_ctr.next();
    }
    tm.end();
    Log::info("ShortLockCounter 1 thread: %.2lf/s (%.4lf)", n / tm.elapsed(), n / tm.elapsed() / base);
    LongLockCounter l_ctr;
    tm.reset();
    tm.start();
    for (int i = 0; i < n; i++) {
        l_ctr.next();
    }
    tm.end();
    Log::info("LongLockCounter 1 thread: %.2lf/s (%.4lf)", n / tm.elapsed(), n / tm.elapsed() / base);
    pthread_t* th = new pthread_t[t];
    function<void()> worker1 = [&ctr, n] {
        while (ctr.next() < 2 * n)
            ;
    };
    tm.reset();
    tm.start();
    for (int i = 0; i < t; i++) {
        Pthread_create(&th[i], nullptr, worker_thread, &worker1);
    }
    for (int i = 0; i < t; i++) {
        Pthread_join(th[i], nullptr);
    }
    tm.end();
    Log::info("Counter %d thread: %.2lf/s (%.4lf)", t, n / tm.elapsed(), n / tm.elapsed() / base);
    function<void()> worker2 = [&s_ctr, n] {
        while (s_ctr.next() < 2 * n)
            ;
    };
    tm.reset();
    tm.start();
    for (int i = 0; i < t; i++) {
        Pthread_create(&th[i], nullptr, worker_thread, &worker2);
    }
    for (int i = 0; i < t; i++) {
        Pthread_join(th[i], nullptr);
    }
    tm.end();
    Log::info("ShortLockCounter %d thread: %.2lf/s (%.4lf)", t, n / tm.elapsed(), n / tm.elapsed() / base);
    function<void()> worker3 = [&l_ctr, n] {
        while (l_ctr.next() < 2 * n)
            ;
    };
    tm.reset();
    tm.start();
    for (int i = 0; i < t; i++) {
        Pthread_create(&th[i], nullptr, worker_thread, &worker3);
    }
    for (int i = 0; i < t; i++) {
        Pthread_join(th[i], nullptr);
    }
    tm.end();
    Log::info("LongLockCounter %d thread: %.2lf/s (%.4lf)", t, n / tm.elapsed(), n / tm.elapsed() / base);
    delete[] th;
    return 0;
}
<commit_msg>add AtomicCounter into counter_bench<commit_after>#include <atomic>

#include "rpc/utils.h"

using namespace rpc;
using namespace std;

class ShortLockCounter: public NoCopy {
    i64 next_;
    ShortLock l_;
public:
    ShortLockCounter(i64 start = 0) : next_(start) { }
    i64 peek_next() {
        l_.lock();
        i64 r = next_;
        l_.unlock();
        return r;
    }
    i64 next(i64 step = 1) {
        l_.lock();
        i64 r = next_;
        next_ += step;
        l_.unlock();
        return r;
    }
    void reset(i64 start = 0) {
        l_.lock();
        next_ = start;
        l_.unlock();
    }
};

class LongLockCounter: public NoCopy {
    i64 next_;
    LongLock l_;
public:
    LongLockCounter(i64 start = 0) : next_(start) { }
    i64 peek_next() {
        l_.lock();
        i64 r = next_;
        l_.unlock();
        return r;
    }
    i64 next(i64 step = 1) {
        l_.lock();
        i64 r = next_;
        next_ += step;
        l_.unlock();
        return r;
    }
    void reset(i64 start = 0) {
        l_.lock();
        next_ = start;
        l_.unlock();
    }
};

class AtomicCounter {
    atomic<i64> n_;
public:
    AtomicCounter(i64 start = 0): n_(start) {}
    i64 peek_next() const {
        return n_;
    }
    i64 next(i64 step = 1) {
        n_ += step;
        return n_;
    }
    void reset(i64 start = 0) {
        n_ = start;
    }
};

static void* worker_thread(void* f) {
    function<void()>* func = (function<void()> *) f;
    (*func)();
    pthread_exit(nullptr);
    return nullptr;
}

int main(int argc, char* argv[]) {
    Log::info("This shall be done!");
    Timer tm;
    volatile int j = 0;
    int n = 1000 * 1000;
    int t = 64;
    tm.start();
    for (volatile int i = 0; i < n; i++) {
        j++;
    }
    tm.end();
    double base = n / tm.elapsed();
    Log::info("i++ 1 thread: %.2lf/s", base);
    Counter ctr;
    tm.reset();
    tm.start();
    for (int i = 0; i < n; i++) {
        ctr.next();
    }
    tm.end();
    Log::info("Counter 1 thread: %.2lf/s (%.4lf)", n / tm.elapsed(), n / tm.elapsed() / base);
    ShortLockCounter s_ctr;
    tm.reset();
    tm.start();
    for (int i = 0; i < n; i++) {
        s_ctr.next();
    }
    tm.end();
    Log::info("ShortLockCounter 1 thread: %.2lf/s (%.4lf)", n / tm.elapsed(), n / tm.elapsed() / base);
    LongLockCounter l_ctr;
    tm.reset();
    tm.start();
    for (int i = 0; i < n; i++) {
        l_ctr.next();
    }
    tm.end();
    Log::info("LongLockCounter 1 thread: %.2lf/s (%.4lf)", n / tm.elapsed(), n / tm.elapsed() / base);
    AtomicCounter a_ctr;
    tm.reset();
    tm.start();
    for (int i = 0; i < n; i++) {
        a_ctr.next();
    }
    tm.end();
    Log::info("AtomicCounter 1 thread: %.2lf/s (%.4lf)", n / tm.elapsed(), n / tm.elapsed() / base);
    pthread_t* th = new pthread_t[t];
    function<void()> worker1 = [&ctr, n] {
        while (ctr.next() < 2 * n)
            ;
    };
    tm.reset();
    tm.start();
    for (int i = 0; i < t; i++) {
        Pthread_create(&th[i], nullptr, worker_thread, &worker1);
    }
    for (int i = 0; i < t; i++) {
        Pthread_join(th[i], nullptr);
    }
    tm.end();
    Log::info("Counter %d thread: %.2lf/s (%.4lf)", t, n / tm.elapsed(), n / tm.elapsed() / base);
    function<void()> worker2 = [&s_ctr, n] {
        while (s_ctr.next() < 2 * n)
            ;
    };
    tm.reset();
    tm.start();
    for (int i = 0; i < t; i++) {
        Pthread_create(&th[i], nullptr, worker_thread, &worker2);
    }
    for (int i = 0; i < t; i++) {
        Pthread_join(th[i], nullptr);
    }
    tm.end();
    Log::info("ShortLockCounter %d thread: %.2lf/s (%.4lf)", t, n / tm.elapsed(), n / tm.elapsed() / base);
    function<void()> worker3 = [&l_ctr, n] {
        while (l_ctr.next() < 2 * n)
            ;
    };
    tm.reset();
    tm.start();
    for (int i = 0; i < t; i++) {
        Pthread_create(&th[i], nullptr, worker_thread, &worker3);
    }
    for (int i = 0; i < t; i++) {
        Pthread_join(th[i], nullptr);
    }
    tm.end();
    Log::info("LongLockCounter %d thread: %.2lf/s (%.4lf)", t, n / tm.elapsed(), n / tm.elapsed() / base);
    function<void()> worker4 = [&a_ctr, n] {
        while (a_ctr.next() < 2 * n)
            ;
    };
    tm.reset();
    tm.start();
    for (int i = 0; i < t; i++) {
        Pthread_create(&th[i], nullptr, worker_thread, &worker4);
    }
    for (int i = 0; i < t; i++) {
        Pthread_join(th[i], nullptr);
    }
    tm.end();
    Log::info("AtomicCounter %d thread: %.2lf/s (%.4lf)", t, n / tm.elapsed(), n / tm.elapsed() / base);
    delete[] th;
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 */
#include <cstdint>
#include <cstring>
#include <ctime>

#include <chrono>
#include <iostream>
#include <stdexcept>
#include <thread>

#include <adios2.h>

#include <gtest/gtest.h>

#include "TestData.h"

#include "ParseArgs.h"
int StartStep = 0;
int EndStep = 4 * 4 * 4 * 4 * 4; // all 4 possibilities for all 5 variables
int SmallSize = 100;

// ADIOS2  write
TEST(CommonWriteTest, ADIOS2CommonWrite)
{
    adios2::ADIOS adios;

    adios2::IO io = adios.DeclareIO("TestIO");

    adios2::Dims big_shape{static_cast<unsigned int>(DataSize)};
    adios2::Dims big_start{static_cast<unsigned int>(0)};
    adios2::Dims big_count{static_cast<unsigned int>(DataSize)};

    adios2::Dims small_shape{static_cast<unsigned int>(SmallSize)};
    adios2::Dims small_start{static_cast<unsigned int>(0)};
    adios2::Dims small_count{static_cast<unsigned int>(SmallSize)};

    std::vector<adios2::Variable<double>> vars(5);
    vars[0] =
        io.DefineVariable<double>("big1", big_shape, big_start, big_count);
    vars[1] = io.DefineVariable<double>("small1", small_shape, small_start,
                                        small_count);
    vars[2] =
        io.DefineVariable<double>("big2", big_shape, big_start, big_count);
    vars[3] = io.DefineVariable<double>("small2", small_shape, small_start,
                                        small_count);
    vars[4] =
        io.DefineVariable<double>("big3", big_shape, big_start, big_count);

    std::vector<std::vector<double>> data(5);
    for (int i = 0; i < 5; i++)
    {
        int size = DataSize;
        if ((i == 1) || (i == 3))
        {
            size = SmallSize;
        }
        data[i] = std::vector<double>(size);
    }

    // Create the Engine
    io.SetEngine(engine);
    io.SetParameters(engineParams);

    adios2::Engine engine = io.Open(fname, adios2::Mode::Write);

    /*
     *   write possibilities:
     *		Don't write
     *          Sync   - always destroy data afterwards
     *		Deferred
     *		Deferred with immediate PerformPuts() or PerformDataWrite() -  Destroy
     *all prior data
     *
     */
    for (int step = StartStep; step < EndStep; ++step)
    {
        int mask = step;
        engine.BeginStep();

        std::cout << "Begin Write Step " << step << " writing vars : ";
        for (int j = 0; j < 5; j++)
        {
            std::fill(data[j].begin(), data[j].end(), (double)j + 1.0);
        }
        for (int j = 0; j < 5; j++)
        {
            adios2::Mode write_mode;
            char c;
            int this_var_mask = (mask & 0x3);
            mask >>= 2;
            switch (this_var_mask)
            {
            case 0:
                continue;
            case 1:
                write_mode = adios2::Mode::Sync;
                c = 's';
                break;
            case 2:
            case 3:
                write_mode = adios2::Mode::Deferred;
                c = 'd';
                break;
            }
            std::cout << j << c << " ";
            engine.Put(vars[j], data[j].data(), write_mode);
            if (this_var_mask == 1)
            {
                std::fill(data[j].begin(), data[j].end(), -100.0);
            }
            else if (this_var_mask == 3)
            {
                if (Flush)
                {
                    std::cout << "PDW ";
                    engine.PerformDataWrite();
                }
                else
                {
                    std::cout << "P ";
                    engine.PerformPuts();
                }
                for (int k = 0; k <= j; k++)
                    std::fill(data[k].begin(), data[k].end(), -100.0);
            }
        }
        std::cout << std::endl;
        engine.EndStep();
    }

    // Close the file
    engine.Close();
}

// ADIOS2  write
TEST(CommonWriteTest, ADIOS2CommonRead)
{
    adios2::ADIOS adios;

    adios2::IO io = adios.DeclareIO("TestIO");

    std::vector<std::vector<double>> data(5);
    for (int i = 0; i < 5; i++)
    {
        int size = DataSize;
        if ((i == 1) || (i == 3))
        {
            size = SmallSize;
        }
        data[i] = (std::vector<double>(size));
    }

    // Create the Engine
    io.SetEngine(engine);
    io.SetParameters(engineParams);

    adios2::Engine engine = io.Open(fname, adios2::Mode::Read);
    EXPECT_TRUE(engine);

    /*
     *   write possibilities:
     *		Don't write
     *          Sync   - always destroy data afterwards
     *		Deferred
     *		Deferred with immediate PerformPuts()  -  Destroy all prior data
     *
     */
    for (int step = StartStep; step < EndStep; ++step)
    {
        EXPECT_TRUE(engine.BeginStep() == adios2::StepStatus::OK);

        std::vector<adios2::Variable<double>> vars(5);
        vars[0] = io.InquireVariable<double>("big1");
        vars[1] = io.InquireVariable<double>("small1");
        vars[2] = io.InquireVariable<double>("big2");
        vars[3] = io.InquireVariable<double>("small2");
        vars[4] = io.InquireVariable<double>("big3");

        std::vector<bool> var_present(vars.size());
        for (size_t i = 0; i < data.size(); i++)
            std::fill(data[i].begin(), data[i].end(), -200.0);
        std::cout << "Variables Read in TS " << step << ": ";
        for (int j = 0; j < 5; j++)
        {
            var_present[j] = (bool)vars[j];
            if (vars[j])
            {
                std::cout << " " << j;
                engine.Get(vars[j], data[j].data());
            }
        }
        std::cout << std::endl;
        engine.EndStep();
        for (int j = 0; j < 5; j++)
        {
            if (var_present[j])
            {
                for (std::size_t index = 0; index < data[j].size(); ++index)
                {
                    EXPECT_EQ(data[j][index], j + 1.0)
                        << "Data isn't correct, for " << vars[j].Name() << "["
                        << index << "]";
                }
            }
        }
    }

    // Close the file
    engine.Close();
}

int main(int argc, char **argv)
{

    int result;
    ::testing::InitGoogleTest(&argc, argv);

    DelayMS = 0; // zero for common writer

    ParseArgs(argc, argv);

    result = RUN_ALL_TESTS();

    return result;
}
<commit_msg>clang-format<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 */
#include <cstdint>
#include <cstring>
#include <ctime>

#include <chrono>
#include <iostream>
#include <stdexcept>
#include <thread>

#include <adios2.h>

#include <gtest/gtest.h>

#include "TestData.h"

#include "ParseArgs.h"
int StartStep = 0;
int EndStep = 4 * 4 * 4 * 4 * 4; // all 4 possibilities for all 5 variables
int SmallSize = 100;

// ADIOS2  write
TEST(CommonWriteTest, ADIOS2CommonWrite)
{
    adios2::ADIOS adios;

    adios2::IO io = adios.DeclareIO("TestIO");

    adios2::Dims big_shape{static_cast<unsigned int>(DataSize)};
    adios2::Dims big_start{static_cast<unsigned int>(0)};
    adios2::Dims big_count{static_cast<unsigned int>(DataSize)};

    adios2::Dims small_shape{static_cast<unsigned int>(SmallSize)};
    adios2::Dims small_start{static_cast<unsigned int>(0)};
    adios2::Dims small_count{static_cast<unsigned int>(SmallSize)};

    std::vector<adios2::Variable<double>> vars(5);
    vars[0] =
        io.DefineVariable<double>("big1", big_shape, big_start, big_count);
    vars[1] = io.DefineVariable<double>("small1", small_shape, small_start,
                                        small_count);
    vars[2] =
        io.DefineVariable<double>("big2", big_shape, big_start, big_count);
    vars[3] = io.DefineVariable<double>("small2", small_shape, small_start,
                                        small_count);
    vars[4] =
        io.DefineVariable<double>("big3", big_shape, big_start, big_count);

    std::vector<std::vector<double>> data(5);
    for (int i = 0; i < 5; i++)
    {
        int size = DataSize;
        if ((i == 1) || (i == 3))
        {
            size = SmallSize;
        }
        data[i] = std::vector<double>(size);
    }

    // Create the Engine
    io.SetEngine(engine);
    io.SetParameters(engineParams);

    adios2::Engine engine = io.Open(fname, adios2::Mode::Write);

    /*
     *   write possibilities:
     *		Don't write
     *          Sync   - always destroy data afterwards
     *		Deferred
     *		Deferred with immediate PerformPuts() or PerformDataWrite() -
     *Destroy all prior data
     *
     */
    for (int step = StartStep; step < EndStep; ++step)
    {
        int mask = step;
        engine.BeginStep();

        std::cout << "Begin Write Step " << step << " writing vars : ";
        for (int j = 0; j < 5; j++)
        {
            std::fill(data[j].begin(), data[j].end(), (double)j + 1.0);
        }
        for (int j = 0; j < 5; j++)
        {
            adios2::Mode write_mode;
            char c;
            int this_var_mask = (mask & 0x3);
            mask >>= 2;
            switch (this_var_mask)
            {
            case 0:
                continue;
            case 1:
                write_mode = adios2::Mode::Sync;
                c = 's';
                break;
            case 2:
            case 3:
                write_mode = adios2::Mode::Deferred;
                c = 'd';
                break;
            }
            std::cout << j << c << " ";
            engine.Put(vars[j], data[j].data(), write_mode);
            if (this_var_mask == 1)
            {
                std::fill(data[j].begin(), data[j].end(), -100.0);
            }
            else if (this_var_mask == 3)
            {
                if (Flush)
                {
                    std::cout << "PDW ";
                    engine.PerformDataWrite();
                }
                else
                {
                    std::cout << "P ";
                    engine.PerformPuts();
                }
                for (int k = 0; k <= j; k++)
                    std::fill(data[k].begin(), data[k].end(), -100.0);
            }
        }
        std::cout << std::endl;
        engine.EndStep();
    }

    // Close the file
    engine.Close();
}

// ADIOS2  write
TEST(CommonWriteTest, ADIOS2CommonRead)
{
    adios2::ADIOS adios;

    adios2::IO io = adios.DeclareIO("TestIO");

    std::vector<std::vector<double>> data(5);
    for (int i = 0; i < 5; i++)
    {
        int size = DataSize;
        if ((i == 1) || (i == 3))
        {
            size = SmallSize;
        }
        data[i] = (std::vector<double>(size));
    }

    // Create the Engine
    io.SetEngine(engine);
    io.SetParameters(engineParams);

    adios2::Engine engine = io.Open(fname, adios2::Mode::Read);
    EXPECT_TRUE(engine);

    /*
     *   write possibilities:
     *		Don't write
     *          Sync   - always destroy data afterwards
     *		Deferred
     *		Deferred with immediate PerformPuts()  -  Destroy all prior data
     *
     */
    for (int step = StartStep; step < EndStep; ++step)
    {
        EXPECT_TRUE(engine.BeginStep() == adios2::StepStatus::OK);

        std::vector<adios2::Variable<double>> vars(5);
        vars[0] = io.InquireVariable<double>("big1");
        vars[1] = io.InquireVariable<double>("small1");
        vars[2] = io.InquireVariable<double>("big2");
        vars[3] = io.InquireVariable<double>("small2");
        vars[4] = io.InquireVariable<double>("big3");

        std::vector<bool> var_present(vars.size());
        for (size_t i = 0; i < data.size(); i++)
            std::fill(data[i].begin(), data[i].end(), -200.0);
        std::cout << "Variables Read in TS " << step << ": ";
        for (int j = 0; j < 5; j++)
        {
            var_present[j] = (bool)vars[j];
            if (vars[j])
            {
                std::cout << " " << j;
                engine.Get(vars[j], data[j].data());
            }
        }
        std::cout << std::endl;
        engine.EndStep();
        for (int j = 0; j < 5; j++)
        {
            if (var_present[j])
            {
                for (std::size_t index = 0; index < data[j].size(); ++index)
                {
                    EXPECT_EQ(data[j][index], j + 1.0)
                        << "Data isn't correct, for " << vars[j].Name() << "["
                        << index << "]";
                }
            }
        }
    }

    // Close the file
    engine.Close();
}

int main(int argc, char **argv)
{

    int result;
    ::testing::InitGoogleTest(&argc, argv);

    DelayMS = 0; // zero for common writer

    ParseArgs(argc, argv);

    result = RUN_ALL_TESTS();

    return result;
}
<|endoftext|>


<commit_before><commit_msg>Adds cout statement to verify that L1 noise is being set properly.<commit_after><|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

//  Software Guide : BeginLatex
//
//  The composite filter we will build combines three filters: a gradient
//  magnitude operator, which will calculate the first-order derivative of
//  the image; a thresholding step to select edges over a given strength;
//  and finally a rescaling filter, to ensure the resulting image data is
//  visible by scaling the intensity to the full spectrum of the output
//  image type.
//
//  Since this filter takes an image and produces another image (of
//  identical type), we will specialize the ImageToImageFilter:
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  Next we include headers for the component filters:
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
#include "itkGradientMagnitudeImageFilter.h"
#include "itkThresholdImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
//  Software Guide : EndCodeSnippet

#include "itkNumericTraits.h"

//  Software Guide : BeginLatex
//
//  Now we can declare the filter itself.  It is within the ITK namespace,
//  and we decide to make it use the same image type for both input and
//  output, thus the template declaration needs only one parameter.
//  Deriving from \code{ImageToImageFilter} provides default behavior for
//  several important aspects, notably allocating the output image (and
//  making it the same dimensions as the input).
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
namespace itk {

template <class TImageType>
class CompositeExampleImageFilter :
    public ImageToImageFilter<TImageType, TImageType>
{
public:
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  Next we have the standard declarations, used for object creation with
//  the object factory:
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
  typedef CompositeExampleImageFilter               Self;
  typedef ImageToImageFilter<TImageType,TImageType> Superclass;
  typedef SmartPointer<Self>                        Pointer;
  typedef SmartPointer<const Self>                  ConstPointer;
//  Software Guide : EndCodeSnippet

  /** Method for creation through object factory */
  itkNewMacro(Self);

  /** Run-time type information */
  itkTypeMacro(CompositeExampleImageFilter, ImageToImageFilter);

  /** Display */
  void PrintSelf( std::ostream& os, Indent indent ) const;

//  Software Guide : BeginLatex
//
//  Here we declare an alias (to save typing) for the image's pixel type,
//  which determines the type of the threshold value.  We then use the
//  convenience macros to define the Get and Set methods for this parameter.
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet

  typedef typename TImageType::PixelType PixelType;

  itkGetMacro( Threshold, PixelType);
  itkSetMacro( Threshold, PixelType);

//  Software Guide : EndCodeSnippet

protected:

  CompositeExampleImageFilter();

//  Software Guide : BeginLatex
//
//  Now we can declare the component filter types, templated over the
//  enclosing image type:
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet

protected:

  typedef ThresholdImageFilter< TImageType >                     ThresholdType;
  typedef GradientMagnitudeImageFilter< TImageType, TImageType > GradientType;
  typedef RescaleIntensityImageFilter< TImageType, TImageType >  RescalerType;
//  Software Guide : EndCodeSnippet

    void GenerateData();

private:

  CompositeExampleImageFilter(Self&);   // intentionally not implemented
  void operator=(const Self&);          // intentionally not implemented

//  Software Guide : BeginLatex
//
//  The component filters are declared as data members, all using the smart
//  pointer types.
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet

  typename GradientType::Pointer     m_GradientFilter;
  typename ThresholdType::Pointer    m_ThresholdFilter;
  typename RescalerType::Pointer     m_RescaleFilter;

  PixelType m_Threshold;
};

} /* namespace itk */
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  The constructor sets up the pipeline, which involves creating the
//  stages, connecting them together, and setting default parameters.
//
//  Software Guide : EndLatex

namespace itk
{

//  Software Guide : BeginCodeSnippet
template <class TImageType>
CompositeExampleImageFilter<TImageType>
::CompositeExampleImageFilter()
{
  m_Threshold = 1;
  m_GradientFilter = GradientType::New();
  m_ThresholdFilter = ThresholdType::New();
  m_ThresholdFilter->SetInput( m_GradientFilter->GetOutput() );
  m_RescaleFilter = RescalerType::New();
  m_RescaleFilter->SetInput( m_ThresholdFilter->GetOutput() );
  m_RescaleFilter->SetOutputMinimum(
                                  NumericTraits<PixelType>::NonpositiveMin());
  m_RescaleFilter->SetOutputMaximum(NumericTraits<PixelType>::max());
}
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  The \code{GenerateData()} is where the composite magic happens.  First,
//  we connect the first component filter to the inputs of the composite
//  filter (the actual input, supplied by the upstream stage).  Then we
//  graft the output of the last stage onto the output of the composite,
//  which ensures the filter regions are updated.  We force the composite
//  pipeline to be processed by calling \code{Update()} on the final stage,
//  then graft the output back onto the output of the enclosing filter, so
//  it has the result available to the downstream filter.
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
template <class TImageType>
void
CompositeExampleImageFilter<TImageType>::
GenerateData()
{
  m_GradientFilter->SetInput( this->GetInput() );

  m_ThresholdFilter->ThresholdBelow( this->m_Threshold );

  m_RescaleFilter->GraftOutput( this->GetOutput() );
  m_RescaleFilter->Update();
  this->GraftOutput( m_RescaleFilter->GetOutput() );
}
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  Finally we define the \code{PrintSelf} method, which (by convention)
//  prints the filter parameters.  Note how it invokes the superclass to
//  print itself first, and also how the indentation prefixes each line.
//
//  Software Guide : EndLatex
//
//  Software Guide : BeginCodeSnippet

template <class TImageType>
void
CompositeExampleImageFilter<TImageType>::
PrintSelf( std::ostream& os, Indent indent ) const
{
  Superclass::PrintSelf(os,indent);

  os
    << indent << "Threshold:" << this->m_Threshold
    << std::endl;
}

} /* end namespace itk */

//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  It is important to note that in the above example, none of the internal
//  details of the pipeline were exposed to users of the class.  The interface
//  consisted of the Threshold parameter (which happened to change the value in
//  the component filter) and the regular ImageToImageFilter interface.  This
//  example pipeline is illustrated in
//  Figure~\ref{fig:CompositeExamplePipeline}.
//
//  Software Guide : EndLatex

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

int main( int argc, char* argv[] )
{
  if( argc < 3 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile  outputImageFile" << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::Image<short, 2>                        ImageType;
  typedef itk::ImageFileReader<ImageType>             ReaderType;
  typedef itk::ImageFileWriter<ImageType>             WriterType;

  typedef itk::CompositeExampleImageFilter<ImageType> FilterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();
  FilterType::Pointer filter = FilterType::New();

  reader->SetFileName( argv[1] );
  filter->SetInput( reader->GetOutput() );
  filter->SetThreshold( 20 );
  writer->SetInput( filter->GetOutput() );
  writer->SetFileName( argv[2] );

  try
    {
    writer->Update();
    }
  catch ( itk::ExceptionObject & e )
    {
    std::cerr << "Error: " << e << std::endl;
    }

  return 0;
}
<commit_msg>DOC: Fix empty code block.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

//  Software Guide : BeginLatex
//
//  The composite filter we will build combines three filters: a gradient
//  magnitude operator, which will calculate the first-order derivative of
//  the image; a thresholding step to select edges over a given strength;
//  and finally a rescaling filter, to ensure the resulting image data is
//  visible by scaling the intensity to the full spectrum of the output
//  image type.
//
//  Since this filter takes an image and produces another image (of
//  identical type), we will specialize the ImageToImageFilter:
//
//  Software Guide : EndLatex

//  Software Guide : BeginLatex
//
//  Next we include headers for the component filters:
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
#include "itkGradientMagnitudeImageFilter.h"
#include "itkThresholdImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
//  Software Guide : EndCodeSnippet

#include "itkNumericTraits.h"

//  Software Guide : BeginLatex
//
//  Now we can declare the filter itself.  It is within the ITK namespace,
//  and we decide to make it use the same image type for both input and
//  output, so that the template declaration needs only one parameter.
//  Deriving from \code{ImageToImageFilter} provides default behavior for
//  several important aspects, notably allocating the output image (and
//  making it the same dimensions as the input).
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
namespace itk {

template <class TImageType>
class CompositeExampleImageFilter :
    public ImageToImageFilter<TImageType, TImageType>
{
public:
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  Next we have the standard declarations, used for object creation with
//  the object factory:
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
  typedef CompositeExampleImageFilter               Self;
  typedef ImageToImageFilter<TImageType,TImageType> Superclass;
  typedef SmartPointer<Self>                        Pointer;
  typedef SmartPointer<const Self>                  ConstPointer;
//  Software Guide : EndCodeSnippet

  /** Method for creation through object factory */
  itkNewMacro(Self);

  /** Run-time type information */
  itkTypeMacro(CompositeExampleImageFilter, ImageToImageFilter);

  /** Display */
  void PrintSelf( std::ostream& os, Indent indent ) const;

//  Software Guide : BeginLatex
//
//  Here we declare an alias (to save typing) for the image's pixel type,
//  which determines the type of the threshold value.  We then use the
//  convenience macros to define the Get and Set methods for this parameter.
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
  typedef typename TImageType::PixelType PixelType;

  itkGetMacro( Threshold, PixelType);
  itkSetMacro( Threshold, PixelType);
//  Software Guide : EndCodeSnippet

protected:

  CompositeExampleImageFilter();

//  Software Guide : BeginLatex
//
//  Now we can declare the component filter types, templated over the
//  enclosing image type:
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
protected:

  typedef ThresholdImageFilter< TImageType >                     ThresholdType;
  typedef GradientMagnitudeImageFilter< TImageType, TImageType > GradientType;
  typedef RescaleIntensityImageFilter< TImageType, TImageType >  RescalerType;
//  Software Guide : EndCodeSnippet

    void GenerateData();

private:

  CompositeExampleImageFilter(Self&);   // intentionally not implemented
  void operator=(const Self&);          // intentionally not implemented

//  Software Guide : BeginLatex
//
//  The component filters are declared as data members, all using the smart
//  pointer types.
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
  typename GradientType::Pointer     m_GradientFilter;
  typename ThresholdType::Pointer    m_ThresholdFilter;
  typename RescalerType::Pointer     m_RescaleFilter;

  PixelType m_Threshold;
};

} /* namespace itk */
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  The constructor sets up the pipeline, which involves creating the
//  stages, connecting them together, and setting default parameters.
//
//  Software Guide : EndLatex

namespace itk
{

//  Software Guide : BeginCodeSnippet
template <class TImageType>
CompositeExampleImageFilter<TImageType>
::CompositeExampleImageFilter()
{
  m_Threshold = 1;
  m_GradientFilter = GradientType::New();
  m_ThresholdFilter = ThresholdType::New();
  m_ThresholdFilter->SetInput( m_GradientFilter->GetOutput() );
  m_RescaleFilter = RescalerType::New();
  m_RescaleFilter->SetInput( m_ThresholdFilter->GetOutput() );
  m_RescaleFilter->SetOutputMinimum(
                                  NumericTraits<PixelType>::NonpositiveMin());
  m_RescaleFilter->SetOutputMaximum(NumericTraits<PixelType>::max());
}
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  The \code{GenerateData()} is where the composite magic happens.  First,
//  we connect the first component filter to the inputs of the composite
//  filter (the actual input, supplied by the upstream stage).  Then we
//  graft the output of the last stage onto the output of the composite,
//  which ensures the filter regions are updated.  We force the composite
//  pipeline to be processed by calling \code{Update()} on the final stage,
//  then graft the output back onto the output of the enclosing filter, so
//  it has the result available to the downstream filter.
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet
template <class TImageType>
void
CompositeExampleImageFilter<TImageType>::
GenerateData()
{
  m_GradientFilter->SetInput( this->GetInput() );

  m_ThresholdFilter->ThresholdBelow( this->m_Threshold );

  m_RescaleFilter->GraftOutput( this->GetOutput() );
  m_RescaleFilter->Update();
  this->GraftOutput( m_RescaleFilter->GetOutput() );
}
//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  Finally we define the \code{PrintSelf} method, which (by convention)
//  prints the filter parameters.  Note how it invokes the superclass to
//  print itself first, and also how the indentation prefixes each line.
//
//  Software Guide : EndLatex
//
//  Software Guide : BeginCodeSnippet

template <class TImageType>
void
CompositeExampleImageFilter<TImageType>::
PrintSelf( std::ostream& os, Indent indent ) const
{
  Superclass::PrintSelf(os,indent);

  os
    << indent << "Threshold:" << this->m_Threshold
    << std::endl;
}

} /* end namespace itk */

//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  It is important to note that in the above example, none of the internal
//  details of the pipeline were exposed to users of the class.  The interface
//  consisted of the Threshold parameter (which happened to change the value in
//  the component filter) and the regular ImageToImageFilter interface.  This
//  example pipeline is illustrated in
//  Figure~\ref{fig:CompositeExamplePipeline}.
//
//  Software Guide : EndLatex

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

int main( int argc, char* argv[] )
{
  if( argc < 3 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile  outputImageFile" << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::Image<short, 2>                        ImageType;
  typedef itk::ImageFileReader<ImageType>             ReaderType;
  typedef itk::ImageFileWriter<ImageType>             WriterType;

  typedef itk::CompositeExampleImageFilter<ImageType> FilterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();
  FilterType::Pointer filter = FilterType::New();

  reader->SetFileName( argv[1] );
  filter->SetInput( reader->GetOutput() );
  filter->SetThreshold( 20 );
  writer->SetInput( filter->GetOutput() );
  writer->SetFileName( argv[2] );

  try
    {
    writer->Update();
    }
  catch ( itk::ExceptionObject & e )
    {
    std::cerr << "Error: " << e << std::endl;
    }

  return 0;
}
<|endoftext|>