<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * [ Copyright (C) 2011 Markus Mohrhard <markus.mohrhard@googlemail.com> (initial developer) ]
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <test/unoapi_test.hxx>

#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#include <com/sun/star/sheet/XCellRangesQuery.hpp>
#include <com/sun/star/sheet/XSheetCellRanges.hpp>
#include <com/sun/star/table/CellAddress.hpp>
#include <com/sun/star/sheet/CellFlags.hpp>

using namespace com::sun::star;

namespace ScCellRangeBase {

class ScXCellRangesQuery : public UnoApiTest
{
public:
    ScXCellRangesQuery();

    uno::Reference<sheet::XCellRangesQuery> init();

    //Testcases
    void testQueryColumnDifference();
    void testQueryContentDifference();
    void testQueryEmptyCells();
    void testQueryFormulaCells();
    void testQueryIntersection();
    void testQueryRowDifference();
    void testQueryVisibleCells();

    CPPUNIT_TEST_SUITE(ScXCellRangesQuery);
    CPPUNIT_TEST(testQueryColumnDifference);
    CPPUNIT_TEST(testQueryContentDifference);
    CPPUNIT_TEST(testQueryEmptyCells);
    //looks broken
    //CPPUNIT_TEST(testQueryFormulaCells);
    CPPUNIT_TEST(testQueryIntersection);
    CPPUNIT_TEST(testQueryRowDifference);
    CPPUNIT_TEST_SUITE_END();

};

ScXCellRangesQuery::ScXCellRangesQuery()
{

}

uno::Reference<sheet::XCellRangesQuery> ScXCellRangesQuery::init()
{
    rtl::OUString aFileURL;
    const rtl::OUString aFileBase(RTL_CONSTASCII_USTRINGPARAM("xcellrangesquery.ods"));
    createFileURL(aFileBase, aFileURL);
    std::cout << rtl::OUStringToOString(aFileURL, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    static uno::Reference< lang::XComponent > xComponent;
    if( !xComponent.is())
        xComponent = loadFromDesktop(aFileURL);
    uno::Reference< sheet::XSpreadsheetDocument> xDoc (xComponent, UNO_QUERY_THROW);
    uno::Reference< container::XIndexAccess > xIndex (xDoc->getSheets(), UNO_QUERY_THROW);
    uno::Reference< sheet::XSpreadsheet > xSheet( xIndex->getByIndex(0), UNO_QUERY_THROW);

    CPPUNIT_ASSERT_MESSAGE("Could not create interface of type XSpreadsheet", xSheet.is());

    uno::Reference<sheet::XCellRangesQuery> xReturn(xSheet->getCellRangeByPosition(0,0,3,4), UNO_QUERY_THROW);

    CPPUNIT_ASSERT_MESSAGE("Could not create object of type XCellRangesQuery", xReturn.is());
    return xReturn;
}

void ScXCellRangesQuery::testQueryColumnDifference()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.B1:C1,Sheet1.B3:C5"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryColumnDifferences(table::CellAddress(0, 1, 1));
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryColumnDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryColumnDifference", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryContentDifference()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.B2:B3"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryContentCells(sheet::CellFlags::VALUE);
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryContentDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryContentDifference", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryEmptyCells()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A1:A5,Sheet1.B1:C1,Sheet1.B5,Sheet1.C3:C5,Sheet1.D1:D5"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryEmptyCells();
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryEmptyCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryEmptyCells", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryFormulaCells()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.C2"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryFormulaCells(sheet::CellFlags::FORMULA);
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryFormulaCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryIntersection()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.D4:D5"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryIntersection(table::CellRangeAddress(0,3,3,7,7));
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryIntersection: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryRowDifference()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A2:A4,Sheet1.C2:D4"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryRowDifferences(table::CellAddress(0,1,1));
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryRowDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryVisibleCells()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A2"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryVisibleCells();
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryVisibleCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}

CPPUNIT_TEST_SUITE_REGISTRATION(ScXCellRangesQuery);

CPPUNIT_PLUGIN_IMPLEMENT();

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>terminate xcellrangesquery correctly<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * [ Copyright (C) 2011 Markus Mohrhard <markus.mohrhard@googlemail.com> (initial developer) ]
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <test/unoapi_test.hxx>

#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/sheet/XSpreadsheet.hpp>
#include <com/sun/star/sheet/XCellRangesQuery.hpp>
#include <com/sun/star/sheet/XSheetCellRanges.hpp>
#include <com/sun/star/table/CellAddress.hpp>
#include <com/sun/star/sheet/CellFlags.hpp>
#include <com/sun/star/util/XCloseable.hpp>

using namespace com::sun::star;

namespace ScCellRangeBase {

#define NUMBER_OF_TESTS 5

class ScXCellRangesQuery : public UnoApiTest
{
public:

    virtual void setUp();
    virtual void tearDown();

    //Testcases
    void testQueryColumnDifference();
    void testQueryContentDifference();
    void testQueryEmptyCells();
    void testQueryFormulaCells();
    void testQueryIntersection();
    void testQueryRowDifference();
    void testQueryVisibleCells();

    CPPUNIT_TEST_SUITE(ScXCellRangesQuery);
    CPPUNIT_TEST(testQueryColumnDifference);
    CPPUNIT_TEST(testQueryContentDifference);
    CPPUNIT_TEST(testQueryEmptyCells);
    //looks broken
    //CPPUNIT_TEST(testQueryFormulaCells);
    CPPUNIT_TEST(testQueryIntersection);
    CPPUNIT_TEST(testQueryRowDifference);
    CPPUNIT_TEST_SUITE_END();

private:
    uno::Reference<sheet::XCellRangesQuery> init();

    static int nTest;
    static uno::Reference< lang::XComponent > xComponent;
};

int ScXCellRangesQuery::nTest = 0;
uno::Reference< lang::XComponent > ScXCellRangesQuery::xComponent;

uno::Reference<sheet::XCellRangesQuery> ScXCellRangesQuery::init()
{
    rtl::OUString aFileURL;
    const rtl::OUString aFileBase(RTL_CONSTASCII_USTRINGPARAM("xcellrangesquery.ods"));
    createFileURL(aFileBase, aFileURL);
    std::cout << rtl::OUStringToOString(aFileURL, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    if( !xComponent.is())
        xComponent = loadFromDesktop(aFileURL);
    uno::Reference< sheet::XSpreadsheetDocument> xDoc (xComponent, UNO_QUERY_THROW);
    uno::Reference< container::XIndexAccess > xIndex (xDoc->getSheets(), UNO_QUERY_THROW);
    uno::Reference< sheet::XSpreadsheet > xSheet( xIndex->getByIndex(0), UNO_QUERY_THROW);

    CPPUNIT_ASSERT_MESSAGE("Could not create interface of type XSpreadsheet", xSheet.is());

    uno::Reference<sheet::XCellRangesQuery> xReturn(xSheet->getCellRangeByPosition(0,0,3,4), UNO_QUERY_THROW);

    CPPUNIT_ASSERT_MESSAGE("Could not create object of type XCellRangesQuery", xReturn.is());
    return xReturn;
}

void ScXCellRangesQuery::testQueryColumnDifference()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.B1:C1,Sheet1.B3:C5"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryColumnDifferences(table::CellAddress(0, 1, 1));
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryColumnDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryColumnDifference", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryContentDifference()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.B2:B3"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryContentCells(sheet::CellFlags::VALUE);
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryContentDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryContentDifference", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryEmptyCells()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A1:A5,Sheet1.B1:C1,Sheet1.B5,Sheet1.C3:C5,Sheet1.D1:D5"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryEmptyCells();
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryEmptyCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryEmptyCells", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryFormulaCells()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.C2"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryFormulaCells(sheet::CellFlags::FORMULA);
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryFormulaCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryIntersection()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.D4:D5"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryIntersection(table::CellRangeAddress(0,3,3,7,7));
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryIntersection: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryRowDifference()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A2:A4,Sheet1.C2:D4"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryRowDifferences(table::CellAddress(0,1,1));
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryRowDifference: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}

void ScXCellRangesQuery::testQueryVisibleCells()
{
    rtl::OUString aExpected(RTL_CONSTASCII_USTRINGPARAM("Sheet1.A2"));
    uno::Reference<sheet::XCellRangesQuery> xCellRangesQuery = init();
    uno::Reference<sheet::XSheetCellRanges> xRanges = xCellRangesQuery->queryVisibleCells();
    rtl::OUString aResult = xRanges->getRangeAddressesAsString();
    std::cout << "testQueryVisibleCells: Result: " << rtl::OUStringToOString(aResult, RTL_TEXTENCODING_UTF8).getStr() << std::endl;
    CPPUNIT_ASSERT_MESSAGE("testQueryFormulaCells", aResult == aExpected);
}

void ScXCellRangesQuery::setUp()
{
    nTest += 1;
    UnoApiTest::setUp();
}

void ScXCellRangesQuery::tearDown()
{
    if (nTest == NUMBER_OF_TESTS)
    {
        uno::Reference< util::XCloseable > xCloseable(xComponent, UNO_QUERY_THROW);
        xCloseable->close( false );
    }

    UnoApiTest::tearDown();

    if (nTest == NUMBER_OF_TESTS)
    {
        mxDesktop->terminate();
        uno::Reference< lang::XComponent>(m_xContext, UNO_QUERY_THROW)->dispose();
    }
}

CPPUNIT_TEST_SUITE_REGISTRATION(ScXCellRangesQuery);

CPPUNIT_PLUGIN_IMPLEMENT();

}

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


<commit_before>#include <QtCore/QVector>
#include <QtCore/QHash>
void local_vector()
{
    QVector<int> vec;
    for (int i = 0; i < 10; ++i) {
        vec << i;      // Test #1: Warning
        vec.append(i); // Test #2: Warning
    }

    QVector<int> vec1;
    vec1.reserve(10);
    for (int i = 0; i < 10; ++i) {
        vec1 << i;      // Test #3: No warning
        vec1.append(i); // Test #4: No warning
    }

    QVector<int> vec2;
    for (int i = 0; i < 10; ++i) {
        if (true) {
            vec1 << i;      // Test #5: No warning
            vec1.append(i); // Test #6: No warning
        }
    }

    for (int i = 0; i < 10; ++i) {
        QVector<int> v;
        v << 1; // OK
    }
}

void non_local_vector(QVector<int> &vec)
{
     // Test #7: No warning
    for (int i = 0; i < 10; ++i) {
        vec << i;
    }
}

bool returns_bool()
{
    return true;
}

unsigned int returns_uint() { return 0; }
int returns_int() { return 0; }
long long returns_long() { return 0; }

void test_complex_expressions()
{
    QVector<int> v;
    int a987r[10];
    for (int i = 0; a987r[i] == 1; ++i)
        v << i; // OK

    for (int i = 0; returns_bool(); ++i)
        v << i; // OK

    QVector<int> v2, v3;
    for (int i = 0; i < v2.size(); ++i)
        v3 << v3[i]; // Warning

    QVector<int> v4, v5;
    for (int i = 0; i < returns_uint(); ++i)
        v4 << v5[i]; // Warning

    QVector<int> v6, v7;
    for (int i = 0; i < returns_int(); ++i)
        v6 << v7[i]; // Warning

    QVector<int> v8, v9;
    for (int i = 0; i < returns_long(); ++i)
        v8 << v9[i]; // Warning
}

void test_nesting()
{
    QVector<int> v;

    while (returns_bool()) {
        for (int i = 0; i < 10; ++i)
            v << i; // OK
    }

    while (returns_bool()) {
        QVector<int> v2;
        for (int i = 0; i < 10; ++i)
            v2 << i; // Warning
    }

    QVector<int> v3;
    // Too many levels, this is ok, unless all of the cond expressions where literals but that's unlikely
    for (int i = 0; i < 10; ++i) {
        for (int i = 0; i < 10;  ++i) {
            for (int i = 0; i < 10; ++i) {
                for (int i = 0; i < 10; ++i) {
                    v3 << i; // OK
                }
            }
        }
    }

    QVector<int> a,b,c,d,e;
    foreach (int i, a)
        foreach (int i2, b)
                c << 1; // OK

}

void test_misc()
{
    QVector<int> v2;
    for (int i = 0; i < 10; ) {
        v2 << i; // OK
    }
}

class B
{
public:
    QVector<int> v;
};

class A
{
    A()
    {
        for (int i = 0; i < 10; ++i)
            v << i; // Warning

        for (int i = 0; i < 10; ++i)
            b.v << i; // OK
    }

