<commit_before>/*
 * Part of Jari Komppa's zx spectrum suite
 * https://github.com/jarikomppa/speccy
 * released under the unlicense, see http://unlicense.org
 * (practically public domain)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

void fprintbin(FILE *f, int val)
{
    fprintf(f, "0b%d%d%d%d%d%d%d%d",
        (val & (1 << 7)) != 0,
        (val & (1 << 6)) != 0,
        (val & (1 << 5)) != 0,
        (val & (1 << 4)) != 0,
        (val & (1 << 3)) != 0,
        (val & (1 << 2)) != 0,
        (val & (1 << 1)) != 0,
        (val & (1 << 0)) != 0);
}

unsigned int spritedata[64];
unsigned int spritemask[64];

int main(int parc, char ** pars)
{
    int x, y, comp;
    memset(spritedata,0,sizeof(int)*64);
    memset(spritemask,0,sizeof(int)*64);
    if (parc < 3)
    {
        printf("Usage: %s pngfile outfile\n", pars[0]);
        return 0;
    }
    stbi_uc * raw = stbi_load(pars[1], &x, &y, &comp, 4);
    printf("%s - %d %d %d\n", pars[1], x, y, comp);
    unsigned int *p = (unsigned int *)raw;

    int i, j, c;
    for (i = 0, c = 0; i < y; i++)
    {
        int d = 0;
        int m = 0;
        int xout = 0;
        for (j = 0; j < x; j++, c++)
        {
            d <<= 1;
            d |= (p[c] == 0xffffffff) != 0;
            m <<= 1;
            m |= (p[c] == 0xffffffff || p[c] == 0xff000000) == 1;
            if (j % 8 == 7)
            {
                spritedata[i] |= d << ((3 - xout) * 8);
                spritemask[i] |= m << ((3 - xout) * 8);
                m = 0;
                d = 0;
                xout++;
            }
        }
    }

    FILE * f = fopen(pars[2],"w");

/*
void drawsprite(short aX, short aY)
{
    aData; aX; aY;

    __asm
        push ix
    	ld	ix,#0
    	add	ix,sp

        push iy
        push hl
        push bc
        push de

        ld d, 7 (ix) ; aY
        ld e, 6 (ix)
        ld hl, #(_yofs)
        add hl, de
        add hl, de
        push hl
        pop iy

        ld h, 5 (ix) ; aX
        ld l, 4 (ix)
        ; divide aX by 8
        srl h
        rr l
        srl h
        rr l
        srl h
        rr l
        push hl
        pop bc

#define HPASS  \
        ld a, (hl)  \
        and XX    \
        or XX     \
        ld (hl),a   \
        inc hl      \
                    \
        ld a, (hl)  \
        and XX    \
        or XX     \
        ld (hl),a   \
        inc hl      \
                    \
        ld a, (hl)  \
        and XX    \
        or XX     \
        ld (hl),a   \
        inc hl

        ld l, 0 (iy)
        ld h, 1 (iy)
        add hl, bc
        HPASS
        ld l, 2 (iy)
        ld h, 3 (iy)
        add hl, bc
        HPASS
...
        ld l, 30 (iy)
        ld h, 31 (iy)
        add hl, bc
        HPASS
#undef HPASS
        pop de
        pop bc
        pop hl
        pop iy
        pop ix
    __endasm;
}

*/

    int shift;
    for (shift = 0; shift < 8; shift++)
    {
        fprintf(f,
        "void drawsprite_bubble_%d(short aX, short aY)\n"
        "{\n"
        "  aX; aY;\n", shift);

        fprintf(f,
    "__asm\n"
    "    push ix\n"
    " 	ld	ix,#0\n"
    "	add	ix,sp\n"
    "\n"
    "   push iy\n"
    "   push hl\n"
    "   push bc\n"
    "   push de\n"
    "\n"
    "    ld d, 7 (ix) ; aY\n"
    "    ld e, 6 (ix) \n"
    "    ld hl, #(_yofs)\n"
    "    add hl, de\n"
    "    add hl, de\n"
    "    push hl\n"
    "    pop iy\n"
    "\n"
    "    ld h, 5 (ix) ; aX\n"
    "    ld l, 4 (ix)\n"
    "    ; divide aX by 8\n"
    "    srl h\n"
    "    rr l\n"
    "    srl h\n"
    "    rr l\n"
    "    srl h\n"
    "    rr l\n"
    "    push hl\n"
    "    pop bc\n"
    "\n");

        for (i = 0; i < y; i++)
        {
            fprintf(f,
            "\n"
            "    ld l, %d (iy)\n"
            "    ld h, %d (iy)\n"
            "    add hl, bc\n", i*2, i*2 + 1);
            for (j = 0; j < (x/8)+1; j++)
            {
                int andval = (~((spritemask[i]) >> shift) >> (8 * (3 - j))) & 0xff;
                int orval = ((spritedata[i] >> shift) >> (8 * (3 - j))) & 0xff;
                if (andval == 0)
                {
                    fprintf(f,"    ld (hl), #%d ; 100%% mask shortcut\n", orval);
                }
                else
                {
                    if (andval!=255) fprintf(f,"    ld a, (hl)\n"); //else fprintf(f,"; skip - andval=255\n");
                    if (andval!=255) fprintf(f,"    and #%d\n", andval); //else fprintf(f,"; skip - andval=255\n");
                    if (orval)       fprintf(f,"    or #%d\n", orval); //else fprintf(f,"; skip - orval=0\n");
                    if (andval!=255) fprintf(f,"    ld (hl), a\n");  //else fprintf(f,"; skip - andval=255\n");
                }
                // find out if this span has more live masks
                // (this could be done in a less heavy-handed way, but, meh)
                int k, n = 0;
                for (k = j+1; k < (x/8)+1; k++)
                {
                    int andval = (~((spritemask[k]) >> shift) >> (8 * (3 - k))) & 0xff;
                    if (andval != 255)
                        {
                        n = 1;
                        //fprintf(f,"; found future span j=%d k=%d andval=%d spritemask=%0x\n", j, k, andval, spritemask[k]);
                    }
                }
                if (n)               fprintf(f,"    inc hl\n");
            }
        }
        fprintf(f,
        "\n"
        "    pop de\n"
        "    pop bc\n"
        "    pop hl\n"
        "    pop iy\n"
        "    pop ix\n"
        "__endasm;\n"
        "}\n"
        "\n");
    }

    fprintf(f,
    "void drawsprite_bubble(short aX, short aY)\n"
    "{\n"
    "  switch (aX & 7)\n"
    "  {\n"
    "  case 0: drawsprite_bubble_0(aX, aY); break; \n"
    "  case 1: drawsprite_bubble_1(aX, aY); break; \n"
    "  case 2: drawsprite_bubble_2(aX, aY); break; \n"
    "  case 3: drawsprite_bubble_3(aX, aY); break; \n"
    "  case 4: drawsprite_bubble_4(aX, aY); break; \n"
    "  case 5: drawsprite_bubble_5(aX, aY); break; \n"
    "  case 6: drawsprite_bubble_6(aX, aY); break; \n"
    "  case 7: drawsprite_bubble_7(aX, aY); break; \n"
    "  }\n"
    "}\n"
    "\n");
   fclose(f);
    return 0;
}<commit_msg>Abusing the stack, we shave about 28 clocks per span.<commit_after>/*
 * Part of Jari Komppa's zx spectrum suite
 * https://github.com/jarikomppa/speccy
 * released under the unlicense, see http://unlicense.org
 * (practically public domain)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

void fprintbin(FILE *f, int val)
{
    fprintf(f, "0b%d%d%d%d%d%d%d%d",
        (val & (1 << 7)) != 0,
        (val & (1 << 6)) != 0,
        (val & (1 << 5)) != 0,
        (val & (1 << 4)) != 0,
        (val & (1 << 3)) != 0,
        (val & (1 << 2)) != 0,
        (val & (1 << 1)) != 0,
        (val & (1 << 0)) != 0);
}

unsigned int spritedata[64];
unsigned int spritemask[64];

int main(int parc, char ** pars)
{
    int x, y, comp;
    memset(spritedata,0,sizeof(int)*64);
    memset(spritemask,0,sizeof(int)*64);
    if (parc < 3)
    {
        printf("Usage: %s pngfile outfile\n", pars[0]);
        return 0;
    }
    stbi_uc * raw = stbi_load(pars[1], &x, &y, &comp, 4);
    printf("%s - %d %d %d\n", pars[1], x, y, comp);
    unsigned int *p = (unsigned int *)raw;

    int i, j, c;
    for (i = 0, c = 0; i < y; i++)
    {
        int d = 0;
        int m = 0;
        int xout = 0;
        for (j = 0; j < x; j++, c++)
        {
            d <<= 1;
            d |= (p[c] == 0xffffffff) != 0;
            m <<= 1;
            m |= (p[c] == 0xffffffff || p[c] == 0xff000000) == 1;
            if (j % 8 == 7)
            {
                spritedata[i] |= d << ((3 - xout) * 8);
                spritemask[i] |= m << ((3 - xout) * 8);
                m = 0;
                d = 0;
                xout++;
            }
        }
    }

    FILE * f = fopen(pars[2],"w");

/*
void drawsprite(short aX, short aY)
{
    aData; aX; aY;

    __asm
        push ix
    	ld	ix,#0
    	add	ix,sp

        push iy
        push hl
        push bc
        push de

        ld d, 7 (ix) ; aY
        ld e, 6 (ix)
        ld hl, #(_yofs)
        add hl, de
        add hl, de
        push hl
        pop iy

        ld h, 5 (ix) ; aX
        ld l, 4 (ix)
        ; divide aX by 8
        srl h
        rr l
        srl h
        rr l
        srl h
        rr l
        push hl
        pop bc

#define HPASS  \
        ld a, (hl)  \
        and XX    \
        or XX     \
        ld (hl),a   \
        inc hl      \
                    \
        ld a, (hl)  \
        and XX    \
        or XX     \
        ld (hl),a   \
        inc hl      \
                    \
        ld a, (hl)  \
        and XX    \
        or XX     \
        ld (hl),a   \
        inc hl

        ld l, 0 (iy)
        ld h, 1 (iy)
        add hl, bc
        HPASS
        ld l, 2 (iy)
        ld h, 3 (iy)
        add hl, bc
        HPASS
...
        ld l, 30 (iy)
        ld h, 31 (iy)
        add hl, bc
        HPASS
#undef HPASS
        pop de
        pop bc
        pop hl
        pop iy
        pop ix
    __endasm;
}

*/

    int shift;
    for (shift = 0; shift < 8; shift++)
    {
        fprintf(f,
        "void drawsprite_bubble_%d(short aX, short aY)\n"
        "{\n"
        "  aX; aY;\n", shift);

        fprintf(f,
    "__asm\n"
    "    push ix\n"
    "    push iy\n"
    "    push hl\n"
    "    push bc\n"
    "    push de\n"
    "\n"
    " 	 ld	ix,#0 ; set up ix to point at stack\n"
    "	 add ix,sp\n"
    "\n"
    "    ld d, 15 (ix) ; aY\n"
    "    ld e, 14 (ix) \n"
    "    ld hl, #(_yofs)\n"
    "    add hl, de\n"
    "    add hl, de\n"
    "    push hl\n"
    "    pop iy\n"
    "\n"
    "    ld h, 13 (ix) ; aX\n"
    "    ld l, 12 (ix)\n"
    "\n"
    "    ; divide aX by 8\n"
    "    srl h\n"
    "    rr l\n"
    "    srl h\n"
    "    rr l\n"
    "    srl h\n"
    "    rr l\n"
    "    push hl\n"
    "    pop bc\n"
    "\n"
    "    ld sp, iy ; set stack to point at yofs table\n"
    "\n; Setup done");

        for (i = 0; i < y; i++)
        {
            fprintf(f,
            "\n"
            "    pop hl ; load y offset\n"
            //"    ld l, %d (iy) ; load y offset\n"
            //"    ld h, %d (iy)\n"
            "    add hl, bc ; add x-offset\n");//, i*2, i*2 + 1);
            for (j = 0; j < (x/8)+1; j++)
            {
                int andval = (~((spritemask[i]) >> shift) >> (8 * (3 - j))) & 0xff;
                int orval = ((spritedata[i] >> shift) >> (8 * (3 - j))) & 0xff;
                if (andval == 0)
                {
                    fprintf(f,"    ld (hl), #%d ; shortcut: background completely masked\n", orval);
                }
                else
                if (andval != 255)
                {
                                     fprintf(f,"    ld a, (hl)\n");
                                     fprintf(f,"    and #%d\n", andval);
                    if (orval)       fprintf(f,"    or #%d\n", orval); else fprintf(f,"; skip or:ing since value was 0\n");
                                     fprintf(f,"    ld (hl), a\n");
                }
                else
                {
                    fprintf(f,"; skip, background completely visible\n");
                }
                // find out if this span has more live masks
                // (this could be done in a less heavy-handed way, but, meh)
                int k, n = 0;
                for (k = j+1; k < (x/8)+1; k++)
                {
                    int andval = (~((spritemask[i]) >> shift) >> (8 * (3 - k))) & 0xff;
                    if (andval != 255)
                        {
                        n = 1;
                        //fprintf(f,"; found future span j=%d k=%d andval=%d spritemask=%0x\n", j, k, andval, spritemask[k]);
                    }
                }
                if (n)               fprintf(f,"    inc hl\n");
            }
        }
        fprintf(f,
        "\n"
        "    ld sp, ix ; Restore stack pointer\n"
        "    pop de\n"
        "    pop bc\n"
        "    pop hl\n"
        "    pop iy\n"
        "    pop ix\n"
        "__endasm;\n"
        "}\n"
        "\n");
    }

    fprintf(f,
    "void drawsprite_bubble(short aX, short aY)\n"
    "{\n"
    "  switch (aX & 7)\n"
    "  {\n"
    "  case 0: drawsprite_bubble_0(aX, aY); break; \n"
    "  case 1: drawsprite_bubble_1(aX, aY); break; \n"
    "  case 2: drawsprite_bubble_2(aX, aY); break; \n"
    "  case 3: drawsprite_bubble_3(aX, aY); break; \n"
    "  case 4: drawsprite_bubble_4(aX, aY); break; \n"
    "  case 5: drawsprite_bubble_5(aX, aY); break; \n"
    "  case 6: drawsprite_bubble_6(aX, aY); break; \n"
    "  case 7: drawsprite_bubble_7(aX, aY); break; \n"
    "  }\n"
    "}\n"
    "\n");
   fclose(f);
    return 0;
}<|endoftext|>


