<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_GEOMETRY_HPP
#define MAPNIK_GEOMETRY_HPP

#include <mapnik/util/variant.hpp>
#include <mapnik/coord.hpp>
#include <vector>
#include <type_traits>
#include <cstddef>

namespace mapnik { namespace geometry {

template <typename T>
struct point
{
    using value_type = T;
    point() {}
    point(T x_, T y_)
        : x(x_), y(y_)
    {}
    // temp - remove when geometry is templated on value_type
    point(mapnik::coord<double, 2> const& c)
        : x(c.x), y(c.y) {}

    point(point const& other) = default;
    point(point && other) noexcept = default;
    point & operator=(point const& other) = default;
    friend inline bool operator== (point<T> const& a, point<T> const& b)
    {
        return a.x == b.x && a.y == b.y;
    }
    friend inline bool operator!= (point<T> const& a, point <T> const& b)
    {
        return a.x != b.x  || a.y != b.y;
    }
    value_type x;
    value_type y;
};

template <typename T>
struct line_string : std::vector<point<T> >
{
    line_string() = default;
    line_string (std::size_t size)
        : std::vector<point<T> >(size) {}
    line_string (line_string && other) = default ;
    line_string& operator=(line_string &&) = default;
    line_string (line_string const& ) = default;
    line_string& operator=(line_string const&) = default;
    inline std::size_t num_points() const { return std::vector<point<T>>::template size(); }
    inline void add_coord(T x, T y) { std::vector<point<T>>::template emplace_back(x,y);}
};

template <typename T>
struct linear_ring : line_string<T>
{
    linear_ring() = default;
    linear_ring(std::size_t size)
        : line_string<T>(size) {}
    linear_ring (linear_ring && other) = default ;
    linear_ring& operator=(linear_ring &&) = default;
    linear_ring(line_string<T> && other)
        : line_string<T>(other) {}
    linear_ring (linear_ring const& ) = default;
    linear_ring(line_string<T> const& other)
        : line_string<T>(other) {}
    linear_ring& operator=(linear_ring const&) = default;

};

template <typename T>
struct polygon
{
    linear_ring<T> exterior_ring;
    std::vector<linear_ring<T>> interior_rings;

    inline void set_exterior_ring(linear_ring<T> && ring)
    {
        exterior_ring = std::move(ring);
    }

    inline void add_hole(linear_ring<T> && ring)
    {
        interior_rings.emplace_back(std::move(ring));
    }

    inline bool empty() const { return exterior_ring.empty(); }

    inline std::size_t num_rings() const
    {
        return 1 + interior_rings.size();
    }
};

template <typename T>
struct multi_point : line_string<T> {};

template <typename T>
struct multi_line_string : std::vector<line_string<T>> {};

template <typename T>
struct multi_polygon : std::vector<polygon<T>> {};

template <typename T>
struct geometry_collection;

struct geometry_empty {};

template <typename T>
using geometry = mapnik::util::variant<geometry_empty,
                                       point<T>,
                                       line_string<T>,
                                       polygon<T>,
                                       multi_point<T>,
                                       multi_line_string<T>,
                                       multi_polygon<T>,
                                       mapnik::util::recursive_wrapper<geometry_collection<T> > >;

template <typename T>
struct geometry_collection : std::vector<geometry<T>> {};

}}

#endif //MAPNIK_GEOMETRY_HPP
<commit_msg>fix compile with gcc<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_GEOMETRY_HPP
#define MAPNIK_GEOMETRY_HPP

#include <mapnik/util/variant.hpp>
#include <mapnik/coord.hpp>
#include <vector>
#include <type_traits>
#include <cstddef>

namespace mapnik { namespace geometry {

template <typename T>
struct point
{
    using value_type = T;
    point() {}
    point(T x_, T y_)
        : x(x_), y(y_)
    {}
    // temp - remove when geometry is templated on value_type
    point(mapnik::coord<double, 2> const& c)
        : x(c.x), y(c.y) {}

    point(point const& other) = default;
    point(point && other) noexcept = default;
    point & operator=(point const& other) = default;
    friend inline bool operator== (point<T> const& a, point<T> const& b)
    {
        return a.x == b.x && a.y == b.y;
    }
    friend inline bool operator!= (point<T> const& a, point <T> const& b)
    {
        return a.x != b.x  || a.y != b.y;
    }
    value_type x;
    value_type y;
};

template <typename T>
struct line_string : std::vector<point<T> >
{
    line_string() = default;
    line_string (std::size_t size)
        : std::vector<point<T> >(size) {}
    line_string (line_string && other) = default ;
    line_string& operator=(line_string &&) = default;
    line_string (line_string const& ) = default;
    line_string& operator=(line_string const&) = default;
    inline std::size_t num_points() const { return std::vector<point<T>>::size(); }
    inline void add_coord(T x, T y) { std::vector<point<T>>::template emplace_back(x,y);}
};

template <typename T>
struct linear_ring : line_string<T>
{
    linear_ring() = default;
    linear_ring(std::size_t size)
        : line_string<T>(size) {}
    linear_ring (linear_ring && other) = default ;
    linear_ring& operator=(linear_ring &&) = default;
    linear_ring(line_string<T> && other)
        : line_string<T>(other) {}
    linear_ring (linear_ring const& ) = default;
    linear_ring(line_string<T> const& other)
        : line_string<T>(other) {}
    linear_ring& operator=(linear_ring const&) = default;

};

template <typename T>
struct polygon
{
    linear_ring<T> exterior_ring;
    std::vector<linear_ring<T>> interior_rings;

    inline void set_exterior_ring(linear_ring<T> && ring)
    {
        exterior_ring = std::move(ring);
    }

    inline void add_hole(linear_ring<T> && ring)
    {
        interior_rings.emplace_back(std::move(ring));
    }

    inline bool empty() const { return exterior_ring.empty(); }

    inline std::size_t num_rings() const
    {
        return 1 + interior_rings.size();
    }
};

template <typename T>
struct multi_point : line_string<T> {};

template <typename T>
struct multi_line_string : std::vector<line_string<T>> {};

template <typename T>
struct multi_polygon : std::vector<polygon<T>> {};

template <typename T>
struct geometry_collection;

struct geometry_empty {};

template <typename T>
using geometry = mapnik::util::variant<geometry_empty,
                                       point<T>,
                                       line_string<T>,
                                       polygon<T>,
                                       multi_point<T>,
                                       multi_line_string<T>,
                                       multi_polygon<T>,
                                       mapnik::util::recursive_wrapper<geometry_collection<T> > >;

template <typename T>
struct geometry_collection : std::vector<geometry<T>> {};

}}

#endif //MAPNIK_GEOMETRY_HPP
<|endoftext|>


<commit_before>/*
 * ttas_spin_mutex.hpp
 */
#ifndef YAMC_TTAS_SIPN_MUTEX_HPP_
#define YAMC_TTAS_SIPN_MUTEX_HPP_

#include <atomic>
#include <thread>

namespace yamc {

/*
 * Test-and-Test-And-Swap(TTAS) spinlock implementation
 */
namespace spin_ttas {

class mutex {
  std::atomic<int> state_{0};

public:
  mutex() = default;
  ~mutex() = default;

  mutex(const mutex&) = delete;
  mutex& operator=(const mutex&) = delete;

  void lock() {
    do {
      while (state_.load(std::memory_order_relaxed) != 0) {
        std::this_thread::yield();
      }
      int state = 0;
    } while (!state_.compare_exchange_weak(state, 1, std::memory_order_acquire));
  }

  bool try_lock() {
    int state = 0;
    return state_.compare_exchange_weak(state, 1, std::memory_order_acquire);
  }

  void unlock() {
    state_.store(0, std::memory_order_release);
  }
};

} // namespace spin_ttas
} // namespace yamc

#endif
<commit_msg>fix variable scope in spin_ttas::mutex::lock()<commit_after>/*
 * ttas_spin_mutex.hpp
 */
#ifndef YAMC_TTAS_SIPN_MUTEX_HPP_
#define YAMC_TTAS_SIPN_MUTEX_HPP_

#include <atomic>
#include <thread>

namespace yamc {

/*
 * Test-and-Test-And-Swap(TTAS) spinlock implementation
 */
namespace spin_ttas {

class mutex {
  std::atomic<int> state_{0};

public:
  mutex() = default;
  ~mutex() = default;

  mutex(const mutex&) = delete;
  mutex& operator=(const mutex&) = delete;

  void lock() {
    int state;
    do {
      while (state_.load(std::memory_order_relaxed) != 0) {
        std::this_thread::yield();
      }
      state = 0;
    } while (!state_.compare_exchange_weak(state, 1, std::memory_order_acquire));
  }

  bool try_lock() {
    int state = 0;
    return state_.compare_exchange_weak(state, 1, std::memory_order_acquire);
  }

  void unlock() {
    state_.store(0, std::memory_order_release);
  }
};

} // namespace spin_ttas
} // namespace yamc

#endif
<|endoftext|>


<commit_before>#ifndef V_SMC_RNG_RANDOM_HPP
#define V_SMC_RNG_RANDOM_HPP

// #include <Random123/aes.h>
// #include <Random123/ars.h>
#include <Random123/philox.h>
#include <Random123/threefry.h>

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4521)
#endif // _MSC_VER

