<commit_before>#ifndef __MAPNIK_VECTOR_PROCESSOR_H__
#define __MAPNIK_VECTOR_PROCESSOR_H__

#include <mapnik/map.hpp>
#include <mapnik/request.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/query.hpp>
#include <mapnik/ctrans.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/proj_transform.hpp>
#include <mapnik/scale_denominator.hpp>
#include <mapnik/attribute_descriptor.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/config.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/version.hpp>
#include <mapnik/noncopyable.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/raster.hpp>
#include <mapnik/warp.hpp>
#include <mapnik/version.hpp>
#include <mapnik/image_scaling.hpp>

// agg
#ifdef CONV_CLIPPER
#include "agg_path_storage.h"
#include "agg_conv_clipper.h"
#else
#include "agg_conv_clip_polygon.h"
#endif

#include "agg_conv_clip_polyline.h"
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"

#include <boost/foreach.hpp>
#include <boost/optional.hpp>
#include <boost/ptr_container/ptr_vector.hpp>

#include <iostream>
#include <string>
#include <stdexcept>

#include "mapnik3x_compatibility.hpp"
#include MAPNIK_MAKE_SHARED_INCLUDE
#include MAPNIK_SHARED_INCLUDE

namespace mapnik { namespace vector {

/*
  This processor combines concepts from mapnik's
  feature_style_processor and agg_renderer. It
  differs in that here we only process layers in
  isolation of their styles, and because of this we need
  options for clipping and simplification, for example,
  that would normally come from a style's symbolizers
*/

    template <typename T>
    class processor : private mapnik::noncopyable
    {
    public:
        typedef T backend_type;
    private:
        backend_type & backend_;
        mapnik::Map const& m_;
        mapnik::request const& m_req_;
        double scale_factor_;
        mapnik::CoordTransform t_;
        unsigned tolerance_;
        std::string image_format_;
        scaling_method_e scaling_method_;
        bool painted_;
    public:
        processor(T & backend,
                  mapnik::Map const& map,
                  mapnik::request const& m_req,
                  double scale_factor=1.0,
                  unsigned offset_x=0,
                  unsigned offset_y=0,
                  unsigned tolerance=1,
                  std::string const& image_format="jpeg",
                  scaling_method_e scaling_method=SCALING_NEAR
                  )
            : backend_(backend),
              m_(map),
              m_req_(m_req),
              scale_factor_(scale_factor),
              t_(m_req.width(),m_req.height(),m_req.extent(),offset_x,offset_y),
              tolerance_(tolerance),
              image_format_(image_format),
              scaling_method_(scaling_method),
              painted_(false) {}

        void apply(double scale_denom=0.0)
        {
            mapnik::projection proj(m_.srs(),true);
            if (scale_denom <= 0.0)
            {
                scale_denom = mapnik::scale_denominator(m_req_.scale(),proj.is_geographic());
            }
            scale_denom *= scale_factor_;
            BOOST_FOREACH ( mapnik::layer const& lay, m_.layers() )
            {
                if (lay.visible(scale_denom))
                {
                    apply_to_layer(lay,
                                   proj,
                                   m_req_.scale(),
                                   scale_denom,
                                   m_req_.width(),
                                   m_req_.height(),
                                   m_req_.extent(),
                                   m_req_.buffer_size());
                }
            }
        }

        bool painted() const
        {
            return painted_;
        }

        void apply_to_layer(mapnik::layer const& lay,
                            mapnik::projection const& proj0,
                            double scale,
                            double scale_denom,
                            unsigned width,
                            unsigned height,
                            box2d<double> const& extent,
                            int buffer_size)
        {
            mapnik::datasource_ptr ds = lay.datasource();
            if (!ds)
            {
                return;
            }
            mapnik::projection proj1(lay.srs(),true);
            mapnik::proj_transform prj_trans(proj0,proj1);
            box2d<double> query_ext = extent; // unbuffered
            box2d<double> buffered_query_ext(query_ext);  // buffered
            double buffer_padding = 2.0 * scale;
            boost::optional<int> layer_buffer_size = lay.buffer_size();
            if (layer_buffer_size) // if layer overrides buffer size, use this value to compute buffered extent
            {
                buffer_padding *= *layer_buffer_size;
            }
            else
            {
                buffer_padding *= buffer_size;
            }
            buffered_query_ext.width(query_ext.width() + buffer_padding);
            buffered_query_ext.height(query_ext.height() + buffer_padding);
            // clip buffered extent by maximum extent, if supplied
            boost::optional<box2d<double> > const& maximum_extent = m_.maximum_extent();
            if (maximum_extent)
            {
                buffered_query_ext.clip(*maximum_extent);
            }
            mapnik::box2d<double> layer_ext = lay.envelope();
            bool fw_success = false;
            bool early_return = false;
            // first, try intersection of map extent forward projected into layer srs
            if (prj_trans.forward(buffered_query_ext, PROJ_ENVELOPE_POINTS) && buffered_query_ext.intersects(layer_ext))
            {
                fw_success = true;
                layer_ext.clip(buffered_query_ext);
            }
            // if no intersection and projections are also equal, early return
            else if (prj_trans.equal())
            {
                early_return = true;
            }
            // next try intersection of layer extent back projected into map srs
            else if (prj_trans.backward(layer_ext, PROJ_ENVELOPE_POINTS) && buffered_query_ext.intersects(layer_ext))
            {
                layer_ext.clip(buffered_query_ext);
                // forward project layer extent back into native projection
                if (! prj_trans.forward(layer_ext, PROJ_ENVELOPE_POINTS))
                {
                    std::cerr << "feature_style_processor: Layer=" << lay.name()
                              << " extent=" << layer_ext << " in map projection "
                              << " did not reproject properly back to layer projection";
                }
            }
            else
            {
                // if no intersection then nothing to do for layer
                early_return = true;
            }
            if (early_return)
            {
                return;
            }

            // if we've got this far, now prepare the unbuffered extent
            // which is used as a bbox for clipping geometries
            if (maximum_extent)
            {
                query_ext.clip(*maximum_extent);
            }
            mapnik::box2d<double> layer_ext2 = lay.envelope();
            if (fw_success)
            {
                if (prj_trans.forward(query_ext, PROJ_ENVELOPE_POINTS))
                {
                    layer_ext2.clip(query_ext);
                }
            }
            else
            {
                if (prj_trans.backward(layer_ext2, PROJ_ENVELOPE_POINTS))
                {
                    layer_ext2.clip(query_ext);
                    prj_trans.forward(layer_ext2, PROJ_ENVELOPE_POINTS);
                }
            }
            double qw = query_ext.width()>0 ? query_ext.width() : 1;
            double qh = query_ext.height()>0 ? query_ext.height() : 1;
            mapnik::query::resolution_type res(width/qw,
                                               height/qh);
            mapnik::query q(layer_ext,res,scale_denom,extent);
            mapnik::layer_descriptor lay_desc = ds->get_descriptor();
            BOOST_FOREACH(mapnik::attribute_descriptor const& desc, lay_desc.get_descriptors())
            {
                q.add_property_name(desc.get_name());
            }
            mapnik::featureset_ptr features = ds->features(q);
            if (!features)
            {
                return;
            }
            mapnik::feature_ptr feature = features->next();
            if (feature) {
                backend_.start_tile_layer(lay.name());
                raster_ptr const& source = feature->get_raster();
                if (source)
                {
                    box2d<double> target_ext = box2d<double>(source->ext_);
                    prj_trans.backward(target_ext, PROJ_ENVELOPE_POINTS);
                    box2d<double> ext = t_.forward(target_ext);
                    int start_x = static_cast<int>(std::floor(ext.minx()+.5));
                    int start_y = static_cast<int>(std::floor(ext.miny()+.5));
                    int end_x = static_cast<int>(std::floor(ext.maxx()+.5));
                    int end_y = static_cast<int>(std::floor(ext.maxy()+.5));
                    int raster_width = end_x - start_x;
                    int raster_height = end_y - start_y;
                    if (raster_width > 0 && raster_height > 0)
                    {
                        #if MAPNIK_VERSION >= 300000
                        raster target(target_ext, raster_width, raster_height, source->get_filter_factor());
                        #else
                        raster target(target_ext, raster_width, raster_height);
                        #endif
                        if (!source->premultiplied_alpha_)
                        {
                            agg::rendering_buffer buffer(source->data_.getBytes(),
                                                         source->data_.width(),
                                                         source->data_.height(),
                                                         source->data_.width() * 4);
                            agg::pixfmt_rgba32 pixf(buffer);
                            pixf.premultiply();
                        }
                        if (!prj_trans.equal())
                        {
                            double offset_x = ext.minx() - start_x;
                            double offset_y = ext.miny() - start_y;
                            #if MAPNIK_VERSION >= 300000
                            reproject_and_scale_raster(target, *source, prj_trans,
                                             offset_x, offset_y,
                                             width,
                                             scaling_method_);
                            #else
                            reproject_and_scale_raster(target, *source, prj_trans,
                                             offset_x, offset_y,
                                             width,
                                             2.0,
                                             scaling_method_);
                            #endif
                        }
                        else
                        {
                            double image_ratio_x = ext.width() / source->data_.width();
                            double image_ratio_y = ext.height() / source->data_.height();
                            #if MAPNIK_VERSION >= 300000
                            scale_image_agg<image_data_32>(target.data_,
                                                           source->data_,
                                                           scaling_method_,
                                                           image_ratio_x,
                                                           image_ratio_y,
                                                           0.0,
                                                           0.0,
                                                           source->get_filter_factor());
                            #else
                            scale_image_agg<image_data_32>(target.data_,
                                                           source->data_,
                                                           scaling_method_,
                                                           image_ratio_x,
                                                           image_ratio_y,
                                                           0.0,
                                                           0.0,
                                                           2.0);
                            #endif
                        }
                        mapnik::image_data_32 im_tile(width,height);
                        composite(im_tile, target.data_,
                                  src_over, 1,
                                  start_x, start_y, false);
                        agg::rendering_buffer buffer(im_tile.getBytes(),
                                                     im_tile.width(),
                                                     im_tile.height(),
                                                     im_tile.width() * 4);
                        agg::pixfmt_rgba32 pixf(buffer);
                        pixf.demultiply();
                        backend_.start_tile_feature(*feature);
                        backend_.add_tile_feature_raster(mapnik::save_to_string(im_tile,image_format_));
                    }
                    backend_.stop_tile_layer();
                    return;
                }
                // vector pathway
                while (feature)
                {
                    boost::ptr_vector<mapnik::geometry_type> & paths = feature->paths();
                    if (paths.empty()) {
                        feature = features->next();
                        continue;
                    }
                    backend_.start_tile_feature(*feature);
                    BOOST_FOREACH( mapnik::geometry_type & geom, paths)
                    {
                        mapnik::box2d<double> geom_box = geom.envelope();
                        if (!geom_box.intersects(buffered_query_ext))
                        {
                            continue;
                        }
                        if (handle_geometry(geom,
                                            prj_trans,
                                            buffered_query_ext) > 0)
                        {
                            painted_ = true;
                        }
                    }
                    backend_.stop_tile_feature();
                    feature = features->next();
                }
                backend_.stop_tile_layer();
            }
        }

