<commit_before>/*
 * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * libbitcoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <cstdint>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <boost/format.hpp>
#include <boost/test/unit_test.hpp>
#include <bitcoin/bitcoin.hpp>
#include "script_number.hpp"
#ifdef ENABLE_DATAGEN
#include "big_number.hpp"
#endif

using namespace bc;

BOOST_AUTO_TEST_SUITE(scriptnum_tests)

// Helpers
// ----------------------------------------------------------------------------

#define BC_SCRIPT_NUMBER_CHECK_EQ(buffer_num, script_num) \
    BOOST_CHECK_EQUAL(bc::encode_hex((buffer_num).bytes), \
        bc::encode_hex((script_num).data())); \
    BOOST_CHECK_EQUAL((buffer_num).number, (script_num).int32())

static bool is(const uint8_t byte)
{
    return byte != 0;
}

// check left - right
static bool subtract_overflow64(const int64_t left, const int64_t right)
{
    return
        ((right > 0 && left < std::numeric_limits<int64_t>::min() + right) ||
        (right < 0 && left > std::numeric_limits<int64_t>::max() + right));
}

static bool add_overflow64(const int64_t left, const int64_t right)
{
    return
        ((right > 0 && left > (std::numeric_limits<int64_t>::max() - right)) ||
        (right < 0 && left < (std::numeric_limits<int64_t>::min() - right)));
}

static bool negate_overflow64(const int64_t number)
{
    return number == std::numeric_limits<int64_t>::min();
}

// Operators
// ----------------------------------------------------------------------------

static void CheckAdd(const int64_t num1, const int64_t num2,
    const script_number_buffer& add)
{
    const script_number scriptnum1(num1);
    const script_number scriptnum2(num2);

    if (!add_overflow64(num1, num2))
    {
        BC_SCRIPT_NUMBER_CHECK_EQ(add, scriptnum1 + scriptnum2);
        BC_SCRIPT_NUMBER_CHECK_EQ(add, scriptnum1 + num2);
        BC_SCRIPT_NUMBER_CHECK_EQ(add, scriptnum2 + num1);
    }
}

static void CheckNegate(const int64_t number,
    const script_number_buffer& negated)
{
    const script_number scriptnum(number);

    if (!negate_overflow64(number))
    {
        BC_SCRIPT_NUMBER_CHECK_EQ(negated, -scriptnum);
    }
}

static void CheckSubtract(const int64_t num1, const int64_t num2,
    const script_number_subtract& subtract)
{
    const script_number scriptnum1(num1);
    const script_number scriptnum2(num2);

    if (!subtract_overflow64(num1, num2))
    {
        BC_SCRIPT_NUMBER_CHECK_EQ(subtract.forward, scriptnum1 - scriptnum2);
        BC_SCRIPT_NUMBER_CHECK_EQ(subtract.forward, scriptnum1 - num2);
    }

    if (!subtract_overflow64(num2, num1))
    {
        BC_SCRIPT_NUMBER_CHECK_EQ(subtract.reverse, scriptnum2 - scriptnum1);
        BC_SCRIPT_NUMBER_CHECK_EQ(subtract.reverse, scriptnum2 - num1);
    }
}

static void CheckCompare(const int64_t num1, const int64_t num2,
    const script_number_compare& compare)
{
    const script_number scriptnum1(num1);
    const script_number scriptnum2(num2);

    BOOST_CHECK(scriptnum1 == scriptnum1);
    BOOST_CHECK(scriptnum1 >= scriptnum1);
    BOOST_CHECK(scriptnum1 <= scriptnum1);
    BOOST_CHECK(!(scriptnum1 != scriptnum1));
    BOOST_CHECK(!(scriptnum1 < scriptnum1));
    BOOST_CHECK(!(scriptnum1 > scriptnum1));

    BOOST_CHECK(scriptnum1 == num1);
    BOOST_CHECK(scriptnum1 >= num1);
    BOOST_CHECK(scriptnum1 <= num1);
    BOOST_CHECK(!(scriptnum1 != num1));
    BOOST_CHECK(!(scriptnum1 < num1));
    BOOST_CHECK(!(scriptnum1 > num1));

    BOOST_CHECK_EQUAL(is(compare.eq), (scriptnum1 == scriptnum2));
    BOOST_CHECK_EQUAL(is(compare.ne), (scriptnum1 != scriptnum2));
    BOOST_CHECK_EQUAL(is(compare.lt), (scriptnum1 < scriptnum2));
    BOOST_CHECK_EQUAL(is(compare.gt), (scriptnum1 > scriptnum2));
    BOOST_CHECK_EQUAL(is(compare.ge), (scriptnum1 >= scriptnum2));
    BOOST_CHECK_EQUAL(is(compare.le), (scriptnum1 <= scriptnum2));

    BOOST_CHECK_EQUAL(is(compare.eq), (scriptnum1 == num2));
    BOOST_CHECK_EQUAL(is(compare.ne), (scriptnum1 != num2));
    BOOST_CHECK_EQUAL(is(compare.lt), (scriptnum1 < num2));
    BOOST_CHECK_EQUAL(is(compare.gt), (scriptnum1 > num2));
    BOOST_CHECK_EQUAL(is(compare.ge), (scriptnum1 >= num2));
    BOOST_CHECK_EQUAL(is(compare.le), (scriptnum1 <= num2));
}

#ifndef ENABLE_DATAGEN

static void RunOperators(const int64_t num1, const int64_t num2,
    const size_t value, const size_t offset, const size_t test)
{
    std::stringstream message;
    std::cout << boost::format(
        ">>> RunOperators: %1% : %2% : %3% : %4% : %5%\n")
        % num1 % num2 % value % offset % test;
    BOOST_MESSAGE(message.str());

    CheckAdd(num1, num2, script_number_adds[value][offset][test]);
    CheckSubtract(num1, num2, script_number_subtracts[value][offset][test]);
    CheckNegate(num1, script_number_negates[value][offset][test]);
    CheckCompare(num1, num2, script_number_compares[value][offset][test]);
}

BOOST_AUTO_TEST_CASE(check_operators)
{
    for (size_t i = 0; i < script_number_values_count; ++i)
    {
        for (size_t j = 0; j < script_number_offsets_count; ++j)
        {
            auto a = script_number_values[i];
            auto b = script_number_offsets[j];

            RunOperators(a, +a,         i, j, 0);
            RunOperators(a, -a,         i, j, 1);
            RunOperators(a, +b,         i, j, 2);
            RunOperators(a, -b,         i, j, 3);
            RunOperators(a + b, +b,     i, j, 4);
            RunOperators(a + b, -b,     i, j, 5);
            RunOperators(a - b, +b,     i, j, 6);
            RunOperators(a - b, -b,     i, j, 7);
            RunOperators(a + b, +a + b, i, j, 8);
            RunOperators(a + b, +a - b, i, j, 9);
            RunOperators(a - b, +a + b, i, j, 10);
            RunOperators(a - b, +a - b, i, j, 11);
        }
    }
}

#else

std::stringstream expectations;

static std::string format_bytes(bc::data_chunk chunk)
{
    std::stringstream buffer;
    buffer << "{";

    for (const auto& byte : chunk)
        buffer << (boost::format(" 0x%02x, ") % static_cast<uint16_t>(byte));

    buffer << "}";
    return buffer.str();
}

static script_number_buffer MakeAdd(const int64_t num1, const int64_t num2)
{
    if (add_overflow64(num1, num2))
        return script_number_buffer();

    big_number bignum1;
    bignum1.set_int64(num1);

    big_number bignum2;
    bignum2.set_int64(num2);

    auto sum = bignum1 + bignum2;
    const script_number_buffer add
    {
        sum.int32(),
        sum.data()
    };

    // Side effect is used to generate the test expectation vector.
    expectations << boost::format("{ %1%, %2% }, ") %
        add.number % format_bytes(add.bytes);

    // Return value is used for verifying the result.
    return add;
}

static script_number_buffer MakeNegate(const int64_t number)
{
    if (negate_overflow64(number))
        return script_number_buffer();

    big_number bignum;
    bignum.set_int64(number);

    auto negative = -bignum;
    const script_number_buffer negated
    {
        negative.int32(),
        negative.data()
    };

    // Side effect is used to generate the test expectation vector.
    expectations << boost::format("{ %1%, %2% }, ") %
        negated.number % format_bytes(negated.bytes);

    // Return value is used for verifying the result.
    return negated;
}

static script_number_subtract MakeSubtract(const int64_t num1,
    const int64_t num2)
{
    big_number bignum1;
    bignum1.set_int64(num1);
    big_number bignum2;
    bignum2.set_int64(num2);

    big_number forward;
    if (!subtract_overflow64(num1, num2))
        forward = bignum1 - bignum2;

    big_number reverse;
    if (!subtract_overflow64(num2, num1))
        reverse = bignum2 - bignum1;

    const script_number_subtract subtract
    {
        { forward.int32(), forward.data() },
        { reverse.int32(), reverse.data() }
    };

    // Side effect is used to generate the test expectation vector.
    expectations << boost::format("{ { %1%, %2% }, { %3%, %4% } }, ") %
        subtract.forward.number % format_bytes(subtract.forward.bytes) %
        subtract.reverse.number % format_bytes(subtract.reverse.bytes);

    // Return value is used for verifying the result.
    return subtract;
}

static script_number_compare MakeCompare(const int64_t num1,
    const int64_t num2)
{
    big_number bignum1;
    bignum1.set_int64(num1);
    big_number bignum2;
    bignum2.set_int64(num2);

    script_number_compare compare
    {
        bignum1 == bignum2,
        bignum1 != bignum2,
        bignum1 < bignum2,
        bignum1 > bignum2,
        bignum1 <= bignum2,
        bignum1 >= bignum2
    };

    // Side effect is used to generate the test expectation vector.
    expectations <<
        boost::format("{ %1%, %2%, %3%, %4%, %5%, %6% },") % compare.eq %
        compare.ne % compare.lt % compare.gt % compare.le % compare.ge;

    // Return value is used for verifying the result.
    return compare;
}

static void MakeOperators(const int64_t num1, const int64_t num2)
{
    // Enable individually to build expectation vector.
    CheckAdd(num1, num2, MakeAdd(num1, num2));
    //CheckSubtract(num1, num2, MakeSubtract(num1, num2));
    //CheckNegate(num1, MakeNegate(num1));
    //CheckCompare(num1, num2, MakeCompare(num1, num2));
}

BOOST_AUTO_TEST_CASE(make_operator_expectations)
{
    expectations << boost::format("[%1%][%2%][%3%]=\n{\n") %
        script_number_values_count % script_number_offsets_count % 12;

    for (size_t i = 7; i < script_number_values_count; ++i)
    {
        expectations << "    {\n";
        for (size_t j = 0; j < script_number_offsets_count; ++j)
        {
            expectations << "        {";

            auto a = script_number_values[i];
            auto b = script_number_offsets[j];

            expectations << "\n              ";
            MakeOperators(a, +a);
            expectations << "\n              ";
            MakeOperators(a, -a);
            expectations << "\n              ";
            MakeOperators(a, +b);
            expectations << "\n              ";
            MakeOperators(a, -b);
            expectations << "\n              ";
            MakeOperators(a + b, +b);
            expectations << "\n              ";
            MakeOperators(a + b, -b);
            expectations << "\n              ";
            MakeOperators(a - b, +b);
            expectations << "\n              ";
            MakeOperators(a - b, -b);
            expectations << "\n              ";
            MakeOperators(a + b, +a + b);
            expectations << "\n              ";
            MakeOperators(a + b, +a - b);
            expectations << "\n              ";
            MakeOperators(a - b, +a + b);
            expectations << "\n              ";
            MakeOperators(a - b, +a - b);
            expectations << "\n        },\n";
        }

        expectations << "    },\n";
    }

    expectations << "};\n";

    // Copy from debug buffer to source code expectation vector.
    const auto& dump = expectations.str();
}
#endif

BOOST_AUTO_TEST_SUITE_END()<commit_msg>Complete datagen implementation.<commit_after>/*
 * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * libbitcoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <cstdint>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <boost/format.hpp>
#include <boost/test/unit_test.hpp>
#include <bitcoin/bitcoin.hpp>
#include "script_number.hpp"
#ifdef ENABLE_DATAGEN
#include "big_number.hpp"
#endif

using namespace bc;

BOOST_AUTO_TEST_SUITE(scriptnum_tests)

// Helpers
// ----------------------------------------------------------------------------

#define BC_SCRIPT_NUMBER_CHECK_EQ(buffer_num, script_num) \
    BOOST_CHECK_EQUAL(bc::encode_hex((buffer_num).bytes), \
        bc::encode_hex((script_num).data())); \
    BOOST_CHECK_EQUAL((buffer_num).number, (script_num).int32())

static bool is(const uint8_t byte)
{
    return byte != 0;
}

// check left - right
static bool subtract_overflow64(const int64_t left, const int64_t right)
{
    return
        ((right > 0 && left < std::numeric_limits<int64_t>::min() + right) ||
        (right < 0 && left > std::numeric_limits<int64_t>::max() + right));
}

static bool add_overflow64(const int64_t left, const int64_t right)
{
    return
        ((right > 0 && left > (std::numeric_limits<int64_t>::max() - right)) ||
        (right < 0 && left < (std::numeric_limits<int64_t>::min() - right)));
}

static bool negate_overflow64(const int64_t number)
{
    return number == std::numeric_limits<int64_t>::min();
}

// Operators
// ----------------------------------------------------------------------------

static void CheckAdd(const int64_t num1, const int64_t num2,
    const script_number_buffer& add)
{
    const script_number scriptnum1(num1);
    const script_number scriptnum2(num2);

    if (!add_overflow64(num1, num2))
    {
        BC_SCRIPT_NUMBER_CHECK_EQ(add, scriptnum1 + scriptnum2);
        BC_SCRIPT_NUMBER_CHECK_EQ(add, scriptnum1 + num2);
        BC_SCRIPT_NUMBER_CHECK_EQ(add, scriptnum2 + num1);
    }
}

static void CheckNegate(const int64_t number,
    const script_number_buffer& negated)
{
    const script_number scriptnum(number);

    if (!negate_overflow64(number))
    {
        BC_SCRIPT_NUMBER_CHECK_EQ(negated, -scriptnum);
    }
}

static void CheckSubtract(const int64_t num1, const int64_t num2,
    const script_number_subtract& subtract)
{
    const script_number scriptnum1(num1);
    const script_number scriptnum2(num2);

    if (!subtract_overflow64(num1, num2))
    {
        BC_SCRIPT_NUMBER_CHECK_EQ(subtract.forward, scriptnum1 - scriptnum2);
        BC_SCRIPT_NUMBER_CHECK_EQ(subtract.forward, scriptnum1 - num2);
    }

    if (!subtract_overflow64(num2, num1))
    {
        BC_SCRIPT_NUMBER_CHECK_EQ(subtract.reverse, scriptnum2 - scriptnum1);
        BC_SCRIPT_NUMBER_CHECK_EQ(subtract.reverse, scriptnum2 - num1);
    }
}

static void CheckCompare(const int64_t num1, const int64_t num2,
    const script_number_compare& compare)
{
    const script_number scriptnum1(num1);
    const script_number scriptnum2(num2);

    BOOST_CHECK(scriptnum1 == scriptnum1);
    BOOST_CHECK(scriptnum1 >= scriptnum1);
    BOOST_CHECK(scriptnum1 <= scriptnum1);
    BOOST_CHECK(!(scriptnum1 != scriptnum1));
    BOOST_CHECK(!(scriptnum1 < scriptnum1));
    BOOST_CHECK(!(scriptnum1 > scriptnum1));

    BOOST_CHECK(scriptnum1 == num1);
    BOOST_CHECK(scriptnum1 >= num1);
    BOOST_CHECK(scriptnum1 <= num1);
    BOOST_CHECK(!(scriptnum1 != num1));
    BOOST_CHECK(!(scriptnum1 < num1));
    BOOST_CHECK(!(scriptnum1 > num1));

    BOOST_CHECK_EQUAL(is(compare.eq), (scriptnum1 == scriptnum2));
    BOOST_CHECK_EQUAL(is(compare.ne), (scriptnum1 != scriptnum2));
    BOOST_CHECK_EQUAL(is(compare.lt), (scriptnum1 < scriptnum2));
    BOOST_CHECK_EQUAL(is(compare.gt), (scriptnum1 > scriptnum2));
    BOOST_CHECK_EQUAL(is(compare.ge), (scriptnum1 >= scriptnum2));
    BOOST_CHECK_EQUAL(is(compare.le), (scriptnum1 <= scriptnum2));

    BOOST_CHECK_EQUAL(is(compare.eq), (scriptnum1 == num2));
    BOOST_CHECK_EQUAL(is(compare.ne), (scriptnum1 != num2));
    BOOST_CHECK_EQUAL(is(compare.lt), (scriptnum1 < num2));
    BOOST_CHECK_EQUAL(is(compare.gt), (scriptnum1 > num2));
    BOOST_CHECK_EQUAL(is(compare.ge), (scriptnum1 >= num2));
    BOOST_CHECK_EQUAL(is(compare.le), (scriptnum1 <= num2));
}

#ifndef ENABLE_DATAGEN

// Test
// ----------------------------------------------------------------------------

static void RunOperators(const int64_t num1, const int64_t num2,
    const size_t value, const size_t offset, const size_t test)
{
    //// Diagnostics
    //std::stringstream message;
    //std::cout << boost::format(
    //    ">>> RunOperators: %1% : %2% : %3% : %4% : %5%\n")
    //    % num1 % num2 % value % offset % test;
    //BOOST_MESSAGE(message.str());

    CheckAdd(num1, num2, script_number_adds[value][offset][test]);
    CheckNegate(num1, script_number_negates[value][offset][test]);
    CheckSubtract(num1, num2, script_number_subtracts[value][offset][test]);
    CheckCompare(num1, num2, script_number_compares[value][offset][test]);
}

BOOST_AUTO_TEST_CASE(check_operators)
{
    for (size_t i = 0; i < script_number_values_count; ++i)
    {
        for (size_t j = 0; j < script_number_offsets_count; ++j)
        {
            auto a = script_number_values[i];
            auto b = script_number_offsets[j];

            RunOperators(a, +a,         i, j, 0);
            RunOperators(a, -a,         i, j, 1);
            RunOperators(a, +b,         i, j, 2);
            RunOperators(a, -b,         i, j, 3);
            RunOperators(a + b, +b,     i, j, 4);
            RunOperators(a + b, -b,     i, j, 5);
            RunOperators(a - b, +b,     i, j, 6);
            RunOperators(a - b, -b,     i, j, 7);
            RunOperators(a + b, +a + b, i, j, 8);
            RunOperators(a + b, +a - b, i, j, 9);
            RunOperators(a - b, +a + b, i, j, 10);
            RunOperators(a - b, +a - b, i, j, 11);
        }
    }
}

#else

// big_number value generators
// ----------------------------------------------------------------------------

static script_number_buffer MakeAdd(const int64_t num1, const int64_t num2)
{
    if (add_overflow64(num1, num2))
        return script_number_buffer();

    big_number bignum1;
    bignum1.set_int64(num1);
    big_number bignum2;
    bignum2.set_int64(num2);

    auto sum = bignum1 + bignum2;
    const script_number_buffer add
    {
        sum.int32(),
        sum.data()
    };

    return add;
}

static script_number_buffer MakeNegate(const int64_t number)
{
    if (negate_overflow64(number))
        return script_number_buffer();

    big_number bignum;
    bignum.set_int64(number);

    auto negative = -bignum;
    const script_number_buffer negated
    {
        negative.int32(),
        negative.data()
    };

    return negated;
}

static script_number_subtract MakeSubtract(const int64_t num1,
    const int64_t num2)
{
    big_number bignum1;
    bignum1.set_int64(num1);
    big_number bignum2;
    bignum2.set_int64(num2);

    big_number forward;
    if (!subtract_overflow64(num1, num2))
        forward = bignum1 - bignum2;

    big_number reverse;
    if (!subtract_overflow64(num2, num1))
        reverse = bignum2 - bignum1;

    const script_number_subtract subtract
    {
        { forward.int32(), forward.data() },
        { reverse.int32(), reverse.data() }
    };

    return subtract;
}

static script_number_compare MakeCompare(const int64_t num1,
    const int64_t num2)
{
    big_number bignum1;
    bignum1.set_int64(num1);
    big_number bignum2;
    bignum2.set_int64(num2);

    script_number_compare compare
    {
        bignum1 == bignum2,
        bignum1 != bignum2,
        bignum1 < bignum2,
        bignum1 > bignum2,
        bignum1 <= bignum2,
        bignum1 >= bignum2
    };

    return compare;
}

// Formatter Helpers
// ----------------------------------------------------------------------------

static void write_bytes(bc::data_chunk chunk, std::ostream& out)
{
    for (const auto& byte : chunk)
        out << (boost::format(" 0x%02x, ") % static_cast<uint16_t>(byte));
}

static void write_buffer(script_number_buffer buffer, std::ostream& out)
{
    out << boost::format("{ %1%, {") % buffer.number;
    write_bytes(buffer.bytes, out);
    out << "} }, ";
}

static void write_compare(script_number_compare compare, std::ostream& out)
{
    out << boost::format("{ %1%, %2%, %3%, %4%, %5%, %6% }, ") % compare.eq %
        compare.ne % compare.lt % compare.gt % compare.le % compare.ge;
}

static void write_subtract(script_number_subtract subtract, std::ostream& out)
{
    out << "{ ";
    write_buffer(subtract.forward, out);
    write_buffer(subtract.reverse, out);
    out << "}, ";
}

static void write_names(const std::string& name, size_t count,
    std::ostream& out)
{
    out << boost::format("const %1%[%2%][%3%][%4%]=\n{\n") % name %
        script_number_values_count % script_number_offsets_count % count;
}

static void write(const std::string& text, std::ostream& add_out,
    std::ostream& neg_out, std::ostream& sub_out, std::ostream& cmp_out)
{
    add_out << text;
    neg_out << text;
    sub_out << text;
    cmp_out << text;
}

static void replace(std::string& buffer, const std::string& find,
    const std::string& replacement)
{
    size_t pos = 0;
    while ((pos = buffer.find(find, pos)) != std::string::npos)
    {
        buffer.replace(pos, find.length(), replacement);
        pos += replacement.length();
    }
}

// Maker
// ----------------------------------------------------------------------------

static void MakeOperators(const int64_t num1, const int64_t num2,
    std::ostream& add_out, std::ostream& neg_out, std::ostream& sub_out,
    std::ostream& cmp_out)
{
    write("\n              ", add_out, neg_out, sub_out, cmp_out);

    auto add = MakeAdd(num1, num2);
    CheckAdd(num1, num2, add);
    write_buffer(add, add_out);

    auto negate = MakeNegate(num1);
    CheckNegate(num1, negate);
    write_buffer(negate, neg_out);

    auto subtract = MakeSubtract(num1, num2);
    CheckSubtract(num1, num2, subtract);
    write_subtract(subtract, sub_out);

    auto compare = MakeCompare(num1, num2);
    CheckCompare(num1, num2, compare);
    write_compare(compare, cmp_out);
}

BOOST_AUTO_TEST_CASE(make_operator_expectations)
{
    std::stringstream add_out;
    std::stringstream neg_out;
    std::stringstream sub_out;
    std::stringstream cmp_out;

    write_names("script_number_buffer script_number_adds", 12, add_out);
    write_names("script_number_buffer script_number_negates", 12, neg_out);
    write_names("script_number_subtract script_number_subtracts", 12, sub_out);
    write_names("script_number_compare script_number_compares", 12, cmp_out);

    for (size_t i = 0; i < script_number_values_count; ++i)
    {
        write("    {\n", add_out, neg_out, sub_out, cmp_out);

        for (size_t j = 0; j < script_number_offsets_count; ++j)
        {
            write("        {", add_out, neg_out, sub_out, cmp_out);

            auto a = script_number_values[i];
            auto b = script_number_offsets[j];

            MakeOperators(a, +a, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a, -a, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a, +b, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a, -b, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a + b, +b, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a + b, -b, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a - b, +b, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a - b, -b, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a + b, +a + b, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a + b, +a - b, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a - b, +a + b, add_out, neg_out, sub_out, cmp_out);
            MakeOperators(a - b, +a - b, add_out, neg_out, sub_out, cmp_out);

            write("\n        },\n", add_out, neg_out, sub_out, cmp_out);
        }

        write("    },\n", add_out, neg_out, sub_out, cmp_out);
    }

    write("};\n", add_out, neg_out, sub_out, cmp_out);

    std::stringstream dump;
    dump << add_out.str();
    dump << neg_out.str();
    dump << sub_out.str();
    dump << cmp_out.str();

    auto source = dump.str();
    replace(source, "-2147483648", "(-2147483647 - 1)");
    replace(source, "-9223372036854775808", "(-9223372036854775807 - 1)");
}
#endif

BOOST_AUTO_TEST_SUITE_END()<|endoftext|>


<commit_before>#include "momentum.h"
#include <boost/unordered_map.hpp>
#include <iostream>

namespace bts
{
uint64_t getBirthdayHash(const uint256 &midHash, uint32_t a);

#define MAX_MOMENTUM_NONCE ( 1<<26 )
#define SEARCH_SPACE_BITS  ( 50 )
#define BIRTHDAYS_PER_HASH ( 8 )

#define DEBUG_MODE ( 0 )

///// UTILITY FUNCTIONS /////

// Compresses "hash" to within MAX_MOMENTUM_NONCE space
#define COMPRESS_CHUNK(chunk) ( chunk % MAX_MOMENTUM_NONCE )
#define COMPRESS_HASH(hash)   ( COMPRESS_CHUNK(hash[0]) )

// HASH is a wrapper for SHA512
// It creates BIRTHDAYS_PER_HASH elements, each one
//   right shifted by (64 - SEARCH_SPACE_BITS)
#define HASH(input, temp, output)                                         \
{                                                                         \
    *hash_input = input;                                                  \
    SHA512((unsigned char *)temp, sizeof(temp), (unsigned char *)output); \
    output[0] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[1] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[2] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[3] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[4] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[5] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[6] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[7] >>= (64 - SEARCH_SPACE_BITS);                               \
}

// Given a hash chunk "cur_hash", if it exists in
//   "hash_list", return the index, else -1.
#define CONTAINS_HASH(cur_chunk, hash_list) \
    (cur_chunk == hash_list[0] ? 0 :        \
     cur_chunk == hash_list[1] ? 1 :        \
     cur_chunk == hash_list[2] ? 2 :        \
     cur_chunk == hash_list[3] ? 3 :        \
     cur_chunk == hash_list[4] ? 4 :        \
     cur_chunk == hash_list[5] ? 5 :        \
     cur_chunk == hash_list[6] ? 6 :        \
     cur_chunk == hash_list[7] ? 7 :        \
     0xFF)

#define PRINT_HASH(hash)                         \
{                                                \
std::cerr << "         0: " << hash[0] << "\n"   \
          << "         1: " << hash[1] << "\n"   \
          << "         2: " << hash[2] << "\n"   \
          << "         3: " << hash[3] << "\n"   \
          << "         4: " << hash[4] << "\n"   \
          << "         5: " << hash[5] << "\n"   \
          << "         6: " << hash[6] << "\n"   \
          << "         7: " << hash[7] << "\n";  \
}

#define COPY_HASH(src, dst) \
{                           \
    dst[0] = src[0];        \
    dst[1] = src[1];        \
    dst[2] = src[2];        \
    dst[3] = src[3];        \
    dst[4] = src[4];        \
    dst[5] = src[5];        \
    dst[6] = src[6];        \
    dst[7] = src[7];        \
}

///// MAIN HASH /////

std::vector< std::pair<uint32_t, uint32_t> > momentum_search(uint256 midHash)
{
    std::vector< std::pair<uint32_t, uint32_t> > results;

    char hash_temp[sizeof(uint256) + 4];
    memcpy((char *)&hash_temp[4], (char *)&midHash, sizeof(midHash));
    uint32_t *hash_input = (uint32_t *)hash_temp;
    uint64_t result_hash[8];

    // Floyd's cycle-finding algorithm
    uint32_t power = 1;
    uint32_t lam = 1;

    uint64_t turtle_hash[8];
    uint32_t turtle_nonce = 0;

    uint64_t hare_hash[8];
    uint32_t hare_nonce = 0;

    // Turtle = X_0
    HASH(0, hash_temp, turtle_hash);

    // Hare = F(X_0)
    hare_nonce = COMPRESS_HASH(result_hash);
    HASH(hare_nonce, hash_temp, hare_hash);

    while (power <= MAX_MOMENTUM_NONCE) {
        for (uint32_t chunk = 0; chunk < BIRTHDAYS_PER_HASH; ++chunk) {
            uint32_t offset = CONTAINS_HASH(hare[chunk], turtle_hash);

            if (offset != 0xFF) {
                if (DEBUG) {
                    std::cerr << "Found hit PART 1\n";
                    std::cerr << "Hare Nonce: " << hare_nonce << " + " << chunk << "\n";
                    PRINT_HASH(hare_hash);
                    std::cerr << "Trtl Nonce: " << turtle_nonce << " + " << offset << "\n";
                    PRITN_HASH(turtle_hash);
                }

                break;
            }
        }

        if (power == lam) {
            COPY_HASH(hare_hash, turtle_hash);
            turtle_nonce = hare_nonce;
            power <<= 1;
            lam = 0;
        }

        hare_nonce = COMPRESS_HASH(hare_hash);
        HASH(hare_nonce, hash_temp, hare_hash);
        ++lam;
    }

    // Nothing found, give up.
    if (power >= MAX_MOMENTUM_NONCE) { return results; }

    // Rewind to find first repetition of nonces
    turtle_nonce = 0;
    HASH(turtle_nonce, hash_temp, turtle_hash);
    hare_nonce = 0;
    HASH_COPY(turtle_hash, hare_hash);

    // Get hare up to speed
    for (uint32_t fastforward = 0; fastforward < lam; ++fastforward) {
        hare_nonce = COMPRESS_HASH(hare_hash);
        HASH(hare_nonce, hash_temp, hare_hash);
    }

    // Keep stepping until they match again
    while (true) {
        for (uint32_t chunk = 0; chunk < BIRTHDAYS_PER_HASH; ++chunk) {
            uint32_t offset = CONTAINS_HASH(hare[chunk], turtle_hash);

            if (offset != 0xFF) {
                if (DEBUG) {
                    std::cerr << "Found hit PART 2\n";
                    std::cerr << "Hare Nonce: " << hare_nonce << " + " << chunk << "\n";
                    PRINT_HASH(hare_hash);
                    std::cerr << "Trtl Nonce: " << turtle_nonce << " + " << offset << "\n";
                    PRITN_HASH(turtle_hash);
                }

                results.push_back( std::make_pair( hare_nonce + chunk, turtle_nonce + offset ) );
                return results;
            }
        }

        turtle_nonce = COMPRESS_HASH(turtle_hash);
        HASH(turtle_nonce, hash_temp, turtle_hash);

        hare_nonce = COMPRESS_HASH(hare_hash);
        HASH(hare_nonce, hash_temp, hare_hash);
    }

    std::cerr << "You should never be here!\n";

    return results;
}

uint64_t getBirthdayHash(const uint256 &midHash, uint32_t a)
{
    uint32_t index = a - (a % 8);
    char  hash_tmp[sizeof(midHash) + 4];

    memcpy(&hash_tmp[4], (char *)&midHash, sizeof(midHash));
    memcpy(&hash_tmp[0], (char *)&index, sizeof(index));

    uint64_t  result_hash[8];

    SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)&result_hash);

    uint64_t r = result_hash[a % BIRTHDAYS_PER_HASH] >> (64 - SEARCH_SPACE_BITS);

    return r;
}

bool momentum_verify(uint256 head, uint32_t a, uint32_t b)
{
    if(a == b) {
        return false;
    }

    if(a > MAX_MOMENTUM_NONCE) {
        return false;
    }

    if(b > MAX_MOMENTUM_NONCE) {
        return false;
    }

    bool r = (getBirthdayHash(head, a) == getBirthdayHash(head, b));
    return r;
}

}
<commit_msg>More syntax fixes<commit_after>#include "momentum.h"
#include <boost/unordered_map.hpp>
#include <iostream>

namespace bts
{
uint64_t getBirthdayHash(const uint256 &midHash, uint32_t a);

#define MAX_MOMENTUM_NONCE ( 1<<26 )
#define SEARCH_SPACE_BITS  ( 50 )
#define BIRTHDAYS_PER_HASH ( 8 )

#define DEBUG_MODE ( 0 )

///// UTILITY FUNCTIONS /////

// Compresses "hash" to within MAX_MOMENTUM_NONCE space
#define COMPRESS_CHUNK(chunk) ( chunk % MAX_MOMENTUM_NONCE )
#define COMPRESS_HASH(hash)   ( COMPRESS_CHUNK(hash[0]) )

// HASH is a wrapper for SHA512
// It creates BIRTHDAYS_PER_HASH elements, each one
//   right shifted by (64 - SEARCH_SPACE_BITS)
#define HASH(input, temp, output)                                         \
{                                                                         \
    *hash_input = input;                                                  \
    SHA512((unsigned char *)temp, sizeof(temp), (unsigned char *)output); \
    output[0] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[1] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[2] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[3] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[4] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[5] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[6] >>= (64 - SEARCH_SPACE_BITS);                               \
    output[7] >>= (64 - SEARCH_SPACE_BITS);                               \
}

// Given a hash chunk "cur_hash", if it exists in
//   "hash_list", return the index, else -1.
#define CONTAINS_HASH(cur_chunk, hash_list) \
    (cur_chunk == hash_list[0] ? 0 :        \
     cur_chunk == hash_list[1] ? 1 :        \
     cur_chunk == hash_list[2] ? 2 :        \
     cur_chunk == hash_list[3] ? 3 :        \
     cur_chunk == hash_list[4] ? 4 :        \
     cur_chunk == hash_list[5] ? 5 :        \
     cur_chunk == hash_list[6] ? 6 :        \
     cur_chunk == hash_list[7] ? 7 :        \
     0xFF)

#define PRINT_HASH(hash)                         \
{                                                \
std::cerr << "         0: " << hash[0] << "\n"   \
          << "         1: " << hash[1] << "\n"   \
          << "         2: " << hash[2] << "\n"   \
          << "         3: " << hash[3] << "\n"   \
          << "         4: " << hash[4] << "\n"   \
          << "         5: " << hash[5] << "\n"   \
          << "         6: " << hash[6] << "\n"   \
          << "         7: " << hash[7] << "\n";  \
}

#define COPY_HASH(src, dst) \
{                           \
    dst[0] = src[0];        \
    dst[1] = src[1];        \
    dst[2] = src[2];        \
    dst[3] = src[3];        \
    dst[4] = src[4];        \
    dst[5] = src[5];        \
    dst[6] = src[6];        \
    dst[7] = src[7];        \
}

///// MAIN HASH /////

std::vector< std::pair<uint32_t, uint32_t> > momentum_search(uint256 midHash)
{
    std::vector< std::pair<uint32_t, uint32_t> > results;

    char hash_temp[sizeof(uint256) + 4];
    memcpy((char *)&hash_temp[4], (char *)&midHash, sizeof(midHash));
    uint32_t *hash_input = (uint32_t *)hash_temp;
    uint64_t result_hash[8];

    // Floyd's cycle-finding algorithm
    uint32_t power = 1;
    uint32_t lam = 1;

    uint64_t turtle_hash[8];
    uint32_t turtle_nonce = 0;

    uint64_t hare_hash[8];
    uint32_t hare_nonce = 0;

    // Turtle = X_0
    HASH(0, hash_temp, turtle_hash);

    // Hare = F(X_0)
    hare_nonce = COMPRESS_HASH(result_hash);
    HASH(hare_nonce, hash_temp, hare_hash);

    while (power <= MAX_MOMENTUM_NONCE) {
        for (uint32_t chunk = 0; chunk < BIRTHDAYS_PER_HASH; ++chunk) {
            uint32_t offset = CONTAINS_HASH(hare_hash[chunk], turtle_hash);

            if (offset != 0xFF) {
                if (DEBUG) {
                    std::cerr << "Found hit PART 1\n";
                    std::cerr << "Hare Nonce: " << hare_nonce << " + " << chunk << "\n";
                    PRINT_HASH(hare_hash);
                    std::cerr << "Trtl Nonce: " << turtle_nonce << " + " << offset << "\n";
                    PRINT_HASH(turtle_hash);
                }

                break;
            }
        }

        if (power == lam) {
            COPY_HASH(hare_hash, turtle_hash);
            turtle_nonce = hare_nonce;
            power <<= 1;
            lam = 0;
        }

        hare_nonce = COMPRESS_HASH(hare_hash);
        HASH(hare_nonce, hash_temp, hare_hash);
        ++lam;
    }

    // Nothing found, give up.
    if (power >= MAX_MOMENTUM_NONCE) { return results; }

    // Rewind to find first repetition of nonces
    turtle_nonce = 0;
    HASH(turtle_nonce, hash_temp, turtle_hash);
    hare_nonce = 0;
    HASH_COPY(turtle_hash, hare_hash);

    // Get hare up to speed
    for (uint32_t fastforward = 0; fastforward < lam; ++fastforward) {
        hare_nonce = COMPRESS_HASH(hare_hash);
        HASH(hare_nonce, hash_temp, hare_hash);
    }

    // Keep stepping until they match again
    while (true) {
        for (uint32_t chunk = 0; chunk < BIRTHDAYS_PER_HASH; ++chunk) {
            uint32_t offset = CONTAINS_HASH(hare_hash[chunk], turtle_hash);

            if (offset != 0xFF) {
                if (DEBUG) {
                    std::cerr << "Found hit PART 2\n";
                    std::cerr << "Hare Nonce: " << hare_nonce << " + " << chunk << "\n";
                    PRINT_HASH(hare_hash);
                    std::cerr << "Trtl Nonce: " << turtle_nonce << " + " << offset << "\n";
                    PRINT_HASH(turtle_hash);
                }

                results.push_back( std::make_pair( hare_nonce + chunk, turtle_nonce + offset ) );
                return results;
            }
        }

        turtle_nonce = COMPRESS_HASH(turtle_hash);
        HASH(turtle_nonce, hash_temp, turtle_hash);

        hare_nonce = COMPRESS_HASH(hare_hash);
        HASH(hare_nonce, hash_temp, hare_hash);
    }

    std::cerr << "You should never be here!\n";

    return results;
}

uint64_t getBirthdayHash(const uint256 &midHash, uint32_t a)
{
    uint32_t index = a - (a % 8);
    char  hash_tmp[sizeof(midHash) + 4];

    memcpy(&hash_tmp[4], (char *)&midHash, sizeof(midHash));
    memcpy(&hash_tmp[0], (char *)&index, sizeof(index));

    uint64_t  result_hash[8];

    SHA512((unsigned char *)hash_tmp, sizeof(hash_tmp), (unsigned char *)&result_hash);

    uint64_t r = result_hash[a % BIRTHDAYS_PER_HASH] >> (64 - SEARCH_SPACE_BITS);

    return r;
}

bool momentum_verify(uint256 head, uint32_t a, uint32_t b)
{
    if(a == b) {
        return false;
    }

    if(a > MAX_MOMENTUM_NONCE) {
        return false;
    }

    if(b > MAX_MOMENTUM_NONCE) {
        return false;
    }

    bool r = (getBirthdayHash(head, a) == getBirthdayHash(head, b));
    return r;
}

}
<|endoftext|>


<commit_before> /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NCatalog.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 02:28:33 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#ifndef _CONNECTIVITY_EVOAB_CATALOG_HXX_
#include "NCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_CONNECTION_HXX_
#include "NConnection.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_TABLES_HXX_
#include "NTables.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX
#include "NDebug.hxx"
#endif

// -------------------------------------------------------------------------
using namespace connectivity::evoab;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -------------------------------------------------------------------------
OEvoabCatalog::OEvoabCatalog(OEvoabConnection* _pCon) :
    connectivity::sdbcx::OCatalog(_pCon)
    ,m_pConnection(_pCon)
    ,m_xMetaData(m_pConnection->getMetaData())
{
}
void OEvoabCatalog::refreshTables()
{
    TStringVector aVector;
    Sequence< ::rtl::OUString > aTypes(1);
    aTypes[0] = ::rtl::OUString::createFromAscii("TABLE");
    Reference< XResultSet > xResult = m_xMetaData->getTables(Any(),
        ::rtl::OUString::createFromAscii("%"),::rtl::OUString::createFromAscii("%"),aTypes);

    if(xResult.is())
    {
        Reference< XRow > xRow(xResult,UNO_QUERY);
        ::rtl::OUString aName;

        while(xResult->next())
        {
            aName = xRow->getString(3);
            aVector.push_back(aName);
        }
    }
    if(m_pTables)
        m_pTables->reFill(aVector);
    else
        m_pTables = new OEvoabTables(m_xMetaData,*this,m_aMutex,aVector);
}
// XTablesSupplier
Reference< XNameAccess > SAL_CALL  OEvoabCatalog::getTables(  ) throw(RuntimeException)
{
        ::osl::MutexGuard aGuard(m_aMutex);

        try
        {
                if (!m_pTables) {
                        refreshTables();
                        }
        }
        catch( const RuntimeException& )
        {
                // allowed to leave this method
                throw;
        }
        catch( const Exception& )
        {
                // allowed
        }

        return m_pTables;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.5.216); FILE MERGED 2008/04/01 10:52:56 thb 1.5.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:31 rt 1.5.216.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: NCatalog.cxx,v $
 * $Revision: 1.6 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "NCatalog.hxx"
#include "NConnection.hxx"
#include "NTables.hxx"
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include "NDebug.hxx"

// -------------------------------------------------------------------------
using namespace connectivity::evoab;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -------------------------------------------------------------------------
OEvoabCatalog::OEvoabCatalog(OEvoabConnection* _pCon) :
    connectivity::sdbcx::OCatalog(_pCon)
    ,m_pConnection(_pCon)
    ,m_xMetaData(m_pConnection->getMetaData())
{
}
void OEvoabCatalog::refreshTables()
{
    TStringVector aVector;
    Sequence< ::rtl::OUString > aTypes(1);
    aTypes[0] = ::rtl::OUString::createFromAscii("TABLE");
    Reference< XResultSet > xResult = m_xMetaData->getTables(Any(),
        ::rtl::OUString::createFromAscii("%"),::rtl::OUString::createFromAscii("%"),aTypes);

    if(xResult.is())
    {
        Reference< XRow > xRow(xResult,UNO_QUERY);
        ::rtl::OUString aName;

        while(xResult->next())
        {
            aName = xRow->getString(3);
            aVector.push_back(aName);
        }
    }
    if(m_pTables)
        m_pTables->reFill(aVector);
    else
        m_pTables = new OEvoabTables(m_xMetaData,*this,m_aMutex,aVector);
}
// XTablesSupplier
Reference< XNameAccess > SAL_CALL  OEvoabCatalog::getTables(  ) throw(RuntimeException)
{
        ::osl::MutexGuard aGuard(m_aMutex);

        try
        {
                if (!m_pTables) {
                        refreshTables();
                        }
        }
        catch( const RuntimeException& )
        {
                // allowed to leave this method
                throw;
        }
        catch( const Exception& )
        {
                // allowed
        }

        return m_pTables;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SQLWarning.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:14:23 $
 *
 *  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 _CONNECTIVITY_JAVA_SQL_SQLWARNING_HXX_
#include "java/sql/SQLWarning.hxx"
#endif
using namespace connectivity;
//**************************************************************
//************ Class: java.sql.SQLWarning
//**************************************************************

jclass java_sql_SQLWarning_BASE::theClass = 0;

java_sql_SQLWarning_BASE::~java_sql_SQLWarning_BASE()
{}

jclass java_sql_SQLWarning_BASE::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/sql/SQLWarning" );
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_SQLWarning_BASE::saveClassRef( jclass pClass )
{
    if( SDBThreadAttach::IsJavaErrorOccured() || pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

<commit_msg>INTEGRATION: CWS mav4 (1.1.1.1.98); FILE MERGED 2003/04/15 12:22:15 oj 1.1.1.1.98.1: #108943# merge from apps61beta2 and statement fix, concurrency<commit_after>/*************************************************************************
 *
 *  $RCSfile: SQLWarning.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-24 13:22:18 $
 *
 *  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 _CONNECTIVITY_JAVA_SQL_SQLWARNING_HXX_
#include "java/sql/SQLWarning.hxx"
#endif
using namespace connectivity;
//**************************************************************
//************ Class: java.sql.SQLWarning
//**************************************************************

jclass java_sql_SQLWarning_BASE::theClass = 0;

java_sql_SQLWarning_BASE::~java_sql_SQLWarning_BASE()
{}

jclass java_sql_SQLWarning_BASE::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/sql/SQLWarning" );
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_SQLWarning_BASE::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

<|endoftext|>


<commit_before>// https://github.com/KubaO/stackoverflown/tree/master/tooling

#include "backport.h"
#include "tooling.h"

#ifdef QT_WIDGETS_LIB

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#if 0  // The Qt-4 style hooks work just fine and are portable.
#include <private/qhooks_p.h>
#endif
#endif
#include <QApplication>
#include <QDebug>
#include <QDesktopWidget>
#include <QDir>
#include <QElapsedTimer>
#include <QEvent>
#include <QFile>
#include <QPainter>
#include <QScreen>

#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
#include <QWindow>
#endif

namespace tooling {

struct Times {
   static int constexpr collect() { return 1000; }
   static int constexpr minCollect() { return 100; }
   static int constexpr screenshotDelay() { return HostOsInfo::isMacHost() ? 250 : 500; }
};

static bool isProxied(QWidget *widget) {
   static EventLoopContext ctx;
   static PointerList<QWidget> proxied;
   Q_ASSERT(widget && !wasDeleted(widget) && widget->isWindow());

   if (ctx.needsRearm()) {
      proxied = getProxiedWidgets();
      ctx.rearm();
   }
   return proxied.contains(widget);
}

static void takeScreenshot(int n, QWidget *w) {
   auto rect = shadowlessFrameGeometry(w->frameGeometry());
   if (HostOsInfo::isMacHost()) rect.adjust(-1, -1, 1, 1);
   QPixmap pix;
#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
   auto *const win = w->windowHandle();
   auto *const screen = win->screen();
   pix = screen->grabWindow(0);
#endif
   if (QT_VERSION < QT_VERSION_CHECK(5, 3, 0))
      pix = QPixmap::grabWindow(QApplication::desktop()->winId());

   if ((1)) {
      pix = pix.copy(rect);
   } else {
      QPainter p(&pix);
      p.drawRect(w->frameGeometry());
      p.end();
   }
   if (pix.isNull()) {
      qWarning() << "Discarding null screenshot of" << w;
      return;
   }
   auto const name = w->objectName();
   auto const fileName =
       QStringLiteral("screenshot_%1_%2%3.png")
           .arg(n)
           .arg(QLatin1String(w->metaObject()->className()))
           .arg(name.isNull() ? QString() : QStringLiteral("_%1").arg(name));
   QDir path = QCoreApplication::applicationDirPath();
   if (HostOsInfo::isMacHost() && path.path().endsWith(".app/Contents/MacOS")) {
      // store the widget in the app-containing folder, not in the bundle itself
      path.cdUp();
      path.cdUp();
      path.cdUp();
   }
   tooling::QSaveFile f(path.absoluteFilePath(fileName));
   if (f.open(QIODevice::WriteOnly | QIODevice::Truncate) && pix.save(&f, "PNG") && f.commit()) {
      qDebug() << "Took screenshot of" << w << ":" << f.fileName();
      if (!showInGraphicalShell(w, f.fileName(), n == 1))
         qWarning()
             << "Can't invoke the graphical file shell to show screenshot location.";
   } else {
      qWarning() << "Can't save screenshot" << f.fileName()
                 << "Error:" << f.errorString();
   }
}

class ScreenshotTaker : public QObject {
   static int n;
   QAtomicInt eventCount = 0;
   enum Phase { Collecting, Collected, Screenshot };
   enum State { Initial, Updated, Painted, Ignored };
   Phase phase = Collecting;
   QBasicTimer timer;
   QElapsedTimer time;
   struct TopLevel {
      QPointer<QWidget> w = {};
      State state = Initial;
      TopLevel() = default;
      explicit TopLevel(QWidget *w, State state = Initial) : w(w), state(state) {}
      operator QWidget *() const { return w; }
      QWidget *operator->() const { return w; }
      bool operator==(QWidget *o) const { return o == w; }
   };
   QVector<TopLevel> topLevels;
   int leftToPaint = 0;
   void timerEvent(QTimerEvent *ev) override {
      if (ev->timerId() == timer.timerId()) {
         if (phase == Collecting || phase == Collected)
            scheduleScreenshots();
         else if (phase == Screenshot)
            takeScreenshots();
      }
   }
   void scheduleScreenshots() {
      qDebug() << "Deferring screenshots. Noted" << topLevels.count() << "widgets.";
      qApp->removeEventFilter(this);
      timer.start(Times::screenshotDelay(), this);
      phase = Screenshot;
   }
   void takeScreenshots() {
      if (qApp->property("no_screenshots").toBool())
         qDebug() << "Screenshot: Disabled by application property";
      else
         for (auto &tl : qAsConst(topLevels)) {
            if (!tl.w)
               continue;
            else if (!tl->isWindow()) {
            } else if (isProxied(tl))
               qDebug() << "Skipping proxied widget" << tl;
            else if (tl.state == Painted)
               takeScreenshot(++n, tl);
         }
      deleteLater();
   }
   bool eventFilter(QObject *o, QEvent *ev) override {
      static bool recursed;
      eventCount.fetchAndAddOrdered(1);
      if (recursed) return recursed = false;
      recursed = true;
      if (o->thread() != thread() || !o->isWidgetType()) return recursed = false;
      auto *w = static_cast<QWidget *>(o);
      auto *window = w->window();
      auto i = std::find(topLevels.begin(), topLevels.end(), window);
      if (phase == Collecting && i == topLevels.end()) {
         topLevels.push_back(TopLevel(window));
         i = std::prev(topLevels.end());
         if (tooling::hasEventLoopSpunUp())
            qDebug() << "Noting" << window << "for a screenshot";
         leftToPaint++;
      } else if (i != topLevels.end()) {
         if (tooling::hasEventLoopSpunUp() && window->isVisible() &&
             i->state == Initial) {
            bool raise =
                QT_VERSION < QT_VERSION_CHECK(5, 0, 0) && HostOsInfo::isMacHost();
            qDebug() << (raise ? "Raising" : "Updating") << window << "for a screnshot";
            if (raise) window->raise();
            window->update();
            i->state = Updated;
         }
         if ((ev->type() == QEvent::Paint || ev->type() == QEvent::UpdateRequest) &&
             i->state != Painted && i->state != Ignored) {
            i->state = Painted;
            (w != window ? qDebug() << window : qDebug()) << w << "painted";
            leftToPaint--;
         }
         if (leftToPaint == 0 && time.elapsed() > Times::minCollect()) {
            timer.stop();
            scheduleScreenshots();
         }
      }
      return recursed = false;
   }

  public:
   ScreenshotTaker(QWidget *parent = {}) : QObject(parent) {
      if (parent) {
         Q_ASSERT(parent->isWindow());
         phase = Collected;
         topLevels.push_back(TopLevel(parent, Painted));
      } else {
         time.start();
         timer.start(Times::collect(), this);
      }
      qApp->installEventFilter(this);
   }
   ~ScreenshotTaker() override {
      qDebug() << "Saw" << eventCount << "events before taking screenshots.";
   }
};  // namespace tooling

int ScreenshotTaker::n;

void takeScreenshot(QWidget *widget) {
   Q_ASSERT(widget && widget->isWindow());
   if (isProxied(widget)) {
      qDebug() << "Skipping proxied widget" << widget;
      return;
   }
   if (!widget->isVisible()) {
      qDebug() << "Skipping hidden widget" << widget;
      return;
   }
   new ScreenshotTaker(widget);
}

static bool takeScreenshots(const HookData &) {
#ifdef NO_SCREENSHOTS
   return;
#endif
   if (qApp->property("no_screenshots").toBool()) {
      qDebug() << "Screenshot: Disabled by application property";
      return false;
   }
   qDebug() << "Screenshot: Startup";
   new ScreenshotTaker();
   return false;
}

static bool initialized = [] {
   registerHook(HasQApplicationHook, &takeScreenshots);
   return true;
}();

}  // namespace tooling

#endif  // QT_WIDGETS_LIB
<commit_msg>Support additional screenshot delay via `screenshot_delay` application property or `SCREENSHOT_DELAY` macro.<commit_after>// https://github.com/KubaO/stackoverflown/tree/master/tooling

#include "backport.h"
#include "tooling.h"

#ifdef QT_WIDGETS_LIB

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#if 0  // The Qt-4 style hooks work just fine and are portable.
#include <private/qhooks_p.h>
#endif
#endif
#include <QApplication>
#include <QDebug>
#include <QDesktopWidget>
#include <QDir>
#include <QElapsedTimer>
#include <QEvent>
#include <QFile>
#include <QPainter>
#include <QScreen>

#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
#include <QWindow>
#endif

namespace tooling {

struct Times {
   static int constexpr collect() { return 1000; }
   static int constexpr minCollect() { return 100; }
   static int constexpr screenshotDelay() { return HostOsInfo::isMacHost() ? 250 : 500; }
};

static bool isProxied(QWidget *widget) {
   static EventLoopContext ctx;
   static PointerList<QWidget> proxied;
   Q_ASSERT(widget && !wasDeleted(widget) && widget->isWindow());

   if (ctx.needsRearm()) {
      proxied = getProxiedWidgets();
      ctx.rearm();
   }
   return proxied.contains(widget);
}

static void takeScreenshot(int n, QWidget *w) {
   auto rect = shadowlessFrameGeometry(w->frameGeometry());
   if (HostOsInfo::isMacHost()) rect.adjust(-1, -1, 1, 1);
   QPixmap pix;
#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
   auto *const win = w->windowHandle();
   auto *const screen = win->screen();
   pix = screen->grabWindow(0);
#endif
   if (QT_VERSION < QT_VERSION_CHECK(5, 3, 0))
      pix = QPixmap::grabWindow(QApplication::desktop()->winId());

   if ((1)) {
      pix = pix.copy(rect);
   } else {
      QPainter p(&pix);
      p.drawRect(w->frameGeometry());
      p.end();
   }
   if (pix.isNull()) {
      qWarning() << "Discarding null screenshot of" << w;
      return;
   }
   auto const name = w->objectName();
   auto const fileName =
       QStringLiteral("screenshot_%1_%2%3.png")
           .arg(n)
           .arg(QLatin1String(w->metaObject()->className()))
           .arg(name.isNull() ? QString() : QStringLiteral("_%1").arg(name));
   QDir path = QCoreApplication::applicationDirPath();
   if (HostOsInfo::isMacHost() && path.path().endsWith(".app/Contents/MacOS")) {
      // store the widget in the app-containing folder, not in the bundle itself
      path.cdUp();
      path.cdUp();
      path.cdUp();
   }
   tooling::QSaveFile f(path.absoluteFilePath(fileName));
   if (f.open(QIODevice::WriteOnly | QIODevice::Truncate) && pix.save(&f, "PNG") && f.commit()) {
      qDebug() << "Took screenshot of" << w << ":" << f.fileName();
      if (!showInGraphicalShell(w, f.fileName(), n == 1))
         qWarning()
             << "Can't invoke the graphical file shell to show screenshot location.";
   } else {
      qWarning() << "Can't save screenshot" << f.fileName()
                 << "Error:" << f.errorString();
   }
}

class ScreenshotTaker : public QObject {
   static int n;
   QAtomicInt eventCount = 0;
   enum Phase { Collecting, Collected, Screenshot };
   enum State { Initial, Updated, Painted, Ignored };
   Phase phase = Collecting;
   QBasicTimer timer;
   QElapsedTimer time;
   struct TopLevel {
      QPointer<QWidget> w = {};
      State state = Initial;
      TopLevel() = default;
      explicit TopLevel(QWidget *w, State state = Initial) : w(w), state(state) {}
      operator QWidget *() const { return w; }
      QWidget *operator->() const { return w; }
      bool operator==(QWidget *o) const { return o == w; }
   };
   QVector<TopLevel> topLevels;
   int leftToPaint = 0;
   void timerEvent(QTimerEvent *ev) override {
      if (ev->timerId() == timer.timerId()) {
         if (phase == Collecting || phase == Collected)
            scheduleScreenshots();
         else if (phase == Screenshot)
            takeScreenshots();
      }
   }
   void scheduleScreenshots() {
      qDebug() << "Deferring screenshots. Noted" << topLevels.count() << "widgets.";
      qApp->removeEventFilter(this);
      auto additionalDelay = qApp->property("screenshot_delay").toInt();
#ifdef SCREENSHOT_DELAY
      additionalDelay += (SCREENSHOT_DELAY);
#endif
      timer.start(Times::screenshotDelay() + additionalDelay, this);
      phase = Screenshot;
   }
   void takeScreenshots() {
      if (qApp->property("no_screenshots").toBool())
         qDebug() << "Screenshot: Disabled by application property";
      else
         for (auto &tl : qAsConst(topLevels)) {
            if (!tl.w)
               continue;
            else if (!tl->isWindow()) {
            } else if (isProxied(tl))
               qDebug() << "Skipping proxied widget" << tl;
            else if (tl.state == Painted)
               takeScreenshot(++n, tl);
         }
      deleteLater();
   }
   bool eventFilter(QObject *o, QEvent *ev) override {
      static bool recursed;
      eventCount.fetchAndAddOrdered(1);
      if (recursed) return recursed = false;
      recursed = true;
      if (o->thread() != thread() || !o->isWidgetType()) return recursed = false;
      auto *w = static_cast<QWidget *>(o);
      auto *window = w->window();
      auto i = std::find(topLevels.begin(), topLevels.end(), window);
      if (phase == Collecting && i == topLevels.end()) {
         topLevels.push_back(TopLevel(window));
         i = std::prev(topLevels.end());
         if (tooling::hasEventLoopSpunUp())
            qDebug() << "Noting" << window << "for a screenshot";
         leftToPaint++;
      } else if (i != topLevels.end()) {
         if (tooling::hasEventLoopSpunUp() && window->isVisible() &&
             i->state == Initial) {
            bool raise =
                QT_VERSION < QT_VERSION_CHECK(5, 0, 0) && HostOsInfo::isMacHost();
            qDebug() << (raise ? "Raising" : "Updating") << window << "for a screnshot";
            if (raise) window->raise();
            window->update();
            i->state = Updated;
         }
         if ((ev->type() == QEvent::Paint || ev->type() == QEvent::UpdateRequest) &&
             i->state != Painted && i->state != Ignored) {
            i->state = Painted;
            (w != window ? qDebug() << window : qDebug()) << w << "painted";
            leftToPaint--;
         }
         if (leftToPaint == 0 && time.elapsed() > Times::minCollect()) {
            timer.stop();
            scheduleScreenshots();
         }
      }
      return recursed = false;
   }

  public:
   ScreenshotTaker(QWidget *parent = {}) : QObject(parent) {
      if (parent) {
         Q_ASSERT(parent->isWindow());
         phase = Collected;
         topLevels.push_back(TopLevel(parent, Painted));
      } else {
         time.start();
         timer.start(Times::collect(), this);
      }
      qApp->installEventFilter(this);
   }
   ~ScreenshotTaker() override {
      qDebug() << "Saw" << eventCount << "events before taking screenshots.";
   }
};  // namespace tooling

int ScreenshotTaker::n;

void takeScreenshot(QWidget *widget) {
   Q_ASSERT(widget && widget->isWindow());
   if (isProxied(widget)) {
      qDebug() << "Skipping proxied widget" << widget;
      return;
   }
   if (!widget->isVisible()) {
      qDebug() << "Skipping hidden widget" << widget;
      return;
   }
   new ScreenshotTaker(widget);
}

static bool takeScreenshots(const HookData &) {
#ifdef NO_SCREENSHOTS
   return;
#endif
   if (qApp->property("no_screenshots").toBool()) {
      qDebug() << "Screenshot: Disabled by application property";
      return false;
   }
   qDebug() << "Screenshot: Startup";
   new ScreenshotTaker();
   return false;
}

static bool initialized = [] {
   registerHook(HasQApplicationHook, &takeScreenshots);
   return true;
}();

}  // namespace tooling

#endif  // QT_WIDGETS_LIB
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: redlndlg.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 09:59:02 $
 *
 *  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 _SWREDLNDLG_HXX
#define _SWREDLNDLG_HXX

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _CHLDWRAP_HXX
#include "chldwrap.hxx"
#endif
#ifndef _REDLINE_HXX
#include <redline.hxx> //CHINA001
#endif
#ifndef _REDLENUM_HXX
#include <redlenum.hxx>
#endif

#ifndef _TOOLS_INTN_HXX //autogen
#include <tools/intn.hxx>
#endif
#ifndef _DATETIME_HXX //autogen
#include <tools/datetime.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVSTDARR_HXX
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SVX_CTREDLIN_HXX //autogen
#include <svx/ctredlin.hxx>
#endif
#ifndef _SVX_POSTATTR_HXX //autogen
#include <svx/postattr.hxx>
#endif

class SwChildWinWrapper;

//CHINA001 class SwRedlineAcceptDlg;
//add CHINA001 begin this part is extracted from sw\source\ui\misc\redlndlg.cxx
struct SwRedlineDataChild
{
    const SwRedlineData*        pChild;     // Verweis auf originale gestackte Daten
    const SwRedlineDataChild*   pNext;      // Verweis auf gestackte Daten
    SvLBoxEntry*                pTLBChild;  // zugehoeriger TreeListBox-Eintrag
};

struct SwRedlineDataParent
{
    const SwRedlineData*        pData;      // RedlineDataPtr
    const SwRedlineDataChild*   pNext;      // Verweis auf gestackte Daten
    SvLBoxEntry*                pTLBParent; // zugehoeriger TreeListBox-Eintrag
    String                      sComment;   // Redline-Kommentar

    inline BOOL operator==( const SwRedlineDataParent& rObj ) const
                        { return (pData && pData->GetSeqNo() == rObj.pData->GetSeqNo()); }
    inline BOOL operator< ( const SwRedlineDataParent& rObj ) const
                        { return (pData && pData->GetSeqNo() <  rObj.pData->GetSeqNo()); }
};

typedef SwRedlineDataParent* SwRedlineDataParentPtr;
SV_DECL_PTRARR_DEL(SwRedlineDataParentArr, SwRedlineDataParentPtr, 10, 20)

SV_DECL_PTRARR_SORT(SwRedlineDataParentSortArr, SwRedlineDataParentPtr, 10, 20)

typedef SwRedlineDataChild* SwRedlineDataChildPtr;
SV_DECL_PTRARR_DEL(SwRedlineDataChildArr, SwRedlineDataChildPtr, 4, 4)

typedef SvLBoxEntry* SvLBoxEntryPtr;
SV_DECL_PTRARR(SvLBoxEntryArr, SvLBoxEntryPtr, 100, 100)

class SW_DLLPUBLIC SwRedlineAcceptDlg
{
    Dialog*                 pParentDlg;
    SwRedlineDataParentArr  aRedlineParents;
    SwRedlineDataChildArr   aRedlineChilds;
    SwRedlineDataParentSortArr aUsedSeqNo;
    SvxAcceptChgCtr         aTabPagesCTRL;
    PopupMenu               aPopup;
    Timer                   aDeselectTimer;
    Timer                   aSelectTimer;
    String                  sInserted;
    String                  sDeleted;
    String                  sFormated;
    String                  sTableChgd;
    String                  sFmtCollSet;
    String                  sFilterAction;
    String                  sAutoFormat;
    Size                    aBorderSz;
    SvxTPView*              pTPView;
    SvxRedlinTable*         pTable;
    Link                    aOldSelectHdl;
    Link                    aOldDeselectHdl;
    BOOL                    bOnlyFormatedRedlines;
    BOOL                    bHasReadonlySel;
    BOOL                    bRedlnAutoFmt;

    // prevent update dialog data during longer operations (cf #102657#)
    bool                    bInhibitActivate;

    SW_DLLPRIVATE DECL_LINK( AcceptHdl,     void* );
    SW_DLLPRIVATE DECL_LINK( AcceptAllHdl,  void* );
    SW_DLLPRIVATE DECL_LINK( RejectHdl,     void* );
    SW_DLLPRIVATE DECL_LINK( RejectAllHdl,  void* );
    SW_DLLPRIVATE DECL_LINK( UndoHdl,           void* );
    SW_DLLPRIVATE DECL_LINK( DeselectHdl,       void* );
    SW_DLLPRIVATE DECL_LINK( SelectHdl,     void* );
    SW_DLLPRIVATE DECL_LINK( GotoHdl,           void* );
    SW_DLLPRIVATE DECL_LINK( CommandHdl,        void* );

    SW_DLLPRIVATE USHORT            CalcDiff(USHORT nStart, BOOL bChild);
    SW_DLLPRIVATE void          InsertChilds(SwRedlineDataParent *pParent, const SwRedline& rRedln, const USHORT nAutoFmt);
    SW_DLLPRIVATE void          InsertParents(USHORT nStart, USHORT nEnd = USHRT_MAX);
    SW_DLLPRIVATE void          RemoveParents(USHORT nStart, USHORT nEnd);
    SW_DLLPRIVATE void          InitAuthors();

    SW_DLLPRIVATE String            GetRedlineText(const SwRedline& rRedln, DateTime &rDateTime, USHORT nStack = 0);
    SW_DLLPRIVATE const String& GetActionText(const SwRedline& rRedln, USHORT nStack = 0);
    SW_DLLPRIVATE USHORT            GetRedlinePos( const SvLBoxEntry& rEntry) const;

public:
    SwRedlineAcceptDlg(Dialog *pParent, BOOL bAutoFmt = FALSE);
    ~SwRedlineAcceptDlg();

    DECL_LINK( FilterChangedHdl, void *pDummy = 0 );

    inline SvxAcceptChgCtr* GetChgCtrl()        { return &aTabPagesCTRL; }
    inline BOOL     HasRedlineAutoFmt() const   { return bRedlnAutoFmt; }

    void            Init(USHORT nStart = 0);
    void            CallAcceptReject( BOOL bSelect, BOOL bAccept );

    void            Initialize(const String &rExtraData);
    void            FillInfo(String &rExtraData) const;

    virtual void    Activate();
    virtual void    Resize();
};
//add CHINA001 end

/*------------------------------------------------------------------------
    Beschreibung:
------------------------------------------------------------------------*/

