<commit_before>/*
 * Copyright (C) 2018 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <concepts>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/for_each.hpp>

#include "bytes.hh"

enum class mutable_view { no, yes, };

/// Fragmented buffer
///
/// Concept `FragmentedBuffer` is satisfied by any class that is a range of
/// fragments and provides a method `size_bytes()` which returns the total
/// size of the buffer. The interfaces accepting `FragmentedBuffer` will attempt
/// to avoid unnecessary linearisation.
template<typename T>
concept FragmentRange = requires (T range) {
    typename T::fragment_type;
    requires std::is_same_v<typename T::fragment_type, bytes_view>
        || std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
    { *range.begin() } -> std::convertible_to<const typename T::fragment_type&>;
    { *range.end() } -> std::convertible_to<const typename T::fragment_type&>;
    { range.size_bytes() } -> std::convertible_to<size_t>;
    { range.empty() } -> std::same_as<bool>; // returns true iff size_bytes() == 0.
};

template<typename T, typename = void>
struct is_fragment_range : std::false_type { };

template<typename T>
struct is_fragment_range<T, std::void_t<typename T::fragment_type>> : std::true_type { };

template<typename T>
static constexpr bool is_fragment_range_v = is_fragment_range<T>::value;

/// A non-mutable view of a FragmentRange
///
/// Provide a trivially copyable and movable, non-mutable view on a
/// fragment range. This allows uniform ownership semantics across
/// multi-fragment ranges and the single fragment and empty fragment
/// adaptors below, i.e. it allows treating all fragment ranges
/// uniformly as views.
template <typename T>
requires FragmentRange<T>
class fragment_range_view {
    const T* _range;
public:
    using fragment_type = typename T::fragment_type;
    using iterator = typename T::const_iterator;
    using const_iterator = typename T::const_iterator;

public:
    explicit fragment_range_view(const T& range) : _range(&range) { }

    const_iterator begin() const { return _range->begin(); }
    const_iterator end() const { return _range->end(); }

    size_t size_bytes() const { return _range->size_bytes(); }
    bool empty() const { return _range->empty(); }
};

/// Single-element fragment range
///
/// This is a helper that allows converting a bytes_view into a FragmentRange.
template<mutable_view is_mutable>
class single_fragment_range {
public:
    using fragment_type = std::conditional_t<is_mutable == mutable_view::no,
                                             bytes_view, bytes_mutable_view>;
private:
    fragment_type _view;
public:
    using iterator = const fragment_type*;
    using const_iterator = const fragment_type*;

    explicit single_fragment_range(fragment_type f) : _view { f } { }

    const_iterator begin() const { return &_view; }
    const_iterator end() const { return &_view + 1; }

    size_t size_bytes() const { return _view.size(); }
    bool empty() const { return _view.empty(); }
};

single_fragment_range(bytes_view) -> single_fragment_range<mutable_view::no>;
single_fragment_range(bytes_mutable_view) -> single_fragment_range<mutable_view::yes>;

/// Empty fragment range.
struct empty_fragment_range {
    using fragment_type = bytes_view;
    using iterator = bytes_view*;
    using const_iterator = bytes_view*;

    iterator begin() const { return nullptr; }
    iterator end() const { return nullptr; }

    size_t size_bytes() const { return 0; }
    bool empty() const { return true; }
};

static_assert(FragmentRange<empty_fragment_range>);
static_assert(FragmentRange<single_fragment_range<mutable_view::no>>);
static_assert(FragmentRange<single_fragment_range<mutable_view::yes>>);

template<typename FragmentedBuffer>
requires FragmentRange<FragmentedBuffer>
bytes linearized(const FragmentedBuffer& buffer)
{
    bytes b(bytes::initialized_later(), buffer.size_bytes());
    auto dst = b.begin();
    using boost::range::for_each;
    for_each(buffer, [&] (bytes_view fragment) {
        dst = boost::copy(fragment, dst);
    });
    return b;
}

template<typename FragmentedBuffer, typename Function>
requires FragmentRange<FragmentedBuffer> && requires (Function fn, bytes_view bv) {
    fn(bv);
}
decltype(auto) with_linearized(const FragmentedBuffer& buffer, Function&& fn)
{
    bytes b;
    bytes_view bv;
    if (__builtin_expect(!buffer.empty() && std::next(buffer.begin()) == buffer.end(), true)) {
        bv = *buffer.begin();
    } else if (!buffer.empty()) {
        b = linearized(buffer);
        bv = b;
    }
    return fn(bv);
}

template<typename T>
concept FragmentedView = requires (T view, size_t n) {
    typename T::fragment_type;
    requires std::is_same_v<typename T::fragment_type, bytes_view>
            || std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
    // No preconditions.
    { view.current_fragment() } -> std::convertible_to<const typename T::fragment_type&>;
    // No preconditions.
    { view.size_bytes() } -> std::convertible_to<size_t>;
    // Precondition: n <= size_bytes()
    { view.prefix(n) } -> std::same_as<T>;
    // Precondition: n <= size_bytes()
    view.remove_prefix(n);
    // Precondition: size_bytes() > 0
    view.remove_current();
};

template<typename T>
concept FragmentedMutableView = requires (T view) {
    requires FragmentedView<T>;
    requires std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
};

template<FragmentedView View>
requires (!FragmentRange<View>)
bytes linearized(View v)
{
    bytes b(bytes::initialized_later(), v.size_bytes());
    auto out = b.begin();
    while (v.size_bytes()) {
        out = std::copy(v.current_fragment().begin(), v.current_fragment().end(), out);
        v.remove_current();
    }
    return b;
}

template<FragmentedView View, typename Function>
requires (!FragmentRange<View>) && std::invocable<Function, bytes_view>
decltype(auto) with_linearized(const View& v, Function&& fn)
{
    if (v.size_bytes() == v.current_fragment().size()) [[likely]] {
        return fn(v.current_fragment());
    } else {
        return fn(linearized(v));
    }
}

class single_fragmented_view {
    bytes_view _view;
public:
    using fragment_type = bytes_view;
    explicit single_fragmented_view(bytes_view bv) : _view(bv) {}
    size_t size_bytes() const { return _view.size(); }
    void remove_prefix(size_t n) { _view.remove_prefix(n); }
    void remove_current() { _view = bytes_view(); }
    bytes_view current_fragment() const { return _view; }
    single_fragmented_view prefix(size_t n) { return single_fragmented_view(_view.substr(0, n)); }
};
static_assert(FragmentedView<single_fragmented_view>);
<commit_msg>utils: fragment_range: use range-based for loop instead of boost::for_each<commit_after>/*
 * Copyright (C) 2018 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <concepts>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/for_each.hpp>

#include "bytes.hh"

enum class mutable_view { no, yes, };

/// Fragmented buffer
///
/// Concept `FragmentedBuffer` is satisfied by any class that is a range of
/// fragments and provides a method `size_bytes()` which returns the total
/// size of the buffer. The interfaces accepting `FragmentedBuffer` will attempt
/// to avoid unnecessary linearisation.
template<typename T>
concept FragmentRange = requires (T range) {
    typename T::fragment_type;
    requires std::is_same_v<typename T::fragment_type, bytes_view>
        || std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
    { *range.begin() } -> std::convertible_to<const typename T::fragment_type&>;
    { *range.end() } -> std::convertible_to<const typename T::fragment_type&>;
    { range.size_bytes() } -> std::convertible_to<size_t>;
    { range.empty() } -> std::same_as<bool>; // returns true iff size_bytes() == 0.
};

template<typename T, typename = void>
struct is_fragment_range : std::false_type { };

template<typename T>
struct is_fragment_range<T, std::void_t<typename T::fragment_type>> : std::true_type { };

template<typename T>
static constexpr bool is_fragment_range_v = is_fragment_range<T>::value;

/// A non-mutable view of a FragmentRange
///
/// Provide a trivially copyable and movable, non-mutable view on a
/// fragment range. This allows uniform ownership semantics across
/// multi-fragment ranges and the single fragment and empty fragment
/// adaptors below, i.e. it allows treating all fragment ranges
/// uniformly as views.
template <typename T>
requires FragmentRange<T>
class fragment_range_view {
    const T* _range;
public:
    using fragment_type = typename T::fragment_type;
    using iterator = typename T::const_iterator;
    using const_iterator = typename T::const_iterator;

public:
    explicit fragment_range_view(const T& range) : _range(&range) { }

    const_iterator begin() const { return _range->begin(); }
    const_iterator end() const { return _range->end(); }

    size_t size_bytes() const { return _range->size_bytes(); }
    bool empty() const { return _range->empty(); }
};

/// Single-element fragment range
///
/// This is a helper that allows converting a bytes_view into a FragmentRange.
template<mutable_view is_mutable>
class single_fragment_range {
public:
    using fragment_type = std::conditional_t<is_mutable == mutable_view::no,
                                             bytes_view, bytes_mutable_view>;
private:
    fragment_type _view;
public:
    using iterator = const fragment_type*;
    using const_iterator = const fragment_type*;

    explicit single_fragment_range(fragment_type f) : _view { f } { }

    const_iterator begin() const { return &_view; }
    const_iterator end() const { return &_view + 1; }

    size_t size_bytes() const { return _view.size(); }
    bool empty() const { return _view.empty(); }
};

single_fragment_range(bytes_view) -> single_fragment_range<mutable_view::no>;
single_fragment_range(bytes_mutable_view) -> single_fragment_range<mutable_view::yes>;

/// Empty fragment range.
struct empty_fragment_range {
    using fragment_type = bytes_view;
    using iterator = bytes_view*;
    using const_iterator = bytes_view*;

    iterator begin() const { return nullptr; }
    iterator end() const { return nullptr; }

    size_t size_bytes() const { return 0; }
    bool empty() const { return true; }
};

static_assert(FragmentRange<empty_fragment_range>);
static_assert(FragmentRange<single_fragment_range<mutable_view::no>>);
static_assert(FragmentRange<single_fragment_range<mutable_view::yes>>);

template<typename FragmentedBuffer>
requires FragmentRange<FragmentedBuffer>
bytes linearized(const FragmentedBuffer& buffer)
{
    bytes b(bytes::initialized_later(), buffer.size_bytes());
    auto dst = b.begin();
    for (bytes_view fragment : buffer) {
        dst = boost::copy(fragment, dst);
    }
    return b;
}

template<typename FragmentedBuffer, typename Function>
requires FragmentRange<FragmentedBuffer> && requires (Function fn, bytes_view bv) {
    fn(bv);
}
decltype(auto) with_linearized(const FragmentedBuffer& buffer, Function&& fn)
{
    bytes b;
    bytes_view bv;
    if (__builtin_expect(!buffer.empty() && std::next(buffer.begin()) == buffer.end(), true)) {
        bv = *buffer.begin();
    } else if (!buffer.empty()) {
        b = linearized(buffer);
        bv = b;
    }
    return fn(bv);
}

template<typename T>
concept FragmentedView = requires (T view, size_t n) {
    typename T::fragment_type;
    requires std::is_same_v<typename T::fragment_type, bytes_view>
            || std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
    // No preconditions.
    { view.current_fragment() } -> std::convertible_to<const typename T::fragment_type&>;
    // No preconditions.
    { view.size_bytes() } -> std::convertible_to<size_t>;
    // Precondition: n <= size_bytes()
    { view.prefix(n) } -> std::same_as<T>;
    // Precondition: n <= size_bytes()
    view.remove_prefix(n);
    // Precondition: size_bytes() > 0
    view.remove_current();
};

template<typename T>
concept FragmentedMutableView = requires (T view) {
    requires FragmentedView<T>;
    requires std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
};

template<FragmentedView View>
requires (!FragmentRange<View>)
bytes linearized(View v)
{
    bytes b(bytes::initialized_later(), v.size_bytes());
    auto out = b.begin();
    while (v.size_bytes()) {
        out = std::copy(v.current_fragment().begin(), v.current_fragment().end(), out);
        v.remove_current();
    }
    return b;
}

template<FragmentedView View, typename Function>
requires (!FragmentRange<View>) && std::invocable<Function, bytes_view>
decltype(auto) with_linearized(const View& v, Function&& fn)
{
    if (v.size_bytes() == v.current_fragment().size()) [[likely]] {
        return fn(v.current_fragment());
    } else {
        return fn(linearized(v));
    }
}

class single_fragmented_view {
    bytes_view _view;
public:
    using fragment_type = bytes_view;
    explicit single_fragmented_view(bytes_view bv) : _view(bv) {}
    size_t size_bytes() const { return _view.size(); }
    void remove_prefix(size_t n) { _view.remove_prefix(n); }
    void remove_current() { _view = bytes_view(); }
    bytes_view current_fragment() const { return _view; }
    single_fragmented_view prefix(size_t n) { return single_fragmented_view(_view.substr(0, n)); }
};
static_assert(FragmentedView<single_fragmented_view>);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include <array>
#include <type_traits>

#include "utils/allocation_strategy.hh"

template<typename T, unsigned InternalSize = 0, typename SizeType = size_t>
class managed_vector {
    static_assert(std::is_nothrow_move_constructible<T>::value,
        "objects stored in managed_vector need to be nothrow move-constructible");
public:
    using value_type = T;
    using size_type = SizeType;
    using iterator = T*;
    using const_iterator = const T*;
private:
    struct external {
        managed_vector* _backref;
        T _data[];

        external(external&& other) noexcept : _backref(other._backref) {
            for (unsigned i = 0; i < _backref->size(); i++) {
                new (_data + i) T(std::move(other._data[i]));
                other._data[i].~T();
            }
            _backref->_data = _data;
        }
    };
    union maybe_constructed {
        constexpr maybe_constructed() { }
        ~maybe_constructed() { }
        T object;
    };
private:
    std::array<maybe_constructed, InternalSize> _internal;
    size_type _size = 0;
    size_type _capacity = InternalSize;
    T* _data = reinterpret_cast<T*>(_internal.data());
private:
    bool is_external() const {
        return _data != reinterpret_cast<const T*>(_internal.data());
    }
    external* get_external() {
        auto ptr = reinterpret_cast<char*>(_data) - offsetof(external, _data);
        return reinterpret_cast<external*>(ptr);
    }
    void maybe_grow(size_type new_size) {
        if (new_size <= _capacity) {
            return;
        }
        auto new_capacity = std::max({ _capacity + std::min(_capacity, size_type(1024)), new_size, size_type(InternalSize + 8) });
        reserve(new_capacity);
    }
public:
    managed_vector() = default;
    managed_vector(const managed_vector& other) {
        reserve(other._size);
        for (const auto& v : other) {
            push_back(v);
        }
    }
    managed_vector(managed_vector&& other) noexcept : _size(other._size), _capacity(other._capacity) {
        if (other.is_external()) {
            _data = other._data;
            other._data = reinterpret_cast<T*>(other._internal.data());
            get_external()->_backref = this;
        } else {
            for (unsigned i = 0; i < _size; i++) {
                new (_data + i) T(std::move(other._data[i]));
                other._data[i].~T();
            }
        }
        other._size = 0;
        other._capacity = InternalSize;
    }

    managed_vector& operator=(const managed_vector& other) {
        // FIXME: not exception safe
        if (this != &other) {
            this->~managed_vector();
            new (this) managed_vector(other);
        }
        return *this;
    }
    managed_vector& operator=(managed_vector&& other) noexcept {
        if (this != &other) {
            this->~managed_vector();
            new (this) managed_vector(std::move(other));
        }
        return *this;
    }

    ~managed_vector() {
        clear();
        if (is_external()) {
            current_allocator().free(get_external());
        }
    }

    T& at(size_type pos) {
        if (pos >= _size) {
            throw std::out_of_range("out of range");
        }
        return operator[](pos);
    }
    const T& at(size_type pos) const {
        if (pos >= _size) {
            throw std::out_of_range("out of range");
        }
        return operator[](pos);
    }
    T& operator[](size_type pos) noexcept {
        return _data[pos];
    }
    const T& operator[](size_type pos) const noexcept {
        return _data[pos];
    }

    T& front() noexcept { return *_data; }
    const T& front() const noexcept { return *_data;  }
    T& back() noexcept { return _data[_size - 1]; }
    const T& back() const noexcept { return _data[_size - 1]; }

    T* data() noexcept { return _data; }
    const T* data() const noexcept { return _data; }

    iterator begin() noexcept { return _data; }
    const_iterator begin() const noexcept { return _data; }
    const_iterator cbegin() const noexcept { return _data; }
    iterator end() noexcept { return _data + _size; }
    const_iterator end() const noexcept { return _data + _size; }
    const_iterator cend() const noexcept { return _data + _size; }

    bool empty() const noexcept { return !_size; }
    size_type size() const noexcept { return _size; }
    size_type capacity() const noexcept { return _capacity; }

    void clear() {
        while (_size) {
            pop_back();
        }
    }
    void reserve(size_type new_capacity) {
        if (new_capacity <= _capacity) {
            return;
        }
        auto ptr = current_allocator().alloc(standard_migrator<external>,
            sizeof(external) + sizeof(T) * new_capacity, alignof(external));
        auto ext = static_cast<external*>(ptr);
        ext->_backref = this;
        T* data_ptr = ext->_data;
        for (unsigned i = 0; i < _size; i++) {
            new (data_ptr + i) T(std::move(_data[i]));
            _data[i].~T();
        }
        if (is_external()) {
            current_allocator().free(get_external());
        }
        _data = data_ptr;
        _capacity = new_capacity;
    }

    iterator erase(iterator it) {
        std::move(it + 1, end(), it);
        _data[_size - 1].~T();
        _size--;
        return it;
    }

    void push_back(const T& value) {
        emplace_back(value);
    }
    void push_back(T&& value) {
        emplace_back(std::move(value));
    }
    template<typename... Args>
    void emplace_back(Args&&... args) {
        maybe_grow(_size + 1);
        new (_data + _size) T(std::forward<Args>(args)...);
        _size++;
    }
    void pop_back() {
        _data[_size - 1].~T();
        _size--;
    }

    void resize(size_type new_size) {
        maybe_grow(new_size);
        while (_size > new_size) {
            pop_back();
        }
        while (_size < new_size) {
            emplace_back();
        }
    }
    void resize(size_type new_size, const T& value) {
        maybe_grow(new_size);
        while (_size > new_size) {
            pop_back();
        }
        while (_size < new_size) {
            push_back(value);
        }
    }
};
<commit_msg>utils: managed_vector: Make copy constructor exception-safe<commit_after>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include <array>
#include <type_traits>

#include "utils/allocation_strategy.hh"

template<typename T, unsigned InternalSize = 0, typename SizeType = size_t>
class managed_vector {
    static_assert(std::is_nothrow_move_constructible<T>::value,
        "objects stored in managed_vector need to be nothrow move-constructible");
public:
    using value_type = T;
    using size_type = SizeType;
    using iterator = T*;
    using const_iterator = const T*;
private:
    struct external {
        managed_vector* _backref;
        T _data[];

        external(external&& other) noexcept : _backref(other._backref) {
            for (unsigned i = 0; i < _backref->size(); i++) {
                new (_data + i) T(std::move(other._data[i]));
                other._data[i].~T();
            }
            _backref->_data = _data;
        }
    };
    union maybe_constructed {
        constexpr maybe_constructed() { }
        ~maybe_constructed() { }
        T object;
    };
private:
    std::array<maybe_constructed, InternalSize> _internal;
    size_type _size = 0;
    size_type _capacity = InternalSize;
    T* _data = reinterpret_cast<T*>(_internal.data());
private:
    bool is_external() const {
        return _data != reinterpret_cast<const T*>(_internal.data());
    }
    external* get_external() {
        auto ptr = reinterpret_cast<char*>(_data) - offsetof(external, _data);
        return reinterpret_cast<external*>(ptr);
    }
    void maybe_grow(size_type new_size) {
        if (new_size <= _capacity) {
            return;
        }
        auto new_capacity = std::max({ _capacity + std::min(_capacity, size_type(1024)), new_size, size_type(InternalSize + 8) });
        reserve(new_capacity);
    }
    void clear_and_release() noexcept {
        clear();
        if (is_external()) {
            current_allocator().free(get_external());
        }
    }
public:
    managed_vector() = default;
    managed_vector(const managed_vector& other) {
        reserve(other._size);
        try {
            for (const auto& v : other) {
                push_back(v);
            }
        } catch (...) {
            clear_and_release();
            throw;
        }
    }
    managed_vector(managed_vector&& other) noexcept : _size(other._size), _capacity(other._capacity) {
        if (other.is_external()) {
            _data = other._data;
            other._data = reinterpret_cast<T*>(other._internal.data());
            get_external()->_backref = this;
        } else {
            for (unsigned i = 0; i < _size; i++) {
                new (_data + i) T(std::move(other._data[i]));
                other._data[i].~T();
            }
        }
        other._size = 0;
        other._capacity = InternalSize;
    }

    managed_vector& operator=(const managed_vector& other) {
        // FIXME: not exception safe
        if (this != &other) {
            this->~managed_vector();
            new (this) managed_vector(other);
        }
        return *this;
    }
    managed_vector& operator=(managed_vector&& other) noexcept {
        if (this != &other) {
            this->~managed_vector();
            new (this) managed_vector(std::move(other));
        }
        return *this;
    }

    ~managed_vector() {
        clear_and_release();
    }

    T& at(size_type pos) {
        if (pos >= _size) {
            throw std::out_of_range("out of range");
        }
        return operator[](pos);
    }
    const T& at(size_type pos) const {
        if (pos >= _size) {
            throw std::out_of_range("out of range");
        }
        return operator[](pos);
    }
    T& operator[](size_type pos) noexcept {
        return _data[pos];
    }
    const T& operator[](size_type pos) const noexcept {
        return _data[pos];
    }

    T& front() noexcept { return *_data; }
    const T& front() const noexcept { return *_data;  }
    T& back() noexcept { return _data[_size - 1]; }
    const T& back() const noexcept { return _data[_size - 1]; }

    T* data() noexcept { return _data; }
    const T* data() const noexcept { return _data; }

    iterator begin() noexcept { return _data; }
    const_iterator begin() const noexcept { return _data; }
    const_iterator cbegin() const noexcept { return _data; }
    iterator end() noexcept { return _data + _size; }
    const_iterator end() const noexcept { return _data + _size; }
    const_iterator cend() const noexcept { return _data + _size; }

    bool empty() const noexcept { return !_size; }
    size_type size() const noexcept { return _size; }
    size_type capacity() const noexcept { return _capacity; }

    void clear() {
        while (_size) {
            pop_back();
        }
    }
    void reserve(size_type new_capacity) {
        if (new_capacity <= _capacity) {
            return;
        }
        auto ptr = current_allocator().alloc(standard_migrator<external>,
            sizeof(external) + sizeof(T) * new_capacity, alignof(external));
        auto ext = static_cast<external*>(ptr);
        ext->_backref = this;
        T* data_ptr = ext->_data;
        for (unsigned i = 0; i < _size; i++) {
            new (data_ptr + i) T(std::move(_data[i]));
            _data[i].~T();
        }
        if (is_external()) {
            current_allocator().free(get_external());
        }
        _data = data_ptr;
        _capacity = new_capacity;
    }

    iterator erase(iterator it) {
        std::move(it + 1, end(), it);
        _data[_size - 1].~T();
        _size--;
        return it;
    }

    void push_back(const T& value) {
        emplace_back(value);
    }
    void push_back(T&& value) {
        emplace_back(std::move(value));
    }
    template<typename... Args>
    void emplace_back(Args&&... args) {
        maybe_grow(_size + 1);
        new (_data + _size) T(std::forward<Args>(args)...);
        _size++;
    }
    void pop_back() {
        _data[_size - 1].~T();
        _size--;
    }

    void resize(size_type new_size) {
        maybe_grow(new_size);
        while (_size > new_size) {
            pop_back();
        }
        while (_size < new_size) {
            emplace_back();
        }
    }
    void resize(size_type new_size, const T& value) {
        maybe_grow(new_size);
        while (_size > new_size) {
            pop_back();
        }
        while (_size < new_size) {
            push_back(value);
        }
    }
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: services.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: sb $ $Date: 2001-08-20 07:10:12 $
 *
 *  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 _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPU_MACROS_HXX_
#include <cppu/macros.hxx>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _UNO_ENVIRONMENT_H_
#include <uno/environment.h>
#endif

#ifndef UUI_IAHNDL_HXX
#include <iahndl.hxx>
#endif

using namespace com::sun::star;

//============================================================================
//
//  component_getImplementationEnvironment
//
//============================================================================

extern "C" void SAL_CALL
component_getImplementationEnvironment(sal_Char const ** pEnvTypeName,
                                       uno_Environment **)
{
    *pEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

//============================================================================
//
//  component_writeInfo
//
//============================================================================

extern "C" sal_Bool SAL_CALL component_writeInfo(void *, void * pRegistryKey)
{
    bool bSuccess = pRegistryKey != 0;
    uno::Reference< registry::XRegistryKey > xKey;
    if (bSuccess)
    {
        rtl::OUString aKeyName(rtl::OUString::createFromAscii("/"));
        aKeyName += rtl::OUString::createFromAscii(
                        UUIInteractionHandler::m_aImplementationName);
        aKeyName += rtl::OUString::createFromAscii("/UNO/SERVICES");
        try
        {
            xKey = static_cast< registry::XRegistryKey * >(pRegistryKey)->
                       createKey(aKeyName);
        }
        catch (registry::InvalidRegistryException &) {}
        bSuccess = xKey.is() != false;
    }
    if (bSuccess)
    {
        uno::Sequence< rtl::OUString >
            aServiceNames(
                UUIInteractionHandler::getSupportedServiceNames_static());
        for (sal_Int32 i = 0; i < aServiceNames.getLength(); ++i)
            try
            {
                xKey->createKey(aServiceNames[i]);
            }
            catch (registry::InvalidRegistryException &)
            {
                bSuccess = false;
                break;
            }
    }
    return bSuccess;
}

//============================================================================
//
//  component_getFactory
//
//============================================================================

extern "C" void * SAL_CALL component_getFactory(sal_Char const * pImplName,
                                                void * pServiceManager,
                                                void *)
{
    void * pFactory = 0;
    if (pServiceManager
        && rtl_str_compare(pImplName,
                           UUIInteractionHandler::m_aImplementationName)
               == 0)
    {
        uno::Reference< lang::XSingleServiceFactory >
            xTheFactory(
                cppu::createSingleFactory(
                    static_cast< lang::XMultiServiceFactory * >(
                        pServiceManager),
                    rtl::OUString::createFromAscii(
                        UUIInteractionHandler::m_aImplementationName),
                    &UUIInteractionHandler::createInstance,
                   UUIInteractionHandler::getSupportedServiceNames_static()));
        if (xTheFactory.is())
        {
            xTheFactory->acquire();
            pFactory = xTheFactory.get();
        }
    }
    return pFactory;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.246); FILE MERGED 2005/09/05 17:09:52 rt 1.5.246.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: services.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 10:27:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPU_MACROS_HXX_
#include <cppu/macros.hxx>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _UNO_ENVIRONMENT_H_
#include <uno/environment.h>
#endif

#ifndef UUI_IAHNDL_HXX
#include <iahndl.hxx>
#endif

using namespace com::sun::star;

//============================================================================
//
//  component_getImplementationEnvironment
//
//============================================================================

extern "C" void SAL_CALL
component_getImplementationEnvironment(sal_Char const ** pEnvTypeName,
                                       uno_Environment **)
{
    *pEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

//============================================================================
//
//  component_writeInfo
//
//============================================================================

extern "C" sal_Bool SAL_CALL component_writeInfo(void *, void * pRegistryKey)
{
    bool bSuccess = pRegistryKey != 0;
    uno::Reference< registry::XRegistryKey > xKey;
    if (bSuccess)
    {
        rtl::OUString aKeyName(rtl::OUString::createFromAscii("/"));
        aKeyName += rtl::OUString::createFromAscii(
                        UUIInteractionHandler::m_aImplementationName);
        aKeyName += rtl::OUString::createFromAscii("/UNO/SERVICES");
        try
        {
            xKey = static_cast< registry::XRegistryKey * >(pRegistryKey)->
                       createKey(aKeyName);
        }
        catch (registry::InvalidRegistryException &) {}
        bSuccess = xKey.is() != false;
    }
    if (bSuccess)
    {
        uno::Sequence< rtl::OUString >
            aServiceNames(
                UUIInteractionHandler::getSupportedServiceNames_static());
        for (sal_Int32 i = 0; i < aServiceNames.getLength(); ++i)
            try
            {
                xKey->createKey(aServiceNames[i]);
            }
            catch (registry::InvalidRegistryException &)
            {
                bSuccess = false;
                break;
            }
    }
    return bSuccess;
}

//============================================================================
//
//  component_getFactory
//
//============================================================================

extern "C" void * SAL_CALL component_getFactory(sal_Char const * pImplName,
                                                void * pServiceManager,
                                                void *)
{
    void * pFactory = 0;
    if (pServiceManager
        && rtl_str_compare(pImplName,
                           UUIInteractionHandler::m_aImplementationName)
               == 0)
    {
        uno::Reference< lang::XSingleServiceFactory >
            xTheFactory(
                cppu::createSingleFactory(
                    static_cast< lang::XMultiServiceFactory * >(
                        pServiceManager),
                    rtl::OUString::createFromAscii(
                        UUIInteractionHandler::m_aImplementationName),
                    &UUIInteractionHandler::createInstance,
                   UUIInteractionHandler::getSupportedServiceNames_static()));
        if (xTheFactory.is())
        {
            xTheFactory->acquire();
            pFactory = xTheFactory.get();
        }
    }
    return pFactory;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>

void run_part_one() {
}
void run_part_two() {
}

int main(int argc, char* argv[]) {
    if (argc > 1) {
        if (std::string(argv[1]) == "--part_two") {
            run_part_two();
        } else {
            std::cout << "Usage: day18 [--part_two]" << std::endl;
            return -1;
        }
    } else {
        run_part_one();
    }
}
<commit_msg>added runtime code for day 18 part one<commit_after>#include <iostream>
#include <string>

#include "LightMap.hpp"

void print_map(LightMap& light_map) {
    for (int y=0;y<100;y++) {
        for(int x=0;x<100;x++) {
            if (light_map.is_on(x,y)) {
                std::cout << '#';
            } else {
                std::cout << '.';
            }
        }
        std::cout << std::endl;
    }
}
void run_part_one() {
    std::string line;
    LightMap map(100,100);
    unsigned int current_line = 0;
    while (std::getline(std::cin,line)) {
        for (unsigned int i=0; i<100; i++) {
            if (line[i] == '#') {
                map.turn_on(i,current_line);
            }
        }
        current_line++;
    }
    for (unsigned int i = 0; i<100; i++) {
        map = map.evolve();
    }
    std::cout << map.get_active_lights() << std::endl;
}
void run_part_two() {
}

int main(int argc, char* argv[]) {
    if (argc > 1) {
        if (std::string(argv[1]) == "--part_two") {
            run_part_two();
        } else {
            std::cout << "Usage: day18 [--part_two]" << std::endl;
            return -1;
        }
    } else {
        run_part_one();
    }
}
<|endoftext|>


<commit_before>#define DeutSelector_cxx
// The class definition in DeutSelector.h has been generated automatically
// by the ROOT utility TTree::MakeSelector(). This class is derived
// from the ROOT class TSelector. For more information on the TSelector
// framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual.

// The following methods are defined in this file:
//    Begin():        called every time a loop on the tree starts,
//                    a convenient place to create your histograms.
//    SlaveBegin():   called after Begin(), when on PROOF called only on the
//                    slave servers.
//    Process():      called for each event, in this function you decide what
//                    to read and fill your histograms.
//    SlaveTerminate: called at the end of the loop on the tree, when on PROOF
//                    called only on the slave servers.
//    Terminate():    called at the end of the loop on the tree,
//                    a convenient place to draw/fit your histograms.
//
// To use this file, try the following session on your Tree T:
//
// Root > T->Process("DeutSelector.C")
// Root > T->Process("DeutSelector.C","some options")
// Root > T->Process("DeutSelector.C+")
//

#include "DeutSelector.h"
#include <TH2.h>
#include <TH2F.h>
#include <TH1D.h>
#include <TStyle.h>
#include <Riostream.h>
#include <TMath.h>
#include <TCanvas.h>
#include <TAxis.h>
#include <TF1.h>

#define EPSILON 1E-5

static void BinLogAxis(const TH1 *h)
{
  //
  // Method for the correct logarithmic binning of histograms
  //
  TAxis *axis = const_cast<TAxis*>(h->GetXaxis());
  const Int_t bins = axis->GetNbins();

  const Double_t from = axis->GetXmin();
  const Double_t to = axis->GetXmax();
  Double_t *newBins = new Double_t[bins + 1];

  newBins[0] = from;
  Double_t factor = pow(to / from, 1. / bins);

  for (Int_t i = 1; i <= bins; i++) {
    newBins[i] = factor * newBins[i - 1];
  }
  axis->Set(bins, newBins);
  delete [] newBins;
}

Double_t BetheBlochAleph(Double_t bg,
			 Double_t kp1,
			 Double_t kp2,
			 Double_t kp3,
			 Double_t kp4,
			 Double_t kp5) {
  Double_t beta = bg/TMath::Sqrt(1.+ bg*bg);
  Double_t aa = TMath::Power(beta,kp4);
  Double_t bb = TMath::Power(1./bg,kp5);
  bb=TMath::Log(kp3+bb);
  return (kp2-aa-bb)*kp1/aa;
}

Double_t DeuteronTPC(Double_t *x,Double_t *par) {
  // Deuteron expected signal in TPC
  // Double_t fAlephParameters[5];
  // fAlephParameters[0] = 0.0283086;
  // fAlephParameters[1] = 2.63394e+01;
  // fAlephParameters[2] = 5.04114e-11;
  // fAlephParameters[3] = 2.12543e+00;
  // fAlephParameters[4] = 4.88663e+00;
  //                                  1.45802,27.4992,4.00313e-15,2.48485,8.31768
  return BetheBlochAleph(x[0] / 1.876,1.45802,27.4992,4.00313e-15,2.48485,8.31768);
  //return BetheBlochAleph(x[0] / 1.876,fAlephParameters[0],fAlephParameters[1],fAlephParameters[2],fAlephParameters[3],fAlephParameters[4]);
}

void DeutSelector::Begin(TTree * /*tree*/)
{
  // The Begin() function is called at the start of the query.
  // When running with PROOF Begin() is only called on the client.
  // The tree argument is deprecated (on PROOF 0 is passed).
  TString option = GetOption();
}

