<commit_before>//
// gsl-lite is based on GSL: Guideline Support Library.
// For more information see https://github.com/martinmoene/gsl-lite
//
// Copyright (c) 2015 Martin Moene
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "gsl-lite.t.h"
#include <vector>

namespace {

struct MyBase {};
struct MyDerived : public MyBase {};
struct Unrelated {};

// Stand-in for a user-defined ref-counted class.
template<typename T>
struct RefCounted
{
    RefCounted( T * p ) : p_( p ) {}
    operator T *() { return p_; }
    T * p_;
};

}

CASE( "not_null<>: Disallows default construction (define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS)" )
{
#if gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS
    not_null< int* > p;
#endif
}

CASE( "not_null<>: Disallows construction from nullptr_t, NULL or 0 (define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS)" )
{
#if gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS
# if gsl_HAVE_NULLPTR
    not_null< int* > p = nullptr;
# endif
    not_null< int* > p = NULL;
    not_null< std::vector<char>* > q = 0;
#endif
}

CASE( "not_null<>: Disallows construction from a unique pointer to underlying type (define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS)" )
{
#if gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS
# if gsl_HAVE_UNIQUE_PTR
    std::unique_ptr< int > up = std::make_unique<int>( 120 );
    not_null< int* > p4 = up;
# endif
#endif
}

CASE( "not_null<>: Disallows assignment from unrelated pointers (define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS)" )
{
#if gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS
    MyDerived derived;
    not_null< MyDerived* > p = &derived;

    not_null< Unrelated* > r = p;
    not_null< Unrelated* > s = reinterpret_cast< Unrelated* >( p );
#endif
}

CASE( "not_null<>: Terminates construction from a null pointer value" )
{
#if gsl_HAVE_NULLPTR
    struct F { static void blow() { int * z = nullptr; not_null<int*> p(z); } };
#else
    struct F { static void blow() { int * z = NULL; not_null<int*> p(z); } };
#endif

    EXPECT_THROWS( F::blow() );
}

CASE( "not_null<>: Terminates construction from related pointer types for null pointer value" )
{
#if gsl_HAVE_NULLPTR
    struct F { static void blow() { MyDerived * z = nullptr; not_null<MyBase*> p(z); } };
#else
    struct F { static void blow() { MyDerived * z = NULL; not_null<MyBase*> p(z); } };
#endif

    EXPECT_THROWS( F::blow() );
}

CASE( "not_null<>: Terminates assignment from a null pointer value" )
{
    int i = 12;
    not_null<int*> p = &i;
#if gsl_HAVE_NULLPTR
    int * z = nullptr;
#else
    int * z = NULL;
#endif

    EXPECT_THROWS( p = z );
}

CASE( "not_null<>: Terminates assignment from related pointer types for null pointer value" )
{
#if gsl_HAVE_NULLPTR
    MyDerived * z = nullptr;
#else
    MyDerived * z = NULL;
#endif
    MyDerived derived;
    not_null< MyBase* > p = &derived;

    EXPECT_THROWS( p = z );
}

CASE( "not_null<>: Allows to construct from a non-null underlying pointer" )
{
    int i = 12;

    not_null< int* > p( &i );

    EXPECT( p.get() == &i );
}

CASE( "not_null<>: Allows to construct from a non-null user-defined ref-counted type" )
{
    int i = 12;
    RefCounted< int > rp = RefCounted<int>( &i );

    not_null<   int*>  p( rp );

    EXPECT( p.get() == &i );
}

CASE( "not_null<>: Allows to construct from a non-null related pointer" )
{
    MyDerived derived;
    not_null< MyBase* > p = &derived;

    EXPECT( p.get() == &derived );
}

CASE( "not_null<>: Allows to construct from a not_null related pointer type" )
{
    MyDerived derived;
    not_null< MyDerived* > p = &derived;

    not_null< MyBase* > q = p;

    EXPECT( q == p );
}

CASE( "not_null<>: Allows assignment from a not_null related pointer type" )
{
    MyDerived derived;
    not_null< MyDerived* > p = &derived;
    not_null< MyBase*    > q = p;

    q = p;

    EXPECT( q == p );
}

CASE( "not_null<>: Allows assignment from a non-null bare recast pointer" )
{
    MyDerived derived;
    not_null< MyDerived* > p = &derived;

    not_null< Unrelated* > t = reinterpret_cast< Unrelated* >( p.get() );

    EXPECT( p.get() == reinterpret_cast<  MyDerived* >( t.get() ) );
}

CASE( "not_null<>: Allows implicit conversion to underlying type" )
{
    struct F { static bool helper( not_null<int*> p ) { return *p == 12; } };

    int i = 12;
    not_null< int* > p = &i;

    EXPECT( F::helper( p ) );
}

CASE( "not_null<>: Allows indirect member access" )
{
    struct S { char c; int i; } s = { 'a', 7 };
    not_null< S* > p = &s;

    EXPECT( p->c == 'a' );
    EXPECT( p->i ==  7  );
}

CASE( "not_null<>: Allows dereferencing" )
{
    int i = 12;
    not_null< int* > p = &i;

    EXPECT( *p == i );
}

// end of file
<commit_msg>Make struct definition nonlocal for C++98, C++03<commit_after>//
// gsl-lite is based on GSL: Guideline Support Library.
// For more information see https://github.com/martinmoene/gsl-lite
//
// Copyright (c) 2015 Martin Moene
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "gsl-lite.t.h"
#include <vector>

namespace {

struct MyBase {};
struct MyDerived : public MyBase {};
struct Unrelated {};

// Stand-in for a user-defined ref-counted class.
template<typename T>
struct RefCounted
{
    RefCounted( T * p ) : p_( p ) {}
    operator T *() { return p_; }
    T * p_;
};

}

CASE( "not_null<>: Disallows default construction (define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS)" )
{
#if gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS
    not_null< int* > p;
#endif
}

CASE( "not_null<>: Disallows construction from nullptr_t, NULL or 0 (define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS)" )
{
#if gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS
# if gsl_HAVE_NULLPTR
    not_null< int* > p = nullptr;
# endif
    not_null< int* > p = NULL;
    not_null< std::vector<char>* > q = 0;
#endif
}

CASE( "not_null<>: Disallows construction from a unique pointer to underlying type (define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS)" )
{
#if gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS
# if gsl_HAVE_UNIQUE_PTR
    std::unique_ptr< int > up = std::make_unique<int>( 120 );
    not_null< int* > p4 = up;
# endif
#endif
}

CASE( "not_null<>: Disallows assignment from unrelated pointers (define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS)" )
{
#if gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS
    MyDerived derived;
    not_null< MyDerived* > p = &derived;

    not_null< Unrelated* > r = p;
    not_null< Unrelated* > s = reinterpret_cast< Unrelated* >( p );
#endif
}

CASE( "not_null<>: Terminates construction from a null pointer value" )
{
#if gsl_HAVE_NULLPTR
    struct F { static void blow() { int * z = nullptr; not_null<int*> p(z); } };
#else
    struct F { static void blow() { int * z = NULL; not_null<int*> p(z); } };
#endif

    EXPECT_THROWS( F::blow() );
}

CASE( "not_null<>: Terminates construction from related pointer types for null pointer value" )
{
#if gsl_HAVE_NULLPTR
    struct F { static void blow() { MyDerived * z = nullptr; not_null<MyBase*> p(z); } };
#else
    struct F { static void blow() { MyDerived * z = NULL; not_null<MyBase*> p(z); } };
#endif

    EXPECT_THROWS( F::blow() );
}

CASE( "not_null<>: Terminates assignment from a null pointer value" )
{
    int i = 12;
    not_null<int*> p = &i;
#if gsl_HAVE_NULLPTR
    int * z = nullptr;
#else
    int * z = NULL;
#endif

    EXPECT_THROWS( p = z );
}

CASE( "not_null<>: Terminates assignment from related pointer types for null pointer value" )
{
#if gsl_HAVE_NULLPTR
    MyDerived * z = nullptr;
#else
    MyDerived * z = NULL;
#endif
    MyDerived derived;
    not_null< MyBase* > p = &derived;

    EXPECT_THROWS( p = z );
}

CASE( "not_null<>: Allows to construct from a non-null underlying pointer" )
{
    int i = 12;

    not_null< int* > p( &i );

    EXPECT( p.get() == &i );
}

CASE( "not_null<>: Allows to construct from a non-null user-defined ref-counted type" )
{
    int i = 12;
    RefCounted< int > rp = RefCounted<int>( &i );

    not_null<   int*>  p( rp );

    EXPECT( p.get() == &i );
}

CASE( "not_null<>: Allows to construct from a non-null related pointer" )
{
    MyDerived derived;
    not_null< MyBase* > p = &derived;

    EXPECT( p.get() == &derived );
}

CASE( "not_null<>: Allows to construct from a not_null related pointer type" )
{
    MyDerived derived;
    not_null< MyDerived* > p = &derived;

    not_null< MyBase* > q = p;

    EXPECT( q == p );
}

CASE( "not_null<>: Allows assignment from a not_null related pointer type" )
{
    MyDerived derived;
    not_null< MyDerived* > p = &derived;
    not_null< MyBase*    > q = p;

    q = p;

    EXPECT( q == p );
}

CASE( "not_null<>: Allows assignment from a non-null bare recast pointer" )
{
    MyDerived derived;
    not_null< MyDerived* > p = &derived;

    not_null< Unrelated* > t = reinterpret_cast< Unrelated* >( p.get() );

    EXPECT( p.get() == reinterpret_cast<  MyDerived* >( t.get() ) );
}

CASE( "not_null<>: Allows implicit conversion to underlying type" )
{
    struct F { static bool helper( not_null<int*> p ) { return *p == 12; } };

    int i = 12;
    not_null< int* > p = &i;

    EXPECT( F::helper( p ) );
}

namespace nonlocal
{
    struct S { char c; int i; };
}

CASE( "not_null<>: Allows indirect member access" )
{
    using namespace nonlocal;
    S s = { 'a', 7 };
    not_null< S* > p = &s;

    EXPECT( p->c == 'a' );
    EXPECT( p->i ==  7  );
}

CASE( "not_null<>: Allows dereferencing" )
{
    int i = 12;
    not_null< int* > p = &i;

    EXPECT( *p == i );
}

// end of file
<|endoftext|>


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

// --- Internal Includes ---
#include <NamedScopedEnum.hpp>
#include <test/catch.hpp>

TEST_CASE( "Test conversion to names" )
{
  NAMED_SCOPED_ENUM(Color, red, green, blue );

  Color color = Color::red;

  CHECK( color.name() == "red" );

}

TEST_CASE( "Test set function" )
{
  NAMED_SCOPED_ENUM(Color, red, green, blue );

  Color color = Color::red;

  color = Color::green;

  CHECK( color == Color::green );

}

