<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://www.opensource.org/licenses/MIT)
//=======================================================================

#ifndef EXPECTED_H
#define EXPECTED_H

#include "types.hpp"
#include "algorithms.hpp"
#include "type_traits.hpp"
#include "utility.hpp"
#include "memory.hpp"
#include "new.hpp"

namespace std {

constexpr struct only_set_valid_t {} only_set_valid;

template <typename E>
struct exceptional {
    typedef E error_type;

    error_type error;

    exceptional(): error() {
        //Nothing else to init
    }

    explicit exceptional(error_type e) : error(e) {
        //Nothing else to init
    }
};

template<typename T, typename E>
union trivial_expected_storage {
    typedef T value_type;
    typedef E error_type;

    error_type error;
    value_type value;

    constexpr trivial_expected_storage() : value(){
        //Nothing else to init
    }

    constexpr trivial_expected_storage(const exceptional<error_type>& e) : error(e.error){
        //Nothing else to init
    }

    template<typename... Args>
    constexpr trivial_expected_storage(Args&&... args): value(std::forward<Args>(args)...){
        //Nothing else to init
    }

    ~trivial_expected_storage() = default;
};

template<typename E>
union trivial_expected_storage <void, E> {
    typedef void value_type;
    typedef E error_type;

    error_type error;

    constexpr trivial_expected_storage() {
        //Nothing else to init
    }

    constexpr trivial_expected_storage(const exceptional<error_type>& e) : error(e.error){
        //Nothing else to init
    }

    ~trivial_expected_storage() = default;
};

template<typename T, typename E>
union non_trivial_expected_storage {
    typedef T value_type;
    typedef E error_type;

    error_type error;
    value_type value;

    constexpr non_trivial_expected_storage() : value(){
        //Nothing else to init
    }

    constexpr non_trivial_expected_storage(exceptional<error_type>& e) : error(e.error){
        //Nothing else to init
    }

    template<typename... Args>
    constexpr non_trivial_expected_storage(Args&&... args): value(std::forward<Args>(args)...){
        //Nothing else to init
    }

    ~non_trivial_expected_storage() {};
};

template<typename E>
union non_trivial_expected_storage <void, E> {
    typedef void value_type;
    typedef E error_type;

    error_type error;

    constexpr non_trivial_expected_storage(){
        //Nothing else to init
    }

    constexpr non_trivial_expected_storage(exceptional<error_type>& e) : error(e.error){
        //Nothing else to init
    }

    ~non_trivial_expected_storage() {};
};

template<typename T, typename E>
struct trivial_expected_base {
    typedef T value_type;
    typedef E error_type;

    bool has_value;
    trivial_expected_storage<T, E> storage;

    trivial_expected_base() : has_value(true), storage(){
        //Nothing else to init
    }

    trivial_expected_base(only_set_valid_t, bool hv) : has_value(hv){
        //Nothing else to init
    }

    trivial_expected_base(const value_type& v) : has_value(true), storage(v){
        //Nothing else to init
    }

    trivial_expected_base(value_type&& v) : has_value(true), storage(std::forward<value_type>(v)){
        //Nothing else to init
    }

    trivial_expected_base(const exceptional<error_type>& e) : has_value(false), storage(e) {
        //Nothing else to init
    }

    ~trivial_expected_base() = default;
};

template<typename E>
struct trivial_expected_base <void, E> {
    typedef E error_type;

    bool has_value;
    trivial_expected_storage<void, E> storage;

    trivial_expected_base() : has_value(true), storage(){
        //Nothing else to init
    }

    trivial_expected_base(only_set_valid_t, bool hv) : has_value(hv){
        //Nothing else to init
    }

    trivial_expected_base(const exceptional<error_type>& e) : has_value(false), storage(e) {
        //Nothing else to init
    }

    ~trivial_expected_base() = default;
};

template<typename T, typename E>
struct non_trivial_expected_base {
    typedef T value_type;
    typedef E error_type;

    bool has_value;
    trivial_expected_storage<T, E> storage;

    non_trivial_expected_base() : has_value(true), storage(){
        //Nothing else to init
    }

    non_trivial_expected_base(only_set_valid_t, bool hv) : has_value(hv){
        //Nothing else to init
    }

    non_trivial_expected_base(const value_type& v) : has_value(true), storage(v){
        //Nothing else to init
    }

    non_trivial_expected_base(value_type&& v) : has_value(true), storage(std::forward<value_type>(v)){
        //Nothing else to init
    }

    non_trivial_expected_base(const exceptional<error_type>& e) : has_value(false), storage(e) {
        //Nothing else to init
    }

    ~non_trivial_expected_base(){
        if(has_value){
            storage.error.~value_type();
        } else {
            storage.error.~error_type();
        }
    }
};

template<typename E>
struct non_trivial_expected_base <void, E> {
    typedef E error_type;

    bool has_value;
    trivial_expected_storage<void, E> storage;

    non_trivial_expected_base() : has_value(true), storage(){
        //Nothing else to init
    }

    non_trivial_expected_base(only_set_valid_t, bool hv) : has_value(hv){
        //Nothing else to init
    }

    non_trivial_expected_base(const exceptional<error_type>& e) : has_value(false), storage(e) {
        //Nothing else to init
    }

    ~non_trivial_expected_base(){
        if(!has_value){
            storage.error.~error_type();
        }
    }
};

template <typename T, typename E>
using expected_base = typename std::conditional<
        std::is_trivially_destructible<T>::value && std::is_trivially_destructible<E>::value,
        trivial_expected_base<T, E>,
        non_trivial_expected_base<T, E>
    >::type;

template<typename T, typename E = size_t>
struct expected : expected_base<T, E> {
    typedef T value_type;
    typedef E error_type;

    typedef expected<T, E> this_type;
    typedef expected_base<T, E> base_type;

private:
    value_type* value_ptr() {
        return std::addressof(base_type::storage.value);
    }

    constexpr const value_type* value_ptr() const {
        return std::static_addressof(base_type::storage.value);
    }

    error_type* error_ptr() {
        return std::addressof(base_type::storage.error);
    }

    constexpr const error_type* error_ptr() const {
        return static_addressof(base_type::storage.error);
    }

    constexpr const bool& contained_has_value() const& {
        return base_type::has_value;
    }

    bool& contained_has_value() & {
        return base_type::has_value;
    }

    bool&& contained_has_value() && {
        return std::move(base_type::has_value);
    }

    constexpr const value_type& contained_value() const& {
        return base_type::storage.value;
    }

    value_type& contained_value() & {
        return base_type::storage.value;
    }

    value_type&& contained_value() && {
        return std::move(base_type::storage.value);
    }

    constexpr const error_type& contained_error() const& {
        return base_type::storage.error;
    }

    error_type& contained_error() & {
        return base_type::storage.error;
    }

    error_type&& contained_error() && {
        return std::move(base_type::storage.error);
    }

public:
    /* Constructors */

    constexpr expected(const value_type& v) : base_type(v){
        //Nothing else to init
    }

    constexpr expected(value_type&& v) : base_type(std::forward<value_type>(v)){
        //Nothing else to init
    }

    expected(const expected& rhs) : base_type(only_set_valid, rhs.valid()) {
        if(rhs.valid()){
            ::new (value_ptr()) value_type(rhs.contained_value());
        } else {
            ::new (error_ptr()) error_type(rhs.contained_error());
        }
    }

    expected(expected&& rhs) : base_type(only_set_valid, rhs.valid()) {
        if(rhs.valid()){
            new (value_ptr()) value_type(std::move(rhs.contained_value()));
        } else {
            new (error_ptr()) error_type(std::move(rhs.contained_error()));
        }
    }

    expected(const exceptional<error_type>& e) : base_type(e) {
        //Nothing else to init
    }

    expected() : base_type() {}

    ~expected() = default;

    /* Operators */
    expected& operator=(const expected& rhs){
        this_type(rhs).swap(*this);
        return *this;
    }

    expected& operator=(expected&& rhs){
        this_type(std::move(rhs)).swap(*this);
        return *this;
    }

    expected& operator=(const value_type& v){
        this_type(v).swap(*this);
        return *this;
    }

    expected& operator=(value_type&& v){
        this_type(std::move(v)).swap(*this);
        return *this;
    }

    /* Swap */

    void swap(expected& rhs){
        if (valid()){
            if (rhs.valid()){
                std::swap(contained_value(), rhs.contained_value());
            } else {
                error_type t = std::move(rhs.contained_error());
                new (rhs.value_ptr()) value_type(std::move(contained_value()));
                new (error_ptr()) error_type(t);
                std::swap(contained_has_value(), rhs.contained_has_value());
            }
        } else {
            if (rhs.valid()){
                rhs.swap(*this);
            } else {
                std::swap(contained_error(), rhs.contained_error());
            }
        }
    }

    /* Accessors */

    constexpr bool valid() const {
        return contained_has_value();
    }

    constexpr explicit operator bool() const {
        return valid();
    }