    ~A()
    {
        for (int i = 0; i < 10; ++i)
            v << i; // Warning
    }

    void foo()
    {
        for (int i = 0; i < 10; ++i)
            v << i; // OK
    }

public:
    QVector<int> v;
    B b;
};

struct Node
{
    Node *next;
    int next2;
};

void testNode()
{
    QVector<int> v, v2;
    Node *node;
    for (int i = 0; i < 10; node = node->next) // OK
        v << i;

    for (int i = 0; i < 10; i = i + 1) v << i; // Warning

    for (auto it = v2.cbegin(), e = v2.cend(); it != e; ++it)
        v << 0; // Warning

    for (auto it = v2.cbegin(), e = v2.cend(); it != e; it = it + 1)
        v << 0; // Warning

    for (int i = 0; i < 10; i = node->next2)
        v << i; // OK

    for (int i = 0; i < 10; ++i) {
        v << 1;  // Warning
        v2 << 1; // Warning
    }

    for (int i = 0; i < 10; i = node->next2) {
        v.push_back(1);  // OK
        v.push_back(1);  // OK
        v2.push_back(1); // OK
        v2.push_back(1); // OK
    }
}

struct testCTOR
{
    testCTOR()
    {
        Node *node;
        for (int i = 0; i < 10; i = node->next2) {
            m_v << 1; // OK
        }
    }

    QVector<int> m_v;
};

void moreStuff()
{
    QVector<int> v;
    for (int i = 0; ; ++i)
        v.push_back(1);

    QHash<int,int> h;
    QHashIterator<int,int> it(h);
    while (it.hasNext()) { // Ok
        v.push_back(1);
    }
}

void rangeLoop()
{
    QVector<int> v1, v2;
    for (auto i : v1)
        v2.push_back(i);
}

struct Foo
{
    Foo ip() const;
    QList<Foo> addressEntries;
};

void testNesting2()
{
    QList<Foo> result;
    QList<Foo> privs;
    foreach (const Foo &p, privs)
        foreach (const Foo &entry, privs)
            result += entry.ip();

    QVector<int> v2;
    for (int u = 0; u < 10; ++u) {
        for (int n = 0; n < 10; ++n) {
            v2.append(1);
        }
    }

}
<commit_msg>Add test-case for false positive<commit_after>#include <QtCore/QVector>
#include <QtCore/QHash>
void local_vector()
{
    QVector<int> vec;
    for (int i = 0; i < 10; ++i) {
        vec << i;      // Test #1: Warning
        vec.append(i); // Test #2: Warning
    }

    QVector<int> vec1;
    vec1.reserve(10);
    for (int i = 0; i < 10; ++i) {
        vec1 << i;      // Test #3: No warning
        vec1.append(i); // Test #4: No warning
    }

    QVector<int> vec2;
    for (int i = 0; i < 10; ++i) {
        if (true) {
            vec1 << i;      // Test #5: No warning
            vec1.append(i); // Test #6: No warning
        }
    }

    for (int i = 0; i < 10; ++i) {
        QVector<int> v;
        v << 1; // OK
    }
}

void non_local_vector(QVector<int> &vec)
{
     // Test #7: No warning
    for (int i = 0; i < 10; ++i) {
        vec << i;
    }
}

bool returns_bool()
{
    return true;
}

unsigned int returns_uint() { return 0; }
int returns_int() { return 0; }
long long returns_long() { return 0; }

void test_complex_expressions()
{
    QVector<int> v;
    int a987r[10];
    for (int i = 0; a987r[i] == 1; ++i)
        v << i; // OK

    for (int i = 0; returns_bool(); ++i)
        v << i; // OK

    QVector<int> v2, v3;
    for (int i = 0; i < v2.size(); ++i)
        v3 << v3[i]; // Warning

    QVector<int> v4, v5;
    for (int i = 0; i < returns_uint(); ++i)
        v4 << v5[i]; // Warning

    QVector<int> v6, v7;
    for (int i = 0; i < returns_int(); ++i)
        v6 << v7[i]; // Warning

    QVector<int> v8, v9;
    for (int i = 0; i < returns_long(); ++i)
        v8 << v9[i]; // Warning
}

void test_nesting()
{
    QVector<int> v;

    while (returns_bool()) {
        for (int i = 0; i < 10; ++i)
            v << i; // OK
    }

    while (returns_bool()) {
        QVector<int> v2;
        for (int i = 0; i < 10; ++i)
            v2 << i; // Warning
    }

    QVector<int> v3;
    // Too many levels, this is ok, unless all of the cond expressions where literals but that's unlikely
    for (int i = 0; i < 10; ++i) {
        for (int i = 0; i < 10;  ++i) {
            for (int i = 0; i < 10; ++i) {
                for (int i = 0; i < 10; ++i) {
                    v3 << i; // OK
                }
            }
        }
    }

    QVector<int> a,b,c,d,e;
    foreach (int i, a)
        foreach (int i2, b)
                c << 1; // OK

}

void test_misc()
{
    QVector<int> v2;
    for (int i = 0; i < 10; ) {
        v2 << i; // OK
    }
}

class B
{
public:
    QVector<int> v;
};

class A
{
    A()
    {
        for (int i = 0; i < 10; ++i)
            v << i; // Warning

        for (int i = 0; i < 10; ++i)
            b.v << i; // OK
    }

    ~A()
    {
        for (int i = 0; i < 10; ++i)
            v << i; // Warning
    }

    void foo()
    {
        for (int i = 0; i < 10; ++i)
            v << i; // OK
    }

public:
    QVector<int> v;
    B b;
};

struct Node
{
    Node *next;
    int next2;
};

void testNode()
{
    QVector<int> v, v2;
    Node *node;
    for (int i = 0; i < 10; node = node->next) // OK
        v << i;

    for (int i = 0; i < 10; i = i + 1) v << i; // Warning

    for (auto it = v2.cbegin(), e = v2.cend(); it != e; ++it)
        v << 0; // Warning

    for (auto it = v2.cbegin(), e = v2.cend(); it != e; it = it + 1)
        v << 0; // Warning

    for (int i = 0; i < 10; i = node->next2)
        v << i; // OK

    for (int i = 0; i < 10; ++i) {
        v << 1;  // Warning
        v2 << 1; // Warning
    }

    for (int i = 0; i < 10; i = node->next2) {
        v.push_back(1);  // OK
        v.push_back(1);  // OK
        v2.push_back(1); // OK
        v2.push_back(1); // OK
    }
}

struct testCTOR
{
    testCTOR()
    {
        Node *node;
        for (int i = 0; i < 10; i = node->next2) {
            m_v << 1; // OK
        }
    }

