<commit_before>#include "vigra/unittest.hxx"

#include "rank_filter.hxx"

class RankFilterTest
{
private:

    const unsigned long size = 10;

    vigra::MultiArray< 1, double >::difference_type size_1;

    vigra::MultiArray< 1, double > array_1;
    vigra::MultiArray< 1, double > reverse_array_1;

    vigra::MultiArray< 1, double > expected_result_1;
    vigra::MultiArray< 1, double > result_1;

    vigra::MultiArray< 2, double >::difference_type size_2;

    vigra::MultiArray< 2, double > array_2;
    vigra::MultiArray< 2, double > reverse_array_2;

    vigra::MultiArray< 2, double > expected_result_2;
    vigra::MultiArray< 2, double > result_2;

public:

    RankFilterTest() : size_1(size), array_1(size_1), reverse_array_1(size_1), expected_result_1(size_1), result_1(size_1),
                       size_2(size, size), array_2(size_2), reverse_array_2(size_2), expected_result_2(size_2), result_2(size_2)
    {
        for (int i = 0; i < array_1.shape(0); i++)
        {
            array_1[i] = i;
        }

        for (int i = 0; i < reverse_array_1.shape(0); i++)
        {
            reverse_array_1[i] = reverse_array_1.shape(0) - i - 1;
        }

        for (int i = 0; i < array_2.shape(0); i++)
        {
            for (int j = 0; j < array_2.shape(1); j++)
            {
                array_2(i, j) = array_2.shape(1)*i + j;
            }
        }

        for (int i = 0; i < reverse_array_2.shape(0); i++)
        {
            for (int j = 0; j < reverse_array_2.shape(1); j++)
            {
                reverse_array_2(i, j) = reverse_array_2.shape(1) * (reverse_array_2.shape(0) - i - 1) + (reverse_array_2.shape(1) - j - 1);
            }
        }
    };

    ~RankFilterTest()
    {
    };

    void test_rank_filter_1()
    {
        expected_result_1 = array_1;

        result_1 = 0;

        rank_filter::lineRankOrderFilter(array_1, result_1, 0, 0.5);

        should(expected_result_1 == result_1);
    };

    void test_rank_filter_2()
    {
        expected_result_1 = reverse_array_1;

        result_1 = 0;

        rank_filter::lineRankOrderFilter(reverse_array_1, result_1, 0, 0.5);

        should(expected_result_1 == result_1);
    };

    void test_rank_filter_3()
    {
        expected_result_1 = array_1;
        expected_result_1[0] = expected_result_1[1];
        expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2];

        result_1 = 0;

        rank_filter::lineRankOrderFilter(array_1, result_1, 1, 0.5);

        should(expected_result_1 == result_1);
    };

    void test_rank_filter_4()
    {
        expected_result_1 = reverse_array_1;
        expected_result_1[0] = expected_result_1[1];
        expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2];

        result_1 = 0;

        rank_filter::lineRankOrderFilter(reverse_array_1, result_1, 1, 0.5);

        should(expected_result_1 == result_1);
    };

    void test_rank_filter_5()
    {
        expected_result_1 = array_1;
        expected_result_1[0] = expected_result_1[1];
        expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2];

        result_1 = 0;

        rank_filter::lineRankOrderFilter(array_1, result_1, 2, 0.5);

        should(expected_result_1 == result_1);
    };

    void test_rank_filter_6()
    {
        expected_result_1 = reverse_array_1;
        expected_result_1[0] = expected_result_1[1];
        expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2];

        result_1 = 0;

        rank_filter::lineRankOrderFilter(reverse_array_1, result_1, 2, 0.5);

        should(expected_result_1 == result_1);
    };

    void test_rank_filter_7()
    {
        expected_result_1 = array_1;
        expected_result_1[0] = expected_result_1[1] = expected_result_1[2];
        expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2] = expected_result_1[expected_result_1.size() - 3];

        result_1 = 0;

        rank_filter::lineRankOrderFilter(array_1, result_1, 3, 0.5);

        should(expected_result_1 == result_1);
    };

    void test_rank_filter_8()
    {
        expected_result_1 = reverse_array_1;
        expected_result_1[0] = expected_result_1[1] = expected_result_1[2];
        expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2] = expected_result_1[expected_result_1.size() - 3];

        result_1 = 0;

        rank_filter::lineRankOrderFilter(reverse_array_1, result_1, 3, 0.5);

        should(expected_result_1 == result_1);
    };

    void test_rank_filter_9()
    {
        expected_result_1 = array_1;
        expected_result_1[0] = expected_result_1[1] = expected_result_1[2];
        expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2] = expected_result_1[expected_result_1.size() - 3];

        result_1 = 0;

        rank_filter::lineRankOrderFilter(array_1.insertSingletonDimension(0), result_1.insertSingletonDimension(0), 3, 0.5, 1);

        should(expected_result_1 == result_1);
    };

    void test_rank_filter_10()
    {
        expected_result_1 = reverse_array_1;
        expected_result_1[0] = expected_result_1[1] = expected_result_1[2];
        expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2] = expected_result_1[expected_result_1.size() - 3];

        result_1 = 0;

        rank_filter::lineRankOrderFilter(reverse_array_1.insertSingletonDimension(0), result_1.insertSingletonDimension(0), 3, 0.5, 1);

        should(expected_result_1 == result_1);
    };

    void test_rank_filter_11()
    {
        expected_result_2 = array_2;

        result_2 = 0;

        rank_filter::lineRankOrderFilter(array_2, result_2, 0, 0.5);

        should(expected_result_2 == result_2);
    };

    void test_rank_filter_12()
    {
        expected_result_2 = reverse_array_2;

        result_2 = 0;

        rank_filter::lineRankOrderFilter(reverse_array_2, result_2, 0, 0.5);

        should(expected_result_2 == result_2);
    };

    void test_rank_filter_13()
    {
        expected_result_2 = array_2;
        expected_result_2.bindInner(0) = expected_result_2.bindInner(1);
        expected_result_2.bindInner(expected_result_2.shape(0) - 1) = expected_result_2.bindInner(expected_result_2.shape(0) - 2);

        result_2 = 0;

        rank_filter::lineRankOrderFilter(array_2, result_2, 1, 0.5);

        should(expected_result_2 == result_2);
    };

    void test_rank_filter_14()
    {
        expected_result_2 = reverse_array_2;
        expected_result_2.bindInner(0) = expected_result_2.bindInner(1);
        expected_result_2.bindInner(expected_result_2.shape(0) - 1) = expected_result_2.bindInner(expected_result_2.shape(0) - 2);

        result_2 = 0;

        rank_filter::lineRankOrderFilter(reverse_array_2, result_2, 1, 0.5);

        should(expected_result_2 == result_2);
    };

    void test_rank_filter_15()
    {
        expected_result_2 = array_2;
        expected_result_2.bindOuter(0) = expected_result_2.bindOuter(1);
        expected_result_2.bindOuter(expected_result_2.shape(0) - 1) = expected_result_2.bindOuter(expected_result_2.shape(0) - 2);

        result_2 = 0;

        rank_filter::lineRankOrderFilter(array_2, result_2, 1, 0.5, 1);

        should(expected_result_2 == result_2);
    };

    void test_rank_filter_16()
    {
        expected_result_2 = reverse_array_2;
        expected_result_2.bindOuter(0) = expected_result_2.bindOuter(1);
        expected_result_2.bindOuter(expected_result_2.shape(0) - 1) = expected_result_2.bindOuter(expected_result_2.shape(0) - 2);

        result_2 = 0;

        rank_filter::lineRankOrderFilter(reverse_array_2, result_2, 1, 0.5, 1);

        should(expected_result_2 == result_2);
    };

    void test_rank_filter_17()
    {
        expected_result_2 = reverse_array_2;
        expected_result_2.bindOuter(0) = expected_result_2.bindOuter(1);
        expected_result_2.bindOuter(expected_result_2.shape(0) - 1) = expected_result_2.bindOuter(expected_result_2.shape(0) - 2);

        result_2 = reverse_array_2;

        rank_filter::lineRankOrderFilter(result_2, result_2, 1, 0.5, 1);

        should(expected_result_2 == result_2);
    };

    void test_rank_filter_18()
    {
        for (size_t i = 0; i < array_1.size(); i++)
        {
            expected_result_1[i] = (i < 5) ? array_1[5] : array_1[4];
        }

        result_1 = 0;

        rank_filter::lineRankOrderFilter(array_1, result_1, size - 1, 0.5, 1);

        should(expected_result_1 == result_1);
    };
};

struct RankFilterTestSuite
        : public vigra::test_suite
{
    RankFilterTestSuite()
            : vigra::test_suite("RankFilterTestSuite")
    {
        add( testCase( &RankFilterTest::test_rank_filter_1 ) );
        add( testCase( &RankFilterTest::test_rank_filter_2 ) );
        add( testCase( &RankFilterTest::test_rank_filter_3 ) );
        add( testCase( &RankFilterTest::test_rank_filter_4 ) );
        add( testCase( &RankFilterTest::test_rank_filter_5 ) );
        add( testCase( &RankFilterTest::test_rank_filter_6 ) );
        add( testCase( &RankFilterTest::test_rank_filter_7 ) );
        add( testCase( &RankFilterTest::test_rank_filter_8 ) );
        add( testCase( &RankFilterTest::test_rank_filter_9 ) );
        add( testCase( &RankFilterTest::test_rank_filter_10 ) );
        add( testCase( &RankFilterTest::test_rank_filter_11 ) );
        add( testCase( &RankFilterTest::test_rank_filter_12 ) );
        add( testCase( &RankFilterTest::test_rank_filter_13 ) );
        add( testCase( &RankFilterTest::test_rank_filter_14 ) );
        add( testCase( &RankFilterTest::test_rank_filter_15 ) );
        add( testCase( &RankFilterTest::test_rank_filter_16 ) );
        add( testCase( &RankFilterTest::test_rank_filter_17 ) );
        add( testCase( &RankFilterTest::test_rank_filter_18 ) );
    }
}; // struct RankFilterTestSuite

int main(int argc, char ** argv)
{
    // run the multi-array testsuite
    RankFilterTestSuite test1;
    int failed = test1.run(vigra::testsToBeExecuted(argc, argv));
    std::cout << test1.report() << std::endl;

    return(failed != 0);
}
<commit_msg>test/test_rank_filter.cxx: Switch to using Boost's test framework.<commit_after>#define BOOST_TEST_MODULE RankFilterModule
#include <boost/test/included/unit_test.hpp>

#include "rank_filter.hxx"

struct RankFilterFixture
{
    public:

        const unsigned long size = 10;

        vigra::MultiArray< 1, double >::difference_type size_1;

        vigra::MultiArray< 1, double > array_1;
        vigra::MultiArray< 1, double > reverse_array_1;

        vigra::MultiArray< 1, double > expected_result_1;
        vigra::MultiArray< 1, double > result_1;

        vigra::MultiArray< 2, double >::difference_type size_2;

        vigra::MultiArray< 2, double > array_2;
        vigra::MultiArray< 2, double > reverse_array_2;

        vigra::MultiArray< 2, double > expected_result_2;
        vigra::MultiArray< 2, double > result_2;

    public:

        RankFilterFixture() : size_1(size), array_1(size_1), reverse_array_1(size_1), expected_result_1(size_1), result_1(size_1),
        size_2(size, size), array_2(size_2), reverse_array_2(size_2), expected_result_2(size_2), result_2(size_2)
        {
            for (int i = 0; i < array_1.shape(0); i++)
            {
                array_1[i] = i;
            }

            for (int i = 0; i < reverse_array_1.shape(0); i++)
            {
                reverse_array_1[i] = reverse_array_1.shape(0) - i - 1;
            }

            for (int i = 0; i < array_2.shape(0); i++)
            {
                for (int j = 0; j < array_2.shape(1); j++)
                {
                    array_2(i, j) = array_2.shape(1)*i + j;
                }
            }

            for (int i = 0; i < reverse_array_2.shape(0); i++)
            {
                for (int j = 0; j < reverse_array_2.shape(1); j++)
                {
                    reverse_array_2(i, j) = reverse_array_2.shape(1) * (reverse_array_2.shape(0) - i - 1) + (reverse_array_2.shape(1) - j - 1);
                }
            }
        };

