<commit_before>#ifndef REFLECTION_BINDING_HPP
#define REFLECTION_BINDING_HPP

#include <string>
#include <type_traits>
#include <utility>

#include "any.hpp"
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
#include <type_list.hpp>
#include <void_t.hpp>

namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
// conversion signature
typedef any (*conversion_binding_signature)(const any&);
// string serialize signature
typedef std::string (*string_serialization_signature)(const any&);
// string deserialization signature
typedef any (*string_deserialization_signature)(const std::string&);
// address of signature
typedef any (*address_of_signature)(any&);
// dereference signature
typedef any (*dereference_signature)(any&);

////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct

namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
    // dispatch: unpacks argument type list and sequence to correctly index into
    // argument array and call get with the right types to retrieve raw values
    // from the anys
    template <class FunctionPointerType,
              FunctionPointerType FunctionPointerValue,
              class... ArgTypes,
              std::size_t... ArgSeq>
    static any
    dispatch(any* argument_array,
             metamusil::t_list::type_list<ArgTypes...>,
             std::index_sequence<ArgSeq...>)
    {
        // necessary to remove reference from types as any only stores
        // unqualified types, ie values only
        return FunctionPointerValue(
            argument_array[ArgSeq]
                .get<typename std::remove_reference_t<ArgTypes>>()...);
    }
};

template <>
struct return_type_specializer<void>
{
    // dispatch: unpacks argument type list and sequence to correctly index into
    // argument array and call get with the right types to retrieve raw values
    // from the anys
    template <class FunctionPointerType,
              FunctionPointerType FunctionPointerValue,
              class... ArgTypes,
              std::size_t... ArgSeq>
    static any
    dispatch(any* argument_array,
             metamusil::t_list::type_list<ArgTypes...>,
             std::index_sequence<ArgSeq...>)
    {
        // necessary to remove reference from types as any only stores
        // unqualified types, ie values only
        FunctionPointerValue(
            argument_array[ArgSeq]
                .get<typename std::remove_reference_t<ArgTypes>>()...);

        // return empty any, ie 'void'
        return any();
    }
};

// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
    typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
    typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
        parameter_types;
    // make integer sequence from type list
    typedef metamusil::t_list::index_sequence_for_t<parameter_types>
        parameter_sequence;

    return return_type_specializer<return_type>::
        template dispatch<FunctionPointerType, FunctionPointerValue>(
            argument_array, parameter_types(), parameter_sequence());
}
} // namespace free_function_detail

namespace member_function_detail
{

template <class ReturnType>
struct return_type_specializer
{
    template <class MemFunPointerType,
              MemFunPointerType MemFunPointerValue,
              class ObjectType,
              class... ParamTypes,
              std::size_t... ParamSequence>
    static any
    dispatch(any& object,
             any* argument_array,
             metamusil::t_list::type_list<ParamTypes...>,
             std::index_sequence<ParamSequence...>)
    {
        return (object.get<ObjectType>().*MemFunPointerValue)(
            argument_array[ParamSequence]
                .get<std::remove_reference_t<ParamTypes>>()...);
    }
};

template <>
struct return_type_specializer<void>
{
    template <class MemFunPointerType,
              MemFunPointerType MemFunPointerValue,
              class ObjectType,
              class... ParamTypes,
              std::size_t... ParamSequence>
    static any
    dispatch(any& object,
             any* argument_array,
             metamusil::t_list::type_list<ParamTypes...>,
             std::index_sequence<ParamSequence...>)
    {
        (object.get<ObjectType>().*MemFunPointerValue)(
            argument_array[ParamSequence]
                .get<std::remove_reference_t<ParamTypes>>()...);

        return any();
    }
};

template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
    // deduce return type
    typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;

    // deduce parameter types
    typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
        parameter_types;

    // make integer sequence from parameter type list
    typedef metamusil::t_list::index_sequence_for_t<parameter_types>
        parameter_sequence;

    // deduce object type
    typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;

    return return_type_specializer<return_type>::
        template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
            object, argument_array, parameter_types(), parameter_sequence());
}
} // namespace member_function_detail

namespace member_variable_detail
{

template <class MemVarPointerType,
          MemVarPointerType MemVarPointerValue,
          class ObjectType,
          class MemVarType>
any
get_dispatch(const any& object)
{
    return (object.get<ObjectType>().*MemVarPointerValue);
}

template <class MemVarPointerType,
          MemVarPointerType MemVarPointerValue,
          class ObjectType,
          class MemVarType>
void
set_dispatch(any& object, const any& value)
{
    (object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}

template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
    typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
        object_type;
    typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
        member_variable_type;

    return get_dispatch<MemVarPointerType,
                        MemVarPointerValue,
                        object_type,
                        member_variable_type>(object);
}

template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
    typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
        object_type;
    typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
        member_variable_type;

    return set_dispatch<MemVarPointerType,
                        MemVarPointerValue,
                        object_type,
                        member_variable_type>(object, value);
}
} // namespace member_variable_detail

namespace constructor_detail
{

// purpose of braced_init_selector is to attempt to use constructor T(...) if
// available, otherwise fall back to braced init list initialization
template <class, class T, class... ParamTypes>
struct braced_init_selector_impl
{
    template <std::size_t... Seq>
    static any
    constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
    {
        any out =
            T{argument_array[Seq]
                  .get<typename std::remove_reference<ParamTypes>::type>()...};
        return out;
    }
};

template <class T, class... ParamTypes>
struct braced_init_selector_impl<
    metamusil::void_t<decltype(T(std::declval<ParamTypes>()...))>,
    T,
    ParamTypes...>
{
    template <std::size_t... Seq>
    static any
    constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
    {
        any out =
            T(argument_array[Seq]
                  .get<typename std::remove_reference<ParamTypes>::type>()...);
        return out;
    }
};

template <class T, class... ParamTypes>
using braced_init_selector = braced_init_selector_impl<void, T, ParamTypes...>;

template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
    typedef std::index_sequence_for<ParamTypes...> param_sequence;

    return braced_init_selector<T, ParamTypes...>::constructor_dispatch(
        argument_array, param_sequence());
}
} // namespace constructor_detail

namespace conversion_detail
{
template <class TargetType, class SourceType, class = void>
struct conversion_specializer;

template <>
struct conversion_specializer<void, void>;

template <class TargetType, class SourceType>
struct conversion_specializer<
    TargetType,
    SourceType,
    std::enable_if_t<std::is_convertible<SourceType, TargetType>::value>>
{
    static any
    dispatch(const any& src)
    {
        TargetType temp = static_cast<TargetType>(src.get<SourceType>());
        return temp;
    }
};

template <class TargetType, class SourceType>
any
generic_conversion_bind_point(const any& src)
{
    return conversion_specializer<TargetType, SourceType>::dispatch(src);
}
} // namespace conversion_detail

namespace string_serialization_detail
{

template <class T, class = void>
struct string_serialize_type_selector;

template <class T>
struct string_serialize_type_selector<
    T,
    std::enable_if_t<std::is_arithmetic<T>::value>>
{
    static std::string
    dispatch(const any& value)
    {
        return std::to_string(value.get<T>());
    }
};

template <>
struct string_serialize_type_selector<std::string>
{
    static std::string
    dispatch(const any& value)
    {
        return value.get<std::string>();
    }
};

template <>
struct string_serialize_type_selector<char>
{
    static std::string
    dispatch(const any& value)
    {
        std::string out;
        out.push_back(value.get<char>());
        return out;
    }
};

template <>
struct string_serialize_type_selector<void>
{
    static std::string
    dispatch(const any&)
    {
        return "empty";
    }
};

template <class T>
std::string
generic_string_serialization_bind_point(const any& value)
{
    return string_serialize_type_selector<T>::dispatch(value);
}

template <class T, class = void>
struct string_deserialize_type_selector;

template <class T>
struct string_deserialize_type_selector<
    T,
    std::enable_if_t<std::is_arithmetic<T>::value>>
{
    static any
    dispatch(const std::string& str_value)
    {
        T out = std::stold(str_value);
        return out;
    }
};

template <>
struct string_deserialize_type_selector<char>
{
    static any
    dispatch(const std::string& str_value)
    {
        return str_value[0];
    }
};

template <>
struct string_deserialize_type_selector<std::string>
{
    static any
    dispatch(const std::string& str_value)
    {
        return str_value;
    }
};

template <>
struct string_deserialize_type_selector<int>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stoi(str_value);
    }
};

template <>
struct string_deserialize_type_selector<long>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stol(str_value);
    }
};

template <>
struct string_deserialize_type_selector<long long>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stoll(str_value);
    }
};

template <>
struct string_deserialize_type_selector<unsigned long>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stoul(str_value);
    }
};

