<commit_before>/*
   Copyright 2011 StormMQ Limited

   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 "Memory/PoolTestSupport.h"
#include "debug_helper.h"

SUITE(Pool)
{
    TEST_FIXTURE(InitializedPoolFixture, callback_should_initialize_object)
    {
        test_type_t *p = (test_type_t *) amqp_allocate(&pool);
        CHECK_EQUAL('A', p->important_stuff[0]);
        for (unsigned i = 0; i < sizeof(p->important_stuff); i++)
        {
            CHECK_EQUAL('A' + (int) i, p->important_stuff[i]);
        }
        amqp_deallocate(&pool, p);
    }

#ifdef DISABLE_MEMORY_POOL
    TEST_FIXTURE(InitializedPoolFixture, verify_allocation_works_when_pool_disabled)
    {
        test_type_t *p, *q;
        p = (test_type_t *) amqp_allocate(&pool);
        q = (test_type_t *) amqp_allocate(&pool);
        amqp_deallocate(&pool, p);
        amqp_deallocate(&pool, q);
    }
#else
    TEST_FIXTURE(InitializedPoolFixture, first_allocate_from_pool_allocates_block)
    {
        CHECK_NULL(pool.block_list);

        amqp_memory_pool_t *p = (amqp_memory_pool_t *) amqp_allocate(&pool);
        CHECK_NOT_NULL(p);

        CHECK_NOT_NULL(pool.block_list);
        CHECK_NULL(pool.block_list->header.previous);
        CHECK_NULL(pool.block_list->header.next);

        amqp_deallocate(&pool, p);
    }

    TEST_FIXTURE(InitializedPoolFixture, allocate_from_pool)
    {
        test_type_t *p = (test_type_t *) amqp_allocate(&pool);

        CHECK_NOT_NULL(pool.block_list);
        CHECK_NULL(pool.block_list->header.previous);
        CHECK_NULL(pool.block_list->header.next);

        CHECK_EQUAL(0xfe, pool.block_list->header.mask.bytes[0]);
        CHECK_NOT_NULL(p);

        amqp_deallocate(&pool, p);
    }

    TEST_FIXTURE(InitializedPoolFixture, allocate_from_pool_increases_allocation_count)
    {
        int i;

        for (i = 0; i < LONG_BIT; i++)
        {
            allocate_from_pool();
            CHECK_EQUAL((unsigned long) (i + 1), pool.stats.outstanding_allocations);
            CHECK_EQUAL((unsigned long) (i + 1), pool.stats.total_allocation_calls);
        }
        while (i > 0)
        {
            i--;
            return_last_allocated_to_pool();
            CHECK_EQUAL((unsigned long) i, pool.stats.outstanding_allocations);
        }
        CHECK_EQUAL((unsigned long) LONG_BIT, pool.stats.total_allocation_calls);
    }

    TEST_FIXTURE(InitializedPoolFixture, allocations_should_be_reflected_in_mask)
    {
        allocate_from_pool(7);
        CHECK_EQUAL(0x80U, (unsigned) pool.block_list->header.mask.bytes[0]);

        allocate_from_pool(1);
        CHECK_EQUAL(0x00U, (unsigned) pool.block_list->header.mask.bytes[0]);
        CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[1]);

        allocate_from_pool(1);
        CHECK_EQUAL(0xfeU, (unsigned) pool.block_list->header.mask.bytes[1]);
        CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[2]);

        allocate_from_pool(6);
        CHECK_EQUAL(0x80U, (unsigned) pool.block_list->header.mask.bytes[1]);

        allocate_from_pool(1);
        CHECK_EQUAL(0x00U, (unsigned) pool.block_list->header.mask.bytes[1]);
        CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[2]);

        allocate_from_pool(1);
        CHECK_EQUAL(0xfeU, (unsigned) pool.block_list->header.mask.bytes[2]);
        CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[3]);

    }

    class BlockChainingTestFixture : public PoolFixture
    {
    public:
        BlockChainingTestFixture() { }
        ~BlockChainingTestFixture() { }

        void test()
        {
            allocate_from_pool(1);
            amqp_memory_block_t *first_block = pool.block_list;
            CHECK_NULL(pool.block_list->header.previous);
            CHECK_NULL(pool.block_list->header.next);

            allocate_from_pool(pool.allocations_per_block - 1);
            CHECK_EQUAL(first_block, pool.block_list);
            CHECK_NULL(pool.block_list->header.previous);
            CHECK_NULL(pool.block_list->header.next);

            allocate_from_pool(1);
            amqp_memory_block_t *second_block = pool.block_list;
            CHECK_EQUAL(first_block, pool.block_list->header.next);
            CHECK_NULL(pool.block_list->header.previous);
            CHECK_NULL(pool.block_list->header.next->header.next);
            CHECK_EQUAL(second_block, pool.block_list->header.next->header.previous);
        }
    };

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block)
    {
        initialize_pool();
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_256)
    {
        break_one();
        initialize_pool(256);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_512)
    {
        initialize_pool(512);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_768)
    {
        initialize_pool(768);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_1024)
    {
        initialize_pool(1024);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_1526)
    {
        initialize_pool(1526);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_2048)
    {
        initialize_pool(2048);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_4096)
    {
        initialize_pool(4096);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, free_allocation_in_block_should_result_in_block_removal_from_chain)
    {
        initialize_pool(256);

        CHECK_NULL(pool.block_list); // no blocks on the pool

        // allocate first block
        allocate_from_pool();
        amqp_memory_block_t *first_block = pool.block_list;

        // allocate remainder of slots in the first block
        allocate_from_pool(pool.allocations_per_block - 1);
        CHECK_EQUAL(first_block, pool.block_list);

        // allocate second block
        allocate_from_pool();
        amqp_memory_block_t *second_block = pool.block_list;
        CHECK(first_block != second_block);

        // allocate remainder of slots in the second block
        allocate_from_pool(pool.allocations_per_block - 1);
        CHECK_EQUAL(second_block, pool.block_list);

        // allocate another causing a third block to be allocated
        test_type_t *p = (test_type_t *) amqp_allocate(&pool);
        amqp_memory_block_t *third_block = pool.block_list;
        CHECK(second_block != third_block);

        CHECK_NULL(first_block->header.next);
        CHECK_EQUAL(second_block, first_block->header.previous);
        CHECK_EQUAL(first_block, second_block->header.next);
        CHECK_EQUAL(third_block, second_block->header.previous);
        CHECK_EQUAL(second_block, third_block->header.next);
        CHECK_NULL(third_block->header.previous);

        for (int i = 0; i < pool.allocations_per_block; i++)
        {
            return_last_allocated_to_pool(); // return last allocated by call to allocate_from_pool();
        }

        // verify that the second block has been removed from the block list
        // because all its allocations have been deallocated
        CHECK_EQUAL(third_block, pool.block_list);
        CHECK_NULL(third_block->header.previous);
        CHECK_EQUAL(first_block, third_block->header.next);
        CHECK_NULL(first_block->header.next);
        CHECK_EQUAL(third_block, first_block->header.previous);

        // now remove the last allocation from the pool causing the third block to be removed from the list.
        amqp_deallocate(&pool, p);

        CHECK_EQUAL(first_block, pool.block_list);
        CHECK_NULL(first_block->header.previous);
        CHECK_NULL(first_block->header.next);

        // deallocate everything from the first block
        for (int i = 0; i < pool.allocations_per_block; i++)
        {
            return_last_allocated_to_pool(); // return last allocated by call to allocate_from_pool();
        }

        CHECK_NULL(pool.block_list); // assert that there are no blocks left
    }
#endif

}
<commit_msg>Remove an unnecessary check that caused tests on 32-bit linux to fail.<commit_after>/*
   Copyright 2011 StormMQ Limited

   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 "Memory/PoolTestSupport.h"
#include "debug_helper.h"

SUITE(Pool)
{
    TEST_FIXTURE(InitializedPoolFixture, callback_should_initialize_object)
    {
        test_type_t *p = (test_type_t *) amqp_allocate(&pool);
        CHECK_EQUAL('A', p->important_stuff[0]);
        for (unsigned i = 0; i < sizeof(p->important_stuff); i++)
        {
            CHECK_EQUAL('A' + (int) i, p->important_stuff[i]);
        }
        amqp_deallocate(&pool, p);
    }

#ifdef DISABLE_MEMORY_POOL
    TEST_FIXTURE(InitializedPoolFixture, verify_allocation_works_when_pool_disabled)
    {
        test_type_t *p, *q;
        p = (test_type_t *) amqp_allocate(&pool);
        q = (test_type_t *) amqp_allocate(&pool);
        amqp_deallocate(&pool, p);
        amqp_deallocate(&pool, q);
    }
#else
    TEST_FIXTURE(InitializedPoolFixture, first_allocate_from_pool_allocates_block)
    {
        CHECK_NULL(pool.block_list);

        amqp_memory_pool_t *p = (amqp_memory_pool_t *) amqp_allocate(&pool);
        CHECK_NOT_NULL(p);

        CHECK_NOT_NULL(pool.block_list);
        CHECK_NULL(pool.block_list->header.previous);
        CHECK_NULL(pool.block_list->header.next);

        amqp_deallocate(&pool, p);
    }

    TEST_FIXTURE(InitializedPoolFixture, allocate_from_pool)
    {
        test_type_t *p = (test_type_t *) amqp_allocate(&pool);

        CHECK_NOT_NULL(pool.block_list);
        CHECK_NULL(pool.block_list->header.previous);
        CHECK_NULL(pool.block_list->header.next);

        CHECK_EQUAL(0xfe, pool.block_list->header.mask.bytes[0]);
        CHECK_NOT_NULL(p);

        amqp_deallocate(&pool, p);
    }

    TEST_FIXTURE(InitializedPoolFixture, allocate_from_pool_increases_allocation_count)
    {
        int i;

        for (i = 0; i < LONG_BIT; i++)
        {
            allocate_from_pool();
            CHECK_EQUAL((unsigned long) (i + 1), pool.stats.outstanding_allocations);
            CHECK_EQUAL((unsigned long) (i + 1), pool.stats.total_allocation_calls);
        }
        while (i > 0)
        {
            i--;
            return_last_allocated_to_pool();
            CHECK_EQUAL((unsigned long) i, pool.stats.outstanding_allocations);
        }
        CHECK_EQUAL((unsigned long) LONG_BIT, pool.stats.total_allocation_calls);
    }

    TEST_FIXTURE(InitializedPoolFixture, allocations_should_be_reflected_in_mask)
    {
        allocate_from_pool(1);
        CHECK_EQUAL(0xfeU, (unsigned) pool.block_list->header.mask.bytes[0]);

        allocate_from_pool(6);
        CHECK_EQUAL(0x80U, (unsigned) pool.block_list->header.mask.bytes[0]);

        allocate_from_pool(1);
        CHECK_EQUAL(0x00U, (unsigned) pool.block_list->header.mask.bytes[0]);
        CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[1]);

        allocate_from_pool(1);
        CHECK_EQUAL(0xfeU, (unsigned) pool.block_list->header.mask.bytes[1]);
        CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[2]);

        allocate_from_pool(6);
        CHECK_EQUAL(0x80U, (unsigned) pool.block_list->header.mask.bytes[1]);

        allocate_from_pool(1);
        CHECK_EQUAL(0x00U, (unsigned) pool.block_list->header.mask.bytes[1]);
        CHECK_EQUAL(0xffU, (unsigned) pool.block_list->header.mask.bytes[2]);

        allocate_from_pool(1);
        CHECK_EQUAL(0xfeU, (unsigned) pool.block_list->header.mask.bytes[2]);
    }

    class BlockChainingTestFixture : public PoolFixture
    {
    public:
        BlockChainingTestFixture() { }
        ~BlockChainingTestFixture() { }

        void test()
        {
            allocate_from_pool(1);
            amqp_memory_block_t *first_block = pool.block_list;
            CHECK_NULL(pool.block_list->header.previous);
            CHECK_NULL(pool.block_list->header.next);

            allocate_from_pool(pool.allocations_per_block - 1);
            CHECK_EQUAL(first_block, pool.block_list);
            CHECK_NULL(pool.block_list->header.previous);
            CHECK_NULL(pool.block_list->header.next);

            allocate_from_pool(1);
            amqp_memory_block_t *second_block = pool.block_list;
            CHECK_EQUAL(first_block, pool.block_list->header.next);
            CHECK_NULL(pool.block_list->header.previous);
            CHECK_NULL(pool.block_list->header.next->header.next);
            CHECK_EQUAL(second_block, pool.block_list->header.next->header.previous);
        }
    };

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block)
    {
        initialize_pool();
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_256)
    {
        break_one();
        initialize_pool(256);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_512)
    {
        initialize_pool(512);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_768)
    {
        initialize_pool(768);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_1024)
    {
        initialize_pool(1024);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_1526)
    {
        initialize_pool(1526);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_2048)
    {
        initialize_pool(2048);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, allocation_beyond_block_capacity_should_allocate_another_block_4096)
    {
        initialize_pool(4096);
        test();
    }

    TEST_FIXTURE(BlockChainingTestFixture, free_allocation_in_block_should_result_in_block_removal_from_chain)
    {
        initialize_pool(256);

        CHECK_NULL(pool.block_list); // no blocks on the pool

        // allocate first block
        allocate_from_pool();
        amqp_memory_block_t *first_block = pool.block_list;

        // allocate remainder of slots in the first block
        allocate_from_pool(pool.allocations_per_block - 1);
        CHECK_EQUAL(first_block, pool.block_list);

        // allocate second block
        allocate_from_pool();
        amqp_memory_block_t *second_block = pool.block_list;
        CHECK(first_block != second_block);

        // allocate remainder of slots in the second block
        allocate_from_pool(pool.allocations_per_block - 1);
        CHECK_EQUAL(second_block, pool.block_list);

        // allocate another causing a third block to be allocated
        test_type_t *p = (test_type_t *) amqp_allocate(&pool);
        amqp_memory_block_t *third_block = pool.block_list;
        CHECK(second_block != third_block);

        CHECK_NULL(first_block->header.next);
        CHECK_EQUAL(second_block, first_block->header.previous);
        CHECK_EQUAL(first_block, second_block->header.next);
        CHECK_EQUAL(third_block, second_block->header.previous);
        CHECK_EQUAL(second_block, third_block->header.next);
        CHECK_NULL(third_block->header.previous);

        for (int i = 0; i < pool.allocations_per_block; i++)
        {
            return_last_allocated_to_pool(); // return last allocated by call to allocate_from_pool();
        }

        // verify that the second block has been removed from the block list
        // because all its allocations have been deallocated
        CHECK_EQUAL(third_block, pool.block_list);
        CHECK_NULL(third_block->header.previous);
        CHECK_EQUAL(first_block, third_block->header.next);
        CHECK_NULL(first_block->header.next);
        CHECK_EQUAL(third_block, first_block->header.previous);

        // now remove the last allocation from the pool causing the third block to be removed from the list.
        amqp_deallocate(&pool, p);

        CHECK_EQUAL(first_block, pool.block_list);
        CHECK_NULL(first_block->header.previous);
        CHECK_NULL(first_block->header.next);

        // deallocate everything from the first block
        for (int i = 0; i < pool.allocations_per_block; i++)
        {
            return_last_allocated_to_pool(); // return last allocated by call to allocate_from_pool();
        }

        CHECK_NULL(pool.block_list); // assert that there are no blocks left
    }
#endif
}
<|endoftext|>


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

#include "net/base/connection_type_histograms.h"

#include "base/histogram.h"

namespace net {

// We're using a histogram as a group of counters.  We're only interested in
// the values of the counters.  Ignore the shape, average, and standard
// deviation of the histograms because they are meaningless.
//
// We use two groups of counters.  In the first group (counter1), each counter
// is a boolean (0 or 1) that indicates whether the user has seen a connection
// of that type during that session.  In the second group (counter2), each
// counter is the number of connections of that type the user has seen during
// that session.
void UpdateConnectionTypeHistograms(ConnectionType type) {
  static bool had_connection_type[NUM_OF_CONNECTION_TYPES];
  static LinearHistogram counter1(L"Net.HadConnectionType",
                                  1, NUM_OF_CONNECTION_TYPES - 1,
                                  NUM_OF_CONNECTION_TYPES);
  static LinearHistogram counter2(L"Net.ConnectionTypeCount",
                                  1, NUM_OF_CONNECTION_TYPES - 1,
                                  NUM_OF_CONNECTION_TYPES);

  if (type >= 0 && type < NUM_OF_CONNECTION_TYPES) {
    if (!had_connection_type[type]) {
      had_connection_type[type] = true;
      counter1.Add(type);
    }
  }
  counter2.Add(type);
}

}  // namespace net
<commit_msg>Push MD5 certificate histograms to UMA.<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/connection_type_histograms.h"

#include "base/histogram.h"

namespace net {

// We're using a histogram as a group of counters.  We're only interested in
// the values of the counters.  Ignore the shape, average, and standard
// deviation of the histograms because they are meaningless.
//
// We use two groups of counters.  In the first group (counter1), each counter
// is a boolean (0 or 1) that indicates whether the user has seen a connection
// of that type during that session.  In the second group (counter2), each
// counter is the number of connections of that type the user has seen during
// that session.
//
// Each histogram has an unused bucket at the end to allow seamless future
// expansion.
void UpdateConnectionTypeHistograms(ConnectionType type) {
  static bool had_connection_type[NUM_OF_CONNECTION_TYPES];
  static LinearHistogram counter1(L"Net.HadConnectionType",
                                  1, NUM_OF_CONNECTION_TYPES,
                                  NUM_OF_CONNECTION_TYPES + 1);
  static LinearHistogram counter2(L"Net.ConnectionTypeCount",
                                  1, NUM_OF_CONNECTION_TYPES,
                                  NUM_OF_CONNECTION_TYPES + 1);

  if (type >= 0 && type < NUM_OF_CONNECTION_TYPES) {
    if (!had_connection_type[type]) {
      had_connection_type[type] = true;
      counter1.SetFlags(kUmaTargetedHistogramFlag);
      counter1.Add(type);
    }
  }
  counter2.SetFlags(kUmaTargetedHistogramFlag);
  counter2.Add(type);
}

}  // namespace net
<|endoftext|>


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

#ifndef INCLUDED_WRITERFILTERDLLAPI_H
#include <WriterFilterDllApi.hxx>
#endif
#include <resourcemodel/WW8ResourceModel.hxx>
#include <boost/shared_ptr.hpp>

namespace writerfilter {
namespace dmapper
{
class PropertyMap;
/** Handler for sprms that contain a measure and a unit
    - Left indent of tables
    - Preferred width of tables
 */
