<commit_before>// Copyright © 2013,2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>

#include <type_traits>

#include <boost/multi_array.hpp>
#include <nix/NDSize.hpp>
#include <nix/DataType.hpp>

#ifndef NIX_HYDRA_H
#define NIX_HYDRA_H

namespace nix {

class InvalidRankException : public std::runtime_error {
public:
    InvalidRankException(const std::string &message)
        : std::runtime_error(message) { }
};

template<typename T>
struct data_traits {

    typedef T                 value_type;
    typedef value_type&       reference;
    typedef const value_type& const_reference;

    typedef T        element_type;
    typedef T*       element_pointer;
    typedef const T* const_element_pointer;

    static DataType data_type(const_reference value) {
        return to_data_type<element_type>::value;
    }

    static NDSize shape(const_reference value) {
        return NDSize();
    }

    static size_t num_elements(const_reference value) {
        return 1;
    }

    static const_element_pointer get_data(const_reference value) {
        return &value;
    }

    static element_pointer get_data(reference value) {
        return &value;
    }

    static void resize(reference value, const NDSize &dims) {
        if (dims.size() != 0) {
            throw InvalidRankException("Cannot resize scalar");
        }
    }

};

template<typename T, size_t N>
class data_traits<T[N]> {
public:

    typedef T                  value_type[N];
    typedef value_type&        reference;
    typedef const value_type&  const_reference;

    typedef T        element_type;
    typedef T*       element_pointer;
    typedef const T* const_element_pointer;

    static DataType data_type(const_reference val) {
        return to_data_type<element_type>::value;
    }

    static NDSize shape(const_reference value) {
        return NDSize{N};
    }

    static size_t num_elements(const_reference value) {
        return N;
    }

    static const_element_pointer get_data(const value_type& value) {
        return value;
    }

    static element_pointer get_data(value_type &value) {
        return value;
    }

    static void resize(reference value, const NDSize &dims) {
        if (dims.size() != 1 || dims[0] != N) {
            throw InvalidRankException("Cannot resize native arrays");
        }
        //NOOP
    }
};

template<typename T, size_t M, size_t N>
class data_traits<T[M][N]> {
public:

    typedef T                 value_type[M][N];
    typedef value_type&       reference;
    typedef const value_type& const_reference;

    typedef T        element_type;
    typedef T*       element_pointer;
    typedef const T* const_element_pointer;

    static DataType data_type(const_reference val) {
        return to_data_type<element_type>::value;
    }

    static NDSize shape(const_reference value) {
        return NDSize{M, N};
    }

    static size_t num_elements(const_reference value) {
        return M*N;
    }

    static const_element_pointer get_data(const value_type& value) {
        return value[0];
    }

    static element_pointer get_data(value_type &value) {
        return value[0];
    }

    static void resize(reference value, const NDSize &dims) {
        if (dims.size() != 2 || dims[0] != M || dims[1] != N) {
            throw InvalidRankException("Cannot resize native arrays");
        }
        //NOOP
    }
};

template<typename T>
class data_traits<std::vector<T>> {
public:

    typedef std::vector<T>     value_type;
    typedef value_type&        reference;
    typedef const value_type&  const_reference;

    typedef T        element_type;
    typedef T*       element_pointer;
    typedef const T* const_element_pointer;

    static DataType data_type(const_reference val) {
        return to_data_type<element_type>::value;
    }

    static NDSize shape(const_reference value) {
        return NDSize{value.size()};
    }

    static size_t num_elements(const_reference value) {
        return value.size();
    }

    static const_element_pointer get_data(const_reference value) {
        return &value[0];
    }

    static element_pointer get_data(value_type &value) {
        return &value[0];
    }

    static void resize(reference value, const NDSize &dims) {

        if (dims.size() != 1) {
            throw InvalidRankException("Cannot change rank of vector"); //FIXME
        }

        if (dims[0] == value.size())
            return;

        value.resize(dims[0]);
    }
};

template<typename T, size_t N>
class data_traits<boost::multi_array<T, N> > {
public:

    typedef boost::multi_array<T, N> value_type;
    typedef value_type&              reference;
    typedef const value_type&        const_reference;

    typedef T        element_type;
    typedef T*       element_pointer;
    typedef const T* const_element_pointer;

    static DataType data_type(const_reference val) {
        return to_data_type<element_type>::value;
    }

    static NDSize shape(const value_type &value) {
        NDSize ndsize(N);
        const size_t *ma_shape = value.shape();
        std::transform(ma_shape, ma_shape + N, ndsize.data(),
                       [](NDSize::const_reference val){ return static_cast<T>(val);});
        return ndsize;
    }

    static size_t num_elements(const_reference value) {
        return  value.num_elements();;
    }

    static const_element_pointer get_data(const value_type& value) {
        return value.data();
    }

    static element_pointer get_data(value_type &value) {
        return value.data();
    }

    static void resize(reference value, const NDSize &dims) {
        if (dims.size() != N) {
            throw InvalidRankException("Cannot change rank of multiarray");
        }

        value.resize(dims);
    }
};

/* *** */
/* new interface */
// DataWriter for wirting to, i.e. reading from disk: non-const types */
template<typename T, typename ElementType>
class DataWriter {
public:
    typedef data_traits<T>  data_traits_t;
    typedef ElementType     data_type;
    typedef data_type      *data_ptr;

    DataWriter(T &val) : value(val) {}

    data_ptr begin() { return data_traits_t::get_data(value); }
    void finish() { }

private:
    T &value;
};

template<typename T>
class DataWriter<T, std::string> {
public:
    typedef data_traits<T>  data_traits_t;
    typedef char           *data_type;
    typedef data_type      *data_ptr;

    DataWriter(T &val) : value(val) {
        size_t nelms = data_traits_t::num_elements(value);
        data = new data_type[nelms];
    }

    data_ptr begin() {
        return data;
    }

    void finish() {
        size_t nelms = data_traits_t::num_elements(value);
        auto vptr = data_traits_t::get_data(value);

        for (size_t i = 0; i < nelms; i++) {
            vptr[i] = data[i];
        }
    }

    ~DataWriter() {
        delete[] data;
    }

private:
    T        &value;
    data_ptr  data;
};

template <typename T, typename ElementType>
class DataReader {
public:
    typedef data_traits<T>        data_traits_t;
    typedef const ElementType     data_type;
    typedef data_type            *data_ptr;

    DataReader(const T &val) : value(val) {}

    data_ptr begin() const { return data_traits_t::get_data(value); }
    void finish() const { }

private:
    const T &value;
};

template<typename T>
class DataReader<T, std::string> {
public:
    typedef data_traits<T>   data_traits_t;
    typedef char const      *data_type;
    typedef data_type       *data_ptr;

    DataReader(const T &val) : value(val) {
        size_t nelms = data_traits_t::num_elements(value);
        data = new data_type[nelms];
        auto vptr = data_traits_t::get_data(value);

        for (size_t i = 0; i < nelms; i++) {
            data[i] = vptr[i].c_str();
        }
    }

    data_ptr begin() const { return data; }

    void finish() const { }

    ~DataReader() {
        delete[] data;
    }

private:
    const T  &value;
    data_ptr  data;
};

template<typename T>
class Hydra {
public:
    typedef T                                    value_type;
    typedef T&                                   reference;
    typedef typename std::remove_const<T>::type  vanilla_type;
    typedef data_traits<vanilla_type>            data_traits_t;
    typedef typename data_traits_t::element_type element_t;

    static const bool vtype_is_const = std::is_const<T>::value;

    typedef       DataWriter<vanilla_type, element_t> writer_t;
    typedef const DataReader<vanilla_type, element_t> reader_t;

    Hydra(reference value_ref) : value(value_ref) {
        static_assert(to_data_type<element_t>::is_valid,
                      "Hydra cannot handle this type");
    }

    DataType element_data_type() const {
        return data_traits<vanilla_type>::data_type(value);
    }

    NDSize shape() const {
        return data_traits<vanilla_type>::shape(value);
    }

    writer_t writer() {
        return writer_t(value);
    }

    reader_t reader() const {
        return reader_t(value);
    }

private:
    reference value;
};

} //::nix

#endif

<commit_msg>Hydra: Add resize method<commit_after>// Copyright © 2013,2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>

#include <type_traits>

#include <boost/multi_array.hpp>
#include <nix/NDSize.hpp>
#include <nix/DataType.hpp>

#ifndef NIX_HYDRA_H
#define NIX_HYDRA_H

namespace nix {

class InvalidRankException : public std::runtime_error {
public:
    InvalidRankException(const std::string &message)
        : std::runtime_error(message) { }
};

template<typename T>
struct data_traits {

    typedef T                 value_type;
    typedef value_type&       reference;
    typedef const value_type& const_reference;

    typedef T        element_type;
    typedef T*       element_pointer;
    typedef const T* const_element_pointer;

    static DataType data_type(const_reference value) {
        return to_data_type<element_type>::value;
    }

    static NDSize shape(const_reference value) {
        return NDSize();
    }

    static size_t num_elements(const_reference value) {
        return 1;
    }

    static const_element_pointer get_data(const_reference value) {
        return &value;
    }

    static element_pointer get_data(reference value) {
        return &value;
    }

    static void resize(reference value, const NDSize &dims) {
        if (dims.size() != 0) {
            throw InvalidRankException("Cannot resize scalar");
        }
    }

};

template<typename T, size_t N>
class data_traits<T[N]> {
public:

    typedef T                  value_type[N];
    typedef value_type&        reference;
    typedef const value_type&  const_reference;

    typedef T        element_type;
    typedef T*       element_pointer;
    typedef const T* const_element_pointer;

    static DataType data_type(const_reference val) {
        return to_data_type<element_type>::value;
    }

    static NDSize shape(const_reference value) {
        return NDSize{N};
    }

    static size_t num_elements(const_reference value) {
        return N;
    }

    static const_element_pointer get_data(const value_type& value) {
        return value;
    }

    static element_pointer get_data(value_type &value) {
        return value;
    }

    static void resize(reference value, const NDSize &dims) {
        if (dims.size() != 1 || dims[0] != N) {
            throw InvalidRankException("Cannot resize native arrays");
        }
        //NOOP
    }
};

template<typename T, size_t M, size_t N>
class data_traits<T[M][N]> {
public:

    typedef T                 value_type[M][N];
    typedef value_type&       reference;
    typedef const value_type& const_reference;

    typedef T        element_type;
    typedef T*       element_pointer;
    typedef const T* const_element_pointer;

    static DataType data_type(const_reference val) {
        return to_data_type<element_type>::value;
    }

    static NDSize shape(const_reference value) {
        return NDSize{M, N};
    }

    static size_t num_elements(const_reference value) {
        return M*N;
    }

    static const_element_pointer get_data(const value_type& value) {
        return value[0];
    }

    static element_pointer get_data(value_type &value) {
        return value[0];
    }

    static void resize(reference value, const NDSize &dims) {
        if (dims.size() != 2 || dims[0] != M || dims[1] != N) {
            throw InvalidRankException("Cannot resize native arrays");
        }
        //NOOP
    }
};

template<typename T>
class data_traits<std::vector<T>> {
public:

    typedef std::vector<T>     value_type;
    typedef value_type&        reference;
    typedef const value_type&  const_reference;

    typedef T        element_type;
    typedef T*       element_pointer;
    typedef const T* const_element_pointer;

    static DataType data_type(const_reference val) {
        return to_data_type<element_type>::value;
    }