template <>
struct string_deserialize_type_selector<unsigned long long>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stoull(str_value);
    }
};

template <>
struct string_deserialize_type_selector<float>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stof(str_value);
    }
};

template <>
struct string_deserialize_type_selector<double>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stod(str_value);
    }
};

template <>
struct string_deserialize_type_selector<long double>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stold(str_value);
    }
};

template <>
struct string_deserialize_type_selector<void>
{
    static any
    dispatch(const std::string&)
    {
        return shadow::any();
    }
};

template <class T>
any
generic_string_deserialization_bind_point(const std::string& str_value)
{
    return string_deserialize_type_selector<T>::dispatch(str_value);
}
} // namespace string_serialization_detail

namespace pointer_detail
{
template <class T>
inline any
generic_address_of_bind_point(any& value)
{
    return any(&(value.get<T>()));
}

template <>
inline any
generic_address_of_bind_point<void>(any&)
{
    return any(nullptr);
}

template <class T>
inline any
generic_dereference_bind_point(any& value)
{
    return any(*(value.get<T*>()));
}

template <>
inline any
generic_dereference_bind_point<void>(any&)
{
    return any();
}

} // namespace pointer_detail

} // namespace shadow

#endif
<commit_msg>Use ostream operator<< for arithmetic types in generic_string_serialization_bind_point. 	modified:   include/reflection_binding.hpp<commit_after>#ifndef REFLECTION_BINDING_HPP
#define REFLECTION_BINDING_HPP

#include <string>
#include <type_traits>
#include <utility>
#include <sstream>

#include "any.hpp"
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
#include <type_list.hpp>
#include <void_t.hpp>

namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
// conversion signature
typedef any (*conversion_binding_signature)(const any&);
// string serialize signature
typedef std::string (*string_serialization_signature)(const any&);
// string deserialization signature
typedef any (*string_deserialization_signature)(const std::string&);
// address of signature
typedef any (*address_of_signature)(any&);
// dereference signature
typedef any (*dereference_signature)(any&);

////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct

namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
    // dispatch: unpacks argument type list and sequence to correctly index into
    // argument array and call get with the right types to retrieve raw values
    // from the anys
    template <class FunctionPointerType,
              FunctionPointerType FunctionPointerValue,
              class... ArgTypes,
              std::size_t... ArgSeq>
    static any
    dispatch(any* argument_array,
             metamusil::t_list::type_list<ArgTypes...>,
             std::index_sequence<ArgSeq...>)
    {
        // necessary to remove reference from types as any only stores
        // unqualified types, ie values only
        return FunctionPointerValue(
            argument_array[ArgSeq]
                .get<typename std::remove_reference_t<ArgTypes>>()...);
    }
};

template <>
struct return_type_specializer<void>
{
    // dispatch: unpacks argument type list and sequence to correctly index into
    // argument array and call get with the right types to retrieve raw values
    // from the anys
    template <class FunctionPointerType,
              FunctionPointerType FunctionPointerValue,
              class... ArgTypes,
              std::size_t... ArgSeq>
    static any
    dispatch(any* argument_array,
             metamusil::t_list::type_list<ArgTypes...>,
             std::index_sequence<ArgSeq...>)
    {
        // necessary to remove reference from types as any only stores
        // unqualified types, ie values only
        FunctionPointerValue(
            argument_array[ArgSeq]
                .get<typename std::remove_reference_t<ArgTypes>>()...);

        // return empty any, ie 'void'
        return any();
    }
};

// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
    typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
    typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
        parameter_types;
    // make integer sequence from type list
    typedef metamusil::t_list::index_sequence_for_t<parameter_types>
        parameter_sequence;

    return return_type_specializer<return_type>::
        template dispatch<FunctionPointerType, FunctionPointerValue>(
            argument_array, parameter_types(), parameter_sequence());
}
} // namespace free_function_detail

namespace member_function_detail
{

template <class ReturnType>
struct return_type_specializer
{
    template <class MemFunPointerType,
              MemFunPointerType MemFunPointerValue,
              class ObjectType,
              class... ParamTypes,
              std::size_t... ParamSequence>
    static any
    dispatch(any& object,
             any* argument_array,
             metamusil::t_list::type_list<ParamTypes...>,
             std::index_sequence<ParamSequence...>)
    {
        return (object.get<ObjectType>().*MemFunPointerValue)(
            argument_array[ParamSequence]
                .get<std::remove_reference_t<ParamTypes>>()...);
    }
};

template <>
struct return_type_specializer<void>
{
    template <class MemFunPointerType,
              MemFunPointerType MemFunPointerValue,
              class ObjectType,
              class... ParamTypes,
              std::size_t... ParamSequence>
    static any
    dispatch(any& object,
             any* argument_array,
             metamusil::t_list::type_list<ParamTypes...>,
             std::index_sequence<ParamSequence...>)
    {
        (object.get<ObjectType>().*MemFunPointerValue)(
            argument_array[ParamSequence]
                .get<std::remove_reference_t<ParamTypes>>()...);

        return any();
    }
};

template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
    // deduce return type
    typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;

    // deduce parameter types
    typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
        parameter_types;

    // make integer sequence from parameter type list
    typedef metamusil::t_list::index_sequence_for_t<parameter_types>
        parameter_sequence;

    // deduce object type
    typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;

    return return_type_specializer<return_type>::
        template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
            object, argument_array, parameter_types(), parameter_sequence());
}
} // namespace member_function_detail

namespace member_variable_detail
{

template <class MemVarPointerType,
          MemVarPointerType MemVarPointerValue,
          class ObjectType,
          class MemVarType>
any
get_dispatch(const any& object)
{
    return (object.get<ObjectType>().*MemVarPointerValue);
}

template <class MemVarPointerType,
          MemVarPointerType MemVarPointerValue,
          class ObjectType,
          class MemVarType>
void
set_dispatch(any& object, const any& value)
{
    (object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}

template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
    typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
        object_type;
    typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
        member_variable_type;

    return get_dispatch<MemVarPointerType,
                        MemVarPointerValue,
                        object_type,
                        member_variable_type>(object);
}

template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
    typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
        object_type;
    typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
        member_variable_type;

    return set_dispatch<MemVarPointerType,
                        MemVarPointerValue,
                        object_type,
                        member_variable_type>(object, value);
}
} // namespace member_variable_detail

namespace constructor_detail
{

// purpose of braced_init_selector is to attempt to use constructor T(...) if
// available, otherwise fall back to braced init list initialization
template <class, class T, class... ParamTypes>
struct braced_init_selector_impl
{
    template <std::size_t... Seq>
    static any
    constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
    {
        any out =
            T{argument_array[Seq]
                  .get<typename std::remove_reference<ParamTypes>::type>()...};
        return out;
    }
};

template <class T, class... ParamTypes>
struct braced_init_selector_impl<
    metamusil::void_t<decltype(T(std::declval<ParamTypes>()...))>,
    T,
    ParamTypes...>
{
    template <std::size_t... Seq>
    static any
    constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
    {
        any out =
            T(argument_array[Seq]
                  .get<typename std::remove_reference<ParamTypes>::type>()...);
        return out;
    }
};

template <class T, class... ParamTypes>
using braced_init_selector = braced_init_selector_impl<void, T, ParamTypes...>;

template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
    typedef std::index_sequence_for<ParamTypes...> param_sequence;

    return braced_init_selector<T, ParamTypes...>::constructor_dispatch(
        argument_array, param_sequence());
}
} // namespace constructor_detail

namespace conversion_detail
{
template <class TargetType, class SourceType, class = void>
struct conversion_specializer;

template <>
struct conversion_specializer<void, void>;

template <class TargetType, class SourceType>
struct conversion_specializer<
    TargetType,
    SourceType,
    std::enable_if_t<std::is_convertible<SourceType, TargetType>::value>>
{
    static any
    dispatch(const any& src)
    {
        TargetType temp = static_cast<TargetType>(src.get<SourceType>());
        return temp;
    }
};

template <class TargetType, class SourceType>
any
generic_conversion_bind_point(const any& src)
{
    return conversion_specializer<TargetType, SourceType>::dispatch(src);
}
} // namespace conversion_detail