class WRITERFILTER_DLLPRIVATE MeasureHandler : public Properties
{
    sal_Int32 m_nMeasureValue;
    sal_Int32 m_nUnit;
    sal_Int16 m_nRowHeightSizeType; //table row height type

public:
    MeasureHandler();
    virtual ~MeasureHandler();

    // Properties
    virtual void attribute(Id Name, Value & val);
    virtual void sprm(Sprm & sprm);

    sal_Int32 getMeasureValue() const;
    //at least tables can have automatic width
    bool isAutoWidth() const;

    sal_Int16 GetRowHeightSizeType() const { return m_nRowHeightSizeType;}
};
typedef boost::shared_ptr
    < MeasureHandler >  MeasureHandlerPtr;
}}

#endif //
<commit_msg>INTEGRATION: CWS changefileheader (1.4.20); FILE MERGED 2008/04/01 13:02:28 thb 1.4.20.2: #i85898# Stripping all external header guards 2008/03/28 15:53:00 rt 1.4.20.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: MeasureHandler.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef INCLUDED_MEASUREHANDLER_HXX
#define INCLUDED_MEASUREHANDLER_HXX

#include <WriterFilterDllApi.hxx>
#include <resourcemodel/WW8ResourceModel.hxx>
#include <boost/shared_ptr.hpp>

namespace writerfilter {
namespace dmapper
{
class PropertyMap;
/** Handler for sprms that contain a measure and a unit
    - Left indent of tables
    - Preferred width of tables
 */
class WRITERFILTER_DLLPRIVATE MeasureHandler : public Properties
{
    sal_Int32 m_nMeasureValue;
    sal_Int32 m_nUnit;
    sal_Int16 m_nRowHeightSizeType; //table row height type

public:
    MeasureHandler();
    virtual ~MeasureHandler();

    // Properties
    virtual void attribute(Id Name, Value & val);
    virtual void sprm(Sprm & sprm);