        unsigned handle_geometry(mapnik::geometry_type & geom,
                                 mapnik::proj_transform const& prj_trans,
                                 mapnik::box2d<double> const& buffered_query_ext)
        {
            unsigned path_count = 0;
            switch (geom.type())
            {
            case MAPNIK_POINT:
            {
                if (geom.size() > 0)
                {
                    typedef mapnik::coord_transform<mapnik::CoordTransform,
                        mapnik::geometry_type> path_type;
                    path_type path(t_, geom, prj_trans);
                    path_count = backend_.add_path(path, tolerance_, geom.type());
                }
                break;
            }
            case MAPNIK_LINESTRING:
            {
                if (geom.size() > 1)
                {
                    typedef agg::conv_clip_polyline<mapnik::geometry_type> line_clipper;
                    line_clipper clipped(geom);
                    clipped.clip_box(
                        buffered_query_ext.minx(),
                        buffered_query_ext.miny(),
                        buffered_query_ext.maxx(),
                        buffered_query_ext.maxy());
                    typedef mapnik::coord_transform<mapnik::CoordTransform, line_clipper> path_type;
                    path_type path(t_, clipped, prj_trans);
                    path_count = backend_.add_path(path, tolerance_, geom.type());
                }
                break;
            }
            case MAPNIK_POLYGON:
            {
                if (geom.size() > 2)
                {
#ifdef CONV_CLIPPER
                    agg::path_storage ps;
                    ps.move_to(buffered_query_ext.minx(), buffered_query_ext.miny());
                    ps.line_to(buffered_query_ext.minx(), buffered_query_ext.maxy());
                    ps.line_to(buffered_query_ext.maxx(), buffered_query_ext.maxy());
                    ps.line_to(buffered_query_ext.maxx(), buffered_query_ext.miny());
                    ps.close_polygon();
                    typedef agg::conv_clipper<mapnik::geometry_type, agg::path_storage> poly_clipper;
                    poly_clipper clipped(geom,ps,
                                         agg::clipper_and,
                                         agg::clipper_non_zero,
                                         agg::clipper_non_zero,
                                         1);
                    //clipped.rewind(0);
#else
                    typedef agg::conv_clip_polygon<mapnik::geometry_type> poly_clipper;
                    poly_clipper clipped(geom);
                    clipped.clip_box(
                        buffered_query_ext.minx(),
                        buffered_query_ext.miny(),
                        buffered_query_ext.maxx(),
                        buffered_query_ext.maxy());
#endif
                    typedef mapnik::coord_transform<mapnik::CoordTransform, poly_clipper> path_type;
                    path_type path(t_, clipped, prj_trans);
                    path_count = backend_.add_path(path, tolerance_, geom.type());
                }
                break;
            }
            case MAPNIK_UNKNOWN:
            default:
            {
                throw std::runtime_error("unhandled geometry type");
                break;
            }
            }
            return path_count;
        }
    };

    }} // end ns

#endif // __MAPNIK_VECTOR_TILE_PROCESSOR_H__
<commit_msg>Include mapnik/image_compositing.hpp for the composite function<commit_after>#ifndef __MAPNIK_VECTOR_PROCESSOR_H__
#define __MAPNIK_VECTOR_PROCESSOR_H__

#include <mapnik/map.hpp>
#include <mapnik/request.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/query.hpp>
#include <mapnik/ctrans.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/proj_transform.hpp>
#include <mapnik/scale_denominator.hpp>
#include <mapnik/attribute_descriptor.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/config.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/version.hpp>
#include <mapnik/noncopyable.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/raster.hpp>
#include <mapnik/warp.hpp>
#include <mapnik/version.hpp>
#include <mapnik/image_scaling.hpp>
#include <mapnik/image_compositing.hpp>

// agg
#ifdef CONV_CLIPPER
#include "agg_path_storage.h"
#include "agg_conv_clipper.h"
#else
#include "agg_conv_clip_polygon.h"
#endif

#include "agg_conv_clip_polyline.h"
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"

#include <boost/foreach.hpp>
#include <boost/optional.hpp>
#include <boost/ptr_container/ptr_vector.hpp>

#include <iostream>
#include <string>
#include <stdexcept>

#include "mapnik3x_compatibility.hpp"
#include MAPNIK_MAKE_SHARED_INCLUDE
#include MAPNIK_SHARED_INCLUDE

namespace mapnik { namespace vector {

/*
  This processor combines concepts from mapnik's
  feature_style_processor and agg_renderer. It
  differs in that here we only process layers in
  isolation of their styles, and because of this we need
  options for clipping and simplification, for example,
  that would normally come from a style's symbolizers
*/

    template <typename T>
    class processor : private mapnik::noncopyable
    {
    public:
        typedef T backend_type;
    private:
        backend_type & backend_;
        mapnik::Map const& m_;
        mapnik::request const& m_req_;
        double scale_factor_;
        mapnik::CoordTransform t_;
        unsigned tolerance_;
        std::string image_format_;
        scaling_method_e scaling_method_;
        bool painted_;
    public:
        processor(T & backend,
                  mapnik::Map const& map,
                  mapnik::request const& m_req,
                  double scale_factor=1.0,
                  unsigned offset_x=0,
                  unsigned offset_y=0,
                  unsigned tolerance=1,
                  std::string const& image_format="jpeg",
                  scaling_method_e scaling_method=SCALING_NEAR
                  )
            : backend_(backend),
              m_(map),
              m_req_(m_req),
              scale_factor_(scale_factor),
              t_(m_req.width(),m_req.height(),m_req.extent(),offset_x,offset_y),
              tolerance_(tolerance),
              image_format_(image_format),
              scaling_method_(scaling_method),
              painted_(false) {}

        void apply(double scale_denom=0.0)
        {
            mapnik::projection proj(m_.srs(),true);
            if (scale_denom <= 0.0)
            {
                scale_denom = mapnik::scale_denominator(m_req_.scale(),proj.is_geographic());
            }
            scale_denom *= scale_factor_;
            BOOST_FOREACH ( mapnik::layer const& lay, m_.layers() )
            {
                if (lay.visible(scale_denom))
                {
                    apply_to_layer(lay,
                                   proj,
                                   m_req_.scale(),
                                   scale_denom,
                                   m_req_.width(),
                                   m_req_.height(),
                                   m_req_.extent(),
                                   m_req_.buffer_size());
                }
            }
        }

        bool painted() const
        {
            return painted_;
        }