namespace string_serialization_detail
{

template <class T, class = void>
struct string_serialize_type_selector;

template <class T>
struct string_serialize_type_selector<
    T,
    std::enable_if_t<std::is_arithmetic<T>::value>>
{
    static std::string
    dispatch(const any& value)
    {
        std::ostringstream out;
        out << value.get<T>();
        return out.str();
    }
};

template <>
struct string_serialize_type_selector<std::string>
{
    static std::string
    dispatch(const any& value)
    {
        return value.get<std::string>();
    }
};

template <>
struct string_serialize_type_selector<char>
{
    static std::string
    dispatch(const any& value)
    {
        std::string out;
        out.push_back(value.get<char>());
        return out;
    }
};

template <>
struct string_serialize_type_selector<void>
{
    static std::string
    dispatch(const any&)
    {
        return "empty";
    }
};

template <class T>
std::string
generic_string_serialization_bind_point(const any& value)
{
    return string_serialize_type_selector<T>::dispatch(value);
}

template <class T, class = void>
struct string_deserialize_type_selector;

template <class T>
struct string_deserialize_type_selector<
    T,
    std::enable_if_t<std::is_arithmetic<T>::value>>
{
    static any
    dispatch(const std::string& str_value)
    {
        T out = std::stold(str_value);
        return out;
    }
};

template <>
struct string_deserialize_type_selector<char>
{
    static any
    dispatch(const std::string& str_value)
    {
        return str_value[0];
    }
};

template <>
struct string_deserialize_type_selector<std::string>
{
    static any
    dispatch(const std::string& str_value)
    {
        return str_value;
    }
};

template <>
struct string_deserialize_type_selector<int>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stoi(str_value);
    }
};

template <>
struct string_deserialize_type_selector<long>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stol(str_value);
    }
};

template <>
struct string_deserialize_type_selector<long long>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stoll(str_value);
    }
};

template <>
struct string_deserialize_type_selector<unsigned long>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stoul(str_value);
    }
};

template <>
struct string_deserialize_type_selector<unsigned long long>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stoull(str_value);
    }
};

template <>
struct string_deserialize_type_selector<float>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stof(str_value);
    }
};

template <>
struct string_deserialize_type_selector<double>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stod(str_value);
    }
};

template <>
struct string_deserialize_type_selector<long double>
{
    static any
    dispatch(const std::string& str_value)
    {
        return std::stold(str_value);
    }
};

template <>
struct string_deserialize_type_selector<void>
{
    static any
    dispatch(const std::string&)
    {
        return shadow::any();
    }
};

template <class T>
any
generic_string_deserialization_bind_point(const std::string& str_value)
{
    return string_deserialize_type_selector<T>::dispatch(str_value);
}
} // namespace string_serialization_detail

namespace pointer_detail
{
template <class T>
inline any
generic_address_of_bind_point(any& value)
{
    return any(&(value.get<T>()));
}

template <>
inline any
generic_address_of_bind_point<void>(any&)
{
    return any(nullptr);
}

template <class T>
inline any
generic_dereference_bind_point(any& value)
{
    return any(*(value.get<T*>()));
}

template <>
inline any
generic_dereference_bind_point<void>(any&)
{
    return any();
}

} // namespace pointer_detail

} // namespace shadow

#endif
<|endoftext|>


<commit_before>#ifndef VIGRA_VISIT_BORDER_HXX_
#define VIGRA_VISIT_BORDER_HXX_

#include <vigra/multi_array.hxx>