class SwModelessRedlineAcceptDlg : public SfxModelessDialog
{
    SwRedlineAcceptDlg*     pImplDlg;
    SwChildWinWrapper*      pChildWin;

    virtual void    Resize();

public:
    SwModelessRedlineAcceptDlg(SfxBindings*, SwChildWinWrapper*, Window *pParent);
    ~SwModelessRedlineAcceptDlg();

    virtual void    Activate();
    virtual void    FillInfo(SfxChildWinInfo&) const;
    void            Initialize (SfxChildWinInfo* pInfo);
};

/*------------------------------------------------------------------------
    Beschreibung:
------------------------------------------------------------------------*/

//CHINA001 class SwModalRedlineAcceptDlg : public SfxModalDialog
//CHINA001 {
//CHINA001 SwRedlineAcceptDlg*      pImplDlg;
//CHINA001
//CHINA001 virtual void Resize();
//CHINA001
//CHINA001 public:
//CHINA001 SwModalRedlineAcceptDlg(Window *pParent);
//CHINA001 ~SwModalRedlineAcceptDlg();
//CHINA001
//CHINA001 void         AcceptAll( BOOL bAccept );
//CHINA001 virtual void Activate();
//CHINA001 };

/*------------------------------------------------------------------------
    Beschreibung:
------------------------------------------------------------------------*/