        void apply_to_layer(mapnik::layer const& lay,
                            mapnik::projection const& proj0,
                            double scale,
                            double scale_denom,
                            unsigned width,
                            unsigned height,
                            box2d<double> const& extent,
                            int buffer_size)
        {
            mapnik::datasource_ptr ds = lay.datasource();
            if (!ds)
            {
                return;
            }
            mapnik::projection proj1(lay.srs(),true);
            mapnik::proj_transform prj_trans(proj0,proj1);
            box2d<double> query_ext = extent; // unbuffered
            box2d<double> buffered_query_ext(query_ext);  // buffered
            double buffer_padding = 2.0 * scale;
            boost::optional<int> layer_buffer_size = lay.buffer_size();
            if (layer_buffer_size) // if layer overrides buffer size, use this value to compute buffered extent
            {
                buffer_padding *= *layer_buffer_size;
            }
            else
            {
                buffer_padding *= buffer_size;
            }
            buffered_query_ext.width(query_ext.width() + buffer_padding);
            buffered_query_ext.height(query_ext.height() + buffer_padding);
            // clip buffered extent by maximum extent, if supplied
            boost::optional<box2d<double> > const& maximum_extent = m_.maximum_extent();
            if (maximum_extent)
            {
                buffered_query_ext.clip(*maximum_extent);
            }
            mapnik::box2d<double> layer_ext = lay.envelope();
            bool fw_success = false;
            bool early_return = false;
            // first, try intersection of map extent forward projected into layer srs
            if (prj_trans.forward(buffered_query_ext, PROJ_ENVELOPE_POINTS) && buffered_query_ext.intersects(layer_ext))
            {
                fw_success = true;
                layer_ext.clip(buffered_query_ext);
            }
            // if no intersection and projections are also equal, early return
            else if (prj_trans.equal())
            {
                early_return = true;
            }
            // next try intersection of layer extent back projected into map srs
            else if (prj_trans.backward(layer_ext, PROJ_ENVELOPE_POINTS) && buffered_query_ext.intersects(layer_ext))
            {
                layer_ext.clip(buffered_query_ext);
                // forward project layer extent back into native projection
                if (! prj_trans.forward(layer_ext, PROJ_ENVELOPE_POINTS))
                {
                    std::cerr << "feature_style_processor: Layer=" << lay.name()
                              << " extent=" << layer_ext << " in map projection "
                              << " did not reproject properly back to layer projection";
                }
            }
            else
            {
                // if no intersection then nothing to do for layer
                early_return = true;
            }
            if (early_return)
            {
                return;
            }

            // if we've got this far, now prepare the unbuffered extent
            // which is used as a bbox for clipping geometries
            if (maximum_extent)
            {
                query_ext.clip(*maximum_extent);
            }
            mapnik::box2d<double> layer_ext2 = lay.envelope();
            if (fw_success)
            {
                if (prj_trans.forward(query_ext, PROJ_ENVELOPE_POINTS))
                {
                    layer_ext2.clip(query_ext);
                }
            }
            else
            {
                if (prj_trans.backward(layer_ext2, PROJ_ENVELOPE_POINTS))
                {
                    layer_ext2.clip(query_ext);
                    prj_trans.forward(layer_ext2, PROJ_ENVELOPE_POINTS);
                }
            }
            double qw = query_ext.width()>0 ? query_ext.width() : 1;
            double qh = query_ext.height()>0 ? query_ext.height() : 1;
            mapnik::query::resolution_type res(width/qw,
                                               height/qh);
            mapnik::query q(layer_ext,res,scale_denom,extent);
            mapnik::layer_descriptor lay_desc = ds->get_descriptor();
            BOOST_FOREACH(mapnik::attribute_descriptor const& desc, lay_desc.get_descriptors())
            {
                q.add_property_name(desc.get_name());
            }
            mapnik::featureset_ptr features = ds->features(q);
            if (!features)
            {
                return;
            }
            mapnik::feature_ptr feature = features->next();
            if (feature) {
                backend_.start_tile_layer(lay.name());
                raster_ptr const& source = feature->get_raster();
                if (source)
                {
                    box2d<double> target_ext = box2d<double>(source->ext_);
                    prj_trans.backward(target_ext, PROJ_ENVELOPE_POINTS);
                    box2d<double> ext = t_.forward(target_ext);
                    int start_x = static_cast<int>(std::floor(ext.minx()+.5));
                    int start_y = static_cast<int>(std::floor(ext.miny()+.5));
                    int end_x = static_cast<int>(std::floor(ext.maxx()+.5));
                    int end_y = static_cast<int>(std::floor(ext.maxy()+.5));
                    int raster_width = end_x - start_x;
                    int raster_height = end_y - start_y;
                    if (raster_width > 0 && raster_height > 0)
                    {
                        #if MAPNIK_VERSION >= 300000
                        raster target(target_ext, raster_width, raster_height, source->get_filter_factor());
                        #else
                        raster target(target_ext, raster_width, raster_height);
                        #endif
                        if (!source->premultiplied_alpha_)
                        {
                            agg::rendering_buffer buffer(source->data_.getBytes(),
                                                         source->data_.width(),
                                                         source->data_.height(),
                                                         source->data_.width() * 4);
                            agg::pixfmt_rgba32 pixf(buffer);
                            pixf.premultiply();
                        }
                        if (!prj_trans.equal())
                        {
                            double offset_x = ext.minx() - start_x;
                            double offset_y = ext.miny() - start_y;
                            #if MAPNIK_VERSION >= 300000
                            reproject_and_scale_raster(target, *source, prj_trans,
                                             offset_x, offset_y,
                                             width,
                                             scaling_method_);
                            #else
                            reproject_and_scale_raster(target, *source, prj_trans,
                                             offset_x, offset_y,
                                             width,
                                             2.0,
                                             scaling_method_);
                            #endif
                        }
                        else
                        {
                            double image_ratio_x = ext.width() / source->data_.width();
                            double image_ratio_y = ext.height() / source->data_.height();
                            #if MAPNIK_VERSION >= 300000
                            scale_image_agg<image_data_32>(target.data_,
                                                           source->data_,
                                                           scaling_method_,
                                                           image_ratio_x,
                                                           image_ratio_y,
                                                           0.0,
                                                           0.0,
                                                           source->get_filter_factor());
                            #else
                            scale_image_agg<image_data_32>(target.data_,
                                                           source->data_,
                                                           scaling_method_,
                                                           image_ratio_x,
                                                           image_ratio_y,
                                                           0.0,
                                                           0.0,
                                                           2.0);
                            #endif
                        }
                        mapnik::image_data_32 im_tile(width,height);
                        composite(im_tile, target.data_,
                                  src_over, 1,
                                  start_x, start_y, false);
                        agg::rendering_buffer buffer(im_tile.getBytes(),
                                                     im_tile.width(),
                                                     im_tile.height(),
                                                     im_tile.width() * 4);
                        agg::pixfmt_rgba32 pixf(buffer);
                        pixf.demultiply();
                        backend_.start_tile_feature(*feature);
                        backend_.add_tile_feature_raster(mapnik::save_to_string(im_tile,image_format_));
                    }
                    backend_.stop_tile_layer();
                    return;
                }
                // vector pathway
                while (feature)
                {
                    boost::ptr_vector<mapnik::geometry_type> & paths = feature->paths();
                    if (paths.empty()) {
                        feature = features->next();
                        continue;
                    }
                    backend_.start_tile_feature(*feature);
                    BOOST_FOREACH( mapnik::geometry_type & geom, paths)
                    {
                        mapnik::box2d<double> geom_box = geom.envelope();
                        if (!geom_box.intersects(buffered_query_ext))
                        {
                            continue;
                        }
                        if (handle_geometry(geom,
                                            prj_trans,
                                            buffered_query_ext) > 0)
                        {
                            painted_ = true;
                        }
                    }
                    backend_.stop_tile_feature();
                    feature = features->next();
                }
                backend_.stop_tile_layer();
            }
        }

        unsigned handle_geometry(mapnik::geometry_type & geom,
                                 mapnik::proj_transform const& prj_trans,
                                 mapnik::box2d<double> const& buffered_query_ext)
        {
            unsigned path_count = 0;
            switch (geom.type())
            {
            case MAPNIK_POINT:
            {
                if (geom.size() > 0)
                {
                    typedef mapnik::coord_transform<mapnik::CoordTransform,
                        mapnik::geometry_type> path_type;
                    path_type path(t_, geom, prj_trans);
                    path_count = backend_.add_path(path, tolerance_, geom.type());
                }
                break;
            }
            case MAPNIK_LINESTRING:
            {
                if (geom.size() > 1)
                {
                    typedef agg::conv_clip_polyline<mapnik::geometry_type> line_clipper;
                    line_clipper clipped(geom);
                    clipped.clip_box(
                        buffered_query_ext.minx(),
                        buffered_query_ext.miny(),
                        buffered_query_ext.maxx(),
                        buffered_query_ext.maxy());
                    typedef mapnik::coord_transform<mapnik::CoordTransform, line_clipper> path_type;
                    path_type path(t_, clipped, prj_trans);
                    path_count = backend_.add_path(path, tolerance_, geom.type());
                }
                break;
            }
            case MAPNIK_POLYGON:
            {
                if (geom.size() > 2)
                {
#ifdef CONV_CLIPPER
                    agg::path_storage ps;
                    ps.move_to(buffered_query_ext.minx(), buffered_query_ext.miny());
                    ps.line_to(buffered_query_ext.minx(), buffered_query_ext.maxy());
                    ps.line_to(buffered_query_ext.maxx(), buffered_query_ext.maxy());
                    ps.line_to(buffered_query_ext.maxx(), buffered_query_ext.miny());
                    ps.close_polygon();
                    typedef agg::conv_clipper<mapnik::geometry_type, agg::path_storage> poly_clipper;
                    poly_clipper clipped(geom,ps,
                                         agg::clipper_and,
                                         agg::clipper_non_zero,
                                         agg::clipper_non_zero,
                                         1);
                    //clipped.rewind(0);
#else
                    typedef agg::conv_clip_polygon<mapnik::geometry_type> poly_clipper;
                    poly_clipper clipped(geom);
                    clipped.clip_box(
                        buffered_query_ext.minx(),
                        buffered_query_ext.miny(),
                        buffered_query_ext.maxx(),
                        buffered_query_ext.maxy());
#endif
                    typedef mapnik::coord_transform<mapnik::CoordTransform, poly_clipper> path_type;
                    path_type path(t_, clipped, prj_trans);
                    path_count = backend_.add_path(path, tolerance_, geom.type());
                }
                break;
            }
            case MAPNIK_UNKNOWN:
            default:
            {
                throw std::runtime_error("unhandled geometry type");
                break;
            }
            }
            return path_count;
        }
    };

    }} // end ns

#endif // __MAPNIK_VECTOR_TILE_PROCESSOR_H__
<|endoftext|>


<commit_before>#include <functional>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

#include <ros/init.h>
#include <ros/node_handle.h>
#include <ros/rate.h>
#include <ros/spinner.h>
#include <sensor_msgs/JointState.h>
#include <xmlrpcpp/XmlRpc.h>

#include <franka/gripper_state.h>
#include <franka_gripper/franka_gripper.h>

namespace {

template <typename T_action, typename T_goal, typename T_result>
void handleErrors(actionlib::SimpleActionServer<T_action>* server,
                  std::function<bool(const T_goal&)> handler,
                  const T_goal& goal) {
  T_result result;
  try {
    result.success = handler(goal);
    server->setSucceeded(result);
  } catch (const franka::Exception& ex) {
    ROS_ERROR_STREAM("" << ex.what());
    result.success = false;
    result.error = ex.what();
    server->setAborted(result);
  }
}

}  // anonymous namespace

using actionlib::SimpleActionServer;
using control_msgs::GripperCommandAction;
using franka_gripper::GraspAction;
using franka_gripper::MoveAction;
using franka_gripper::HomingAction;
using franka_gripper::StopAction;
using franka_gripper::GraspGoalConstPtr;
using franka_gripper::MoveGoalConstPtr;
using franka_gripper::StopGoalConstPtr;
using franka_gripper::HomingGoalConstPtr;
using franka_gripper::HomingResult;
using franka_gripper::GraspResult;
using franka_gripper::MoveResult;
using franka_gripper::StopResult;
using franka_gripper::homing;
using franka_gripper::stop;
using franka_gripper::grasp;
using franka_gripper::move;
using franka_gripper::gripperCommandExecuteCallback;
using franka_gripper::getGripperState;