    static NDSize shape(const_reference value) {
        return NDSize{value.size()};
    }

    static size_t num_elements(const_reference value) {
        return value.size();
    }

    static const_element_pointer get_data(const_reference value) {
        return &value[0];
    }

    static element_pointer get_data(value_type &value) {
        return &value[0];
    }

    static void resize(reference value, const NDSize &dims) {

        if (dims.size() != 1) {
            throw InvalidRankException("Cannot change rank of vector"); //FIXME
        }

        if (dims[0] == value.size())
            return;

        value.resize(dims[0]);
    }
};

template<typename T, size_t N>
class data_traits<boost::multi_array<T, N> > {
public:

    typedef boost::multi_array<T, N> value_type;
    typedef value_type&              reference;
    typedef const value_type&        const_reference;

    typedef T        element_type;
    typedef T*       element_pointer;
    typedef const T* const_element_pointer;

    static DataType data_type(const_reference val) {
        return to_data_type<element_type>::value;
    }

    static NDSize shape(const value_type &value) {
        NDSize ndsize(N);
        const size_t *ma_shape = value.shape();
        std::transform(ma_shape, ma_shape + N, ndsize.data(),
                       [](NDSize::const_reference val){ return static_cast<T>(val);});
        return ndsize;
    }

    static size_t num_elements(const_reference value) {
        return  value.num_elements();;
    }

    static const_element_pointer get_data(const value_type& value) {
        return value.data();
    }

    static element_pointer get_data(value_type &value) {
        return value.data();
    }

    static void resize(reference value, const NDSize &dims) {
        if (dims.size() != N) {
            throw InvalidRankException("Cannot change rank of multiarray");
        }

        value.resize(dims);
    }
};

/* *** */
/* new interface */
// DataWriter for wirting to, i.e. reading from disk: non-const types */
template<typename T, typename ElementType>
class DataWriter {
public:
    typedef data_traits<T>  data_traits_t;
    typedef ElementType     data_type;
    typedef data_type      *data_ptr;

    DataWriter(T &val) : value(val) {}

    data_ptr begin() { return data_traits_t::get_data(value); }
    void finish() { }

private:
    T &value;
};

template<typename T>
class DataWriter<T, std::string> {
public:
    typedef data_traits<T>  data_traits_t;
    typedef char           *data_type;
    typedef data_type      *data_ptr;

    DataWriter(T &val) : value(val) {
        size_t nelms = data_traits_t::num_elements(value);
        data = new data_type[nelms];
    }

    data_ptr begin() {
        return data;
    }

    void finish() {
        size_t nelms = data_traits_t::num_elements(value);
        auto vptr = data_traits_t::get_data(value);

        for (size_t i = 0; i < nelms; i++) {
            vptr[i] = data[i];
        }
    }

    ~DataWriter() {
        delete[] data;
    }

private:
    T        &value;
    data_ptr  data;
};

template <typename T, typename ElementType>
class DataReader {
public:
    typedef data_traits<T>        data_traits_t;
    typedef const ElementType     data_type;
    typedef data_type            *data_ptr;

    DataReader(const T &val) : value(val) {}

    data_ptr begin() const { return data_traits_t::get_data(value); }
    void finish() const { }

private:
    const T &value;
};

template<typename T>
class DataReader<T, std::string> {
public:
    typedef data_traits<T>   data_traits_t;
    typedef char const      *data_type;
    typedef data_type       *data_ptr;

    DataReader(const T &val) : value(val) {
        size_t nelms = data_traits_t::num_elements(value);
        data = new data_type[nelms];
        auto vptr = data_traits_t::get_data(value);

        for (size_t i = 0; i < nelms; i++) {
            data[i] = vptr[i].c_str();
        }
    }

    data_ptr begin() const { return data; }

    void finish() const { }

    ~DataReader() {
        delete[] data;
    }

private:
    const T  &value;
    data_ptr  data;
};

template<typename T>
class Hydra {
public:
    typedef T                                    value_type;
    typedef T&                                   reference;
    typedef typename std::remove_const<T>::type  vanilla_type;
    typedef data_traits<vanilla_type>            data_traits_t;
    typedef typename data_traits_t::element_type element_t;

    static const bool vtype_is_const = std::is_const<T>::value;

    typedef       DataWriter<vanilla_type, element_t> writer_t;
    typedef const DataReader<vanilla_type, element_t> reader_t;

    Hydra(reference value_ref) : value(value_ref) {
        static_assert(to_data_type<element_t>::is_valid,
                      "Hydra cannot handle this type");
    }

    DataType element_data_type() const {
        return data_traits<vanilla_type>::data_type(value);
    }

    NDSize shape() const {
        return data_traits<vanilla_type>::shape(value);
    }

    void resize(const NDSize &new_shape) {
        data_traits<vanilla_type>::resize(value, new_shape);
    }

    writer_t writer() {
        return writer_t(value);
    }

    reader_t reader() const {
        return reader_t(value);
    }

private:
    reference value;
};

} //::nix

#endif

<|endoftext|>


<commit_before>/*
   (c) Copyright 2000-2002  convergence integrated media GmbH.
   (c) Copyright 2002       convergence GmbH.

   All rights reserved.

   Written by Denis Oliver Kropp <dok@directfb.org>,
              Andreas Hundt <andi@fischlustig.de> and
              Sven Neumann <sven@convergence.de>.

   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.

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

extern "C" {
#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <malloc.h>

#include <directfb.h>

#include <media/idirectfbvideoprovider.h>

#include <core/coredefs.h>
#include <core/coretypes.h>

#include <core/state.h>
#include <core/gfxcard.h>
#include <core/layers.h>
#include <core/surfaces.h>

#include <display/idirectfbsurface.h>

#include <direct/interface.h>
#include <direct/mem.h>

#include <misc/util.h>

static DFBResult
Probe( IDirectFBVideoProvider_ProbeContext *ctx );

static DFBResult
Construct( IDirectFBVideoProvider *thiz,
           const char             *filename );

#include <direct/interface_implementation.h>

DIRECT_INTERFACE_IMPLEMENTATION( IDirectFBVideoProvider, AviFile )

}

/*
 * This is only for C++ to use our C constructor.
 */
static class Foo { public: Foo() {} } foo;

#include <aviplay.h>
#include <fourcc.h>

/*
 * private data struct of IDirectFBVideoProvider
 */
typedef struct {
     int               ref;       /* reference counter */
     IAviPlayer       *player;

     IDirectFBSurface *destination;
     DFBRectangle      dest_rect;
     DVFrameCallback   callback;
     void             *ctx;

     CardState         state;
     CoreSurface      *source;
} IDirectFBVideoProvider_AviFile_data;

static void IDirectFBVideoProvider_AviFile_Destruct(
                                                 IDirectFBVideoProvider *thiz )
{
     IDirectFBVideoProvider_AviFile_data *data;

     data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;

     if (data->player->IsPlaying())
          data->player->Stop();

     delete data->player;

     if (data->destination) {
          data->destination->Release( data->destination );
          data->destination = NULL;     /* FIXME: remove listener */
     }

     dfb_surface_unref( data->source );

     DIRECT_DEALLOCATE_INTERFACE( thiz );
}

static DFBResult IDirectFBVideoProvider_AviFile_AddRef(
                                                 IDirectFBVideoProvider *thiz )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     data->ref++;

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_Release(
                                                 IDirectFBVideoProvider *thiz )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (--data->ref == 0) {
          IDirectFBVideoProvider_AviFile_Destruct( thiz );
     }

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_GetCapabilities(
                                           IDirectFBVideoProvider       *thiz,
                                           DFBVideoProviderCapabilities *caps )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!caps)
          return DFB_INVARG;

     *caps = (DFBVideoProviderCapabilities) ( DVCAPS_BASIC |
                                              DVCAPS_SCALE |
                                              DVCAPS_SEEK );

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_GetSurfaceDescription(
                                                 IDirectFBVideoProvider *thiz,
                                                 DFBSurfaceDescription  *desc )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!desc)
          return DFB_INVARG;

     desc->flags = (DFBSurfaceDescriptionFlags)
          (DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT);
     desc->width  = data->player->GetWidth();
     desc->height = data->player->GetHeight();
     desc->pixelformat = dfb_primary_layer_pixelformat();

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_PlayTo(
                                           IDirectFBVideoProvider *thiz,
                                           IDirectFBSurface       *destination,
                                           const DFBRectangle     *dstrect,
                                           DVFrameCallback         callback,
                                           void                   *ctx )
{
     DFBRectangle           rect;
     IDirectFBSurface_data *dst_data;

     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!destination)
        return DFB_INVARG;

     dst_data = (IDirectFBSurface_data*)destination->priv;

     if (!dst_data)
          return DFB_DEAD;

     /* URGENT: keep in sync with DrawCallback */

     switch (dst_data->surface->format) {
          case DSPF_YUY2:
               data->source->format = DSPF_YUY2;
               if (data->player->SetColorSpace( fccYUY2, 0 ))
                    return DFB_UNSUPPORTED;
               break;
          case DSPF_UYVY:
               data->source->format = DSPF_UYVY;
               if (data->player->SetColorSpace( fccUYVY, 0 ))
                    return DFB_UNSUPPORTED;
               break;
          default:
               data->source->format = DSPF_RGB16;
               data->player->SetColorSpace( 0, 0 );
               break;
     }

     /* build the destination rectangle */
     if (dstrect) {
          if (dstrect->w < 1  ||  dstrect->h < 1)
               return DFB_INVARG;

          rect = *dstrect;

          rect.x += dst_data->area.wanted.x;
          rect.y += dst_data->area.wanted.y;
     }
     else
          rect = dst_data->area.wanted;

     /* save for later blitting operation */
     data->dest_rect = rect;

     /* build the clip rectangle */
     if (!dfb_rectangle_intersect( &rect, &dst_data->area.current ))
          return DFB_INVARG;

     /* put the destination clip into the state */
     data->state.clip.x1 = rect.x;
     data->state.clip.y1 = rect.y;
     data->state.clip.x2 = rect.x + rect.w - 1;
     data->state.clip.y2 = rect.y + rect.h - 1;
     data->state.destination = dst_data->surface;
     data->state.modified = (StateModificationFlags)
                            (data->state.modified | SMF_CLIP | SMF_DESTINATION);

     if (data->destination) {
          data->destination->Release( data->destination );
          data->destination = NULL;     /* FIXME: remove listener */
     }

     destination->AddRef( destination );
     data->destination = destination;   /* FIXME: install listener */

     data->callback = callback;
     data->ctx = ctx;

     switch (data->player->GetState( NULL )) {
          case IAviPlayer::Playing:
               break;
          case IAviPlayer::Paused:
               data->player->Pause(false);
               break;
          default:
               data->player->Start();
     }

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_Stop(
                                                 IDirectFBVideoProvider *thiz )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (data->player->IsPlaying())
          data->player->Pause(true);

     if (data->destination) {
          data->destination->Release( data->destination );
          data->destination = NULL;     /* FIXME: remove listener */
     }

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_SeekTo(
                                               IDirectFBVideoProvider *thiz,
                                               double                  seconds)
{
     double curpos;

     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     curpos = data->player->GetPos();
     data->player->Reseek( seconds );
     /* seeking forward for some small amount may actually bring us
      * _back_ to the last key frame -> compensate via PageUp()
      */
     if (seconds > curpos && curpos > data->player->GetPos())
       data->player->PageUp();

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_GetPos(
     IDirectFBVideoProvider *thiz,
     double                 *seconds)
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!seconds)
        return DFB_INVARG;

     *seconds = data->player->GetPos();

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_GetLength(
     IDirectFBVideoProvider *thiz,
     double                 *seconds)
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!seconds)
        return DFB_INVARG;

     *seconds = data->player->GetVideoLength();

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_GetColorAdjustment(
                                                  IDirectFBVideoProvider *thiz,
                                                  DFBColorAdjustment     *adj )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!adj)
          return DFB_INVARG;

     return DFB_UNIMPLEMENTED;
}