    QVector<int> m_v;
};

void moreStuff()
{
    QVector<int> v;
    for (int i = 0; ; ++i)
        v.push_back(1);

    QHash<int,int> h;
    QHashIterator<int,int> it(h);
    while (it.hasNext()) { // Ok
        v.push_back(1);
    }
}

void rangeLoop()
{
    QVector<int> v1, v2;
    for (auto i : v1)
        v2.push_back(i);
}

struct Foo
{
    Foo ip() const;
    QList<Foo> addressEntries;
};

void testNesting2()
{
    QList<Foo> result;
    QList<Foo> privs;
    foreach (const Foo &p, privs)
        foreach (const Foo &entry, privs)
            result += entry.ip();

    QVector<int> v2;
    for (int u = 0; u < 10; ++u) {
        for (int n = 0; n < 10; ++n) {
            v2.append(1);
        }
    }
}

#include <QtCore/QQueue>
void bug362943()
{
    QVector<int> vect;
    QQueue<int> q;
    q.reserve(10);
    for (const int i: vect) {
        q << i;
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011-2013 Blender Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

#include "tile.h"

#include "util_algorithm.h"
#include "util_types.h"

CCL_NAMESPACE_BEGIN

TileManager::TileManager(bool progressive_, int num_samples_, int2 tile_size_, int start_resolution_,
                         bool preserve_tile_device_, bool background_, TileOrder tile_order_, int num_devices_)
{
	progressive = progressive_;
	tile_size = tile_size_;
	tile_order = tile_order_;
	start_resolution = start_resolution_;
	num_devices = num_devices_;
	preserve_tile_device = preserve_tile_device_;
	background = background_;

	BufferParams buffer_params;
	reset(buffer_params, 0);
}

TileManager::~TileManager()
{
}

void TileManager::reset(BufferParams& params_, int num_samples_)
{
	params = params_;

	int divider = 1;
	int w = params.width, h = params.height;

	if(start_resolution != INT_MAX) {
		while(w*h > start_resolution*start_resolution) {
			w = max(1, w/2);
			h = max(1, h/2);

			divider *= 2;
		}
	}

	num_samples = num_samples_;

	state.buffer = BufferParams();
	state.sample = -1;
	state.num_tiles = 0;
	state.num_rendered_tiles = 0;
	state.num_samples = 0;
	state.resolution_divider = divider;
	state.tiles.clear();
}

void TileManager::set_samples(int num_samples_)
{
	num_samples = num_samples_;
}

/* splits image into tiles and assigns equal amount of tiles to every render device */
void TileManager::gen_tiles_global()
{
	int resolution = state.resolution_divider;
	int image_w = max(1, params.width/resolution);
	int image_h = max(1, params.height/resolution);

	state.tiles.clear();

	int tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)/tile_size.x;
	int tile_h = (tile_size.y >= image_h)? 1: (image_h + tile_size.y - 1)/tile_size.y;

	int num_logical_devices = preserve_tile_device? num_devices: 1;
	int num = min(image_h, num_logical_devices);
	int tile_index = 0;

	int tiles_per_device = (tile_w * tile_h + num - 1) / num;
	int cur_device = 0, cur_tiles = 0;

	for(int tile_y = 0; tile_y < tile_h; tile_y++) {
		for(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) {
			int x = tile_x * tile_size.x;
			int y = tile_y * tile_size.y;
			int w = (tile_x == tile_w-1)? image_w - x: tile_size.x;
			int h = (tile_y == tile_h-1)? image_h - y: tile_size.y;

			state.tiles.push_back(Tile(tile_index, x, y, w, h, cur_device));
			cur_tiles++;

			if(cur_tiles == tiles_per_device) {
				cur_tiles = 0;
				cur_device++;
			}
		}
	}
}

/* slices image into as much pieces as how many devices are rendering this image */
void TileManager::gen_tiles_sliced()
{
	int resolution = state.resolution_divider;
	int image_w = max(1, params.width/resolution);
	int image_h = max(1, params.height/resolution);

	state.tiles.clear();

	int num_logical_devices = preserve_tile_device? num_devices: 1;
	int num = min(image_h, num_logical_devices);
	int tile_index = 0;

	for(int device = 0; device < num; device++) {
		int device_y = (image_h/num)*device;
		int device_h = (device == num-1)? image_h - device*(image_h/num): image_h/num;

		int tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)/tile_size.x;
		int tile_h = (tile_size.y >= device_h)? 1: (device_h + tile_size.y - 1)/tile_size.y;

		for(int tile_y = 0; tile_y < tile_h; tile_y++) {
			for(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) {
				int x = tile_x * tile_size.x;
				int y = tile_y * tile_size.y;
				int w = (tile_x == tile_w-1)? image_w - x: tile_size.x;
				int h = (tile_y == tile_h-1)? device_h - y: tile_size.y;

				state.tiles.push_back(Tile(tile_index, x, y + device_y, w, h, device));
			}
		}
	}
}

void TileManager::set_tiles()
{
	int resolution = state.resolution_divider;
	int image_w = max(1, params.width/resolution);
	int image_h = max(1, params.height/resolution);

	if(background)
		gen_tiles_global();
	else
		gen_tiles_sliced();

	state.num_tiles = state.tiles.size();

	state.buffer.width = image_w;
	state.buffer.height = image_h;

	state.buffer.full_x = params.full_x/resolution;
	state.buffer.full_y = params.full_y/resolution;
	state.buffer.full_width = max(1, params.full_width/resolution);
	state.buffer.full_height = max(1, params.full_height/resolution);
}

list<Tile>::iterator TileManager::next_viewport_tile(int device)
{
	list<Tile>::iterator iter;

	int logical_device = preserve_tile_device? device: 0;

	for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {
		if(iter->device == logical_device && iter->rendering == false)
		return iter;
	}

	return state.tiles.end();
}

list<Tile>::iterator TileManager::next_background_tile(int device, TileOrder tile_order)
{
	list<Tile>::iterator iter, best = state.tiles.end();

	int resolution = state.resolution_divider;
	int logical_device = preserve_tile_device? device: 0;

	int64_t cordx = max(1, params.width/resolution);
	int64_t cordy = max(1, params.height/resolution);
	int64_t mindist = INT_MAX;

	int64_t centx = cordx / 2, centy = cordy / 2;

	for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {
		if(iter->device == logical_device && iter->rendering == false) {
			Tile &cur_tile = *iter;

			int64_t distx = cordx;
			int64_t disty = cordy;

			switch (tile_order) {
				case TILE_CENTER:
					distx = centx - (cur_tile.x + cur_tile.w);
					disty = centy - (cur_tile.y + cur_tile.h);
					distx = (int64_t)sqrt((double)(distx * distx + disty * disty));
					break;
				case TILE_RIGHT_TO_LEFT:
					distx = cordx - cur_tile.x;
					break;
				case TILE_LEFT_TO_RIGHT:
					distx = cordx + cur_tile.x;
					break;
				case TILE_TOP_TO_BOTTOM:
					distx = cordx - cur_tile.y;
					break;
				case TILE_BOTTOM_TO_TOP:
					distx = cordx + cur_tile.y;
					break;
				default:
					break;
			}

			if(distx < mindist) {
				best = iter;
				mindist = distx;
			}
		}
	}

	return best;
}

bool TileManager::next_tile(Tile& tile, int device)
{
	list<Tile>::iterator tile_it;

	if (background)
		tile_it = next_background_tile(device, tile_order);
	else
		tile_it = next_viewport_tile(device);

	if(tile_it != state.tiles.end()) {
		tile_it->rendering = true;
		tile = *tile_it;
		state.num_rendered_tiles++;

		return true;
	}

	return false;
}

bool TileManager::done()
{
	return (state.sample+state.num_samples >= num_samples && state.resolution_divider == 1);
}

bool TileManager::next()
{
	if(done())
		return false;

	if(progressive && state.resolution_divider > 1) {
		state.sample = 0;
		state.resolution_divider /= 2;
		state.num_samples = 1;
		set_tiles();
	}
	else {
		state.sample++;

		if(progressive)
			state.num_samples = 1;
		else
			state.num_samples = num_samples;

		state.resolution_divider = 1;
		set_tiles();
	}

	return true;
}

CCL_NAMESPACE_END

<commit_msg>Cycles: Center Tile order had a slight offset to the left.<commit_after>/*
 * Copyright 2011-2013 Blender Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

#include "tile.h"

#include "util_algorithm.h"
#include "util_types.h"

CCL_NAMESPACE_BEGIN

TileManager::TileManager(bool progressive_, int num_samples_, int2 tile_size_, int start_resolution_,
                         bool preserve_tile_device_, bool background_, TileOrder tile_order_, int num_devices_)
{
	progressive = progressive_;
	tile_size = tile_size_;
	tile_order = tile_order_;
	start_resolution = start_resolution_;
	num_devices = num_devices_;
	preserve_tile_device = preserve_tile_device_;
	background = background_;

	BufferParams buffer_params;
	reset(buffer_params, 0);
}

TileManager::~TileManager()
{
}

void TileManager::reset(BufferParams& params_, int num_samples_)
{
	params = params_;

	int divider = 1;
	int w = params.width, h = params.height;

	if(start_resolution != INT_MAX) {
		while(w*h > start_resolution*start_resolution) {
			w = max(1, w/2);
			h = max(1, h/2);

			divider *= 2;
		}
	}

	num_samples = num_samples_;

	state.buffer = BufferParams();
	state.sample = -1;
	state.num_tiles = 0;
	state.num_rendered_tiles = 0;
	state.num_samples = 0;
	state.resolution_divider = divider;
	state.tiles.clear();
}

void TileManager::set_samples(int num_samples_)
{
	num_samples = num_samples_;
}

/* splits image into tiles and assigns equal amount of tiles to every render device */
void TileManager::gen_tiles_global()
{
	int resolution = state.resolution_divider;
	int image_w = max(1, params.width/resolution);
	int image_h = max(1, params.height/resolution);

	state.tiles.clear();

	int tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)/tile_size.x;
	int tile_h = (tile_size.y >= image_h)? 1: (image_h + tile_size.y - 1)/tile_size.y;

	int num_logical_devices = preserve_tile_device? num_devices: 1;
	int num = min(image_h, num_logical_devices);
	int tile_index = 0;

	int tiles_per_device = (tile_w * tile_h + num - 1) / num;
	int cur_device = 0, cur_tiles = 0;

	for(int tile_y = 0; tile_y < tile_h; tile_y++) {
		for(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) {
			int x = tile_x * tile_size.x;
			int y = tile_y * tile_size.y;
			int w = (tile_x == tile_w-1)? image_w - x: tile_size.x;
			int h = (tile_y == tile_h-1)? image_h - y: tile_size.y;

			state.tiles.push_back(Tile(tile_index, x, y, w, h, cur_device));
			cur_tiles++;

			if(cur_tiles == tiles_per_device) {
				cur_tiles = 0;
				cur_device++;
			}
		}
	}
}

/* slices image into as much pieces as how many devices are rendering this image */
void TileManager::gen_tiles_sliced()
{
	int resolution = state.resolution_divider;
	int image_w = max(1, params.width/resolution);
	int image_h = max(1, params.height/resolution);

	state.tiles.clear();

	int num_logical_devices = preserve_tile_device? num_devices: 1;
	int num = min(image_h, num_logical_devices);
	int tile_index = 0;

	for(int device = 0; device < num; device++) {
		int device_y = (image_h/num)*device;
		int device_h = (device == num-1)? image_h - device*(image_h/num): image_h/num;

		int tile_w = (tile_size.x >= image_w)? 1: (image_w + tile_size.x - 1)/tile_size.x;
		int tile_h = (tile_size.y >= device_h)? 1: (device_h + tile_size.y - 1)/tile_size.y;

		for(int tile_y = 0; tile_y < tile_h; tile_y++) {
			for(int tile_x = 0; tile_x < tile_w; tile_x++, tile_index++) {
				int x = tile_x * tile_size.x;
				int y = tile_y * tile_size.y;
				int w = (tile_x == tile_w-1)? image_w - x: tile_size.x;
				int h = (tile_y == tile_h-1)? device_h - y: tile_size.y;

				state.tiles.push_back(Tile(tile_index, x, y + device_y, w, h, device));
			}
		}
	}
}

void TileManager::set_tiles()
{
	int resolution = state.resolution_divider;
	int image_w = max(1, params.width/resolution);
	int image_h = max(1, params.height/resolution);

	if(background)
		gen_tiles_global();
	else
		gen_tiles_sliced();

	state.num_tiles = state.tiles.size();

	state.buffer.width = image_w;
	state.buffer.height = image_h;

	state.buffer.full_x = params.full_x/resolution;
	state.buffer.full_y = params.full_y/resolution;
	state.buffer.full_width = max(1, params.full_width/resolution);
	state.buffer.full_height = max(1, params.full_height/resolution);
}

list<Tile>::iterator TileManager::next_viewport_tile(int device)
{
	list<Tile>::iterator iter;

	int logical_device = preserve_tile_device? device: 0;

	for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {
		if(iter->device == logical_device && iter->rendering == false)
		return iter;
	}

	return state.tiles.end();
}

list<Tile>::iterator TileManager::next_background_tile(int device, TileOrder tile_order)
{
	list<Tile>::iterator iter, best = state.tiles.end();

	int resolution = state.resolution_divider;
	int logical_device = preserve_tile_device? device: 0;

	int64_t cordx = max(1, params.width/resolution);
	int64_t cordy = max(1, params.height/resolution);
	int64_t mindist = INT_MAX;

	int64_t centx = cordx / 2, centy = cordy / 2;

	for(iter = state.tiles.begin(); iter != state.tiles.end(); iter++) {
		if(iter->device == logical_device && iter->rendering == false) {
			Tile &cur_tile = *iter;

			int64_t distx = cordx;
			int64_t disty = cordy;

			switch (tile_order) {
				case TILE_CENTER:
					distx = centx - (cur_tile.x + (cur_tile.w / 2));
					disty = centy - (cur_tile.y + (cur_tile.h / 2));
					distx = (int64_t)sqrt((double)(distx * distx + disty * disty));
					break;
				case TILE_RIGHT_TO_LEFT:
					distx = cordx - cur_tile.x;
					break;
				case TILE_LEFT_TO_RIGHT:
					distx = cordx + cur_tile.x;
					break;
				case TILE_TOP_TO_BOTTOM:
					distx = cordx - cur_tile.y;
					break;
				case TILE_BOTTOM_TO_TOP:
					distx = cordx + cur_tile.y;
					break;
				default:
					break;
			}

			if(distx < mindist) {
				best = iter;
				mindist = distx;
			}
		}
	}

	return best;
}

bool TileManager::next_tile(Tile& tile, int device)
{
	list<Tile>::iterator tile_it;

	if (background)
		tile_it = next_background_tile(device, tile_order);
	else
		tile_it = next_viewport_tile(device);

	if(tile_it != state.tiles.end()) {
		tile_it->rendering = true;
		tile = *tile_it;
		state.num_rendered_tiles++;

		return true;
	}

	return false;
}

bool TileManager::done()
{
	return (state.sample+state.num_samples >= num_samples && state.resolution_divider == 1);
}

bool TileManager::next()
{
	if(done())
		return false;

	if(progressive && state.resolution_divider > 1) {
		state.sample = 0;
		state.resolution_divider /= 2;
		state.num_samples = 1;
		set_tiles();
	}
	else {
		state.sample++;

		if(progressive)
			state.num_samples = 1;
		else
			state.num_samples = num_samples;

		state.resolution_divider = 1;
		set_tiles();
	}

	return true;
}