    sal_Int32 getMeasureValue() const;
    //at least tables can have automatic width
    bool isAutoWidth() const;

    sal_Int16 GetRowHeightSizeType() const { return m_nRowHeightSizeType;}
};
typedef boost::shared_ptr
    < MeasureHandler >  MeasureHandlerPtr;
}}

#endif //
<|endoftext|>


<commit_before>#include "OsiCplexSolverInterface.hpp"
#include <CoinMpsIO.hpp>
#include <cplex.h>
//#include <algorithm>

// default constructor
OsiCplexSolverInterface::OsiCplexSolverInterface(): OsiCpxSolverInterface() {
  CPXENVptr env = getEnvironmentPtr();
  // set parameter number of threads to 1, CPXPARAM_Threads
  CPXINT num_threads = 1;
  CPXINT status;
  // Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
  status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
  if (status) {
    std::cerr << "Cplex status error!" << std::endl;
    throw std::exception();
  }
}

// copy constructor
OsiCplexSolverInterface::OsiCplexSolverInterface(const OsiCplexSolverInterface & other):
  OsiCpxSolverInterface(other) {
  CPXENVptr env = getEnvironmentPtr();
  // set parameter number of threads to 1, CPXPARAM_Threads
  CPXINT num_threads = 1;
  CPXINT status;
  // Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
  status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
  if (status) {
    std::cerr << "Cplex status error!" << std::endl;
    throw std::exception();
  }
}

// copy assignment operator
OsiCplexSolverInterface & OsiCplexSolverInterface::operator=(const OsiCplexSolverInterface & rhs) {
  // copy rhs to this
  OsiCpxSolverInterface::operator=(rhs);
  CPXENVptr env = getEnvironmentPtr();
  // set parameter number of threads to 1, CPXPARAM_Threads
  CPXINT num_threads = 1;
  CPXINT status;
  // Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
  status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
  if (status) {
    std::cerr << "Cplex status error!" << std::endl;
    throw std::exception();
  }
  return *this;
}

// get conic constraints
void OsiCplexSolverInterface::getConicConstraint(int index,
                                                 OsiLorentzConeType & type,
                                                 int & numMembers,
                                                 int *& members) const {
  int ok = 0;
  // cplex status, 0 for success
  int status;
  // number of linear part nonzeros
  int linnz;
  int linsurplus = 0;
  // number of quadratic part nonzeros
  int qnz;
  numMembers = 0;
  CPXLPptr lp = getMutableLpPtr();
  CPXENVptr env = getMutableEnvironmentPtr();
  // detect array lengths
  status = CPXgetqconstr(env, lp, &linnz, &qnz, NULL, NULL,
                         NULL, NULL, 0, &linsurplus,
                         NULL, NULL, NULL, 0, &numMembers, index);
  if (status==0) {
    // means number of variables in cone is 0.
    return;
  }
  else if (status == CPXERR_NEGATIVE_SURPLUS) {
    // linear or quadratic cone size was not enough
    if (numMembers==0) {
      // cone size was enough, means no member in cone
      return;
    }
    else {
      // cone size is greater than 0
      numMembers = -numMembers;
    }
  }
  // allocate memory for quadratic part
  int * qrow = new int[numMembers];
  int * qcol = new int[numMembers];
  double * qval = new double[numMembers];
  int qsurplus;
  // call get constraints again with updated cone size
  status = CPXgetqconstr(env, lp, &linnz, &qnz, NULL, NULL,
                         NULL, NULL, 0, &linsurplus,
                         qrow, qcol, qval, numMembers, &qsurplus, index);
  if (status!=0 && status!=CPXERR_NEGATIVE_SURPLUS) {
    std::cerr << "Cplex status error!" << std::endl;
    throw std::exception();
  }
  if (qsurplus<0) {
    std::cerr << "This should not happen. Cplex cheated!" << std::endl;
    throw std::exception();
  }
  members = qcol;
  delete[] qrow;
  if (qval[0]==-1.0 && qval[1]==1.0) {
    type = OSI_QUAD;
  }
  else {
    std::cerr << "This part is not implemented yet!" << std::endl;
    throw std::exception();
  }
  delete[] qval;
}

// add conic constraint in lorentz cone form
void OsiCplexSolverInterface::addConicConstraint(OsiLorentzConeType type,
                                                 int numMembers,
                                               const int * members) {
  if (type==OSI_RQUAD) {
    std::cerr << "Rotated Cones are not implemented yet!" << std::endl;
    throw std::exception();
  }
  int status;
  CPXLPptr lp = getMutableLpPtr();
  CPXENVptr env = getEnvironmentPtr();
  double * qval = new double[numMembers];
  qval[0] = -1.0;
  std::fill_n(qval+1, numMembers-1, 1.0);
  status = CPXaddqconstr (env, lp, 0, numMembers,
                          0.0, 'L', NULL, NULL,
                          members, members, qval, NULL);
  if (status != 0) {
    std::cerr << "Cplex function is not successful." << std::endl;
    throw std::exception();
  }
  // leading variable is nonnegative
  double bound[] = {0.0};
  char lu[] = {'L'};
  status = CPXchgbds (env, lp, 1, members, lu, bound);
  if (status != 0) {
    std::cerr << "Cplex function is not successful." << std::endl;
    throw std::exception();
  }
}