#include <Random123/conventional/Engine.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER

#include <vSMC/internal/config.hpp>
#include <vSMC/rng/common.hpp>

/// The parallel RNG (based on Random123) seed, unsigned
#ifndef V_SMC_CRNG_SEED
#define V_SMC_CRNG_SEED 0xdeadbeefU
#endif // V_SMC_CRNG_SEED

/// The parallel RNG (based on Random123) type, philox or threefry
#ifndef V_SMC_CRNG_TYPE
#define V_SMC_CRNG_TYPE r123::Threefry4x64
#endif // V_SMC_CRNG_TYPE

#ifdef V_SMC_USE_STD_RANDOM
#include <random>
#else // V_SMC_USE_STD_RANDOM
#include <boost/random.hpp>
#endif // V_SMC_USE_STD_RANDOM

namespace vSMC { namespace rng {

#ifdef V_SMC_USE_STD_RANDOM

using std::uniform_int_distribution;
using std::uniform_real_distribution;

using std::bernoulli_distribution;
using std::binomial_distribution;
using std::extreme_value_distribution;
using std::geometric_distribution;
using std::negative_binomial_distribution;

using std::exponential_distribution;
using std::gamma_distribution;
using std::poisson_distribution;
using std::weibull_distribution;

using std::cauchy_distribution;
using std::chi_squared_distribution;
using std::fisher_f_distribution;
using std::lognormal_distribution;
using std::normal_distribution;
using std::student_t_distribution;

using std::discrete_distribution;
using std::piecewise_constant_distribution;
using std::piecewise_linear_distribution;

#else // V_SMC_USE_STD_RANDOM

using boost::random::uniform_int_distribution;
using boost::random::uniform_real_distribution;

typedef boost::random::bernoulli_distribution<double> bernoulli_distribution;
using boost::random::binomial_distribution;
using boost::random::extreme_value_distribution;
using boost::random::geometric_distribution;
using boost::random::negative_binomial_distribution;

using boost::random::exponential_distribution;
using boost::random::gamma_distribution;
using boost::random::poisson_distribution;
using boost::random::weibull_distribution;

using boost::random::cauchy_distribution;
using boost::random::chi_squared_distribution;
using boost::random::fisher_f_distribution;
using boost::random::lognormal_distribution;
using boost::random::normal_distribution;
using boost::random::student_t_distribution;

using boost::random::discrete_distribution;
using boost::random::piecewise_constant_distribution;
using boost::random::piecewise_linear_distribution;

#endif // V_SMC_USE_STD_RANDOM

} } // namespace vSMC::rng

#include <vSMC/rng/beta_distribution.hpp>
#include <vSMC/rng/laplace_distribution.hpp>

#endif // V_SMC_RNG_RANDOM_HPP
<commit_msg>cleanup<commit_after>#ifndef V_SMC_RNG_RANDOM_HPP
#define V_SMC_RNG_RANDOM_HPP

// #include <Random123/aes.h>
// #include <Random123/ars.h>
#include <Random123/philox.h>
#include <Random123/threefry.h>

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4521)
#endif // _MSC_VER

#include <Random123/conventional/Engine.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER

#include <vSMC/internal/config.hpp>
#include <vSMC/rng/common.hpp>

/// The parallel RNG (based on Random123) seed, unsigned
#ifndef V_SMC_CRNG_SEED
#define V_SMC_CRNG_SEED 0xdeadbeefU
#endif // V_SMC_CRNG_SEED

/// The parallel RNG (based on Random123) type, philox or threefry
#ifndef V_SMC_CRNG_TYPE
#define V_SMC_CRNG_TYPE r123::Threefry4x64
#endif // V_SMC_CRNG_TYPE

#ifdef V_SMC_USE_STD_RANDOM
#include <random>
#else // V_SMC_USE_STD_RANDOM
#include <boost/random.hpp>
#endif // V_SMC_USE_STD_RANDOM

namespace vSMC { namespace rng {

#ifdef V_SMC_USE_STD_RANDOM

using std::uniform_int_distribution;
using std::uniform_real_distribution;

using std::bernoulli_distribution;
using std::binomial_distribution;
using std::geometric_distribution;
using std::negative_binomial_distribution;

using std::exponential_distribution;
using std::extreme_value_distribution;
using std::gamma_distribution;
using std::poisson_distribution;
using std::weibull_distribution;

using std::cauchy_distribution;
using std::chi_squared_distribution;
using std::fisher_f_distribution;
using std::lognormal_distribution;
using std::normal_distribution;
using std::student_t_distribution;

using std::discrete_distribution;
using std::piecewise_constant_distribution;
using std::piecewise_linear_distribution;

#else // V_SMC_USE_STD_RANDOM

using boost::random::uniform_int_distribution;
using boost::random::uniform_real_distribution;

typedef boost::random::bernoulli_distribution<double> bernoulli_distribution;
using boost::random::binomial_distribution;
using boost::random::geometric_distribution;
using boost::random::negative_binomial_distribution;

using boost::random::exponential_distribution;
using boost::random::extreme_value_distribution;
using boost::random::gamma_distribution;
using boost::random::poisson_distribution;
using boost::random::weibull_distribution;

using boost::random::cauchy_distribution;
using boost::random::chi_squared_distribution;
using boost::random::fisher_f_distribution;
using boost::random::lognormal_distribution;
using boost::random::normal_distribution;
using boost::random::student_t_distribution;

using boost::random::discrete_distribution;
using boost::random::piecewise_constant_distribution;
using boost::random::piecewise_linear_distribution;

#endif // V_SMC_USE_STD_RANDOM

} } // namespace vSMC::rng

#include <vSMC/rng/beta_distribution.hpp>
#include <vSMC/rng/laplace_distribution.hpp>

#endif // V_SMC_RNG_RANDOM_HPP
<|endoftext|>


<commit_before>/************************************************************************/
/*                                                                      */
/*               Copyright 1998-2001 by Ullrich Koethe                  */
/*               Copyright 2001-2002 by Gunnar Kedenburg                */
/*       Cognitive Systems Group, University of Hamburg, Germany        */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    You may use, modify, and distribute this software according       */
/*    to the terms stated in the LICENSE file included in               */
/*    the VIGRA distribution.                                           */
/*                                                                      */
/*    The VIGRA Website is                                              */
/*        http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/      */
/*    Please direct questions, bug reports, and contributions to        */
/*        koethe@informatik.uni-hamburg.de                              */
/*                                                                      */
/*  THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR          */
/*  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED      */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_IMAGEINFO_HXX
#define VIGRA_IMAGEINFO_HXX

#include <memory>
#include <string>
#include "vigra/utilities.hxx"
#include "vigra/codec.hxx"

namespace vigra
{
/** \addtogroup VigraImpex Image Import/Export Facilities

    supports GIF, TIFF, JPEG, BMP, PNM (PBM, PGM, PPM), PNG, SunRaster, KHOROS-VIFF formats
**/
//@{

    /** \brief List the image formats VIGRA can read and write.

        This is useful for creating error messages if VIGRA encounters an
        image format it doesn't recognize.

         Usage:

        \#include "vigra/imageinfo.hxx"

        Namespace: vigra

        \code
        std::cout << "supported formats: " << vigra::impexListFormats() << std::endl;
        \endcode

    **/
std::string impexListFormats();

    /** \brief List the file extension VIGRA understands.

        This is useful for creating file dialogs that only list image files
        VIGRA can actually import.

         Usage:

        \#include "vigra/imageinfo.hxx"

        Namespace: vigra

        \code
        std::cout << "supported extensions: " << vigra::impexListExtensions() << std::endl;
        \endcode

    **/
std::string impexListExtensions();

/** \brief Test whether a file is an image format known to VIGRA.

    This checks the first few bytes of the file and compares them with the
    "magic strings" of each recognized image format.

     Usage:

    \#include "vigra/imageinfo.hxx"

    Namespace: vigra

    \code
    std::cout << "is image: " << vigra::isImage("foo.bmp") << std::endl;
    \endcode

**/
bool isImage(char const * filename);

/********************************************************/
/*                                                      */
/*                   ImageExportInfo                    */
/*                                                      */
/********************************************************/

/** \brief Argument object for the function exportImage().
    See \ref exportImage() for usage example. This object must be used
    to define the properties of an image to be written to disk.

    \#include "vigra/imageinfo.hxx"

    Namespace: vigra
**/
class ImageExportInfo
{
  public:
        /** Construct ImageExportInfo object.

            The image will be stored under the given filename.
            The file type will be guessed from the extension unless overridden
            by \ref setFileType(). Recognized extensions: '.bmp', '.gif',
            '.jpeg', '.jpg', '.p7', '.png', '.pbm', '.pgm', '.pnm', '.ppm', '.ras',
            '.tif', '.tiff', '.xv'.
            JPEG support requires libjpeg, PNG support requires libpng, and
            TIFF support requires libtiff.
        **/
    ImageExportInfo( const char * );

    const char * getFileName() const;