CCL_NAMESPACE_END

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
using namespace std;

template<typename T>
struct Node
{
	T x;
	Node<T> * left;
	Node<T> * right;
	Node(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {}
};

template<typename T>
class Tree
{
private:
	Node<T> * root;
public:
	Tree()
	{
		root  = nullptr;
	}

	~Tree()
	{
		deleteNode(root);
	}

	void deleteNode(Node<T> * node)
	{
		if (node == nullptr) return;
		deleteNode(node->left);
		deleteNode(node->right);
		delete node;
	}

	T x_() const
	{
		return root->x;
	}

	T left_() const
	{
		return root->left->x;
	}

	T right_() const
	{
		return root->right->;
	}

	Node<T> * root_() const
	{
		return root;
	}

	void insert(const T& value)
	{
		insert(root, value);
	}

	void insert(Node<T>* & node, const T& value)
	{
		if (node) {
			if (value < node->x) {
				insert(node->left, value);
			}
			else if (value > node->x) {
				insert(node->right, value);
			}
			else {
				return;
			}
		}
		else {
			node = new Node<T>(value);
		}
	}

	Node<T> * search(const T& x)const
	{
		Node<T> * curEl = root;
		while (curEl != nullptr)
		{
			if (curEl->x == x)
				break;
			else
			{
				if (x > curEl->x)
					curEl = curEl->right;
				else curEl = curEl->left;
			}
		}
		return curEl;
	}

	void fIn(const string filename)
	{
		ifstream fin;
		unsigned int k;
		fin.open(filename);
		if (!fin.is_open())
			cout << "The file isn't find" << endl;
		else
		{
			deleteNode(root);
			if (fin.eof()) return;
			else
			{
				fin >> k;
				T newEl;
				for (unsigned int i = 0; i < k; ++i)
				{
					fin >> newEl;
					insert(newEl);
				}
			}
			fin.close();
		}
	}

	unsigned int size(Node<T> * node)const
	{
		unsigned int size_ = 0;
		if (node != nullptr)
			size_ = size(node->left) + 1 + size(node->right);
		return size_;
	}

	void out_to_file(const string filename)const
	{
		ofstream fout;
		fout.open(filename);
		if (!fout.is_open())
			cout << "The file isn't find" << endl;
		else
		{
			unsigned int size_ = size(root);
			if (size_ == 0)
				return;
			fout << size_ << "\t";
			fOut(root, fout);
			fout.close();
		}
	}

	void fOut(Node<T> * node, ostream&stream)const
	{
		if (node != nullptr)
		{
			fOut(node->left, stream);
			stream << node->x << " ";
			fOut(node->right, stream);
		}
	}

	void out(ostream & stream)const
	{
		Out(root, stream, 0);
	}

	void Out(Node<T> * node, ostream&stream, size_t level)const
	{
		Node<T> * curEl = node;
		if (curEl != nullptr)
		{
			Out(curEl->right, stream, level + 1);
			for (unsigned int i = 0; i < level; ++i)
				stream << '-';
			stream << curEl->x << endl;
			Out(curEl->left, stream, level + 1);
		}
	}
};
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
using namespace std;

template<typename T>
struct Node
{
	T x;
	Node<T> * left;
	Node<T> * right;
	Node(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {}
};

template<typename T>
class Tree
{
private:
	Node<T> * root;
public:
	Tree()
	{
		root  = nullptr;
	}

	~Tree()
	{
		deleteNode(root);
	}

	void deleteNode(Node<T> * node)
	{
		if (node == nullptr) return;
		deleteNode(node->left);
		deleteNode(node->right);
		delete node;
	}

	T x_() const
	{
		return root->x;
	}

	T left_() const
	{
		return root->left->x;
	}

	T right_() const
	{
		return root->right->x;
	}

	Node<T> * root_() const
	{
		return root;
	}

	void insert(const T& value)
	{
		insert(root, value);
	}

	void insert(Node<T>* & node, const T& value)
	{
		if (node) {
			if (value < node->x) {
				insert(node->left, value);
			}
			else if (value > node->x) {
				insert(node->right, value);
			}
			else {
				return;
			}
		}
		else {
			node = new Node<T>(value);
		}
	}

	Node<T> * search(const T& x)const
	{
		Node<T> * curEl = root;
		while (curEl != nullptr)
		{
			if (curEl->x == x)
				break;
			else
			{
				if (x > curEl->x)
					curEl = curEl->right;
				else curEl = curEl->left;
			}
		}
		return curEl;
	}

	void fIn(const string filename)
	{
		ifstream fin;
		unsigned int k;
		fin.open(filename);
		if (!fin.is_open())
			cout << "The file isn't find" << endl;
		else
		{
			deleteNode(root);
			if (fin.eof()) return;
			else
			{
				fin >> k;
				T newEl;
				for (unsigned int i = 0; i < k; ++i)
				{
					fin >> newEl;
					insert(newEl);
				}
			}
			fin.close();
		}
	}

	unsigned int size(Node<T> * node)const
	{
		unsigned int size_ = 0;
		if (node != nullptr)
			size_ = size(node->left) + 1 + size(node->right);
		return size_;
	}

	void out_to_file(const string filename)const
	{
		ofstream fout;
		fout.open(filename);
		if (!fout.is_open())
			cout << "The file isn't find" << endl;
		else
		{
			unsigned int size_ = size(root);
			if (size_ == 0)
				return;
			fout << size_ << "\t";
			fOut(root, fout);
			fout.close();
		}
	}

	void fOut(Node<T> * node, ostream&stream)const
	{
		if (node != nullptr)
		{
			fOut(node->left, stream);
			stream << node->x << " ";
			fOut(node->right, stream);
		}
	}

	void out(ostream & stream)const
	{
		Out(root, stream, 0);
	}

	void Out(Node<T> * node, ostream&stream, size_t level)const
	{
		Node<T> * curEl = node;
		if (curEl != nullptr)
		{
			Out(curEl->right, stream, level + 1);
			for (unsigned int i = 0; i < level; ++i)
				stream << '-';
			stream << curEl->x << endl;
			Out(curEl->left, stream, level + 1);
		}
	}
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlfonte.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 12:53:13 $
 *
 *  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_sc.hxx"
#ifdef PRECOMPILED
#include "filt_pch.hxx"
#endif

#ifndef SC_ITEMS_HXX
#include "scitems.hxx"
#endif

#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD

#ifndef _XMLOFF_XMLFONTAUTOSTYLEPOOL_HXX
#include <xmloff/XMLFontAutoStylePool.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif
#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif
#ifndef _MyEDITENG_HXX
#include <svx/editeng.hxx>
#endif

#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_SCDOCPOL_HXX
#include "docpool.hxx"
#endif
#ifndef SC_XMLEXPRT_HXX
#include "xmlexprt.hxx"
#endif
#ifndef SC_STLPOOL_HXX
#include "stlpool.hxx"
#endif
#ifndef SC_SCATTR_HXX
#include "attrib.hxx"
#endif

class ScXMLFontAutoStylePool_Impl: public XMLFontAutoStylePool
{
    void AddFontItems(sal_uInt16* pWhichIds, sal_uInt8 nIdCount, const SfxItemPool* pPool, const sal_Bool bExportDefaults);
    public:

    ScXMLFontAutoStylePool_Impl( ScXMLExport& rExport );

};

void ScXMLFontAutoStylePool_Impl::AddFontItems(sal_uInt16* pWhichIds, sal_uInt8 nIdCount, const SfxItemPool* pPool, const sal_Bool bExportDefaults)
{
    const SfxPoolItem* pItem;
    for( sal_uInt16 i=0; i < nIdCount; ++i )
    {
        sal_uInt16 nWhichId(pWhichIds[i]);
        if (bExportDefaults && (0 != (pItem = &pPool->GetDefaultItem(nWhichId))))
        {
            const SvxFontItem *pFont((const SvxFontItem *)pItem);
            Add( pFont->GetFamilyName(), pFont->GetStyleName(),
                    pFont->GetFamily(), pFont->GetPitch(),
                    pFont->GetCharSet() );
        }
        sal_uInt16 nItems(pPool->GetItemCount( nWhichId ));
        for( sal_uInt16 j = 0; j < nItems; ++j )
        {
            if( 0 != (pItem = pPool->GetItem( nWhichId, j ) ) )
            {
                const SvxFontItem *pFont((const SvxFontItem *)pItem);
                Add( pFont->GetFamilyName(), pFont->GetStyleName(),
                     pFont->GetFamily(), pFont->GetPitch(),
                     pFont->GetCharSet() );
            }
        }
    }
}

ScXMLFontAutoStylePool_Impl::ScXMLFontAutoStylePool_Impl(
    ScXMLExport& rExport ) :
    XMLFontAutoStylePool( rExport )
{
    sal_uInt16 aWhichIds[3] = { ATTR_FONT, ATTR_CJK_FONT,
                                ATTR_CTL_FONT };
    sal_uInt16 aEditWhichIds[3] = { EE_CHAR_FONTINFO, EE_CHAR_FONTINFO_CJK,
                                    EE_CHAR_FONTINFO_CTL };
    sal_uInt16 aPageWhichIds[4] = { ATTR_PAGE_HEADERLEFT, ATTR_PAGE_FOOTERLEFT,
                                    ATTR_PAGE_HEADERRIGHT, ATTR_PAGE_FOOTERRIGHT };

    const SfxItemPool* pPool(rExport.GetDocument() ? rExport.GetDocument()->GetPool() : NULL);
    AddFontItems(aWhichIds, 3, pPool, sal_True);
    const SfxItemPool* pEditPool(rExport.GetDocument()->GetEditPool());
    AddFontItems(aEditWhichIds, 3, pEditPool, sal_False);

    SfxStyleSheetIterator* pItr(rExport.GetDocument() ? rExport.GetDocument()->GetStyleSheetPool()->CreateIterator(SFX_STYLE_FAMILY_PAGE, 0xFFFF) : NULL);
    if(pItr)
    {
        SfxStyleSheetBase* pStyle(pItr->First());
        SfxItemPool* pPageEditPool(EditEngine::CreatePool());
        EditEngine aEditEngine(pPageEditPool);
        while (pStyle)
        {
            const SfxItemPool& rPagePool(pStyle->GetPool().GetPool());
            for (sal_uInt8 j = 0; j < 4; ++j)
            {
                sal_uInt16 nPageWhichId(aPageWhichIds[j]);
                sal_uInt16 nPageHFItems(rPagePool.GetItemCount(nPageWhichId));
                const ScPageHFItem* pPageItem;
                for (sal_uInt16 k = 0; k < nPageHFItems; ++k)
                {
                    if (0 != (pPageItem = static_cast<const ScPageHFItem*>(rPagePool.GetItem(nPageWhichId, k))))
                    {
                        const EditTextObject* pLeftArea(pPageItem->GetLeftArea());
                        if (pLeftArea)
                        {
                            aEditEngine.SetText(*pLeftArea);
                            AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);
                        }
                        const EditTextObject* pCenterArea(pPageItem->GetCenterArea());
                        if (pCenterArea)
                        {
                            aEditEngine.SetText(*pCenterArea);
                            AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);
                        }
                        const EditTextObject* pRightArea(pPageItem->GetRightArea());
                        if (pRightArea)
                        {
                            aEditEngine.SetText(*pRightArea);
                            AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);
                        }
                    }
                }
            }
            pStyle = pItr->Next();
        }
    }
}