<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CONCURRENT_SOFI_HPP
#define IOX_HOOFS_CONCURRENT_SOFI_HPP

#include "iceoryx_hoofs/platform/platform_correction.hpp"

#include <atomic>
#include <cstdint>
#include <cstring>

namespace iox
{
namespace concurrent
{
/// @brief
/// Thread safe producer and consumer queue with a safe overflowing behavior.
/// SoFi is designed in a FIFO Manner but prevents data loss when pushing into
/// a full SoFi. When SoFi is full and a Sender tries to push, the data at the
/// current read position will be returned. SoFi is a Thread safe without using
/// locks. When the buffer is filled, new data is written starting at the
/// beginning of the buffer and overwriting the old.The SoFi is especially
/// designed to provide fixed capacity storage. When its capacity is exhausted,
/// newly inserted elements will cause elements either at the beginning
/// to be overwritten.The SoFi only allocates memory when
/// created , capacity can be is adjusted explicitly.
///
/// @param[in] ValueType        DataType to be stored, must be trivially copyable
/// @param[in] CapacityValue    Capacity of the SoFi
template <class ValueType, uint64_t CapacityValue>
class SoFi
{
    static_assert(std::is_trivially_copyable<ValueType>::value, "SoFi can handle only trivially copyable data types");
    /// @brief Check if Atomic integer is lockfree on platform
    /// ATOMIC_INT_LOCK_FREE = 2 - is always lockfree
    /// ATOMIC_INT_LOCK_FREE = 1 - is sometimes lockfree
    /// ATOMIC_INT_LOCK_FREE = 0 - is never lockfree
    static_assert(2 <= ATOMIC_INT_LOCK_FREE, "SoFi is not able to run lock free on this data type");

    /// @brief Internal size needs to be bigger than the size desirred by the user
    /// This is because of buffer empty detection and overflow handling
    static constexpr uint32_t INTERNAL_SIZE_ADD_ON = 1;

    /// @brief This is the resulting internal size on creation
    static constexpr uint32_t INTERNAL_SOFI_SIZE = CapacityValue + INTERNAL_SIZE_ADD_ON;

  public:
    /// @brief default constructor which constructs an empty sofi
    SoFi() noexcept;

    /// @brief pushs an element into sofi. if sofi is full the oldest data will be
    ///         returned and the pushed element is stored in its place instead.
    /// @param[in] valueOut value which should be stored
    /// @param[out] f_paramOut_r if sofi is overflowing  the value of the overridden value
    ///                            is stored here
    /// @concurrent restricted thread safe: single pop, single push no
    ///             push calls from multiple contexts
    /// @return return true if push was sucessfull else false.
    /// @code
    /// (initial situation, SOFI is FULL)
    ///     Start|-----A-------|
    ///                        |-----B-------|
    ///                                      |-----C-------|
    ///                                                    |-----D-------|
    ///
    ///
    /// (calling push with data ’E’)
    ///     Start|-----E-------|
    ///                        |-----A-------|
    ///                                      |-----B-------|
    ///                                                    |-----C-------|
    ///                                     (’D’ is returned as value_out)
    ///
    ///###################################################################
    ///
    /// (if SOFI is not FULL , calling push() add new data)
    ///     Start|-------------|
    ///                        |-------------|  ( Initial SOFI )
    ///  (push() Called two times)
    ///
    ///                                      |-------------|
    ///                                      (New Data)
    ///                                                     |-------------|
    ///                                                      (New Data)
    /// @endcode
    bool push(const ValueType& valueOut, ValueType& f_paramOut_r) noexcept;

    /// @brief pop the oldest element
    /// @param[out] valueOut storage of the pop'ed value
    /// @concurrent restricted thread safe: single pop, single push no
    ///             pop or popIf calls from multiple contexts
    /// @return false if sofi is empty, otherwise true
    bool pop(ValueType& valueOut) noexcept;

    /// @brief conditional pop call to provide an alternative for a peek
    ///         and pop approach. If the verificator returns true the
    ///         peeked element is returned.
    /// @param[out] valueOut storage of the pop'ed value
    /// @param[in] verificator callable of type bool(const ValueType& peekValue)
    ///             which takes the value which would be pop'ed as argument and returns
    ///             true if it should be pop'ed, otherwise false
    /// @code
    ///     int limit = 7128;
    ///     mysofi.popIf(value, [=](const ValueType & peek)
    ///         {
    ///             return peek < limit; // pop only when peek is smaller than limit
    ///         }
    ///     ); // pop's a value only if it is smaller than 9012
    /// @endcode
    /// @concurrent restricted thread safe: single pop, single push no
    ///             pop or popIf calls from multiple contexts
    /// @return false if sofi is empty or when verificator returns false, otherwise true
    template <typename Verificator_T>
    bool popIf(ValueType& valueOut, const Verificator_T& verificator) noexcept;

    /// @brief returns true if sofi is empty, otherwise false
    /// @note the use of this function is limited in the concurrency case. if you
    ///         call this and in another thread pop is called the result can be out
    ///         of date as soon as you require it
    /// @concurrent unrestricted thread safe
    bool empty() const noexcept;

    /// @brief resizes sofi
    /// @param[in] newSize valid values are 0 < newSize < CapacityValue
    /// @pre it is important that no pop or push calls occur during
    ///         this call
    /// @concurrent not thread safe
    bool setCapacity(const uint64_t newSize) noexcept;

    /// @brief returns the capacity of sofi
    /// @concurrent unrestricted thread safe
    uint64_t capacity() const noexcept;

    /// @brief returns the current size of sofi
    /// @concurrent unrestricted thread safe
    uint64_t size() const noexcept;

  private:
    ValueType m_data[INTERNAL_SOFI_SIZE];
    uint64_t m_size = INTERNAL_SOFI_SIZE;

    /// @brief the write/read pointers are "atomic pointers" so that they are not
    /// reordered (read or written too late)
    std::atomic<uint64_t> m_readPosition{0u};
    std::atomic<uint64_t> m_writePosition{0u};
};

} // namespace concurrent
} // namespace iox

#include "iceoryx_hoofs/internal/concurrent/sofi.inl"

#endif // IOX_HOOFS_CONCURRENT_SOFI_HPP
<commit_msg>iox-#831 Add type trait include for GCC 5.4<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CONCURRENT_SOFI_HPP
#define IOX_HOOFS_CONCURRENT_SOFI_HPP

#include "iceoryx_hoofs/cxx/type_traits.hpp"
#include "iceoryx_hoofs/platform/platform_correction.hpp"

#include <atomic>
#include <cstdint>
#include <cstring>

namespace iox
{
namespace concurrent
{
/// @brief
/// Thread safe producer and consumer queue with a safe overflowing behavior.
/// SoFi is designed in a FIFO Manner but prevents data loss when pushing into
/// a full SoFi. When SoFi is full and a Sender tries to push, the data at the
/// current read position will be returned. SoFi is a Thread safe without using
/// locks. When the buffer is filled, new data is written starting at the
/// beginning of the buffer and overwriting the old.The SoFi is especially
/// designed to provide fixed capacity storage. When its capacity is exhausted,
/// newly inserted elements will cause elements either at the beginning
/// to be overwritten.The SoFi only allocates memory when
/// created , capacity can be is adjusted explicitly.
///
/// @param[in] ValueType        DataType to be stored, must be trivially copyable
/// @param[in] CapacityValue    Capacity of the SoFi
template <class ValueType, uint64_t CapacityValue>
class SoFi
{
    static_assert(std::is_trivially_copyable<ValueType>::value, "SoFi can handle only trivially copyable data types");
    /// @brief Check if Atomic integer is lockfree on platform
    /// ATOMIC_INT_LOCK_FREE = 2 - is always lockfree
    /// ATOMIC_INT_LOCK_FREE = 1 - is sometimes lockfree
    /// ATOMIC_INT_LOCK_FREE = 0 - is never lockfree
    static_assert(2 <= ATOMIC_INT_LOCK_FREE, "SoFi is not able to run lock free on this data type");