static DFBResult IDirectFBVideoProvider_AviFile_SetColorAdjustment( IDirectFBVideoProvider   *thiz,
                                                                    const DFBColorAdjustment *adj )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!adj)
          return DFB_INVARG;

     return DFB_UNIMPLEMENTED;
}

static void AviFile_KillCallback( int bogus, void *p )
{
  /* AviFile_KillCallback gets called when AviFile->Stop is called.
     At the moment we do nothing here...

     IDirectFBVideoProvider_AviFile_data *data =
          (IDirectFBVideoProvider_AviFile_data*)p;
   */
}

static void AviFile_DrawCallback( const CImage *image, void *p )
{
     IDirectFBVideoProvider_AviFile_data *data =
          (IDirectFBVideoProvider_AviFile_data*)p;

     data->source->front_buffer->system.addr   = (void*)(image->Data());
     data->source->front_buffer->system.pitch  = image->Bpl();

     DFBRectangle rect = { 0, 0, image->Width(), image->Height() };

     if (rect.w == data->dest_rect.w  &&  rect.h == data->dest_rect.h) {
          dfb_gfxcard_blit( &rect, data->dest_rect.x,
                            data->dest_rect.y, &data->state );
     }
     else {
          DFBRectangle drect = data->dest_rect;

          dfb_gfxcard_stretchblit( &rect, &drect, &data->state );
     }

     if (data->callback)
          data->callback( data->ctx );
}

/* exported symbols */

extern "C" {

static DFBResult
Probe( IDirectFBVideoProvider_ProbeContext *ctx )
{
     if (strstr( ctx->filename, ".avi" ) ||
         strstr( ctx->filename, ".AVI" ) ||
         strstr( ctx->filename, ".asf" ) ||
         strstr( ctx->filename, ".ASF" ))
          return DFB_OK;

     return DFB_UNSUPPORTED;
}

static DFBResult
Construct( IDirectFBVideoProvider *thiz, const char *filename )
{
     DFBResult ret;

     DIRECT_ALLOCATE_INTERFACE_DATA(thiz, IDirectFBVideoProvider_AviFile)

     data->ref = 1;

     try {
          data->player = CreateAviPlayer( filename, 16 /* FIXME */ );

          data->player->SetDrawCallback2( AviFile_DrawCallback, data );
          data->player->SetKillHandler( AviFile_KillCallback, data );
     }
     catch (FatalError e) {
          ERRORMSG( "DirectFB/AviFile: CreateAviPlayer failed: %s\n",
                    e.GetDesc() );
          DIRECT_DEALLOCATE_INTERFACE( thiz );
          return DFB_FAILURE;
     }

     ret = dfb_surface_create_preallocated( data->player->GetWidth(),
                                            data->player->GetHeight(),
                                            DSPF_RGB16, CSP_SYSTEMONLY,
                                            DSCAPS_SYSTEMONLY, NULL,
                                            NULL, NULL, 0, 0, &data->source );
     if (ret) {
          delete data->player;
          DIRECT_DEALLOCATE_INTERFACE(thiz);
          return ret;
     }

     data->state.source   = data->source;
     data->state.modified = SMF_ALL;

     thiz->AddRef    = IDirectFBVideoProvider_AviFile_AddRef;
     thiz->Release   = IDirectFBVideoProvider_AviFile_Release;
     thiz->GetCapabilities = IDirectFBVideoProvider_AviFile_GetCapabilities;
     thiz->GetSurfaceDescription =
          IDirectFBVideoProvider_AviFile_GetSurfaceDescription;
     thiz->PlayTo    = IDirectFBVideoProvider_AviFile_PlayTo;
     thiz->Stop      = IDirectFBVideoProvider_AviFile_Stop;
     thiz->SeekTo    = IDirectFBVideoProvider_AviFile_SeekTo;
     thiz->GetPos    = IDirectFBVideoProvider_AviFile_GetPos;
     thiz->GetLength = IDirectFBVideoProvider_AviFile_GetLength;
     thiz->GetColorAdjustment =
          IDirectFBVideoProvider_AviFile_GetColorAdjustment;
     thiz->SetColorAdjustment =
          IDirectFBVideoProvider_AviFile_SetColorAdjustment;

     return DFB_OK;
}

}

<commit_msg>Avifile video provider compiles again.<commit_after>/*
   (c) Copyright 2000-2002  convergence integrated media GmbH.
   (c) Copyright 2002       convergence GmbH.

   All rights reserved.

   Written by Denis Oliver Kropp <dok@directfb.org>,
              Andreas Hundt <andi@fischlustig.de> and
              Sven Neumann <sven@convergence.de>.

   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.

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

extern "C" {
#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <malloc.h>

#include <directfb.h>

#include <media/idirectfbvideoprovider.h>

#include <core/coredefs.h>
#include <core/coretypes.h>

#include <core/state.h>
#include <core/gfxcard.h>
#include <core/layers.h>
#include <core/surfaces.h>

#include <display/idirectfbsurface.h>

#include <direct/messages.h>
#include <direct/interface.h>
#include <direct/mem.h>

#include <misc/util.h>

static DFBResult
Probe( IDirectFBVideoProvider_ProbeContext *ctx );

static DFBResult
Construct( IDirectFBVideoProvider *thiz,
           const char             *filename );

#include <direct/interface_implementation.h>

DIRECT_INTERFACE_IMPLEMENTATION( IDirectFBVideoProvider, AviFile )

}

/*
 * This is only for C++ to use our C constructor.
 */
static class Foo { public: Foo() {} } foo;

#include <aviplay.h>
#include <fourcc.h>

/*
 * private data struct of IDirectFBVideoProvider
 */
typedef struct {
     int               ref;       /* reference counter */
     IAviPlayer       *player;

     IDirectFBSurface *destination;
     DFBRectangle      dest_rect;
     DVFrameCallback   callback;
     void             *ctx;

     CardState         state;
     CoreSurface      *source;
} IDirectFBVideoProvider_AviFile_data;

static void IDirectFBVideoProvider_AviFile_Destruct(
                                                 IDirectFBVideoProvider *thiz )
{
     IDirectFBVideoProvider_AviFile_data *data;

     data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;

     if (data->player->IsPlaying())
          data->player->Stop();

     delete data->player;

     if (data->destination) {
          data->destination->Release( data->destination );
          data->destination = NULL;     /* FIXME: remove listener */
     }

     dfb_surface_unref( data->source );

     DIRECT_DEALLOCATE_INTERFACE( thiz );
}

static DFBResult IDirectFBVideoProvider_AviFile_AddRef(
                                                 IDirectFBVideoProvider *thiz )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     data->ref++;

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_Release(
                                                 IDirectFBVideoProvider *thiz )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (--data->ref == 0) {
          IDirectFBVideoProvider_AviFile_Destruct( thiz );
     }

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_GetCapabilities(
                                           IDirectFBVideoProvider       *thiz,
                                           DFBVideoProviderCapabilities *caps )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!caps)
          return DFB_INVARG;

     *caps = (DFBVideoProviderCapabilities) ( DVCAPS_BASIC |
                                              DVCAPS_SCALE |
                                              DVCAPS_SEEK );

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_GetSurfaceDescription(
                                                 IDirectFBVideoProvider *thiz,
                                                 DFBSurfaceDescription  *desc )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!desc)
          return DFB_INVARG;

     desc->flags = (DFBSurfaceDescriptionFlags)
          (DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT);
     desc->width  = data->player->GetWidth();
     desc->height = data->player->GetHeight();
     desc->pixelformat = dfb_primary_layer_pixelformat();

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_PlayTo(
                                           IDirectFBVideoProvider *thiz,
                                           IDirectFBSurface       *destination,
                                           const DFBRectangle     *dstrect,
                                           DVFrameCallback         callback,
                                           void                   *ctx )
{
     DFBRectangle           rect;
     IDirectFBSurface_data *dst_data;

     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!destination)
        return DFB_INVARG;

     dst_data = (IDirectFBSurface_data*)destination->priv;

     if (!dst_data)
          return DFB_DEAD;

     /* URGENT: keep in sync with DrawCallback */

     switch (dst_data->surface->format) {
          case DSPF_YUY2:
               data->source->format = DSPF_YUY2;
               if (data->player->SetColorSpace( fccYUY2, 0 ))
                    return DFB_UNSUPPORTED;
               break;
          case DSPF_UYVY:
               data->source->format = DSPF_UYVY;
               if (data->player->SetColorSpace( fccUYVY, 0 ))
                    return DFB_UNSUPPORTED;
               break;
          default:
               data->source->format = DSPF_RGB16;
               data->player->SetColorSpace( 0, 0 );
               break;
     }

     /* build the destination rectangle */
     if (dstrect) {
          if (dstrect->w < 1  ||  dstrect->h < 1)
               return DFB_INVARG;

          rect = *dstrect;

          rect.x += dst_data->area.wanted.x;
          rect.y += dst_data->area.wanted.y;
     }
     else
          rect = dst_data->area.wanted;

     /* save for later blitting operation */
     data->dest_rect = rect;

     /* build the clip rectangle */
     if (!dfb_rectangle_intersect( &rect, &dst_data->area.current ))
          return DFB_INVARG;

     /* put the destination clip into the state */
     data->state.clip.x1 = rect.x;
     data->state.clip.y1 = rect.y;
     data->state.clip.x2 = rect.x + rect.w - 1;
     data->state.clip.y2 = rect.y + rect.h - 1;
     data->state.destination = dst_data->surface;
     data->state.modified = (StateModificationFlags)
                            (data->state.modified | SMF_CLIP | SMF_DESTINATION);

     if (data->destination) {
          data->destination->Release( data->destination );
          data->destination = NULL;     /* FIXME: remove listener */
     }

     destination->AddRef( destination );
     data->destination = destination;   /* FIXME: install listener */

     data->callback = callback;
     data->ctx = ctx;

     switch (data->player->GetState( NULL )) {
          case IAviPlayer::Playing:
               break;
          case IAviPlayer::Paused:
               data->player->Pause(false);
               break;
          default:
               data->player->Start();
     }

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_Stop(
                                                 IDirectFBVideoProvider *thiz )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (data->player->IsPlaying())
          data->player->Pause(true);

     if (data->destination) {
          data->destination->Release( data->destination );
          data->destination = NULL;     /* FIXME: remove listener */
     }

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_SeekTo(
                                               IDirectFBVideoProvider *thiz,
                                               double                  seconds)
{
     double curpos;

     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     curpos = data->player->GetPos();
     data->player->Reseek( seconds );
     /* seeking forward for some small amount may actually bring us
      * _back_ to the last key frame -> compensate via PageUp()
      */
     if (seconds > curpos && curpos > data->player->GetPos())
       data->player->PageUp();

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_GetPos(
     IDirectFBVideoProvider *thiz,
     double                 *seconds)
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!seconds)
        return DFB_INVARG;

     *seconds = data->player->GetPos();

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_GetLength(
     IDirectFBVideoProvider *thiz,
     double                 *seconds)
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!seconds)
        return DFB_INVARG;

     *seconds = data->player->GetVideoLength();

     return DFB_OK;
}