XMLFontAutoStylePool* ScXMLExport::CreateFontAutoStylePool()
{
    return new ScXMLFontAutoStylePool_Impl( *this );
}
<commit_msg>INTEGRATION: CWS calcwarnings (1.9.110); FILE MERGED 2006/12/13 10:30:19 nn 1.9.110.2: #i69284# warning-free: filter/xml, unxlngi6 2006/12/01 13:29:19 nn 1.9.110.1: #i69284# warning-free: filter/xml, wntmsci10<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlfonte.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: vg $ $Date: 2007-02-27 12:51:13 $
 *
 *  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_sc.hxx"
#ifdef PRECOMPILED
#include "filt_pch.hxx"
#endif

#ifndef SC_ITEMS_HXX
#include "scitems.hxx"
#endif

#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD

#ifndef _XMLOFF_XMLFONTAUTOSTYLEPOOL_HXX
#include <xmloff/XMLFontAutoStylePool.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif
#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif
#ifndef _MyEDITENG_HXX
#include <svx/editeng.hxx>
#endif

#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_SCDOCPOL_HXX
#include "docpool.hxx"
#endif
#ifndef SC_XMLEXPRT_HXX
#include "xmlexprt.hxx"
#endif
#ifndef SC_STLPOOL_HXX
#include "stlpool.hxx"
#endif
#ifndef SC_SCATTR_HXX
#include "attrib.hxx"
#endif

class ScXMLFontAutoStylePool_Impl: public XMLFontAutoStylePool
{
    void AddFontItems(sal_uInt16* pWhichIds, sal_uInt8 nIdCount, const SfxItemPool* pItemPool, const sal_Bool bExportDefaults);
    public:

    ScXMLFontAutoStylePool_Impl( ScXMLExport& rExport );

};

void ScXMLFontAutoStylePool_Impl::AddFontItems(sal_uInt16* pWhichIds, sal_uInt8 nIdCount, const SfxItemPool* pItemPool, const sal_Bool bExportDefaults)
{
    const SfxPoolItem* pItem;
    for( sal_uInt16 i=0; i < nIdCount; ++i )
    {
        sal_uInt16 nWhichId(pWhichIds[i]);
        if (bExportDefaults && (0 != (pItem = &pItemPool->GetDefaultItem(nWhichId))))
        {
            const SvxFontItem *pFont((const SvxFontItem *)pItem);
            Add( pFont->GetFamilyName(), pFont->GetStyleName(),
                    sal::static_int_cast<sal_Int16>(pFont->GetFamily()),
                    sal::static_int_cast<sal_Int16>(pFont->GetPitch()),
                    pFont->GetCharSet() );
        }
        sal_uInt16 nItems(pItemPool->GetItemCount( nWhichId ));
        for( sal_uInt16 j = 0; j < nItems; ++j )
        {
            if( 0 != (pItem = pItemPool->GetItem( nWhichId, j ) ) )
            {
                const SvxFontItem *pFont((const SvxFontItem *)pItem);
                Add( pFont->GetFamilyName(), pFont->GetStyleName(),
                     sal::static_int_cast<sal_Int16>(pFont->GetFamily()),
                     sal::static_int_cast<sal_Int16>(pFont->GetPitch()),
                     pFont->GetCharSet() );
            }
        }
    }
}

ScXMLFontAutoStylePool_Impl::ScXMLFontAutoStylePool_Impl(
    ScXMLExport& rExportP ) :
    XMLFontAutoStylePool( rExportP )
{
    sal_uInt16 aWhichIds[3] = { ATTR_FONT, ATTR_CJK_FONT,
                                ATTR_CTL_FONT };
    sal_uInt16 aEditWhichIds[3] = { EE_CHAR_FONTINFO, EE_CHAR_FONTINFO_CJK,
                                    EE_CHAR_FONTINFO_CTL };
    sal_uInt16 aPageWhichIds[4] = { ATTR_PAGE_HEADERLEFT, ATTR_PAGE_FOOTERLEFT,
                                    ATTR_PAGE_HEADERRIGHT, ATTR_PAGE_FOOTERRIGHT };

    const SfxItemPool* pItemPool(rExportP.GetDocument() ? rExportP.GetDocument()->GetPool() : NULL);
    AddFontItems(aWhichIds, 3, pItemPool, sal_True);
    const SfxItemPool* pEditPool(rExportP.GetDocument()->GetEditPool());
    AddFontItems(aEditWhichIds, 3, pEditPool, sal_False);

    SfxStyleSheetIterator* pItr(rExportP.GetDocument() ? rExportP.GetDocument()->GetStyleSheetPool()->CreateIterator(SFX_STYLE_FAMILY_PAGE, 0xFFFF) : NULL);
    if(pItr)
    {
        SfxStyleSheetBase* pStyle(pItr->First());
        SfxItemPool* pPageEditPool(EditEngine::CreatePool());
        EditEngine aEditEngine(pPageEditPool);
        while (pStyle)
        {
            const SfxItemPool& rPagePool(pStyle->GetPool().GetPool());
            for (sal_uInt8 j = 0; j < 4; ++j)
            {
                sal_uInt16 nPageWhichId(aPageWhichIds[j]);
                sal_uInt16 nPageHFItems(rPagePool.GetItemCount(nPageWhichId));
                const ScPageHFItem* pPageItem;
                for (sal_uInt16 k = 0; k < nPageHFItems; ++k)
                {
                    if (0 != (pPageItem = static_cast<const ScPageHFItem*>(rPagePool.GetItem(nPageWhichId, k))))
                    {
                        const EditTextObject* pLeftArea(pPageItem->GetLeftArea());
                        if (pLeftArea)
                        {
                            aEditEngine.SetText(*pLeftArea);
                            AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);
                        }
                        const EditTextObject* pCenterArea(pPageItem->GetCenterArea());
                        if (pCenterArea)
                        {
                            aEditEngine.SetText(*pCenterArea);
                            AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);
                        }
                        const EditTextObject* pRightArea(pPageItem->GetRightArea());
                        if (pRightArea)
                        {
                            aEditEngine.SetText(*pRightArea);
                            AddFontItems(aEditWhichIds, 3, pPageEditPool, sal_False);
                        }
                    }
                }
            }
            pStyle = pItr->Next();
        }
    }
}