    /// @brief Internal size needs to be bigger than the size desirred by the user
    /// This is because of buffer empty detection and overflow handling
    static constexpr uint32_t INTERNAL_SIZE_ADD_ON = 1;

    /// @brief This is the resulting internal size on creation
    static constexpr uint32_t INTERNAL_SOFI_SIZE = CapacityValue + INTERNAL_SIZE_ADD_ON;

  public:
    /// @brief default constructor which constructs an empty sofi
    SoFi() noexcept;

    /// @brief pushs an element into sofi. if sofi is full the oldest data will be
    ///         returned and the pushed element is stored in its place instead.
    /// @param[in] valueOut value which should be stored
    /// @param[out] f_paramOut_r if sofi is overflowing  the value of the overridden value
    ///                            is stored here
    /// @concurrent restricted thread safe: single pop, single push no
    ///             push calls from multiple contexts
    /// @return return true if push was sucessfull else false.
    /// @code
    /// (initial situation, SOFI is FULL)
    ///     Start|-----A-------|
    ///                        |-----B-------|
    ///                                      |-----C-------|
    ///                                                    |-----D-------|
    ///
    ///
    /// (calling push with data ’E’)
    ///     Start|-----E-------|
    ///                        |-----A-------|
    ///                                      |-----B-------|
    ///                                                    |-----C-------|
    ///                                     (’D’ is returned as value_out)
    ///
    ///###################################################################
    ///
    /// (if SOFI is not FULL , calling push() add new data)
    ///     Start|-------------|
    ///                        |-------------|  ( Initial SOFI )
    ///  (push() Called two times)
    ///
    ///                                      |-------------|
    ///                                      (New Data)
    ///                                                     |-------------|
    ///                                                      (New Data)
    /// @endcode
    bool push(const ValueType& valueOut, ValueType& f_paramOut_r) noexcept;

    /// @brief pop the oldest element
    /// @param[out] valueOut storage of the pop'ed value
    /// @concurrent restricted thread safe: single pop, single push no
    ///             pop or popIf calls from multiple contexts
    /// @return false if sofi is empty, otherwise true
    bool pop(ValueType& valueOut) noexcept;

    /// @brief conditional pop call to provide an alternative for a peek
    ///         and pop approach. If the verificator returns true the
    ///         peeked element is returned.
    /// @param[out] valueOut storage of the pop'ed value
    /// @param[in] verificator callable of type bool(const ValueType& peekValue)
    ///             which takes the value which would be pop'ed as argument and returns
    ///             true if it should be pop'ed, otherwise false
    /// @code
    ///     int limit = 7128;
    ///     mysofi.popIf(value, [=](const ValueType & peek)
    ///         {
    ///             return peek < limit; // pop only when peek is smaller than limit
    ///         }
    ///     ); // pop's a value only if it is smaller than 9012
    /// @endcode
    /// @concurrent restricted thread safe: single pop, single push no
    ///             pop or popIf calls from multiple contexts
    /// @return false if sofi is empty or when verificator returns false, otherwise true
    template <typename Verificator_T>
    bool popIf(ValueType& valueOut, const Verificator_T& verificator) noexcept;

    /// @brief returns true if sofi is empty, otherwise false
    /// @note the use of this function is limited in the concurrency case. if you
    ///         call this and in another thread pop is called the result can be out
    ///         of date as soon as you require it
    /// @concurrent unrestricted thread safe
    bool empty() const noexcept;

    /// @brief resizes sofi
    /// @param[in] newSize valid values are 0 < newSize < CapacityValue
    /// @pre it is important that no pop or push calls occur during
    ///         this call
    /// @concurrent not thread safe
    bool setCapacity(const uint64_t newSize) noexcept;

    /// @brief returns the capacity of sofi
    /// @concurrent unrestricted thread safe
    uint64_t capacity() const noexcept;

    /// @brief returns the current size of sofi
    /// @concurrent unrestricted thread safe
    uint64_t size() const noexcept;

  private:
    ValueType m_data[INTERNAL_SOFI_SIZE];
    uint64_t m_size = INTERNAL_SOFI_SIZE;

    /// @brief the write/read pointers are "atomic pointers" so that they are not
    /// reordered (read or written too late)
    std::atomic<uint64_t> m_readPosition{0u};
    std::atomic<uint64_t> m_writePosition{0u};
};

} // namespace concurrent
} // namespace iox

#include "iceoryx_hoofs/internal/concurrent/sofi.inl"

#endif // IOX_HOOFS_CONCURRENT_SOFI_HPP
<|endoftext|>


<commit_before><commit_msg>Fixed statSN numbering bug<commit_after><|endoftext|>


<commit_before>#include "foobarnowplayingannouncer.h"
#include <QDebug>

// TODO: REMOVE, DEBUGGING ONLY
#include <QWaitCondition>
#include <QMutex>

// This should be more than enough, since the struct is smaller
#define BUFSIZE 2048

struct songInfo {
    // These are in UTF-8; use QString::fromUtf8() to create a QString
    char artist[512];
    char title[512];
};

FoobarNowPlayingAnnouncer::FoobarNowPlayingAnnouncer(QObject *parent) : QObject(parent) {
}

