<commit_before>/*
 * Copyright (c) 2013 Immo Software
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * o Neither the name of the copyright holder nor the names of its contributors may
 *   be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "argon/argon.h"
#include "kernel_tests.h"
#include "mbed.h"

//------------------------------------------------------------------------------
// Definitions
//------------------------------------------------------------------------------

#define TEST_CASE_CLASS TestMutex1

//------------------------------------------------------------------------------
// Prototypes
//------------------------------------------------------------------------------

void main_thread(void * arg);
void x_thread(void * arg);
void y_thread(void * arg);

class Foo
{
public:

    void my_entry() //void * param)
    {
        while (1)
        {
            printf("hi from Foo!\n");
            Ar::Thread::sleep(1000);
        }
    }
};

//------------------------------------------------------------------------------
// Variables
//------------------------------------------------------------------------------

#if !defined(__ICCARM__)
Ar::ThreadWithStack<512> g_mainThread("main", main_thread, 0, 56);
#endif

TEST_CASE_CLASS g_testCase;

Ar::ThreadWithStack<512> g_xThread("x", x_thread, 0, 130);
Ar::ThreadWithStack<512> g_yThread("y", y_thread, 0, 120);

Ar::Thread * g_fpThread1;
Ar::Thread * g_fpThread2;
Ar::TypedChannel<float> g_fchan("f");

Ar::TypedChannel<int> g_chan("c");

Ar::Thread g_fooThread;

Ar::Thread * g_dyn;

//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------

#if defined(__MICROLIB)
#pragma weak __aeabi_assert
extern "C" void __aeabi_assert(const char *s, const char *f, int l)
{
    Ar::_halt();
}
#endif

void x_thread(void * arg)
{
    Ar::Thread * self = Ar::Thread::getCurrent();
    const char * myName = self->getName();
    ar_status_t status;

    while (1)
    {
        printf("[%d:%s] receiving on channel\n", us_ticker_read(), myName);
        int foo = g_chan.receive();
        printf("[%d:%s] received from channel (foo=%d)\n", us_ticker_read(), myName, foo);

        printf("[%d:%s] sleeping a bit\n", us_ticker_read(), myName);
        Ar::Thread::sleep(1000);

        printf("[%d:%s] receiving on channel\n", us_ticker_read(), myName);
        foo = g_chan.receive();
        printf("[%d:%s] received from channel (foo=%d)\n", us_ticker_read(), myName, foo);

        printf("[%d:%s] receiving on channel (will timeout)\n", us_ticker_read(), myName);
        status = g_chan.receive(foo, 500);
        if (status != kArTimeoutError)
        {
            printf("[%d:%s] receiving didn't timeout!\n", us_ticker_read(), myName);
        }
        else
        {
            printf("[%d:%s] receiving timed out successfully\n", us_ticker_read(), myName);
        }

        printf("[%d:%s] sleeping a bit\n", us_ticker_read(), myName);
        Ar::Thread::sleep(4000);
    }
}

void y_thread(void * arg)
{
    Ar::Thread * self = Ar::Thread::getCurrent();
    const char * myName = self->getName();
    ar_status_t status;

    while (1)
    {
        printf("[%d:%s] sending to channel\n", us_ticker_read(), myName);
        g_chan.send(128);
        printf("[%d:%s] sent to channel\n", us_ticker_read(), myName);

        printf("[%d:%s] sending to channel\n", us_ticker_read(), myName);
        g_chan.send(256);
        printf("[%d:%s] sent to channel\n", us_ticker_read(), myName);

        printf("[%d:%s] sleeping a bit\n", us_ticker_read(), myName);
        Ar::Thread::sleep(2000);

        printf("[%d:%s] sending on channel (will timeout)\n", us_ticker_read(), myName);
        status = g_chan.send(1, 2);
        if (status != kArTimeoutError)
        {
            printf("[%d:%s] sending didn't timeout!\n", us_ticker_read(), myName);
        }
        else
        {
            printf("[%d:%s] sending timed out successfully\n", us_ticker_read(), myName);
        }
    }
}

#define ADCR_VDD                (65535.0f)    /*! Maximum value when use 16b resolution */
#define V_BG                    (1000.0f)     /*! BANDGAP voltage in mV (trim to 1.0V) */
#define V_TEMP25                (716.0f)      /*! Typical VTEMP25 in mV */
#define M                       (1620.0f)     /*! Typical slope: (mV x 1000)/oC */
#define STANDARD_TEMP           (25.0f)

static float adcrTemp25 = 0;             /*! Calibrated ADCR_TEMP25 */
static float adcr100m = 0;

void get_vdd()
{
    // Enable bandgap.
    HW_PMC_REGSC(PMC_BASE).B.BGBE = 1;

    AnalogIn bandgap(ADC0_BANDGAP);

    // Get VDD value measured in mV: VDD = (ADCR_VDD x V_BG) / ADCR_BG
    float vdd = ADCR_VDD * V_BG / (float)bandgap.read_u16();
    printf("vdd=%.3f mV\n", vdd);

    // Calibrate ADCR_TEMP25: ADCR_TEMP25 = ADCR_VDD x V_TEMP25 / VDD
    adcrTemp25 = ADCR_VDD * V_TEMP25 / vdd;

    // ADCR_100M = ADCR_VDD x M x 100 / VDD
    adcr100m = (ADCR_VDD * M) / (vdd * 10);

    // Disable bandgap.
    HW_PMC_REGSC(PMC_BASE).B.BGBE = 0;
}

void fp1_thread(void * arg)
{
    get_vdd();
    AnalogIn adc(ADC0_TEMP);

    while (1)
    {
//         float v = adc.read();

        // Temperature = 25 - (ADCR_T - ADCR_TEMP25) * 100 / ADCR_100M
        float currentTemperature = (STANDARD_TEMP - ((float)adc.read_u16() - adcrTemp25) * 100.0f / adcr100m);

        currentTemperature >> g_fchan;
    }
}

void fp2_thread(void * arg)
{
    while (1)
    {
        float v;

        v <<= g_fchan;

        printf("temp=%.3f\n", v);

        Ar::Thread::sleep(1000);
    }
}

void dyn_test(void * arg)
{
    printf("hi from dyn_test\n");
    printf("__cplusplus = '%d'\n", __cplusplus);
}

void main_thread(void * arg)
{
    Ar::Thread * self = Ar::Thread::getCurrent();
    const char * myName = self->getName();

    printf("[%d:%s] Main thread is running\r\n", us_ticker_read(), myName);

//     while (1)
//     {
//         printf("hi\n");
//         Ar::Thread::sleep(1000);
//     }

//     g_testCase.init();
//     g_testCase.run();

    Foo * foo = new Foo;
    g_fooThread.init("foo", foo, &Foo::my_entry, NULL, 512, 120);

    g_dyn = new Ar::Thread("dyn", dyn_test, 0, 512, 120);

    g_fpThread1 = new Ar::Thread("fp1", fp1_thread, 0, 1024, 100);

    g_fpThread2 = new Ar::Thread("fp2", fp2_thread, 0, 1024, 100);

    printf("[%d:%s] goodbye!\r\n", us_ticker_read(), myName);
}

int main(void)
{
    us_ticker_init();

    printf("Running test...\r\n");

#if 0
    printf("sizeof(Thread)=%d\r\n", sizeof(Ar::Thread));
    printf("sizeof(Channel)=%d\r\n", sizeof(Ar::Channel));
    printf("sizeof(Semaphore)=%d\r\n", sizeof(Ar::Semaphore));
    printf("sizeof(Mutex)=%d\r\n", sizeof(Ar::Mutex));
    printf("sizeof(Queue)=%d\r\n", sizeof(Ar::Queue));
    printf("sizeof(Timer)=%d\r\n", sizeof(Ar::Timer));
#endif

#if defined(__ICCARM__)
    main_thread(0);
    Ar::Thread::getCurrent()->suspend();
#else
//     g_mainThread.init("main", main_thread, 0, 56);
//     g_mainThread.resume();
    ar_kernel_run();
    Ar::_halt();
#endif

    return 0;
}

//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<commit_msg>basic_test sends/receives avg temp via nRF.<commit_after>/*
 * Copyright (c) 2013 Immo Software
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * o Neither the name of the copyright holder nor the names of its contributors may
 *   be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "argon/argon.h"
#include "kernel_tests.h"
#include "mbed.h"
#include "drivers/nrf/nrf.h"

//------------------------------------------------------------------------------
// Definitions
//------------------------------------------------------------------------------

#define TEST_CASE_CLASS TestMutex1

#if TARGET_K22F
#define ROLE_TRANSMITTER 0
#define ROLE_RECEIVER 1
#else
#define ROLE_TRANSMITTER 1
#define ROLE_RECEIVER 0
#endif

enum {
    kRadioAddress = 0xdeadbeef
};

#define ADCR_VDD                (65535.0f)    /*! Maximum value when use 16b resolution */
#define V_BG                    (1000.0f)     /*! BANDGAP voltage in mV (trim to 1.0V) */
#define V_TEMP25                (716.0f)      /*! Typical VTEMP25 in mV */
#define M                       (1620.0f)     /*! Typical slope: (mV x 1000)/oC */
#define STANDARD_TEMP           (25.0f)

//------------------------------------------------------------------------------
// Prototypes
//------------------------------------------------------------------------------

void main_thread(void * arg);
void x_thread(void * arg);
void y_thread(void * arg);
void rf_thread(void * arg);

class Foo
{
public:

    void my_entry() //void * param)
    {
        while (1)
        {
            printf("hi from Foo!\n");
            Ar::Thread::sleep(1000);
        }
    }
};

//------------------------------------------------------------------------------
// Variables
//------------------------------------------------------------------------------

#if !defined(__ICCARM__)
Ar::ThreadWithStack<512> g_mainThread("main", main_thread, 0, 56);
#endif

// TEST_CASE_CLASS g_testCase;

// Ar::ThreadWithStack<512> g_xThread("x", x_thread, 0, 130);
// Ar::ThreadWithStack<512> g_yThread("y", y_thread, 0, 120);

Ar::Thread * g_fpThread1;
Ar::Thread * g_fpThread2;
Ar::TypedChannel<float> g_fchan("f");
Ar::TypedChannel<float> g_avgTempChan("avgtemp");

Ar::TypedChannel<int> g_chan("c");

Ar::Thread g_fooThread;

// Ar::Thread * g_dyn;

// (ce, cs, sck, mosi, miso, irq)
NordicRadio g_nrf(D0, D10, D13, D11, D12, D1);
Ar::Semaphore g_receiveSem;
Ar::Thread * g_rfThread;

float adcrTemp25 = 0;             /*! Calibrated ADCR_TEMP25 */
float adcr100m = 0;

#if ROLE_TRANSMITTER
DigitalOut g_led(LED_RED);
#endif

//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------

#if defined(__MICROLIB)
#pragma weak __aeabi_assert
extern "C" void __aeabi_assert(const char *s, const char *f, int l)
{
    Ar::_halt();
}
#endif