int main(int argc, char** argv) {
  ros::init(argc, argv, "franka_gripper_node");
  ros::NodeHandle node_handle("~");
  std::string robot_ip;
  if (!node_handle.getParam("robot_ip", robot_ip)) {
    ROS_ERROR("franka_gripper_node: Could not parse robot_ip parameter");
    return -1;
  }
  double width_tolerance(0.01);
  if (node_handle.getParam("width_tolerance", width_tolerance)) {
    ROS_INFO_STREAM("franka_gripper_node: Found width_tolerance"
                    << width_tolerance);
  }

  double default_speed(0.1);
  if (node_handle.getParam("default_speed", default_speed)) {
    ROS_INFO_STREAM("franka_gripper_node: Found default_speed"
                    << default_speed);
  }

  double newton_to_m_ampere_factor(14.9);
  if (node_handle.getParam("newton_to_m_ampere_factor",
                           newton_to_m_ampere_factor)) {
    ROS_INFO_STREAM("franka_gripper_node: Found newton_to_m_ampere_factor"
                    << newton_to_m_ampere_factor);
  }

  franka::Gripper gripper(robot_ip);

  std::function<bool(const HomingGoalConstPtr&)> homing_handler =
      std::bind(homing, std::cref(gripper), std::placeholders::_1);
  std::function<bool(const StopGoalConstPtr&)> stop_handler =
      std::bind(stop, std::cref(gripper), std::placeholders::_1);
  std::function<bool(const GraspGoalConstPtr&)> grasp_handler =
      std::bind(grasp, std::cref(gripper), std::placeholders::_1);
  std::function<bool(const MoveGoalConstPtr&)> move_handler =
      std::bind(move, std::cref(gripper), std::placeholders::_1);

  SimpleActionServer<HomingAction> homing_action_server_(
      node_handle, "homing",
      std::bind(handleErrors<HomingAction, HomingGoalConstPtr, HomingResult>,
                &homing_action_server_, homing_handler, std::placeholders::_1),
      false);

  SimpleActionServer<StopAction> stop_action_server_(
      node_handle, "stop",
      std::bind(handleErrors<StopAction, StopGoalConstPtr, StopResult>,
                &stop_action_server_, stop_handler, std::placeholders::_1),
      false);

  SimpleActionServer<MoveAction> move_action_server_(
      node_handle, "move",
      std::bind(handleErrors<MoveAction, MoveGoalConstPtr, MoveResult>,
                &move_action_server_, move_handler, std::placeholders::_1),
      false);

  SimpleActionServer<GraspAction> grasp_action_server_(
      node_handle, "grasp",
      std::bind(handleErrors<GraspAction, GraspGoalConstPtr, GraspResult>,
                &grasp_action_server_, grasp_handler, std::placeholders::_1),
      false);

  SimpleActionServer<GripperCommandAction> gripper_command_action_server(
      node_handle, "gripper_action",
      std::bind(&gripperCommandExecuteCallback, std::cref(gripper),
                default_speed, newton_to_m_ampere_factor,
                &gripper_command_action_server, std::placeholders::_1),
      false);

  homing_action_server_.start();
  stop_action_server_.start();
  move_action_server_.start();
  grasp_action_server_.start();
  gripper_command_action_server.start();

  double publish_rate(30.0);
  if (!node_handle.getParam("publish_rate", publish_rate)) {
    ROS_INFO_STREAM(
        "franka_gripper_node: Could not find parameter publish_rate. "
        "Defaulting to "
        << publish_rate);
  }

  XmlRpc::XmlRpcValue params;
  if (!node_handle.getParam("joint_names", params)) {
    ROS_ERROR("franka_gripper_node: Could not parse joint_names!");
    return -1;
  }
  if (params.size() != 2) {
    ROS_ERROR("franka_gripper_node: Got wrong number of joint_names!");
    return -1;
  }
  std::vector<std::string> joint_names(params.size());
  for (int i = 0; i < params.size(); ++i) {
    joint_names[i] = static_cast<std::string>(params[i]);
  }

  franka::GripperState gripper_state;
  std::mutex lock;
  std::thread read_thread([&gripper_state, &gripper, &lock]() {
    ros::Rate read_rate(10);
    franka::GripperState new_gripper_state;

    while (ros::ok()) {
      if (getGripperState(gripper, &new_gripper_state) && lock.try_lock()) {
        gripper_state = new_gripper_state;
        lock.unlock();
      }
      read_rate.sleep();
    }
  });

  ros::Publisher gripper_state_publisher =
      node_handle.advertise<sensor_msgs::JointState>("joint_states", 1);
  ros::AsyncSpinner spinner(2);
  spinner.start();
  ros::Rate rate(publish_rate);
  while (ros::ok()) {
    if (lock.try_lock()) {
      sensor_msgs::JointState joint_states;
      joint_states.header.stamp = ros::Time::now();
      joint_states.name.push_back(joint_names[0]);
      joint_states.name.push_back(joint_names[1]);
      joint_states.position.push_back(gripper_state.width * 0.5);
      joint_states.position.push_back(gripper_state.width * 0.5);
      joint_states.velocity.push_back(0.0);
      joint_states.velocity.push_back(0.0);
      joint_states.effort.push_back(0.0);
      joint_states.effort.push_back(0.0);
      gripper_state_publisher.publish(joint_states);
      lock.unlock();
    }
    rate.sleep();
  }
  read_thread.join();
  return 0;
}
<commit_msg>changed to lock_guard<commit_after>#include <functional>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

#include <ros/init.h>
#include <ros/node_handle.h>
#include <ros/rate.h>
#include <ros/spinner.h>
#include <sensor_msgs/JointState.h>
#include <xmlrpcpp/XmlRpc.h>

#include <franka/gripper_state.h>
#include <franka_gripper/franka_gripper.h>

namespace {

template <typename T_action, typename T_goal, typename T_result>
void handleErrors(actionlib::SimpleActionServer<T_action>* server,
                  std::function<bool(const T_goal&)> handler,
                  const T_goal& goal) {
  T_result result;
  try {
    result.success = handler(goal);
    server->setSucceeded(result);
  } catch (const franka::Exception& ex) {
    ROS_ERROR_STREAM("" << ex.what());
    result.success = false;
    result.error = ex.what();
    server->setAborted(result);
  }
}

}  // anonymous namespace

using actionlib::SimpleActionServer;
using control_msgs::GripperCommandAction;
using franka_gripper::GraspAction;
using franka_gripper::MoveAction;
using franka_gripper::HomingAction;
using franka_gripper::StopAction;
using franka_gripper::GraspGoalConstPtr;
using franka_gripper::MoveGoalConstPtr;
using franka_gripper::StopGoalConstPtr;
using franka_gripper::HomingGoalConstPtr;
using franka_gripper::HomingResult;
using franka_gripper::GraspResult;
using franka_gripper::MoveResult;
using franka_gripper::StopResult;
using franka_gripper::homing;
using franka_gripper::stop;
using franka_gripper::grasp;
using franka_gripper::move;
using franka_gripper::gripperCommandExecuteCallback;
using franka_gripper::getGripperState;

int main(int argc, char** argv) {
  ros::init(argc, argv, "franka_gripper_node");
  ros::NodeHandle node_handle("~");
  std::string robot_ip;
  if (!node_handle.getParam("robot_ip", robot_ip)) {
    ROS_ERROR("franka_gripper_node: Could not parse robot_ip parameter");
    return -1;
  }
  double width_tolerance(0.01);
  if (node_handle.getParam("width_tolerance", width_tolerance)) {
    ROS_INFO_STREAM("franka_gripper_node: Found width_tolerance"
                    << width_tolerance);
  }

  double default_speed(0.1);
  if (node_handle.getParam("default_speed", default_speed)) {
    ROS_INFO_STREAM("franka_gripper_node: Found default_speed"
                    << default_speed);
  }

  double newton_to_m_ampere_factor(14.9);
  if (node_handle.getParam("newton_to_m_ampere_factor",
                           newton_to_m_ampere_factor)) {
    ROS_INFO_STREAM("franka_gripper_node: Found newton_to_m_ampere_factor"
                    << newton_to_m_ampere_factor);
  }

  franka::Gripper gripper(robot_ip);

  std::function<bool(const HomingGoalConstPtr&)> homing_handler =
      std::bind(homing, std::cref(gripper), std::placeholders::_1);
  std::function<bool(const StopGoalConstPtr&)> stop_handler =
      std::bind(stop, std::cref(gripper), std::placeholders::_1);
  std::function<bool(const GraspGoalConstPtr&)> grasp_handler =
      std::bind(grasp, std::cref(gripper), std::placeholders::_1);
  std::function<bool(const MoveGoalConstPtr&)> move_handler =
      std::bind(move, std::cref(gripper), std::placeholders::_1);

  SimpleActionServer<HomingAction> homing_action_server_(
      node_handle, "homing",
      std::bind(handleErrors<HomingAction, HomingGoalConstPtr, HomingResult>,
                &homing_action_server_, homing_handler, std::placeholders::_1),
      false);

  SimpleActionServer<StopAction> stop_action_server_(
      node_handle, "stop",
      std::bind(handleErrors<StopAction, StopGoalConstPtr, StopResult>,
                &stop_action_server_, stop_handler, std::placeholders::_1),
      false);

  SimpleActionServer<MoveAction> move_action_server_(
      node_handle, "move",
      std::bind(handleErrors<MoveAction, MoveGoalConstPtr, MoveResult>,
                &move_action_server_, move_handler, std::placeholders::_1),
      false);

  SimpleActionServer<GraspAction> grasp_action_server_(
      node_handle, "grasp",
      std::bind(handleErrors<GraspAction, GraspGoalConstPtr, GraspResult>,
                &grasp_action_server_, grasp_handler, std::placeholders::_1),
      false);

  SimpleActionServer<GripperCommandAction> gripper_command_action_server(
      node_handle, "gripper_action",
      std::bind(&gripperCommandExecuteCallback, std::cref(gripper),
                default_speed, newton_to_m_ampere_factor,
                &gripper_command_action_server, std::placeholders::_1),
      false);

  homing_action_server_.start();
  stop_action_server_.start();
  move_action_server_.start();
  grasp_action_server_.start();
  gripper_command_action_server.start();

  double publish_rate(30.0);
  if (!node_handle.getParam("publish_rate", publish_rate)) {
    ROS_INFO_STREAM(
        "franka_gripper_node: Could not find parameter publish_rate. "
        "Defaulting to "
        << publish_rate);
  }

  XmlRpc::XmlRpcValue params;
  if (!node_handle.getParam("joint_names", params)) {
    ROS_ERROR("franka_gripper_node: Could not parse joint_names!");
    return -1;
  }
  if (params.size() != 2) {
    ROS_ERROR("franka_gripper_node: Got wrong number of joint_names!");
    return -1;
  }
  std::vector<std::string> joint_names(params.size());
  for (int i = 0; i < params.size(); ++i) {
    joint_names[i] = static_cast<std::string>(params[i]);
  }

  franka::GripperState gripper_state;
  std::mutex gripper_state_mutex;
  std::thread read_thread([&gripper_state, &gripper, &gripper_state_mutex]() {
    ros::Rate read_rate(10);
    franka::GripperState new_gripper_state;
    while (read_rate.sleep() && ros::ok()) {
      std::lock_guard<std::mutex> lock(gripper_state_mutex);
      if (getGripperState(gripper, &new_gripper_state) &&
          gripper_state_mutex.try_lock()) {
        gripper_state = new_gripper_state;
      }
    }
  });

  ros::Publisher gripper_state_publisher =
      node_handle.advertise<sensor_msgs::JointState>("joint_states", 1);
  ros::AsyncSpinner spinner(2);
  spinner.start();
  ros::Rate rate(publish_rate);
  while (ros::ok()) {
    if (gripper_state_mutex.try_lock()) {
      sensor_msgs::JointState joint_states;
      joint_states.header.stamp = ros::Time::now();
      joint_states.name.push_back(joint_names[0]);
      joint_states.name.push_back(joint_names[1]);
      joint_states.position.push_back(gripper_state.width * 0.5);
      joint_states.position.push_back(gripper_state.width * 0.5);
      joint_states.velocity.push_back(0.0);
      joint_states.velocity.push_back(0.0);
      joint_states.effort.push_back(0.0);
      joint_states.effort.push_back(0.0);
      gripper_state_publisher.publish(joint_states);
      gripper_state_mutex.unlock();
    }
    rate.sleep();
  }
  read_thread.join();
  return 0;
}
<|endoftext|>


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

#include "waterlevel.h"

using namespace upm;

WaterLevel::WaterLevel(int pin)
{
    m_gpio = mraa_gpio_init(pin);
    mraa_gpio_dir(m_gpio, MRAA_GPIO_IN);
}