        ~RankFilterFixture()
        {
        };
};

BOOST_AUTO_TEST_SUITE( RankFilterSuite )

BOOST_FIXTURE_TEST_CASE(test_rank_filter_1, RankFilterFixture)
{
    expected_result_1 = array_1;

    result_1 = 0;

    rank_filter::lineRankOrderFilter(array_1, result_1, 0, 0.5);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_2, RankFilterFixture)
{
    expected_result_1 = reverse_array_1;

    result_1 = 0;

    rank_filter::lineRankOrderFilter(reverse_array_1, result_1, 0, 0.5);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_3, RankFilterFixture)
{
    expected_result_1 = array_1;
    expected_result_1[0] = expected_result_1[1];
    expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2];

    result_1 = 0;

    rank_filter::lineRankOrderFilter(array_1, result_1, 1, 0.5);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_4, RankFilterFixture)
{
    expected_result_1 = reverse_array_1;
    expected_result_1[0] = expected_result_1[1];
    expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2];

    result_1 = 0;

    rank_filter::lineRankOrderFilter(reverse_array_1, result_1, 1, 0.5);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_5, RankFilterFixture)
{
    expected_result_1 = array_1;
    expected_result_1[0] = expected_result_1[1];
    expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2];

    result_1 = 0;

    rank_filter::lineRankOrderFilter(array_1, result_1, 2, 0.5);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_6, RankFilterFixture)
{
    expected_result_1 = reverse_array_1;
    expected_result_1[0] = expected_result_1[1];
    expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2];

    result_1 = 0;

    rank_filter::lineRankOrderFilter(reverse_array_1, result_1, 2, 0.5);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_7, RankFilterFixture)
{
    expected_result_1 = array_1;
    expected_result_1[0] = expected_result_1[1] = expected_result_1[2];
    expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2] = expected_result_1[expected_result_1.size() - 3];

    result_1 = 0;

    rank_filter::lineRankOrderFilter(array_1, result_1, 3, 0.5);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_8, RankFilterFixture)
{
    expected_result_1 = reverse_array_1;
    expected_result_1[0] = expected_result_1[1] = expected_result_1[2];
    expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2] = expected_result_1[expected_result_1.size() - 3];

    result_1 = 0;

    rank_filter::lineRankOrderFilter(reverse_array_1, result_1, 3, 0.5);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_9, RankFilterFixture)
{
    expected_result_1 = array_1;
    expected_result_1[0] = expected_result_1[1] = expected_result_1[2];
    expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2] = expected_result_1[expected_result_1.size() - 3];

    result_1 = 0;

    rank_filter::lineRankOrderFilter(array_1.insertSingletonDimension(0), result_1.insertSingletonDimension(0), 3, 0.5, 1);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_10, RankFilterFixture)
{
    expected_result_1 = reverse_array_1;
    expected_result_1[0] = expected_result_1[1] = expected_result_1[2];
    expected_result_1[expected_result_1.size()  - 1] = expected_result_1[expected_result_1.size() - 2] = expected_result_1[expected_result_1.size() - 3];

    result_1 = 0;

    rank_filter::lineRankOrderFilter(reverse_array_1.insertSingletonDimension(0), result_1.insertSingletonDimension(0), 3, 0.5, 1);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_11, RankFilterFixture)
{
    expected_result_2 = array_2;

    result_2 = 0;

    rank_filter::lineRankOrderFilter(array_2, result_2, 0, 0.5);

    BOOST_CHECK_EQUAL(expected_result_2, result_2);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_12, RankFilterFixture)
{
    expected_result_2 = reverse_array_2;

    result_2 = 0;

    rank_filter::lineRankOrderFilter(reverse_array_2, result_2, 0, 0.5);

    BOOST_CHECK_EQUAL(expected_result_2, result_2);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_13, RankFilterFixture)
{
    expected_result_2 = array_2;
    expected_result_2.bindInner(0) = expected_result_2.bindInner(1);
    expected_result_2.bindInner(expected_result_2.shape(0) - 1) = expected_result_2.bindInner(expected_result_2.shape(0) - 2);

    result_2 = 0;

    rank_filter::lineRankOrderFilter(array_2, result_2, 1, 0.5);

    BOOST_CHECK_EQUAL(expected_result_2, result_2);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_14, RankFilterFixture)
{
    expected_result_2 = reverse_array_2;
    expected_result_2.bindInner(0) = expected_result_2.bindInner(1);
    expected_result_2.bindInner(expected_result_2.shape(0) - 1) = expected_result_2.bindInner(expected_result_2.shape(0) - 2);

    result_2 = 0;

    rank_filter::lineRankOrderFilter(reverse_array_2, result_2, 1, 0.5);

    BOOST_CHECK_EQUAL(expected_result_2, result_2);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_15, RankFilterFixture)
{
    expected_result_2 = array_2;
    expected_result_2.bindOuter(0) = expected_result_2.bindOuter(1);
    expected_result_2.bindOuter(expected_result_2.shape(0) - 1) = expected_result_2.bindOuter(expected_result_2.shape(0) - 2);

    result_2 = 0;

    rank_filter::lineRankOrderFilter(array_2, result_2, 1, 0.5, 1);

    BOOST_CHECK_EQUAL(expected_result_2, result_2);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_16, RankFilterFixture)
{
    expected_result_2 = reverse_array_2;
    expected_result_2.bindOuter(0) = expected_result_2.bindOuter(1);
    expected_result_2.bindOuter(expected_result_2.shape(0) - 1) = expected_result_2.bindOuter(expected_result_2.shape(0) - 2);

    result_2 = 0;

    rank_filter::lineRankOrderFilter(reverse_array_2, result_2, 1, 0.5, 1);

    BOOST_CHECK_EQUAL(expected_result_2, result_2);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_17, RankFilterFixture)
{
    expected_result_2 = reverse_array_2;
    expected_result_2.bindOuter(0) = expected_result_2.bindOuter(1);
    expected_result_2.bindOuter(expected_result_2.shape(0) - 1) = expected_result_2.bindOuter(expected_result_2.shape(0) - 2);

    result_2 = reverse_array_2;

    rank_filter::lineRankOrderFilter(result_2, result_2, 1, 0.5, 1);

    BOOST_CHECK_EQUAL(expected_result_2, result_2);
}