void x_thread(void * arg)
{
    Ar::Thread * self = Ar::Thread::getCurrent();
    const char * myName = self->getName();
    ar_status_t status;

    while (1)
    {
        printf("[%d:%s] receiving on channel\n", us_ticker_read(), myName);
        int foo = g_chan.receive();
        printf("[%d:%s] received from channel (foo=%d)\n", us_ticker_read(), myName, foo);

        printf("[%d:%s] sleeping a bit\n", us_ticker_read(), myName);
        Ar::Thread::sleep(1000);

        printf("[%d:%s] receiving on channel\n", us_ticker_read(), myName);
        foo = g_chan.receive();
        printf("[%d:%s] received from channel (foo=%d)\n", us_ticker_read(), myName, foo);

        printf("[%d:%s] receiving on channel (will timeout)\n", us_ticker_read(), myName);
        status = g_chan.receive(foo, 500);
        if (status != kArTimeoutError)
        {
            printf("[%d:%s] receiving didn't timeout!\n", us_ticker_read(), myName);
        }
        else
        {
            printf("[%d:%s] receiving timed out successfully\n", us_ticker_read(), myName);
        }

        printf("[%d:%s] sleeping a bit\n", us_ticker_read(), myName);
        Ar::Thread::sleep(4000);
    }
}

void y_thread(void * arg)
{
    Ar::Thread * self = Ar::Thread::getCurrent();
    const char * myName = self->getName();
    ar_status_t status;

    while (1)
    {
        printf("[%d:%s] sending to channel\n", us_ticker_read(), myName);
        g_chan.send(128);
        printf("[%d:%s] sent to channel\n", us_ticker_read(), myName);

        printf("[%d:%s] sending to channel\n", us_ticker_read(), myName);
        g_chan.send(256);
        printf("[%d:%s] sent to channel\n", us_ticker_read(), myName);

        printf("[%d:%s] sleeping a bit\n", us_ticker_read(), myName);
        Ar::Thread::sleep(2000);

        printf("[%d:%s] sending on channel (will timeout)\n", us_ticker_read(), myName);
        status = g_chan.send(1, 2);
        if (status != kArTimeoutError)
        {
            printf("[%d:%s] sending didn't timeout!\n", us_ticker_read(), myName);
        }
        else
        {
            printf("[%d:%s] sending timed out successfully\n", us_ticker_read(), myName);
        }
    }
}

void get_vdd()
{
    // Enable bandgap.
    HW_PMC_REGSC(PMC_BASE).B.BGBE = 1;

    AnalogIn bandgap(ADC0_BANDGAP);

    // Get VDD value measured in mV: VDD = (ADCR_VDD x V_BG) / ADCR_BG
    float vdd = ADCR_VDD * V_BG / (float)bandgap.read_u16();
    printf("vdd=%.3f mV\n", vdd);

    // Calibrate ADCR_TEMP25: ADCR_TEMP25 = ADCR_VDD x V_TEMP25 / VDD
    adcrTemp25 = ADCR_VDD * V_TEMP25 / vdd;

    // ADCR_100M = ADCR_VDD x M x 100 / VDD
    adcr100m = (ADCR_VDD * M) / (vdd * 10);

    // Disable bandgap.
    HW_PMC_REGSC(PMC_BASE).B.BGBE = 0;
}

void fp1_thread(void * arg)
{
    get_vdd();
    AnalogIn adc(ADC0_TEMP);

    while (1)
    {
//         float v = adc.read();

        // Temperature = 25 - (ADCR_T - ADCR_TEMP25) * 100 / ADCR_100M
        float currentTemperature = (STANDARD_TEMP - ((float)adc.read_u16() - adcrTemp25) * 100.0f / adcr100m);

        printf("sending temp=%.3f\n", currentTemperature);
        currentTemperature >> g_fchan;
    }
}

void fp2_thread(void * arg)
{
    const int kHistoryCount = 10;
    float history[kHistoryCount];
    int count = 0;
    while (1)
    {
        float v;
        v <<= g_fchan;
        printf("received temp=%.3f\n", v);

        if (count >= kHistoryCount)
        {
            memcpy(&history[0], &history[1], sizeof(float)*(kHistoryCount-1));
            --count;
        }
        history[count] = v;
        ++count;

        float sum = 0;
        int i;
        for (i=0; i < count; ++i)
        {
            sum += history[i];
        }
        float avg = sum / float(count);

        printf("average temp=%.3f over last %d samples\n", avg, count);

#if ROLE_TRANSMITTER
        avg >> g_avgTempChan;
#endif

        Ar::Thread::sleep(1000);
    }
}

void dyn_test(void * arg)
{
    printf("hi from dyn_test\n");
    printf("__cplusplus = '%d'\n", __cplusplus);
}

void rf_thread(void * arg)
{
    g_nrf.init(kRadioAddress);
    g_nrf.setReceiveSem(&g_receiveSem);
    g_nrf.dump();

#if ROLE_TRANSMITTER

    while (1)
    {
        float temp;
        temp <<= g_avgTempChan;

        g_led = 0;

        uint8_t buf[32];// = "Hello world!";
        memcpy(buf, &temp, sizeof(temp));
        g_nrf.send(kRadioAddress, buf, sizeof(temp));

        g_led = 1;

        Ar::Thread::sleep(2000);
    }

#else

    while (1)
    {
        g_nrf.startReceive();

        g_receiveSem.get(1000);
//         g_nrf.dump();

        g_nrf.stopReceive();

        while (g_nrf.isPacketAvailable())
        {
            uint8_t buf[32];
            uint32_t count = g_nrf.readPacket(buf);
            if (count)
            {
                float temp;
                memcpy(&temp, buf, sizeof(temp));
                printf("Remote temperature = %.3f deg\n", temp);
            }

            g_nrf.clearReceiveFlag();
        }

        Ar::Thread::sleep(1500);
    }

#endif
}

void main_thread(void * arg)
{
    Ar::Thread * self = Ar::Thread::getCurrent();
    const char * myName = self->getName();

    printf("[%d:%s] Main thread is running\r\n", us_ticker_read(), myName);

#if ROLE_TRANSMITTER
    // Turn off LED
    g_led = 1;
#endif

//     while (1)
//     {
//         printf("hi\n");
//         Ar::Thread::sleep(1000);
//     }

//     g_testCase.init();
//     g_testCase.run();

//     Foo * foo = new Foo;
//     g_fooThread.init("foo", foo, &Foo::my_entry, NULL, 512, 120);
//
//     g_dyn = new Ar::Thread("dyn", dyn_test, 0, 512, 120);

#if ROLE_TRANSMITTER
    g_fpThread1 = new Ar::Thread("fp1", fp1_thread, 0, 1024, 100);
    g_fpThread2 = new Ar::Thread("fp2", fp2_thread, 0, 1024, 100);
#endif

    g_rfThread = new Ar::Thread("rf", rf_thread, 0, 1536, 80);

    printf("[%d:%s] goodbye!\r\n", us_ticker_read(), myName);

}

int main(void)
{
    us_ticker_init();

    printf("Running test...\r\n");

#if 0
    printf("sizeof(Thread)=%d\r\n", sizeof(Ar::Thread));
    printf("sizeof(Channel)=%d\r\n", sizeof(Ar::Channel));
    printf("sizeof(Semaphore)=%d\r\n", sizeof(Ar::Semaphore));
    printf("sizeof(Mutex)=%d\r\n", sizeof(Ar::Mutex));
    printf("sizeof(Queue)=%d\r\n", sizeof(Ar::Queue));
    printf("sizeof(Timer)=%d\r\n", sizeof(Ar::Timer));
#endif

#if defined(__ICCARM__)
    main_thread(0);
    Ar::Thread::getCurrent()->suspend();
#else
//     g_mainThread.init("main", main_thread, 0, 56);
//     g_mainThread.resume();
    ar_kernel_run();
    Ar::_halt();
#endif

    return 0;
}

//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef USER_SYSTEM_HPP
#define USER_SYSTEM_HPP

#include <types.hpp>

void exit(size_t return_code) __attribute__((noreturn));

//TODO Put the function in noreturn once the system call is written
void exit(size_t return_code) {
    asm volatile("mov rax, 0x666; mov rbx, %0; int 50"
        : //No outputs
        : "r" (return_code)
        : "rax", "rbx");

    __builtin_unreachable();
}

#endif
<commit_msg>Remove old TODO<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef USER_SYSTEM_HPP
#define USER_SYSTEM_HPP

#include <types.hpp>

void exit(size_t return_code) __attribute__((noreturn));

void exit(size_t return_code) {
    asm volatile("mov rax, 0x666; mov rbx, %0; int 50"
        : //No outputs
        : "r" (return_code)
        : "rax", "rbx");

    __builtin_unreachable();
}

#endif
<|endoftext|>


<commit_before>#ifndef SIPLASPLAS_UTILITY_MEMORY_MANIP_HPP
#define SIPLASPLAS_UTILITY_MEMORY_MANIP_HPP

#include <memory>
#include <siplasplas/utility/export.hpp>

namespace cpp
{
    namespace detail
    {
        SIPLASPLAS_UTILITY_EXPORT char* aligned_ptr(char* pointer, std::size_t alignment);
        SIPLASPLAS_UTILITY_EXPORT void* aligned_ptr(void* pointer, std::size_t alignment);

        template<typename T>
        void write_at(char* pointer, const T& value, std::intptr_t offset = 0)
        {
            *(reinterpret_cast<T*>(pointer) + offset) = value;
        }

        template<typename T>
        void write_at(void* pointer, const T& value, std::intptr_t offset = 0)
        {
            write_at(reinterpret_cast<char*>(pointer), value, offset);
        }

        template<typename T>
        T read_at(const char* pointer, std::intptr_t offset = 0)
        {
            return *(reinterpret_cast<const T*>(pointer + offset));
        }

        template<typename T>
        T read_at(const void* pointer, std::intptr_t offset = 0)
        {
            return read_at<T>(reinterpret_cast<const char*>(pointer), offset);
        }

        template<typename T>
        void write_before(char* pointer, const T& value)
        {
            write_at(pointer, value, -sizeof(T));
        }

        template<typename T>
        void write_before(void* pointer, const T& value)
        {
            write_before(reinterpret_cast<char*>(pointer), value);
        }

        template<typename T>
        T read_before(const char* pointer)
        {
            return read_at<T>(pointer, - sizeof(T));
        }

        template<typename T>
        T read_before(const void* pointer)
        {
            return read_before<T>(reinterpret_cast<const char*>(pointer));
        }

        template<typename T>
        class RawReaderWriter
        {
        public:
            RawReaderWriter(void* at) :
                _at{reinterpret_cast<char*>(at)}
            {}

            T get() const
            {
                return detail::read_at<T>(_at);
            }

            operator T() const
            {
                return get();
            }

            T operator=(T value)
            {
                detail::write_at(_at, value);
                return value;
            }
        private:
            char* _at;
        };
    }
}

#endif // SIPLASPLAS_UTILITY_MEMORY_MANIP_HPP