    /** Store image as given file type.

        This will override any type guessed
        from the file name's extension. Recognized file types:

"BMP"
 Microsoft Windows bitmap image file.

"GIF"
 CompuServe graphics interchange format; 8-bit color.

"JPEG"
 Joint Photographic Experts Group JFIF format;
        compressed 24-bit color (only available if libjpeg is installed).

"PNG"
 Portable Network Graphic
        (only available if libpng is installed).

"PBM"
 Portable bitmap format (black and white).

"PGM"
 Portable graymap format (gray scale).

"PNM"
 Portable anymap.

"PPM"
 Portable pixmap format (color).

"SUN"
 SUN Rasterfile.

"TIFF"
 Tagged Image File Format.
        (only available if libtiff is installed.)

"VIFF"
 Khoros Visualization image file.

        With the exception of TIFF and VIFF, all file types store
        1 byte (gray scale and mapped RGB) or 3 bytes (RGB) per
        pixel.

        TIFF and VIFF are aditionally able to store short and long
        integers (2 or 4 bytes) and real values (32 bit float and
        64 bit double) without conversion. So you will need to use
        TIFF or VIFF if you need to store images with high
        accuracy (the appropriate type to write is automatically
        derived from the image type to be exported). However, many
        other programs using TIFF (e.g. ImageMagick) have not
        implemented support for those pixel types.  So don't be
        surprised if the generated TIFF is not readable in some
        cases.  If this happens, convert the image to 'unsigned
        char' or 'RGBValue\<unsigned char\>' prior to exporting.
    **/
    ImageExportInfo & setFileType( const char * );
    const char * getFileType() const;

    /** Set compression type.

        Recognized strings: "" (no compression), "LZW",
        "RunLength", "1" ... "100". A number is interpreted as the
        compression quality for JPEG compression. JPEG compression is
        supported by the JPEG and TIFF formats.
    **/
    ImageExportInfo & setCompression( const char * );
    const char * getCompression() const;

    /** Set the pixel type of the image. Possible values are:

"UINT8"
 8-bit unsigned integer (unsigned char)

"INT16"
 16-bit signed integer (short)

"INT32"
 32-bit signed integer (long)

"FLOAT"
 32-bit floating point (float)

"DOUBLE"
 64-bit floating point (double)

    **/
    ImageExportInfo & setPixelType( const char * );

    /** Get the pixel type of the image. Possible values are:

"UINT8"
 8-bit unsigned integer (unsigned char)

"INT16"
 16-bit signed integer (short)

"INT32"
 32-bit signed integer (long)

"FLOAT"
 32-bit floating point (float)

"DOUBLE"
 64-bit floating point (double)

    **/
    const char * getPixelType() const;

    /** Set the image resolution in horizontal direction
    **/
    ImageExportInfo & setXResolution( float );
    float getXResolution() const;

    /** Set the image resolution in vertical direction
    **/
    ImageExportInfo & setYResolution( float );
    float getYResolution() const;

  private:
    std::string m_filename, m_filetype, m_pixeltype, m_comp;
    float m_x_res, m_y_res;
};

// return an encoder for a given ImageExportInfo object
std::auto_ptr<Encoder> encoder( const ImageExportInfo & info );

/********************************************************/
/*                                                      */
/*                   ImageImportInfo                    */
/*                                                      */
/********************************************************/

/** \brief Argument object for the function importImage().
See \ref importImage() for a usage example. This object must be
used to read an image from disk and enquire about its properties.

\#include "vigra/imageinfo.hxx"

Namespace: vigra
**/
class ImageImportInfo
{
  public:
    enum PixelType { UINT8, INT16, INT32, FLOAT, DOUBLE };

        /** Construct ImageImportInfo object.

            The image with the given filename is read into memory.
            The file type will be determined by the first few bytes of the
            file (magic number). Recognized file types:

"BMP"
 Microsoft Windows bitmap image file.

"JPEG"
 Joint Photographic Experts Group JFIF format
            (only available if libjpeg is installed).

"GIF"
 CompuServe graphics interchange format; 8-bit color.

"PNG"
 Portable Network Graphics
            (only available if libpng is installed).

"PBM"
 Portable bitmap format (black and white).

"PGM"
 Portable graymap format (gray scale).

"PNM"
 Portable anymap.

"PPM"
 Portable pixmap format (color).

"SUN"
 SUN Rasterfile.

"TIFF"
 Tagged Image File Format.
            (only available if libtiff is installed.)

"VIFF"
 Khoros Visualization image file.

        **/
    ImageImportInfo( const char *  );

    const char * getFileName() const;

        /** Get the file type of the image associated with this
            info object.

            See ImageImportInfo::ImageImportInfo for a list of the
            available file types.
        **/
    const char * getFileType() const;

        /** Get width of the image.
         **/
    int width() const;

        /** Get height of the image.
         **/
    int height() const;

        /** Get the number bands in the image.
         **/
    int numBands() const;

        /** Get size of the image.
         **/
    Size2D size() const;

        /** Returns true if the image is gray scale.
         **/
    bool isGrayscale() const;

        /** Returns true if the image is colored (RGB).
         **/
    bool isColor() const;

        /** Query the pixel type of the image.

            Possible values are:

"UINT8"
 8-bit unsigned integer (unsigned char)

"INT16"
 16-bit signed integer (short)

"INT32"
 32-bit signed integer (long)

"FLOAT"
 32-bit floating point (float)

"DOUBLE"
 64-bit floating point (double)

        **/
    const char * getPixelType() const;

        /// deprecated: use getPixelType()
    PixelType pixelType() const;

        /** Returns true if the image has 1 byte per pixel (gray) or
            3 bytes per pixel (RGB).
        **/
    bool isByte() const;

        /** Returns the image resolution in horizontal direction
         **/
    float getXResolution() const;

        /** Returns the image resolution in vertical direction
         **/
    float getYResolution() const;

  private:
    std::string m_filename, m_filetype, m_pixeltype;
    int m_width, m_height, m_num_bands;
    float m_x_res, m_y_res;
};

// return a decoder for a given ImageImportInfo object
std::auto_ptr<vigra::Decoder> decoder( const ImageImportInfo & info );

} // namespace vigra

#endif // VIGRA_IMAGEINFO_HXX
<commit_msg>adapted documentation of setPixelType() to new export semantics (forse output pixel type)<commit_after>/************************************************************************/
/*                                                                      */
/*               Copyright 1998-2001 by Ullrich Koethe                  */
/*               Copyright 2001-2002 by Gunnar Kedenburg                */
/*       Cognitive Systems Group, University of Hamburg, Germany        */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    You may use, modify, and distribute this software according       */
/*    to the terms stated in the LICENSE file included in               */
/*    the VIGRA distribution.                                           */
/*                                                                      */
/*    The VIGRA Website is                                              */
/*        http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/      */
/*    Please direct questions, bug reports, and contributions to        */
/*        koethe@informatik.uni-hamburg.de                              */
/*                                                                      */
/*  THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR          */
/*  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED      */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_IMAGEINFO_HXX
#define VIGRA_IMAGEINFO_HXX

#include <memory>
#include <string>
#include "vigra/utilities.hxx"
#include "vigra/codec.hxx"

namespace vigra
{
/** \addtogroup VigraImpex Image Import/Export Facilities

    supports GIF, TIFF, JPEG, BMP, PNM (PBM, PGM, PPM), PNG, SunRaster, KHOROS-VIFF formats
**/
//@{

    /** \brief List the image formats VIGRA can read and write.

        This is useful for creating error messages if VIGRA encounters an
        image format it doesn't recognize.

         Usage:

        \#include "vigra/imageinfo.hxx"

        Namespace: vigra

        \code
        std::cout << "supported formats: " << vigra::impexListFormats() << std::endl;
        \endcode

    **/
std::string impexListFormats();

    /** \brief List the file extension VIGRA understands.

        This is useful for creating file dialogs that only list image files
        VIGRA can actually import.

         Usage:

        \#include "vigra/imageinfo.hxx"

        Namespace: vigra

        \code
        std::cout << "supported extensions: " << vigra::impexListExtensions() << std::endl;
        \endcode

    **/
std::string impexListExtensions();

/** \brief Test whether a file is an image format known to VIGRA.

    This checks the first few bytes of the file and compares them with the
    "magic strings" of each recognized image format.

     Usage:

    \#include "vigra/imageinfo.hxx"

    Namespace: vigra

    \code
    std::cout << "is image: " << vigra::isImage("foo.bmp") << std::endl;
    \endcode

**/
bool isImage(char const * filename);

/********************************************************/
/*                                                      */
/*                   ImageExportInfo                    */
/*                                                      */
/********************************************************/

/** \brief Argument object for the function exportImage().
    See \ref exportImage() for usage example. This object must be used
    to define the properties of an image to be written to disk.

    \#include "vigra/imageinfo.hxx"

    Namespace: vigra
**/
class ImageExportInfo
{
  public:
        /** Construct ImageExportInfo object.

            The image will be stored under the given filename.
            The file type will be guessed from the extension unless overridden
            by \ref setFileType(). Recognized extensions: '.bmp', '.gif',
            '.jpeg', '.jpg', '.p7', '.png', '.pbm', '.pgm', '.pnm', '.ppm', '.ras',
            '.tif', '.tiff', '.xv'.
            JPEG support requires libjpeg, PNG support requires libpng, and
            TIFF support requires libtiff.
        **/
    ImageExportInfo( const char * );