namespace vigra
{

namespace visit_border_detail
{

template <unsigned int K>
struct visit_border_impl
{
    template <unsigned int N, class Data, class S1,
                              class Label, class S2,
              class Shape, class Visitor>
    static void exec(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2> u_labels,
                     const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2> v_labels,
                     const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
    {
        static const unsigned int D = K - 1;
        typedef visit_border_impl<D> next;

        if(block_difference[D] == -1)
        {
            MultiArrayIndex last = v_data.shape(D) - 1;
            next::exec(u_data.bindAt(D, 0), u_labels.bindAt(D, 0),
                       v_data.bindAt(D, last), v_labels.bindAt(D, last),
                       block_difference, neighborhood, visitor);
        }
        else if(block_difference[D] == 1)
        {
            MultiArrayIndex last = u_data.shape(D) - 1;
            next::exec(u_data.bindAt(D, last), u_labels.bindAt(D, last),
                       v_data.bindAt(D, 0), v_labels.bindAt(D, 0),
                       block_difference, neighborhood, visitor);
        }
        else if(block_difference[D] == 0)
        {
            next::exec(u_data, u_labels, v_data, v_labels, block_difference, neighborhood, visitor);
        }
        else
        {
            vigra_precondition(false, "invalid block difference");
        }
    }
};

template <>
struct visit_border_impl<0>
{
    template <class Data, class S1,
              class Label, class S2,
              class Shape, class Visitor>
    static void exec(const MultiArrayView<0, Data, S1>& u_data, MultiArrayView<0, Label, S2> u_labels,
                     const MultiArrayView<0, Data, S1>& v_data, MultiArrayView<0, Label, S2> v_labels,
                     const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
    {
        visitor(u_data(0), u_labels(0), v_data(0), v_labels(0), block_difference);
    }
    template <unsigned int N, class Data, class S1,
                              class Label, class S2,
              class Shape, class Visitor>
    static void exec(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2> u_labels,
                     const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2> v_labels,
                     const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
    {
        if(neighborhood == DirectNeighborhood)
        {
            typedef typename MultiArrayView<N, Data, S1>::const_iterator DataIterator;
            typedef typename MultiArrayView<N, Label, S2>::iterator LabelsIterator;

            DataIterator u_data_it = u_data.begin();
            LabelsIterator u_labels_it = u_labels.begin();

            DataIterator v_data_it = v_data.begin();
            LabelsIterator v_labels_it = v_labels.begin();

            for( ; u_data_it != u_data.end(); ++u_data_it, ++u_labels_it, ++v_data_it, ++v_labels_it)
            {
                visitor(*u_data_it, *u_labels_it, *v_data_it, *v_labels_it, block_difference);
            }
        }
        else if(neighborhood == IndirectNeighborhood)
        {
            typedef GridGraph<N, undirected_tag> Graph;
            typedef typename Graph::NodeIt GraphScanner;
            typedef typename Graph::OutArcIt NeighborIterator;

            static const int global_dim_number = Shape::static_size;
            TinyVector<unsigned int, N> dim_mapping; // mapping of every local dimension to their actual global dimension indices
            int local_dims_pos = 0;
            int global_dims_pos = 0;
            for( ; global_dims_pos != global_dim_number; ++global_dims_pos)
            {
                if(block_difference[global_dims_pos] == 0)
                {
                    vigra_assert(local_dims_pos != N, "");
                    dim_mapping[local_dims_pos] = global_dims_pos;
                    ++local_dims_pos;
                }
            }
            vigra_assert(local_dims_pos == N, "");

            Graph graph(u_data.shape(), neighborhood);
            Shape pixel_difference = block_difference;
            for(GraphScanner node(graph); node != lemon::INVALID; ++node)
            {
                // compare neighbors that have have equal coordinates in all unbound dimensions
                // their pixel-level difference is exactly block_difference
                visitor(u_data[*node], u_labels[*node], v_data[*node], v_labels[*node], block_difference);
                // now let unbound dimensions vary
                for(NeighborIterator arc(graph, *node); arc != lemon::INVALID; ++arc)
                {
                    for(int i = 0; i != N; ++i)
                        pixel_difference[dim_mapping[i]] = graph.target(*arc)[i];
                    visitor(u_data[*node], u_labels[*node], v_data[graph.target(*arc)], v_labels[graph.target(*arc)], pixel_difference);
                }
            }
        }
    }
};

}
template <unsigned int N, class Data, class S1,
                          class Label, class S2,
          class Shape, class Visitor>
void visitBorder(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2>& u_labels,
                 const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2>& v_labels,
                 const Shape& difference, NeighborhoodType neighborhood, Visitor visitor)
{
    vigra_precondition(u_data.shape() == u_labels.shape() && v_data.shape() == v_labels.shape(),
                       "differing block shapes");
    visit_border_detail::visit_border_impl<N>::exec(u_data, u_labels,
                                                    v_data, v_labels,
                                                    difference, neighborhood, visitor);
}

}

#endif

<commit_msg>fix visit border pixel diff problem<commit_after>#ifndef VIGRA_VISIT_BORDER_HXX_
#define VIGRA_VISIT_BORDER_HXX_

#include <vigra/multi_array.hxx>

namespace vigra
{

namespace visit_border_detail
{

template <unsigned int K>
struct visit_border_impl
{
    template <unsigned int N, class Data, class S1,
                              class Label, class S2,
              class Shape, class Visitor>
    static void exec(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2> u_labels,
                     const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2> v_labels,
                     const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
    {
        static const unsigned int D = K - 1;
        typedef visit_border_impl<D> next;

        if(block_difference[D] == -1)
        {
            MultiArrayIndex last = v_data.shape(D) - 1;
            next::exec(u_data.bindAt(D, 0), u_labels.bindAt(D, 0),
                       v_data.bindAt(D, last), v_labels.bindAt(D, last),
                       block_difference, neighborhood, visitor);
        }
        else if(block_difference[D] == 1)
        {
            MultiArrayIndex last = u_data.shape(D) - 1;
            next::exec(u_data.bindAt(D, last), u_labels.bindAt(D, last),
                       v_data.bindAt(D, 0), v_labels.bindAt(D, 0),
                       block_difference, neighborhood, visitor);
        }
        else if(block_difference[D] == 0)
        {
            next::exec(u_data, u_labels, v_data, v_labels, block_difference, neighborhood, visitor);
        }
        else
        {
            vigra_precondition(false, "invalid block difference");
        }
    }
};

template <>
struct visit_border_impl<0>
{
    template <class Data, class S1,
              class Label, class S2,
              class Shape, class Visitor>
    static void exec(const MultiArrayView<0, Data, S1>& u_data, MultiArrayView<0, Label, S2> u_labels,
                     const MultiArrayView<0, Data, S1>& v_data, MultiArrayView<0, Label, S2> v_labels,
                     const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
    {
        visitor(u_data(0), u_labels(0), v_data(0), v_labels(0), block_difference);
    }
    template <unsigned int N, class Data, class S1,
                              class Label, class S2,
              class Shape, class Visitor>
    static void exec(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2> u_labels,
                     const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2> v_labels,
                     const Shape& block_difference, NeighborhoodType neighborhood, Visitor visitor)
    {
        if(neighborhood == DirectNeighborhood)
        {
            typedef typename MultiArrayView<N, Data, S1>::const_iterator DataIterator;
            typedef typename MultiArrayView<N, Label, S2>::iterator LabelsIterator;

            DataIterator u_data_it = u_data.begin();
            LabelsIterator u_labels_it = u_labels.begin();

            DataIterator v_data_it = v_data.begin();
            LabelsIterator v_labels_it = v_labels.begin();

            for( ; u_data_it != u_data.end(); ++u_data_it, ++u_labels_it, ++v_data_it, ++v_labels_it)
            {
                visitor(*u_data_it, *u_labels_it, *v_data_it, *v_labels_it, block_difference);
            }
        }
        else if(neighborhood == IndirectNeighborhood)
        {
            typedef GridGraph<N, undirected_tag> Graph;
            typedef typename Graph::NodeIt GraphScanner;
            typedef typename Graph::OutArcIt NeighborIterator;

            static const int global_dim_number = Shape::static_size;
            TinyVector<unsigned int, N> dim_mapping; // mapping of every local dimension to their actual global dimension indices
            int local_dims_pos = 0;
            int global_dims_pos = 0;
            for( ; global_dims_pos != global_dim_number; ++global_dims_pos)
            {
                if(block_difference[global_dims_pos] == 0)
                {
                    vigra_assert(local_dims_pos != N, "");
                    dim_mapping[local_dims_pos] = global_dims_pos;
                    ++local_dims_pos;
                }
            }
            vigra_assert(local_dims_pos == N, "");

            Graph graph(u_data.shape(), neighborhood);
            Shape pixel_difference = block_difference;
            for(GraphScanner node(graph); node != lemon::INVALID; ++node)
            {
                // compare neighbors that have have equal coordinates in all unbound dimensions
                // their pixel-level difference is exactly block_difference
                visitor(u_data[*node], u_labels[*node], v_data[*node], v_labels[*node], block_difference);
                // now let unbound dimensions vary
                for(NeighborIterator arc(graph, *node); arc != lemon::INVALID; ++arc)
                {
                    for(int i = 0; i != N; ++i)
                        pixel_difference[dim_mapping[i]] = graph.target(*arc)[i] - (*node)[i];
                    visitor(u_data[*node], u_labels[*node], v_data[graph.target(*arc)], v_labels[graph.target(*arc)], pixel_difference);
                }
            }
        }
    }
};

}
template <unsigned int N, class Data, class S1,
                          class Label, class S2,
          class Shape, class Visitor>
void visitBorder(const MultiArrayView<N, Data, S1>& u_data, MultiArrayView<N, Label, S2>& u_labels,
                 const MultiArrayView<N, Data, S1>& v_data, MultiArrayView<N, Label, S2>& v_labels,
                 const Shape& difference, NeighborhoodType neighborhood, Visitor visitor)
{
    vigra_precondition(u_data.shape() == u_labels.shape() && v_data.shape() == v_labels.shape(),
                       "differing block shapes");
    visit_border_detail::visit_border_impl<N>::exec(u_data, u_labels,
                                                    v_data, v_labels,
                                                    difference, neighborhood, visitor);
}

}

#endif

<|endoftext|>


<commit_before>/*
 * Copyright 2016 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <fstream>

#include <ox/clargs/clargs.hpp>
#include <ox/fs/fs.hpp>

#include "pack/pack.hpp"

static ox::Error writeFileBuff(const ox::String &path, const ox::Vector<char> &buff) noexcept {
	try {
		std::ofstream f(path.c_str(), std::ios::binary);
		f.write(buff.data(), static_cast<intptr_t>(buff.size()));
	} catch (const std::fstream::failure&) {
		return OxError(2, "failed to write file");
	}
	return OxError(0);
}

static ox::Error run(const ox::ClArgs &args) noexcept {
	ox::trace::init();
	const auto argSrc = args.getString("src", "");
	const auto argDst = args.getString("dst", "");
	if (argSrc == "") {
		oxErr("\033[31;1;1merror:\033[0m must specify a source directory\n");
		return OxError(1, "must specify a source directory");
	}
	if (argDst == "") {
		oxErr("\033[31;1;1merror:\033[0m must specify a destination ROM file\n");
		return OxError(1, "must specify a destination ROM file");
	}
	ox::Vector<char> buff(32 * ox::units::MB);
	oxReturnError(ox::FileSystem32::format(buff.data(), buff.size()));
	ox::PassThroughFS src(argSrc.c_str());
	ox::FileSystem32 dst(ox::FileStore32(buff.data(), buff.size()));
	oxReturnError(nostalgia::pack(&src, &dst));

	oxReturnError(dst.resize());
	oxRequire(dstSize, dst.size());
	oxOutf("new size: {}\n", dstSize);
	buff.resize(dstSize);

	oxReturnError(writeFileBuff(argDst, buff));
	return OxError(0);
}

int main(int argc, const char **args) {
	const auto err = run(ox::ClArgs(argc, args));
	oxAssert(err, "pack failed");
	return static_cast<int>(err);
}
<commit_msg>[nostalgia/tools/pack] Replace ox::Vector<char> with ox::Buffer<commit_after>/*
 * Copyright 2016 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <fstream>

#include <ox/clargs/clargs.hpp>
#include <ox/fs/fs.hpp>

#include "pack/pack.hpp"

static ox::Error writeFileBuff(const ox::String &path, const ox::Buffer &buff) noexcept {
	try {
		std::ofstream f(path.c_str(), std::ios::binary);
		f.write(buff.data(), static_cast<intptr_t>(buff.size()));
	} catch (const std::fstream::failure&) {
		return OxError(2, "failed to write file");
	}
	return OxError(0);
}

static ox::Error run(const ox::ClArgs &args) noexcept {
	ox::trace::init();
	const auto argSrc = args.getString("src", "");
	const auto argDst = args.getString("dst", "");
	if (argSrc == "") {
		oxErr("\033[31;1;1merror:\033[0m must specify a source directory\n");
		return OxError(1, "must specify a source directory");
	}
	if (argDst == "") {
		oxErr("\033[31;1;1merror:\033[0m must specify a destination ROM file\n");
		return OxError(1, "must specify a destination ROM file");
	}
	ox::Buffer buff(32 * ox::units::MB);
	oxReturnError(ox::FileSystem32::format(buff.data(), buff.size()));
	ox::PassThroughFS src(argSrc.c_str());
	ox::FileSystem32 dst(ox::FileStore32(buff.data(), buff.size()));
	oxReturnError(nostalgia::pack(&src, &dst));

	oxReturnError(dst.resize());
	oxRequire(dstSize, dst.size());
	oxOutf("new size: {}\n", dstSize);
	buff.resize(dstSize);

	oxReturnError(writeFileBuff(argDst, buff));
	return OxError(0);
}

int main(int argc, const char **args) {
	const auto err = run(ox::ClArgs(argc, args));
	oxAssert(err, "pack failed");
	return static_cast<int>(err);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: FilteredContainer.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 14:59:57 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBACCESS_CORE_FILTERED_CONTAINER_HXX
#include "FilteredContainer.hxx"
#endif
#ifndef DBA_CORE_REFRESHLISTENER_HXX
#include "RefreshListener.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif

namespace dbaccess
{
    using namespace dbtools;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::util;
    using namespace ::com::sun::star::container;
    using namespace ::osl;
    using namespace ::comphelper;
    using namespace ::cppu;
    using namespace ::connectivity::sdbcx;

    //------------------------------------------------------------------------------
    /** compare two strings
    */
    extern int
    #if defined( WNT )
     __cdecl
    #endif
    #if defined( ICC ) && defined( OS2 )
    _Optlink
    #endif
    NameCompare( const void* pFirst, const void* pSecond)
    {
        return reinterpret_cast< const ::rtl::OUString* >(pFirst)->compareTo(*reinterpret_cast< const ::rtl::OUString* >(pSecond));
    }
    //------------------------------------------------------------------------------
    /** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
    */
    sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
    {
        // for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
        // for them
        ::rtl::OUString* pTableFilters = _rTableFilter.getArray();
        ::rtl::OUString* pEnd          = pTableFilters + _rTableFilter.getLength();
        sal_Int32 nShiftPos = 0;
        for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
        {
            if (pTableFilters->indexOf('%') != -1)
            {
                _rOut.push_back(WildCard(pTableFilters->replace('%', '*')));
            }
            else
            {
                if (nShiftPos != i)
                {
                    _rTableFilter.getArray()[nShiftPos] = _rTableFilter.getArray()[i];
                }
                ++nShiftPos;
            }
        }
        // now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
        _rTableFilter.realloc(nShiftPos);
        return nShiftPos;
    }