<commit_msg>[#52] aligned_ptr documentation<commit_after>#ifndef SIPLASPLAS_UTILITY_MEMORY_MANIP_HPP
#define SIPLASPLAS_UTILITY_MEMORY_MANIP_HPP

#include <memory>
#include <siplasplas/utility/export.hpp>

namespace cpp
{
    namespace detail
    {
        /**
         * \ingroup utility
         * \brief Returns an address aligned to an specific boundary
         *
         * \param pointer Starting address
         * \param alignment Alignment boundary. Must be a power of two
         *
         * \returns The next (upper) address from the given address that's aligned
         * to the required boundary
         */
        SIPLASPLAS_UTILITY_EXPORT char* aligned_ptr(char* pointer, std::size_t alignment);

        /**
         * \ingroup utility
         * \brief Returns an address aligned to an specific boundary
         *
         * \param pointer Starting address
         * \param alignment Alignment boundary. Must be a power of two
         *
         * \returns The next (upper) address from the given address that's aligned
         * to the required boundary
         */
        SIPLASPLAS_UTILITY_EXPORT void* aligned_ptr(void* pointer, std::size_t alignment);

        template<typename T>
        void write_at(char* pointer, const T& value, std::intptr_t offset = 0)
        {
            *(reinterpret_cast<T*>(pointer) + offset) = value;
        }

        template<typename T>
        void write_at(void* pointer, const T& value, std::intptr_t offset = 0)
        {
            write_at(reinterpret_cast<char*>(pointer), value, offset);
        }

        template<typename T>
        T read_at(const char* pointer, std::intptr_t offset = 0)
        {
            return *(reinterpret_cast<const T*>(pointer + offset));
        }

        template<typename T>
        T read_at(const void* pointer, std::intptr_t offset = 0)
        {
            return read_at<T>(reinterpret_cast<const char*>(pointer), offset);
        }

        template<typename T>
        void write_before(char* pointer, const T& value)
        {
            write_at(pointer, value, -sizeof(T));
        }

        template<typename T>
        void write_before(void* pointer, const T& value)
        {
            write_before(reinterpret_cast<char*>(pointer), value);
        }

        template<typename T>
        T read_before(const char* pointer)
        {
            return read_at<T>(pointer, - sizeof(T));
        }

        template<typename T>
        T read_before(const void* pointer)
        {
            return read_before<T>(reinterpret_cast<const char*>(pointer));
        }

        template<typename T>
        class RawReaderWriter
        {
        public:
            RawReaderWriter(void* at) :
                _at{reinterpret_cast<char*>(at)}
            {}

            T get() const
            {
                return detail::read_at<T>(_at);
            }

            operator T() const
            {
                return get();
            }

            T operator=(T value)
            {
                detail::write_at(_at, value);
                return value;
            }
        private:
            char* _at;
        };
    }
}

#endif // SIPLASPLAS_UTILITY_MEMORY_MANIP_HPP

<|endoftext|>


<commit_before>/**
 *  @file example2.cpp
 *
 */

//  Example
//
//  Read a mechanism and a thermodynamics file for the
//  class IdealSolidSolnPhase in order to test that it's
//  working correctly
//

#include <iostream>
#include <string>
#include <vector>

#include "ct_defs.h"
#include "xml.h"
#include "ctml.h"

using namespace std;

#ifdef DEBUG_HKM
int iDebug_HKM = 0;
#endif

/*****************************************************************/
/*****************************************************************/
/*****************************************************************/
static void printUsage()
{
    cout << "ctitoxml [-h] infile.cti" << endl;
    cout << "    Translates a cti formated file to an xml file" << endl;
    cout << "    The xml file will be named infile.xml" << endl;
}

int main(int argc, char** argv) {
    string infile;
    // look for command-line options
    if (argc > 1) {
      string tok;
      for (int j = 1; j < argc; j++) {
	tok = string(argv[j]);
	if (tok[0] == '-') {
	  int nopt = tok.size();
	  for (int n = 1; n < nopt; n++) {
	    if (tok[n] == 'h') {
	      printUsage();
	      exit(0);
	    } else {
	      printUsage();
	      exit(1);
	    }
	  }
	} else if (infile == "") {
	  infile = tok;
	}
	else {
	  printUsage();
	  exit(1);
	}
      }
    }
    if (infile == "") {
	  printUsage();
	  exit(1);
    }

    try {
      XML_Node *xc = new XML_Node();
      string path = findInputFile(infile);
      ctml::get_CTML_Tree(xc, path);
      XML_Node *xd = new XML_Node();
      xc->copy(xd);
      ofstream tout;
      tout.open("testdest.xml");
      xc->write(tout);
      tout.close();
      tout.open("testdest2.xml");
      xd->write(tout);
      tout.close();

    }
    catch (CanteraError) {
      showErrors(cout);
    }

    return 0;
}
/***********************************************************/
<commit_msg>MSVC warning message<commit_after>/**
 *  @file example2.cpp
 *
 */

//  Example
//
//  Read a mechanism and a thermodynamics file for the
//  class IdealSolidSolnPhase in order to test that it's
//  working correctly
//

#include <iostream>
#include <string>
#include <vector>

#include "ct_defs.h"
#include "xml.h"
#include "ctml.h"

using namespace std;

#ifdef DEBUG_HKM
int iDebug_HKM = 0;
#endif

/*****************************************************************/
/*****************************************************************/
/*****************************************************************/
static void printUsage()
{
    cout << "ctitoxml [-h] infile.cti" << endl;
    cout << "    Translates a cti formated file to an xml file" << endl;
    cout << "    The xml file will be named infile.xml" << endl;
}

int main(int argc, char** argv) {
    string infile;
    // look for command-line options
    if (argc > 1) {
      string tok;
      for (int j = 1; j < argc; j++) {
	tok = string(argv[j]);
	if (tok[0] == '-') {
	  int nopt = static_cast<int>(tok.size());
	  for (int n = 1; n < nopt; n++) {
	    if (tok[n] == 'h') {
	      printUsage();
	      exit(0);
	    } else {
	      printUsage();
	      exit(1);
	    }
	  }
	} else if (infile == "") {
	  infile = tok;
	}
	else {
	  printUsage();
	  exit(1);
	}
      }
    }
    if (infile == "") {
	  printUsage();
	  exit(1);
    }

    try {
      XML_Node *xc = new XML_Node();
      string path = findInputFile(infile);
      ctml::get_CTML_Tree(xc, path);
      XML_Node *xd = new XML_Node();
      xc->copy(xd);
      ofstream tout;
      tout.open("testdest.xml");
      xc->write(tout);
      tout.close();
      tout.open("testdest2.xml");
      xd->write(tout);
      tout.close();

    }
    catch (CanteraError) {
      showErrors(cout);
    }

    return 0;
}
/***********************************************************/
<|endoftext|>


<commit_before>#include "navigation_star.h"
#include "extra_solar_transforms.h"
#include "solar_system.h"
#include <cmath>
#include "AACoordinateTransformation.h"
#include "AAPrecession.h"
#include "AAAberration.h"
#include "AANutation.h"
#include "AADynamicalTime.h"
#include "neo_bsc_starlist.h"
#include <algorithm>

inline uint32_t get_bsc_number( uint32_t index ){
  return flash_memory_array::bsc_array[index].BSCnum;
}

int32_t extra_solar::neo_get_index_fast( const uint32_t bsc_number ){
  uint32_t lo = 0;
  uint32_t hi = flash_memory_array::bsc_array.size() - 1;
  while( lo <= hi ){
    uint32_t mid = lo + (hi - lo)/2;
    uint32_t mid_bsc = get_bsc_number( mid );
    if( mid_bsc > bsc_number ){
      hi = mid - 1;
    }else if( mid_bsc < bsc_number ){
      lo = mid + 1;
    }else if( bsc_number < mid_bsc ){
      return mid;
    }
  }
  return -1; // Not found.
}

int32_t extra_solar::neo_get_index( uint32_t bsc_number ){
  for( uint32_t i=0; i<flash_memory_array::bsc_array.size(); ++i ){
    if( flash_memory_array::bsc_array[i].BSCnum == static_cast<int32_t>(bsc_number) ){
      return static_cast<int32_t>(i);
    }
  }
  return -1;
}

CAA2DCoordinate extra_solar::proper_motion_adjusted_position(const star_data & sd,
						double JD)
{
  CAA2DCoordinate ra_dec;
  sexagesimal::Sexagesimal RA;
  RA.set_binary_data(sd.RAdata);
  ra_dec.X = RA.to_double();
  sexagesimal::Sexagesimal DEC;
  DEC.set_binary_data(sd.DECdata);
  ra_dec.Y = DEC.to_double();
  /* Bright Star Catalog proper motions are arc seconds per year. */
  double days = JD - solar_system::J2000_0;
  double years = days / 365.25;
  double DECrad =
      CAACoordinateTransformation::DegreesToRadians(DEC.to_double());
  double cos_factor = cos(DECrad);
  CAA2DCoordinate pm_arc_sec;
  pm_arc_sec.X = sd.RApm * years / 3600;
  pm_arc_sec.Y = sd.DECpm * years / 3600;
  if (cos_factor != 0.0) { /* This approach fails at the poles.  */
    ra_dec.X += sd.RApm * years * (24.0 / 360.0) * (1.0 / 3600.0) / cos_factor;
    ra_dec.Y += sd.DECpm * years * (1.0 / 3600.0);
  }
  return ra_dec;
}

/*
 * Applicable to stars, deep space objects.
 *
 * ra_dec should be J2000.0 coordinates.
 * JD should be corrected for dynamical time.
 *
 * This uses CAAAberration::EquatorialAberration(RA,Dec,JD)
 */
CAA2DCoordinate apply_aberration(CAA2DCoordinate ra_dec, double JD)
{
  CAA2DCoordinate ra_dec_a;
  ra_dec_a.X = ra_dec.X;
  ra_dec_a.Y = ra_dec.Y;
  CAA2DCoordinate aberration_addon =
      CAAAberration::EquatorialAberration(ra_dec.X, ra_dec.Y, JD);
  ra_dec_a.X += aberration_addon.X;
  ra_dec_a.Y += aberration_addon.Y;
  return ra_dec_a;
}

CAA2DCoordinate precession_correct(CAA2DCoordinate RA_Dec_J2000, double JD)
{
  CAA2DCoordinate position;
  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_J2000.X, RA_Dec_J2000.Y,
				       solar_system::J2000_0, JD);
  return position;
}

CAA2DCoordinate precession_correct(CAA2DCoordinate RA_Dec_J2000, double JD_0, double JD_1)
{
  CAA2DCoordinate position;
  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_J2000.X, RA_Dec_J2000.Y, JD_0, JD_1);
  return position;
}

CAA2DCoordinate precession_and_nutation_correct(CAA2DCoordinate RA_Dec_J2000,
						double JD)
{
  CAA2DCoordinate position;
  double nil;
  double nio;
  double toe;
  double RA_nutation;
  double DEC_nutation;

  /* At the end, I add on a nutation correction.
   * Should I subtract such a correction at the start?
   * If so, include this conditional code.
   *
   * Usually J2000 Coordinates are with respect to the mean eqinox so it
   * is incorrect tu un-apply nutation at the start of the calculation.
   *
   * Consider eliminating this function to avoid erronious use.
   */
#if 1
  nil = CAANutation::NutationInLongitude(solar_system::J2000_0);	/* arc seconds. */
  nio = CAANutation::NutationInObliquity(solar_system::J2000_0);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(solar_system::J2000_0);	/*  Degrees */
  /* Will the compiler reconize that nil, nio, and toe as set above are constants?
   * They are return value of a static function with a constant argument */
  RA_nutation = CAANutation::NutationInRightAscension(RA_Dec_J2000.X,
						      RA_Dec_J2000.Y,
						      toe, nil, nio);
  DEC_nutation = CAANutation::NutationInDeclination(RA_Dec_J2000.X, toe, nil, nio);
  RA_Dec_J2000.X -= RA_nutation / 3600.0 / 15.0;
  RA_Dec_J2000.Y -= DEC_nutation / 3600.0;
#endif

  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_J2000.X, RA_Dec_J2000.Y,
				       solar_system::J2000_0, JD);

  nil = CAANutation::NutationInLongitude(JD);	/* arc seconds. */
  nio = CAANutation::NutationInObliquity(JD);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(JD);	/*  Degrees */
  RA_nutation = CAANutation::NutationInRightAscension(position.X,
							     position.Y,
							     toe,
							     nil,
							     nio);
  DEC_nutation = CAANutation::NutationInDeclination(position.X,
							   toe,
							   nil,
							   nio);
  /* RA_nutation and DEC_nutation are both in arc seconds. */

  position.X += RA_nutation / 3600.0 / 15.0;
  position.Y += DEC_nutation / 3600.0;

  return position;
}