// add conic constraint in |Ax-b| <= dx-h form
void OsiCplexSolverInterface::addConicConstraint(CoinPackedMatrix const * A,
                                                 CoinPackedVector const * b,
                                                 CoinPackedVector const * d,
                                                 double h) {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

void OsiCplexSolverInterface::removeConicConstraint(int index) {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

void OsiCplexSolverInterface::modifyConicConstraint(int index,
                                                    OsiLorentzConeType type,
                                                    int numMembers,
                                                    const int * members) {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

int OsiCplexSolverInterface::getNumCones() const {

  CPXLPptr lp = getMutableLpPtr();
  CPXENVptr env = getMutableEnvironmentPtr();
  int n = CPXgetnumqconstrs(env, lp);
  return n;
}

int OsiCplexSolverInterface::getConeSize(int i) const {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

OsiConeType OsiCplexSolverInterface::getConeType(int i) const {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

OsiLorentzConeType OsiCplexSolverInterface::getLorentzConeType(int i) const {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

// fills array of cone sizes.
void OsiCplexSolverInterface::getConeSize(int * size) const {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

// fills array of cone types.
void OsiCplexSolverInterface::getConeType(OsiConeType * type) const {
  int num_cones = getNumCones();
  for (int i=0; i<num_cones; ++i) {
    type[i] = getConeType(i);
  }
}

void OsiCplexSolverInterface::getConeType(OsiLorentzConeType * type) const {
  int num_cones = getNumCones();
  for (int i=0; i<num_cones; ++i) {
    type[i] = getLorentzConeType(i);
  }
}

OsiConicSolverInterface * OsiCplexSolverInterface::clone(bool copyData) const {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

OsiCplexSolverInterface::~OsiCplexSolverInterface() {
}

int OsiCplexSolverInterface::readMps(const char * filename,
                                     const char * extension) {
  OsiConicSolverInterface::readMps(filename, extension);
}

void OsiCplexSolverInterface::initialSolve() {
  //todo(aykut) I am not sure what switchToLp() does.
  switchToLP();
  CPXLPptr lp = getMutableLpPtr();
  CPXENVptr env = getEnvironmentPtr();
  double objoffset;
  double primalobjlimit;
  double dualobjlimit;
  if (messageHandler()->logLevel() == 0)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 0);
  else if (messageHandler()->logLevel() == 1)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 1);
  else if (messageHandler()->logLevel() > 1)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 2);
  getDblParam(OsiObjOffset, objoffset);
  getDblParam(OsiPrimalObjectiveLimit, primalobjlimit);
  getDblParam(OsiDualObjectiveLimit, dualobjlimit);
  if (getObjSense() == +1) {
    if (primalobjlimit < COIN_DBL_MAX)
      CPXsetdblparam(env, CPX_PARAM_OBJLLIM, primalobjlimit + objoffset);
    if (dualobjlimit > -COIN_DBL_MAX)
      CPXsetdblparam(env, CPX_PARAM_OBJULIM, dualobjlimit + objoffset);
  }
  else {
    if (primalobjlimit > -COIN_DBL_MAX)
      CPXsetdblparam(env, CPX_PARAM_OBJULIM, primalobjlimit + objoffset);
    if (dualobjlimit < COIN_DBL_MAX)
      CPXsetdblparam(env, CPX_PARAM_OBJLLIM, dualobjlimit + objoffset);
  }
  int status = CPXhybbaropt(env, lp, CPX_ALG_NONE);
  if (status!=0) {
    std::cerr << "Cplex did not return 0 status." << std::endl;
    throw std::exception();
  }
}

//-----------------------------------------------------------------------------
// resolve is same as initialSolve, no warm start capability.
void OsiCplexSolverInterface::resolve() {
  //todo(aykut) I am not sure what switchToLp() does.
  switchToLP();
  CPXLPptr lp = getMutableLpPtr();
  CPXENVptr env = getEnvironmentPtr();
  if (messageHandler()->logLevel() == 0)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 0);
  else if (messageHandler()->logLevel() == 1)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 1);
  else if (messageHandler()->logLevel() > 1)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 2);
  int status = CPXhybbaropt(env, lp, CPX_ALG_NONE);
  if (status!=0) {
    std::cerr << "Cplex did not return 0 status." << std::endl;
    throw std::exception();
  }
}
<commit_msg>Adding rotated lorentz cones implemented.<commit_after>#include "OsiCplexSolverInterface.hpp"
#include <CoinMpsIO.hpp>
#include <cplex.h>
//#include <algorithm>

// todo(aykut)
// error check routine. Copied from OsiCpxSolverInterface.
// I am not sure whether this is a license violation. This
// may be removed/replaced in future.
// I would not experince any problem if this function was not static
// in OsiCpxSolverInterface.cpp. Since it is, I have to copy it here
// and create redundancy.
static inline void
checkCPXerror(int err, std::string cpxfuncname, std::string osimethod) {
  if(err != 0) {
    char s[100];
    sprintf( s, "%s returned error %d", cpxfuncname.c_str(), err );
#ifdef DEBUG
    std::cerr << "ERROR: " << s << " (" << osimethod << " in OsiCpxSolverInterface)" << std::endl;
#endif
    throw CoinError(s, osimethod.c_str(), "OsiCplexSolverInterface");
  }
}

// default constructor
OsiCplexSolverInterface::OsiCplexSolverInterface(): OsiCpxSolverInterface() {
  CPXENVptr env = getEnvironmentPtr();
  // set parameter number of threads to 1, CPXPARAM_Threads
  CPXINT num_threads = 1;
  CPXINT status;
  // Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
  status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
  if (status) {
    std::cerr << "Cplex status error!" << std::endl;
    throw std::exception();
  }
}

// copy constructor
OsiCplexSolverInterface::OsiCplexSolverInterface(const OsiCplexSolverInterface & other):
  OsiCpxSolverInterface(other) {
  CPXENVptr env = getEnvironmentPtr();
  // set parameter number of threads to 1, CPXPARAM_Threads
  CPXINT num_threads = 1;
  CPXINT status;
  // Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
  status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
  if (status) {
    std::cerr << "Cplex status error!" << std::endl;
    throw std::exception();
  }
}

// copy assignment operator
OsiCplexSolverInterface & OsiCplexSolverInterface::operator=(const OsiCplexSolverInterface & rhs) {
  // copy rhs to this
  OsiCpxSolverInterface::operator=(rhs);
  CPXENVptr env = getEnvironmentPtr();
  // set parameter number of threads to 1, CPXPARAM_Threads
  CPXINT num_threads = 1;
  CPXINT status;
  // Name prior to V12.6.0 is CPX_PARAM_THREADS, we assume V12.6.0 or later
  status = CPXsetintparam(env, CPXPARAM_Threads, num_threads);
  if (status) {
    std::cerr << "Cplex status error!" << std::endl;
    throw std::exception();
  }
  return *this;
}

// get conic constraints
void OsiCplexSolverInterface::getConicConstraint(int index,
                                                 OsiLorentzConeType & type,
                                                 int & numMembers,
                                                 int *& members) const {
  int ok = 0;
  // cplex status, 0 for success
  int status;
  // number of linear part nonzeros
  int linnz;
  int linsurplus = 0;
  // number of quadratic part nonzeros
  int qnz;
  numMembers = 0;
  CPXLPptr lp = getMutableLpPtr();
  CPXENVptr env = getMutableEnvironmentPtr();
  // detect array lengths
  status = CPXgetqconstr(env, lp, &linnz, &qnz, NULL, NULL,
                         NULL, NULL, 0, &linsurplus,
                         NULL, NULL, NULL, 0, &numMembers, index);
  if (status==0) {
    // means number of variables in cone is 0.
    return;
  }
  else if (status == CPXERR_NEGATIVE_SURPLUS) {
    // linear or quadratic cone size was not enough
    if (numMembers==0) {
      // cone size was enough, means no member in cone
      return;
    }
    else {
      // cone size is greater than 0
      numMembers = -numMembers;
    }
  }
  // allocate memory for quadratic part
  int * qrow = new int[numMembers];
  int * qcol = new int[numMembers];
  double * qval = new double[numMembers];
  int qsurplus;
  // call get constraints again with updated cone size
  status = CPXgetqconstr(env, lp, &linnz, &qnz, NULL, NULL,
                         NULL, NULL, 0, &linsurplus,
                         qrow, qcol, qval, numMembers, &qsurplus, index);
  if (status!=0 && status!=CPXERR_NEGATIVE_SURPLUS) {
    std::cerr << "Cplex status error!" << std::endl;
    throw std::exception();
  }
  if (qsurplus<0) {
    std::cerr << "This should not happen. Cplex cheated!" << std::endl;
    throw std::exception();
  }
  members = qcol;
  delete[] qrow;
  if (qval[0]==-1.0 && qval[1]==1.0) {
    type = OSI_QUAD;
  }
  else {
    std::cerr << "This part is not implemented yet!" << std::endl;
    throw std::exception();
  }
  delete[] qval;
}

// add conic constraint in lorentz cone form
void OsiCplexSolverInterface::addConicConstraint(OsiLorentzConeType type,
                                                 int numMembers,
                                               const int * members) {
  int status;
  CPXLPptr lp = getMutableLpPtr();
  CPXENVptr env = getEnvironmentPtr();
  if (type==OSI_QUAD) {
    double * qval = new double[numMembers];
    qval[0] = -1.0;
    std::fill_n(qval+1, numMembers-1, 1.0);
    status = CPXaddqconstr (env, lp, 0, numMembers,
                            0.0, 'L', NULL, NULL,
                            members, members, qval, NULL);
    delete[] qval;
    checkCPXerror(status, std::string("CPXaddqconstr"),
                  std::string("addConicConstraint"));
    // leading variable is nonnegative
    double bound[] = {0.0};
    char lu[] = {'L'};
    status = CPXchgbds (env, lp, 1, members, lu, bound);
    checkCPXerror(status, std::string("CPXchgbds"),
                  std::string("addConicConstraint"));
  }
  else if (type==OSI_RQUAD) {
    double * qval = new double[numMembers-1];
    qval[0] = -2.0;
    std::fill_n(qval+1, numMembers-1, 1.0);
    int * members2 = new int[numMembers-1];
    members2[0] = members[0];
    std::copy(members+2, members+numMembers, members2+1);
    status = CPXaddqconstr (env, lp, 0, numMembers-1,
                            0.0, 'L', NULL, NULL,
                            members+1, members2, qval, NULL);
    delete[] qval;
    delete[] members2;
    checkCPXerror(status, std::string("CPXaddqconstr"),
                  std::string("addConicConstraint"));
    // leading variable is nonnegative
    double bound[] = {0.0};
    char lu[] = {'L'};
    // update lower bound to 0 for leading variables
    status = CPXchgbds (env, lp, 1, members, lu, bound);
    checkCPXerror(status, std::string("CPXchgbds"),
                  std::string("addConicConstraint"));
    status = CPXchgbds (env, lp, 1, members+1, lu, bound);
    checkCPXerror(status, std::string("CPXchgbds"),
                  std::string("addConicConstraint"));
  }
  else {
    std::cerr << "Unknown cone type!" << std::endl;
    throw std::exception();
  }
}

// add conic constraint in |Ax-b| <= dx-h form
void OsiCplexSolverInterface::addConicConstraint(CoinPackedMatrix const * A,
                                                 CoinPackedVector const * b,
                                                 CoinPackedVector const * d,
                                                 double h) {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

void OsiCplexSolverInterface::removeConicConstraint(int index) {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

void OsiCplexSolverInterface::modifyConicConstraint(int index,
                                                    OsiLorentzConeType type,
                                                    int numMembers,
                                                    const int * members) {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

int OsiCplexSolverInterface::getNumCones() const {

  CPXLPptr lp = getMutableLpPtr();
  CPXENVptr env = getMutableEnvironmentPtr();
  int n = CPXgetnumqconstrs(env, lp);
  return n;
}

int OsiCplexSolverInterface::getConeSize(int i) const {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

OsiConeType OsiCplexSolverInterface::getConeType(int i) const {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

OsiLorentzConeType OsiCplexSolverInterface::getLorentzConeType(int i) const {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

// fills array of cone sizes.
void OsiCplexSolverInterface::getConeSize(int * size) const {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

// fills array of cone types.
void OsiCplexSolverInterface::getConeType(OsiConeType * type) const {
  int num_cones = getNumCones();
  for (int i=0; i<num_cones; ++i) {
    type[i] = getConeType(i);
  }
}

void OsiCplexSolverInterface::getConeType(OsiLorentzConeType * type) const {
  int num_cones = getNumCones();
  for (int i=0; i<num_cones; ++i) {
    type[i] = getLorentzConeType(i);
  }
}

OsiConicSolverInterface * OsiCplexSolverInterface::clone(bool copyData) const {
  std::cerr << "Not implemented yet!" << std::cerr;
  throw std::exception();
}

OsiCplexSolverInterface::~OsiCplexSolverInterface() {
}

int OsiCplexSolverInterface::readMps(const char * filename,
                                     const char * extension) {
  OsiConicSolverInterface::readMps(filename, extension);
}

void OsiCplexSolverInterface::initialSolve() {
  //todo(aykut) I am not sure what switchToLp() does.
  switchToLP();
  CPXLPptr lp = getMutableLpPtr();
  CPXENVptr env = getEnvironmentPtr();
  double objoffset;
  double primalobjlimit;
  double dualobjlimit;
  if (messageHandler()->logLevel() == 0)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 0);
  else if (messageHandler()->logLevel() == 1)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 1);
  else if (messageHandler()->logLevel() > 1)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 2);
  getDblParam(OsiObjOffset, objoffset);
  getDblParam(OsiPrimalObjectiveLimit, primalobjlimit);
  getDblParam(OsiDualObjectiveLimit, dualobjlimit);
  if (getObjSense() == +1) {
    if (primalobjlimit < COIN_DBL_MAX)
      CPXsetdblparam(env, CPX_PARAM_OBJLLIM, primalobjlimit + objoffset);
    if (dualobjlimit > -COIN_DBL_MAX)
      CPXsetdblparam(env, CPX_PARAM_OBJULIM, dualobjlimit + objoffset);
  }
  else {
    if (primalobjlimit > -COIN_DBL_MAX)
      CPXsetdblparam(env, CPX_PARAM_OBJULIM, primalobjlimit + objoffset);
    if (dualobjlimit < COIN_DBL_MAX)
      CPXsetdblparam(env, CPX_PARAM_OBJLLIM, dualobjlimit + objoffset);
  }
  int status = CPXhybbaropt(env, lp, CPX_ALG_NONE);
  if (status!=0) {
    std::cerr << "Cplex did not return 0 status." << std::endl;
    throw std::exception();
  }
}

//-----------------------------------------------------------------------------
// resolve is same as initialSolve, no warm start capability.
void OsiCplexSolverInterface::resolve() {
  //todo(aykut) I am not sure what switchToLp() does.
  switchToLP();
  CPXLPptr lp = getMutableLpPtr();
  CPXENVptr env = getEnvironmentPtr();
  if (messageHandler()->logLevel() == 0)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 0);
  else if (messageHandler()->logLevel() == 1)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 1);
  else if (messageHandler()->logLevel() > 1)
    CPXsetintparam(env, CPX_PARAM_SIMDISPLAY, 2);
  int status = CPXhybbaropt(env, lp, CPX_ALG_NONE);
  if (status!=0) {
    std::cerr << "Cplex did not return 0 status." << std::endl;
    throw std::exception();
  }
}
<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   HydraulicOverCenterValve.hpp
//! @author Mikael Axin <mikael.axin@liu.se>
//! @date   2010-01-13
//!
//! @brief Contains a hydraulic over center valve with first order dynamics
//!
//$Id$

#ifndef HYDRAULICOVERCENTERVALVE_HPP_INCLUDED
#define HYDRAULICOVERCENTERVALVE_HPP_INCLUDED

#include "ComponentEssentials.h"
#include "ComponentUtilities.h"

namespace hopsan {

    //!
    //! @brief
    //! @ingroup HydraulicComponents
    //!
    class HydraulicOverCenterValve : public ComponentQ
    {
    private:
        // Member variables
        TurbulentFlowFunction mTurb;
        ValveHysteresis mHyst;
        FirstOrderTransferFunction mFilterLP;
        double mPrevX0, mCs, mCf;

        // Port and node data pointers
        Port *mpP1, *mpP2, *mpPControl;
        double *mpP1_p, *mpP1_q, *mpP1_c, *mpP1_Zc, *mpP2_p, *mpP2_q, *mpP2_c, *mpP2_Zc,
               *mpPControl_p, *mpPControl_c;
        double *mpPref, *mpPh, *mpArat, *mpXv;

        // Constants
        double mTao, mKcs, mKcf, mPnom, mQnom;

    public:
        static Component *Creator()
        {
            return new HydraulicOverCenterValve();
        }

        void configure()
        {
            mpP1 = addPowerPort("P1", "NodeHydraulic");
            mpP2 = addPowerPort("P2", "NodeHydraulic");
            mpPControl = addPowerPort("P_CONTROL", "NodeHydraulic");

            addInputVariable("p_ref", "Reference Opening Pressure", "Pa", 2000000, &mpPref);
            addInputVariable("p_h", "Hysteresis Width", "Pa", 500000, &mpPh);
            addInputVariable("a_ratio", "Area ratio", "-", 5.0, &mpArat);

            addOutputVariable("xv", "Equivalent spool position", "", &mpXv);

            addConstant("tao", "Time Constant of Spool", "s", 0.01, mTao);
            addConstant("k_cs", "Steady State Characteristic due to Spring", "(m^3/s)/Pa", 0.00000001, mKcs);
            addConstant("k_cf", "Steady State Characteristic due to Flow Forces", "(m^3/s)/Pa", 0.00000001, mKcf);
            addConstant("q_nom", "Flow with Fully Open Valve and pressure drop p_nom", "m^3/s", 0.001, mQnom);
            addConstant("p_nom", "Nominal pressure drop", "Pa", 7e6, mPnom);
        }

        void initialize()
        {
            mpP1_p = getSafeNodeDataPtr(mpP1, NodeHydraulic::Pressure);
            mpP1_q = getSafeNodeDataPtr(mpP1, NodeHydraulic::Flow);
            mpP1_c = getSafeNodeDataPtr(mpP1, NodeHydraulic::WaveVariable);
            mpP1_Zc = getSafeNodeDataPtr(mpP1, NodeHydraulic::CharImpedance);

            mpP2_p = getSafeNodeDataPtr(mpP2, NodeHydraulic::Pressure);
            mpP2_q = getSafeNodeDataPtr(mpP2, NodeHydraulic::Flow);
            mpP2_c = getSafeNodeDataPtr(mpP2, NodeHydraulic::WaveVariable);
            mpP2_Zc = getSafeNodeDataPtr(mpP2, NodeHydraulic::CharImpedance);

            mpPControl_p = getSafeNodeDataPtr(mpPControl, NodeHydraulic::Pressure);
            mpPControl_c = getSafeNodeDataPtr(mpPControl, NodeHydraulic::WaveVariable);

            mPrevX0 = 0.0;
            mCs = sqrt(mPnom)/mKcs;
            mCf = 1/(mKcf * sqrt(mPnom));
            double x0max = mQnom/sqrt(mPnom);

            double wCutoff = 1 / mTao;
            double num[2] = {1.0, 0.0};
            double den[2] = {1.0, 1.0/wCutoff};
            mFilterLP.initialize(mTimestep, num, den, mPrevX0, mPrevX0, 0, x0max);
        }

        void simulateOneTimestep()
        {
            //Declare local variables
            double p1, q1, c1, Zc1, p2, q2, c2, Zc2, p_control, c_control;
            double b1, xs, xh, xsh, pref, ph, arat;
            bool cav = false;

            //Get variable values from nodes
            p1 = (*mpP1_p);
            q1 = (*mpP1_q);
            c1 = (*mpP1_c);
            Zc1 = (*mpP1_Zc);
            p2 = (*mpP2_p);
            q2 = (*mpP2_q);
            c2 = (*mpP2_c);
            Zc2 = (*mpP2_Zc);
            p_control = (*mpPControl_p);
            c_control = (*mpPControl_c);
            pref = (*mpPref);
            ph = (*mpPh);
            arat = (*mpArat);

            /* Equations */

            b1 = mCs+mCf*(p1-p2);                               // Help Variable, equals sqrt(p1-p2)/Kctot
            xs = (p1 / arat - pref + p_control) / b1;           // Spool position calculation
            xh = ph/b1;
            xsh = mHyst.getValue(xs, xh, mPrevX0);              // Hysteresis
            double x0 = mFilterLP.update(xsh);                  // Dynamics
            mTurb.setFlowCoefficient(x0);                       // Turbulent Flow Calculation
            q2 = mTurb.getFlow(c1, c2, Zc1, Zc2);
            q1 = -q2;

            p1 = c1 + Zc1 * q1;                                 // Pressure Calulation
            p2 = c2 + Zc2 * q2;
            p_control = c_control;

            p_control = std::max(0.0, p_control);

            if (p1 < 0.0)                                       // Check for cavitation
            {
                c1 = 0.0;
                Zc1 = 0.0;
                cav = true;
            }
            if (p2 < 0.0)
            {
                c2 = 0.0;
                Zc2 = 0.0;
                cav = true;
            }
            if (cav)                                            // Cavitatiaon, redo calculations with new c and Zc
            {
                q2 = mTurb.getFlow(c1, c2, Zc1, Zc2);
                q1 = -q2;
                p1 = c1 + Zc1 * q1;
                p2 = c2 + Zc2 * q2;
                if (p1 < 0.0) { p1 = 0.0; }
                if (p2 < 0.0) { p2 = 0.0; }
            }

            mPrevX0 = x0;

            (*mpP1_p) = p1;                                    // Write new values to nodes
            (*mpP1_q) = q1;
            (*mpP2_p) = p2;
            (*mpP2_q) = q2;
            (*mpPControl_p) = p_control;
            (*mpXv) = x0;
        }
    };
}

#endif // HYDRAULICPRESSURECONTROLLEDVALVE_HPP_INCLUDED

<commit_msg>Corrected area ratio parameter for over-center valve component. Resolves #1388.<commit_after>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   HydraulicOverCenterValve.hpp
//! @author Mikael Axin <mikael.axin@liu.se>
//! @date   2010-01-13
//!
//! @brief Contains a hydraulic over center valve with first order dynamics
//!
//$Id$

#ifndef HYDRAULICOVERCENTERVALVE_HPP_INCLUDED
#define HYDRAULICOVERCENTERVALVE_HPP_INCLUDED

#include "ComponentEssentials.h"
#include "ComponentUtilities.h"

namespace hopsan {

    //!
    //! @brief
    //! @ingroup HydraulicComponents
    //!
    class HydraulicOverCenterValve : public ComponentQ
    {
    private:
        // Member variables
        TurbulentFlowFunction mTurb;
        ValveHysteresis mHyst;
        FirstOrderTransferFunction mFilterLP;
        double mPrevX0, mCs, mCf;

        // Port and node data pointers
        Port *mpP1, *mpP2, *mpPControl;
        double *mpP1_p, *mpP1_q, *mpP1_c, *mpP1_Zc, *mpP2_p, *mpP2_q, *mpP2_c, *mpP2_Zc,
               *mpPControl_p, *mpPControl_c;
        double *mpPref, *mpPh, *mpArat, *mpXv;

        // Constants
        double mTao, mKcs, mKcf, mPnom, mQnom;

    public:
        static Component *Creator()
        {
            return new HydraulicOverCenterValve();
        }

        void configure()
        {
            mpP1 = addPowerPort("P1", "NodeHydraulic");
            mpP2 = addPowerPort("P2", "NodeHydraulic");
            mpPControl = addPowerPort("P_CONTROL", "NodeHydraulic");

            addInputVariable("p_ref", "Reference Opening Pressure", "Pa", 2000000, &mpPref);
            addInputVariable("p_h", "Hysteresis Width", "Pa", 500000, &mpPh);
            addInputVariable("a_ratio", "Area ratio", "-", 5.0, &mpArat);

            addOutputVariable("xv", "Equivalent spool position", "", &mpXv);

            addConstant("tao", "Time Constant of Spool", "s", 0.01, mTao);
            addConstant("k_cs", "Steady State Characteristic due to Spring", "(m^3/s)/Pa", 0.00000001, mKcs);
            addConstant("k_cf", "Steady State Characteristic due to Flow Forces", "(m^3/s)/Pa", 0.00000001, mKcf);
            addConstant("q_nom", "Flow with Fully Open Valve and pressure drop p_nom", "m^3/s", 0.001, mQnom);
            addConstant("p_nom", "Nominal pressure drop", "Pa", 7e6, mPnom);
        }

        void initialize()
        {
            mpP1_p = getSafeNodeDataPtr(mpP1, NodeHydraulic::Pressure);
            mpP1_q = getSafeNodeDataPtr(mpP1, NodeHydraulic::Flow);
            mpP1_c = getSafeNodeDataPtr(mpP1, NodeHydraulic::WaveVariable);
            mpP1_Zc = getSafeNodeDataPtr(mpP1, NodeHydraulic::CharImpedance);

            mpP2_p = getSafeNodeDataPtr(mpP2, NodeHydraulic::Pressure);
            mpP2_q = getSafeNodeDataPtr(mpP2, NodeHydraulic::Flow);
            mpP2_c = getSafeNodeDataPtr(mpP2, NodeHydraulic::WaveVariable);
            mpP2_Zc = getSafeNodeDataPtr(mpP2, NodeHydraulic::CharImpedance);

            mpPControl_p = getSafeNodeDataPtr(mpPControl, NodeHydraulic::Pressure);
            mpPControl_c = getSafeNodeDataPtr(mpPControl, NodeHydraulic::WaveVariable);

            mPrevX0 = 0.0;
            mCs = sqrt(mPnom)/mKcs;
            mCf = 1/(mKcf * sqrt(mPnom));
            double x0max = mQnom/sqrt(mPnom);

            double wCutoff = 1 / mTao;
            double num[2] = {1.0, 0.0};
            double den[2] = {1.0, 1.0/wCutoff};
            mFilterLP.initialize(mTimestep, num, den, mPrevX0, mPrevX0, 0, x0max);
        }

        void simulateOneTimestep()
        {
            //Declare local variables
            double p1, q1, c1, Zc1, p2, q2, c2, Zc2, p_control, c_control;
            double b1, xs, xh, xsh, pref, ph, arat;
            bool cav = false;

            //Get variable values from nodes
            p1 = (*mpP1_p);
            q1 = (*mpP1_q);
            c1 = (*mpP1_c);
            Zc1 = (*mpP1_Zc);
            p2 = (*mpP2_p);
            q2 = (*mpP2_q);
            c2 = (*mpP2_c);
            Zc2 = (*mpP2_Zc);
            p_control = (*mpPControl_p);
            c_control = (*mpPControl_c);
            pref = (*mpPref);
            ph = (*mpPh);
            arat = (*mpArat);

            /* Equations */

            b1 = mCs+mCf*(p1-p2);                               // Help Variable, equals sqrt(p1-p2)/Kctot
            xs = (p1 - pref + arat * p_control) / b1;           // Spool position calculation
            xh = ph/b1;
            xsh = mHyst.getValue(xs, xh, mPrevX0);              // Hysteresis
            double x0 = mFilterLP.update(xsh);                  // Dynamics
            mTurb.setFlowCoefficient(x0);                       // Turbulent Flow Calculation
            q2 = mTurb.getFlow(c1, c2, Zc1, Zc2);
            q1 = -q2;

            p1 = c1 + Zc1 * q1;                                 // Pressure Calulation
            p2 = c2 + Zc2 * q2;
            p_control = c_control;

            p_control = std::max(0.0, p_control);

            if (p1 < 0.0)                                       // Check for cavitation
            {
                c1 = 0.0;
                Zc1 = 0.0;
                cav = true;
            }
            if (p2 < 0.0)
            {
                c2 = 0.0;
                Zc2 = 0.0;
                cav = true;
            }
            if (cav)                                            // Cavitatiaon, redo calculations with new c and Zc
            {
                q2 = mTurb.getFlow(c1, c2, Zc1, Zc2);
                q1 = -q2;
                p1 = c1 + Zc1 * q1;
                p2 = c2 + Zc2 * q2;
                if (p1 < 0.0) { p1 = 0.0; }
                if (p2 < 0.0) { p2 = 0.0; }
            }

            mPrevX0 = x0;

            (*mpP1_p) = p1;                                    // Write new values to nodes
            (*mpP1_q) = q1;
            (*mpP2_p) = p2;
            (*mpP2_q) = q2;
            (*mpPControl_p) = p_control;
            (*mpXv) = x0;
        }
    };
}

#endif // HYDRAULICPRESSURECONTROLLEDVALVE_HPP_INCLUDED

<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group 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.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/

#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkKnownDriverIds.inl"

using namespace vk;

namespace vkt
{
namespace api
{
namespace
{

enum TestType
{
	TEST_TYPE_DRIVER_ID_MATCH			= 0,
	TEST_TYPE_NAME_IS_NOT_EMPTY,
	TEST_TYPE_NAME_ZERO_TERMINATED,
	TEST_TYPE_INFO_ZERO_TERMINATED,
	TEST_TYPE_VERSION,
};

static const VkConformanceVersionKHR knownConformanceVersions[] =
{
	makeConformanceVersion(1, 2, 7, 0),
	makeConformanceVersion(1, 2, 6, 2),
	makeConformanceVersion(1, 2, 6, 1),
	makeConformanceVersion(1, 2, 6, 0),
	makeConformanceVersion(1, 2, 5, 2),
	makeConformanceVersion(1, 2, 5, 1),
	makeConformanceVersion(1, 2, 5, 0),
	makeConformanceVersion(1, 2, 4, 1),
	makeConformanceVersion(1, 2, 4, 0),
	makeConformanceVersion(1, 2, 3, 3),
	makeConformanceVersion(1, 2, 3, 2),
	makeConformanceVersion(1, 2, 3, 1),
	makeConformanceVersion(1, 2, 3, 0),
	makeConformanceVersion(1, 2, 2, 2),
	makeConformanceVersion(1, 2, 2, 1),
	makeConformanceVersion(1, 2, 2, 0),
	makeConformanceVersion(1, 2, 1, 2),
	makeConformanceVersion(1, 2, 1, 1),
	makeConformanceVersion(1, 2, 1, 0),
	makeConformanceVersion(1, 2, 0, 2),
	makeConformanceVersion(1, 2, 0, 1),
	makeConformanceVersion(1, 2, 0, 0),
	makeConformanceVersion(1, 1, 6, 3),
	makeConformanceVersion(1, 1, 6, 2),
	makeConformanceVersion(1, 1, 6, 1),
	makeConformanceVersion(1, 1, 6, 0),
	makeConformanceVersion(1, 1, 5, 2),
	makeConformanceVersion(1, 1, 5, 1),
	makeConformanceVersion(1, 1, 5, 0),
	makeConformanceVersion(1, 1, 4, 3),
	makeConformanceVersion(1, 1, 4, 2),
	makeConformanceVersion(1, 1, 4, 1),
	makeConformanceVersion(1, 1, 4, 0),
	makeConformanceVersion(1, 1, 3, 3),
	makeConformanceVersion(1, 1, 3, 2),
	makeConformanceVersion(1, 1, 3, 1),
	makeConformanceVersion(1, 1, 3, 0),
};

DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
	return deStrnlen(str, maxSize) < maxSize;
}

DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)
{
	return ((a.major == b.major)		&&
			(a.minor == b.minor)		&&
			(a.subminor == b.subminor)	&&
			(a.patch == b.patch));
}

void checkSupport (Context& context, const TestType config)
{
	DE_UNREF(config);
	context.requireDeviceFunctionality("VK_KHR_driver_properties");
}

void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	for (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++)
	{
		if (deviceDriverProperties.driverID == driverIds[driverNdx].id)
			return;
	}

	TCU_FAIL("Driver ID did not match any known driver");
}

void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (deviceDriverProperties.driverName[0] == 0)
		TCU_FAIL("Driver name is empty");
}

void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
		TCU_FAIL("Driver name is not a null-terminated string");
}

void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
		TCU_FAIL("Driver info is not a null-terminated string");
}

void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)
{
	const deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion);
	const deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion);

	if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||
		(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&
		 deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))
	{
		TCU_FAIL("Wrong driver conformance version (older than used API version)");
	}

	for (const VkConformanceVersionKHR* pConformanceVersion  = knownConformanceVersions;
										pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
									  ++pConformanceVersion)
	{
		if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
			return;
	}

	TCU_FAIL("Wrong driver conformance version (not known)");
}