TEST_CASE( "Test size function" )
{
  NAMED_SCOPED_ENUM(Color, red, green, blue );

  CHECK( Color::size() == 3 );

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

// --- Internal Includes ---
#include <NamedScopedEnum.hpp>
#include <test/catch.hpp>

TEST_CASE( "Test conversion to names" )
{
  NAMED_SCOPED_ENUM( Color, red, green, blue );

  Color color = Color::red;

  CHECK( color.name() == "red" );

}

TEST_CASE( "Test set function" )
{
  NAMED_SCOPED_ENUM( Color, red, green, blue );

  Color color = Color::red;

  color = Color::green;

  CHECK( color == Color::green );

}

TEST_CASE( "Test size function" )
{
  NAMED_SCOPED_ENUM( Color, red, green, blue );

  CHECK( Color::size() == 3 );

}
<|endoftext|>


<commit_before><commit_msg>more cleanup<commit_after><|endoftext|>


<commit_before>#include "treeface/graphics/guts/LineStroker.h"

#include "treeface/graphics/guts/utils.h"

#include "treeface/math/constants.h"
#include "treeface/math/mat2.h"

using namespace treecore;

namespace treeface
{

int LineStroker::HalfOutline::find_cross_from_tail(const Vec2f& p1, const Vec2f& p2, Vec2f& p_cross) const
{
    jassert(outline.size() > 1);

    Vec2f v12 = p2 - p1;

    for (int i = outline.size() - 2; i >= 0; i--)
    {
        const Vec2f& p3 = outline[i];
        const Vec2f& p4 = outline[i+1];
        Vec2f v34 = p4 - p3;

        if (cross_test_exc(p1, p2, v12, p3, p4, v34, p_cross))
            return i;
    }

    return -1;
}

void LineStroker::HalfOutline::add_miter_point(const Vec2f& skeleton1, JointID id, const Vec2f& ortho_prev, const Vec2f& ortho_curr, const InternalStrokeStyle& style)
{
    // only do miter join if angle is not too sharp
    float turn_cosine = ortho_prev * ortho_curr;
    if (turn_cosine > style.miter_cutoff_cosine)
    {
        Vec2f ortho_mid = ortho_prev + ortho_curr;
        ortho_mid.normalize();

        float half_cosine = ortho_mid * ortho_prev;
        jassert(0.0f < half_cosine && half_cosine < 1.0f);
        Vec2f r_mid = ortho_mid * (style.half_width * side / half_cosine);

        add(skeleton1 + r_mid, id);
    }
}

void LineStroker::HalfOutline::add_round_points(const Vec2f& skeleton1, JointID id, const Vec2f& ortho_prev, const Vec2f& ortho_curr, const InternalStrokeStyle& style)
{
    // calculate step
    float turn_angle = std::acos(ortho_prev * ortho_curr);
    int num_step = turn_angle / PI * 32;
    if (num_step < 5) num_step = 5;
    float step_angle = turn_angle / num_step;

    Mat2f step_mat;
    step_mat.set_rotate(-side * step_angle);

    // do rotation
    Vec2f r_tmp = ortho_prev * side * style.half_width;
    for (int i = 1; i < num_step; i++)
    {
        r_tmp = step_mat * r_tmp;
        add(skeleton1 + r_tmp, id);
    }
}

void LineStroker::HalfOutline::process_inner(const HalfOutline& outer_peer,
                                             const Vec2f& skeleton1,
                                             const JointID id1,
                                             const Vec2f& skeleton2,
                                             const Vec2f& ortho_curr,
                                             const InternalStrokeStyle& style)
{
    const JointID id2 = id1 + 1;
    Vec2f p_cross;

    Vec2f r_curr = ortho_curr * (side * style.half_width);
    Vec2f p1 = skeleton1 + r_curr;
    Vec2f p2 = skeleton2 + r_curr;

    {
        int i_self = find_cross_from_tail(p1, p2, p_cross);
        if (i_self >= 0)
        {
            resize(i_self+1);
            add(p_cross, id1);
            add(p2,      id2);
            sunken = false;
            return;
        }
    }

    {
        int i_peer = outer_peer.find_cross_from_tail(p1, p2, p_cross);
        if (i_peer >= 0)
        {
            add(p_cross, id1);
            add(p2, id2);
            sunken = false;
            return;
        }
    }

    sunken = true;
}

void LineStroker::extend_stroke(const Vec2f& p_prev, const Vec2f& p1, const Vec2f& p2, bool use_line_join)
{
    jassert(p_prev != p1);
    jassert(p2 != p1);

    Vec2f v_prev = p1 - p_prev;
    Vec2f v_curr = p2 - p1;
    v_prev.normalize();
    v_curr.normalize();
    Vec2f ortho_prev = v_prev.get_ortholog();
    Vec2f ortho_curr = v_curr.get_ortholog();

    Vec2f r_prev = ortho_prev * style.half_width;
    Vec2f r_curr = ortho_curr * style.half_width;

    float turn_sine = v_prev ^ v_curr;
    float turn_cosine = v_prev * v_curr;

    JointID joint_id1 = std::max(part_left.joint_ids.getLast(), part_right.joint_ids.getLast());
    JointID joint_id2 = joint_id1 + 1;

    // is turning
    if (turn_sine != 0.0f)
    {
        HalfOutline* part_inner;
        HalfOutline* part_outer;

        // decide turn side
        if (turn_sine > 0.0f)
        {
            part_inner = &part_left;
            part_outer = &part_right;
        }
        else
        {
            part_inner = &part_right;
            part_outer = &part_left;
        }

        // process outer side
        part_outer->salvage(p1, r_prev, joint_id1);

        if (use_line_join)
        {
            switch (style.join)
            {
            case LINE_JOIN_MITER:
                part_outer->add_miter_point(p1, joint_id1, ortho_prev, ortho_curr, style);
                break;
            case LINE_JOIN_ROUND:
                part_outer->add_round_points(p1, joint_id1, ortho_prev, ortho_curr, style);
                break;
            case LINE_JOIN_BEVEL:
                break;
            }
        }

        part_outer->add(p1 + r_curr * part_outer->side, joint_id1);
        part_outer->add(p2 + r_curr * part_outer->side, joint_id2);

        // process inner side
        part_inner->process_inner(*part_outer, p1, joint_id1, p2, ortho_curr, style);
    }
    // no turn
    else
    {
        part_left.add(p2 + r_curr, joint_id2);
        part_right.add(p2 - r_curr, joint_id2);
    }
}

} // namespace treeface
<commit_msg>use bounding box while traversing outline<commit_after>#include "treeface/graphics/guts/LineStroker.h"

#include "treeface/graphics/guts/utils.h"

#include "treeface/math/constants.h"
#include "treeface/math/mat2.h"

using namespace treecore;

namespace treeface
{

int LineStroker::HalfOutline::find_cross_from_tail(const Vec2f& p1, const Vec2f& p2, Vec2f& p_cross) const
{
    jassert(outline.size() > 1);
    jassert(outline.size() == outline_bounds.size() + 1);

    Vec2f v12 = p2 - p1;

    const BBox2f bound_input(p1, p2);

    for (int i = outline.size() - 2; i >= 0; i--)
    {
        if (bound_input ^ outline_bounds[i])
        {
            const Vec2f& p3 = outline[i];
            const Vec2f& p4 = outline[i+1];
            Vec2f v34 = p4 - p3;

            if (cross_test_exc(p1, p2, v12, p3, p4, v34, p_cross))
                return i;
        }
    }

    return -1;
}

void LineStroker::HalfOutline::add_miter_point(const Vec2f& skeleton1, JointID id, const Vec2f& ortho_prev, const Vec2f& ortho_curr, const InternalStrokeStyle& style)
{
    // only do miter join if angle is not too sharp
    float turn_cosine = ortho_prev * ortho_curr;
    if (turn_cosine > style.miter_cutoff_cosine)
    {
        Vec2f ortho_mid = ortho_prev + ortho_curr;
        ortho_mid.normalize();

        float half_cosine = ortho_mid * ortho_prev;
        jassert(0.0f < half_cosine && half_cosine < 1.0f);
        Vec2f r_mid = ortho_mid * (style.half_width * side / half_cosine);

        add(skeleton1 + r_mid, id);
    }
}

void LineStroker::HalfOutline::add_round_points(const Vec2f& skeleton1, JointID id, const Vec2f& ortho_prev, const Vec2f& ortho_curr, const InternalStrokeStyle& style)
{
    // calculate step
    float turn_angle = std::acos(ortho_prev * ortho_curr);
    int num_step = turn_angle / PI * 32;
    if (num_step < 5) num_step = 5;
    float step_angle = turn_angle / num_step;

    Mat2f step_mat;
    step_mat.set_rotate(-side * step_angle);

    // do rotation
    Vec2f r_tmp = ortho_prev * side * style.half_width;
    for (int i = 1; i < num_step; i++)
    {
        r_tmp = step_mat * r_tmp;
        add(skeleton1 + r_tmp, id);
    }
}

void LineStroker::HalfOutline::process_inner(const HalfOutline& outer_peer,
                                             const Vec2f& skeleton1,
                                             const JointID id1,
                                             const Vec2f& skeleton2,
                                             const Vec2f& ortho_curr,
                                             const InternalStrokeStyle& style)
{
    const JointID id2 = id1 + 1;
    Vec2f p_cross;

    Vec2f r_curr = ortho_curr * (side * style.half_width);
    Vec2f p1 = skeleton1 + r_curr;
    Vec2f p2 = skeleton2 + r_curr;

    {
        int i_self = find_cross_from_tail(p1, p2, p_cross);
        if (i_self >= 0)
        {
            resize(i_self+1);
            add(p_cross, id1);
            add(p2,      id2);
            sunken = false;
            return;
        }
    }

    {
        int i_peer = outer_peer.find_cross_from_tail(p1, p2, p_cross);
        if (i_peer >= 0)
        {
            add(p_cross, id1);
            add(p2, id2);
            sunken = false;
            return;
        }
    }

    sunken = true;
}

void LineStroker::extend_stroke(const Vec2f& p_prev, const Vec2f& p1, const Vec2f& p2, bool use_line_join)
{
    jassert(p_prev != p1);
    jassert(p2 != p1);

    Vec2f v_prev = p1 - p_prev;
    Vec2f v_curr = p2 - p1;
    v_prev.normalize();
    v_curr.normalize();
    Vec2f ortho_prev = v_prev.get_ortholog();
    Vec2f ortho_curr = v_curr.get_ortholog();

    Vec2f r_prev = ortho_prev * style.half_width;
    Vec2f r_curr = ortho_curr * style.half_width;

    float turn_sine = v_prev ^ v_curr;
    float turn_cosine = v_prev * v_curr;

    JointID joint_id1 = std::max(part_left.joint_ids.getLast(), part_right.joint_ids.getLast());
    JointID joint_id2 = joint_id1 + 1;

    // is turning
    if (turn_sine != 0.0f)
    {
        HalfOutline* part_inner;
        HalfOutline* part_outer;

        // decide turn side
        if (turn_sine > 0.0f)
        {
            part_inner = &part_left;
            part_outer = &part_right;
        }
        else
        {
            part_inner = &part_right;
            part_outer = &part_left;
        }

        // process outer side
        part_outer->salvage(p1, r_prev, joint_id1);

        if (use_line_join)
        {
            switch (style.join)
            {
            case LINE_JOIN_MITER:
                part_outer->add_miter_point(p1, joint_id1, ortho_prev, ortho_curr, style);
                break;
            case LINE_JOIN_ROUND:
                part_outer->add_round_points(p1, joint_id1, ortho_prev, ortho_curr, style);
                break;
            case LINE_JOIN_BEVEL:
                break;
            }
        }

        part_outer->add(p1 + r_curr * part_outer->side, joint_id1);
        part_outer->add(p2 + r_curr * part_outer->side, joint_id2);

        // process inner side
        part_inner->process_inner(*part_outer, p1, joint_id1, p2, ortho_curr, style);
    }
    // no turn
    else
    {
        part_left.add(p2 + r_curr, joint_id2);
        part_right.add(p2 - r_curr, joint_id2);
    }
}

} // namespace treeface
<|endoftext|>


<commit_before>#ifndef MATH_CORE_MATRIX_HPP
#define MATH_CORE_MATRIX_HPP

#include <array>
#include <cstddef>

#include "vector.hpp"

#ifdef minor
#undef minor
#endif

namespace math {
namespace core {
namespace {

/**
 * Checks that the given matrix dimensions make a square matrix.
 * @struct is_square_matrix
 * @param M Number of rows in the matrix.
 * @param N Number of columns in the matrix.
 */
template<std::size_t M, std::size_t N>
struct is_square_matrix : std::integral_constant<bool, N == M> {};

/**
 * Definition of the components available in a generic matrix. Column-major.
 * @class matrix_components
 * @tparam T Storage type.
 * @tparam M Number of rows.
 * @tparam N Number of columns.
 */
template<typename T, std::size_t M, std::size_t N>
class matrix_components {
public:
	explicit matrix_components(void) : data() {}
	explicit matrix_components(const std::array<vector<T, M>, N>& data) : data(data) {}
	explicit matrix_components(const matrix_components<T, M, N>&) = default;
	explicit matrix_components(matrix_components<T, M, N>&&) = default;

	std::array<vector<T, M>, N> data;
};

/**
 * Matrix component specialization for column vectors. Column-major.
 * @class matrix_components
 * @tparam T Storage type.
 * @tparam M Number of rows.
 */
template<typename T, std::size_t M>
class matrix_components<T, M, 1> {
public:
	explicit matrix_components(void) : data() {}
	explicit matrix_components(const std::array<vector<T, M>, 1>& data) : data(data) {}
	explicit matrix_components(const vector<T, M>& V) : data({{V}}) {}
	explicit matrix_components(const matrix_components<T, M, 1>&) = default;
	explicit matrix_components(matrix_components<T, M, 1>&&) = default;

	std::array<vector<T, M>, 1> data;
};

/**
 * Matrix component specialization for matrices with 2 columns. Column-major.
 * @class matrix_components
 * @tparam T Storage type.
 * @tparam M Number of rows.
 */
template<typename T, std::size_t M>
class matrix_components<T, M, 2> {
public:
	explicit matrix_components(void) : data() {}
	explicit matrix_components(const std::array<vector<T, M>, 2>& data) : data(data) {}
	explicit matrix_components(const vector<T, M>& V1, const vector<T, M>& V2) : data({{V1, V2}}) {}
	explicit matrix_components(const matrix_components<T, M, 2>&) = default;
	explicit matrix_components(matrix_components<T, M, 2>&&) = default;

	std::array<vector<T, M>, 2> data;
};

/**
 * Matrix component specialization for matrices with 3 columns. Column-major.
 * @class matrix_components
 * @tparam T Storage type.
 * @tparam M Number of rows.
 */
template<typename T, std::size_t M>
class matrix_components<T, M, 3> {
public:
	explicit matrix_components(void) : data() {}
	explicit matrix_components(const std::array<vector<T, M>, 3>& data) : data(data) {}
	explicit matrix_components(const vector<T, M>& V1, const vector<T, M>& V2, const vector<T, M>& V3) :
		data({{V1, V2, V3}}) {}
	explicit matrix_components(const matrix_components<T, M, 3>&) = default;
	explicit matrix_components(matrix_components<T, M, 3>&&) = default;

	std::array<vector<T, M>, 3> data;
};

/**
 * Matrix component specialization for matrices with 4 columns. Column-major.
 * @class matrix_components
 * @tparam T Storage type.
 * @tparam M Number of rows.
 */
template<typename T, std::size_t M>
class matrix_components<T, M, 4> {
public:
	explicit matrix_components(void) : data() {}
	explicit matrix_components(const std::array<vector<T, M>, 4>& data) : data(data) {}
	explicit matrix_components(const vector<T, M>& V1, const vector<T, M>& V2, const vector<T, M>& V3, const vector<T, M>& V4) :
		data({{V1, V2, V3, V4}}) {}
	explicit matrix_components(const matrix_components<T, M, 4>&) = default;
	explicit matrix_components(matrix_components<T, M, 4>&&) = default;

	std::array<vector<T, M>, 4> data;
};

}

/**
 * A matrix with generic size and type. Column-major.
 * @class matrix
 * @tparam T Storage type.
 * @tparam M Number of rows.
 * @tparam N Number of columns. Defaults to number of rows.
 */
template<typename T, std::size_t M, std::size_t N = M>
class matrix : public matrix_components<T, M, N> {
public:
	using matrix_components<T, M, N>::matrix_components;

	~matrix(void) = default;

	matrix<T, M, N>& operator=(const matrix<T, M, N>&);

	vector<T, M> operator[](const std::size_t) const;
	vector<T, M>& operator[](const std::size_t);

	matrix<T, M, N> operator-(void) const;
	matrix<T, M, N> operator+(const matrix<T, M, N>&) const;
	matrix<T, M, N>& operator+=(const matrix<T, M, N>&);
	matrix<T, M, N> operator-(const matrix<T, M, N>&) const;
	matrix<T, M, N>& operator-=(const matrix<T, M, N>&);

	template<std::size_t P>
	matrix<T, M, P> operator*(const matrix<T, N, P>&) const;

	matrix<T, M, N> operator*(const T&) const;
	matrix<T, M, N>& operator*=(const T&);
	matrix<T, M, N> operator/(const T&) const;
	matrix<T, M, N>& operator/=(const T&);

	matrix<T, N, M> transpose(void) const;

	bool operator==(const matrix<T, M, N>&) const;
	bool operator!=(const matrix<T, M, N>&) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	T minor(const std::size_t, const std::size_t) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	T det(void) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	matrix<T, M, N> minors(void) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	matrix<T, M, N> cofactor(void) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	matrix<T, M, N> adjugate(void) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	matrix<T, M, N> inverse(void) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value && M == 4, U>::type>
	static matrix<T, M, N> translation(const vector<T, 3>&);

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value && M == 4, U>::type>
	static matrix<T, M, N> rotation(const vector<T, 3>&, const vector<T, 3>&);

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value && M == 4, U>::type>
	static matrix<T, M, N> scale(const T&, const T&, const T&);

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value && M == 4, U>::type>
	static matrix<T, M, N> orthographic(const T&, const T&, const T&, const T&, const T&, const T&);

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value && M == 4, U>::type>
	static matrix<T, M, N> perspective(const T&, const T&, const T&, const T&);
};

}
}

#include "matrix.inl"

#endif
<commit_msg>Moved is_square_matrix assertion to math::core namespace.<commit_after>#ifndef MATH_CORE_MATRIX_HPP
#define MATH_CORE_MATRIX_HPP

#include <array>
#include <cstddef>

#include "vector.hpp"

#ifdef minor
#undef minor
#endif

namespace math {
namespace core {

/**
 * Checks that the given matrix dimensions make a square matrix.
 * @struct is_square_matrix
 * @param M Number of rows in the matrix.
 * @param N Number of columns in the matrix.
 */
template<std::size_t M, std::size_t N>
struct is_square_matrix : std::integral_constant<bool, N == M> {};

namespace {

/**
 * Definition of the components available in a generic matrix. Column-major.
 * @class matrix_components
 * @tparam T Storage type.
 * @tparam M Number of rows.
 * @tparam N Number of columns.
 */
template<typename T, std::size_t M, std::size_t N>
class matrix_components {
public:
	explicit matrix_components(void) : data() {}
	explicit matrix_components(const std::array<vector<T, M>, N>& data) : data(data) {}
	explicit matrix_components(const matrix_components<T, M, N>&) = default;
	explicit matrix_components(matrix_components<T, M, N>&&) = default;

	std::array<vector<T, M>, N> data;
};

/**
 * Matrix component specialization for column vectors. Column-major.
 * @class matrix_components
 * @tparam T Storage type.
 * @tparam M Number of rows.
 */
template<typename T, std::size_t M>
class matrix_components<T, M, 1> {
public:
	explicit matrix_components(void) : data() {}
	explicit matrix_components(const std::array<vector<T, M>, 1>& data) : data(data) {}
	explicit matrix_components(const vector<T, M>& V) : data({{V}}) {}
	explicit matrix_components(const matrix_components<T, M, 1>&) = default;
	explicit matrix_components(matrix_components<T, M, 1>&&) = default;

	std::array<vector<T, M>, 1> data;
};

/**
 * Matrix component specialization for matrices with 2 columns. Column-major.
 * @class matrix_components
 * @tparam T Storage type.
 * @tparam M Number of rows.
 */
template<typename T, std::size_t M>
class matrix_components<T, M, 2> {
public:
	explicit matrix_components(void) : data() {}
	explicit matrix_components(const std::array<vector<T, M>, 2>& data) : data(data) {}
	explicit matrix_components(const vector<T, M>& V1, const vector<T, M>& V2) : data({{V1, V2}}) {}
	explicit matrix_components(const matrix_components<T, M, 2>&) = default;
	explicit matrix_components(matrix_components<T, M, 2>&&) = default;

	std::array<vector<T, M>, 2> data;
};

/**
 * Matrix component specialization for matrices with 3 columns. Column-major.
 * @class matrix_components
 * @tparam T Storage type.
 * @tparam M Number of rows.
 */
template<typename T, std::size_t M>
class matrix_components<T, M, 3> {
public:
	explicit matrix_components(void) : data() {}
	explicit matrix_components(const std::array<vector<T, M>, 3>& data) : data(data) {}
	explicit matrix_components(const vector<T, M>& V1, const vector<T, M>& V2, const vector<T, M>& V3) :
		data({{V1, V2, V3}}) {}
	explicit matrix_components(const matrix_components<T, M, 3>&) = default;
	explicit matrix_components(matrix_components<T, M, 3>&&) = default;

	std::array<vector<T, M>, 3> data;
};

/**
 * Matrix component specialization for matrices with 4 columns. Column-major.
 * @class matrix_components
 * @tparam T Storage type.
 * @tparam M Number of rows.
 */
template<typename T, std::size_t M>
class matrix_components<T, M, 4> {
public:
	explicit matrix_components(void) : data() {}
	explicit matrix_components(const std::array<vector<T, M>, 4>& data) : data(data) {}
	explicit matrix_components(const vector<T, M>& V1, const vector<T, M>& V2, const vector<T, M>& V3, const vector<T, M>& V4) :
		data({{V1, V2, V3, V4}}) {}
	explicit matrix_components(const matrix_components<T, M, 4>&) = default;
	explicit matrix_components(matrix_components<T, M, 4>&&) = default;

	std::array<vector<T, M>, 4> data;
};

}

/**
 * A matrix with generic size and type. Column-major.
 * @class matrix
 * @tparam T Storage type.
 * @tparam M Number of rows.
 * @tparam N Number of columns. Defaults to number of rows.
 */
template<typename T, std::size_t M, std::size_t N = M>
class matrix : public matrix_components<T, M, N> {
public:
	using matrix_components<T, M, N>::matrix_components;

	~matrix(void) = default;

	matrix<T, M, N>& operator=(const matrix<T, M, N>&);

	vector<T, M> operator[](const std::size_t) const;
	vector<T, M>& operator[](const std::size_t);

	matrix<T, M, N> operator-(void) const;
	matrix<T, M, N> operator+(const matrix<T, M, N>&) const;
	matrix<T, M, N>& operator+=(const matrix<T, M, N>&);
	matrix<T, M, N> operator-(const matrix<T, M, N>&) const;
	matrix<T, M, N>& operator-=(const matrix<T, M, N>&);

	template<std::size_t P>
	matrix<T, M, P> operator*(const matrix<T, N, P>&) const;

	matrix<T, M, N> operator*(const T&) const;
	matrix<T, M, N>& operator*=(const T&);
	matrix<T, M, N> operator/(const T&) const;
	matrix<T, M, N>& operator/=(const T&);

	matrix<T, N, M> transpose(void) const;

	bool operator==(const matrix<T, M, N>&) const;
	bool operator!=(const matrix<T, M, N>&) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	T minor(const std::size_t, const std::size_t) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	T det(void) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	matrix<T, M, N> minors(void) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	matrix<T, M, N> cofactor(void) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	matrix<T, M, N> adjugate(void) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value, U>::type>
	matrix<T, M, N> inverse(void) const;

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value && M == 4, U>::type>
	static matrix<T, M, N> translation(const vector<T, 3>&);

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value && M == 4, U>::type>
	static matrix<T, M, N> rotation(const vector<T, 3>&, const vector<T, 3>&);

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value && M == 4, U>::type>
	static matrix<T, M, N> scale(const T&, const T&, const T&);

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value && M == 4, U>::type>
	static matrix<T, M, N> orthographic(const T&, const T&, const T&, const T&, const T&, const T&);

	template<typename U = T,
		typename = typename std::enable_if<is_square_matrix<M, N>::value && M == 4, U>::type>
	static matrix<T, M, N> perspective(const T&, const T&, const T&, const T&);
};

}
}

#include "matrix.inl"

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#if !defined(PLATFORMDEFINITIONS_HEADER_GUARD_1357924680)
#define PLATFORMDEFINITIONS_HEADER_GUARD_1357924680

#include "xercesc/util/XercesDefs.hpp"

#if defined(_MSC_VER)
#include "VCPPDefinitions.hpp"
#elif defined(CYGWIN)
#include "CygwinDefinitions.hpp"
#elif defined(__GNUC__)
#include "GCCDefinitions.hpp"
#elif defined(_AIX)
#include "AIXDefinitions.hpp"
#elif defined(__hpux)
#include "HPUXDefinitions.hpp"
#elif defined(SOLARIS)
#include "SolarisDefinitions.hpp"
#elif defined(OS390)
#include "OS390Definitions.hpp"
#elif defined(OS400)
#include "OS400Definitions.hpp"
#elif defined(__DECCXX)
#include "TRU64Definitions.hpp"
#elif defined(__INTEL_COMPILER)
#include "IntelDefinitions.hpp"
#else
#error Unknown compiler!
#endif

#include "XalanVersion.hpp"

#if defined(__cplusplus)

// ---------------------------------------------------------------------------
// Define namespace symbols if the compiler supports it.
// ---------------------------------------------------------------------------
#if defined(XALAN_HAS_CPP_NAMESPACE)
	#define XALAN_CPP_NAMESPACE_BEGIN namespace XALAN_CPP_NAMESPACE {
	#define XALAN_CPP_NAMESPACE_END  }
	#define XALAN_CPP_NAMESPACE_USE using namespace XALAN_CPP_NAMESPACE;
	#define XALAN_CPP_NAMESPACE_QUALIFIER XALAN_CPP_NAMESPACE::
	#define XALAN_USING(NAMESPACE,NAME) using NAMESPACE :: NAME;
	#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) namespace NAMESPACE { class NAME; }
	#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) namespace NAMESPACE { struct NAME; }

	namespace XALAN_CPP_NAMESPACE { }
	namespace xalanc = XALAN_CPP_NAMESPACE;
#else
	#if defined(XALAN_CPP_NAMESPACE)
	#undef XALAN_CPP_NAMESPACE
	#endif

	#define XALAN_CPP_NAMESPACE
	#define XALAN_CPP_NAMESPACE_BEGIN
	#define XALAN_CPP_NAMESPACE_END
	#define XALAN_CPP_NAMESPACE_USE
	#define XALAN_CPP_NAMESPACE_QUALIFIER
	#define XALAN_USING(NAMESPACE,NAME)
	#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) class NAME;
	#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) struct NAME;
	#if !defined(XALAN_NO_STD_NAMESPACE)
		#define XALAN_NO_STD_NAMESPACE
	#endif
#endif

#if defined(XALAN_NO_STD_NAMESPACE)
	#define XALAN_USING_STD(NAME)
	#define XALAN_STD_QUALIFIER
#else
	#define XALAN_USING_STD(NAME) using std :: NAME;
	#define XALAN_STD_QUALIFIER  std ::
#endif

#define XALAN_DECLARE_XALAN_CLASS(NAME) XALAN_DECLARE_CLASS(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_DECLARE_XALAN_STRUCT(NAME) XALAN_DECLARE_STRUCT(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_USING_XALAN(NAME) XALAN_USING(XALAN_CPP_NAMESPACE, NAME)

#if defined(XERCES_HAS_CPP_NAMESPACE)
	#define XALAN_USING_XERCES(NAME) XALAN_USING(XERCES_CPP_NAMESPACE, NAME)
	#define XALAN_DECLARE_XERCES_CLASS(NAME) XALAN_DECLARE_CLASS(XERCES_CPP_NAMESPACE, NAME)
	#define XALAN_DECLARE_XERCES_STRUCT(NAME) XALAN_DECLARE_STRUCT(XERCES_CPP_NAMESPACE, NAME)
#else
	#define XERCES_CPP_NAMESPACE_QUALIFIER
	#define XERCES_CPP_NAMESPACE_BEGIN
	#define XERCES_CPP_NAMESPACE_END
	#define XERCES_CPP_NAMESPACE_USE
	#define XALAN_USING_XERCES(NAME)
	#define XALAN_DECLARE_XERCES_CLASS(NAME) class NAME;
	#define XALAN_DECLARE_XERCES_STRUCT(NAME) struct NAME;
#endif

#include <cstddef>

XALAN_CPP_NAMESPACE_BEGIN
#if defined(XALAN_USE_NATIVE_WCHAR_T)
typedef wchar_t			XalanDOMChar;
#else
// UTF-16 character...
typedef unsigned short	XalanDOMChar;
#endif
XALAN_CPP_NAMESPACE_END

#endif // __cplusplus

#endif	// PLATFORMDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>Fix allowing compiling C-API Test<commit_after>/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#if !defined(PLATFORMDEFINITIONS_HEADER_GUARD_1357924680)
#define PLATFORMDEFINITIONS_HEADER_GUARD_1357924680

#if defined(__cplusplus)
#include "xercesc/util/XercesDefs.hpp"
#endif

#if defined(_MSC_VER)
#include "VCPPDefinitions.hpp"
#elif defined(CYGWIN)
#include "CygwinDefinitions.hpp"
#elif defined(__GNUC__)
#include "GCCDefinitions.hpp"
#elif defined(_AIX)
#include "AIXDefinitions.hpp"
#elif defined(__hpux)
#include "HPUXDefinitions.hpp"
#elif defined(SOLARIS)
#include "SolarisDefinitions.hpp"
#elif defined(OS390)
#include "OS390Definitions.hpp"
#elif defined(OS400)
#include "OS400Definitions.hpp"
#elif defined(__DECCXX)
#include "TRU64Definitions.hpp"
#elif defined(__INTEL_COMPILER)
#include "IntelDefinitions.hpp"
#else
#error Unknown compiler!
#endif

#include "XalanVersion.hpp"

#if defined(__cplusplus)

// ---------------------------------------------------------------------------
// Define namespace symbols if the compiler supports it.
// ---------------------------------------------------------------------------
#if defined(XALAN_HAS_CPP_NAMESPACE)
	#define XALAN_CPP_NAMESPACE_BEGIN namespace XALAN_CPP_NAMESPACE {
	#define XALAN_CPP_NAMESPACE_END  }
	#define XALAN_CPP_NAMESPACE_USE using namespace XALAN_CPP_NAMESPACE;
	#define XALAN_CPP_NAMESPACE_QUALIFIER XALAN_CPP_NAMESPACE::
	#define XALAN_USING(NAMESPACE,NAME) using NAMESPACE :: NAME;
	#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) namespace NAMESPACE { class NAME; }
	#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) namespace NAMESPACE { struct NAME; }

	namespace XALAN_CPP_NAMESPACE { }
	namespace xalanc = XALAN_CPP_NAMESPACE;
#else
	#if defined(XALAN_CPP_NAMESPACE)
	#undef XALAN_CPP_NAMESPACE
	#endif

	#define XALAN_CPP_NAMESPACE
	#define XALAN_CPP_NAMESPACE_BEGIN
	#define XALAN_CPP_NAMESPACE_END
	#define XALAN_CPP_NAMESPACE_USE
	#define XALAN_CPP_NAMESPACE_QUALIFIER
	#define XALAN_USING(NAMESPACE,NAME)
	#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) class NAME;
	#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) struct NAME;
	#if !defined(XALAN_NO_STD_NAMESPACE)
		#define XALAN_NO_STD_NAMESPACE
	#endif
#endif

#if defined(XALAN_NO_STD_NAMESPACE)
	#define XALAN_USING_STD(NAME)
	#define XALAN_STD_QUALIFIER
#else
	#define XALAN_USING_STD(NAME) using std :: NAME;
	#define XALAN_STD_QUALIFIER  std ::
#endif

#define XALAN_DECLARE_XALAN_CLASS(NAME) XALAN_DECLARE_CLASS(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_DECLARE_XALAN_STRUCT(NAME) XALAN_DECLARE_STRUCT(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_USING_XALAN(NAME) XALAN_USING(XALAN_CPP_NAMESPACE, NAME)

#if defined(XERCES_HAS_CPP_NAMESPACE)
	#define XALAN_USING_XERCES(NAME) XALAN_USING(XERCES_CPP_NAMESPACE, NAME)
	#define XALAN_DECLARE_XERCES_CLASS(NAME) XALAN_DECLARE_CLASS(XERCES_CPP_NAMESPACE, NAME)
	#define XALAN_DECLARE_XERCES_STRUCT(NAME) XALAN_DECLARE_STRUCT(XERCES_CPP_NAMESPACE, NAME)
#else
	#define XERCES_CPP_NAMESPACE_QUALIFIER
	#define XERCES_CPP_NAMESPACE_BEGIN
	#define XERCES_CPP_NAMESPACE_END
	#define XERCES_CPP_NAMESPACE_USE
	#define XALAN_USING_XERCES(NAME)
	#define XALAN_DECLARE_XERCES_CLASS(NAME) class NAME;
	#define XALAN_DECLARE_XERCES_STRUCT(NAME) struct NAME;
#endif

#include <cstddef>

XALAN_CPP_NAMESPACE_BEGIN
#if defined(XALAN_USE_NATIVE_WCHAR_T)
typedef wchar_t			XalanDOMChar;
#else
// UTF-16 character...
typedef unsigned short	XalanDOMChar;
#endif
XALAN_CPP_NAMESPACE_END

#endif // __cplusplus

#endif	// PLATFORMDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
*    if any, must include the following acknowledgment:
*       "This product includes software developed by the
*        Apache Software Foundation (http://www.apache.org/)."
*    Alternately, this acknowledgment may appear in the software itself,
*    if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
*    not be used to endorse or promote products derived from this
*    software without prior written permission. For written
*    permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
*    nor may "Apache" appear in their name, without prior written
*    permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com.  For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include "MsgCreator.h"
#include "InMemHandler.hpp"
#include "ICUResHandler.hpp"
#include "NLSHandler.hpp"
#include <cassert>

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

XALAN_USING_STD(cerr)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)

// ---------------------------------------------------------------------------
//  Local helper methods
// ---------------------------------------------------------------------------
static void usage()
{
    cout << "\nUsage:\n"
		"    MsgCreator [options] <XML file>\n\n"
		"This program reads XML message file, and then creates C++ the " << endl <<
		" source / data files for message localization (for .dll/.so build) \n"

		"Options:\n"
		"   -TYPE xxx    Type of localization [ICU | NLS | InMem*]\n"
		"   -LOCAL       ex: [ fr | fr_FR ]; The default is an 'en' local \n"
		"                       If your .xlf file doesn't contain translation \n"
		"                       to 'xx_YY' local, the system will look for\n"
		"                       'xx' translation; "<< endl <<
		"   <XML file>   Can be provided optionally. If not provided, the \n"
		"                       program looks for ${XALANCROOT}/xalanc/NLS directory, \n"
		"                       and looking for XalanMsg_<given local>.xlf file. \n"
		"  * = Default if not provided explicitly.\n\n"
		"    -?          Show this help.\n\n"
		"\n"
		<<  endl;
}

class CmdLineParams
{

public:

	typedef enum{

		ICU_LOCALMSG = 0,
		INMEM_LOCALMSG,
		NLS_LOCALMSG

	}TypeOfLocalMsg;

	const char*		inXMLFileName;

	TypeOfLocalMsg  enTypeOfLocalMsg;

	const char*      encodingName;

	char*		localName;

	bool		isLocalGiven;

	CmdLineParams():
	inXMLFileName(0),
		enTypeOfLocalMsg(INMEM_LOCALMSG),
		encodingName("LATIN1"),
		localName(0),
		isLocalGiven(false){}

	~CmdLineParams() { delete[] localName; }
};

#if defined(OS390)
#include <strings.h>

int
compareNoCase(
			  const char*		str1,
			  const char*		str2)
{
	return strcasecmp(str1, str2);
}

#else

int
compareNoCase(
			  const char*		str1,
			  const char*		str2)
{
	return stricmp(str1, str2);
}

#endif

bool
getArgs(
		int				argc,
		char*			argv[],
		CmdLineParams&	p,
		const char**	pErrorMsg)
{
	bool fSuccess = true;
	const char*		errorMessage = 0;
	if ( argc > 7)
	{
		fSuccess = false;
		errorMessage = "Too many parameters\n";
	}
	for (int i = 1; i < argc && fSuccess == true; ++i)
	{
		if (!compareNoCase("-h", argv[i]) || !compareNoCase("-?", argv[i]))
		{
			fSuccess = false;
		}
		else if (!compareNoCase("-LOCAL", argv[i]) )
		{
			++i;
			if( i < argc && argv[i][0] != '-' )
			{
				int localLen = strlen(argv[i]);
				if ( localLen != 2 && localLen !=5)
				{
					fSuccess = false;
					errorMessage = "Unrecognized local\n";
				}

				if ( fSuccess  && localLen == 5 && argv[i][2] != '_')
				{
					fSuccess = false;
					errorMessage = "Unrecognized form of local\n";
				}
				if ( fSuccess )
				{
					p.isLocalGiven = true;

					p.localName = new char[10];

					strcpy(p.localName,argv[i]);

					p.localName[9]='\0'; // just in case
				}
			}
		}
		else if (!compareNoCase("-TYPE", argv[i]) )
		{
			++i;

			if( i < argc && argv[i][0] != '-' )
			{
				if( !compareNoCase("ICU",argv[i] ))
				{
					p.enTypeOfLocalMsg = CmdLineParams::ICU_LOCALMSG;

				}else if( !compareNoCase("NLS",argv[i] ))
				{
					p.enTypeOfLocalMsg = CmdLineParams::NLS_LOCALMSG;

				}
				else if( !compareNoCase("InMem",argv[i] ))
				{
					p.enTypeOfLocalMsg = CmdLineParams::INMEM_LOCALMSG;

				}else
				{
					fSuccess = false;
					errorMessage = "Unknown TYPE of localization\n";
				}
			}
			else
			{
				fSuccess = false;
			}
		}else if ( argv[i][0] != '-' )
		{
			p.inXMLFileName = argv[i];
		}
	}

	if ( fSuccess )
	{
		*pErrorMsg = 0;
	}
	else
	{
		*pErrorMsg = errorMessage;
	}

	return fSuccess;
}

static char* buildInputFileName(const CmdLineParams&	p)
{

	char* result = new char[85];
	result[0] = '\0';

	// if file name was given expisitly, don't build it
	if( p.inXMLFileName != 0)
	{
		assert(strlen(p.inXMLFileName) < 84);
		strcpy(result,p.inXMLFileName);
		return result;
	}

	strcat(result,s_xalanMsgFileName);

	if( p.isLocalGiven )
	{

		strncat(result,p.localName,2);

	}
	else
	{
		strcat(result,s_en);

	}
	strcat(result,s_xliffExten);

	return result;
}

static char* buildOutputFileName(const CmdLineParams&	p)
{
	char* pOutputFileName = new char[80];
	pOutputFileName[0] = '\0';

	switch(p.enTypeOfLocalMsg){
	case CmdLineParams::ICU_LOCALMSG:
		{
			if (p.isLocalGiven )
			{
				strcpy(pOutputFileName, p.localName);
			}
			else
			{
				strcpy(pOutputFileName, s_en);
			}

			strcat(pOutputFileName, s_txtExten);

			break;
		}
	case CmdLineParams::INMEM_LOCALMSG:
		{
			strcpy(pOutputFileName, DATA_FILE_NAME);
			break;
		}

	case CmdLineParams::NLS_LOCALMSG:
		{
			strcpy(pOutputFileName,s_xalanMsgFileName);

			if (p.isLocalGiven )
			{
				strncat(pOutputFileName, p.localName,6);
			}
			else
			{
				strncat(pOutputFileName, s_en,3);
			}

			strcat(pOutputFileName, s_msgExten);

			break;
		}
	default:
		{
			// in that stage the local should be defined
			assert ( 0 );
		}
	}
	return pOutputFileName;
}

// ---------------------------------------------------------------------------
//  Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{

#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	CmdLineParams	theParams;
	int iReturnValue = 0;
	const char* errorMessage = 0;
	if (getArgs(argC, argV, theParams, &errorMessage) == false)
	{
		if ( errorMessage != 0)
		{
			cerr << errorMessage;
		}
		usage();
		iReturnValue = 1;

	}
	else
	{

		try
		{
			XMLPlatformUtils::Initialize();
		}

		catch (const XMLException& toCatch)
		{
			cerr << "Error during initialization! :\n"
				<< StrX(toCatch.getMessage()) << endl;
			iReturnValue = 2;
		}
		if (iReturnValue == 0)
		{

			{	//  Create a SAX parser object.
				SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();

				parser->setFeature(XMLUni::fgSAX2CoreValidation, false);

				parser->setFeature(XMLUni::fgXercesDynamic, true);

				parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, false);

				parser->setFeature(XMLUni::fgXercesSchema, true);

				parser->setFeature(XMLUni::fgXercesSchemaFullChecking, false);

				parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, false);

				//  Create the handler object and install it as the document and error
				//  handler for the parser. Then parse the file and catch any exceptions
				//  that propogate out
				//

				int errorCount = 0;

				char* const		fileName = buildInputFileName(theParams);

				char* const		pOutputFileName = buildOutputFileName(theParams);

				SAX2Handler* handler = 0;
				try
				{
					switch(theParams.enTypeOfLocalMsg){
					case CmdLineParams::ICU_LOCALMSG:
						{
							handler = new ICUResHandler(pOutputFileName);
							break;
						}
					case CmdLineParams::INMEM_LOCALMSG:
						{
							handler = new InMemHandler(pOutputFileName);
							break;
						}
					case CmdLineParams::NLS_LOCALMSG:
						{
							handler = new NLSHandler(pOutputFileName);
							break;
						}
					default:
						{
							assert (0);
						}
					}
				}

				catch(const XalanFileOutputStream::XalanFileOutputStreamOpenException& e)
				{
					cerr << "\nAn error occurred\n  Error: ";
					if (e.m_pMessage != 0)
					{
						cerr << e.m_pMessage <<  endl;
					}
					else
					{
						cerr << "unknown (XalanFileOutputStreamOpenException) " << "\n" << endl;

					}

					iReturnValue = 4;

				}
				catch(const XalanFileOutputStream::XalanFileOutputStreamWriteException& e)
				{
					cerr << "\nAn error occurred\n  Error: ";
					if (e.m_pMessage != 0)
					{
						cerr << e.m_pMessage << endl;
					}
					else
					{
						cerr << "unknown (XalanFileOutputStreamWriteException) " << "\n" << endl;

					}

					iReturnValue = 5;

				}
				catch (...)
				{
					cerr << "Unknown error occured." << endl;
					iReturnValue = 6;
				}

				// run the parser
				if ( iReturnValue == 0)
				{
					try
					{
						if ( theParams.isLocalGiven == true )
						{
							handler->setXML_Lang(theParams.localName);
						}

						parser->setContentHandler(handler);

						parser->setErrorHandler(handler);

						parser->parse(fileName);

						errorCount = parser->getErrorCount();
					}

					catch (const XMLException& toCatch)
					{
						cerr << "\nAn error occurred\n  Error: "
							<< StrX(toCatch.getMessage())
							<< "\n" << endl;
						iReturnValue = 7;
					}
					catch (...)
					{
						cerr << endl << "General error occured." << endl;
						iReturnValue = 8;
					}
				}

				delete handler;

				delete[] pOutputFileName;

				delete[] fileName;
				//
				//  Delete the parser itself.  Must be done prior to calling Terminate, below.
				//
				delete parser;

				if (errorCount != 0)
					iReturnValue = 9;

			}
			// And call the termination method
			XMLPlatformUtils::Terminate();

		}

	}
	return iReturnValue;
}