    constexpr const value_type& value() const {
        return contained_value();
    }

    constexpr const value_type&  operator*() const {
        return contained_value();
    }

    value_type& operator*(){
        return contained_value();
    }

    constexpr const value_type* operator->() const {
        return value_ptr();
    }

    value_type* operator->(){
        return value_ptr();
    }

    constexpr const error_type& error() const {
        return contained_error();
    }

    constexpr bool has_error(const error_type& e) const {
        return contained_error() == e;
    }

    constexpr exceptional<error_type> get_exceptional() const {
        return exceptional<error_type>(contained_error());
    }
};

template<typename E>
struct expected <void, E> : expected_base<void, E> {
    typedef void value_type;
    typedef E error_type;

    typedef expected<void, E> this_type;
    typedef expected_base<void, E> base_type;

private:
    error_type* error_ptr() {
        return std::addressof(base_type::storage.error);
    }

    constexpr const error_type* error_ptr() const {
        return static_addressof(base_type::storage.error);
    }

    constexpr const bool& contained_has_value() const& {
        return base_type::has_value;
    }

    bool& contained_has_value() & {
        return base_type::has_value;
    }

    bool&& contained_has_value() && {
        return std::move(base_type::has_value);
    }

    constexpr const error_type& contained_error() const& {
        return base_type::storage.error;
    }

    error_type& contained_error() & {
        return base_type::storage.error;
    }

    error_type&& contained_error() && {
        return std::move(base_type::storage.error);
    }

public:
    /* Constructors */

    expected(const expected& rhs) : base_type(only_set_valid, rhs.valid()) {
        if(!rhs.valid()){
            ::new (error_ptr()) error_type(rhs.contained_error());
        }
    }

    expected(expected&& rhs) : base_type(only_set_valid, rhs.valid()) {
        if(!rhs.valid()){
            new (error_ptr()) error_type(std::move(rhs.contained_error()));
        }
    }

    expected(const exceptional<error_type>& e) : base_type(e) {
        //Nothing else to init
    }

    expected() : base_type() {}

    ~expected() = default;

    /* Operators */
    expected& operator=(const expected& rhs){
        this_type(rhs).swap(*this);
        return *this;
    }

    expected& operator=(expected&& rhs){
        this_type(std::move(rhs)).swap(*this);
        return *this;
    }

    /* Swap */

    void swap(expected& rhs){
        if (valid()){
            if (!rhs.valid()){
                error_type t = std::move(rhs.contained_error());
                new (error_ptr()) error_type(t);
            }
        } else {
            if (!rhs.valid()){
                std::swap(contained_error(), rhs.contained_error());
            }
        }
    }

    /* Accessors */

    constexpr bool valid() const {
        return contained_has_value();
    }

    constexpr explicit operator bool() const {
        return valid();
    }

    constexpr const error_type& error() const {
        return contained_error();
    }

    constexpr bool has_error(const error_type& e) const {
        return contained_error() == e;
    }

    constexpr exceptional<error_type> get_exceptional() const {
        return exceptional<error_type>(contained_error());
    }
};

template<typename T>
inline expected<T> make_expected(T&& v){
    return expected<T>(std::forward<T>(v));
}

template<typename T>
inline expected<T> make_expected(const T& v){
    return expected<T>(v);
}

template<typename T, typename U, typename E>
inline expected<T, U> make_expected_from_error(E v){
    return expected<T, U>(exceptional<U>(v));
}

template<typename T, typename E>
inline expected<T, E> make_expected_from_error(E v){
    return expected<T, E>(exceptional<E>(v));
}

inline expected<void> make_expected(){
    return expected<void>();
}

// Make sure the size is maintained reasonable
static_assert(sizeof(expected<void>) == 2 * sizeof(size_t), "expected<void> should not have overhead");
static_assert(sizeof(expected<size_t>) == 2 * sizeof(size_t), "expected<size_t> should not have overhead");

} //end of namespace std

#endif
<commit_msg>Add make_unexpected<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://www.opensource.org/licenses/MIT)
//=======================================================================

#ifndef EXPECTED_H
#define EXPECTED_H

#include "types.hpp"
#include "algorithms.hpp"
#include "type_traits.hpp"
#include "utility.hpp"
#include "memory.hpp"
#include "new.hpp"

namespace std {

constexpr struct only_set_valid_t {} only_set_valid;

template <typename E>
struct exceptional {
    typedef E error_type;

    error_type error;

    exceptional(): error() {
        //Nothing else to init
    }

    explicit exceptional(error_type e) : error(e) {
        //Nothing else to init
    }
};

template<typename T, typename E>
union trivial_expected_storage {
    typedef T value_type;
    typedef E error_type;

    error_type error;
    value_type value;

    constexpr trivial_expected_storage() : value(){
        //Nothing else to init
    }

    constexpr trivial_expected_storage(const exceptional<error_type>& e) : error(e.error){
        //Nothing else to init
    }

    template<typename... Args>
    constexpr trivial_expected_storage(Args&&... args): value(std::forward<Args>(args)...){
        //Nothing else to init
    }

    ~trivial_expected_storage() = default;
};

template<typename E>
union trivial_expected_storage <void, E> {
    typedef void value_type;
    typedef E error_type;

    error_type error;

    constexpr trivial_expected_storage() {
        //Nothing else to init
    }

    constexpr trivial_expected_storage(const exceptional<error_type>& e) : error(e.error){
        //Nothing else to init
    }

    ~trivial_expected_storage() = default;
};

template<typename T, typename E>
union non_trivial_expected_storage {
    typedef T value_type;
    typedef E error_type;

    error_type error;
    value_type value;

    constexpr non_trivial_expected_storage() : value(){
        //Nothing else to init
    }

    constexpr non_trivial_expected_storage(exceptional<error_type>& e) : error(e.error){
        //Nothing else to init
    }

    template<typename... Args>
    constexpr non_trivial_expected_storage(Args&&... args): value(std::forward<Args>(args)...){
        //Nothing else to init
    }

    ~non_trivial_expected_storage() {};
};

template<typename E>
union non_trivial_expected_storage <void, E> {
    typedef void value_type;
    typedef E error_type;

    error_type error;

    constexpr non_trivial_expected_storage(){
        //Nothing else to init
    }

    constexpr non_trivial_expected_storage(exceptional<error_type>& e) : error(e.error){
        //Nothing else to init
    }

    ~non_trivial_expected_storage() {};
};

template<typename T, typename E>
struct trivial_expected_base {
    typedef T value_type;
    typedef E error_type;

    bool has_value;
    trivial_expected_storage<T, E> storage;

    trivial_expected_base() : has_value(true), storage(){
        //Nothing else to init
    }

    trivial_expected_base(only_set_valid_t, bool hv) : has_value(hv){
        //Nothing else to init
    }

    trivial_expected_base(const value_type& v) : has_value(true), storage(v){
        //Nothing else to init
    }

    trivial_expected_base(value_type&& v) : has_value(true), storage(std::forward<value_type>(v)){
        //Nothing else to init
    }

    trivial_expected_base(const exceptional<error_type>& e) : has_value(false), storage(e) {
        //Nothing else to init
    }

    ~trivial_expected_base() = default;
};

template<typename E>
struct trivial_expected_base <void, E> {
    typedef E error_type;

    bool has_value;
    trivial_expected_storage<void, E> storage;

    trivial_expected_base() : has_value(true), storage(){
        //Nothing else to init
    }

    trivial_expected_base(only_set_valid_t, bool hv) : has_value(hv){
        //Nothing else to init
    }

    trivial_expected_base(const exceptional<error_type>& e) : has_value(false), storage(e) {
        //Nothing else to init
    }

    ~trivial_expected_base() = default;
};

template<typename T, typename E>
struct non_trivial_expected_base {
    typedef T value_type;
    typedef E error_type;

    bool has_value;
    trivial_expected_storage<T, E> storage;

    non_trivial_expected_base() : has_value(true), storage(){
        //Nothing else to init
    }

    non_trivial_expected_base(only_set_valid_t, bool hv) : has_value(hv){
        //Nothing else to init
    }

    non_trivial_expected_base(const value_type& v) : has_value(true), storage(v){
        //Nothing else to init
    }

    non_trivial_expected_base(value_type&& v) : has_value(true), storage(std::forward<value_type>(v)){
        //Nothing else to init
    }

    non_trivial_expected_base(const exceptional<error_type>& e) : has_value(false), storage(e) {
        //Nothing else to init
    }

    ~non_trivial_expected_base(){
        if(has_value){
            storage.error.~value_type();
        } else {
            storage.error.~error_type();
        }
    }
};

template<typename E>
struct non_trivial_expected_base <void, E> {
    typedef E error_type;

    bool has_value;
    trivial_expected_storage<void, E> storage;

    non_trivial_expected_base() : has_value(true), storage(){
        //Nothing else to init
    }

    non_trivial_expected_base(only_set_valid_t, bool hv) : has_value(hv){
        //Nothing else to init
    }