BOOST_FIXTURE_TEST_CASE(test_rank_filter_18, RankFilterFixture)
{
    for (size_t i = 0; i < array_1.size(); i++)
    {
        expected_result_1[i] = (i < 5) ? array_1[5] : array_1[4];
    }

    result_1 = 0;

    rank_filter::lineRankOrderFilter(array_1, result_1, size - 1, 0.5, 1);

    BOOST_CHECK_EQUAL(expected_result_1, result_1);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit - Output data to Treasure Data
 *  =========================================
 *  Copyright (C) 2015 Treasure Data Inc.
 *
 *  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 <unistd.h>
#include <fluent-bit.h>

int main(int argc, char **argv)
{
    int i;
    int n;
    int ret;
    char tmp[256];
    struct flb_config *config;

    if (argc < 2) {
        fprintf(stderr, "Usage: td /path/to/configuration.file\n");
        exit(EXIT_FAILURE);
    }

    /* Create configuration context */
    config = flb_config_init();
    if (!config) {
        exit(EXIT_FAILURE);
    }

    /* Enable verbose messages */
    flb_config_verbose(FLB_TRUE);

    /* Load a configuration file (required by TD output plugin) */
    ret = flb_lib_config_file(config, argv[1]);

    /* Initialize library */
    ret = flb_lib_init(config, (char *) "td");
    if (ret != 0) {
        exit(EXIT_FAILURE);
    }

    /* Start the background worker */
    flb_lib_start(config);

    /* Push some data */
    for (i = 0; i < 100; i++) {
        n = snprintf(tmp, sizeof(tmp) - 1, "{\"key\": \"val %i\"}", i);
        flb_lib_push(config, tmp, n);
    }

    flb_lib_stop(config);

    return 0;
}
<commit_msg>example: Treasure Data example must include 'time' field in JSON data<commit_after>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit - Output data to Treasure Data
 *  =========================================
 *  Copyright (C) 2015 Treasure Data Inc.
 *
 *  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 <unistd.h>
#include <fluent-bit.h>

int main(int argc, char **argv)
{
    int i;
    int n;
    int ret;
    char tmp[256];
    struct flb_config *config;

    if (argc < 2) {
        fprintf(stderr, "Usage: td /path/to/configuration.file\n");
        exit(EXIT_FAILURE);
    }

    /* Create configuration context */
    config = flb_config_init();
    if (!config) {
        exit(EXIT_FAILURE);
    }

    /* Enable verbose messages */
    flb_config_verbose(FLB_TRUE);

    /* Load a configuration file (required by TD output plugin) */
    ret = flb_lib_config_file(config, argv[1]);

    /* Initialize library */
    ret = flb_lib_init(config, (char *) "td");
    if (ret != 0) {
        exit(EXIT_FAILURE);
    }

    /* Start the background worker */
    flb_lib_start(config);

    /* Push some data */
    for (i = 0; i < 100; i++) {
        n = snprintf(tmp, sizeof(tmp) - 1,
                     "{\"time\": 1442875576, \"key\": \"val %i\"}", i);
        flb_lib_push(config, tmp, n);
    }

    flb_lib_stop(config);

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Agora.cpp
 *
 *  Created on: May 18, 2014
 *      Author: Flix Robles felrobelv at gmail dot com
 * Loosely based on Agora Voting:
 * https://github.com/agoraciudadana/agora-ciudadana/blob/security/agora_site/static/js/agora/views/voting_booth.js
 */

#include "Agora.h"

Agora::Encrypted_answer::Encrypted_answer()
{
	mpz_init(alpha);
	mpz_init(beta);
	mpz_init(challenge);
	mpz_init(response);
}

Agora::Encrypted_answer::Encrypted_answer(const mpz_t &alpha, const mpz_t &beta, const ElGamal::PlaintextCommitment &commitment,
				const mpz_t &challenge,const mpz_t &response)
{
	this->commitment = commitment;
	mpz_init_set(this->alpha, alpha);
	mpz_init_set(this->beta, beta);
	mpz_init_set(this->challenge, challenge);
	mpz_init_set(this->response, response);
}

Agora::Encrypted_answer Agora::encryptAnswer(const ElGamal::PublicKey &pk, const mpz_t &encoded_answer, const mpz_t &randomness) {
	/**
	 * Here we not only just encrypt the answer but also provide a
	 * verifiable Proof of Knowledge (PoK) of the plaintext, using the
	 * Schnorr Protocol with Fiat-Shamir (which is a method of
	 * converting an interactive PoK into non interactive using a hash
	 * that substitutes the random oracle). We use sha256 for hashing.
	 */
	Agora::Encrypted_answer answer;
	bool b = true;
	ElGamal::Plaintext plaintext = ElGamal::Plaintext(encoded_answer, pk, b);
	mpz_t m;
	mpz_init_set_str(m, "0", 10);
	plaintext.getM(m);
	mpz_t zero, random;
	mpz_init(zero);
	mpz_init(random);
	//returns 0 only if randomness == 0
	if (0 == mpz_cmp(randomness,zero)) 	{
		Random::getRandomInteger(random, pk.q);
	} else if (mpz_cmp(randomness,pk.q) > 0 ) { //randomness is too big
		mpz_mod(random, randomness, pk.q);
	}
	else {
		mpz_set(random, randomness);
	}
	ElGamal::Ciphertext ciphertext = ElGamal::encrypt(pk, plaintext, random);
	ElGamal::Fiatshamir_dlog_challenge_generator generator;
	ElGamal::DLogProof proof = plaintext.proveKnowledge(ciphertext.alpha, random, generator);
	answer = Agora::Encrypted_answer(ciphertext.alpha, ciphertext.beta, proof.commitment, proof.response, proof.challenge);
	return answer;
}
<commit_msg>remove unused code<commit_after>/*
 * Agora.cpp
 *
 *  Created on: May 18, 2014
 *      Author: Flix Robles felrobelv at gmail dot com
 * Loosely based on Agora Voting:
 * https://github.com/agoraciudadana/agora-ciudadana/blob/security/agora_site/static/js/agora/views/voting_booth.js
 */

#include "Agora.h"

Agora::Encrypted_answer::Encrypted_answer()
{
	mpz_init(alpha);
	mpz_init(beta);
	mpz_init(challenge);
	mpz_init(response);
}

Agora::Encrypted_answer::Encrypted_answer(const mpz_t &alpha, const mpz_t &beta, const ElGamal::PlaintextCommitment &commitment,
				const mpz_t &challenge,const mpz_t &response)
{
	this->commitment = commitment;
	mpz_init_set(this->alpha, alpha);
	mpz_init_set(this->beta, beta);
	mpz_init_set(this->challenge, challenge);
	mpz_init_set(this->response, response);
}

Agora::Encrypted_answer Agora::encryptAnswer(const ElGamal::PublicKey &pk, const mpz_t &encoded_answer, const mpz_t &randomness) {
	/**
	 * Here we not only just encrypt the answer but also provide a
	 * verifiable Proof of Knowledge (PoK) of the plaintext, using the
	 * Schnorr Protocol with Fiat-Shamir (which is a method of
	 * converting an interactive PoK into non interactive using a hash
	 * that substitutes the random oracle). We use sha256 for hashing.
	 */
	Agora::Encrypted_answer answer;
	bool b = true;
	ElGamal::Plaintext plaintext = ElGamal::Plaintext(encoded_answer, pk, b);
	mpz_t zero, random;
	mpz_init(zero);
	mpz_init(random);
	//returns 0 only if randomness == 0
	if (0 == mpz_cmp(randomness,zero)) 	{
		Random::getRandomInteger(random, pk.q);
	} else if (mpz_cmp(randomness,pk.q) > 0 ) { //randomness is too big
		mpz_mod(random, randomness, pk.q);
	}
	else {
		mpz_set(random, randomness);
	}
	ElGamal::Ciphertext ciphertext = ElGamal::encrypt(pk, plaintext, random);
	ElGamal::Fiatshamir_dlog_challenge_generator generator;
	ElGamal::DLogProof proof = plaintext.proveKnowledge(ciphertext.alpha, random, generator);
	answer = Agora::Encrypted_answer(ciphertext.alpha, ciphertext.beta, proof.commitment, proof.response, proof.challenge);
	return answer;
}
<|endoftext|>


<commit_before>#include <Monitoring/sys.hpp>

#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main(int argc,char* argv[])
{
    cout<<"Sys infos:\n\tosName: "<<sys::osName()
        <<"\n\tosBit: "<<sys::osBit()
        <<"\n\tosNameBit: "<<sys::osNameBit()
        <<"\n\tcheckBit: "<<sys::checkBit()
        <<std::endl;
    cout<<"Cpu::processors: "<<sys::Cpu::processors()<<endl;

    return 0;
}
<commit_msg>update info display<commit_after>#include <Monitoring/sys.hpp>

#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main(int argc,char* argv[])
{
    cout<<"Sys infos:\n\tosName: "<<sys::osName()
        <<"\n\tosBit: "<<sys::osBit()
        <<"\n\tosNameBit: "<<sys::osNameBit()
        <<"\n\tcheckBit: "<<sys::checkBit()
        <<"\n\tmemory::Physical"
        <<"\n\t\ttotal: "<<sys::memory::Physical::total()
        <<"\n\t\tused: "<<sys::memory::Physical::used()
        <<"\n\t\tusedByProc: "<<sys::memory::Physical::usedByProc()
        <<"\n\tmemory::Virtual"
        <<"\n\t\ttotal: "<<sys::memory::Virtual::total()
        <<"\n\t\tused: "<<sys::memory::Virtual::used()
        <<"\n\t\tusedByProc: "<<sys::memory::Virtual::usedByProc()
        <<"\n\tCpu::processors: "<<sys::Cpu::processors()
        <<endl;

    return 0;
}
<|endoftext|>


<commit_before>template<typename T>
struct Heap {
  T val;
  Heap *l, *r;
  Heap(T v) : val(v) {}
};

template<typename T>
Heap<T> *meld(Heap<T> *a, Heap<T> *b) {
  if (!a) return b;
  if (!b) return a;
  if (a->val > b->val) swap(a, b);
  a->r = meld(a->r, b);
  swap(a->l, a->r);
  return a;
}

template<typename T>
Heap<T> *push(Heap<T> *h, T v) {
  Heap<T> *p = new Heap<T>(v);
  return meld(h, p);
}

template<typename T>
Heap<T> *pop(Heap<T> *h) {
  Heap<T> *res = meld(h->l, h->r);
  free(h);
  return res;
}
<commit_msg>fix bug in constructor of skewheap<commit_after>template<typename T>
struct Heap {
  T val;
  Heap *l, *r;
  Heap(T v) : val(v), l(nullptr), r(nullptr) {}
};

template<typename T>
Heap<T> *meld(Heap<T> *a, Heap<T> *b) {
  if (!a) return b;
  if (!b) return a;
  if (a->val > b->val) swap(a, b);
  a->r = meld(a->r, b);
  swap(a->l, a->r);
  return a;
}

template<typename T>
Heap<T> *push(Heap<T> *h, T v) {
  Heap<T> *p = new Heap<T>(v);
  return meld(h, p);
}

template<typename T>
Heap<T> *pop(Heap<T> *h) {
  Heap<T> *res = meld(h->l, h->r);
  free(h);
  return res;
}
<|endoftext|>


<commit_before>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/ChannelRequest>

#include "TelepathyQt4/_gen/cli-channel-request-body.hpp"
#include "TelepathyQt4/_gen/cli-channel-request.moc.hpp"
#include "TelepathyQt4/_gen/channel-request.moc.hpp"

#include "TelepathyQt4/debug-internal.h"

#include <TelepathyQt4/Account>
#include <TelepathyQt4/PendingFailure>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/PendingVoidMethodCall>

#include <QDateTime>

/**
 * \addtogroup clientsideproxies Client-side proxies
 *
 * Proxy objects representing remote service objects accessed via D-Bus.
 *
 * In addition to providing direct access to methods, signals and properties
 * exported by the remote objects, some of these proxies offer features like
 * automatic inspection of remote object capabilities, property tracking,
 * backwards compatibility helpers for older services and other utilities.
 */

/**
 * \defgroup clientchannelrequest ChannelRequest proxies
 * \ingroup clientsideproxies
 *
 * Proxy objects representing remote Telepathy Channel Requests and their
 * optional interfaces.
 */

namespace Tp
{

struct ChannelRequest::Private
{
    Private(ChannelRequest *parent);
    ~Private();

    static void introspectMain(Private *self);

    // Public object
    ChannelRequest *parent;

    // Instance of generated interface class
    Client::ChannelRequestInterface *baseInterface;

    // Optional interface proxies
    Client::DBus::PropertiesInterface *properties;

    ReadinessHelper *readinessHelper;

    // Introspection
    QStringList interfaces;
    AccountPtr account;
    QDateTime userActionTime;
    QString preferredHandler;
    QualifiedPropertyValueMapList requests;
};

ChannelRequest::Private::Private(ChannelRequest *parent)
    : parent(parent),
      baseInterface(new Client::ChannelRequestInterface(
                    parent->dbusConnection(), parent->busName(),
                    parent->objectPath(), parent)),
      properties(0),
      readinessHelper(parent->readinessHelper())
{
    debug() << "Creating new ChannelRequest:" << parent->objectPath();

    ReadinessHelper::Introspectables introspectables;

    // As ChannelRequest does not have predefined statuses let's simulate one (0)
    ReadinessHelper::Introspectable introspectableCore(
        QSet<uint>() << 0,                                           // makesSenseForStatuses
        Features(),                                                  // dependsOnFeatures
        QStringList(),                                               // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectMain,
        this);
    introspectables[FeatureCore] = introspectableCore;

    readinessHelper->addIntrospectables(introspectables);
    readinessHelper->becomeReady(Features() << FeatureCore);
}

ChannelRequest::Private::~Private()
{
}

void ChannelRequest::Private::introspectMain(ChannelRequest::Private *self)
{
    if (!self->properties) {
        self->properties = self->parent->propertiesInterface();
        Q_ASSERT(self->properties != 0);
    }

    connect(self->baseInterface,
            SIGNAL(Failed(const QString &, const QString &)),
            self->parent,
            SIGNAL(failed(const QString &, const QString &)));
    connect(self->baseInterface,
            SIGNAL(Succeeded()),
            self->parent,
            SIGNAL(succeeded()));

    debug() << "Calling Properties::GetAll(ChannelRequest)";
    QDBusPendingCallWatcher *watcher =
        new QDBusPendingCallWatcher(
                self->properties->GetAll(TELEPATHY_INTERFACE_CHANNEL_REQUEST),
                self->parent);
    self->parent->connect(watcher,
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            SLOT(gotMainProperties(QDBusPendingCallWatcher*)));
}

/**
 * \class ChannelRequest
 * \ingroup clientchannelrequest
 * \headerfile <TelepathyQt4/channel-request.h> <TelepathyQt4/ChannelRequest>
 *
 * High-level proxy object for accessing remote Telepathy ChannelRequest objects.
 */

const Feature ChannelRequest::FeatureCore = Feature(ChannelRequest::staticMetaObject.className(), 0, true);

ChannelRequestPtr ChannelRequest::create(const QString &objectPath,
        const QVariantMap &immutableProperties)
{
    return ChannelRequestPtr(new ChannelRequest(objectPath,
                immutableProperties));
}

ChannelRequestPtr ChannelRequest::create(const QDBusConnection &bus,
        const QString &objectPath, const QVariantMap &immutableProperties)
{
    return ChannelRequestPtr(new ChannelRequest(bus, objectPath,
                immutableProperties));
}

ChannelRequest::ChannelRequest(const QString &objectPath,
        const QVariantMap &immutableProperties)
    : StatefulDBusProxy(QDBusConnection::sessionBus(),
            "org.freedesktop.Telepathy.ChannelDispatcher",
            objectPath),
      OptionalInterfaceFactory<ChannelRequest>(this),
      ReadyObject(this, FeatureCore),
      mPriv(new Private(this))
{
    // FIXME: remember the immutableProperties, and use them to reduce the
    // number of D-Bus calls we need to make (but we should make at least
    // one, to check that the channel request does in fact exist)
}

ChannelRequest::ChannelRequest(const QDBusConnection &bus,
        const QString &objectPath, const QVariantMap &immutableProperties)
    : StatefulDBusProxy(bus,
            "org.freedesktop.Telepathy.ChannelDispatcher",
            objectPath),
      OptionalInterfaceFactory<ChannelRequest>(this),
      ReadyObject(this, FeatureCore),
      mPriv(new Private(this))
{
    // FIXME: remember the immutableProperties, and use them to reduce the
    // number of D-Bus calls we need to make (but we should make at least
    // one, to check that the channel request does in fact exist)
}

/**
 * Class destructor.
 */
ChannelRequest::~ChannelRequest()
{
    delete mPriv;
}

QStringList ChannelRequest::interfaces() const
{
    if (!isReady()) {
        warning() << "ChannelRequest::interfaces() used channel request not ready";
    }
    return mPriv->interfaces;
}

AccountPtr ChannelRequest::account() const
{
    if (!isReady()) {
        warning() << "ChannelRequest::account() used channel request not ready";
    }
    return mPriv->account;
}

QDateTime ChannelRequest::userActionTime() const
{
    if (!isReady()) {
        warning() << "ChannelRequest::userActionTime() used channel request not ready";
    }
    return mPriv->userActionTime;
}

QString ChannelRequest::preferredHandler() const
{
    if (!isReady()) {
        warning() << "ChannelRequest::preferredHandler() used channel request not ready";
    }
    return mPriv->preferredHandler;
}

QualifiedPropertyValueMapList ChannelRequest::requests() const
{
    if (!isReady()) {
        warning() << "ChannelRequest::requests() used channel request not ready";
    }
    return mPriv->requests;
}

PendingOperation *ChannelRequest::cancel()
{
    if (!isReady()) {
        return new PendingFailure(this, TELEPATHY_ERROR_NOT_AVAILABLE,
                "ChannelRequest not ready");
    }

    return new PendingVoidMethodCall(this, mPriv->baseInterface->Cancel());
}

/**
 * Get the ChannelRequestInterface for this ChannelRequest class. This method is
 * protected since the convenience methods provided by this class should
 * always be used instead of the interface by users of the class.
 *
 * \return A pointer to the existing ChannelRequestInterface for this
 *         ChannelRequest
 */
Client::ChannelRequestInterface *ChannelRequest::baseInterface() const
{
    return mPriv->baseInterface;
}

void ChannelRequest::gotMainProperties(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QVariantMap> reply = *watcher;
    QVariantMap props;

    if (!reply.isError()) {
        debug() << "Got reply to Properties::GetAll(ChannelRequest)";
        props = reply.value();

        mPriv->interfaces = qdbus_cast<QStringList>(props["Interfaces"]);

        QDBusObjectPath accountObjectPath =
            qdbus_cast<QDBusObjectPath>(props["Account"]);
        mPriv->account = Account::create(
                TELEPATHY_ACCOUNT_MANAGER_BUS_NAME,
                accountObjectPath.path());
        connect(mPriv->account->becomeReady(),
                SIGNAL(finished(Tp::PendingOperation *)),
                SLOT(onAccountReady(Tp::PendingOperation *)));

        // FIXME: Telepathy supports 64-bit time_t, but Qt only does so on
        // ILP64 systems (e.g. sparc64, but not x86_64). If QDateTime
        // gains a fromTimestamp64 method, we should use it instead.
        uint stamp = (uint) qdbus_cast<qlonglong>(props["UserActionTime"]);
        if (stamp != 0) {
            mPriv->userActionTime = QDateTime::fromTime_t(stamp);
        }

        mPriv->preferredHandler = qdbus_cast<QString>(props["PreferredHandler"]);
        mPriv->requests = qdbus_cast<QualifiedPropertyValueMapList>(props["Requests"]);
    }
    else {
        mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, false, reply.error());
        warning().nospace() << "Properties::GetAll(ChannelRequest) failed with "
            << reply.error().name() << ": " << reply.error().message();
    }
}

void ChannelRequest::onAccountReady(PendingOperation *op)
{
    if (op->isError()) {
        warning() << "Unable to make account ready";
        mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, false,
                op->errorName(), op->errorMessage());
        return;
    }
    mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);
}

} // Tp
<commit_msg>ChannelRequest: Fixed coding style.<commit_after>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/ChannelRequest>