<commit_msg>Fixed glitches.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
*    if any, must include the following acknowledgment:
*       "This product includes software developed by the
*        Apache Software Foundation (http://www.apache.org/)."
*    Alternately, this acknowledgment may appear in the software itself,
*    if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
*    not be used to endorse or promote products derived from this
*    software without prior written permission. For written
*    permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
*    nor may "Apache" appear in their name, without prior written
*    permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com.  For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include "MsgCreator.h"
#include "InMemHandler.hpp"
#include "ICUResHandler.hpp"
#include "NLSHandler.hpp"
#include <cassert>

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

XALAN_USING_STD(cerr)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)

// ---------------------------------------------------------------------------
//  Local helper methods
// ---------------------------------------------------------------------------
static void usage()
{
    cout << "\nUsage:\n"
		"    MsgCreator [options] <XML file>\n\n"
		"This program reads XML message file, and then creates C++ the " << endl <<
		" source / data files for message localization (for .dll/.so build) \n"

		"Options:\n"
		"   -TYPE xxx    Type of localization [ICU | NLS | InMem*]\n"
		"   -LOCAL       ex: [ fr | fr_FR ]; The default is an 'en' local \n"
		"                       If your .xlf file doesn't contain translation \n"
		"                       to 'xx_YY' local, the system will look for\n"
		"                       'xx' translation; "<< endl <<
		"   <XML file>   Can be provided optionally. If not provided, the \n"
		"                       program looks for ${XALANCROOT}/xalanc/NLS directory, \n"
		"                       and looking for XalanMsg_<given local>.xlf file. \n"
		"  * = Default if not provided explicitly.\n\n"
		"    -?          Show this help.\n\n"
		"\n"
		<<  endl;
}

