<commit_before>/*
 * Copyright 2007-2022 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * 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.
 *
 * 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
 * FOUNDATION 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 "Base.hxx"
#include "util/StringCompare.hxx"

#include <cassert>

const char *
base_tail(const char *uri, std::string_view base) noexcept
{
	assert(uri != nullptr);

	if (!is_base(base))
		/* not a valid base */
		return nullptr;

	return StringAfterPrefix(uri, base);
}

const char *
require_base_tail(const char *uri, std::string_view base) noexcept
{
	assert(uri != nullptr);
	assert(is_base(base));
	assert(StringStartsWith(uri, base));

	return uri + base.size();
}

std::size_t
base_string(std::string_view uri, std::string_view tail) noexcept
{
	if (uri.size() == tail.size())
		/* special case: zero-length prefix (not followed by a
		   slash) */
		return uri == tail ? 0 : (std::size_t)-1;

	return uri.size() > tail.size() &&
		uri[uri.size() - tail.size() - 1] == '/' &&
		memcmp(uri.data() + uri.size() - tail.size(),
		       tail.data(), tail.size()) == 0
		? uri.size() - tail.size()
		: (std::size_t)-1;
}

bool
is_base(std::string_view uri) noexcept
{
	return uri.ends_with('/');
}
<commit_msg>uri/Base: use string_view::ends_with()<commit_after>/*
 * Copyright 2007-2022 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * 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.
 *
 * 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
 * FOUNDATION 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 "Base.hxx"
#include "util/StringCompare.hxx"

#include <cassert>

const char *
base_tail(const char *uri, std::string_view base) noexcept
{
	assert(uri != nullptr);

	if (!is_base(base))
		/* not a valid base */
		return nullptr;

	return StringAfterPrefix(uri, base);
}

const char *
require_base_tail(const char *uri, std::string_view base) noexcept
{
	assert(uri != nullptr);
	assert(is_base(base));
	assert(StringStartsWith(uri, base));

	return uri + base.size();
}

std::size_t
base_string(std::string_view uri, std::string_view tail) noexcept
{
	if (uri.size() == tail.size())
		/* special case: zero-length prefix (not followed by a
		   slash) */
		return uri == tail ? 0 : (std::size_t)-1;

	return uri.size() > tail.size() &&
		uri[uri.size() - tail.size() - 1] == '/' &&
		uri.ends_with(tail)
		? uri.size() - tail.size()
		: (std::size_t)-1;
}

bool
is_base(std::string_view uri) noexcept
{
	return uri.ends_with('/');
}
<|endoftext|>


<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#define CAF_SUITE detail.parser.read_number

#include "caf/detail/parser/read_number.hpp"

#include "caf/test/unit_test.hpp"

#include <string>

#include "caf/detail/parser/add_ascii.hpp"
#include "caf/detail/parser/sub_ascii.hpp"
#include "caf/expected.hpp"
#include "caf/parser_state.hpp"
#include "caf/pec.hpp"
#include "caf/string_view.hpp"
#include "caf/variant.hpp"

using namespace caf;

namespace {

struct number_consumer {
  variant<int64_t, double> x;
  void value(double y) {
    x = y;
  }
  void value(int64_t y) {
    x = y;
  }
};

struct range_consumer {
  std::vector<int64_t> xs;
  void value(double) {
    CAF_FAIL("range consumer called with a double");
  }
  void value(int64_t y) {
    xs.emplace_back(y);
  }
};

struct res_t {
  variant<pec, double, int64_t> val;
  template <class T>
  res_t(T&& x) : val(std::forward<T>(x)) {
    // nop
  }
};

std::string to_string(const res_t& x) {
  return caf::visit([](auto& y) { return deep_to_string(y); }, x.val);
}

bool operator==(const res_t& x, const res_t& y) {
  if (x.val.index() != y.val.index())
    return false;
  // Implements a safe equal comparison for double.
  caf::test::equal_to f;
  using caf::get;
  using caf::holds_alternative;
  if (holds_alternative<pec>(x.val))
    return f(get<pec>(x.val), get<pec>(y.val));
  if (holds_alternative<double>(x.val))
    return f(get<double>(x.val), get<double>(y.val));
  return f(get<int64_t>(x.val), get<int64_t>(y.val));
}

struct numbers_parser {
  res_t operator()(string_view str) {
    number_consumer f;
    string_parser_state res{str.begin(), str.end()};
    detail::parser::read_number(res, f);
    if (res.code == pec::success)
      return f.x;
    return res.code;
  }
};

struct range_parser {
  expected<std::vector<int64_t>> operator()(string_view str) {
    range_consumer f;
    string_parser_state res{str.begin(), str.end()};
    detail::parser::read_number(res, f, std::true_type{}, std::true_type{});
    if (res.code == pec::success)
      return std::move(f.xs);
    return make_error(res);
  }
};

template <class T>
typename std::enable_if<std::is_integral<T>::value, res_t>::type res(T x) {
  return {static_cast<int64_t>(x)};
}

template <class T>
typename std::enable_if<std::is_floating_point<T>::value, res_t>::type
res(T x) {
  return {static_cast<double>(x)};
}

struct fixture {
  numbers_parser p;
  range_parser r;
};

} // namespace

#define CHECK_NUMBER(x) CAF_CHECK_EQUAL(p(#x), res(x))

CAF_TEST_FIXTURE_SCOPE(read_number_tests, fixture)

CAF_TEST(add ascii - unsigned) {
  using detail::parser::add_ascii;
  auto rd = [](string_view str) -> expected<uint8_t> {
    uint8_t x = 0;
    for (auto c : str)
      if (!add_ascii<10>(x, c))
        return pec::integer_overflow;
    return x;
  };
  for (int i = 0; i < 256; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), static_cast<uint8_t>(i));
  for (int i = 256; i < 513; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), pec::integer_overflow);
}

CAF_TEST(add ascii - signed) {
  auto rd = [](string_view str) -> expected<int8_t> {
    int8_t x = 0;
    for (auto c : str)
      if (!detail::parser::add_ascii<10>(x, c))
        return pec::integer_overflow;
    return x;
  };
  for (int i = 0; i < 128; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), static_cast<int8_t>(i));
  for (int i = 128; i < 513; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), pec::integer_overflow);
}

CAF_TEST(sub ascii) {
  auto rd = [](string_view str) -> expected<int8_t> {
    int8_t x = 0;
    for (auto c : str)
      if (!detail::parser::sub_ascii<10>(x, c))
        return pec::integer_underflow;
    return x;
  };
  // Using sub_ascii in this way behaves as if we'd prefix the number with a
  // minus sign, i.e., "123" will result in -123.
  for (int i = 1; i < 129; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), static_cast<int8_t>(-i));
  for (int i = 129; i < 513; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), pec::integer_underflow);
}

CAF_TEST(binary numbers) {
  /* TODO: use this implementation when switching to C++14
  CHECK_NUMBER(0b0);
  CHECK_NUMBER(0b10);
  CHECK_NUMBER(0b101);
  CHECK_NUMBER(0B1001);
  CHECK_NUMBER(-0b0);
  CHECK_NUMBER(-0b101);
  CHECK_NUMBER(-0B1001);
  */
  CAF_CHECK_EQUAL(p("0b0"), res(0));
  CAF_CHECK_EQUAL(p("0b10"), res(2));
  CAF_CHECK_EQUAL(p("0b101"), res(5));
  CAF_CHECK_EQUAL(p("0B1001"), res(9));
  CAF_CHECK_EQUAL(p("-0b0"), res(0));
  CAF_CHECK_EQUAL(p("-0b101"), res(-5));
  CAF_CHECK_EQUAL(p("-0B1001"), res(-9));
}

CAF_TEST(octal numbers) {
  // valid numbers
  CHECK_NUMBER(00);
  CHECK_NUMBER(010);
  CHECK_NUMBER(0123);
  CHECK_NUMBER(0777);
  CHECK_NUMBER(-00);
  CHECK_NUMBER(-0123);
  // invalid numbers
  CAF_CHECK_EQUAL(p("018"), pec::trailing_character);
}

CAF_TEST(decimal numbers) {
  CHECK_NUMBER(0);
  CHECK_NUMBER(10);
  CHECK_NUMBER(123);
  CHECK_NUMBER(-0);
  CHECK_NUMBER(-123);
}