void DeutSelector::SlaveBegin(TTree * /*tree*/)
{
  // The SlaveBegin() function is called after the Begin() function.
  // When running with PROOF SlaveBegin() is called on each slave server.
  // The tree argument is deprecated (on PROOF 0 is passed).

  TString option = GetOption();
  fBeta = new TH1D("fBeta",";#beta;Entries",100,0.f,1.f);
  fGamma = new TH1D("fGamma",";#gamma;Entries",1000,1.f,1000.f);
  fdEdxTPC = new TH2F("fdEdxTPC",";p (GeV/c);dE/dx (a.u.)",500,0.1,5.,1000,0,2000);
  fdEdxTPCSignal = new TH2F("fdEdxTPCSignal",";p (GeV/c);dE/dx (a.u.)",500,0.1,5.,2000,0,2000);
  fdEdxTPCproj = new TH2F("fdEdxTPCproj",";p (GeV/c);dE/dx (a.u.)",93,0.4,3.2,2000,0,2000);
  BinLogAxis(fdEdxTPC);
  fSignal = new TH1D("fSignal",";",600,0.1,6.1);
  GetOutputList()->Add(fdEdxTPC);
  GetOutputList()->Add(fdEdxTPCSignal);
  GetOutputList()->Add(fdEdxTPCproj);
  GetOutputList()->Add(fSignal);
  GetOutputList()->Add(fBeta);
  GetOutputList()->Add(fGamma);

}