class CmdLineParams
{

public:

	typedef enum{

		ICU_LOCALMSG = 0,
		INMEM_LOCALMSG,
		NLS_LOCALMSG

	}TypeOfLocalMsg;

	const char*		inXMLFileName;

	TypeOfLocalMsg  enTypeOfLocalMsg;

	const char*      encodingName;

	char*		localName;

	bool		isLocalGiven;

	CmdLineParams():
	inXMLFileName(0),
		enTypeOfLocalMsg(INMEM_LOCALMSG),
		encodingName("LATIN1"),
		localName(0),
		isLocalGiven(false){}

	~CmdLineParams() { delete[] localName; }
};

#if defined(OS390)
#include <strings.h>

int
compareNoCase(
			  const char*		str1,
			  const char*		str2)
{
	return strcasecmp(str1, str2);
}

#else

int
compareNoCase(
			  const char*		str1,
			  const char*		str2)
{
	return stricmp(str1, str2);
}

#endif

bool
getArgs(
		int				argc,
		char*			argv[],
		CmdLineParams&	p,
		const char**	pErrorMsg)
{
	bool fSuccess = true;
	const char*		errorMessage = 0;
	if ( argc > 7)
	{
		fSuccess = false;
		errorMessage = "Too many parameters\n";
	}
	for (int i = 1; i < argc && fSuccess == true; ++i)
	{
		if (!compareNoCase("-h", argv[i]) || !compareNoCase("-?", argv[i]))
		{
			fSuccess = false;
		}
		else if (!compareNoCase("-LOCAL", argv[i]) )
		{
			++i;
			if( i < argc && argv[i][0] != '-' )
			{
#if defined(XALAN_STRICT_ANSI_HEADERS)
				using std::size_t;
#endif

				const size_t	localLen = strlen(argv[i]);
				if ( localLen != 2 && localLen !=5)
				{
					fSuccess = false;
					errorMessage = "Unrecognized local\n";
				}

				if ( fSuccess  && localLen == 5 && argv[i][2] != '_')
				{
					fSuccess = false;
					errorMessage = "Unrecognized form of local\n";
				}
				if ( fSuccess )
				{
					p.isLocalGiven = true;

					p.localName = new char[10];

					strcpy(p.localName,argv[i]);

					p.localName[9]='\0'; // just in case
				}
			}
		}
		else if (!compareNoCase("-TYPE", argv[i]) )
		{
			++i;

			if( i < argc && argv[i][0] != '-' )
			{
				if( !compareNoCase("ICU",argv[i] ))
				{
					p.enTypeOfLocalMsg = CmdLineParams::ICU_LOCALMSG;

				}else if( !compareNoCase("NLS",argv[i] ))
				{
					p.enTypeOfLocalMsg = CmdLineParams::NLS_LOCALMSG;

				}
				else if( !compareNoCase("InMem",argv[i] ))
				{
					p.enTypeOfLocalMsg = CmdLineParams::INMEM_LOCALMSG;

				}else
				{
					fSuccess = false;
					errorMessage = "Unknown TYPE of localization\n";
				}
			}
			else
			{
				fSuccess = false;
			}
		}else if ( argv[i][0] != '-' )
		{
			p.inXMLFileName = argv[i];
		}
	}

	if ( fSuccess )
	{
		*pErrorMsg = 0;
	}
	else
	{
		*pErrorMsg = errorMessage;
	}

	return fSuccess;
}

