<commit_before>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef GCN_IMAGE_HPP
#define GCN_IMAGE_HPP

#include <string>

#include "guichan/platform.hpp"

namespace gcn
{
    class Color;
    class ImageLoader;

    /**
     * Holds an image. To be able to use this class you must first set an
     * ImageLoader in Image by calling
     * @code Image::setImageLoader(myImageLoader) @endcode
     * The function is static. If this is not done, the constructor taking a
     * filename will throw an exception. The ImageLoader you use must be
     * compatible with the Graphics object you use.
     *
     * EXAMPLE: If you use SDLGraphics you should use SDLImageLoader.
     *          Otherwise your program will crash in a most bizarre way.
     */
    class GCN_CORE_DECLSPEC Image
    {
    public:

        /**
         * Constructor.
         */
        Image();

        /**
         * Destructor.
         */
        virtual ~Image();

        /**
         * Loads an image by calling the Image class' ImageLoader. With most image loaders
         * you can assume a newly instantiated image is return which must be deleted in
         * order to avoid a memory leak.
         *
         * NOTE: The functions getPixel and putPixel are only guaranteed to work
         *       before an image has been converted to display format.
         *
         * @param filename the file to load.
         * @param convertToDisplayFormat true if the image should be converted
         *                               to display, false otherwise.
         */
        static Image* load(const std::string& filename, bool convertToDisplayFormat = true);

        /**
         * Gets the ImageLoader used for loading Images.
         *
         * @return the ImageLoader used for loading Images.
         * @see SDLImageLoader, AllegroImageLoader
         */
        static ImageLoader* getImageLoader();

        /**
         * Sets the ImageLoader to be used for loading images.
         *
         * IMPORTANT: The ImageLoader is static and MUST be set before loading
         *            images!
         *
         * @param imageLoader the ImageLoader to be used for loading images.
         * @see SDLImageLoader, AllegroImageLoader
         */
        static void setImageLoader(ImageLoader* imageLoader);

        /**
         * Frees an image.
         */
        virtual void free() = 0;

        /**
         * Gets the width of the Image.
         *
         * @return the image width
         */
        virtual int getWidth() const = 0;

        /**
         * Gets the height of the Image.
         *
         * @return the image height
         */
        virtual int getHeight() const = 0;

        /**
         * Gets the color of a pixel at coordinate (x, y) in the image.
         *
         * IMPORTANT: Only guaranteed to work before the image has been
         *            converted to display format.
         *
         * @param x the x coordinate.
         * @param y the y coordinate.
         * @return the color of the pixel.
         */
        virtual Color getPixel(int x, int y) = 0;

        /**
         * Puts a pixel with a certain color at coordinate (x, y).
         *
         * @param x the x coordinate.
         * @param y the y coordinate.
         * @param color the color of the pixel to put.
         */
        virtual void putPixel(int x, int y, const Color& color) = 0;

        /**
         * Converts the image, if possible, to display format.
         *
         * IMPORTANT: Only guaranteed to work before the image has been
         *            converted to display format.
         */
        virtual void convertToDisplayFormat() = 0;

    protected:
        static ImageLoader* mImageLoader;
    };
}

#endif // end GCN_IMAGE_HPP
<commit_msg>Documentation has been improved.<commit_after>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef GCN_IMAGE_HPP
#define GCN_IMAGE_HPP

#include <string>

#include "guichan/platform.hpp"

namespace gcn
{
    class Color;
    class ImageLoader;

    /**
     * Holds an image. To be able to use this class you must first set an
     * ImageLoader in Image by calling
     * @code Image::setImageLoader(myImageLoader) @endcode
     * The function is static. If this is not done, the constructor taking a
     * filename will throw an exception. The ImageLoader you use must be
     * compatible with the Graphics object you use.
     *
     * EXAMPLE: If you use SDLGraphics you should use SDLImageLoader.
     *          Otherwise your program will crash in a most bizarre way.
     */
    class GCN_CORE_DECLSPEC Image
    {
    public:

        /**
         * Constructor.
         */
        Image();

        /**
         * Destructor.
         */
        virtual ~Image();

        /**
         * Loads an image by calling the Image class' ImageLoader. All image loaders implemented
         * in Guichan returns a newly instantiated image which must be deleted in
         * order to avoid a memory leak.
         *
         * NOTE: The functions getPixel and putPixel are only guaranteed to work
         *       before an image has been converted to display format.
         *
         * @param filename the file to load.
         * @param convertToDisplayFormat true if the image should be converted
         *                               to display, false otherwise.
         */
        static Image* load(const std::string& filename, bool convertToDisplayFormat = true);

        /**
         * Gets the ImageLoader used for loading Images.
         *
         * @return the ImageLoader used for loading Images.
         * @see SDLImageLoader, AllegroImageLoader
         */
        static ImageLoader* getImageLoader();

        /**
         * Sets the ImageLoader to be used for loading images.
         *
         * IMPORTANT: The ImageLoader is static and MUST be set before loading
         *            images!
         *
         * @param imageLoader the ImageLoader to be used for loading images.
         * @see SDLImageLoader, AllegroImageLoader
         */
        static void setImageLoader(ImageLoader* imageLoader);

        /**
         * Frees an image.
         */
        virtual void free() = 0;

        /**
         * Gets the width of the Image.
         *
         * @return the image width
         */
        virtual int getWidth() const = 0;

        /**
         * Gets the height of the Image.
         *
         * @return the image height
         */
        virtual int getHeight() const = 0;

        /**
         * Gets the color of a pixel at coordinate (x, y) in the image.
         *
         * IMPORTANT: Only guaranteed to work before the image has been
         *            converted to display format.
         *
         * @param x the x coordinate.
         * @param y the y coordinate.
         * @return the color of the pixel.
         */
        virtual Color getPixel(int x, int y) = 0;

        /**
         * Puts a pixel with a certain color at coordinate (x, y).
         *
         * @param x the x coordinate.
         * @param y the y coordinate.
         * @param color the color of the pixel to put.
         */
        virtual void putPixel(int x, int y, const Color& color) = 0;

        /**
         * Converts the image, if possible, to display format.
         *
         * IMPORTANT: Only guaranteed to work before the image has been
         *            converted to display format.
         */
        virtual void convertToDisplayFormat() = 0;

    protected:
        static ImageLoader* mImageLoader;
    };
}

#endif // end GCN_IMAGE_HPP
<|endoftext|>


<commit_before>#ifndef LIBICS3_ICS3_EEPPARAM_H_
#define LIBICS3_ICS3_EEPPARAM_H_

#include"ics3/check_invalid.hpp"
#include"ics3/baudrate.hpp"

#include<array>

namespace ics {
  class EepParam {
  public:
    using type = uint16_t;
    using size_type = std::size_t;
    using TargetContainer = std::array<uint8_t, 64>;
    using InvalidChecker = type (&)(type, type, type);
    enum Flag : type {
      REVERSE =   0x01,
      FREE =      0x02,
      PWMINH =    0x08,
      ROLL_MODE = 0x10,
      SLAVE =     0x80
    };
    static constexpr int byteSize {4};
    static constexpr type mask {0xF};

    static constexpr EepParam stretch(type = 60);
    static constexpr EepParam speed(type = 127);
    static constexpr EepParam punch(type = 1);
    static constexpr EepParam deadBand(type = 2);
    static constexpr EepParam dumping(type = 40);
    static constexpr EepParam selfTimer(type = 250);
    static constexpr EepParam flag(type = 0x8C);
    static constexpr EepParam pulseMax(type = 11500);
    static constexpr EepParam pulseMin(type = 3500);
    static constexpr EepParam baudrate(type = 10);
    static constexpr EepParam temperature(type = 80);
    static constexpr EepParam current(type = 63);
    static constexpr EepParam response(type = 0);
    static constexpr EepParam userOffset(type = 0);
    static constexpr EepParam id(type = 0);
    static constexpr EepParam strech1(type = 60);
    static constexpr EepParam strech2(type = 60);
    static constexpr EepParam strech3(type = 60);
    static constexpr EepParam newEepParam(const EepParam&, type);

    constexpr type get() const noexcept;
    constexpr operator type() const noexcept;
    void set(type);
    EepParam& operator=(type);
    void read(const TargetContainer&);
    void write(TargetContainer&) const noexcept;
  private:
    constexpr EepParam( // non explicit, user cannot touch this
        size_type,
        size_type,
        type,
        type,
        InvalidChecker,
        type);
    static constexpr type checkInvalidRange(type, type, type);
    static constexpr type checkInvalidEvenRange(type, type, type);
    static constexpr type checkInvalidFlag(type, type, type);
    static constexpr type checkInvalidBaudrate(type, type, type);
    static constexpr type checkInvalidOffset(type, type, type);

    const size_type offset;
    const size_type length;
    const type min;
    const type max;
    InvalidChecker setFunc;
    type data;
  };

  constexpr EepParam EepParam::stretch(type data) {
    return {2, 2, 2, 254, EepParam::checkInvalidEvenRange, data};
  }

