<commit_before>
/*

                        /~` _  _ _|_. _     _ |_ | _
                        \_,(_)| | | || ||_|(_||_)|(/_

                    https://github.com/Naios/continuable
                                   v4.0.0

  Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files(the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions :

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
**/

#ifndef CONTINUABLE_RESULT_HPP_INCLUDED
#define CONTINUABLE_RESULT_HPP_INCLUDED

#include <type_traits>
#include <utility>
#include <continuable/continuable-primitives.hpp>
#include <continuable/detail/utility/flat-variant.hpp>
#include <continuable/detail/utility/result-trait.hpp>
#include <continuable/detail/utility/traits.hpp>
#include <continuable/detail/utility/util.hpp>

namespace cti {
/// \defgroup Result Result
/// provides the \ref result class and corresponding utility functions to work
/// with the result of an asynchronous operation which can possibly yield:
/// - *no result*: If the operation didn't finish
/// - *a value*: If the operation finished successfully
/// - *an exception*: If the operation finished with an exception
/// \{

/// A class which is convertible to any \ref result and that definitly holds no
/// value so the real result gets invalidated when this object is passed to it.
///
/// \since 4.0.0
///
struct empty_result {};

/// A class which is convertible to any result and that definitly holds
/// an exception which is then passed to the converted result object.
///
/// \since 4.0.0
///
class exceptional_result {
  exception_t exception_;

public:
  exceptional_result() = delete;
  exceptional_result(exceptional_result const&) = default;
  exceptional_result(exceptional_result&&) = default;
  exceptional_result& operator=(exceptional_result const&) = default;
  exceptional_result& operator=(exceptional_result&&) = default;
  ~exceptional_result() = default;

  explicit exceptional_result(exception_t exception)
      // NOLINTNEXTLINE(hicpp-move-const-arg, performance-move-const-arg)
      : exception_(std::move(exception)) {
  }

  exceptional_result& operator=(exception_t exception) {
    // NOLINTNEXTLINE(hicpp-move-const-arg, performance-move-const-arg)
    exception_ = std::move(exception);
    return *this;
  }

  /// Sets an exception
  void set_exception(exception_t exception) {
    // NOLINTNEXTLINE(hicpp-move-const-arg, performance-move-const-arg)
    exception_ = std::move(exception);
  }

  /// Returns the contained exception
  exception_t& get_exception() & noexcept {
    return exception_;
  }
  /// \copydoc get_exception
  exception_t const& get_exception() const& noexcept {
    return exception_;
  }
  /// \copydoc get_exception
  exception_t&& get_exception() && noexcept {
    return std::move(exception_);
  }
};

/// The result class can carry the three kinds of results an asynchronous
/// operation possibly can return, it's implemented in a variant like
/// data structure which is also specialized to hold arbitrary arguments.
///
/// The result can be in the following three states:
/// - *no result*: If the operation didn't finish
/// - *a value*: If the operation finished successfully
/// - *an exception*: If the operation finished with an exception
///
/// The interface of the result object is similar to the one proposed in
/// the `std::expected` proposal:
/// ```cpp
/// result<std::string> result = make_result("Hello World!");
/// bool(result);
/// result.is_value();
/// result.is_exception();
/// *result; // Same as result.get_value()
/// result.get_value();
/// result.get_exception();
/// ```
///
/// \since 4.0.0
///
template <typename... T>
class result {
  using trait_t = detail::result_trait<T...>;
  using surrogate_t = typename trait_t::surrogate_t;

  struct init_arg_t {};

  template <typename... Args, detail::traits::void_t<decltype(trait_t::wrap(
                                  std::declval<Args>()...))>* = nullptr>
  explicit result(init_arg_t, Args&&... values)
      : variant_(trait_t::wrap(std::forward<Args>(values)...)) {
  }
  explicit result(init_arg_t, exception_t exception)
      : variant_(std::move(exception)) {
  }

public:
  using value_t = typename trait_t::value_t;

  template <typename FirstArg, typename... Args,
            detail::traits::void_t<decltype(trait_t::wrap(
                std::declval<FirstArg>(), std::declval<Args>()...))>* = nullptr>
  explicit result(FirstArg&& first, Args&&... values)
      : variant_(trait_t::wrap(std::forward<FirstArg>(first),
                               std::forward<Args>(values)...)) {
  }

  result() = default;
  result(result const&) = default;
  result(result&&) = default;
  result& operator=(result const&) = default;
  result& operator=(result&&) = default;
  ~result() = default;

  explicit result(exception_t exception) : variant_(std::move(exception)) {
  }
  result(empty_result) {
  }
  result(exceptional_result exceptional_result)
      : variant_(std::move(exceptional_result.get_exception())) {
  }

  result& operator=(empty_result) {
    set_empty();
    return *this;
  }
  result& operator=(exceptional_result exceptional_result) {
    set_exception(std::move(exceptional_result.get_exception()));
    return *this;
  }

  /// Set the result to an empty state
  void set_empty() {
    variant_.set_empty();
  }
  /// Set the result to a the state which holds the corresponding value
  void set_value(T... values) {
    variant_ = trait_t::wrap(std::move(values)...);
  }
  /// Set the result into a state which holds the corresponding exception
  void set_exception(exception_t exception) {
    variant_ = std::move(exception);
  }

  /// Returns true if the state of the result is empty
  bool is_empty() const noexcept {
    return variant_.is_empty();
  }
  /// Returns true if the state of the result holds the result
  bool is_value() const noexcept {
    return variant_.template is<surrogate_t>();
  }
  /// Returns true if the state of the result holds an exception
  bool is_exception() const noexcept {
    return variant_.template is<exception_t>();
  }

  /// \copydoc is_value
  explicit constexpr operator bool() const noexcept {
    return is_value();
  }

  /// Returns the values of the result, if the result doesn't hold the value
  /// the behaviour is undefined but will assert in debug mode.
  decltype(auto) get_value() & noexcept {
    return trait_t::unwrap(variant_.template cast<surrogate_t>());
  }
  ///\copydoc get_value
  decltype(auto) get_value() const& noexcept {
    return trait_t::unwrap(variant_.template cast<surrogate_t>());
  }
  ///\copydoc get_value
  decltype(auto) get_value() && noexcept {
    return trait_t::unwrap(std::move(variant_).template cast<surrogate_t>());
  }

  ///\copydoc get_value
  decltype(auto) operator*() & noexcept {
    return get_value();
  }
  ///\copydoc get_value
  decltype(auto) operator*() const& noexcept {
    return get_value();
  }
  ///\copydoc get_value
  decltype(auto) operator*() && noexcept {
    return std::move(*this).get_value();
  }

  /// Returns the exception of the result, if the result doesn't hold an
  /// exception the behaviour is undefined but will assert in debug mode.
  exception_t& get_exception() & noexcept {
    return variant_.template cast<exception_t>();
  }
  /// \copydoc get_exception
  exception_t const& get_exception() const& noexcept {
    return variant_.template cast<exception_t>();
  }
  /// \copydoc get_exception
  exception_t&& get_exception() && noexcept {
    return std::move(variant_).template cast<exception_t>();
  }

  /// Creates a present result from the given values
  static result from(T... values) {
    return result{init_arg_t{}, std::move(values)...};
  }
  /// Creates a present result from the given exception
  static result from(exception_t exception) {
    return result{init_arg_t{}, std::move(exception)};
  }

private:
  detail::container::flat_variant<surrogate_t, exception_t> variant_;
};

/// Returns the value at position I of the given result
template <std::size_t I, typename... T>
decltype(auto) get(result<T...>& result) {
  return detail::result_trait<T...>::template get<I>(result);
}
/// \copydoc get
template <std::size_t I, typename... T>
decltype(auto) get(result<T...> const& result) {
  return detail::result_trait<T...>::template get<I>(result);
}
/// \copydoc get
template <std::size_t I, typename... T>
decltype(auto) get(result<T...>&& result) {
  return detail::result_trait<T...>::template get<I>(std::move(result));
}

/// Creates a present result from the given values
///
/// \since 4.0.0
template <typename... T,
          typename Result = result<detail::traits::unrefcv_t<T>...>>
Result make_result(T&&... values) {
  return Result::from(std::forward<T>(values)...);
}
/// \}
} // namespace cti

namespace std {
// The GCC standard library defines tuple_size as class and struct which
// triggers a warning here.
#if defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmismatched-tags"
#endif
template <typename... Args>
struct tuple_size<cti::result<Args...>>
    : std::integral_constant<size_t, sizeof...(Args)> {};

template <std::size_t I, typename... Args>
struct tuple_element<I, cti::result<Args...>>
    : tuple_element<I, tuple<Args...>> {};
#if defined(__clang__) || defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
} // namespace std

#endif // CONTINUABLE_RESULT_HPP_INCLUDED
<commit_msg>Remove a bad GCC diagnostic pop when using result<...> and GCC<commit_after>
/*

                        /~` _  _ _|_. _     _ |_ | _
                        \_,(_)| | | || ||_|(_||_)|(/_

                    https://github.com/Naios/continuable
                                   v4.0.0

  Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files(the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions :

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
**/

#ifndef CONTINUABLE_RESULT_HPP_INCLUDED
#define CONTINUABLE_RESULT_HPP_INCLUDED

#include <type_traits>
#include <utility>
#include <continuable/continuable-primitives.hpp>
#include <continuable/detail/utility/flat-variant.hpp>
#include <continuable/detail/utility/result-trait.hpp>
#include <continuable/detail/utility/traits.hpp>
#include <continuable/detail/utility/util.hpp>

namespace cti {
/// \defgroup Result Result
/// provides the \ref result class and corresponding utility functions to work
/// with the result of an asynchronous operation which can possibly yield:
/// - *no result*: If the operation didn't finish
/// - *a value*: If the operation finished successfully
/// - *an exception*: If the operation finished with an exception
/// \{

/// A class which is convertible to any \ref result and that definitly holds no
/// value so the real result gets invalidated when this object is passed to it.
///
/// \since 4.0.0
///
struct empty_result {};

/// A class which is convertible to any result and that definitly holds
/// an exception which is then passed to the converted result object.
///
/// \since 4.0.0
///
class exceptional_result {
  exception_t exception_;

public:
  exceptional_result() = delete;
  exceptional_result(exceptional_result const&) = default;
  exceptional_result(exceptional_result&&) = default;
  exceptional_result& operator=(exceptional_result const&) = default;
  exceptional_result& operator=(exceptional_result&&) = default;
  ~exceptional_result() = default;

  explicit exceptional_result(exception_t exception)
      // NOLINTNEXTLINE(hicpp-move-const-arg, performance-move-const-arg)
      : exception_(std::move(exception)) {
  }

  exceptional_result& operator=(exception_t exception) {
    // NOLINTNEXTLINE(hicpp-move-const-arg, performance-move-const-arg)
    exception_ = std::move(exception);
    return *this;
  }