#include "TelepathyQt4/_gen/cli-channel-request-body.hpp"
#include "TelepathyQt4/_gen/cli-channel-request.moc.hpp"
#include "TelepathyQt4/_gen/channel-request.moc.hpp"

#include "TelepathyQt4/debug-internal.h"

#include <TelepathyQt4/Account>
#include <TelepathyQt4/PendingFailure>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/PendingVoidMethodCall>

#include <QDateTime>

/**
 * \addtogroup clientsideproxies Client-side proxies
 *
 * Proxy objects representing remote service objects accessed via D-Bus.
 *
 * In addition to providing direct access to methods, signals and properties
 * exported by the remote objects, some of these proxies offer features like
 * automatic inspection of remote object capabilities, property tracking,
 * backwards compatibility helpers for older services and other utilities.
 */

/**
 * \defgroup clientchannelrequest ChannelRequest proxies
 * \ingroup clientsideproxies
 *
 * Proxy objects representing remote Telepathy Channel Requests and their
 * optional interfaces.
 */

namespace Tp
{

struct ChannelRequest::Private
{
    Private(ChannelRequest *parent);
    ~Private();

    static void introspectMain(Private *self);

    // Public object
    ChannelRequest *parent;

    // Instance of generated interface class
    Client::ChannelRequestInterface *baseInterface;

    // Optional interface proxies
    Client::DBus::PropertiesInterface *properties;

    ReadinessHelper *readinessHelper;

    // Introspection
    QStringList interfaces;
    AccountPtr account;
    QDateTime userActionTime;
    QString preferredHandler;
    QualifiedPropertyValueMapList requests;
};

ChannelRequest::Private::Private(ChannelRequest *parent)
    : parent(parent),
      baseInterface(new Client::ChannelRequestInterface(
                    parent->dbusConnection(), parent->busName(),
                    parent->objectPath(), parent)),
      properties(0),
      readinessHelper(parent->readinessHelper())
{
    debug() << "Creating new ChannelRequest:" << parent->objectPath();

    ReadinessHelper::Introspectables introspectables;

    // As ChannelRequest does not have predefined statuses let's simulate one (0)
    ReadinessHelper::Introspectable introspectableCore(
        QSet<uint>() << 0,                                           // makesSenseForStatuses
        Features(),                                                  // dependsOnFeatures
        QStringList(),                                               // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectMain,
        this);
    introspectables[FeatureCore] = introspectableCore;

    readinessHelper->addIntrospectables(introspectables);
    readinessHelper->becomeReady(Features() << FeatureCore);
}

ChannelRequest::Private::~Private()
{
}

void ChannelRequest::Private::introspectMain(ChannelRequest::Private *self)
{
    if (!self->properties) {
        self->properties = self->parent->propertiesInterface();
        Q_ASSERT(self->properties != 0);
    }

    connect(self->baseInterface,
            SIGNAL(Failed(const QString &, const QString &)),
            self->parent,
            SIGNAL(failed(const QString &, const QString &)));
    connect(self->baseInterface,
            SIGNAL(Succeeded()),
            self->parent,
            SIGNAL(succeeded()));

    debug() << "Calling Properties::GetAll(ChannelRequest)";
    QDBusPendingCallWatcher *watcher =
        new QDBusPendingCallWatcher(
                self->properties->GetAll(TELEPATHY_INTERFACE_CHANNEL_REQUEST),
                self->parent);
    self->parent->connect(watcher,
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            SLOT(gotMainProperties(QDBusPendingCallWatcher*)));
}

/**
 * \class ChannelRequest
 * \ingroup clientchannelrequest
 * \headerfile <TelepathyQt4/channel-request.h> <TelepathyQt4/ChannelRequest>
 *
 * High-level proxy object for accessing remote Telepathy ChannelRequest objects.
 */

const Feature ChannelRequest::FeatureCore = Feature(ChannelRequest::staticMetaObject.className(), 0, true);

ChannelRequestPtr ChannelRequest::create(const QString &objectPath,
        const QVariantMap &immutableProperties)
{
    return ChannelRequestPtr(new ChannelRequest(objectPath,
                immutableProperties));
}

ChannelRequestPtr ChannelRequest::create(const QDBusConnection &bus,
        const QString &objectPath, const QVariantMap &immutableProperties)
{
    return ChannelRequestPtr(new ChannelRequest(bus, objectPath,
                immutableProperties));
}

ChannelRequest::ChannelRequest(const QString &objectPath,
        const QVariantMap &immutableProperties)
    : StatefulDBusProxy(QDBusConnection::sessionBus(),
            "org.freedesktop.Telepathy.ChannelDispatcher",
            objectPath),
      OptionalInterfaceFactory<ChannelRequest>(this),
      ReadyObject(this, FeatureCore),
      mPriv(new Private(this))
{
    // FIXME: remember the immutableProperties, and use them to reduce the
    // number of D-Bus calls we need to make (but we should make at least
    // one, to check that the channel request does in fact exist)
}

ChannelRequest::ChannelRequest(const QDBusConnection &bus,
        const QString &objectPath, const QVariantMap &immutableProperties)
    : StatefulDBusProxy(bus,
            "org.freedesktop.Telepathy.ChannelDispatcher",
            objectPath),
      OptionalInterfaceFactory<ChannelRequest>(this),
      ReadyObject(this, FeatureCore),
      mPriv(new Private(this))
{
    // FIXME: remember the immutableProperties, and use them to reduce the
    // number of D-Bus calls we need to make (but we should make at least
    // one, to check that the channel request does in fact exist)
}

/**
 * Class destructor.
 */
ChannelRequest::~ChannelRequest()
{
    delete mPriv;
}

QStringList ChannelRequest::interfaces() const
{
    if (!isReady()) {
        warning() << "ChannelRequest::interfaces() used channel request not ready";
    }
    return mPriv->interfaces;
}

AccountPtr ChannelRequest::account() const
{
    if (!isReady()) {
        warning() << "ChannelRequest::account() used channel request not ready";
    }
    return mPriv->account;
}

QDateTime ChannelRequest::userActionTime() const
{
    if (!isReady()) {
        warning() << "ChannelRequest::userActionTime() used channel request not ready";
    }
    return mPriv->userActionTime;
}

QString ChannelRequest::preferredHandler() const
{
    if (!isReady()) {
        warning() << "ChannelRequest::preferredHandler() used channel request not ready";
    }
    return mPriv->preferredHandler;
}

QualifiedPropertyValueMapList ChannelRequest::requests() const
{
    if (!isReady()) {
        warning() << "ChannelRequest::requests() used channel request not ready";
    }
    return mPriv->requests;
}

PendingOperation *ChannelRequest::cancel()
{
    if (!isReady()) {
        return new PendingFailure(this, TELEPATHY_ERROR_NOT_AVAILABLE,
                "ChannelRequest not ready");
    }

    return new PendingVoidMethodCall(this, mPriv->baseInterface->Cancel());
}

/**
 * Get the ChannelRequestInterface for this ChannelRequest class. This method is
 * protected since the convenience methods provided by this class should
 * always be used instead of the interface by users of the class.
 *
 * \return A pointer to the existing ChannelRequestInterface for this
 *         ChannelRequest
 */
Client::ChannelRequestInterface *ChannelRequest::baseInterface() const
{
    return mPriv->baseInterface;
}

void ChannelRequest::gotMainProperties(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QVariantMap> reply = *watcher;
    QVariantMap props;

    if (!reply.isError()) {
        debug() << "Got reply to Properties::GetAll(ChannelRequest)";
        props = reply.value();

        mPriv->interfaces = qdbus_cast<QStringList>(props["Interfaces"]);

        QDBusObjectPath accountObjectPath =
            qdbus_cast<QDBusObjectPath>(props["Account"]);
        mPriv->account = Account::create(
                TELEPATHY_ACCOUNT_MANAGER_BUS_NAME,
                accountObjectPath.path());
        connect(mPriv->account->becomeReady(),
                SIGNAL(finished(Tp::PendingOperation *)),
                SLOT(onAccountReady(Tp::PendingOperation *)));

        // FIXME: Telepathy supports 64-bit time_t, but Qt only does so on
        // ILP64 systems (e.g. sparc64, but not x86_64). If QDateTime
        // gains a fromTimestamp64 method, we should use it instead.
        uint stamp = (uint) qdbus_cast<qlonglong>(props["UserActionTime"]);
        if (stamp != 0) {
            mPriv->userActionTime = QDateTime::fromTime_t(stamp);
        }

        mPriv->preferredHandler = qdbus_cast<QString>(props["PreferredHandler"]);
        mPriv->requests =
            qdbus_cast<QualifiedPropertyValueMapList>(props["Requests"]);
    }
    else {
        mPriv->readinessHelper->setIntrospectCompleted(FeatureCore,
                false, reply.error());
        warning().nospace() << "Properties::GetAll(ChannelRequest) failed with "
            << reply.error().name() << ": " << reply.error().message();
    }
}

void ChannelRequest::onAccountReady(PendingOperation *op)
{
    if (op->isError()) {
        warning() << "Unable to make account ready";
        mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, false,
                op->errorName(), op->errorMessage());
        return;
    }
    mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);
}

} // Tp
<|endoftext|>