WaterLevel::~WaterLevel()
{
    mraa_gpio_close(m_gpio);
}

bool WaterLevel::isSubmerged()
{
	// Submerged causes 0; being above water is 1
	return (!(bool)mraa_gpio_read(m_gpio));
}
<commit_msg>waterlevel: throw exception(s) on fatal errors<commit_after>/*
 * Author: Zion Orent <sorent@ics.com>
 * Copyright (c) 2015 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <string>
#include <stdexcept>
#include "waterlevel.h"

using namespace upm;

WaterLevel::WaterLevel(int pin)
{
    if ( !(m_gpio = mraa_gpio_init(pin)) )
      {
        throw std::invalid_argument(std::string(__FUNCTION__) +
                                    ": mraa_gpio_init() failed, invalid pin?");
        return;
      }
    mraa_gpio_dir(m_gpio, MRAA_GPIO_IN);
}

WaterLevel::~WaterLevel()
{
    mraa_gpio_close(m_gpio);
}

bool WaterLevel::isSubmerged()
{
	// Submerged causes 0; being above water is 1
	return (!(bool)mraa_gpio_read(m_gpio));
}
<|endoftext|>


<commit_before>/*
 * FreeGaitActionServer.cpp
 *
 *  Created on: Feb 6, 2015
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#include <free_gait_ros/FreeGaitActionServer.hpp>
#include <free_gait_core/free_gait_core.hpp>

// ROS
#include <free_gait_msgs/ExecuteStepsFeedback.h>
#include <free_gait_msgs/ExecuteStepsResult.h>

#include <iostream>

namespace free_gait {

FreeGaitActionServer::FreeGaitActionServer(ros::NodeHandle nodeHandle, const std::string& name,
                                           std::shared_ptr<Executor> executor)
    : nodeHandle_(nodeHandle),
      name_(name),
      executor_(executor),
      rosConverter_(executor),
      server_(nodeHandle_, name_, false),
      isPreempting_(false)
{
}

FreeGaitActionServer::~FreeGaitActionServer()
{
}

void FreeGaitActionServer::initialize()
{
  server_.registerGoalCallback(boost::bind(&FreeGaitActionServer::goalCallback, this));
  server_.registerPreemptCallback(boost::bind(&FreeGaitActionServer::preemptCallback, this));
  server_.start();
  ROS_INFO_STREAM("Started " << name_ << " action server.");
}

void FreeGaitActionServer::update()
{
  if (!server_.isActive()) return;
  if (executor_->getQueue().empty()) {
    // Succeeded.
    if (isPreempting_) {
      // Preempted.
      setPreempted();
    } else {
      setSucceeded();
    }
  } else {
    // Ongoing.
    publishFeedback();
  }
}

void FreeGaitActionServer::shutdown()
{
  server_.shutdown();
}

void FreeGaitActionServer::goalCallback()
{
  ROS_DEBUG("Received goal for StepAction.");
//  if (server_.isActive()) server_.setRejected();

  const auto goal = server_.acceptNewGoal();

  for (auto& stepMessage : goal->steps) {
    Step step;
    rosConverter_.fromMessage(stepMessage, step);
    Executor::Lock lock(executor_->getMutex());
    executor_->getQueue().add(step);
  }
}

void FreeGaitActionServer::preemptCallback()
{
  ROS_INFO("StepAction is requested to preempt.");
  if (executor_->getQueue().empty()) return;
  if (executor_->getQueue().size() <= 1) return;
  Executor::Lock lock(executor_->getMutex());
  executor_->getQueue().clearNextSteps();
  isPreempting_ = true;
}

void FreeGaitActionServer::publishFeedback()
{
  free_gait_msgs::ExecuteStepsFeedback feedback;
  if (executor_->getQueue().empty()) return;
//  const auto& step = executor_->getQueue().getCurrentStep();
  feedback.queue_size = executor_->getQueue().size();

//  if (step.checkStatus() == false) {
//    feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_PAUSED;
//    feedback.description = "Paused.";
//  } else {
//    switch (step.getState()) {
//      feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_EXECUTING;
//      case Step::State::PreStep:
//        feedback.description = "Pre step.";
//        break;
//      case Step::State::AtStep:
//        feedback.description = "At step.";
//        break;
//      case Step::State::PostStep:
//        feedback.description = "Post step.";
//        break;
//      default:
//        feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_UNKNOWN;
//        feedback.description = "Unknown.";
//        break;
//    }
//  }

//  feedback.duration = ros::Duration(step.getTotalDuration());
//  feedback.phase = step.getTotalPhase();
//  for (const auto& stepData : step.getSwingData())
//    feedback.swing_leg_names.push_back(stepData.first);

  server_.publishFeedback(feedback);
}

void FreeGaitActionServer::setSucceeded()
{
  ROS_INFO("StepAction succeeded.");
  free_gait_msgs::ExecuteStepsResult result;
  result.status = free_gait_msgs::ExecuteStepsResult::RESULT_REACHED;
  server_.setSucceeded(result, "Step action has been reached.");
}

void FreeGaitActionServer::setPreempted()
{
  ROS_INFO("StepAction preempted.");
  free_gait_msgs::ExecuteStepsResult result;
  result.status = free_gait_msgs::ExecuteStepsResult::RESULT_FAILED;
  server_.setPreempted(result, "Step action has been preempted.");
  isPreempting_ = false;
}

void FreeGaitActionServer::setAborted()
{
  ROS_INFO("StepAction aborted.");
  free_gait_msgs::ExecuteStepsResult result;
  result.status = free_gait_msgs::ExecuteStepsResult::RESULT_FAILED;
  server_.setAborted(result, "Step action has failed.");
}

} /* namespace */
<commit_msg>Trying to improve reliability of mutex locking.<commit_after>/*
 * FreeGaitActionServer.cpp
 *
 *  Created on: Feb 6, 2015
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#include <free_gait_ros/FreeGaitActionServer.hpp>
#include <free_gait_core/free_gait_core.hpp>

// ROS
#include <free_gait_msgs/ExecuteStepsFeedback.h>
#include <free_gait_msgs/ExecuteStepsResult.h>

#include <iostream>

namespace free_gait {

FreeGaitActionServer::FreeGaitActionServer(ros::NodeHandle nodeHandle, const std::string& name,
                                           std::shared_ptr<Executor> executor)
    : nodeHandle_(nodeHandle),
      name_(name),
      executor_(executor),
      rosConverter_(executor),
      server_(nodeHandle_, name_, false),
      isPreempting_(false)
{
}

FreeGaitActionServer::~FreeGaitActionServer()
{
}

void FreeGaitActionServer::initialize()
{
  server_.registerGoalCallback(boost::bind(&FreeGaitActionServer::goalCallback, this));
  server_.registerPreemptCallback(boost::bind(&FreeGaitActionServer::preemptCallback, this));
  server_.start();
  ROS_INFO_STREAM("Started " << name_ << " action server.");
}

void FreeGaitActionServer::update()
{
  if (!server_.isActive()) return;
  if (executor_->getQueue().empty()) {
    // Succeeded.
    if (isPreempting_) {
      // Preempted.
      setPreempted();
    } else {
      setSucceeded();
    }
  } else {
    // Ongoing.
    publishFeedback();
  }
}

void FreeGaitActionServer::shutdown()
{
  server_.shutdown();
}

void FreeGaitActionServer::goalCallback()
{
  ROS_INFO("Received goal for StepAction.");
//  if (server_.isActive()) server_.setRejected();

  const auto goal = server_.acceptNewGoal();

  Executor::Lock lock(executor_->getMutex());
  for (auto& stepMessage : goal->steps) {
    Step step;
    rosConverter_.fromMessage(stepMessage, step);
    executor_->getQueue().add(step);
  }
}

void FreeGaitActionServer::preemptCallback()
{
  ROS_INFO("StepAction is requested to preempt.");
  Executor::Lock lock(executor_->getMutex());
  if (executor_->getQueue().empty()) return;
  if (executor_->getQueue().size() <= 1) return;
  executor_->getQueue().clearNextSteps();
  isPreempting_ = true;
}

void FreeGaitActionServer::publishFeedback()
{
  free_gait_msgs::ExecuteStepsFeedback feedback;
  Executor::Lock lock(executor_->getMutex());
  if (executor_->getQueue().empty()) return;
//  const auto& step = executor_->getQueue().getCurrentStep();
  feedback.queue_size = executor_->getQueue().size();
  lock.unlock();

//  if (step.checkStatus() == false) {
//    feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_PAUSED;
//    feedback.description = "Paused.";
//  } else {
//    switch (step.getState()) {
//      feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_EXECUTING;
//      case Step::State::PreStep:
//        feedback.description = "Pre step.";
//        break;
//      case Step::State::AtStep:
//        feedback.description = "At step.";
//        break;
//      case Step::State::PostStep:
//        feedback.description = "Post step.";
//        break;
//      default:
//        feedback.status = free_gait_msgs::ExecuteStepsFeedback::PROGRESS_UNKNOWN;
//        feedback.description = "Unknown.";
//        break;
//    }
//  }

//  feedback.duration = ros::Duration(step.getTotalDuration());
//  feedback.phase = step.getTotalPhase();
//  for (const auto& stepData : step.getSwingData())
//    feedback.swing_leg_names.push_back(stepData.first);

  server_.publishFeedback(feedback);
}

void FreeGaitActionServer::setSucceeded()
{
  ROS_INFO("StepAction succeeded.");
  free_gait_msgs::ExecuteStepsResult result;
  result.status = free_gait_msgs::ExecuteStepsResult::RESULT_REACHED;
  server_.setSucceeded(result, "Step action has been reached.");
}

void FreeGaitActionServer::setPreempted()
{
  ROS_INFO("StepAction preempted.");
  free_gait_msgs::ExecuteStepsResult result;
  result.status = free_gait_msgs::ExecuteStepsResult::RESULT_FAILED;
  server_.setPreempted(result, "Step action has been preempted.");
  isPreempting_ = false;
}

void FreeGaitActionServer::setAborted()
{
  ROS_INFO("StepAction aborted.");
  free_gait_msgs::ExecuteStepsResult result;
  result.status = free_gait_msgs::ExecuteStepsResult::RESULT_FAILED;
  server_.setAborted(result, "Step action has failed.");
}

} /* namespace */
<|endoftext|>


<commit_before>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/ui/file_dialog.h"

#include "atom/browser/native_window_views.h"
#include "atom/browser/unresponsive_suppressor.h"
#include "base/callback.h"
#include "base/files/file_util.h"
#include "base/strings/string_util.h"
#include "chrome/browser/ui/libgtkui/gtk_signal.h"
#include "chrome/browser/ui/libgtkui/gtk_util.h"
#include "ui/views/widget/desktop_aura/x11_desktop_handler.h"