  /// Sets an exception
  void set_exception(exception_t exception) {
    // NOLINTNEXTLINE(hicpp-move-const-arg, performance-move-const-arg)
    exception_ = std::move(exception);
  }

  /// Returns the contained exception
  exception_t& get_exception() & noexcept {
    return exception_;
  }
  /// \copydoc get_exception
  exception_t const& get_exception() const& noexcept {
    return exception_;
  }
  /// \copydoc get_exception
  exception_t&& get_exception() && noexcept {
    return std::move(exception_);
  }
};

/// The result class can carry the three kinds of results an asynchronous
/// operation possibly can return, it's implemented in a variant like
/// data structure which is also specialized to hold arbitrary arguments.
///
/// The result can be in the following three states:
/// - *no result*: If the operation didn't finish
/// - *a value*: If the operation finished successfully
/// - *an exception*: If the operation finished with an exception
///
/// The interface of the result object is similar to the one proposed in
/// the `std::expected` proposal:
/// ```cpp
/// result<std::string> result = make_result("Hello World!");
/// bool(result);
/// result.is_value();
/// result.is_exception();
/// *result; // Same as result.get_value()
/// result.get_value();
/// result.get_exception();
/// ```
///
/// \since 4.0.0
///
template <typename... T>
class result {
  using trait_t = detail::result_trait<T...>;
  using surrogate_t = typename trait_t::surrogate_t;

  struct init_arg_t {};

  template <typename... Args, detail::traits::void_t<decltype(trait_t::wrap(
                                  std::declval<Args>()...))>* = nullptr>
  explicit result(init_arg_t, Args&&... values)
      : variant_(trait_t::wrap(std::forward<Args>(values)...)) {
  }
  explicit result(init_arg_t, exception_t exception)
      : variant_(std::move(exception)) {
  }

public:
  using value_t = typename trait_t::value_t;

  template <typename FirstArg, typename... Args,
            detail::traits::void_t<decltype(trait_t::wrap(
                std::declval<FirstArg>(), std::declval<Args>()...))>* = nullptr>
  explicit result(FirstArg&& first, Args&&... values)
      : variant_(trait_t::wrap(std::forward<FirstArg>(first),
                               std::forward<Args>(values)...)) {
  }

  result() = default;
  result(result const&) = default;
  result(result&&) = default;
  result& operator=(result const&) = default;
  result& operator=(result&&) = default;
  ~result() = default;

  explicit result(exception_t exception) : variant_(std::move(exception)) {
  }
  result(empty_result) {
  }
  result(exceptional_result exceptional_result)
      : variant_(std::move(exceptional_result.get_exception())) {
  }

  result& operator=(empty_result) {
    set_empty();
    return *this;
  }
  result& operator=(exceptional_result exceptional_result) {
    set_exception(std::move(exceptional_result.get_exception()));
    return *this;
  }

  /// Set the result to an empty state
  void set_empty() {
    variant_.set_empty();
  }
  /// Set the result to a the state which holds the corresponding value
  void set_value(T... values) {
    variant_ = trait_t::wrap(std::move(values)...);
  }
  /// Set the result into a state which holds the corresponding exception
  void set_exception(exception_t exception) {
    variant_ = std::move(exception);
  }

  /// Returns true if the state of the result is empty
  bool is_empty() const noexcept {
    return variant_.is_empty();
  }
  /// Returns true if the state of the result holds the result
  bool is_value() const noexcept {
    return variant_.template is<surrogate_t>();
  }
  /// Returns true if the state of the result holds an exception
  bool is_exception() const noexcept {
    return variant_.template is<exception_t>();
  }

  /// \copydoc is_value
  explicit constexpr operator bool() const noexcept {
    return is_value();
  }

  /// Returns the values of the result, if the result doesn't hold the value
  /// the behaviour is undefined but will assert in debug mode.
  decltype(auto) get_value() & noexcept {
    return trait_t::unwrap(variant_.template cast<surrogate_t>());
  }
  ///\copydoc get_value
  decltype(auto) get_value() const& noexcept {
    return trait_t::unwrap(variant_.template cast<surrogate_t>());
  }
  ///\copydoc get_value
  decltype(auto) get_value() && noexcept {
    return trait_t::unwrap(std::move(variant_).template cast<surrogate_t>());
  }

  ///\copydoc get_value
  decltype(auto) operator*() & noexcept {
    return get_value();
  }
  ///\copydoc get_value
  decltype(auto) operator*() const& noexcept {
    return get_value();
  }
  ///\copydoc get_value
  decltype(auto) operator*() && noexcept {
    return std::move(*this).get_value();
  }

  /// Returns the exception of the result, if the result doesn't hold an
  /// exception the behaviour is undefined but will assert in debug mode.
  exception_t& get_exception() & noexcept {
    return variant_.template cast<exception_t>();
  }
  /// \copydoc get_exception
  exception_t const& get_exception() const& noexcept {
    return variant_.template cast<exception_t>();
  }
  /// \copydoc get_exception
  exception_t&& get_exception() && noexcept {
    return std::move(variant_).template cast<exception_t>();
  }

  /// Creates a present result from the given values
  static result from(T... values) {
    return result{init_arg_t{}, std::move(values)...};
  }
  /// Creates a present result from the given exception
  static result from(exception_t exception) {
    return result{init_arg_t{}, std::move(exception)};
  }

private:
  detail::container::flat_variant<surrogate_t, exception_t> variant_;
};

/// Returns the value at position I of the given result
template <std::size_t I, typename... T>
decltype(auto) get(result<T...>& result) {
  return detail::result_trait<T...>::template get<I>(result);
}
/// \copydoc get
template <std::size_t I, typename... T>
decltype(auto) get(result<T...> const& result) {
  return detail::result_trait<T...>::template get<I>(result);
}
/// \copydoc get
template <std::size_t I, typename... T>
decltype(auto) get(result<T...>&& result) {
  return detail::result_trait<T...>::template get<I>(std::move(result));
}

/// Creates a present result from the given values
///
/// \since 4.0.0
template <typename... T,
          typename Result = result<detail::traits::unrefcv_t<T>...>>
Result make_result(T&&... values) {
  return Result::from(std::forward<T>(values)...);
}
/// \}
} // namespace cti

namespace std {
// The GCC standard library defines tuple_size as class and struct which
// triggers a warning here.
#if defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmismatched-tags"
#endif
template <typename... Args>
struct tuple_size<cti::result<Args...>>
    : std::integral_constant<size_t, sizeof...(Args)> {};

template <std::size_t I, typename... Args>
struct tuple_element<I, cti::result<Args...>>
    : tuple_element<I, tuple<Args...>> {};
#if defined(__clang__)
#pragma GCC diagnostic pop
#endif
} // namespace std

#endif // CONTINUABLE_RESULT_HPP_INCLUDED
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#ifndef FLUSSPFERD_PROPERTY_ATTRIBUTES
#define FLUSSPFERD_PROPERTY_ATTRIBUTES

#include <boost/optional.hpp>

namespace flusspferd {

class function;

/*
 * Property flags.
 *
 * @ingroup property_types
 */
enum property_flag {
  /// The property is normal.
  no_property_flag = 0U,

  /// The property is not enumerable.
  dont_enumerate = 1U,

  /// The property is read-only.
  read_only_property = 2U,

  /// The property can not be deleted.
  permanent_property = 4U,

  /// The property's attributes are shared between objects.
  shared_property = 8U,

  /// The property is both permanent and shared.
  permanent_shared_property = 12U
};

/**
 * Combine (union).
 *
 * @relates property_flag
 */
inline property_flag operator|(property_flag a, property_flag b) {
  return static_cast<property_flag>(unsigned(a) | unsigned(b));
}

/**
 * Combine (intersection).
 */
inline property_flag operator&(property_flag a, property_flag b) {
  return static_cast<property_flag>(unsigned(a) & unsigned(b));
}

/**
 * Invert.
 */
inline property_flag operator~(property_flag x) {
  return static_cast<property_flag>(~unsigned(x));
}

/**
 * A property's attributes: flags, getters and setters.
 *
 * @ingroup property_types
 */
struct property_attributes {
  /// The property's flags.
  property_flag flags;

  /**
   *  The property's getter.
   *
   *  A function returning the property's value.
   */
  boost::optional<function const &> getter;

  /**
   * The property's setter.
   *
   * A function taking the property's value.
   */
  boost::optional<function const &> setter;

  /// Construct default attributes.
  property_attributes();

  /**
   * Construct property attributes.
   *
   * @param flags The flags.
   * @param getter The getter.
   * @param setter The setter.
   */
  property_attributes(property_flag flags,
    boost::optional<function const &> getter = boost::none,
    boost::optional<function const &> setter = boost::none);
};

}