<commit_before>//
// Helper.cpp - various helper functions used by VTBuilder
//
// Copyright (c) 2001-2008 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "Builder.h"
#include "Helper.h"
#include "vtdata/vtLog.h"
#include "minidata/LocalDatabuf.h"
#include "TilingOptions.h"

#if SUPPORT_SQUISH
#include "squish.h"
#ifdef _MSC_VER
	#pragma message( "Adding link with squish.lib" )
	#pragma comment( lib, "squish.lib" )
#endif
#endif

#define USE_LIBMINI_SQUISH 0
#define USE_LIBMINI_CONVHOOK 1

#if (USE_LIBMINI_DATABUF && USE_LIBMINI_SQUISH)
#include <mini/squishbase.h>
#endif

#if (USE_LIBMINI_DATABUF && USE_LIBMINI_CONVHOOK)
#include "minidata/convbase.h"
#endif

/*
#if (USE_LIBMINI_DATABUF && (USE_LIBMINI_SQUISH || USE_LIBMINI_CONVHOOK))
#ifdef _MSC_VER
  #if _MSC_VER >= 1400	// vc8
	  #pragma message( "Adding link with libMiniSFX-vc8.lib" )
	  #pragma comment( lib, "libMiniSFX-vc8.lib" )
  #else					// vc71
	  #pragma message( "Adding link with libMiniSFX-vc7.lib" )
	  #pragma comment( lib, "libMiniSFX-vc7.lib" )
  #endif
#endif
#endif
*/

void WriteMiniImage(const vtString &fname, const TilingOptions &opts,
					unsigned char *rgb_bytes, vtMiniDatabuf &output_buf,
					int iUncompressedSize, ImageGLCanvas *pCanvas)
{
	if (opts.bUseTextureCompression)
	{
		// Compressed
		// Output to a compressed RGB .db file

		if (opts.eCompressionType == TC_OPENGL)
		{
#if USE_OPENGL
			DoTextureCompress(rgb_bytes, output_buf, pCanvas->m_iTex, opts.bMaskUnknownAreas);

			output_buf.savedata(fname);
			output_buf.release();

			if (output_buf.xsize == 256)
				pCanvas->Refresh(false);
#endif
		}
		else if (opts.eCompressionType == TC_SQUISH_FAST ||
			opts.eCompressionType == TC_SQUISH_SLOW)
		{
#if SUPPORT_SQUISH
			DoTextureSquish(rgb_bytes, output_buf, opts.eCompressionType == TC_SQUISH_FAST);
			output_buf.savedata(fname);
			output_buf.release();
#endif
		}
		else if (opts.eCompressionType == TC_JPEG)
		{
			output_buf.type = 3;	// RGB
			output_buf.bytes = iUncompressedSize;
			output_buf.data = malloc(iUncompressedSize);
			memcpy(output_buf.data, rgb_bytes, iUncompressedSize);
			output_buf.savedata(fname, databuf::DATABUF_EXTFMT_JPEG);
			output_buf.release();
		}
	}
	else
	{
		// Uncompressed
		if (opts.bMaskUnknownAreas)
		{
			// Output to a plain RGBA .db file
			output_buf.type = 4;	// RGBA
		}
		else
		{
			// Output to a plain RGB .db file
			output_buf.type = 3;	// RGB
		}
		output_buf.bytes = iUncompressedSize;
		output_buf.data = malloc(iUncompressedSize);
		memcpy(output_buf.data, rgb_bytes, iUncompressedSize);
		output_buf.savedata(fname);
		output_buf.release();
	}
}

void CheckCompressionMethod(TilingOptions &opts)
{
#if !USE_OPENGL
	// Check if they asked for OpenGL, but it's not available
	if (opts.eCompressionType == TC_OPENGL)
	{
#if SUPPORT_SQUISH
		opts.eCompressionType = TC_SQUISH_FAST;
#else
		opts.bUseTextureCompression = false;
#endif
	}
#endif
#if !SUPPORT_SQUISH
	// Check if they asked for Squish, but it's not available
	if (opts.eCompressionType == TC_SQUISH_FAST || opts.eCompressionType == TC_SQUISH_SLOW)
	{
#if USE_OPENGL
		opts.eCompressionType = TC_OPENGL;
#else
		opts.bUseTextureCompression = false;
#endif
	}
#endif
}

/////////////////////////////////////////////////////

#if USE_OPENGL

#ifdef __DARWIN_OSX__
  #include <OpenGL/gl.h>
  #include <OpenGL/glext.h>
#else
  #include <GL/gl.h>
  #include <GL/glext.h>
#endif
#ifdef _MSC_VER
	#pragma message( "Adding link with opengl32.lib" )
	#pragma comment( lib, "opengl32.lib" )
#endif

#if !WIN32
#include <dlfcn.h>
#endif
#ifdef __DARWIN_OSX__
# include <mach-o/dyld.h>
#endif

void* getGLExtensionFuncPtr(const char *funcName)
{
#if defined(WIN32)
	return (void*)wglGetProcAddress(funcName);

#elif defined(__APPLE__)
	std::string temp( "_" );
	temp += funcName;    // Mac OS X prepends an underscore on function names
	if ( NSIsSymbolNameDefined( temp.c_str() ) )
	{
		NSSymbol symbol = NSLookupAndBindSymbol( temp.c_str() );
		return NSAddressOfSymbol( symbol );
	} else
		return NULL;

#elif defined (__sun)
	static void *handle = dlopen((const char *)0L, RTLD_LAZY);
	return dlsym(handle, funcName);

#elif defined (__sgi)
	static void *handle = dlopen((const char *)0L, RTLD_LAZY);
	return dlsym(handle, funcName);

#elif defined (__FreeBSD__)
	return dlsym( RTLD_DEFAULT, funcName );

#elif defined (__linux__)
	typedef void (*__GLXextFuncPtr)(void);
	typedef __GLXextFuncPtr (*GetProcAddressARBProc)(const char*);
	static GetProcAddressARBProc s_glXGetProcAddressARB = (GetProcAddressARBProc)dlsym(0, "glXGetProcAddressARB");
	if (s_glXGetProcAddressARB)
	{
		return (void*) (s_glXGetProcAddressARB)(funcName);
	}
	else
	{
		return dlsym(0, funcName);
	}

#else // all other unixes
	return dlsym(0, funcName);

#endif
}

void DoTextureCompress(unsigned char *rgb_bytes, vtMiniDatabuf &output_buf,
					   GLuint &iTex, bool bAlpha)
{
	// Next, compress them to a DXT1 output file
	GLenum target = GL_TEXTURE_2D;
	int level = 0;
	GLenum format;
	GLint internalformat;
	if (bAlpha)
	{
		format = GL_RGBA;
		internalformat = GL_COMPRESSED_RGBA_ARB;
	}
	else
	{
		format = GL_RGB;
		internalformat = GL_COMPRESSED_RGB_ARB;
	}
	int border = 0;
	GLenum type = GL_UNSIGNED_BYTE;
	GLvoid *pixels = rgb_bytes;

	if (iTex == 9999)	// not yet assigned
		glGenTextures(1, &iTex);
	glBindTexture(GL_TEXTURE_2D, iTex);

	glTexImage2D(target, level, internalformat,
		output_buf.xsize, output_buf.ysize, border, format, type, pixels);

	// Check to see if the compression operation succeeded
	GLint iParam;
	glGetTexLevelParameteriv(target, level, GL_TEXTURE_COMPRESSED_ARB, &iParam);
//	VTLOG("GL_TEXTURE_COMPRESSED_ARB: %d\n", iParam);

	GLint iInternalFormat;
	glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &iInternalFormat);
//	VTLOG("GL_TEXTURE_INTERNAL_FORMAT: %d\n", iInternalFormat);

	GLint iSize;
	glGetTexLevelParameteriv(target, level, GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB, &iSize);
//	VTLOG("GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB: %d\n", iSize);

	if (bAlpha)
		output_buf.type = 6;	// compressed RGBA (S3TC DXT1 with 1-bit alpha)
	else
		output_buf.type = 5;	// compressed RGB (S3TC DXT1)
	output_buf.bytes = iSize;
	output_buf.data = malloc(iSize);

	PFNGLGETCOMPRESSEDTEXIMAGEARBPROC gctia = (PFNGLGETCOMPRESSEDTEXIMAGEARBPROC)
		getGLExtensionFuncPtr("glGetCompressedTexImageARB");
	gctia(target, level, output_buf.data);
}

//
// ImageGLCanvas class:
//  We need to open an OpenGL context in order to do the texture compression,
//  so we may as well draw something into it, since it requires little extra
//  work, and provides interesting visual feedback to the user.
//
BEGIN_EVENT_TABLE(ImageGLCanvas, wxGLCanvas)
EVT_PAINT(ImageGLCanvas::OnPaint)
EVT_SIZE(ImageGLCanvas::OnSize)
END_EVENT_TABLE()

ImageGLCanvas::ImageGLCanvas(wxWindow *parent, const wxWindowID id, const wxPoint& pos,
	const wxSize& size, long style, const wxString &name,
	int* gl_attrib) : wxGLCanvas(parent, id, pos, size, style, name, gl_attrib)
{
	m_iTex = 9999;

	// These two lines are needed for wxGTK (and possibly other platforms, but not wxMSW)
	parent->Show(TRUE);
	SetCurrent();
}

void ImageGLCanvas::OnPaint(wxPaintEvent& event)
{
	wxPaintDC dc(this);
	if (m_iTex == 9999)
		return;

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	IPoint2 size;
	GetClientSize(&size.x, &size.y);

	// Direct pixel coordinates with origin in center of window
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-size.x/2,size.x/2,-size.y/2,size.y/2,0,1);

	// Draw a quad with the current texture
	glEnable(GL_TEXTURE_2D);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glBindTexture(GL_TEXTURE_2D, m_iTex);
	glColor3f(0.0f, 0.0f, 1.0f);
	glBegin(GL_QUADS);
	glTexCoord2f(0, 1);	glVertex3f(-128, -128, 0);
	glTexCoord2f(1, 1);	glVertex3f( 128, -128, 0);
	glTexCoord2f(1, 0);	glVertex3f( 128,  128, 0);
	glTexCoord2f(0, 0);	glVertex3f(-128,  128, 0);
	glEnd();
	glDisable(GL_TEXTURE_2D);

	SwapBuffers();
}

void ImageGLCanvas::OnSize(wxSizeEvent& event)
{
	glViewport(0, 0, event.m_size.x, event.m_size.y);
}
#endif	// USE_OPENGL

///////////////////////////////////////////////////////////////////////
// As an alternative to using OpenGL for texture compression, use the
//  Squish library if available.
//
#if SUPPORT_SQUISH
using namespace squish;