namespace file_dialog {

namespace {

// Makes sure that .jpg also shows .JPG.
gboolean FileFilterCaseInsensitive(const GtkFileFilterInfo* file_info,
                                   std::string* file_extension) {
  // Makes .* file extension matches all file types.
  if (*file_extension == ".*")
    return true;
  return base::EndsWith(
    file_info->filename,
    *file_extension, base::CompareCase::INSENSITIVE_ASCII);
}

// Deletes |data| when gtk_file_filter_add_custom() is done with it.
void OnFileFilterDataDestroyed(std::string* file_extension) {
  delete file_extension;
}

class FileChooserDialog {
 public:
  FileChooserDialog(GtkFileChooserAction action,
                    atom::NativeWindow* parent_window,
                    const std::string& title,
                    const std::string& button_label,
                    const base::FilePath& default_path,
                    const Filters& filters)
      : parent_(static_cast<atom::NativeWindowViews*>(parent_window)),
        filters_(filters) {
    const char* confirm_text = GTK_STOCK_OK;

    if (!button_label.empty())
      confirm_text = button_label.c_str();
    else if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
      confirm_text = GTK_STOCK_SAVE;
    else if (action == GTK_FILE_CHOOSER_ACTION_OPEN)
      confirm_text = GTK_STOCK_OPEN;

    dialog_ = gtk_file_chooser_dialog_new(
        title.c_str(),
        NULL,
        action,
        GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
        confirm_text, GTK_RESPONSE_ACCEPT,
        NULL);
    if (parent_) {
      parent_->SetEnabled(false);
      libgtkui::SetGtkTransientForAura(dialog_, parent_->GetNativeWindow());
      gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);
    }

    if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
      gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog_),
                                                     TRUE);
    if (action != GTK_FILE_CHOOSER_ACTION_OPEN)
      gtk_file_chooser_set_create_folders(GTK_FILE_CHOOSER(dialog_), TRUE);

    if (!default_path.empty()) {
      if (base::DirectoryExists(default_path)) {
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog_),
                                            default_path.value().c_str());
      } else {
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog_),
            default_path.DirName().value().c_str());
        gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog_),
            default_path.BaseName().value().c_str());
      }
    }

    if (!filters.empty())
      AddFilters(filters);
  }

  ~FileChooserDialog() {
    gtk_widget_destroy(dialog_);
    if (parent_)
      parent_->SetEnabled(true);
  }

  void SetupProperties(int properties) {
    if (properties & FILE_DIALOG_MULTI_SELECTIONS)
      gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog()), TRUE);
    if (properties & FILE_DIALOG_SHOW_HIDDEN_FILES)
      g_object_set(dialog(), "show-hidden", TRUE, NULL);
  }

  void RunAsynchronous() {
    g_signal_connect(dialog_, "delete-event",
                     G_CALLBACK(gtk_widget_hide_on_delete), NULL);
    g_signal_connect(dialog_, "response",
                     G_CALLBACK(OnFileDialogResponseThunk), this);
    gtk_widget_show_all(dialog_);

    // We need to call gtk_window_present after making the widgets visible to
    // make sure window gets correctly raised and gets focus.
    int time = ui::X11EventSource::GetInstance()->GetTimestamp();
    gtk_window_present_with_time(GTK_WINDOW(dialog_), time);
  }

  void RunSaveAsynchronous(const SaveDialogCallback& callback) {
    save_callback_ = callback;
    RunAsynchronous();
  }

  void RunOpenAsynchronous(const OpenDialogCallback& callback) {
    open_callback_ = callback;
    RunAsynchronous();
  }

  base::FilePath GetFileName() const {
    gchar* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog_));
    base::FilePath path = AddExtensionForFilename(filename);
    g_free(filename);
    return path;
  }

  std::vector<base::FilePath> GetFileNames() const {
    std::vector<base::FilePath> paths;
    GSList* filenames = gtk_file_chooser_get_filenames(
        GTK_FILE_CHOOSER(dialog_));
    for (GSList* iter = filenames; iter != NULL; iter = g_slist_next(iter)) {
      base::FilePath path = AddExtensionForFilename(
          static_cast<char*>(iter->data));
      g_free(iter->data);
      paths.push_back(path);
    }
    g_slist_free(filenames);
    return paths;
  }

  CHROMEGTK_CALLBACK_1(FileChooserDialog, void, OnFileDialogResponse, int);

  GtkWidget* dialog() const { return dialog_; }

 private:
  void AddFilters(const Filters& filters);
  base::FilePath AddExtensionForFilename(const gchar* filename) const;

  atom::NativeWindowViews* parent_;
  atom::UnresponsiveSuppressor unresponsive_suppressor_;

  GtkWidget* dialog_;

  Filters filters_;
  SaveDialogCallback save_callback_;
  OpenDialogCallback open_callback_;

  DISALLOW_COPY_AND_ASSIGN(FileChooserDialog);
};

void FileChooserDialog::OnFileDialogResponse(GtkWidget* widget, int response) {
  gtk_widget_hide(dialog_);

  if (!save_callback_.is_null()) {
    if (response == GTK_RESPONSE_ACCEPT)
      save_callback_.Run(true, GetFileName());
    else
      save_callback_.Run(false, base::FilePath());
  } else if (!open_callback_.is_null()) {
    if (response == GTK_RESPONSE_ACCEPT)
      open_callback_.Run(true, GetFileNames());
    else
      open_callback_.Run(false, std::vector<base::FilePath>());
  }
  delete this;
}

void FileChooserDialog::AddFilters(const Filters& filters) {
  for (size_t i = 0; i < filters.size(); ++i) {
    const Filter& filter = filters[i];
    GtkFileFilter* gtk_filter = gtk_file_filter_new();

    for (size_t j = 0; j < filter.second.size(); ++j) {
      std::unique_ptr<std::string> file_extension(
          new std::string("." + filter.second[j]));
      gtk_file_filter_add_custom(
          gtk_filter,
          GTK_FILE_FILTER_FILENAME,
          reinterpret_cast<GtkFileFilterFunc>(FileFilterCaseInsensitive),
          file_extension.release(),
          reinterpret_cast<GDestroyNotify>(OnFileFilterDataDestroyed));
    }

    gtk_file_filter_set_name(gtk_filter, filter.first.c_str());
    gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog_), gtk_filter);
  }
}

base::FilePath FileChooserDialog::AddExtensionForFilename(
    const gchar* filename) const {
  base::FilePath path(filename);
  GtkFileFilter* selected_filter =
      gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog_));
  if (!selected_filter)
    return path;

  GSList* filters = gtk_file_chooser_list_filters(GTK_FILE_CHOOSER(dialog_));
  int i = g_slist_index(filters, selected_filter);
  g_slist_free(filters);
  if (i >= filters_.size())
    return path;

  const auto& extensions = filters_[i].second;
  for (const auto& extension : extensions) {
    if (extension == "*" ||
        base::EndsWith(path.value(), "." + extension,
                       base::CompareCase::INSENSITIVE_ASCII))
      return path;
  }

  return path.ReplaceExtension(extensions[0]);
}

}  // namespace

bool ShowOpenDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const std::string& button_label,
                    const base::FilePath& default_path,
                    const Filters& filters,
                    int properties,
                    const std::string& message,
                    std::vector<base::FilePath>* paths) {
  GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN;
  if (properties & FILE_DIALOG_OPEN_DIRECTORY)
    action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
  FileChooserDialog open_dialog(action, parent_window, title, button_label,
                                default_path, filters);
  open_dialog.SetupProperties(properties);

  gtk_widget_show_all(open_dialog.dialog());
  int response = gtk_dialog_run(GTK_DIALOG(open_dialog.dialog()));
  if (response == GTK_RESPONSE_ACCEPT) {
    *paths = open_dialog.GetFileNames();
    return true;
  } else {
    return false;
  }
}

void ShowOpenDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const std::string& button_label,
                    const base::FilePath& default_path,
                    const Filters& filters,
                    int properties,
                    const std::string& message,
                    const OpenDialogCallback& callback) {
  GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN;
  if (properties & FILE_DIALOG_OPEN_DIRECTORY)
    action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
  FileChooserDialog* open_dialog = new FileChooserDialog(
      action, parent_window, title, button_label, default_path, filters);
  open_dialog->SetupProperties(properties);
  open_dialog->RunOpenAsynchronous(callback);
}

bool ShowSaveDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const std::string& button_label,
                    const base::FilePath& default_path,
                    const Filters& filters,
                    const std::string& message,
                    const std::string& name_field_label,
                    const bool& shows_tag_field,
                    base::FilePath* path) {
  FileChooserDialog save_dialog(GTK_FILE_CHOOSER_ACTION_SAVE, parent_window,
                                title, button_label, default_path, filters);
  gtk_widget_show_all(save_dialog.dialog());
  int response = gtk_dialog_run(GTK_DIALOG(save_dialog.dialog()));
  if (response == GTK_RESPONSE_ACCEPT) {
    *path = save_dialog.GetFileName();
    return true;
  } else {
    return false;
  }
}

void ShowSaveDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const std::string& button_label,
                    const base::FilePath& default_path,
                    const Filters& filters,
                    const SaveDialogCallback& callback) {
  FileChooserDialog* save_dialog = new FileChooserDialog(
      GTK_FILE_CHOOSER_ACTION_SAVE, parent_window, title, button_label,
      default_path, filters);
  save_dialog->RunSaveAsynchronous(callback);
}

}  // namespace file_dialog
<commit_msg>Fix wrong signature for gtk's ShowSaveDialog()<commit_after>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/ui/file_dialog.h"

#include "atom/browser/native_window_views.h"
#include "atom/browser/unresponsive_suppressor.h"
#include "base/callback.h"
#include "base/files/file_util.h"
#include "base/strings/string_util.h"
#include "chrome/browser/ui/libgtkui/gtk_signal.h"
#include "chrome/browser/ui/libgtkui/gtk_util.h"
#include "ui/views/widget/desktop_aura/x11_desktop_handler.h"