class SwRedlineAcceptChild : public SwChildWinWrapper
{
public:
    SwRedlineAcceptChild(   Window* ,
                            USHORT nId,
                            SfxBindings*,
                            SfxChildWinInfo*  );

    SFX_DECL_CHILDWINDOW( SwRedlineAcceptChild );

    virtual BOOL    ReInitDlg(SwDocShell *pDocSh);
};

#endif

<commit_msg>INTEGRATION: CWS pb11 (1.4.196); FILE MERGED 2006/02/02 10:29:44 pb 1.4.196.1: fix: #i48648# SvxRedlinTable now SvHeaderTabListBox<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: redlndlg.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2006-02-06 13:10:21 $
 *
 *  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 _SWREDLNDLG_HXX
#define _SWREDLNDLG_HXX

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _CHLDWRAP_HXX
#include "chldwrap.hxx"
#endif
#ifndef _REDLINE_HXX
#include <redline.hxx> //CHINA001
#endif
#ifndef _REDLENUM_HXX
#include <redlenum.hxx>
#endif

#ifndef _TOOLS_INTN_HXX //autogen
#include <tools/intn.hxx>
#endif
#ifndef _DATETIME_HXX //autogen
#include <tools/datetime.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVSTDARR_HXX
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SVX_CTREDLIN_HXX //autogen
#include <svx/ctredlin.hxx>
#endif
#ifndef _SVX_POSTATTR_HXX //autogen
#include <svx/postattr.hxx>
#endif