void DoTextureSquish(unsigned char *rgb_bytes, vtMiniDatabuf &output_buf, bool bFast)
{
	int flags = kDxt1;

	if (bFast)
	{
		//! Use a fast but low quality colour compressor.
		flags |= kColourRangeFit;
	}
	else
	{
		//! Use a slow but very high quality colour compressor.
		flags |= kColourClusterFit;
	}

	int bytesPerBlock = ( ( flags & kDxt1 ) != 0 ) ? 8 : 16;
	int targetDataSize = bytesPerBlock*output_buf.xsize*output_buf.ysize/16;
	int stride = output_buf.xsize * 3;

	output_buf.type = 5;	// compressed RGB
	output_buf.bytes = targetDataSize;
	output_buf.data = malloc(targetDataSize);

	// loop over blocks and compress them
	u8* targetBlock = (u8 *) output_buf.data;
	for( unsigned int y = 0; y < output_buf.ysize; y += 4 )
	{
		// process a row of blocks
		for( unsigned int x = 0; x < output_buf.xsize; x += 4 )
		{
			// get the block data
			u8 sourceRgba[16*4];

			for( int py = 0, i = 0; py < 4; ++py )
			{
				u8 const *row = rgb_bytes + (y + py)*stride + (x*3);
				for( int px = 0; px < 4; ++px, ++i )
				{
					// get the pixel colour
					for( int j = 0; j < 3; ++j )
						sourceRgba[4*i + j] = *row++;

					// skip alpha for now
					sourceRgba[4*i + 3] = 255;
				}
			}

			// compress this block
			Compress( sourceRgba, targetBlock, flags );

			// advance
			targetBlock += bytesPerBlock;
		}
	}
}
#endif	// SUPPORT_SQUISH

<commit_msg>USE_LIBMINI_SQUISH is not used, remove definition<commit_after>//
// Helper.cpp - various helper functions used by VTBuilder
//
// Copyright (c) 2001-2008 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "Builder.h"
#include "Helper.h"
#include "vtdata/vtLog.h"
#include "minidata/LocalDatabuf.h"
#include "TilingOptions.h"

#if SUPPORT_SQUISH
#include "squish.h"
#ifdef _MSC_VER
	#pragma message( "Adding link with squish.lib" )
	#pragma comment( lib, "squish.lib" )
#endif
#endif

#define USE_LIBMINI_CONVHOOK 1

#if (USE_LIBMINI_DATABUF && USE_LIBMINI_CONVHOOK)
#include "minidata/convbase.h"
#endif

void WriteMiniImage(const vtString &fname, const TilingOptions &opts,
					unsigned char *rgb_bytes, vtMiniDatabuf &output_buf,
					int iUncompressedSize, ImageGLCanvas *pCanvas)
{
	if (opts.bUseTextureCompression)
	{
		// Compressed
		// Output to a compressed RGB .db file

		if (opts.eCompressionType == TC_OPENGL)
		{
#if USE_OPENGL
			DoTextureCompress(rgb_bytes, output_buf, pCanvas->m_iTex, opts.bMaskUnknownAreas);

			output_buf.savedata(fname);
			output_buf.release();

			if (output_buf.xsize == 256)
				pCanvas->Refresh(false);
#endif
		}
		else if (opts.eCompressionType == TC_SQUISH_FAST ||
			opts.eCompressionType == TC_SQUISH_SLOW)
		{
#if SUPPORT_SQUISH
			DoTextureSquish(rgb_bytes, output_buf, opts.eCompressionType == TC_SQUISH_FAST);
			output_buf.savedata(fname);
			output_buf.release();
#endif
		}
		else if (opts.eCompressionType == TC_JPEG)
		{
			output_buf.type = 3;	// RGB
			output_buf.bytes = iUncompressedSize;
			output_buf.data = malloc(iUncompressedSize);
			memcpy(output_buf.data, rgb_bytes, iUncompressedSize);
			output_buf.savedata(fname, databuf::DATABUF_EXTFMT_JPEG);
			output_buf.release();
		}
	}
	else
	{
		// Uncompressed
		if (opts.bMaskUnknownAreas)
		{
			// Output to a plain RGBA .db file
			output_buf.type = 4;	// RGBA
		}
		else
		{
			// Output to a plain RGB .db file
			output_buf.type = 3;	// RGB
		}
		output_buf.bytes = iUncompressedSize;
		output_buf.data = malloc(iUncompressedSize);
		memcpy(output_buf.data, rgb_bytes, iUncompressedSize);
		output_buf.savedata(fname);
		output_buf.release();
	}
}

void CheckCompressionMethod(TilingOptions &opts)
{
#if !USE_OPENGL
	// Check if they asked for OpenGL, but it's not available
	if (opts.eCompressionType == TC_OPENGL)
	{
#if SUPPORT_SQUISH
		opts.eCompressionType = TC_SQUISH_FAST;
#else
		opts.bUseTextureCompression = false;
#endif
	}
#endif
#if !SUPPORT_SQUISH
	// Check if they asked for Squish, but it's not available
	if (opts.eCompressionType == TC_SQUISH_FAST || opts.eCompressionType == TC_SQUISH_SLOW)
	{
#if USE_OPENGL
		opts.eCompressionType = TC_OPENGL;
#else
		opts.bUseTextureCompression = false;
#endif
	}
#endif
}

/////////////////////////////////////////////////////

#if USE_OPENGL

#ifdef __DARWIN_OSX__
  #include <OpenGL/gl.h>
  #include <OpenGL/glext.h>
#else
  #include <GL/gl.h>
  #include <GL/glext.h>
#endif
#ifdef _MSC_VER
	#pragma message( "Adding link with opengl32.lib" )
	#pragma comment( lib, "opengl32.lib" )
#endif

#if !WIN32
#include <dlfcn.h>
#endif
#ifdef __DARWIN_OSX__
# include <mach-o/dyld.h>
#endif

void* getGLExtensionFuncPtr(const char *funcName)
{
#if defined(WIN32)
	return (void*)wglGetProcAddress(funcName);

#elif defined(__APPLE__)
	std::string temp( "_" );
	temp += funcName;    // Mac OS X prepends an underscore on function names
	if ( NSIsSymbolNameDefined( temp.c_str() ) )
	{
		NSSymbol symbol = NSLookupAndBindSymbol( temp.c_str() );
		return NSAddressOfSymbol( symbol );
	} else
		return NULL;

#elif defined (__sun)
	static void *handle = dlopen((const char *)0L, RTLD_LAZY);
	return dlsym(handle, funcName);

#elif defined (__sgi)
	static void *handle = dlopen((const char *)0L, RTLD_LAZY);
	return dlsym(handle, funcName);

#elif defined (__FreeBSD__)
	return dlsym( RTLD_DEFAULT, funcName );

#elif defined (__linux__)
	typedef void (*__GLXextFuncPtr)(void);
	typedef __GLXextFuncPtr (*GetProcAddressARBProc)(const char*);
	static GetProcAddressARBProc s_glXGetProcAddressARB = (GetProcAddressARBProc)dlsym(0, "glXGetProcAddressARB");
	if (s_glXGetProcAddressARB)
	{
		return (void*) (s_glXGetProcAddressARB)(funcName);
	}
	else
	{
		return dlsym(0, funcName);
	}

#else // all other unixes
	return dlsym(0, funcName);

#endif
}

void DoTextureCompress(unsigned char *rgb_bytes, vtMiniDatabuf &output_buf,
					   GLuint &iTex, bool bAlpha)
{
	// Next, compress them to a DXT1 output file
	GLenum target = GL_TEXTURE_2D;
	int level = 0;
	GLenum format;
	GLint internalformat;
	if (bAlpha)
	{
		format = GL_RGBA;
		internalformat = GL_COMPRESSED_RGBA_ARB;
	}
	else
	{
		format = GL_RGB;
		internalformat = GL_COMPRESSED_RGB_ARB;
	}
	int border = 0;
	GLenum type = GL_UNSIGNED_BYTE;
	GLvoid *pixels = rgb_bytes;

	if (iTex == 9999)	// not yet assigned
		glGenTextures(1, &iTex);
	glBindTexture(GL_TEXTURE_2D, iTex);

	glTexImage2D(target, level, internalformat,
		output_buf.xsize, output_buf.ysize, border, format, type, pixels);

	// Check to see if the compression operation succeeded
	GLint iParam;
	glGetTexLevelParameteriv(target, level, GL_TEXTURE_COMPRESSED_ARB, &iParam);
//	VTLOG("GL_TEXTURE_COMPRESSED_ARB: %d\n", iParam);

	GLint iInternalFormat;
	glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &iInternalFormat);
//	VTLOG("GL_TEXTURE_INTERNAL_FORMAT: %d\n", iInternalFormat);

	GLint iSize;
	glGetTexLevelParameteriv(target, level, GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB, &iSize);
//	VTLOG("GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB: %d\n", iSize);

	if (bAlpha)
		output_buf.type = 6;	// compressed RGBA (S3TC DXT1 with 1-bit alpha)
	else
		output_buf.type = 5;	// compressed RGB (S3TC DXT1)
	output_buf.bytes = iSize;
	output_buf.data = malloc(iSize);

	PFNGLGETCOMPRESSEDTEXIMAGEARBPROC gctia = (PFNGLGETCOMPRESSEDTEXIMAGEARBPROC)
		getGLExtensionFuncPtr("glGetCompressedTexImageARB");
	gctia(target, level, output_buf.data);
}

//
// ImageGLCanvas class:
//  We need to open an OpenGL context in order to do the texture compression,
//  so we may as well draw something into it, since it requires little extra
//  work, and provides interesting visual feedback to the user.
//
BEGIN_EVENT_TABLE(ImageGLCanvas, wxGLCanvas)
EVT_PAINT(ImageGLCanvas::OnPaint)
EVT_SIZE(ImageGLCanvas::OnSize)
END_EVENT_TABLE()

ImageGLCanvas::ImageGLCanvas(wxWindow *parent, const wxWindowID id, const wxPoint& pos,
	const wxSize& size, long style, const wxString &name,
	int* gl_attrib) : wxGLCanvas(parent, id, pos, size, style, name, gl_attrib)
{
	m_iTex = 9999;

	// These two lines are needed for wxGTK (and possibly other platforms, but not wxMSW)
	parent->Show(TRUE);
	SetCurrent();
}

void ImageGLCanvas::OnPaint(wxPaintEvent& event)
{
	wxPaintDC dc(this);
	if (m_iTex == 9999)
		return;

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	IPoint2 size;
	GetClientSize(&size.x, &size.y);

	// Direct pixel coordinates with origin in center of window
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-size.x/2,size.x/2,-size.y/2,size.y/2,0,1);

	// Draw a quad with the current texture
	glEnable(GL_TEXTURE_2D);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glBindTexture(GL_TEXTURE_2D, m_iTex);
	glColor3f(0.0f, 0.0f, 1.0f);
	glBegin(GL_QUADS);
	glTexCoord2f(0, 1);	glVertex3f(-128, -128, 0);
	glTexCoord2f(1, 1);	glVertex3f( 128, -128, 0);
	glTexCoord2f(1, 0);	glVertex3f( 128,  128, 0);
	glTexCoord2f(0, 0);	glVertex3f(-128,  128, 0);
	glEnd();
	glDisable(GL_TEXTURE_2D);

	SwapBuffers();
}

void ImageGLCanvas::OnSize(wxSizeEvent& event)
{
	glViewport(0, 0, event.m_size.x, event.m_size.y);
}
#endif	// USE_OPENGL

///////////////////////////////////////////////////////////////////////
// As an alternative to using OpenGL for texture compression, use the
//  Squish library if available.
//
#if SUPPORT_SQUISH
using namespace squish;