static DFBResult IDirectFBVideoProvider_AviFile_GetColorAdjustment(
                                                  IDirectFBVideoProvider *thiz,
                                                  DFBColorAdjustment     *adj )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!adj)
          return DFB_INVARG;

     return DFB_UNIMPLEMENTED;
}

static DFBResult IDirectFBVideoProvider_AviFile_SetColorAdjustment( IDirectFBVideoProvider   *thiz,
                                                                    const DFBColorAdjustment *adj )
{
     DIRECT_INTERFACE_GET_DATA(IDirectFBVideoProvider_AviFile)

     if (!adj)
          return DFB_INVARG;

     return DFB_UNIMPLEMENTED;
}

static void AviFile_KillCallback( int bogus, void *p )
{
  /* AviFile_KillCallback gets called when AviFile->Stop is called.
     At the moment we do nothing here...

     IDirectFBVideoProvider_AviFile_data *data =
          (IDirectFBVideoProvider_AviFile_data*)p;
   */
}

static void AviFile_DrawCallback( const CImage *image, void *p )
{
     IDirectFBVideoProvider_AviFile_data *data =
          (IDirectFBVideoProvider_AviFile_data*)p;

     data->source->front_buffer->system.addr   = (void*)(image->Data());
     data->source->front_buffer->system.pitch  = image->Bpl();

     DFBRectangle rect = { 0, 0, image->Width(), image->Height() };

     if (rect.w == data->dest_rect.w  &&  rect.h == data->dest_rect.h) {
          dfb_gfxcard_blit( &rect, data->dest_rect.x,
                            data->dest_rect.y, &data->state );
     }
     else {
          DFBRectangle drect = data->dest_rect;

          dfb_gfxcard_stretchblit( &rect, &drect, &data->state );
     }

     if (data->callback)
          data->callback( data->ctx );
}

/* exported symbols */

extern "C" {

static DFBResult
Probe( IDirectFBVideoProvider_ProbeContext *ctx )
{
     if (strstr( ctx->filename, ".avi" ) ||
         strstr( ctx->filename, ".AVI" ) ||
         strstr( ctx->filename, ".asf" ) ||
         strstr( ctx->filename, ".ASF" ))
          return DFB_OK;

     return DFB_UNSUPPORTED;
}

static DFBResult
Construct( IDirectFBVideoProvider *thiz, const char *filename )
{
     DFBResult ret;

     DIRECT_ALLOCATE_INTERFACE_DATA(thiz, IDirectFBVideoProvider_AviFile)

     data->ref = 1;

     try {
          data->player = CreateAviPlayer( filename, 16 /* FIXME */ );

          data->player->SetDrawCallback2( AviFile_DrawCallback, data );
          data->player->SetKillHandler( AviFile_KillCallback, data );
     }
     catch (FatalError e) {
          D_ERROR( "DirectFB/AviFile: CreateAviPlayer failed: %s\n",
                    e.GetDesc() );
          DIRECT_DEALLOCATE_INTERFACE( thiz );
          return DFB_FAILURE;
     }

     ret = dfb_surface_create_preallocated( NULL,
                                            data->player->GetWidth(),
                                            data->player->GetHeight(),
                                            DSPF_RGB16, CSP_SYSTEMONLY,
                                            DSCAPS_SYSTEMONLY, NULL,
                                            NULL, NULL, 0, 0, &data->source );
     if (ret) {
          delete data->player;
          DIRECT_DEALLOCATE_INTERFACE(thiz);
          return ret;
     }

     data->state.source   = data->source;
     data->state.modified = SMF_ALL;

     thiz->AddRef    = IDirectFBVideoProvider_AviFile_AddRef;
     thiz->Release   = IDirectFBVideoProvider_AviFile_Release;
     thiz->GetCapabilities = IDirectFBVideoProvider_AviFile_GetCapabilities;
     thiz->GetSurfaceDescription =
          IDirectFBVideoProvider_AviFile_GetSurfaceDescription;
     thiz->PlayTo    = IDirectFBVideoProvider_AviFile_PlayTo;
     thiz->Stop      = IDirectFBVideoProvider_AviFile_Stop;
     thiz->SeekTo    = IDirectFBVideoProvider_AviFile_SeekTo;
     thiz->GetPos    = IDirectFBVideoProvider_AviFile_GetPos;
     thiz->GetLength = IDirectFBVideoProvider_AviFile_GetLength;
     thiz->GetColorAdjustment =
          IDirectFBVideoProvider_AviFile_GetColorAdjustment;
     thiz->SetColorAdjustment =
          IDirectFBVideoProvider_AviFile_SetColorAdjustment;

     return DFB_OK;
}

}

<|endoftext|>


<commit_before>#ifndef UTIL_TASK_HPP
#define UTIL_TASK_HPP

#include <atomic>
#include <deque>

namespace Util {
	struct task {

		/** Initializes any resources deferred from constructor
 		 * @param alive Shared status; false signals shutdown
 		 */
		virtual void init(std::atomic_bool& alive) =0;
		/** Runs a given task
 		 * @param alive Shared status; false signals shutdown
 		 */
		virtual void run(std::atomic_bool& alive) =0;
		virtual ~task(void) {}

		/** Initializes any resources deferred from constructor
 		 * @param alive Shared status; false signals shutdown
 		 * @param t The task to initialize */
		static void init(std::atomic_bool &alive, task *t) {
			t -> init(alive);
		}
		/** Runs a given task
 		 * @param alive Shared status; false signals shutdown
 		 * @param t The task to run
 		 */
		static void run(std::atomic_bool &alive, task *t) {
			t -> run(alive);
		}
	};

	struct supertask : public virtual task {
		std::deque<task*> tasks;
		void init(std::atomic_bool& alive) {
			for(auto t : tasks) {
				t -> init(alive);
			}
		}
		void run(std::atomic_bool& alive) {
			for(auto t : tasks) {
				t -> run(alive);
			}
		}
		virtual ~supertask(void) {}
	};
}

#endif
<commit_msg>Added worker type<commit_after>#ifndef UTIL_TASK_HPP
#define UTIL_TASK_HPP

#include <atomic>
#include <deque>

namespace Util {
	struct task {

		/** Initializes any resources deferred from constructor
 		 * @param alive Shared status; false signals shutdown
 		 */
		virtual void init(std::atomic_bool& alive) =0;
		/** Polls for changes
 		 * @param alive Shared status; false signals shutdown
 		 */
		virtual void poll(std::atomic_bool &alive) =0;
		/** Runs a given task
 		 * @param alive Shared status; false signals shutdown
 		 */
		virtual void run(std::atomic_bool& alive) =0;
		virtual ~task(void) {}

		/** Initializes any resources deferred from constructor
 		 * @param alive Shared status; false signals shutdown
 		 * @param t The task to initialize */
		static void init(std::atomic_bool &alive, task *t) {
			t -> init(alive);
		}
		static void poll(std::atomic_bool &alive, task *t) {
			t -> poll(alive);
		}
		/** Runs a given task
 		 * @param alive Shared status; false signals shutdown
 		 * @param t The task to run
 		 */
		static void run(std::atomic_bool &alive, task *t) {
			t -> run(alive);
		}
	};

	struct supertask : public virtual task {
		std::deque<task*> tasks;
		void init(std::atomic_bool& alive) {
			for(auto t : tasks) {
				t -> init(alive);
			}
		}
		void poll(std::atomic_bool& alive) {
			for(auto t : tasks) {
				t -> poll(alive);
			}
		}
		void run(std::atomic_bool& alive) {
			for(auto t : tasks) {
				t -> run(alive);
			}
		}
		virtual ~supertask(void) {}
	};

	struct worker : public virtual task {
		std::function<void (std::atomic_bool &)>
			m_init, m_poll, m_run;
		//void (*m_run)(std::atomic_bool &);
		void init(std::atomic_bool &alive) {
			m_init(alive);
		}
		void poll(std::atomic_bool &alive) {
			m_poll(alive);
		}
		void run(std::atomic_bool &alive) {
			m_run(alive);
		}
		worker(std::function<void (std::atomic_bool &)> m_init,
				std::function<void (std::atomic_bool &)> m_poll,
				std::function<void (std::atomic_bool &)> m_run):
			m_init(m_init), m_poll(m_poll), m_run(m_run) {}
		virtual ~worker(void) {}
	};
}

#endif
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
/// \file   pcap.hpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Support for PCAP file format writing.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com>
// Created: 2010-10-21
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of the utxx open-source project.

Copyright (C) 2010 Serge Aleynikov <saleyn@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.1 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.

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

***** END LICENSE BLOCK *****
*/
#ifndef _UTXX_PCAP_HPP_
#define _UTXX_PCAP_HPP_

#include <utxx/error.hpp>
#include <utxx/endian.hpp>
#include <boost/cstdint.hpp>
#include <boost/static_assert.hpp>
#include <stdio.h>
#include <arpa/inet.h>

namespace utxx {

namespace detail {
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netinet/if_ether.h>
}

/**
 * PCAP file reader/writer
 */
struct pcap {
    struct file_header {
        uint32_t magic_number;   /* magic number */
        uint16_t version_major;  /* major version number */
        uint16_t version_minor;  /* minor version number */
        int32_t  thiszone;       /* GMT to local correction */
        uint32_t sigfigs;        /* accuracy of timestamps */
        uint32_t snaplen;        /* max length of captured packets, in octets */
        uint32_t network;        /* data link type */
    };

    struct packet_header {
        uint32_t ts_sec;         /* timestamp seconds */
        uint32_t ts_usec;        /* timestamp microseconds */
        uint32_t incl_len;       /* number of octets of packet saved in file */
        uint32_t orig_len;       /* actual length of packet */
    };

    struct udp_frame {
        struct detail::ethhdr eth;
        struct detail::iphdr  ip;
        struct detail::udphdr udp;

        uint8_t  protocol() const { return ip.protocol;       }
        uint32_t src_ip()   const { return ntohl(ip.saddr);   }
        uint32_t dst_ip()   const { return ntohl(ip.daddr);   }
        uint16_t src_port() const { return ntohs(udp.source); }
        uint16_t dst_port() const { return ntohs(udp.dest);   }

        std::string src() const {
            char buf[32];
            return std::string(fmt(buf, src_ip(), src_port()));
        }
        std::string dst() const {
            char buf[32];
            return std::string(fmt(buf, dst_ip(), dst_port()));
        }

    private:
        static const char* fmt(char* buf, uint32_t ip, uint16_t port) {
            sprintf(buf, "%u.%u.%u.%u:%d",
                ip >> 24 & 0xFF, ip >> 16 & 0xFF, ip >> 8 & 0xFF, ip & 0xFF, port);
            return buf;
        }
    } __attribute__ ((__packed__));

    BOOST_STATIC_ASSERT(sizeof(detail::ethhdr) == 14);
    BOOST_STATIC_ASSERT(sizeof(detail::iphdr)  == 20);
    BOOST_STATIC_ASSERT(sizeof(detail::udphdr) ==  8);
    BOOST_STATIC_ASSERT(sizeof(udp_frame)      == 42);

    pcap() : m_big_endian(true), m_file(NULL), m_own_handle(false) {}

    long open_read(const std::string& a_filename, bool a_is_pipe = false) {
        return open(a_filename.c_str(), a_is_pipe ? "r" : "rb");
    }