    const char * getFileName() const;

    /** Store image as given file type.

        This will override any type guessed
        from the file name's extension. Recognized file types:

"BMP"
 Microsoft Windows bitmap image file.

"GIF"
 CompuServe graphics interchange format; 8-bit color.

"JPEG"
 Joint Photographic Experts Group JFIF format;
        compressed 24-bit color (only available if libjpeg is installed).

"PNG"
 Portable Network Graphic
        (only available if libpng is installed).

"PBM"
 Portable bitmap format (black and white).

"PGM"
 Portable graymap format (gray scale).

"PNM"
 Portable anymap.

"PPM"
 Portable pixmap format (color).

"SUN"
 SUN Rasterfile.

"TIFF"
 Tagged Image File Format.
        (only available if libtiff is installed.)

"VIFF"
 Khoros Visualization image file.

        With the exception of TIFF and VIFF, all file types store
        1 byte (gray scale and mapped RGB) or 3 bytes (RGB) per
        pixel.

        TIFF and VIFF are aditionally able to store short and long
        integers (2 or 4 bytes) and real values (32 bit float and
        64 bit double) without conversion. So you will need to use
        TIFF or VIFF if you need to store images with high
        accuracy (the appropriate type to write is automatically
        derived from the image type to be exported). However, many
        other programs using TIFF (e.g. ImageMagick) have not
        implemented support for those pixel types.  So don't be
        surprised if the generated TIFF is not readable in some
        cases.  If this happens, export the image as 'unsigned
        char' or 'RGBValue\<unsigned char\>' by calling
        \ref ImageExportInfo::setPixelType().
    **/
    ImageExportInfo & setFileType( const char * );
    const char * getFileType() const;

    /** Set compression type.

        Recognized strings: "" (no compression), "LZW",
        "RunLength", "1" ... "100". A number is interpreted as the
        compression quality for JPEG compression. JPEG compression is
        supported by the JPEG and TIFF formats. "LZW" is only available
        if libtiff was installed with LZW enabled. By default, libtiff comes
        with LZW disabled due to Unisys patent enforcement. In this case,
        VIGRA stores the image uncompressed.
    **/
    ImageExportInfo & setCompression( const char * );
    const char * getCompression() const;

    /** Set the pixel type of the image file. Possible values are:

"UINT8"
 8-bit unsigned integer (unsigned char)

"INT16"
 16-bit signed integer (short)

"INT32"
 32-bit signed integer (long)

"FLOAT"
 32-bit floating point (float)

"DOUBLE"
 64-bit floating point (double)

        Usage:
        FImage img(w,h);

        // by default, float images are exported with pixeltype float
        // when the target format support this type, i.e. is TIFF or VIFF.
        exportImage(srcImageRange(img), ImageExportInfo("asFloat.tif"));

        // if this is not desired, force a different pixeltype
        exportImage(srcImageRange(img), ImageExportInfo("asByte.tif").setPixelType("UINT8"));
    **/
    ImageExportInfo & setPixelType( const char * );

    /** Get the pixel type of the image. Possible values are:

"UINT8"
 8-bit unsigned integer (unsigned char)

"INT16"
 16-bit signed integer (short)

"INT32"
 32-bit signed integer (long)

"FLOAT"
 32-bit floating point (float)

"DOUBLE"
 64-bit floating point (double)

    **/
    const char * getPixelType() const;

    /** Set the image resolution in horizontal direction
    **/
    ImageExportInfo & setXResolution( float );
    float getXResolution() const;

    /** Set the image resolution in vertical direction
    **/
    ImageExportInfo & setYResolution( float );
    float getYResolution() const;

  private:
    std::string m_filename, m_filetype, m_pixeltype, m_comp;
    float m_x_res, m_y_res;
};

// return an encoder for a given ImageExportInfo object
std::auto_ptr<Encoder> encoder( const ImageExportInfo & info );

/********************************************************/
/*                                                      */
/*                   ImageImportInfo                    */
/*                                                      */
/********************************************************/

/** \brief Argument object for the function importImage().
See \ref importImage() for a usage example. This object must be
used to read an image from disk and enquire about its properties.

\#include "vigra/imageinfo.hxx"

Namespace: vigra
**/
class ImageImportInfo
{
  public:
    enum PixelType { UINT8, INT16, INT32, FLOAT, DOUBLE };

        /** Construct ImageImportInfo object.

            The image with the given filename is read into memory.
            The file type will be determined by the first few bytes of the
            file (magic number). Recognized file types:

"BMP"
 Microsoft Windows bitmap image file.

"JPEG"
 Joint Photographic Experts Group JFIF format
            (only available if libjpeg is installed).

"GIF"
 CompuServe graphics interchange format; 8-bit color.

"PNG"
 Portable Network Graphics
            (only available if libpng is installed).

"PBM"
 Portable bitmap format (black and white).

"PGM"
 Portable graymap format (gray scale).

"PNM"
 Portable anymap.

"PPM"
 Portable pixmap format (color).

"SUN"
 SUN Rasterfile.

"TIFF"
 Tagged Image File Format.
            (only available if libtiff is installed.)

"VIFF"
 Khoros Visualization image file.

        **/
    ImageImportInfo( const char *  );

    const char * getFileName() const;

        /** Get the file type of the image associated with this
            info object.

            See ImageImportInfo::ImageImportInfo for a list of the
            available file types.
        **/
    const char * getFileType() const;

        /** Get width of the image.
         **/
    int width() const;

        /** Get height of the image.
         **/
    int height() const;

        /** Get the number bands in the image.
         **/
    int numBands() const;

        /** Get size of the image.
         **/
    Size2D size() const;

        /** Returns true if the image is gray scale.
         **/
    bool isGrayscale() const;

        /** Returns true if the image is colored (RGB).
         **/
    bool isColor() const;

        /** Query the pixel type of the image.

            Possible values are:

"UINT8"
 8-bit unsigned integer (unsigned char)

"INT16"
 16-bit signed integer (short)

"INT32"
 32-bit signed integer (long)

"FLOAT"
 32-bit floating point (float)

"DOUBLE"
 64-bit floating point (double)

        **/
    const char * getPixelType() const;

        /// deprecated: use getPixelType()
    PixelType pixelType() const;

        /** Returns true if the image has 1 byte per pixel (gray) or
            3 bytes per pixel (RGB).
        **/
    bool isByte() const;

        /** Returns the image resolution in horizontal direction
         **/
    float getXResolution() const;

        /** Returns the image resolution in vertical direction
         **/
    float getYResolution() const;

  private:
    std::string m_filename, m_filetype, m_pixeltype;
    int m_width, m_height, m_num_bands;
    float m_x_res, m_y_res;
};

// return a decoder for a given ImageImportInfo object
std::auto_ptr<vigra::Decoder> decoder( const ImageImportInfo & info );

} // namespace vigra

#endif // VIGRA_IMAGEINFO_HXX
<|endoftext|>


<commit_before>//===-- C-API.cpp ---------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

// Include the public API.
#include <llbuild/llbuild.h>

#include "llbuild/Basic/Version.h"
#include "llbuild/Core/BuildDB.h"
#include "llbuild/Core/BuildEngine.h"

using namespace llbuild;
using namespace llbuild::core;

/* Misc API */

const char* llb_get_full_version_string(void) {
  // Use a static local to store the version string, to avoid lifetime issues.
  static std::string versionString = getLLBuildFullVersion();

  return versionString.c_str();
}

/* Build Engine API */

namespace {

class CAPIBuildEngineDelegate : public BuildEngineDelegate {
  llb_buildengine_delegate_t cAPIDelegate;

  friend class CAPITask;

  virtual ~CAPIBuildEngineDelegate() {
    if (cAPIDelegate.destroy_context) {
      cAPIDelegate.destroy_context(cAPIDelegate.context);
    }
  }

  virtual Rule lookupRule(const KeyType& key) override {
    void* engineContext = cAPIDelegate.context;
    llb_rule_t rule{};
    llb_data_t key_data{ key.length(), (const uint8_t*)key.data() };
    cAPIDelegate.lookup_rule(cAPIDelegate.context, &key_data, &rule);

    std::function<bool(const Rule&, const ValueType&)> isResultValid;
    if (rule.is_result_valid) {
      isResultValid = [rule, engineContext] (const Rule& nativeRule,
                                             const ValueType& value) {
        // FIXME: Why do we pass the rule here, it is redundant. NativeRule
        // should be == rule here.
        llb_data_t value_data{ value.size(), value.data() };
        return rule.is_result_valid(rule.context, engineContext, &rule,
                                    &value_data);
      };
    }

    std::function<void(Rule::StatusKind)> updateStatus;
    if (rule.update_status) {
      updateStatus = [rule, engineContext] (Rule::StatusKind kind) {
        return rule.update_status(rule.context, engineContext,
                                  (llb_rule_status_kind_t)kind);
      };
    }

    return Rule{
      // FIXME: This is a wasteful copy.
      key,
      [rule, engineContext] (BuildEngine& engine) {
        return (Task*) rule.create_task(rule.context, engineContext);
      },
      isResultValid,
      updateStatus };
  }