void DoTextureSquish(unsigned char *rgb_bytes, vtMiniDatabuf &output_buf, bool bFast)
{
	int flags = kDxt1;

	if (bFast)
	{
		//! Use a fast but low quality colour compressor.
		flags |= kColourRangeFit;
	}
	else
	{
		//! Use a slow but very high quality colour compressor.
		flags |= kColourClusterFit;
	}

	int bytesPerBlock = ( ( flags & kDxt1 ) != 0 ) ? 8 : 16;
	int targetDataSize = bytesPerBlock*output_buf.xsize*output_buf.ysize/16;
	int stride = output_buf.xsize * 3;

	output_buf.type = 5;	// compressed RGB
	output_buf.bytes = targetDataSize;
	output_buf.data = malloc(targetDataSize);

	// loop over blocks and compress them
	u8* targetBlock = (u8 *) output_buf.data;
	for( unsigned int y = 0; y < output_buf.ysize; y += 4 )
	{
		// process a row of blocks
		for( unsigned int x = 0; x < output_buf.xsize; x += 4 )
		{
			// get the block data
			u8 sourceRgba[16*4];

			for( int py = 0, i = 0; py < 4; ++py )
			{
				u8 const *row = rgb_bytes + (y + py)*stride + (x*3);
				for( int px = 0; px < 4; ++px, ++i )
				{
					// get the pixel colour
					for( int j = 0; j < 3; ++j )
						sourceRgba[4*i + j] = *row++;

					// skip alpha for now
					sourceRgba[4*i + 3] = 255;
				}
			}

			// compress this block
			Compress( sourceRgba, targetBlock, flags );

			// advance
			targetBlock += bytesPerBlock;
		}
	}
}
#endif	// SUPPORT_SQUISH
<|endoftext|>


<commit_before><commit_msg>Extended logging for delete_object()<commit_after><|endoftext|>


<commit_before>#ifndef WARPED_EVENT_HPP
#define WARPED_EVENT_HPP

#include <string>
#include "serialization.hpp"
#include "VTime.hpp"

namespace warped {

struct compareEvents;

enum class EventType : bool {
    NEGATIVE = 0,
    POSITIVE
};

// Events are passed between objects. They may contain data, and must be
// serializable. See serialization.hpp for info on serializing Events.
class Event {
public:
    Event() : send_time_(&VTime::getZero()) {};
    Event(const VTime& send_time, const std::string sender_name) :
       sender_name_(sender_name), send_time_(&send_time) {};
    virtual ~Event() {}

    bool operator== (const Event &other) {
        return ((this->timestamp() == other.timestamp())
                && (this->send_time_ == other.send_time_)
                && (this->sender_name_ == other.sender_name_)
                && (this->generation_ == other.generation_));
    }

    bool operator< (const Event &other) {
        return  (this->timestamp() < other.timestamp()) ? true :
                ((this->timestamp() != other.timestamp()) ? false :
                  ((this->send_time_ < other.send_time_) ? true :
                  ((this->send_time_ != other.send_time_) ? false :
                    ((this->sender_name_ < other.sender_name_) ? true :
                    ((this->sender_name_ != other.sender_name_) ? false :
                      ((this->generation_ < other.generation_) ? true :
                      ((this->generation_ != other.generation_) ? false : false)))))));
    }

    bool operator<= (const Event &other) {
        return (*this < other) || (*this == other);
    }

    bool operator>= (const Event &other) {
        return !(*this < other);
    }

    bool operator> (const Event &other) {
        return !(*this <= other);
    }

    // The name of the SimualtionObject that should receive this event.
    virtual const std::string& receiverName() const = 0;

    // The timestamp of when the event should be received.
    virtual const VTime& timestamp() const = 0;

    // The name of the SimualtionObject that sends this event.
    std::string sender_name_;

    // Event type - positive or negative
    EventType event_type_ = EventType::POSITIVE;

    // Send time
    const VTime* send_time_;

    // For differentiating same events which is caused by
    //  anti-message + regeneration of event.
    unsigned long long generation_ = 0;

    WARPED_REGISTER_SERIALIZABLE_MEMBERS(sender_name_, event_type_, generation_)

};

class NegativeEvent : public Event {
public:
    NegativeEvent() : receive_time_(&VTime::getZero()) {};
    NegativeEvent(std::shared_ptr<Event> e) :
       Event(*e->send_time_, e->sender_name_), receive_time_(&(e->timestamp())) {
        receiver_name_ = e->receiverName();
        event_type_ = EventType::NEGATIVE;
        generation_ = e->generation_;
    }

    const std::string& receiverName() const { return receiver_name_; }
    const VTime& timestamp() const { return *receive_time_; }

    std::string receiver_name_;
    const VTime* receive_time_;

    WARPED_REGISTER_SERIALIZABLE_MEMBERS(cereal::base_class<Event>(this), receiver_name_)
};

// Initial event used with the initial state save of all objects
class InitialEvent : public Event {
public:
    InitialEvent() : Event(VTime::getZero(), "") {
        generation_ = 0;
   }

    const std::string& receiverName() const { return receiver_name_; }
    const VTime& timestamp() const { return VTime::getZero(); }

    std::string receiver_name_ = "";
};

/* Compares two events to see if one has a receive time less than to the other */
struct compareEvents {
public:
    bool operator() (const std::shared_ptr<Event>& first,
                     const std::shared_ptr<Event>& second) const {
        return  (first->timestamp() < second->timestamp()) ? true :
                ((first->timestamp() != second->timestamp()) ? false :
                  ((first->send_time_ < second->send_time_) ? true :
                  ((first->send_time_ != second->send_time_) ? false :
                    ((first->sender_name_ < second->sender_name_) ? true :
                    ((first->sender_name_ != second->sender_name_) ? false :
                      ((first->generation_ < second->generation_) ? true :
                      ((first->generation_ != second->generation_) ? false :
                        ((first->event_type_ < second->event_type_) ? true :
                        ((first->event_type_ != second->event_type_) ? false : false)))))))));
    }
};

} // namespace warped

#endif
<commit_msg>Fix compilation problems<commit_after>#ifndef WARPED_EVENT_HPP
#define WARPED_EVENT_HPP

#include <string>
#include "serialization.hpp"
#include "VTime.hpp"

namespace warped {

struct compareEvents;

enum class EventType : bool {
    NEGATIVE = 0,
    POSITIVE
};

// Events are passed between objects. They may contain data, and must be
// serializable. See serialization.hpp for info on serializing Events.
class Event {
public:
    Event(EventType type = EventType::POSITIVE) : event_type_(type), generation_(0) {};
    virtual ~Event() {}

    bool operator== (const Event &other) {
        return ((this->timestamp() == other.timestamp())
                && (this->send_time_ == other.send_time_)
                && (this->sender_name_ == other.sender_name_)
                && (this->generation_ == other.generation_));
    }

    bool operator< (const Event &other) {
        return  (this->timestamp() < other.timestamp()) ? true :
                ((this->timestamp() != other.timestamp()) ? false :
                  ((this->send_time_ < other.send_time_) ? true :
                  ((this->send_time_ != other.send_time_) ? false :
                    ((this->sender_name_ < other.sender_name_) ? true :
                    ((this->sender_name_ != other.sender_name_) ? false :
                      ((this->generation_ < other.generation_) ? true :
                      ((this->generation_ != other.generation_) ? false : false)))))));
    }

    bool operator<= (const Event &other) {
        return (*this < other) || (*this == other);
    }

    bool operator>= (const Event &other) {
        return !(*this < other);
    }

    bool operator> (const Event &other) {
        return !(*this <= other);
    }

    // The name of the SimualtionObject that should receive this event.
    virtual const std::string& receiverName() const = 0;

    // The timestamp of when the event should be received.
    virtual const VTime& timestamp() const = 0;

    // The name of the SimualtionObject that sends this event.
    std::string sender_name_;

    // Event type - positive or negative
    EventType event_type_;

    // Send time
    const VTime* send_time_;

    // For differentiating same events which is caused by
    //  anti-message + regeneration of event.
    unsigned long long generation_;

    WARPED_REGISTER_SERIALIZABLE_MEMBERS(sender_name_, event_type_, generation_)

};

class NegativeEvent : public Event {
public:
    NegativeEvent() : receive_time_(&VTime::getZero()) {};
    NegativeEvent(std::shared_ptr<Event> e) {
        receive_time_ = &(e->timestamp());
        receiver_name_ = e->receiverName();
        event_type_ = EventType::NEGATIVE;
        generation_ = e->generation_;
    }

    const std::string& receiverName() const { return receiver_name_; }
    const VTime& timestamp() const { return *receive_time_; }

    std::string receiver_name_;
    const VTime* receive_time_;

    WARPED_REGISTER_SERIALIZABLE_MEMBERS(cereal::base_class<Event>(this), receiver_name_)
};

// Initial event used with the initial state save of all objects
class InitialEvent : public Event {
public:
    InitialEvent() {
   }

    const std::string& receiverName() const { return receiver_name_; }
    const VTime& timestamp() const { return VTime::getZero(); }

    std::string receiver_name_ = "";
};

/* Compares two events to see if one has a receive time less than to the other */
struct compareEvents {
public:
    bool operator() (const std::shared_ptr<Event>& first,
                     const std::shared_ptr<Event>& second) const {
        return  (first->timestamp() < second->timestamp()) ? true :
                ((first->timestamp() != second->timestamp()) ? false :
                  ((first->send_time_ < second->send_time_) ? true :
                  ((first->send_time_ != second->send_time_) ? false :
                    ((first->sender_name_ < second->sender_name_) ? true :
                    ((first->sender_name_ != second->sender_name_) ? false :
                      ((first->generation_ < second->generation_) ? true :
                      ((first->generation_ != second->generation_) ? false :
                        ((first->event_type_ < second->event_type_) ? true :
                        ((first->event_type_ != second->event_type_) ? false : false)))))))));
    }
};

} // namespace warped

#endif
<|endoftext|>


<commit_before>
#include <verse.h>

#include <Ample.h>

using namespace verse::ample;