    long open_write(const std::string& a_filename, bool a_is_pipe = false) {
        long sz = open(a_filename.c_str(), a_is_pipe ? "w" : "wb+", a_is_pipe);
        if (sz < 0)
            return sz;
        write_file_header();
        return sz;
    }

    long popen(const char* a_filename, const std::string& a_mode) {
        return open(a_filename, a_mode, true);
    }

    long open(const char* a_filename, const std::string& a_mode) {
        return open(a_filename, a_mode, false);
    }

    ~pcap() {
        close();
    }

    static bool is_pcap_header(const char* buf, size_t sz) {
        return sz >= 4 &&
             ( *reinterpret_cast<const uint32_t*>(buf) == 0xa1b2c3d4
            || *reinterpret_cast<const uint32_t*>(buf) == 0xd4c3b2a1);
    }

    static int set_file_header(char* buf, size_t sz) {
        BOOST_ASSERT(sz >= sizeof(file_header));
        file_header* p = reinterpret_cast<file_header*>(buf);
        p->magic_number     = 0xa1b2c3d4;
        p->version_major    = 2;
        p->version_minor    = 4;
        p->thiszone         = 0;
        p->sigfigs          = 0;
        p->snaplen          = 65535;
        p->network          = 1;
        return sizeof(file_header);
    }

    template <size_t N>
    static int set_packet_header(char (&buf)[N],
        const struct timeval& tv, size_t len)
    {
        BOOST_STATIC_ASSERT(N >= sizeof(packet_header));
        packet_header* p = reinterpret_cast<packet_header*>(buf);
        p->ts_sec   = tv.tv_sec;
        p->ts_usec  = tv.tv_usec;
        p->incl_len = len;
        p->orig_len = len;
        return sizeof(packet_header);
    }

    int read_file_header() {
        char buf[sizeof(file_header)];
        const char* p = buf;
        size_t n = read(buf, sizeof(buf));
        if (n < sizeof(buf))
            return -1;
        return read_file_header(p, sizeof(buf));
    }

    int read_file_header(const char*& buf, size_t sz) {
        if (sz < sizeof(file_header) || !is_pcap_header(buf, sz))
            return -1;

        m_big_endian = buf[0] == 0xa1
                    && buf[1] == 0xb2
                    && buf[2] == 0xc3
                    && buf[3] == 0xd4;
        if (!m_big_endian) {
            m_file_header = *reinterpret_cast<const file_header*>(buf);
            buf += sizeof(file_header);
        } else {
            m_file_header.magic_number  = get32be(buf);
            m_file_header.version_major = get16be(buf);
            m_file_header.version_minor = get16be(buf);
            m_file_header.thiszone      = (int32_t)get32be(buf);
            m_file_header.sigfigs       = get32be(buf);
            m_file_header.snaplen       = get32be(buf);
            m_file_header.network       = get32be(buf);
        }
        return 0;
    }

    int read_packet_header(const char*& buf, size_t sz) {
        if (sz < sizeof(packet_header))
            return -1;
        if (!m_big_endian) {
            m_pkt_header = *reinterpret_cast<const packet_header*>(buf);
            buf += sizeof(packet_header);
        } else {
            m_pkt_header.ts_sec   = get32be(buf);
            m_pkt_header.ts_usec  = get32be(buf);
            m_pkt_header.incl_len = get32be(buf);
            m_pkt_header.orig_len = get32be(buf);
        }
        return m_pkt_header.incl_len;
    }

    int parse_udp_frame(const char*&buf, size_t sz) {
        if (sz < 42)
            return -2;

        memcpy(&m_frame, buf, sizeof(m_frame)); buf += sizeof(m_frame);

        return m_frame.ip.protocol != IPPROTO_UDP ? -1 : 42;
    }

    /// @param a_mask is an IP address mask in network byte order.
    bool match_dst_ip(uint32_t a_ip_mask, uint16_t a_port = 0) {
        uint8_t b = a_ip_mask >> 24 & 0xFF;
        if (b != 0 && (b != (m_frame.ip.daddr >> 24 & 0xFF)))
            return false;
        b = a_ip_mask >> 16 & 0xFF;
        if (b != 0 && (b != (m_frame.ip.daddr >> 16 & 0xFF)))
            return false;
        b = a_ip_mask >> 8 & 0xFF;
        if (b != 0 && (b != (m_frame.ip.daddr >> 8 & 0xFF)))
            return false;
        b = a_ip_mask & 0xFF;
        if (b != 0 && (b != (m_frame.ip.daddr & 0xFF)))
            return false;
        if (a_port != 0 && (a_port != m_frame.udp.dest))
            return false;
        return true;
    }

    size_t read(char* buf, size_t sz) {
        return fread(buf, 1, sz, m_file);
    }

    int write_file_header() {
        char buf[sizeof(file_header)];
        int n = set_file_header(buf, sizeof(buf));
        return fwrite(buf, 1, n, m_file);
    }

    int write_packet_header(
        const struct timeval& a_timestamp, size_t a_packet_size)
    {
        char buf[sizeof(packet_header)];
        int n = set_packet_header(buf, a_timestamp, a_packet_size);
        return fwrite(buf, 1, n, m_file);
    }

    int write_packet_header(const packet_header& a_header) {
        return fwrite(&a_header, 1, sizeof(packet_header), m_file);
    }

    int write_udp_frame(const udp_frame& a_frame) {
        return fwrite(&a_frame, 1, sizeof(udp_frame), m_file);
    }

    int write(const char* buf, size_t sz) {
        return fwrite(buf, 1, sz, m_file);
    }

    bool     is_open()              const { return m_file != NULL; }
    uint64_t tell()                 const { return m_file ? ftell(m_file) : 0; }

    const file_header&   header()   const { return m_file_header; }
    const packet_header& packet()   const { return m_pkt_header;  }
    const udp_frame&     frame()    const { return m_frame;       }

    void set_handle(FILE* a_handle) {
        close();
        m_own_handle = false;
        m_file = a_handle;
    }

private:
    void close() {
        if (m_file && m_own_handle) {
            m_is_pipe ? pclose(m_file) : fclose(m_file);
            m_is_pipe = false;
            m_file    = NULL;
        }
    }

    long open(const char* a_filename, const std::string& a_mode, bool a_is_pipe) {
        close();
        if (a_is_pipe)
            m_file = ::popen(a_filename, a_mode.c_str());
        else
            m_file = ::fopen(a_filename, a_mode.c_str());
        if (!m_file)
            return -1;
        m_is_pipe    = a_is_pipe;
        m_own_handle = true;
        if (fseek(m_file, 0, SEEK_END) < 0)
            return -1;
        long sz = ftell(m_file);
        if (fseek(m_file, 0, SEEK_SET) < 0)
            return -1;
        return (m_file == NULL) ? -1 : sz;
    }

    udp_frame     m_frame;
    file_header   m_file_header;
    packet_header m_pkt_header;
    bool          m_big_endian;
    FILE*         m_file;
    bool          m_own_handle;
    bool          m_is_pipe;
};

} // namespace utxx

#endif // _UTXX_PCAP_HPP_

<commit_msg>Bug fix in popen<commit_after>//----------------------------------------------------------------------------
/// \file   pcap.hpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Support for PCAP file format writing.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com>
// Created: 2010-10-21
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of the utxx open-source project.

Copyright (C) 2010 Serge Aleynikov <saleyn@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.1 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.

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

***** END LICENSE BLOCK *****
*/
#ifndef _UTXX_PCAP_HPP_
#define _UTXX_PCAP_HPP_

#include <utxx/error.hpp>
#include <utxx/endian.hpp>
#include <boost/cstdint.hpp>
#include <boost/static_assert.hpp>
#include <stdio.h>
#include <arpa/inet.h>

namespace utxx {

namespace detail {
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netinet/if_ether.h>
}

/**
 * PCAP file reader/writer
 */
struct pcap {
    struct file_header {
        uint32_t magic_number;   /* magic number */
        uint16_t version_major;  /* major version number */
        uint16_t version_minor;  /* minor version number */
        int32_t  thiszone;       /* GMT to local correction */
        uint32_t sigfigs;        /* accuracy of timestamps */
        uint32_t snaplen;        /* max length of captured packets, in octets */
        uint32_t network;        /* data link type */
    };

    struct packet_header {
        uint32_t ts_sec;         /* timestamp seconds */
        uint32_t ts_usec;        /* timestamp microseconds */
        uint32_t incl_len;       /* number of octets of packet saved in file */
        uint32_t orig_len;       /* actual length of packet */
    };

    struct udp_frame {
        struct detail::ethhdr eth;
        struct detail::iphdr  ip;
        struct detail::udphdr udp;

        uint8_t  protocol() const { return ip.protocol;       }
        uint32_t src_ip()   const { return ntohl(ip.saddr);   }
        uint32_t dst_ip()   const { return ntohl(ip.daddr);   }
        uint16_t src_port() const { return ntohs(udp.source); }
        uint16_t dst_port() const { return ntohs(udp.dest);   }

        std::string src() const {
            char buf[32];
            return std::string(fmt(buf, src_ip(), src_port()));
        }
        std::string dst() const {
            char buf[32];
            return std::string(fmt(buf, dst_ip(), dst_port()));
        }

    private:
        static const char* fmt(char* buf, uint32_t ip, uint16_t port) {
            sprintf(buf, "%u.%u.%u.%u:%d",
                ip >> 24 & 0xFF, ip >> 16 & 0xFF, ip >> 8 & 0xFF, ip & 0xFF, port);
            return buf;
        }
    } __attribute__ ((__packed__));

    BOOST_STATIC_ASSERT(sizeof(detail::ethhdr) == 14);
    BOOST_STATIC_ASSERT(sizeof(detail::iphdr)  == 20);
    BOOST_STATIC_ASSERT(sizeof(detail::udphdr) ==  8);
    BOOST_STATIC_ASSERT(sizeof(udp_frame)      == 42);

    pcap() : m_big_endian(true), m_file(NULL), m_own_handle(false) {}

    long open_read(const std::string& a_filename, bool a_is_pipe = false) {
        return open(a_filename.c_str(), a_is_pipe ? "r" : "rb", a_is_pipe);
    }

    long open_write(const std::string& a_filename, bool a_is_pipe = false) {
        long sz = open(a_filename.c_str(), a_is_pipe ? "w" : "wb+", a_is_pipe);
        if (sz < 0)
            return sz;
        write_file_header();
        return sz;
    }

    long popen(const char* a_filename, const std::string& a_mode) {
        return open(a_filename, a_mode, true);
    }

    long open(const char* a_filename, const std::string& a_mode) {
        return open(a_filename, a_mode, false);
    }

    ~pcap() {
        close();
    }

    static bool is_pcap_header(const char* buf, size_t sz) {
        return sz >= 4 &&
             ( *reinterpret_cast<const uint32_t*>(buf) == 0xa1b2c3d4
            || *reinterpret_cast<const uint32_t*>(buf) == 0xd4c3b2a1);
    }

    static int set_file_header(char* buf, size_t sz) {
        BOOST_ASSERT(sz >= sizeof(file_header));
        file_header* p = reinterpret_cast<file_header*>(buf);
        p->magic_number     = 0xa1b2c3d4;
        p->version_major    = 2;
        p->version_minor    = 4;
        p->thiszone         = 0;
        p->sigfigs          = 0;
        p->snaplen          = 65535;
        p->network          = 1;
        return sizeof(file_header);
    }