void FoobarNowPlayingAnnouncer::run() {
    // TODO
    // TODO: error handling, retrying etc!
    // TODO

    HANDLE hPipe = CreateFile(TEXT("\\\\.\\pipe\\foo_simpleserver_announce"), GENERIC_READ | FILE_WRITE_ATTRIBUTES /* NO GENERIC_WRITE */, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (hPipe == INVALID_HANDLE_VALUE) {
        qWarning() << "Unable to connect to foo_simpleserver_announce pipe";
        return;
    }

    DWORD mode = PIPE_READMODE_MESSAGE;
    if (!SetNamedPipeHandleState(hPipe, &mode, NULL, NULL)) {
        qWarning() << "Unable to set PIPE_READMODE_MESSAGE for foo_simpleserver_announce pipe";
        return;
    }

    char *responseData = (char *)HeapAlloc(GetProcessHeap(), 0, BUFSIZE);
    if (!responseData) {
        CloseHandle(hPipe);
        qWarning() << "Unable to allocate memory for foo_simpleserver_announce response data";
        return;
    }

    while (true) {
        DWORD bytes_read = 0;
        bool success = ReadFile(hPipe, responseData, BUFSIZE, &bytes_read, NULL);

        if (!success) {
            qWarning() << "ReadFile failed; GetLastError() ==" << GetLastError();
            CloseHandle(hPipe);
            HeapFree(GetProcessHeap(), 0, responseData);
            return;
        }

        if (bytes_read != sizeof(struct songInfo)) {
            qWarning() << "foo_simpleserver_announce read failed: unexpected data size" << bytes_read << "bytes";
            CloseHandle(hPipe);
            HeapFree(GetProcessHeap(), 0, responseData);
            return;
        }

        struct songInfo *info = reinterpret_cast<struct songInfo *>(responseData);

        qDebug() << "New song:" << info->artist << "-" << info->title;
    }

//  FlushFileBuffers(hPipe);
    HeapFree(GetProcessHeap(), 0, responseData);

    /*
    int i = 0;
    while (true) {
        qDebug() << "FoobarNowPlayingAnnouncer still here...";
        QMutex mutex;
        mutex.lock();
        QWaitCondition waitCondition;
        waitCondition.wait(&mutex, 1000);
        mutex.unlock();

        if (i++ % 5 == 0)
            emit newTrack("Some artist", QString("Some track #%1").arg(i));
    }
    */
}
<commit_msg>Loop and retry etc. in the foobar interface<commit_after>#include "foobarnowplayingannouncer.h"
#include <QDebug>
#include <QThread>

// TODO: REMOVE, DEBUGGING ONLY
#include <QWaitCondition>
#include <QMutex>

// This should be more than enough, since the struct is smaller
#define BUFSIZE 2048

struct songInfo {
    // These are in UTF-8; use QString::fromUtf8() to create a QString
    char artist[512];
    char title[512];
};

FoobarNowPlayingAnnouncer::FoobarNowPlayingAnnouncer(QObject *parent) : QObject(parent) {
}

void FoobarNowPlayingAnnouncer::run() {
    char *responseData = (char *)HeapAlloc(GetProcessHeap(), 0, BUFSIZE);
    if (!responseData) {
        qWarning() << "Unable to allocate memory for foo_simpleserver_announce response data";
        return;
    }

    bool initial_run = true;

    // Loop retrying to connect to the pipe, in case it fails (or disconnects after initially succeeding)
    while (true) {
restart_loop:
        if (!initial_run) {
            QThread::sleep(4);
        }
        else
            initial_run = false;

        HANDLE hPipe = CreateFile(TEXT("\\\\.\\pipe\\foo_simpleserver_announce"), GENERIC_READ | FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, 0, NULL);
        if (hPipe == INVALID_HANDLE_VALUE) {
            continue;
        }

        DWORD mode = PIPE_READMODE_MESSAGE;
        if (!SetNamedPipeHandleState(hPipe, &mode, NULL, NULL)) {
            qWarning() << "Unable to set PIPE_READMODE_MESSAGE for foo_simpleserver_announce pipe";
            CloseHandle(hPipe);
            continue;
        }

        // Loop while connected to this pipe
        while (true) {
            DWORD bytes_read = 0;
            bool success = ReadFile(hPipe, responseData, BUFSIZE, &bytes_read, NULL);

            if (!success) {
                qWarning() << "foo_simpleserver_announce ReadFile failed; GetLastError() ==" << GetLastError();
                CloseHandle(hPipe);
                goto restart_loop; // Weee!
            }

            if (bytes_read != sizeof(struct songInfo)) {
                qWarning() << "foo_simpleserver_announce read failed: unexpected data size" << bytes_read << "bytes";
                CloseHandle(hPipe);
                goto restart_loop; // Weee!
            }

            struct songInfo *info = reinterpret_cast<struct songInfo *>(responseData);

            QString artist = QString::fromUtf8(info->artist);
            QString title = QString::fromUtf8(info->title);

            if (artist.length() > 0 && title.length() > 0)
                emit newTrack(artist, title);
        }
    }

    // This won't ever be reached... oh well.
    HeapFree(GetProcessHeap(), 0, responseData);
}
<|endoftext|>


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

#ifndef _DBAUI_ADMINPAGES_HXX_
#define _DBAUI_ADMINPAGES_HXX_

#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _DBAUI_DSNTYPES_HXX_
#include "dsntypes.hxx"
#endif
#ifndef _DBAUI_COMMON_TYPES_HXX_
#include "commontypes.hxx"
#endif
#ifndef _SVTOOLS_WIZARDMACHINE_HXX_
#include <svtools/wizardmachine.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif

class NumericField;
class Edit;
//.........................................................................
namespace dbaui
{
//.........................................................................
    /// helper class to wrap the savevalue and disable call
    class SAL_NO_VTABLE ISaveValueWrapper
    {
    public:
        virtual bool SaveValue() = 0;
        virtual bool Disable() = 0;
    };

    template < class T > class OSaveValueWrapper : public ISaveValueWrapper
    {
        T*  m_pSaveValue;
    public:
        OSaveValueWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue)
        { OSL_ENSURE(m_pSaveValue,"Illegal argument!"); }

        virtual bool SaveValue() { m_pSaveValue->SaveValue(); return true;} // bool return value only for stl
        virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl
    };

    template < class T > class ODisableWrapper : public ISaveValueWrapper
    {
        T*  m_pSaveValue;
    public:
        ODisableWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue)
        { OSL_ENSURE(m_pSaveValue,"Illegal argument!"); }

        virtual bool SaveValue() { return true;} // bool return value only for stl
        virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl
    };

    struct TSaveValueWrapperFunctor : public ::std::unary_function< ISaveValueWrapper, bool>
    {
        bool operator() (ISaveValueWrapper* lhs)
        {
            return lhs->SaveValue();
        }
    };
    struct TDisableWrapperFunctor : public ::std::unary_function< ISaveValueWrapper, bool>
    {
        bool operator() (ISaveValueWrapper* lhs)
        {
            return lhs->Disable();
        }
    };

    struct TDeleteWrapperFunctor : public ::std::unary_function< ISaveValueWrapper, bool>
    {
        bool operator() (ISaveValueWrapper* lhs)
        {
            delete lhs;
            return true;
        }
    };

    //=========================================================================
    //= OGenericAdministrationPage
    //=========================================================================
    class IDatabaseSettingsDialog;
    class IItemSetHelper;
    class OGenericAdministrationPage : public SfxTabPage, public svt::IWizardPage
    {
    private:
        Link            m_aModifiedHandler;     /// to be called if something on the page has been modified
        sal_Bool        m_abEnableRoadmap;
    protected:
        IDatabaseSettingsDialog*   m_pAdminDialog;
        IItemSetHelper* m_pItemSetHelper;
        FixedText*      m_pFT_HeaderText;

        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                            m_xORB;
    public:
        OGenericAdministrationPage(Window* _pParent, const ResId& _rId, const SfxItemSet& _rAttrSet);
        ~OGenericAdministrationPage();

        /// set a handler which gets called every time something on the page has been modified
        void SetModifiedHandler(const Link& _rHandler) { m_aModifiedHandler = _rHandler; }

        /** Sets the ParentDialog
            @param  _pAdminDialog
                the ParentDialog
            @param  _pItemSetHelper
                the itemset helper
        */
        inline void SetAdminDialog(IDatabaseSettingsDialog* _pDialog,IItemSetHelper* _pItemSetHelper)
        {
            OSL_ENSURE(_pDialog && _pItemSetHelper,"Values are NULL!");
            m_pAdminDialog = _pDialog;
            m_pItemSetHelper = _pItemSetHelper;
        }

        /** Sets the ServiceFactory
            @param  _rxORB
                The service factory.
        */
        virtual void SetServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > _rxORB)
        {
            m_xORB = _rxORB;
        }

        /** opens a dialog filled with all data sources available for this type and
            returns the selected on.
            @param  _eType
                The type for which the data source dialog should be opened.
            @param  _sReturn
                <OUT/> contains the selected name.
            @return
                <FALSE/> if an error occured, otherwise <TRUE/>
        */
        sal_Bool getSelectedDataSource(DATASOURCE_TYPE _eType,::rtl::OUString& _sReturn,::rtl::OUString& _sCurr);

        // svt::IWizardPage
        virtual void enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, GrantAccess );
        virtual void initializePage();
        virtual sal_Bool commitPage(COMMIT_REASON _eReason);

        void                SetRoadmapStateValue( sal_Bool _bDoEnable ) { m_abEnableRoadmap = _bDoEnable; }
        bool                GetRoadmapStateValue() const { return m_abEnableRoadmap; }

    protected:
        /// default implementation: call FillItemSet, call prepareLeave,
        virtual int DeactivatePage(SfxItemSet* pSet);
        using SfxTabPage::DeactivatePage;
        /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_False
        virtual void Reset(const SfxItemSet& _rCoreAttrs);
        /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_True
        virtual void ActivatePage(const SfxItemSet& _rSet);

        // TabPage overridables
        virtual void    ActivatePage();

    protected:
        void callModifiedHdl() const { if (m_aModifiedHandler.IsSet()) m_aModifiedHandler.Call((void*)this); }

        /// called from within DeactivatePage. The page is allowed to be deactivated if this method returns sal_True
        virtual sal_Bool prepareLeave() { return sal_True; }

        /** called from within Reset and ActivatePage, use to initialize the controls with the items from the given set
            @param      _bSaveValue     if set to sal_True, the implementation should call SaveValue on all relevant controls
        */
        virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue);

        /// analyze the invalid and the readonly flag which may be present in the set
        void getFlags(const SfxItemSet& _rSet, sal_Bool& _rValid, sal_Bool& _rReadonly);

        /** will be called inside <method>implInitControls</method> to save the value if necessary
            @param  _rControlList
                The list must be filled with the controls.
                It is not allowed to clear the list before pusching data into it.
        */
        virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList) = 0;

        /** will be called inside <method>implInitControls</method> to disable if necessary
            @param  _rControlList
                The list must be filled with the controls.
                It is not allowed to clear the list before pusching data into it.
        */
        virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList) = 0;

        /** fills the Boolean value into the item set when the value changed.
            @param  _rSet
                The item set where to put the new value into.
            @param  _pCheckBox
                The check box which is checked.
            @param  _nID
                The id in the itemset to set whith the new value.
            @param  _bChangedSomething
                <TRUE/> if something changed otherwise <FALSE/>
            @param _bRevertValue
                set to <TRUE/> if the display value should be reverted before putting it into the set
        */
        void fillBool( SfxItemSet& _rSet, CheckBox* _pCheckBox, USHORT _nID, sal_Bool& _bChangedSomething, bool _bRevertValue = false);

        /** fills the int value into the item set when the value changed.
            @param  _rSet
                The item set where to put the new value into.
            @param  _pEdit
                The check box which is checked.
            @param  _nID
                The id in the itemset to set whith the new value.
            @param  _bChangedSomething
                <TRUE/> if something changed otherwise <FALSE/>
        */
        void fillInt32(SfxItemSet& _rSet,NumericField* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething);

        /** fills the String value into the item set when the value changed.
            @param  _rSet
                The item set where to put the new value into.
            @param  _pEdit
                The check box which is checked.
            @param  _nID
                The id in the itemset to set whith the new value.
            @param  _bChangedSomething
                <TRUE/> if something changed otherwise <FALSE/>
        */
        void fillString(SfxItemSet& _rSet,Edit* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething);

        // used to set the right Pane header of a wizard to bold
        void SetControlFontWeight(Window* _pWindow, FontWeight _eWeight = WEIGHT_BOLD);
        void SetHeaderText( USHORT _nFTResId, USHORT _StringResId);

        Point MovePoint(Point _aPixelBasePoint, sal_Int32 _XShift, sal_Int32 _YShift);

    protected:
        /** This link be used for controls where the tabpage does not need to take any special action when the control
            is modified. The implementation just calls callModifiedHdl.
        */
        DECL_LINK(OnControlModified, Control*);
        DECL_LINK(OnTestConnectionClickHdl,PushButton*);

        /// may be used in SetXXXHdl calls to controls, is a link to <method>OnControlModified</method>
        virtual Link getControlModifiedLink() { return LINK(this, OGenericAdministrationPage, OnControlModified); }
    };

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // _DBAUI_ADMINPAGES_HXX_

<commit_msg>INTEGRATION: CWS odbmacros2 (1.32.20); FILE MERGED 2008/02/11 11:17:53 fs 1.32.20.3: IWizardPage is COMMIT_REASON is deprecated - replace usages with CommitPageReason, while I have an svtools-incompatible CWS 2008/02/04 13:08:04 fs 1.32.20.2: RESYNC: (1.32-1.33); FILE MERGED 2008/01/15 09:50:00 fs 1.32.20.1: some re-factoring of OWizardMachine, RoadmapWizard and derived classes, to prepare the migration UI for #i49133#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: adminpages.hxx,v $
 *
 *  $Revision: 1.34 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 18:16:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DBAUI_ADMINPAGES_HXX_
#define _DBAUI_ADMINPAGES_HXX_

#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _DBAUI_DSNTYPES_HXX_
#include "dsntypes.hxx"
#endif
#ifndef _DBAUI_COMMON_TYPES_HXX_
#include "commontypes.hxx"
#endif
#ifndef _SVTOOLS_WIZARDMACHINE_HXX_
#include <svtools/wizardmachine.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif

class NumericField;
class Edit;
//.........................................................................
namespace dbaui
{
//.........................................................................
    /// helper class to wrap the savevalue and disable call
    class SAL_NO_VTABLE ISaveValueWrapper
    {
    public:
        virtual bool SaveValue() = 0;
        virtual bool Disable() = 0;
    };

    template < class T > class OSaveValueWrapper : public ISaveValueWrapper
    {
        T*  m_pSaveValue;
    public:
        OSaveValueWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue)
        { OSL_ENSURE(m_pSaveValue,"Illegal argument!"); }