Bool_t DeutSelector::Process(Long64_t entry)
{
  // The Process() function is called for each entry in the tree (or possibly
  // keyed object in the case of PROOF) to be processed. The entry argument
  // specifies which entry in the currently loaded tree is to be processed.
  // It can be passed to either DeutSelector::GetEntry() or TBranch::GetEntry()
  // to read either all or the required parts of the data. When processing
  // keyed objects with PROOF, the object is already loaded and is available
  // via the fObject pointer.
  //
  // This function should contain the "body" of the analysis. It can contain
  // simple or elaborate selection criteria, run algorithms on the data
  // of the event and typically fill histograms.
  //
  // The processing can be stopped by calling Abort().
  //
  // Use fStatus to set the return value of TTree::Process().
  //
  // The return value is currently not used.

  GetEntry(entry);
  fdEdxTPC->Fill(pTPC,TPCsignal);
  fdEdxTPCproj->Fill(pTPC,TPCsignal);

  if (TOFtime > 0.f && length > 0.f) {
    Float_t beta = length / (2.99792457999999984e-02 * TOFtime);
    fBeta->Fill(beta);
    if (beta < (1.f - EPSILON)) {
      Float_t gamma = 1 / TMath::Sqrt(1 - (beta * beta));
      fGamma->Fill(gamma);
      fSignal->Fill(p / (beta * gamma));
      if (p / (beta * gamma) > 1.5f ) {
        fdEdxTPCSignal->Fill(pTPC,TPCsignal);
      }
    }
  }
  return kTRUE;
}