CAF_TEST(hexadecimal numbers) {
  // valid numbers
  CHECK_NUMBER(0x0);
  CHECK_NUMBER(0x10);
  CHECK_NUMBER(0X123);
  CHECK_NUMBER(0xAF01);
  CHECK_NUMBER(-0x0);
  CHECK_NUMBER(-0x123);
  CHECK_NUMBER(-0xaf01);
  // invalid numbers
  CAF_CHECK_EQUAL(p("0xFG"), pec::trailing_character);
  CAF_CHECK_EQUAL(p("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
                  pec::integer_overflow);
  CAF_CHECK_EQUAL(p("-0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
                  pec::integer_underflow);
}

CAF_TEST(floating point numbers) {
  CHECK_NUMBER(0.0);
  CHECK_NUMBER(.0);
  CHECK_NUMBER(0.);
  CHECK_NUMBER(1.1);
  CHECK_NUMBER(.1);
  CHECK_NUMBER(1.);
  CHECK_NUMBER(0.123);
  CHECK_NUMBER(.123);
  CHECK_NUMBER(123.456);
  CHECK_NUMBER(-0.0);
  CHECK_NUMBER(-.0);
  CHECK_NUMBER(-0.);
  CHECK_NUMBER(-1.1);
  CHECK_NUMBER(-.1);
  CHECK_NUMBER(-1.);
  CHECK_NUMBER(-0.123);
  CHECK_NUMBER(-.123);
  CHECK_NUMBER(-123.456);
}

CAF_TEST(integer mantissa with positive exponent) {
  CHECK_NUMBER(321E1);
  CHECK_NUMBER(321e1);
  CHECK_NUMBER(321e+1);
  CHECK_NUMBER(123e2);
  CHECK_NUMBER(-4e2);
  CHECK_NUMBER(1e1);
  CHECK_NUMBER(1e2);
  CHECK_NUMBER(1e3);
  CHECK_NUMBER(1e4);
  CHECK_NUMBER(1e5);
  CHECK_NUMBER(1e6);
}

CAF_TEST(integer mantissa with negative exponent) {
  // valid numbers
  CHECK_NUMBER(321E-1);
  CHECK_NUMBER(321e-1);
  CHECK_NUMBER(123e-2);
  CHECK_NUMBER(-4e-2);
  CHECK_NUMBER(1e-1);
  CHECK_NUMBER(1e-2);
  CHECK_NUMBER(1e-3);
  CHECK_NUMBER(1e-4);
  CHECK_NUMBER(1e-5);
  CHECK_NUMBER(1e-6);
  // invalid numbers
  CAF_CHECK_EQUAL(p("-9.9999e-e511"), pec::unexpected_character);
  CAF_CHECK_EQUAL(p("-9.9999e-511"), pec::exponent_underflow);
}

CAF_TEST(fractional mantissa with positive exponent) {
  CHECK_NUMBER(3.21E1);
  CHECK_NUMBER(3.21e+1);
  CHECK_NUMBER(3.21e+1);
  CHECK_NUMBER(12.3e2);
  CHECK_NUMBER(-0.001e3);
  CHECK_NUMBER(0.0001e5);
  CHECK_NUMBER(-42.001e3);
  CHECK_NUMBER(42.0001e5);
}

CAF_TEST(fractional mantissa with negative exponent) {
  CHECK_NUMBER(3.21E-1);
  CHECK_NUMBER(3.21e-1);
  CHECK_NUMBER(12.3e-2);
  CHECK_NUMBER(-0.001e-3);
  CHECK_NUMBER(-0.0001e-5);
  CHECK_NUMBER(-42.001e-3);
  CHECK_NUMBER(-42001e-6);
  CHECK_NUMBER(-42.0001e-5);
}

#define CHECK_RANGE(expr, ...)                                                 \
  CAF_CHECK_EQUAL(r(expr), std::vector<int64_t>({__VA_ARGS__}))

CAF_TEST(a range from n to n is just n) {
  CHECK_RANGE("0..0", 0);
  CHECK_RANGE("1..1", 1);
  CHECK_RANGE("2..2", 2);
  CHECK_RANGE("101..101", 101);
  CHECK_RANGE("101..101..1", 101);
  CHECK_RANGE("101..101..2", 101);
  CHECK_RANGE("101..101..-1", 101);
  CHECK_RANGE("101..101..-2", 101);
}

CAF_TEST(ranges are either ascending or descending) {
  CHECK_RANGE("0..1", 0, 1);
  CHECK_RANGE("0..2", 0, 1, 2);
  CHECK_RANGE("0..3", 0, 1, 2, 3);
  CHECK_RANGE("3..0", 3, 2, 1, 0);
  CHECK_RANGE("3..1", 3, 2, 1);
  CHECK_RANGE("3..2", 3, 2);
}

CAF_TEST(ranges can use positive step values) {
  CHECK_RANGE("2..6..2", 2, 4, 6);
  CHECK_RANGE("3..8..3", 3, 6);
}

CAF_TEST(ranges can use negative step values) {
  CHECK_RANGE("6..2..-2", 6, 4, 2);
  CHECK_RANGE("8..3..-3", 8, 5);
}

CAF_TEST(ranges can use signed integers) {
  CHECK_RANGE("+2..+6..+2", 2, 4, 6);
  CHECK_RANGE("+6..+2..-2", 6, 4, 2);
  CHECK_RANGE("+2..-2..-2", 2, 0, -2);
  CHECK_RANGE("-2..+2..+2", -2, 0, 2);
}

CAF_TEST(the parser rejects invalid step values) {
  CAF_CHECK_EQUAL(r("-2..+2..-2"), pec::invalid_range_expression);
  CAF_CHECK_EQUAL(r("+2..-2..+2"), pec::invalid_range_expression);
}

CAF_TEST_FIXTURE_SCOPE_END()
<commit_msg>Fix error checks on GCC<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#define CAF_SUITE detail.parser.read_number

#include "caf/detail/parser/read_number.hpp"

#include "caf/test/unit_test.hpp"

#include <string>

#include "caf/detail/parser/add_ascii.hpp"
#include "caf/detail/parser/sub_ascii.hpp"
#include "caf/expected.hpp"
#include "caf/parser_state.hpp"
#include "caf/pec.hpp"
#include "caf/string_view.hpp"
#include "caf/variant.hpp"

using namespace caf;

namespace {

struct number_consumer {
  variant<int64_t, double> x;
  void value(double y) {
    x = y;
  }
  void value(int64_t y) {
    x = y;
  }
};

struct range_consumer {
  std::vector<int64_t> xs;
  void value(double) {
    CAF_FAIL("range consumer called with a double");
  }
  void value(int64_t y) {
    xs.emplace_back(y);
  }
};

struct res_t {
  variant<pec, double, int64_t> val;
  template <class T>
  res_t(T&& x) : val(std::forward<T>(x)) {
    // nop
  }
};

std::string to_string(const res_t& x) {
  return caf::visit([](auto& y) { return deep_to_string(y); }, x.val);
}

bool operator==(const res_t& x, const res_t& y) {
  if (x.val.index() != y.val.index())
    return false;
  // Implements a safe equal comparison for double.
  caf::test::equal_to f;
  using caf::get;
  using caf::holds_alternative;
  if (holds_alternative<pec>(x.val))
    return f(get<pec>(x.val), get<pec>(y.val));
  if (holds_alternative<double>(x.val))
    return f(get<double>(x.val), get<double>(y.val));
  return f(get<int64_t>(x.val), get<int64_t>(y.val));
}

struct numbers_parser {
  res_t operator()(string_view str) {
    number_consumer f;
    string_parser_state res{str.begin(), str.end()};
    detail::parser::read_number(res, f);
    if (res.code == pec::success)
      return f.x;
    return res.code;
  }
};

struct range_parser {
  expected<std::vector<int64_t>> operator()(string_view str) {
    range_consumer f;
    string_parser_state res{str.begin(), str.end()};
    detail::parser::read_number(res, f, std::true_type{}, std::true_type{});
    if (res.code == pec::success)
      return std::move(f.xs);
    return make_error(res);
  }
};

template <class T>
typename std::enable_if<std::is_integral<T>::value, res_t>::type res(T x) {
  return {static_cast<int64_t>(x)};
}

template <class T>
typename std::enable_if<std::is_floating_point<T>::value, res_t>::type
res(T x) {
  return {static_cast<double>(x)};
}

struct fixture {
  numbers_parser p;
  range_parser r;
};

} // namespace

#define CHECK_NUMBER(x) CAF_CHECK_EQUAL(p(#x), res(x))

CAF_TEST_FIXTURE_SCOPE(read_number_tests, fixture)

CAF_TEST(add ascii - unsigned) {
  using detail::parser::add_ascii;
  auto rd = [](string_view str) -> expected<uint8_t> {
    uint8_t x = 0;
    for (auto c : str)
      if (!add_ascii<10>(x, c))
        return pec::integer_overflow;
    return x;
  };
  for (int i = 0; i < 256; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), static_cast<uint8_t>(i));
  for (int i = 256; i < 513; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), pec::integer_overflow);
}

CAF_TEST(add ascii - signed) {
  auto rd = [](string_view str) -> expected<int8_t> {
    int8_t x = 0;
    for (auto c : str)
      if (!detail::parser::add_ascii<10>(x, c))
        return pec::integer_overflow;
    return x;
  };
  for (int i = 0; i < 128; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), static_cast<int8_t>(i));
  for (int i = 128; i < 513; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), pec::integer_overflow);
}

CAF_TEST(sub ascii) {
  auto rd = [](string_view str) -> expected<int8_t> {
    int8_t x = 0;
    for (auto c : str)
      if (!detail::parser::sub_ascii<10>(x, c))
        return pec::integer_underflow;
    return x;
  };
  // Using sub_ascii in this way behaves as if we'd prefix the number with a
  // minus sign, i.e., "123" will result in -123.
  for (int i = 1; i < 129; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), static_cast<int8_t>(-i));
  for (int i = 129; i < 513; ++i)
    CAF_CHECK_EQUAL(rd(std::to_string(i)), pec::integer_underflow);
}

CAF_TEST(binary numbers) {
  /* TODO: use this implementation when switching to C++14
  CHECK_NUMBER(0b0);
  CHECK_NUMBER(0b10);
  CHECK_NUMBER(0b101);
  CHECK_NUMBER(0B1001);
  CHECK_NUMBER(-0b0);
  CHECK_NUMBER(-0b101);
  CHECK_NUMBER(-0B1001);
  */
  CAF_CHECK_EQUAL(p("0b0"), res(0));
  CAF_CHECK_EQUAL(p("0b10"), res(2));
  CAF_CHECK_EQUAL(p("0b101"), res(5));
  CAF_CHECK_EQUAL(p("0B1001"), res(9));
  CAF_CHECK_EQUAL(p("-0b0"), res(0));
  CAF_CHECK_EQUAL(p("-0b101"), res(-5));
  CAF_CHECK_EQUAL(p("-0B1001"), res(-9));
}

CAF_TEST(octal numbers) {
  // valid numbers
  CHECK_NUMBER(00);
  CHECK_NUMBER(010);
  CHECK_NUMBER(0123);
  CHECK_NUMBER(0777);
  CHECK_NUMBER(-00);
  CHECK_NUMBER(-0123);
  // invalid numbers
  CAF_CHECK_EQUAL(p("018"), pec::trailing_character);
}

CAF_TEST(decimal numbers) {
  CHECK_NUMBER(0);
  CHECK_NUMBER(10);
  CHECK_NUMBER(123);
  CHECK_NUMBER(-0);
  CHECK_NUMBER(-123);
}