class SwChildWinWrapper;

//CHINA001 class SwRedlineAcceptDlg;
//add CHINA001 begin this part is extracted from sw\source\ui\misc\redlndlg.cxx
struct SwRedlineDataChild
{
    const SwRedlineData*        pChild;     // Verweis auf originale gestackte Daten
    const SwRedlineDataChild*   pNext;      // Verweis auf gestackte Daten
    SvLBoxEntry*                pTLBChild;  // zugehoeriger TreeListBox-Eintrag
};

struct SwRedlineDataParent
{
    const SwRedlineData*        pData;      // RedlineDataPtr
    const SwRedlineDataChild*   pNext;      // Verweis auf gestackte Daten
    SvLBoxEntry*                pTLBParent; // zugehoeriger TreeListBox-Eintrag
    String                      sComment;   // Redline-Kommentar

    inline BOOL operator==( const SwRedlineDataParent& rObj ) const
                        { return (pData && pData->GetSeqNo() == rObj.pData->GetSeqNo()); }
    inline BOOL operator< ( const SwRedlineDataParent& rObj ) const
                        { return (pData && pData->GetSeqNo() <  rObj.pData->GetSeqNo()); }
};

typedef SwRedlineDataParent* SwRedlineDataParentPtr;
SV_DECL_PTRARR_DEL(SwRedlineDataParentArr, SwRedlineDataParentPtr, 10, 20)