/*
 *
 * I add on nutation at the end, so logicaly it should be subracted at the start.
 * TODO see if the subtract off part is zero for epoch JD2000.
 * Done: These are not zero for JD2000.  See the test program nutation_info.
 *
 */
CAA2DCoordinate precession_and_nutation_correct(CAA2DCoordinate RA_Dec_0,
						double JD_0, double JD_1)
{
  double nil;
  double nio;
  double toe;
  double RA_nutation;
  double DEC_nutation;

  /*
   * Calculate and subtract off nutation for JD_0.  Effectivly, undo an assumed present nutation correction.
   */
  nil = CAANutation::NutationInLongitude(JD_0);	/* arc seconds. */
  nio = CAANutation::NutationInObliquity(JD_0);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(JD_0);	/*  Degrees */
  RA_nutation = CAANutation::NutationInRightAscension(RA_Dec_0.X,
						      RA_Dec_0.Y,
						      toe, nil, nio);
  DEC_nutation = CAANutation::NutationInDeclination(RA_Dec_0.X, toe, nil, nio);
  RA_Dec_0.X -= RA_nutation / 3600.0 / 15.0;
  RA_Dec_0.Y -= DEC_nutation / 3600.0;

  CAA2DCoordinate position;

  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_0.X, RA_Dec_0.Y, JD_0, JD_1);

  nil = CAANutation::NutationInLongitude(JD_1);	/*  arc seconds */
  nio = CAANutation::NutationInObliquity(JD_1);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(JD_1);	/*  Degrees */
  RA_nutation = CAANutation::NutationInRightAscension(position.X,
						      position.Y,
						      toe, nil, nio);
  DEC_nutation = CAANutation::NutationInDeclination(position.X, toe, nil, nio);
  /* RA_nutation and DEC_nutation are both in arc seconds. */
  position.X += RA_nutation / 3600.0 / 15.0;
  position.Y += DEC_nutation / 3600.0;

  return position;
}

/*
 * "Mean Equinox" coordinates have nutation "averaged out."
 *
 *  So, do not un-apply nutation correction at the start of the calculation.
 *
 *  Any expression of a value that makes a decomposition ((Mean Value) + (Variations From Mean Value)).
 *  must somehow choose what the Mean Value is.  Evidently, the nutation expressions take the Mean Value
 *  to be nothing more than the precession described by the Rigorous method of Meeus, Chapter 21.
 *
 *  One should not expect that (Variations From Mean Value) will average to zero.
 */
CAA2DCoordinate precession_and_nutation_correct_from_mean_eqinox(CAA2DCoordinate RA_Dec_0,
						double JD_0, double JD_1)
{
  double nil;
  double nio;
  double toe;
  double RA_nutation;
  double DEC_nutation;

  CAA2DCoordinate position;

  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_0.X, RA_Dec_0.Y, JD_0, JD_1);

  nil = CAANutation::NutationInLongitude(JD_1);	/*  arc seconds */
  nio = CAANutation::NutationInObliquity(JD_1);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(JD_1);	/*  Degrees */
  RA_nutation = CAANutation::NutationInRightAscension(position.X,
						      position.Y,
						      toe, nil, nio);
  DEC_nutation = CAANutation::NutationInDeclination(position.X, toe, nil, nio);
  /* RA_nutation and DEC_nutation are both in arc seconds. */
  position.X += RA_nutation / 3600.0 / 15.0;
  position.Y += DEC_nutation / 3600.0;

  return position;
}

/* This is an example of what I believe to be correct and rigorous coordinate transformations. */
CAA2DCoordinate burnham_correct(CAA2DCoordinate RA_Dec, double JD ){
  RA_Dec = precession_correct( RA_Dec, solar_system::B1950_0, solar_system::J2000_0 );
  double deltaT = CAADynamicalTime::DeltaT( JD );
  RA_Dec = apply_aberration( RA_Dec, JD + deltaT/86400.0 );
  RA_Dec = precession_and_nutation_correct_from_mean_eqinox( RA_Dec, solar_system::J2000_0, JD );

  return RA_Dec;
}

/* Overide where initial Julian date is solar_system::J2000_0 = 2451545.0  */
CAA2DCoordinate precession_and_nutation_correct_from_mean_eqinox(CAA2DCoordinate RA_Dec_J2000,
						double JD)
{
#if 1
  return precession_and_nutation_correct_from_mean_eqinox( RA_Dec_J2000, solar_system::J2000_0, JD);
#else
  /* Smaller code results if we do it the other way. Keeping this code in case errors are found. */
  CAA2DCoordinate position;
  double nil;
  double nio;
  double toe;
  double RA_nutation;
  double DEC_nutation;

  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_J2000.X, RA_Dec_J2000.Y,
				       solar_system::J2000_0, JD);

  nil = CAANutation::NutationInLongitude(JD);	/* arc seconds. */
  nio = CAANutation::NutationInObliquity(JD);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(JD);	/*  Degrees */
  RA_nutation = CAANutation::NutationInRightAscension(position.X,
							     position.Y,
							     toe,
							     nil,
							     nio);
  DEC_nutation = CAANutation::NutationInDeclination(position.X,
							   toe,
							   nil,
							   nio);
  /* RA_nutation and DEC_nutation are both in arc seconds. */

  position.X += RA_nutation / 3600.0 / 15.0;
  position.Y += DEC_nutation / 3600.0;

  return position;
#endif
}

CAA2DCoordinate navigation_star::nav_star_RA_Dec(int navstar_num, double JD)
{
  CAA2DCoordinate RA_Dec;
  int bsc_num = navigation_star::nav2bsc[navstar_num];
  int index = extra_solar::neo_get_index_fast( bsc_num );
  if (index < 0) {
    RA_Dec.X = RA_Dec.Y = 0;
    return RA_Dec;
  }
  RA_Dec = extra_solar::proper_motion_adjusted_position(flash_memory_array::bsc_array[index], JD);
  double deltaT = CAADynamicalTime::DeltaT(JD);

  RA_Dec = apply_aberration(RA_Dec, JD + deltaT/86400.0 );

  RA_Dec = precession_and_nutation_correct_from_mean_eqinox(RA_Dec, JD);

  return RA_Dec;
}
<commit_msg>Fixed another botch job in bisection.<commit_after>#include "navigation_star.h"
#include "extra_solar_transforms.h"
#include "solar_system.h"
#include <cmath>
#include "AACoordinateTransformation.h"
#include "AAPrecession.h"
#include "AAAberration.h"
#include "AANutation.h"
#include "AADynamicalTime.h"
#include "neo_bsc_starlist.h"
#include <algorithm>

inline uint32_t get_bsc_number( uint32_t index ){
  return flash_memory_array::bsc_array[index].BSCnum;
}

int32_t extra_solar::neo_get_index_fast( const uint32_t bsc_number ){
  uint32_t lo = 0;
  uint32_t hi = flash_memory_array::bsc_array.size() - 1;
  while( lo <= hi ){
    uint32_t mid = lo + (hi - lo)/2;
    uint32_t mid_bsc = get_bsc_number( mid );
    if( mid_bsc > bsc_number ){
      hi = mid - 1;
    }else if( mid_bsc < bsc_number ){
      lo = mid + 1;
    }else if( bsc_number == mid_bsc ){
      return mid;
    }
  }
  return -1; // Not found.
}

int32_t extra_solar::neo_get_index( uint32_t bsc_number ){
  for( uint32_t i=0; i<flash_memory_array::bsc_array.size(); ++i ){
    if( flash_memory_array::bsc_array[i].BSCnum == static_cast<int32_t>(bsc_number) ){
      return static_cast<int32_t>(i);
    }
  }
  return -1;
}

CAA2DCoordinate extra_solar::proper_motion_adjusted_position(const star_data & sd,
						double JD)
{
  CAA2DCoordinate ra_dec;
  sexagesimal::Sexagesimal RA;
  RA.set_binary_data(sd.RAdata);
  ra_dec.X = RA.to_double();
  sexagesimal::Sexagesimal DEC;
  DEC.set_binary_data(sd.DECdata);
  ra_dec.Y = DEC.to_double();
  /* Bright Star Catalog proper motions are arc seconds per year. */
  double days = JD - solar_system::J2000_0;
  double years = days / 365.25;
  double DECrad =
      CAACoordinateTransformation::DegreesToRadians(DEC.to_double());
  double cos_factor = cos(DECrad);
  CAA2DCoordinate pm_arc_sec;
  pm_arc_sec.X = sd.RApm * years / 3600;
  pm_arc_sec.Y = sd.DECpm * years / 3600;
  if (cos_factor != 0.0) { /* This approach fails at the poles.  */
    ra_dec.X += sd.RApm * years * (24.0 / 360.0) * (1.0 / 3600.0) / cos_factor;
    ra_dec.Y += sd.DECpm * years * (1.0 / 3600.0);
  }
  return ra_dec;
}

/*
 * Applicable to stars, deep space objects.
 *
 * ra_dec should be J2000.0 coordinates.
 * JD should be corrected for dynamical time.
 *
 * This uses CAAAberration::EquatorialAberration(RA,Dec,JD)
 */
CAA2DCoordinate apply_aberration(CAA2DCoordinate ra_dec, double JD)
{
  CAA2DCoordinate ra_dec_a;
  ra_dec_a.X = ra_dec.X;
  ra_dec_a.Y = ra_dec.Y;
  CAA2DCoordinate aberration_addon =
      CAAAberration::EquatorialAberration(ra_dec.X, ra_dec.Y, JD);
  ra_dec_a.X += aberration_addon.X;
  ra_dec_a.Y += aberration_addon.Y;
  return ra_dec_a;
}

CAA2DCoordinate precession_correct(CAA2DCoordinate RA_Dec_J2000, double JD)
{
  CAA2DCoordinate position;
  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_J2000.X, RA_Dec_J2000.Y,
				       solar_system::J2000_0, JD);
  return position;
}

CAA2DCoordinate precession_correct(CAA2DCoordinate RA_Dec_J2000, double JD_0, double JD_1)
{
  CAA2DCoordinate position;
  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_J2000.X, RA_Dec_J2000.Y, JD_0, JD_1);
  return position;
}