namespace file_dialog {

namespace {

// Makes sure that .jpg also shows .JPG.
gboolean FileFilterCaseInsensitive(const GtkFileFilterInfo* file_info,
                                   std::string* file_extension) {
  // Makes .* file extension matches all file types.
  if (*file_extension == ".*")
    return true;
  return base::EndsWith(
    file_info->filename,
    *file_extension, base::CompareCase::INSENSITIVE_ASCII);
}

// Deletes |data| when gtk_file_filter_add_custom() is done with it.
void OnFileFilterDataDestroyed(std::string* file_extension) {
  delete file_extension;
}

class FileChooserDialog {
 public:
  FileChooserDialog(GtkFileChooserAction action,
                    atom::NativeWindow* parent_window,
                    const std::string& title,
                    const std::string& button_label,
                    const base::FilePath& default_path,
                    const Filters& filters)
      : parent_(static_cast<atom::NativeWindowViews*>(parent_window)),
        filters_(filters) {
    const char* confirm_text = GTK_STOCK_OK;

    if (!button_label.empty())
      confirm_text = button_label.c_str();
    else if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
      confirm_text = GTK_STOCK_SAVE;
    else if (action == GTK_FILE_CHOOSER_ACTION_OPEN)
      confirm_text = GTK_STOCK_OPEN;

    dialog_ = gtk_file_chooser_dialog_new(
        title.c_str(),
        NULL,
        action,
        GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
        confirm_text, GTK_RESPONSE_ACCEPT,
        NULL);
    if (parent_) {
      parent_->SetEnabled(false);
      libgtkui::SetGtkTransientForAura(dialog_, parent_->GetNativeWindow());
      gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);
    }

    if (action == GTK_FILE_CHOOSER_ACTION_SAVE)
      gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog_),
                                                     TRUE);
    if (action != GTK_FILE_CHOOSER_ACTION_OPEN)
      gtk_file_chooser_set_create_folders(GTK_FILE_CHOOSER(dialog_), TRUE);

    if (!default_path.empty()) {
      if (base::DirectoryExists(default_path)) {
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog_),
                                            default_path.value().c_str());
      } else {
        gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog_),
            default_path.DirName().value().c_str());
        gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog_),
            default_path.BaseName().value().c_str());
      }
    }

    if (!filters.empty())
      AddFilters(filters);
  }

  ~FileChooserDialog() {
    gtk_widget_destroy(dialog_);
    if (parent_)
      parent_->SetEnabled(true);
  }

  void SetupProperties(int properties) {
    if (properties & FILE_DIALOG_MULTI_SELECTIONS)
      gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog()), TRUE);
    if (properties & FILE_DIALOG_SHOW_HIDDEN_FILES)
      g_object_set(dialog(), "show-hidden", TRUE, NULL);
  }

  void RunAsynchronous() {
    g_signal_connect(dialog_, "delete-event",
                     G_CALLBACK(gtk_widget_hide_on_delete), NULL);
    g_signal_connect(dialog_, "response",
                     G_CALLBACK(OnFileDialogResponseThunk), this);
    gtk_widget_show_all(dialog_);

    // We need to call gtk_window_present after making the widgets visible to
    // make sure window gets correctly raised and gets focus.
    int time = ui::X11EventSource::GetInstance()->GetTimestamp();
    gtk_window_present_with_time(GTK_WINDOW(dialog_), time);
  }

  void RunSaveAsynchronous(const SaveDialogCallback& callback) {
    save_callback_ = callback;
    RunAsynchronous();
  }

  void RunOpenAsynchronous(const OpenDialogCallback& callback) {
    open_callback_ = callback;
    RunAsynchronous();
  }

  base::FilePath GetFileName() const {
    gchar* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog_));
    base::FilePath path = AddExtensionForFilename(filename);
    g_free(filename);
    return path;
  }

  std::vector<base::FilePath> GetFileNames() const {
    std::vector<base::FilePath> paths;
    GSList* filenames = gtk_file_chooser_get_filenames(
        GTK_FILE_CHOOSER(dialog_));
    for (GSList* iter = filenames; iter != NULL; iter = g_slist_next(iter)) {
      base::FilePath path = AddExtensionForFilename(
          static_cast<char*>(iter->data));
      g_free(iter->data);
      paths.push_back(path);
    }
    g_slist_free(filenames);
    return paths;
  }

  CHROMEGTK_CALLBACK_1(FileChooserDialog, void, OnFileDialogResponse, int);

  GtkWidget* dialog() const { return dialog_; }

 private:
  void AddFilters(const Filters& filters);
  base::FilePath AddExtensionForFilename(const gchar* filename) const;

  atom::NativeWindowViews* parent_;
  atom::UnresponsiveSuppressor unresponsive_suppressor_;

  GtkWidget* dialog_;

  Filters filters_;
  SaveDialogCallback save_callback_;
  OpenDialogCallback open_callback_;

  DISALLOW_COPY_AND_ASSIGN(FileChooserDialog);
};

void FileChooserDialog::OnFileDialogResponse(GtkWidget* widget, int response) {
  gtk_widget_hide(dialog_);

  if (!save_callback_.is_null()) {
    if (response == GTK_RESPONSE_ACCEPT)
      save_callback_.Run(true, GetFileName());
    else
      save_callback_.Run(false, base::FilePath());
  } else if (!open_callback_.is_null()) {
    if (response == GTK_RESPONSE_ACCEPT)
      open_callback_.Run(true, GetFileNames());
    else
      open_callback_.Run(false, std::vector<base::FilePath>());
  }
  delete this;
}

void FileChooserDialog::AddFilters(const Filters& filters) {
  for (size_t i = 0; i < filters.size(); ++i) {
    const Filter& filter = filters[i];
    GtkFileFilter* gtk_filter = gtk_file_filter_new();

    for (size_t j = 0; j < filter.second.size(); ++j) {
      std::unique_ptr<std::string> file_extension(
          new std::string("." + filter.second[j]));
      gtk_file_filter_add_custom(
          gtk_filter,
          GTK_FILE_FILTER_FILENAME,
          reinterpret_cast<GtkFileFilterFunc>(FileFilterCaseInsensitive),
          file_extension.release(),
          reinterpret_cast<GDestroyNotify>(OnFileFilterDataDestroyed));
    }

    gtk_file_filter_set_name(gtk_filter, filter.first.c_str());
    gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog_), gtk_filter);
  }
}

base::FilePath FileChooserDialog::AddExtensionForFilename(
    const gchar* filename) const {
  base::FilePath path(filename);
  GtkFileFilter* selected_filter =
      gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog_));
  if (!selected_filter)
    return path;

  GSList* filters = gtk_file_chooser_list_filters(GTK_FILE_CHOOSER(dialog_));
  int i = g_slist_index(filters, selected_filter);
  g_slist_free(filters);
  if (i >= filters_.size())
    return path;

  const auto& extensions = filters_[i].second;
  for (const auto& extension : extensions) {
    if (extension == "*" ||
        base::EndsWith(path.value(), "." + extension,
                       base::CompareCase::INSENSITIVE_ASCII))
      return path;
  }

  return path.ReplaceExtension(extensions[0]);
}

}  // namespace

bool ShowOpenDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const std::string& button_label,
                    const base::FilePath& default_path,
                    const Filters& filters,
                    int properties,
                    const std::string& message,
                    std::vector<base::FilePath>* paths) {
  GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN;
  if (properties & FILE_DIALOG_OPEN_DIRECTORY)
    action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
  FileChooserDialog open_dialog(action, parent_window, title, button_label,
                                default_path, filters);
  open_dialog.SetupProperties(properties);

  gtk_widget_show_all(open_dialog.dialog());
  int response = gtk_dialog_run(GTK_DIALOG(open_dialog.dialog()));
  if (response == GTK_RESPONSE_ACCEPT) {
    *paths = open_dialog.GetFileNames();
    return true;
  } else {
    return false;
  }
}

void ShowOpenDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const std::string& button_label,
                    const base::FilePath& default_path,
                    const Filters& filters,
                    int properties,
                    const std::string& message,
                    const OpenDialogCallback& callback) {
  GtkFileChooserAction action = GTK_FILE_CHOOSER_ACTION_OPEN;
  if (properties & FILE_DIALOG_OPEN_DIRECTORY)
    action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER;
  FileChooserDialog* open_dialog = new FileChooserDialog(
      action, parent_window, title, button_label, default_path, filters);
  open_dialog->SetupProperties(properties);
  open_dialog->RunOpenAsynchronous(callback);
}

bool ShowSaveDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const std::string& button_label,
                    const base::FilePath& default_path,
                    const Filters& filters,
                    const std::string& message,
                    const std::string& name_field_label,
                    const bool& shows_tag_field,
                    base::FilePath* path) {
  FileChooserDialog save_dialog(GTK_FILE_CHOOSER_ACTION_SAVE, parent_window,
                                title, button_label, default_path, filters);
  gtk_widget_show_all(save_dialog.dialog());
  int response = gtk_dialog_run(GTK_DIALOG(save_dialog.dialog()));
  if (response == GTK_RESPONSE_ACCEPT) {
    *path = save_dialog.GetFileName();
    return true;
  } else {
    return false;
  }
}

void ShowSaveDialog(atom::NativeWindow* parent_window,
                    const std::string& title,
                    const std::string& button_label,
                    const base::FilePath& default_path,
                    const Filters& filters,
                    const std::string& message,
                    const std::string& name_field_label,
                    const bool& shows_tag_field,
                    const SaveDialogCallback& callback) {
  FileChooserDialog* save_dialog = new FileChooserDialog(
      GTK_FILE_CHOOSER_ACTION_SAVE, parent_window, title, button_label,
      default_path, filters);
  save_dialog->RunSaveAsynchronous(callback);
}

}  // namespace file_dialog
<|endoftext|>


<commit_before>//
//  StaticAnalyser.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 24/06/2021.
//  Copyright 2021 Thomas Harte. All rights reserved.
//

#include "StaticAnalyser.hpp"
#include "Target.hpp"

#include "../../../Storage/Disk/Parsers/FAT.hpp"

#include <algorithm>

namespace {

bool insensitive_equal(const std::string &lhs, const std::string &rhs) {
	return std::equal(
		lhs.begin(), lhs.end(),
		rhs.begin(), rhs.end(),
		[] (char l, char r) {
			return tolower(l) == tolower(r);
	});
}

}

Analyser::Static::TargetList Analyser::Static::Enterprise::GetTargets(const Media &media, const std::string &, TargetPlatform::IntType) {
	// This analyser can comprehend disks only.
	if(media.disks.empty()) return {};

	// Otherwise, assume a return will happen.
	Analyser::Static::TargetList targets;
	using Target = Analyser::Static::Enterprise::Target;
	auto *const target = new Target;
	target->media = media;

	// Always require a BASIC.
	target->basic_version = Target::BASICVersion::Any;

	// Inspect any supplied disks.
	if(!media.disks.empty()) {
		// DOS will be needed.
		target->dos = Target::DOS::EXDOS;

		// Grab the volume information, which includes the root directory.
		auto volume = Storage::Disk::FAT::GetVolume(media.disks.front());
		if(volume) {
			// If there's an EXDOS.INI then this disk should be able to boot itself.
			// If not but if there's only one .COM or .BAS, automatically load that.
			// Failing that, issue a :DIR and give the user a clue as to how to load.
			const Storage::Disk::FAT::File *selected_file = nullptr;
			bool has_exdos_ini = false;
			bool did_pick_file = false;
			for(const auto &file: (*volume).root_directory) {
				if(insensitive_equal(file.name, "exdos") && insensitive_equal(file.extension, "ini")) {
					has_exdos_ini = true;
					break;
				}

				if(insensitive_equal(file.extension, "com") || insensitive_equal(file.extension, "bas")) {
					did_pick_file = !selected_file;
					selected_file = &file;
				}
			}

			if(!has_exdos_ini) {
				if(did_pick_file) {
					target->loading_command = std::string("run \"") + selected_file->name + "." + selected_file->extension + "\"";
				} else {
					target->loading_command = ":dir\n";
				}
			}
		}
	}

	targets.push_back(std::unique_ptr<Analyser::Static::Target>(target));

	return targets;
}
<commit_msg>Ensure run command is issued.<commit_after>//
//  StaticAnalyser.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 24/06/2021.
//  Copyright 2021 Thomas Harte. All rights reserved.
//