static char* buildInputFileName(const CmdLineParams&	p)
{

	char* result = new char[85];
	result[0] = '\0';

	// if file name was given expisitly, don't build it
	if( p.inXMLFileName != 0)
	{
		assert(strlen(p.inXMLFileName) < 84);
		strcpy(result,p.inXMLFileName);
		return result;
	}

	strcat(result,s_xalanMsgFileName);

	if( p.isLocalGiven )
	{

		strncat(result,p.localName,2);

	}
	else
	{
		strcat(result,s_en);

	}
	strcat(result,s_xliffExten);

	return result;
}

static char* buildOutputFileName(const CmdLineParams&	p)
{
	char* pOutputFileName = new char[80];
	pOutputFileName[0] = '\0';

	switch(p.enTypeOfLocalMsg){
	case CmdLineParams::ICU_LOCALMSG:
		{
			if (p.isLocalGiven )
			{
				strcpy(pOutputFileName, p.localName);
			}
			else
			{
				strcpy(pOutputFileName, s_en);
			}

			strcat(pOutputFileName, s_txtExten);

			break;
		}
	case CmdLineParams::INMEM_LOCALMSG:
		{
			strcpy(pOutputFileName, DATA_FILE_NAME);
			break;
		}

	case CmdLineParams::NLS_LOCALMSG:
		{
			strcpy(pOutputFileName,s_xalanMsgFileName);

			if (p.isLocalGiven )
			{
				strncat(pOutputFileName, p.localName,6);
			}
			else
			{
				strncat(pOutputFileName, s_en,3);
			}

			strcat(pOutputFileName, s_msgExten);

			break;
		}
	default:
		{
			// in that stage the local should be defined
			assert ( 0 );
		}
	}
	return pOutputFileName;
}