  virtual void cycleDetected(const std::vector<core::Rule*>& items) override {
    // FIXME.
    assert(0 && "unexpected cycle!");
  }

public:
  CAPIBuildEngineDelegate(llb_buildengine_delegate_t delegate)
    : cAPIDelegate(delegate)
  {

  }
};

class CAPITask : public Task {
  llb_task_delegate_t cAPIDelegate;

public:
  CAPITask(llb_task_delegate_t delegate)
    : Task("C-API-Task"), cAPIDelegate(delegate)
  {

  }

  virtual void start(BuildEngine& engine) override {
    CAPIBuildEngineDelegate* delegate =
      static_cast<CAPIBuildEngineDelegate*>(engine.getDelegate());
    cAPIDelegate.start(cAPIDelegate.context,
                       delegate->cAPIDelegate.context,
                       (llb_task_t*)this);
  }

  virtual void provideValue(BuildEngine& engine, uintptr_t inputID,
                            const ValueType& value) override {
    CAPIBuildEngineDelegate* delegate =
      static_cast<CAPIBuildEngineDelegate*>(engine.getDelegate());
    llb_data_t valueData{ value.size(), value.data() };
    cAPIDelegate.provide_value(cAPIDelegate.context,
                               delegate->cAPIDelegate.context,
                               (llb_task_t*)this,
                               inputID, &valueData);
  }

  virtual void inputsAvailable(BuildEngine& engine) override {
    CAPIBuildEngineDelegate* delegate =
      static_cast<CAPIBuildEngineDelegate*>(engine.getDelegate());
    cAPIDelegate.inputs_available(cAPIDelegate.context,
                                  delegate->cAPIDelegate.context,
                                  (llb_task_t*)this);
  }
};

};

llb_buildengine_t* llb_buildengine_create(llb_buildengine_delegate_t delegate) {
  // FIXME: Delegate is leaked, need to provide a provision for owning the
  // delegate.
  BuildEngineDelegate* engine_delegate = new CAPIBuildEngineDelegate(delegate);
  return (llb_buildengine_t*) new BuildEngine(*engine_delegate);
}

void llb_buildengine_destroy(llb_buildengine_t* engine) {
  // FIXME: Delegate is lost.
  delete (BuildEngine*)engine;
}

bool llb_buildengine_attach_db(llb_buildengine_t* engine_p,
                               const llb_data_t* path,
                               uint32_t schema_version,
                               char** error_out) {
  BuildEngine* engine = (BuildEngine*) engine_p;

  std::string error;
  std::unique_ptr<BuildDB> db(createSQLiteBuildDB(
                                  std::string((char*)path->data,
                                              path->length),
                                  schema_version,
                                  &error));
  if (!db) {
    *error_out = strdup(error.c_str());
    return false;
  }

  engine->attachDB(std::move(db));
  return true;
}

void llb_buildengine_build(llb_buildengine_t* engine_p, const llb_data_t* key,
                           llb_data_t* result_out) {
  BuildEngine* engine = (BuildEngine*) engine_p;

  auto& result = engine->build(KeyType((const char*)key->data, key->length));

  *result_out = llb_data_t{ result.size(), result.data() };
}

llb_task_t* llb_buildengine_register_task(llb_buildengine_t* engine_p,
                                          llb_task_t* task) {
  BuildEngine* engine = (BuildEngine*) engine_p;
  engine->registerTask((Task*)task);
  return task;
}

void llb_buildengine_task_needs_input(llb_buildengine_t* engine_p,
                                      llb_task_t* task,
                                      const llb_data_t* key,
                                      uintptr_t input_id) {
  BuildEngine* engine = (BuildEngine*) engine_p;
  engine->taskNeedsInput((Task*)task,
                         KeyType((const char*)key->data, key->length),
                         input_id);
}

void llb_buildengine_task_must_follow(llb_buildengine_t* engine_p,
                                      llb_task_t* task,
                                      const llb_data_t* key) {
  BuildEngine* engine = (BuildEngine*) engine_p;
  engine->taskMustFollow((Task*)task,
                         KeyType((const char*)key->data, key->length));
}

void llb_buildengine_task_discovered_dependency(llb_buildengine_t* engine_p,
                                                llb_task_t* task,
                                                const llb_data_t* key) {
  BuildEngine* engine = (BuildEngine*) engine_p;
  engine->taskDiscoveredDependency((Task*)task,
                                   KeyType((const char*)key->data,
                                           key->length));
}

void llb_buildengine_task_is_complete(llb_buildengine_t* engine_p,
                                      llb_task_t* task,
                                      const llb_data_t* value,
                                      bool force_change) {
  BuildEngine* engine = (BuildEngine*) engine_p;
  std::vector<uint8_t> result(value->length);
  memcpy(result.data(), value->data, value->length);
  engine->taskIsComplete((Task*)task, std::move(result));
}

llb_task_t* llb_task_create(llb_task_delegate_t delegate) {
  return (llb_task_t*) new CAPITask(delegate);
}
<commit_msg>[C-API] Add some sanity checking asserts.<commit_after>//===-- C-API.cpp ---------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

// Include the public API.
#include <llbuild/llbuild.h>

#include "llbuild/Basic/Version.h"
#include "llbuild/Core/BuildDB.h"
#include "llbuild/Core/BuildEngine.h"

using namespace llbuild;
using namespace llbuild::core;

/* Misc API */

const char* llb_get_full_version_string(void) {
  // Use a static local to store the version string, to avoid lifetime issues.
  static std::string versionString = getLLBuildFullVersion();

  return versionString.c_str();
}

/* Build Engine API */

namespace {

class CAPIBuildEngineDelegate : public BuildEngineDelegate {
  llb_buildengine_delegate_t cAPIDelegate;

  friend class CAPITask;

  virtual ~CAPIBuildEngineDelegate() {
    if (cAPIDelegate.destroy_context) {
      cAPIDelegate.destroy_context(cAPIDelegate.context);
    }
  }

  virtual Rule lookupRule(const KeyType& key) override {
    void* engineContext = cAPIDelegate.context;
    llb_rule_t rule{};
    llb_data_t key_data{ key.length(), (const uint8_t*)key.data() };
    cAPIDelegate.lookup_rule(cAPIDelegate.context, &key_data, &rule);

    // FIXME: Check that the client created the rule appropriately. We should
    // change the API to be type safe here, by forcing the client to return a
    // handle created by the C API.
    assert(rule.create_task && "client failed to initialize rule");

    std::function<bool(const Rule&, const ValueType&)> isResultValid;
    if (rule.is_result_valid) {
      isResultValid = [rule, engineContext] (const Rule& nativeRule,
                                             const ValueType& value) {
        // FIXME: Why do we pass the rule here, it is redundant. NativeRule
        // should be == rule here.
        llb_data_t value_data{ value.size(), value.data() };
        return rule.is_result_valid(rule.context, engineContext, &rule,
                                    &value_data);
      };
    }

    std::function<void(Rule::StatusKind)> updateStatus;
    if (rule.update_status) {
      updateStatus = [rule, engineContext] (Rule::StatusKind kind) {
        return rule.update_status(rule.context, engineContext,
                                  (llb_rule_status_kind_t)kind);
      };
    }

    return Rule{
      // FIXME: This is a wasteful copy.
      key,
      [rule, engineContext] (BuildEngine& engine) {
        return (Task*) rule.create_task(rule.context, engineContext);
      },
      isResultValid,
      updateStatus };
  }

  virtual void cycleDetected(const std::vector<core::Rule*>& items) override {
    // FIXME.
    assert(0 && "unexpected cycle!");
  }

public:
  CAPIBuildEngineDelegate(llb_buildengine_delegate_t delegate)
    : cAPIDelegate(delegate)
  {

  }
};

class CAPITask : public Task {
  llb_task_delegate_t cAPIDelegate;

public:
  CAPITask(llb_task_delegate_t delegate)
    : Task("C-API-Task"), cAPIDelegate(delegate)
  {
      assert(cAPIDelegate.start && "missing task start function");
      assert(cAPIDelegate.provide_value &&
             "missing task provide_value function");
      assert(cAPIDelegate.inputs_available &&
             "missing task inputs_available function");
  }

  virtual void start(BuildEngine& engine) override {
    CAPIBuildEngineDelegate* delegate =
      static_cast<CAPIBuildEngineDelegate*>(engine.getDelegate());
    cAPIDelegate.start(cAPIDelegate.context,
                       delegate->cAPIDelegate.context,
                       (llb_task_t*)this);
  }

  virtual void provideValue(BuildEngine& engine, uintptr_t inputID,
                            const ValueType& value) override {
    CAPIBuildEngineDelegate* delegate =
      static_cast<CAPIBuildEngineDelegate*>(engine.getDelegate());
    llb_data_t valueData{ value.size(), value.data() };
    cAPIDelegate.provide_value(cAPIDelegate.context,
                               delegate->cAPIDelegate.context,
                               (llb_task_t*)this,
                               inputID, &valueData);
  }