CAF_TEST(hexadecimal numbers) {
  // valid numbers
  CHECK_NUMBER(0x0);
  CHECK_NUMBER(0x10);
  CHECK_NUMBER(0X123);
  CHECK_NUMBER(0xAF01);
  CHECK_NUMBER(-0x0);
  CHECK_NUMBER(-0x123);
  CHECK_NUMBER(-0xaf01);
  // invalid numbers
  CAF_CHECK_EQUAL(p("0xFG"), pec::trailing_character);
  CAF_CHECK_EQUAL(p("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
                  pec::integer_overflow);
  CAF_CHECK_EQUAL(p("-0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
                  pec::integer_underflow);
}

CAF_TEST(floating point numbers) {
  CHECK_NUMBER(0.0);
  CHECK_NUMBER(.0);
  CHECK_NUMBER(0.);
  CHECK_NUMBER(1.1);
  CHECK_NUMBER(.1);
  CHECK_NUMBER(1.);
  CHECK_NUMBER(0.123);
  CHECK_NUMBER(.123);
  CHECK_NUMBER(123.456);
  CHECK_NUMBER(-0.0);
  CHECK_NUMBER(-.0);
  CHECK_NUMBER(-0.);
  CHECK_NUMBER(-1.1);
  CHECK_NUMBER(-.1);
  CHECK_NUMBER(-1.);
  CHECK_NUMBER(-0.123);
  CHECK_NUMBER(-.123);
  CHECK_NUMBER(-123.456);
}

CAF_TEST(integer mantissa with positive exponent) {
  CHECK_NUMBER(321E1);
  CHECK_NUMBER(321e1);
  CHECK_NUMBER(321e+1);
  CHECK_NUMBER(123e2);
  CHECK_NUMBER(-4e2);
  CHECK_NUMBER(1e1);
  CHECK_NUMBER(1e2);
  CHECK_NUMBER(1e3);
  CHECK_NUMBER(1e4);
  CHECK_NUMBER(1e5);
  CHECK_NUMBER(1e6);
}

CAF_TEST(integer mantissa with negative exponent) {
  // valid numbers
  CHECK_NUMBER(321E-1);
  CHECK_NUMBER(321e-1);
  CHECK_NUMBER(123e-2);
  CHECK_NUMBER(-4e-2);
  CHECK_NUMBER(1e-1);
  CHECK_NUMBER(1e-2);
  CHECK_NUMBER(1e-3);
  CHECK_NUMBER(1e-4);
  CHECK_NUMBER(1e-5);
  CHECK_NUMBER(1e-6);
  // invalid numbers
  CAF_CHECK_EQUAL(p("-9.9999e-e511"), pec::unexpected_character);
  CAF_CHECK_EQUAL(p("-9.9999e-511"), pec::exponent_underflow);
}

CAF_TEST(fractional mantissa with positive exponent) {
  CHECK_NUMBER(3.21E1);
  CHECK_NUMBER(3.21e+1);
  CHECK_NUMBER(3.21e+1);
  CHECK_NUMBER(12.3e2);
  CHECK_NUMBER(-0.001e3);
  CHECK_NUMBER(0.0001e5);
  CHECK_NUMBER(-42.001e3);
  CHECK_NUMBER(42.0001e5);
}

CAF_TEST(fractional mantissa with negative exponent) {
  CHECK_NUMBER(3.21E-1);
  CHECK_NUMBER(3.21e-1);
  CHECK_NUMBER(12.3e-2);
  CHECK_NUMBER(-0.001e-3);
  CHECK_NUMBER(-0.0001e-5);
  CHECK_NUMBER(-42.001e-3);
  CHECK_NUMBER(-42001e-6);
  CHECK_NUMBER(-42.0001e-5);
}

#define CHECK_RANGE(expr, ...)                                                 \
  CAF_CHECK_EQUAL(r(expr), std::vector<int64_t>({__VA_ARGS__}))

CAF_TEST(a range from n to n is just n) {
  CHECK_RANGE("0..0", 0);
  CHECK_RANGE("1..1", 1);
  CHECK_RANGE("2..2", 2);
  CHECK_RANGE("101..101", 101);
  CHECK_RANGE("101..101..1", 101);
  CHECK_RANGE("101..101..2", 101);
  CHECK_RANGE("101..101..-1", 101);
  CHECK_RANGE("101..101..-2", 101);
}

CAF_TEST(ranges are either ascending or descending) {
  CHECK_RANGE("0..1", 0, 1);
  CHECK_RANGE("0..2", 0, 1, 2);
  CHECK_RANGE("0..3", 0, 1, 2, 3);
  CHECK_RANGE("3..0", 3, 2, 1, 0);
  CHECK_RANGE("3..1", 3, 2, 1);
  CHECK_RANGE("3..2", 3, 2);
}

CAF_TEST(ranges can use positive step values) {
  CHECK_RANGE("2..6..2", 2, 4, 6);
  CHECK_RANGE("3..8..3", 3, 6);
}

CAF_TEST(ranges can use negative step values) {
  CHECK_RANGE("6..2..-2", 6, 4, 2);
  CHECK_RANGE("8..3..-3", 8, 5);
}

CAF_TEST(ranges can use signed integers) {
  CHECK_RANGE("+2..+6..+2", 2, 4, 6);
  CHECK_RANGE("+6..+2..-2", 6, 4, 2);
  CHECK_RANGE("+2..-2..-2", 2, 0, -2);
  CHECK_RANGE("-2..+2..+2", -2, 0, 2);
}

#define CHECK_ERR(expr, enum_value)                                            \
  if (auto res = r(expr)) {                                                    \
    CAF_FAIL("expected expression to produce to an error");                    \
  } else {                                                                     \
    auto& err = res.error();                                                   \
    CAF_CHECK_EQUAL(err.category(), atom("parser"));                           \
    CAF_CHECK_EQUAL(err.code(), static_cast<uint8_t>(enum_value));             \
  }

CAF_TEST(the parser rejects invalid step values) {
  CHECK_ERR("-2..+2..-2", pec::invalid_range_expression);
  CHECK_ERR("+2..-2..+2", pec::invalid_range_expression);
}

CAF_TEST_FIXTURE_SCOPE_END()
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: attarray.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 10:01:30 $
 *
 *  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_ATRARR_HXX
#define SC_ATRARR_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_SCATTR_HXX
#include "attrib.hxx"
#endif

class ScDocument;
class ScMarkArray;
class ScPatternAttr;
class ScStyleSheet;

class Rectangle;
class SfxItemPoolCache;
class SfxStyleSheetBase;
class SvxBorderLine;
class SvxBoxItem;
class SvxBoxInfoItem;

#define SC_LINE_EMPTY           0
#define SC_LINE_SET             1
#define SC_LINE_DONTCARE        2

#define SC_ATTRARRAY_DELTA      4

struct ScLineFlags
{
    BYTE    nLeft;
    BYTE    nRight;
    BYTE    nTop;
    BYTE    nBottom;
    BYTE    nHori;
    BYTE    nVert;

    ScLineFlags() : nLeft(SC_LINE_EMPTY),nRight(SC_LINE_EMPTY),nTop(SC_LINE_EMPTY),
                    nBottom(SC_LINE_EMPTY),nHori(SC_LINE_EMPTY),nVert(SC_LINE_EMPTY) {}
};

struct ScAttrEntry
{
    SCROW                   nRow;
    const ScPatternAttr*    pPattern;
};

class ScAttrArray
{
private:
    SCCOL           nCol;
    SCTAB           nTab;
    ScDocument*     pDocument;

    SCSIZE          nCount;
    SCSIZE          nLimit;
    ScAttrEntry*    pData;

friend class ScDocument;                // fuer FillInfo
friend class ScDocumentIterator;
friend class ScAttrIterator;
friend class ScHorizontalAttrIterator;
friend void lcl_IterGetNumberFormat( ULONG& nFormat,
        const ScAttrArray*& rpArr, SCROW& nAttrEndRow,
        const ScAttrArray* pNewArr, SCROW nRow, ScDocument* pDoc );

    BOOL    ApplyFrame( const SvxBoxItem* pLineOuter, const SvxBoxInfoItem* pLineInner,
                            SCROW nStartRow, SCROW nEndRow,
                            BOOL bLeft, SCCOL nDistRight, BOOL bTop, SCROW nDistBottom );

public:
            ScAttrArray( SCCOL nNewCol, SCTAB nNewTab, ScDocument* pDoc );
            ~ScAttrArray();

    void    SetTab(SCTAB nNewTab)   { nTab = nNewTab; }
    void    SetCol(SCCOL nNewCol)   { nCol = nNewCol; }

    void    TestData() const;
    void    Reset( const ScPatternAttr* pPattern, BOOL bAlloc = TRUE );
    BOOL    Concat(SCSIZE nPos);

    const ScPatternAttr* GetPattern( SCROW nRow ) const;
    const ScPatternAttr* GetPatternRange( SCROW& rStartRow, SCROW& rEndRow, SCROW nRow ) const;
    void    MergePatternArea( SCROW nStartRow, SCROW nEndRow, SfxItemSet** ppSet, BOOL bDeep ) const;

    void    MergeBlockFrame( SvxBoxItem* pLineOuter, SvxBoxInfoItem* pLineInner, ScLineFlags& rFlags,
                            SCROW nStartRow, SCROW nEndRow, BOOL bLeft, SCCOL nDistRight ) const;
    void    ApplyBlockFrame( const SvxBoxItem* pLineOuter, const SvxBoxInfoItem* pLineInner,
                            SCROW nStartRow, SCROW nEndRow, BOOL bLeft, SCCOL nDistRight );

    void    SetPattern( SCROW nRow, const ScPatternAttr* pPattern, BOOL bPutToPool = FALSE );
    void    SetPatternArea( SCROW nStartRow, SCROW nEndRow, const ScPatternAttr* pPattern, BOOL bPutToPool = FALSE);
    void    ApplyStyleArea( SCROW nStartRow, SCROW nEndRow, ScStyleSheet* pStyle );
    void    ApplyCacheArea( SCROW nStartRow, SCROW nEndRow, SfxItemPoolCache* pCache );
    void    ApplyLineStyleArea( SCROW nStartRow, SCROW nEndRow,
                                const SvxBorderLine* pLine, BOOL bColorOnly );

    void    ClearItems( SCROW nStartRow, SCROW nEndRow, const USHORT* pWhich );
    void    ChangeIndent( SCROW nStartRow, SCROW nEndRow, BOOL bIncrement );

            /// Including current, may return -1
    SCsROW  GetNextUnprotected( SCsROW nRow, BOOL bUp ) const;

            /// May return -1 if not found
    SCsROW  SearchStyle( SCsROW nRow, const ScStyleSheet* pSearchStyle,
                            BOOL bUp, ScMarkArray* pMarkArray = NULL );
    BOOL    SearchStyleRange( SCsROW& rRow, SCsROW& rEndRow, const ScStyleSheet* pSearchStyle,
                            BOOL bUp, ScMarkArray* pMarkArray = NULL );

    BOOL    ApplyFlags( SCROW nStartRow, SCROW nEndRow, INT16 nFlags );
    BOOL    RemoveFlags( SCROW nStartRow, SCROW nEndRow, INT16 nFlags );

    BOOL    Search( SCROW nRow, SCSIZE& nIndex ) const;

    BOOL    HasLines( SCROW nRow1, SCROW nRow2, Rectangle& rSizes,
                        BOOL bLeft, BOOL bRight ) const;
    BOOL    HasAttrib( SCROW nRow1, SCROW nRow2, USHORT nMask ) const;
    BOOL    ExtendMerge( SCCOL nThisCol, SCROW nStartRow, SCROW nEndRow,
                                SCCOL& rPaintCol, SCROW& rPaintRow,
                                BOOL bRefresh, BOOL bAttrs );
    BOOL    RemoveAreaMerge( SCROW nStartRow, SCROW nEndRow );

    void    FindStyleSheet( const SfxStyleSheetBase* pStyleSheet, BOOL* pUsed, BOOL bReset );
    BOOL    IsStyleSheetUsed( const ScStyleSheet& rStyle, BOOL bGatherAllStyles ) const;

    void    DeleteAreaSafe(SCROW nStartRow, SCROW nEndRow);
    void    SetPatternAreaSafe( SCROW nStartRow, SCROW nEndRow,
                                    const ScPatternAttr* pWantedPattern, BOOL bDefault );
    void    CopyAreaSafe( SCROW nStartRow, SCROW nEndRow, long nDy, ScAttrArray& rAttrArray );

    BOOL    IsEmpty() const;

    SCROW   GetFirstEntryPos() const;
    SCROW   GetLastEntryPos( BOOL bIncludeBottom ) const;

    BOOL    HasVisibleAttr( SCROW& rFirstRow, SCROW& rLastRow, BOOL bSkipFirst ) const;
    BOOL    HasVisibleAttrIn( SCROW nStartRow, SCROW nEndRow ) const;
    BOOL    IsVisibleEqual( const ScAttrArray& rOther,
                            SCROW nStartRow, SCROW nEndRow ) const;
    BOOL    IsAllEqual( const ScAttrArray& rOther, SCROW nStartRow, SCROW nEndRow ) const;

    BOOL    TestInsertCol( SCROW nStartRow, SCROW nEndRow) const;
    BOOL    TestInsertRow( SCSIZE nSize ) const;
    void    InsertRow( SCROW nStartRow, SCSIZE nSize );
    void    DeleteRow( SCROW nStartRow, SCSIZE nSize );
    void    DeleteRange( SCSIZE nStartIndex, SCSIZE nEndIndex );
    void    DeleteArea( SCROW nStartRow, SCROW nEndRow );
    void    MoveTo( SCROW nStartRow, SCROW nEndRow, ScAttrArray& rAttrArray );
    void    CopyArea( SCROW nStartRow, SCROW nEndRow, long nDy, ScAttrArray& rAttrArray,
                        INT16 nStripFlags = 0 );

    void    DeleteHardAttr( SCROW nStartRow, SCROW nEndRow );

    void    Save( SvStream& rStream ) const;
    void    Load( SvStream& rStream );
    void    ConvertFontsAfterLoad();     // old binary file format
};

//  ------------------------------------------------------------------------------
//                              Iterator fuer Attribute
//  ------------------------------------------------------------------------------

class ScAttrIterator
{
    const ScAttrArray*  pArray;
    SCSIZE              nPos;
    SCROW               nRow;
    SCROW               nEndRow;
public:
    inline              ScAttrIterator( const ScAttrArray* pNewArray, SCROW nStart, SCROW nEnd );
    inline const ScPatternAttr* Next( SCROW& rTop, SCROW& rBottom );
    SCROW               GetNextRow() const { return nRow; }
};

inline ScAttrIterator::ScAttrIterator( const ScAttrArray* pNewArray, SCROW nStart, SCROW nEnd ) :
    pArray( pNewArray ),
    nRow( nStart ),
    nEndRow( nEnd )
{
    if ( nStart > 0 )
        pArray->Search( nStart, nPos );
    else
        nPos = 0;
}

inline const ScPatternAttr* ScAttrIterator::Next( SCROW& rTop, SCROW& rBottom )
{
    const ScPatternAttr* pRet;
    if ( nPos < pArray->nCount && nRow <= nEndRow )
    {
        rTop = nRow;
        rBottom = Min( pArray->pData[nPos].nRow, nEndRow );
        pRet = pArray->pData[nPos].pPattern;
        nRow = rBottom + 1;
        ++nPos;
    }
    else
        pRet = NULL;
    return pRet;
}

#endif

<commit_msg>INTEGRATION: CWS calc29 (1.5.292); FILE MERGED 2005/01/28 18:48:06 nn 1.5.292.1: #i30830# skip large formatted areas below data in GetPrintArea<commit_after>/*************************************************************************
 *
 *  $RCSfile: attarray.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-21 15:56:26 $
 *
 *  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_ATRARR_HXX
#define SC_ATRARR_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_SCATTR_HXX
#include "attrib.hxx"
#endif

class ScDocument;
class ScMarkArray;
class ScPatternAttr;
class ScStyleSheet;

class Rectangle;
class SfxItemPoolCache;
class SfxStyleSheetBase;
class SvxBorderLine;
class SvxBoxItem;
class SvxBoxInfoItem;

#define SC_LINE_EMPTY           0
#define SC_LINE_SET             1
#define SC_LINE_DONTCARE        2

#define SC_ATTRARRAY_DELTA      4

struct ScLineFlags
{
    BYTE    nLeft;
    BYTE    nRight;
    BYTE    nTop;
    BYTE    nBottom;
    BYTE    nHori;
    BYTE    nVert;

    ScLineFlags() : nLeft(SC_LINE_EMPTY),nRight(SC_LINE_EMPTY),nTop(SC_LINE_EMPTY),
                    nBottom(SC_LINE_EMPTY),nHori(SC_LINE_EMPTY),nVert(SC_LINE_EMPTY) {}
};

struct ScAttrEntry
{
    SCROW                   nRow;
    const ScPatternAttr*    pPattern;
};

class ScAttrArray
{
private:
    SCCOL           nCol;
    SCTAB           nTab;
    ScDocument*     pDocument;

    SCSIZE          nCount;
    SCSIZE          nLimit;
    ScAttrEntry*    pData;

friend class ScDocument;                // fuer FillInfo
friend class ScDocumentIterator;
friend class ScAttrIterator;
friend class ScHorizontalAttrIterator;
friend void lcl_IterGetNumberFormat( ULONG& nFormat,
        const ScAttrArray*& rpArr, SCROW& nAttrEndRow,
        const ScAttrArray* pNewArr, SCROW nRow, ScDocument* pDoc );

    BOOL    ApplyFrame( const SvxBoxItem* pLineOuter, const SvxBoxInfoItem* pLineInner,
                            SCROW nStartRow, SCROW nEndRow,
                            BOOL bLeft, SCCOL nDistRight, BOOL bTop, SCROW nDistBottom );

public:
            ScAttrArray( SCCOL nNewCol, SCTAB nNewTab, ScDocument* pDoc );
            ~ScAttrArray();

    void    SetTab(SCTAB nNewTab)   { nTab = nNewTab; }
    void    SetCol(SCCOL nNewCol)   { nCol = nNewCol; }

    void    TestData() const;
    void    Reset( const ScPatternAttr* pPattern, BOOL bAlloc = TRUE );
    BOOL    Concat(SCSIZE nPos);

    const ScPatternAttr* GetPattern( SCROW nRow ) const;
    const ScPatternAttr* GetPatternRange( SCROW& rStartRow, SCROW& rEndRow, SCROW nRow ) const;
    void    MergePatternArea( SCROW nStartRow, SCROW nEndRow, SfxItemSet** ppSet, BOOL bDeep ) const;

    void    MergeBlockFrame( SvxBoxItem* pLineOuter, SvxBoxInfoItem* pLineInner, ScLineFlags& rFlags,
                            SCROW nStartRow, SCROW nEndRow, BOOL bLeft, SCCOL nDistRight ) const;
    void    ApplyBlockFrame( const SvxBoxItem* pLineOuter, const SvxBoxInfoItem* pLineInner,
                            SCROW nStartRow, SCROW nEndRow, BOOL bLeft, SCCOL nDistRight );

    void    SetPattern( SCROW nRow, const ScPatternAttr* pPattern, BOOL bPutToPool = FALSE );
    void    SetPatternArea( SCROW nStartRow, SCROW nEndRow, const ScPatternAttr* pPattern, BOOL bPutToPool = FALSE);
    void    ApplyStyleArea( SCROW nStartRow, SCROW nEndRow, ScStyleSheet* pStyle );
    void    ApplyCacheArea( SCROW nStartRow, SCROW nEndRow, SfxItemPoolCache* pCache );
    void    ApplyLineStyleArea( SCROW nStartRow, SCROW nEndRow,
                                const SvxBorderLine* pLine, BOOL bColorOnly );

    void    ClearItems( SCROW nStartRow, SCROW nEndRow, const USHORT* pWhich );
    void    ChangeIndent( SCROW nStartRow, SCROW nEndRow, BOOL bIncrement );

            /// Including current, may return -1
    SCsROW  GetNextUnprotected( SCsROW nRow, BOOL bUp ) const;

            /// May return -1 if not found
    SCsROW  SearchStyle( SCsROW nRow, const ScStyleSheet* pSearchStyle,
                            BOOL bUp, ScMarkArray* pMarkArray = NULL );
    BOOL    SearchStyleRange( SCsROW& rRow, SCsROW& rEndRow, const ScStyleSheet* pSearchStyle,
                            BOOL bUp, ScMarkArray* pMarkArray = NULL );

    BOOL    ApplyFlags( SCROW nStartRow, SCROW nEndRow, INT16 nFlags );
    BOOL    RemoveFlags( SCROW nStartRow, SCROW nEndRow, INT16 nFlags );

    BOOL    Search( SCROW nRow, SCSIZE& nIndex ) const;

    BOOL    HasLines( SCROW nRow1, SCROW nRow2, Rectangle& rSizes,
                        BOOL bLeft, BOOL bRight ) const;
    BOOL    HasAttrib( SCROW nRow1, SCROW nRow2, USHORT nMask ) const;
    BOOL    ExtendMerge( SCCOL nThisCol, SCROW nStartRow, SCROW nEndRow,
                                SCCOL& rPaintCol, SCROW& rPaintRow,
                                BOOL bRefresh, BOOL bAttrs );
    BOOL    RemoveAreaMerge( SCROW nStartRow, SCROW nEndRow );

    void    FindStyleSheet( const SfxStyleSheetBase* pStyleSheet, BOOL* pUsed, BOOL bReset );
    BOOL    IsStyleSheetUsed( const ScStyleSheet& rStyle, BOOL bGatherAllStyles ) const;

    void    DeleteAreaSafe(SCROW nStartRow, SCROW nEndRow);
    void    SetPatternAreaSafe( SCROW nStartRow, SCROW nEndRow,
                                    const ScPatternAttr* pWantedPattern, BOOL bDefault );
    void    CopyAreaSafe( SCROW nStartRow, SCROW nEndRow, long nDy, ScAttrArray& rAttrArray );

    BOOL    IsEmpty() const;

    SCROW   GetFirstEntryPos() const;
    SCROW   GetLastEntryPos( BOOL bIncludeBottom ) const;

    BOOL    GetFirstVisibleAttr( SCROW& rFirstRow ) const;
    BOOL    GetLastVisibleAttr( SCROW& rLastRow, SCROW nLastData ) const;
    BOOL    HasVisibleAttrIn( SCROW nStartRow, SCROW nEndRow ) const;
    BOOL    IsVisibleEqual( const ScAttrArray& rOther,
                            SCROW nStartRow, SCROW nEndRow ) const;
    BOOL    IsAllEqual( const ScAttrArray& rOther, SCROW nStartRow, SCROW nEndRow ) const;

    BOOL    TestInsertCol( SCROW nStartRow, SCROW nEndRow) const;
    BOOL    TestInsertRow( SCSIZE nSize ) const;
    void    InsertRow( SCROW nStartRow, SCSIZE nSize );
    void    DeleteRow( SCROW nStartRow, SCSIZE nSize );
    void    DeleteRange( SCSIZE nStartIndex, SCSIZE nEndIndex );
    void    DeleteArea( SCROW nStartRow, SCROW nEndRow );
    void    MoveTo( SCROW nStartRow, SCROW nEndRow, ScAttrArray& rAttrArray );
    void    CopyArea( SCROW nStartRow, SCROW nEndRow, long nDy, ScAttrArray& rAttrArray,
                        INT16 nStripFlags = 0 );

    void    DeleteHardAttr( SCROW nStartRow, SCROW nEndRow );

    void    Save( SvStream& rStream ) const;
    void    Load( SvStream& rStream );
    void    ConvertFontsAfterLoad();     // old binary file format
};

//  ------------------------------------------------------------------------------
//                              Iterator fuer Attribute
//  ------------------------------------------------------------------------------

class ScAttrIterator
{
    const ScAttrArray*  pArray;
    SCSIZE              nPos;
    SCROW               nRow;
    SCROW               nEndRow;
public:
    inline              ScAttrIterator( const ScAttrArray* pNewArray, SCROW nStart, SCROW nEnd );
    inline const ScPatternAttr* Next( SCROW& rTop, SCROW& rBottom );
    SCROW               GetNextRow() const { return nRow; }
};

inline ScAttrIterator::ScAttrIterator( const ScAttrArray* pNewArray, SCROW nStart, SCROW nEnd ) :
    pArray( pNewArray ),
    nRow( nStart ),
    nEndRow( nEnd )
{
    if ( nStart > 0 )
        pArray->Search( nStart, nPos );
    else
        nPos = 0;
}

inline const ScPatternAttr* ScAttrIterator::Next( SCROW& rTop, SCROW& rBottom )
{
    const ScPatternAttr* pRet;
    if ( nPos < pArray->nCount && nRow <= nEndRow )
    {
        rTop = nRow;
        rBottom = Min( pArray->pData[nPos].nRow, nEndRow );
        pRet = pArray->pData[nPos].pPattern;
        nRow = rBottom + 1;
        ++nPos;
    }
    else
        pRet = NULL;
    return pRet;
}

#endif

<|endoftext|>


<commit_before>/*
 * IODescriptors_test.cpp
 *
 *  Created on: Nov 21, 2013
 *      Author: andresf
 */

#include <gtest/gtest.h>
#include <opencv2/core/core.hpp>

#include <FileUtils.hpp>

TEST(IODescriptors, LoadSave) {

	cv::Mat original;
	FileUtils::loadDescriptors("all_souls_000000.yaml.gz", original);

	FileUtils::saveDescriptors("sift_desc_tmp.yaml.gz", original);
	cv::Mat loaded;
	FileUtils::loadDescriptors("sift_desc_tmp.yaml.gz", loaded);

	// Check number of rows, columns and type are equal
	EXPECT_TRUE(original.rows == loaded.rows);
	EXPECT_TRUE(original.cols == loaded.cols);
	EXPECT_TRUE(original.type() == loaded.type());

	// Check elements are equal
	for (int i = 0; i < original.rows; i++) {
		for (int j = 0; j < original.cols; j++) {
			EXPECT_TRUE(original.at<float>(i, j) == loaded.at<float>(i, j));
		}
	}

}

<commit_msg>Common/tests/IODescriptors_test.cpp * Implemented tests for testing methods FileUilts::saveDescriptors and FileUilts::loadDescriptors.<commit_after>/*
 * IODescriptors_test.cpp
 *
 *  Created on: Nov 21, 2013
 *      Author: andresf
 */

#include <gtest/gtest.h>
#include <opencv2/core/core.hpp>
#include <opencv2/flann/logger.h>

#include <FileUtils.hpp>

TEST(IODescriptors, LoadSave) {

	cv::Mat original;
	FileUtils::loadDescriptors("all_souls_000000.yaml.gz", original);
	FileUtils::saveDescriptors("sift_desc_tmp.yaml.gz", original);

	cv::Mat loaded;
	FileUtils::loadDescriptors("sift_desc_tmp.yaml.gz", loaded);

	// Check number of rows, columns and type are equal
	EXPECT_TRUE(original.rows == loaded.rows);
	EXPECT_TRUE(original.cols == loaded.cols);
	EXPECT_TRUE(original.type() == loaded.type());

	// Check elements are equal
	for (int i = 0; i < original.rows; i++) {
		for (int j = 0; j < original.cols; j++) {
			EXPECT_TRUE(original.at<float>(i, j) == loaded.at<float>(i, j));
		}
	}

}

TEST(IODescriptors, LoadStress) {

	cvflann::Logger::setDestination("load_times.log");

	cv::Mat descriptors;

	for (size_t i = 0; i < 5008; i++) {
		descriptors = cv::Mat();

		double mytime = cv::getTickCount();
		FileUtils::loadDescriptors("all_souls_000000.yaml.gz", descriptors);
		mytime = (double(cv::getTickCount()) - mytime) / cv::getTickFrequency()
				* 1000.0;

		cvflann::Logger::log(0, "%lf\n", mytime);
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "config/navcoin-config.h"
#endif

#include "utiltime.h"

#include <chrono>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

using namespace std;

static int64_t nMockTime = 0; //!< For unit testing
static int64_t nNtpTimeOffset = 0;

int64_t GetTime()
{
    if (nMockTime) return nMockTime;

    time_t now = time(NULL);
    assert(now > 0);
    return now - GetNtpTimeOffset();
}

int64_t GetTimeNow()
{
    if (nMockTime) return nMockTime;

    time_t now = time(NULL);
    assert(now > 0);
    return now;
}

int64_t GetSteadyTime()
{
    auto now = std::chrono::steady_clock::now();
    auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
    assert(millisecs.count() > 0);
    return millisecs.count();
}

void SetMockTime(int64_t nMockTimeIn)
{
    nMockTime = nMockTimeIn;
}

int64_t GetTimeMillis()
{
    int64_t now = (boost::posix_time::microsec_clock::universal_time() -
                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
    assert(now > 0);
    return now - (GetNtpTimeOffset() * 1000);
}

int64_t GetTimeMicros()
{
    int64_t now = (boost::posix_time::microsec_clock::universal_time() -
                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
    assert(now > 0);
    return now - (GetNtpTimeOffset() * 1000  * 1000);
}

/** Return a time useful for the debug log */
int64_t GetLogTimeMicros()
{
    if (nMockTime) return nMockTime*1000000;

    return GetTimeMicros();
}

void MilliSleep(int64_t n)
{

/**
 * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50
 * until fixed in 1.52. Use the deprecated sleep method for the broken case.
 * See: https://svn.boost.org/trac/boost/ticket/7238
 */
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
    boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
    boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}

std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
    // std::locale takes ownership of the pointer
    std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
    std::stringstream ss;
    ss.imbue(loc);
    ss << boost::posix_time::from_time_t(nTime);
    return ss.str();
}

int64_t GetNtpTimeOffset()
{
    return nNtpTimeOffset;
}

void SetNtpTimeOffset(uint64_t nTimeOffsetIn)
{
    nNtpTimeOffset = nTimeOffsetIn;
}
<commit_msg>remove offset from GetTimeMicros()<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "config/navcoin-config.h"
#endif

#include "utiltime.h"

#include <chrono>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>

using namespace std;

static int64_t nMockTime = 0; //!< For unit testing
static int64_t nNtpTimeOffset = 0;

int64_t GetTime()
{
    if (nMockTime) return nMockTime;

    time_t now = time(NULL);
    assert(now > 0);
    return now - GetNtpTimeOffset();
}

int64_t GetTimeNow()
{
    if (nMockTime) return nMockTime;

    time_t now = time(NULL);
    assert(now > 0);
    return now;
}

int64_t GetSteadyTime()
{
    auto now = std::chrono::steady_clock::now();
    auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
    assert(millisecs.count() > 0);
    return millisecs.count();
}

void SetMockTime(int64_t nMockTimeIn)
{
    nMockTime = nMockTimeIn;
}

int64_t GetTimeMillis()
{
    int64_t now = (boost::posix_time::microsec_clock::universal_time() -
                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
    assert(now > 0);
    return now - (GetNtpTimeOffset() * 1000);
}

int64_t GetTimeMicros()
{
    int64_t now = (boost::posix_time::microsec_clock::universal_time() -
                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
    assert(now > 0);
    return now;
}

/** Return a time useful for the debug log */
int64_t GetLogTimeMicros()
{
    if (nMockTime) return nMockTime*1000000;

    return GetTimeMicros();
}

void MilliSleep(int64_t n)
{

/**
 * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50
 * until fixed in 1.52. Use the deprecated sleep method for the broken case.
 * See: https://svn.boost.org/trac/boost/ticket/7238
 */
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
    boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
    boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}

std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
    // std::locale takes ownership of the pointer
    std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
    std::stringstream ss;
    ss.imbue(loc);
    ss << boost::posix_time::from_time_t(nTime);
    return ss.str();
}

int64_t GetNtpTimeOffset()
{
    return nNtpTimeOffset;
}

void SetNtpTimeOffset(uint64_t nTimeOffsetIn)
{
    nNtpTimeOffset = nTimeOffsetIn;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/win/metro.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/win/scoped_comptr.h"
#include "base/win/windows_version.h"

namespace base {
namespace win {

namespace {
bool g_should_tsf_aware_required = false;
}

HMODULE GetMetroModule() {
  const HMODULE kUninitialized = reinterpret_cast<HMODULE>(1);
  static HMODULE metro_module = kUninitialized;

  if (metro_module == kUninitialized) {
    // Initialize the cache, note that the initialization is idempotent
    // under the assumption that metro_driver is never unloaded, so the
    // race to this assignment is safe.
    metro_module = GetModuleHandleA("metro_driver.dll");
    if (metro_module != NULL) {
      // This must be a metro process if the metro_driver is loaded.
      DCHECK(IsMetroProcess());
    }
  }

  DCHECK(metro_module != kUninitialized);
  return metro_module;
}

bool IsMetroProcess() {
  enum ImmersiveState {
    kImmersiveUnknown,
    kImmersiveTrue,
    kImmersiveFalse
  };
  // The immersive state of a process can never change.
  // Look it up once and cache it here.
  static ImmersiveState state = kImmersiveUnknown;

  if (state == kImmersiveUnknown) {
    if (IsProcessImmersive(::GetCurrentProcess())) {
      state = kImmersiveTrue;
    } else {
      state = kImmersiveFalse;
    }
  }
  DCHECK_NE(kImmersiveUnknown, state);
  return state == kImmersiveTrue;
}

bool IsProcessImmersive(HANDLE process) {
  typedef BOOL (WINAPI* IsImmersiveProcessFunc)(HANDLE process);
  HMODULE user32 = ::GetModuleHandleA("user32.dll");
  DCHECK(user32 != NULL);

  IsImmersiveProcessFunc is_immersive_process =
      reinterpret_cast<IsImmersiveProcessFunc>(
          ::GetProcAddress(user32, "IsImmersiveProcess"));

  if (is_immersive_process)
    return is_immersive_process(process) ? true: false;
  return false;
}

bool IsTsfAwareRequired() {
  // Although this function is equal to IsMetroProcess at this moment,
  // Chrome for Win7 and Vista may support TSF in the future.
  return g_should_tsf_aware_required || IsMetroProcess();
}

void SetForceToUseTsf() {
  g_should_tsf_aware_required = true;

  // Since Windows 8 Metro mode disables CUAS (Cicero Unaware Application
  // Support) via ImmDisableLegacyIME API, Chrome must be fully TSF-aware on
  // Metro mode. For debugging purposes, explicitly call ImmDisableLegacyIME so
  // that one can test TSF functionality even on Windows 8 desktop mode. Note
  // that CUAS cannot be disabled on Windows Vista/7 where ImmDisableLegacyIME
  // is not available.
  typedef BOOL (* ImmDisableLegacyIMEFunc)();
  HMODULE imm32 = ::GetModuleHandleA("imm32.dll");
  if (imm32 == NULL)
    return;

  ImmDisableLegacyIMEFunc imm_disable_legacy_ime =
      reinterpret_cast<ImmDisableLegacyIMEFunc>(
          ::GetProcAddress(imm32, "ImmDisableLegacyIME"));

  if (imm_disable_legacy_ime == NULL) {
    // Unsupported API, just do nothing.
    return;
  }

  if (!imm_disable_legacy_ime()) {
    DVLOG(1) << "Failed to disable legacy IME.";
  }
}

wchar_t* LocalAllocAndCopyString(const string16& src) {
  size_t dest_size = (src.length() + 1) * sizeof(wchar_t);
  wchar_t* dest = reinterpret_cast<wchar_t*>(LocalAlloc(LPTR, dest_size));
  base::wcslcpy(dest, src.c_str(), dest_size);
  return dest;
}

bool IsTouchEnabled() {
  int value = GetSystemMetrics(SM_DIGITIZER);
  return value & (NID_READY | NID_INTEGRATED_TOUCH) ==
             (NID_READY | NID_INTEGRATED_TOUCH);
}

bool IsParentalControlActivityLoggingOn() {
  // Query this info on Windows Vista and above.
  if (base::win::GetVersion() < base::win::VERSION_VISTA)
    return false;

  static bool parental_control_logging_required = false;
  static bool parental_control_status_determined = false;

  if (parental_control_status_determined)
    return parental_control_logging_required;

  parental_control_status_determined = true;

  ScopedComPtr<IWindowsParentalControlsCore> parent_controls;
  HRESULT hr = parent_controls.CreateInstance(
      __uuidof(WindowsParentalControls));
  if (FAILED(hr))
    return false;

  ScopedComPtr<IWPCSettings> settings;
  hr = parent_controls->GetUserSettings(NULL, settings.Receive());
  if (FAILED(hr))
    return false;

  unsigned long restrictions = 0;
  settings->GetRestrictions(&restrictions);

  parental_control_logging_required =
      (restrictions & WPCFLAG_LOGGING_REQUIRED) == WPCFLAG_LOGGING_REQUIRED;
  return parental_control_logging_required;
}

// Metro driver exports for getting the launch type, initial url, initial
// search term, etc.
extern "C" {
typedef const wchar_t* (*GetInitialUrl)();
typedef const wchar_t* (*GetInitialSearchString)();
typedef base::win::MetroLaunchType (*GetLaunchType)(
    base::win::MetroPreviousExecutionState* previous_state);
}

MetroLaunchType GetMetroLaunchParams(string16* params) {
  HMODULE metro = base::win::GetMetroModule();
  if (!metro)
    return base::win::METRO_LAUNCH_ERROR;

  GetLaunchType get_launch_type = reinterpret_cast<GetLaunchType>(
      ::GetProcAddress(metro, "GetLaunchType"));
  DCHECK(get_launch_type);

  base::win::MetroLaunchType launch_type = get_launch_type(NULL);

  if ((launch_type == base::win::METRO_PROTOCOL) ||
      (launch_type == base::win::METRO_LAUNCH)) {
    GetInitialUrl initial_metro_url = reinterpret_cast<GetInitialUrl>(
        ::GetProcAddress(metro, "GetInitialUrl"));
    DCHECK(initial_metro_url);
    *params = initial_metro_url();
  } else if (launch_type == base::win::METRO_SEARCH) {
    GetInitialSearchString initial_search_string =
        reinterpret_cast<GetInitialSearchString>(
            ::GetProcAddress(metro, "GetInitialSearchString"));
    DCHECK(initial_search_string);
    *params = initial_search_string();
  }
  return launch_type;
}

}  // namespace win
}  // namespace base
<commit_msg>fix operator precedence in IsTouchEnabled<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/win/metro.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/win/scoped_comptr.h"
#include "base/win/windows_version.h"

namespace base {
namespace win {

namespace {
bool g_should_tsf_aware_required = false;
}

HMODULE GetMetroModule() {
  const HMODULE kUninitialized = reinterpret_cast<HMODULE>(1);
  static HMODULE metro_module = kUninitialized;

  if (metro_module == kUninitialized) {
    // Initialize the cache, note that the initialization is idempotent
    // under the assumption that metro_driver is never unloaded, so the
    // race to this assignment is safe.
    metro_module = GetModuleHandleA("metro_driver.dll");
    if (metro_module != NULL) {
      // This must be a metro process if the metro_driver is loaded.
      DCHECK(IsMetroProcess());
    }
  }

  DCHECK(metro_module != kUninitialized);
  return metro_module;
}

bool IsMetroProcess() {
  enum ImmersiveState {
    kImmersiveUnknown,
    kImmersiveTrue,
    kImmersiveFalse
  };
  // The immersive state of a process can never change.
  // Look it up once and cache it here.
  static ImmersiveState state = kImmersiveUnknown;

  if (state == kImmersiveUnknown) {
    if (IsProcessImmersive(::GetCurrentProcess())) {
      state = kImmersiveTrue;
    } else {
      state = kImmersiveFalse;
    }
  }
  DCHECK_NE(kImmersiveUnknown, state);
  return state == kImmersiveTrue;
}

bool IsProcessImmersive(HANDLE process) {
  typedef BOOL (WINAPI* IsImmersiveProcessFunc)(HANDLE process);
  HMODULE user32 = ::GetModuleHandleA("user32.dll");
  DCHECK(user32 != NULL);

  IsImmersiveProcessFunc is_immersive_process =
      reinterpret_cast<IsImmersiveProcessFunc>(
          ::GetProcAddress(user32, "IsImmersiveProcess"));

  if (is_immersive_process)
    return is_immersive_process(process) ? true: false;
  return false;
}

bool IsTsfAwareRequired() {
  // Although this function is equal to IsMetroProcess at this moment,
  // Chrome for Win7 and Vista may support TSF in the future.
  return g_should_tsf_aware_required || IsMetroProcess();
}

void SetForceToUseTsf() {
  g_should_tsf_aware_required = true;

  // Since Windows 8 Metro mode disables CUAS (Cicero Unaware Application
  // Support) via ImmDisableLegacyIME API, Chrome must be fully TSF-aware on
  // Metro mode. For debugging purposes, explicitly call ImmDisableLegacyIME so
  // that one can test TSF functionality even on Windows 8 desktop mode. Note
  // that CUAS cannot be disabled on Windows Vista/7 where ImmDisableLegacyIME
  // is not available.
  typedef BOOL (* ImmDisableLegacyIMEFunc)();
  HMODULE imm32 = ::GetModuleHandleA("imm32.dll");
  if (imm32 == NULL)
    return;

  ImmDisableLegacyIMEFunc imm_disable_legacy_ime =
      reinterpret_cast<ImmDisableLegacyIMEFunc>(
          ::GetProcAddress(imm32, "ImmDisableLegacyIME"));

  if (imm_disable_legacy_ime == NULL) {
    // Unsupported API, just do nothing.
    return;
  }

  if (!imm_disable_legacy_ime()) {
    DVLOG(1) << "Failed to disable legacy IME.";
  }
}

wchar_t* LocalAllocAndCopyString(const string16& src) {
  size_t dest_size = (src.length() + 1) * sizeof(wchar_t);
  wchar_t* dest = reinterpret_cast<wchar_t*>(LocalAlloc(LPTR, dest_size));
  base::wcslcpy(dest, src.c_str(), dest_size);
  return dest;
}

bool IsTouchEnabled() {
  int value = GetSystemMetrics(SM_DIGITIZER);
  return (value & (NID_READY | NID_INTEGRATED_TOUCH)) ==
             (NID_READY | NID_INTEGRATED_TOUCH);
}

bool IsParentalControlActivityLoggingOn() {
  // Query this info on Windows Vista and above.
  if (base::win::GetVersion() < base::win::VERSION_VISTA)
    return false;

  static bool parental_control_logging_required = false;
  static bool parental_control_status_determined = false;

  if (parental_control_status_determined)
    return parental_control_logging_required;

  parental_control_status_determined = true;

  ScopedComPtr<IWindowsParentalControlsCore> parent_controls;
  HRESULT hr = parent_controls.CreateInstance(
      __uuidof(WindowsParentalControls));
  if (FAILED(hr))
    return false;

  ScopedComPtr<IWPCSettings> settings;
  hr = parent_controls->GetUserSettings(NULL, settings.Receive());
  if (FAILED(hr))
    return false;

  unsigned long restrictions = 0;
  settings->GetRestrictions(&restrictions);

  parental_control_logging_required =
      (restrictions & WPCFLAG_LOGGING_REQUIRED) == WPCFLAG_LOGGING_REQUIRED;
  return parental_control_logging_required;
}

// Metro driver exports for getting the launch type, initial url, initial
// search term, etc.
extern "C" {
typedef const wchar_t* (*GetInitialUrl)();
typedef const wchar_t* (*GetInitialSearchString)();
typedef base::win::MetroLaunchType (*GetLaunchType)(
    base::win::MetroPreviousExecutionState* previous_state);
}

MetroLaunchType GetMetroLaunchParams(string16* params) {
  HMODULE metro = base::win::GetMetroModule();
  if (!metro)
    return base::win::METRO_LAUNCH_ERROR;

  GetLaunchType get_launch_type = reinterpret_cast<GetLaunchType>(
      ::GetProcAddress(metro, "GetLaunchType"));
  DCHECK(get_launch_type);

  base::win::MetroLaunchType launch_type = get_launch_type(NULL);

  if ((launch_type == base::win::METRO_PROTOCOL) ||
      (launch_type == base::win::METRO_LAUNCH)) {
    GetInitialUrl initial_metro_url = reinterpret_cast<GetInitialUrl>(
        ::GetProcAddress(metro, "GetInitialUrl"));
    DCHECK(initial_metro_url);
    *params = initial_metro_url();
  } else if (launch_type == base::win::METRO_SEARCH) {
    GetInitialSearchString initial_search_string =
        reinterpret_cast<GetInitialSearchString>(
            ::GetProcAddress(metro, "GetInitialSearchString"));
    DCHECK(initial_search_string);
    *params = initial_search_string();
  }
  return launch_type;
}

}  // namespace win
}  // namespace base
<|endoftext|>


<commit_before>#pragma once

#include <type_traits>
#include <utility>
#include <memory>
#include <uv.h>
#include "event.hpp"
#include "handle.hpp"
#include "util.hpp"

namespace uvw {

namespace details {

enum class UVPollEvent: std::underlying_type_t<uv_poll_event> {
    READABLE = UV_READABLE,
    WRITABLE = UV_WRITABLE,
    DISCONNECT = UV_DISCONNECT
};

}

/**
 * @brief PollEvent event.
 *
 * It will be emitted by PollHandle according with its functionalities.
 */
struct PollEvent: Event<PollEvent> {
    explicit PollEvent(Flags _flags) noexcept
        : flags{std::move(_flags)}
    {}

    /**
     * @brief Detected events all in one.
     *
     * Available flags are:
     *
     * * `PollHandle::Event::READABLE`
     * * `PollHandle::Event::WRITABLE`
     * * `PollHandle::Event::DISCONNECT`
     */
    Flags flags;
};

/**
 * @brief The PollHandle handle.
 *
 * Poll handles are used to watch file descriptors for readability, writability
 * and disconnection.
 *
 * To create a `PollHandle` through a `Loop`, arguments follow:
 *
 * * A descriptor that can be:
 *     * either an `int` file descriptor
 *     * or a `OSSocketHandle` socket descriptor
 *
 * See the official
 * [documentation](http://docs.libuv.org/en/v1.x/poll.html)
 * for further details.
 */
class PollHandle final: public Handle<PollHandle, uv_poll_t> {
    static void startCallback(uv_poll_t *handle, int status, int events) {
        PollHandle &poll = *(static_cast<PollHandle*>(handle->data));
        if(status) { poll.publish(ErrorEvent{status}); }
        else { poll.publish(PollEvent{static_cast<std::underlying_type_t<Event>>(events)}); }
    }

public:
    using Event = details::UVPollEvent;

    explicit PollHandle(ConstructorAccess ca, std::shared_ptr<Loop> ref, int desc)
        : Handle{std::move(ca), std::move(ref)}, tag{FD}, fd{desc}
    {}

    explicit PollHandle(ConstructorAccess ca, std::shared_ptr<Loop> ref, OSSocketHandle sock)
        : Handle{std::move(ca), std::move(ref)}, tag{SOCKET}, socket{sock}
    {}

    /**
     * @brief Initializes the handle.
     * @return True in case of success, false otherwise.
     */
    bool init() {
        return (tag == SOCKET)
                ? initialize(&uv_poll_init_socket, socket)
                : initialize(&uv_poll_init, fd);
    }

    /**
     * @brief Starts polling the file descriptor.
     *
     * Available flags are:
     *
     * * `PollHandle::Event::READABLE`
     * * `PollHandle::Event::WRITABLE`
     * * `PollHandle::Event::DISCONNECT`
     *
     * As soon as an event is detected, a PollEvent is emitted by the
     * handle.

     * It could happen that ErrorEvent events are emitted while running.
     *
     * Calling more than once this method will update the flags to which the
     * caller is interested.
     *
     * @param flags The events to which the caller is interested.
     */
    void start(Flags<Event> flags) {
        invoke(&uv_poll_start, get(), flags, &startCallback);
    }

    /**
     * @brief Starts polling the file descriptor.
     *
     * Available flags are:
     *
     * * `PollHandle::Event::READABLE`
     * * `PollHandle::Event::WRITABLE`
     * * `PollHandle::Event::DISCONNECT`
     *
     * As soon as an event is detected, a PollEvent is emitted by the
     * handle.

     * It could happen that ErrorEvent events are emitted while running.
     *
     * Calling more than once this method will update the flags to which the
     * caller is interested.
     *
     * @param event The event to which the caller is interested.
     */
    void start(Event event) {
        start(Flags<Event>{event});
    }

    /**
     * @brief Stops polling the file descriptor.
     */
    void stop() {
        invoke(&uv_poll_stop, get());
    }

private:
    enum { FD, SOCKET } tag;
    union {
        int fd;
        OSSocketHandle::Type socket;
    };
};

}
<commit_msg>Update poll.hpp<commit_after>#pragma once

#include <type_traits>
#include <utility>
#include <memory>
#include <uv.h>
#include "event.hpp"
#include "handle.hpp"
#include "util.hpp"

namespace uvw {

namespace details {

enum class UVPollEvent: std::underlying_type_t<uv_poll_event> {
    READABLE = UV_READABLE,
    WRITABLE = UV_WRITABLE,
    DISCONNECT = UV_DISCONNECT
};

}

/**
 * @brief PollEvent event.
 *
 * It will be emitted by PollHandle according with its functionalities.
 */
struct PollEvent: Event<PollEvent> {
    explicit PollEvent(Flags events) noexcept
        : flags{std::move(events)}
    {}

    /**
     * @brief Detected events all in one.
     *
     * Available flags are:
     *
     * * `PollHandle::Event::READABLE`
     * * `PollHandle::Event::WRITABLE`
     * * `PollHandle::Event::DISCONNECT`
     */
    Flags flags;
};

/**
 * @brief The PollHandle handle.
 *
 * Poll handles are used to watch file descriptors for readability, writability
 * and disconnection.
 *
 * To create a `PollHandle` through a `Loop`, arguments follow:
 *
 * * A descriptor that can be:
 *     * either an `int` file descriptor
 *     * or a `OSSocketHandle` socket descriptor
 *
 * See the official
 * [documentation](http://docs.libuv.org/en/v1.x/poll.html)
 * for further details.
 */
class PollHandle final: public Handle<PollHandle, uv_poll_t> {
    static void startCallback(uv_poll_t *handle, int status, int events) {
        PollHandle &poll = *(static_cast<PollHandle*>(handle->data));
        if(status) { poll.publish(ErrorEvent{status}); }
        else { poll.publish(PollEvent{static_cast<std::underlying_type_t<Event>>(events)}); }
    }

public:
    using Event = details::UVPollEvent;

    explicit PollHandle(ConstructorAccess ca, std::shared_ptr<Loop> ref, int desc)
        : Handle{std::move(ca), std::move(ref)}, tag{FD}, fd{desc}
    {}

    explicit PollHandle(ConstructorAccess ca, std::shared_ptr<Loop> ref, OSSocketHandle sock)
        : Handle{std::move(ca), std::move(ref)}, tag{SOCKET}, socket{sock}
    {}

    /**
     * @brief Initializes the handle.
     * @return True in case of success, false otherwise.
     */
    bool init() {
        return (tag == SOCKET)
                ? initialize(&uv_poll_init_socket, socket)
                : initialize(&uv_poll_init, fd);
    }

    /**
     * @brief Starts polling the file descriptor.
     *
     * Available flags are:
     *
     * * `PollHandle::Event::READABLE`
     * * `PollHandle::Event::WRITABLE`
     * * `PollHandle::Event::DISCONNECT`
     *
     * As soon as an event is detected, a PollEvent is emitted by the
     * handle.

     * It could happen that ErrorEvent events are emitted while running.
     *
     * Calling more than once this method will update the flags to which the
     * caller is interested.
     *
     * @param flags The events to which the caller is interested.
     */
    void start(Flags<Event> flags) {
        invoke(&uv_poll_start, get(), flags, &startCallback);
    }

    /**
     * @brief Starts polling the file descriptor.
     *
     * Available flags are:
     *
     * * `PollHandle::Event::READABLE`
     * * `PollHandle::Event::WRITABLE`
     * * `PollHandle::Event::DISCONNECT`
     *
     * As soon as an event is detected, a PollEvent is emitted by the
     * handle.

     * It could happen that ErrorEvent events are emitted while running.
     *
     * Calling more than once this method will update the flags to which the
     * caller is interested.
     *
     * @param event The event to which the caller is interested.
     */
    void start(Event event) {
        start(Flags<Event>{event});
    }

    /**
     * @brief Stops polling the file descriptor.
     */
    void stop() {
        invoke(&uv_poll_stop, get());
    }

private:
    enum { FD, SOCKET } tag;
    union {
        int fd;
        OSSocketHandle::Type socket;
    };
};

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: printopt.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:49:04 $
 *
 *  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 SC_PRINTOPT_HXX
#define SC_PRINTOPT_HXX

#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif

#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif

#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif

class SC_DLLPUBLIC ScPrintOptions
{
private:
    BOOL    bSkipEmpty;
    BOOL    bAllSheets;

public:
                ScPrintOptions();
                ScPrintOptions( const ScPrintOptions& rCpy );
                ~ScPrintOptions();

    BOOL    GetSkipEmpty() const            { return bSkipEmpty; }
    void    SetSkipEmpty( BOOL bVal )       { bSkipEmpty = bVal; }
    BOOL    GetAllSheets() const            { return bAllSheets; }
    void    SetAllSheets( BOOL bVal )       { bAllSheets = bVal; }

    void    SetDefaults();

    const ScPrintOptions&   operator=  ( const ScPrintOptions& rCpy );
    int                     operator== ( const ScPrintOptions& rOpt ) const;
    int                     operator!= ( const ScPrintOptions& rOpt ) const;
};

//==================================================================
// item for the dialog / options page
//==================================================================

class SC_DLLPUBLIC ScTpPrintItem : public SfxPoolItem
{
public:
                TYPEINFO();
                ScTpPrintItem( USHORT nWhich );
                ScTpPrintItem( USHORT nWhich,
                               const ScPrintOptions& rOpt );
                ScTpPrintItem( const ScTpPrintItem& rItem );
                ~ScTpPrintItem();

    virtual String          GetValueText() const;
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;

    const ScPrintOptions&   GetPrintOptions() const { return theOptions; }

private:
    ScPrintOptions theOptions;
};

//==================================================================
// config item
//==================================================================

class ScPrintCfg : public ScPrintOptions, public utl::ConfigItem
{
    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();

public:
            ScPrintCfg();

    void            SetOptions( const ScPrintOptions& rNew );
    void            OptionsChanged();   // after direct access to ScPrintOptions base class

    virtual void    Commit();
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.698); FILE MERGED 2008/04/01 15:29:39 thb 1.4.698.3: #i85898# Stripping all external header guards 2008/04/01 12:35:59 thb 1.4.698.2: #i85898# Stripping all external header guards 2008/03/31 17:13:33 rt 1.4.698.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: printopt.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 SC_PRINTOPT_HXX
#define SC_PRINTOPT_HXX

#include <svtools/poolitem.hxx>
#include <unotools/configitem.hxx>
#include "scdllapi.h"

class SC_DLLPUBLIC ScPrintOptions
{
private:
    BOOL    bSkipEmpty;
    BOOL    bAllSheets;

public:
                ScPrintOptions();
                ScPrintOptions( const ScPrintOptions& rCpy );
                ~ScPrintOptions();

    BOOL    GetSkipEmpty() const            { return bSkipEmpty; }
    void    SetSkipEmpty( BOOL bVal )       { bSkipEmpty = bVal; }
    BOOL    GetAllSheets() const            { return bAllSheets; }
    void    SetAllSheets( BOOL bVal )       { bAllSheets = bVal; }

    void    SetDefaults();

    const ScPrintOptions&   operator=  ( const ScPrintOptions& rCpy );
    int                     operator== ( const ScPrintOptions& rOpt ) const;
    int                     operator!= ( const ScPrintOptions& rOpt ) const;
};

//==================================================================
// item for the dialog / options page
//==================================================================

class SC_DLLPUBLIC ScTpPrintItem : public SfxPoolItem
{
public:
                TYPEINFO();
                ScTpPrintItem( USHORT nWhich );
                ScTpPrintItem( USHORT nWhich,
                               const ScPrintOptions& rOpt );
                ScTpPrintItem( const ScTpPrintItem& rItem );
                ~ScTpPrintItem();

    virtual String          GetValueText() const;
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;

    const ScPrintOptions&   GetPrintOptions() const { return theOptions; }

private:
    ScPrintOptions theOptions;
};

//==================================================================
// config item
//==================================================================

class ScPrintCfg : public ScPrintOptions, public utl::ConfigItem
{
    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();

public:
            ScPrintCfg();

    void            SetOptions( const ScPrintOptions& rNew );
    void            OptionsChanged();   // after direct access to ScPrintOptions base class

    virtual void    Commit();
};

#endif
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   Model.cpp
    created:    Tue May 27 2014
    author:     Timotei Dolean <timotei21@gmail.com>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "Model.h"
#include "CEGUI/PropertyHelper.h"

using namespace CEGUI;

template<typename T>
static ModelIndex makeValidIndex(size_t id, std::vector<T>& vector)
{
    if (id >= 0 && id < vector.size())
        return ModelIndex(&vector.at(id));

    return ModelIndex();
}

//----------------------------------------------------------------------------//
InventoryItem InventoryItem::make(const CEGUI::String& name, float weight)
{
    InventoryItem item;

    item.d_name = name;
    item.d_weight = weight;

    return item;
}

//----------------------------------------------------------------------------//
void InventoryModel::load()
{
    InventoryItem prev_matryoshka;
    // matryoshka D to A
    bool has_child = false;
    for (char chr = 'D'; chr >= 'A'; --chr)
    {
        InventoryItem matryoshka = InventoryItem::make("Matryoshka " + chr, 1.0f);

        if (has_child)
            matryoshka.d_items.push_back(prev_matryoshka);

        prev_matryoshka = matryoshka;
        has_child = true;
    }

    InventoryItem beans = InventoryItem::make("Beans!", 0.1f);
    InventoryItem beans_can = InventoryItem::make("Beans can", 1.0f);
    beans_can.d_items.push_back(beans);

    InventoryItem backpack = InventoryItem::make("Trip backpack", 2.0f);
    backpack.d_items.push_back(prev_matryoshka);
    backpack.d_items.push_back(beans_can);

    d_inventoryItems.push_back(backpack);

    InventoryItem bow = InventoryItem::make("Bow", 23.451f);
    for (int i = 0; i < 25; ++i)
    {
        InventoryItem arrow = InventoryItem::make(
            "arrow " + PropertyHelper<int>::toString(i), 0.2f);
        bow.d_items.push_back(arrow);
    }
    d_inventoryItems.push_back(bow);

    // generate *many* items :D
    for (int i = 1960; i < 2000; i += 2)
    {
        InventoryItem almanach = InventoryItem::make(
            "Almanach " + PropertyHelper<int>::toString(i), 0.34f);
        d_inventoryItems.push_back(almanach);
    }
}

//----------------------------------------------------------------------------//
bool InventoryModel::isValidIndex(const ModelIndex& model_index) const
{
    //TODO: check if we still have a reference to model_index.userdata?
    return model_index.d_modelData != 0;
}

//----------------------------------------------------------------------------//
CEGUI::ModelIndex InventoryModel::makeIndex(size_t child, const ModelIndex& parent_index)
{
    // root item
    if (parent_index.d_modelData == 0)
    {
        return makeValidIndex(child, d_inventoryItems);
    }

    InventoryItem* item = static_cast<InventoryItem*>(parent_index.d_modelData);

    return makeValidIndex(child, item->d_items);
}

//----------------------------------------------------------------------------//
CEGUI::ModelIndex InventoryModel::getParentIndex(const ModelIndex& model_index)
{
    return CEGUI::ModelIndex();
}

//----------------------------------------------------------------------------//
CEGUI::ModelIndex InventoryModel::getRootIndex()
{
    return ModelIndex();
}

//----------------------------------------------------------------------------//
size_t InventoryModel::getChildCount(const ModelIndex& model_index)
{
    if (model_index.d_modelData == 0)
        return d_inventoryItems.size();

    return static_cast<InventoryItem*>(model_index.d_modelData)->d_items.size();
}

//----------------------------------------------------------------------------//
CEGUI::String InventoryModel::getData(const ModelIndex& model_index, ItemDataRole role /*= IDR_Text*/)
{
    if (model_index.d_modelData == 0)
        return "";

    InventoryItem* item = static_cast<InventoryItem*>(model_index.d_modelData);
    if (role == CEGUI::IDR_Text)
        return item->d_name;

    return "";
}

//----------------------------------------------------------------------------//
void InventoryModel::clear()
{
    size_t items_count = d_inventoryItems.size();
    d_inventoryItems.clear();
    notifyChildrenRemoved(makeIndex(0, getRootIndex()), items_count);
}

//----------------------------------------------------------------------------//
void InventoryModel::addItem(InventoryItem& new_item)
{
    d_inventoryItems.insert(d_inventoryItems.begin(), new_item);

    //TODO: see how we specify that we added items starting *before* or *after* that start index
    notifyChildrenAdded(makeIndex(0, getRootIndex()), 1);
}

//----------------------------------------------------------------------------//
bool InventoryModel::areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2)
{
    return index1.d_modelData == index2.d_modelData;
}<commit_msg>Fix string creation from char<commit_after>/***********************************************************************
    filename:   Model.cpp
    created:    Tue May 27 2014
    author:     Timotei Dolean <timotei21@gmail.com>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "Model.h"
#include "CEGUI/PropertyHelper.h"

using namespace CEGUI;

template<typename T>
static ModelIndex makeValidIndex(size_t id, std::vector<T>& vector)
{
    if (id >= 0 && id < vector.size())
        return ModelIndex(&vector.at(id));

    return ModelIndex();
}

//----------------------------------------------------------------------------//
InventoryItem InventoryItem::make(const CEGUI::String& name, float weight)
{
    InventoryItem item;

    item.d_name = name;
    item.d_weight = weight;

    return item;
}

//----------------------------------------------------------------------------//
void InventoryModel::load()
{
    InventoryItem prev_matryoshka;
    // matryoshka D to A
    bool has_child = false;
    for (char chr = 'D'; chr >= 'A'; --chr)
    {
        InventoryItem matryoshka = InventoryItem::make("Matryoshka " + String(1, chr), 1.0f);

        if (has_child)
            matryoshka.d_items.push_back(prev_matryoshka);

        prev_matryoshka = matryoshka;
        has_child = true;
    }

    InventoryItem beans = InventoryItem::make("Beans!", 0.1f);
    InventoryItem beans_can = InventoryItem::make("Beans can", 1.0f);
    beans_can.d_items.push_back(beans);

    InventoryItem backpack = InventoryItem::make("Trip backpack", 2.0f);
    backpack.d_items.push_back(prev_matryoshka);
    backpack.d_items.push_back(beans_can);

    d_inventoryItems.push_back(backpack);

    InventoryItem bow = InventoryItem::make("Bow", 23.451f);
    for (int i = 0; i < 25; ++i)
    {
        InventoryItem arrow = InventoryItem::make(
            "arrow " + PropertyHelper<int>::toString(i), 0.2f);
        bow.d_items.push_back(arrow);
    }
    d_inventoryItems.push_back(bow);

    // generate *many* items :D
    for (int i = 1960; i < 2000; i += 2)
    {
        InventoryItem almanach = InventoryItem::make(
            "Almanach " + PropertyHelper<int>::toString(i), 0.34f);
        d_inventoryItems.push_back(almanach);
    }
}

//----------------------------------------------------------------------------//
bool InventoryModel::isValidIndex(const ModelIndex& model_index) const
{
    //TODO: check if we still have a reference to model_index.userdata?
    return model_index.d_modelData != 0;
}

//----------------------------------------------------------------------------//
CEGUI::ModelIndex InventoryModel::makeIndex(size_t child, const ModelIndex& parent_index)
{
    // root item
    if (parent_index.d_modelData == 0)
    {
        return makeValidIndex(child, d_inventoryItems);
    }

    InventoryItem* item = static_cast<InventoryItem*>(parent_index.d_modelData);

    return makeValidIndex(child, item->d_items);
}

//----------------------------------------------------------------------------//
CEGUI::ModelIndex InventoryModel::getParentIndex(const ModelIndex& model_index)
{
    return CEGUI::ModelIndex();
}

//----------------------------------------------------------------------------//
CEGUI::ModelIndex InventoryModel::getRootIndex()
{
    return ModelIndex();
}

//----------------------------------------------------------------------------//
size_t InventoryModel::getChildCount(const ModelIndex& model_index)
{
    if (model_index.d_modelData == 0)
        return d_inventoryItems.size();

    return static_cast<InventoryItem*>(model_index.d_modelData)->d_items.size();
}

//----------------------------------------------------------------------------//
CEGUI::String InventoryModel::getData(const ModelIndex& model_index, ItemDataRole role /*= IDR_Text*/)
{
    if (model_index.d_modelData == 0)
        return "";

    InventoryItem* item = static_cast<InventoryItem*>(model_index.d_modelData);
    if (role == CEGUI::IDR_Text)
        return item->d_name;

    return "";
}

//----------------------------------------------------------------------------//
void InventoryModel::clear()
{
    size_t items_count = d_inventoryItems.size();
    d_inventoryItems.clear();
    notifyChildrenRemoved(makeIndex(0, getRootIndex()), items_count);
}

//----------------------------------------------------------------------------//
void InventoryModel::addItem(InventoryItem& new_item)
{
    d_inventoryItems.insert(d_inventoryItems.begin(), new_item);

    //TODO: see how we specify that we added items starting *before* or *after* that start index
    notifyChildrenAdded(makeIndex(0, getRootIndex()), 1);
}

//----------------------------------------------------------------------------//
bool InventoryModel::areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2)
{
    return index1.d_modelData == index2.d_modelData;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: subtotal.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 10:16:21 $
 *
 *  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_SUBTOTAL_HXX
#define SC_SUBTOTAL_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

class SubTotal
{
private:
    long    nCount;
    long    nCount2;
    double  nSum;
    double  nSumSqr;
    double  nMax;
    double  nMin;
    double  nProduct;
    BOOL    bSumOk;
    BOOL    bSumSqrOk;
    BOOL    bProductOk;
    USHORT  nProgress;

public:
    SCSIZE  nIndex;         // Test

public:
            SubTotal();
            ~SubTotal();

    void    UpdateNoVal();
    void    Update( double nVal );
    void    Update( const SubTotal& rVal );

    short   Valid( USHORT nFunction ) const;
                            // return 0 => Fehler, -1 => kein Wert, 1 => ok
    double  Result( USHORT nFunction ) const;
    static  BOOL SafePlus( double& fVal1, double fVal2);
    static  BOOL SafeMult( double& fVal1, double fVal2);
    static  BOOL SafeDiv( double& fVal1, double fVal2);
};

struct ScFunctionData                   // zum Berechnen von einzelnen Funktionen
{
    ScSubTotalFunc  eFunc;
    double          nVal;
    long            nCount;
    BOOL            bError;

    ScFunctionData( ScSubTotalFunc eFn ) :
        eFunc(eFn), nVal(0.0), nCount(0), bError(FALSE) {}
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.452); FILE MERGED 2005/09/05 15:01:02 rt 1.3.452.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: subtotal.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:59:26 $
 *
 *  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 SC_SUBTOTAL_HXX
#define SC_SUBTOTAL_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

class SubTotal
{
private:
    long    nCount;
    long    nCount2;
    double  nSum;
    double  nSumSqr;
    double  nMax;
    double  nMin;
    double  nProduct;
    BOOL    bSumOk;
    BOOL    bSumSqrOk;
    BOOL    bProductOk;
    USHORT  nProgress;

public:
    SCSIZE  nIndex;         // Test

public:
            SubTotal();
            ~SubTotal();

    void    UpdateNoVal();
    void    Update( double nVal );
    void    Update( const SubTotal& rVal );

    short   Valid( USHORT nFunction ) const;
                            // return 0 => Fehler, -1 => kein Wert, 1 => ok
    double  Result( USHORT nFunction ) const;
    static  BOOL SafePlus( double& fVal1, double fVal2);
    static  BOOL SafeMult( double& fVal1, double fVal2);
    static  BOOL SafeDiv( double& fVal1, double fVal2);
};

struct ScFunctionData                   // zum Berechnen von einzelnen Funktionen
{
    ScSubTotalFunc  eFunc;
    double          nVal;
    long            nCount;
    BOOL            bError;

    ScFunctionData( ScSubTotalFunc eFn ) :
        eFunc(eFn), nVal(0.0), nCount(0), bError(FALSE) {}
};

#endif

<|endoftext|>