    //==========================================================================
    //= OViewContainer
    //==========================================================================
    OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
                                 ::osl::Mutex& _rMutex,
                                 const Reference< XConnection >& _xCon,
                                 sal_Bool _bCase,
                                 IRefreshListener*  _pRefreshListener,
                                 IWarningsContainer* _pWarningsContainer)
    :OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
    ,m_bConstructed(sal_False)
    ,m_xConnection(_xCon)
    ,m_pWarningsContainer(_pWarningsContainer)
    ,m_pRefreshListener(_pRefreshListener)
    {

    }
    // -------------------------------------------------------------------------
    void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
                                    const Sequence< ::rtl::OUString >& _rTableFilter,
                                    const Sequence< ::rtl::OUString >& _rTableTypeFilter)
    {
        try
        {
            Reference<XConnection> xCon = m_xConnection;
            if ( xCon.is() )
                m_xMetaData = xCon->getMetaData();
        }
        catch(SQLException&)
        {
        }

        m_xMasterContainer = _rxMasterContainer;

        if(m_xMasterContainer.is())
        {
            addMasterContainerListener();
            sal_Int32   nTableFilterLen = _rTableFilter.getLength();

            connectivity::TStringVector aTableNames;
            sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
            if(!bNoTableFilters)
            {
                Sequence< ::rtl::OUString > aTableFilter        = _rTableFilter;
                Sequence< ::rtl::OUString > aTableTypeFilter    = _rTableTypeFilter;
                // build sorted versions of the filter sequences, so the visibility decision is faster
                qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);

                // as we want to modify nTableFilterLen, remember this

                // for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
                // for them
                ::std::vector< WildCard > aWCSearch; // contains the wildcards for the table filter
                nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);

                aTableNames.reserve(nTableFilterLen + (aWCSearch.size() * 10));

                Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
                const ::rtl::OUString* pBegin   = aNames.getConstArray();
                const ::rtl::OUString* pEnd     = pBegin + aNames.getLength();
                for(;pBegin != pEnd;++pBegin)
                {
                    if(isNameValid(*pBegin,aTableFilter,aTableTypeFilter,aWCSearch))
                        aTableNames.push_back(*pBegin);
                }
            }
            else
            {
                // no filter so insert all names
                Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
                const ::rtl::OUString* pBegin   = aNames.getConstArray();
                const ::rtl::OUString* pEnd     = pBegin + aNames.getLength();
                aTableNames = connectivity::TStringVector(pBegin,pEnd);
            }
            reFill(aTableNames);
            m_bConstructed = sal_True;
        }
        else
        {
            construct(_rTableFilter,_rTableTypeFilter);
        }
    }
    //------------------------------------------------------------------------------
    void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
    {
        try
        {
            Reference<XConnection> xCon = m_xConnection;
            if ( xCon.is() )
                m_xMetaData = xCon->getMetaData();
        }
        catch(SQLException&)
        {
        }
        // build sorted versions of the filter sequences, so the visibility decision is faster
        Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
        sal_Int32   nTableFilterLen = aTableFilter.getLength();

        if (nTableFilterLen)
            qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);

        sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
            // as we want to modify nTableFilterLen, remember this

        // for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
        // for them
        ::std::vector< WildCard > aWCSearch;
        nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);

        try
        {
            if (m_xMetaData.is())
            {
                static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
                Sequence< ::rtl::OUString > sTableTypes = getTableTypeFilter(_rTableTypeFilter);
                if ( m_bConstructed && sTableTypes.getLength() == 0 )
                    return;

                Reference< XResultSet > xTables = m_xMetaData->getTables(Any(), sAll, sAll, sTableTypes);
                Reference< XRow > xCurrentRow(xTables, UNO_QUERY);
                if (xCurrentRow.is())
                {

                        // after creation the set is positioned before the first record, per definitionem

                    ::rtl::OUString sCatalog, sSchema, sName, sType;
                    ::rtl::OUString sComposedName;

                    // we first collect the names and construct the OTable objects later, as the ctor of the table may need
                    // another result set from the connection, and some drivers support only one statement per connection

                    sal_Bool bFilterMatch;
                    while (xTables->next())
                    {
                        sCatalog    = xCurrentRow->getString(1);
                        sSchema     = xCurrentRow->getString(2);
                        sName       = xCurrentRow->getString(3);
                        // we're not interested in the "wasNull", as the getStrings would return an empty string in
                        // that case, which is sufficient here

                        composeTableName(m_xMetaData, sCatalog, sSchema, sName, sComposedName, sal_False,::dbtools::eInDataManipulation);
                        bFilterMatch =  bNoTableFilters
                                    ||  ((nTableFilterLen != 0) && (NULL != bsearch(&sComposedName, aTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare)));
                        // the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches

                        if (!bFilterMatch && aWCSearch.size())
                        {   // or if one of the wildcrad expression matches
                            for (   ::std::vector< WildCard >::const_iterator aLoop = aWCSearch.begin();
                                    aLoop != aWCSearch.end() && !bFilterMatch;
                                    ++aLoop
                                )
                                bFilterMatch = aLoop->Matches(sComposedName);
                        }

                        if (bFilterMatch)
                        {   // the table name is allowed (not filtered out)
                            insertElement(sComposedName,NULL);
                        }
                    }

                    // dispose the tables result set, in case the connection can handle only one concurrent statement
                    // (the table object creation will need it's own statements)
                    disposeComponent(xTables);
                }
                else
                    OSL_ENSURE(0,"OFilteredContainer::construct : did not get a XRow from the tables result set !");
            }
            else
                OSL_ENSURE(0,"OFilteredContainer::construct : no connection meta data !");
        }
        catch (SQLException&)
        {
            OSL_ENSURE(0,"OFilteredContainer::construct : catched an SQL-Exception !");
            disposing();
            return;
        }

        m_bConstructed = sal_True;
    }
    //------------------------------------------------------------------------------
    void OFilteredContainer::disposing()
    {
        OCollection::disposing();
        removeMasterContainerListener();

        m_xMasterContainer  = NULL;
        m_xMetaData         = NULL;
        m_pWarningsContainer = NULL;
        m_pRefreshListener  = NULL;
        m_bConstructed      = sal_False;
    }
    // -------------------------------------------------------------------------
    void OFilteredContainer::impl_refresh() throw(RuntimeException)
    {
        if ( m_pRefreshListener )
        {
            m_bConstructed = sal_False;
            Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
            if ( xRefresh.is() )
                xRefresh->refresh();
            m_pRefreshListener->refresh(this);
        }
    }
    // -------------------------------------------------------------------------
    sal_Bool OFilteredContainer::isNameValid(   const ::rtl::OUString& _rName,
                                            const Sequence< ::rtl::OUString >& _rTableFilter,
                                            const Sequence< ::rtl::OUString >& _rTableTypeFilter,
                                            const ::std::vector< WildCard >& _rWCSearch) const
    {
        sal_Int32 nTableFilterLen = _rTableFilter.getLength();

        sal_Bool bFilterMatch = (NULL != bsearch(&_rName, _rTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare));
        // the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
        if (!bFilterMatch && !_rWCSearch.empty())
        {   // or if one of the wildcrad expression matches
            String sWCCompare = (const sal_Unicode*)_rName;
            for (   ::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
                    aLoop != _rWCSearch.end() && !bFilterMatch;
                    ++aLoop
                )
                bFilterMatch = aLoop->Matches(sWCCompare);
        }

        return bFilterMatch;
    }
    // -------------------------------------------------------------------------
    Reference< XNamed > OFilteredContainer::cloneObject(const Reference< XPropertySet >& _xDescriptor)
    {
        Reference< XNamed > xName(_xDescriptor,UNO_QUERY);
        OSL_ENSURE(xName.is(),"Must be a XName interface here !");
        return xName.is() ? createObject(xName->getName()) : Reference< XNamed >();
    }
    // -----------------------------------------------------------------------------