XMLFontAutoStylePool* ScXMLExport::CreateFontAutoStylePool()
{
    return new ScXMLFontAutoStylePool_Impl( *this );
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tabpages.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 13:15:52 $
 *
 *  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_sc.hxx"

#undef SC_DLLIMPLEMENTATION

#include "global.hxx"
#include "document.hxx"
#include "attrib.hxx"
#include "scresid.hxx"
#include "sc.hrc"

#include "attrdlg.hrc"
#include "tabpages.hxx"

// STATIC DATA -----------------------------------------------------------

static USHORT pProtectionRanges[] =
{
    SID_SCATTR_PROTECTION,
    SID_SCATTR_PROTECTION,
    0
};

//========================================================================
// Zellschutz-Tabpage:
//========================================================================

ScTabPageProtection::ScTabPageProtection( Window*           pParent,
                                          const SfxItemSet& rCoreAttrs )
    :   SfxTabPage          ( pParent,
                              ScResId( RID_SCPAGE_PROTECTION ),
                              rCoreAttrs ),
        //
        aFlProtect          ( this, ScResId( FL_PROTECTION      ) ),
        aBtnProtect         ( this, ScResId( BTN_PROTECTED      ) ),
        aBtnHideCell        ( this, ScResId( BTN_HIDE_ALL       ) ),
        aBtnHideFormula     ( this, ScResId( BTN_HIDE_FORMULAR  ) ),
        aTxtHint            ( this, ScResId( FT_HINT            ) ),
        aFlPrint            ( this, ScResId( FL_PRINT           ) ),
        aBtnHidePrint       ( this, ScResId( BTN_HIDE_PRINT     ) ),
        aTxtHint2           ( this, ScResId( FT_HINT2           ) )
{
    // diese Page braucht ExchangeSupport
    SetExchangeSupport();

    //  States werden in Reset gesetzt
    bTriEnabled = bDontCare = bProtect = bHideForm = bHideCell = bHidePrint = FALSE;

    aBtnProtect.SetClickHdl(     LINK( this, ScTabPageProtection, ButtonClickHdl ) );
    aBtnHideCell.SetClickHdl(    LINK( this, ScTabPageProtection, ButtonClickHdl ) );
    aBtnHideFormula.SetClickHdl( LINK( this, ScTabPageProtection, ButtonClickHdl ) );
    aBtnHidePrint.SetClickHdl(   LINK( this, ScTabPageProtection, ButtonClickHdl ) );

    FreeResource();
}

// -----------------------------------------------------------------------

__EXPORT ScTabPageProtection::~ScTabPageProtection()
{
}

//------------------------------------------------------------------------

USHORT* __EXPORT ScTabPageProtection::GetRanges()
{
    return pProtectionRanges;
}

// -----------------------------------------------------------------------

SfxTabPage* __EXPORT ScTabPageProtection::Create( Window*           pParent,
                                                  const SfxItemSet& rAttrSet )
{
    return ( new ScTabPageProtection( pParent, rAttrSet ) );
}

//------------------------------------------------------------------------

void __EXPORT ScTabPageProtection::Reset( const SfxItemSet& rCoreAttrs )
{
    //  Variablen initialisieren

    USHORT nWhich = GetWhich( SID_SCATTR_PROTECTION );
    const ScProtectionAttr* pProtAttr = NULL;
    SfxItemState eItemState = rCoreAttrs.GetItemState( nWhich, FALSE,
                                          (const SfxPoolItem**)&pProtAttr );

    // handelt es sich um ein Default-Item?
    if ( eItemState == SFX_ITEM_DEFAULT )
        pProtAttr = (const ScProtectionAttr*)&(rCoreAttrs.Get(nWhich));
    // bei SFX_ITEM_DONTCARE auf 0 lassen

    bTriEnabled = ( pProtAttr == NULL );                // TriState, wenn DontCare
    bDontCare = bTriEnabled;
    if (bTriEnabled)
    {
        //  Defaults, die erscheinen wenn ein TriState weggeklickt wird:
        //  (weil alles zusammen ein Attribut ist, kann auch nur alles zusammen
        //  auf DontCare stehen - #38543#)
        bProtect = TRUE;
        bHideForm = bHideCell = bHidePrint = FALSE;
    }
    else
    {
        bProtect = pProtAttr->GetProtection();
        bHideCell = pProtAttr->GetHideCell();
        bHideForm = pProtAttr->GetHideFormula();
        bHidePrint = pProtAttr->GetHidePrint();
    }

    //  Controls initialisieren

    aBtnProtect     .EnableTriState( bTriEnabled );
    aBtnHideCell    .EnableTriState( bTriEnabled );
    aBtnHideFormula .EnableTriState( bTriEnabled );
    aBtnHidePrint   .EnableTriState( bTriEnabled );

    UpdateButtons();
}

// -----------------------------------------------------------------------

BOOL __EXPORT ScTabPageProtection::FillItemSet( SfxItemSet& rCoreAttrs )
{
    BOOL                bAttrsChanged   = FALSE;
    USHORT              nWhich          = GetWhich( SID_SCATTR_PROTECTION );
    const SfxPoolItem*  pOldItem        = GetOldItem( rCoreAttrs, SID_SCATTR_PROTECTION );
    const SfxItemSet&   rOldSet         = GetItemSet();
    SfxItemState        eItemState      = rOldSet.GetItemState( nWhich, FALSE );
    ScProtectionAttr    aProtAttr;

    if ( !bDontCare )
    {
        aProtAttr.SetProtection( bProtect );
        aProtAttr.SetHideCell( bHideCell );
        aProtAttr.SetHideFormula( bHideForm );
        aProtAttr.SetHidePrint( bHidePrint );

        if ( bTriEnabled )
            bAttrsChanged = TRUE;                   // DontCare -> richtiger Wert
        else
            bAttrsChanged = !pOldItem || !( aProtAttr == *(const ScProtectionAttr*)pOldItem );
    }

    //--------------------------------------------------

    if ( bAttrsChanged )
        rCoreAttrs.Put( aProtAttr );
    else if ( eItemState == SFX_ITEM_DEFAULT )
        rCoreAttrs.ClearItem( nWhich );

    return bAttrsChanged;
}

//------------------------------------------------------------------------

int __EXPORT ScTabPageProtection::DeactivatePage( SfxItemSet* pSet )
{
    if ( pSet )
        FillItemSet( *pSet );

    return LEAVE_PAGE;
}

//------------------------------------------------------------------------

IMPL_LINK( ScTabPageProtection, ButtonClickHdl, TriStateBox*, pBox )
{
    TriState eState = pBox->GetState();
    if ( eState == STATE_DONTKNOW )
        bDontCare = TRUE;                           // alles zusammen auf DontCare
    else
    {
        bDontCare = FALSE;                          // DontCare ueberall aus
        BOOL bOn = ( eState == STATE_CHECK );       // ausgewaehlter Wert

        if ( pBox == &aBtnProtect )
            bProtect = bOn;
        else if ( pBox == &aBtnHideCell )
            bHideCell = bOn;
        else if ( pBox == &aBtnHideFormula )
            bHideForm = bOn;
        else if ( pBox == &aBtnHidePrint )
            bHidePrint = bOn;
        else
            DBG_ERRORFILE("falscher Button");
    }

    UpdateButtons();        // TriState und Enable-Logik

    return 0;
}

//------------------------------------------------------------------------

void ScTabPageProtection::UpdateButtons()
{
    if ( bDontCare )
    {
        aBtnProtect.SetState( STATE_DONTKNOW );
        aBtnHideCell.SetState( STATE_DONTKNOW );
        aBtnHideFormula.SetState( STATE_DONTKNOW );
        aBtnHidePrint.SetState( STATE_DONTKNOW );
    }
    else
    {
        aBtnProtect.SetState( bProtect ? STATE_CHECK : STATE_NOCHECK );
        aBtnHideCell.SetState( bHideCell ? STATE_CHECK : STATE_NOCHECK );
        aBtnHideFormula.SetState( bHideForm ? STATE_CHECK : STATE_NOCHECK );
        aBtnHidePrint.SetState( bHidePrint ? STATE_CHECK : STATE_NOCHECK );
    }

    BOOL bEnable = ( aBtnHideCell.GetState() != STATE_CHECK );
    {
        aBtnProtect.Enable( bEnable );
        aBtnHideFormula.Enable( bEnable );
    }
}
<commit_msg>INTEGRATION: CWS calcwarnings (1.6.110); FILE MERGED 2006/12/12 17:03:07 nn 1.6.110.1: #i69284# warning-free: ui, unxlngi6<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tabpages.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2007-02-27 13:00:23 $
 *
 *  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_sc.hxx"

#undef SC_DLLIMPLEMENTATION

#include "global.hxx"
#include "document.hxx"
#include "attrib.hxx"
#include "scresid.hxx"
#include "sc.hrc"

#include "attrdlg.hrc"
#include "tabpages.hxx"

// STATIC DATA -----------------------------------------------------------

static USHORT pProtectionRanges[] =
{
    SID_SCATTR_PROTECTION,
    SID_SCATTR_PROTECTION,
    0
};

//========================================================================
// Zellschutz-Tabpage:
//========================================================================

ScTabPageProtection::ScTabPageProtection( Window*           pParent,
                                          const SfxItemSet& rCoreAttrs )
    :   SfxTabPage          ( pParent,
                              ScResId( RID_SCPAGE_PROTECTION ),
                              rCoreAttrs ),
        //
        aFlProtect          ( this, ScResId( FL_PROTECTION      ) ),
        aBtnHideCell        ( this, ScResId( BTN_HIDE_ALL       ) ),
        aBtnProtect         ( this, ScResId( BTN_PROTECTED      ) ),
        aBtnHideFormula     ( this, ScResId( BTN_HIDE_FORMULAR  ) ),
        aTxtHint            ( this, ScResId( FT_HINT            ) ),
        aFlPrint            ( this, ScResId( FL_PRINT           ) ),
        aBtnHidePrint       ( this, ScResId( BTN_HIDE_PRINT     ) ),
        aTxtHint2           ( this, ScResId( FT_HINT2           ) )
{
    // diese Page braucht ExchangeSupport
    SetExchangeSupport();

    //  States werden in Reset gesetzt
    bTriEnabled = bDontCare = bProtect = bHideForm = bHideCell = bHidePrint = FALSE;

    aBtnProtect.SetClickHdl(     LINK( this, ScTabPageProtection, ButtonClickHdl ) );
    aBtnHideCell.SetClickHdl(    LINK( this, ScTabPageProtection, ButtonClickHdl ) );
    aBtnHideFormula.SetClickHdl( LINK( this, ScTabPageProtection, ButtonClickHdl ) );
    aBtnHidePrint.SetClickHdl(   LINK( this, ScTabPageProtection, ButtonClickHdl ) );

    FreeResource();
}

// -----------------------------------------------------------------------

__EXPORT ScTabPageProtection::~ScTabPageProtection()
{
}

//------------------------------------------------------------------------

USHORT* __EXPORT ScTabPageProtection::GetRanges()
{
    return pProtectionRanges;
}

// -----------------------------------------------------------------------

SfxTabPage* __EXPORT ScTabPageProtection::Create( Window*           pParent,
                                                  const SfxItemSet& rAttrSet )
{
    return ( new ScTabPageProtection( pParent, rAttrSet ) );
}

//------------------------------------------------------------------------

void __EXPORT ScTabPageProtection::Reset( const SfxItemSet& rCoreAttrs )
{
    //  Variablen initialisieren

    USHORT nWhich = GetWhich( SID_SCATTR_PROTECTION );
    const ScProtectionAttr* pProtAttr = NULL;
    SfxItemState eItemState = rCoreAttrs.GetItemState( nWhich, FALSE,
                                          (const SfxPoolItem**)&pProtAttr );

    // handelt es sich um ein Default-Item?
    if ( eItemState == SFX_ITEM_DEFAULT )
        pProtAttr = (const ScProtectionAttr*)&(rCoreAttrs.Get(nWhich));
    // bei SFX_ITEM_DONTCARE auf 0 lassen

    bTriEnabled = ( pProtAttr == NULL );                // TriState, wenn DontCare
    bDontCare = bTriEnabled;
    if (bTriEnabled)
    {
        //  Defaults, die erscheinen wenn ein TriState weggeklickt wird:
        //  (weil alles zusammen ein Attribut ist, kann auch nur alles zusammen
        //  auf DontCare stehen - #38543#)
        bProtect = TRUE;
        bHideForm = bHideCell = bHidePrint = FALSE;
    }
    else
    {
        bProtect = pProtAttr->GetProtection();
        bHideCell = pProtAttr->GetHideCell();
        bHideForm = pProtAttr->GetHideFormula();
        bHidePrint = pProtAttr->GetHidePrint();
    }

    //  Controls initialisieren

    aBtnProtect     .EnableTriState( bTriEnabled );
    aBtnHideCell    .EnableTriState( bTriEnabled );
    aBtnHideFormula .EnableTriState( bTriEnabled );
    aBtnHidePrint   .EnableTriState( bTriEnabled );

    UpdateButtons();
}

// -----------------------------------------------------------------------

BOOL __EXPORT ScTabPageProtection::FillItemSet( SfxItemSet& rCoreAttrs )
{
    BOOL                bAttrsChanged   = FALSE;
    USHORT              nWhich          = GetWhich( SID_SCATTR_PROTECTION );
    const SfxPoolItem*  pOldItem        = GetOldItem( rCoreAttrs, SID_SCATTR_PROTECTION );
    const SfxItemSet&   rOldSet         = GetItemSet();
    SfxItemState        eItemState      = rOldSet.GetItemState( nWhich, FALSE );
    ScProtectionAttr    aProtAttr;

    if ( !bDontCare )
    {
        aProtAttr.SetProtection( bProtect );
        aProtAttr.SetHideCell( bHideCell );
        aProtAttr.SetHideFormula( bHideForm );
        aProtAttr.SetHidePrint( bHidePrint );

        if ( bTriEnabled )
            bAttrsChanged = TRUE;                   // DontCare -> richtiger Wert
        else
            bAttrsChanged = !pOldItem || !( aProtAttr == *(const ScProtectionAttr*)pOldItem );
    }

    //--------------------------------------------------

    if ( bAttrsChanged )
        rCoreAttrs.Put( aProtAttr );
    else if ( eItemState == SFX_ITEM_DEFAULT )
        rCoreAttrs.ClearItem( nWhich );

    return bAttrsChanged;
}

//------------------------------------------------------------------------

int __EXPORT ScTabPageProtection::DeactivatePage( SfxItemSet* pSetP )
{
    if ( pSetP )
        FillItemSet( *pSetP );

    return LEAVE_PAGE;
}

//------------------------------------------------------------------------

IMPL_LINK( ScTabPageProtection, ButtonClickHdl, TriStateBox*, pBox )
{
    TriState eState = pBox->GetState();
    if ( eState == STATE_DONTKNOW )
        bDontCare = TRUE;                           // alles zusammen auf DontCare
    else
    {
        bDontCare = FALSE;                          // DontCare ueberall aus
        BOOL bOn = ( eState == STATE_CHECK );       // ausgewaehlter Wert

        if ( pBox == &aBtnProtect )
            bProtect = bOn;
        else if ( pBox == &aBtnHideCell )
            bHideCell = bOn;
        else if ( pBox == &aBtnHideFormula )
            bHideForm = bOn;
        else if ( pBox == &aBtnHidePrint )
            bHidePrint = bOn;
        else
            DBG_ERRORFILE("falscher Button");
    }

    UpdateButtons();        // TriState und Enable-Logik

    return 0;
}

//------------------------------------------------------------------------

void ScTabPageProtection::UpdateButtons()
{
    if ( bDontCare )
    {
        aBtnProtect.SetState( STATE_DONTKNOW );
        aBtnHideCell.SetState( STATE_DONTKNOW );
        aBtnHideFormula.SetState( STATE_DONTKNOW );
        aBtnHidePrint.SetState( STATE_DONTKNOW );
    }
    else
    {
        aBtnProtect.SetState( bProtect ? STATE_CHECK : STATE_NOCHECK );
        aBtnHideCell.SetState( bHideCell ? STATE_CHECK : STATE_NOCHECK );
        aBtnHideFormula.SetState( bHideForm ? STATE_CHECK : STATE_NOCHECK );
        aBtnHidePrint.SetState( bHidePrint ? STATE_CHECK : STATE_NOCHECK );
    }

    BOOL bEnable = ( aBtnHideCell.GetState() != STATE_CHECK );
    {
        aBtnProtect.Enable( bEnable );
        aBtnHideFormula.Enable( bEnable );
    }
}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX64M/RX71M/RX651/RX65N/RX66T グループ・システム制御
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX600/system.hpp"

#ifndef F_ICLK
#  error "system_io.hpp requires F_ICLK to be defined"
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  systen_io クラス
		@param[in]	BASE_CLOCK	ベース・クロック周波数（１２ＭＨｚ）
		@param[in]	INTR_CLOCK	内臓クロック周波数（２４０ＭＨｚ）
		@param[in]	EXT_CLOCK	外部クロックに入力を行う場合「true」
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t BASE_CLOCK = 12000000, uint32_t INTR_CLOCK = 240000000,
		bool EXT_CLOCK = false>
	struct system_io {

		static uint8_t clock_div_(uint32_t clk) noexcept
		{
			uint8_t div = 0;
			while(clk < INTR_CLOCK) {
				++div;
				clk <<= 1;
			}
			return div;
		}

		//-------------------------------------------------------------//
		/*!
			@brief  システム・クロックの設定
		*/
		//-------------------------------------------------------------//
		static void setup_system_clock() noexcept
		{
			device::SYSTEM::PRCR = 0xA50B;	// クロック、低消費電力、関係書き込み許可

			device::SYSTEM::MOSCWTCR = 9;	// 1ms wait
			// メインクロック強制発振とドライブ能力設定
			uint8_t modrv2 = 0b11;
			if(BASE_CLOCK > 20000000) modrv2 = 0b00;
			else if(BASE_CLOCK > 16000000) modrv2 = 0b01;
			else if(BASE_CLOCK > 8000000) modrv2 = 0b10;
			device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(modrv2)
						  | device::SYSTEM::MOFCR.MOSEL.b(EXT_CLOCK);
///						  device::SYSTEM::MOFCR.MOFXIN.b(1)
			device::SYSTEM::MOSCCR.MOSTP = 0;		// メインクロック発振器動作
			while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) { asm("nop"); }

			// RX71M、240MHz 時の MEMWAIT はスーパーバイザモードでの設定が必須なので、
			// device::SYSTEM::MEMWAIT = 1; は、start.s で設定される。

#if defined(SIG_RX65N)
			if(F_ICLK >= 120000000) {  // 120MHz 以上の場合設定
				device::SYSTEM::ROMWT = 0b10;
			} else if(F_ICLK >= 100000000) {
				device::SYSTEM::ROMWT = 0b01;
			} else if(F_ICLK >= 50000000) {
				device::SYSTEM::ROMWT = 0b00;
			}
#endif
#if defined(SIG_RX66T)
			if(F_ICLK > 120000000) {  // 120MHz 以上の場合設定
				device::SYSTEM::MEMWAIT = 1;
			}
#endif
			// (x10.0) 0b010011, (x10.5) 0b010100, (x11.0) 0b010101, (x11.5) 0b010110
			// ... MAX x30.0
			uint32_t n = INTR_CLOCK * 2 / BASE_CLOCK;
			if(n < 20) n = 20;
			else if(n > 60) n = 60;
			n -= 20;
			device::SYSTEM::PLLCR.STC = n + 0b010011;  // base 240MHz(12MHz)
			device::SYSTEM::PLLCR2.PLLEN = 0;			// PLL 動作
			while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm("nop"); }

			device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(clock_div_(F_FCLK))
								  | device::SYSTEM::SCKCR.ICK.b(clock_div_(F_ICLK))
								  | device::SYSTEM::SCKCR.BCK.b(clock_div_(F_BCLK))
								  | device::SYSTEM::SCKCR.PCKA.b(clock_div_(F_PCLKA))
								  | device::SYSTEM::SCKCR.PCKB.b(clock_div_(F_PCLKB))
								  | device::SYSTEM::SCKCR.PCKC.b(clock_div_(F_PCLKC))
								  | device::SYSTEM::SCKCR.PCKD.b(clock_div_(F_PCLKD));
			device::SYSTEM::SCKCR2.UCK = 0b0100;  // USB Clock: 1/5 (120/5=24)
			device::SYSTEM::SCKCR3.CKSEL = 0b100;	///< PLL 選択

			// クロック関係書き込み不許可
			device::SYSTEM::PRCR = 0xA500;

#if defined(SIG_RX65N) || defined(SIG_RX66T)
			// ROM キャッシュを有効（標準）
			device::SYSTEM::ROMCE = 1;
#endif
		}
	};

	//-------------------------------------------------------------//
	/*!
		@brief  ソフト・リセットの起動
	*/
	//-------------------------------------------------------------//
	inline void assert_soft_reset()
	{
		device::SYSTEM::PRCR = 0xA502;
		device::SYSTEM::SWRR = 0xA501;
		device::SYSTEM::PRCR = 0xA500;
	}
}
<commit_msg>fix: base clock divider for RX66T<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX64M/RX71M/RX651/RX65N/RX66T グループ・システム制御
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX600/system.hpp"