SV_DECL_PTRARR_SORT(SwRedlineDataParentSortArr, SwRedlineDataParentPtr, 10, 20)

typedef SwRedlineDataChild* SwRedlineDataChildPtr;
SV_DECL_PTRARR_DEL(SwRedlineDataChildArr, SwRedlineDataChildPtr, 4, 4)

typedef SvLBoxEntry* SvLBoxEntryPtr;
SV_DECL_PTRARR(SvLBoxEntryArr, SvLBoxEntryPtr, 100, 100)

class SW_DLLPUBLIC SwRedlineAcceptDlg
{
    Dialog*                 pParentDlg;
    SwRedlineDataParentArr  aRedlineParents;
    SwRedlineDataChildArr   aRedlineChilds;
    SwRedlineDataParentSortArr aUsedSeqNo;
    SvxAcceptChgCtr         aTabPagesCTRL;
    PopupMenu               aPopup;
    Timer                   aDeselectTimer;
    Timer                   aSelectTimer;
    String                  sInserted;
    String                  sDeleted;
    String                  sFormated;
    String                  sTableChgd;
    String                  sFmtCollSet;
    String                  sFilterAction;
    String                  sAutoFormat;
    Size                    aBorderSz;
    SvxTPView*              pTPView;
    SvxRedlinTable*         pTable; // PB 2006/02/02 #i48648 now SvHeaderTabListBox
    Link                    aOldSelectHdl;
    Link                    aOldDeselectHdl;
    BOOL                    bOnlyFormatedRedlines;
    BOOL                    bHasReadonlySel;
    BOOL                    bRedlnAutoFmt;