        virtual bool SaveValue() { m_pSaveValue->SaveValue(); return true;} // bool return value only for stl
        virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl
    };

    template < class T > class ODisableWrapper : public ISaveValueWrapper
    {
        T*  m_pSaveValue;
    public:
        ODisableWrapper(T* _pSaveValue) : m_pSaveValue(_pSaveValue)
        { OSL_ENSURE(m_pSaveValue,"Illegal argument!"); }

        virtual bool SaveValue() { return true;} // bool return value only for stl
        virtual bool Disable() { m_pSaveValue->Disable(); return true;} // bool return value only for stl
    };

    struct TSaveValueWrapperFunctor : public ::std::unary_function< ISaveValueWrapper, bool>
    {
        bool operator() (ISaveValueWrapper* lhs)
        {
            return lhs->SaveValue();
        }
    };
    struct TDisableWrapperFunctor : public ::std::unary_function< ISaveValueWrapper, bool>
    {
        bool operator() (ISaveValueWrapper* lhs)
        {
            return lhs->Disable();
        }
    };

    struct TDeleteWrapperFunctor : public ::std::unary_function< ISaveValueWrapper, bool>
    {
        bool operator() (ISaveValueWrapper* lhs)
        {
            delete lhs;
            return true;
        }
    };

    //=========================================================================
    //= OGenericAdministrationPage
    //=========================================================================
    class IDatabaseSettingsDialog;
    class IItemSetHelper;
    class OGenericAdministrationPage : public SfxTabPage, public svt::IWizardPage
    {
    private:
        Link            m_aModifiedHandler;     /// to be called if something on the page has been modified
        sal_Bool        m_abEnableRoadmap;
    protected:
        IDatabaseSettingsDialog*   m_pAdminDialog;
        IItemSetHelper* m_pItemSetHelper;
        FixedText*      m_pFT_HeaderText;

        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                            m_xORB;
    public:
        OGenericAdministrationPage(Window* _pParent, const ResId& _rId, const SfxItemSet& _rAttrSet);
        ~OGenericAdministrationPage();

        /// set a handler which gets called every time something on the page has been modified
        void SetModifiedHandler(const Link& _rHandler) { m_aModifiedHandler = _rHandler; }

        /** Sets the ParentDialog
            @param  _pAdminDialog
                the ParentDialog
            @param  _pItemSetHelper
                the itemset helper
        */
        inline void SetAdminDialog(IDatabaseSettingsDialog* _pDialog,IItemSetHelper* _pItemSetHelper)
        {
            OSL_ENSURE(_pDialog && _pItemSetHelper,"Values are NULL!");
            m_pAdminDialog = _pDialog;
            m_pItemSetHelper = _pItemSetHelper;
        }

        /** Sets the ServiceFactory
            @param  _rxORB
                The service factory.
        */
        virtual void SetServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > _rxORB)
        {
            m_xORB = _rxORB;
        }

        /** opens a dialog filled with all data sources available for this type and
            returns the selected on.
            @param  _eType
                The type for which the data source dialog should be opened.
            @param  _sReturn
                <OUT/> contains the selected name.
            @return
                <FALSE/> if an error occured, otherwise <TRUE/>
        */
        sal_Bool getSelectedDataSource(DATASOURCE_TYPE _eType,::rtl::OUString& _sReturn,::rtl::OUString& _sCurr);

        // svt::IWizardPage
        virtual void initializePage();
        virtual sal_Bool commitPage( CommitPageReason _eReason );

        void                SetRoadmapStateValue( sal_Bool _bDoEnable ) { m_abEnableRoadmap = _bDoEnable; }
        bool                GetRoadmapStateValue() const { return m_abEnableRoadmap; }

    protected:
        /// default implementation: call FillItemSet, call prepareLeave,
        virtual int DeactivatePage(SfxItemSet* pSet);
        using SfxTabPage::DeactivatePage;
        /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_False
        virtual void Reset(const SfxItemSet& _rCoreAttrs);
        /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_True
        virtual void ActivatePage(const SfxItemSet& _rSet);

        // TabPage overridables
        virtual void    ActivatePage();

    protected:
        void callModifiedHdl() const { if (m_aModifiedHandler.IsSet()) m_aModifiedHandler.Call((void*)this); }

        /// called from within DeactivatePage. The page is allowed to be deactivated if this method returns sal_True
        virtual sal_Bool prepareLeave() { return sal_True; }

        /** called from within Reset and ActivatePage, use to initialize the controls with the items from the given set
            @param      _bSaveValue     if set to sal_True, the implementation should call SaveValue on all relevant controls
        */
        virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue);

        /// analyze the invalid and the readonly flag which may be present in the set
        void getFlags(const SfxItemSet& _rSet, sal_Bool& _rValid, sal_Bool& _rReadonly);

        /** will be called inside <method>implInitControls</method> to save the value if necessary
            @param  _rControlList
                The list must be filled with the controls.
                It is not allowed to clear the list before pusching data into it.
        */
        virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList) = 0;

        /** will be called inside <method>implInitControls</method> to disable if necessary
            @param  _rControlList
                The list must be filled with the controls.
                It is not allowed to clear the list before pusching data into it.
        */
        virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList) = 0;

        /** fills the Boolean value into the item set when the value changed.
            @param  _rSet
                The item set where to put the new value into.
            @param  _pCheckBox
                The check box which is checked.
            @param  _nID
                The id in the itemset to set whith the new value.
            @param  _bChangedSomething
                <TRUE/> if something changed otherwise <FALSE/>
            @param _bRevertValue
                set to <TRUE/> if the display value should be reverted before putting it into the set
        */
        void fillBool( SfxItemSet& _rSet, CheckBox* _pCheckBox, USHORT _nID, sal_Bool& _bChangedSomething, bool _bRevertValue = false);

        /** fills the int value into the item set when the value changed.
            @param  _rSet
                The item set where to put the new value into.
            @param  _pEdit
                The check box which is checked.
            @param  _nID
                The id in the itemset to set whith the new value.
            @param  _bChangedSomething
                <TRUE/> if something changed otherwise <FALSE/>
        */
        void fillInt32(SfxItemSet& _rSet,NumericField* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething);

        /** fills the String value into the item set when the value changed.
            @param  _rSet
                The item set where to put the new value into.
            @param  _pEdit
                The check box which is checked.
            @param  _nID
                The id in the itemset to set whith the new value.
            @param  _bChangedSomething
                <TRUE/> if something changed otherwise <FALSE/>
        */
        void fillString(SfxItemSet& _rSet,Edit* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething);

        // used to set the right Pane header of a wizard to bold
        void SetControlFontWeight(Window* _pWindow, FontWeight _eWeight = WEIGHT_BOLD);
        void SetHeaderText( USHORT _nFTResId, USHORT _StringResId);

        Point MovePoint(Point _aPixelBasePoint, sal_Int32 _XShift, sal_Int32 _YShift);

    protected:
        /** This link be used for controls where the tabpage does not need to take any special action when the control
            is modified. The implementation just calls callModifiedHdl.
        */
        DECL_LINK(OnControlModified, Control*);
        DECL_LINK(OnTestConnectionClickHdl,PushButton*);

        /// may be used in SetXXXHdl calls to controls, is a link to <method>OnControlModified</method>
        virtual Link getControlModifiedLink() { return LINK(this, OGenericAdministrationPage, OnControlModified); }
    };

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // _DBAUI_ADMINPAGES_HXX_

<|endoftext|>


<commit_before>#define _XOPEN_SOURCE
#include <errno.h>
#include <iconv.h>
#include <unistd.h>
#include <node.h>

using namespace v8;

static char SECURE_SALT[21] = "$5$";
#define TRIP_MAX 128

static Handle<Value> setup_callback(Arguments const &args) {
	HandleScope scope;

	if (args.Length() != 1)
		return False();
	String::Utf8Value saltVal(args[0]->ToString());
	if (saltVal.length() != 16)
		return False();
	char *salt = *saltVal;
	if (!salt)
		return False();
	memcpy(SECURE_SALT + 3, salt, 16);
	SECURE_SALT[19] = '$';
	SECURE_SALT[20] = 0;
	return True();
}

static void fix_char(char &c) {
	static const char *from = ":;<=>?@[\\]^_`", *to = "ABCDEFGabcdef";
	const char *p;
	if (c < '.' || c > 'z')
		c = '.';
	else if ((p = strchr(from, c)))
		c = to[p - from];
}

static void hash_trip(char *key, size_t len, char *dest) {
	char *digest, salt[3] = "..";
	if (len == 1)
		salt[0] = 'H';
	else if (len == 2) {
		salt[0] = key[1];
		salt[1] = 'H';
	}
	else if (len)
		strncpy(salt, key + 1, 2);
	fix_char(salt[0]);
	fix_char(salt[1]);
	digest = crypt(key, salt);
	if (!digest)
		return;
	len = strlen(digest);
	if (len < 11)
		return;
	digest += len - 11;
	digest[0] = '!';
	strncpy(dest, digest, 12);
}

static void hash_secure(char *key, size_t len, char *dest) {
	size_t i;
	char *digest;
	if (len > TRIP_MAX) {
		len = TRIP_MAX;
		key[TRIP_MAX] = 0;
	}
	for (i = 0; i < len; i++)
		fix_char(key[i]);
	digest = crypt(key, SECURE_SALT);
	if (!digest)
		return;
	len = strlen(digest);
	if (len < 12)
		return;
	digest += len - 12;
	digest[0] = digest[1] = '!';
	strncpy(dest, digest, 13);
}

static iconv_t conv_desc;

static int setup_conv() {
	conv_desc = iconv_open("SHIFT_JIS", "UTF-8");
	if (conv_desc == (iconv_t) -1) {
		fprintf(stderr, "Can't convert to SHIFT_JIS.\n");
		return 0;
	}
	return 1;
}

typedef void (*trip_f)(char *, size_t, char *);

static void with_SJIS(String::Utf8Value &trip, trip_f func, char *ret) {
	char *src = *trip;
	if (!src)
		return;
	size_t src_left = trip.length(), dest_left = TRIP_MAX;
	if (!src_left)
		return;
	if (src_left > TRIP_MAX / 2)
		src_left = TRIP_MAX / 2;
	char sjis[TRIP_MAX+1];
	char *dest = sjis;
	size_t result = iconv(conv_desc, &src, &src_left, &dest, &dest_left);
	if (result == (size_t) -1 && errno != EILSEQ && errno != EINVAL) {
		perror("iconv");
		return;
	}
	ssize_t len = TRIP_MAX - dest_left;
	if (len > 0) {
		sjis[len] = 0;
		func(sjis, len, ret);
	}
}

static Handle<Value> hash_callback(Arguments const &args) {
	HandleScope scope;
	if (args.Length() != 2)
		return Null();

	String::Utf8Value trip(args[0]->ToString()),
			secure(args[1]->ToString());
	char digest[24];
	digest[0] = 0;
	with_SJIS(trip, &hash_trip, digest);
	with_SJIS(secure, &hash_secure, digest + strlen(digest));
	return scope.Close(String::New(digest));
}

extern "C" void init(Handle<Object> target) {
	if (!setup_conv())
		return;
	target->Set(String::NewSymbol("setSalt"),
			FunctionTemplate::New(&setup_callback)->GetFunction());
	target->Set(String::NewSymbol("hash"),
			FunctionTemplate::New(&hash_callback)->GetFunction());
}

NODE_MODULE(tripcode, init);
<commit_msg>Add missing import for tripcode<commit_after>#define _XOPEN_SOURCE
#include <errno.h>
#include <iconv.h>
#include <unistd.h>
#include <node.h>
#include <string.h>

using namespace v8;

static char SECURE_SALT[21] = "$5$";
#define TRIP_MAX 128

static Handle<Value> setup_callback(Arguments const &args) {
	HandleScope scope;

	if (args.Length() != 1)
		return False();
	String::Utf8Value saltVal(args[0]->ToString());
	if (saltVal.length() != 16)
		return False();
	char *salt = *saltVal;
	if (!salt)
		return False();
	memcpy(SECURE_SALT + 3, salt, 16);
	SECURE_SALT[19] = '$';
	SECURE_SALT[20] = 0;
	return True();
}

static void fix_char(char &c) {
	static const char *from = ":;<=>?@[\\]^_`", *to = "ABCDEFGabcdef";
	const char *p;
	if (c < '.' || c > 'z')
		c = '.';
	else if ((p = strchr(from, c)))
		c = to[p - from];
}

static void hash_trip(char *key, size_t len, char *dest) {
	char *digest, salt[3] = "..";
	if (len == 1)
		salt[0] = 'H';
	else if (len == 2) {
		salt[0] = key[1];
		salt[1] = 'H';
	}
	else if (len)
		strncpy(salt, key + 1, 2);
	fix_char(salt[0]);
	fix_char(salt[1]);
	digest = crypt(key, salt);
	if (!digest)
		return;
	len = strlen(digest);
	if (len < 11)
		return;
	digest += len - 11;
	digest[0] = '!';
	strncpy(dest, digest, 12);
}