#endif
<commit_msg>changed property_attribute to own getter/setter member. (fix #158)<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#ifndef FLUSSPFERD_PROPERTY_ATTRIBUTES
#define FLUSSPFERD_PROPERTY_ATTRIBUTES

#include <boost/optional.hpp>

namespace flusspferd {

class function;

/*
 * Property flags.
 *
 * @ingroup property_types
 */
enum property_flag {
  /// The property is normal.
  no_property_flag = 0U,

  /// The property is not enumerable.
  dont_enumerate = 1U,

  /// The property is read-only.
  read_only_property = 2U,

  /// The property can not be deleted.
  permanent_property = 4U,

  /// The property's attributes are shared between objects.
  shared_property = 8U,

  /// The property is both permanent and shared.
  permanent_shared_property = 12U
};

/**
 * Combine (union).
 *
 * @relates property_flag
 */
inline property_flag operator|(property_flag a, property_flag b) {
  return static_cast<property_flag>(unsigned(a) | unsigned(b));
}

/**
 * Combine (intersection).
 */
inline property_flag operator&(property_flag a, property_flag b) {
  return static_cast<property_flag>(unsigned(a) & unsigned(b));
}

/**
 * Invert.
 */
inline property_flag operator~(property_flag x) {
  return static_cast<property_flag>(~unsigned(x));
}

/**
 * A property's attributes: flags, getters and setters.
 *
 * @ingroup property_types
 */
struct property_attributes {
  /// The property's flags.
  property_flag flags;

  /**
   *  The property's getter.
   *
   *  A function returning the property's value.
   */
  boost::optional<function> getter;

  /**
   * The property's setter.
   *
   * A function taking the property's value.
   */
  boost::optional<function> setter;

  /// Construct default attributes.
  property_attributes();

  /**
   * Construct property attributes.
   *
   * @param flags The flags.
   * @param getter The getter.
   * @param setter The setter.
   */
  property_attributes(property_flag flags,
    boost::optional<function const &> getter = boost::none,
    boost::optional<function const &> setter = boost::none);
};

}

#endif
<|endoftext|>


<commit_before>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/IO/XMLObjectReader.h>

#include <vector>

#include <boost/static_assert.hpp>
#include <vpr/IO/ObjectReader.h>

#include <vpr/Util/Assert.h>
#include <vpr/Util/Debug.h>

#include <cppdom/cppdom.h>
#include <cppdom/version.h>
#include <string>
#include <sstream>
#include <iterator>

#define XML_OR_LEVEL vprDBG_HEX_LVL

namespace
{
 /** Helper to read the data from the current string. */
 template<class T>
 vpr::ReturnStatus readValueStringRep(T& val, std::stringstream* inStream)
 {
    vprASSERT(inStream != NULL);

    // Just to be safe do this again for the heck of it. :)
    //in_stream->exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );
    vprASSERT(!inStream->bad() && "Bad stream, BAAADDD stream.");
    vprASSERT(!inStream->fail() && "Stream failed.");
    vprASSERT(!inStream->eof() && "Stream EOF'd.");
    vprASSERT(inStream->good());

    //stream_content = (*in_stream).str();

    (*inStream) >> val;

    return vpr::ReturnStatus::Succeed;
 }

}

namespace vpr
{

XMLObjectReader::XMLObjectReader(std::vector<vpr::Uint8> data)
   : mCurSource(CdataSource)
{
   initCppDomTree(data);
   //mAttribSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );
}

XMLObjectReader::XMLObjectReader(cppdom::NodePtr rootNode)
   : mCurSource(CdataSource)
{
   mRootNode = rootNode;
   //mAttribSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );
}

XMLObjectReader::NodeState::NodeState(cppdom::Node* cur_node)
   : node(cur_node)
{
   nextChild_i = node->getChildren().begin();     // Initialize to the first child
   endChild_i = node->getChildren().end();
   //cdataSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );
   cdataSource.str(node->getFullCdata());
}

XMLObjectReader::NodeState::NodeState(const NodeState& rhs)
{
   node = rhs.node;
   nextChild_i = rhs.nextChild_i;
   endChild_i = rhs.endChild_i;
   //cdataSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );
   cdataSource.str(rhs.cdataSource.str());
}

XMLObjectReader::NodeState& XMLObjectReader::NodeState::operator=(const NodeState& rhs)
{
   node = rhs.node;
   nextChild_i = rhs.nextChild_i;
   endChild_i = rhs.endChild_i;
   cdataSource.str(rhs.cdataSource.str());
   return *this;
}

void XMLObjectReader::NodeState::debugDump(int debug_level)
{
   vprDEBUG(vprDBG_ALL, debug_level) << "Node:" << node->getName() << "  num children:" << node->getChildren().size()
                                     << "  distance: nextChild-->endChild:" << std::distance(nextChild_i,endChild_i) << std::endl << vprDEBUG_FLUSH;
}

/** Get the current string source we are reading from.
*/
std::stringstream* XMLObjectReader::getCurSource()
{
   std::stringstream* in_stream(NULL);

   if(AttribSource == mCurSource)
   {
      in_stream = &mAttribSource;
   }
   else
   {
      in_stream = &(mCurNodeStack.back().cdataSource);
   }

   return in_stream;
}

/**
 * Initialize the members based on a serialized version of something in the
 * data buffer.
 */
void XMLObjectReader::initCppDomTree(std::vector<vpr::Uint8> data)
{
   std::string xml_data(data.begin(), data.end());
   std::stringstream xml_stream(xml_data);
   cppdom::ContextPtr cxt(new cppdom::Context);
   cppdom::NodePtr new_node = cppdom::NodePtr(new cppdom::Node(cxt));
   new_node->load(xml_stream, cxt);

   mRootNode = new_node;

   std::string root_name = mRootNode->getName();   // Debugging

   mCurNodeStack.clear();
}

void XMLObjectReader::debugDumpStack(int debug_level)
{
   vprDEBUG_OutputGuard(vprDBG_ALL, debug_level, "mCurNodeStack:\n", "end node stack\n");

   for(unsigned i=0; i<mCurNodeStack.size(); ++i)
   {
      mCurNodeStack[i].debugDump(debug_level);
   }
}

/**
 * Starting a new tag.
 * Get the local cdata into the current data source.
 */
vpr::ReturnStatus XMLObjectReader::beginTag(std::string tagName)
{
   vprDEBUG_OutputGuard(vprDBG_ALL, XML_OR_LEVEL, std::string("beginTag:[") + tagName + std::string("]\n"), "endTag");

   vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "mCurNodeStack: size: " << mCurNodeStack.size() << std::endl << vprDEBUG_FLUSH;
   debugDumpStack(XML_OR_LEVEL);

   // Find the correct child
   if(mCurNodeStack.empty())  // We should enter the root
   {
      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "mCurNodeStack is empty. Push on root.\n" << vprDEBUG_FLUSH;
      mCurNodeStack.push_back(NodeState(mRootNode.get()));
   }
   else                      // Find the next child and push it on
   {
      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "Attempting to find next child: "
                             << " cur node (back): " << mCurNodeStack.back().node->getName()
                             << "  num children:" << mCurNodeStack.back().node->getChildren().size() << std::endl << vprDEBUG_FLUSH;

      vprASSERT(mCurNodeStack.back().nextChild_i != mCurNodeStack.back().endChild_i && "Past last child. No remaining child tags.");

      // Make sure that we get to child of type node.
      // While next child is not of type node skip over cdata...
#if CPPDOM_VERSION_MAJOR == 0 && CPPDOM_VERSION_MINOR < 4
      while( (*(mCurNodeStack.back().nextChild_i))->getType() != cppdom::xml_nt_node)
#else
      while( (*(mCurNodeStack.back().nextChild_i))->getType() != cppdom::Node::xml_nt_node)
#endif
      {
         vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "Skip node: " << (*(mCurNodeStack.back().nextChild_i))->getName() << " -- non nt_node type.\n" << vprDEBUG_FLUSH;
         mCurNodeStack.back().nextChild_i++;
         vprASSERT(mCurNodeStack.back().nextChild_i != mCurNodeStack.back().endChild_i && "Skipped past last child. No remaining child tags.");
      }

      cppdom::NodePtr tag_node = *(mCurNodeStack.back().nextChild_i);   // Get the node with the given tag
      mCurNodeStack.back().nextChild_i++;                               // Step to the next child for next time

      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "Incrementing next child:  at end:" << (mCurNodeStack.back().nextChild_i == mCurNodeStack.back().endChild_i) << std::endl << vprDEBUG_FLUSH;

      mCurNodeStack.push_back( NodeState(tag_node.get()));              // Add the child to the stack
      vprASSERT(tag_node.get() == mCurNodeStack.back().node);

      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "Found node:" << tag_node->getName() << std::endl << vprDEBUG_FLUSH;
      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "  Node stack size:" << mCurNodeStack.size() << std::endl << vprDEBUG_FLUSH;
      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "  Num children:" << tag_node->getChildren().size() << std::endl << vprDEBUG_FLUSH;
      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "  New node child at end:" << (mCurNodeStack.back().nextChild_i == mCurNodeStack.back().endChild_i)
                             << std::endl << vprDEBUG_FLUSH;
   }

   std::string cur_node_name = mCurNodeStack.back().node->getName();
   vprASSERT(tagName == cur_node_name && "Reading back in incorrect order");
   return vpr::ReturnStatus::Succeed;
}

/**
 * Ends the most recently named tag.
 * Just pop of the current node state information.
 */
vpr::ReturnStatus XMLObjectReader::endTag()
{
   vprASSERT(!mCurNodeStack.empty());
   mCurNodeStack.pop_back();
   return vpr::ReturnStatus::Succeed;
}

/**
 * Starts an attribute of the name attributeName.
 * Get the attribute content and set the attribute source with that content.
 */
vpr::ReturnStatus XMLObjectReader::beginAttribute(std::string attributeName)
{
   //std::cout << "beginAttribute: " << attributeName << std::endl;
   std::string attrib_content = mCurNodeStack.back().node->getAttribute(attributeName).getString();
   //std::cout << "  attrib content: [" << attrib_content << "]\n";
   mAttribSource.clear();                       // Clear error states
   mAttribSource.str(attrib_content);
   mAttribSource.seekg(0,std::ios::beg);        // Seek to beginning
   //std::cout << "  mAttribSource.str():[" << mAttribSource.str() << "]" << std::endl;
   mCurSource = AttribSource;             // Get content from attribute now
   return vpr::ReturnStatus::Succeed;
}

/** Ends the most recently named attribute. */
vpr::ReturnStatus XMLObjectReader::endAttribute()
{
   mAttribSource.clear();
   mAttribSource.seekg(0,std::ios::beg);
   mAttribSource.str("");     // Clear the attrib content (not required, but helps point out bugs)
   mCurSource = CdataSource;     // Set back to getting data from cdata
   return vpr::ReturnStatus::Succeed;
}
//@}

void XMLObjectReader::resetReading()
{
   mCurSource = CdataSource;
   mCurNodeStack.clear();
}

void XMLObjectReader::pushState()
{
   ReadState cur_state;
   cur_state.mNodeStack = mCurNodeStack;
   mReadStateStack.push_back(cur_state);
}

void XMLObjectReader::popState()
{
   ReadState new_state = mReadStateStack.back();
   mReadStateStack.pop_back();
   mCurNodeStack = new_state.mNodeStack;
}

vpr::Uint8 XMLObjectReader::readUint8()
{
   // Read a uint16 so that it does not treat it as a single char
   vpr::Uint16 temp_data;
   readValueStringRep(temp_data, getCurSource());
   return vpr::Uint8(temp_data);
}

vpr::Uint16 XMLObjectReader::readUint16()
{
   vpr::Uint16 val;
   readValueStringRep(val, getCurSource());
   return val;
}

vpr::Uint32 XMLObjectReader::readUint32()
{
   vpr::Uint32 val;
   readValueStringRep(val, getCurSource());
   return val;
}

vpr::Uint64 XMLObjectReader::readUint64()
{
   vpr::Uint64 val;
   readValueStringRep(val, getCurSource());
   return val;
}

float XMLObjectReader::readFloat()
{
   float val;
   readValueStringRep(val, getCurSource());
   return val;
}

double XMLObjectReader::readDouble()
{
   double val;
   readValueStringRep(val, getCurSource());
   return val;
}

std::string XMLObjectReader::readString()
{
   std::string ret_val("");

   if(AttribSource == mCurSource)   // Just return a copy of the attribute source
   {
      ret_val = mAttribSource.str();
   }
   else  // Cdata, extract the "'s around the string
   {
      char char_buffer[1024];    // Buffer for writing the final value
      char temp_char('0');

      // Get the first "
      while('"' != temp_char)
      {
         mCurNodeStack.back().cdataSource.get(temp_char);
         vprASSERT(('>' != temp_char) && ('<' != temp_char) && "String delimiter not found");
      }

      // Get the contents of the string
      char next_char = mCurNodeStack.back().cdataSource.peek();
      bool done_reading(next_char == '"');                           // If next char is already ", then we are done reading empty string

      while(!done_reading)
      {
         mCurNodeStack.back().cdataSource.get(char_buffer,1024, '"');      // Copy over to target until we have second "
         ret_val += char_buffer;                                           // append onto end
         next_char = mCurNodeStack.back().cdataSource.peek();
         done_reading = (next_char == '"');     // Done reading if got to a "
      }
      mCurNodeStack.back().cdataSource.ignore(1);                    // Ignore that " as well
   }

   return ret_val;
}

bool XMLObjectReader::readBool()
{
   bool val;
   readValueStringRep(val, getCurSource());
   return val;
}

} // namespace vpr
<commit_msg>Silenced an ICC compiler warning.  I don't know why GCC didn't complain about this one.<commit_after>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/IO/XMLObjectReader.h>

#include <vector>

#include <boost/concept_check.hpp>
#include <boost/static_assert.hpp>
#include <vpr/IO/ObjectReader.h>

#include <vpr/Util/Assert.h>
#include <vpr/Util/Debug.h>

#include <cppdom/cppdom.h>
#include <cppdom/version.h>
#include <string>
#include <sstream>
#include <iterator>

#define XML_OR_LEVEL vprDBG_HEX_LVL

namespace
{
 /** Helper to read the data from the current string. */
 template<class T>
 vpr::ReturnStatus readValueStringRep(T& val, std::stringstream* inStream)
 {
    vprASSERT(inStream != NULL);

    // Just to be safe do this again for the heck of it. :)
    //in_stream->exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );
    vprASSERT(!inStream->bad() && "Bad stream, BAAADDD stream.");
    vprASSERT(!inStream->fail() && "Stream failed.");
    vprASSERT(!inStream->eof() && "Stream EOF'd.");
    vprASSERT(inStream->good());

    //stream_content = (*in_stream).str();

    (*inStream) >> val;

    return vpr::ReturnStatus::Succeed;
 }

}

namespace vpr
{

XMLObjectReader::XMLObjectReader(std::vector<vpr::Uint8> data)
   : mCurSource(CdataSource)
{
   initCppDomTree(data);
   //mAttribSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );
}

XMLObjectReader::XMLObjectReader(cppdom::NodePtr rootNode)
   : mCurSource(CdataSource)
{
   mRootNode = rootNode;
   //mAttribSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );
}

XMLObjectReader::NodeState::NodeState(cppdom::Node* cur_node)
   : node(cur_node)
{
   nextChild_i = node->getChildren().begin();     // Initialize to the first child
   endChild_i = node->getChildren().end();
   //cdataSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );
   cdataSource.str(node->getFullCdata());
}

XMLObjectReader::NodeState::NodeState(const NodeState& rhs)
{
   node = rhs.node;
   nextChild_i = rhs.nextChild_i;
   endChild_i = rhs.endChild_i;
   //cdataSource.exceptions( std::ios::eofbit | std::ios::failbit | std::ios::badbit );
   cdataSource.str(rhs.cdataSource.str());
}

XMLObjectReader::NodeState& XMLObjectReader::NodeState::operator=(const NodeState& rhs)
{
   node = rhs.node;
   nextChild_i = rhs.nextChild_i;
   endChild_i = rhs.endChild_i;
   cdataSource.str(rhs.cdataSource.str());
   return *this;
}

void XMLObjectReader::NodeState::debugDump(int debug_level)
{
   vprDEBUG(vprDBG_ALL, debug_level) << "Node:" << node->getName() << "  num children:" << node->getChildren().size()
                                     << "  distance: nextChild-->endChild:" << std::distance(nextChild_i,endChild_i) << std::endl << vprDEBUG_FLUSH;
}

/** Get the current string source we are reading from.
*/
std::stringstream* XMLObjectReader::getCurSource()
{
   std::stringstream* in_stream(NULL);

   if(AttribSource == mCurSource)
   {
      in_stream = &mAttribSource;
   }
   else
   {
      in_stream = &(mCurNodeStack.back().cdataSource);
   }

   return in_stream;
}

/**
 * Initialize the members based on a serialized version of something in the
 * data buffer.
 */
void XMLObjectReader::initCppDomTree(std::vector<vpr::Uint8> data)
{
   std::string xml_data(data.begin(), data.end());
   std::stringstream xml_stream(xml_data);
   cppdom::ContextPtr cxt(new cppdom::Context);
   cppdom::NodePtr new_node = cppdom::NodePtr(new cppdom::Node(cxt));
   new_node->load(xml_stream, cxt);

   mRootNode = new_node;

#ifdef VPR_DEBUG
   std::string root_name = mRootNode->getName();   // Debugging
   boost::ignore_unused_variable_warning(root_name);
#endif

   mCurNodeStack.clear();
}

void XMLObjectReader::debugDumpStack(int debug_level)
{
   vprDEBUG_OutputGuard(vprDBG_ALL, debug_level, "mCurNodeStack:\n", "end node stack\n");

   for(unsigned i=0; i<mCurNodeStack.size(); ++i)
   {
      mCurNodeStack[i].debugDump(debug_level);
   }
}

/**
 * Starting a new tag.
 * Get the local cdata into the current data source.
 */
vpr::ReturnStatus XMLObjectReader::beginTag(std::string tagName)
{
   vprDEBUG_OutputGuard(vprDBG_ALL, XML_OR_LEVEL, std::string("beginTag:[") + tagName + std::string("]\n"), "endTag");

   vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "mCurNodeStack: size: " << mCurNodeStack.size() << std::endl << vprDEBUG_FLUSH;
   debugDumpStack(XML_OR_LEVEL);

   // Find the correct child
   if(mCurNodeStack.empty())  // We should enter the root
   {
      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "mCurNodeStack is empty. Push on root.\n" << vprDEBUG_FLUSH;
      mCurNodeStack.push_back(NodeState(mRootNode.get()));
   }
   else                      // Find the next child and push it on
   {
      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "Attempting to find next child: "
                             << " cur node (back): " << mCurNodeStack.back().node->getName()
                             << "  num children:" << mCurNodeStack.back().node->getChildren().size() << std::endl << vprDEBUG_FLUSH;

      vprASSERT(mCurNodeStack.back().nextChild_i != mCurNodeStack.back().endChild_i && "Past last child. No remaining child tags.");

      // Make sure that we get to child of type node.
      // While next child is not of type node skip over cdata...
#if CPPDOM_VERSION_MAJOR == 0 && CPPDOM_VERSION_MINOR < 4
      while( (*(mCurNodeStack.back().nextChild_i))->getType() != cppdom::xml_nt_node)
#else
      while( (*(mCurNodeStack.back().nextChild_i))->getType() != cppdom::Node::xml_nt_node)
#endif
      {
         vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "Skip node: " << (*(mCurNodeStack.back().nextChild_i))->getName() << " -- non nt_node type.\n" << vprDEBUG_FLUSH;
         mCurNodeStack.back().nextChild_i++;
         vprASSERT(mCurNodeStack.back().nextChild_i != mCurNodeStack.back().endChild_i && "Skipped past last child. No remaining child tags.");
      }

      cppdom::NodePtr tag_node = *(mCurNodeStack.back().nextChild_i);   // Get the node with the given tag
      mCurNodeStack.back().nextChild_i++;                               // Step to the next child for next time

      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "Incrementing next child:  at end:" << (mCurNodeStack.back().nextChild_i == mCurNodeStack.back().endChild_i) << std::endl << vprDEBUG_FLUSH;

      mCurNodeStack.push_back( NodeState(tag_node.get()));              // Add the child to the stack
      vprASSERT(tag_node.get() == mCurNodeStack.back().node);

      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "Found node:" << tag_node->getName() << std::endl << vprDEBUG_FLUSH;
      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "  Node stack size:" << mCurNodeStack.size() << std::endl << vprDEBUG_FLUSH;
      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "  Num children:" << tag_node->getChildren().size() << std::endl << vprDEBUG_FLUSH;
      vprDEBUG(vprDBG_ALL,XML_OR_LEVEL) << "  New node child at end:" << (mCurNodeStack.back().nextChild_i == mCurNodeStack.back().endChild_i)
                             << std::endl << vprDEBUG_FLUSH;
   }

   std::string cur_node_name = mCurNodeStack.back().node->getName();
   vprASSERT(tagName == cur_node_name && "Reading back in incorrect order");
   return vpr::ReturnStatus::Succeed;
}

/**
 * Ends the most recently named tag.
 * Just pop of the current node state information.
 */
vpr::ReturnStatus XMLObjectReader::endTag()
{
   vprASSERT(!mCurNodeStack.empty());
   mCurNodeStack.pop_back();
   return vpr::ReturnStatus::Succeed;
}

/**
 * Starts an attribute of the name attributeName.
 * Get the attribute content and set the attribute source with that content.
 */
vpr::ReturnStatus XMLObjectReader::beginAttribute(std::string attributeName)
{
   //std::cout << "beginAttribute: " << attributeName << std::endl;
   std::string attrib_content = mCurNodeStack.back().node->getAttribute(attributeName).getString();
   //std::cout << "  attrib content: [" << attrib_content << "]\n";
   mAttribSource.clear();                       // Clear error states
   mAttribSource.str(attrib_content);
   mAttribSource.seekg(0,std::ios::beg);        // Seek to beginning
   //std::cout << "  mAttribSource.str():[" << mAttribSource.str() << "]" << std::endl;
   mCurSource = AttribSource;             // Get content from attribute now
   return vpr::ReturnStatus::Succeed;
}

/** Ends the most recently named attribute. */
vpr::ReturnStatus XMLObjectReader::endAttribute()
{
   mAttribSource.clear();
   mAttribSource.seekg(0,std::ios::beg);
   mAttribSource.str("");     // Clear the attrib content (not required, but helps point out bugs)
   mCurSource = CdataSource;     // Set back to getting data from cdata
   return vpr::ReturnStatus::Succeed;
}
//@}

void XMLObjectReader::resetReading()
{
   mCurSource = CdataSource;
   mCurNodeStack.clear();
}

void XMLObjectReader::pushState()
{
   ReadState cur_state;
   cur_state.mNodeStack = mCurNodeStack;
   mReadStateStack.push_back(cur_state);
}

void XMLObjectReader::popState()
{
   ReadState new_state = mReadStateStack.back();
   mReadStateStack.pop_back();
   mCurNodeStack = new_state.mNodeStack;
}

vpr::Uint8 XMLObjectReader::readUint8()
{
   // Read a uint16 so that it does not treat it as a single char
   vpr::Uint16 temp_data;
   readValueStringRep(temp_data, getCurSource());
   return vpr::Uint8(temp_data);
}

vpr::Uint16 XMLObjectReader::readUint16()
{
   vpr::Uint16 val;
   readValueStringRep(val, getCurSource());
   return val;
}

vpr::Uint32 XMLObjectReader::readUint32()
{
   vpr::Uint32 val;
   readValueStringRep(val, getCurSource());
   return val;
}

vpr::Uint64 XMLObjectReader::readUint64()
{
   vpr::Uint64 val;
   readValueStringRep(val, getCurSource());
   return val;
}

float XMLObjectReader::readFloat()
{
   float val;
   readValueStringRep(val, getCurSource());
   return val;
}

double XMLObjectReader::readDouble()
{
   double val;
   readValueStringRep(val, getCurSource());
   return val;
}

std::string XMLObjectReader::readString()
{
   std::string ret_val("");

   if(AttribSource == mCurSource)   // Just return a copy of the attribute source
   {
      ret_val = mAttribSource.str();
   }
   else  // Cdata, extract the "'s around the string
   {
      char char_buffer[1024];    // Buffer for writing the final value
      char temp_char('0');

      // Get the first "
      while('"' != temp_char)
      {
         mCurNodeStack.back().cdataSource.get(temp_char);
         vprASSERT(('>' != temp_char) && ('<' != temp_char) && "String delimiter not found");
      }

      // Get the contents of the string
      char next_char = mCurNodeStack.back().cdataSource.peek();
      bool done_reading(next_char == '"');                           // If next char is already ", then we are done reading empty string

      while(!done_reading)
      {
         mCurNodeStack.back().cdataSource.get(char_buffer,1024, '"');      // Copy over to target until we have second "
         ret_val += char_buffer;                                           // append onto end
         next_char = mCurNodeStack.back().cdataSource.peek();
         done_reading = (next_char == '"');     // Done reading if got to a "
      }
      mCurNodeStack.back().cdataSource.ignore(1);                    // Ignore that " as well
   }

   return ret_val;
}

bool XMLObjectReader::readBool()
{
   bool val;
   readValueStringRep(val, getCurSource());
   return val;
}

} // namespace vpr
<|endoftext|>


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

#ifndef MAPNIK_SYMBOLIZER_GRAMMAR_HPP
#define MAPNIK_SYMBOLIZER_GRAMMAR_HPP

// boost
#define BOOST_SPIRIT_USE_PHOENIX_V3 1
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

// mapnik
#include <mapnik/symbolizer.hpp>
#include <mapnik/json/generic_json.hpp>

namespace mapnik { namespace json {

namespace qi = boost::spirit::qi;
namespace phoenix = boost::phoenix;
namespace fusion = boost::fusion;
namespace standard_wide =  boost::spirit::standard_wide;
using standard_wide::space_type;

template <typename T>
struct put_property_visitor : boost::static_visitor<>
{
    typedef T value_type;

    put_property_visitor(mapnik::keys key, value_type const& val)
        : key_(key), val_(val) {}

    template <typename Symbolizer>
    void operator() (Symbolizer & sym) const
    {
        std::cerr << std::get<0>(get_meta(key_)) << ":" << val_ << std::endl;
        // put<value_type>(sym, key_, val_);
    }

    keys key_;
    value_type const& val_;
};

struct put_property
{
    typedef void result_type;
    //explicit put_property(mapnik::transcoder const& tr)
    //    : tr_(tr) {}
    template <typename T0,typename T1, typename T2>
    result_type operator() (T0 & sym, T1 const& name, T2 const& val) const
    {
        try
        {
            boost::apply_visitor(put_property_visitor<T2>(get_key(name),val), sym);
        }
        catch (std::runtime_error const& err)
        {
            std::cerr <<  err.what() << std::endl;
        }
    }
//    mapnik::transcoder const& tr_;
};

template <typename Iterator>
struct symbolizer_grammar : qi::grammar<Iterator, space_type, symbolizer()>
{
    symbolizer_grammar(generic_json<Iterator> & json)
        : symbolizer_grammar::base_type(sym, "symbolizer"),
          json_(json)
    {
        using qi::lit;
        using qi::double_;
        using qi::int_;
        using qi::no_skip;
        using qi::omit;
        using qi::_val;
        using qi::_a;
        using qi::_r1;
        using qi::_1;
        using qi::_2;
        using qi::_3;
        using qi::_4;
        using qi::fail;
        using qi::on_error;
        using standard_wide::char_;
        using phoenix::construct;

        // generic json types
        json_.value =  json_.object | json_.array | json_.string_
            | json_.number
            ;

        json_.pairs = json_.key_value % lit(',')
            ;

        json_.key_value = (json_.string_ >> lit(':') >> json_.value)
            ;

        json_.object = lit('{')
            >> *json_.pairs
            >> lit('}')
            ;

        json_.array = lit('[')
            >> json_.value >> *(lit(',') >> json_.value)
            >> lit(']')
        ;

        json_.number %= json_.strict_double
            | json_.int__
            | lit("true") [_val = true]
            | lit ("false") [_val = false]
            | lit("null")[_val = construct<value_null>()]
            ;
        json_.unesc_char.add
            ("\\\"", '\"') // quotation mark
            ("\\\\", '\\') // reverse solidus
            ("\\/", '/')   // solidus
            ("\\b", '\b')  // backspace
            ("\\f", '\f')  // formfeed
            ("\\n", '\n')  // newline
            ("\\r", '\r')  // carrige return
            ("\\t", '\t')  // tab
        ;

        json_.string_ %= lit('"') >> no_skip[*(json_.unesc_char | "\\u" >> json_.hex4 | (char_ - lit('"')))] >> lit('"')
            ;

        sym = lit('{')
            >> lit("\"type\"") >> lit(':')
            >> (lit("\"PointSymbolizer\"")[_val = construct<point_symbolizer>()]
                |
                lit("\"LineSymbolizer\"")[_val = construct<line_symbolizer>()]
                |
                lit("\"PolygonSymbolizer\"")[_val = construct<polygon_symbolizer>()]
                )
            >> lit(',')
            >> lit("\"properties\"") >> lit(':')
            >> ((lit('{') >> *property(_val) >> lit('}')) | lit("null"))
            >> lit('}')
            ;

        property = (json_.string_ [_a = _1] >> lit(':') >> property_value [put_property_(_r1,_a,_1)]) % lit(',')
            ;

        property_value %= json.number | json.string_  ;

    }

    // generic JSON
    generic_json<Iterator> & json_;
    // symbolizer
    qi::rule<Iterator, space_type, mapnik::symbolizer()> sym;
    qi::rule<Iterator,qi::locals<std::string>, void(mapnik::symbolizer&),space_type> property;
    qi::rule<Iterator,boost::variant<value_null,value_bool,value_integer,value_double, std::string>, space_type> property_value;

    phoenix::function<put_property> put_property_;
    // error
    //boost::phoenix::function<where_message> where_message_;
};

}}

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

#ifndef MAPNIK_SYMBOLIZER_GRAMMAR_HPP
#define MAPNIK_SYMBOLIZER_GRAMMAR_HPP

// boost
#define BOOST_SPIRIT_USE_PHOENIX_V3 1
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

// mapnik
#include <mapnik/symbolizer.hpp>
#include <mapnik/json/generic_json.hpp>

namespace mapnik { namespace json {

namespace qi = boost::spirit::qi;
namespace phoenix = boost::phoenix;
namespace fusion = boost::fusion;
namespace standard_wide =  boost::spirit::standard_wide;
using standard_wide::space_type;

template <typename Symbolizer>
struct json_value_visitor : boost::static_visitor<>
{
    json_value_visitor(Symbolizer & sym, mapnik::keys key)
        : sym_(sym), key_(key) {}

    void operator() (value_bool val) const
    {
        put<value_bool>(sym_, key_, val);
    }

    void operator() (value_integer val) const
    {
        put<value_integer>(sym_, key_, val);
    }

    void operator() (value_double val) const
    {
        put<value_double>(sym_, key_, val);
    }

    void operator() (std::string const& val) const
    {
        std::cerr << std::get<0>(get_meta(key_)) << ":" << val <<  std::endl;
        put<std::string>(sym_, key_, val);
    }

    template <typename T>
    void operator() (T const& val) const
    {
        std::cerr << std::get<0>(get_meta(key_)) << ":" << val <<  std::endl;
        //put<T>(sym_, key_, val);
    }

    Symbolizer & sym_;
    keys key_;
};

template <typename T>
struct put_property_visitor : boost::static_visitor<>
{
    typedef T value_type;

    put_property_visitor(mapnik::keys key, value_type const& val)
        : key_(key), val_(val) {}

    template <typename Symbolizer>
    void operator() (Symbolizer & sym) const
    {
        boost::apply_visitor(json_value_visitor<Symbolizer>(sym, key_), val_);
    }

    keys key_;
    value_type const& val_;
};

struct put_property
{
    typedef void result_type;
    template <typename T0,typename T1, typename T2>
    result_type operator() (T0 & sym, T1 const& name, T2 const& val) const
    {
        try
        {
            boost::apply_visitor(put_property_visitor<T2>(get_key(name),val), sym);
        }
        catch (std::runtime_error const& err)
        {
            std::cerr <<  err.what() << std::endl;
        }
    }
};

template <typename Iterator>
struct symbolizer_grammar : qi::grammar<Iterator, space_type, symbolizer()>
{
    typedef boost::variant<value_null,value_bool,value_integer,value_double, std::string> json_value_type;
    symbolizer_grammar(generic_json<Iterator> & json)
        : symbolizer_grammar::base_type(sym, "symbolizer"),
          json_(json)
    {
        using qi::lit;
        using qi::double_;
        using qi::int_;
        using qi::no_skip;
        using qi::omit;
        using qi::_val;
        using qi::_a;
        using qi::_r1;
        using qi::_1;
        using qi::_2;
        using qi::_3;
        using qi::_4;
        using qi::fail;
        using qi::on_error;
        using standard_wide::char_;
        using phoenix::construct;

        // generic json types
        json_.value =  json_.object | json_.array | json_.string_
            | json_.number
            ;

        json_.pairs = json_.key_value % lit(',')
            ;

        json_.key_value = (json_.string_ >> lit(':') >> json_.value)
            ;

        json_.object = lit('{')
            >> *json_.pairs
            >> lit('}')
            ;

        json_.array = lit('[')
            >> json_.value >> *(lit(',') >> json_.value)
            >> lit(']')
        ;

        json_.number %= json_.strict_double
            | json_.int__
            | lit("true") [_val = true]
            | lit ("false") [_val = false]
            | lit("null")[_val = construct<value_null>()]
            ;
        json_.unesc_char.add
            ("\\\"", '\"') // quotation mark
            ("\\\\", '\\') // reverse solidus
            ("\\/", '/')   // solidus
            ("\\b", '\b')  // backspace
            ("\\f", '\f')  // formfeed
            ("\\n", '\n')  // newline
            ("\\r", '\r')  // carrige return
            ("\\t", '\t')  // tab
        ;

        json_.string_ %= lit('"') >> no_skip[*(json_.unesc_char | "\\u" >> json_.hex4 | (char_ - lit('"')))] >> lit('"')
            ;

        sym = lit('{')
            >> lit("\"type\"") >> lit(':')
            >> (lit("\"PointSymbolizer\"")[_val = construct<point_symbolizer>()]
                |
                lit("\"LineSymbolizer\"")[_val = construct<line_symbolizer>()]
                |
                lit("\"PolygonSymbolizer\"")[_val = construct<polygon_symbolizer>()]
                )
            >> lit(',')
            >> lit("\"properties\"") >> lit(':')
            >> ((lit('{') >> *property(_val) >> lit('}')) | lit("null"))
            >> lit('}')
            ;

        property = (json_.string_ [_a = _1] >> lit(':') >> property_value [put_property_(_r1,_a,_1)]) % lit(',')
            ;

        property_value %= json.number | json.string_  ;

    }

    // generic JSON
    generic_json<Iterator> & json_;
    // symbolizer
    qi::rule<Iterator, space_type, mapnik::symbolizer()> sym;
    qi::rule<Iterator,qi::locals<std::string>, void(mapnik::symbolizer&),space_type> property;
    qi::rule<Iterator, space_type, json_value_type()> property_value;

    phoenix::function<put_property> put_property_;
    // error
    //boost::phoenix::function<where_message> where_message_;
};

}}

#endif // MAPNIK_FEATURE_GRAMMAR_HPP
<|endoftext|>


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

#include "videoplayer.h"
#include <QQmlInfo>
#include <QTimer>
#include "renderer.h"
#include <QPainter>
#include <QMatrix4x4>
#include <cmath>

VideoPlayer::VideoPlayer(QQuickItem *parent) :
  QQuickPaintedItem(parent),
  m_renderer(0),
  m_bin(0),
  m_src(0),
  m_sink(0) {

  setRenderTarget(QQuickPaintedItem::FramebufferObject);
  setSmooth(false);
  setAntialiasing(false);
}

VideoPlayer::~VideoPlayer() {
  stop();

  if (m_bin) {
    gst_object_unref(m_bin);
    m_bin = 0;
  }
}

void VideoPlayer::componentComplete() {
  QQuickPaintedItem::componentComplete();
}

void VideoPlayer::classBegin() {
  QQuickPaintedItem::classBegin();

  m_bin = gst_element_factory_make("camerabin", NULL);
  m_src = gst_element_factory_make("droidcamsrc", NULL);
  GstElement *src = gst_element_factory_make ("pulsesrc", NULL);
  g_object_set (m_bin, "audio-source", src, "camera-source", m_src, NULL);

  GstBus *bus = gst_element_get_bus(m_bin);
  gst_bus_add_watch(bus, bus_call, this);
  gst_object_unref(bus);
}

bool VideoPlayer::start() {
  if (!m_renderer) {
    m_renderer = QtCamViewfinderRenderer::create(this);
    if (!m_renderer) {
      qmlInfo(this) << "Failed to create viewfinder renderer";
      return false;
    }

    QObject::connect(m_renderer, SIGNAL(updateRequested()), this, SLOT(updateRequested()));
  }

  m_renderer->resize(QSizeF(width(), height()));

  if (!m_bin) {
    qmlInfo(this) << "no playbin";
    return false;
  }

  if (!m_sink) {
    m_sink = m_renderer->sinkElement();
    g_object_set (m_bin, "viewfinder-sink", m_sink, NULL);
  } else {
    // This will allow resetting EGLDisplay
    m_renderer->sinkElement();
  }

  if (gst_element_set_state(m_bin, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
    qmlInfo(this) << "error setting pipeline to PLAYING";
    return false;
  }

  return true;
}

bool VideoPlayer::stop() {
  if (gst_element_set_state(m_bin, GST_STATE_NULL) == GST_STATE_CHANGE_FAILURE) {
    qmlInfo(this) << "error setting pipeline to NULL";
    return false;
  }

  m_renderer->reset();

  return true;
}

void VideoPlayer::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) {
  QQuickPaintedItem::geometryChanged(newGeometry, oldGeometry);

  if (m_renderer) {
    m_renderer->resize(newGeometry.size());
  }
}

void VideoPlayer::paint(QPainter *painter) {
  painter->fillRect(contentsBoundingRect(), Qt::black);

  if (!m_renderer) {
    return;
  }

  bool needsNativePainting = m_renderer->needsNativePainting();

  if (needsNativePainting) {
    painter->beginNativePainting();
  }

  m_renderer->paint(QMatrix4x4(painter->combinedTransform()), painter->viewport());

  if (needsNativePainting) {
    painter->endNativePainting();
  }
}

gboolean VideoPlayer::bus_call(GstBus *bus, GstMessage *msg, gpointer data) {
  Q_UNUSED(bus);

  VideoPlayer *that = (VideoPlayer *) data;

  gchar *debug = NULL;
  GError *err = NULL;

  switch (GST_MESSAGE_TYPE(msg)) {
  case GST_MESSAGE_EOS:
    that->stop();
    break;

  case GST_MESSAGE_ERROR:
    gst_message_parse_error (msg, &err, &debug);
    qWarning() << "Error" << err->message;

    emit that->error(err->message, err->code, debug);
    that->stop();

    if (err) {
      g_error_free (err);
    }

    if (debug) {
      g_free (debug);
    }

    break;

  default:
    break;
  }

  return TRUE;
}

void VideoPlayer::updateRequested() {
  update();
}
<commit_msg>don't enable any camerabin flags<commit_after>/*
 * gst-droid
 *
 * Copyright (C) 2014 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "videoplayer.h"
#include <QQmlInfo>
#include <QTimer>
#include "renderer.h"
#include <QPainter>
#include <QMatrix4x4>
#include <cmath>

VideoPlayer::VideoPlayer(QQuickItem *parent) :
  QQuickPaintedItem(parent),
  m_renderer(0),
  m_bin(0),
  m_src(0),
  m_sink(0) {

  setRenderTarget(QQuickPaintedItem::FramebufferObject);
  setSmooth(false);
  setAntialiasing(false);
}

VideoPlayer::~VideoPlayer() {
  stop();

  if (m_bin) {
    gst_object_unref(m_bin);
    m_bin = 0;
  }
}

void VideoPlayer::componentComplete() {
  QQuickPaintedItem::componentComplete();
}

void VideoPlayer::classBegin() {
  QQuickPaintedItem::classBegin();

  m_bin = gst_element_factory_make("camerabin", NULL);
  m_src = gst_element_factory_make("droidcamsrc", NULL);
  GstElement *src = gst_element_factory_make ("pulsesrc", NULL);
  g_object_set (m_bin, "audio-source", src, "camera-source", m_src, "flags",
		0x00000001 | 0x00000002 | 0x00000004 | 0x00000008, NULL);

  GstBus *bus = gst_element_get_bus(m_bin);
  gst_bus_add_watch(bus, bus_call, this);
  gst_object_unref(bus);
}

bool VideoPlayer::start() {
  if (!m_renderer) {
    m_renderer = QtCamViewfinderRenderer::create(this);
    if (!m_renderer) {
      qmlInfo(this) << "Failed to create viewfinder renderer";
      return false;
    }

    QObject::connect(m_renderer, SIGNAL(updateRequested()), this, SLOT(updateRequested()));
  }

  m_renderer->resize(QSizeF(width(), height()));

  if (!m_bin) {
    qmlInfo(this) << "no playbin";
    return false;
  }

  if (!m_sink) {
    m_sink = m_renderer->sinkElement();
    g_object_set (m_bin, "viewfinder-sink", m_sink, NULL);
  } else {
    // This will allow resetting EGLDisplay
    m_renderer->sinkElement();
  }

  if (gst_element_set_state(m_bin, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
    qmlInfo(this) << "error setting pipeline to PLAYING";
    return false;
  }

  return true;
}

bool VideoPlayer::stop() {
  if (gst_element_set_state(m_bin, GST_STATE_NULL) == GST_STATE_CHANGE_FAILURE) {
    qmlInfo(this) << "error setting pipeline to NULL";
    return false;
  }

  m_renderer->reset();

  return true;
}

void VideoPlayer::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) {
  QQuickPaintedItem::geometryChanged(newGeometry, oldGeometry);

  if (m_renderer) {
    m_renderer->resize(newGeometry.size());
  }
}

void VideoPlayer::paint(QPainter *painter) {
  painter->fillRect(contentsBoundingRect(), Qt::black);

  if (!m_renderer) {
    return;
  }

  bool needsNativePainting = m_renderer->needsNativePainting();

  if (needsNativePainting) {
    painter->beginNativePainting();
  }

  m_renderer->paint(QMatrix4x4(painter->combinedTransform()), painter->viewport());

  if (needsNativePainting) {
    painter->endNativePainting();
  }
}

gboolean VideoPlayer::bus_call(GstBus *bus, GstMessage *msg, gpointer data) {
  Q_UNUSED(bus);

  VideoPlayer *that = (VideoPlayer *) data;

  gchar *debug = NULL;
  GError *err = NULL;

  switch (GST_MESSAGE_TYPE(msg)) {
  case GST_MESSAGE_EOS:
    that->stop();
    break;

  case GST_MESSAGE_ERROR:
    gst_message_parse_error (msg, &err, &debug);
    qWarning() << "Error" << err->message;

    emit that->error(err->message, err->code, debug);
    that->stop();

    if (err) {
      g_error_free (err);
    }

    if (debug) {
      g_free (debug);
    }

    break;

  default:
    break;
  }

  return TRUE;
}

void VideoPlayer::updateRequested() {
  update();
}
<|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/.
 */

#include "optaboutconfig.hxx"
#include "optHeaderTabListbox.hxx"
#include <svtools/svlbitm.hxx>
#include <svtools/treelistentry.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/configuration/theDefaultProvider.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/beans/Property.hpp>
#include <com/sun/star/beans/XProperty.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>

using namespace svx;
using namespace ::com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::container;

#define ITEMID_PREFNAME     1
#define ITEMID_PROPERTY     2
#define ITEMID_TYPE         3
#define ITEMID_VALUE        4

CuiAboutConfigTabPage::CuiAboutConfigTabPage( Window* pParent, const SfxItemSet& rItemSet )
    :SfxTabPage( pParent, "AboutConfig", "cui/ui/aboutconfigdialog.ui", rItemSet)
{
    get(m_pDefaultBtn,"default");
    get(m_pEditBtn, "edit");

    m_pPrefCtrl = get<SvxSimpleTableContainer>("preferences");

    Size aControlSize(200,200);
    m_pPrefCtrl->set_width_request(aControlSize.Width());
    m_pPrefCtrl->set_height_request(aControlSize.Height());

    WinBits nBits = WB_SCROLL | WB_SORT | WB_HSCROLL | WB_VSCROLL;
    pPrefBox = new svx::OptHeaderTabListBox( *m_pPrefCtrl, nBits );

    m_pEditBtn->SetClickHdl( LINK( this, CuiAboutConfigTabPage, StandardHdl_Impl ) );

    HeaderBar &rBar = pPrefBox->GetTheHeaderBar();
    rBar.InsertItem( ITEMID_PREFNAME, get<FixedText>("preference")->GetText(), 0, HIB_LEFT | HIB_VCENTER | HIB_CLICKABLE | HIB_UPARROW);
    rBar.InsertItem( ITEMID_PROPERTY, get<FixedText>("property")->GetText(), 0,  HIB_LEFT | HIB_VCENTER | HIB_CLICKABLE | HIB_UPARROW );
    rBar.InsertItem( ITEMID_TYPE, get<FixedText>("type")->GetText(), 0,  HIB_LEFT | HIB_VCENTER | HIB_CLICKABLE | HIB_UPARROW );
    rBar.InsertItem( ITEMID_VALUE, get<FixedText>("value")->GetText(), 0,  HIB_LEFT | HIB_VCENTER | HIB_CLICKABLE | HIB_UPARROW );

    long aTabs[] = {4,120,50,50,50};//TODO: Not works correctly hardcoded for now.

    aTabs[2] += aTabs[1] + rBar.GetTextWidth(rBar.GetItemText(1));
    aTabs[3] += aTabs[2] + 160; //rBar.GetTextWidth(rBar.GetItemText(2));
    aTabs[4] += aTabs[3] + 40; //rBar.GetTextWidth(rBar.GetItemText(3));

    pPrefBox->SetTabs(aTabs, MAP_PIXEL);

}

CuiAboutConfigTabPage::~CuiAboutConfigTabPage()
{
    delete pPrefBox;
}

SfxTabPage* CuiAboutConfigTabPage::Create( Window* pParent, const SfxItemSet& rItemSet )
{
    return ( new CuiAboutConfigTabPage( pParent, rItemSet) );
}

void CuiAboutConfigTabPage::InsertEntry( OUString& rProp, OUString&  rStatus, OUString& rType, OUString& rValue)
{
    SvTreeListEntry* pEntry = new SvTreeListEntry;

    pEntry->AddItem( new SvLBoxContextBmp( pEntry, 0, Image(), Image(), 0)); //It is needed, otherwise causes crash
    pEntry->AddItem( new SvLBoxString( pEntry, 0, rProp));
    pEntry->AddItem( new SvLBoxString( pEntry, 0, rStatus));
    pEntry->AddItem( new SvLBoxString( pEntry, 0, rType));
    pEntry->AddItem( new SvLBoxString( pEntry, 0, rValue));

    pPrefBox->Insert( pEntry );
}

void CuiAboutConfigTabPage::Reset( const SfxItemSet& )
{
   OUString sRootNodePath = "/";
   pPrefBox->Clear();

   m_pDefaultBtn->Enable(sal_False);
   m_pEditBtn->Enable(sal_False);

   Reference< XNameAccess > xConfigAccess = getConfigAccess( sRootNodePath, sal_False );

   FillItems( xConfigAccess, sRootNodePath );
}

void CuiAboutConfigTabPage::FillItems( Reference< XNameAccess >xNameAccess, OUString sPath)
{
    sal_Bool bIsLeafNode;

    Reference< XHierarchicalNameAccess > xHierarchicalNameAccess( xNameAccess, uno::UNO_QUERY_THROW );

    pPrefBox->SetUpdateMode(sal_False);

    uno::Sequence< OUString > seqItems = xNameAccess->getElementNames();
    for( sal_Int16 i = 0; i < seqItems.getLength(); ++i )
    {
        Any aNode = xHierarchicalNameAccess->getByHierarchicalName( seqItems[i] );

        bIsLeafNode = sal_True;

        try
        {
            Reference< XHierarchicalNameAccess >xNextHierarchicalNameAccess( aNode, uno::UNO_QUERY_THROW );
            Reference< XNameAccess > xNextNameAccess( xNextHierarchicalNameAccess, uno::UNO_QUERY_THROW );
            uno::Sequence < OUString  > seqNext = xNextNameAccess->getElementNames();
            FillItems( xNextNameAccess, sPath + OUString("/") + seqItems[i] );
            bIsLeafNode = sal_False;

        }
        catch( uno::Exception& )
        {
        }

        if( bIsLeafNode )
        {
            Any aProp = xHierarchicalNameAccess->getByHierarchicalName(seqItems[i]); //xProperty->getAsProperty();

            OUString sValue;
            if( aProp.hasValue() )
            {
                switch( aProp.getValueType().getTypeClass() )
                {
                    case ::com::sun::star::uno::TypeClass_UNSIGNED_SHORT :
                    case ::com::sun::star::uno::TypeClass_SHORT :
                    case ::com::sun::star::uno::TypeClass_UNSIGNED_LONG :
                    case ::com::sun::star::uno::TypeClass_LONG :
                    //case ::com::sun::star::uno::TypeClass_INT :
                    {
                        sal_Int32 nVal = 0;
                        if(aProp >>= nVal)
                        {
                            OUString aNumber( OUString::valueOf( nVal ) );
                            sValue = aNumber;
                        }
                    }
                    break;

                    case ::com::sun::star::uno::TypeClass_BOOLEAN :
                    {
                        sal_Bool bVal = sal_False;
                        if(aProp >>= bVal  )
                        {
                            OUString sBoolean( OUString::valueOf( bVal ) );
                            sValue = sBoolean;
                        }
                    }
                    break;

                    case ::com::sun::star::uno::TypeClass_STRING :
                    {
                        OUString sString;
                        if(aProp >>= sString)
                        {
                            sValue = sString;
                        }

                    }
                    break;

                    case ::com::sun::star::uno::TypeClass_SEQUENCE :
                    //case ::com::sun::star::uno::TypeClass_ARRAY :
                    {
                        sValue = OUString("");
                        if( OUString("[]long") ==aProp.getValueTypeName() ||
                                OUString("[]short")==aProp.getValueTypeName() )
                        {
                            uno::Sequence<sal_Int32> seqLong;
                            if( aProp >>= seqLong )
                            {
                                for(sal_Int16 nInd=0;  nInd < seqLong.getLength(); ++nInd)
                                {
                                    OUString sNumber( OUString::valueOf(seqLong[nInd]) );
                                    sValue += sNumber;
                                    sValue += OUString(",");
                                }
                            }
                        }

                        if( OUString("[]string") == aProp.getValueTypeName() )
                        {
                            uno::Sequence< OUString > seqOUString;
                            if( aProp >>= seqOUString )
                            {
                                for( sal_Int16 nInd=0; nInd < seqOUString.getLength(); ++nInd )
                                {
                                    sValue += seqOUString[nInd] + OUString(",");
                                }
                            }
                        }
                    }
                    break;

                    default:
                    {
                        sValue = OUString("test");
                    }
                }
            }

            OUString sType = aProp.getValueTypeName();
            //OUString sPrefName = sPath + OUString("-") + seqItems[i] ;
            InsertEntry( sPath, seqItems [ i ], sType, sValue);
        }
    }

    pPrefBox->SetUpdateMode(sal_True);
}

Reference< XNameAccess > CuiAboutConfigTabPage::getConfigAccess( OUString sNodePath, sal_Bool bUpdate )
{
    uno::Reference< uno::XComponentContext > xContext( ::comphelper::getProcessComponentContext() );

    uno::Reference< lang::XMultiServiceFactory > xConfigProvider(
                com::sun::star::configuration::theDefaultProvider::get( xContext  ) );

    beans::NamedValue aProperty;
    aProperty.Name = "nodepath";
    aProperty.Value = uno::makeAny( sNodePath );

    uno::Sequence< uno::Any > aArgumentList( 1 );
    aArgumentList[0] = uno::makeAny( aProperty );

    OUString sAccessString;

    if( bUpdate )
        sAccessString = "com.sun.star.configuration.ConfigurationUpdateAccess";
    else
        sAccessString = "com.sun.star.configuration.ConfigurationAccess";

    uno::Reference< container::XNameAccess > xNameAccess(
                xConfigProvider->createInstanceWithArguments(
                    sAccessString, aArgumentList ),
                uno::UNO_QUERY_THROW );

    return xNameAccess;
}

IMPL_LINK( CuiAboutConfigTabPage, HeaderSelect_Impl, HeaderBar*, pBar )
{
    if ( pBar && pBar->GetCurItemId() != ITEMID_TYPE )
        return 0;

    HeaderBarItemBits nBits = pBar->GetItemBits(ITEMID_TYPE);
    sal_Bool bUp = ( ( nBits & HIB_UPARROW ) == HIB_UPARROW );
    SvSortMode eMode = SortAscending;

    if ( bUp )
    {
        nBits &= ~HIB_UPARROW;
        nBits |= HIB_DOWNARROW;
        eMode = SortDescending;
    }
    else
    {
        nBits &= ~HIB_DOWNARROW;
        nBits |= HIB_UPARROW;
    }
    pBar->SetItemBits( ITEMID_TYPE, nBits );
    SvTreeList* pModel = pPrefBox->GetModel();
    pModel->SetSortMode( eMode );
    pModel->Resort();
    return 1;
}

IMPL_LINK_NOARG( CuiAboutConfigTabPage, StandardHdl_Impl )
{
    SvTreeListEntry* pEntry = pPrefBox->FirstSelected();

    OUString sType = pPrefBox->GetEntryText( pEntry, 2 );

    if( sType == OUString("boolean") )
    {
        //TODO: this is just cosmetic, take all needed value and handle them properly
        OUString sValue = pPrefBox->GetEntryText( pEntry, 3 );
            if (sValue == OUString("true"))
                pPrefBox->SetEntryText( OUString("false"), pEntry, 3 );
            else if(sValue == OUString("false"))
                pPrefBox->SetEntryText( OUString("true"), pEntry, 3 );
    }
    //TODO: add other types

    return 0;

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Hardcoded 3 toplevel configuration names for merging to master<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/.
 */

#include "optaboutconfig.hxx"
#include "optHeaderTabListbox.hxx"
#include <svtools/svlbitm.hxx>
#include <svtools/treelistentry.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/configuration/theDefaultProvider.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/beans/Property.hpp>
#include <com/sun/star/beans/XProperty.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>

using namespace svx;
using namespace ::com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::container;

#define ITEMID_PREFNAME     1
#define ITEMID_PROPERTY     2
#define ITEMID_TYPE         3
#define ITEMID_VALUE        4

CuiAboutConfigTabPage::CuiAboutConfigTabPage( Window* pParent, const SfxItemSet& rItemSet )
    :SfxTabPage( pParent, "AboutConfig", "cui/ui/aboutconfigdialog.ui", rItemSet)
{
    get(m_pDefaultBtn,"default");
    get(m_pEditBtn, "edit");

    m_pPrefCtrl = get<SvxSimpleTableContainer>("preferences");

    Size aControlSize(200,200);
    m_pPrefCtrl->set_width_request(aControlSize.Width());
    m_pPrefCtrl->set_height_request(aControlSize.Height());

    WinBits nBits = WB_SCROLL | WB_SORT | WB_HSCROLL | WB_VSCROLL;
    pPrefBox = new svx::OptHeaderTabListBox( *m_pPrefCtrl, nBits );

    m_pEditBtn->SetClickHdl( LINK( this, CuiAboutConfigTabPage, StandardHdl_Impl ) );

    HeaderBar &rBar = pPrefBox->GetTheHeaderBar();
    rBar.InsertItem( ITEMID_PREFNAME, get<FixedText>("preference")->GetText(), 0, HIB_LEFT | HIB_VCENTER | HIB_CLICKABLE | HIB_UPARROW);
    rBar.InsertItem( ITEMID_PROPERTY, get<FixedText>("property")->GetText(), 0,  HIB_LEFT | HIB_VCENTER | HIB_CLICKABLE | HIB_UPARROW );
    rBar.InsertItem( ITEMID_TYPE, get<FixedText>("type")->GetText(), 0,  HIB_LEFT | HIB_VCENTER | HIB_CLICKABLE | HIB_UPARROW );
    rBar.InsertItem( ITEMID_VALUE, get<FixedText>("value")->GetText(), 0,  HIB_LEFT | HIB_VCENTER | HIB_CLICKABLE | HIB_UPARROW );

    long aTabs[] = {4,120,50,50,50};//TODO: Not works correctly hardcoded for now.

    aTabs[2] += aTabs[1] + rBar.GetTextWidth(rBar.GetItemText(1));
    aTabs[3] += aTabs[2] + 160; //rBar.GetTextWidth(rBar.GetItemText(2));
    aTabs[4] += aTabs[3] + 40; //rBar.GetTextWidth(rBar.GetItemText(3));

    pPrefBox->SetTabs(aTabs, MAP_PIXEL);

}

CuiAboutConfigTabPage::~CuiAboutConfigTabPage()
{
    delete pPrefBox;
}

SfxTabPage* CuiAboutConfigTabPage::Create( Window* pParent, const SfxItemSet& rItemSet )
{
    return ( new CuiAboutConfigTabPage( pParent, rItemSet) );
}

void CuiAboutConfigTabPage::InsertEntry( OUString& rProp, OUString&  rStatus, OUString& rType, OUString& rValue)
{
    SvTreeListEntry* pEntry = new SvTreeListEntry;

    pEntry->AddItem( new SvLBoxContextBmp( pEntry, 0, Image(), Image(), 0)); //It is needed, otherwise causes crash
    pEntry->AddItem( new SvLBoxString( pEntry, 0, rProp));
    pEntry->AddItem( new SvLBoxString( pEntry, 0, rStatus));
    pEntry->AddItem( new SvLBoxString( pEntry, 0, rType));
    pEntry->AddItem( new SvLBoxString( pEntry, 0, rValue));

    pPrefBox->Insert( pEntry );
}

void CuiAboutConfigTabPage::Reset( const SfxItemSet& )
{
   OUString sRootNodePath = "/";
   pPrefBox->Clear();

   m_pDefaultBtn->Enable(sal_False);
   m_pEditBtn->Enable(sal_False);

   OUString array[ 3 ] = {
           "/org.openoffice.Office.Common",
           "/org.openoffice.Office.Math",
           "/org.openoffice.Office.Addons" };

    for (sal_Int16 nInd = 0; nInd < 3 ; ++nInd )
    {
        sRootNodePath = array[nInd];
        Reference< XNameAccess > xConfigAccess = getConfigAccess( sRootNodePath, sal_False );
        FillItems( xConfigAccess, sRootNodePath );
    }

   //Reference< XNameAccess > xConfigAccess = getConfigAccess( sRootNodePath, sal_False );

   //FillItems( xConfigAccess, sRootNodePath );
}

void CuiAboutConfigTabPage::FillItems( Reference< XNameAccess >xNameAccess, OUString sPath)
{
    sal_Bool bIsLeafNode;

    Reference< XHierarchicalNameAccess > xHierarchicalNameAccess( xNameAccess, uno::UNO_QUERY_THROW );

    pPrefBox->SetUpdateMode(sal_False);

    uno::Sequence< OUString > seqItems = xNameAccess->getElementNames();
    for( sal_Int16 i = 0; i < seqItems.getLength(); ++i )
    {
        Any aNode = xHierarchicalNameAccess->getByHierarchicalName( seqItems[i] );

        bIsLeafNode = sal_True;

        try
        {
            Reference< XHierarchicalNameAccess >xNextHierarchicalNameAccess( aNode, uno::UNO_QUERY_THROW );
            Reference< XNameAccess > xNextNameAccess( xNextHierarchicalNameAccess, uno::UNO_QUERY_THROW );
            uno::Sequence < OUString  > seqNext = xNextNameAccess->getElementNames();
            FillItems( xNextNameAccess, sPath + OUString("/") + seqItems[i] );
            bIsLeafNode = sal_False;

        }
        catch( uno::Exception& )
        {
        }

        if( bIsLeafNode )
        {
            Any aProp = xHierarchicalNameAccess->getByHierarchicalName(seqItems[i]); //xProperty->getAsProperty();

            OUString sValue;
            if( aProp.hasValue() )
            {
                switch( aProp.getValueType().getTypeClass() )
                {
                    case ::com::sun::star::uno::TypeClass_UNSIGNED_SHORT :
                    case ::com::sun::star::uno::TypeClass_SHORT :
                    case ::com::sun::star::uno::TypeClass_UNSIGNED_LONG :
                    case ::com::sun::star::uno::TypeClass_LONG :
                    //case ::com::sun::star::uno::TypeClass_INT :
                    {
                        sal_Int32 nVal = 0;
                        if(aProp >>= nVal)
                        {
                            OUString aNumber( OUString::valueOf( nVal ) );
                            sValue = aNumber;
                        }
                    }
                    break;

                    case ::com::sun::star::uno::TypeClass_BOOLEAN :
                    {
                        sal_Bool bVal = sal_False;
                        if(aProp >>= bVal  )
                        {
                            OUString sBoolean( OUString::valueOf( bVal ) );
                            sValue = sBoolean;
                        }
                    }
                    break;

                    case ::com::sun::star::uno::TypeClass_STRING :
                    {
                        OUString sString;
                        if(aProp >>= sString)
                        {
                            sValue = sString;
                        }

                    }
                    break;

                    case ::com::sun::star::uno::TypeClass_SEQUENCE :
                    //case ::com::sun::star::uno::TypeClass_ARRAY :
                    {
                        sValue = OUString("");
                        if( OUString("[]long") ==aProp.getValueTypeName() ||
                                OUString("[]short")==aProp.getValueTypeName() )
                        {
                            uno::Sequence<sal_Int32> seqLong;
                            if( aProp >>= seqLong )
                            {
                                for(sal_Int16 nInd=0;  nInd < seqLong.getLength(); ++nInd)
                                {
                                    OUString sNumber( OUString::valueOf(seqLong[nInd]) );
                                    sValue += sNumber;
                                    sValue += OUString(",");
                                }
                            }
                        }

                        if( OUString("[]string") == aProp.getValueTypeName() )
                        {
                            uno::Sequence< OUString > seqOUString;
                            if( aProp >>= seqOUString )
                            {
                                for( sal_Int16 nInd=0; nInd < seqOUString.getLength(); ++nInd )
                                {
                                    sValue += seqOUString[nInd] + OUString(",");
                                }
                            }
                        }
                    }
                    break;

                    default:
                    {
                        sValue = OUString("test");
                    }
                }
            }

            OUString sType = aProp.getValueTypeName();
            //OUString sPrefName = sPath + OUString("-") + seqItems[i] ;
            InsertEntry( sPath, seqItems [ i ], sType, sValue);
        }
    }

    pPrefBox->SetUpdateMode(sal_True);
}

Reference< XNameAccess > CuiAboutConfigTabPage::getConfigAccess( OUString sNodePath, sal_Bool bUpdate )
{
    uno::Reference< uno::XComponentContext > xContext( ::comphelper::getProcessComponentContext() );

    uno::Reference< lang::XMultiServiceFactory > xConfigProvider(
                com::sun::star::configuration::theDefaultProvider::get( xContext  ) );

    beans::NamedValue aProperty;
    aProperty.Name = "nodepath";
    aProperty.Value = uno::makeAny( sNodePath );

    uno::Sequence< uno::Any > aArgumentList( 1 );
    aArgumentList[0] = uno::makeAny( aProperty );

    OUString sAccessString;

    if( bUpdate )
        sAccessString = "com.sun.star.configuration.ConfigurationUpdateAccess";
    else
        sAccessString = "com.sun.star.configuration.ConfigurationAccess";

    uno::Reference< container::XNameAccess > xNameAccess(
                xConfigProvider->createInstanceWithArguments(
                    sAccessString, aArgumentList ),
                uno::UNO_QUERY_THROW );

    return xNameAccess;
}

IMPL_LINK( CuiAboutConfigTabPage, HeaderSelect_Impl, HeaderBar*, pBar )
{
    if ( pBar && pBar->GetCurItemId() != ITEMID_TYPE )
        return 0;

    HeaderBarItemBits nBits = pBar->GetItemBits(ITEMID_TYPE);
    sal_Bool bUp = ( ( nBits & HIB_UPARROW ) == HIB_UPARROW );
    SvSortMode eMode = SortAscending;

    if ( bUp )
    {
        nBits &= ~HIB_UPARROW;
        nBits |= HIB_DOWNARROW;
        eMode = SortDescending;
    }
    else
    {
        nBits &= ~HIB_DOWNARROW;
        nBits |= HIB_UPARROW;
    }
    pBar->SetItemBits( ITEMID_TYPE, nBits );
    SvTreeList* pModel = pPrefBox->GetModel();
    pModel->SetSortMode( eMode );
    pModel->Resort();
    return 1;
}

IMPL_LINK_NOARG( CuiAboutConfigTabPage, StandardHdl_Impl )
{
    SvTreeListEntry* pEntry = pPrefBox->FirstSelected();

    OUString sType = pPrefBox->GetEntryText( pEntry, 2 );

    if( sType == OUString("boolean") )
    {
        //TODO: this is just cosmetic, take all needed value and handle them properly
        OUString sValue = pPrefBox->GetEntryText( pEntry, 3 );
            if (sValue == OUString("true"))
                pPrefBox->SetEntryText( OUString("false"), pEntry, 3 );
            else if(sValue == OUString("false"))
                pPrefBox->SetEntryText( OUString("true"), pEntry, 3 );
    }
    //TODO: add other types

    return 0;

}

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