    // prevent update dialog data during longer operations (cf #102657#)
    bool                    bInhibitActivate;

    SW_DLLPRIVATE DECL_LINK( AcceptHdl,     void* );
    SW_DLLPRIVATE DECL_LINK( AcceptAllHdl,  void* );
    SW_DLLPRIVATE DECL_LINK( RejectHdl,     void* );
    SW_DLLPRIVATE DECL_LINK( RejectAllHdl,  void* );
    SW_DLLPRIVATE DECL_LINK( UndoHdl,           void* );
    SW_DLLPRIVATE DECL_LINK( DeselectHdl,       void* );
    SW_DLLPRIVATE DECL_LINK( SelectHdl,     void* );
    SW_DLLPRIVATE DECL_LINK( GotoHdl,           void* );
    SW_DLLPRIVATE DECL_LINK( CommandHdl,        void* );

    SW_DLLPRIVATE USHORT            CalcDiff(USHORT nStart, BOOL bChild);
    SW_DLLPRIVATE void          InsertChilds(SwRedlineDataParent *pParent, const SwRedline& rRedln, const USHORT nAutoFmt);
    SW_DLLPRIVATE void          InsertParents(USHORT nStart, USHORT nEnd = USHRT_MAX);
    SW_DLLPRIVATE void          RemoveParents(USHORT nStart, USHORT nEnd);
    SW_DLLPRIVATE void          InitAuthors();