// ..............................................................................
} // namespace
// ..............................................................................

<commit_msg>INTEGRATION: CWS dba24 (1.4.80); FILE MERGED 2005/02/10 16:52:05 fs 1.4.80.2: grammar and debug diagnostics 2005/02/09 08:12:57 oj 1.4.80.1: #i26950# remove the need for XNamed<commit_after>/*************************************************************************
 *
 *  $RCSfile: FilteredContainer.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-10 16:29:48 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBACCESS_CORE_FILTERED_CONTAINER_HXX
#include "FilteredContainer.hxx"
#endif
#ifndef DBA_CORE_REFRESHLISTENER_HXX
#include "RefreshListener.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif

namespace dbaccess
{
    using namespace dbtools;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::util;
    using namespace ::com::sun::star::container;
    using namespace ::osl;
    using namespace ::comphelper;
    using namespace ::cppu;
    using namespace ::connectivity::sdbcx;

    //------------------------------------------------------------------------------
    /** compare two strings
    */
    extern int
    #if defined( WNT )
     __cdecl
    #endif
    #if defined( ICC ) && defined( OS2 )
    _Optlink
    #endif
    NameCompare( const void* pFirst, const void* pSecond)
    {
        return reinterpret_cast< const ::rtl::OUString* >(pFirst)->compareTo(*reinterpret_cast< const ::rtl::OUString* >(pSecond));
    }
    //------------------------------------------------------------------------------
    /** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
    */
    sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
    {
        // for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
        // for them
        ::rtl::OUString* pTableFilters = _rTableFilter.getArray();
        ::rtl::OUString* pEnd          = pTableFilters + _rTableFilter.getLength();
        sal_Int32 nShiftPos = 0;
        for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
        {
            if (pTableFilters->indexOf('%') != -1)
            {
                _rOut.push_back(WildCard(pTableFilters->replace('%', '*')));
            }
            else
            {
                if (nShiftPos != i)
                {
                    _rTableFilter.getArray()[nShiftPos] = _rTableFilter.getArray()[i];
                }
                ++nShiftPos;
            }
        }
        // now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
        _rTableFilter.realloc(nShiftPos);
        return nShiftPos;
    }

    //==========================================================================
    //= OViewContainer
    //==========================================================================
    OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
                                 ::osl::Mutex& _rMutex,
                                 const Reference< XConnection >& _xCon,
                                 sal_Bool _bCase,
                                 IRefreshListener*  _pRefreshListener,
                                 IWarningsContainer* _pWarningsContainer)
    :OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
    ,m_bConstructed(sal_False)
    ,m_xConnection(_xCon)
    ,m_pWarningsContainer(_pWarningsContainer)
    ,m_pRefreshListener(_pRefreshListener)
    {

    }
    // -------------------------------------------------------------------------
    void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
                                    const Sequence< ::rtl::OUString >& _rTableFilter,
                                    const Sequence< ::rtl::OUString >& _rTableTypeFilter)
    {
        try
        {
            Reference<XConnection> xCon = m_xConnection;
            if ( xCon.is() )
                m_xMetaData = xCon->getMetaData();
        }
        catch(SQLException&)
        {
        }

        m_xMasterContainer = _rxMasterContainer;

        if(m_xMasterContainer.is())
        {
            addMasterContainerListener();
            sal_Int32   nTableFilterLen = _rTableFilter.getLength();

            connectivity::TStringVector aTableNames;
            sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
            if(!bNoTableFilters)
            {
                Sequence< ::rtl::OUString > aTableFilter        = _rTableFilter;
                Sequence< ::rtl::OUString > aTableTypeFilter    = _rTableTypeFilter;
                // build sorted versions of the filter sequences, so the visibility decision is faster
                qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);

                // as we want to modify nTableFilterLen, remember this

                // for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
                // for them
                ::std::vector< WildCard > aWCSearch; // contains the wildcards for the table filter
                nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);

                aTableNames.reserve(nTableFilterLen + (aWCSearch.size() * 10));

                Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
                const ::rtl::OUString* pBegin   = aNames.getConstArray();
                const ::rtl::OUString* pEnd     = pBegin + aNames.getLength();
                for(;pBegin != pEnd;++pBegin)
                {
                    if(isNameValid(*pBegin,aTableFilter,aTableTypeFilter,aWCSearch))
                        aTableNames.push_back(*pBegin);
                }
            }
            else
            {
                // no filter so insert all names
                Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
                const ::rtl::OUString* pBegin   = aNames.getConstArray();
                const ::rtl::OUString* pEnd     = pBegin + aNames.getLength();
                aTableNames = connectivity::TStringVector(pBegin,pEnd);
            }
            reFill(aTableNames);
            m_bConstructed = sal_True;
        }
        else
        {
            construct(_rTableFilter,_rTableTypeFilter);
        }
    }
    //------------------------------------------------------------------------------
    void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
    {
        try
        {
            Reference<XConnection> xCon = m_xConnection;
            if ( xCon.is() )
                m_xMetaData = xCon->getMetaData();
        }
        catch(SQLException&)
        {
        }
        // build sorted versions of the filter sequences, so the visibility decision is faster
        Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
        sal_Int32   nTableFilterLen = aTableFilter.getLength();

        if (nTableFilterLen)
            qsort(aTableFilter.getArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare);

        sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
            // as we want to modify nTableFilterLen, remember this

        // for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
        // for them
        ::std::vector< WildCard > aWCSearch;
        nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);

        try
        {
            if (m_xMetaData.is())
            {
                static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
                Sequence< ::rtl::OUString > sTableTypes = getTableTypeFilter(_rTableTypeFilter);
                if ( m_bConstructed && sTableTypes.getLength() == 0 )
                    return;

                Reference< XResultSet > xTables = m_xMetaData->getTables(Any(), sAll, sAll, sTableTypes);
                Reference< XRow > xCurrentRow(xTables, UNO_QUERY);
                if (xCurrentRow.is())
                {

                        // after creation the set is positioned before the first record, per definitionem

                    ::rtl::OUString sCatalog, sSchema, sName, sType;
                    ::rtl::OUString sComposedName;

                    // we first collect the names and construct the OTable objects later, as the ctor of the table may need
                    // another result set from the connection, and some drivers support only one statement per connection

                    sal_Bool bFilterMatch;
                    while (xTables->next())
                    {
                        sCatalog    = xCurrentRow->getString(1);
                        sSchema     = xCurrentRow->getString(2);
                        sName       = xCurrentRow->getString(3);
#if OSL_DEBUG_LEVEL > 0
                        ::rtl::OUString sTableType = xCurrentRow->getString(4);
#endif
                        // we're not interested in the "wasNull", as the getStrings would return an empty string in
                        // that case, which is sufficient here

                        composeTableName(m_xMetaData, sCatalog, sSchema, sName, sComposedName, sal_False,::dbtools::eInDataManipulation);
                        bFilterMatch =  bNoTableFilters
                                    ||  ((nTableFilterLen != 0) && (NULL != bsearch(&sComposedName, aTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare)));
                        // the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches

                        if (!bFilterMatch && aWCSearch.size())
                        {   // or if one of the wildcrad expression matches
                            for (   ::std::vector< WildCard >::const_iterator aLoop = aWCSearch.begin();
                                    aLoop != aWCSearch.end() && !bFilterMatch;
                                    ++aLoop
                                )
                                bFilterMatch = aLoop->Matches(sComposedName);
                        }

                        if (bFilterMatch)
                        {   // the table name is allowed (not filtered out)
                            insertElement(sComposedName,NULL);
                        }
                    }

                    // dispose the tables result set, in case the connection can handle only one concurrent statement
                    // (the table object creation will need it's own statements)
                    disposeComponent(xTables);
                }
                else
                    OSL_ENSURE(0,"OFilteredContainer::construct : did not get a XRow from the tables result set !");
            }
            else
                OSL_ENSURE(0,"OFilteredContainer::construct : no connection meta data !");
        }
        catch (SQLException&)
        {
            OSL_ENSURE(0,"OFilteredContainer::construct: caught an SQL-Exception !");
            disposing();
            return;
        }

        m_bConstructed = sal_True;
    }
    //------------------------------------------------------------------------------
    void OFilteredContainer::disposing()
    {
        OCollection::disposing();
        removeMasterContainerListener();

        m_xMasterContainer  = NULL;
        m_xMetaData         = NULL;
        m_pWarningsContainer = NULL;
        m_pRefreshListener  = NULL;
        m_bConstructed      = sal_False;
    }
    // -------------------------------------------------------------------------
    void OFilteredContainer::impl_refresh() throw(RuntimeException)
    {
        if ( m_pRefreshListener )
        {
            m_bConstructed = sal_False;
            Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
            if ( xRefresh.is() )
                xRefresh->refresh();
            m_pRefreshListener->refresh(this);
        }
    }
    // -------------------------------------------------------------------------
    sal_Bool OFilteredContainer::isNameValid(   const ::rtl::OUString& _rName,
                                            const Sequence< ::rtl::OUString >& _rTableFilter,
                                            const Sequence< ::rtl::OUString >& _rTableTypeFilter,
                                            const ::std::vector< WildCard >& _rWCSearch) const
    {
        sal_Int32 nTableFilterLen = _rTableFilter.getLength();

        sal_Bool bFilterMatch = (NULL != bsearch(&_rName, _rTableFilter.getConstArray(), nTableFilterLen, sizeof(::rtl::OUString), NameCompare));
        // the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
        if (!bFilterMatch && !_rWCSearch.empty())
        {   // or if one of the wildcrad expression matches
            String sWCCompare = (const sal_Unicode*)_rName;
            for (   ::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
                    aLoop != _rWCSearch.end() && !bFilterMatch;
                    ++aLoop
                )
                bFilterMatch = aLoop->Matches(sWCCompare);
        }

        return bFilterMatch;
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString OFilteredContainer::getNameForObject(const ObjectType& _xObject)
    {
        OSL_ENSURE(_xObject.is(),"OTables::getNameForObject: Object is NULL!");
        return ::dbtools::composeTableName(m_xMetaData,_xObject,sal_False,::dbtools::eInDataManipulation);
    }
// ..............................................................................
} // namespace
// ..............................................................................

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <svtools/fltcall.hxx>