    non_trivial_expected_base(const exceptional<error_type>& e) : has_value(false), storage(e) {
        //Nothing else to init
    }

    ~non_trivial_expected_base(){
        if(!has_value){
            storage.error.~error_type();
        }
    }
};

template <typename T, typename E>
using expected_base = typename std::conditional<
        std::is_trivially_destructible<T>::value && std::is_trivially_destructible<E>::value,
        trivial_expected_base<T, E>,
        non_trivial_expected_base<T, E>
    >::type;

template<typename T, typename E = size_t>
struct expected : expected_base<T, E> {
    typedef T value_type;
    typedef E error_type;

    typedef expected<T, E> this_type;
    typedef expected_base<T, E> base_type;

private:
    value_type* value_ptr() {
        return std::addressof(base_type::storage.value);
    }

    constexpr const value_type* value_ptr() const {
        return std::static_addressof(base_type::storage.value);
    }

    error_type* error_ptr() {
        return std::addressof(base_type::storage.error);
    }

    constexpr const error_type* error_ptr() const {
        return static_addressof(base_type::storage.error);
    }

    constexpr const bool& contained_has_value() const& {
        return base_type::has_value;
    }

    bool& contained_has_value() & {
        return base_type::has_value;
    }

    bool&& contained_has_value() && {
        return std::move(base_type::has_value);
    }

    constexpr const value_type& contained_value() const& {
        return base_type::storage.value;
    }

    value_type& contained_value() & {
        return base_type::storage.value;
    }

    value_type&& contained_value() && {
        return std::move(base_type::storage.value);
    }

    constexpr const error_type& contained_error() const& {
        return base_type::storage.error;
    }

    error_type& contained_error() & {
        return base_type::storage.error;
    }

    error_type&& contained_error() && {
        return std::move(base_type::storage.error);
    }

public:
    /* Constructors */

    constexpr expected(const value_type& v) : base_type(v){
        //Nothing else to init
    }

    constexpr expected(value_type&& v) : base_type(std::forward<value_type>(v)){
        //Nothing else to init
    }

    expected(const expected& rhs) : base_type(only_set_valid, rhs.valid()) {
        if(rhs.valid()){
            ::new (value_ptr()) value_type(rhs.contained_value());
        } else {
            ::new (error_ptr()) error_type(rhs.contained_error());
        }
    }

    expected(expected&& rhs) : base_type(only_set_valid, rhs.valid()) {
        if(rhs.valid()){
            new (value_ptr()) value_type(std::move(rhs.contained_value()));
        } else {
            new (error_ptr()) error_type(std::move(rhs.contained_error()));
        }
    }

    expected(const exceptional<error_type>& e) : base_type(e) {
        //Nothing else to init
    }

    expected() : base_type() {}

    ~expected() = default;

    /* Operators */
    expected& operator=(const expected& rhs){
        this_type(rhs).swap(*this);
        return *this;
    }

    expected& operator=(expected&& rhs){
        this_type(std::move(rhs)).swap(*this);
        return *this;
    }

    expected& operator=(const value_type& v){
        this_type(v).swap(*this);
        return *this;
    }

    expected& operator=(value_type&& v){
        this_type(std::move(v)).swap(*this);
        return *this;
    }

    /* Swap */

    void swap(expected& rhs){
        if (valid()){
            if (rhs.valid()){
                std::swap(contained_value(), rhs.contained_value());
            } else {
                error_type t = std::move(rhs.contained_error());
                new (rhs.value_ptr()) value_type(std::move(contained_value()));
                new (error_ptr()) error_type(t);
                std::swap(contained_has_value(), rhs.contained_has_value());
            }
        } else {
            if (rhs.valid()){
                rhs.swap(*this);
            } else {
                std::swap(contained_error(), rhs.contained_error());
            }
        }
    }

    /* Accessors */

    constexpr bool valid() const {
        return contained_has_value();
    }

    constexpr explicit operator bool() const {
        return valid();
    }

    constexpr const value_type& value() const {
        return contained_value();
    }

    constexpr const value_type&  operator*() const {
        return contained_value();
    }

    value_type& operator*(){
        return contained_value();
    }

    constexpr const value_type* operator->() const {
        return value_ptr();
    }

    value_type* operator->(){
        return value_ptr();
    }

    constexpr const error_type& error() const {
        return contained_error();
    }

    constexpr bool has_error(const error_type& e) const {
        return contained_error() == e;
    }

    constexpr exceptional<error_type> get_exceptional() const {
        return exceptional<error_type>(contained_error());
    }
};

template<typename E>
struct expected <void, E> : expected_base<void, E> {
    typedef void value_type;
    typedef E error_type;

    typedef expected<void, E> this_type;
    typedef expected_base<void, E> base_type;

private:
    error_type* error_ptr() {
        return std::addressof(base_type::storage.error);
    }

    constexpr const error_type* error_ptr() const {
        return static_addressof(base_type::storage.error);
    }

    constexpr const bool& contained_has_value() const& {
        return base_type::has_value;
    }

    bool& contained_has_value() & {
        return base_type::has_value;
    }

    bool&& contained_has_value() && {
        return std::move(base_type::has_value);
    }

    constexpr const error_type& contained_error() const& {
        return base_type::storage.error;
    }

    error_type& contained_error() & {
        return base_type::storage.error;
    }

    error_type&& contained_error() && {
        return std::move(base_type::storage.error);
    }

public:
    /* Constructors */

    expected(const expected& rhs) : base_type(only_set_valid, rhs.valid()) {
        if(!rhs.valid()){
            ::new (error_ptr()) error_type(rhs.contained_error());
        }
    }

    expected(expected&& rhs) : base_type(only_set_valid, rhs.valid()) {
        if(!rhs.valid()){
            new (error_ptr()) error_type(std::move(rhs.contained_error()));
        }
    }

    expected(const exceptional<error_type>& e) : base_type(e) {
        //Nothing else to init
    }

    expected() : base_type() {}

    ~expected() = default;

    /* Operators */
    expected& operator=(const expected& rhs){
        this_type(rhs).swap(*this);
        return *this;
    }

    expected& operator=(expected&& rhs){
        this_type(std::move(rhs)).swap(*this);
        return *this;
    }

    /* Swap */

    void swap(expected& rhs){
        if (valid()){
            if (!rhs.valid()){
                error_type t = std::move(rhs.contained_error());
                new (error_ptr()) error_type(t);
            }
        } else {
            if (!rhs.valid()){
                std::swap(contained_error(), rhs.contained_error());
            }
        }
    }

    /* Accessors */

    constexpr bool valid() const {
        return contained_has_value();
    }

    constexpr explicit operator bool() const {
        return valid();
    }

    constexpr const error_type& error() const {
        return contained_error();
    }

    constexpr bool has_error(const error_type& e) const {
        return contained_error() == e;
    }

    constexpr exceptional<error_type> get_exceptional() const {
        return exceptional<error_type>(contained_error());
    }
};

template<typename T>
inline expected<T> make_expected(T&& v){
    return expected<T>(std::forward<T>(v));
}

template<typename T>
inline expected<T> make_expected(const T& v){
    return expected<T>(v);
}

template<typename T, typename U, typename E>
inline expected<T, U> make_expected_from_error(E v){
    return expected<T, U>(exceptional<U>(v));
}

template<typename T, typename E>
inline expected<T, E> make_expected_from_error(E v){
    return expected<T, E>(exceptional<E>(v));
}

template<typename T, typename E>
inline expected<T, E> make_unexpected(E v){
    return expected<T, E>(exceptional<E>(v));
}

inline expected<void> make_expected(){
    return expected<void>();
}

// Make sure the size is maintained reasonable
static_assert(sizeof(expected<void>) == 2 * sizeof(size_t), "expected<void> should not have overhead");
static_assert(sizeof(expected<size_t>) == 2 * sizeof(size_t), "expected<size_t> should not have overhead");

} //end of namespace std

#endif
<|endoftext|>