    SW_DLLPRIVATE String            GetRedlineText(const SwRedline& rRedln, DateTime &rDateTime, USHORT nStack = 0);
    SW_DLLPRIVATE const String& GetActionText(const SwRedline& rRedln, USHORT nStack = 0);
    SW_DLLPRIVATE USHORT            GetRedlinePos( const SvLBoxEntry& rEntry) const;

public:
    SwRedlineAcceptDlg(Dialog *pParent, BOOL bAutoFmt = FALSE);
    ~SwRedlineAcceptDlg();

    DECL_LINK( FilterChangedHdl, void *pDummy = 0 );

    inline SvxAcceptChgCtr* GetChgCtrl()        { return &aTabPagesCTRL; }
    inline BOOL     HasRedlineAutoFmt() const   { return bRedlnAutoFmt; }

    void            Init(USHORT nStart = 0);
    void            CallAcceptReject( BOOL bSelect, BOOL bAccept );

    void            Initialize(const String &rExtraData);
    void            FillInfo(String &rExtraData) const;

    virtual void    Activate();
    virtual void    Resize();
};
//add CHINA001 end

/*------------------------------------------------------------------------
    Beschreibung:
------------------------------------------------------------------------*/

class SwModelessRedlineAcceptDlg : public SfxModelessDialog
{
    SwRedlineAcceptDlg*     pImplDlg;
    SwChildWinWrapper*      pChildWin;