CAA2DCoordinate precession_and_nutation_correct(CAA2DCoordinate RA_Dec_J2000,
						double JD)
{
  CAA2DCoordinate position;
  double nil;
  double nio;
  double toe;
  double RA_nutation;
  double DEC_nutation;

  /* At the end, I add on a nutation correction.
   * Should I subtract such a correction at the start?
   * If so, include this conditional code.
   *
   * Usually J2000 Coordinates are with respect to the mean eqinox so it
   * is incorrect tu un-apply nutation at the start of the calculation.
   *
   * Consider eliminating this function to avoid erronious use.
   */
#if 1
  nil = CAANutation::NutationInLongitude(solar_system::J2000_0);	/* arc seconds. */
  nio = CAANutation::NutationInObliquity(solar_system::J2000_0);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(solar_system::J2000_0);	/*  Degrees */
  /* Will the compiler reconize that nil, nio, and toe as set above are constants?
   * They are return value of a static function with a constant argument */
  RA_nutation = CAANutation::NutationInRightAscension(RA_Dec_J2000.X,
						      RA_Dec_J2000.Y,
						      toe, nil, nio);
  DEC_nutation = CAANutation::NutationInDeclination(RA_Dec_J2000.X, toe, nil, nio);
  RA_Dec_J2000.X -= RA_nutation / 3600.0 / 15.0;
  RA_Dec_J2000.Y -= DEC_nutation / 3600.0;
#endif

  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_J2000.X, RA_Dec_J2000.Y,
				       solar_system::J2000_0, JD);

  nil = CAANutation::NutationInLongitude(JD);	/* arc seconds. */
  nio = CAANutation::NutationInObliquity(JD);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(JD);	/*  Degrees */
  RA_nutation = CAANutation::NutationInRightAscension(position.X,
							     position.Y,
							     toe,
							     nil,
							     nio);
  DEC_nutation = CAANutation::NutationInDeclination(position.X,
							   toe,
							   nil,
							   nio);
  /* RA_nutation and DEC_nutation are both in arc seconds. */

  position.X += RA_nutation / 3600.0 / 15.0;
  position.Y += DEC_nutation / 3600.0;

  return position;
}

/*
 *
 * I add on nutation at the end, so logicaly it should be subracted at the start.
 * TODO see if the subtract off part is zero for epoch JD2000.
 * Done: These are not zero for JD2000.  See the test program nutation_info.
 *
 */
CAA2DCoordinate precession_and_nutation_correct(CAA2DCoordinate RA_Dec_0,
						double JD_0, double JD_1)
{
  double nil;
  double nio;
  double toe;
  double RA_nutation;
  double DEC_nutation;

  /*
   * Calculate and subtract off nutation for JD_0.  Effectivly, undo an assumed present nutation correction.
   */
  nil = CAANutation::NutationInLongitude(JD_0);	/* arc seconds. */
  nio = CAANutation::NutationInObliquity(JD_0);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(JD_0);	/*  Degrees */
  RA_nutation = CAANutation::NutationInRightAscension(RA_Dec_0.X,
						      RA_Dec_0.Y,
						      toe, nil, nio);
  DEC_nutation = CAANutation::NutationInDeclination(RA_Dec_0.X, toe, nil, nio);
  RA_Dec_0.X -= RA_nutation / 3600.0 / 15.0;
  RA_Dec_0.Y -= DEC_nutation / 3600.0;

  CAA2DCoordinate position;

  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_0.X, RA_Dec_0.Y, JD_0, JD_1);

  nil = CAANutation::NutationInLongitude(JD_1);	/*  arc seconds */
  nio = CAANutation::NutationInObliquity(JD_1);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(JD_1);	/*  Degrees */
  RA_nutation = CAANutation::NutationInRightAscension(position.X,
						      position.Y,
						      toe, nil, nio);
  DEC_nutation = CAANutation::NutationInDeclination(position.X, toe, nil, nio);
  /* RA_nutation and DEC_nutation are both in arc seconds. */
  position.X += RA_nutation / 3600.0 / 15.0;
  position.Y += DEC_nutation / 3600.0;

  return position;
}

/*
 * "Mean Equinox" coordinates have nutation "averaged out."
 *
 *  So, do not un-apply nutation correction at the start of the calculation.
 *
 *  Any expression of a value that makes a decomposition ((Mean Value) + (Variations From Mean Value)).
 *  must somehow choose what the Mean Value is.  Evidently, the nutation expressions take the Mean Value
 *  to be nothing more than the precession described by the Rigorous method of Meeus, Chapter 21.
 *
 *  One should not expect that (Variations From Mean Value) will average to zero.
 */
CAA2DCoordinate precession_and_nutation_correct_from_mean_eqinox(CAA2DCoordinate RA_Dec_0,
						double JD_0, double JD_1)
{
  double nil;
  double nio;
  double toe;
  double RA_nutation;
  double DEC_nutation;

  CAA2DCoordinate position;

  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_0.X, RA_Dec_0.Y, JD_0, JD_1);

  nil = CAANutation::NutationInLongitude(JD_1);	/*  arc seconds */
  nio = CAANutation::NutationInObliquity(JD_1);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(JD_1);	/*  Degrees */
  RA_nutation = CAANutation::NutationInRightAscension(position.X,
						      position.Y,
						      toe, nil, nio);
  DEC_nutation = CAANutation::NutationInDeclination(position.X, toe, nil, nio);
  /* RA_nutation and DEC_nutation are both in arc seconds. */
  position.X += RA_nutation / 3600.0 / 15.0;
  position.Y += DEC_nutation / 3600.0;

  return position;
}

/* This is an example of what I believe to be correct and rigorous coordinate transformations. */
CAA2DCoordinate burnham_correct(CAA2DCoordinate RA_Dec, double JD ){
  RA_Dec = precession_correct( RA_Dec, solar_system::B1950_0, solar_system::J2000_0 );
  double deltaT = CAADynamicalTime::DeltaT( JD );
  RA_Dec = apply_aberration( RA_Dec, JD + deltaT/86400.0 );
  RA_Dec = precession_and_nutation_correct_from_mean_eqinox( RA_Dec, solar_system::J2000_0, JD );

  return RA_Dec;
}

/* Overide where initial Julian date is solar_system::J2000_0 = 2451545.0  */
CAA2DCoordinate precession_and_nutation_correct_from_mean_eqinox(CAA2DCoordinate RA_Dec_J2000,
						double JD)
{
#if 1
  return precession_and_nutation_correct_from_mean_eqinox( RA_Dec_J2000, solar_system::J2000_0, JD);
#else
  /* Smaller code results if we do it the other way. Keeping this code in case errors are found. */
  CAA2DCoordinate position;
  double nil;
  double nio;
  double toe;
  double RA_nutation;
  double DEC_nutation;

  position =
      CAAPrecession::PrecessEquatorial(RA_Dec_J2000.X, RA_Dec_J2000.Y,
				       solar_system::J2000_0, JD);

  nil = CAANutation::NutationInLongitude(JD);	/* arc seconds. */
  nio = CAANutation::NutationInObliquity(JD);	/*  arc seconds */
  toe = CAANutation::TrueObliquityOfEcliptic(JD);	/*  Degrees */
  RA_nutation = CAANutation::NutationInRightAscension(position.X,
							     position.Y,
							     toe,
							     nil,
							     nio);
  DEC_nutation = CAANutation::NutationInDeclination(position.X,
							   toe,
							   nil,
							   nio);
  /* RA_nutation and DEC_nutation are both in arc seconds. */

  position.X += RA_nutation / 3600.0 / 15.0;
  position.Y += DEC_nutation / 3600.0;

  return position;
#endif
}

CAA2DCoordinate navigation_star::nav_star_RA_Dec(int navstar_num, double JD)
{
  CAA2DCoordinate RA_Dec;
  int bsc_num = navigation_star::nav2bsc[navstar_num];
  int index = extra_solar::neo_get_index_fast( bsc_num );
  if (index < 0) {
    RA_Dec.X = RA_Dec.Y = 0;
    return RA_Dec;
  }
  RA_Dec = extra_solar::proper_motion_adjusted_position(flash_memory_array::bsc_array[index], JD);
  double deltaT = CAADynamicalTime::DeltaT(JD);

  RA_Dec = apply_aberration(RA_Dec, JD + deltaT/86400.0 );

  RA_Dec = precession_and_nutation_correct_from_mean_eqinox(RA_Dec, JD);

  return RA_Dec;
}
<|endoftext|>


<commit_before>
#include <togo/assert.hpp>
#include <togo/log.hpp>
#include <togo/system.hpp>

using namespace togo;

signed main() {
	TOGO_LOGF("num_cores = %u\n", system::num_cores());
	TOGO_LOG("Sleeping for 5 seconds\n");
	TOGO_LOGF("exec_dir: %s\n", system::exec_dir());
	TOGO_ASSERTE(system::secs_since_epoch() > 1407135980u);
	float const start = system::time_monotonic();
	TOGO_LOGF("start       : time_monotonic() = %.6f\n", start);
	system::sleep_ms(1000u);
	TOGO_LOGF("1000ms delay: time_monotonic() = %.6f\n", system::time_monotonic() - start);
	system::sleep_ms(100u);
	TOGO_LOGF("100ms delay : time_monotonic() = %.6f\n", system::time_monotonic() - start);
	system::sleep_ms(10u);
	TOGO_LOGF("10ms delay  : time_monotonic() = %.6f\n", system::time_monotonic() - start);
	system::sleep_ms(1u);
	TOGO_LOGF("1ms delay   : time_monotonic() = %.6f\n", system::time_monotonic() - start);
	return 0;
}
<commit_msg>test/system/general: updated exec_dir() test; tidy.<commit_after>
#include <togo/assert.hpp>
#include <togo/log.hpp>
#include <togo/string.hpp>
#include <togo/system.hpp>

using namespace togo;

signed main() {
	TOGO_LOGF("num_cores = %u\n", system::num_cores());
	StringRef exec_dir = system::exec_dir();
	TOGO_LOGF("exec_dir: %.*s\n", exec_dir.size, exec_dir.data);
	TOGO_ASSERTE(system::secs_since_epoch() > 1407135980u);

	TOGO_LOG("\n");
	float const start = system::time_monotonic();
	TOGO_LOGF("start       : time_monotonic() = %.6f\n", start);
	system::sleep_ms(1000u);
	TOGO_LOGF("1000ms delay: time_monotonic() = %.6f\n", system::time_monotonic() - start);
	system::sleep_ms(100u);
	TOGO_LOGF("100ms delay : time_monotonic() = %.6f\n", system::time_monotonic() - start);
	system::sleep_ms(10u);
	TOGO_LOGF("10ms delay  : time_monotonic() = %.6f\n", system::time_monotonic() - start);
	system::sleep_ms(1u);
	TOGO_LOGF("1ms delay   : time_monotonic() = %.6f\n", system::time_monotonic() - start);

	return 0;
}
<|endoftext|>


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

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

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef __SBX_SBXVARIABLE_HXX
#include <basic/sbxvar.hxx>
#endif

#include "zoomitem.hxx"

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

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

TYPEINIT1_AUTOFACTORY(SvxZoomItem,SfxUInt16Item);

#define ZOOM_PARAM_VALUE    "Value"
#define ZOOM_PARAM_VALUESET "ValueSet"
#define ZOOM_PARAM_TYPE     "Type"
#define ZOOM_PARAMS         3

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

SvxZoomItem::SvxZoomItem
(
    SvxZoomType eZoomType,
    sal_uInt16      nVal,
    sal_uInt16      _nWhich
)
:   SfxUInt16Item( _nWhich, nVal ),
    nValueSet( SVX_ZOOM_ENABLE_ALL ),
    eType( eZoomType )
{
}

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

