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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkReleaseDataFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkRandomImageSource.h"
#include "itkMeanImageFilter.h"
#include "itkTextOutput.h"
#include "itkImageRegionIterator.h"
#include "itkShiftScaleImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkStreamingImageFilter.h"

#include "../IO/itkPipelineMonitorImageFilter.h"

int itkReleaseDataFilterTest(int, char* [] )
{
  // Comment the following if you want to use the itk text output window
  itk::OutputWindow::SetInstance(itk::TextOutput::New());

  typedef itk::Image<float,2> ImageType;
  typedef itk::PipelineMonitorImageFilter<ImageType> MonitorFilter;

  ImageType::SetGlobalReleaseDataFlag(true);

  typedef itk::RandomImageSource<ImageType> RandomImageSourceType;
  RandomImageSourceType::Pointer random = RandomImageSourceType::New();
  random->SetMin(0.0);
  random->SetMax(1000.0);

  unsigned long randomSize[2];
  randomSize[0] = randomSize[1] = 16;
  random->SetSize(randomSize);

  float spacing[2] = {0.7, 2.1};
  random->SetSpacing( spacing );
  float origin[2] = {15, 400};
  random->SetOrigin( origin );

  MonitorFilter::Pointer monitor1 = MonitorFilter::New();
  monitor1->SetInput( random->GetOutput() );

  // pipeline a

  // Create a mean image
  typedef itk::MeanImageFilter<ImageType, ImageType> MeanImageFilterType;
  MeanImageFilterType::Pointer mean1 = MeanImageFilterType::New();
  mean1->SetInput( monitor1->GetOutput() );

  // define the neighborhood size used for the mean filter
  ImageType::SizeType neighRadius;
  neighRadius.Fill(2);
  mean1->SetRadius( neighRadius );

  MonitorFilter::Pointer monitor2a = MonitorFilter::New();
  monitor2a->SetInput( mean1->GetOutput() );

  // pipeline b
  typedef itk::ShiftScaleImageFilter<ImageType, ImageType> ShiftScaleImageFilterType;
  ShiftScaleImageFilterType::Pointer shiftscale = ShiftScaleImageFilterType::New();
  shiftscale->SetInput( monitor1->GetOutput() );
  shiftscale->SetScale( 2.0 );
  shiftscale->SetShift( -100.0 );

  typedef itk::ShrinkImageFilter<ImageType, ImageType> ShrinkImageFilterType;
  ShrinkImageFilterType::Pointer shrinker = ShrinkImageFilterType::New();
  shrinker->SetInput( shiftscale->GetOutput() );
  shrinker->SetShrinkFactors( 2 );

  MonitorFilter::Pointer monitor2b = MonitorFilter::New();
  monitor2b->SetInput( shrinker->GetOutput() );

  typedef itk::StreamingImageFilter<ImageType, ImageType> StreamingImageFilterType;
  StreamingImageFilterType::Pointer streamer = StreamingImageFilterType::New();
  streamer->SetInput( monitor2b->GetOutput() );
  streamer->SetNumberOfStreamDivisions( 4 );

  ImageType::SizeType zeroSize;
  zeroSize.Fill(0);

  std::cout << "---- Updating \"a\" Pipeline ---" << std::endl;
  monitor2a->Update();
  if ( !monitor1->VerifyAllInputCanStream(1) ||
       !monitor2a->VerifyAllInputCanStream(1) ||
       !monitor2b->VerifyAllNoUpdate() )
    {
    std::cout << "Monitor1:\n" << monitor1 << std::endl;
    std::cout << "Monitor2a:\n" << monitor2a << std::endl;
    std::cout << "Monitor2b:\n" << monitor2b << std::endl;
    std::cout << "Monitor's VerifyAllInputCanStream failed!" << std::endl;
    return EXIT_FAILURE;
    }
  if ( random->GetOutput()->GetBufferedRegion().GetSize() != zeroSize ||
       monitor1->GetOutput()->GetBufferedRegion().GetSize() != zeroSize)
    {
    std::cout << "Random's output was not release!" << std::endl;
    return EXIT_FAILURE;
    }

  // no updates should happen
  std::cout << "---- Reupdating \"a\" Pipeline ---" << std::endl;
  monitor2a->Update();
  if ( !monitor1->VerifyAllNoUpdate() ||
       !monitor2a->VerifyAllNoUpdate() ||
       !monitor2b->VerifyAllNoUpdate() )
    {
    std::cout << "monitor1:\n" << monitor1 << std::endl;
    std::cout << "monitor2a:\n" << monitor2a << std::endl;
    std::cout << "Monitor2b:\n" << monitor2b << std::endl;
    std::cout << "Monitor's VerifyAllNoUpdate failed!" << std::endl;
    return EXIT_FAILURE;
    }
  if ( random->GetOutput()->GetBufferedRegion().GetSize() != zeroSize )
    {
    std::cout << "Random's output was not release!" << std::endl;
    return EXIT_FAILURE;
    }
  monitor2a->ClearPipelineSavedInformation();

  std::cout << "---- Streaming \"b\" Pipeline ---" << std::endl;
  streamer->Update();
  if ( !monitor1->VerifyAllInputCanStream(4) ||
       !monitor2a->VerifyAllNoUpdate() ||
       !monitor2b->VerifyAllInputCanStream(4) )
    {
    std::cout << "monitor1:\n" << monitor1 << std::endl;
    std::cout << "monitor2a:\n" << monitor2a << std::endl;
    std::cout << "Monitor2b:\n" << monitor2b << std::endl;
    std::cout << "Monitor's VerifyAllNoUpdate failed!" << std::endl;
    return EXIT_FAILURE;
    }
  if ( random->GetOutput()->GetBufferedRegion().GetSize() != zeroSize ||
       shiftscale->GetOutput()->GetBufferedRegion().GetSize() != zeroSize ||
       shrinker->GetOutput()->GetBufferedRegion().GetSize() != zeroSize )
    {
    std::cout << "random or shiftscale or shrink's output was not release!" << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<commit_msg>BUG: DataObject:: GlobalReleaseDataFlag static member functions were not used, they are now<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkReleaseDataFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkRandomImageSource.h"
#include "itkMeanImageFilter.h"
#include "itkTextOutput.h"
#include "itkImageRegionIterator.h"
#include "itkShiftScaleImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkStreamingImageFilter.h"

#include "../IO/itkPipelineMonitorImageFilter.h"

int itkReleaseDataFilterTest(int, char* [] )
{
  // Comment the following if you want to use the itk text output window
  itk::OutputWindow::SetInstance(itk::TextOutput::New());

  typedef itk::Image<float,2> ImageType;
  typedef itk::PipelineMonitorImageFilter<ImageType> MonitorFilter;

  // use all the static GlobalReleaseData methods
  ImageType::SetGlobalReleaseDataFlag( ImageType::GetGlobalReleaseDataFlag() );
  ImageType::GlobalReleaseDataFlagOff();
  ImageType::GlobalReleaseDataFlagOn();

  typedef itk::RandomImageSource<ImageType> RandomImageSourceType;
  RandomImageSourceType::Pointer random = RandomImageSourceType::New();
  random->SetMin(0.0);
  random->SetMax(1000.0);

  unsigned long randomSize[2];
  randomSize[0] = randomSize[1] = 16;
  random->SetSize(randomSize);

  float spacing[2] = {0.7, 2.1};
  random->SetSpacing( spacing );
  float origin[2] = {15, 400};
  random->SetOrigin( origin );

  MonitorFilter::Pointer monitor1 = MonitorFilter::New();
  monitor1->SetInput( random->GetOutput() );

  // pipeline a

  // Create a mean image
  typedef itk::MeanImageFilter<ImageType, ImageType> MeanImageFilterType;
  MeanImageFilterType::Pointer mean1 = MeanImageFilterType::New();
  mean1->SetInput( monitor1->GetOutput() );

  // define the neighborhood size used for the mean filter
  ImageType::SizeType neighRadius;
  neighRadius.Fill(2);
  mean1->SetRadius( neighRadius );

  MonitorFilter::Pointer monitor2a = MonitorFilter::New();
  monitor2a->SetInput( mean1->GetOutput() );

  // pipeline b
  typedef itk::ShiftScaleImageFilter<ImageType, ImageType> ShiftScaleImageFilterType;
  ShiftScaleImageFilterType::Pointer shiftscale = ShiftScaleImageFilterType::New();
  shiftscale->SetInput( monitor1->GetOutput() );
  shiftscale->SetScale( 2.0 );
  shiftscale->SetShift( -100.0 );

  typedef itk::ShrinkImageFilter<ImageType, ImageType> ShrinkImageFilterType;
  ShrinkImageFilterType::Pointer shrinker = ShrinkImageFilterType::New();
  shrinker->SetInput( shiftscale->GetOutput() );
  shrinker->SetShrinkFactors( 2 );

  MonitorFilter::Pointer monitor2b = MonitorFilter::New();
  monitor2b->SetInput( shrinker->GetOutput() );

  typedef itk::StreamingImageFilter<ImageType, ImageType> StreamingImageFilterType;
  StreamingImageFilterType::Pointer streamer = StreamingImageFilterType::New();
  streamer->SetInput( monitor2b->GetOutput() );
  streamer->SetNumberOfStreamDivisions( 4 );

  ImageType::SizeType zeroSize;
  zeroSize.Fill(0);

  std::cout << "---- Updating \"a\" Pipeline ---" << std::endl;
  monitor2a->Update();
  if ( !monitor1->VerifyAllInputCanStream(1) ||
       !monitor2a->VerifyAllInputCanStream(1) ||
       !monitor2b->VerifyAllNoUpdate() )
    {
    std::cout << "Monitor1:\n" << monitor1 << std::endl;
    std::cout << "Monitor2a:\n" << monitor2a << std::endl;
    std::cout << "Monitor2b:\n" << monitor2b << std::endl;
    std::cout << "Monitor's VerifyAllInputCanStream failed!" << std::endl;
    return EXIT_FAILURE;
    }
  if ( random->GetOutput()->GetBufferedRegion().GetSize() != zeroSize ||
       monitor1->GetOutput()->GetBufferedRegion().GetSize() != zeroSize)
    {
    std::cout << "Random's output was not release!" << std::endl;
    return EXIT_FAILURE;
    }

  // no updates should happen
  std::cout << "---- Reupdating \"a\" Pipeline ---" << std::endl;
  monitor2a->Update();
  if ( !monitor1->VerifyAllNoUpdate() ||
       !monitor2a->VerifyAllNoUpdate() ||
       !monitor2b->VerifyAllNoUpdate() )
    {
    std::cout << "monitor1:\n" << monitor1 << std::endl;
    std::cout << "monitor2a:\n" << monitor2a << std::endl;
    std::cout << "Monitor2b:\n" << monitor2b << std::endl;
    std::cout << "Monitor's VerifyAllNoUpdate failed!" << std::endl;
    return EXIT_FAILURE;
    }
  if ( random->GetOutput()->GetBufferedRegion().GetSize() != zeroSize )
    {
    std::cout << "Random's output was not release!" << std::endl;
    return EXIT_FAILURE;
    }
  monitor2a->ClearPipelineSavedInformation();

  std::cout << "---- Streaming \"b\" Pipeline ---" << std::endl;
  streamer->Update();
  if ( !monitor1->VerifyAllInputCanStream(4) ||
       !monitor2a->VerifyAllNoUpdate() ||
       !monitor2b->VerifyAllInputCanStream(4) )
    {
    std::cout << "monitor1:\n" << monitor1 << std::endl;
    std::cout << "monitor2a:\n" << monitor2a << std::endl;
    std::cout << "Monitor2b:\n" << monitor2b << std::endl;
    std::cout << "Monitor's VerifyAllNoUpdate failed!" << std::endl;
    return EXIT_FAILURE;
    }
  if ( random->GetOutput()->GetBufferedRegion().GetSize() != zeroSize ||
       shiftscale->GetOutput()->GetBufferedRegion().GetSize() != zeroSize ||
       shrinker->GetOutput()->GetBufferedRegion().GetSize() != zeroSize )
    {
    std::cout << "random or shiftscale or shrink's output was not release!" << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * fileio.hpp
 *
 *  Created on: Oct 21, 2009
 *      Author: rasmussn
 */

#ifndef FILEIO_HPP_
#define FILEIO_HPP_

#include "io.h"
#include "../include/PVLayerLoc.h"
#include "../columns/Communicator.hpp"

namespace PV {

FILE * pvp_open_write_file(const char * filename, Communicator * comm, bool append);

int pvp_close_file(FILE * fp, Communicator * comm);

int pvp_read_header(const char * filename, Communicator * comm, double * time,
                    int * filetype, int * datatype, int params[], int * numParams);
int pvp_write_header(FILE * fp, Communicator * comm, double time, const PVLayerLoc * loc,
                     int filetype, int datatype, int subRecordSize,
                     bool extended, bool contiguous, unsigned int numParams, size_t localSize);

int read(const char * filename, Communicator * comm, double * time, pvdata_t * data,
         const PVLayerLoc * loc, int datatype, bool extended, bool contiguous);

int write(const char * filename, Communicator * comm, double time, const pvdata_t * data,
          const PVLayerLoc * loc, int datatype, bool extended, bool contiguous);

int writeActivity(FILE * fp, Communicator * comm, double time, PVLayer * l);

int writeActivitySparse(FILE * fp, Communicator * comm, double time, PVLayer * l);

int readWeights(PVPatch ** patches, int numPatches, const char * filename,
                Communicator * comm, double * time, const PVLayerLoc * loc, bool extended);

int writeWeights(const char * filename, Communicator * comm, double time, bool append,
                 const PVLayerLoc * loc, int nxp, int nyp, int nfp, float minVal, float maxVal,
                 PVPatch ** patches, int numPatches);

int pvp_check_file_header(Communicator * comm, const PVLayerLoc * loc, int params[], int numParams);

} // namespace PV

#endif /* FILEIO_HPP_ */
<commit_msg>Includes a function to write layer state variables.<commit_after>/*
 * fileio.hpp
 *
 *  Created on: Oct 21, 2009
 *      Author: rasmussn
 */

#ifndef FILEIO_HPP_
#define FILEIO_HPP_

#include "io.h"
#include "../include/PVLayerLoc.h"
#include "../columns/Communicator.hpp"

namespace PV {

FILE * pvp_open_write_file(const char * filename, Communicator * comm, bool append);

int pvp_close_file(FILE * fp, Communicator * comm);

int pvp_read_header(const char * filename, Communicator * comm, double * time,
                    int * filetype, int * datatype, int params[], int * numParams);
int pvp_write_header(FILE * fp, Communicator * comm, double time, const PVLayerLoc * loc,
                     int filetype, int datatype, int subRecordSize,
                     bool extended, bool contiguous, unsigned int numParams, size_t localSize);

int read(const char * filename, Communicator * comm, double * time, pvdata_t * data,
         const PVLayerLoc * loc, int datatype, bool extended, bool contiguous);

int write(const char * filename, Communicator * comm, double time, const pvdata_t * data,
          const PVLayerLoc * loc, int datatype, bool extended, bool contiguous);

int writeStateVariable(FILE *fp, Communicator * comm, double time, PVLayer * l, pvdata_t * VmemVals);

int writeActivity(FILE * fp, Communicator * comm, double time, PVLayer * l);

int writeActivitySparse(FILE * fp, Communicator * comm, double time, PVLayer * l);

int readWeights(PVPatch ** patches, int numPatches, const char * filename,
                Communicator * comm, double * time, const PVLayerLoc * loc, bool extended);

int writeWeights(const char * filename, Communicator * comm, double time, bool append,
                 const PVLayerLoc * loc, int nxp, int nyp, int nfp, float minVal, float maxVal,
                 PVPatch ** patches, int numPatches);

int pvp_check_file_header(Communicator * comm, const PVLayerLoc * loc, int params[], int numParams);

} // namespace PV

#endif /* FILEIO_HPP_ */
<|endoftext|>


<commit_before>/*
* Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
* License for more details.
*/

#include "ircbuffer.h"
#include "ircbuffer_p.h"
#include "ircsession.h"
#include "ircsession_p.h"

/*!
    \class Irc::Buffer ircbuffer.h
    \brief The Irc::Buffer class provides an IRC buffer.

    ...
 */

/*!
    \enum Irc::Buffer::MessageFlag

    This enum describes available message flags.
 */

/*!
    \var Irc::Buffer::NoFlags

    No flags for the message.
 */

/*!
    \var Irc::Buffer::IdentifiedFlag

    Message was sent from an identified nick.
 */

/*!
    \var Irc::Buffer::EchoFlag

    Message echoed back from library.
 */

/*!
    \fn void Irc::Buffer::receiverChanged(const QString& receiver)

    This signal is emitted whenever \a receiver has changed.
 */

/*!
    \fn void Irc::Buffer::joined(const QString& origin)

    This signal is emitted when \a origin has joined.
 */

/*!
    \fn void Irc::Buffer::parted(const QString& origin, const QString& message)

    This signal is emitted when \a origin has parted with \a message.
 */

/*!
    \fn void Irc::Buffer::quit(const QString& origin, const QString& message)

    This signal is emitted when \a origin has quit with \a message.
 */

/*!
    \fn void Irc::Buffer::nickChanged(const QString& origin, const QString& nick)

    This signal is emitted when \a origin has changed \a nick.
 */

/*!
    \fn void Irc::Buffer::modeChanged(const QString& origin, const QString& mode, const QString& args)

    This signal is emitted when \a origin has changed \a mode with \a args.
 */

/*!
    \fn void Irc::Buffer::topicChanged(const QString& origin, const QString& topic)

    This signal is emitted when \a origin has changed \a topic.
 */

/*!
    \fn void Irc::Buffer::invited(const QString& origin, const QString& receiver, const QString& channel)

    This signal is emitted when \a origin has invited \a receiver to \a channel.
 */

/*!
    \fn void Irc::Buffer::kicked(const QString& origin, const QString& nick, const QString& message)

    This signal is emitted when \a origin has kicked \a nick with \a message.
 */

/*!
    \fn void Irc::Buffer::messageReceived(const QString& origin, const QString& message)

    This signal is emitted when \a origin has sent \a message.
 */

/*!
    \fn void Irc::Buffer::noticeReceived(const QString& origin, const QString& notice)

    This signal is emitted when \a origin has sent \a notice.
 */

/*!
    \fn void Irc::Buffer::ctcpRequestReceived(const QString& origin, const QString& request)

    This signal is emitted when \a origin has sent a CTCP \a request.
 */

/*!
    \fn void Irc::Buffer::ctcpReplyReceived(const QString& origin, const QString& reply)

    This signal is emitted when \a origin has sent a CTCP \a reply.
 */

/*!
    \fn void Irc::Buffer::ctcpActionReceived(const QString& origin, const QString& action)

    This signal is emitted when \a origin has sent a CTCP \a action.
 */

/*!
    \fn void Irc::Buffer::numericMessageReceived(const QString& origin, uint code, const QStringList& params)

    This signal is emitted when \a origin has sent a numeric message with \a code and \a params.
 */

/*!
    \fn void Irc::Buffer::unknownMessageReceived(const QString& origin, const QStringList& params)

    This signal is emitted when \a origin has sent an unknown message with \a params.
 */

namespace Irc
{
    BufferPrivate::BufferPrivate() :
        q_ptr(0)
    {
    }

    void BufferPrivate::addName(QString name)
    {
        QString mode;
        if (name.startsWith(QLatin1Char('@')))
        {
            mode = QLatin1Char('o');
            name = name.remove(0, 1);
        }
        else if (name.startsWith(QLatin1Char('+')))
        {
            mode = QLatin1Char('v');
            name = name.remove(0, 1);
        }
        names.insert(name, mode);
    }

    void BufferPrivate::removeName(const QString& name)
    {
        names.remove(name);
    }

    void BufferPrivate::updateMode(const QString& name, const QString& mode)
    {
        bool add = true;
        QString updated = names.value(name);
        for (int i = 0; i < mode.size(); ++i)
        {
            QChar c = mode.at(i);
            switch (c.toAscii())
            {
                case '+':
                    add = true;
                    break;
                case '-':
                    add = false;
                    break;
                default:
                    if (add)
                    {
                        if (!updated.contains(c))
                            updated += c;
                    }
                    else
                    {
                        updated.remove(c);
                    }
                    break;
            }
        }
        names.insert(name, updated);
    }

    void BufferPrivate::setReceiver(const QString& rec, bool replace)
    {
        Q_Q(Buffer);
        if (receiver != rec)
        {
            Session* s = q->session();
            if (s)
            {
                if (replace)
                    s->d_func()->buffers.remove(receiver);
                s->d_func()->buffers.insert(rec, q);
            }
            receiver = rec;
            emit q->receiverChanged(receiver);
        }
    }

    Buffer::Buffer(const QString& receiver, Session* parent) : QObject(parent), d_ptr(new BufferPrivate)
    {
        Q_D(Buffer);
        d->q_ptr = this;
        d->receiver = receiver;
    }

    Buffer::Buffer(BufferPrivate& dd, const QString& receiver, Session* parent) : QObject(parent), d_ptr(&dd)
    {
        Q_D(Buffer);
        d->q_ptr = this;
        d->receiver = receiver;
    }

    /*!
        Destructs the IRC buffer.
     */
    Buffer::~Buffer()
    {
        Session* s = session();
        if (s)
            s->d_func()->removeBuffer(this);

        Q_D(Buffer);
        delete d;
    }

    /*!
        Returns the session.
     */
    Session* Buffer::session() const
    {
        return qobject_cast<Session*>(parent());
    }

    /*!
        Returns the receiver.
     */
    QString Buffer::receiver() const
    {
        Q_D(const Buffer);
        return d->receiver;
    }

    /*!
        Returns the topic.
     */
    QString Buffer::topic() const
    {
        Q_D(const Buffer);
        return d->topic;
    }

    /*!
        Returns the names.
     */
    QStringList Buffer::names() const
    {
        Q_D(const Buffer);
        return d->names.keys();
    }

    /*!
        Returns the modes of \a name.
     */
    QString Buffer::modes(const QString& name) const
    {
        Q_D(const Buffer);
        return d->names.value(name);
    }

    /*!
        Returns the visual mode of \a name.
     */
    QString Buffer::visualMode(const QString& name) const
    {
        Q_D(const Buffer);
        QString modes = d->names.value(name);
        if (modes.contains(QLatin1Char('o')))
            return QLatin1String("@");
        if (modes.contains(QLatin1Char('v')))
            return QLatin1String("+");
        return QString();
    }

    /*!
        This convenience function sends a \a message to the buffer's receiver.

        \sa Session::message()
     */
    bool Buffer::message(const QString& message)
    {
        Q_D(Buffer);
        Session* s = session();
        return s && s->message(d->receiver, message);
    }

    /*!
        This convenience function sends a \a notice to the buffer's receiver.

        \sa Session::notice()
     */
    bool Buffer::notice(const QString& notice)
    {
        Q_D(Buffer);
        Session* s = session();
        return s && s->notice(d->receiver, notice);
    }

    /*!
        This convenience function sends a CTCP \a action to the buffers' receiver.

        \sa Session::ctcpAction()
     */
    bool Buffer::ctcpAction(const QString& action)
    {
        Q_D(Buffer);
        Session* s = session();
        return s && s->ctcpAction(d->receiver, action);
    }
}

#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const Irc::Buffer* buffer)
{
    if (!buffer)
        return debug << "Irc::Buffer(0x0) ";
    debug.nospace() << buffer->metaObject()->className() << '(' << (void*) buffer;
    if (!buffer->objectName().isEmpty())
        debug << ", name = " << buffer->objectName();
    if (!buffer->receiver().isEmpty())
        debug << ", receiver = " << buffer->receiver();
    debug << ')';
    return debug.space();
}
#endif // QT_NO_DEBUG_STREAM

#include "moc_ircbuffer.cpp"
<commit_msg>Updated Irc::Buffer docs<commit_after>/*
* Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
* License for more details.
*/

#include "ircbuffer.h"
#include "ircbuffer_p.h"
#include "ircsession.h"
#include "ircsession_p.h"

/*!
    \class Irc::Buffer ircbuffer.h
    \brief The Irc::Buffer class provides an IRC buffer.

    ...
 */

/*!
    \enum Irc::Buffer::MessageFlag

    This enum describes available message flags.
 */

/*!
    \var Irc::Buffer::NoFlags

    No flags for the message.
 */

/*!
    \var Irc::Buffer::IdentifiedFlag

    Message was sent from an identified nick.
 */

/*!
    \var Irc::Buffer::EchoFlag

    Message echoed back from library.
 */

/*!
    \fn void Irc::Buffer::receiverChanged(const QString& receiver)

    This signal is emitted whenever \a receiver has changed.
 */

/*!
    \fn void Irc::Buffer::motdReceived(const QString& motd)

    This signal is emitted when message of the day \a motd has been changed.
 */

/*!
    \fn void Irc::Buffer::joined(const QString& origin)

    This signal is emitted when \a origin has joined.
 */

/*!
    \fn void Irc::Buffer::parted(const QString& origin, const QString& message)

    This signal is emitted when \a origin has parted with \a message.
 */

/*!
    \fn void Irc::Buffer::quit(const QString& origin, const QString& message)

    This signal is emitted when \a origin has quit with \a message.
 */

/*!
    \fn void Irc::Buffer::nickChanged(const QString& origin, const QString& nick)

    This signal is emitted when \a origin has changed \a nick.
 */

/*!
    \fn void Irc::Buffer::modeChanged(const QString& origin, const QString& mode, const QString& args)

    This signal is emitted when \a origin has changed \a mode with \a args.
 */

/*!
    \fn void Irc::Buffer::topicChanged(const QString& origin, const QString& topic)

    This signal is emitted when \a origin has changed \a topic.
 */

/*!
    \fn void Irc::Buffer::invited(const QString& origin, const QString& receiver, const QString& channel)

    This signal is emitted when \a origin has invited \a receiver to \a channel.
 */

/*!
    \fn void Irc::Buffer::kicked(const QString& origin, const QString& nick, const QString& message)

    This signal is emitted when \a origin has kicked \a nick with \a message.
 */

/*!
    \fn void Irc::Buffer::messageReceived(const QString& origin, const QString& message, Irc::Buffer::MessageFlags flags = Irc::Buffer::NoFlags)

    This signal is emitted when \a origin has sent \a message.
 */

/*!
    \fn void Irc::Buffer::noticeReceived(const QString& origin, const QString& notice, Irc::Buffer::MessageFlags flags = Irc::Buffer::NoFlags)

    This signal is emitted when \a origin has sent \a notice.
 */

/*!
    \fn void Irc::Buffer::ctcpRequestReceived(const QString& origin, const QString& request, Irc::Buffer::MessageFlags flags = Irc::Buffer::NoFlags)

    This signal is emitted when \a origin has sent a CTCP \a request.
 */

/*!
    \fn void Irc::Buffer::ctcpReplyReceived(const QString& origin, const QString& reply, Irc::Buffer::MessageFlags flags = Irc::Buffer::NoFlags)

    This signal is emitted when \a origin has sent a CTCP \a reply.
 */

/*!
    \fn void Irc::Buffer::ctcpActionReceived(const QString& origin, const QString& action, Irc::Buffer::MessageFlags flags = Irc::Buffer::NoFlags)

    This signal is emitted when \a origin has sent a CTCP \a action.
 */

/*!
    \fn void Irc::Buffer::numericMessageReceived(const QString& origin, uint code, const QStringList& params)

    This signal is emitted when \a origin has sent a numeric message with \a code and \a params.
 */

/*!
    \fn void Irc::Buffer::unknownMessageReceived(const QString& origin, const QStringList& params)

    This signal is emitted when \a origin has sent an unknown message with \a params.
 */

namespace Irc
{
    BufferPrivate::BufferPrivate() :
        q_ptr(0)
    {
    }

    void BufferPrivate::addName(QString name)
    {
        QString mode;
        if (name.startsWith(QLatin1Char('@')))
        {
            mode = QLatin1Char('o');
            name = name.remove(0, 1);
        }
        else if (name.startsWith(QLatin1Char('+')))
        {
            mode = QLatin1Char('v');
            name = name.remove(0, 1);
        }
        names.insert(name, mode);
    }

    void BufferPrivate::removeName(const QString& name)
    {
        names.remove(name);
    }

    void BufferPrivate::updateMode(const QString& name, const QString& mode)
    {
        bool add = true;
        QString updated = names.value(name);
        for (int i = 0; i < mode.size(); ++i)
        {
            QChar c = mode.at(i);
            switch (c.toAscii())
            {
                case '+':
                    add = true;
                    break;
                case '-':
                    add = false;
                    break;
                default:
                    if (add)
                    {
                        if (!updated.contains(c))
                            updated += c;
                    }
                    else
                    {
                        updated.remove(c);
                    }
                    break;
            }
        }
        names.insert(name, updated);
    }

    void BufferPrivate::setReceiver(const QString& rec, bool replace)
    {
        Q_Q(Buffer);
        if (receiver != rec)
        {
            Session* s = q->session();
            if (s)
            {
                if (replace)
                    s->d_func()->buffers.remove(receiver);
                s->d_func()->buffers.insert(rec, q);
            }
            receiver = rec;
            emit q->receiverChanged(receiver);
        }
    }

    Buffer::Buffer(const QString& receiver, Session* parent) : QObject(parent), d_ptr(new BufferPrivate)
    {
        Q_D(Buffer);
        d->q_ptr = this;
        d->receiver = receiver;
    }

    Buffer::Buffer(BufferPrivate& dd, const QString& receiver, Session* parent) : QObject(parent), d_ptr(&dd)
    {
        Q_D(Buffer);
        d->q_ptr = this;
        d->receiver = receiver;
    }

    /*!
        Destructs the IRC buffer.
     */
    Buffer::~Buffer()
    {
        Session* s = session();
        if (s)
            s->d_func()->removeBuffer(this);

        Q_D(Buffer);
        delete d;
    }

    /*!
        Returns the session.
     */
    Session* Buffer::session() const
    {
        return qobject_cast<Session*>(parent());
    }

    /*!
        Returns the receiver.
     */
    QString Buffer::receiver() const
    {
        Q_D(const Buffer);
        return d->receiver;
    }

    /*!
        Returns the topic.
     */
    QString Buffer::topic() const
    {
        Q_D(const Buffer);
        return d->topic;
    }

    /*!
        Returns the names.
     */
    QStringList Buffer::names() const
    {
        Q_D(const Buffer);
        return d->names.keys();
    }

    /*!
        Returns the modes of \a name.
     */
    QString Buffer::modes(const QString& name) const
    {
        Q_D(const Buffer);
        return d->names.value(name);
    }

    /*!
        Returns the visual mode of \a name.
     */
    QString Buffer::visualMode(const QString& name) const
    {
        Q_D(const Buffer);
        QString modes = d->names.value(name);
        if (modes.contains(QLatin1Char('o')))
            return QLatin1String("@");
        if (modes.contains(QLatin1Char('v')))
            return QLatin1String("+");
        return QString();
    }

    /*!
        This convenience function sends a \a message to the buffer's receiver.

        \sa Session::message()
     */
    bool Buffer::message(const QString& message)
    {
        Q_D(Buffer);
        Session* s = session();
        return s && s->message(d->receiver, message);
    }

    /*!
        This convenience function sends a \a notice to the buffer's receiver.

        \sa Session::notice()
     */
    bool Buffer::notice(const QString& notice)
    {
        Q_D(Buffer);
        Session* s = session();
        return s && s->notice(d->receiver, notice);
    }

    /*!
        This convenience function sends a CTCP \a action to the buffers' receiver.

        \sa Session::ctcpAction()
     */
    bool Buffer::ctcpAction(const QString& action)
    {
        Q_D(Buffer);
        Session* s = session();
        return s && s->ctcpAction(d->receiver, action);
    }
}

#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const Irc::Buffer* buffer)
{
    if (!buffer)
        return debug << "Irc::Buffer(0x0) ";
    debug.nospace() << buffer->metaObject()->className() << '(' << (void*) buffer;
    if (!buffer->objectName().isEmpty())
        debug << ", name = " << buffer->objectName();
    if (!buffer->receiver().isEmpty())
        debug << ", receiver = " << buffer->receiver();
    debug << ')';
    return debug.space();
}
#endif // QT_NO_DEBUG_STREAM

#include "moc_ircbuffer.cpp"
<|endoftext|>


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

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_
#include <com/sun/star/frame/XInterceptorInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTION_HPP_
#include <com/sun/star/frame/XDispatchProviderInterception.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif

struct HelpHistoryEntry_Impl
{
    String  aURL;
    com::sun::star::uno::Any    aViewData;

    HelpHistoryEntry_Impl( const String& rURL, const com::sun::star::uno::Any& rViewData ) :
        aURL( rURL ), aViewData(rViewData) {}
};

DECLARE_LIST(HelpHistoryList_Impl,HelpHistoryEntry_Impl*);

class SfxHelpWindow_Impl;
class HelpInterceptor_Impl : public ::cppu::WeakImplHelper3<

        ::com::sun::star::frame::XDispatchProviderInterceptor,
        ::com::sun::star::frame::XInterceptorInfo,
        ::com::sun::star::frame::XDispatch >

{
private:
friend class HelpDispatch_Impl;
friend class SfxHelpWindow_Impl;

    // the component which's dispatches we're intercepting
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > m_xIntercepted;

    // chaining
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xSlaveDispatcher;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xMasterDispatcher;

    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener > m_xListener;

    HelpHistoryList_Impl*       m_pHistory;
    SfxHelpWindow_Impl*         m_pWindow;
    ULONG                       m_nCurPos;
    String                      m_aCurrentURL;
    com::sun::star::uno::Any    m_aViewData;

    void                        addURL( const String& rURL );

public:
    HelpInterceptor_Impl();
    ~HelpInterceptor_Impl();

    void                    setInterception( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame );
    void                    SetStartURL( const String& rURL );
    String                  GetCurrentURL() const { return m_aCurrentURL; }

    const com::sun::star::uno::Any&     GetViewData()const {return m_aViewData;}

    sal_Bool                HasHistoryPred() const;     // is there a predecessor for the current in the history
    sal_Bool                HasHistorySucc() const;     // is there a successor for the current in the history

    // XDispatchProvider
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL
                            queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL
                            queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw(::com::sun::star::uno::RuntimeException);

    // XDispatchProviderInterceptor
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL
                            getSlaveDispatchProvider(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlave ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL
                            getMasterDispatchProvider(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMaster ) throw(::com::sun::star::uno::RuntimeException);

    // XInterceptorInfo
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
                            getInterceptedURLs(  ) throw(::com::sun::star::uno::RuntimeException);

    // XDispatch
    virtual void SAL_CALL   dispatch( const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   addStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, const ::com::sun::star::util::URL& aURL ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   removeStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, const ::com::sun::star::util::URL& aURL ) throw(::com::sun::star::uno::RuntimeException);

    // extras
    void                    InitWaiter( SfxHelpWindow_Impl* pWindow )
                                { m_pWindow = pWindow; }
    SfxHelpWindow_Impl*     GetHelpWindow() const { return m_pWindow; }
};

// HelpListener_Impl -----------------------------------------------------

class HelpListener_Impl : public ::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener >
{
private:
    HelpInterceptor_Impl*   pInterceptor;
    Link                    aChangeLink;
    String                  aFactory;

public:
    HelpListener_Impl( HelpInterceptor_Impl* pInter );

    virtual void SAL_CALL   statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event )
                                throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL   disposing( const ::com::sun::star::lang::EventObject& obj )
                                throw( ::com::sun::star::uno::RuntimeException );

    void                    SetChangeHdl( const Link& rLink ) { aChangeLink = rLink; }
    String                  GetFactory() const { return aFactory; }
};
// HelpStatusListener_Impl -----------------------------------------------------

class HelpStatusListener_Impl : public
::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener >
{
private:
    ::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatch > xDispatch;
    ::com::sun::star::frame::FeatureStateEvent                              aStateEvent;

public:
    HelpStatusListener_Impl(
        ::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatch > xDispatch,
        com::sun::star::util::URL& rURL);
    ~HelpStatusListener_Impl();

    virtual void SAL_CALL   statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event )
                                throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL   disposing( const ::com::sun::star::lang::EventObject& obj )
                                throw( ::com::sun::star::uno::RuntimeException );
    const ::com::sun::star::frame::FeatureStateEvent&
                            GetStateEvent() const {return aStateEvent;}
};

#endif // #ifndef INCLUDED_SFX_HELPINTERCEPTOR_HXX

<commit_msg>INTEGRATION: CWS warnings01 (1.16.66); FILE MERGED 2005/11/28 16:13:23 cd 1.16.66.1: #i55991# Remove warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: helpinterceptor.hxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 22:09:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef INCLUDED_SFX_HELPINTERCEPTOR_HXX
#define INCLUDED_SFX_HELPINTERCEPTOR_HXX

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_
#include <com/sun/star/frame/XDispatchProviderInterceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_
#include <com/sun/star/frame/XInterceptorInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTION_HPP_
#include <com/sun/star/frame/XDispatchProviderInterception.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif

struct HelpHistoryEntry_Impl
{
    String  aURL;
    com::sun::star::uno::Any    aViewData;

    HelpHistoryEntry_Impl( const String& rURL, const com::sun::star::uno::Any& rViewData ) :
        aURL( rURL ), aViewData(rViewData) {}
};

DECLARE_LIST(HelpHistoryList_Impl,HelpHistoryEntry_Impl*)

class SfxHelpWindow_Impl;
class HelpInterceptor_Impl : public ::cppu::WeakImplHelper3<

        ::com::sun::star::frame::XDispatchProviderInterceptor,
        ::com::sun::star::frame::XInterceptorInfo,
        ::com::sun::star::frame::XDispatch >

{
private:
friend class HelpDispatch_Impl;
friend class SfxHelpWindow_Impl;

    // the component which's dispatches we're intercepting
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > m_xIntercepted;

    // chaining
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xSlaveDispatcher;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xMasterDispatcher;

    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener > m_xListener;

    HelpHistoryList_Impl*       m_pHistory;
    SfxHelpWindow_Impl*         m_pWindow;
    ULONG                       m_nCurPos;
    String                      m_aCurrentURL;
    com::sun::star::uno::Any    m_aViewData;

    void                        addURL( const String& rURL );

public:
    HelpInterceptor_Impl();
    ~HelpInterceptor_Impl();

    void                    setInterception( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame );
    void                    SetStartURL( const String& rURL );
    String                  GetCurrentURL() const { return m_aCurrentURL; }

    const com::sun::star::uno::Any&     GetViewData()const {return m_aViewData;}

    sal_Bool                HasHistoryPred() const;     // is there a predecessor for the current in the history
    sal_Bool                HasHistorySucc() const;     // is there a successor for the current in the history

    // XDispatchProvider
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL
                            queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL
                            queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw(::com::sun::star::uno::RuntimeException);

    // XDispatchProviderInterceptor
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL
                            getSlaveDispatchProvider(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlave ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL
                            getMasterDispatchProvider(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMaster ) throw(::com::sun::star::uno::RuntimeException);

    // XInterceptorInfo
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
                            getInterceptedURLs(  ) throw(::com::sun::star::uno::RuntimeException);

    // XDispatch
    virtual void SAL_CALL   dispatch( const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   addStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, const ::com::sun::star::util::URL& aURL ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   removeStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, const ::com::sun::star::util::URL& aURL ) throw(::com::sun::star::uno::RuntimeException);

    // extras
    void                    InitWaiter( SfxHelpWindow_Impl* pWindow )
                                { m_pWindow = pWindow; }
    SfxHelpWindow_Impl*     GetHelpWindow() const { return m_pWindow; }
};

// HelpListener_Impl -----------------------------------------------------

class HelpListener_Impl : public ::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener >
{
private:
    HelpInterceptor_Impl*   pInterceptor;
    Link                    aChangeLink;
    String                  aFactory;

public:
    HelpListener_Impl( HelpInterceptor_Impl* pInter );

    virtual void SAL_CALL   statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event )
                                throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL   disposing( const ::com::sun::star::lang::EventObject& obj )
                                throw( ::com::sun::star::uno::RuntimeException );

    void                    SetChangeHdl( const Link& rLink ) { aChangeLink = rLink; }
    String                  GetFactory() const { return aFactory; }
};
// HelpStatusListener_Impl -----------------------------------------------------

class HelpStatusListener_Impl : public
::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener >
{
private:
    ::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatch > xDispatch;
    ::com::sun::star::frame::FeatureStateEvent                              aStateEvent;

public:
    HelpStatusListener_Impl(
        ::com::sun::star::uno::Reference < ::com::sun::star::frame::XDispatch > xDispatch,
        com::sun::star::util::URL& rURL);
    ~HelpStatusListener_Impl();

    virtual void SAL_CALL   statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event )
                                throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL   disposing( const ::com::sun::star::lang::EventObject& obj )
                                throw( ::com::sun::star::uno::RuntimeException );
    const ::com::sun::star::frame::FeatureStateEvent&
                            GetStateEvent() const {return aStateEvent;}
};

#endif // #ifndef INCLUDED_SFX_HELPINTERCEPTOR_HXX

<|endoftext|>


<commit_before>#include "PoiActionRunner.h"

PoiActionRunner::PoiActionRunner(PoiTimer& ptimer, LogLevel logLevel) :
  _currentAction(NO_ACTION), _currentSyncId(0), _currentScene(0),
  _imageCache(_flashMemory.getSizeOfImageSection(), logLevel),
  _playHandler(_imageCache), _fadeHandler(_imageCache),
  _progHandler(_playHandler, _flashMemory, logLevel),
  _animationHandler(_imageCache),
  _ptimer(ptimer), _logLevel(logLevel)
{}

void PoiActionRunner::clearImageMap(){
  _imageCache.clearImageMap();
}

void PoiActionRunner::setup(){
  // Create semaphore to inform us when the timer has fired
  _timerSemaphore = xSemaphoreCreateBinary();
  _imageCache.clearImageMap();
  _flashMemory.setup(_logLevel, _imageCache.getRawImageData());
  _progHandler.setup(); // load program
  _updateSceneFromFlash(0); // load scene 0 into flash
}

/**********************
  * Utility functions *
  *********************/

void PoiActionRunner::_display(rgbVal* frame){
    ws2812_setColors(N_PIXELS, frame);
}

void PoiActionRunner::_displayRegister(uint8_t registerId){
    ws2812_setColors(N_PIXELS, _imageCache.getRegister(registerId));
}

/****************************
  * External action methods *
  ***************************/

void PoiActionRunner::initializeFlash(){
    _imageCache.clearImageMap();
    _flashMemory.initializeFlash(_logLevel, _imageCache.getRawImageData());
}

void PoiActionRunner::setPixel(uint8_t scene_idx, uint8_t frame_idx, uint8_t pixel_idx,
    uint8_t r, uint8_t g, uint8_t b){
  // TODO: possibly handle cases in which scene_idx changes
  _currentScene = scene_idx;
  _imageCache.setPixel(frame_idx, pixel_idx, r, g, b);
}

void PoiActionRunner::saveScene(uint8_t scene){
  if (_logLevel != MUTE) printf("Saving image of scene %d to flash.\n", _currentScene);
  if (_flashMemory.saveImage(scene, _imageCache.getRawImageData())){
    _currentScene = scene;
    if (_logLevel != MUTE) printf("Image of scene %d saved to flash.\n", _currentScene);
  }
  else {
    printf("Error saving scene %d to flash.", _currentScene);
  }
}

// load scene from flash into memory
void PoiActionRunner::_updateSceneFromFlash(uint8_t scene){
  if (_flashMemory.loadImage(scene, _imageCache.getRawImageData())){
    _currentScene = scene;
    if (_logLevel != MUTE) printf("Scene %d loaded from Flash.\n", _currentScene);
  }
  else{
    printf("Error. Cannot load scene %d\n", scene);
  }
}

void PoiActionRunner::showStaticFrame(uint8_t scene, uint8_t frame, uint8_t timeOutMSB, uint8_t timeOutLSB){
  _currentAction = SHOW_STATIC_FRAME;
  _updateSceneFromFlash(scene);
  uint8_t timeout = (uint16_t)timeOutMSB *256 + timeOutLSB;
  if (_logLevel != MUTE)  printf("Play static frame: %d timeout: %d \n", frame, timeout);
  _imageCache.copyFrameToRegister(0, frame);

  // play initial frame right away
  _ptimer.disable();
  _displayRegister(0);
  _ptimer.setIntervalAndEnable( timeout );
}

void PoiActionRunner::playScene(uint8_t scene, uint8_t startFrame, uint8_t endFrame, uint8_t speed, uint8_t loops){
  _currentAction = PLAY_DIRECT;
  if (scene != _currentScene){
    _updateSceneFromFlash(scene);
    _currentScene = scene;
  }
  _playHandler.init(startFrame, endFrame, speed, loops);
  if (_logLevel != MUTE) _playHandler.printInfo();

  // play initial frame right away
  _ptimer.disable();
  _display(_playHandler.getDisplayFrame());
  _ptimer.setIntervalAndEnable( _playHandler.getDelayMs() );
}

void PoiActionRunner::showStaticRgb(uint8_t r, uint8_t g, uint8_t b, uint8_t nLeds) {
  // directly "play" out of register
  _imageCache.fillRegister(0, makeRGBVal(r,g,b), nLeds);

  _currentAction = SHOW_STATIC_RGB;
  _ptimer.disable();
  _displayRegister(0);
}

void PoiActionRunner::displayOff() {
  showStaticRgb(0,0,0);
}

void PoiActionRunner::fadeToBlack(uint8_t fadeMSB, uint8_t fadeLSB){

  uint16_t fadeTime = (uint16_t)fadeMSB * 256 + fadeLSB;

  if (fadeTime < MIN_FADE_TIME){
  	displayOff();
      return;
  }

  _currentAction = FADE_TO_BLACK;
  _fadeHandler.init(fadeTime);
  if (_logLevel != MUTE) _fadeHandler.printInfo();

  _ptimer.disable();
  _display(_fadeHandler.getDisplayFrame());
  _ptimer.setIntervalAndEnable( _fadeHandler.getDelayMs() );
}

void PoiActionRunner::playWorm(Color color, uint8_t registerLength, uint8_t numLoops, bool synchronous){

  _currentAction = ANIMATION_WORM;
  uint16_t delayMs = 25;
  _animationHandler.init(ANIMATIONTYPE_WORM, registerLength, numLoops, color, delayMs);

  if (_logLevel != MUTE)  {
    printf("Play Worm Animation: Color %d Len: %d delay: %d \n",
    color, registerLength, delayMs);
    _animationHandler.printInfo();
  }

  // play initial state of register right away
  _ptimer.disable();
  _display(_animationHandler.getDisplayFrame());

  if (synchronous){
    while (true){
      _animationHandler.next();
      if (!_animationHandler.isActive()){
        break;
      }
      _display(_animationHandler.getDisplayFrame());
      delay(delayMs);
    }
    displayOff();
    _currentAction = NO_ACTION;
  }
  else {
    _ptimer.setIntervalAndEnable( delayMs );
  }
}

void PoiActionRunner::displayIp(uint8_t ipIncrement, bool withStaticBackground){
  // set back the ip led to black
  _imageCache.clearRegister(0);
  if (withStaticBackground){
    rgbVal paleWhite = makeRGBVal(8,8,8);
    _imageCache.fillRegister(0, paleWhite, N_POIS);
  }
  rgbVal* reg0 =  _imageCache.getRegister(0);
    // display colored led (first one less bright for each)
  uint8_t b = 64;
  if (ipIncrement %2 == 0){
    b=8;
  }
  rgbVal color =  makeRGBValue(RED, b);
  switch(ipIncrement/2){
    case 1:
    color =  makeRGBValue(GREEN, b);
    break;

    case 2:
    color =  makeRGBValue(BLUE, b);
    break;

    case 3:
    color =  makeRGBValue(YELLOW, b);
    break;

    case 4:
    color =  makeRGBValue(LILA, b);
    break;
  }
  reg0[ipIncrement]= color;

  _displayRegister(0);
}

/****************************
  * Program related methods *
  ***************************/

void PoiActionRunner::addCmdToProgram(unsigned char cmd[7]){
  _progHandler.addCmdToProgram(cmd);
}

void PoiActionRunner::startProg(){
  _currentAction = PLAY_PROG;
  if (!_progHandler.checkProgram()){
    return;
  }
  _progHandler.init();
  if (_logLevel != MUTE) _progHandler.printInfo();

  // play initial frame right away
  _ptimer.disable();
  _display((_progHandler.getDisplayFrame());
  _ptimer.setIntervalAndEnable( _progHandler.getDelayMs() );
}

void PoiActionRunner::pauseProg(){
  _currentAction = PAUSE_PROG;
  if (_logLevel != MUTE) printf("Program paused.\n" );
}

void PoiActionRunner::pauseAction(){
  _currentAction = PAUSE_PROG;
  if (_logLevel != MUTE) printf("Action paused.\n" );
}

void PoiActionRunner::jumptoSync(uint8_t syncId){
  if (syncId == 0){
    _currentSyncId++;
    _progHandler.syncNow(_currentSyncId);
  }
  else {
    _progHandler.syncNow(syncId);
  }
}

void PoiActionRunner::continueProg() {
  _currentAction = PLAY_PROG;
  if (_logLevel != MUTE) printf("Program continuing.\n" );
}

bool PoiActionRunner::isProgramActive(){
  return _progHandler.isActive();
}

uint8_t PoiActionRunner::getIpIncrement(){
  uint8_t ipIncrement = 0;
  _flashMemory.loadIpIncrement(&ipIncrement);
  return ipIncrement;
}

void PoiActionRunner::saveIpIncrement(uint8_t ipIncrement){
  _flashMemory.saveIpIncrement(ipIncrement);
}

/*******************************
  * Interrupt & State handling *
  ******************************/

// no printf in interrupt!
void IRAM_ATTR PoiActionRunner::onInterrupt(){

  if (_currentAction != NO_ACTION){
    //Serial.println("play next frame");
    // Give a semaphore that we can check in the loop
    xSemaphoreGiveFromISR(_timerSemaphore, NULL);
  }
}

void PoiActionRunner::loop(){

  float factor = 1;

  if (xSemaphoreTake(_timerSemaphore, 0) == pdTRUE){
    switch(_currentAction){

      case PLAY_DIRECT:
      _playHandler.next();
      if (_logLevel == CHATTY) _playHandler.printState();
      if (_playHandler.isActive()){
        _display(_playHandler.getDisplayFrame());
      }
      else {
        _currentAction = NO_ACTION;
        if (_logLevel != MUTE) printf("End of program PLAY_DIRECT.\n");
      }
      break;

      case PLAY_PROG:
      if (!_progHandler.checkProgram()){
        _currentAction = NO_ACTION;
        return;
      }
      _progHandler.next();

      if (_progHandler.isActive()){
        // check and update scene and interval if changed
        if (_progHandler.hasDelayChanged()) {
          _ptimer.disable();
        }
        uint8_t scene = _progHandler.getCurrentScene();
        if (scene != _currentScene){
          _updateSceneFromFlash(scene);
          _currentScene = scene;
        }
        // finally display the frame
        _display(_progHandler.getDisplayFrame());
        if (_progHandler.hasDelayChanged()) {
          _ptimer.setIntervalAndEnable( _progHandler.getDelayMs() ); }
      }
      else {
        _currentAction = NO_ACTION;
        if (_logLevel != MUTE) printf("End of program PLAY_PROG.\n");
      }
      break;

      case SHOW_STATIC_FRAME:
      // reached timeout
      _currentAction = NO_ACTION;
      if (_logLevel != MUTE) printf("Timeout of SHOW_STATIC_FRAME reached.\n");
      break;

      case FADE_TO_BLACK:
      _fadeHandler.next();
      if (_logLevel == CHATTY)  _fadeHandler.printState();
      if (_fadeHandler.isActive()){
        _display(_fadeHandler.getDisplayFrame());
      }
      else {
        _currentAction = NO_ACTION;
        if (_logLevel != MUTE) printf("End of program FADE_TO_BLACK.\n");
      }
      break;

      case ANIMATION_WORM:
      _animationHandler.next();
      if (_logLevel == CHATTY)  _animationHandler.printState();
      _display(_animationHandler.getDisplayFrame()); // regardless whether it is active
      if (!_animationHandler.isActive()){
        _currentAction = NO_ACTION;
        if (_logLevel != MUTE) printf("End of program ANIMATION_WORM.\n");
      }
      break;

      case NO_ACTION:
      case PAUSE_PROG:
      // do nothing
      break;

      default:
      break;
    }
  }
}
<commit_msg>small typo<commit_after>#include "PoiActionRunner.h"

PoiActionRunner::PoiActionRunner(PoiTimer& ptimer, LogLevel logLevel) :
  _currentAction(NO_ACTION), _currentSyncId(0), _currentScene(0),
  _imageCache(_flashMemory.getSizeOfImageSection(), logLevel),
  _playHandler(_imageCache), _fadeHandler(_imageCache),
  _progHandler(_playHandler, _flashMemory, logLevel),
  _animationHandler(_imageCache),
  _ptimer(ptimer), _logLevel(logLevel)
{}

void PoiActionRunner::clearImageMap(){
  _imageCache.clearImageMap();
}

void PoiActionRunner::setup(){
  // Create semaphore to inform us when the timer has fired
  _timerSemaphore = xSemaphoreCreateBinary();
  _imageCache.clearImageMap();
  _flashMemory.setup(_logLevel, _imageCache.getRawImageData());
  _progHandler.setup(); // load program
  _updateSceneFromFlash(0); // load scene 0 into flash
}

/**********************
  * Utility functions *
  *********************/

void PoiActionRunner::_display(rgbVal* frame){
    ws2812_setColors(N_PIXELS, frame);
}

void PoiActionRunner::_displayRegister(uint8_t registerId){
    ws2812_setColors(N_PIXELS, _imageCache.getRegister(registerId));
}

/****************************
  * External action methods *
  ***************************/

void PoiActionRunner::initializeFlash(){
    _imageCache.clearImageMap();
    _flashMemory.initializeFlash(_logLevel, _imageCache.getRawImageData());
}

void PoiActionRunner::setPixel(uint8_t scene_idx, uint8_t frame_idx, uint8_t pixel_idx,
    uint8_t r, uint8_t g, uint8_t b){
  // TODO: possibly handle cases in which scene_idx changes
  _currentScene = scene_idx;
  _imageCache.setPixel(frame_idx, pixel_idx, r, g, b);
}

void PoiActionRunner::saveScene(uint8_t scene){
  if (_logLevel != MUTE) printf("Saving image of scene %d to flash.\n", _currentScene);
  if (_flashMemory.saveImage(scene, _imageCache.getRawImageData())){
    _currentScene = scene;
    if (_logLevel != MUTE) printf("Image of scene %d saved to flash.\n", _currentScene);
  }
  else {
    printf("Error saving scene %d to flash.", _currentScene);
  }
}

// load scene from flash into memory
void PoiActionRunner::_updateSceneFromFlash(uint8_t scene){
  if (_flashMemory.loadImage(scene, _imageCache.getRawImageData())){
    _currentScene = scene;
    if (_logLevel != MUTE) printf("Scene %d loaded from Flash.\n", _currentScene);
  }
  else{
    printf("Error. Cannot load scene %d\n", scene);
  }
}

void PoiActionRunner::showStaticFrame(uint8_t scene, uint8_t frame, uint8_t timeOutMSB, uint8_t timeOutLSB){
  _currentAction = SHOW_STATIC_FRAME;
  _updateSceneFromFlash(scene);
  uint8_t timeout = (uint16_t)timeOutMSB *256 + timeOutLSB;
  if (_logLevel != MUTE)  printf("Play static frame: %d timeout: %d \n", frame, timeout);
  _imageCache.copyFrameToRegister(0, frame);

  // play initial frame right away
  _ptimer.disable();
  _displayRegister(0);
  _ptimer.setIntervalAndEnable( timeout );
}

void PoiActionRunner::playScene(uint8_t scene, uint8_t startFrame, uint8_t endFrame, uint8_t speed, uint8_t loops){
  _currentAction = PLAY_DIRECT;
  if (scene != _currentScene){
    _updateSceneFromFlash(scene);
    _currentScene = scene;
  }
  _playHandler.init(startFrame, endFrame, speed, loops);
  if (_logLevel != MUTE) _playHandler.printInfo();

  // play initial frame right away
  _ptimer.disable();
  _display(_playHandler.getDisplayFrame());
  _ptimer.setIntervalAndEnable( _playHandler.getDelayMs() );
}

void PoiActionRunner::showStaticRgb(uint8_t r, uint8_t g, uint8_t b, uint8_t nLeds) {
  // directly "play" out of register
  _imageCache.fillRegister(0, makeRGBVal(r,g,b), nLeds);

  _currentAction = SHOW_STATIC_RGB;
  _ptimer.disable();
  _displayRegister(0);
}

void PoiActionRunner::displayOff() {
  showStaticRgb(0,0,0);
}

void PoiActionRunner::fadeToBlack(uint8_t fadeMSB, uint8_t fadeLSB){

  uint16_t fadeTime = (uint16_t)fadeMSB * 256 + fadeLSB;

  if (fadeTime < MIN_FADE_TIME){
  	displayOff();
      return;
  }

  _currentAction = FADE_TO_BLACK;
  _fadeHandler.init(fadeTime);
  if (_logLevel != MUTE) _fadeHandler.printInfo();

  _ptimer.disable();
  _display(_fadeHandler.getDisplayFrame());
  _ptimer.setIntervalAndEnable( _fadeHandler.getDelayMs() );
}

void PoiActionRunner::playWorm(Color color, uint8_t registerLength, uint8_t numLoops, bool synchronous){

  _currentAction = ANIMATION_WORM;
  uint16_t delayMs = 25;
  _animationHandler.init(ANIMATIONTYPE_WORM, registerLength, numLoops, color, delayMs);

  if (_logLevel != MUTE)  {
    printf("Play Worm Animation: Color %d Len: %d delay: %d \n",
    color, registerLength, delayMs);
    _animationHandler.printInfo();
  }

  // play initial state of register right away
  _ptimer.disable();
  _display(_animationHandler.getDisplayFrame());

  if (synchronous){
    while (true){
      _animationHandler.next();
      if (!_animationHandler.isActive()){
        break;
      }
      _display(_animationHandler.getDisplayFrame());
      delay(delayMs);
    }
    displayOff();
    _currentAction = NO_ACTION;
  }
  else {
    _ptimer.setIntervalAndEnable( delayMs );
  }
}

void PoiActionRunner::displayIp(uint8_t ipIncrement, bool withStaticBackground){
  // set back the ip led to black
  _imageCache.clearRegister(0);
  if (withStaticBackground){
    rgbVal paleWhite = makeRGBVal(8,8,8);
    _imageCache.fillRegister(0, paleWhite, N_POIS);
  }
  rgbVal* reg0 =  _imageCache.getRegister(0);
    // display colored led (first one less bright for each)
  uint8_t b = 64;
  if (ipIncrement %2 == 0){
    b=8;
  }
  rgbVal color =  makeRGBValue(RED, b);
  switch(ipIncrement/2){
    case 1:
    color =  makeRGBValue(GREEN, b);
    break;

    case 2:
    color =  makeRGBValue(BLUE, b);
    break;

    case 3:
    color =  makeRGBValue(YELLOW, b);
    break;

    case 4:
    color =  makeRGBValue(LILA, b);
    break;
  }
  reg0[ipIncrement]= color;

  _displayRegister(0);
}

/****************************
  * Program related methods *
  ***************************/

void PoiActionRunner::addCmdToProgram(unsigned char cmd[7]){
  _progHandler.addCmdToProgram(cmd);
}

void PoiActionRunner::startProg(){
  _currentAction = PLAY_PROG;
  if (!_progHandler.checkProgram()){
    return;
  }
  _progHandler.init();
  if (_logLevel != MUTE) _progHandler.printInfo();

  // play initial frame right away
  _ptimer.disable();
  _display(_progHandler.getDisplayFrame());
  _ptimer.setIntervalAndEnable( _progHandler.getDelayMs() );
}

void PoiActionRunner::pauseProg(){
  _currentAction = PAUSE_PROG;
  if (_logLevel != MUTE) printf("Program paused.\n" );
}

void PoiActionRunner::pauseAction(){
  _currentAction = PAUSE_PROG;
  if (_logLevel != MUTE) printf("Action paused.\n" );
}

void PoiActionRunner::jumptoSync(uint8_t syncId){
  if (syncId == 0){
    _currentSyncId++;
    _progHandler.syncNow(_currentSyncId);
  }
  else {
    _progHandler.syncNow(syncId);
  }
}

void PoiActionRunner::continueProg() {
  _currentAction = PLAY_PROG;
  if (_logLevel != MUTE) printf("Program continuing.\n" );
}

bool PoiActionRunner::isProgramActive(){
  return _progHandler.isActive();
}

uint8_t PoiActionRunner::getIpIncrement(){
  uint8_t ipIncrement = 0;
  _flashMemory.loadIpIncrement(&ipIncrement);
  return ipIncrement;
}

void PoiActionRunner::saveIpIncrement(uint8_t ipIncrement){
  _flashMemory.saveIpIncrement(ipIncrement);
}

/*******************************
  * Interrupt & State handling *
  ******************************/

// no printf in interrupt!
void IRAM_ATTR PoiActionRunner::onInterrupt(){

  if (_currentAction != NO_ACTION){
    //Serial.println("play next frame");
    // Give a semaphore that we can check in the loop
    xSemaphoreGiveFromISR(_timerSemaphore, NULL);
  }
}

void PoiActionRunner::loop(){

  float factor = 1;

  if (xSemaphoreTake(_timerSemaphore, 0) == pdTRUE){
    switch(_currentAction){

      case PLAY_DIRECT:
      _playHandler.next();
      if (_logLevel == CHATTY) _playHandler.printState();
      if (_playHandler.isActive()){
        _display(_playHandler.getDisplayFrame());
      }
      else {
        _currentAction = NO_ACTION;
        if (_logLevel != MUTE) printf("End of program PLAY_DIRECT.\n");
      }
      break;

      case PLAY_PROG:
      if (!_progHandler.checkProgram()){
        _currentAction = NO_ACTION;
        return;
      }
      _progHandler.next();

      if (_progHandler.isActive()){
        // check and update scene and interval if changed
        if (_progHandler.hasDelayChanged()) {
          _ptimer.disable();
        }
        uint8_t scene = _progHandler.getCurrentScene();
        if (scene != _currentScene){
          _updateSceneFromFlash(scene);
          _currentScene = scene;
        }
        // finally display the frame
        _display(_progHandler.getDisplayFrame());
        if (_progHandler.hasDelayChanged()) {
          _ptimer.setIntervalAndEnable( _progHandler.getDelayMs() ); }
      }
      else {
        _currentAction = NO_ACTION;
        if (_logLevel != MUTE) printf("End of program PLAY_PROG.\n");
      }
      break;

      case SHOW_STATIC_FRAME:
      // reached timeout
      _currentAction = NO_ACTION;
      if (_logLevel != MUTE) printf("Timeout of SHOW_STATIC_FRAME reached.\n");
      break;

      case FADE_TO_BLACK:
      _fadeHandler.next();
      if (_logLevel == CHATTY)  _fadeHandler.printState();
      if (_fadeHandler.isActive()){
        _display(_fadeHandler.getDisplayFrame());
      }
      else {
        _currentAction = NO_ACTION;
        if (_logLevel != MUTE) printf("End of program FADE_TO_BLACK.\n");
      }
      break;

      case ANIMATION_WORM:
      _animationHandler.next();
      if (_logLevel == CHATTY)  _animationHandler.printState();
      _display(_animationHandler.getDisplayFrame()); // regardless whether it is active
      if (!_animationHandler.isActive()){
        _currentAction = NO_ACTION;
        if (_logLevel != MUTE) printf("End of program ANIMATION_WORM.\n");
      }
      break;

      case NO_ACTION:
      case PAUSE_PROG:
      // do nothing
      break;

      default:
      break;
    }
  }
}
<|endoftext|>


<commit_before>/*
 * File: src/commonpp/thread/Thread.cpp
 * Part of commonpp.
 *
 * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2015 Thomas Sanchez.  All rights reserved.
 *
 */
#include "commonpp/thread/Thread.hpp"

#include "commonpp/core/config.hpp"

#if HAVE_HWLOC == 1
# include "detail/Cores.hpp"
#endif

#if HAVE_SYS_PRCTL_H
# include <sys/prctl.h>
# include <cerrno>
# include <cstring>
#endif

#include <thread>
#include <sstream>

#ifndef HAVE_THREAD_LOCAL_SPECIFIER
# include <boost/thread/tss.hpp>
#endif

#include "commonpp/core/LoggingInterface.hpp"

namespace commonpp
{
namespace thread
{

CREATE_LOGGER(thread_logger, "commonpp::thread");

#if HAVE_THREAD_LOCAL_SPECIFIER
static thread_local std::string current_name;
#else
static boost::thread_specific_ptr<std::string> current_name;
#endif

void set_current_thread_name(const std::string& name)
{
#if HAVE_THREAD_LOCAL_SPECIFIER
    current_name = name;
#else
    current_name.reset(new std::string(name));
#endif

#if defined(HAVE_SYS_PRCTL_H)
    auto short_thread_name = name.substr(0, 15);
    if (prctl(PR_SET_NAME, short_thread_name.c_str()))
    {
        LOG(thread_logger, warning)
            << "Cannot set the custom thread name: " << short_thread_name
            << ", errno: " << errno << ", msg: " << strerror(errno);
    }
#endif
}

const std::string& get_current_thread_name()
{
#if HAVE_THREAD_LOCAL_SPECIFIER
    if (!current_name.empty())
    {
        return current_name;
    }
#else
    if (current_name.get())
    {
        return *current_name;
    }
#endif

    std::ostringstream out;
    out << std::this_thread::get_id();
    set_current_thread_name(out.str());

    return get_current_thread_name();
}

#if HAVE_HWLOC == 1
int get_nb_physical_core()
{
    return detail::Cores(detail::Cores::PHYSICAL).cores();
}

int get_nb_logical_core()
{
    return detail::Cores(detail::Cores::ALL).cores();
}

bool set_affinity_to_physical_core(int core)
{
    return detail::Cores(detail::Cores::PHYSICAL)[core].bind();
}

bool set_affinity_to_logical_core(int core)
{
    return detail::Cores(detail::Cores::PHYSICAL)[core].bind();
}

bool set_affinity_to_physical_core(int core, std::thread& th)
{
    return detail::Cores(detail::Cores::PHYSICAL)[core].bind(th);
}

bool set_affinity_to_logical_core(int core, std::thread& th)
{
    return detail::Cores(detail::Cores::PHYSICAL)[core].bind(th);
}
#else
int get_nb_physical_core()
{
    return -1;
}
int get_nb_logical_core()
{
    return -1;
}

bool set_affinity_to_physical_core(int core)
{
    return false;
}
bool set_affinity_to_logical_core(int core)
{
    return false;
}
bool set_affinity_to_physical_core(int core, std::thread&)
{
    return false;
}
bool set_affinity_to_logical_core(int core, std::thread&)
{
    return false
}

#endif

} // namespace thread
} // namespace httpp
<commit_msg>Fix compilation<commit_after>/*
 * File: src/commonpp/thread/Thread.cpp
 * Part of commonpp.
 *
 * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2015 Thomas Sanchez.  All rights reserved.
 *
 */
#include "commonpp/thread/Thread.hpp"

#include "commonpp/core/config.hpp"

#if HAVE_HWLOC == 1
# include "detail/Cores.hpp"
#endif

#if HAVE_SYS_PRCTL_H
# include <sys/prctl.h>
# include <cerrno>
# include <cstring>
#endif

#include <thread>
#include <sstream>

#ifndef HAVE_THREAD_LOCAL_SPECIFIER
# include <boost/thread/tss.hpp>
#endif

#include "commonpp/core/LoggingInterface.hpp"

namespace commonpp
{
namespace thread
{

CREATE_LOGGER(thread_logger, "commonpp::thread");

#if HAVE_THREAD_LOCAL_SPECIFIER
static thread_local std::string current_name;
#else
static boost::thread_specific_ptr<std::string> current_name;
#endif

void set_current_thread_name(const std::string& name)
{
#if HAVE_THREAD_LOCAL_SPECIFIER
    current_name = name;
#else
    current_name.reset(new std::string(name));
#endif

#if defined(HAVE_SYS_PRCTL_H)
    auto short_thread_name = name.substr(0, 15);
    if (prctl(PR_SET_NAME, short_thread_name.c_str()))
    {
        LOG(thread_logger, warning)
            << "Cannot set the custom thread name: " << short_thread_name
            << ", errno: " << errno << ", msg: " << strerror(errno);
    }
#endif
}

const std::string& get_current_thread_name()
{
#if HAVE_THREAD_LOCAL_SPECIFIER
    if (!current_name.empty())
    {
        return current_name;
    }
#else
    if (current_name.get())
    {
        return *current_name;
    }
#endif

    std::ostringstream out;
    out << std::this_thread::get_id();
    set_current_thread_name(out.str());

    return get_current_thread_name();
}

#if HAVE_HWLOC == 1
int get_nb_physical_core()
{
    return detail::Cores(detail::Cores::PHYSICAL).cores();
}

int get_nb_logical_core()
{
    return detail::Cores(detail::Cores::ALL).cores();
}

bool set_affinity_to_physical_core(int core)
{
    return detail::Cores(detail::Cores::PHYSICAL)[core].bind();
}

bool set_affinity_to_logical_core(int core)
{
    return detail::Cores(detail::Cores::PHYSICAL)[core].bind();
}

bool set_affinity_to_physical_core(int core, std::thread& th)
{
    return detail::Cores(detail::Cores::PHYSICAL)[core].bind(th);
}

bool set_affinity_to_logical_core(int core, std::thread& th)
{
    return detail::Cores(detail::Cores::PHYSICAL)[core].bind(th);
}
#else
int get_nb_physical_core()
{
    return -1;
}

int get_nb_logical_core()
{
    return -1;
}

bool set_affinity_to_physical_core(int core)
{
    return false;
}

bool set_affinity_to_logical_core(int core)
{
    return false;
}

bool set_affinity_to_physical_core(int core, std::thread&)
{
    return false;
}

bool set_affinity_to_logical_core(int core, std::thread&)
{
    return false;
}
#endif

} // namespace thread
} // namespace httpp
<|endoftext|>


<commit_before>// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
//    following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
//    and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/** \file blacs_grid.hpp
 *
 *  \brief Contains declaration and implementation of BLACS_grid class.
 */

#ifndef __BLACS_GRID_HPP__
#define __BLACS_GRID_HPP__

#include <memory>
#include "mpi_grid.hpp"
#include "linalg_base.hpp"

namespace sddk {

/// BLACS grid wrapper.
class BLACS_grid
{
  private:
    Communicator const& comm_;

    std::unique_ptr<MPI_grid> mpi_grid_;

    int num_ranks_row_;

    int num_ranks_col_;

    int rank_row_;

    int rank_col_;

    int blacs_handler_;

    int blacs_context_;

    /* forbid copy constructor */
    BLACS_grid(BLACS_grid const& src) = delete;
    /* forbid assigment operator */
    BLACS_grid& operator=(BLACS_grid const& src) = delete;

  public:
    BLACS_grid(Communicator const& comm__, int num_ranks_row__, int num_ranks_col__)
        : comm_(comm__)
        , num_ranks_row_(num_ranks_row__)
        , num_ranks_col_(num_ranks_col__)
        , blacs_handler_(-1)
        , blacs_context_(-1)
    {
        PROFILE("sddk::BLACS_grid::BLACS_grid");

        mpi_grid_ = std::unique_ptr<MPI_grid>(new MPI_grid({num_ranks_row__, num_ranks_col__}, comm_));

        rank_row_ = mpi_grid_->coordinate(0);
        rank_col_ = mpi_grid_->coordinate(1);

        #ifdef __SCALAPACK
        /* create handler first */
        blacs_handler_ = linalg_base::create_blacs_handler(mpi_grid_->communicator().mpi_comm());

        std::vector<int> map_ranks(num_ranks_row__ * num_ranks_col__);
        for (int j = 0; j < num_ranks_col__; j++) {
            for (int i = 0; i < num_ranks_row__; i++) {
                map_ranks[i + j * num_ranks_row__] = mpi_grid_->communicator().cart_rank({i, j});
            }
        }

        /* create context */
        blacs_context_ = blacs_handler_;
        linalg_base::gridmap(&blacs_context_, &map_ranks[0], num_ranks_row__, num_ranks_row__, num_ranks_col__);

        /* check the grid */
        int nrow1, ncol1, irow1, icol1;
        linalg_base::gridinfo(blacs_context_, &nrow1, &ncol1, &irow1, &icol1);

        if (rank_row_ != irow1 || rank_col_ != icol1 || num_ranks_row__ != nrow1 || num_ranks_col__ != ncol1) {
            std::stringstream s;
            s << "wrong grid" << std::endl
              << "            row | col | nrow | ncol " << std::endl
              << " mpi_grid " << rank_row_ << " " << rank_col_ << " " << num_ranks_row__ << " " << num_ranks_col__
              << std::endl
              << " blacs    " << irow1 << " " << icol1 << " " << nrow1 << " " << ncol1;
            TERMINATE(s);
        }
        #endif
    }

    ~BLACS_grid()
    {
        PROFILE("sddk::BLACS_grid::~BLACS_grid");

        #ifdef __SCALAPACK
        linalg_base::gridexit(blacs_context_);
        linalg_base::free_blacs_handler(blacs_handler_);
        #endif
    }

    inline int context() const
    {
        return blacs_context_;
    }

    inline Communicator const& comm() const
    {
        return comm_;
    }

    inline Communicator const& comm_row() const
    {
        return mpi_grid_->communicator(1 << 0);
    }

    inline Communicator const& comm_col() const
    {
        return mpi_grid_->communicator(1 << 1);
    }

    inline int num_ranks_row() const
    {
        return num_ranks_row_;
    }

    inline int rank_row() const
    {
        return rank_row_;
    }

    inline int num_ranks_col() const
    {
        return num_ranks_col_;
    }

    inline int rank_col() const
    {
        return rank_col_;
    }

    inline int cart_rank(int irow__, int icol__) const
    {
        return mpi_grid_->communicator().cart_rank({irow__, icol__});
    }

    MPI_grid const& mpi_grid() const
    {
        return *mpi_grid_;
    }
};

} // namespace sddk

#endif // __BLACS_GRID_HPP__
<commit_msg>default values<commit_after>// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
//    following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
//    and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/** \file blacs_grid.hpp
 *
 *  \brief Contains declaration and implementation of BLACS_grid class.
 */

#ifndef __BLACS_GRID_HPP__
#define __BLACS_GRID_HPP__

#include <memory>
#include "mpi_grid.hpp"
#include "linalg_base.hpp"

namespace sddk {

/// BLACS grid wrapper.
class BLACS_grid
{
  private:
    Communicator const& comm_;

    std::unique_ptr<MPI_grid> mpi_grid_;

    int num_ranks_row_{-1};

    int num_ranks_col_{-1};

    int rank_row_{-1};

    int rank_col_{-1};

    int blacs_handler_{-1};

    int blacs_context_{-1};

    /* forbid copy constructor */
    BLACS_grid(BLACS_grid const& src) = delete;
    /* forbid assigment operator */
    BLACS_grid& operator=(BLACS_grid const& src) = delete;

  public:
    BLACS_grid(Communicator const& comm__, int num_ranks_row__, int num_ranks_col__)
        : comm_(comm__)
        , num_ranks_row_(num_ranks_row__)
        , num_ranks_col_(num_ranks_col__)
    {
        PROFILE("sddk::BLACS_grid::BLACS_grid");

        mpi_grid_ = std::unique_ptr<MPI_grid>(new MPI_grid({num_ranks_row__, num_ranks_col__}, comm_));

        rank_row_ = mpi_grid_->coordinate(0);
        rank_col_ = mpi_grid_->coordinate(1);

        #ifdef __SCALAPACK
        /* create handler first */
        blacs_handler_ = linalg_base::create_blacs_handler(mpi_grid_->communicator().mpi_comm());

        std::vector<int> map_ranks(num_ranks_row__ * num_ranks_col__);
        for (int j = 0; j < num_ranks_col__; j++) {
            for (int i = 0; i < num_ranks_row__; i++) {
                map_ranks[i + j * num_ranks_row__] = mpi_grid_->communicator().cart_rank({i, j});
            }
        }

        /* create context */
        blacs_context_ = blacs_handler_;
        linalg_base::gridmap(&blacs_context_, &map_ranks[0], num_ranks_row__, num_ranks_row__, num_ranks_col__);

        /* check the grid */
        int nrow1, ncol1, irow1, icol1;
        linalg_base::gridinfo(blacs_context_, &nrow1, &ncol1, &irow1, &icol1);

        if (rank_row_ != irow1 || rank_col_ != icol1 || num_ranks_row__ != nrow1 || num_ranks_col__ != ncol1) {
            std::stringstream s;
            s << "wrong grid" << std::endl
              << "            row | col | nrow | ncol " << std::endl
              << " mpi_grid " << rank_row_ << " " << rank_col_ << " " << num_ranks_row__ << " " << num_ranks_col__
              << std::endl
              << " blacs    " << irow1 << " " << icol1 << " " << nrow1 << " " << ncol1;
            TERMINATE(s);
        }
        #endif
    }

    ~BLACS_grid()
    {
        PROFILE("sddk::BLACS_grid::~BLACS_grid");

        #ifdef __SCALAPACK
        linalg_base::gridexit(blacs_context_);
        linalg_base::free_blacs_handler(blacs_handler_);
        #endif
    }

    inline int context() const
    {
        return blacs_context_;
    }

    inline Communicator const& comm() const
    {
        return comm_;
    }

    inline Communicator const& comm_row() const
    {
        return mpi_grid_->communicator(1 << 0);
    }

    inline Communicator const& comm_col() const
    {
        return mpi_grid_->communicator(1 << 1);
    }

    inline int num_ranks_row() const
    {
        return num_ranks_row_;
    }

    inline int rank_row() const
    {
        return rank_row_;
    }

    inline int num_ranks_col() const
    {
        return num_ranks_col_;
    }

    inline int rank_col() const
    {
        return rank_col_;
    }

    inline int cart_rank(int irow__, int icol__) const
    {
        return mpi_grid_->communicator().cart_rank({irow__, icol__});
    }

    MPI_grid const& mpi_grid() const
    {
        return *mpi_grid_;
    }
};

} // namespace sddk

#endif // __BLACS_GRID_HPP__
<|endoftext|>


<commit_before>/* Copyright 2018 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/kernels/eigen_support.h"

#include <utility>

#include "tensorflow/lite/arena_planner.h"
#include "tensorflow/lite/kernels/internal/optimized/eigen_spatial_convolutions.h"
#include "tensorflow/lite/kernels/op_macros.h"

namespace tflite {
namespace eigen_support {
namespace {

#ifndef EIGEN_DONT_ALIGN
// Eigen may require buffers to be algiend to 16, 32 or 64 bytes depending on
// hardware architecture and build configurations.
// If the static assertion fails, try to increase `kDefaultTensorAlignment` to
// in `arena_planner.h` to 32 or 64.
static_assert(
    kDefaultTensorAlignment % EIGEN_MAX_ALIGN_BYTES == 0,
    "kDefaultArenaAlignment doesn't comply with Eigen alignment requirement.");
#endif  // EIGEN_DONT_ALIGN

// Helper routine for updating the global Eigen thread count used for OpenMP.
void SetEigenNbThreads(int threads) {
#if defined(EIGEN_HAS_OPENMP)
  // The global Eigen thread count is only used when OpenMP is enabled. As this
  // call causes problems with tsan, make it only when OpenMP is available.
  Eigen::setNbThreads(context->recommended_num_threads);
#endif  // defined(EIGEN_HAS_OPENMP)
}

// We have a single global threadpool for all convolution operations. This means
// that inferences started from different threads may block each other, but
// since the underlying resource of CPU cores should be consumed by the
// operations anyway, it shouldn't affect overall performance.
class EigenThreadPoolWrapper : public Eigen::ThreadPoolInterface {
 public:
  // Takes ownership of 'pool'
  explicit EigenThreadPoolWrapper(Eigen::ThreadPool* pool) : pool_(pool) {}
  ~EigenThreadPoolWrapper() override {}

  void Schedule(std::function<void()> fn) override {
    pool_->Schedule(std::move(fn));
  }
  int NumThreads() const override { return pool_->NumThreads(); }
  int CurrentThreadId() const override { return pool_->CurrentThreadId(); }

 private:
  std::unique_ptr<Eigen::ThreadPool> pool_;
};

struct RefCountedEigenContext : public TfLiteExternalContext {
  std::unique_ptr<Eigen::ThreadPoolInterface> thread_pool_wrapper;
  std::unique_ptr<Eigen::ThreadPoolDevice> device;
  int num_references = 0;
};

RefCountedEigenContext* GetEigenContext(TfLiteContext* context) {
  return reinterpret_cast<RefCountedEigenContext*>(
      context->GetExternalContext(context, kTfLiteEigenContext));
}

void InitDevice(TfLiteContext* context, RefCountedEigenContext* ptr) {
  int num_threads = 4;
  if (context->recommended_num_threads != -1) {
    num_threads = context->recommended_num_threads;
  }
  ptr->device.reset();  // destroy before we invalidate the thread pool
  ptr->thread_pool_wrapper.reset(
      new EigenThreadPoolWrapper(new Eigen::ThreadPool(num_threads)));
  ptr->device.reset(
      new Eigen::ThreadPoolDevice(ptr->thread_pool_wrapper.get(), num_threads));
}

TfLiteStatus Refresh(TfLiteContext* context) {
  SetEigenNbThreads(context->recommended_num_threads);

  auto* ptr = GetEigenContext(context);
  if (ptr != nullptr) {
    InitDevice(context, ptr);
  }

  return kTfLiteOk;
}

}  // namespace

void IncrementUsageCounter(TfLiteContext* context) {
  auto* ptr = GetEigenContext(context);
  if (ptr == nullptr) {
    if (context->recommended_num_threads != -1) {
      SetEigenNbThreads(context->recommended_num_threads);
    }
    ptr = new RefCountedEigenContext;
    ptr->type = kTfLiteEigenContext;
    ptr->Refresh = Refresh;
    ptr->num_references = 0;
    InitDevice(context, ptr);
    context->SetExternalContext(context, kTfLiteEigenContext, ptr);
  }
  ptr->num_references++;
}

void DecrementUsageCounter(TfLiteContext* context) {
  auto* ptr = GetEigenContext(context);
  if (ptr == nullptr) {
    TF_LITE_FATAL(
        "Call to DecrementUsageCounter() not preceded by "
        "IncrementUsageCounter()");
  }
  if (--ptr->num_references == 0) {
    delete ptr;
    context->SetExternalContext(context, kTfLiteEigenContext, nullptr);
  }
}

const Eigen::ThreadPoolDevice* GetThreadPoolDevice(TfLiteContext* context) {
  auto* ptr = GetEigenContext(context);
  if (ptr == nullptr) {
    TF_LITE_FATAL(
        "Call to GetFromContext() not preceded by IncrementUsageCounter()");
  }
  return ptr->device.get();
}

}  // namespace eigen_support
}  // namespace tflite
<commit_msg>[OpenMP] Fix undeclared identifier in eigen_support.cc<commit_after>/* Copyright 2018 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/kernels/eigen_support.h"

#include <utility>

#include "tensorflow/lite/arena_planner.h"
#include "tensorflow/lite/kernels/internal/optimized/eigen_spatial_convolutions.h"
#include "tensorflow/lite/kernels/op_macros.h"

namespace tflite {
namespace eigen_support {
namespace {

#ifndef EIGEN_DONT_ALIGN
// Eigen may require buffers to be algiend to 16, 32 or 64 bytes depending on
// hardware architecture and build configurations.
// If the static assertion fails, try to increase `kDefaultTensorAlignment` to
// in `arena_planner.h` to 32 or 64.
static_assert(
    kDefaultTensorAlignment % EIGEN_MAX_ALIGN_BYTES == 0,
    "kDefaultArenaAlignment doesn't comply with Eigen alignment requirement.");
#endif  // EIGEN_DONT_ALIGN

// Helper routine for updating the global Eigen thread count used for OpenMP.
void SetEigenNbThreads(int threads) {
#if defined(EIGEN_HAS_OPENMP)
  // The global Eigen thread count is only used when OpenMP is enabled. As this
  // call causes problems with tsan, make it only when OpenMP is available.
  Eigen::setNbThreads(threads);
#endif  // defined(EIGEN_HAS_OPENMP)
}

// We have a single global threadpool for all convolution operations. This means
// that inferences started from different threads may block each other, but
// since the underlying resource of CPU cores should be consumed by the
// operations anyway, it shouldn't affect overall performance.
class EigenThreadPoolWrapper : public Eigen::ThreadPoolInterface {
 public:
  // Takes ownership of 'pool'
  explicit EigenThreadPoolWrapper(Eigen::ThreadPool* pool) : pool_(pool) {}
  ~EigenThreadPoolWrapper() override {}

  void Schedule(std::function<void()> fn) override {
    pool_->Schedule(std::move(fn));
  }
  int NumThreads() const override { return pool_->NumThreads(); }
  int CurrentThreadId() const override { return pool_->CurrentThreadId(); }

 private:
  std::unique_ptr<Eigen::ThreadPool> pool_;
};

struct RefCountedEigenContext : public TfLiteExternalContext {
  std::unique_ptr<Eigen::ThreadPoolInterface> thread_pool_wrapper;
  std::unique_ptr<Eigen::ThreadPoolDevice> device;
  int num_references = 0;
};

RefCountedEigenContext* GetEigenContext(TfLiteContext* context) {
  return reinterpret_cast<RefCountedEigenContext*>(
      context->GetExternalContext(context, kTfLiteEigenContext));
}

void InitDevice(TfLiteContext* context, RefCountedEigenContext* ptr) {
  int num_threads = 4;
  if (context->recommended_num_threads != -1) {
    num_threads = context->recommended_num_threads;
  }
  ptr->device.reset();  // destroy before we invalidate the thread pool
  ptr->thread_pool_wrapper.reset(
      new EigenThreadPoolWrapper(new Eigen::ThreadPool(num_threads)));
  ptr->device.reset(
      new Eigen::ThreadPoolDevice(ptr->thread_pool_wrapper.get(), num_threads));
}

TfLiteStatus Refresh(TfLiteContext* context) {
  SetEigenNbThreads(context->recommended_num_threads);

  auto* ptr = GetEigenContext(context);
  if (ptr != nullptr) {
    InitDevice(context, ptr);
  }

  return kTfLiteOk;
}

}  // namespace

void IncrementUsageCounter(TfLiteContext* context) {
  auto* ptr = GetEigenContext(context);
  if (ptr == nullptr) {
    if (context->recommended_num_threads != -1) {
      SetEigenNbThreads(context->recommended_num_threads);
    }
    ptr = new RefCountedEigenContext;
    ptr->type = kTfLiteEigenContext;
    ptr->Refresh = Refresh;
    ptr->num_references = 0;
    InitDevice(context, ptr);
    context->SetExternalContext(context, kTfLiteEigenContext, ptr);
  }
  ptr->num_references++;
}

void DecrementUsageCounter(TfLiteContext* context) {
  auto* ptr = GetEigenContext(context);
  if (ptr == nullptr) {
    TF_LITE_FATAL(
        "Call to DecrementUsageCounter() not preceded by "
        "IncrementUsageCounter()");
  }
  if (--ptr->num_references == 0) {
    delete ptr;
    context->SetExternalContext(context, kTfLiteEigenContext, nullptr);
  }
}

const Eigen::ThreadPoolDevice* GetThreadPoolDevice(TfLiteContext* context) {
  auto* ptr = GetEigenContext(context);
  if (ptr == nullptr) {
    TF_LITE_FATAL(
        "Call to GetFromContext() not preceded by IncrementUsageCounter()");
  }
  return ptr->device.get();
}

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