    template <size_t N>
    static int set_packet_header(char (&buf)[N],
        const struct timeval& tv, size_t len)
    {
        BOOST_STATIC_ASSERT(N >= sizeof(packet_header));
        packet_header* p = reinterpret_cast<packet_header*>(buf);
        p->ts_sec   = tv.tv_sec;
        p->ts_usec  = tv.tv_usec;
        p->incl_len = len;
        p->orig_len = len;
        return sizeof(packet_header);
    }

    int read_file_header() {
        char buf[sizeof(file_header)];
        const char* p = buf;
        size_t n = read(buf, sizeof(buf));
        if (n < sizeof(buf))
            return -1;
        return read_file_header(p, sizeof(buf));
    }

    int read_file_header(const char*& buf, size_t sz) {
        if (sz < sizeof(file_header) || !is_pcap_header(buf, sz))
            return -1;

        m_big_endian = buf[0] == 0xa1
                    && buf[1] == 0xb2
                    && buf[2] == 0xc3
                    && buf[3] == 0xd4;
        if (!m_big_endian) {
            m_file_header = *reinterpret_cast<const file_header*>(buf);
            buf += sizeof(file_header);
        } else {
            m_file_header.magic_number  = get32be(buf);
            m_file_header.version_major = get16be(buf);
            m_file_header.version_minor = get16be(buf);
            m_file_header.thiszone      = (int32_t)get32be(buf);
            m_file_header.sigfigs       = get32be(buf);
            m_file_header.snaplen       = get32be(buf);
            m_file_header.network       = get32be(buf);
        }
        return 0;
    }

    int read_packet_header(const char*& buf, size_t sz) {
        if (sz < sizeof(packet_header))
            return -1;
        if (!m_big_endian) {
            m_pkt_header = *reinterpret_cast<const packet_header*>(buf);
            buf += sizeof(packet_header);
        } else {
            m_pkt_header.ts_sec   = get32be(buf);
            m_pkt_header.ts_usec  = get32be(buf);
            m_pkt_header.incl_len = get32be(buf);
            m_pkt_header.orig_len = get32be(buf);
        }
        return m_pkt_header.incl_len;
    }

    int parse_udp_frame(const char*&buf, size_t sz) {
        if (sz < 42)
            return -2;

        memcpy(&m_frame, buf, sizeof(m_frame)); buf += sizeof(m_frame);

        return m_frame.ip.protocol != IPPROTO_UDP ? -1 : 42;
    }

    /// @param a_mask is an IP address mask in network byte order.
    bool match_dst_ip(uint32_t a_ip_mask, uint16_t a_port = 0) {
        uint8_t b = a_ip_mask >> 24 & 0xFF;
        if (b != 0 && (b != (m_frame.ip.daddr >> 24 & 0xFF)))
            return false;
        b = a_ip_mask >> 16 & 0xFF;
        if (b != 0 && (b != (m_frame.ip.daddr >> 16 & 0xFF)))
            return false;
        b = a_ip_mask >> 8 & 0xFF;
        if (b != 0 && (b != (m_frame.ip.daddr >> 8 & 0xFF)))
            return false;
        b = a_ip_mask & 0xFF;
        if (b != 0 && (b != (m_frame.ip.daddr & 0xFF)))
            return false;
        if (a_port != 0 && (a_port != m_frame.udp.dest))
            return false;
        return true;
    }

    size_t read(char* buf, size_t sz) {
        return fread(buf, 1, sz, m_file);
    }

    int write_file_header() {
        char buf[sizeof(file_header)];
        int n = set_file_header(buf, sizeof(buf));
        return fwrite(buf, 1, n, m_file);
    }

    int write_packet_header(
        const struct timeval& a_timestamp, size_t a_packet_size)
    {
        char buf[sizeof(packet_header)];
        int n = set_packet_header(buf, a_timestamp, a_packet_size);
        return fwrite(buf, 1, n, m_file);
    }

    int write_packet_header(const packet_header& a_header) {
        return fwrite(&a_header, 1, sizeof(packet_header), m_file);
    }

    int write_udp_frame(const udp_frame& a_frame) {
        return fwrite(&a_frame, 1, sizeof(udp_frame), m_file);
    }

    int write(const char* buf, size_t sz) {
        return fwrite(buf, 1, sz, m_file);
    }

    bool     is_open()              const { return m_file != NULL; }
    uint64_t tell()                 const { return m_file ? ftell(m_file) : 0; }

    const file_header&   header()   const { return m_file_header; }
    const packet_header& packet()   const { return m_pkt_header;  }
    const udp_frame&     frame()    const { return m_frame;       }

    void set_handle(FILE* a_handle) {
        close();
        m_own_handle = false;
        m_file = a_handle;
    }

private:
    void close() {
        if (m_file && m_own_handle) {
            m_is_pipe ? pclose(m_file) : fclose(m_file);
            m_is_pipe = false;
            m_file    = NULL;
        }
    }

    long open(const char* a_filename, const std::string& a_mode, bool a_is_pipe) {
        close();
        if (a_is_pipe)
            m_file = ::popen(a_filename, a_mode.c_str());
        else
            m_file = ::fopen(a_filename, a_mode.c_str());
        if (!m_file)
            return -1;
        m_is_pipe    = a_is_pipe;
        m_own_handle = true;
        long sz;
        if (a_is_pipe)
            sz = 0;
        else {
            if (fseek(m_file, 0, SEEK_END) < 0) return -1;
            sz = ftell(m_file);
            if (fseek(m_file, 0, SEEK_SET) < 0) return -1;
        }
        return (m_file == NULL) ? -1 : sz;
    }

    udp_frame     m_frame;
    file_header   m_file_header;
    packet_header m_pkt_header;
    bool          m_big_endian;
    FILE*         m_file;
    bool          m_own_handle;
    bool          m_is_pipe;
};

} // namespace utxx

#endif // _UTXX_PCAP_HPP_

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling 2>&1 | FileCheck %s

#include "cling/Interpreter/Interpreter.h"

int a = 21;
gCling->toString("a");
// CHECK: "21"
<commit_msg>Fix printing test in Cling<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling 2>&1 | FileCheck %s

#include "cling/Interpreter/Interpreter.h"

int a = 21;
gCling->toString("a");
// CHECK: 21
<|endoftext|>


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

#include "ash/launcher/launcher.h"

#include "ash/launcher/launcher_model.h"
#include "ash/launcher/launcher_view.h"
#include "ash/shell.h"
#include "ash/shell_delegate.h"
#include "ash/shell_window_ids.h"
#include "grit/ui_resources.h"
#include "ui/aura/window.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/compositor/layer.h"
#include "ui/gfx/image/image.h"
#include "ui/views/painter.h"
#include "ui/views/widget/widget.h"

namespace ash {

namespace {

// Used to draw the background of the shelf.
class ShelfPainter : public views::Painter {
 public:
  ShelfPainter() {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    image_ = *rb.GetImageNamed(IDR_AURA_LAUNCHER_BACKGROUND).ToSkBitmap();
  }

  virtual void Paint(int w, int h, gfx::Canvas* canvas) OVERRIDE {
    canvas->TileImageInt(image_, 0, 0, w, h);
  }

 private:
  SkBitmap image_;

  DISALLOW_COPY_AND_ASSIGN(ShelfPainter);
};

}  // namespace

// The contents view of the Widget. This view contains LauncherView and
// sizes it to the width of the widget minus the size of the status area.
class Launcher::DelegateView : public views::WidgetDelegateView {
 public:
  explicit DelegateView();
  virtual ~DelegateView();

  void SetStatusWidth(int width);
  int status_width() const { return status_width_; }

  // views::View overrides
  virtual gfx::Size GetPreferredSize() OVERRIDE;
  virtual void Layout() OVERRIDE;

 private:
  int status_width_;

  DISALLOW_COPY_AND_ASSIGN(DelegateView);
};

Launcher::DelegateView::DelegateView()
    : status_width_(0) {
  set_background(
      views::Background::CreateBackgroundPainter(true, new ShelfPainter()));
}

Launcher::DelegateView::~DelegateView() {
}

void Launcher::DelegateView::SetStatusWidth(int width) {
  if (status_width_ == width)
    return;

  status_width_ = width;
  Layout();
}

gfx::Size Launcher::DelegateView::GetPreferredSize() {
  return child_count() > 0 ? child_at(0)->GetPreferredSize() : gfx::Size();
}

void Launcher::DelegateView::Layout() {
  if (child_count() == 0)
    return;
  child_at(0)->SetBounds(0, 0, std::max(0, width() - status_width_), height());
}

Launcher::Launcher(aura::Window* window_container)
    : widget_(NULL),
      window_container_(window_container),
      delegate_view_(NULL) {
  model_.reset(new LauncherModel);

  widget_ = new views::Widget;
  views::Widget::InitParams params(
      views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  params.create_texture_for_layer = true;
  params.transparent = true;
  params.parent = Shell::GetInstance()->GetContainer(
      ash::internal::kShellWindowId_LauncherContainer);
  internal::LauncherView* launcher_view =
      new internal::LauncherView(model_.get());
  launcher_view->Init();
  delegate_view_ = new DelegateView;
  delegate_view_->AddChildView(launcher_view);
  params.delegate = delegate_view_;
  widget_->Init(params);
  gfx::Size pref = static_cast<views::View*>(launcher_view)->GetPreferredSize();
  widget_->SetBounds(gfx::Rect(0, 0, pref.width(), pref.height()));
  widget_->SetContentsView(delegate_view_);
  widget_->Show();
  widget_->GetNativeView()->SetName("LauncherView");
}

Launcher::~Launcher() {
  widget_->CloseNow();
}

void Launcher::SetStatusWidth(int width) {
  delegate_view_->SetStatusWidth(width);
}

int Launcher::GetStatusWidth() {
  return delegate_view_->status_width();
}

}  // namespace ash
<commit_msg>Fix launcher to not request focus on creation<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/launcher/launcher.h"

#include "ash/launcher/launcher_model.h"
#include "ash/launcher/launcher_view.h"
#include "ash/shell.h"
#include "ash/shell_delegate.h"
#include "ash/shell_window_ids.h"
#include "grit/ui_resources.h"
#include "ui/aura/window.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/compositor/layer.h"
#include "ui/gfx/image/image.h"
#include "ui/views/painter.h"
#include "ui/views/widget/widget.h"

namespace ash {

namespace {

// Used to draw the background of the shelf.
class ShelfPainter : public views::Painter {
 public:
  ShelfPainter() {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    image_ = *rb.GetImageNamed(IDR_AURA_LAUNCHER_BACKGROUND).ToSkBitmap();
  }

  virtual void Paint(int w, int h, gfx::Canvas* canvas) OVERRIDE {
    canvas->TileImageInt(image_, 0, 0, w, h);
  }

 private:
  SkBitmap image_;

  DISALLOW_COPY_AND_ASSIGN(ShelfPainter);
};

}  // namespace

// The contents view of the Widget. This view contains LauncherView and
// sizes it to the width of the widget minus the size of the status area.
class Launcher::DelegateView : public views::WidgetDelegateView {
 public:
  explicit DelegateView();
  virtual ~DelegateView();

  void SetStatusWidth(int width);
  int status_width() const { return status_width_; }

  // views::View overrides
  virtual gfx::Size GetPreferredSize() OVERRIDE;
  virtual void Layout() OVERRIDE;

 private:
  int status_width_;