//============================ XPMWriter ==================================

class XPMWriter {

private:

    SvStream&           m_rOStm;            // Die auszugebende XPM-Datei
    sal_uInt16              mpOStmOldModus;

    sal_Bool                mbStatus;
    sal_Bool                mbTrans;
    BitmapReadAccess*   mpAcc;
    sal_uLong               mnWidth, mnHeight;  // Bildausmass in Pixeln
    sal_uInt16              mnColors;

    com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator > xStatusIndicator;

    void                ImplCallback( sal_uInt16 nPercent );
    sal_Bool                ImplWriteHeader();
    void                ImplWritePalette();
    void                ImplWriteColor( sal_uInt16 );
    void                ImplWriteBody();
    void                ImplWriteNumber( sal_Int32 );
    void                ImplWritePixel( sal_uLong ) const;

public:
    XPMWriter(SvStream& rOStm);
    ~XPMWriter();

    sal_Bool                WriteXPM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem );
};

//=================== Methoden von XPMWriter ==============================

XPMWriter::XPMWriter(SvStream& rOStm)
    : m_rOStm(rOStm)
    , mbStatus(sal_True)
    , mbTrans(sal_False)
    , mpAcc(NULL)
{
}

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

XPMWriter::~XPMWriter()
{
}

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

void XPMWriter::ImplCallback( sal_uInt16 nPercent )
{
    if ( xStatusIndicator.is() )
    {
        if ( nPercent <= 100 )
            xStatusIndicator->setValue( nPercent );
    }
}

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

sal_Bool XPMWriter::WriteXPM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem)
{
    Bitmap  aBmp;

    if ( pFilterConfigItem )
    {
        xStatusIndicator = pFilterConfigItem->GetStatusIndicator();
        if ( xStatusIndicator.is() )
        {
            rtl::OUString aMsg;
            xStatusIndicator->start( aMsg, 100 );
        }
    }

    BitmapEx    aBmpEx( rGraphic.GetBitmapEx() );
    aBmp = aBmpEx.GetBitmap();

    if ( rGraphic.IsTransparent() )                 // event. transparente Farbe erzeugen
    {
        mbTrans = sal_True;
        if ( aBmp.GetBitCount() >= 8 )              // wenn noetig Bild auf 8 bit konvertieren
            aBmp.Convert( BMP_CONVERSION_8BIT_TRANS );
        else
            aBmp.Convert( BMP_CONVERSION_4BIT_TRANS );
        aBmp.Replace( aBmpEx.GetMask(), BMP_COL_TRANS );
    }
    else
    {
        if ( aBmp.GetBitCount() > 8 )               // wenn noetig Bild auf 8 bit konvertieren
            aBmp.Convert( BMP_CONVERSION_8BIT_COLORS );
    }
    mpAcc = aBmp.AcquireReadAccess();
    if ( mpAcc )
    {
        mnColors = mpAcc->GetPaletteEntryCount();
        mpOStmOldModus = m_rOStm.GetNumberFormatInt();
        m_rOStm.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );

        if ( ImplWriteHeader() )
        {
            ImplWritePalette();
            ImplWriteBody();
            m_rOStm << "\x22XPMENDEXT\x22\x0a};";
        }
        aBmp.ReleaseAccess( mpAcc );
    }
    else
        mbStatus = sal_False;

    m_rOStm.SetNumberFormatInt( mpOStmOldModus );

    if ( xStatusIndicator.is() )
        xStatusIndicator->end();

    return mbStatus;
}

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

sal_Bool XPMWriter::ImplWriteHeader()
{
    mnWidth = mpAcc->Width();
    mnHeight = mpAcc->Height();
    if ( mnWidth && mnHeight && mnColors )
    {
        m_rOStm << "/* XPM */\x0astatic char * image[] = \x0a{\x0a\x22";
        ImplWriteNumber( mnWidth );
        m_rOStm << (sal_uInt8)32;
        ImplWriteNumber( mnHeight );
        m_rOStm << (sal_uInt8)32;
        ImplWriteNumber( mnColors );
        m_rOStm << (sal_uInt8)32;
        ImplWriteNumber( ( mnColors > 26 ) ? 2 : 1 );
        m_rOStm << "\x22,\x0a";
    }
    else mbStatus = sal_False;
    return mbStatus;
}

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

void XPMWriter::ImplWritePalette()
{
    sal_uInt16 nTransIndex = 0xffff;

    if ( mbTrans )
        nTransIndex = mpAcc->GetBestMatchingColor( BMP_COL_TRANS );
    for ( sal_uInt16 i = 0; i < mnColors; i++ )
    {
        m_rOStm << "\x22";
        ImplWritePixel( i );
        m_rOStm << (sal_uInt8)32;
        if ( nTransIndex != i )
        {
            ImplWriteColor( i );
            m_rOStm << "\x22,\x0a";
        }
        else
            m_rOStm << "c none\x22,\x0a";
    }
}

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

void XPMWriter::ImplWriteBody()
{
    for ( sal_uLong y = 0; y < mnHeight; y++ )
    {
        ImplCallback( (sal_uInt16)( ( 100 * y ) / mnHeight ) );         // processing output in percent
        m_rOStm << (sal_uInt8)0x22;
        for ( sal_uLong x = 0; x < mnWidth; x++ )
        {
            ImplWritePixel( (sal_uInt8)(mpAcc->GetPixel( y, x ) ) );
        }
        m_rOStm << "\x22,\x0a";
    }
}

// ------------------------------------------------------------------------
// eine Dezimalzahl im ASCII format wird in den Stream geschrieben

void XPMWriter::ImplWriteNumber(sal_Int32 nNumber)
{
    const rtl::OString aNum(rtl::OString::valueOf(nNumber));
    m_rOStm << aNum.getStr();
}

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

void XPMWriter::ImplWritePixel( sal_uLong nCol ) const
{
    if ( mnColors > 26 )
    {
        sal_uInt8 nDiff = (sal_uInt8) ( nCol / 26 );
        m_rOStm << (sal_uInt8)( nDiff + 'A' );
        m_rOStm << (sal_uInt8)( nCol - ( nDiff*26 ) + 'A' );
    }
    else
        m_rOStm << (sal_uInt8)( nCol + 'A' );
}

// ------------------------------------------------------------------------
// ein Farbwert wird im Hexadezimalzahlformat in den Stream geschrieben
void XPMWriter::ImplWriteColor( sal_uInt16 nNumber )
{
    sal_uLong   nTmp;
    sal_uInt8   j;

    m_rOStm << "c #";   // # zeigt einen folgenden Hexwert an
    const BitmapColor& rColor = mpAcc->GetPaletteColor( nNumber );
    nTmp = ( rColor.GetRed() << 16 ) | ( rColor.GetGreen() << 8 ) | rColor.GetBlue();
    for ( signed char i = 20; i >= 0 ; i-=4 )
    {
        if ( ( j = (sal_uInt8)( nTmp >> i ) & 0xf ) > 9 )
            j += 'A' - 10;
        else
            j += '0';
        m_rOStm << j;
    }
}

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