class Listener : public SessionObserver,
		 //public TextNodeObserver,
		 public TextBufferObserver,
		 public GeometryNodeObserver,
		 public GeometryLayerObserver,
		 public TagGroupObserver,
		 public TagObserver
{
public:
  void onAccept(Session& session)
  {
    printf("Accepted session %s\n", session.getAddress().c_str());

    /*
    session.createNode("text", V_NT_TEXT);
    session.createNode("geometry", V_NT_GEOMETRY);
    */
  }

  void onTerminate(Session& session, const std::string& byebye)
  {
    printf("Terminated session %s with %s\n",
           session.getAddress().c_str(),
	   byebye.c_str());
  }

  void onCreateNode(Session& session, Node& node)
  {
    printf("Created node %u of type %u\n", node.getID(), node.getType());

    /*
    if (node.isMine())
    {
      node.createTagGroup("group");

      switch (node.getType())
      {
	case V_NT_GEOMETRY:
	{
	  GeometryNode* geometryNode = dynamic_cast<GeometryNode*>(&node);
	  geometryNode->createLayer("layer", VN_G_LAYER_VERTEX_REAL);
	  break;
	}

	case V_NT_TEXT:
	{
	  TextNode* textNode = dynamic_cast<TextNode*>(&node);
	  textNode->createBuffer("buffer");
	  break;
	}
      }
    }
    */

    node.addObserver(*this);
  }

  void onDestroyNode(Session& session, Node& node)
  {
    printf("Destroyed node %u (%s)\n", node.getID(), node.getName().c_str());
  }

  void onCreateTagGroup(Node& node, TagGroup& group)
  {
    printf("Created tag group %s(%u) in node %u (%s)\n",
           group.getName().c_str(),
	   group.getID(),
	   node.getID(),
	   node.getName().c_str());

    group.addObserver(*this);

    /*
    if (group.getNode().isMine())
    {
      VNTag value;
      value.vboolean = true;
      group.createTag("tag", VN_TAG_BOOLEAN, value);
    }
    */
  }

  void onDestroyTagGroup(Node& node, TagGroup& group)
  {
    printf("Destroyed tag group %s(%u) in node %u (%s)\n",
           group.getName().c_str(),
	   group.getID(),
	   node.getID(),
	   node.getName().c_str());
  }

  void onSetName(Node& node, const std::string& name)
  {
    printf("Set name %s for node %u\n", name.c_str(), node.getID());
  }

  void onCreateVertex(GeometryNode& node, uint32 vertexID, const BaseVertex& vertex)
  {
    printf("Created vertex %u in node %u(%s)\n",
           vertexID,
	   node.getID(),
	   node.getName().c_str());

    BaseMesh mesh;
    node.getBaseMesh(mesh);
    printf("Base mesh has %u polygons and %u vertices\n", mesh.mPolygons.size(), mesh.mVertices.size());
  }

  void onDeleteVertex(GeometryNode& node, uint32 vertexID)
  {
    printf("Deleted vertex %u in node %u(%s)\n",
           vertexID,
	   node.getID(),
	   node.getName().c_str());
  }

  void onCreatePolygon(GeometryNode& node, uint32 polygonID, const BasePolygon& polygon)
  {
    printf("Created polygon %u in node %u(%s)\n",
           polygonID,
	   node.getID(),
	   node.getName().c_str());

    BaseMesh mesh;
    node.getBaseMesh(mesh);
    printf("Base mesh has %u polygons and %u vertices\n", mesh.mPolygons.size(), mesh.mVertices.size());
  }

  void onDeletePolygon(GeometryNode& node, uint32 polygonID)
  {
    printf("Deleted polygon %u in node %u(%s)\n",
           polygonID,
	   node.getID(),
	   node.getName().c_str());
  }

  void onCreateLayer(GeometryNode& node, GeometryLayer& layer)
  {
    printf("Created geometry layer %s(%u) of type %u in node %u (%s)\n",
           layer.getName().c_str(),
	   layer.getID(),
	   layer.getType(),
	   node.getID(),
	   node.getName().c_str());

    /*
    if (node.isMine())
      layer.setName("renamed_layer");
    */

    layer.addObserver(*this);
  }

  void onDestroyLayer(GeometryNode& node, GeometryLayer& layer)
  {
    printf("Destroyed geometry layer %s(%u) of in node %u (%s)\n",
           layer.getName().c_str(),
	   layer.getID(),
	   node.getID(),
	   node.getName().c_str());
  }

  void onSetSlot(GeometryLayer& layer, uint32 slotID, const void* data)
  {
    printf("Changed slot %u in layer %s(%u) of node %u (%s)\n",
           slotID,
	   layer.getName().c_str(),
	   layer.getID(),
	   layer.getNode().getID(),
	   layer.getNode().getName().c_str());
  }

  void onSetName(GeometryLayer& layer, const std::string& name)
  {
    printf("Changed name of layer %s(%u) to %s in node %u (%s)\n",
           layer.getName().c_str(),
	   layer.getID(),
	   name.c_str(),
	   layer.getNode().getID(),
	   layer.getNode().getName().c_str());
  }

  void onCreateTag(TagGroup& group, Tag& tag)
  {
    printf("Created tag %s in group %s(%u) of node %u (%s)\n",
           tag.getName().c_str(),
	   group.getName().c_str(),
	   group.getID(),
	   group.getNode().getID(),
	   group.getNode().getName().c_str());

    tag.addObserver(*this);

    /*
    tag.setName("renamed_tag");
    */
  }

  void onDestroyTag(TagGroup& group, Tag& tag)
  {
    printf("Destroyed tag %s in group %s(%u) of node %u (%s)\n",
           tag.getName().c_str(),
	   group.getName().c_str(),
	   group.getID(),
	   group.getNode().getID(),
	   group.getNode().getName().c_str());
  }

  void onSetName(TagGroup& group, const std::string& name)
  {
    printf("Changed name of group %s(%u) to %s of node %u (%s)\n",
	   group.getName().c_str(),
	   group.getID(),
	   name.c_str(),
	   group.getNode().getID(),
	   group.getNode().getName().c_str());
  }

  void onChange(Tag& tag)
  {
    printf("Changed something in tag %s in group %s of node %u (%s)\n",
           tag.getName().c_str(),
	   tag.getGroup().getName().c_str(),
	   tag.getGroup().getNode().getID(),
	   tag.getGroup().getNode().getName().c_str());
  }
};

int main(int argc, char** argv)
{
  std::string host;

  if (argc == 1)
    host = "localhost";
  else
    host = argv[1];

  Session* session = Session::create(host, "spoo", "fleem");
  if (!session)
    return 1;

  Listener listener;
  session->addObserver(listener);

  while (session->getState() != Session::TERMINATED)
    Session::update(10000);
}

<commit_msg>Vertex change events.<commit_after>
#include <verse.h>

#include <Ample.h>

using namespace verse::ample;

class Listener : public SessionObserver,
		 //public TextNodeObserver,
		 public TextBufferObserver,
		 public GeometryNodeObserver,
		 public GeometryLayerObserver,
		 public TagGroupObserver,
		 public TagObserver
{
public:
  void onAccept(Session& session)
  {
    printf("Accepted session %s\n", session.getAddress().c_str());

    /*
    session.createNode("text", V_NT_TEXT);
    session.createNode("geometry", V_NT_GEOMETRY);
    */
  }

  void onTerminate(Session& session, const std::string& byebye)
  {
    printf("Terminated session %s with %s\n",
           session.getAddress().c_str(),
	   byebye.c_str());
  }

  void onCreateNode(Session& session, Node& node)
  {
    printf("Created node %u of type %u\n", node.getID(), node.getType());

    /*
    if (node.isMine())
    {
      node.createTagGroup("group");

      switch (node.getType())
      {
	case V_NT_GEOMETRY:
	{
	  GeometryNode* geometryNode = dynamic_cast<GeometryNode*>(&node);
	  geometryNode->createLayer("layer", VN_G_LAYER_VERTEX_REAL);
	  break;
	}

	case V_NT_TEXT:
	{
	  TextNode* textNode = dynamic_cast<TextNode*>(&node);
	  textNode->createBuffer("buffer");
	  break;
	}
      }
    }
    */

    node.addObserver(*this);
  }

  void onDestroyNode(Session& session, Node& node)
  {
    printf("Destroyed node %u (%s)\n", node.getID(), node.getName().c_str());
  }

  void onCreateTagGroup(Node& node, TagGroup& group)
  {
    printf("Created tag group %s(%u) in node %u (%s)\n",
           group.getName().c_str(),
	   group.getID(),
	   node.getID(),
	   node.getName().c_str());

    group.addObserver(*this);

    /*
    if (group.getNode().isMine())
    {
      VNTag value;
      value.vboolean = true;
      group.createTag("tag", VN_TAG_BOOLEAN, value);
    }
    */
  }

  void onDestroyTagGroup(Node& node, TagGroup& group)
  {
    printf("Destroyed tag group %s(%u) in node %u (%s)\n",
           group.getName().c_str(),
	   group.getID(),
	   node.getID(),
	   node.getName().c_str());
  }

  void onSetName(Node& node, const std::string& name)
  {
    printf("Set name %s for node %u\n", name.c_str(), node.getID());
  }

  void onCreateVertex(GeometryNode& node, uint32 vertexID, const BaseVertex& vertex)
  {
    printf("Created vertex %u in node %u(%s)\n",
           vertexID,
	   node.getID(),
	   node.getName().c_str());

    BaseMesh mesh;
    node.getBaseMesh(mesh);
    printf("Base mesh has %u polygons and %u vertices\n", mesh.mPolygons.size(), mesh.mVertices.size());
  }

  void onChangeBaseVertex(GeometryNode& node, uint32 vertexID, const BaseVertex& vertex)
  {
    printf("Changed vertex %u in node %u(%s)\n",
           vertexID,
	   node.getID(),
	   node.getName().c_str());
  }

  void onDeleteVertex(GeometryNode& node, uint32 vertexID)
  {
    printf("Deleted vertex %u in node %u(%s)\n",
           vertexID,
	   node.getID(),
	   node.getName().c_str());
  }

  void onCreatePolygon(GeometryNode& node, uint32 polygonID, const BasePolygon& polygon)
  {
    printf("Created polygon %u in node %u(%s)\n",
           polygonID,
	   node.getID(),
	   node.getName().c_str());

    BaseMesh mesh;
    node.getBaseMesh(mesh);
    printf("Base mesh has %u polygons and %u vertices\n", mesh.mPolygons.size(), mesh.mVertices.size());
  }

  void onChangeBasePolygon(GeometryNode& node, uint32 polygonID, const BasePolygon& polygon)
  {
    printf("Changed polygon %u in node %u(%s)\n",
           polygonID,
	   node.getID(),
	   node.getName().c_str());
  }

  void onDeletePolygon(GeometryNode& node, uint32 polygonID)
  {
    printf("Deleted polygon %u in node %u(%s)\n",
           polygonID,
	   node.getID(),
	   node.getName().c_str());
  }

  void onCreateLayer(GeometryNode& node, GeometryLayer& layer)
  {
    printf("Created geometry layer %s(%u) of type %u in node %u (%s)\n",
           layer.getName().c_str(),
	   layer.getID(),
	   layer.getType(),
	   node.getID(),
	   node.getName().c_str());

    /*
    if (node.isMine())
      layer.setName("renamed_layer");
    */

    layer.addObserver(*this);
  }

  void onDestroyLayer(GeometryNode& node, GeometryLayer& layer)
  {
    printf("Destroyed geometry layer %s(%u) of in node %u (%s)\n",
           layer.getName().c_str(),
	   layer.getID(),
	   node.getID(),
	   node.getName().c_str());
  }

  void onSetSlot(GeometryLayer& layer, uint32 slotID, const void* data)
  {
    printf("Changed slot %u in layer %s(%u) of node %u (%s)\n",
           slotID,
	   layer.getName().c_str(),
	   layer.getID(),
	   layer.getNode().getID(),
	   layer.getNode().getName().c_str());
  }

  void onSetName(GeometryLayer& layer, const std::string& name)
  {
    printf("Changed name of layer %s(%u) to %s in node %u (%s)\n",
           layer.getName().c_str(),
	   layer.getID(),
	   name.c_str(),
	   layer.getNode().getID(),
	   layer.getNode().getName().c_str());
  }

  void onCreateTag(TagGroup& group, Tag& tag)
  {
    printf("Created tag %s in group %s(%u) of node %u (%s)\n",
           tag.getName().c_str(),
	   group.getName().c_str(),
	   group.getID(),
	   group.getNode().getID(),
	   group.getNode().getName().c_str());

    tag.addObserver(*this);

    /*
    tag.setName("renamed_tag");
    */
  }

  void onDestroyTag(TagGroup& group, Tag& tag)
  {
    printf("Destroyed tag %s in group %s(%u) of node %u (%s)\n",
           tag.getName().c_str(),
	   group.getName().c_str(),
	   group.getID(),
	   group.getNode().getID(),
	   group.getNode().getName().c_str());
  }

  void onSetName(TagGroup& group, const std::string& name)
  {
    printf("Changed name of group %s(%u) to %s of node %u (%s)\n",
	   group.getName().c_str(),
	   group.getID(),
	   name.c_str(),
	   group.getNode().getID(),
	   group.getNode().getName().c_str());
  }

  void onChange(Tag& tag)
  {
    printf("Changed something in tag %s in group %s of node %u (%s)\n",
           tag.getName().c_str(),
	   tag.getGroup().getName().c_str(),
	   tag.getGroup().getNode().getID(),
	   tag.getGroup().getNode().getName().c_str());
  }
};

int main(int argc, char** argv)
{
  std::string host;

  if (argc == 1)
    host = "localhost";
  else
    host = argv[1];

  Session* session = Session::create(host, "ample-linter", "secret");
  if (!session)
    return 1;

  Listener listener;
  session->addObserver(listener);

  while (session->getState() != Session::TERMINATED)
    Session::update(10000);
}

<|endoftext|>