void DeutSelector::SlaveTerminate()
{
  // The SlaveTerminate() function is called after all entries or objects
  // have been processed. When running with PROOF SlaveTerminate() is called
  // on each slave server.

}

void DeutSelector::Terminate()
{
  // The Terminate() function is the last function to be called during
  // a query. It always runs on the client, it can be used to present
  // the results graphically or save the results to file.

  TFile f("final.root","recreate");
  TF1 fbb("BBAleph",DeuteronTPC,0.4f,5.f,0);
  TCanvas c;
  fdEdxTPC = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPC"));
  if (fdEdxTPC) {
    c.cd();
    fdEdxTPC->DrawClone();
    fbb.DrawClone("same");
    f.cd();
    c.Write();
    fdEdxTPC->Write();
  }

  fdEdxTPCSignal = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPCSignal"));
  if (fdEdxTPCSignal) {
    fdEdxTPCSignal->Write();
  }

  fdEdxTPCproj = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPCproj"));
  if (fdEdxTPCproj) {
    fdEdxTPCproj->Write();
  }

  fBeta = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fBeta"));
  if (fBeta) {
    fBeta->Write();
  }

  fGamma = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fGamma"));
  if (fGamma) {
    fGamma->Write();
  }

  fSignal = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fSignal"));
  if (fSignal) {
    fSignal->Write();
  }
  f.Close();

}
<commit_msg>Further rebinding<commit_after>#define DeutSelector_cxx
// The class definition in DeutSelector.h has been generated automatically
// by the ROOT utility TTree::MakeSelector(). This class is derived
// from the ROOT class TSelector. For more information on the TSelector
// framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual.