SvxZoomItem::SvxZoomItem( const SvxZoomItem& rOrig )
:   SfxUInt16Item( rOrig.Which(), rOrig.GetValue() ),
    nValueSet( rOrig.GetValueSet() ),
    eType( rOrig.GetType() )
{
}

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

SvxZoomItem::~SvxZoomItem()
{
}

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

SfxPoolItem* SvxZoomItem::Clone( SfxItemPool * /*pPool*/ ) const
{
    return new SvxZoomItem( *this );
}

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

SfxPoolItem* SvxZoomItem::Create( SvStream& rStrm, sal_uInt16 /*nVersion*/ ) const
{
    sal_uInt16 nValue;
    sal_uInt16 nValSet;
    sal_Int8 nType;
    rStrm >> nValue >> nValSet >> nType;
    SvxZoomItem* pNew = new SvxZoomItem( (SvxZoomType)nType, nValue, Which() );
    pNew->SetValueSet( nValSet );
    return pNew;
}

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

SvStream& SvxZoomItem::Store( SvStream& rStrm, sal_uInt16 /*nItemVersion*/ ) const
{
    rStrm << (sal_uInt16)GetValue()
          << nValueSet
          << (sal_Int8)eType;
    return rStrm;
}

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

int SvxZoomItem::operator==( const SfxPoolItem& rAttr ) const
{
    DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );

    SvxZoomItem& rItem = (SvxZoomItem&)rAttr;

    return ( GetValue() == rItem.GetValue()     &&
             nValueSet  == rItem.GetValueSet()  &&
             eType      == rItem.GetType()          );
}

sal_Bool SvxZoomItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
//  sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
    nMemberId &= ~CONVERT_TWIPS;
    switch ( nMemberId )
    {
        case 0 :
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq( ZOOM_PARAMS );
            aSeq[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUE ));
            aSeq[0].Value <<= sal_Int32( GetValue() );
            aSeq[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUESET ));
            aSeq[1].Value <<= sal_Int16( nValueSet );
            aSeq[2].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_TYPE ));
            aSeq[2].Value <<= sal_Int16( eType );
            rVal <<= aSeq;
        }
        break;

        case MID_VALUE: rVal <<= (sal_Int32) GetValue(); break;
        case MID_VALUESET: rVal <<= (sal_Int16) nValueSet; break;
        case MID_TYPE: rVal <<= (sal_Int16) eType; break;
        default:
            DBG_ERROR("svx::SvxZoomItem::QueryValue(), Wrong MemberId!");
            return sal_False;
    }

    return sal_True;
}

sal_Bool SvxZoomItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
//  sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
    nMemberId &= ~CONVERT_TWIPS;
    switch ( nMemberId )
    {
        case 0 :
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq;
            if (( rVal >>= aSeq ) && ( aSeq.getLength() == ZOOM_PARAMS ))
            {
                sal_Int32 nValueTmp( 0 );
                sal_Int16 nValueSetTmp( 0 );
                sal_Int16 nTypeTmp( 0 );
                sal_Bool  bAllConverted( sal_True );
                sal_Int16 nConvertedCount( 0 );
                for ( sal_Int32 i = 0; i < aSeq.getLength(); i++ )
                {
                    if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUE ))
                    {
                        bAllConverted &= ( aSeq[i].Value >>= nValueTmp );
                        ++nConvertedCount;
                    }
                    else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUESET ))
                    {
                        bAllConverted &= ( aSeq[i].Value >>= nValueSetTmp );
                        ++nConvertedCount;
                    }
                    else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_TYPE ))
                    {
                        bAllConverted &= ( aSeq[i].Value >>= nTypeTmp );
                        ++nConvertedCount;
                    }
                }

                if ( bAllConverted && nConvertedCount == ZOOM_PARAMS )
                {
                    SetValue( (UINT16)nValueTmp );
                    nValueSet = nValueSetTmp;
                    eType = SvxZoomType( nTypeTmp );
                    return sal_True;
                }
            }

            return sal_False;
        }

        case MID_VALUE:
        {
            sal_Int32 nVal = 0;
            if ( rVal >>= nVal )
            {
                SetValue( (UINT16)nVal );
                return sal_True;
            }
            else
                return sal_False;
        }

        case MID_VALUESET:
        case MID_TYPE:
        {
            sal_Int16 nVal = sal_Int16();
            if ( rVal >>= nVal )
            {
                if ( nMemberId == MID_VALUESET )
                    nValueSet = (sal_Int16) nVal;
                else if ( nMemberId == MID_TYPE )
                    eType = SvxZoomType( (sal_Int16) nVal );
                return sal_True;
            }
            else
                return sal_False;
        }

        default:
            DBG_ERROR("svx::SvxZoomItem::PutValue(), Wrong MemberId!");
            return sal_False;
    }

    return sal_True;
}
<commit_msg>INTEGRATION: CWS pchfix04 (1.10.24); FILE MERGED 2007/02/05 12:14:06 os 1.10.24.1: #i73604# usage of ITEMID_* removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: zoomitem.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 14:54: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
 *
 ************************************************************************/

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

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef __SBX_SBXVARIABLE_HXX
#include <basic/sbxvar.hxx>
#endif

#include "zoomitem.hxx"

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

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

TYPEINIT1_FACTORY(SvxZoomItem,SfxUInt16Item, new SvxZoomItem);

#define ZOOM_PARAM_VALUE    "Value"
#define ZOOM_PARAM_VALUESET "ValueSet"
#define ZOOM_PARAM_TYPE     "Type"
#define ZOOM_PARAMS         3

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

SvxZoomItem::SvxZoomItem
(
    SvxZoomType eZoomType,
    sal_uInt16      nVal,
    sal_uInt16      _nWhich
)
:   SfxUInt16Item( _nWhich, nVal ),
    nValueSet( SVX_ZOOM_ENABLE_ALL ),
    eType( eZoomType )
{
}

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

SvxZoomItem::SvxZoomItem( const SvxZoomItem& rOrig )
:   SfxUInt16Item( rOrig.Which(), rOrig.GetValue() ),
    nValueSet( rOrig.GetValueSet() ),
    eType( rOrig.GetType() )
{
}

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

SvxZoomItem::~SvxZoomItem()
{
}

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

SfxPoolItem* SvxZoomItem::Clone( SfxItemPool * /*pPool*/ ) const
{
    return new SvxZoomItem( *this );
}

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

SfxPoolItem* SvxZoomItem::Create( SvStream& rStrm, sal_uInt16 /*nVersion*/ ) const
{
    sal_uInt16 nValue;
    sal_uInt16 nValSet;
    sal_Int8 nType;
    rStrm >> nValue >> nValSet >> nType;
    SvxZoomItem* pNew = new SvxZoomItem( (SvxZoomType)nType, nValue, Which() );
    pNew->SetValueSet( nValSet );
    return pNew;
}

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

SvStream& SvxZoomItem::Store( SvStream& rStrm, sal_uInt16 /*nItemVersion*/ ) const
{
    rStrm << (sal_uInt16)GetValue()
          << nValueSet
          << (sal_Int8)eType;
    return rStrm;
}

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

int SvxZoomItem::operator==( const SfxPoolItem& rAttr ) const
{
    DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );

    SvxZoomItem& rItem = (SvxZoomItem&)rAttr;

    return ( GetValue() == rItem.GetValue()     &&
             nValueSet  == rItem.GetValueSet()  &&
             eType      == rItem.GetType()          );
}

sal_Bool SvxZoomItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
//  sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
    nMemberId &= ~CONVERT_TWIPS;
    switch ( nMemberId )
    {
        case 0 :
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq( ZOOM_PARAMS );
            aSeq[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUE ));
            aSeq[0].Value <<= sal_Int32( GetValue() );
            aSeq[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUESET ));
            aSeq[1].Value <<= sal_Int16( nValueSet );
            aSeq[2].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_TYPE ));
            aSeq[2].Value <<= sal_Int16( eType );
            rVal <<= aSeq;
        }
        break;

        case MID_VALUE: rVal <<= (sal_Int32) GetValue(); break;
        case MID_VALUESET: rVal <<= (sal_Int16) nValueSet; break;
        case MID_TYPE: rVal <<= (sal_Int16) eType; break;
        default:
            DBG_ERROR("svx::SvxZoomItem::QueryValue(), Wrong MemberId!");
            return sal_False;
    }

    return sal_True;
}

sal_Bool SvxZoomItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
//  sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
    nMemberId &= ~CONVERT_TWIPS;
    switch ( nMemberId )
    {
        case 0 :
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq;
            if (( rVal >>= aSeq ) && ( aSeq.getLength() == ZOOM_PARAMS ))
            {
                sal_Int32 nValueTmp( 0 );
                sal_Int16 nValueSetTmp( 0 );
                sal_Int16 nTypeTmp( 0 );
                sal_Bool  bAllConverted( sal_True );
                sal_Int16 nConvertedCount( 0 );
                for ( sal_Int32 i = 0; i < aSeq.getLength(); i++ )
                {
                    if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUE ))
                    {
                        bAllConverted &= ( aSeq[i].Value >>= nValueTmp );
                        ++nConvertedCount;
                    }
                    else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUESET ))
                    {
                        bAllConverted &= ( aSeq[i].Value >>= nValueSetTmp );
                        ++nConvertedCount;
                    }
                    else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_TYPE ))
                    {
                        bAllConverted &= ( aSeq[i].Value >>= nTypeTmp );
                        ++nConvertedCount;
                    }
                }

                if ( bAllConverted && nConvertedCount == ZOOM_PARAMS )
                {
                    SetValue( (UINT16)nValueTmp );
                    nValueSet = nValueSetTmp;
                    eType = SvxZoomType( nTypeTmp );
                    return sal_True;
                }
            }

            return sal_False;
        }

        case MID_VALUE:
        {
            sal_Int32 nVal = 0;
            if ( rVal >>= nVal )
            {
                SetValue( (UINT16)nVal );
                return sal_True;
            }
            else
                return sal_False;
        }

        case MID_VALUESET:
        case MID_TYPE:
        {
            sal_Int16 nVal = sal_Int16();
            if ( rVal >>= nVal )
            {
                if ( nMemberId == MID_VALUESET )
                    nValueSet = (sal_Int16) nVal;
                else if ( nMemberId == MID_TYPE )
                    eType = SvxZoomType( (sal_Int16) nVal );
                return sal_True;
            }
            else
                return sal_False;
        }

        default:
            DBG_ERROR("svx::SvxZoomItem::PutValue(), Wrong MemberId!");
            return sal_False;
    }

    return sal_True;
}
<|endoftext|>


<commit_before>#include <stack>
#include <Refal2.h>