tcu::TestStatus testQueryProperties (Context& context, const TestType testType)
{
	// Query the driver properties
	const VkPhysicalDevice				physDevice			= context.getPhysicalDevice();
	const int							memsetPattern		= 0xaa;
	VkPhysicalDeviceProperties2			deviceProperties2;
	VkPhysicalDeviceDriverProperties	deviceDriverProperties;

	deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
	deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
	deviceDriverProperties.pNext = DE_NULL;

	deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
	deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
	deviceProperties2.pNext = &deviceDriverProperties;

	context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);

	// Verify the returned values
	switch (testType)
	{
		case TEST_TYPE_DRIVER_ID_MATCH:			testDriverMatch			(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_IS_NOT_EMPTY:		testNameIsNotEmpty		(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_ZERO_TERMINATED:	testNameZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_INFO_ZERO_TERMINATED:	testInfoZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_VERSION:					testVersion				(deviceDriverProperties, context.getUsedApiVersion());	break;
		default:								TCU_THROW(InternalError, "Unknown test type specified");
	}

	return tcu::TestStatus::pass("Pass");
}

void createTestCases (tcu::TestCaseGroup* group)
{
	addFunctionCase(group, "driver_id_match",		"Check driverID is supported",					checkSupport,	testQueryProperties,	TEST_TYPE_DRIVER_ID_MATCH);
	addFunctionCase(group, "name_is_not_empty",		"Check name field is not empty",				checkSupport,	testQueryProperties,	TEST_TYPE_NAME_IS_NOT_EMPTY);
	addFunctionCase(group, "name_zero_terminated",	"Check name field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_NAME_ZERO_TERMINATED);
	addFunctionCase(group, "info_zero_terminated",	"Check info field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_INFO_ZERO_TERMINATED);
	addFunctionCase(group, "conformance_version",	"Check conformanceVersion reported by driver",	checkSupport,	testQueryProperties,	TEST_TYPE_VERSION);
}

} // anonymous

tcu::TestCaseGroup*	createDriverPropertiesTests(tcu::TestContext& testCtx)
{
	return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}

} // api
} // vkt
<commit_msg>Allow Vulkan CTS 1.2.7.1<commit_after>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group 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.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/