// The following methods are defined in this file:
//    Begin():        called every time a loop on the tree starts,
//                    a convenient place to create your histograms.
//    SlaveBegin():   called after Begin(), when on PROOF called only on the
//                    slave servers.
//    Process():      called for each event, in this function you decide what
//                    to read and fill your histograms.
//    SlaveTerminate: called at the end of the loop on the tree, when on PROOF
//                    called only on the slave servers.
//    Terminate():    called at the end of the loop on the tree,
//                    a convenient place to draw/fit your histograms.
//
// To use this file, try the following session on your Tree T:
//
// Root > T->Process("DeutSelector.C")
// Root > T->Process("DeutSelector.C","some options")
// Root > T->Process("DeutSelector.C+")
//

#include "DeutSelector.h"
#include <TH2.h>
#include <TH2F.h>
#include <TH1D.h>
#include <TStyle.h>
#include <Riostream.h>
#include <TMath.h>
#include <TCanvas.h>
#include <TAxis.h>
#include <TF1.h>

#define EPSILON 1E-5

static void BinLogAxis(const TH1 *h)
{
  //
  // Method for the correct logarithmic binning of histograms
  //
  TAxis *axis = const_cast<TAxis*>(h->GetXaxis());
  const Int_t bins = axis->GetNbins();

  const Double_t from = axis->GetXmin();
  const Double_t to = axis->GetXmax();
  Double_t *newBins = new Double_t[bins + 1];

  newBins[0] = from;
  Double_t factor = pow(to / from, 1. / bins);

  for (Int_t i = 1; i <= bins; i++) {
    newBins[i] = factor * newBins[i - 1];
  }
  axis->Set(bins, newBins);
  delete [] newBins;
}

Double_t BetheBlochAleph(Double_t bg,
			 Double_t kp1,
			 Double_t kp2,
			 Double_t kp3,
			 Double_t kp4,
			 Double_t kp5) {
  Double_t beta = bg/TMath::Sqrt(1.+ bg*bg);
  Double_t aa = TMath::Power(beta,kp4);
  Double_t bb = TMath::Power(1./bg,kp5);
  bb=TMath::Log(kp3+bb);
  return (kp2-aa-bb)*kp1/aa;
}

Double_t DeuteronTPC(Double_t *x,Double_t *par) {
  // Deuteron expected signal in TPC
  // Double_t fAlephParameters[5];
  // fAlephParameters[0] = 0.0283086;
  // fAlephParameters[1] = 2.63394e+01;
  // fAlephParameters[2] = 5.04114e-11;
  // fAlephParameters[3] = 2.12543e+00;
  // fAlephParameters[4] = 4.88663e+00;
  //                                  1.45802,27.4992,4.00313e-15,2.48485,8.31768
  return BetheBlochAleph(x[0] / 1.876,1.45802,27.4992,4.00313e-15,2.48485,8.31768);
  //return BetheBlochAleph(x[0] / 1.876,fAlephParameters[0],fAlephParameters[1],fAlephParameters[2],fAlephParameters[3],fAlephParameters[4]);
}

void DeutSelector::Begin(TTree * /*tree*/)
{
  // The Begin() function is called at the start of the query.
  // When running with PROOF Begin() is only called on the client.
  // The tree argument is deprecated (on PROOF 0 is passed).
  TString option = GetOption();
}

void DeutSelector::SlaveBegin(TTree * /*tree*/)
{
  // The SlaveBegin() function is called after the Begin() function.
  // When running with PROOF SlaveBegin() is called on each slave server.
  // The tree argument is deprecated (on PROOF 0 is passed).

  TString option = GetOption();
  fBeta = new TH1D("fBeta",";#beta;Entries",100,0.f,1.f);
  fGamma = new TH1D("fGamma",";#gamma;Entries",1000,1.f,1000.f);
  fdEdxTPC = new TH2F("fdEdxTPC",";p (GeV/c);dE/dx (a.u.)",500,0.1,5.,500,0,2000);
  fdEdxTPCSignal = new TH2F("fdEdxTPCSignal",";p (GeV/c);dE/dx (a.u.)",500,0.1,5.,2000,0,2000);
  fdEdxTPCproj = new TH2F("fdEdxTPCproj",";p (GeV/c);dE/dx (a.u.)",93,0.4,3.2,2000,0,2000);
  BinLogAxis(fdEdxTPC);
  fSignal = new TH1D("fSignal",";",600,0.1,6.1);
  GetOutputList()->Add(fdEdxTPC);
  GetOutputList()->Add(fdEdxTPCSignal);
  GetOutputList()->Add(fdEdxTPCproj);
  GetOutputList()->Add(fSignal);
  GetOutputList()->Add(fBeta);
  GetOutputList()->Add(fGamma);

}

Bool_t DeutSelector::Process(Long64_t entry)
{
  // The Process() function is called for each entry in the tree (or possibly
  // keyed object in the case of PROOF) to be processed. The entry argument
  // specifies which entry in the currently loaded tree is to be processed.
  // It can be passed to either DeutSelector::GetEntry() or TBranch::GetEntry()
  // to read either all or the required parts of the data. When processing
  // keyed objects with PROOF, the object is already loaded and is available
  // via the fObject pointer.
  //
  // This function should contain the "body" of the analysis. It can contain
  // simple or elaborate selection criteria, run algorithms on the data
  // of the event and typically fill histograms.
  //
  // The processing can be stopped by calling Abort().
  //
  // Use fStatus to set the return value of TTree::Process().
  //
  // The return value is currently not used.

  GetEntry(entry);
  fdEdxTPC->Fill(pTPC,TPCsignal);
  fdEdxTPCproj->Fill(pTPC,TPCsignal);

  if (TOFtime > 0.f && length > 0.f) {
    Float_t beta = length / (2.99792457999999984e-02 * TOFtime);
    fBeta->Fill(beta);
    if (beta < (1.f - EPSILON)) {
      Float_t gamma = 1 / TMath::Sqrt(1 - (beta * beta));
      fGamma->Fill(gamma);
      fSignal->Fill(p / (beta * gamma));
      if (p / (beta * gamma) > 1.5f ) {
        fdEdxTPCSignal->Fill(pTPC,TPCsignal);
      }
    }
  }
  return kTRUE;
}

void DeutSelector::SlaveTerminate()
{
  // The SlaveTerminate() function is called after all entries or objects
  // have been processed. When running with PROOF SlaveTerminate() is called
  // on each slave server.

}

void DeutSelector::Terminate()
{
  // The Terminate() function is the last function to be called during
  // a query. It always runs on the client, it can be used to present
  // the results graphically or save the results to file.

  TFile f("final.root","recreate");
  TF1 fbb("BBAleph",DeuteronTPC,0.4f,5.f,0);
  TCanvas c;
  fdEdxTPC = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPC"));
  if (fdEdxTPC) {
    c.cd();
    fdEdxTPC->DrawClone();
    fbb.DrawClone("same");
    f.cd();
    c.Write();
    fdEdxTPC->Write();
  }

  fdEdxTPCSignal = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPCSignal"));
  if (fdEdxTPCSignal) {
    fdEdxTPCSignal->Write();
  }

  fdEdxTPCproj = dynamic_cast<TH2F*>(GetOutputList()->FindObject("fdEdxTPCproj"));
  if (fdEdxTPCproj) {
    fdEdxTPCproj->Write();
  }

  fBeta = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fBeta"));
  if (fBeta) {
    fBeta->Write();
  }

  fGamma = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fGamma"));
  if (fGamma) {
    fGamma->Write();
  }

  fSignal = dynamic_cast<TH1D*>(GetOutputList()->FindObject("fSignal"));
  if (fSignal) {
    fSignal->Write();
  }
  f.Close();

}
<|endoftext|>


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