// ---------------------------------------------------------------------------
//  Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{

#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	CmdLineParams	theParams;
	int iReturnValue = 0;
	const char* errorMessage = 0;
	if (getArgs(argC, argV, theParams, &errorMessage) == false)
	{
		if ( errorMessage != 0)
		{
			cerr << errorMessage;
		}
		usage();
		iReturnValue = 1;

	}
	else
	{

		try
		{
			XMLPlatformUtils::Initialize();
		}

		catch (const XMLException& toCatch)
		{
			cerr << "Error during initialization! :\n"
				<< StrX(toCatch.getMessage()) << endl;
			iReturnValue = 2;
		}
		if (iReturnValue == 0)
		{

			{	//  Create a SAX parser object.
				SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();

				parser->setFeature(XMLUni::fgSAX2CoreValidation, false);

				parser->setFeature(XMLUni::fgXercesDynamic, true);

				parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, false);

				parser->setFeature(XMLUni::fgXercesSchema, true);

				parser->setFeature(XMLUni::fgXercesSchemaFullChecking, false);

				parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, false);

				//  Create the handler object and install it as the document and error
				//  handler for the parser. Then parse the file and catch any exceptions
				//  that propogate out
				//

				int errorCount = 0;

				char* const		fileName = buildInputFileName(theParams);

				char* const		pOutputFileName = buildOutputFileName(theParams);

				SAX2Handler* handler = 0;
				try
				{
					switch(theParams.enTypeOfLocalMsg){
					case CmdLineParams::ICU_LOCALMSG:
						{
							handler = new ICUResHandler(pOutputFileName);
							break;
						}
					case CmdLineParams::INMEM_LOCALMSG:
						{
							handler = new InMemHandler(pOutputFileName);
							break;
						}
					case CmdLineParams::NLS_LOCALMSG:
						{
							handler = new NLSHandler(pOutputFileName);
							break;
						}
					default:
						{
							assert (0);
						}
					}
				}

				catch(const XalanFileOutputStream::XalanFileOutputStreamOpenException& e)
				{
					cerr << "\nAn error occurred\n  Error: ";
					if (e.m_pMessage != 0)
					{
						cerr << e.m_pMessage <<  endl;
					}
					else
					{
						cerr << "unknown (XalanFileOutputStreamOpenException) " << "\n" << endl;

					}

					iReturnValue = 4;

				}
				catch(const XalanFileOutputStream::XalanFileOutputStreamWriteException& e)
				{
					cerr << "\nAn error occurred\n  Error: ";
					if (e.m_pMessage != 0)
					{
						cerr << e.m_pMessage << endl;
					}
					else
					{
						cerr << "unknown (XalanFileOutputStreamWriteException) " << "\n" << endl;

					}

					iReturnValue = 5;

				}
				catch (...)
				{
					cerr << "Unknown error occured." << endl;
					iReturnValue = 6;
				}

				// run the parser
				if ( iReturnValue == 0)
				{
					try
					{
						if ( theParams.isLocalGiven == true )
						{
							handler->setXML_Lang(theParams.localName);
						}

						parser->setContentHandler(handler);

						parser->setErrorHandler(handler);

						parser->parse(fileName);

						errorCount = parser->getErrorCount();
					}

					catch (const XMLException& toCatch)
					{
						cerr << "\nAn error occurred\n  Error: "
							<< StrX(toCatch.getMessage())
							<< "\n" << endl;
						iReturnValue = 7;
					}
					catch (...)
					{
						cerr << endl << "General error occured." << endl;
						iReturnValue = 8;
					}
				}

				delete handler;

				delete[] pOutputFileName;

				delete[] fileName;
				//
				//  Delete the parser itself.  Must be done prior to calling Terminate, below.
				//
				delete parser;

				if (errorCount != 0)
					iReturnValue = 9;

			}
			// And call the termination method
			XMLPlatformUtils::Terminate();

		}

	}
	return iReturnValue;
}

<|endoftext|>


<commit_before>/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 *
 * @author David N. Bertoni (david_n_bertoni@lotus.com)
 * */

// Base class header file.
#include "ProblemListenerDefault.hpp"

#include <xalanc/XalanDOM/XalanNode.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/PrintWriter.hpp>
#include <xalanc/PlatformSupport/XalanMessageLoader.hpp>

#include <xalanc/XSLT/ElemTemplateElement.hpp>

XALAN_CPP_NAMESPACE_BEGIN

static const char* const	xslHeader = "XSLT ";
static const char* const	xmlHeader = "XML ";
static const char* const	xpathHeader = "XPath ";

static const char* const	uriHeader = "";

static const char* const	locationOpen = " (";
static const char* const	locationClose = ")";

ProblemListenerDefault::ProblemListenerDefault(PrintWriter*		pw) :
	ProblemListener(),
	m_pw(pw)
{
}

ProblemListenerDefault::~ProblemListenerDefault()
{
}

void
ProblemListenerDefault::setPrintWriter(PrintWriter*		pw)
{
	m_pw = pw;
}

void
ProblemListenerDefault::problem(
			eProblemSource				where,
			eClassification				classification,
			const XalanNode*			sourceNode,
			const ElemTemplateElement*	styleNode,
			const XalanDOMString&		msg,
			const XalanDOMChar*			uri,
			int							lineNo,
			int							charOffset)
{
	if (m_pw != 0)
	{
		problem(*m_pw, where, classification, sourceNode, styleNode, msg, uri, lineNo, charOffset);
	}
}

void
ProblemListenerDefault::problem(
			PrintWriter&				pw,
			eProblemSource				where,
			eClassification				classification,
			const XalanNode*			sourceNode,
			const ElemTemplateElement*	styleNode,
			const XalanDOMString&		msg,
			const XalanDOMChar*			uri,
			int							lineNo,
			int							charOffset)
{
	if (eXMLPARSER == where)
	{
		pw.print(xmlHeader);
	}
	else if (eXPATH == where)
	{
		pw.print(xpathHeader);
	}
	else
	{
		pw.print(xslHeader);
	}

	if (eERROR == classification)
	{
		pw.print(XalanMessageLoader::getMessage(XalanMessages::Error_1Param, msg));
	}
	else if (eWARNING == classification)
	{
		pw.print(XalanMessageLoader::getMessage(XalanMessages::Warning_1Param, msg));
	}
	else
	{
		pw.print(XalanMessageLoader::getMessage(XalanMessages::Message_1Param, msg));
	}

	if (0 != styleNode)
	{
		pw.print(XalanMessageLoader::getMessage(XalanMessages::StyleTreeNode_1Param, styleNode->getElementName()));
	}

	if (0 != sourceNode)
	{
		pw.print(XalanMessageLoader::getMessage(XalanMessages::SourceTreeNode_1Param, sourceNode->getNodeName()));
	}

	pw.print(locationOpen);

	if (0 != uri)
	{
		pw.print(uriHeader);
		pw.print(uri);
	}

	const XalanDOMString lineNoString = LongToDOMString(lineNo);

	const XalanDOMString charOffsetString = LongToDOMString(charOffset);

	pw.print(XalanMessageLoader::getMessage(XalanMessages::LineNumberColumnNumber_2Params, lineNoString , charOffsetString));

	pw.print(locationClose);

	pw.println();
}