  virtual void inputsAvailable(BuildEngine& engine) override {
    CAPIBuildEngineDelegate* delegate =
      static_cast<CAPIBuildEngineDelegate*>(engine.getDelegate());
    cAPIDelegate.inputs_available(cAPIDelegate.context,
                                  delegate->cAPIDelegate.context,
                                  (llb_task_t*)this);
  }
};

};

llb_buildengine_t* llb_buildengine_create(llb_buildengine_delegate_t delegate) {
  // FIXME: Delegate is leaked, need to provide a provision for owning the
  // delegate.
  BuildEngineDelegate* engine_delegate = new CAPIBuildEngineDelegate(delegate);
  return (llb_buildengine_t*) new BuildEngine(*engine_delegate);
}

void llb_buildengine_destroy(llb_buildengine_t* engine) {
  // FIXME: Delegate is lost.
  delete (BuildEngine*)engine;
}

bool llb_buildengine_attach_db(llb_buildengine_t* engine_p,
                               const llb_data_t* path,
                               uint32_t schema_version,
                               char** error_out) {
  BuildEngine* engine = (BuildEngine*) engine_p;

  std::string error;
  std::unique_ptr<BuildDB> db(createSQLiteBuildDB(
                                  std::string((char*)path->data,
                                              path->length),
                                  schema_version,
                                  &error));
  if (!db) {
    *error_out = strdup(error.c_str());
    return false;
  }

  engine->attachDB(std::move(db));
  return true;
}

void llb_buildengine_build(llb_buildengine_t* engine_p, const llb_data_t* key,
                           llb_data_t* result_out) {
  BuildEngine* engine = (BuildEngine*) engine_p;

  auto& result = engine->build(KeyType((const char*)key->data, key->length));

  *result_out = llb_data_t{ result.size(), result.data() };
}

llb_task_t* llb_buildengine_register_task(llb_buildengine_t* engine_p,
                                          llb_task_t* task) {
  BuildEngine* engine = (BuildEngine*) engine_p;
  engine->registerTask((Task*)task);
  return task;
}

void llb_buildengine_task_needs_input(llb_buildengine_t* engine_p,
                                      llb_task_t* task,
                                      const llb_data_t* key,
                                      uintptr_t input_id) {
  BuildEngine* engine = (BuildEngine*) engine_p;
  engine->taskNeedsInput((Task*)task,
                         KeyType((const char*)key->data, key->length),
                         input_id);
}

void llb_buildengine_task_must_follow(llb_buildengine_t* engine_p,
                                      llb_task_t* task,
                                      const llb_data_t* key) {
  BuildEngine* engine = (BuildEngine*) engine_p;
  engine->taskMustFollow((Task*)task,
                         KeyType((const char*)key->data, key->length));
}

void llb_buildengine_task_discovered_dependency(llb_buildengine_t* engine_p,
                                                llb_task_t* task,
                                                const llb_data_t* key) {
  BuildEngine* engine = (BuildEngine*) engine_p;
  engine->taskDiscoveredDependency((Task*)task,
                                   KeyType((const char*)key->data,
                                           key->length));
}

void llb_buildengine_task_is_complete(llb_buildengine_t* engine_p,
                                      llb_task_t* task,
                                      const llb_data_t* value,
                                      bool force_change) {
  BuildEngine* engine = (BuildEngine*) engine_p;
  std::vector<uint8_t> result(value->length);
  memcpy(result.data(), value->data, value->length);
  engine->taskIsComplete((Task*)task, std::move(result));
}

llb_task_t* llb_task_create(llb_task_delegate_t delegate) {
  return (llb_task_t*) new CAPITask(delegate);
}
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUICoordConverter.cpp
    created:    Sun Sep 18 2005
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   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 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 "CEGUICoordConverter.h"
#include "CEGUIWindow.h"