#include "StaticAnalyser.hpp"
#include "Target.hpp"

#include "../../../Storage/Disk/Parsers/FAT.hpp"

#include <algorithm>

namespace {

bool insensitive_equal(const std::string &lhs, const std::string &rhs) {
	return std::equal(
		lhs.begin(), lhs.end(),
		rhs.begin(), rhs.end(),
		[] (char l, char r) {
			return tolower(l) == tolower(r);
	});
}

}

Analyser::Static::TargetList Analyser::Static::Enterprise::GetTargets(const Media &media, const std::string &, TargetPlatform::IntType) {
	// This analyser can comprehend disks only.
	if(media.disks.empty()) return {};

	// Otherwise, assume a return will happen.
	Analyser::Static::TargetList targets;
	using Target = Analyser::Static::Enterprise::Target;
	auto *const target = new Target;
	target->media = media;

	// Always require a BASIC.
	target->basic_version = Target::BASICVersion::Any;

	// Inspect any supplied disks.
	if(!media.disks.empty()) {
		// DOS will be needed.
		target->dos = Target::DOS::EXDOS;

		// Grab the volume information, which includes the root directory.
		auto volume = Storage::Disk::FAT::GetVolume(media.disks.front());
		if(volume) {
			// If there's an EXDOS.INI then this disk should be able to boot itself.
			// If not but if there's only one .COM or .BAS, automatically load that.
			// Failing that, issue a :DIR and give the user a clue as to how to load.
			const Storage::Disk::FAT::File *selected_file = nullptr;
			bool has_exdos_ini = false;
			bool did_pick_file = false;
			for(const auto &file: (*volume).root_directory) {
				if(insensitive_equal(file.name, "exdos") && insensitive_equal(file.extension, "ini")) {
					has_exdos_ini = true;
					break;
				}

				if(insensitive_equal(file.extension, "com") || insensitive_equal(file.extension, "bas")) {
					did_pick_file = !selected_file;
					selected_file = &file;
				}
			}

			if(!has_exdos_ini) {
				if(did_pick_file) {
					target->loading_command = std::string("run \"") + selected_file->name + "." + selected_file->extension + "\"\n";
				} else {
					target->loading_command = ":dir\n";
				}
			}
		}
	}

	targets.push_back(std::unique_ptr<Analyser::Static::Target>(target));

	return targets;
}
<|endoftext|>


<commit_before>// RTcmix - Copyright (C) 2005  The RTcmix Development Team
// See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
// the license to this software and for a DISCLAIMER OF ALL WARRANTIES.

#include <RTOscPField.h>
#include <RTcmixOSC.h>
#include <PField.h>
#include <Ougens.h>
#include <string.h>
#include <unistd.h>
#include <float.h>
#include <assert.h>

#define DEBUG 0

extern int resetval;		// declared in src/rtcmix/minc_functions.c

const double kInvalidValue = DBL_MAX;

RTOscPField::RTOscPField(
		RTcmixOSC			*oscserver,
		const char 			*path,
		const int			index,
		const double		inputmin,
		const double		inputmax,
		const double		outputmin,
		const double		outputmax,
		const double		defaultval,
		const double		lag)				// in range [0, 1]
	: RTNumberPField(0),
	  _oscserver(oscserver), _index(index), _badMessages(0), _lastBadArgc(0),
	  _inputmin(inputmin), _inputmax(inputmax), _outputmin(outputmin),
	  _default(defaultval), _rawvalue(kInvalidValue), _callbackReturn(0)
{
	assert(_oscserver != NULL);
	assert(_index >= 0);

	_path = new char [strlen(path) + 1];
	strcpy(_path, path);

	_factor = (outputmax - _outputmin) / (_inputmax - _inputmin);

	// NOTE: We rely on the control rate in effect when this PField is created.
	_filter = new Oonepole(resetval);
	_filter->setlag(lag);

	while (!_oscserver->ready())
		usleep(100);
	_oscserver->registerPField(this, handler);
}

RTOscPField::~RTOscPField()
{
	// Prevent our handler from continuing to be called even after we delete
	// this PField.
	_oscserver->unregisterPField(this);

	delete [] _path;
	delete _filter;

	if (_badMessages > 0)
		fprintf(stderr, "WARNING: OSC index out of range for %d messages.\n",
		                                                       _badMessages);
}

double RTOscPField::doubleValue(double) const
{
	// map _rawvalue, clamped to input range, into output range
	double val = _rawvalue;
	if (val == kInvalidValue)
		val = _default;
	else {
		if (val < _inputmin)
			val = _inputmin;
		else if (val > _inputmax)
			val = _inputmax;
		val = ((val - _inputmin) * _factor) + _outputmin;
	}
	return _filter->next(val);
}

int RTOscPField::handler(const char *path, const char *types, lo_arg **argv,
		int argc, lo_message msg, void *context)
{
	RTOscPField *pfield = (RTOscPField *) context;
	assert(pfield != NULL);

#if DEBUG > 1
	printf("rcv OSC msg: %s, argc=%d: ", path, argc);
	for (int i = 0; i < argc; i++) {
		lo_arg_pp((lo_type) types[i], argv[i]);
		if (i == argc - 1)
			printf("\n");
		else
			printf(", ");
	}
#endif

	const int index = pfield->index();
	if (index < argc) {
		lo_type type = (lo_type) types[index];
		if (type == LO_FLOAT)	// the most common one
			pfield->rawvalue(argv[index]->f);
		else if (lo_is_numerical_type(type)) {
			double val = lo_hires_val(type, argv[index]);
			pfield->rawvalue(val);
		}
		else
			fprintf(stderr, "WARNING: incoming OSC value of type '%c' can't "
								 "be coerced to double.\n", type);
	}
	else {
		if (pfield->badMessages() == 0 || pfield->lastBadArgc() != argc) {
			fprintf(stderr, "WARNING: OSC index (%d) out of range. Message has "
		           "only %d items. (Others skipped silently.)\n", index, argc);
			pfield->lastBadArgc(argc);
		}
		pfield->incrementBadMessages();
	}

	return pfield->callbackReturn();
}

<commit_msg>Set initial sample value of smoothing filter to the requested RTOscPField default value.<commit_after>// RTcmix - Copyright (C) 2005  The RTcmix Development Team
// See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
// the license to this software and for a DISCLAIMER OF ALL WARRANTIES.

#include <RTOscPField.h>
#include <RTcmixOSC.h>
#include <PField.h>
#include <Ougens.h>
#include <string.h>
#include <unistd.h>
#include <float.h>
#include <assert.h>

#define DEBUG 0

extern int resetval;		// declared in src/rtcmix/minc_functions.c

const double kInvalidValue = DBL_MAX;

RTOscPField::RTOscPField(
		RTcmixOSC			*oscserver,
		const char 			*path,
		const int			index,
		const double		inputmin,
		const double		inputmax,
		const double		outputmin,
		const double		outputmax,
		const double		defaultval,
		const double		lag)				// in range [0, 1]
	: RTNumberPField(0),
	  _oscserver(oscserver), _index(index), _badMessages(0), _lastBadArgc(0),
	  _inputmin(inputmin), _inputmax(inputmax), _outputmin(outputmin),
	  _default(defaultval), _rawvalue(kInvalidValue), _callbackReturn(0)
{
	assert(_oscserver != NULL);
	assert(_index >= 0);

	_path = new char [strlen(path) + 1];
	strcpy(_path, path);

	_factor = (outputmax - _outputmin) / (_inputmax - _inputmin);

	// NOTE: We rely on the control rate in effect when this PField is created.
	_filter = new Oonepole(resetval);
	_filter->sethist(_default);
	_filter->setlag(lag);

	while (!_oscserver->ready())
		usleep(100);
	_oscserver->registerPField(this, handler);
}

RTOscPField::~RTOscPField()
{
	// Prevent our handler from continuing to be called even after we delete
	// this PField.
	_oscserver->unregisterPField(this);

	delete [] _path;
	delete _filter;

	if (_badMessages > 0)
		fprintf(stderr, "WARNING: OSC index out of range for %d messages.\n",
		                                                       _badMessages);
}

double RTOscPField::doubleValue(double) const
{
	// map _rawvalue, clamped to input range, into output range
	double val = _rawvalue;
	if (val == kInvalidValue)
		val = _default;
	else {
		if (val < _inputmin)
			val = _inputmin;
		else if (val > _inputmax)
			val = _inputmax;
		val = ((val - _inputmin) * _factor) + _outputmin;
	}
	return _filter->next(val);
}

int RTOscPField::handler(const char *path, const char *types, lo_arg **argv,
		int argc, lo_message msg, void *context)
{
	RTOscPField *pfield = (RTOscPField *) context;
	assert(pfield != NULL);

#if DEBUG > 1
	printf("rcv OSC msg: %s, argc=%d: ", path, argc);
	for (int i = 0; i < argc; i++) {
		lo_arg_pp((lo_type) types[i], argv[i]);
		if (i == argc - 1)
			printf("\n");
		else
			printf(", ");
	}
#endif

	const int index = pfield->index();
	if (index < argc) {
		lo_type type = (lo_type) types[index];
		if (type == LO_FLOAT)	// the most common one
			pfield->rawvalue(argv[index]->f);
		else if (lo_is_numerical_type(type)) {
			double val = lo_hires_val(type, argv[index]);
			pfield->rawvalue(val);
		}
		else
			fprintf(stderr, "WARNING: incoming OSC value of type '%c' can't "
								 "be coerced to double.\n", type);
	}
	else {
		if (pfield->badMessages() == 0 || pfield->lastBadArgc() != argc) {
			fprintf(stderr, "WARNING: OSC index (%d) out of range. Message has "
		           "only %d items. (Others skipped silently.)\n", index, argc);
			pfield->lastBadArgc(argc);
		}
		pfield->incrementBadMessages();
	}

	return pfield->callbackReturn();
}

<|endoftext|>