<commit_before>/*
 * SessionPdfLatex.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionPdfLatex.hpp"

#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>

#include <core/system/Environment.hpp>
#include <core/FileSerializer.hpp>

#include <session/projects/SessionProjects.hpp>

#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>

#include "SessionTexUtils.hpp"

using namespace core;

namespace session {
namespace modules {
namespace tex {
namespace pdflatex {

namespace {

class LatexProgramTypes : boost::noncopyable
{
public:
   LatexProgramTypes()
   {
      types_.push_back("pdfLaTeX");
      types_.push_back("XeLaTeX");
   }

   const std::vector<std::string>& allTypes() const
   {
      return types_;
   }

   json::Array allTypesAsJson() const
   {
      json::Array typesJson;
      std::transform(types_.begin(),
                     types_.end(),
                     std::back_inserter(typesJson),
                     json::toJsonString);
      return typesJson;
   }

   bool isValidTypeName(const std::string& name) const
   {
      BOOST_FOREACH(const std::string& type, types_)
      {
         if (boost::algorithm::iequals(name, type))
            return true;
      }

      return false;
   }

   std::string printableTypeNames() const
   {
      if (types_.size() == 1)
         return types_[0];
      else if (types_.size() == 2)
         return types_[0] + " and " + types_[1];
      else
      {
         std::string str;
         for (std::size_t i=0; i<types_.size(); i++)
         {
            str.append(types_[i]);
            if (i != (types_.size() - 1))
               str.append(", ");
            if (i == (types_.size() - 2))
               str.append("and ");
         }
         return str;
      }
   }

private:
   std::vector<std::string> types_;
};

const LatexProgramTypes& programTypes()
{
   static LatexProgramTypes instance;
   return instance;
}

std::string latexProgramMagicComment(
                     const core::tex::TexMagicComments& magicComments)
{
   BOOST_FOREACH(const core::tex::TexMagicComment& mc, magicComments)
   {
      if (boost::algorithm::iequals(mc.scope(), "tex") &&
          (boost::algorithm::iequals(mc.variable(), "program") ||
           boost::algorithm::iequals(mc.variable(), "ts-program")))
      {
         return mc.value();
      }
   }

   return std::string();
}

void setInvalidProgramTypeMessage(const std::string& program,
                                  std::string* pUserErrMsg)
{
   *pUserErrMsg = "Unknown LaTeX program type '" + program +
                  "' specified (valid types are " +
                  programTypes().printableTypeNames() + ")";
}

bool validateLatexProgram(const std::string& program,
                          FilePath* pTexProgramPath,
                          std::string* pUserErrMsg)
{
   // convert to lower case for finding
   std::string programName = string_utils::toLower(program);

   // try to find on the path
   *pTexProgramPath = module_context::findProgram(programName);
   if (pTexProgramPath->empty())
   {
      *pUserErrMsg = "Unabled to find specified LaTeX program '" +
                     program + "' on the system path";
      return false;
   }
   else
   {
      return true;
   }
}

bool validateLatexProgramType(const std::string& programType,
                              std::string* pUserErrMsg)
{
   if (!programTypes().isValidTypeName(programType))
   {
      setInvalidProgramTypeMessage(programType, pUserErrMsg);
      return false;
   }
   else
   {
      return true;
   }
}

void appendEnvVarNotice(std::string* pUserErrMsg)
{
   pUserErrMsg->append(" (the program was specified using the "
                       "RSTUDIO_PDFLATEX environment variable)");
}

shell_utils::ShellArgs shellArgs(const PdfLatexOptions& options)
{
   shell_utils::ShellArgs args;

   if (options.fileLineError)
   {
      if (options.isMikTeX())
         args << kCStyleErrorsOption;
      else
         args << kFileLineErrorOption;
   }
   if (options.syncTex)
   {
      args << kSynctexOption;
   }
   if (options.shellEscape)
   {
      if (options.isMikTeX())
         args << kEnableWrite18Option;
      else
         args << kShellEscapeOption;
   }
   args << "-interaction=nonstopmode";

   return args;
}

FilePath programPath(const std::string& name, const std::string& envOverride)
{
   std::string envProgram = core::system::getenv(envOverride);
   std::string program = envProgram.empty() ? name : envProgram;
   return module_context::findProgram(program);
}

bool lineIncludes(const std::string& line, const boost::regex& regex)
{
    boost::smatch match;
    return boost::regex_search(line, match, regex);
}

int countCitationMisses(const FilePath& logFilePath)
{
   // read the log file
   std::vector<std::string> lines;
   Error error = core::readStringVectorFromFile(logFilePath, &lines);
   if (error)
   {
      LOG_ERROR(error);
      return 0;
   }

   // look for misses
   boost::regex missRegex("Warning:.*Citation.*undefined");
   int misses = std::count_if(lines.begin(),
                              lines.end(),
                              boost::bind(lineIncludes, _1, missRegex));
   return misses;
}

bool logIncludesRerun(const FilePath& logFilePath)
{
   std::string logContents;
   Error error = core::readStringFromFile(logFilePath, &logContents);
   if (error)
   {
      LOG_ERROR(error);
      return false;
   }

   return logContents.find("Rerun to get") != std::string::npos;
}

} // anonymous namespace

const char * const kFileLineErrorOption = "-file-line-error";
const char * const kCStyleErrorsOption = "-c-style-errors";
const char * const kShellEscapeOption = "-shell-escape";
const char * const kEnableWrite18Option = "–enable-write18";
const char * const kSynctexOption = "-synctex=1";

bool isInstalled()
{
   return !module_context::findProgram("pdflatex").empty();
}

core::json::Array supportedTypes()
{
   return programTypes().allTypesAsJson();
}

bool latexProgramForFile(const core::tex::TexMagicComments& magicComments,
                         FilePath* pTexProgramPath,
                         std::string* pUserErrMsg)
{
   // get (optional) magic comments and environment variable override
   std::string latexProgramMC = latexProgramMagicComment(magicComments);
   std::string pdflatexEnv = core::system::getenv("RSTUDIO_PDFLATEX");

   // magic comment always takes highest priority
   if (!latexProgramMC.empty())
   {
      // validate magic comment
      if (!validateLatexProgramType(latexProgramMC, pUserErrMsg))
      {
         return false;
      }
      else
      {
         return validateLatexProgram(latexProgramMC,
                                     pTexProgramPath,
                                     pUserErrMsg);
      }
   }

   // next is environment variable
   else if (!pdflatexEnv.empty())
   {
      if (FilePath::isRootPath(pdflatexEnv))
      {
         FilePath texProgramPath(pdflatexEnv);
         if (texProgramPath.exists())
         {
            *pTexProgramPath = texProgramPath;
            return true;
         }
         else
         {
            *pUserErrMsg = "Unabled to find specified LaTeX program " +
                           pdflatexEnv;
            appendEnvVarNotice(pUserErrMsg);
            return false;
         }
      }
      else
      {
         bool validated = validateLatexProgram(pdflatexEnv,
                                               pTexProgramPath,
                                               pUserErrMsg);

         if (!validated)
            appendEnvVarNotice(pUserErrMsg);

         return validated;
      }
   }

   // project or global default setting
   else
   {
      std::string defaultProgram = projects::projectContext().hasProject() ?
                projects::projectContext().config().defaultLatexProgram :
                userSettings().defaultLatexProgram();

      if (!validateLatexProgramType(defaultProgram, pUserErrMsg))
      {
         return false;
      }
      else
      {
         return validateLatexProgram(defaultProgram,
                                     pTexProgramPath,
                                     pUserErrMsg);
      }
   }
}

// this function provides an "emulated" version of texi2dvi for when the
// user has texi2dvi disabled. For example to workaround this bug:
//
//  http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=534458
//
// this code is a port of the simillar logic which exists in the
// tools::texi2dvi function (but the regex for detecting citation
// warnings was made a bit more liberal)
//
core::Error texToPdf(const core::FilePath& texProgramPath,
                     const core::FilePath& texFilePath,
                     const tex::pdflatex::PdfLatexOptions& options,
                     core::system::ProcessResult* pResult)
{
   // input file paths
   FilePath baseFilePath = texFilePath.parent().complete(texFilePath.stem());
   FilePath idxFilePath(baseFilePath.absolutePath() + ".idx");
   FilePath logFilePath(baseFilePath.absolutePath() + ".log");

   // bibtex and makeindex program paths
   FilePath bibtexProgramPath = programPath("bibtex", "BIBTEX");
   FilePath makeindexProgramPath = programPath("makeindex", "MAKEINDEX");

   // args and process options for running bibtex and makeindex
   core::shell_utils::ShellArgs bibtexArgs;
   bibtexArgs << string_utils::utf8ToSystem(baseFilePath.filename());
   core::shell_utils::ShellArgs makeindexArgs;
   makeindexArgs << string_utils::utf8ToSystem(idxFilePath.filename());
   core::system::ProcessOptions procOptions;
   procOptions.environment = utils::rTexInputsEnvVars();
   procOptions.workingDir = texFilePath.parent();

   // run the initial compile
   Error error = utils::runTexCompile(texProgramPath,
                                      utils::rTexInputsEnvVars(),
                                      shellArgs(options),
                                      texFilePath,
                                      pResult);
   if (error)
      return error;

   // count misses
   int misses = countCitationMisses(logFilePath);
   int previousMisses = 0;

   // resolve citation misses and index
   for (int i=0; i<10; i++)
   {
      // run bibtex if necessary
      if (misses > 0 && !bibtexProgramPath.empty())
      {
         core::system::ProcessResult result;
         Error error = core::system::runProgram(
               string_utils::utf8ToSystem(bibtexProgramPath.absolutePath()),
               bibtexArgs,
               "",
               procOptions,
               pResult);
         if (error)
            LOG_ERROR(error);
         else if (pResult->exitStatus != EXIT_SUCCESS)
            return Success(); // pass error state on to caller
      }
      previousMisses = misses;

      // run makeindex if necessary
      if (idxFilePath.exists() && !makeindexProgramPath.empty())
      {
         Error error = core::system::runProgram(
               string_utils::utf8ToSystem(makeindexProgramPath.absolutePath()),
               makeindexArgs,
               "",
               procOptions,
               pResult);
         if (error)
            LOG_ERROR(error);
         else if (pResult->exitStatus != EXIT_SUCCESS)
            return Success(); // pass error state on to caller
      }

      // re-run latex
      Error error = utils::runTexCompile(texProgramPath,
                                         utils::rTexInputsEnvVars(),
                                         shellArgs(options),
                                         texFilePath,
                                         pResult);
      if (error)
         return error;

      // count misses
      misses = countCitationMisses(logFilePath);

      // if there is no change in misses and there is no "Rerun to get"
      // in the log file then break
      if ((misses == previousMisses) && !logIncludesRerun(logFilePath))
         break;
   }

   return Success();
}

} // namespace pdflatex
} // namespace tex
} // namespace modules
} // namesapce session

<commit_msg>fix latex shell escape option on windows<commit_after>/*
 * SessionPdfLatex.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionPdfLatex.hpp"

#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>

#include <core/system/Environment.hpp>
#include <core/FileSerializer.hpp>

#include <session/projects/SessionProjects.hpp>

#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>

#include "SessionTexUtils.hpp"

using namespace core;

namespace session {
namespace modules {
namespace tex {
namespace pdflatex {

namespace {

class LatexProgramTypes : boost::noncopyable
{
public:
   LatexProgramTypes()
   {
      types_.push_back("pdfLaTeX");
      types_.push_back("XeLaTeX");
   }

   const std::vector<std::string>& allTypes() const
   {
      return types_;
   }

   json::Array allTypesAsJson() const
   {
      json::Array typesJson;
      std::transform(types_.begin(),
                     types_.end(),
                     std::back_inserter(typesJson),
                     json::toJsonString);
      return typesJson;
   }

   bool isValidTypeName(const std::string& name) const
   {
      BOOST_FOREACH(const std::string& type, types_)
      {
         if (boost::algorithm::iequals(name, type))
            return true;
      }

      return false;
   }

   std::string printableTypeNames() const
   {
      if (types_.size() == 1)
         return types_[0];
      else if (types_.size() == 2)
         return types_[0] + " and " + types_[1];
      else
      {
         std::string str;
         for (std::size_t i=0; i<types_.size(); i++)
         {
            str.append(types_[i]);
            if (i != (types_.size() - 1))
               str.append(", ");
            if (i == (types_.size() - 2))
               str.append("and ");
         }
         return str;
      }
   }

private:
   std::vector<std::string> types_;
};

const LatexProgramTypes& programTypes()
{
   static LatexProgramTypes instance;
   return instance;
}

std::string latexProgramMagicComment(
                     const core::tex::TexMagicComments& magicComments)
{
   BOOST_FOREACH(const core::tex::TexMagicComment& mc, magicComments)
   {
      if (boost::algorithm::iequals(mc.scope(), "tex") &&
          (boost::algorithm::iequals(mc.variable(), "program") ||
           boost::algorithm::iequals(mc.variable(), "ts-program")))
      {
         return mc.value();
      }
   }

   return std::string();
}

void setInvalidProgramTypeMessage(const std::string& program,
                                  std::string* pUserErrMsg)
{
   *pUserErrMsg = "Unknown LaTeX program type '" + program +
                  "' specified (valid types are " +
                  programTypes().printableTypeNames() + ")";
}

bool validateLatexProgram(const std::string& program,
                          FilePath* pTexProgramPath,
                          std::string* pUserErrMsg)
{
   // convert to lower case for finding
   std::string programName = string_utils::toLower(program);

   // try to find on the path
   *pTexProgramPath = module_context::findProgram(programName);
   if (pTexProgramPath->empty())
   {
      *pUserErrMsg = "Unabled to find specified LaTeX program '" +
                     program + "' on the system path";
      return false;
   }
   else
   {
      return true;
   }
}

bool validateLatexProgramType(const std::string& programType,
                              std::string* pUserErrMsg)
{
   if (!programTypes().isValidTypeName(programType))
   {
      setInvalidProgramTypeMessage(programType, pUserErrMsg);
      return false;
   }
   else
   {
      return true;
   }
}

void appendEnvVarNotice(std::string* pUserErrMsg)
{
   pUserErrMsg->append(" (the program was specified using the "
                       "RSTUDIO_PDFLATEX environment variable)");
}

shell_utils::ShellArgs shellArgs(const PdfLatexOptions& options)
{
   shell_utils::ShellArgs args;

   if (options.fileLineError)
   {
      if (options.isMikTeX())
         args << kCStyleErrorsOption;
      else
         args << kFileLineErrorOption;
   }
   if (options.syncTex)
   {
      args << kSynctexOption;
   }
   if (options.shellEscape)
   {
      if (options.isMikTeX())
         args << kEnableWrite18Option;
      else
         args << kShellEscapeOption;
   }
   args << "-interaction=nonstopmode";

   return args;
}

FilePath programPath(const std::string& name, const std::string& envOverride)
{
   std::string envProgram = core::system::getenv(envOverride);
   std::string program = envProgram.empty() ? name : envProgram;
   return module_context::findProgram(program);
}

bool lineIncludes(const std::string& line, const boost::regex& regex)
{
    boost::smatch match;
    return boost::regex_search(line, match, regex);
}

int countCitationMisses(const FilePath& logFilePath)
{
   // read the log file
   std::vector<std::string> lines;
   Error error = core::readStringVectorFromFile(logFilePath, &lines);
   if (error)
   {
      LOG_ERROR(error);
      return 0;
   }

   // look for misses
   boost::regex missRegex("Warning:.*Citation.*undefined");
   int misses = std::count_if(lines.begin(),
                              lines.end(),
                              boost::bind(lineIncludes, _1, missRegex));
   return misses;
}

bool logIncludesRerun(const FilePath& logFilePath)
{
   std::string logContents;
   Error error = core::readStringFromFile(logFilePath, &logContents);
   if (error)
   {
      LOG_ERROR(error);
      return false;
   }

   return logContents.find("Rerun to get") != std::string::npos;
}

} // anonymous namespace

const char * const kFileLineErrorOption = "-file-line-error";
const char * const kCStyleErrorsOption = "-c-style-errors";
const char * const kShellEscapeOption = "-shell-escape";
const char * const kEnableWrite18Option = "-enable-write18";
const char * const kSynctexOption = "-synctex=1";

bool isInstalled()
{
   return !module_context::findProgram("pdflatex").empty();
}

core::json::Array supportedTypes()
{
   return programTypes().allTypesAsJson();
}

bool latexProgramForFile(const core::tex::TexMagicComments& magicComments,
                         FilePath* pTexProgramPath,
                         std::string* pUserErrMsg)
{
   // get (optional) magic comments and environment variable override
   std::string latexProgramMC = latexProgramMagicComment(magicComments);
   std::string pdflatexEnv = core::system::getenv("RSTUDIO_PDFLATEX");

   // magic comment always takes highest priority
   if (!latexProgramMC.empty())
   {
      // validate magic comment
      if (!validateLatexProgramType(latexProgramMC, pUserErrMsg))
      {
         return false;
      }
      else
      {
         return validateLatexProgram(latexProgramMC,
                                     pTexProgramPath,
                                     pUserErrMsg);
      }
   }

   // next is environment variable
   else if (!pdflatexEnv.empty())
   {
      if (FilePath::isRootPath(pdflatexEnv))
      {
         FilePath texProgramPath(pdflatexEnv);
         if (texProgramPath.exists())
         {
            *pTexProgramPath = texProgramPath;
            return true;
         }
         else
         {
            *pUserErrMsg = "Unabled to find specified LaTeX program " +
                           pdflatexEnv;
            appendEnvVarNotice(pUserErrMsg);
            return false;
         }
      }
      else
      {
         bool validated = validateLatexProgram(pdflatexEnv,
                                               pTexProgramPath,
                                               pUserErrMsg);

         if (!validated)
            appendEnvVarNotice(pUserErrMsg);

         return validated;
      }
   }

   // project or global default setting
   else
   {
      std::string defaultProgram = projects::projectContext().hasProject() ?
                projects::projectContext().config().defaultLatexProgram :
                userSettings().defaultLatexProgram();

      if (!validateLatexProgramType(defaultProgram, pUserErrMsg))
      {
         return false;
      }
      else
      {
         return validateLatexProgram(defaultProgram,
                                     pTexProgramPath,
                                     pUserErrMsg);
      }
   }
}

// this function provides an "emulated" version of texi2dvi for when the
// user has texi2dvi disabled. For example to workaround this bug:
//
//  http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=534458
//
// this code is a port of the simillar logic which exists in the
// tools::texi2dvi function (but the regex for detecting citation
// warnings was made a bit more liberal)
//
core::Error texToPdf(const core::FilePath& texProgramPath,
                     const core::FilePath& texFilePath,
                     const tex::pdflatex::PdfLatexOptions& options,
                     core::system::ProcessResult* pResult)
{
   // input file paths
   FilePath baseFilePath = texFilePath.parent().complete(texFilePath.stem());
   FilePath idxFilePath(baseFilePath.absolutePath() + ".idx");
   FilePath logFilePath(baseFilePath.absolutePath() + ".log");

   // bibtex and makeindex program paths
   FilePath bibtexProgramPath = programPath("bibtex", "BIBTEX");
   FilePath makeindexProgramPath = programPath("makeindex", "MAKEINDEX");

   // args and process options for running bibtex and makeindex
   core::shell_utils::ShellArgs bibtexArgs;
   bibtexArgs << string_utils::utf8ToSystem(baseFilePath.filename());
   core::shell_utils::ShellArgs makeindexArgs;
   makeindexArgs << string_utils::utf8ToSystem(idxFilePath.filename());
   core::system::ProcessOptions procOptions;
   procOptions.environment = utils::rTexInputsEnvVars();
   procOptions.workingDir = texFilePath.parent();

   // run the initial compile
   Error error = utils::runTexCompile(texProgramPath,
                                      utils::rTexInputsEnvVars(),
                                      shellArgs(options),
                                      texFilePath,
                                      pResult);
   if (error)
      return error;

   // count misses
   int misses = countCitationMisses(logFilePath);
   int previousMisses = 0;

   // resolve citation misses and index
   for (int i=0; i<10; i++)
   {
      // run bibtex if necessary
      if (misses > 0 && !bibtexProgramPath.empty())
      {
         core::system::ProcessResult result;
         Error error = core::system::runProgram(
               string_utils::utf8ToSystem(bibtexProgramPath.absolutePath()),
               bibtexArgs,
               "",
               procOptions,
               pResult);
         if (error)
            LOG_ERROR(error);
         else if (pResult->exitStatus != EXIT_SUCCESS)
            return Success(); // pass error state on to caller
      }
      previousMisses = misses;

      // run makeindex if necessary
      if (idxFilePath.exists() && !makeindexProgramPath.empty())
      {
         Error error = core::system::runProgram(
               string_utils::utf8ToSystem(makeindexProgramPath.absolutePath()),
               makeindexArgs,
               "",
               procOptions,
               pResult);
         if (error)
            LOG_ERROR(error);
         else if (pResult->exitStatus != EXIT_SUCCESS)
            return Success(); // pass error state on to caller
      }

      // re-run latex
      Error error = utils::runTexCompile(texProgramPath,
                                         utils::rTexInputsEnvVars(),
                                         shellArgs(options),
                                         texFilePath,
                                         pResult);
      if (error)
         return error;

      // count misses
      misses = countCitationMisses(logFilePath);

      // if there is no change in misses and there is no "Rerun to get"
      // in the log file then break
      if ((misses == previousMisses) && !logIncludesRerun(logFilePath))
         break;
   }

   return Success();
}

} // namespace pdflatex
} // namespace tex
} // namespace modules
} // namesapce session

<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Log.h"
#include "WebUI.h"

class WebUISampleApp : public ci::app::App {
public:
    WebUISampleApp();

	void setup() override;
    void resize() override;
    void keyDown( ci::app::KeyEvent event ) override;
	void update() override;
	void draw() override;

private:
    ci::CameraPersp                 mCam;
    webui::WebUI                    mUI;
    webui::BoundParam< float >      mRadius;
    webui::BoundParam< glm::vec2 >  mCenter;
    webui::BoundParam< glm::vec3 >  mRotation;
    webui::BoundParam< int >        mNumCubes, mSubdivisions;
};

using namespace ci;
using namespace ci::app;
using namespace std;

WebUISampleApp::WebUISampleApp() :
mRadius( 0.5f ),
mCenter( vec2( 0.f ) ),
mRotation( vec3( 0.1f ) ),
mNumCubes( 1 ),
mSubdivisions( 12 )
{
}

void WebUISampleApp::setup()
{
    log::manager()->enableSystemLogging();
    log::manager()->setSystemLoggingLevel( log::LEVEL_INFO );
//    log::manager()->enableConsoleLogging();

    mUI.listen( 9002 );

    mUI.bind( "radius", &mRadius );
    mUI.bind( "center", &mCenter );
    mUI.bind( "rotation", &mRotation );
    mUI.bind( "num-cubes", &mNumCubes );
    mUI.bind( "subdivisions", &mSubdivisions );

    resize();
}

void WebUISampleApp::resize()
{
    mCam.lookAt( vec3( 0, 0, 10 ), vec3( 0 ) );
    mCam.setPerspective( 45.f, getWindowAspectRatio(), 1.f, 20.f );
}

void WebUISampleApp::keyDown( KeyEvent event )
{
    if ( event.getCode() == KeyEvent::KEY_UP )
    {
        mRadius += 0.1;
    }

    else if ( event.getCode() == KeyEvent::KEY_DOWN )
    {
        mRadius -= 0.1;
    }
}

void WebUISampleApp::update()
{
    mUI.update();

}

void WebUISampleApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );
    gl::setMatrices( mCam );

    for ( int i = 0; i < mNumCubes; ++i )
    {
        gl::ScopedModelMatrix scp_mtx;
        vec2 center = mCenter() + vec2( float(i) * mRadius * 2.f + ( mNumCubes - 1 ) * -mRadius, 0.f );

//        gl::translate( -center );
        gl::translate( center );
        gl::rotate( 1.f, mRotation() * float( M_PI ) * 2.f );
        gl::drawSphere( vec3( 0.f ), mRadius, mSubdivisions );
    }
}

CINDER_APP( WebUISampleApp, RendererGl )
<commit_msg>A little clean up<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Log.h"
#include "WebUI.h"

class WebUISampleApp : public ci::app::App {
public:
    WebUISampleApp();

	void setup() override;
    void resize() override;
    void keyDown( ci::app::KeyEvent event ) override;
	void update() override;
	void draw() override;

private:
    ci::CameraPersp                 mCam;
    webui::WebUI                    mUI;
    webui::BoundParam< float >      mRadius;
    webui::BoundParam< glm::vec2 >  mCenter;
    webui::BoundParam< glm::vec3 >  mRotation;
    webui::BoundParam< int >        mNumCubes, mSubdivisions;
};

using namespace ci;
using namespace ci::app;
using namespace std;

WebUISampleApp::WebUISampleApp() :
mRadius( 0.5f ),
mCenter( vec2( 0.f ) ),
mRotation( vec3( 0.1f ) ),
mNumCubes( 1 ),
mSubdivisions( 12 )
{
}

void WebUISampleApp::setup()
{
    log::manager()->enableConsoleLogging();

    mUI.listen( 9002 );

    mUI.bind( "radius", &mRadius );
    mUI.bind( "center", &mCenter );
    mUI.bind( "rotation", &mRotation );
    mUI.bind( "num-cubes", &mNumCubes );
    mUI.bind( "subdivisions", &mSubdivisions );

    resize();
}

void WebUISampleApp::resize()
{
    mCam.lookAt( vec3( 0, 0, 10 ), vec3( 0 ) );
    mCam.setPerspective( 45.f, getWindowAspectRatio(), 1.f, 20.f );
}

void WebUISampleApp::keyDown( KeyEvent event )
{
    if ( event.getCode() == KeyEvent::KEY_UP )
    {
        mRadius += 0.1;
    }

    else if ( event.getCode() == KeyEvent::KEY_DOWN )
    {
        mRadius -= 0.1;
    }
}

void WebUISampleApp::update()
{
    mUI.update();

}

void WebUISampleApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );
    gl::setMatrices( mCam );

    for ( int i = 0; i < mNumCubes; ++i )
    {
        gl::ScopedModelMatrix scp_mtx;
        vec2 center = mCenter() + vec2( float(i) * mRadius * 2.f + ( mNumCubes - 1 ) * -mRadius, 0.f );

        gl::translate( center );
        gl::rotate( 1.f, mRotation() * float( M_PI ) * 2.f );
        gl::drawSphere( vec3( 0.f ), mRadius, mSubdivisions );
    }
}

CINDER_APP( WebUISampleApp, RendererGl )
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SC_XMLEXPORTDDELINKS_HXX
#define SC_XMLEXPORTDDELINKS_HXX

#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>

class String;
class ScXMLExport;
class ScMatrixValue;

class ScXMLExportDDELinks
{
    ScXMLExport&        rExport;

    sal_Bool            CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue,
                                    const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue) const;
    void                WriteCell(const ScMatrixValue& aVal, sal_Int32 nRepeat);
    void                WriteTable(const sal_Int32 nPos);
public:
    ScXMLExportDDELinks(ScXMLExport& rExport);
    ~ScXMLExportDDELinks();
    void WriteDDELinks(::com::sun::star::uno::Reference < ::com::sun::star::sheet::XSpreadsheetDocument >& xSpreadDoc);
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: struct vs class<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SC_XMLEXPORTDDELINKS_HXX
#define SC_XMLEXPORTDDELINKS_HXX

#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>

class String;
class ScXMLExport;
struct ScMatrixValue;

class ScXMLExportDDELinks
{
    ScXMLExport&        rExport;

    sal_Bool            CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue,
                                    const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue) const;
    void                WriteCell(const ScMatrixValue& aVal, sal_Int32 nRepeat);
    void                WriteTable(const sal_Int32 nPos);
public:
    ScXMLExportDDELinks(ScXMLExport& rExport);
    ~ScXMLExportDDELinks();
    void WriteDDELinks(::com::sun::star::uno::Reference < ::com::sun::star::sheet::XSpreadsheetDocument >& xSpreadDoc);
};

#endif

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


<commit_before>/*************************************************************************
 *
 *  $RCSfile: AccessibleContextBase.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: sab $ $Date: 2002-03-22 16:20:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SC_ACCESSIBLECONTEXTBASE_HXX
#define _SC_ACCESSIBLECONTEXTBASE_HXX

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <drafts/com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECOMPONENT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleComponent.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_IllegalAccessibleComponentStateException_HPP_
#include <drafts/com/sun/star/accessibility/IllegalAccessibleComponentStateException.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICENAME_HPP_
#include <com/sun/star/lang/XServiceName.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif

#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#include <cppuhelper/compbase5.hxx>
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#include <unotools/servicehelper.hxx>
#include <comphelper/broadcasthelper.hxx>

class Rectangle;

/** @descr
        This base class provides an implementation of the
        AccessibleContext service.
*/