#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkKnownDriverIds.inl"

using namespace vk;

namespace vkt
{
namespace api
{
namespace
{

enum TestType
{
	TEST_TYPE_DRIVER_ID_MATCH			= 0,
	TEST_TYPE_NAME_IS_NOT_EMPTY,
	TEST_TYPE_NAME_ZERO_TERMINATED,
	TEST_TYPE_INFO_ZERO_TERMINATED,
	TEST_TYPE_VERSION,
};

static const VkConformanceVersionKHR knownConformanceVersions[] =
{
	makeConformanceVersion(1, 2, 7, 1),
	makeConformanceVersion(1, 2, 7, 0),
	makeConformanceVersion(1, 2, 6, 2),
	makeConformanceVersion(1, 2, 6, 1),
	makeConformanceVersion(1, 2, 6, 0),
	makeConformanceVersion(1, 2, 5, 2),
	makeConformanceVersion(1, 2, 5, 1),
	makeConformanceVersion(1, 2, 5, 0),
	makeConformanceVersion(1, 2, 4, 1),
	makeConformanceVersion(1, 2, 4, 0),
	makeConformanceVersion(1, 2, 3, 3),
	makeConformanceVersion(1, 2, 3, 2),
	makeConformanceVersion(1, 2, 3, 1),
	makeConformanceVersion(1, 2, 3, 0),
	makeConformanceVersion(1, 2, 2, 2),
	makeConformanceVersion(1, 2, 2, 1),
	makeConformanceVersion(1, 2, 2, 0),
	makeConformanceVersion(1, 2, 1, 2),
	makeConformanceVersion(1, 2, 1, 1),
	makeConformanceVersion(1, 2, 1, 0),
	makeConformanceVersion(1, 2, 0, 2),
	makeConformanceVersion(1, 2, 0, 1),
	makeConformanceVersion(1, 2, 0, 0),
	makeConformanceVersion(1, 1, 6, 3),
	makeConformanceVersion(1, 1, 6, 2),
	makeConformanceVersion(1, 1, 6, 1),
	makeConformanceVersion(1, 1, 6, 0),
	makeConformanceVersion(1, 1, 5, 2),
	makeConformanceVersion(1, 1, 5, 1),
	makeConformanceVersion(1, 1, 5, 0),
	makeConformanceVersion(1, 1, 4, 3),
	makeConformanceVersion(1, 1, 4, 2),
	makeConformanceVersion(1, 1, 4, 1),
	makeConformanceVersion(1, 1, 4, 0),
	makeConformanceVersion(1, 1, 3, 3),
	makeConformanceVersion(1, 1, 3, 2),
	makeConformanceVersion(1, 1, 3, 1),
	makeConformanceVersion(1, 1, 3, 0),
};

DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
	return deStrnlen(str, maxSize) < maxSize;
}

DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)
{
	return ((a.major == b.major)		&&
			(a.minor == b.minor)		&&
			(a.subminor == b.subminor)	&&
			(a.patch == b.patch));
}

void checkSupport (Context& context, const TestType config)
{
	DE_UNREF(config);
	context.requireDeviceFunctionality("VK_KHR_driver_properties");
}

void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	for (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++)
	{
		if (deviceDriverProperties.driverID == driverIds[driverNdx].id)
			return;
	}