#include "coretext/common.h"

#ifdef MACOSX

#include "aqua/salframe.h"
#include "coretext/salgdi.h"

#else

#include <premac.h>
#include <UIKit/UIKit.h>
#include <postmac.h>

#include <basebmp/scanlineformats.hxx>

#include "saldatabasic.hxx"
#include "headless/svpframe.hxx"
#include "headless/svpgdi.hxx"

#endif

#include "coretext/salcoretextstyle.hxx"

#ifdef MACOSX

QuartzSalGraphics::QuartzSalGraphics()
    : mpFrame( NULL )
    , mxLayer( NULL )
    , mrContext( NULL )
    , mpXorEmulation( NULL )
    , mnXorMode( 0 )
    , mnWidth( 0 )
    , mnHeight( 0 )
    , mnBitmapDepth( 0 )
    , mnRealDPIX( 0 )
    , mnRealDPIY( 0 )
    , mfFakeDPIScale( 1.0 )
    , mxClipPath( NULL )
    , maLineColor( COL_WHITE )
    , maFillColor( COL_BLACK )
    , mbNonAntialiasedText( false )
    , mbPrinter( false )
    , mbVirDev( false )
    , mbWindow( false )
{
    SAL_INFO( "vcl.coretext.gr", "QuartzSalGraphics::QuartzSalGraphics() " << this );

    m_style = new CoreTextStyleInfo();
}

QuartzSalGraphics::~QuartzSalGraphics()
{
    SAL_INFO( "vcl.coretext.gr", "~QuartzSalGraphics(" << this << ")" );

    if(m_style)
    {
        delete m_style;
        m_style = NULL;
    }
}

#endif

inline bool QuartzSalGraphics::AddTempDevFont( ImplDevFontList*,
                                             const OUString& ,
                                             const OUString& )
{
    OSL_ASSERT( FALSE );
    return false;
}

void QuartzSalGraphics::DrawServerFontLayout( const ServerFontLayout& )
{
}

void QuartzSalGraphics::FreeEmbedFontData( const void* pData, long /*nDataLen*/ )
{
    // TODO: implementing this only makes sense when the implementation of
    //      QuartzSalGraphics::GetEmbedFontData() returns non-NULL
    (void)pData;
    DBG_ASSERT( (pData!=NULL), "QuartzSalGraphics::FreeEmbedFontData() is not implemented\n");
}

void QuartzSalGraphics::GetDevFontList( ImplDevFontList* pFontList )
{
    DBG_ASSERT( pFontList, "QuartzSalGraphics::GetDevFontList(NULL) !");

    SalData* pSalData = GetSalData();
    if (pSalData->mpFontList == NULL)
    {
        pSalData->mpFontList = new SystemFontList();
    }
    // Copy all PhysicalFontFace objects contained in the SystemFontList
    pSalData->mpFontList->AnnounceFonts( *pFontList );
}

void QuartzSalGraphics::ClearDevFontCache()
{
    SalData* pSalData = GetSalData();
    delete pSalData->mpFontList;
    pSalData->mpFontList = NULL;
}

void QuartzSalGraphics::GetDevFontSubstList( OutputDevice* )
{
    // nothing to do since there are no device-specific fonts on Aqua
}

const void* QuartzSalGraphics::GetEmbedFontData( const PhysicalFontFace*,
                              const sal_Ucs* /*pUnicodes*/,
                              sal_Int32* /*pWidths*/,
                              FontSubsetInfo&,
                              long* /*pDataLen*/ )
{
    return NULL;
}

const Ucs2SIntMap* QuartzSalGraphics::GetFontEncodingVector(const PhysicalFontFace*,
                                                          const Ucs2OStrMap** /*ppNonEncoded*/ )
{
    return NULL;
}

void QuartzSalGraphics::GetFontMetric( ImplFontMetricData* pMetric, int nFallbackLevel )
{
    (void)nFallbackLevel; // glyph-fallback on CoreText is done differently -> no fallback level

    pMetric->mbScalableFont = true;
    pMetric->mbKernableFont = true;
    CTFontRef font = m_style->GetFont();
    DBG_ASSERT(font, "GetFontMetric without font set in style");

    pMetric->mnAscent = static_cast<long>( CTFontGetAscent(font) * mfFakeDPIScale + 0.5);
    pMetric->mnDescent = static_cast<long>(CTFontGetDescent(font) * mfFakeDPIScale + 0.5);
    const long nExtDescent  = static_cast<long>((CTFontGetLeading(font) + CTFontGetDescent(font)) *
                                                mfFakeDPIScale + 0.5);
    pMetric->mnExtLeading   = nExtDescent + pMetric->mnDescent;
    pMetric->mnIntLeading   = 0;
    pMetric->mnWidth = m_style->GetFontStretchedSize();

    SAL_INFO( "vcl.coretext.gr",
              "GetFontMetric(" << this << ") returning: {ascent=" << pMetric->mnAscent <<
              ",descent=" << pMetric->mnDescent <<
              ",extleading=" << pMetric->mnExtLeading <<
              ",intleading=" << pMetric->mnIntLeading <<
              ",width=" << pMetric->mnWidth <<
              "}" );
}

sal_Bool QuartzSalGraphics::GetGlyphBoundRect( sal_GlyphId /*nGlyphId*/, Rectangle& /*rRect*/ )
{
    /* TODO: create a Ghyph iterator to keep track ot 'state' between call */
    return false;
}

sal_Bool QuartzSalGraphics::GetGlyphOutline( sal_GlyphId /*nGlyphId*/, basegfx::B2DPolyPolygon& /*rPolyPoly*/ )
{
    /* TODO */
    return false;
}

void QuartzSalGraphics::GetGlyphWidths( const PhysicalFontFace* /*pFontData*/, bool /*bVertical*/,
                                      Int32Vector& /*rGlyphWidths*/, Ucs2UIntMap& /*rUnicodeEnc*/ )
{
}

sal_uLong QuartzSalGraphics::GetKernPairs( sal_uLong, ImplKernPairData* )
{
    return 0;
}

bool QuartzSalGraphics::GetImplFontCapabilities(vcl::FontCapabilities &rFontCapabilities) const
{
    if( !m_style )
    {
        return false;
    }
    CoreTextPhysicalFontFace* font_face = m_style->GetFontFace();
    if( !font_face)
    {
        return false;
    }
    return font_face->GetImplFontCapabilities(rFontCapabilities);
}

const ImplFontCharMap* QuartzSalGraphics::GetImplFontCharMap() const
{
    if( !m_style )
    {
        return NULL;
    }
    CoreTextPhysicalFontFace* font_face = m_style->GetFontFace();
    if( !font_face)
    {
        return ImplFontCharMap::GetDefaultMap();
    }
    return font_face->GetImplFontCharMap();
}

#ifndef IOS

bool QuartzSalGraphics::GetRawFontData( const PhysicalFontFace* pFontFace,
                     std::vector<unsigned char>& rBuffer, bool* pJustCFF )
{
    const CoreTextPhysicalFontFace* font_face = static_cast<const CoreTextPhysicalFontFace*>(pFontFace);

    return font_face->GetRawFontData(rBuffer, pJustCFF);
}

#endif

SystemFontData QuartzSalGraphics::GetSysFontData( int /* nFallbacklevel */ ) const
{
    SystemFontData aSysFontData;
    aSysFontData.nSize = sizeof( SystemFontData );
    aSysFontData.bAntialias = true;

    CTFontRef font = CTFontCreateUIFontForLanguage(kCTFontSystemFontType, 0.0, NULL);
    font = (CTFontRef)CFRetain(font);
    aSysFontData.rCTFont = font;

    CTFontRef italic_font = CTFontCreateCopyWithSymbolicTraits( font,
                                                                0.0,
                                                                NULL,
                                                                kCTFontItalicTrait,
                                                                kCTFontItalicTrait + kCTFontBoldTrait);
    aSysFontData.bFakeItalic = italic_font ? false : true;
    SafeCFRelease(italic_font);

    CTFontRef bold_font = CTFontCreateCopyWithSymbolicTraits( font,
                                                              0.0,
                                                              NULL,
                                                              kCTFontBoldTrait,
                                                              kCTFontItalicTrait + kCTFontBoldTrait);
    aSysFontData.bFakeBold = bold_font ? false : true;
    SafeCFRelease(bold_font);

    CTFontRef vertical_font = CTFontCreateCopyWithSymbolicTraits( font,
                                                                  0.0,
                                                                  NULL,
                                                                  kCTFontVerticalTrait,
                                                                  kCTFontVerticalTrait);
    aSysFontData.bVerticalCharacterType = vertical_font ? true : false;
    SafeCFRelease(vertical_font);

    return aSysFontData;
}

sal_uInt16 QuartzSalGraphics::SetFont( FontSelectPattern* pReqFont, int /*nFallbackLevel*/ )
{
    m_style->SetFont(pReqFont);

    return 0;
}

void QuartzSalGraphics::SetTextColor( SalColor nSalColor )
{
    m_style->SetColor(nSalColor);
}

#ifdef IOS

// Note that "QuartzSalGraphics" *is* SvpSalGraphics for iOS