// Start of CEGUI namespace section
namespace CEGUI
{
float CoordConverter::windowToScreenX(const Window& window, const UDim& x)
{
    return getBaseXValue(window) + x.asAbsolute(window.getPixelSize().d_width);
}

//----------------------------------------------------------------------------//

float CoordConverter::windowToScreenY(const Window& window, const UDim& y)
{
    return getBaseYValue(window) + y.asAbsolute(window.getPixelSize().d_height);
}

//----------------------------------------------------------------------------//

Vector2 CoordConverter::windowToScreen(const Window& window, const UVector2& vec)
{
    return getBaseValue(window) + vec.asAbsolute(window.getPixelSize());
}

//----------------------------------------------------------------------------//

Rect CoordConverter::windowToScreen(const Window& window, const URect& rect)
{
    Rect tmp(rect.asAbsolute(window.getPixelSize()));
    return tmp.offset(getBaseValue(window));
}

//----------------------------------------------------------------------------//

float CoordConverter::screenToWindowX(const Window& window, const UDim& x)
{
    return x.asAbsolute(
        System::getSingleton().getRenderer()->getDisplaySize().d_width) -
           getBaseXValue(window);
}

//----------------------------------------------------------------------------//

float CoordConverter::screenToWindowY(const Window& window, const UDim& y)
{
    return y.asAbsolute(
        System::getSingleton().getRenderer()->getDisplaySize().d_height) -
           getBaseYValue(window);
}

//----------------------------------------------------------------------------//

Vector2 CoordConverter::screenToWindow(const Window& window, const UVector2& vec)
{
    return vec.asAbsolute(
        System::getSingleton().getRenderer()->getDisplaySize()) -
           getBaseValue(window);
}

//----------------------------------------------------------------------------//

Rect CoordConverter::screenToWindow(const Window& window, const URect& rect)
{
    Vector2 base(getBaseValue(window));
    Rect pixel(
        rect.asAbsolute(System::getSingleton().getRenderer()->getDisplaySize()));

    // negate base position
    base.d_x = -base.d_x;
    base.d_y = -base.d_y;

    return pixel.offset(base);
}

//----------------------------------------------------------------------------//

float CoordConverter::windowToScreenX(const Window& window, const float x)
{
    return getBaseXValue(window) + x;
}

//----------------------------------------------------------------------------//

float CoordConverter::windowToScreenY(const Window& window, const float y)
{
    return getBaseYValue(window) + y;
}

//----------------------------------------------------------------------------//

Vector2 CoordConverter::windowToScreen(const Window& window, const Vector2& vec)
{
    return getBaseValue(window) + vec;
}

//----------------------------------------------------------------------------//

Rect CoordConverter::windowToScreen(const Window& window, const Rect& rect)
{
    Rect tmp(rect);
    return tmp.offset(getBaseValue(window));
}

//----------------------------------------------------------------------------//

float CoordConverter::screenToWindowX(const Window& window, const float x)
{
    return x - getBaseXValue(window);
}

//----------------------------------------------------------------------------//

float CoordConverter::screenToWindowY(const Window& window, const float y)
{
    return y - getBaseYValue(window);
}

//----------------------------------------------------------------------------//

Vector2 CoordConverter::screenToWindow(const Window& window, const Vector2& vec)
{
    return vec - getBaseValue(window);
}

//----------------------------------------------------------------------------//

Rect CoordConverter::screenToWindow(const Window& window, const Rect& rect)
{
    Vector2 base(getBaseValue(window));

    // negate base position
    base.d_x = -base.d_x;
    base.d_y = -base.d_y;

    Rect tmp(rect);
    return tmp.offset(base);
}

//----------------------------------------------------------------------------//

float CoordConverter::getBaseXValue(const Window& window)
{
    const Window* parent = window.getParent();

    const Rect parent_rect(
        parent ? window.isNonClientWindow() ? parent->getUnclippedOuterRect() :
                                              parent->getUnclippedInnerRect() :
                 Rect(Vector2(0, 0),
                      System::getSingleton().getRenderer()->getDisplaySize())
    );

    const float parent_width = parent_rect.getWidth();
    float baseX = parent_rect.d_left;

    baseX += window.getArea().d_min.d_x.asAbsolute(parent_width);

    switch(window.getHorizontalAlignment())
    {
        case HA_CENTRE:
            baseX += (parent_width - window.getPixelSize().d_width) * 0.5f;
            break;
        case HA_RIGHT:
            baseX += parent_width - window.getPixelSize().d_width;
            break;
        default:
            break;
    }

    return baseX;
}

//----------------------------------------------------------------------------//

float CoordConverter::getBaseYValue(const Window& window)
{
    const Window* parent = window.getParent();

    const Rect parent_rect(
        parent ? window.isNonClientWindow() ? parent->getUnclippedOuterRect() :
                                              parent->getUnclippedInnerRect() :
                 Rect(Vector2(0, 0),
                      System::getSingleton().getRenderer()->getDisplaySize())
    );

    const float parent_height = parent_rect.getHeight();
    float baseY = parent_rect.d_top;

    baseY += window.getArea().d_min.d_y.asAbsolute(parent_height);

    switch(window.getVerticalAlignment())
    {
        case VA_CENTRE:
            baseY += (parent_height - window.getPixelSize().d_height) * 0.5f;
            break;
        case VA_BOTTOM:
            baseY += parent_height - window.getPixelSize().d_height;
            break;
        default:
            break;
    }

    return baseY;
}

//----------------------------------------------------------------------------//

Vector2 CoordConverter::getBaseValue(const Window& window)
{
    return Vector2(getBaseXValue(window), getBaseYValue(window));
}

} // End of  CEGUI namespace section
<commit_msg>FIX: Ensure base co-ords used for window to screen conversions are pixel aligned.  This fixes issues caused by per-window geometry buffer translations (and associated clippers) not being pixel aligned and causing blurred imagery.<commit_after>/***********************************************************************
    filename:   CEGUICoordConverter.cpp
    created:    Sun Sep 18 2005
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   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 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 "CEGUICoordConverter.h"
#include "CEGUIWindow.h"

// Start of CEGUI namespace section
namespace CEGUI
{
float CoordConverter::windowToScreenX(const Window& window, const UDim& x)
{
    return getBaseXValue(window) + x.asAbsolute(window.getPixelSize().d_width);
}

//----------------------------------------------------------------------------//

float CoordConverter::windowToScreenY(const Window& window, const UDim& y)
{
    return getBaseYValue(window) + y.asAbsolute(window.getPixelSize().d_height);
}

//----------------------------------------------------------------------------//

Vector2 CoordConverter::windowToScreen(const Window& window, const UVector2& vec)
{
    return getBaseValue(window) + vec.asAbsolute(window.getPixelSize());
}

//----------------------------------------------------------------------------//

Rect CoordConverter::windowToScreen(const Window& window, const URect& rect)
{
    Rect tmp(rect.asAbsolute(window.getPixelSize()));
    return tmp.offset(getBaseValue(window));
}

//----------------------------------------------------------------------------//

float CoordConverter::screenToWindowX(const Window& window, const UDim& x)
{
    return x.asAbsolute(
        System::getSingleton().getRenderer()->getDisplaySize().d_width) -
           getBaseXValue(window);
}

//----------------------------------------------------------------------------//

float CoordConverter::screenToWindowY(const Window& window, const UDim& y)
{
    return y.asAbsolute(
        System::getSingleton().getRenderer()->getDisplaySize().d_height) -
           getBaseYValue(window);
}

//----------------------------------------------------------------------------//

Vector2 CoordConverter::screenToWindow(const Window& window, const UVector2& vec)
{
    return vec.asAbsolute(
        System::getSingleton().getRenderer()->getDisplaySize()) -
           getBaseValue(window);
}

//----------------------------------------------------------------------------//

Rect CoordConverter::screenToWindow(const Window& window, const URect& rect)
{
    Vector2 base(getBaseValue(window));
    Rect pixel(
        rect.asAbsolute(System::getSingleton().getRenderer()->getDisplaySize()));

    // negate base position
    base.d_x = -base.d_x;
    base.d_y = -base.d_y;

    return pixel.offset(base);
}

//----------------------------------------------------------------------------//

float CoordConverter::windowToScreenX(const Window& window, const float x)
{
    return getBaseXValue(window) + x;
}

//----------------------------------------------------------------------------//

float CoordConverter::windowToScreenY(const Window& window, const float y)
{
    return getBaseYValue(window) + y;
}

//----------------------------------------------------------------------------//

Vector2 CoordConverter::windowToScreen(const Window& window, const Vector2& vec)
{
    return getBaseValue(window) + vec;
}

//----------------------------------------------------------------------------//

Rect CoordConverter::windowToScreen(const Window& window, const Rect& rect)
{
    Rect tmp(rect);
    return tmp.offset(getBaseValue(window));
}

//----------------------------------------------------------------------------//

float CoordConverter::screenToWindowX(const Window& window, const float x)
{
    return x - getBaseXValue(window);
}

//----------------------------------------------------------------------------//

float CoordConverter::screenToWindowY(const Window& window, const float y)
{
    return y - getBaseYValue(window);
}

//----------------------------------------------------------------------------//

Vector2 CoordConverter::screenToWindow(const Window& window, const Vector2& vec)
{
    return vec - getBaseValue(window);
}

//----------------------------------------------------------------------------//

Rect CoordConverter::screenToWindow(const Window& window, const Rect& rect)
{
    Vector2 base(getBaseValue(window));

    // negate base position
    base.d_x = -base.d_x;
    base.d_y = -base.d_y;

    Rect tmp(rect);
    return tmp.offset(base);
}

//----------------------------------------------------------------------------//

float CoordConverter::getBaseXValue(const Window& window)
{
    const Window* parent = window.getParent();

    const Rect parent_rect(
        parent ? window.isNonClientWindow() ? parent->getUnclippedOuterRect() :
                                              parent->getUnclippedInnerRect() :
                 Rect(Vector2(0, 0),
                      System::getSingleton().getRenderer()->getDisplaySize())
    );

    const float parent_width = parent_rect.getWidth();
    float baseX = parent_rect.d_left;

    baseX += window.getArea().d_min.d_x.asAbsolute(parent_width);

    switch(window.getHorizontalAlignment())
    {
        case HA_CENTRE:
            baseX += (parent_width - window.getPixelSize().d_width) * 0.5f;
            break;
        case HA_RIGHT:
            baseX += parent_width - window.getPixelSize().d_width;
            break;
        default:
            break;
    }

    return PixelAligned(baseX);
}

//----------------------------------------------------------------------------//

float CoordConverter::getBaseYValue(const Window& window)
{
    const Window* parent = window.getParent();

    const Rect parent_rect(
        parent ? window.isNonClientWindow() ? parent->getUnclippedOuterRect() :
                                              parent->getUnclippedInnerRect() :
                 Rect(Vector2(0, 0),
                      System::getSingleton().getRenderer()->getDisplaySize())
    );

    const float parent_height = parent_rect.getHeight();
    float baseY = parent_rect.d_top;

    baseY += window.getArea().d_min.d_y.asAbsolute(parent_height);

    switch(window.getVerticalAlignment())
    {
        case VA_CENTRE:
            baseY += (parent_height - window.getPixelSize().d_height) * 0.5f;
            break;
        case VA_BOTTOM:
            baseY += parent_height - window.getPixelSize().d_height;
            break;
        default:
            break;
    }

    return PixelAligned(baseY);
}

//----------------------------------------------------------------------------//

Vector2 CoordConverter::getBaseValue(const Window& window)
{
    return Vector2(getBaseXValue(window), getBaseYValue(window));
}

} // End of  CEGUI namespace section
<|endoftext|>


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

#ifndef SVX_DBAOBJECTEX_HXX
#include "dbaobjectex.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _COMPHELPER_PROPERTSETINFO_HXX_
#include <comphelper/propertysetinfo.hxx>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif

//........................................................................
namespace svx
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::ucb;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::datatransfer;
    using namespace ::svxform;
    using namespace ::comphelper;

    //====================================================================
    //= OComponentTransferable
    //====================================================================
    //--------------------------------------------------------------------
    OComponentTransferable::OComponentTransferable(const ::rtl::OUString& _rDatasourceOrLocation
            ,const Reference< XContent>& _xContent)
    {
        m_aDescriptor.setDataSource(_rDatasourceOrLocation);
        m_aDescriptor[daComponent] <<= _xContent;
    }

    //--------------------------------------------------------------------
    sal_uInt32 OComponentTransferable::getDescriptorFormatId()
    {
        static sal_uInt32 s_nFormat = (sal_uInt32)-1;
        if ((sal_uInt32)-1 == s_nFormat)
        {
            s_nFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.ComponentDescriptorTransfer\""));
            OSL_ENSURE((sal_uInt32)-1 != s_nFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
        }
        return s_nFormat;
    }

    //--------------------------------------------------------------------
    void OComponentTransferable::AddSupportedFormats()
    {
        AddFormat(getDescriptorFormatId());
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::GetData( const DataFlavor& _rFlavor )
    {
        const sal_uInt32 nFormatId = SotExchange::GetFormat(_rFlavor);
        if ( nFormatId == getDescriptorFormatId() )
            return SetAny( makeAny( m_aDescriptor.createPropertyValueSequence() ), _rFlavor );

        return sal_False;
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::canExtractComponentDescriptor(const DataFlavorExVector& _rFlavors )
    {
        DataFlavorExVector::const_iterator aEnd = _rFlavors.end();
        for (   DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();
                aCheck != aEnd;
                ++aCheck
            )
        {
            if ( getDescriptorFormatId() == aCheck->mnSotId )
                return sal_True;
        }

        return sal_False;
    }

    //--------------------------------------------------------------------
    ODataAccessDescriptor OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData)
    {
        if ( _rData.HasFormat(getDescriptorFormatId()) )
        {
            // the object has a real descriptor object (not just the old compatible format)

            // extract the any from the transferable
            DataFlavor aFlavor;
#if OSL_DEBUG_LEVEL > 0
            sal_Bool bSuccess =
#endif
            SotExchange::GetFormatDataFlavor(getDescriptorFormatId(), aFlavor);
            OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid data format (no flavor)!");

            Any aDescriptor = _rData.GetAny(aFlavor);

            // extract the property value sequence
            Sequence< PropertyValue > aDescriptorProps;
#if OSL_DEBUG_LEVEL > 0
            bSuccess =
#endif
            aDescriptor >>= aDescriptorProps;
            OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid clipboard format!");

            // build the real descriptor
            return ODataAccessDescriptor(aDescriptorProps);
        }

        return ODataAccessDescriptor();
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData
        , ::rtl::OUString&  _rDatasourceOrLocation
        , ::com::sun::star::uno::Reference< XContent>& _xContent)
    {
        if (_rData.HasFormat(getDescriptorFormatId()))
        {
            ODataAccessDescriptor aDescriptor = extractComponentDescriptor(_rData);
            _rDatasourceOrLocation = aDescriptor.getDataSource();
            aDescriptor[daComponent]            >>= _xContent;
            return sal_True;
        }

        return sal_False;
    }
//........................................................................
}   // namespace svx
//........................................................................

<commit_msg>INTEGRATION: CWS dba201b (1.2.678); FILE MERGED 2005/09/21 17:12:04 oj 1.2.678.2: RESYNC: (1.2-1.3); FILE MERGED 2005/07/11 13:36:36 fs 1.2.678.1: merging CWS dba201 into dba201b<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dbaobjectex.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2005-09-23 11:58:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SVX_DBAOBJECTEX_HXX
#include "dbaobjectex.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _COMPHELPER_PROPERTSETINFO_HXX_
#include <comphelper/propertysetinfo.hxx>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif

//........................................................................
namespace svx
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::ucb;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::datatransfer;
    using namespace ::svxform;
    using namespace ::comphelper;

    //====================================================================
    //= OComponentTransferable
    //====================================================================
    //--------------------------------------------------------------------
    OComponentTransferable::OComponentTransferable(const ::rtl::OUString& _rDatasourceOrLocation
            ,const Reference< XContent>& _xContent)
    {
        m_aDescriptor.setDataSource(_rDatasourceOrLocation);
        m_aDescriptor[daComponent] <<= _xContent;
    }

    //--------------------------------------------------------------------
    sal_uInt32 OComponentTransferable::getDescriptorFormatId(sal_Bool _bExtractForm)
    {
        static sal_uInt32 s_nReportFormat = (sal_uInt32)-1;
        static sal_uInt32 s_nFormFormat = (sal_uInt32)-1;
        if ( _bExtractForm && (sal_uInt32)-1 == s_nFormFormat )
        {
            s_nFormFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.FormComponentDescriptorTransfer\"" ));
            OSL_ENSURE((sal_uInt32)-1 != s_nFormFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
        }
        else if ( !_bExtractForm && (sal_uInt32)-1 == s_nReportFormat)
        {
            s_nReportFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.ReportComponentDescriptorTransfer\""));
            OSL_ENSURE((sal_uInt32)-1 != s_nReportFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
        }
        return _bExtractForm ? s_nFormFormat : s_nReportFormat;
    }

    //--------------------------------------------------------------------
    void OComponentTransferable::AddSupportedFormats()
    {
        sal_Bool bForm = sal_True;
        try
        {
            Reference<XPropertySet> xProp;
            m_aDescriptor[daComponent] >>= xProp;
            if ( xProp.is() )
                xProp->getPropertyValue(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsForm"))) >>= bForm;
        }
        catch(Exception)
        {}
        AddFormat(getDescriptorFormatId(bForm));
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::GetData( const DataFlavor& _rFlavor )
    {
        const sal_uInt32 nFormatId = SotExchange::GetFormat(_rFlavor);
        if ( nFormatId == getDescriptorFormatId(sal_True) || nFormatId == getDescriptorFormatId(sal_False) )
            return SetAny( makeAny( m_aDescriptor.createPropertyValueSequence() ), _rFlavor );

        return sal_False;
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::canExtractComponentDescriptor(const DataFlavorExVector& _rFlavors,sal_Bool _bForm )
    {
        DataFlavorExVector::const_iterator aEnd = _rFlavors.end();
        for (   DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();
                aCheck != aEnd;
                ++aCheck
            )
        {
            if ( getDescriptorFormatId(_bForm) == aCheck->mnSotId )
                return sal_True;
        }

        return sal_False;
    }

    //--------------------------------------------------------------------
    ODataAccessDescriptor OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData)
    {
        sal_Bool bForm;
        if ( (bForm = _rData.HasFormat(getDescriptorFormatId(sal_True))) || _rData.HasFormat(getDescriptorFormatId(sal_False)) )
        {
            // the object has a real descriptor object (not just the old compatible format)

            // extract the any from the transferable
            DataFlavor aFlavor;
#if OSL_DEBUG_LEVEL > 0
            sal_Bool bSuccess =
#endif
            SotExchange::GetFormatDataFlavor(getDescriptorFormatId(bForm), aFlavor);
            OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid data format (no flavor)!");

            Any aDescriptor = _rData.GetAny(aFlavor);

            // extract the property value sequence
            Sequence< PropertyValue > aDescriptorProps;
#if OSL_DEBUG_LEVEL > 0
            bSuccess =
#endif
            aDescriptor >>= aDescriptorProps;
            OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid clipboard format!");

            // build the real descriptor
            return ODataAccessDescriptor(aDescriptorProps);
        }

        return ODataAccessDescriptor();
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData
        ,sal_Bool _bExtractForm
        , ::rtl::OUString&  _rDatasourceOrLocation
        , ::com::sun::star::uno::Reference< XContent>& _xContent)
    {
        if ( _rData.HasFormat( getDescriptorFormatId(_bExtractForm)) )
        {
            ODataAccessDescriptor aDescriptor = extractComponentDescriptor(_rData);
            _rDatasourceOrLocation = aDescriptor.getDataSource();
            aDescriptor[daComponent]            >>= _xContent;
            return sal_True;
        }

        return sal_False;
    }
//........................................................................
}   // namespace svx
//........................................................................

<|endoftext|>


<commit_before>/*
    Copyright (c) 2009 Stephen Kelly <steveire@gmail.com>
*/