  constexpr EepParam EepParam::speed(type data) {
    return {4, 2, 1, 127, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::punch(type data) {
    return {6, 2, 0, 10, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::deadBand(type data) {
    return {8, 2, 0, 5, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::dumping(type data) {
    return {10, 2, 1, 255, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::selfTimer(type data) {
    return {12, 2, 10, 255, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::flag(type data) {
    return {14, 2, 0, 255, EepParam::checkInvalidFlag, data};
  }

  constexpr EepParam EepParam::pulseMax(type data) {
    return {16, 4, 3500, 11500, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::pulseMin(type data) {
    return {20, 4, 3500, 11500, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::baudrate(type data) {
    return {26, 2, 0, 10, EepParam::checkInvalidBaudrate, data};
  }

  constexpr EepParam EepParam::temperature(type data) {
    return {28, 2, 1, 127, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::current(type data) {
    return {30, 2, 1, 63, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::response(type data) {
    return {50, 2, 1, 5, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::userOffset(type data) {
    return {52, 2, 0x81, 127, EepParam::checkInvalidOffset, data}; // 0x81 is -127 on uint8_t type
  }

  constexpr EepParam EepParam::id(type data) {
    return {56, 2, 0, 31, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::strech1(type data) {
    return {58, 2, 2, 254, EepParam::checkInvalidEvenRange, data};
  }

  constexpr EepParam EepParam::strech2(type data) {
    return {60, 2, 2, 254, EepParam::checkInvalidEvenRange, data};
  }

  constexpr EepParam EepParam::strech3(type data) {
    return {62, 2, 2, 254, EepParam::checkInvalidEvenRange, data};
  }

  constexpr EepParam EepParam::newEepParam(const EepParam& paramType, type data) {
    return {paramType.offset, paramType.length, paramType.min, paramType.max, paramType.setFunc, data};
  }

  constexpr EepParam::type EepParam::get() const noexcept {
    return data;
  }

  constexpr EepParam::operator type() const noexcept {
    return get();
  }

  inline void EepParam::set(type input) {
    data = setFunc(input, min, max); // throw std::invalid_argument, std::out_of_range
  }

  inline EepParam& EepParam::operator=(type input) {
    set(input);
    return *this;
  }

  inline void EepParam::read(const TargetContainer& src) {
    type result {0};
    const size_type loopend = offset + length;
    for (size_type i {offset}; i < loopend; ++i) {
      result <<= byteSize;
      result |= src[i] & mask;
    }
    set(result); // throw std::invalid_argument, std::out_of_range
  }

  inline void EepParam::write(TargetContainer& dest) const noexcept {
    type nowData {data};
    for (size_type i {offset + length - 1}; i >= offset; --i) {
      dest[i] = nowData & mask;
      nowData >>= byteSize;
    }
  }

  constexpr EepParam::EepParam(
      size_type offset,
      size_type length,
      type min,
      type max,
      InvalidChecker setFunc,
      type data)
  : offset(offset),
    length(length),
    min(min),
    max(max),
    setFunc(setFunc),
    data(setFunc(data, min, max)) // throw std::invalid_argument, std::out_of_range
  {}

  constexpr EepParam::type EepParam::checkInvalidRange(type input, type min, type max) {
    return ics::checkInvalidRange(input, min, max);
  }

  constexpr EepParam::type EepParam::checkInvalidEvenRange(type input, type min, type max) {
    return input % 2 ?
           throw std::out_of_range {"Must even value"} :
           checkInvalidRange(input, min, max); // throw std::out_of_range
  }

  constexpr EepParam::type EepParam::checkInvalidFlag(type input, type, type) {
    return !(input & 0x04) ? throw std::invalid_argument {"Eepparam(flag): Must up bits 0x04"} :
           ~(input | ~0x60) ? throw std::invalid_argument {"Eepparam(flag): Must down bits 0x60"} :
           input;
  }

  constexpr EepParam::type EepParam::checkInvalidBaudrate(type input, type, type) {
    return input == Baudrate::RATE115200().get() ? input :
           //input == Baudrate::RATE625000().get() ? input :
           //input == Baudrate::RATE1250000().get() ? input :
           throw std::invalid_argument {"baudrate not exist"};
  }

  constexpr EepParam::type EepParam::checkInvalidOffset(type input, type min, type max) {
    return input < max ? input : // this min < 0; min value is 0
           min < input ? input : // this min < 0; input must is bigger than min.
           throw std::out_of_range {"Eeprom(offset): range over"}; // min < input < max is failed
  }
}

#endif // LIBICS3_ICS3_EEPPARAM_H_
<commit_msg>Update alias type to correct type<commit_after>#ifndef LIBICS3_ICS3_EEPPARAM_H_
#define LIBICS3_ICS3_EEPPARAM_H_

#include"ics3/check_invalid.hpp"
#include"ics3/baudrate.hpp"

#include<array>

namespace ics {
  class EepParam {
  public:
    using type = uint16_t;
    using TargetContainer = std::array<uint8_t, 64>;
    using size_type = TargetContainer::size_type;
    using InvalidChecker = type (&)(type, type, type);
    enum Flag : type {
      REVERSE =   0x01,
      FREE =      0x02,
      PWMINH =    0x08,
      ROLL_MODE = 0x10,
      SLAVE =     0x80
    };
    static constexpr int byteSize {4};
    static constexpr type mask {0xF};

    static constexpr EepParam stretch(type = 60);
    static constexpr EepParam speed(type = 127);
    static constexpr EepParam punch(type = 1);
    static constexpr EepParam deadBand(type = 2);
    static constexpr EepParam dumping(type = 40);
    static constexpr EepParam selfTimer(type = 250);
    static constexpr EepParam flag(type = 0x8C);
    static constexpr EepParam pulseMax(type = 11500);
    static constexpr EepParam pulseMin(type = 3500);
    static constexpr EepParam baudrate(type = 10);
    static constexpr EepParam temperature(type = 80);
    static constexpr EepParam current(type = 63);
    static constexpr EepParam response(type = 0);
    static constexpr EepParam userOffset(type = 0);
    static constexpr EepParam id(type = 0);
    static constexpr EepParam strech1(type = 60);
    static constexpr EepParam strech2(type = 60);
    static constexpr EepParam strech3(type = 60);
    static constexpr EepParam newEepParam(const EepParam&, type);

    constexpr type get() const noexcept;
    constexpr operator type() const noexcept;
    void set(type);
    EepParam& operator=(type);
    void read(const TargetContainer&);
    void write(TargetContainer&) const noexcept;
  private:
    constexpr EepParam( // non explicit, user cannot touch this
        size_type,
        size_type,
        type,
        type,
        InvalidChecker,
        type);
    static constexpr type checkInvalidRange(type, type, type);
    static constexpr type checkInvalidEvenRange(type, type, type);
    static constexpr type checkInvalidFlag(type, type, type);
    static constexpr type checkInvalidBaudrate(type, type, type);
    static constexpr type checkInvalidOffset(type, type, type);

    const size_type offset;
    const size_type length;
    const type min;
    const type max;
    InvalidChecker setFunc;
    type data;
  };

  constexpr EepParam EepParam::stretch(type data) {
    return {2, 2, 2, 254, EepParam::checkInvalidEvenRange, data};
  }

  constexpr EepParam EepParam::speed(type data) {
    return {4, 2, 1, 127, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::punch(type data) {
    return {6, 2, 0, 10, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::deadBand(type data) {
    return {8, 2, 0, 5, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::dumping(type data) {
    return {10, 2, 1, 255, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::selfTimer(type data) {
    return {12, 2, 10, 255, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::flag(type data) {
    return {14, 2, 0, 255, EepParam::checkInvalidFlag, data};
  }

  constexpr EepParam EepParam::pulseMax(type data) {
    return {16, 4, 3500, 11500, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::pulseMin(type data) {
    return {20, 4, 3500, 11500, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::baudrate(type data) {
    return {26, 2, 0, 10, EepParam::checkInvalidBaudrate, data};
  }

  constexpr EepParam EepParam::temperature(type data) {
    return {28, 2, 1, 127, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::current(type data) {
    return {30, 2, 1, 63, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::response(type data) {
    return {50, 2, 1, 5, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::userOffset(type data) {
    return {52, 2, 0x81, 127, EepParam::checkInvalidOffset, data}; // 0x81 is -127 on uint8_t type
  }

  constexpr EepParam EepParam::id(type data) {
    return {56, 2, 0, 31, EepParam::checkInvalidRange, data};
  }

  constexpr EepParam EepParam::strech1(type data) {
    return {58, 2, 2, 254, EepParam::checkInvalidEvenRange, data};
  }

  constexpr EepParam EepParam::strech2(type data) {
    return {60, 2, 2, 254, EepParam::checkInvalidEvenRange, data};
  }

  constexpr EepParam EepParam::strech3(type data) {
    return {62, 2, 2, 254, EepParam::checkInvalidEvenRange, data};
  }

  constexpr EepParam EepParam::newEepParam(const EepParam& paramType, type data) {
    return {paramType.offset, paramType.length, paramType.min, paramType.max, paramType.setFunc, data};
  }

  constexpr EepParam::type EepParam::get() const noexcept {
    return data;
  }

  constexpr EepParam::operator type() const noexcept {
    return get();
  }

  inline void EepParam::set(type input) {
    data = setFunc(input, min, max); // throw std::invalid_argument, std::out_of_range
  }

  inline EepParam& EepParam::operator=(type input) {
    set(input);
    return *this;
  }

  inline void EepParam::read(const TargetContainer& src) {
    type result {0};
    const size_type loopend = offset + length;
    for (size_type i {offset}; i < loopend; ++i) {
      result <<= byteSize;
      result |= src[i] & mask;
    }
    set(result); // throw std::invalid_argument, std::out_of_range
  }

  inline void EepParam::write(TargetContainer& dest) const noexcept {
    type nowData {data};
    for (size_type i {offset + length - 1}; i >= offset; --i) {
      dest[i] = nowData & mask;
      nowData >>= byteSize;
    }
  }

  constexpr EepParam::EepParam(
      size_type offset,
      size_type length,
      type min,
      type max,
      InvalidChecker setFunc,
      type data)
  : offset(offset),
    length(length),
    min(min),
    max(max),
    setFunc(setFunc),
    data(setFunc(data, min, max)) // throw std::invalid_argument, std::out_of_range
  {}

  constexpr EepParam::type EepParam::checkInvalidRange(type input, type min, type max) {
    return ics::checkInvalidRange(input, min, max);
  }

  constexpr EepParam::type EepParam::checkInvalidEvenRange(type input, type min, type max) {
    return input % 2 ?
           throw std::out_of_range {"Must even value"} :
           checkInvalidRange(input, min, max); // throw std::out_of_range
  }

  constexpr EepParam::type EepParam::checkInvalidFlag(type input, type, type) {
    return !(input & 0x04) ? throw std::invalid_argument {"Eepparam(flag): Must up bits 0x04"} :
           ~(input | ~0x60) ? throw std::invalid_argument {"Eepparam(flag): Must down bits 0x60"} :
           input;
  }

  constexpr EepParam::type EepParam::checkInvalidBaudrate(type input, type, type) {
    return input == Baudrate::RATE115200().get() ? input :
           //input == Baudrate::RATE625000().get() ? input :
           //input == Baudrate::RATE1250000().get() ? input :
           throw std::invalid_argument {"baudrate not exist"};
  }

  constexpr EepParam::type EepParam::checkInvalidOffset(type input, type min, type max) {
    return input < max ? input : // this min < 0; min value is 0
           min < input ? input : // this min < 0; input must is bigger than min.
           throw std::out_of_range {"Eeprom(offset): range over"}; // min < input < max is failed
  }
}

#endif // LIBICS3_ICS3_EEPPARAM_H_
<|endoftext|>


<commit_before>// Copyright (c) 2013-2017 mogemimi. Distributed under the MIT license.

#include "Pomdog/Graphics/GraphicsCommandList.hpp"
#include "../RenderSystem/NativeGraphicsDevice.hpp"
#include "../RenderSystem/NativeGraphicsCommandList.hpp"
#include "Pomdog/Math/Color.hpp"
#include "Pomdog/Math/Rectangle.hpp"
#include "Pomdog/Graphics/ConstantBuffer.hpp"
#include "Pomdog/Graphics/GraphicsDevice.hpp"
#include "Pomdog/Graphics/PipelineState.hpp"
#include "Pomdog/Graphics/RenderPass.hpp"
#include "Pomdog/Graphics/SamplerState.hpp"
#include "Pomdog/Graphics/VertexBufferBinding.hpp"
#include "Pomdog/Graphics/Viewport.hpp"
#include "Pomdog/Utility/Assert.hpp"

namespace Pomdog {

GraphicsCommandList::GraphicsCommandList(GraphicsDevice & graphicsDevice)
{
    auto nativeDevice = graphicsDevice.GetNativeGraphicsDevice();
    POMDOG_ASSERT(nativeDevice != nullptr);

    nativeCommandList = nativeDevice->CreateGraphicsCommandList();
}

GraphicsCommandList::GraphicsCommandList(const std::shared_ptr<GraphicsDevice>& graphicsDevice)
    : GraphicsCommandList(*graphicsDevice)
{}

GraphicsCommandList::~GraphicsCommandList() = default;

void GraphicsCommandList::Close()
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->Close();
}

void GraphicsCommandList::Reset()
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->Reset();
}

std::size_t GraphicsCommandList::GetCount() const noexcept
{
    POMDOG_ASSERT(nativeCommandList);
    return nativeCommandList->GetCount();
}

void GraphicsCommandList::Draw(
    std::size_t vertexCount,
    std::size_t startVertexLocation)
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->Draw(vertexCount, startVertexLocation);
}

void GraphicsCommandList::DrawIndexed(
    const std::shared_ptr<IndexBuffer>& indexBuffer,
    std::size_t indexCount,
    std::size_t startIndexLocation)
{
    POMDOG_ASSERT(indexBuffer);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetIndexBuffer(indexBuffer);
    nativeCommandList->DrawIndexed(indexCount, startIndexLocation);
}

void GraphicsCommandList::DrawInstanced(
    std::size_t vertexCountPerInstance,
    std::size_t instanceCount,
    std::size_t startVertexLocation,
    std::size_t startInstanceLocation)
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->DrawInstanced(
        vertexCountPerInstance,
        instanceCount,
        startVertexLocation,
        startInstanceLocation);
}

void GraphicsCommandList::DrawIndexedInstanced(
    const std::shared_ptr<IndexBuffer>& indexBuffer,
    std::size_t indexCountPerInstance,
    std::size_t instanceCount,
    std::size_t startIndexLocation,
    std::size_t startInstanceLocation)
{
    POMDOG_ASSERT(indexBuffer);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetIndexBuffer(indexBuffer);
    nativeCommandList->DrawIndexedInstanced(
        indexCountPerInstance,
        instanceCount,
        startIndexLocation,
        startInstanceLocation);
}

void GraphicsCommandList::SetRenderPass(RenderPass && renderPass)
{
    POMDOG_ASSERT(nativeCommandList);

#if defined(DEBUG) && !defined(NDEBUG)
    if (renderPass.Viewport) {
        POMDOG_ASSERT(renderPass.Viewport->Width > 0);
        POMDOG_ASSERT(renderPass.Viewport->Height > 0);
    }
    if (renderPass.ScissorRect) {
        POMDOG_ASSERT(renderPass.Viewport->Width > 0);
        POMDOG_ASSERT(renderPass.Viewport->Height > 0);
    }
#endif

    nativeCommandList->SetRenderPass(std::move(renderPass));
}

void GraphicsCommandList::SetPrimitiveTopology(PrimitiveTopology primitiveTopology)
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetPrimitiveTopology(primitiveTopology);
}

void GraphicsCommandList::SetBlendFactor(const Color& blendFactor)
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetBlendFactor(blendFactor);
}

void GraphicsCommandList::SetVertexBuffer(const std::shared_ptr<VertexBuffer>& vertexBuffer)
{
    POMDOG_ASSERT(vertexBuffer);
    POMDOG_ASSERT(nativeCommandList);

    nativeCommandList->SetVertexBuffers({
        VertexBufferBinding{vertexBuffer, 0}});
}

void GraphicsCommandList::SetVertexBuffer(const std::shared_ptr<VertexBuffer>& vertexBuffer, std::size_t offset)
{
    POMDOG_ASSERT(vertexBuffer);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetVertexBuffers({
        VertexBufferBinding{vertexBuffer, offset}});
}

void GraphicsCommandList::SetVertexBuffers(const std::vector<VertexBufferBinding>& vertexBuffers)
{
    POMDOG_ASSERT(!vertexBuffers.empty());
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetVertexBuffers(vertexBuffers);
}

void GraphicsCommandList::SetVertexBuffers(std::vector<VertexBufferBinding> && vertexBuffers)
{
    POMDOG_ASSERT(!vertexBuffers.empty());
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetVertexBuffers(std::move(vertexBuffers));
}

void GraphicsCommandList::SetPipelineState(const std::shared_ptr<PipelineState>& pipelineState)
{
    POMDOG_ASSERT(pipelineState);
    POMDOG_ASSERT(nativeCommandList);

    using Detail::NativePipelineState;
    std::shared_ptr<NativePipelineState> nativePipelineState(
        pipelineState, pipelineState->GetNativePipelineState());

    nativeCommandList->SetPipelineState(nativePipelineState);
}

void GraphicsCommandList::SetConstantBuffer(int index, const std::shared_ptr<ConstantBuffer>& constantBuffer)
{
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(constantBuffer);
    POMDOG_ASSERT(nativeCommandList);

    std::shared_ptr<Detail::NativeBuffer> nativeConstantBuffer(
        constantBuffer, constantBuffer->GetNativeConstantBuffer());

    nativeCommandList->SetConstantBuffer(index, nativeConstantBuffer);
}

void GraphicsCommandList::SetTexture(int index)
{
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetTexture(index);
}

void GraphicsCommandList::SetTexture(int index, const std::shared_ptr<Texture2D>& texture)
{
    POMDOG_ASSERT(texture);
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetTexture(index, texture);
}

void GraphicsCommandList::SetTexture(int index, const std::shared_ptr<RenderTarget2D>& texture)
{
    POMDOG_ASSERT(texture);
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetTexture(index, texture);
}

void GraphicsCommandList::SetSamplerState(int index, const std::shared_ptr<SamplerState>& samplerState)
{
    POMDOG_ASSERT(samplerState);
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(samplerState->GetNativeSamplerState());
    POMDOG_ASSERT(nativeCommandList);

    std::shared_ptr<Detail::NativeSamplerState> nativeSamplerState(
        samplerState, samplerState->GetNativeSamplerState());

    nativeCommandList->SetSampler(index, std::move(nativeSamplerState));
}

Detail::NativeGraphicsCommandList* GraphicsCommandList::GetNativeGraphicsCommandList()
{
    POMDOG_ASSERT(nativeCommandList);
    return nativeCommandList.get();
}

} // namespace Pomdog
<commit_msg>Use references and fix a typo: Viewport -> ScissorRect<commit_after>// Copyright (c) 2013-2017 mogemimi. Distributed under the MIT license.

#include "Pomdog/Graphics/GraphicsCommandList.hpp"
#include "../RenderSystem/NativeGraphicsDevice.hpp"
#include "../RenderSystem/NativeGraphicsCommandList.hpp"
#include "Pomdog/Math/Color.hpp"
#include "Pomdog/Math/Rectangle.hpp"
#include "Pomdog/Graphics/ConstantBuffer.hpp"
#include "Pomdog/Graphics/GraphicsDevice.hpp"
#include "Pomdog/Graphics/PipelineState.hpp"
#include "Pomdog/Graphics/RenderPass.hpp"
#include "Pomdog/Graphics/SamplerState.hpp"
#include "Pomdog/Graphics/VertexBufferBinding.hpp"
#include "Pomdog/Graphics/Viewport.hpp"
#include "Pomdog/Utility/Assert.hpp"

namespace Pomdog {

GraphicsCommandList::GraphicsCommandList(GraphicsDevice & graphicsDevice)
{
    auto nativeDevice = graphicsDevice.GetNativeGraphicsDevice();
    POMDOG_ASSERT(nativeDevice != nullptr);

    nativeCommandList = nativeDevice->CreateGraphicsCommandList();
}

GraphicsCommandList::GraphicsCommandList(const std::shared_ptr<GraphicsDevice>& graphicsDevice)
    : GraphicsCommandList(*graphicsDevice)
{}

GraphicsCommandList::~GraphicsCommandList() = default;

void GraphicsCommandList::Close()
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->Close();
}

void GraphicsCommandList::Reset()
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->Reset();
}

std::size_t GraphicsCommandList::GetCount() const noexcept
{
    POMDOG_ASSERT(nativeCommandList);
    return nativeCommandList->GetCount();
}

void GraphicsCommandList::Draw(
    std::size_t vertexCount,
    std::size_t startVertexLocation)
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->Draw(vertexCount, startVertexLocation);
}

void GraphicsCommandList::DrawIndexed(
    const std::shared_ptr<IndexBuffer>& indexBuffer,
    std::size_t indexCount,
    std::size_t startIndexLocation)
{
    POMDOG_ASSERT(indexBuffer);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetIndexBuffer(indexBuffer);
    nativeCommandList->DrawIndexed(indexCount, startIndexLocation);
}

void GraphicsCommandList::DrawInstanced(
    std::size_t vertexCountPerInstance,
    std::size_t instanceCount,
    std::size_t startVertexLocation,
    std::size_t startInstanceLocation)
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->DrawInstanced(
        vertexCountPerInstance,
        instanceCount,
        startVertexLocation,
        startInstanceLocation);
}

void GraphicsCommandList::DrawIndexedInstanced(
    const std::shared_ptr<IndexBuffer>& indexBuffer,
    std::size_t indexCountPerInstance,
    std::size_t instanceCount,
    std::size_t startIndexLocation,
    std::size_t startInstanceLocation)
{
    POMDOG_ASSERT(indexBuffer);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetIndexBuffer(indexBuffer);
    nativeCommandList->DrawIndexedInstanced(
        indexCountPerInstance,
        instanceCount,
        startIndexLocation,
        startInstanceLocation);
}

void GraphicsCommandList::SetRenderPass(RenderPass && renderPass)
{
    POMDOG_ASSERT(nativeCommandList);

#if defined(DEBUG) && !defined(NDEBUG)
    if (renderPass.Viewport) {
        const auto& viewport = *renderPass.Viewport;
        POMDOG_ASSERT(viewport.Width > 0);
        POMDOG_ASSERT(viewport.Height > 0);
    }
    if (renderPass.ScissorRect) {
        const auto& scissorRect = *renderPass.ScissorRect;
        POMDOG_ASSERT(scissorRect.Width > 0);
        POMDOG_ASSERT(scissorRect.Height > 0);
    }
#endif

    nativeCommandList->SetRenderPass(std::move(renderPass));
}

void GraphicsCommandList::SetPrimitiveTopology(PrimitiveTopology primitiveTopology)
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetPrimitiveTopology(primitiveTopology);
}

void GraphicsCommandList::SetBlendFactor(const Color& blendFactor)
{
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetBlendFactor(blendFactor);
}

void GraphicsCommandList::SetVertexBuffer(const std::shared_ptr<VertexBuffer>& vertexBuffer)
{
    POMDOG_ASSERT(vertexBuffer);
    POMDOG_ASSERT(nativeCommandList);

    nativeCommandList->SetVertexBuffers({
        VertexBufferBinding{vertexBuffer, 0}});
}

void GraphicsCommandList::SetVertexBuffer(const std::shared_ptr<VertexBuffer>& vertexBuffer, std::size_t offset)
{
    POMDOG_ASSERT(vertexBuffer);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetVertexBuffers({
        VertexBufferBinding{vertexBuffer, offset}});
}

void GraphicsCommandList::SetVertexBuffers(const std::vector<VertexBufferBinding>& vertexBuffers)
{
    POMDOG_ASSERT(!vertexBuffers.empty());
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetVertexBuffers(vertexBuffers);
}

void GraphicsCommandList::SetVertexBuffers(std::vector<VertexBufferBinding> && vertexBuffers)
{
    POMDOG_ASSERT(!vertexBuffers.empty());
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetVertexBuffers(std::move(vertexBuffers));
}

void GraphicsCommandList::SetPipelineState(const std::shared_ptr<PipelineState>& pipelineState)
{
    POMDOG_ASSERT(pipelineState);
    POMDOG_ASSERT(nativeCommandList);

    using Detail::NativePipelineState;
    std::shared_ptr<NativePipelineState> nativePipelineState(
        pipelineState, pipelineState->GetNativePipelineState());

    nativeCommandList->SetPipelineState(nativePipelineState);
}

void GraphicsCommandList::SetConstantBuffer(int index, const std::shared_ptr<ConstantBuffer>& constantBuffer)
{
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(constantBuffer);
    POMDOG_ASSERT(nativeCommandList);

    std::shared_ptr<Detail::NativeBuffer> nativeConstantBuffer(
        constantBuffer, constantBuffer->GetNativeConstantBuffer());

    nativeCommandList->SetConstantBuffer(index, nativeConstantBuffer);
}

void GraphicsCommandList::SetTexture(int index)
{
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetTexture(index);
}

void GraphicsCommandList::SetTexture(int index, const std::shared_ptr<Texture2D>& texture)
{
    POMDOG_ASSERT(texture);
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetTexture(index, texture);
}

void GraphicsCommandList::SetTexture(int index, const std::shared_ptr<RenderTarget2D>& texture)
{
    POMDOG_ASSERT(texture);
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(nativeCommandList);
    nativeCommandList->SetTexture(index, texture);
}

void GraphicsCommandList::SetSamplerState(int index, const std::shared_ptr<SamplerState>& samplerState)
{
    POMDOG_ASSERT(samplerState);
    POMDOG_ASSERT(index >= 0);
    POMDOG_ASSERT(samplerState->GetNativeSamplerState());
    POMDOG_ASSERT(nativeCommandList);

    std::shared_ptr<Detail::NativeSamplerState> nativeSamplerState(
        samplerState, samplerState->GetNativeSamplerState());

    nativeCommandList->SetSampler(index, std::move(nativeSamplerState));
}

Detail::NativeGraphicsCommandList* GraphicsCommandList::GetNativeGraphicsCommandList()
{
    POMDOG_ASSERT(nativeCommandList);
    return nativeCommandList.get();
}

} // namespace Pomdog
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2012, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreGL/ToGLBufferConverter.h"

#include "IECoreGL/Buffer.h"

#include "IECore/Data.h"
#include "IECore/DespatchTypedData.h"

using namespace IECore;
using namespace IECoreGL;

IE_CORE_DEFINERUNTIMETYPED( ToGLBufferConverter );

ToGLConverter::ConverterDescription<ToGLBufferConverter> ToGLBufferConverter::g_description;

namespace IECoreGL
{
namespace Detail
{

/// \todo Would this be useful in DespatchTypedData.h?
struct TypedDataBytes
{

	typedef size_t ReturnType;

	template<typename T>
	ReturnType operator()( typename T::ConstPtr data ) const
	{
		return sizeof( typename T::BaseType ) * data->baseSize();
	}

};

} // namespace Detail
} // namespace IECoreGL

ToGLBufferConverter::ToGLBufferConverter( IECore::ConstDataPtr toConvert )
	:	ToGLConverter( "Converts IECore::Data objects to IECoreGL::Buffer objects.", IECore::DataTypeId )
{
	srcParameter()->setValue( boost::const_pointer_cast<IECore::Data>( toConvert ) );
}

ToGLBufferConverter::~ToGLBufferConverter()
{
}

IECore::RunTimeTypedPtr ToGLBufferConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const
{
	IECore::ConstDataPtr data = boost::static_pointer_cast<const IECore::Data>( src ); // safe because the parameter validated it for us

	const void *address = despatchTypedData<TypedDataAddress, TypeTraits::IsNumericBasedTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( data.get() ) );
	size_t size = despatchTypedData<Detail::TypedDataBytes, TypeTraits::IsNumericBasedTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( data.get() ) );

	return new Buffer( address, size );
}
<commit_msg>ToGLBufferConverter : Prefer DataAlgo to DespatchTypedData<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2012, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreGL/ToGLBufferConverter.h"

#include "IECoreGL/Buffer.h"

#include "IECore/Data.h"
#include "IECore/DataAlgo.h"
#include "IECore/Exception.h"
#include "IECore/TypeTraits.h"

using namespace IECore;
using namespace IECoreGL;

IE_CORE_DEFINERUNTIMETYPED( ToGLBufferConverter );

ToGLConverter::ConverterDescription<ToGLBufferConverter> ToGLBufferConverter::g_description;

namespace
{

struct Bytes
{

	template<typename T>
	size_t operator()( const TypedData<T> *data, typename std::enable_if<TypeTraits::IsNumericBasedTypedData<TypedData<T>>::value>::type *enabler = nullptr  )
	{
		return sizeof( typename TypedData<T>::BaseType ) * data->baseSize();
	}

	size_t operator()( const Data *data )
	{
		throw IECore::InvalidArgumentException( "Expected numeric data" );
	}

};

} // namespace

ToGLBufferConverter::ToGLBufferConverter( IECore::ConstDataPtr toConvert )
	:	ToGLConverter( "Converts IECore::Data objects to IECoreGL::Buffer objects.", IECore::DataTypeId )
{
	srcParameter()->setValue( boost::const_pointer_cast<IECore::Data>( toConvert ) );
}

ToGLBufferConverter::~ToGLBufferConverter()
{
}

IECore::RunTimeTypedPtr ToGLBufferConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const
{
	const Data *data = static_cast<const IECore::Data *>( src.get() ); // safe because the parameter validated it for us

	return new Buffer(
		address( data ),
		dispatch( data, Bytes() )
	);
}
<|endoftext|>


<commit_before><commit_msg>Removing debug statement causes a flood in log<commit_after><|endoftext|>


<commit_before>/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
*/

#include "JDKSAvdeccMCU_World.hpp"
#include "JDKSAvdeccMCU_RawSocketWin32.hpp"

#if defined( _WIN32 ) && JDKSAVDECCMCU_ENABLE_RAWSOCKETWIN32

#include <pcap.h>
#include <iphlpapi.h>
#include <winsock2.h>
#pragma comment( lib, "IPHLPAPI.lib" )
#pragma comment( lib, "wpcap.lib" )
#pragma comment( lib, "Ws2_32.lib" )

namespace JDKSAvdeccMCU
{
static pcap_if_t *rawsocket_win32_raw_alldevs = 0;

static void rawsocket_win32_raw_cleanup();

static void rawsocket_win32_raw_cleanup()
{
    if ( rawsocket_win32_raw_alldevs )
    {
        pcap_freealldevs( rawsocket_win32_raw_alldevs );
    }
}

static void rawsocket_win32_initialize()
{
    static bool initted = false;
    if ( !initted )
    {
        WSADATA wsaData;
        WORD version;
        int error;
        version = MAKEWORD( 2, 2 );
        error = WSAStartup( version, &wsaData );
        if ( error == 0 && version == wsaData.wVersion )
        {
            initted = true;
        }
    }
}

RawSocketWin32::RawSocketWin32( const char *device,
                                uint16_t ethertype,
                                const jdksavdecc_eui48 *multicast_to_join )
    : m_fd( bad_filedescriptor ), m_device( device ), m_ethertype( ethertype )
{
    filedescriptor_type r = -1;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *p;

    m_ethertype = ethertype;
    if ( multicast_to_join )
    {
        m_default_dest_mac_address = *multicast_to_join;
    }
    else
    {
        jdksavdecc_eui48_zero( &m_default_dest_mac_address );
    }

    p = pcap_open_live( device, 65536, 1, 1, errbuf );
    m_pcap = (void *)p;

    if ( !p )
    {
        // fprintf( stderr, "pcap open error on interface '%s': %s\n",
        // interface_name, errbuf );
        r = bad_filedescriptor;
        return;
    }
    else
    {
        int dl = pcap_datalink( p );

        if ( dl != DLT_EN10MB && dl != DLT_IEEE802_11 )
        {
            // fprintf( stderr, "Interface %s is not an Ethernet or wireless
            // interface\n", interface_name );
            r = bad_filedescriptor;
        }
        else
        {
            pcap_if_t *d = 0;
            m_interface_id = -1;
            if ( rawsocket_win32_raw_alldevs == 0 )
            {
                if ( pcap_findalldevs( &rawsocket_win32_raw_alldevs, errbuf )
                     != 0 || rawsocket_win32_raw_alldevs == 0 )
                {
                    // fprintf( stderr, "pcap_findalldevs failed\n" );
                    pcap_close( p );
                    return;
                }
            }
            {
                for ( d = rawsocket_win32_raw_alldevs; d != NULL; d = d->next )
                {
                    m_interface_id++;

                    /* find the interface by name */
                    if ( strcmp( device, d->name ) == 0 )
                    {
                        PIP_ADAPTER_INFO info = NULL, ninfo;
                        ULONG ulOutBufLen = 0;
                        DWORD dwRetVal = 0;
                        if ( GetAdaptersInfo( info, &ulOutBufLen )
                             == ERROR_BUFFER_OVERFLOW )
                        {
                            info = (PIP_ADAPTER_INFO)malloc( ulOutBufLen );
                            if ( info != NULL )
                            {
                                if ( ( dwRetVal = GetAdaptersInfo(
                                           info, &ulOutBufLen ) ) == NO_ERROR )
                                {
                                    ninfo = info;
                                    while ( ninfo != NULL )
                                    {
                                        if ( strstr( d->name,
                                                     ninfo->AdapterName ) > 0 )
                                        {
                                            if ( ninfo->AddressLength == 6 )
                                                memcpy( &m_mac_address.value[0],
                                                        ninfo->Address,
                                                        6 );
                                            break;
                                        }
                                        ninfo = ninfo->Next;
                                    }
                                }
                                else
                                {
                                    // fprintf( stderr, "Error in
                                    // GetAdaptersInfo\n" );
                                    r = bad_filedescriptor;
                                }
                                free( info );
                            }
                            else
                            {
                                // fprintf( stderr, "Error in malloc for
                                // GetAdaptersInfo\n" );
                                r = bad_filedescriptor;
                            }
                        }
                        break;
                    }
                }

                if ( m_interface_id == -1 )
                {
                    // fprintf( stderr, "unable to get MAC address for interface
                    // '%s'\n", interface_name );
                    r = r = bad_filedescriptor;
                }
                else
                {
                    /* enable ether protocol filter */
                    if (multicast_to_join)
                    {
                        joinMulticast(*multicast_to_join);
                    }
                    r = pcap_fileno( p );
                    if ( m_fd == bad_filedescriptor )
                    {
                        // fprintf( stderr, "Unable to get pcap fd\n" );
                        r = bad_filedescriptor;
                    }
                    else
                    {
                        r = m_fd;
                    }
                }
            }
        }
    }

    if ( r == bad_filedescriptor )
    {
        if ( p )
        {
            pcap_close( p );
            m_pcap = 0;
        }
    }
    else
    {
        setNonblocking();
    }
    m_fd = r;
}

RawSocketWin32::~RawSocketWin32()
{
    if ( m_fd != bad_filedescriptor )
    {
        _close( m_fd );
        m_fd = bad_filedescriptor;
    }

    if ( m_pcap )
    {
        pcap_close( (pcap_t *)m_pcap );
        m_pcap = 0;
    }
}

bool RawSocketWin32::recvFrame( Frame *frame )
{
    bool r = false;
    pcap_t *pcap = (pcap_t *)m_pcap;

    if ( pcap )
    {
        const uint8_t *data;
        struct pcap_pkthdr *header;
        int e = pcap_next_ex( pcap, &header, &data );

        if ( e == 1 && ( (ssize_t)header->caplen <= frame->getMaxLength() ) )
        {
            memcpy( frame->getBuf(), &data, r );
            frame->setLength( header->caplen );
            frame->setTimeInMilliseconds( ( header->ts.tv_sec * 1000 )
                                          + ( header->ts.tv_usec / 1000 ) );
            r = true;
        }
    }
    return r;
}

bool RawSocketWin32::sendFrame( const Frame &frame,
                                const uint8_t *data1,
                                uint16_t len1,
                                const uint8_t *data2,
                                uint16_t len2 )
{
    pcap_t *pcap = (pcap_t *)m_pcap;
    bool r = false;

    if ( m_fd != bad_filedescriptor )
    {
        /// fully formed ethernet frame buffer
        uint8_t buffer[1514];

        /// Fill it in with our data concatenated
        uint16_t buffer_length = 0;
        memcpy( buffer, frame.getBuf(), frame.getLength() );
        buffer_length += frame.getLength();
        if ( data1 != 0 && len1 > 0 )
        {
            if ( buffer_length + len1 > sizeof( buffer ) )
            {
                return false;
            }
            memcpy( &buffer[buffer_length], data1, len1 );
            buffer_length += len1;
        }
        if ( data2 != 0 && len2 > 0 )
        {
            if ( buffer_length + len2 > sizeof( buffer ) )
            {
                return false;
            }
            memcpy( &buffer[buffer_length], data2, len2 );
            buffer_length += len2;
        }

        // If dest address is not set in the frame we want to send, then fill in
        // the default destination address
        uint8_t *h_dest = &buffer[0];
        if ( h_dest[0] == 0 && h_dest[1] == 0 && h_dest[2] == 0
             && h_dest[3] == 0 && h_dest[4] == 0 && h_dest[5] == 0 )
        {
            memcpy( &h_dest[0], &m_default_dest_mac_address.value[0], 6 );
        }

        // Set the src address of the frame to match our real ethernet MAC
        // address
        uint8_t *h_source = &buffer[6];
        memcpy( &h_source[0], &m_mac_address.value[0], 6 );

        // Set the ethertype of the frame to match our real ethernet MAC address
        uint8_t *h_proto = &buffer[12];
        h_proto[0] = ( m_ethertype >> 8 ) & 0xff;
        h_proto[1] = ( m_ethertype >> 0 ) & 0xff;

        // pad the buffer with zeros to fill in the minimum payload size
        if ( buffer_length < JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH )
        {
            memset( &buffer[buffer_length],
                    0,
                    JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH - buffer_length );
            buffer_length = JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH;
        }

        r = pcap_sendpacket( pcap, buffer, buffer_length ) == 0 ? true : false;
    }

    return r;
}

bool RawSocketWin32::sendReplyFrame( Frame &frame,
                                     const uint8_t *data1,
                                     uint16_t len1,
                                     const uint8_t *data2,
                                     uint16_t len2 )
{
    pcap_t *pcap = (pcap_t *)m_pcap;
    bool r = false;

    if ( m_fd != bad_filedescriptor )
    {
        /// fully formed ethernet frame buffer
        uint8_t buffer[1514];

        /// Fill it in with our data concatenated
        uint16_t buffer_length = 0;
        memcpy( buffer, frame.getBuf(), frame.getLength() );
        buffer_length += frame.getLength();
        if ( data1 != 0 && len1 > 0 )
        {
            if ( buffer_length + len1 > sizeof( buffer ) )
            {
                return false;
            }
            memcpy( &buffer[buffer_length], data1, len1 );
            buffer_length += len1;
        }
        if ( data2 != 0 && len2 > 0 )
        {
            if ( buffer_length + len2 > sizeof( buffer ) )
            {
                return false;
            }
            memcpy( &buffer[buffer_length], data2, len2 );
            buffer_length += len2;
        }

        // set the destination address to what the source was
        uint8_t *h_dest = &buffer[0];
        uint8_t *h_source = &buffer[6];
        uint8_t *h_proto = &buffer[12];

        memcpy( &h_dest[0], &h_source[0], 6 );

        // make sure it was not a multicast
        h_dest[0] &= 0xfe;

        // Set the src address of the frame to match our real ethernet MAC
        // address
        memcpy( &h_source[0], &m_mac_address.value[0], 6 );

        // Set the ethertype of the frame to match our real ethernet MAC address
        h_proto[0] = ( m_ethertype >> 8 ) & 0xff;
        h_proto[1] = ( m_ethertype >> 0 ) & 0xff;

        // pad the buffer with zeros to fill in the minimum payload size
        if ( buffer_length < JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH )
        {
            memset( &buffer[buffer_length],
                    0,
                    JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH - buffer_length );
            buffer_length = JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH;
        }

        r = pcap_sendpacket( pcap, buffer, buffer_length ) == 0 ? true : false;
    }

    return r;
}

bool RawSocketWin32::joinMulticast( const jdksavdecc_eui48 &multicast_mac )
{
    bool r = false;
    struct bpf_program fcode;
    pcap_t *p = (pcap_t *)m_pcap;
    char filter[1024];
    /* TODO: add multicast address to pcap filter here if multicast_mac is set
     */
    (void)multicast_mac;
    sprintf_s( filter, "ether proto 0x%04x", m_ethertype );

    if ( pcap_compile( p, &fcode, filter, 1, 0xffffffff ) < 0 )
    {
        pcap_close( p );
        // fprintf( stderr, "Unable to pcap_compile: '%s'\n", filter );
        r = false;
    }
    else
    {
        if ( pcap_setfilter( p, &fcode ) < 0 )
        {
            pcap_close( p );
            // fprintf( stderr, "Unable to pcap_setfilter\n" );
            r = false;
        }
        else
        {
            r = true;
        }
        pcap_freecode( &fcode );
    }
    return r;
}

void RawSocketWin32::setNonblocking()
{
    u_long mode = 1;
    if ( ioctlsocket( m_fd, FIONBIO, &mode ) != NO_ERROR )
    {
        // fprintf(stderr, "fcntl F_SETFL O_NONBLOCK failed\n");
    }
}

void RawSocketWin32::initialize() { rawsocket_win32_initialize(); }
}

#else
const char *jdksavdeccmcu_rawsocketwin32_file = __FILE__;
#endif
<commit_msg>fix redundant assignment<commit_after>/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
*/

#include "JDKSAvdeccMCU_World.hpp"
#include "JDKSAvdeccMCU_RawSocketWin32.hpp"

#if defined( _WIN32 ) && JDKSAVDECCMCU_ENABLE_RAWSOCKETWIN32

#include <pcap.h>
#include <iphlpapi.h>
#include <winsock2.h>
#pragma comment( lib, "IPHLPAPI.lib" )
#pragma comment( lib, "wpcap.lib" )
#pragma comment( lib, "Ws2_32.lib" )

namespace JDKSAvdeccMCU
{
static pcap_if_t *rawsocket_win32_raw_alldevs = 0;

static void rawsocket_win32_raw_cleanup();

static void rawsocket_win32_raw_cleanup()
{
    if ( rawsocket_win32_raw_alldevs )
    {
        pcap_freealldevs( rawsocket_win32_raw_alldevs );
    }
}

static void rawsocket_win32_initialize()
{
    static bool initted = false;
    if ( !initted )
    {
        WSADATA wsaData;
        WORD version;
        int error;
        version = MAKEWORD( 2, 2 );
        error = WSAStartup( version, &wsaData );
        if ( error == 0 && version == wsaData.wVersion )
        {
            initted = true;
        }
    }
}

RawSocketWin32::RawSocketWin32( const char *device,
                                uint16_t ethertype,
                                const jdksavdecc_eui48 *multicast_to_join )
    : m_fd( bad_filedescriptor ), m_device( device ), m_ethertype( ethertype )
{
    filedescriptor_type r = -1;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *p;

    m_ethertype = ethertype;
    if ( multicast_to_join )
    {
        m_default_dest_mac_address = *multicast_to_join;
    }
    else
    {
        jdksavdecc_eui48_zero( &m_default_dest_mac_address );
    }

    p = pcap_open_live( device, 65536, 1, 1, errbuf );
    m_pcap = (void *)p;

    if ( !p )
    {
        // fprintf( stderr, "pcap open error on interface '%s': %s\n",
        // interface_name, errbuf );
        r = bad_filedescriptor;
        return;
    }
    else
    {
        int dl = pcap_datalink( p );

        if ( dl != DLT_EN10MB && dl != DLT_IEEE802_11 )
        {
            // fprintf( stderr, "Interface %s is not an Ethernet or wireless
            // interface\n", interface_name );
            r = bad_filedescriptor;
        }
        else
        {
            pcap_if_t *d = 0;
            m_interface_id = -1;
            if ( rawsocket_win32_raw_alldevs == 0 )
            {
                if ( pcap_findalldevs( &rawsocket_win32_raw_alldevs, errbuf )
                     != 0 || rawsocket_win32_raw_alldevs == 0 )
                {
                    // fprintf( stderr, "pcap_findalldevs failed\n" );
                    pcap_close( p );
                    return;
                }
            }
            {
                for ( d = rawsocket_win32_raw_alldevs; d != NULL; d = d->next )
                {
                    m_interface_id++;

                    /* find the interface by name */
                    if ( strcmp( device, d->name ) == 0 )
                    {
                        PIP_ADAPTER_INFO info = NULL, ninfo;
                        ULONG ulOutBufLen = 0;
                        DWORD dwRetVal = 0;
                        if ( GetAdaptersInfo( info, &ulOutBufLen )
                             == ERROR_BUFFER_OVERFLOW )
                        {
                            info = (PIP_ADAPTER_INFO)malloc( ulOutBufLen );
                            if ( info != NULL )
                            {
                                if ( ( dwRetVal = GetAdaptersInfo(
                                           info, &ulOutBufLen ) ) == NO_ERROR )
                                {
                                    ninfo = info;
                                    while ( ninfo != NULL )
                                    {
                                        if ( strstr( d->name,
                                                     ninfo->AdapterName ) > 0 )
                                        {
                                            if ( ninfo->AddressLength == 6 )
                                                memcpy( &m_mac_address.value[0],
                                                        ninfo->Address,
                                                        6 );
                                            break;
                                        }
                                        ninfo = ninfo->Next;
                                    }
                                }
                                else
                                {
                                    // fprintf( stderr, "Error in
                                    // GetAdaptersInfo\n" );
                                    r = bad_filedescriptor;
                                }
                                free( info );
                            }
                            else
                            {
                                // fprintf( stderr, "Error in malloc for
                                // GetAdaptersInfo\n" );
                                r = bad_filedescriptor;
                            }
                        }
                        break;
                    }
                }

                if ( m_interface_id == -1 )
                {
                    // fprintf( stderr, "unable to get MAC address for interface
                    // '%s'\n", interface_name );
                    r = bad_filedescriptor;
                }
                else
                {
                    /* enable ether protocol filter */
                    if (multicast_to_join)
                    {
                        joinMulticast(*multicast_to_join);
                    }
                    r = pcap_fileno( p );
                    if ( m_fd == bad_filedescriptor )
                    {
                        // fprintf( stderr, "Unable to get pcap fd\n" );
                        r = bad_filedescriptor;
                    }
                    else
                    {
                        r = m_fd;
                    }
                }
            }
        }
    }

    if ( r == bad_filedescriptor )
    {
        if ( p )
        {
            pcap_close( p );
            m_pcap = 0;
        }
    }
    else
    {
        setNonblocking();
    }
    m_fd = r;
}

RawSocketWin32::~RawSocketWin32()
{
    if ( m_fd != bad_filedescriptor )
    {
        _close( m_fd );
        m_fd = bad_filedescriptor;
    }

    if ( m_pcap )
    {
        pcap_close( (pcap_t *)m_pcap );
        m_pcap = 0;
    }
}

bool RawSocketWin32::recvFrame( Frame *frame )
{
    bool r = false;
    pcap_t *pcap = (pcap_t *)m_pcap;

    if ( pcap )
    {
        const uint8_t *data;
        struct pcap_pkthdr *header;
        int e = pcap_next_ex( pcap, &header, &data );

        if ( e == 1 && ( (ssize_t)header->caplen <= frame->getMaxLength() ) )
        {
            memcpy( frame->getBuf(), &data, r );
            frame->setLength( header->caplen );
            frame->setTimeInMilliseconds( ( header->ts.tv_sec * 1000 )
                                          + ( header->ts.tv_usec / 1000 ) );
            r = true;
        }
    }
    return r;
}

bool RawSocketWin32::sendFrame( const Frame &frame,
                                const uint8_t *data1,
                                uint16_t len1,
                                const uint8_t *data2,
                                uint16_t len2 )
{
    pcap_t *pcap = (pcap_t *)m_pcap;
    bool r = false;

    if ( m_fd != bad_filedescriptor )
    {
        /// fully formed ethernet frame buffer
        uint8_t buffer[1514];

        /// Fill it in with our data concatenated
        uint16_t buffer_length = 0;
        memcpy( buffer, frame.getBuf(), frame.getLength() );
        buffer_length += frame.getLength();
        if ( data1 != 0 && len1 > 0 )
        {
            if ( buffer_length + len1 > sizeof( buffer ) )
            {
                return false;
            }
            memcpy( &buffer[buffer_length], data1, len1 );
            buffer_length += len1;
        }
        if ( data2 != 0 && len2 > 0 )
        {
            if ( buffer_length + len2 > sizeof( buffer ) )
            {
                return false;
            }
            memcpy( &buffer[buffer_length], data2, len2 );
            buffer_length += len2;
        }

        // If dest address is not set in the frame we want to send, then fill in
        // the default destination address
        uint8_t *h_dest = &buffer[0];
        if ( h_dest[0] == 0 && h_dest[1] == 0 && h_dest[2] == 0
             && h_dest[3] == 0 && h_dest[4] == 0 && h_dest[5] == 0 )
        {
            memcpy( &h_dest[0], &m_default_dest_mac_address.value[0], 6 );
        }

        // Set the src address of the frame to match our real ethernet MAC
        // address
        uint8_t *h_source = &buffer[6];
        memcpy( &h_source[0], &m_mac_address.value[0], 6 );

        // Set the ethertype of the frame to match our real ethernet MAC address
        uint8_t *h_proto = &buffer[12];
        h_proto[0] = ( m_ethertype >> 8 ) & 0xff;
        h_proto[1] = ( m_ethertype >> 0 ) & 0xff;

        // pad the buffer with zeros to fill in the minimum payload size
        if ( buffer_length < JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH )
        {
            memset( &buffer[buffer_length],
                    0,
                    JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH - buffer_length );
            buffer_length = JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH;
        }

        r = pcap_sendpacket( pcap, buffer, buffer_length ) == 0 ? true : false;
    }

    return r;
}

bool RawSocketWin32::sendReplyFrame( Frame &frame,
                                     const uint8_t *data1,
                                     uint16_t len1,
                                     const uint8_t *data2,
                                     uint16_t len2 )
{
    pcap_t *pcap = (pcap_t *)m_pcap;
    bool r = false;

    if ( m_fd != bad_filedescriptor )
    {
        /// fully formed ethernet frame buffer
        uint8_t buffer[1514];

        /// Fill it in with our data concatenated
        uint16_t buffer_length = 0;
        memcpy( buffer, frame.getBuf(), frame.getLength() );
        buffer_length += frame.getLength();
        if ( data1 != 0 && len1 > 0 )
        {
            if ( buffer_length + len1 > sizeof( buffer ) )
            {
                return false;
            }
            memcpy( &buffer[buffer_length], data1, len1 );
            buffer_length += len1;
        }
        if ( data2 != 0 && len2 > 0 )
        {
            if ( buffer_length + len2 > sizeof( buffer ) )
            {
                return false;
            }
            memcpy( &buffer[buffer_length], data2, len2 );
            buffer_length += len2;
        }

        // set the destination address to what the source was
        uint8_t *h_dest = &buffer[0];
        uint8_t *h_source = &buffer[6];
        uint8_t *h_proto = &buffer[12];

        memcpy( &h_dest[0], &h_source[0], 6 );

        // make sure it was not a multicast
        h_dest[0] &= 0xfe;

        // Set the src address of the frame to match our real ethernet MAC
        // address
        memcpy( &h_source[0], &m_mac_address.value[0], 6 );

        // Set the ethertype of the frame to match our real ethernet MAC address
        h_proto[0] = ( m_ethertype >> 8 ) & 0xff;
        h_proto[1] = ( m_ethertype >> 0 ) & 0xff;

        // pad the buffer with zeros to fill in the minimum payload size
        if ( buffer_length < JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH )
        {
            memset( &buffer[buffer_length],
                    0,
                    JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH - buffer_length );
            buffer_length = JDKSAVDECCMCU_RAWSOCKET_MIN_FRAME_LENGTH;
        }

        r = pcap_sendpacket( pcap, buffer, buffer_length ) == 0 ? true : false;
    }

    return r;
}

bool RawSocketWin32::joinMulticast( const jdksavdecc_eui48 &multicast_mac )
{
    bool r = false;
    struct bpf_program fcode;
    pcap_t *p = (pcap_t *)m_pcap;
    char filter[1024];
    /* TODO: add multicast address to pcap filter here if multicast_mac is set
     */
    (void)multicast_mac;
    sprintf_s( filter, "ether proto 0x%04x", m_ethertype );

    if ( pcap_compile( p, &fcode, filter, 1, 0xffffffff ) < 0 )
    {
        pcap_close( p );
        // fprintf( stderr, "Unable to pcap_compile: '%s'\n", filter );
        r = false;
    }
    else
    {
        if ( pcap_setfilter( p, &fcode ) < 0 )
        {
            pcap_close( p );
            // fprintf( stderr, "Unable to pcap_setfilter\n" );
            r = false;
        }
        else
        {
            r = true;
        }
        pcap_freecode( &fcode );
    }
    return r;
}

void RawSocketWin32::setNonblocking()
{
    u_long mode = 1;
    if ( ioctlsocket( m_fd, FIONBIO, &mode ) != NO_ERROR )
    {
        // fprintf(stderr, "fcntl F_SETFL O_NONBLOCK failed\n");
    }
}

void RawSocketWin32::initialize() { rawsocket_win32_initialize(); }
}

#else
const char *jdksavdeccmcu_rawsocketwin32_file = __FILE__;
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sdpage_animations.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:16: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
 *
 ************************************************************************/

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

#ifndef _COM_SUN_STAR_PRESENTATION_PARAGRAPHTARGET_HPP_
#include <com/sun/star/presentation/ParagraphTarget.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_EFFECTNODETYPE_HPP_
#include <com/sun/star/presentation/EffectNodeType.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

#ifndef _OUTLINER_HXX
#include <svx/outliner.hxx>
#endif

#ifndef _SD_CUSTOMANIMATIONCLONER_HXX
#include "CustomAnimationCloner.hxx"
#endif

#ifndef _DRAWDOC_HXX
#include "drawdoc.hxx"
#endif

#ifndef _SDPAGE_HXX
#include "sdpage.hxx"
#endif

#ifndef _SD_CUSTOMANIMATIONPRESET_HXX
#include <CustomAnimationPreset.hxx>
#endif

#ifndef _SD_TRANSITIONPRESET_HXX
#include <TransitionPreset.hxx>
#endif

#ifndef _SD_UNDO_ANIM_HXX
#include "undoanim.hxx"
#endif

#ifndef _SD_EFFECT_MIGRATION_HXX
#include "EffectMigration.hxx"
#endif

using namespace ::vos;
using namespace ::rtl;
using namespace ::sd;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::animations;
using namespace ::com::sun::star::presentation;

using ::com::sun::star::drawing::XShape;

/** returns a helper class to manipulate effects inside the main sequence */
sd::MainSequencePtr SdPage::getMainSequence()
{
    if( 0 == mpMainSequence.get() )
        mpMainSequence.reset( new sd::MainSequence( getAnimationNode() ) );

    return mpMainSequence;
}

/** returns the main animation node */
Reference< XAnimationNode > SdPage::getAnimationNode() throw (RuntimeException)
{
    if( !mxAnimationNode.is() )
    {
        mxAnimationNode = Reference< XAnimationNode >::query(::comphelper::getProcessServiceFactory()->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.animations.ParallelTimeContainer"))));
        if( mxAnimationNode.is() )
        {
            Sequence< ::com::sun::star::beans::NamedValue > aUserData( 1 );
            aUserData[0].Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "node-type" ) );
            aUserData[0].Value <<= ::com::sun::star::presentation::EffectNodeType::TIMING_ROOT;
            mxAnimationNode->setUserData( aUserData );
        }
    }

    return mxAnimationNode;
}

void SdPage::setAnimationNode( Reference< XAnimationNode >& xNode ) throw (RuntimeException)
{
    mxAnimationNode = xNode;
    if( mpMainSequence.get() )
        mpMainSequence->reset( xNode );
}

/** removes all custom animations for the given shape */
void SdPage::removeAnimations( const SdrObject* pObj )
{
    if( mxAnimationNode.is() )
    {
        getMainSequence();

        Reference< XShape > xShape( const_cast<SdrObject*>(pObj)->getUnoShape(), UNO_QUERY );

        if( mpMainSequence->hasEffect( xShape ) )
            mpMainSequence->disposeShape( xShape );
    }
}

bool SdPage::hasAnimationNode() const
{
    return mxAnimationNode.is();
}

void SdPage::SetFadeEffect(::com::sun::star::presentation::FadeEffect eNewEffect)
{
    EffectMigration::SetFadeEffect( this, eNewEffect );
}

FadeEffect SdPage::GetFadeEffect() const
{
    return EffectMigration::GetFadeEffect( this );
}

/** callback from the sd::View when a new paragraph for one object on this page is created */
void SdPage::onParagraphInserted( ::Outliner* pOutliner, Paragraph* pPara, SdrObject* pObj )
{
    if( mxAnimationNode.is() )
    {
        ParagraphTarget aTarget;
        aTarget.Shape = Reference< XShape >( pObj->getUnoShape(), UNO_QUERY );
        aTarget.Paragraph = (sal_Int16)pOutliner->GetAbsPos( pPara );

        getMainSequence()->insertTextRange( makeAny( aTarget ) );
    }
}

/** callback from the sd::View when a paragraph from one object on this page is removed */
void SdPage::onParagraphRemoving( ::Outliner* pOutliner, Paragraph* pPara, SdrObject* pObj )
{
    if( mxAnimationNode.is() )
    {
        ParagraphTarget aTarget;
        aTarget.Shape = Reference< XShape >( pObj->getUnoShape(), UNO_QUERY );
        aTarget.Paragraph = (sal_Int16)pOutliner->GetAbsPos( pPara );

        getMainSequence()->disposeTextRange( makeAny( aTarget ) );
    }
}

/** callback from the sd::View when an object just left text edit mode */
void SdPage::onEndTextEdit( SdrObject* pObj )
{
    if( pObj && mxAnimationNode.is() )
    {
        Reference< XShape > xObj( pObj->getUnoShape(), UNO_QUERY );
        getMainSequence()->onTextChanged( xObj );
    }
}

void SdPage::cloneAnimations( SdPage& rTargetPage ) const
{
    if( mxAnimationNode.is() )
    {
        Reference< XAnimationNode > xClonedNode(
            ::sd::Clone( mxAnimationNode, this, &rTargetPage ) );

        if( xClonedNode.is() )
            rTargetPage.setAnimationNode( xClonedNode );
    }
}

<commit_msg>INTEGRATION: CWS impresstables2 (1.14.114); FILE MERGED 2007/07/31 11:21:39 cl 1.14.114.1: fixing linux build problems<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sdpage_animations.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 11:28:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _COM_SUN_STAR_PRESENTATION_PARAGRAPHTARGET_HPP_
#include <com/sun/star/presentation/ParagraphTarget.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_EFFECTNODETYPE_HPP_
#include <com/sun/star/presentation/EffectNodeType.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

#ifndef _OUTLINER_HXX
#include <svx/outliner.hxx>
#endif

#ifndef _SD_CUSTOMANIMATIONCLONER_HXX
#include "CustomAnimationCloner.hxx"
#endif

#ifndef _DRAWDOC_HXX
#include "drawdoc.hxx"
#endif

#ifndef _SDPAGE_HXX
#include "sdpage.hxx"
#endif

#ifndef _SD_CUSTOMANIMATIONPRESET_HXX
#include <CustomAnimationPreset.hxx>
#endif

#ifndef _SD_TRANSITIONPRESET_HXX
#include <TransitionPreset.hxx>
#endif

#ifndef _SD_UNDO_ANIM_HXX
#include "undoanim.hxx"
#endif

#ifndef _SD_EFFECT_MIGRATION_HXX
#include "EffectMigration.hxx"
#endif

using namespace ::vos;
using ::rtl::OUString;
using namespace ::sd;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::animations;
using namespace ::com::sun::star::presentation;

using ::com::sun::star::drawing::XShape;

/** returns a helper class to manipulate effects inside the main sequence */
sd::MainSequencePtr SdPage::getMainSequence()
{
    if( 0 == mpMainSequence.get() )
        mpMainSequence.reset( new sd::MainSequence( getAnimationNode() ) );

    return mpMainSequence;
}

/** returns the main animation node */
Reference< XAnimationNode > SdPage::getAnimationNode() throw (RuntimeException)
{
    if( !mxAnimationNode.is() )
    {
        mxAnimationNode = Reference< XAnimationNode >::query(::comphelper::getProcessServiceFactory()->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.animations.ParallelTimeContainer"))));
        if( mxAnimationNode.is() )
        {
            Sequence< ::com::sun::star::beans::NamedValue > aUserData( 1 );
            aUserData[0].Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "node-type" ) );
            aUserData[0].Value <<= ::com::sun::star::presentation::EffectNodeType::TIMING_ROOT;
            mxAnimationNode->setUserData( aUserData );
        }
    }

    return mxAnimationNode;
}

void SdPage::setAnimationNode( Reference< XAnimationNode >& xNode ) throw (RuntimeException)
{
    mxAnimationNode = xNode;
    if( mpMainSequence.get() )
        mpMainSequence->reset( xNode );
}

/** removes all custom animations for the given shape */
void SdPage::removeAnimations( const SdrObject* pObj )
{
    if( mxAnimationNode.is() )
    {
        getMainSequence();

        Reference< XShape > xShape( const_cast<SdrObject*>(pObj)->getUnoShape(), UNO_QUERY );

        if( mpMainSequence->hasEffect( xShape ) )
            mpMainSequence->disposeShape( xShape );
    }
}

bool SdPage::hasAnimationNode() const
{
    return mxAnimationNode.is();
}

void SdPage::SetFadeEffect(::com::sun::star::presentation::FadeEffect eNewEffect)
{
    EffectMigration::SetFadeEffect( this, eNewEffect );
}

FadeEffect SdPage::GetFadeEffect() const
{
    return EffectMigration::GetFadeEffect( this );
}

/** callback from the sd::View when a new paragraph for one object on this page is created */
void SdPage::onParagraphInserted( ::Outliner* pOutliner, Paragraph* pPara, SdrObject* pObj )
{
    if( mxAnimationNode.is() )
    {
        ParagraphTarget aTarget;
        aTarget.Shape = Reference< XShape >( pObj->getUnoShape(), UNO_QUERY );
        aTarget.Paragraph = (sal_Int16)pOutliner->GetAbsPos( pPara );

        getMainSequence()->insertTextRange( makeAny( aTarget ) );
    }
}

/** callback from the sd::View when a paragraph from one object on this page is removed */
void SdPage::onParagraphRemoving( ::Outliner* pOutliner, Paragraph* pPara, SdrObject* pObj )
{
    if( mxAnimationNode.is() )
    {
        ParagraphTarget aTarget;
        aTarget.Shape = Reference< XShape >( pObj->getUnoShape(), UNO_QUERY );
        aTarget.Paragraph = (sal_Int16)pOutliner->GetAbsPos( pPara );

        getMainSequence()->disposeTextRange( makeAny( aTarget ) );
    }
}

/** callback from the sd::View when an object just left text edit mode */
void SdPage::onEndTextEdit( SdrObject* pObj )
{
    if( pObj && mxAnimationNode.is() )
    {
        Reference< XShape > xObj( pObj->getUnoShape(), UNO_QUERY );
        getMainSequence()->onTextChanged( xObj );
    }
}

void SdPage::cloneAnimations( SdPage& rTargetPage ) const
{
    if( mxAnimationNode.is() )
    {
        Reference< XAnimationNode > xClonedNode(
            ::sd::Clone( mxAnimationNode, this, &rTargetPage ) );

        if( xClonedNode.is() )
            rTargetPage.setAnimationNode( xClonedNode );
    }
}

<|endoftext|>