static void hash_secure(char *key, size_t len, char *dest) {
	size_t i;
	char *digest;
	if (len > TRIP_MAX) {
		len = TRIP_MAX;
		key[TRIP_MAX] = 0;
	}
	for (i = 0; i < len; i++)
		fix_char(key[i]);
	digest = crypt(key, SECURE_SALT);
	if (!digest)
		return;
	len = strlen(digest);
	if (len < 12)
		return;
	digest += len - 12;
	digest[0] = digest[1] = '!';
	strncpy(dest, digest, 13);
}

static iconv_t conv_desc;

static int setup_conv() {
	conv_desc = iconv_open("SHIFT_JIS", "UTF-8");
	if (conv_desc == (iconv_t) -1) {
		fprintf(stderr, "Can't convert to SHIFT_JIS.\n");
		return 0;
	}
	return 1;
}

typedef void (*trip_f)(char *, size_t, char *);

static void with_SJIS(String::Utf8Value &trip, trip_f func, char *ret) {
	char *src = *trip;
	if (!src)
		return;
	size_t src_left = trip.length(), dest_left = TRIP_MAX;
	if (!src_left)
		return;
	if (src_left > TRIP_MAX / 2)
		src_left = TRIP_MAX / 2;
	char sjis[TRIP_MAX+1];
	char *dest = sjis;
	size_t result = iconv(conv_desc, &src, &src_left, &dest, &dest_left);
	if (result == (size_t) -1 && errno != EILSEQ && errno != EINVAL) {
		perror("iconv");
		return;
	}
	ssize_t len = TRIP_MAX - dest_left;
	if (len > 0) {
		sjis[len] = 0;
		func(sjis, len, ret);
	}
}

static Handle<Value> hash_callback(Arguments const &args) {
	HandleScope scope;
	if (args.Length() != 2)
		return Null();

	String::Utf8Value trip(args[0]->ToString()),
			secure(args[1]->ToString());
	char digest[24];
	digest[0] = 0;
	with_SJIS(trip, &hash_trip, digest);
	with_SJIS(secure, &hash_secure, digest + strlen(digest));
	return scope.Close(String::New(digest));
}

extern "C" void init(Handle<Object> target) {
	if (!setup_conv())
		return;
	target->Set(String::NewSymbol("setSalt"),
			FunctionTemplate::New(&setup_callback)->GetFunction());
	target->Set(String::NewSymbol("hash"),
			FunctionTemplate::New(&hash_callback)->GetFunction());
}

NODE_MODULE(tripcode, init);
<|endoftext|>