XALAN_CPP_NAMESPACE_END
<commit_msg>Use static UTF-16 strings, rather than rely on code page transcoding.<commit_after>/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 *
 * @author David N. Bertoni (david_n_bertoni@lotus.com)
 * */

// Base class header file.
#include "ProblemListenerDefault.hpp"

#include <xalanc/XalanDOM/XalanNode.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/PrintWriter.hpp>
#include <xalanc/PlatformSupport/XalanMessageLoader.hpp>

#include <xalanc/XSLT/ElemTemplateElement.hpp>

XALAN_CPP_NAMESPACE_BEGIN

static const XalanDOMChar	xsltHeader[] =
{
	XalanUnicode::charLetter_X,
	XalanUnicode::charLetter_S,
	XalanUnicode::charLetter_L,
	XalanUnicode::charLetter_T,
	XalanUnicode::charSpace,
	0
};

static const XalanDOMChar	xmlHeader[] =
{
	XalanUnicode::charLetter_X,
	XalanUnicode::charLetter_M,
	XalanUnicode::charLetter_L,
	XalanUnicode::charSpace,
	0
};

static const XalanDOMChar	xpathHeader[] =
{
	XalanUnicode::charLetter_X,
	XalanUnicode::charLetter_P,
	XalanUnicode::charLetter_a,
	XalanUnicode::charLetter_t,
	XalanUnicode::charLetter_h,
	XalanUnicode::charSpace,
	0
};

static const XalanDOMChar	uriHeader[] =
{
	0
};

static const XalanDOMChar	uriSeparator[] =
{
	XalanUnicode::charComma,
	XalanUnicode::charSpace,
	0
};

static const XalanDOMChar	locationOpen[] =
{
	XalanUnicode::charSpace,
	XalanUnicode::charLeftParenthesis,
	0
};

static const XalanDOMChar	locationClose[] =
{
	XalanUnicode::charRightParenthesis,
	0
};

ProblemListenerDefault::ProblemListenerDefault(PrintWriter*		pw) :
	ProblemListener(),
	m_pw(pw)
{
}

ProblemListenerDefault::~ProblemListenerDefault()
{
}

void
ProblemListenerDefault::setPrintWriter(PrintWriter*		pw)
{
	m_pw = pw;
}

void
ProblemListenerDefault::problem(
			eProblemSource				where,
			eClassification				classification,
			const XalanNode*			sourceNode,
			const ElemTemplateElement*	styleNode,
			const XalanDOMString&		msg,
			const XalanDOMChar*			uri,
			int							lineNo,
			int							charOffset)
{
	if (m_pw != 0)
	{
		problem(*m_pw, where, classification, sourceNode, styleNode, msg, uri, lineNo, charOffset);
	}
}

void
ProblemListenerDefault::problem(
			PrintWriter&				pw,
			eProblemSource				where,
			eClassification				classification,
			const XalanNode*			sourceNode,
			const ElemTemplateElement*	styleNode,
			const XalanDOMString&		msg,
			const XalanDOMChar*			uri,
			int							lineNo,
			int							charOffset)
{
	if (eXMLPARSER == where)
	{
		pw.print(xmlHeader);
	}
	else if (eXPATH == where)
	{
		pw.print(xpathHeader);
	}
	else
	{
		pw.print(xsltHeader);
	}

	if (eERROR == classification)
	{
		pw.print(XalanMessageLoader::getMessage(XalanMessages::Error_1Param, msg));
	}
	else if (eWARNING == classification)
	{
		pw.print(XalanMessageLoader::getMessage(XalanMessages::Warning_1Param, msg));
	}
	else
	{
		pw.print(XalanMessageLoader::getMessage(XalanMessages::Message_1Param, msg));
	}

	pw.write(XalanDOMChar(XalanUnicode::charSpace));

	if (0 != styleNode)
	{
		pw.print(XalanMessageLoader::getMessage(XalanMessages::StyleTreeNode_1Param, styleNode->getElementName()));
	}

	if (0 != sourceNode)
	{
		pw.print(XalanMessageLoader::getMessage(XalanMessages::SourceTreeNode_1Param, sourceNode->getNodeName()));
	}

	pw.print(locationOpen);

	if (0 != uri)
	{
		pw.print(uri);
		pw.print(uriSeparator);
	}

	const XalanDOMString lineNoString = LongToDOMString(lineNo);

	const XalanDOMString charOffsetString = LongToDOMString(charOffset);

	pw.print(XalanMessageLoader::getMessage(XalanMessages::LineNumberColumnNumber_2Params, lineNoString , charOffsetString));

	pw.print(locationClose);

	pw.println();
}

XALAN_CPP_NAMESPACE_END
<|endoftext|>


<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
 * Copyright (C) 2006 Artem Pavlenko
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#ifndef AGG_RENDERER_HPP
#define AGG_RENDERER_HPP

#include "feature_style_processor.hpp"

namespace mapnik
{
    struct agg_renderer : public feature_style_processor<agg_renderer>
    {
	agg_renderer(Map const& m, Image32 & pixmap);
	void process(point_symbolizer const& sym,Feature const& feature);
	void process(line_symbolizer const& sym,Feature const& feature);
	void process(line_pattern_symbolizer const& sym,Feature const& feature);
	void process(polygon_symbolizer const& sym,Feature const& feature);
	void process(polygon_pattern_symbolizer const& sym,Feature const& feature);
	void process(raster_symbolizer const& sym,Feature const& feature);
    private:
	Image32 & pixmap_;
	CoordTransform t_;
    };
}

#endif //AGG_RENDERER_HPP
<commit_msg>make agg_renderer non-copyable<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
 * Copyright (C) 2006 Artem Pavlenko
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#ifndef AGG_RENDERER_HPP
#define AGG_RENDERER_HPP

#include "feature_style_processor.hpp"
#include <boost/utility.hpp>

namespace mapnik
{
    struct agg_renderer : public feature_style_processor<agg_renderer>,
			  private boost::noncopyable
    {
	agg_renderer(Map const& m, Image32 & pixmap);
	void process(point_symbolizer const& sym,Feature const& feature);
	void process(line_symbolizer const& sym,Feature const& feature);
	void process(line_pattern_symbolizer const& sym,Feature const& feature);
	void process(polygon_symbolizer const& sym,Feature const& feature);
	void process(polygon_pattern_symbolizer const& sym,Feature const& feature);
	void process(raster_symbolizer const& sym,Feature const& feature);
    private:
	Image32 & pixmap_;
	CoordTransform t_;
    };
}

#endif //AGG_RENDERER_HPP
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef AST_POSITION_H
#define AST_POSITION_H

#include <string>
#include <ostream>

namespace eddic {

namespace ast {

/*!
 * \struct Position
 * \brief Define a position in the source code.
 */
struct Position {
    std::string file;       /*!< The source file */
    std::string theLine;    /*!< The source line content */
    int line;               /*!< The source line number */
    int column;             /*!< The source column number */
};

std::ostream& operator<< (std::ostream& stream, Position position);

bool operator==(const ast::Position& a, const ast::Position& b);
bool operator!=(const ast::Position& a, const ast::Position& b);

} //end of ast

} //end of eddic

#endif
<commit_msg>revert<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef AST_POSITION_H
#define AST_POSITION_H

#include <string>
#include <ostream>

#include <boost/range/iterator_range.hpp>

namespace eddic {

namespace ast {

/*!
 * \struct Position
 * \brief Define a position in the source code.
 */
struct Position {
    std::string file;       /*!< The source file */
    std::string theLine;    /*!< The source line content */
    int line;               /*!< The source line number */
    int column;             /*!< The source column number */
};

std::ostream& operator<< (std::ostream& stream, Position position);

bool operator==(const ast::Position& a, const ast::Position& b);
bool operator!=(const ast::Position& a, const ast::Position& b);

} //end of ast

} //end of eddic

#endif
<|endoftext|>


<commit_before>#pragma once

///////////////////////////////////////////////////////////////////////////////
/// @file Bun.hpp
/// @author BrainlessLabs
/// @version 0.3
/// @brief The include file for Bun ORM. This file includes all the source
///        to make the class/struct persist in sqlite. Users need to include
///        only this file.
///////////////////////////////////////////////////////////////////////////////
#include <string>
#include <boost/preprocessor.hpp>
#include <third_party/fmt/format.hpp>
#include "blib/bun/BunHelper.hpp"
#include "blib/bun/DbBackend.hpp"
#include "blib/bun/DbLogger.hpp"
#include "blib/bun/CppTypeToSQLString.hpp"

///////////////////////////////////////////////////////////////////////////////
/// @basic Basic Persistance Start
/// @details We will be using the Bun class for all the examples and
///          understanding
///          struct Bun {
///            std::string bun_name,
///            float sugar_quantity;
///            float flour_quantity;
///            float milk_quantity;
///            float yeast_quantity;
///            float butter_quantity;
///            int bun_length;
///          };
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
/// Helper Macros Start
///////////////////////////////////////////////////////////////////////////////

/// @brief createSchema Helper Macros
/// @details We need to pass only the data members as a tuple to this macro
/// @param ELEMS_TUP = (bun_name, sugar_quantity, flour_quantity, milk_quantity, yeast_quantity, butter_quantity, bun_length)
/// @brief Expands the class members for CREATE TABLE
#define EXPAND_CLASS_MEMBERS_createSchema_I(z, n, ELEMS_TUP) BOOST_STRINGIZE(BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP)) " {}"
#define EXPAND_CLASS_MEMBERS_createSchema(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_CLASS_MEMBERS_createSchema_I, ELEMS_TUP)

/// @brief Expands the class members for CREATE TABLE to get the type info
#define EXPAND_CLASS_TYPE_MEMBERS_createSchema_I(z, n, CLASS_ELEMS_TUP) BOOST_PP_COMMA_IF(n) blib::bun::cppTypeToDbTypeString<decltype(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)::BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(n,1), CLASS_ELEMS_TUP))>()
#define EXPAND_CLASS_TYPE_MEMBERS_createSchema(CLASS_ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_SUB(BOOST_PP_TUPLE_SIZE(CLASS_ELEMS_TUP), 1), EXPAND_CLASS_TYPE_MEMBERS_createSchema_I, CLASS_ELEMS_TUP)

/// @brief persistObj Helper Macros
/// @brief Changes related to INSERT INTO
/// @brief EXPAND_CLASS_TYPE_MEMBERS_persistObj
#define EXPAND_FIELDS_persistObj_I(z, n, ELEMS_TUP) BOOST_PP_IDENTITY(",")() BOOST_STRINGIZE(BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP))
#define EXPAND_FIELDS_persistObj(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_FIELDS_persistObj_I, ELEMS_TUP)

/// @brief Expand the variables for persistObj
#define EXPAND_VARIABLES_persistObj_I(z, n, ELEMS_TUP) BOOST_PP_COMMA_IF(n)obj->BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP)
#define EXPAND_VARIABLES_persistObj(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_VARIABLES_persistObj_I, ELEMS_TUP)