bool SvpSalGraphics::CheckContext()
{
    const basegfx::B2IVector size = m_aDevice->getSize();
    const basegfx::B2IVector bufferSize = m_aDevice->getBufferSize();
    const sal_Int32 scanlineStride = m_aDevice->getScanlineStride();
    basebmp::RawMemorySharedArray pixelBuffer = m_aDevice->getBuffer();

    SAL_INFO( "vcl.ios",
              "CheckContext: device=" << m_aDevice.get() <<
              " size=" << size.getX() << "x" << size.getY() <<
              (m_aDevice->isTopDown() ? " top-down" : " bottom-up") <<
              " stride=" << scanlineStride <<
              " bufferSize=(" << bufferSize.getX() << "," << bufferSize.getY() << ")" );

    switch( m_aDevice->getScanlineFormat() ) {
    case basebmp::Format::EIGHT_BIT_PAL:
        mrContext = CGBitmapContextCreate(pixelBuffer.get(),
                                          bufferSize.getX(), bufferSize.getY(),
                                          8, scanlineStride,
                                          CGColorSpaceCreateDeviceGray(),
                                          kCGImageAlphaNone);
        break;
    case basebmp::Format::THIRTYTWO_BIT_TC_MASK_RGBA:
        mrContext = CGBitmapContextCreate(pixelBuffer.get(),
                                          bufferSize.getX(), bufferSize.getY(),
                                          8, scanlineStride,
                                          CGColorSpaceCreateDeviceRGB(),
                                          kCGImageAlphaNoneSkipLast);
        break;
    default:
        SAL_INFO( "vcl.ios", "CheckContext: unsupported color format " << basebmp::Format::formatName( m_aDevice->getScanlineFormat() ) );
    }

    SAL_WARN_IF( mrContext == NULL, "vcl.ios", "CheckContext() failed" );

    // Should we also clip the context? (Then we need to add a
    // getBounds() function to BitmapDevice.)

    if( mrContext != NULL && m_aDevice->isTopDown() )
    {
        CGContextTranslateCTM( mrContext, 0, bufferSize.getY() );
        CGContextScaleCTM( mrContext, 1, -1 );
    }

    SAL_INFO( "vcl.ios", "CheckContext: context=" << mrContext );

    return ( mrContext != NULL );
}

CGContextRef SvpSalGraphics::GetContext()
{
    if ( !mrContext )
        CheckContext();

    return mrContext;
}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>[coretext] Fix line spacing<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "coretext/common.h"

#ifdef MACOSX

#include "aqua/salframe.h"
#include "coretext/salgdi.h"

#else

#include <premac.h>
#include <UIKit/UIKit.h>
#include <postmac.h>

#include <basebmp/scanlineformats.hxx>

#include "saldatabasic.hxx"
#include "headless/svpframe.hxx"
#include "headless/svpgdi.hxx"

#endif

#include "coretext/salcoretextstyle.hxx"

#ifdef MACOSX

QuartzSalGraphics::QuartzSalGraphics()
    : mpFrame( NULL )
    , mxLayer( NULL )
    , mrContext( NULL )
    , mpXorEmulation( NULL )
    , mnXorMode( 0 )
    , mnWidth( 0 )
    , mnHeight( 0 )
    , mnBitmapDepth( 0 )
    , mnRealDPIX( 0 )
    , mnRealDPIY( 0 )
    , mfFakeDPIScale( 1.0 )
    , mxClipPath( NULL )
    , maLineColor( COL_WHITE )
    , maFillColor( COL_BLACK )
    , mbNonAntialiasedText( false )
    , mbPrinter( false )
    , mbVirDev( false )
    , mbWindow( false )
{
    SAL_INFO( "vcl.coretext.gr", "QuartzSalGraphics::QuartzSalGraphics() " << this );

    m_style = new CoreTextStyleInfo();
}

QuartzSalGraphics::~QuartzSalGraphics()
{
    SAL_INFO( "vcl.coretext.gr", "~QuartzSalGraphics(" << this << ")" );

    if(m_style)
    {
        delete m_style;
        m_style = NULL;
    }
}

#endif

inline bool QuartzSalGraphics::AddTempDevFont( ImplDevFontList*,
                                             const OUString& ,
                                             const OUString& )
{
    OSL_ASSERT( FALSE );
    return false;
}

void QuartzSalGraphics::DrawServerFontLayout( const ServerFontLayout& )
{
}

void QuartzSalGraphics::FreeEmbedFontData( const void* pData, long /*nDataLen*/ )
{
    // TODO: implementing this only makes sense when the implementation of
    //      QuartzSalGraphics::GetEmbedFontData() returns non-NULL
    (void)pData;
    DBG_ASSERT( (pData!=NULL), "QuartzSalGraphics::FreeEmbedFontData() is not implemented\n");
}

void QuartzSalGraphics::GetDevFontList( ImplDevFontList* pFontList )
{
    DBG_ASSERT( pFontList, "QuartzSalGraphics::GetDevFontList(NULL) !");

    SalData* pSalData = GetSalData();
    if (pSalData->mpFontList == NULL)
    {
        pSalData->mpFontList = new SystemFontList();
    }
    // Copy all PhysicalFontFace objects contained in the SystemFontList
    pSalData->mpFontList->AnnounceFonts( *pFontList );
}

void QuartzSalGraphics::ClearDevFontCache()
{
    SalData* pSalData = GetSalData();
    delete pSalData->mpFontList;
    pSalData->mpFontList = NULL;
}

void QuartzSalGraphics::GetDevFontSubstList( OutputDevice* )
{
    // nothing to do since there are no device-specific fonts on Aqua
}

const void* QuartzSalGraphics::GetEmbedFontData( const PhysicalFontFace*,
                              const sal_Ucs* /*pUnicodes*/,
                              sal_Int32* /*pWidths*/,
                              FontSubsetInfo&,
                              long* /*pDataLen*/ )
{
    return NULL;
}

const Ucs2SIntMap* QuartzSalGraphics::GetFontEncodingVector(const PhysicalFontFace*,
                                                          const Ucs2OStrMap** /*ppNonEncoded*/ )
{
    return NULL;
}

void QuartzSalGraphics::GetFontMetric( ImplFontMetricData* pMetric, int nFallbackLevel )
{
    (void)nFallbackLevel; // glyph-fallback on CoreText is done differently -> no fallback level

    pMetric->mbScalableFont = true;
    pMetric->mbKernableFont = true;
    CTFontRef font = m_style->GetFont();
    DBG_ASSERT(font, "GetFontMetric without font set in style");

    pMetric->mnAscent = static_cast<long>( CTFontGetAscent(font) * mfFakeDPIScale + 0.5);
    pMetric->mnDescent = static_cast<long>(CTFontGetDescent(font) * mfFakeDPIScale + 0.5);
    pMetric->mnExtLeading = static_cast<long>(CTFontGetLeading(font) * mfFakeDPIScale + 0.5);
    pMetric->mnIntLeading   = 0;
    pMetric->mnWidth = m_style->GetFontStretchedSize();

    SAL_INFO( "vcl.coretext.gr",
              "GetFontMetric(" << this << ") returning: {ascent=" << pMetric->mnAscent <<
              ",descent=" << pMetric->mnDescent <<
              ",extleading=" << pMetric->mnExtLeading <<
              ",intleading=" << pMetric->mnIntLeading <<
              ",width=" << pMetric->mnWidth <<
              "}" );
}

sal_Bool QuartzSalGraphics::GetGlyphBoundRect( sal_GlyphId /*nGlyphId*/, Rectangle& /*rRect*/ )
{
    /* TODO: create a Ghyph iterator to keep track ot 'state' between call */
    return false;
}

sal_Bool QuartzSalGraphics::GetGlyphOutline( sal_GlyphId /*nGlyphId*/, basegfx::B2DPolyPolygon& /*rPolyPoly*/ )
{
    /* TODO */
    return false;
}

void QuartzSalGraphics::GetGlyphWidths( const PhysicalFontFace* /*pFontData*/, bool /*bVertical*/,
                                      Int32Vector& /*rGlyphWidths*/, Ucs2UIntMap& /*rUnicodeEnc*/ )
{
}

sal_uLong QuartzSalGraphics::GetKernPairs( sal_uLong, ImplKernPairData* )
{
    return 0;
}

bool QuartzSalGraphics::GetImplFontCapabilities(vcl::FontCapabilities &rFontCapabilities) const
{
    if( !m_style )
    {
        return false;
    }
    CoreTextPhysicalFontFace* font_face = m_style->GetFontFace();
    if( !font_face)
    {
        return false;
    }
    return font_face->GetImplFontCapabilities(rFontCapabilities);
}

const ImplFontCharMap* QuartzSalGraphics::GetImplFontCharMap() const
{
    if( !m_style )
    {
        return NULL;
    }
    CoreTextPhysicalFontFace* font_face = m_style->GetFontFace();
    if( !font_face)
    {
        return ImplFontCharMap::GetDefaultMap();
    }
    return font_face->GetImplFontCharMap();
}

#ifndef IOS

bool QuartzSalGraphics::GetRawFontData( const PhysicalFontFace* pFontFace,
                     std::vector<unsigned char>& rBuffer, bool* pJustCFF )
{
    const CoreTextPhysicalFontFace* font_face = static_cast<const CoreTextPhysicalFontFace*>(pFontFace);

    return font_face->GetRawFontData(rBuffer, pJustCFF);
}

#endif