namespace Refal2 {

void PrintRule(const CFunctionRule& rule)
{
	printf("\t");
	if( rule.isRightDirection ) {
		printf("R");
	}
	printf(" ");
	PrintUnitList( rule.leftPart, &rule.variables );
	printf("= ");
	PrintUnitList( rule.rightPart, &rule.variables );
}

void PrintFunction(const CFunction& function)
{
	for( const CFunctionRule* rule = function.firstRule; rule != 0;
		rule = rule->nextRule )
	{
		PrintRule( *rule );
		printf("\n");
	}
}

CFunctionBuilder::CFunctionBuilder(IFunctionBuilderListener* listener):
	CVariablesBuilder( dynamic_cast<IVariablesBuilderListener*>(listener) ),
	CListener<IFunctionBuilderListener>(listener),
	state(FBS_Direction),
	isRightDirection(false),
	firstRule(0),
	lastRule(0)
{
}

void CFunctionBuilder::Reset()
{
	CVariablesBuilder::Reset();
	state = FBS_Direction;
	acc.Empty();
	emptyRules();
	emptyStack();
}

void CFunctionBuilder::Export(CFunction* function)
{
	assert( state == FBS_Direction );

	if( !HasErrors() ) {
		if( firstRule != 0 ) {
			function->SetParsed( &firstRule );
		} else {
			error( FBEC_ThereAreNoRulesInFunction );
		}
	}

	Reset();
}

void CFunctionBuilder::OnErrors()
{
	emptyRules();
	CVariablesBuilder::OnErrors();
}

void CFunctionBuilder::AddDirection(bool _isRightDirection)
{
	assert( state == FBS_Direction );

	isRightDirection = _isRightDirection;
	state = FBS_Left;
}

void CFunctionBuilder::AddEndOfLeft()
{
	assert( state == FBS_Left );

	while( !balanceStack.empty() ) {
		balanceStack.pop();
		error( FBEC_UnclosedLeftParenInLeftPart );
	}

	if( HasErrors() ) {
		acc.Empty();
	} else {
		acc.Move( &leftPart );
	}

	state = FBS_Right;
}

void CFunctionBuilder::AddEndOfRight()
{
	assert( state == FBS_Right );

	while( !balanceStack.empty() ) {
		CUnitNode* unit = balanceStack.top();
		balanceStack.pop();
		error( unit->IsLeftParen() ? FBEC_UnclosedLeftParenInRightPart :
			FBEC_UnclosedLeftBracketInRightPart );
	}

	if( HasErrors() ) {
		acc.Empty();
		CVariablesBuilder::Reset();
	} else {
		addRule();
	}

	state = FBS_Direction;
}

void CFunctionBuilder::AddLeftVariable(TVariableType type, TVariableName name,
	CQualifier* qualifier)
{
	assert( state == FBS_Left );

	TVariableIndex index = CVariablesBuilder::AddLeft( name, type, qualifier );
	if( !HasErrors() ) {
		if( index == InvalidVariableIndex ) {
			SetErrors();
		} else {
			acc.AppendVariable( index );
		}
	}
}

void CFunctionBuilder::AddRightVariable(TVariableType type, TVariableName name)
{
	assert( state == FBS_Right );

	TVariableIndex index = CVariablesBuilder::AddRight( name, type );
	if( !HasErrors() ) {
		if( index == InvalidVariableIndex ) {
			SetErrors();
		} else {
			acc.AppendVariable( index );
		}
	}
}

void CFunctionBuilder::AddLeftParen()
{
	assert( state != FBS_Direction );

	balanceStack.push( acc.AppendLeftParen() );
}

void CFunctionBuilder::AddRightParen()
{
	assert( state != FBS_Direction );

	CUnitNode* leftParen = 0;

	if( !balanceStack.empty() ) {
		leftParen = balanceStack.top();
	}

	if( leftParen != 0 && leftParen->IsLeftParen() ) {
		leftParen->PairedParen() = acc.AppendRightParen(leftParen);
		balanceStack.pop();
	} else {
		error( FBEC_RightParenDoesNotMatchLeftParen );
	}
}

void CFunctionBuilder::AddLeftBracket()
{
	assert( state != FBS_Direction );

	if( state == FBS_Left ) {
		error( FBEC_IllegalLeftBracketInLeftPart );
	} else {
		balanceStack.push( acc.AppendLeftBracket() );
	}
}

void CFunctionBuilder::AddRightBracket()
{
	assert( state != FBS_Direction );

	if( state == FBS_Left ) {
		error( FBEC_IllegalRightBracketInLeftPart );
	} else {
		CUnitNode* leftBracket = 0;

		if( !balanceStack.empty() ) {
			leftBracket = balanceStack.top();
		}

		if( leftBracket != 0 && leftBracket->IsLeftBracket() ) {
			leftBracket->PairedParen() = acc.AppendRightBracket(leftBracket);
			balanceStack.pop();
		} else {
			error( FBEC_RightBracketDoesNotMatchLeftBracket );
		}
	}
}

void CFunctionBuilder::emptyRules()
{
	if( firstRule != 0 ) {
		while( firstRule != 0 ) {
			CFunctionRule* tmp = firstRule;
			firstRule = firstRule->nextRule;
			delete tmp;
		}
	}
	firstRule = 0;
	lastRule = 0;
}

void CFunctionBuilder::addRule()
{
	CFunctionRule* newRule = new CFunctionRule( isRightDirection );
	leftPart.Move( &(newRule->leftPart) );
	acc.Move( &(newRule->rightPart) );
	CVariablesBuilder::Export( &(newRule->variables) );

	if( firstRule != 0 ) {
		lastRule->nextRule = newRule;
		lastRule = lastRule->nextRule;
	} else {
		firstRule = newRule;
		lastRule = firstRule;
	}
}

} // end of namespace refal2
<commit_msg>Debug: dont show variables qualifier in right part<commit_after>#include <stack>
#include <Refal2.h>

namespace Refal2 {

void PrintRule(const CFunctionRule& rule)
{
	printf("\t");
	if( rule.isRightDirection ) {
		printf("R");
	}
	printf(" ");
	PrintUnitList( rule.leftPart, &rule.variables );
	printf("= ");
	PrintUnitList( rule.rightPart );
}

void PrintFunction(const CFunction& function)
{
	for( const CFunctionRule* rule = function.firstRule; rule != 0;
		rule = rule->nextRule )
	{
		PrintRule( *rule );
		printf("\n");
	}
}

CFunctionBuilder::CFunctionBuilder(IFunctionBuilderListener* listener):
	CVariablesBuilder( dynamic_cast<IVariablesBuilderListener*>(listener) ),
	CListener<IFunctionBuilderListener>(listener),
	state(FBS_Direction),
	isRightDirection(false),
	firstRule(0),
	lastRule(0)
{
}

void CFunctionBuilder::Reset()
{
	CVariablesBuilder::Reset();
	state = FBS_Direction;
	acc.Empty();
	emptyRules();
	emptyStack();
}

void CFunctionBuilder::Export(CFunction* function)
{
	assert( state == FBS_Direction );

	if( !HasErrors() ) {
		if( firstRule != 0 ) {
			function->SetParsed( &firstRule );
		} else {
			error( FBEC_ThereAreNoRulesInFunction );
		}
	}

	Reset();
}

void CFunctionBuilder::OnErrors()
{
	emptyRules();
	CVariablesBuilder::OnErrors();
}

void CFunctionBuilder::AddDirection(bool _isRightDirection)
{
	assert( state == FBS_Direction );

	isRightDirection = _isRightDirection;
	state = FBS_Left;
}

void CFunctionBuilder::AddEndOfLeft()
{
	assert( state == FBS_Left );

	while( !balanceStack.empty() ) {
		balanceStack.pop();
		error( FBEC_UnclosedLeftParenInLeftPart );
	}

	if( HasErrors() ) {
		acc.Empty();
	} else {
		acc.Move( &leftPart );
	}

	state = FBS_Right;
}

void CFunctionBuilder::AddEndOfRight()
{
	assert( state == FBS_Right );

	while( !balanceStack.empty() ) {
		CUnitNode* unit = balanceStack.top();
		balanceStack.pop();
		error( unit->IsLeftParen() ? FBEC_UnclosedLeftParenInRightPart :
			FBEC_UnclosedLeftBracketInRightPart );
	}

	if( HasErrors() ) {
		acc.Empty();
		CVariablesBuilder::Reset();
	} else {
		addRule();
	}

	state = FBS_Direction;
}

void CFunctionBuilder::AddLeftVariable(TVariableType type, TVariableName name,
	CQualifier* qualifier)
{
	assert( state == FBS_Left );

	TVariableIndex index = CVariablesBuilder::AddLeft( name, type, qualifier );
	if( !HasErrors() ) {
		if( index == InvalidVariableIndex ) {
			SetErrors();
		} else {
			acc.AppendVariable( index );
		}
	}
}

void CFunctionBuilder::AddRightVariable(TVariableType type, TVariableName name)
{
	assert( state == FBS_Right );

	TVariableIndex index = CVariablesBuilder::AddRight( name, type );
	if( !HasErrors() ) {
		if( index == InvalidVariableIndex ) {
			SetErrors();
		} else {
			acc.AppendVariable( index );
		}
	}
}

void CFunctionBuilder::AddLeftParen()
{
	assert( state != FBS_Direction );

	balanceStack.push( acc.AppendLeftParen() );
}

void CFunctionBuilder::AddRightParen()
{
	assert( state != FBS_Direction );

	CUnitNode* leftParen = 0;

	if( !balanceStack.empty() ) {
		leftParen = balanceStack.top();
	}

	if( leftParen != 0 && leftParen->IsLeftParen() ) {
		leftParen->PairedParen() = acc.AppendRightParen(leftParen);
		balanceStack.pop();
	} else {
		error( FBEC_RightParenDoesNotMatchLeftParen );
	}
}

void CFunctionBuilder::AddLeftBracket()
{
	assert( state != FBS_Direction );

	if( state == FBS_Left ) {
		error( FBEC_IllegalLeftBracketInLeftPart );
	} else {
		balanceStack.push( acc.AppendLeftBracket() );
	}
}

void CFunctionBuilder::AddRightBracket()
{
	assert( state != FBS_Direction );

	if( state == FBS_Left ) {
		error( FBEC_IllegalRightBracketInLeftPart );
	} else {
		CUnitNode* leftBracket = 0;

		if( !balanceStack.empty() ) {
			leftBracket = balanceStack.top();
		}

		if( leftBracket != 0 && leftBracket->IsLeftBracket() ) {
			leftBracket->PairedParen() = acc.AppendRightBracket(leftBracket);
			balanceStack.pop();
		} else {
			error( FBEC_RightBracketDoesNotMatchLeftBracket );
		}
	}
}

void CFunctionBuilder::emptyRules()
{
	if( firstRule != 0 ) {
		while( firstRule != 0 ) {
			CFunctionRule* tmp = firstRule;
			firstRule = firstRule->nextRule;
			delete tmp;
		}
	}
	firstRule = 0;
	lastRule = 0;
}

void CFunctionBuilder::addRule()
{
	CFunctionRule* newRule = new CFunctionRule( isRightDirection );
	leftPart.Move( &(newRule->leftPart) );
	acc.Move( &(newRule->rightPart) );
	CVariablesBuilder::Export( &(newRule->variables) );

	if( firstRule != 0 ) {
		lastRule->nextRule = newRule;
		lastRule = lastRule->nextRule;
	} else {
		firstRule = newRule;
		lastRule = firstRule;
	}
}

} // end of namespace refal2
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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 _SVDFMTF_HXX
#define _SVDFMTF_HXX

#include <tools/contnr.hxx>
#include <vcl/metaact.hxx>
#include <vcl/virdev.hxx>
#include <svx/svdobj.hxx>

//************************************************************
// Forward Declarations
//************************************************************

class SfxItemSet;
class SdrObjList;
class SdrModel;
class SdrPage;
class SdrObject;
class SvdProgressInfo;

//************************************************************
// Helper Class SdrObjRefList
//************************************************************

class SdrObjRefList
{
    Container                   aList;
public:

    SdrObjRefList()
    :   aList(1024,64,64)
    {}

    void Clear() { aList.Clear(); }
    sal_uLong GetObjCount() const { return aList.Count(); }
    SdrObject* GetObj(sal_uLong nNum) const { return (SdrObject*)aList.GetObject(nNum); }
    SdrObject* operator[](sal_uLong nNum) const { return (SdrObject*)aList.GetObject(nNum); }
    void InsertObject(SdrObject* pObj, sal_uLong nPos=CONTAINER_APPEND) { aList.Insert(pObj,nPos); }
    void RemoveObject(sal_uLong nPos) { aList.Remove(nPos); }
};

//************************************************************
// Helper Class ImpSdrGDIMetaFileImport
//************************************************************

class ImpSdrGDIMetaFileImport
{
protected:
    SdrObjRefList               aTmpList;
    VirtualDevice               aVD;
    Rectangle                   aScaleRect;
    sal_uLong                       nMapScalingOfs; // from here on, not edited with MapScaling
    SfxItemSet*                 pLineAttr;
    SfxItemSet*                 pFillAttr;
    SfxItemSet*                 pTextAttr;
    SdrPage*                    pPage;
    SdrModel*                   pModel;
    SdrLayerID                  nLayer;
    Color                       aOldLineColor;
    sal_Int32                   nLineWidth;
    basegfx::B2DLineJoin        maLineJoin;
    XDash                       maDash;

    sal_Bool                    bMov;
    sal_Bool                    bSize;
    Point                       aOfs;
    double                      fScaleX;
    double                      fScaleY;
    Fraction                    aScaleX;
    Fraction                    aScaleY;

    sal_Bool                    bFntDirty;

    // to optimize (PenNULL,Brush,DrawPoly),(Pen,BrushNULL,DrawPoly) -> two-in-one
    sal_Bool                    bLastObjWasPolyWithoutLine;
    sal_Bool                    bNoLine;
    sal_Bool                    bNoFill;

    // to optimize multiple lines into a Polyline
    sal_Bool                    bLastObjWasLine;

protected:
    void DoAction(MetaPixelAction           & rAct) const;
    void DoAction(MetaPointAction           & rAct) const;
    void DoAction(MetaLineAction            & rAct);
    void DoAction(MetaRectAction            & rAct);
    void DoAction(MetaRoundRectAction       & rAct);
    void DoAction(MetaEllipseAction         & rAct);
    void DoAction(MetaArcAction             & rAct);
    void DoAction(MetaPieAction             & rAct);
    void DoAction(MetaChordAction           & rAct);
    void DoAction(MetaPolyLineAction        & rAct);
    void DoAction(MetaPolygonAction         & rAct);
    void DoAction(MetaPolyPolygonAction     & rAct);
    void DoAction(MetaTextAction            & rAct);
    void DoAction(MetaTextArrayAction       & rAct);
    void DoAction(MetaStretchTextAction     & rAct);
    void DoAction(MetaBmpAction             & rAct);
    void DoAction(MetaBmpScaleAction        & rAct);
    void DoAction(MetaBmpExAction           & rAct);
    void DoAction(MetaBmpExScaleAction      & rAct);
    void DoAction(MetaHatchAction           & rAct);
    void DoAction(MetaLineColorAction       & rAct);
    void DoAction(MetaMapModeAction         & rAct);
    void DoAction(MetaFillColorAction       & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaTextColorAction       & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaTextFillColorAction   & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaFontAction            & rAct) { rAct.Execute(&aVD); bFntDirty=sal_True; }
    void DoAction(MetaTextAlignAction       & rAct) { rAct.Execute(&aVD); bFntDirty=sal_True; }
    void DoAction(MetaClipRegionAction      & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaRasterOpAction        & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaPushAction            & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaPopAction             & rAct) { rAct.Execute(&aVD); bFntDirty=sal_True; }
    void DoAction(MetaMoveClipRegionAction  & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaISectRectClipRegionAction& rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaISectRegionClipRegionAction& rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaCommentAction& rAct, GDIMetaFile* pMtf);
    void DoAction(MetaRenderGraphicAction& rAct);

    void ImportText( const Point& rPos, const XubString& rStr, const MetaAction& rAct );
    void SetAttributes(SdrObject* pObj, bool bForceTextAttr = false);
    void InsertObj( SdrObject* pObj, sal_Bool bScale = sal_True );
    void MapScaling();

    // #i73407# reformulation to use new B2DPolygon classes
    bool CheckLastLineMerge(const basegfx::B2DPolygon& rSrcPoly);
    bool CheckLastPolyLineAndFillMerge(const basegfx::B2DPolyPolygon& rPolyPolygon);

public:
    ImpSdrGDIMetaFileImport(SdrModel& rModel);
    ~ImpSdrGDIMetaFileImport();
    sal_uLong DoImport(const GDIMetaFile& rMtf, SdrObjList& rDestList, sal_uLong nInsPos=CONTAINER_APPEND, SvdProgressInfo *pProgrInfo = NULL);
    void SetLayer(SdrLayerID nLay) { nLayer=nLay; }
    SdrLayerID GetLayer() const { return nLayer; }
    void SetScaleRect(const Rectangle& rRect) { aScaleRect=rRect; }
    const Rectangle& GetScaleRect() const { return aScaleRect; }
};

#endif //_SVDFMTF_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Convert aList in SdrObjRefList class from Container to std::vector<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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 _SVDFMTF_HXX
#define _SVDFMTF_HXX

#include <tools/contnr.hxx>
#include <vcl/metaact.hxx>
#include <vcl/virdev.hxx>
#include <svx/svdobj.hxx>

//************************************************************
// Forward Declarations
//************************************************************

class SfxItemSet;
class SdrObjList;
class SdrModel;
class SdrPage;
class SdrObject;
class SvdProgressInfo;

//************************************************************
// Helper Class SdrObjRefList
//************************************************************

class SdrObjRefList
{
    std::vector<SdrObject*>            aList;
public:

    SdrObjRefList()
    :   aList()
    {}

    void Clear() { aList.clear(); }
    sal_uLong GetObjCount() const { return aList.size(); }
    SdrObject* GetObj(sal_uLong nNum) const { return aList[nNum]; }
    SdrObject* operator[](sal_uLong nNum) const { return aList[nNum]; }
    void InsertObject(SdrObject* pObj) { aList.push_back(pObj); }
    void InsertObject(SdrObject* pObj, sal_uLong nPos)
    {
        if(nPos==CONTAINER_APPEND)
            aList.push_back(pObj);
        else
            aList.insert(aList.begin() + nPos, pObj);
    }
    void RemoveObject(sal_uLong nPos) { aList.erase(aList.begin()+nPos); }
};

//************************************************************
// Helper Class ImpSdrGDIMetaFileImport
//************************************************************

class ImpSdrGDIMetaFileImport
{
protected:
    SdrObjRefList               aTmpList;
    VirtualDevice               aVD;
    Rectangle                   aScaleRect;
    sal_uLong                       nMapScalingOfs; // from here on, not edited with MapScaling
    SfxItemSet*                 pLineAttr;
    SfxItemSet*                 pFillAttr;
    SfxItemSet*                 pTextAttr;
    SdrPage*                    pPage;
    SdrModel*                   pModel;
    SdrLayerID                  nLayer;
    Color                       aOldLineColor;
    sal_Int32                   nLineWidth;
    basegfx::B2DLineJoin        maLineJoin;
    XDash                       maDash;

    sal_Bool                    bMov;
    sal_Bool                    bSize;
    Point                       aOfs;
    double                      fScaleX;
    double                      fScaleY;
    Fraction                    aScaleX;
    Fraction                    aScaleY;

    sal_Bool                    bFntDirty;

    // to optimize (PenNULL,Brush,DrawPoly),(Pen,BrushNULL,DrawPoly) -> two-in-one
    sal_Bool                    bLastObjWasPolyWithoutLine;
    sal_Bool                    bNoLine;
    sal_Bool                    bNoFill;

    // to optimize multiple lines into a Polyline
    sal_Bool                    bLastObjWasLine;

protected:
    void DoAction(MetaPixelAction           & rAct) const;
    void DoAction(MetaPointAction           & rAct) const;
    void DoAction(MetaLineAction            & rAct);
    void DoAction(MetaRectAction            & rAct);
    void DoAction(MetaRoundRectAction       & rAct);
    void DoAction(MetaEllipseAction         & rAct);
    void DoAction(MetaArcAction             & rAct);
    void DoAction(MetaPieAction             & rAct);
    void DoAction(MetaChordAction           & rAct);
    void DoAction(MetaPolyLineAction        & rAct);
    void DoAction(MetaPolygonAction         & rAct);
    void DoAction(MetaPolyPolygonAction     & rAct);
    void DoAction(MetaTextAction            & rAct);
    void DoAction(MetaTextArrayAction       & rAct);
    void DoAction(MetaStretchTextAction     & rAct);
    void DoAction(MetaBmpAction             & rAct);
    void DoAction(MetaBmpScaleAction        & rAct);
    void DoAction(MetaBmpExAction           & rAct);
    void DoAction(MetaBmpExScaleAction      & rAct);
    void DoAction(MetaHatchAction           & rAct);
    void DoAction(MetaLineColorAction       & rAct);
    void DoAction(MetaMapModeAction         & rAct);
    void DoAction(MetaFillColorAction       & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaTextColorAction       & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaTextFillColorAction   & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaFontAction            & rAct) { rAct.Execute(&aVD); bFntDirty=sal_True; }
    void DoAction(MetaTextAlignAction       & rAct) { rAct.Execute(&aVD); bFntDirty=sal_True; }
    void DoAction(MetaClipRegionAction      & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaRasterOpAction        & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaPushAction            & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaPopAction             & rAct) { rAct.Execute(&aVD); bFntDirty=sal_True; }
    void DoAction(MetaMoveClipRegionAction  & rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaISectRectClipRegionAction& rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaISectRegionClipRegionAction& rAct) { rAct.Execute(&aVD); }
    void DoAction(MetaCommentAction& rAct, GDIMetaFile* pMtf);
    void DoAction(MetaRenderGraphicAction& rAct);

    void ImportText( const Point& rPos, const XubString& rStr, const MetaAction& rAct );
    void SetAttributes(SdrObject* pObj, bool bForceTextAttr = false);
    void InsertObj( SdrObject* pObj, sal_Bool bScale = sal_True );
    void MapScaling();

    // #i73407# reformulation to use new B2DPolygon classes
    bool CheckLastLineMerge(const basegfx::B2DPolygon& rSrcPoly);
    bool CheckLastPolyLineAndFillMerge(const basegfx::B2DPolyPolygon& rPolyPolygon);

public:
    ImpSdrGDIMetaFileImport(SdrModel& rModel);
    ~ImpSdrGDIMetaFileImport();
    sal_uLong DoImport(const GDIMetaFile& rMtf, SdrObjList& rDestList, sal_uLong nInsPos=CONTAINER_APPEND, SvdProgressInfo *pProgrInfo = NULL);
    void SetLayer(SdrLayerID nLay) { nLayer=nLay; }
    SdrLayerID GetLayer() const { return nLayer; }
    void SetScaleRect(const Rectangle& rRect) { aScaleRect=rRect; }
    const Rectangle& GetScaleRect() const { return aScaleRect; }
};

#endif //_SVDFMTF_HXX

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