#include "context.h"

using namespace Grantlee;

namespace Grantlee
{
class ContextPrivate
{
  ContextPrivate(Context *context, const QVariantHash &variantHash)
    : q_ptr(context), m_autoescape(false)
  {
    m_variantHashStack.append(variantHash);
  }

  QList<QVariantHash> m_variantHashStack;
  bool m_autoescape;

  Q_DECLARE_PUBLIC(Context)
  Context *q_ptr;

};

}

Context::Context(const QVariantHash &variantHash)
  : d_ptr(new ContextPrivate(this, variantHash))
{
}

Context::~Context()
{
  delete d_ptr;
}

bool Context::autoescape() const
{
  Q_D(const Context);
  return d->m_autoescape;
}

void Context::setAutoescape(bool autoescape)
{
  Q_D(Context);
  d->m_autoescape = autoescape;
}

QVariant Context::lookup(const QString &str) const
{
  Q_D(const Context);

  // return a variant from the stack.
  QListIterator<QVariantHash> i(d->m_variantHashStack);
  while (i.hasNext())
  {
    QVariantHash h = i.next();
    if (h.contains(str))
      return h[str];
  }

  return QVariant();
}

void Context::push()
{
  Q_D(Context);

  QHash<QString, QVariant> hash;
  d->m_variantHashStack.prepend(hash);
}

void Context::pop()
{
  Q_D(Context);

  d->m_variantHashStack.removeFirst();
}

void Context::insert(const QString &name, const QVariant &variant)
{
  Q_D(Context);

  d->m_variantHashStack[0].insert(name, variant);
}

QHash<QString, QVariant> Context::stackHash(int depth) const
{
  Q_D(const Context);

  return d->m_variantHashStack.value(depth);
}
<commit_msg>autoescape should default to 'on'.<commit_after>/*
    Copyright (c) 2009 Stephen Kelly <steveire@gmail.com>
*/

#include "context.h"

using namespace Grantlee;

namespace Grantlee
{
class ContextPrivate
{
  ContextPrivate(Context *context, const QVariantHash &variantHash)
    : q_ptr(context), m_autoescape(true)
  {
    m_variantHashStack.append(variantHash);
  }

  QList<QVariantHash> m_variantHashStack;
  bool m_autoescape;

  Q_DECLARE_PUBLIC(Context)
  Context *q_ptr;

};

}

Context::Context(const QVariantHash &variantHash)
  : d_ptr(new ContextPrivate(this, variantHash))
{
}

Context::~Context()
{
  delete d_ptr;
}

bool Context::autoescape() const
{
  Q_D(const Context);
  return d->m_autoescape;
}

void Context::setAutoescape(bool autoescape)
{
  Q_D(Context);
  d->m_autoescape = autoescape;
}

QVariant Context::lookup(const QString &str) const
{
  Q_D(const Context);

  // return a variant from the stack.
  QListIterator<QVariantHash> i(d->m_variantHashStack);
  while (i.hasNext())
  {
    QVariantHash h = i.next();
    if (h.contains(str))
      return h[str];
  }

  return QVariant();
}

void Context::push()
{
  Q_D(Context);

  QHash<QString, QVariant> hash;
  d->m_variantHashStack.prepend(hash);
}

void Context::pop()
{
  Q_D(Context);

  d->m_variantHashStack.removeFirst();
}

void Context::insert(const QString &name, const QVariant &variant)
{
  Q_D(Context);

  d->m_variantHashStack[0].insert(name, variant);
}

QHash<QString, QVariant> Context::stackHash(int depth) const
{
  Q_D(const Context);

  return d->m_variantHashStack.value(depth);
}
<|endoftext|>