	TCU_FAIL("Driver ID did not match any known driver");
}

void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (deviceDriverProperties.driverName[0] == 0)
		TCU_FAIL("Driver name is empty");
}

void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
		TCU_FAIL("Driver name is not a null-terminated string");
}

void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
		TCU_FAIL("Driver info is not a null-terminated string");
}

void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)
{
	const deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion);
	const deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion);

	if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||
		(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&
		 deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))
	{
		TCU_FAIL("Wrong driver conformance version (older than used API version)");
	}

	for (const VkConformanceVersionKHR* pConformanceVersion  = knownConformanceVersions;
										pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
									  ++pConformanceVersion)
	{
		if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
			return;
	}

	TCU_FAIL("Wrong driver conformance version (not known)");
}

tcu::TestStatus testQueryProperties (Context& context, const TestType testType)
{
	// Query the driver properties
	const VkPhysicalDevice				physDevice			= context.getPhysicalDevice();
	const int							memsetPattern		= 0xaa;
	VkPhysicalDeviceProperties2			deviceProperties2;
	VkPhysicalDeviceDriverProperties	deviceDriverProperties;

	deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
	deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
	deviceDriverProperties.pNext = DE_NULL;

	deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
	deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
	deviceProperties2.pNext = &deviceDriverProperties;

	context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);

	// Verify the returned values
	switch (testType)
	{
		case TEST_TYPE_DRIVER_ID_MATCH:			testDriverMatch			(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_IS_NOT_EMPTY:		testNameIsNotEmpty		(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_ZERO_TERMINATED:	testNameZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_INFO_ZERO_TERMINATED:	testInfoZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_VERSION:					testVersion				(deviceDriverProperties, context.getUsedApiVersion());	break;
		default:								TCU_THROW(InternalError, "Unknown test type specified");
	}

	return tcu::TestStatus::pass("Pass");
}

void createTestCases (tcu::TestCaseGroup* group)
{
	addFunctionCase(group, "driver_id_match",		"Check driverID is supported",					checkSupport,	testQueryProperties,	TEST_TYPE_DRIVER_ID_MATCH);
	addFunctionCase(group, "name_is_not_empty",		"Check name field is not empty",				checkSupport,	testQueryProperties,	TEST_TYPE_NAME_IS_NOT_EMPTY);
	addFunctionCase(group, "name_zero_terminated",	"Check name field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_NAME_ZERO_TERMINATED);
	addFunctionCase(group, "info_zero_terminated",	"Check info field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_INFO_ZERO_TERMINATED);
	addFunctionCase(group, "conformance_version",	"Check conformanceVersion reported by driver",	checkSupport,	testQueryProperties,	TEST_TYPE_VERSION);
}

} // anonymous

tcu::TestCaseGroup*	createDriverPropertiesTests(tcu::TestContext& testCtx)
{
	return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}

} // api
} // vkt
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#ifndef FLUSSPFERD_XML_MISC_NODES_HPP
#define FLUSSPFERD_XML_MISC_NODES_HPP

#include "node.hpp"