#ifndef F_ICLK
#  error "system_io.hpp requires F_ICLK to be defined"
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  systen_io クラス
		@param[in]	BASE_CLOCK	ベース・クロック周波数（１２ＭＨｚ）
		@param[in]	INTR_CLOCK	内臓クロック周波数（２４０ＭＨｚ）
		@param[in]	EXT_CLOCK	外部クロックに入力を行う場合「true」
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t BASE_CLOCK = 12000000, uint32_t INTR_CLOCK = 240000000, bool EXT_CLOCK = false>
	struct system_io {

		static uint8_t clock_div_(uint32_t clk) noexcept
		{
			uint8_t div = 0;
			while(clk < INTR_CLOCK) {
				++div;
				clk <<= 1;
			}
			return div;
		}

		//-------------------------------------------------------------//
		/*!
			@brief  システム・クロックの設定
		*/
		//-------------------------------------------------------------//
		static void setup_system_clock() noexcept
		{
			device::SYSTEM::PRCR = 0xA50B;	// クロック、低消費電力、関係書き込み許可

			device::SYSTEM::MOSCWTCR = 9;	// 1ms wait
			// メインクロック強制発振とドライブ能力設定
			uint8_t modrv2 = 0b11;
			if(BASE_CLOCK > 20000000) modrv2 = 0b00;
			else if(BASE_CLOCK > 16000000) modrv2 = 0b01;
			else if(BASE_CLOCK > 8000000) modrv2 = 0b10;
			device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(modrv2)
						  | device::SYSTEM::MOFCR.MOSEL.b(EXT_CLOCK);
///						  device::SYSTEM::MOFCR.MOFXIN.b(1)
			device::SYSTEM::MOSCCR.MOSTP = 0;		// メインクロック発振器動作
			while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) { asm("nop"); }

			// RX71M、240MHz 時の MEMWAIT はスーパーバイザモードでの設定が必須なので、
			// device::SYSTEM::MEMWAIT = 1; は、start.s で設定される。

#if defined(SIG_RX65N)
			if(F_ICLK >= 120000000) {  // 120MHz 以上の場合設定
				device::SYSTEM::ROMWT = 0b10;
			} else if(F_ICLK >= 100000000) {
				device::SYSTEM::ROMWT = 0b01;
			} else if(F_ICLK >= 50000000) {
				device::SYSTEM::ROMWT = 0b00;
			}
#endif
#if defined(SIG_RX66T)
			if(F_ICLK > 120000000) {  // 120MHz 以上の場合設定
				device::SYSTEM::MEMWAIT = 1;
			}
#endif
			// (x10.0) 0b010011, (x10.5) 0b010100, (x11.0) 0b010101, (x11.5) 0b010110
			// ... MAX x30.0
			uint32_t n = INTR_CLOCK * 2 / BASE_CLOCK;
			if(n < 20) n = 20;
			else if(n > 60) n = 60;
			n -= 20;
			device::SYSTEM::PLLCR.STC = n + 0b010011;  // base x10
			device::SYSTEM::PLLCR2.PLLEN = 0;			// PLL 動作
			while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm("nop"); }

			device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(clock_div_(F_FCLK))
								  | device::SYSTEM::SCKCR.ICK.b(clock_div_(F_ICLK))
								  | device::SYSTEM::SCKCR.BCK.b(clock_div_(F_BCLK))
								  | device::SYSTEM::SCKCR.PCKA.b(clock_div_(F_PCLKA))
								  | device::SYSTEM::SCKCR.PCKB.b(clock_div_(F_PCLKB))
								  | device::SYSTEM::SCKCR.PCKC.b(clock_div_(F_PCLKC))
								  | device::SYSTEM::SCKCR.PCKD.b(clock_div_(F_PCLKD));
			device::SYSTEM::SCKCR2.UCK = 0b0100;  // USB Clock: 1/5 (120/5=24)
			device::SYSTEM::SCKCR3.CKSEL = 0b100;	///< PLL 選択

			// クロック関係書き込み不許可
			device::SYSTEM::PRCR = 0xA500;

#if defined(SIG_RX65N) || defined(SIG_RX66T)
			// ROM キャッシュを有効（標準）
			device::SYSTEM::ROMCE = 1;
#endif
		}
	};

	//-------------------------------------------------------------//
	/*!
		@brief  ソフト・リセットの起動
	*/
	//-------------------------------------------------------------//
	inline void assert_soft_reset()
	{
		device::SYSTEM::PRCR = 0xA502;
		device::SYSTEM::SWRR = 0xA501;
		device::SYSTEM::PRCR = 0xA500;
	}
}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX64M システム制御 @n
			Copyright 2017 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "RX64M/system.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  systen_io クラス
		@param[in]	base_clock	ベース・クロック周波数（１２ＭＨｚ）
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t base_clock = 12000000>
	struct system_io {

		//-------------------------------------------------------------//
		/*!
			@brief  システム・クロックの設定
		*/
		//-------------------------------------------------------------//
		void setup_system_clock()
		{
			device::SYSTEM::PRCR = 0xA50B;	// クロック、低消費電力、関係書き込み許可

			device::SYSTEM::MOSCWTCR = 9;	// 1ms wait
			// メインクロック強制発振とドライブ能力設定
			device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(0b10)
						  | device::SYSTEM::MOFCR.MOFXIN.b(1);
			device::SYSTEM::MOSCCR.MOSTP = 0;		// メインクロック発振器動作
			while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop");

			// Base Clock 12MHz
			device::SYSTEM::PLLCR.STC = 0b010011;		// PLL 10 倍(120MHz)
			device::SYSTEM::PLLCR2.PLLEN = 0;			// PLL 動作
			while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm("nop"); }

			device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(1)    // 1/2 (120/2=60)
								  | device::SYSTEM::SCKCR.ICK.b(0)    // 1/1 (120/1=120)
								  | device::SYSTEM::SCKCR.BCK.b(1)    // 1/2 (120/2=60)
								  | device::SYSTEM::SCKCR.PCKA.b(0)   // 1/1 (120/1=120)
								  | device::SYSTEM::SCKCR.PCKB.b(1)   // 1/2 (120/2=60)
								  | device::SYSTEM::SCKCR.PCKC.b(1)   // 1/2 (120/2=60)
								  | device::SYSTEM::SCKCR.PCKD.b(1);  // 1/2 (120/2=60)
			device::SYSTEM::SCKCR2.UCK = 0b0100;  // USB Clock: 1/5 (120/5=24)
			device::SYSTEM::SCKCR3.CKSEL = 0b100;	///< PLL 選択
		}
	};
}
<commit_msg>add init port func<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX64M システム制御 @n
			Copyright 2017 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "RX64M/system.hpp"

namespace device {