// ---------------------
// - exported function -
// ---------------------

#ifdef DISABLE_DYNLOADING
#define GraphicExport expGraphicExport
#endif

extern "C" SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL
GraphicExport(SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pFilterConfigItem, sal_Bool)
{
    XPMWriter aXPMWriter(rStream);

    return aXPMWriter.WriteXPM( rGraphic, pFilterConfigItem );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#707516: Uninitialized scalar variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <svtools/fltcall.hxx>

//============================ XPMWriter ==================================

class XPMWriter {

private:

    SvStream&           m_rOStm;            // Die auszugebende XPM-Datei

    sal_Bool                mbStatus;
    sal_Bool                mbTrans;
    BitmapReadAccess*   mpAcc;
    sal_uLong               mnWidth, mnHeight;  // Bildausmass in Pixeln
    sal_uInt16              mnColors;

    com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator > xStatusIndicator;

    void                ImplCallback( sal_uInt16 nPercent );
    sal_Bool                ImplWriteHeader();
    void                ImplWritePalette();
    void                ImplWriteColor( sal_uInt16 );
    void                ImplWriteBody();
    void                ImplWriteNumber( sal_Int32 );
    void                ImplWritePixel( sal_uLong ) const;

public:
    XPMWriter(SvStream& rOStm);
    ~XPMWriter();

    sal_Bool                WriteXPM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem );
};

//=================== Methoden von XPMWriter ==============================

XPMWriter::XPMWriter(SvStream& rOStm)
    : m_rOStm(rOStm)
    , mbStatus(sal_True)
    , mbTrans(sal_False)
    , mpAcc(NULL)
{
}

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

XPMWriter::~XPMWriter()
{
}

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

void XPMWriter::ImplCallback( sal_uInt16 nPercent )
{
    if ( xStatusIndicator.is() )
    {
        if ( nPercent <= 100 )
            xStatusIndicator->setValue( nPercent );
    }
}

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

sal_Bool XPMWriter::WriteXPM( const Graphic& rGraphic, FilterConfigItem* pFilterConfigItem)
{
    Bitmap  aBmp;

    if ( pFilterConfigItem )
    {
        xStatusIndicator = pFilterConfigItem->GetStatusIndicator();
        if ( xStatusIndicator.is() )
        {
            rtl::OUString aMsg;
            xStatusIndicator->start( aMsg, 100 );
        }
    }

    BitmapEx    aBmpEx( rGraphic.GetBitmapEx() );
    aBmp = aBmpEx.GetBitmap();

    if ( rGraphic.IsTransparent() )                 // event. transparente Farbe erzeugen
    {
        mbTrans = sal_True;
        if ( aBmp.GetBitCount() >= 8 )              // wenn noetig Bild auf 8 bit konvertieren
            aBmp.Convert( BMP_CONVERSION_8BIT_TRANS );
        else
            aBmp.Convert( BMP_CONVERSION_4BIT_TRANS );
        aBmp.Replace( aBmpEx.GetMask(), BMP_COL_TRANS );
    }
    else
    {
        if ( aBmp.GetBitCount() > 8 )               // wenn noetig Bild auf 8 bit konvertieren
            aBmp.Convert( BMP_CONVERSION_8BIT_COLORS );
    }
    mpAcc = aBmp.AcquireReadAccess();
    if ( mpAcc )
    {
        sal_uInt16 nOStmOldModus = m_rOStm.GetNumberFormatInt();
        m_rOStm.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );

        mnColors = mpAcc->GetPaletteEntryCount();
        if ( ImplWriteHeader() )
        {
            ImplWritePalette();
            ImplWriteBody();
            m_rOStm << "\x22XPMENDEXT\x22\x0a};";
        }

        m_rOStm.SetNumberFormatInt(nOStmOldModus);

        aBmp.ReleaseAccess( mpAcc );
    }
    else
        mbStatus = sal_False;

    if ( xStatusIndicator.is() )
        xStatusIndicator->end();

    return mbStatus;
}

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

sal_Bool XPMWriter::ImplWriteHeader()
{
    mnWidth = mpAcc->Width();
    mnHeight = mpAcc->Height();
    if ( mnWidth && mnHeight && mnColors )
    {
        m_rOStm << "/* XPM */\x0astatic char * image[] = \x0a{\x0a\x22";
        ImplWriteNumber( mnWidth );
        m_rOStm << (sal_uInt8)32;
        ImplWriteNumber( mnHeight );
        m_rOStm << (sal_uInt8)32;
        ImplWriteNumber( mnColors );
        m_rOStm << (sal_uInt8)32;
        ImplWriteNumber( ( mnColors > 26 ) ? 2 : 1 );
        m_rOStm << "\x22,\x0a";
    }
    else mbStatus = sal_False;
    return mbStatus;
}

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

void XPMWriter::ImplWritePalette()
{
    sal_uInt16 nTransIndex = 0xffff;

    if ( mbTrans )
        nTransIndex = mpAcc->GetBestMatchingColor( BMP_COL_TRANS );
    for ( sal_uInt16 i = 0; i < mnColors; i++ )
    {
        m_rOStm << "\x22";
        ImplWritePixel( i );
        m_rOStm << (sal_uInt8)32;
        if ( nTransIndex != i )
        {
            ImplWriteColor( i );
            m_rOStm << "\x22,\x0a";
        }
        else
            m_rOStm << "c none\x22,\x0a";
    }
}

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

void XPMWriter::ImplWriteBody()
{
    for ( sal_uLong y = 0; y < mnHeight; y++ )
    {
        ImplCallback( (sal_uInt16)( ( 100 * y ) / mnHeight ) );         // processing output in percent
        m_rOStm << (sal_uInt8)0x22;
        for ( sal_uLong x = 0; x < mnWidth; x++ )
        {
            ImplWritePixel( (sal_uInt8)(mpAcc->GetPixel( y, x ) ) );
        }
        m_rOStm << "\x22,\x0a";
    }
}

// ------------------------------------------------------------------------
// eine Dezimalzahl im ASCII format wird in den Stream geschrieben

void XPMWriter::ImplWriteNumber(sal_Int32 nNumber)
{
    const rtl::OString aNum(rtl::OString::valueOf(nNumber));
    m_rOStm << aNum.getStr();
}

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

void XPMWriter::ImplWritePixel( sal_uLong nCol ) const
{
    if ( mnColors > 26 )
    {
        sal_uInt8 nDiff = (sal_uInt8) ( nCol / 26 );
        m_rOStm << (sal_uInt8)( nDiff + 'A' );
        m_rOStm << (sal_uInt8)( nCol - ( nDiff*26 ) + 'A' );
    }
    else
        m_rOStm << (sal_uInt8)( nCol + 'A' );
}

// ------------------------------------------------------------------------
// ein Farbwert wird im Hexadezimalzahlformat in den Stream geschrieben
void XPMWriter::ImplWriteColor( sal_uInt16 nNumber )
{
    sal_uLong   nTmp;
    sal_uInt8   j;

    m_rOStm << "c #";   // # zeigt einen folgenden Hexwert an
    const BitmapColor& rColor = mpAcc->GetPaletteColor( nNumber );
    nTmp = ( rColor.GetRed() << 16 ) | ( rColor.GetGreen() << 8 ) | rColor.GetBlue();
    for ( signed char i = 20; i >= 0 ; i-=4 )
    {
        if ( ( j = (sal_uInt8)( nTmp >> i ) & 0xf ) > 9 )
            j += 'A' - 10;
        else
            j += '0';
        m_rOStm << j;
    }
}

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

// ---------------------
// - exported function -
// ---------------------

#ifdef DISABLE_DYNLOADING
#define GraphicExport expGraphicExport
#endif

extern "C" SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL
GraphicExport(SvStream& rStream, Graphic& rGraphic, FilterConfigItem* pFilterConfigItem, sal_Bool)
{
    XPMWriter aXPMWriter(rStream);

    return aXPMWriter.WriteXPM( rGraphic, pFilterConfigItem );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#ifndef BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP
#define BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP

#include <Bull/Core/Support/Xlib/Xlib.hpp>

#include <Bull/Render/Context/ExtensionsLoader.hpp>

#define GLX_CONTEXT_OPENGL_NO_ERROR_ARB 0x31B3

#endif // BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP
<commit_msg>[Render/GlxContextNoError] Remove useless header<commit_after>#ifndef BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP
#define BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP

#define GLX_CONTEXT_OPENGL_NO_ERROR_ARB 0x31B3

#endif // BULL_RENDER_CONTEXT_GLX_GLXCONTEXTNOERROR_HPP
<|endoftext|>