namespace xml_plugin {

FLUSSPFERD_CLASS_DESCRIPTION(
    notation,
    (base, node)
    (constructible, false)
    (full_name, "xml.Notation")
    (constructor_name, "Notation")
    /*(properties,
      ("publicId", getter, getPublicId)
      ("systemId", getter, getSystemId)
    )*/
)
{
public:
  typedef arabica_notation wrapped_type;

  notation(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
    : base_type(proto,node, map),
      impl_(node)
  { }

  // Property getters/setters
  //string_type getPublicId() { return impl_.getPublicId(); }
  //string_type getSystemId() { return impl_.getSystemId(); }

  // Methods

protected:
  wrapped_type impl_;
};

FLUSSPFERD_CLASS_DESCRIPTION(
    entity,
    (base, node)
    (constructible, false)
    (full_name, "xml.Entity")
    (constructor_name, "Entity")
    (properties,
      //("publicId", getter, getPublicId)
      //("systemId", getter, getSystemId)
      //("notationName", getter, getNotationName)
    )
)
{
public:
  typedef arabica_entity wrapped_type;

  entity(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
    : base_type(proto,node, map),
      impl_(node)
  { }

  // Property getters/setters
  //string_type getPublicId() { return impl_.getPublicId(); }
  //string_type getSystemId() { return impl_.getSystemId(); }
  //string_type getNotationName() { return impl_.getNotationName(); }

  // Methods

protected:
  wrapped_type impl_;
};

FLUSSPFERD_CLASS_DESCRIPTION(
    entity_ref,
    (base, node)
    (constructible, false)
    (full_name, "xml.EntityReference")
    (constructor_name, "EntityReference")
)
{
public:
  typedef arabica_entity_ref wrapped_type;

  entity_ref(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
    : base_type(proto,node, map)
  { }
  // No methods or properties on this class
};

FLUSSPFERD_CLASS_DESCRIPTION(
    processing_instruction,
    (base, node)
    (constructible, false)
    (full_name, "xml.ProcessingInstruction")
    (constructor_name, "ProcessingInstruction")
    (properties,
      ("target", getter, getTarget)
      ("data", getter_setter, (getData, setData))
    )
)
{
public:
  typedef arabica_pi wrapped_type;

  processing_instruction(flusspferd::object const &proto,
                         wrapped_type const &node, weak_node_map map)
    : base_type(proto,node, map),
      impl_(node)
  { }

  // Property getters/setters
  string_type getTarget() { return impl_.getTarget(); }
  string_type getData() { return impl_.getData(); }
  void setData(string_type s) { impl_.setData(s); }

  // Methods

protected:
  wrapped_type impl_;
};

} // namespace xml_plugin

#endif

<commit_msg>xml_arabica: fixed issue with empty properties.<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#ifndef FLUSSPFERD_XML_MISC_NODES_HPP
#define FLUSSPFERD_XML_MISC_NODES_HPP

#include "node.hpp"

namespace xml_plugin {

FLUSSPFERD_CLASS_DESCRIPTION(
    notation,
    (base, node)
    (constructible, false)
    (full_name, "xml.Notation")
    (constructor_name, "Notation")
    /*(properties,
      ("publicId", getter, getPublicId)
      ("systemId", getter, getSystemId)
    )*/
)
{
public:
  typedef arabica_notation wrapped_type;

  notation(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
    : base_type(proto,node, map),
      impl_(node)
  { }

  // Property getters/setters
  //string_type getPublicId() { return impl_.getPublicId(); }
  //string_type getSystemId() { return impl_.getSystemId(); }

  // Methods

protected:
  wrapped_type impl_;
};

FLUSSPFERD_CLASS_DESCRIPTION(
    entity,
    (base, node)
    (constructible, false)
    (full_name, "xml.Entity")
    (constructor_name, "Entity")
    /*
    (properties,
      //("publicId", getter, getPublicId)
      //("systemId", getter, getSystemId)
      //("notationName", getter, getNotationName)
    )
    */
)
{
public:
  typedef arabica_entity wrapped_type;

  entity(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
    : base_type(proto,node, map),
      impl_(node)
  { }

  // Property getters/setters
  //string_type getPublicId() { return impl_.getPublicId(); }
  //string_type getSystemId() { return impl_.getSystemId(); }
  //string_type getNotationName() { return impl_.getNotationName(); }

  // Methods

protected:
  wrapped_type impl_;
};

FLUSSPFERD_CLASS_DESCRIPTION(
    entity_ref,
    (base, node)
    (constructible, false)
    (full_name, "xml.EntityReference")
    (constructor_name, "EntityReference")
)
{
public:
  typedef arabica_entity_ref wrapped_type;

  entity_ref(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map)
    : base_type(proto,node, map)
  { }
  // No methods or properties on this class
};

FLUSSPFERD_CLASS_DESCRIPTION(
    processing_instruction,
    (base, node)
    (constructible, false)
    (full_name, "xml.ProcessingInstruction")
    (constructor_name, "ProcessingInstruction")
    (properties,
      ("target", getter, getTarget)
      ("data", getter_setter, (getData, setData))
    )
)
{
public:
  typedef arabica_pi wrapped_type;

  processing_instruction(flusspferd::object const &proto,
                         wrapped_type const &node, weak_node_map map)
    : base_type(proto,node, map),
      impl_(node)
  { }

  // Property getters/setters
  string_type getTarget() { return impl_.getTarget(); }
  string_type getData() { return impl_.getData(); }
  void setData(string_type s) { impl_.setData(s); }

  // Methods

protected:
  wrapped_type impl_;
};

} // namespace xml_plugin

#endif

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// FunctionDef.cpp
// Executable function definitions
//
// File is under the MIT license; see LICENSE for details
//------------------------------------------------------------------------------
#include "slang/codegen/FunctionDef.h"

#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>

#include "slang/codegen/CodeGenerator.h"
#include "slang/mir/Instr.h"

namespace slang {

using namespace mir;

FunctionDef::FunctionDef(const CodeGenerator& codegen, string_view name, llvm::Type* returnType,
                         span<const ParamDef> params) :
    returnType(returnType),
    name(name), params(params) {

    SmallVectorSized<llvm::Type*, 8> types;
    for (auto& param : params)
        types.append(param.nativeType);

    if (!returnType)
        returnType = llvm::Type::getVoidTy(codegen.getContext());

    auto funcType =
        llvm::FunctionType::get(returnType, llvm::ArrayRef<llvm::Type*>(types.begin(), types.end()),
                                /* isVarArg */ false);

    nativeFunc =
        llvm::Function::Create(funcType, llvm::Function::ExternalLinkage,
                               llvm::StringRef(name.data(), name.length()), codegen.getModule());
}

FunctionDef FunctionDef::getSystemFunc(CodeGenerator& codegen, SysCallKind kind) {
    auto& ctx = codegen.getContext();
    auto voidType = llvm::Type::getVoidTy(ctx);
    auto boolType = llvm::Type::getInt1Ty(ctx);
    auto int8Type = llvm::Type::getInt8Ty(ctx);
    auto int32Type = llvm::Type::getInt32Ty(ctx);

    SmallVectorSized<ParamDef, 8> params;
    switch (kind) {
        case SysCallKind::printChar:
            params.append({ int8Type });
            break;
        case SysCallKind::printInt:
            params.append({ codegen.getGenericIntPtrType() });
            params.append({ int8Type });
            params.append({ int32Type });
            params.append({ boolType });
            break;
        default:
            THROW_UNREACHABLE;
    }

    return FunctionDef(codegen, toString(kind), voidType, params.copy(codegen));
}

} // namespace slang<commit_msg>Remove obsolete FunctionDef.cpp file<commit_after><|endoftext|>


<commit_before>//
// PROJECT:         Aspia
// FILE:            console/about_dialog.cc
// LICENSE:         GNU General Public License 3
// PROGRAMMERS:     Dmitry Chapyshev (dmitry@aspia.ru)
//

#include "console/about_dialog.h"

#include <QAbstractButton>
#include <QDesktopServices>

#include "version.h"

namespace aspia {

namespace {

const char kGplLink[] = "https://www.gnu.org/licenses/gpl.html";
const char kGplTranslationLink[] = "http://www.gnu.org/licenses/translations.html";
const char kHomeLink[] = "https://aspia.org";
const char kGitHubLink[] = "https://github.com/dchapyshev/aspia";
const char kDonateLink[] = "https://aspia.org/donate";

const char* kDevelopers[] = { "Dmitry Chapyshev (dmitry@aspia.ru)" };

const char* kTranslators[] =
{
    "Dmitry Chapyshev (Russian)",
    "Mark Jansen (Dutch)"
};

const char* kThirdParty[] =
{
    "Qt Framework © 2015 The Qt Company Ltd., GNU General Public License 3.0",
    "libvpx © 2010, The WebM Project authors, BSD 3-Clause License",
    "libyuv © 2011 The LibYuv Project Authors, BSD 3-Clause License",
    "libsodium © 2013-2017 Frank Denis, ISC License",
    "protobuf © 2014 Google Inc., BSD 3-Clause License",
    "zlib-ng © 1995-2013 Jean-loup Gailly and Mark Adler, Zlib License",
    "FatCow Icons © 2009-2014 FatCow Web Hosting, Creative Commons Attribution 3.0 License",
    "Fugue Icons © 2013 Yusuke Kamiyamane, Creative Commons Attribution 3.0 License"
};

QString createList(const QString& title, const char* array[], size_t array_size)
{
    if (!array_size)
        return QString();

    QString list;

    for (size_t i = 0; i < array_size; ++i)
    {
        list.append(QString("• %1").arg(array[i]));
        if (i + 1 != array_size)
            list.append(QLatin1String("
"));
    }

    return QString("%1
%2").arg(title).arg(list);
}

} // namespace

AboutDialog::AboutDialog(QWidget* parent)
    : QDialog(parent)
{
    ui.setupUi(this);

    ui.label_version->setText(tr("Version: %1").arg(QLatin1String(ASPIA_VERSION_STRING)));

    QString license =
        QString("%1
%2
%3")
        .arg(tr("Aspia is free software released under GNU General Public License 3."))
        .arg(tr("You can get a copy of license here:"))
        .arg(kGplLink);

    QString license_translation =
        QString("%1
%2")
        .arg(tr("You can also get a translation of GNU GPL license here:"))
        .arg(kGplTranslationLink);

    QString links =
        QString("%1
%2 %3
%4 %5")
        .arg(tr("Links:"))
        .arg(tr("Home page:")).arg(kHomeLink)
        .arg(tr("GitHub page:")).arg(kGitHubLink);

    QString developers =
        createList(tr("Developers:"), kDevelopers, _countof(kDevelopers));
    QString translators =
        createList(tr("Translators:"), kTranslators, _countof(kTranslators));
    QString third_party =
        createList(tr("Third-party components:"), kThirdParty, _countof(kThirdParty));

    QString html;

    html += "";
    html += "
" + license + "
";
    html += "
" + license_translation + "
";
    html += "
" + links + "
";
    html += "
" + developers + "
";
    html += "
" + translators + "
";
    html += "
" + third_party + "
";
    html += "";

    ui.text_edit->setHtml(html);

    connect(ui.push_button_donate, &QPushButton::pressed, [this]()
    {
        QDesktopServices::openUrl(QUrl(kDonateLink));
    });

    connect(ui.push_button_close, &QPushButton::pressed, this, &AboutDialog::close);
}

AboutDialog::~AboutDialog() = default;

} // namespace aspia
<commit_msg>- https instead http.<commit_after>//
// PROJECT:         Aspia
// FILE:            console/about_dialog.cc
// LICENSE:         GNU General Public License 3
// PROGRAMMERS:     Dmitry Chapyshev (dmitry@aspia.ru)
//

#include "console/about_dialog.h"

#include <QAbstractButton>
#include <QDesktopServices>

#include "version.h"

namespace aspia {

namespace {

const char kGplLink[] = "https://www.gnu.org/licenses/gpl.html";
const char kGplTranslationLink[] = "https://www.gnu.org/licenses/translations.html";
const char kHomeLink[] = "https://aspia.org";
const char kGitHubLink[] = "https://github.com/dchapyshev/aspia";
const char kDonateLink[] = "https://aspia.org/donate";

const char* kDevelopers[] = { "Dmitry Chapyshev (dmitry@aspia.ru)" };

const char* kTranslators[] =
{
    "Dmitry Chapyshev (Russian)",
    "Mark Jansen (Dutch)"
};

const char* kThirdParty[] =
{
    "Qt Framework © 2015 The Qt Company Ltd., GNU General Public License 3.0",
    "libvpx © 2010, The WebM Project authors, BSD 3-Clause License",
    "libyuv © 2011 The LibYuv Project Authors, BSD 3-Clause License",
    "libsodium © 2013-2017 Frank Denis, ISC License",
    "protobuf © 2014 Google Inc., BSD 3-Clause License",
    "zlib-ng © 1995-2013 Jean-loup Gailly and Mark Adler, Zlib License",
    "FatCow Icons © 2009-2014 FatCow Web Hosting, Creative Commons Attribution 3.0 License",
    "Fugue Icons © 2013 Yusuke Kamiyamane, Creative Commons Attribution 3.0 License"
};

QString createList(const QString& title, const char* array[], size_t array_size)
{
    if (!array_size)
        return QString();

    QString list;

    for (size_t i = 0; i < array_size; ++i)
    {
        list.append(QString("• %1").arg(array[i]));
        if (i + 1 != array_size)
            list.append(QLatin1String("
"));
    }

    return QString("%1
%2").arg(title).arg(list);
}

} // namespace

AboutDialog::AboutDialog(QWidget* parent)
    : QDialog(parent)
{
    ui.setupUi(this);

    ui.label_version->setText(tr("Version: %1").arg(QLatin1String(ASPIA_VERSION_STRING)));

    QString license =
        QString("%1
%2
%3")
        .arg(tr("Aspia is free software released under GNU General Public License 3."))
        .arg(tr("You can get a copy of license here:"))
        .arg(kGplLink);

    QString license_translation =
        QString("%1
%2")
        .arg(tr("You can also get a translation of GNU GPL license here:"))
        .arg(kGplTranslationLink);

    QString links =
        QString("%1
%2 %3
%4 %5")
        .arg(tr("Links:"))
        .arg(tr("Home page:")).arg(kHomeLink)
        .arg(tr("GitHub page:")).arg(kGitHubLink);

    QString developers =
        createList(tr("Developers:"), kDevelopers, _countof(kDevelopers));
    QString translators =
        createList(tr("Translators:"), kTranslators, _countof(kTranslators));
    QString third_party =
        createList(tr("Third-party components:"), kThirdParty, _countof(kThirdParty));

    QString html;

    html += "";
    html += "
" + license + "
";
    html += "
" + license_translation + "
";
    html += "
" + links + "
";
    html += "
" + developers + "
";
    html += "
" + translators + "
";
    html += "
" + third_party + "
";
    html += "";

    ui.text_edit->setHtml(html);

    connect(ui.push_button_donate, &QPushButton::pressed, [this]()
    {
        QDesktopServices::openUrl(QUrl(kDonateLink));
    });

    connect(ui.push_button_close, &QPushButton::pressed, this, &AboutDialog::close);
}

AboutDialog::~AboutDialog() = default;

} // namespace aspia
<|endoftext|>