<commit_before>// @(#)root/gui:$Id$
// Author: Fons Rademakers   09/01/98

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/
/**************************************************************************

    This source is based on Xclass95, a Win95-looking GUI toolkit.
    Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.

    Xclass95 is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

**************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TMsgBox                                                              //
//                                                                      //
// A message dialog box.                                                //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGMsgBox.h"
#include "TGButton.h"
#include "TGIcon.h"
#include "TGLabel.h"
#include "TList.h"

ClassImp(TGMsgBox)

//______________________________________________________________________________
TGMsgBox::TGMsgBox(const TGWindow *p, const TGWindow *main,
                   const char *title, const char *msg, const TGPicture *icon,
                   Int_t buttons, Int_t *ret_code, UInt_t options,
                   Int_t text_align) :
   TGTransientFrame(p, main, 10, 10, options)
{
   // Create a message dialog box.

   if (p)
      PMsgBox(title, msg, icon, buttons, ret_code, text_align);
   else
      MakeZombie();
}

//______________________________________________________________________________
TGMsgBox::TGMsgBox(const TGWindow *p, const TGWindow *main,
                   const char *title, const char *msg, EMsgBoxIcon icon,
                   Int_t buttons, Int_t *ret_code, UInt_t options,
                   Int_t text_align) :
   TGTransientFrame(p, main, 10, 10, options)
{
   // Create a message dialog box with the following parameters:.
   //       title: Window title
   //         msg: Message to be shown ('\n' may be used to split it in lines)
   //        icon: Picture to be shown at the left on the dialog window.
   //              It might take any of the following values:
   //              kMBIconStop, kMBIconQuestion,
   //              kMBIconExclamation, kMBIconAsterisk
   //     buttons: Buttons to be shown at the botton of the dialgo window.
   //              Look at EMsgBoxButton for the different possible values.
   //    ret_code: It will hold the value of the button pressed when the
   //              dialog is closed
   //     options: Frame options of this dialog window.
   //  text_align: Align options for 'msg'. See ETextJustification for the values.

   const TGPicture *icon_pic;

   switch (icon) {
      case kMBIconStop:
         icon_pic = fClient->GetPicture("mb_stop_s.xpm");
         if (!icon_pic) Error("TGMsgBox", "mb_stop_s.xpm not found");
         break;

      case kMBIconQuestion:
         icon_pic = fClient->GetPicture("mb_question_s.xpm");
         if (!icon_pic) Error("TGMsgBox", "mb_question_s.xpm not found");
         break;

      case kMBIconExclamation:
         icon_pic = fClient->GetPicture("mb_exclamation_s.xpm");
         if (!icon_pic) Error("TGMsgBox", "mb_exclamation_s.xpm not found");
         break;

      case kMBIconAsterisk:
         icon_pic = fClient->GetPicture("mb_asterisk_s.xpm");
         if (!icon_pic) Error("TGMsgBox", "mb_asterisk_s.xpm not found");
         break;

      default:
         icon_pic = 0;
         break;
   }

   if (p)
      PMsgBox(title, msg, icon_pic, buttons, ret_code, text_align);
   else
      MakeZombie();
}

//______________________________________________________________________________
void TGMsgBox::PMsgBox(const char *title, const char *msg,
                       const TGPicture *icon, Int_t buttons, Int_t *ret_code,
                       Int_t text_align)
{
   // Protected, common message dialog box initialization.

   UInt_t nb, width, height;

   fYes = fNo = fOK = fApply = fRetry = fIgnore = fCancel = fClose =
   fYesAll = fNoAll = fNewer = fAppend = fDismiss   = 0;
   fIcon      = 0;
   fMsgList   = new TList;
   fRetCode   = ret_code;
   nb = width = 0;

   // create the buttons

   fButtonFrame = new TGHorizontalFrame(this, 60, 20, kFixedWidth);
   fL1 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 3, 3, 0, 0);

   buttons &= (kMBYes | kMBNo | kMBOk | kMBApply |
               kMBRetry | kMBIgnore | kMBCancel | kMBClose | kMBDismiss |
               kMBYesAll | kMBNoAll | kMBAppend | kMBNewer);
   if (buttons == 0) buttons = kMBDismiss;

   if (buttons & kMBYes) {
      fYes = new TGTextButton(fButtonFrame, new TGHotString("&Yes"), kMBYes);
      fYes->Associate(this);
      fButtonFrame->AddFrame(fYes, fL1);
      width = TMath::Max(width, fYes->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBNo) {
      fNo = new TGTextButton(fButtonFrame, new TGHotString("&No"), kMBNo);
      fNo->Associate(this);
      fButtonFrame->AddFrame(fNo, fL1);
      width = TMath::Max(width, fNo->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBOk) {
      fOK = new TGTextButton(fButtonFrame, new TGHotString("&OK"), kMBOk);
      fOK->Associate(this);
      fButtonFrame->AddFrame(fOK, fL1);
      width = TMath::Max(width, fOK->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBApply) {
      fApply = new TGTextButton(fButtonFrame, new TGHotString("&Apply"), kMBApply);
      fApply->Associate(this);
      fButtonFrame->AddFrame(fApply, fL1);
      width = TMath::Max(width, fApply->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBRetry) {
      fRetry = new TGTextButton(fButtonFrame, new TGHotString("&Retry"), kMBRetry);
      fRetry->Associate(this);
      fButtonFrame->AddFrame(fRetry, fL1);
      width = TMath::Max(width, fRetry->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBIgnore) {
      fIgnore = new TGTextButton(fButtonFrame, new TGHotString("&Ignore"), kMBIgnore);
      fIgnore->Associate(this);
      fButtonFrame->AddFrame(fIgnore, fL1);
      width = TMath::Max(width, fIgnore->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBCancel) {
      fCancel = new TGTextButton(fButtonFrame, new TGHotString("&Cancel"), kMBCancel);
      fCancel->Associate(this);
      fButtonFrame->AddFrame(fCancel, fL1);
      width = TMath::Max(width, fCancel->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBClose) {
      fClose = new TGTextButton(fButtonFrame, new TGHotString("C&lose"), kMBClose);
      fClose->Associate(this);
      fButtonFrame->AddFrame(fClose, fL1);
      width = TMath::Max(width, fClose->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBYesAll) {
      fYesAll = new TGTextButton(fButtonFrame, new TGHotString("Y&es to All"), kMBYesAll);
      fYesAll->Associate(this);
      fButtonFrame->AddFrame(fYesAll, fL1);
      width = TMath::Max(width, fYesAll->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBNoAll) {
      fNoAll = new TGTextButton(fButtonFrame, new TGHotString("No &to All"), kMBNoAll);
      fNoAll->Associate(this);
      fButtonFrame->AddFrame(fNoAll, fL1);
      width = TMath::Max(width, fNoAll->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBNewer) {
      fNewer = new TGTextButton(fButtonFrame, new TGHotString("Ne&wer Only"), kMBNewer);
      fNewer->Associate(this);
      fButtonFrame->AddFrame(fNewer, fL1);
      width = TMath::Max(width, fNewer->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBAppend) {
      fAppend = new TGTextButton(fButtonFrame, new TGHotString("A&ppend"), kMBAppend);
      fAppend->Associate(this);
      fButtonFrame->AddFrame(fAppend, fL1);
      width = TMath::Max(width, fAppend->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBDismiss) {
      fDismiss = new TGTextButton(fButtonFrame, new TGHotString("&Dismiss"), kMBDismiss);
      fDismiss->Associate(this);
      fButtonFrame->AddFrame(fDismiss, fL1);
      width = TMath::Max(width, fDismiss->GetDefaultWidth()); ++nb;
   }

   // place buttons at the bottom

   fL2 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5);
   AddFrame(fButtonFrame, fL2);

   // keep the buttons centered and with the same width

   fButtonFrame->Resize((width + 20) * nb, GetDefaultHeight());

   fIconFrame = new TGHorizontalFrame(this, 60, 20);

   fL3 = new TGLayoutHints(kLHintsCenterY | kLHintsLeft, 2, 2, 2, 2);

   if (icon) {
      fIcon = new TGIcon(fIconFrame, icon, icon->GetWidth(), icon->GetHeight());
      fIconFrame->AddFrame(fIcon, fL3);
   }

   fLabelFrame = new TGVerticalFrame(fIconFrame, 60, 20);

   fL4 = new TGLayoutHints(kLHintsCenterY | kLHintsLeft | kLHintsExpandX,
                           4, 2, 2, 2);
   fL5 = new TGLayoutHints(kLHintsTop | kLHintsExpandX, 10, 10, 7, 2);

   // make one label per line of the message
   TGLabel *label;

   char *line;
   char *tmpMsg, *nextLine;

   tmpMsg = new char[strlen(msg) + 1];
   nextLine = tmpMsg;

   line = tmpMsg;
   strlcpy(nextLine, msg, strlen(msg) + 1);
   while ((nextLine = strchr(line, '\n'))) {
      *nextLine = 0;
      label = new TGLabel(fLabelFrame, line);
      label->SetTextJustify(text_align);
      fMsgList->Add(label);
      fLabelFrame->AddFrame(label, fL4);
      line = nextLine + 1;
   }

   label = new TGLabel(fLabelFrame, line);
   label->SetTextJustify(text_align);
   fMsgList->Add(label);
   fLabelFrame->AddFrame(label, fL4);
   delete [] tmpMsg;

   fIconFrame->AddFrame(fLabelFrame, fL4);
   AddFrame(fIconFrame, fL5);

   MapSubwindows();

   width  = GetDefaultWidth();
   height = GetDefaultHeight();

   Resize(width, height);

   // position relative to the parent's window

   CenterOnParent();

   // make the message box non-resizable

   SetWMSize(width, height);
   SetWMSizeHints(width, height, width, height, 0, 0);

   // set names

   SetWindowName(title);
   SetIconName(title);
   SetClassHints("MsgBox", "MsgBox");

   SetMWMHints(kMWMDecorAll | kMWMDecorResizeH  | kMWMDecorMaximize |
                              kMWMDecorMinimize | kMWMDecorMenu,
               kMWMFuncAll  | kMWMFuncResize    | kMWMFuncMaximize |
                              kMWMFuncMinimize,
               kMWMInputModeless);

   MapRaised();
   fClient->WaitFor(this);
}

//______________________________________________________________________________
TGMsgBox::~TGMsgBox()
{
   // Destroy message dialog box.

   if (IsZombie()) return;
   if (fYes)     delete fYes;
   if (fNo)      delete fNo;
   if (fOK)      delete fOK;
   if (fApply)   delete fApply;
   if (fRetry)   delete fRetry;
   if (fIgnore)  delete fIgnore;
   if (fCancel)  delete fCancel;
   if (fClose)   delete fClose;
   if (fDismiss) delete fDismiss;
   if (fYesAll)  delete fYesAll;
   if (fNoAll)   delete fNoAll;
   if (fNewer)   delete fNewer;
   if (fAppend)  delete fAppend;

   if (fIcon) delete fIcon;
   delete fButtonFrame;
   delete fIconFrame;
   delete fLabelFrame;
   fMsgList->Delete();
   delete fMsgList;
   delete fL1; delete fL2; delete fL3; delete fL4; delete fL5;
}

//______________________________________________________________________________
void TGMsgBox::CloseWindow()
{
   // Close dialog box. Before deleting itself it sets the return code
   // to kMBClose.

   if (fRetCode) *fRetCode = kMBClose;
   DeleteWindow();
}

//______________________________________________________________________________
Bool_t TGMsgBox::ProcessMessage(Long_t msg, Long_t parm1, Long_t)
{
   // Process message dialog box event.

   switch (GET_MSG(msg)) {
      case kC_COMMAND:
         switch (GET_SUBMSG(msg)) {
            case kCM_BUTTON:
               if (fRetCode) *fRetCode = (Int_t) parm1;
               DeleteWindow();
               break;

            default:
               break;
         }
         break;
      default:
         break;
   }
   return kTRUE;
}
<commit_msg>another strlcpy warning fix.<commit_after>// @(#)root/gui:$Id$
// Author: Fons Rademakers   09/01/98

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/
/**************************************************************************

    This source is based on Xclass95, a Win95-looking GUI toolkit.
    Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.

    Xclass95 is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

**************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TMsgBox                                                              //
//                                                                      //
// A message dialog box.                                                //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGMsgBox.h"
#include "TGButton.h"
#include "TGIcon.h"
#include "TGLabel.h"
#include "TList.h"

ClassImp(TGMsgBox)

//______________________________________________________________________________
TGMsgBox::TGMsgBox(const TGWindow *p, const TGWindow *main,
                   const char *title, const char *msg, const TGPicture *icon,
                   Int_t buttons, Int_t *ret_code, UInt_t options,
                   Int_t text_align) :
   TGTransientFrame(p, main, 10, 10, options)
{
   // Create a message dialog box.

   if (p)
      PMsgBox(title, msg, icon, buttons, ret_code, text_align);
   else
      MakeZombie();
}

//______________________________________________________________________________
TGMsgBox::TGMsgBox(const TGWindow *p, const TGWindow *main,
                   const char *title, const char *msg, EMsgBoxIcon icon,
                   Int_t buttons, Int_t *ret_code, UInt_t options,
                   Int_t text_align) :
   TGTransientFrame(p, main, 10, 10, options)
{
   // Create a message dialog box with the following parameters:.
   //       title: Window title
   //         msg: Message to be shown ('\n' may be used to split it in lines)
   //        icon: Picture to be shown at the left on the dialog window.
   //              It might take any of the following values:
   //              kMBIconStop, kMBIconQuestion,
   //              kMBIconExclamation, kMBIconAsterisk
   //     buttons: Buttons to be shown at the botton of the dialgo window.
   //              Look at EMsgBoxButton for the different possible values.
   //    ret_code: It will hold the value of the button pressed when the
   //              dialog is closed
   //     options: Frame options of this dialog window.
   //  text_align: Align options for 'msg'. See ETextJustification for the values.

   const TGPicture *icon_pic;

   switch (icon) {
      case kMBIconStop:
         icon_pic = fClient->GetPicture("mb_stop_s.xpm");
         if (!icon_pic) Error("TGMsgBox", "mb_stop_s.xpm not found");
         break;

      case kMBIconQuestion:
         icon_pic = fClient->GetPicture("mb_question_s.xpm");
         if (!icon_pic) Error("TGMsgBox", "mb_question_s.xpm not found");
         break;

      case kMBIconExclamation:
         icon_pic = fClient->GetPicture("mb_exclamation_s.xpm");
         if (!icon_pic) Error("TGMsgBox", "mb_exclamation_s.xpm not found");
         break;

      case kMBIconAsterisk:
         icon_pic = fClient->GetPicture("mb_asterisk_s.xpm");
         if (!icon_pic) Error("TGMsgBox", "mb_asterisk_s.xpm not found");
         break;

      default:
         icon_pic = 0;
         break;
   }

   if (p)
      PMsgBox(title, msg, icon_pic, buttons, ret_code, text_align);
   else
      MakeZombie();
}

//______________________________________________________________________________
void TGMsgBox::PMsgBox(const char *title, const char *msg,
                       const TGPicture *icon, Int_t buttons, Int_t *ret_code,
                       Int_t text_align)
{
   // Protected, common message dialog box initialization.

   UInt_t nb, width, height;

   fYes = fNo = fOK = fApply = fRetry = fIgnore = fCancel = fClose =
   fYesAll = fNoAll = fNewer = fAppend = fDismiss   = 0;
   fIcon      = 0;
   fMsgList   = new TList;
   fRetCode   = ret_code;
   nb = width = 0;

   // create the buttons

   fButtonFrame = new TGHorizontalFrame(this, 60, 20, kFixedWidth);
   fL1 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 3, 3, 0, 0);

   buttons &= (kMBYes | kMBNo | kMBOk | kMBApply |
               kMBRetry | kMBIgnore | kMBCancel | kMBClose | kMBDismiss |
               kMBYesAll | kMBNoAll | kMBAppend | kMBNewer);
   if (buttons == 0) buttons = kMBDismiss;

   if (buttons & kMBYes) {
      fYes = new TGTextButton(fButtonFrame, new TGHotString("&Yes"), kMBYes);
      fYes->Associate(this);
      fButtonFrame->AddFrame(fYes, fL1);
      width = TMath::Max(width, fYes->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBNo) {
      fNo = new TGTextButton(fButtonFrame, new TGHotString("&No"), kMBNo);
      fNo->Associate(this);
      fButtonFrame->AddFrame(fNo, fL1);
      width = TMath::Max(width, fNo->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBOk) {
      fOK = new TGTextButton(fButtonFrame, new TGHotString("&OK"), kMBOk);
      fOK->Associate(this);
      fButtonFrame->AddFrame(fOK, fL1);
      width = TMath::Max(width, fOK->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBApply) {
      fApply = new TGTextButton(fButtonFrame, new TGHotString("&Apply"), kMBApply);
      fApply->Associate(this);
      fButtonFrame->AddFrame(fApply, fL1);
      width = TMath::Max(width, fApply->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBRetry) {
      fRetry = new TGTextButton(fButtonFrame, new TGHotString("&Retry"), kMBRetry);
      fRetry->Associate(this);
      fButtonFrame->AddFrame(fRetry, fL1);
      width = TMath::Max(width, fRetry->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBIgnore) {
      fIgnore = new TGTextButton(fButtonFrame, new TGHotString("&Ignore"), kMBIgnore);
      fIgnore->Associate(this);
      fButtonFrame->AddFrame(fIgnore, fL1);
      width = TMath::Max(width, fIgnore->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBCancel) {
      fCancel = new TGTextButton(fButtonFrame, new TGHotString("&Cancel"), kMBCancel);
      fCancel->Associate(this);
      fButtonFrame->AddFrame(fCancel, fL1);
      width = TMath::Max(width, fCancel->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBClose) {
      fClose = new TGTextButton(fButtonFrame, new TGHotString("C&lose"), kMBClose);
      fClose->Associate(this);
      fButtonFrame->AddFrame(fClose, fL1);
      width = TMath::Max(width, fClose->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBYesAll) {
      fYesAll = new TGTextButton(fButtonFrame, new TGHotString("Y&es to All"), kMBYesAll);
      fYesAll->Associate(this);
      fButtonFrame->AddFrame(fYesAll, fL1);
      width = TMath::Max(width, fYesAll->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBNoAll) {
      fNoAll = new TGTextButton(fButtonFrame, new TGHotString("No &to All"), kMBNoAll);
      fNoAll->Associate(this);
      fButtonFrame->AddFrame(fNoAll, fL1);
      width = TMath::Max(width, fNoAll->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBNewer) {
      fNewer = new TGTextButton(fButtonFrame, new TGHotString("Ne&wer Only"), kMBNewer);
      fNewer->Associate(this);
      fButtonFrame->AddFrame(fNewer, fL1);
      width = TMath::Max(width, fNewer->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBAppend) {
      fAppend = new TGTextButton(fButtonFrame, new TGHotString("A&ppend"), kMBAppend);
      fAppend->Associate(this);
      fButtonFrame->AddFrame(fAppend, fL1);
      width = TMath::Max(width, fAppend->GetDefaultWidth()); ++nb;
   }

   if (buttons & kMBDismiss) {
      fDismiss = new TGTextButton(fButtonFrame, new TGHotString("&Dismiss"), kMBDismiss);
      fDismiss->Associate(this);
      fButtonFrame->AddFrame(fDismiss, fL1);
      width = TMath::Max(width, fDismiss->GetDefaultWidth()); ++nb;
   }

   // place buttons at the bottom

   fL2 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5);
   AddFrame(fButtonFrame, fL2);

   // keep the buttons centered and with the same width

   fButtonFrame->Resize((width + 20) * nb, GetDefaultHeight());

   fIconFrame = new TGHorizontalFrame(this, 60, 20);

   fL3 = new TGLayoutHints(kLHintsCenterY | kLHintsLeft, 2, 2, 2, 2);

   if (icon) {
      fIcon = new TGIcon(fIconFrame, icon, icon->GetWidth(), icon->GetHeight());
      fIconFrame->AddFrame(fIcon, fL3);
   }

   fLabelFrame = new TGVerticalFrame(fIconFrame, 60, 20);

   fL4 = new TGLayoutHints(kLHintsCenterY | kLHintsLeft | kLHintsExpandX,
                           4, 2, 2, 2);
   fL5 = new TGLayoutHints(kLHintsTop | kLHintsExpandX, 10, 10, 7, 2);

   // make one label per line of the message
   TGLabel *label;

   char *line;
   char *tmpMsg, *nextLine;

   int len = strlen(msg) + 1;
   tmpMsg = new char[len];
   nextLine = tmpMsg;

   line = tmpMsg;
   strlcpy(nextLine, msg, len);
   while ((nextLine = strchr(line, '\n'))) {
      *nextLine = 0;
      label = new TGLabel(fLabelFrame, line);
      label->SetTextJustify(text_align);
      fMsgList->Add(label);
      fLabelFrame->AddFrame(label, fL4);
      line = nextLine + 1;
   }

   label = new TGLabel(fLabelFrame, line);
   label->SetTextJustify(text_align);
   fMsgList->Add(label);
   fLabelFrame->AddFrame(label, fL4);
   delete [] tmpMsg;

   fIconFrame->AddFrame(fLabelFrame, fL4);
   AddFrame(fIconFrame, fL5);

   MapSubwindows();

   width  = GetDefaultWidth();
   height = GetDefaultHeight();

   Resize(width, height);

   // position relative to the parent's window

   CenterOnParent();

   // make the message box non-resizable

   SetWMSize(width, height);
   SetWMSizeHints(width, height, width, height, 0, 0);

   // set names

   SetWindowName(title);
   SetIconName(title);
   SetClassHints("MsgBox", "MsgBox");

   SetMWMHints(kMWMDecorAll | kMWMDecorResizeH  | kMWMDecorMaximize |
                              kMWMDecorMinimize | kMWMDecorMenu,
               kMWMFuncAll  | kMWMFuncResize    | kMWMFuncMaximize |
                              kMWMFuncMinimize,
               kMWMInputModeless);

   MapRaised();
   fClient->WaitFor(this);
}

//______________________________________________________________________________
TGMsgBox::~TGMsgBox()
{
   // Destroy message dialog box.

   if (IsZombie()) return;
   if (fYes)     delete fYes;
   if (fNo)      delete fNo;
   if (fOK)      delete fOK;
   if (fApply)   delete fApply;
   if (fRetry)   delete fRetry;
   if (fIgnore)  delete fIgnore;
   if (fCancel)  delete fCancel;
   if (fClose)   delete fClose;
   if (fDismiss) delete fDismiss;
   if (fYesAll)  delete fYesAll;
   if (fNoAll)   delete fNoAll;
   if (fNewer)   delete fNewer;
   if (fAppend)  delete fAppend;

   if (fIcon) delete fIcon;
   delete fButtonFrame;
   delete fIconFrame;
   delete fLabelFrame;
   fMsgList->Delete();
   delete fMsgList;
   delete fL1; delete fL2; delete fL3; delete fL4; delete fL5;
}

//______________________________________________________________________________
void TGMsgBox::CloseWindow()
{
   // Close dialog box. Before deleting itself it sets the return code
   // to kMBClose.

   if (fRetCode) *fRetCode = kMBClose;
   DeleteWindow();
}

//______________________________________________________________________________
Bool_t TGMsgBox::ProcessMessage(Long_t msg, Long_t parm1, Long_t)
{
   // Process message dialog box event.

   switch (GET_MSG(msg)) {
      case kC_COMMAND:
         switch (GET_SUBMSG(msg)) {
            case kCM_BUTTON:
               if (fRetCode) *fRetCode = (Int_t) parm1;
               DeleteWindow();
               break;

            default:
               break;
         }
         break;
      default:
         break;
   }
   return kTRUE;
}
<|endoftext|>


<commit_before>#ifndef LUA_H
	#include "lua_adapter.hpp"
#endif

int main (int argc, char *argv[]) {

    LuaAdapter lua;

    // Hint: You CAN change a default value of a global lua variable BEFORE loading the actual lua-file
    if(lua.set("GlobalVar", 321)==false){
        std::cout << "Could not set 'GlobalVar'!\n";
    }

    // and THEN load the script:
    lua.load("test.lua");

    //get int
    int width {0};
    lua.get("width", width);
    std::cout << "width: " << width << "\n";

    //get double
    double number {0};
    lua.get("number", number);
    std::cout << "Number: "<< number << "\n";

    //get string
    std::string title {"empty"};
    lua.get("title", title);
    std::cout << "title: " << title << "\n";

    std::cout << "\n";

    // tables
    if(lua.openTable("Table1")) {
        int ID {0};
        lua.getField("ID", ID);
        std::cout << "ID: " << ID << "\n";

        int Val {0};
        lua.getField("Val", Val);
        std::cout << "Val: " << Val << "\n";

        lua.closeTable(); // close tables when you're done
    }

    std::cout << "\n";

    if(lua.openTable("matrix")) {
        for(unsigned char j=1; j<=3; j++){
            for(unsigned char i=1; i<=3; i++){
                int temp = 0;
                lua.getNestedField(j, i, temp); // matrix[j][i]
                std::cout << temp << " ";
            }
            std::cout << "\n";
        }
        lua.closeTable();
    }
    std::cout << "\n";

    // more table-tests
    if(lua.openTable("Table2")) {
        int X {0};
        lua.getField("X", X);
        std::cout << "X: " << X << "\n";

        int Y {0};
        lua.getField("Y", Y);
        std::cout << "Y: " << Y << "\n";

        if(lua.openNestedTable("Test") )  {
            int A = 0;
            lua.getField("A", A);
            std::cout << "\t A: " << A << "\n";
            int B = 0;
            lua.getField("B", B);
            std::cout << "\t B: " << B << "\n";

            lua.closeTable();
        }
        lua.closeTable();
    }

    // Check lua's internal stack
    std::cout << "\n";
    std::cout << "Lua stack top: " << lua.getTop() << "\n";

    // calling a function from test.lua to compute stuff:
    int test[] = {36, 24};
    int result {0};
    lua.callFunction("gcd", 2, test, result);
    std::cout << "gcd: " << result << "\n";

    std::cout << "\nLua stack top: " << lua.getTop() << "\n";
    std::cout << "\n";

    return 0;
}
<commit_msg>re-structured the tests<commit_after>#ifndef LUA_H
	#include "lua_adapter.hpp"
#endif

int main (int argc, char *argv[]) {

    LuaAdapter lua("test.lua");

    //simply parameterize your application!
    int height {0};
    lua.get("height", height);
    std::cout << "height: " << height << "\n";

    // let's close ..
    lua.close();
    // and (re-)initialize for further tests..
    lua.init();

    // Hint: You CAN change a (default) value of a global lua variable BEFORE loading the actual lua-file
    if(lua.set("GlobalVar", 321)==false){
        std::cout << "Could not set 'GlobalVar'!\n";
    }

    // and THEN load the script:
    lua.load("test.lua");

    //get an int
    int width {0};
    lua.get("width", width);
    std::cout << "width: " << width << "\n";

    //get double
    double number {0};
    lua.get("number", number);
    std::cout << "Number: "<< number << "\n";

    //get string
    std::string title {"empty"};
    lua.get("title", title);
    std::cout << "title: " << title << "\n";

    std::cout << "\n";

    // tables
    if(lua.openTable("Table1")) {
        int ID {0};
        lua.getField("ID", ID);
        std::cout << "ID: " << ID << "\n";

        int Val {0};
        lua.getField("Val", Val);
        std::cout << "Val: " << Val << "\n";

        lua.closeTable(); // close "Table1"
    }

    std::cout << "\n";

    if(lua.openTable("matrix")) {
        for(unsigned char j=1; j<=3; j++){
            for(unsigned char i=1; i<=3; i++){
                int temp = 0;
                lua.getNestedField(j, i, temp); // matrix[j][i]
                std::cout << temp << " ";
            }
            std::cout << "\n";
        }
        lua.closeTable(); // close table "matrix"
    }
    std::cout << "\n";

    // more table-tests
    if(lua.openTable("Table2")) {
        int X {0};
        lua.getField("X", X);
        std::cout << "X: " << X << "\n";

        int Y {0};
        lua.getField("Y", Y);
        std::cout << "Y: " << Y << "\n";

        if(lua.openNestedTable("Test") )  {
            int A = 0;
            lua.getField("A", A);
            std::cout << "\t A: " << A << "\n";
            int B = 0;
            lua.getField("B", B);
            std::cout << "\t B: " << B << "\n";

            lua.closeTable(); // close nested table "Test"
        }
        lua.closeTable(); // close "Table2"
    }

    // Check lua's internal stack
    std::cout << "\n";
    std::cout << "Lua stack top: " << lua.getTop() << "\n"; // should be 0

    // calling a function from test.lua to compute stuff
    int test[] = {36, 24};
    int result {0};
    lua.callFunction("gcd", 2, test, result);
    std::cout << "gcd: " << result << "\n";

    return 0;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////
// generate_primes_oop.cpp
// This example shows how to use the generatePrimes()
// method with classes. The Foo class inherits
// PrimeSieveCallback<T> with T = uint32_t or uint64_t.

#include <primesieve/soe/PrimeSieve.h>
#include <primesieve/soe/PrimeSieveCallback.h>
#include <iostream>

class Foo : public PrimeSieveCallback<unsigned int> {
public:
  void callback(unsigned int prime)
  {
    std::cout << prime << '\n';
  }
};

int main()
{
  Foo foo;
  PrimeSieve ps;
  ps.generatePrimes(0, 1000, &foo);
  return 0;
}
<commit_msg>comment<commit_after>////////////////////////////////////////////////////////////////////
// generate_primes_oop.cpp
// This example shows how to use the generatePrimes()
// methods with classes.

#include <primesieve/soe/PrimeSieve.h>
#include <primesieve/soe/PrimeSieveCallback.h>
#include <iostream>

class Foo : public PrimeSieveCallback<unsigned int> {
public:
  void callback(unsigned int prime)
  {
    std::cout << prime << '\n';
  }
};

int main()
{
  Foo foo;
  PrimeSieve ps;
  ps.generatePrimes(0, 1000, &foo);
  return 0;
}
<|endoftext|>