SystemFontData QuartzSalGraphics::GetSysFontData( int /* nFallbacklevel */ ) const
{
    SystemFontData aSysFontData;
    aSysFontData.nSize = sizeof( SystemFontData );
    aSysFontData.bAntialias = true;

    CTFontRef font = CTFontCreateUIFontForLanguage(kCTFontSystemFontType, 0.0, NULL);
    font = (CTFontRef)CFRetain(font);
    aSysFontData.rCTFont = font;

    CTFontRef italic_font = CTFontCreateCopyWithSymbolicTraits( font,
                                                                0.0,
                                                                NULL,
                                                                kCTFontItalicTrait,
                                                                kCTFontItalicTrait + kCTFontBoldTrait);
    aSysFontData.bFakeItalic = italic_font ? false : true;
    SafeCFRelease(italic_font);

    CTFontRef bold_font = CTFontCreateCopyWithSymbolicTraits( font,
                                                              0.0,
                                                              NULL,
                                                              kCTFontBoldTrait,
                                                              kCTFontItalicTrait + kCTFontBoldTrait);
    aSysFontData.bFakeBold = bold_font ? false : true;
    SafeCFRelease(bold_font);

    CTFontRef vertical_font = CTFontCreateCopyWithSymbolicTraits( font,
                                                                  0.0,
                                                                  NULL,
                                                                  kCTFontVerticalTrait,
                                                                  kCTFontVerticalTrait);
    aSysFontData.bVerticalCharacterType = vertical_font ? true : false;
    SafeCFRelease(vertical_font);

    return aSysFontData;
}

sal_uInt16 QuartzSalGraphics::SetFont( FontSelectPattern* pReqFont, int /*nFallbackLevel*/ )
{
    m_style->SetFont(pReqFont);

    return 0;
}

void QuartzSalGraphics::SetTextColor( SalColor nSalColor )
{
    m_style->SetColor(nSalColor);
}

#ifdef IOS

// Note that "QuartzSalGraphics" *is* SvpSalGraphics for iOS

bool SvpSalGraphics::CheckContext()
{
    const basegfx::B2IVector size = m_aDevice->getSize();
    const basegfx::B2IVector bufferSize = m_aDevice->getBufferSize();
    const sal_Int32 scanlineStride = m_aDevice->getScanlineStride();
    basebmp::RawMemorySharedArray pixelBuffer = m_aDevice->getBuffer();

    SAL_INFO( "vcl.ios",
              "CheckContext: device=" << m_aDevice.get() <<
              " size=" << size.getX() << "x" << size.getY() <<
              (m_aDevice->isTopDown() ? " top-down" : " bottom-up") <<
              " stride=" << scanlineStride <<
              " bufferSize=(" << bufferSize.getX() << "," << bufferSize.getY() << ")" );

    switch( m_aDevice->getScanlineFormat() ) {
    case basebmp::Format::EIGHT_BIT_PAL:
        mrContext = CGBitmapContextCreate(pixelBuffer.get(),
                                          bufferSize.getX(), bufferSize.getY(),
                                          8, scanlineStride,
                                          CGColorSpaceCreateDeviceGray(),
                                          kCGImageAlphaNone);
        break;
    case basebmp::Format::THIRTYTWO_BIT_TC_MASK_RGBA:
        mrContext = CGBitmapContextCreate(pixelBuffer.get(),
                                          bufferSize.getX(), bufferSize.getY(),
                                          8, scanlineStride,
                                          CGColorSpaceCreateDeviceRGB(),
                                          kCGImageAlphaNoneSkipLast);
        break;
    default:
        SAL_INFO( "vcl.ios", "CheckContext: unsupported color format " << basebmp::Format::formatName( m_aDevice->getScanlineFormat() ) );
    }

    SAL_WARN_IF( mrContext == NULL, "vcl.ios", "CheckContext() failed" );

    // Should we also clip the context? (Then we need to add a
    // getBounds() function to BitmapDevice.)

    if( mrContext != NULL && m_aDevice->isTopDown() )
    {
        CGContextTranslateCTM( mrContext, 0, bufferSize.getY() );
        CGContextScaleCTM( mrContext, 1, -1 );
    }

    SAL_INFO( "vcl.ios", "CheckContext: context=" << mrContext );

    return ( mrContext != NULL );
}

CGContextRef SvpSalGraphics::GetContext()
{
    if ( !mrContext )
        CheckContext();

    return mrContext;
}

#endif

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


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sallang.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-25 10:07:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SALLANG_HXX
#define _SALLANG_HXX

//#ifndef _TOOLS_LANG_HXX
//#include <tools/lang.hxx>
//#endif
#ifndef INCLUDED_I18NPOOL_MSLANGID_HXX
#include <i18npool/mslangid.hxx>
#endif

// --------------------
// - Language Strings -
// --------------------

// --- Key-Namen ---
#define LSTR_KEY_SHIFT                       0
#define LSTR_KEY_CTRL                        1
#define LSTR_KEY_ALT                         2
#define LSTR_KEY_UP                          3
#define LSTR_KEY_DOWN                        4
#define LSTR_KEY_LEFT                        5
#define LSTR_KEY_RIGHT                       6
#define LSTR_KEY_HOME                        7
#define LSTR_KEY_END                         8
#define LSTR_KEY_PAGEUP                      9
#define LSTR_KEY_PAGEDOWN                   10
#define LSTR_KEY_RETURN                     11
#define LSTR_KEY_ESC                        12
#define LSTR_KEY_TAB                        13
#define LSTR_KEY_BACKSPACE                  14
#define LSTR_KEY_SPACE                      15
#define LSTR_KEY_INSERT                     16
#define LSTR_KEY_DELETE                     17

// --- Anzahl der Texte ---

#define LSTR_COUNT                          18

// --------------------------------------------
// - Methoden zum Abfragen der Sprach-Strings -
// --------------------------------------------

const sal_Unicode** ImplGetLangTab( LanguageType eLang );

#endif // _SALLANG_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.178); FILE MERGED 2008/04/01 16:05:24 thb 1.4.178.2: #i85898# Stripping all external header guards 2008/03/28 15:44:27 rt 1.4.178.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: sallang.hxx,v $
 * $Revision: 1.5 $
 *
 * 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 _SALLANG_HXX
#define _SALLANG_HXX

//#ifndef _TOOLS_LANG_HXX
//#include <tools/lang.hxx>
//#endif
#include <i18npool/mslangid.hxx>

// --------------------
// - Language Strings -
// --------------------

// --- Key-Namen ---
#define LSTR_KEY_SHIFT                       0
#define LSTR_KEY_CTRL                        1
#define LSTR_KEY_ALT                         2
#define LSTR_KEY_UP                          3
#define LSTR_KEY_DOWN                        4
#define LSTR_KEY_LEFT                        5
#define LSTR_KEY_RIGHT                       6
#define LSTR_KEY_HOME                        7
#define LSTR_KEY_END                         8
#define LSTR_KEY_PAGEUP                      9
#define LSTR_KEY_PAGEDOWN                   10
#define LSTR_KEY_RETURN                     11
#define LSTR_KEY_ESC                        12
#define LSTR_KEY_TAB                        13
#define LSTR_KEY_BACKSPACE                  14
#define LSTR_KEY_SPACE                      15
#define LSTR_KEY_INSERT                     16
#define LSTR_KEY_DELETE                     17

// --- Anzahl der Texte ---

#define LSTR_COUNT                          18

// --------------------------------------------
// - Methoden zum Abfragen der Sprach-Strings -
// --------------------------------------------

const sal_Unicode** ImplGetLangTab( LanguageType eLang );

#endif // _SALLANG_HXX
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioo_dl_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_fbc_ioo_dl_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

fapi2::ReturnCode p9_fbc_ioo_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& TGT0)
{
    {
        fapi2::ATTR_OPTICS_CONFIG_MODE_Type l_TGT0_ATTR_OPTICS_CONFIG_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_OPTICS_CONFIG_MODE, TGT0, l_TGT0_ATTR_OPTICS_CONFIG_MODE));
        uint64_t l_def_OBUS_FBC_ENABLED = (l_TGT0_ATTR_OPTICS_CONFIG_MODE == ENUM_ATTR_OPTICS_CONFIG_MODE_SMP);
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x901080aull, l_scom_buffer ));

            if (l_def_OBUS_FBC_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON = 0x1;
                l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x901080aull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>p9.fbc.ioo_dl.scom.initfile -- set CONFIG_NVx_NPU_ENABLED<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioo_dl_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_fbc_ioo_dl_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

fapi2::ReturnCode p9_fbc_ioo_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& TGT0)
{
    {
        fapi2::ATTR_OPTICS_CONFIG_MODE_Type l_TGT0_ATTR_OPTICS_CONFIG_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_OPTICS_CONFIG_MODE, TGT0, l_TGT0_ATTR_OPTICS_CONFIG_MODE));
        uint64_t l_def_OBUS_FBC_ENABLED = (l_TGT0_ATTR_OPTICS_CONFIG_MODE == ENUM_ATTR_OPTICS_CONFIG_MODE_SMP);
        uint64_t l_def_OBUS_NV_ENABLED = (l_TGT0_ATTR_OPTICS_CONFIG_MODE == ENUM_ATTR_OPTICS_CONFIG_MODE_NV);
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x901080aull, l_scom_buffer ));

            if (l_def_OBUS_FBC_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON = 0x1;
                l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x901080aull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x901080full, l_scom_buffer ));

            if (l_def_OBUS_NV_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<61, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<62, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<63, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x901080full, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before><commit_msg>vcl quartz: restore old outline front drawing<commit_after><|endoftext|>