/// @brief updateObj Helper Macros
/// @brief Changes related to UPDATE table SET
/// @brief Expand the braces for updateObj
#define EXPAND_BRACES_updateObj_I(z, n, ELEMS_TUP) BOOST_PP_EXPR_IF(n, ",")BOOST_STRINGIZE({} = {})
#define EXPAND_BRACES_updateObj(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_BRACES_updateObj_I, ELEMS_TUP)

/// @brief Expand the variables for updateObj
#define EXPAND_VARIABLES_updateObj_I(z, n, ELEMS_TUP) BOOST_PP_COMMA()BOOST_STRINGIZE(BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP))BOOST_PP_COMMA()obj->BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP)
#define EXPAND_VARIABLES_updateObj(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_VARIABLES_updateObj_I, ELEMS_TUP)

/// @brief Create n number of string
#define Repeat_N_String_With_Precomma_I(z, n, text)  BOOST_PP_IDENTITY(",")() BOOST_STRINGIZE(text)
#define Repeat_N_String_With_Precomma(n, text) BOOST_PP_REPEAT(n, Repeat_N_String_With_Precomma_I, text)

#define BLIB_MACRO_COMMENTS_IF(a) BOOST_PP_EXPR_IF(1, a)

///////////////////////////////////////////////////////////////////////////////
/// Helper Macros End
///////////////////////////////////////////////////////////////////////////////
/// SPECIALIZE_BUN_HELPER Start
#define SPECIALIZE_BUN_HELPER(CLASS_ELEMS_TUP) namespace blib{namespace bun{\
template<>\
struct BunHelper<BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)>{\
using ClassType = BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP);\
\
inline static void createSchema(){\
BLIB_MACRO_COMMENTS_IF("@brief createSchema for creating the schema of an object");\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
static std::string const query = "CREATE TABLE IF NOT EXISTS '{}' (oid_high INTEGER PRIMARY KEY AUTOINCREMENT, oid_low INTEGER NOT NULL" \
EXPAND_CLASS_MEMBERS_createSchema(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP )) \
 ")";\
static std::string const sql = fmt::format(query, class_name, EXPAND_CLASS_TYPE_MEMBERS_createSchema(CLASS_ELEMS_TUP));\
l().info(sql);\
}\
\
inline static void deleteSchema(){\
BLIB_MACRO_COMMENTS_IF("@brief deleteSchema for deleting the schema of an object");\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
static std::string const sql = fmt::format("DROP TABLE '{}'", class_name);\
}\
\
inline static SimpleOID persistObj( T* obj ){\
BLIB_MACRO_COMMENTS_IF("@brief persistObj for persisting the object");\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
SimpleOID oid;\
oid.populateLow();\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
static std::string const query = "INSERT INTO '{}' (oid_low" \
EXPAND_FIELDS_persistObj(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP ))\
") VALUES ({}" \
Repeat_N_String_With_Precomma(BOOST_PP_TUPLE_SIZE(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP )), {})\
;\
std::string const sql = fmt::format(query, class_name, oid.low,\
EXPAND_VARIABLES_persistObj(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP ))\
);\
return oid;\
}\
inline static void updateObj( T* obj, SimpleOID const& oid ){\
BLIB_MACRO_COMMENTS_IF("@brief updateObj for updating a persisted object");\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
static std::string const query = "UPDATE {} SET " \
EXPAND_BRACES_updateObj(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP )) \
" WHERE oid_low={} AND oid_high={}";\
static std::string const sql = fmt::format(query, class_name \
EXPAND_VARIABLES_updateObj(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP )) \
,oid.low, oid.high);\
}\
};\
}\
}\

/// SPECIALIZE_BUN_HELPER End

///////////////////////////////////////////////////////////////////////////////
/// @basic Basic Persistance End
///////////////////////////////////////////////////////////////////////////////<commit_msg>deleteObj string generations are complete.<commit_after>#pragma once

///////////////////////////////////////////////////////////////////////////////
/// @file Bun.hpp
/// @author BrainlessLabs
/// @version 0.3
/// @brief The include file for Bun ORM. This file includes all the source
///        to make the class/struct persist in sqlite. Users need to include
///        only this file.
///////////////////////////////////////////////////////////////////////////////
#include <string>
#include <boost/preprocessor.hpp>
#include <third_party/fmt/format.hpp>
#include "blib/bun/BunHelper.hpp"
#include "blib/bun/DbBackend.hpp"
#include "blib/bun/DbLogger.hpp"
#include "blib/bun/CppTypeToSQLString.hpp"

///////////////////////////////////////////////////////////////////////////////
/// @basic Basic Persistance Start
/// @details We will be using the Bun class for all the examples and
///          understanding
///          struct Bun {
///            std::string bun_name,
///            float sugar_quantity;
///            float flour_quantity;
///            float milk_quantity;
///            float yeast_quantity;
///            float butter_quantity;
///            int bun_length;
///          };
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
/// Helper Macros Start
///////////////////////////////////////////////////////////////////////////////

/// @brief createSchema Helper Macros
/// @details We need to pass only the data members as a tuple to this macro
/// @param ELEMS_TUP = (bun_name, sugar_quantity, flour_quantity, milk_quantity, yeast_quantity, butter_quantity, bun_length)
/// @brief Expands the class members for CREATE TABLE
#define EXPAND_CLASS_MEMBERS_createSchema_I(z, n, ELEMS_TUP) BOOST_STRINGIZE(BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP)) " {}"
#define EXPAND_CLASS_MEMBERS_createSchema(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_CLASS_MEMBERS_createSchema_I, ELEMS_TUP)

/// @brief Expands the class members for CREATE TABLE to get the type info
#define EXPAND_CLASS_TYPE_MEMBERS_createSchema_I(z, n, CLASS_ELEMS_TUP) BOOST_PP_COMMA_IF(n) blib::bun::cppTypeToDbTypeString<decltype(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)::BOOST_PP_TUPLE_ELEM(BOOST_PP_ADD(n,1), CLASS_ELEMS_TUP))>()
#define EXPAND_CLASS_TYPE_MEMBERS_createSchema(CLASS_ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_SUB(BOOST_PP_TUPLE_SIZE(CLASS_ELEMS_TUP), 1), EXPAND_CLASS_TYPE_MEMBERS_createSchema_I, CLASS_ELEMS_TUP)

/// @brief persistObj Helper Macros
/// @brief Changes related to INSERT INTO
/// @brief EXPAND_CLASS_TYPE_MEMBERS_persistObj
#define EXPAND_FIELDS_persistObj_I(z, n, ELEMS_TUP) BOOST_PP_IDENTITY(",")() BOOST_STRINGIZE(BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP))
#define EXPAND_FIELDS_persistObj(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_FIELDS_persistObj_I, ELEMS_TUP)

/// @brief Expand the variables for persistObj
#define EXPAND_VARIABLES_persistObj_I(z, n, ELEMS_TUP) BOOST_PP_COMMA_IF(n)obj->BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP)
#define EXPAND_VARIABLES_persistObj(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_VARIABLES_persistObj_I, ELEMS_TUP)

/// @brief updateObj Helper Macros
/// @brief Changes related to UPDATE table SET
/// @brief Expand the braces for updateObj
#define EXPAND_BRACES_updateObj_I(z, n, ELEMS_TUP) BOOST_PP_EXPR_IF(n, ",")BOOST_STRINGIZE({} = {})
#define EXPAND_BRACES_updateObj(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_BRACES_updateObj_I, ELEMS_TUP)

/// @brief Expand the variables for updateObj
#define EXPAND_VARIABLES_updateObj_I(z, n, ELEMS_TUP) BOOST_PP_COMMA()BOOST_STRINGIZE(BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP))BOOST_PP_COMMA()obj->BOOST_PP_TUPLE_ELEM(n, ELEMS_TUP)
#define EXPAND_VARIABLES_updateObj(ELEMS_TUP) BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(ELEMS_TUP), EXPAND_VARIABLES_updateObj_I, ELEMS_TUP)

/// @brief Create n number of string
#define Repeat_N_String_With_Precomma_I(z, n, text)  BOOST_PP_IDENTITY(",")() BOOST_STRINGIZE(text)
#define Repeat_N_String_With_Precomma(n, text) BOOST_PP_REPEAT(n, Repeat_N_String_With_Precomma_I, text)

#define BLIB_MACRO_COMMENTS_IF(a) BOOST_PP_EXPR_IF(1, a)

///////////////////////////////////////////////////////////////////////////////
/// Helper Macros End
///////////////////////////////////////////////////////////////////////////////
/// SPECIALIZE_BUN_HELPER Start
#define SPECIALIZE_BUN_HELPER(CLASS_ELEMS_TUP) namespace blib{namespace bun{\
template<>\
struct BunHelper<BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP)>{\
using ClassType = BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP);\
\
inline static void createSchema(){\
BLIB_MACRO_COMMENTS_IF("@brief createSchema for creating the schema of an object");\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
static std::string const query = "CREATE TABLE IF NOT EXISTS '{}' (oid_high INTEGER PRIMARY KEY AUTOINCREMENT, oid_low INTEGER NOT NULL" \
EXPAND_CLASS_MEMBERS_createSchema(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP )) \
 ")";\
static std::string const sql = fmt::format(query, class_name, EXPAND_CLASS_TYPE_MEMBERS_createSchema(CLASS_ELEMS_TUP));\
l().info(sql);\
}\
\
inline static void deleteSchema(){\
BLIB_MACRO_COMMENTS_IF("@brief deleteSchema for deleting the schema of an object");\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
static std::string const sql = fmt::format("DROP TABLE '{}'", class_name);\
}\
\
inline static SimpleOID persistObj( T* obj ){\
BLIB_MACRO_COMMENTS_IF("@brief persistObj for persisting the object");\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
SimpleOID oid;\
oid.populateLow();\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
static std::string const query = "INSERT INTO '{}' (oid_low" \
EXPAND_FIELDS_persistObj(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP ))\
") VALUES ({}" \
Repeat_N_String_With_Precomma(BOOST_PP_TUPLE_SIZE(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP )), {})\
;\
std::string const sql = fmt::format(query, class_name, oid.low,\
EXPAND_VARIABLES_persistObj(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP ))\
);\
return oid;\
}\
inline static void updateObj( T* obj, SimpleOID const& oid ){\
BLIB_MACRO_COMMENTS_IF("@brief updateObj for updating a persisted object");\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
static std::string const query = "UPDATE {} SET " \
EXPAND_BRACES_updateObj(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP )) \
" WHERE oid_low={} AND oid_high={}";\
std::string const sql = fmt::format(query, class_name \
EXPAND_VARIABLES_updateObj(BOOST_PP_TUPLE_POP_FRONT( CLASS_ELEMS_TUP )) \
,oid.low, oid.high);\
}\
inline static void deleteObj( SimpleOID const& oid ){\
BLIB_MACRO_COMMENTS_IF("@brief deleteObj for deleting a persisted object");\
static std::string const class_name = BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, CLASS_ELEMS_TUP));\
static std::string const query = "DELETE FROM {} WHERE oid_high={} AND oid_low={}";\
std::string const sql = fmt::format(query, class_name, oid.high, oid.low);\
}\
};\
}\
}\

/// SPECIALIZE_BUN_HELPER End

///////////////////////////////////////////////////////////////////////////////
/// @basic Basic Persistance End
///////////////////////////////////////////////////////////////////////////////<|endoftext|>