  DISALLOW_COPY_AND_ASSIGN(DelegateView);
};

Launcher::DelegateView::DelegateView()
    : status_width_(0) {
  set_background(
      views::Background::CreateBackgroundPainter(true, new ShelfPainter()));
}

Launcher::DelegateView::~DelegateView() {
}

void Launcher::DelegateView::SetStatusWidth(int width) {
  if (status_width_ == width)
    return;

  status_width_ = width;
  Layout();
}

gfx::Size Launcher::DelegateView::GetPreferredSize() {
  return child_count() > 0 ? child_at(0)->GetPreferredSize() : gfx::Size();
}

void Launcher::DelegateView::Layout() {
  if (child_count() == 0)
    return;
  child_at(0)->SetBounds(0, 0, std::max(0, width() - status_width_), height());
}

Launcher::Launcher(aura::Window* window_container)
    : widget_(NULL),
      window_container_(window_container),
      delegate_view_(NULL) {
  model_.reset(new LauncherModel);

  widget_ = new views::Widget;
  views::Widget::InitParams params(
      views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  params.create_texture_for_layer = true;
  params.transparent = true;
  params.parent = Shell::GetInstance()->GetContainer(
      ash::internal::kShellWindowId_LauncherContainer);
  internal::LauncherView* launcher_view =
      new internal::LauncherView(model_.get());
  launcher_view->Init();
  delegate_view_ = new DelegateView;
  delegate_view_->AddChildView(launcher_view);
  params.delegate = delegate_view_;
  widget_->Init(params);
  gfx::Size pref = static_cast<views::View*>(launcher_view)->GetPreferredSize();
  widget_->SetBounds(gfx::Rect(0, 0, pref.width(), pref.height()));
  // The launcher should not take focus when it is initially shown.
  widget_->set_focus_on_creation(false);
  widget_->SetContentsView(delegate_view_);
  widget_->Show();
  widget_->GetNativeView()->SetName("LauncherView");
}

Launcher::~Launcher() {
  widget_->CloseNow();
}

void Launcher::SetStatusWidth(int width) {
  delegate_view_->SetStatusWidth(width);
}

int Launcher::GetStatusWidth() {
  return delegate_view_->status_width();
}

}  // namespace ash
<|endoftext|>


<commit_before>/* rbOOmit: An implementation of the Certified Reduced Basis method. */
/* Copyright (C) 2009, 2010 David J. Knezevic */
/*     This file is part of rbOOmit. */

/* rbOOmit 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.1 of the License, or (at your option) any later version. */

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

//
Reduced Basis: Example 6 - Heat transfer on a curved domain in 3D

// In this example we consider heat transfer modeled by a Poisson equation with
// Robin boundary condition:
//  -kappa \Laplacian u = 1, on \Omega
//  -kappa du\dn = kappa Bi u, on \partial\Omega_Biot,
//  u = 0 on \partial\Omega_Dirichlet,
//
// We consider a reference domain \Omega_hat = [-0.2,0.2]x[-0.2,0.2]x[0,3], and the
// physical domain is then obtain via the parametrized mapping:
//  x = -1/mu + (1/mu+x_hat)*cos(mu*z_hat)
//  y = y_hat
//  z = (1/mu+x_hat)*sin(mu*z_hat)
// for (x_hat,y_hat,z_hat) \in \Omega_hat. (Here "hats" denotes reference domain.)
// Also, the "reference Dirichlet boundaries" are [-0.2,0.2]x[-0.2,0.2]x{0} and
// [-0.2,0.2]x[-0.2,0.2]x{3}, and the remaining boundaries are the "Biot" boundaries.

// Then, after putting the PDE into weak form and mapping it to the reference domain,
// we obtain:
//  \kappa \int_\Omega_hat [ (1+mu*x_hat) v_x w_x + (1+mu*x_hat) v_y w_y + 1/(1+mu*x_hat) v_z w_z ]
//    + \kappa Bi \int_\partial\Omega_hat_Biot1 (1-0.2mu) u v
//    + \kappa Bi \int_\partial\Omega_hat_Biot2 (1+mu x_hat) u v
//    + \kappa Bi \int_\partial\Omega_hat_Biot3 (1+0.2mu) u v
//    = \int_\Omega_hat (1+mu x_hat) v
// where
//  \partial\Omega_hat_Biot1 = [-0.2] x [-0.2,0.2] x [0,3]
//  \partial\Omega_hat_Biot2 = [-0.2,0.2] x {-0.2} x [0,3] \UNION [-0.2,0.2] x {0.2} x [0,3]
//  \partial\Omega_hat_Biot3 = [0.2] x [-0.2,0.2] x [0,3]

// The term
//  \kappa \int_\Omega_hat 1/(1+mu*x_hat) v_z w_z
// is "non-affine" (in the Reduced Basis sense), since we can't express it
// in the form \sum theta_q(kappa,mu) a(v,w). As a result, (as in
// reduced_basis_ex4) we must employ the Empirical Interpolation Method (EIM)
// in order to apply the Reduced Basis method here.

// The approach we use is to construct an EIM approximation, G_EIM, to the vector-valued function
//  G(x_hat,y_hat;mu) = (1 + mu*x_hat, 1 + mu*x_hat, 1/(1+mu*x_hat))
// and then we express the "volumetric integral part" of the left-hand side operator as
//  a(v,w;mu) = \int_\hat\Omega G_EIM(x_hat,y_hat;mu) \dot (v_x w_x, v_y w_y, v_z w_z).
// (We actually only need EIM for the third component of G_EIM, but it's helpful to
// demonstrate "vector-valued" EIM here.)

// C++ include files that we need
#include <iostream>
#include <algorithm>
#include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC
#include <cmath>
#include <set>

// Basic include file needed for the mesh functionality.
#include "libmesh/libmesh.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/exodusII_io.h"
#include "libmesh/equation_systems.h"
#include "libmesh/dof_map.h"
#include "libmesh/getpot.h"
#include "libmesh/elem.h"

// local includes
#include "rb_classes.h"
#include "eim_classes.h"
#include "assembly.h"

// Bring in everything from the libMesh namespace
using namespace libMesh;

// Define a function to scale the mesh according to the parameter.
void transform_mesh_and_plot(EquationSystems& es, Real curvature, const std::string& filename);

// The main program.
int main (int argc, char** argv)
{
  // Initialize libMesh.
  LibMeshInit init (argc, argv);

#if !defined(LIBMESH_HAVE_XDR)
  // We need XDR support to write out reduced bases
  libmesh_example_assert(false, "--enable-xdr");
#elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION)
  // XDR binary support requires double precision
  libmesh_example_assert(false, "--disable-singleprecision");
#endif

  // This is a 3D example
  libmesh_example_assert(3 == LIBMESH_DIM, "3D support");

  // Parse the input file using GetPot
  std::string eim_parameters = "eim.in";
  std::string rb_parameters  = "rb.in";
  std::string main_parameters = "reduced_basis_ex6.in";
  GetPot infile(main_parameters);

  unsigned int n_elem_xy = infile("n_elem_xy", 1);
  unsigned int n_elem_z  = infile("n_elem_z", 1);

  // Do we write the RB basis functions to disk?
  bool store_basis_functions = infile("store_basis_functions", true);

  // Read the "online_mode" flag from the command line
  GetPot command_line (argc, argv);
  int online_mode = 0;
  if ( command_line.search(1, "-online_mode") )
    online_mode = command_line.next(online_mode);

  // Build a mesh.
  Mesh mesh;
  MeshTools::Generation::build_cube (mesh,
                                     n_elem_xy, n_elem_xy, n_elem_z,
                                     -0.2, 0.2,
                                     -0.2, 0.2,
                                     0., 3.,
                                     HEX8);

  // Create an equation systems object.
  EquationSystems equation_systems (mesh);

  SimpleEIMConstruction & eim_construction =
    equation_systems.add_system<SimpleEIMConstruction> ("EIM");
  SimpleRBConstruction & rb_construction =
    equation_systems.add_system<SimpleRBConstruction> ("RB");

  // Initialize the data structures for the equation system.
  equation_systems.init ();

  // Print out some information about the "truth" discretization
  equation_systems.print_info();
  mesh.print_info();

  // Initialize the standard RBEvaluation object
  SimpleRBEvaluation rb_eval;

  // Initialize the EIM RBEvaluation object
  SimpleEIMEvaluation eim_rb_eval;

  // Set the rb_eval objects for the RBConstructions
  eim_construction.set_rb_evaluation(eim_rb_eval);
  rb_construction.set_rb_evaluation(rb_eval);

  if(!online_mode) // Perform the Offline stage of the RB method
  {
    // Read data from input file and print state
    eim_construction.process_parameters_file(eim_parameters);
    eim_construction.print_info();

    // Perform the EIM Greedy and write out the data
    eim_construction.initialize_rb_construction();

    eim_construction.train_reduced_basis();
    eim_construction.get_rb_evaluation().write_offline_data_to_files("eim_data");

    // Read data from input file and print state
    rb_construction.process_parameters_file(rb_parameters);

    // attach the EIM theta objects to the RBEvaluation
    eim_rb_eval.initialize_eim_theta_objects();
    rb_eval.get_rb_theta_expansion().attach_multiple_A_theta(eim_rb_eval.get_eim_theta_objects());

    // attach the EIM assembly objects to the RBConstruction
    eim_construction.initialize_eim_assembly_objects();
    rb_construction.get_rb_assembly_expansion().attach_multiple_A_assembly(eim_construction.get_eim_assembly_objects());

    // Print out the state of rb_construction now that the EIM objects have been attached
    rb_construction.print_info();

    // Need to initialize _after_ EIM greedy so that
    // the system knows how many affine terms there are
    rb_construction.initialize_rb_construction();
    rb_construction.train_reduced_basis();
    rb_construction.get_rb_evaluation().write_offline_data_to_files("rb_data");

    // Write out the basis functions, if requested
    if(store_basis_functions)
    {
      // Write out the basis functions
      eim_construction.get_rb_evaluation().write_out_basis_functions(eim_construction,"eim_data");
      rb_construction.get_rb_evaluation().write_out_basis_functions(rb_construction,"rb_data");
    }
  }
  else // Perform the Online stage of the RB method
  {
    eim_rb_eval.read_offline_data_from_files("eim_data");

    // attach the EIM theta objects to rb_eval objects
    eim_rb_eval.initialize_eim_theta_objects();
    rb_eval.get_rb_theta_expansion().attach_multiple_A_theta(eim_rb_eval.get_eim_theta_objects());

    // Read in the offline data for rb_eval
    rb_eval.read_offline_data_from_files("rb_data");

    // Get the parameters at which we will do a reduced basis solve
    Real online_curvature = infile("online_curvature", 0.);
    Real online_Bi        = infile("online_Bi", 0.);
    Real online_kappa     = infile("online_kappa", 0.);
    RBParameters online_mu;
    online_mu.set_value("curvature", online_curvature);
    online_mu.set_value("Bi", online_Bi);
    online_mu.set_value("kappa", online_kappa);
    rb_eval.set_parameters(online_mu);
    rb_eval.print_parameters();
    rb_eval.rb_solve( rb_eval.get_n_basis_functions() );

    // plot the solution, if requested
    if(store_basis_functions)
    {
      // read in the data from files
      eim_rb_eval.read_in_basis_functions(eim_construction,"eim_data");
      rb_eval.read_in_basis_functions(rb_construction,"rb_data");

      eim_construction.load_rb_solution();
      rb_construction.load_rb_solution();

      transform_mesh_and_plot(equation_systems,online_curvature,"RB_sol.e");
    }
  }

  return 0;
}

void transform_mesh_and_plot(EquationSystems& es, Real curvature, const std::string& filename)
{
  // Loop over the mesh nodes and move them!
  MeshBase& mesh = es.get_mesh();

  MeshBase::node_iterator       node_it  = mesh.nodes_begin();
  const MeshBase::node_iterator node_end = mesh.nodes_end();

  for( ; node_it != node_end; node_it++)
  {
    Node* node = *node_it;

    Real x = (*node)(0);
    Real z = (*node)(2);

    (*node)(0) = -1./curvature + (1./curvature + x)*cos(curvature*z);
    (*node)(2) = (1./curvature + x)*sin(curvature*z);
  }

#ifdef LIBMESH_HAVE_EXODUS_API
  ExodusII_IO(mesh).write_equation_systems(filename, es);
#endif
}

<commit_msg>reduced_basis example 6 (at least...) isn't distributed mesh compatible yet.<commit_after>/* rbOOmit: An implementation of the Certified Reduced Basis method. */
/* Copyright (C) 2009, 2010 David J. Knezevic */
/*     This file is part of rbOOmit. */

/* rbOOmit 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.1 of the License, or (at your option) any later version. */

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

//
Reduced Basis: Example 6 - Heat transfer on a curved domain in 3D

// In this example we consider heat transfer modeled by a Poisson equation with
// Robin boundary condition:
//  -kappa \Laplacian u = 1, on \Omega
//  -kappa du\dn = kappa Bi u, on \partial\Omega_Biot,
//  u = 0 on \partial\Omega_Dirichlet,
//
// We consider a reference domain \Omega_hat = [-0.2,0.2]x[-0.2,0.2]x[0,3], and the
// physical domain is then obtain via the parametrized mapping:
//  x = -1/mu + (1/mu+x_hat)*cos(mu*z_hat)
//  y = y_hat
//  z = (1/mu+x_hat)*sin(mu*z_hat)
// for (x_hat,y_hat,z_hat) \in \Omega_hat. (Here "hats" denotes reference domain.)
// Also, the "reference Dirichlet boundaries" are [-0.2,0.2]x[-0.2,0.2]x{0} and
// [-0.2,0.2]x[-0.2,0.2]x{3}, and the remaining boundaries are the "Biot" boundaries.

// Then, after putting the PDE into weak form and mapping it to the reference domain,
// we obtain:
//  \kappa \int_\Omega_hat [ (1+mu*x_hat) v_x w_x + (1+mu*x_hat) v_y w_y + 1/(1+mu*x_hat) v_z w_z ]
//    + \kappa Bi \int_\partial\Omega_hat_Biot1 (1-0.2mu) u v
//    + \kappa Bi \int_\partial\Omega_hat_Biot2 (1+mu x_hat) u v
//    + \kappa Bi \int_\partial\Omega_hat_Biot3 (1+0.2mu) u v
//    = \int_\Omega_hat (1+mu x_hat) v
// where
//  \partial\Omega_hat_Biot1 = [-0.2] x [-0.2,0.2] x [0,3]
//  \partial\Omega_hat_Biot2 = [-0.2,0.2] x {-0.2} x [0,3] \UNION [-0.2,0.2] x {0.2} x [0,3]
//  \partial\Omega_hat_Biot3 = [0.2] x [-0.2,0.2] x [0,3]

// The term
//  \kappa \int_\Omega_hat 1/(1+mu*x_hat) v_z w_z
// is "non-affine" (in the Reduced Basis sense), since we can't express it
// in the form \sum theta_q(kappa,mu) a(v,w). As a result, (as in
// reduced_basis_ex4) we must employ the Empirical Interpolation Method (EIM)
// in order to apply the Reduced Basis method here.

// The approach we use is to construct an EIM approximation, G_EIM, to the vector-valued function
//  G(x_hat,y_hat;mu) = (1 + mu*x_hat, 1 + mu*x_hat, 1/(1+mu*x_hat))
// and then we express the "volumetric integral part" of the left-hand side operator as
//  a(v,w;mu) = \int_\hat\Omega G_EIM(x_hat,y_hat;mu) \dot (v_x w_x, v_y w_y, v_z w_z).
// (We actually only need EIM for the third component of G_EIM, but it's helpful to
// demonstrate "vector-valued" EIM here.)

// C++ include files that we need
#include <iostream>
#include <algorithm>
#include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC
#include <cmath>
#include <set>

// Basic include file needed for the mesh functionality.
#include "libmesh/libmesh.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/exodusII_io.h"
#include "libmesh/equation_systems.h"
#include "libmesh/dof_map.h"
#include "libmesh/getpot.h"
#include "libmesh/elem.h"

// local includes
#include "rb_classes.h"
#include "eim_classes.h"
#include "assembly.h"

// Bring in everything from the libMesh namespace
using namespace libMesh;

// Define a function to scale the mesh according to the parameter.
void transform_mesh_and_plot(EquationSystems& es, Real curvature, const std::string& filename);

// The main program.
int main (int argc, char** argv)
{
  // Initialize libMesh.
  LibMeshInit init (argc, argv);

#if !defined(LIBMESH_HAVE_XDR)
  // We need XDR support to write out reduced bases
  libmesh_example_assert(false, "--enable-xdr");
#elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION)
  // XDR binary support requires double precision
  libmesh_example_assert(false, "--disable-singleprecision");
#endif

#ifdef LIBMESH_ENABLE_PARMESH
  // RBEIMConstruction currently tries to query the entire mesh on
  // every processor
  libmesh_example_assert(false, "--disable-parmesh");
#endif

  // This is a 3D example
  libmesh_example_assert(3 == LIBMESH_DIM, "3D support");

  // Parse the input file using GetPot
  std::string eim_parameters = "eim.in";
  std::string rb_parameters  = "rb.in";
  std::string main_parameters = "reduced_basis_ex6.in";
  GetPot infile(main_parameters);

  unsigned int n_elem_xy = infile("n_elem_xy", 1);
  unsigned int n_elem_z  = infile("n_elem_z", 1);

  // Do we write the RB basis functions to disk?
  bool store_basis_functions = infile("store_basis_functions", true);

  // Read the "online_mode" flag from the command line
  GetPot command_line (argc, argv);
  int online_mode = 0;
  if ( command_line.search(1, "-online_mode") )
    online_mode = command_line.next(online_mode);

  // Build a mesh.
  Mesh mesh;
  MeshTools::Generation::build_cube (mesh,
                                     n_elem_xy, n_elem_xy, n_elem_z,
                                     -0.2, 0.2,
                                     -0.2, 0.2,
                                     0., 3.,
                                     HEX8);

  // Create an equation systems object.
  EquationSystems equation_systems (mesh);

  SimpleEIMConstruction & eim_construction =
    equation_systems.add_system<SimpleEIMConstruction> ("EIM");
  SimpleRBConstruction & rb_construction =
    equation_systems.add_system<SimpleRBConstruction> ("RB");

  // Initialize the data structures for the equation system.
  equation_systems.init ();

  // Print out some information about the "truth" discretization
  equation_systems.print_info();
  mesh.print_info();

  // Initialize the standard RBEvaluation object
  SimpleRBEvaluation rb_eval;

  // Initialize the EIM RBEvaluation object
  SimpleEIMEvaluation eim_rb_eval;

  // Set the rb_eval objects for the RBConstructions
  eim_construction.set_rb_evaluation(eim_rb_eval);
  rb_construction.set_rb_evaluation(rb_eval);

  if(!online_mode) // Perform the Offline stage of the RB method
  {
    // Read data from input file and print state
    eim_construction.process_parameters_file(eim_parameters);
    eim_construction.print_info();

    // Perform the EIM Greedy and write out the data
    eim_construction.initialize_rb_construction();

    eim_construction.train_reduced_basis();
    eim_construction.get_rb_evaluation().write_offline_data_to_files("eim_data");

    // Read data from input file and print state
    rb_construction.process_parameters_file(rb_parameters);

    // attach the EIM theta objects to the RBEvaluation
    eim_rb_eval.initialize_eim_theta_objects();
    rb_eval.get_rb_theta_expansion().attach_multiple_A_theta(eim_rb_eval.get_eim_theta_objects());

    // attach the EIM assembly objects to the RBConstruction
    eim_construction.initialize_eim_assembly_objects();
    rb_construction.get_rb_assembly_expansion().attach_multiple_A_assembly(eim_construction.get_eim_assembly_objects());

    // Print out the state of rb_construction now that the EIM objects have been attached
    rb_construction.print_info();

    // Need to initialize _after_ EIM greedy so that
    // the system knows how many affine terms there are
    rb_construction.initialize_rb_construction();
    rb_construction.train_reduced_basis();
    rb_construction.get_rb_evaluation().write_offline_data_to_files("rb_data");

    // Write out the basis functions, if requested
    if(store_basis_functions)
    {
      // Write out the basis functions
      eim_construction.get_rb_evaluation().write_out_basis_functions(eim_construction,"eim_data");
      rb_construction.get_rb_evaluation().write_out_basis_functions(rb_construction,"rb_data");
    }
  }
  else // Perform the Online stage of the RB method
  {
    eim_rb_eval.read_offline_data_from_files("eim_data");

    // attach the EIM theta objects to rb_eval objects
    eim_rb_eval.initialize_eim_theta_objects();
    rb_eval.get_rb_theta_expansion().attach_multiple_A_theta(eim_rb_eval.get_eim_theta_objects());

    // Read in the offline data for rb_eval
    rb_eval.read_offline_data_from_files("rb_data");

    // Get the parameters at which we will do a reduced basis solve
    Real online_curvature = infile("online_curvature", 0.);
    Real online_Bi        = infile("online_Bi", 0.);
    Real online_kappa     = infile("online_kappa", 0.);
    RBParameters online_mu;
    online_mu.set_value("curvature", online_curvature);
    online_mu.set_value("Bi", online_Bi);
    online_mu.set_value("kappa", online_kappa);
    rb_eval.set_parameters(online_mu);
    rb_eval.print_parameters();
    rb_eval.rb_solve( rb_eval.get_n_basis_functions() );

    // plot the solution, if requested
    if(store_basis_functions)
    {
      // read in the data from files
      eim_rb_eval.read_in_basis_functions(eim_construction,"eim_data");
      rb_eval.read_in_basis_functions(rb_construction,"rb_data");

      eim_construction.load_rb_solution();
      rb_construction.load_rb_solution();

      transform_mesh_and_plot(equation_systems,online_curvature,"RB_sol.e");
    }
  }

  return 0;
}

void transform_mesh_and_plot(EquationSystems& es, Real curvature, const std::string& filename)
{
  // Loop over the mesh nodes and move them!
  MeshBase& mesh = es.get_mesh();

  MeshBase::node_iterator       node_it  = mesh.nodes_begin();
  const MeshBase::node_iterator node_end = mesh.nodes_end();

  for( ; node_it != node_end; node_it++)
  {
    Node* node = *node_it;

    Real x = (*node)(0);
    Real z = (*node)(2);

    (*node)(0) = -1./curvature + (1./curvature + x)*cos(curvature*z);
    (*node)(2) = (1./curvature + x)*sin(curvature*z);
  }

#ifdef LIBMESH_HAVE_EXODUS_API
  ExodusII_IO(mesh).write_equation_systems(filename, es);
#endif
}

<|endoftext|>