typedef cppu::WeakAggComponentImplHelper5<
                ::drafts::com::sun::star::accessibility::XAccessible,
                ::drafts::com::sun::star::accessibility::XAccessibleComponent,
                ::drafts::com::sun::star::accessibility::XAccessibleContext,
                ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster,
                ::com::sun::star::lang::XServiceInfo
                > ScAccessibleContextBaseWeakImpl;

typedef cppu::ImplHelper1<
                ::drafts::com::sun::star::accessibility::XAccessibleEventListener
                > ScAccessibleContextBaseImplEvent;

class ScAccessibleContextBase
    :   public comphelper::OBaseMutex,
        public ScAccessibleContextBaseWeakImpl,
        public ScAccessibleContextBaseImplEvent,
        public SfxListener
{
public:
    //=====  internal  ========================================================
    ScAccessibleContextBase(
        const ::com::sun::star::uno::Reference<
        ::drafts::com::sun::star::accessibility::XAccessible>& rxParent,
        const sal_Int16 aRole);

    virtual void Init();
    virtual void SAL_CALL disposing();
protected:
    virtual ~ScAccessibleContextBase(void);
public:
    ///=====  SfxListener  =====================================================

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    ///=====  XInterface  =====================================================

    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
        ::com::sun::star::uno::Type const & rType )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL acquire() throw ();

    virtual void SAL_CALL release() throw ();

    ///=====  XAccessible  =====================================================

    /// Return the XAccessibleContext.
    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleContext> SAL_CALL
        getAccessibleContext(void) throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleComponent  ============================================

    virtual sal_Bool SAL_CALL contains(
        const ::com::sun::star::awt::Point& rPoint )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible >
        SAL_CALL getAccessibleAt(
        const ::com::sun::star::awt::Point& rPoint )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::awt::Point SAL_CALL getLocation(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::awt::Size SAL_CALL getSize(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL isShowing(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL isVisible(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL isFocusTraversable(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL addFocusListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL removeFocusListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL grabFocus(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding(  )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleContext  ==============================================

    /// Return the number of currently visible children.
    virtual sal_Int32 SAL_CALL
        getAccessibleChildCount(void) throw (::com::sun::star::uno::RuntimeException);

    /// Return the specified child or NULL if index is invalid.
    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible> SAL_CALL
        getAccessibleChild(sal_Int32 nIndex)
        throw (::com::sun::star::uno::RuntimeException,
                ::com::sun::star::lang::IndexOutOfBoundsException);

    /// Return a reference to the parent.
    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible> SAL_CALL
        getAccessibleParent(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return this objects index among the parents children.
    virtual sal_Int32 SAL_CALL
        getAccessibleIndexInParent(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return this object's role.
    virtual sal_Int16 SAL_CALL
        getAccessibleRole(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return this object's description.
    virtual ::rtl::OUString SAL_CALL
        getAccessibleDescription(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current name.
    virtual ::rtl::OUString SAL_CALL
        getAccessibleName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return NULL to indicate that an empty relation set.
    virtual ::com::sun::star::uno::Reference<
            ::drafts::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL
        getAccessibleRelationSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the set of current states.
    virtual ::com::sun::star::uno::Reference<
            ::drafts::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
        getAccessibleStateSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Return the parents locale or throw exception if this object has no
        parent yet/anymore.
    */
    virtual ::com::sun::star::lang::Locale SAL_CALL
        getLocale(void)
        throw (::com::sun::star::uno::RuntimeException,
            ::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException);

    ///=====  XAccessibleEventBroadcaster  =====================================

    /** Add listener that is informed of future changes of name,
          description and so on events.
    */
    virtual void SAL_CALL
        addEventListener(
            const ::com::sun::star::uno::Reference<
                ::drafts::com::sun::star::accessibility::XAccessibleEventListener>& xListener)
        throw (com::sun::star::uno::RuntimeException);

    //  Remove an existing event listener.
    virtual void SAL_CALL
        removeEventListener(
            const ::com::sun::star::uno::Reference<
                ::drafts::com::sun::star::accessibility::XAccessibleEventListener>& xListener)
        throw (com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleEventListener  ========================================

    virtual void SAL_CALL
        disposing( const ::com::sun::star::lang::EventObject& Source )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        notifyEvent(
        const ::drafts::com::sun::star::accessibility::AccessibleEventObject& aEvent )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XServiceInfo  ====================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Return whether the specified service is supported by this class.
    */
    virtual sal_Bool SAL_CALL
        supportsService(const ::rtl::OUString& sServiceName)
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a list of all supported services.  In this case that is just
        the AccessibleContext and Accessible service.
    */
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XTypeProvider  ===================================================

     /// returns the possible types
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
        getTypes()
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a implementation id.
    */
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
        getImplementationId(void)
        throw (::com::sun::star::uno::RuntimeException);

protected:
    /// Return this object's description.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleDescription(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current name.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the desktop.
    virtual Rectangle GetBoundingBoxOnScreen(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the parent object.
    virtual Rectangle GetBoundingBox(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Calls all Listener to tell they the change.
    void
        CommitChange(const drafts::com::sun::star::accessibility::AccessibleEventObject& rEvent);

    /// Calls all Listener to tell they that the object is now DEFUNC
    void CommitDefunc();

    /// Calls all FocusListener to tell they that the focus is gained.
    void CommitFocusGained(const com::sun::star::awt::FocusEvent& rFocusEvent);

    /// Calls all FocusListener to tell they that the focus is lost.
    void CommitFocusLost(const com::sun::star::awt::FocusEvent& rFocusEvent);

    sal_Bool IsDefunc() { return rBHelper.bDisposed; }

private:
    /// Reference to the parent object.
    ::com::sun::star::uno::Reference<
         ::drafts::com::sun::star::accessibility::XAccessible> mxParent;

    /** Description of this object.  This is not a constant because it can
        be set from the outside.  Furthermore, it changes according the the
        draw page's display mode.
    */
    ::rtl::OUString msDescription;

    /** Name of this object.  It changes according the the draw page's
        display mode.
    */
    ::rtl::OUString msName;

    /// List of property change listeners.
    cppu::OInterfaceContainerHelper* mpEventListeners;

    /// List of focus listeners.
    cppu::OInterfaceContainerHelper* mpFocusListeners;

    /** This is the role of this object.
    */
    sal_Int16 maRole;
};

#endif
<commit_msg>#95584#; make all commit methods const and CommitChange public so it is possible to call it in helper classes<commit_after>/*************************************************************************
 *
 *  $RCSfile: AccessibleContextBase.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: sab $ $Date: 2002-04-19 17:53:08 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SC_ACCESSIBLECONTEXTBASE_HXX
#define _SC_ACCESSIBLECONTEXTBASE_HXX

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <drafts/com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECOMPONENT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleComponent.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_IllegalAccessibleComponentStateException_HPP_
#include <drafts/com/sun/star/accessibility/IllegalAccessibleComponentStateException.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICENAME_HPP_
#include <com/sun/star/lang/XServiceName.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif

#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#include <cppuhelper/compbase5.hxx>
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#include <unotools/servicehelper.hxx>
#include <comphelper/broadcasthelper.hxx>

class Rectangle;

/** @descr
        This base class provides an implementation of the
        AccessibleContext service.
*/

typedef cppu::WeakAggComponentImplHelper5<
                ::drafts::com::sun::star::accessibility::XAccessible,
                ::drafts::com::sun::star::accessibility::XAccessibleComponent,
                ::drafts::com::sun::star::accessibility::XAccessibleContext,
                ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster,
                ::com::sun::star::lang::XServiceInfo
                > ScAccessibleContextBaseWeakImpl;

typedef cppu::ImplHelper1<
                ::drafts::com::sun::star::accessibility::XAccessibleEventListener
                > ScAccessibleContextBaseImplEvent;

class ScAccessibleContextBase
    :   public comphelper::OBaseMutex,
        public ScAccessibleContextBaseWeakImpl,
        public ScAccessibleContextBaseImplEvent,
        public SfxListener
{
public:
    //=====  internal  ========================================================
    ScAccessibleContextBase(
        const ::com::sun::star::uno::Reference<
        ::drafts::com::sun::star::accessibility::XAccessible>& rxParent,
        const sal_Int16 aRole);

    virtual void Init();
    virtual void SAL_CALL disposing();
protected:
    virtual ~ScAccessibleContextBase(void);
public:
    ///=====  SfxListener  =====================================================

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    ///=====  XInterface  =====================================================

    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
        ::com::sun::star::uno::Type const & rType )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL acquire() throw ();

    virtual void SAL_CALL release() throw ();

    ///=====  XAccessible  =====================================================

    /// Return the XAccessibleContext.
    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleContext> SAL_CALL
        getAccessibleContext(void) throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleComponent  ============================================

    virtual sal_Bool SAL_CALL contains(
        const ::com::sun::star::awt::Point& rPoint )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible >
        SAL_CALL getAccessibleAt(
        const ::com::sun::star::awt::Point& rPoint )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::awt::Point SAL_CALL getLocation(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::awt::Size SAL_CALL getSize(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL isShowing(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL isVisible(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL isFocusTraversable(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL addFocusListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL removeFocusListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL grabFocus(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding(  )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleContext  ==============================================

    /// Return the number of currently visible children.
    virtual sal_Int32 SAL_CALL
        getAccessibleChildCount(void) throw (::com::sun::star::uno::RuntimeException);

    /// Return the specified child or NULL if index is invalid.
    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible> SAL_CALL
        getAccessibleChild(sal_Int32 nIndex)
        throw (::com::sun::star::uno::RuntimeException,
                ::com::sun::star::lang::IndexOutOfBoundsException);

    /// Return a reference to the parent.
    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible> SAL_CALL
        getAccessibleParent(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return this objects index among the parents children.
    virtual sal_Int32 SAL_CALL
        getAccessibleIndexInParent(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return this object's role.
    virtual sal_Int16 SAL_CALL
        getAccessibleRole(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return this object's description.
    virtual ::rtl::OUString SAL_CALL
        getAccessibleDescription(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current name.
    virtual ::rtl::OUString SAL_CALL
        getAccessibleName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return NULL to indicate that an empty relation set.
    virtual ::com::sun::star::uno::Reference<
            ::drafts::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL
        getAccessibleRelationSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the set of current states.
    virtual ::com::sun::star::uno::Reference<
            ::drafts::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
        getAccessibleStateSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Return the parents locale or throw exception if this object has no
        parent yet/anymore.
    */
    virtual ::com::sun::star::lang::Locale SAL_CALL
        getLocale(void)
        throw (::com::sun::star::uno::RuntimeException,
            ::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException);

    ///=====  XAccessibleEventBroadcaster  =====================================

    /** Add listener that is informed of future changes of name,
          description and so on events.
    */
    virtual void SAL_CALL
        addEventListener(
            const ::com::sun::star::uno::Reference<
                ::drafts::com::sun::star::accessibility::XAccessibleEventListener>& xListener)
        throw (com::sun::star::uno::RuntimeException);

    //  Remove an existing event listener.
    virtual void SAL_CALL
        removeEventListener(
            const ::com::sun::star::uno::Reference<
                ::drafts::com::sun::star::accessibility::XAccessibleEventListener>& xListener)
        throw (com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleEventListener  ========================================

    virtual void SAL_CALL
        disposing( const ::com::sun::star::lang::EventObject& Source )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        notifyEvent(
        const ::drafts::com::sun::star::accessibility::AccessibleEventObject& aEvent )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XServiceInfo  ====================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Return whether the specified service is supported by this class.
    */
    virtual sal_Bool SAL_CALL
        supportsService(const ::rtl::OUString& sServiceName)
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a list of all supported services.  In this case that is just
        the AccessibleContext and Accessible service.
    */
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XTypeProvider  ===================================================

     /// returns the possible types
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
        getTypes()
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a implementation id.
    */
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
        getImplementationId(void)
        throw (::com::sun::star::uno::RuntimeException);

protected:
    /// Return this object's description.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleDescription(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current name.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the desktop.
    virtual Rectangle GetBoundingBoxOnScreen(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the parent object.
    virtual Rectangle GetBoundingBox(void)
        throw (::com::sun::star::uno::RuntimeException);

public:
    /// Calls all Listener to tell they the change.
    void
        CommitChange(const drafts::com::sun::star::accessibility::AccessibleEventObject& rEvent) const;

protected:
    /// Calls all Listener to tell they that the object is now DEFUNC
    void CommitDefunc() const;

    /// Calls all FocusListener to tell they that the focus is gained.
    void CommitFocusGained(const com::sun::star::awt::FocusEvent& rFocusEvent) const;

    /// Calls all FocusListener to tell they that the focus is lost.
    void CommitFocusLost(const com::sun::star::awt::FocusEvent& rFocusEvent) const;

    sal_Bool IsDefunc() { return rBHelper.bDisposed; }

private:
    /// Reference to the parent object.
    ::com::sun::star::uno::Reference<
         ::drafts::com::sun::star::accessibility::XAccessible> mxParent;

    /** Description of this object.  This is not a constant because it can
        be set from the outside.  Furthermore, it changes according the the
        draw page's display mode.
    */
    ::rtl::OUString msDescription;

    /** Name of this object.  It changes according the the draw page's
        display mode.
    */
    ::rtl::OUString msName;

    /// List of property change listeners.
    cppu::OInterfaceContainerHelper* mpEventListeners;

    /// List of focus listeners.
    cppu::OInterfaceContainerHelper* mpFocusListeners;

    /** This is the role of this object.
    */
    sal_Int16 maRole;
};

#endif
<|endoftext|>


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

#include "CCodeReviewComment.h"

#include "ModelBase/src/model/TreeManager.h"

#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/items/ViewItem.h"
#include "VisualizationBase/src/VisualizationManager.h"

#include "../overlays/CodeReviewCommentOverlay.h"

using namespace Visualization;

namespace CodeReview {

CCodeReviewComment::CCodeReviewComment() : Command{"comment"} {}

bool CCodeReviewComment::canInterpret(Visualization::Item*, Visualization::Item*,
		const QStringList&, const std::unique_ptr<Visualization::Cursor>& )
{
	return true;
}

Interaction::CommandResult* CCodeReviewComment::execute(Visualization::Item*, Visualization::Item*,
				const QStringList&, const std::unique_ptr<Visualization::Cursor>& cursor)
{
	auto cursorOwner = cursor->owner();
	auto overlay = new CodeReviewCommentOverlay{cursorOwner};
	cursorOwner->addOverlay(overlay, "CodeReviewComment");

	return new Interaction::CommandResult{};
}

QList<Interaction::CommandSuggestion*> CCodeReviewComment::suggest(Visualization::Item*, Visualization::Item*,
		const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)
{
	if (name().startsWith(textSoFar))
	{
		return {new Interaction::CommandSuggestion{name()}};
	}
	return {};
}

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

#include "CCodeReviewComment.h"

#include "ModelBase/src/model/TreeManager.h"

#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/items/ViewItem.h"
#include "VisualizationBase/src/VisualizationManager.h"

#include "../overlays/CodeReviewCommentOverlay.h"

using namespace Visualization;

namespace CodeReview {

CCodeReviewComment::CCodeReviewComment() : Command{"comment"} {}

bool CCodeReviewComment::canInterpret(Visualization::Item*, Visualization::Item*,
		const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& )
{
	if (commandTokens.size() > 0)
		return name() == commandTokens.first();
	return false;
}

Interaction::CommandResult* CCodeReviewComment::execute(Visualization::Item*, Visualization::Item*,
				const QStringList&, const std::unique_ptr<Visualization::Cursor>& cursor)
{
	auto cursorOwner = cursor->owner();
	auto overlay = new CodeReviewCommentOverlay{cursorOwner};
	cursorOwner->addOverlay(overlay, "CodeReviewComment");

	return new Interaction::CommandResult{};
}

QList<Interaction::CommandSuggestion*> CCodeReviewComment::suggest(Visualization::Item*, Visualization::Item*,
		const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>&)
{
	if (name().startsWith(textSoFar))
	{
		return {new Interaction::CommandSuggestion{name()}};
	}
	return {};
}

}
<|endoftext|>