    virtual void    Resize();

public:
    SwModelessRedlineAcceptDlg(SfxBindings*, SwChildWinWrapper*, Window *pParent);
    ~SwModelessRedlineAcceptDlg();

    virtual void    Activate();
    virtual void    FillInfo(SfxChildWinInfo&) const;
    void            Initialize (SfxChildWinInfo* pInfo);
};

/*------------------------------------------------------------------------
    Beschreibung:
------------------------------------------------------------------------*/

//CHINA001 class SwModalRedlineAcceptDlg : public SfxModalDialog
//CHINA001 {
//CHINA001 SwRedlineAcceptDlg*      pImplDlg;
//CHINA001
//CHINA001 virtual void Resize();
//CHINA001
//CHINA001 public:
//CHINA001 SwModalRedlineAcceptDlg(Window *pParent);
//CHINA001 ~SwModalRedlineAcceptDlg();
//CHINA001
//CHINA001 void         AcceptAll( BOOL bAccept );
//CHINA001 virtual void Activate();
//CHINA001 };

/*------------------------------------------------------------------------
    Beschreibung:
------------------------------------------------------------------------*/

class SwRedlineAcceptChild : public SwChildWinWrapper
{
public:
    SwRedlineAcceptChild(   Window* ,
                            USHORT nId,
                            SfxBindings*,
                            SfxChildWinInfo*  );

    SFX_DECL_CHILDWINDOW( SwRedlineAcceptChild );

    virtual BOOL    ReInitDlg(SwDocShell *pDocSh);
};

#endif

<|endoftext|>