	//-------------------------------------------------------------//
	/*!
		@brief  ポートの初期設定
	*/
	//-------------------------------------------------------------//
	static void init_port()
	{
		PORT0::PCR = 0xff;
		PORT1::PCR = 0xff;
		PORT2::PCR = 0xff;
		PORT3::PCR = 0xff;
		PORT4::PCR = 0xff;
		PORT5::PCR = 0xff;
		PORT6::PCR = 0xff;
		PORT7::PCR = 0xff;
		PORT8::PCR = 0xff;
		PORT9::PCR = 0xff;
		PORTA::PCR = 0xff;
		PORTB::PCR = 0xff;
		PORTC::PCR = 0xff;
		PORTD::PCR = 0xff;
		PORTE::PCR = 0xff;
		PORTF::PCR = 0xff;
		PORTG::PCR = 0xff;
		PORTJ::PCR = 0xff;
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  systen_io クラス
		@param[in]	base_clock	ベース・クロック周波数（１２ＭＨｚ）
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t base_clock = 12000000>
	struct system_io {

		//-------------------------------------------------------------//
		/*!
			@brief  システム・クロックの設定
		*/
		//-------------------------------------------------------------//
		static void setup_system_clock()
		{
			device::SYSTEM::PRCR = 0xA50B;	// クロック、低消費電力、関係書き込み許可

			device::SYSTEM::MOSCWTCR = 9;	// 1ms wait
			// メインクロック強制発振とドライブ能力設定
			device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(0b10)
						  | device::SYSTEM::MOFCR.MOFXIN.b(1);
			device::SYSTEM::MOSCCR.MOSTP = 0;		// メインクロック発振器動作
			while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop");

			// Base Clock 12MHz
			device::SYSTEM::PLLCR.STC = 0b010011;		// PLL 10 倍(120MHz)
			device::SYSTEM::PLLCR2.PLLEN = 0;			// PLL 動作
			while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) { asm("nop"); }

			device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(1)    // 1/2 (120/2=60)
								  | device::SYSTEM::SCKCR.ICK.b(0)    // 1/1 (120/1=120)
								  | device::SYSTEM::SCKCR.BCK.b(1)    // 1/2 (120/2=60)
								  | device::SYSTEM::SCKCR.PCKA.b(0)   // 1/1 (120/1=120)
								  | device::SYSTEM::SCKCR.PCKB.b(1)   // 1/2 (120/2=60)
								  | device::SYSTEM::SCKCR.PCKC.b(1)   // 1/2 (120/2=60)
								  | device::SYSTEM::SCKCR.PCKD.b(1);  // 1/2 (120/2=60)
			device::SYSTEM::SCKCR2.UCK = 0b0100;  // USB Clock: 1/5 (120/5=24)
			device::SYSTEM::SCKCR3.CKSEL = 0b100;	///< PLL 選択
		}
	};
}
<|endoftext|>


<commit_before>#include "Map.h"

Map::Map(sf::Vector2f position, float length)
{
    this->position = position;
    start = position - sf::Vector2f(length/2.f, 0);
    end = position + sf::Vector2f(length/2.f, 0);

    leftUnits.emplace_back();
    rightUnits.emplace_back();
}

Map::~Map()
{
}

void Map::update(float dt)
{
    for(Unit& unit : leftUnits)
    {
        if(unit.moving)
            unit.advancement += unit.speed*dt;
        else
            rightUnits.front().life = std::max(0.f, rightUnits.front().life-unit.damage*dt);
    }

    for(Unit& unit : rightUnits)
    {
        if(unit.moving)
            unit.advancement += unit.speed*dt;
        else
            leftUnits.front().life = std::max(0.f, leftUnits.front().life-unit.damage*dt);
    }

    std::sort(leftUnits.begin(), leftUnits.end(), [](const Unit& first, const Unit& second){return first.advancement > second.advancement;});
    std::sort(rightUnits.begin(), rightUnits.end(), [](const Unit& first, const Unit& second){return first.advancement > second.advancement;});

    for(Unit& unit : leftUnits)
        unit.moving = ((unit.advancement+rightUnits.front().advancement+unit.range) <= 1.f);

    for(Unit& unit : rightUnits)
        unit.moving = ((unit.advancement+leftUnits.front().advancement+unit.range) <= 1.f);

    for(auto it = leftUnits.begin(); it != leftUnits.end(); it++)
    {
        if(it->life <= 0)
            it = leftUnits.begin() + (std::distance(leftUnits.begin(), leftUnits.erase(it)) - 1);
    }

    for(auto it = rightUnits.begin(); it != rightUnits.end(); it++)
    {
        if(it->life <= 0)
            it = rightUnits.begin() + (std::distance(rightUnits.begin(), rightUnits.erase(it)) - 1);
    }

    leftUnitSpawnTime += dt;
    rightUnitSpawnTime += dt;

    if(leftUnitSpawnTime >= leftUnitRate)
    {
        leftUnits.emplace_back();
        leftUnitSpawnTime -= leftUnitRate;
    }

    if(rightUnitSpawnTime >= rightUnitRate)
    {
        rightUnits.emplace_back();
        rightUnitSpawnTime -= rightUnitRate;
    }
}

void Map::render(sf::RenderTarget& target)
{
    for(Unit& unit : leftUnits)
        unit.render(target, start + (end-start)*unit.advancement);

    for(Unit& unit : rightUnits)
        unit.render(target, end - (end-start)*unit.advancement);
}
<commit_msg>fixed some shit<commit_after>#include "Map.h"

Map::Map(sf::Vector2f position, float length)
{
    this->position = position;
    start = position - sf::Vector2f(length/2.f, 0);
    end = position + sf::Vector2f(length/2.f, 0);

    leftUnits.emplace_back();
    rightUnits.emplace_back();
}

Map::~Map()
{
}

void Map::update(float dt)
{
    for(Unit& unit : leftUnits)
    {
        if(unit.moving)
            unit.advancement += unit.speed*dt;
        else
            rightUnits.front().life = std::max(0.f, rightUnits.front().life-unit.damage*dt);
    }

    for(Unit& unit : rightUnits)
    {
        if(unit.moving)
            unit.advancement += unit.speed*dt;
        else
            leftUnits.front().life = std::max(0.f, leftUnits.front().life-unit.damage*dt);
    }

    std::sort(leftUnits.begin(), leftUnits.end(), [](const Unit& first, const Unit& second){return first.advancement > second.advancement;});
    std::sort(rightUnits.begin(), rightUnits.end(), [](const Unit& first, const Unit& second){return first.advancement > second.advancement;});

    for(Unit& unit : leftUnits)
        unit.moving = (rightUnits.size() ? (unit.advancement+rightUnits.front().advancement+unit.range) <= 1.f : true);

    for(Unit& unit : rightUnits)
        unit.moving = (leftUnits.size() ? (unit.advancement+leftUnits.front().advancement+unit.range) <= 1.f : true);

    for(auto it = leftUnits.begin(); it != leftUnits.end(); it++)
    {
        if(it->life <= 0 || it->advancement >= 1)
            it = leftUnits.begin() + (std::distance(leftUnits.begin(), leftUnits.erase(it)) - 1);
    }

    for(auto it = rightUnits.begin(); it != rightUnits.end(); it++)
    {
        if(it->life <= 0 || it->advancement >= 1)
            it = rightUnits.begin() + (std::distance(rightUnits.begin(), rightUnits.erase(it)) - 1);
    }

    leftUnitSpawnTime += dt;
    rightUnitSpawnTime += dt;

    if(leftUnitSpawnTime >= leftUnitRate)
    {
        leftUnits.emplace_back();
        leftUnitSpawnTime -= leftUnitRate;
    }

    if(rightUnitSpawnTime >= rightUnitRate)
    {
        rightUnits.emplace_back();
        rightUnitSpawnTime -= rightUnitRate;
    }
}

void Map::render(sf::RenderTarget& target)
{
    for(Unit& unit : leftUnits)
        unit.render(target, start + (end-start)*unit.advancement);

    for(Unit& unit : rightUnits)
        unit.render(target, end - (end-start)*unit.advancement);
}
<|endoftext|>


<commit_before>#include "algorithm.h"
#include "all.h"

#include <cstdio>
#include "benchmark.h"

#include <cstdlib>

class Test {

    static const size_t size = 1024 * 4;
    static const size_t n = 16;

    const size_t iterations = 10;

    float* input[n];
    float  output[n];
    float* const_vector;

public:
    Test() {
        for (size_t i=0; i < n; i++) {
            input[i] = new float[size];
            initialize_vector(input[i]);
        }

        const_vector = new float[size];
        initialize_vector(const_vector);
    }

    ~Test() {
        for (size_t i=0; i < n; i++) {
            delete[] input[i];
        }

        delete[] const_vector;
    }

    void run() {

        test_scalar("scalar", scalar_dist_vectors);
        test_scalar("SSE",    sse_dist_vector);

        test("SSE (custom)",  sse_dist_vector_many);
    }

private:
    void initialize_vector(float* v) {
        for (size_t i=0; i < size; i++) {
            v[i] = (rand() % 1000)/1000.0 - 0.5;
        }
    }

    template <typename FUNCTION>
    void test_scalar(const char* name, FUNCTION function) {

        auto fn = [this, function]() {
            dist_vector_many(function, size, const_vector, n, input, output);
        };

        BEST_TIME(/**/, fn(), name, iterations, size);
    }

    template <typename FUNCTION>
    void test(const char* name, FUNCTION dist_vector_many) {

        auto fn = [this, dist_vector_many]() {
            dist_vector_many(size, const_vector, n, input, output);
        };

        BEST_TIME(/**/, fn(), name, iterations, size);
    }
};

int main() {

    Test test;

    test.run();

    return EXIT_SUCCESS;
}
<commit_msg>More flexible tests<commit_after>#include "algorithm.h"
#include "all.h"

#include "benchmark.h"

#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cassert>

class Test {

    const size_t size;
    const size_t count;

    const size_t iterations = 10;

    float** input;
    float*  output;
    float*  const_vector;

public:
    Test(size_t size_, size_t count_) : size(size_), count(count_) {

        assert(size  % 64 == 0);
        assert(count %  4 == 0);

        input = new float*[count];
        for (size_t i=0; i < count; i++) {
            input[i] = new float[size];
            initialize_vector(input[i]);
        }

        output = new float[count];
        const_vector = new float[size];
        initialize_vector(const_vector);
    }

    ~Test() {
        for (size_t i=0; i < count; i++) {
            delete[] input[i];
        }

        delete[] input;
        delete[] output;
        delete[] const_vector;
    }

    void run() {

        test_scalar("scalar", scalar_dist_vectors);
        test_scalar("SSE",    sse_dist_vector);

        test("SSE (custom)",  sse_dist_vector_many);
    }

private:
    void initialize_vector(float* v) {
        for (size_t i=0; i < size; i++) {
            v[i] = (rand() % 1000)/1000.0 - 0.5;
        }
    }

    template <typename FUNCTION>
    void test_scalar(const char* name, FUNCTION function) {

        auto fn = [this, function]() {
            dist_vector_many(function, size, const_vector, count, input, output);
        };

        BEST_TIME(/**/, fn(), name, iterations, size);
    }

    template <typename FUNCTION>
    void test(const char* name, FUNCTION dist_vector_many) {

        auto fn = [this, dist_vector_many]() {
            dist_vector_many(size, const_vector, count, input, output);
        };

        BEST_TIME(/**/, fn(), name, iterations, size);
    }
};

int main() {

    size_t vector_count[] = {8, 16, 32, 64, 128, 256};
    size_t vector_size[] = {64, 128, 256, 512, 1024, 1024*4, 1024*8};

    for (size_t count: vector_count) {
        for (size_t size: vector_size) {
            printf("vector size=%lu, count=%lu\n", size, count);
            Test test(size, count);

            test.run();
        }
    }

    return EXIT_SUCCESS;
}
<|endoftext|>