<commit_before>// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "common.h"

#include "sal.h"
#include "gcenv.structs.h"
#include "gcenv.base.h"

#include <stdlib.h>

#pragma warning(disable:4297)

extern "C" Object * RhNewObject(MethodTable * pMT);
extern "C" Object * RhNewArray(MethodTable * pMT, int32_t elements);
extern "C" void * RhTypeCast_IsInstanceOf(void * pObject, MethodTable * pMT);
extern "C" void * RhTypeCast_CheckCast(void * pObject, MethodTable * pMT);
extern "C" void RhpStelemRef(void * pArray, int index, void * pObj);
extern "C" void * RhpLdelemaRef(void * pArray, int index, MethodTable * pMT);
extern "C" __declspec(noreturn) void RhpThrowEx(void * pEx);

#ifdef CPPCODEGEN

extern "C" Object * __allocate_object(MethodTable * pMT)
{
    return RhNewObject(pMT);
}

extern "C" Object * __allocate_array(size_t elements, MethodTable * pMT)
{
    return RhNewArray(pMT, (int32_t)elements); // TODO: type mismatch
}

extern "C" Object * __castclass(void * obj, MethodTable * pTargetMT)
{
    return (Object *)RhTypeCast_CheckCast(obj, pTargetMT);
}

extern "C" Object * __isinst(void * obj, MethodTable * pTargetMT)
{
    return (Object *)RhTypeCast_IsInstanceOf(obj, pTargetMT);
}

extern "C" void __stelem_ref(void * pArray, unsigned idx, void * obj)
{
    RhpStelemRef(pArray, idx, obj);
}

extern "C" void* __ldelema_ref(void * pArray, unsigned idx, MethodTable * type)
{
    return RhpLdelemaRef(pArray, idx, type);
}

extern "C" void __throw_exception(void * pEx)
{
    RhpThrowEx(pEx);
}

void __range_check_fail()
{
    throw "ThrowRangeOverflowException";
}
#endif // CPPCODEGEN

extern "C" void RhpReversePInvoke2(ReversePInvokeFrame* pRevFrame);
extern "C" void RhpReversePInvokeReturn(ReversePInvokeFrame* pRevFrame);
extern "C" int32_t RhpEnableConservativeStackReporting();
extern "C" void RhpRegisterSimpleModule(SimpleModuleHeader* pModule);
extern "C" void * RhpHandleAlloc(void * pObject, int handleType);

#define DLL_PROCESS_ATTACH      1
extern "C" BOOL WINAPI RtuDllMain(HANDLE hPalInstance, DWORD dwReason, void* pvReserved);

#include "platform.h"

int __initialize_runtime()
{
    RtuDllMain(NULL, DLL_PROCESS_ATTACH, NULL);

    RhpEnableConservativeStackReporting();

    return 0;
}

void __shutdown_runtime()
{
}

void __reverse_pinvoke(ReversePInvokeFrame* pRevFrame)
{
    RhpReversePInvoke2(pRevFrame);
}

void __reverse_pinvoke_return(ReversePInvokeFrame* pRevFrame)
{
    RhpReversePInvokeReturn(pRevFrame);
}

void __register_module(SimpleModuleHeader* pModule)
{
    RhpRegisterSimpleModule(pModule);
}

namespace System_Private_CoreLib { namespace System {

    class Object {
    public:
        MethodTable * get_EEType() { return *(MethodTable **)this; }
    };

    class Array : public Object {
    public:
        int32_t GetArrayLength() {
            return *(int32_t *)((void **)this + 1);
        }
        void * GetArrayData() {
            return (void **)this + 2;
        }
    };

    class String : public Object { public:
        static MethodTable * __getMethodTable();
    };

    class String__Array : public Object { public:
        static MethodTable * __getMethodTable();
    };

    class EETypePtr { public:
        intptr_t m_value;
    };

}; };

using namespace System_Private_CoreLib;

extern "C" void __EEType_System_Private_CoreLib_System_String();
extern "C" void __EEType_System_Private_CoreLib_System_String__Array();

Object * __allocate_string(int32_t len)
{
#ifdef CPPCODEGEN
    return RhNewArray(System::String::__getMethodTable(), len);
#else
    return RhNewArray((MethodTable*)__EEType_System_Private_CoreLib_System_String, len);
#endif
}

void PrintStringObject(System::String *pStringToPrint)
{
    // Get the number of characters in managed string (stored as UTF16)
    int32_t length = *((int32_t*)((char*)(pStringToPrint)+sizeof(intptr_t)));

    // Get the pointer to the start of the character array
    uint16_t *pString = (uint16_t*)((char*)(pStringToPrint)+sizeof(intptr_t) + sizeof(int32_t));

    // Loop to display the string
    int32_t index = 0;
    while (index < length)
    {
        putwchar(*pString);
        pString++;
        index++;
    }
}
extern "C" void __not_yet_implemented(System::String * pMethodName, System::String * pMessage)
{
    printf("ILCompiler failed generating code for this method; execution cannot continue.\n");
    printf("This is likely because of a feature that is not yet implemented in the compiler.\n");
    printf("Method: ");
    PrintStringObject(pMethodName);
    printf("\n\n");
    printf("Reason: ");
    PrintStringObject(pMessage);
    printf("\n");

    exit(-1);
}

extern "C" void __fail_fast()
{
    // TODO: FailFast
    throw "__fail_fast";
}

Object * __load_string_literal(const char * string)
{
    // TODO: Cache/intern string literals
    // TODO: Unicode string literals

    size_t len = strlen(string);

    Object * pString = __allocate_string((int32_t)len);

    uint16_t * p = (uint16_t *)((char*)pString + sizeof(intptr_t) + sizeof(int32_t));
    for (size_t i = 0; i < len; i++)
        p[i] = string[i];
    return pString;
}

extern "C" void RhGetCurrentThreadStackTrace()
{
    throw "RhGetCurrentThreadStackTrace";
}

extern "C" void RhCollect()
{
    throw "RhCollect";
}
extern "C" void RhpCallCatchFunclet()
{
    throw "RhpCallCatchFunclet";
}
extern "C" void RhpCallFilterFunclet()
{
    throw "RhpCallFilterFunclet";
}
extern "C" void RhpCallFinallyFunclet()
{
    throw "RhpCallFinallyFunclet";
}
extern "C" void RhpUniversalTransition()
{
    throw "RhpUniversalTransition";
}
extern "C" void RhpFailFastForPInvokeExceptionPreemp()
{
    throw "RhpFailFastForPInvokeExceptionPreemp";
}
extern "C" void RhpThrowEx(void * pEx)
{
    throw "RhpThrowEx";
}
extern "C" void RhpThrowHwEx()
{
    throw "RhpThrowHwEx";
}
extern "C" void RhpEtwExceptionThrown()
{
    throw "RhpEtwExceptionThrown";
}
extern "C" void RhReRegisterForFinalize()
{
    throw "RhReRegisterForFinalize";
}

extern "C" void * g_pDispatchMapTemporaryWorkaround;
void * g_pDispatchMapTemporaryWorkaround;

extern "C" void __StringTableStart();
extern "C" void __StringTableEnd();
extern "C" void* GetModuleSection(int id, int* length)
{
    struct ModuleSectionSymbol
    {
        void* symbolId;
        size_t length;
    };

    // TODO: emit this table from the compiler per module.
    // !!!
    // The order should be kept in sync with ModuleSectionIds in StartupCodeHelpers.cs in CoreLib.
    static ModuleSectionSymbol symbols[] = {
#ifdef CPPCODEGEN
        { System::String::__getMethodTable(), sizeof(void*) },
        { nullptr, 0 },
#else
        { __EEType_System_Private_CoreLib_System_String, sizeof(void*) },
        { __StringTableStart, (uint8_t*)__StringTableEnd - (uint8_t*)__StringTableStart },
#endif
    };

    *length = (int) symbols[id].length;
    return symbols[id].symbolId;
}

#ifndef CPPCODEGEN
SimpleModuleHeader __module = { NULL, NULL /* &__gcStatics, &__gcStaticsDescs */ };

extern "C" void* __InterfaceDispatchMapTable;
extern "C" void* __GCStaticRegionStart;
extern "C" void* __GCStaticRegionEnd;
int __statics_fixup()
{
    for (void** currentBlock = &__GCStaticRegionStart; currentBlock < &__GCStaticRegionEnd; currentBlock++)
    {
        Object* gcBlock = RhNewObject((MethodTable*)*currentBlock);
        // TODO: OOM handling
        *currentBlock = RhpHandleAlloc(gcBlock, 2 /* Normal */);
    }

    return 0;
}

#if defined(_WIN32)
extern "C" int __managed__Main(int argc, char* argv[]); // TODO: Use wchar_t
int main(int argc, char* argv[]) // TODO: Use wmain and wchar_t
#else
extern "C" int __managed__Main(int argc, char* argv[]);
int main(int argc, char* argv[])
#endif
{
    if (__initialize_runtime() != 0) return -1;
    __register_module(&__module);
    g_pDispatchMapTemporaryWorkaround = (void*)&__InterfaceDispatchMapTable;
    ReversePInvokeFrame frame; __reverse_pinvoke(&frame);

    if (__statics_fixup() != 0) return -1;

    int retval;
    try
    {
		// Managed apps don't see the first args argument (full path of executable) so skip it
		assert(argc > 0);
		retval = __managed__Main(argc, argv);
    }
    catch (const char* &e)
    {
        printf("Call to an unimplemented runtime method; execution cannot continue.\n");
        printf("Method: %s\n", e);
        retval = -1;
    }

    __reverse_pinvoke_return(&frame);
    __shutdown_runtime();
    return retval;
}

#endif // !CPPCODEGEN
<commit_msg>Fix for data declaration<commit_after>// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "common.h"

#include "sal.h"
#include "gcenv.structs.h"
#include "gcenv.base.h"

#include <stdlib.h>

#pragma warning(disable:4297)

extern "C" Object * RhNewObject(MethodTable * pMT);
extern "C" Object * RhNewArray(MethodTable * pMT, int32_t elements);
extern "C" void * RhTypeCast_IsInstanceOf(void * pObject, MethodTable * pMT);
extern "C" void * RhTypeCast_CheckCast(void * pObject, MethodTable * pMT);
extern "C" void RhpStelemRef(void * pArray, int index, void * pObj);
extern "C" void * RhpLdelemaRef(void * pArray, int index, MethodTable * pMT);
extern "C" __declspec(noreturn) void RhpThrowEx(void * pEx);

#ifdef CPPCODEGEN

extern "C" Object * __allocate_object(MethodTable * pMT)
{
    return RhNewObject(pMT);
}

extern "C" Object * __allocate_array(size_t elements, MethodTable * pMT)
{
    return RhNewArray(pMT, (int32_t)elements); // TODO: type mismatch
}

extern "C" Object * __castclass(void * obj, MethodTable * pTargetMT)
{
    return (Object *)RhTypeCast_CheckCast(obj, pTargetMT);
}

extern "C" Object * __isinst(void * obj, MethodTable * pTargetMT)
{
    return (Object *)RhTypeCast_IsInstanceOf(obj, pTargetMT);
}

extern "C" void __stelem_ref(void * pArray, unsigned idx, void * obj)
{
    RhpStelemRef(pArray, idx, obj);
}

extern "C" void* __ldelema_ref(void * pArray, unsigned idx, MethodTable * type)
{
    return RhpLdelemaRef(pArray, idx, type);
}

extern "C" void __throw_exception(void * pEx)
{
    RhpThrowEx(pEx);
}

void __range_check_fail()
{
    throw "ThrowRangeOverflowException";
}
#endif // CPPCODEGEN

extern "C" void RhpReversePInvoke2(ReversePInvokeFrame* pRevFrame);
extern "C" void RhpReversePInvokeReturn(ReversePInvokeFrame* pRevFrame);
extern "C" int32_t RhpEnableConservativeStackReporting();
extern "C" void RhpRegisterSimpleModule(SimpleModuleHeader* pModule);
extern "C" void * RhpHandleAlloc(void * pObject, int handleType);

#define DLL_PROCESS_ATTACH      1
extern "C" BOOL WINAPI RtuDllMain(HANDLE hPalInstance, DWORD dwReason, void* pvReserved);

#include "platform.h"

int __initialize_runtime()
{
    RtuDllMain(NULL, DLL_PROCESS_ATTACH, NULL);

    RhpEnableConservativeStackReporting();

    return 0;
}

void __shutdown_runtime()
{
}

void __reverse_pinvoke(ReversePInvokeFrame* pRevFrame)
{
    RhpReversePInvoke2(pRevFrame);
}

void __reverse_pinvoke_return(ReversePInvokeFrame* pRevFrame)
{
    RhpReversePInvokeReturn(pRevFrame);
}

void __register_module(SimpleModuleHeader* pModule)
{
    RhpRegisterSimpleModule(pModule);
}

namespace System_Private_CoreLib { namespace System {

    class Object {
    public:
        MethodTable * get_EEType() { return *(MethodTable **)this; }
    };

    class Array : public Object {
    public:
        int32_t GetArrayLength() {
            return *(int32_t *)((void **)this + 1);
        }
        void * GetArrayData() {
            return (void **)this + 2;
        }
    };

    class String : public Object { public:
        static MethodTable * __getMethodTable();
    };

    class String__Array : public Object { public:
        static MethodTable * __getMethodTable();
    };

    class EETypePtr { public:
        intptr_t m_value;
    };

}; };

using namespace System_Private_CoreLib;

extern "C" void* __EEType_System_Private_CoreLib_System_String;

Object * __allocate_string(int32_t len)
{
#ifdef CPPCODEGEN
    return RhNewArray(System::String::__getMethodTable(), len);
#else
    return RhNewArray((MethodTable*)__EEType_System_Private_CoreLib_System_String, len);
#endif
}

void PrintStringObject(System::String *pStringToPrint)
{
    // Get the number of characters in managed string (stored as UTF16)
    int32_t length = *((int32_t*)((char*)(pStringToPrint)+sizeof(intptr_t)));

    // Get the pointer to the start of the character array
    uint16_t *pString = (uint16_t*)((char*)(pStringToPrint)+sizeof(intptr_t) + sizeof(int32_t));

    // Loop to display the string
    int32_t index = 0;
    while (index < length)
    {
        putwchar(*pString);
        pString++;
        index++;
    }
}
extern "C" void __not_yet_implemented(System::String * pMethodName, System::String * pMessage)
{
    printf("ILCompiler failed generating code for this method; execution cannot continue.\n");
    printf("This is likely because of a feature that is not yet implemented in the compiler.\n");
    printf("Method: ");
    PrintStringObject(pMethodName);
    printf("\n\n");
    printf("Reason: ");
    PrintStringObject(pMessage);
    printf("\n");

    exit(-1);
}

extern "C" void __fail_fast()
{
    // TODO: FailFast
    throw "__fail_fast";
}

Object * __load_string_literal(const char * string)
{
    // TODO: Cache/intern string literals
    // TODO: Unicode string literals

    size_t len = strlen(string);

    Object * pString = __allocate_string((int32_t)len);

    uint16_t * p = (uint16_t *)((char*)pString + sizeof(intptr_t) + sizeof(int32_t));
    for (size_t i = 0; i < len; i++)
        p[i] = string[i];
    return pString;
}

extern "C" void RhGetCurrentThreadStackTrace()
{
    throw "RhGetCurrentThreadStackTrace";
}

extern "C" void RhCollect()
{
    throw "RhCollect";
}
extern "C" void RhpCallCatchFunclet()
{
    throw "RhpCallCatchFunclet";
}
extern "C" void RhpCallFilterFunclet()
{
    throw "RhpCallFilterFunclet";
}
extern "C" void RhpCallFinallyFunclet()
{
    throw "RhpCallFinallyFunclet";
}
extern "C" void RhpUniversalTransition()
{
    throw "RhpUniversalTransition";
}
extern "C" void RhpFailFastForPInvokeExceptionPreemp()
{
    throw "RhpFailFastForPInvokeExceptionPreemp";
}
extern "C" void RhpThrowEx(void * pEx)
{
    throw "RhpThrowEx";
}
extern "C" void RhpThrowHwEx()
{
    throw "RhpThrowHwEx";
}
extern "C" void RhpEtwExceptionThrown()
{
    throw "RhpEtwExceptionThrown";
}
extern "C" void RhReRegisterForFinalize()
{
    throw "RhReRegisterForFinalize";
}

extern "C" void * g_pDispatchMapTemporaryWorkaround;
void * g_pDispatchMapTemporaryWorkaround;

extern "C" void* __StringTableStart;
extern "C" void* __StringTableEnd;
extern "C" void* GetModuleSection(int id, int* length)
{
    struct ModuleSectionSymbol
    {
        void* symbolId;
        size_t length;
    };

    // TODO: emit this table from the compiler per module.
    // !!!
    // The order should be kept in sync with ModuleSectionIds in StartupCodeHelpers.cs in CoreLib.
    static ModuleSectionSymbol symbols[] = {
#ifdef CPPCODEGEN
        { System::String::__getMethodTable(), sizeof(void*) },
        { nullptr, 0 },
#else
        { &__EEType_System_Private_CoreLib_System_String, sizeof(void*) },
        { &__StringTableStart, (uint8_t*)&__StringTableEnd - (uint8_t*)&__StringTableStart },
#endif
    };

    *length = (int) symbols[id].length;
    return symbols[id].symbolId;
}

#ifndef CPPCODEGEN
SimpleModuleHeader __module = { NULL, NULL /* &__gcStatics, &__gcStaticsDescs */ };

extern "C" void* __InterfaceDispatchMapTable;
extern "C" void* __GCStaticRegionStart;
extern "C" void* __GCStaticRegionEnd;
int __statics_fixup()
{
    for (void** currentBlock = &__GCStaticRegionStart; currentBlock < &__GCStaticRegionEnd; currentBlock++)
    {
        Object* gcBlock = RhNewObject((MethodTable*)*currentBlock);
        // TODO: OOM handling
        *currentBlock = RhpHandleAlloc(gcBlock, 2 /* Normal */);
    }

    return 0;
}

#if defined(_WIN32)
extern "C" int __managed__Main(int argc, char* argv[]); // TODO: Use wchar_t
int main(int argc, char* argv[]) // TODO: Use wmain and wchar_t
#else
extern "C" int __managed__Main(int argc, char* argv[]);
int main(int argc, char* argv[])
#endif
{
    if (__initialize_runtime() != 0) return -1;
    __register_module(&__module);
    g_pDispatchMapTemporaryWorkaround = (void*)&__InterfaceDispatchMapTable;
    ReversePInvokeFrame frame; __reverse_pinvoke(&frame);

    if (__statics_fixup() != 0) return -1;

    int retval;
    try
    {
		// Managed apps don't see the first args argument (full path of executable) so skip it
		assert(argc > 0);
		retval = __managed__Main(argc, argv);
    }
    catch (const char* &e)
    {
        printf("Call to an unimplemented runtime method; execution cannot continue.\n");
        printf("Method: %s\n", e);
        retval = -1;
    }

    __reverse_pinvoke_return(&frame);
    __shutdown_runtime();
    return retval;
}

#endif // !CPPCODEGEN
<|endoftext|>


<commit_before>/**
 * Copyright 2013 Truphone
 */
#include "include/KeyCommand.h"

#include <bb/cascades/AbstractTextControl>
#include <bb/cascades/Application>
#include <bb/cascades/Control>

#include "Utils.h"
#include "Connection.h"

using bb::cascades::AbstractTextControl;
using bb::cascades::Application;
using bb::cascades::Control;

namespace truphone
{
namespace test
{
namespace cascades
{
    const QString KeyCommand::CMD_NAME = "key";

    KeyCommand::KeyCommand(Connection * const socket,
                           QObject * parent)
        : Command(parent),
          client(socket)
    {
    }

    KeyCommand::~KeyCommand()
    {
    }

    bool KeyCommand::executeCommand(QStringList * const arguments)
    {
        bool ret = false;
        int theKey = 0, isPressed = 0, isAlt = 0, isShift = 0, isCtrl = 0, processed = 0;
        QString target;

        for (int param = 0 ; param < 6 ; param++)
        {
            bool ok = false;
            switch (param)
            {
            case 0:
                theKey = QString(arguments->first()).toInt(&ok);
                break;
            case 1:
                isPressed = QString(arguments->first()).toInt(&ok);
                break;
            case 2:
                isAlt = QString(arguments->first()).toInt(&ok);
                break;
            case 3:
                isShift = QString(arguments->first()).toInt(&ok);
                break;
            case 4:
                isCtrl = QString(arguments->first()).toInt(&ok);
                break;
            case 5:
                target = arguments->first();
                ok = not target.isNull() and not target.isEmpty();
                break;
            default:
                break;
            }
            if (ok)
            {
                processed++;
            }
            arguments->removeFirst();
        }

        Q_UNUSED(isAlt);
        Q_UNUSED(isShift);
        Q_UNUSED(isCtrl);

        if (processed not_eq 6)  // 6 items are expected
        {
            this->client->write(tr("ERROR: wrong number of arguments to key command") + "\r\n");
        }
        else
        {
            QObject * const targetObject = Utils::findObject(target);
            if (not targetObject)
            {
                this->client->write(tr("ERROR: Couldn't find the target of the keypress") + "\r\n");
            }
            else
            {
                Control * const ctrl = qobject_cast<Control*>(targetObject);
                if (ctrl)
                {
                    if (not ctrl->isFocused())
                    {
                        ctrl->requestFocus();
                    }
                    AbstractTextControl * const field =
                            qobject_cast<AbstractTextControl*>(ctrl);
                    if (field)
                    {
                        if (isPressed)
                        {
                            if (theKey >= ' ' and theKey <= 'z')
                            {
                                field->setProperty("text",
                                                   QVariant(field->property("text").toString()
                                                              + QChar(theKey)));
                            }
                            else
                            {
                                switch (theKey)
                                {
                                    case '\b':
                                        field->setText(field->text().left(
                                                           field->text().length()-1));
                                        break;
                                    /* might need some extra special cases here later */
                                    default:
                                        /* dropped */
                                        break;
                                }
                            }
                        }
                        ret = true;
                    }
                    else
                    {
                        // for propogation (parents might not understand it, thats fine)
                        ret = true;
                    }
                }
                else
                {
                    // for propogation (parents might not understand it, thats fine)
                    ret = true;
                }
            }
        }
        return ret;
    }

    void KeyCommand::showHelp()
    {
        this->client->write(tr("> key <code> <pressed> <alt> <shift> <ctrl> <target>") + "\r\n");
        this->client->write(tr("Simulate a key press") + "\r\n");
    }
}  // namespace cascades
}  // namespace test
}  // namespace truphone
<commit_msg>Fix for invalid arguments on the Key command.<commit_after>/**
 * Copyright 2013 Truphone
 */
#include "include/KeyCommand.h"

#include <bb/cascades/AbstractTextControl>
#include <bb/cascades/Application>
#include <bb/cascades/Control>

#include "Utils.h"
#include "Connection.h"

using bb::cascades::AbstractTextControl;
using bb::cascades::Application;
using bb::cascades::Control;

namespace truphone
{
namespace test
{
namespace cascades
{
    const QString KeyCommand::CMD_NAME = "key";

    KeyCommand::KeyCommand(Connection * const socket,
                           QObject * parent)
        : Command(parent),
          client(socket)
    {
    }

    KeyCommand::~KeyCommand()
    {
    }

    bool KeyCommand::executeCommand(QStringList * const arguments)
    {
        bool ret = false;
        int theKey = 0, isPressed = 0, isAlt = 0, isShift = 0, isCtrl = 0, processed = 0;
        QString target;

        for (int param = 0 ; param < 6 ; param++)
        {
            if (not arguments->isEmpty())
            {
                bool ok = false;
                switch (param)
                {
                case 0:
                    theKey = QString(arguments->first()).toInt(&ok);
                    break;
                case 1:
                    isPressed = QString(arguments->first()).toInt(&ok);
                    break;
                case 2:
                    isAlt = QString(arguments->first()).toInt(&ok);
                    break;
                case 3:
                    isShift = QString(arguments->first()).toInt(&ok);
                    break;
                case 4:
                    isCtrl = QString(arguments->first()).toInt(&ok);
                    break;
                case 5:
                    target = arguments->first();
                    ok = not target.isNull() and not target.isEmpty();
                    break;
                default:
                    break;
                }
                if (ok)
                {
                    processed++;
                }
                arguments->removeFirst();
            }
        }

        Q_UNUSED(isAlt);
        Q_UNUSED(isShift);
        Q_UNUSED(isCtrl);

        if (processed not_eq 6)  // 6 items are expected
        {
            this->client->write(tr("ERROR: wrong number of arguments to key command") + "\r\n");
        }
        else
        {
            QObject * const targetObject = Utils::findObject(target);
            if (not targetObject)
            {
                this->client->write(tr("ERROR: Couldn't find the target of the keypress") + "\r\n");
            }
            else
            {
                Control * const ctrl = qobject_cast<Control*>(targetObject);
                if (ctrl)
                {
                    if (not ctrl->isFocused())
                    {
                        ctrl->requestFocus();
                    }
                    AbstractTextControl * const field =
                            qobject_cast<AbstractTextControl*>(ctrl);
                    if (field)
                    {
                        if (isPressed)
                        {
                            if (theKey >= ' ' and theKey <= 'z')
                            {
                                field->setProperty("text",
                                                   QVariant(field->property("text").toString()
                                                              + QChar(theKey)));
                            }
                            else
                            {
                                switch (theKey)
                                {
                                    case '\b':
                                        field->setText(field->text().left(
                                                           field->text().length()-1));
                                        break;
                                    /* might need some extra special cases here later */
                                    default:
                                        /* dropped */
                                        break;
                                }
                            }
                        }
                        ret = true;
                    }
                    else
                    {
                        // for propogation (parents might not understand it, thats fine)
                        ret = true;
                    }
                }
                else
                {
                    // for propogation (parents might not understand it, thats fine)
                    ret = true;
                }
            }
        }
        return ret;
    }

    void KeyCommand::showHelp()
    {
        this->client->write(tr("> key <code> <pressed> <alt> <shift> <ctrl> <target>") + "\r\n");
        this->client->write(tr("Simulate a key press") + "\r\n");
    }
}  // namespace cascades
}  // namespace test
}  // namespace truphone
<|endoftext|>


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

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

#ifndef _DBA_COREAPI_QUERYDESCRIPTOR_HXX_
#include "querydescriptor.hxx"
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _DBACORE_DEFINITIONCOLUMN_HXX_
#include "definitioncolumn.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::util;
using namespace ::comphelper;
using namespace ::osl;
using namespace ::cppu;

//........................................................................
namespace dbaccess
{
//........................................................................

//==========================================================================
//= OQueryDescriptor
//==========================================================================
DBG_NAME(OQueryDescriptor)
//--------------------------------------------------------------------------
OQueryDescriptor::OQueryDescriptor()
    :OQueryDescriptor_Base(m_aMutex,*this)
    ,ODataSettings(m_aBHelper,sal_True)
{
    DBG_CTOR(OQueryDescriptor,NULL);
    registerProperties();
    ODataSettings::registerPropertiesFor(this);
}

//--------------------------------------------------------------------------
OQueryDescriptor::OQueryDescriptor(const Reference< XPropertySet >& _rxCommandDefinition)
    :OQueryDescriptor_Base(m_aMutex,*this)
    ,ODataSettings(m_aBHelper,sal_True)
{
    DBG_CTOR(OQueryDescriptor,NULL);
    registerProperties();
    ODataSettings::registerPropertiesFor(this);

    osl_incrementInterlockedCount(&m_refCount);

    OSL_ENSURE(_rxCommandDefinition.is(), "OQueryDescriptor_Base::OQueryDescriptor_Base : invalid source property set !");
    try
    {
        ::comphelper::copyProperties(_rxCommandDefinition,this);
    }
    catch(Exception&)
    {
        OSL_ENSURE(sal_False, "OQueryDescriptor_Base::OQueryDescriptor_Base: caught an exception!");
    }
    osl_decrementInterlockedCount(&m_refCount);
}

//--------------------------------------------------------------------------
OQueryDescriptor::OQueryDescriptor(const OQueryDescriptor_Base& _rSource)
    :OQueryDescriptor_Base(_rSource,*this)
    ,ODataSettings(m_aBHelper,sal_True)
{
    DBG_CTOR(OQueryDescriptor,NULL);
    registerProperties();
    ODataSettings::registerPropertiesFor(this);
}
// -----------------------------------------------------------------------------
IMPLEMENT_TYPEPROVIDER2(OQueryDescriptor,OQueryDescriptor_Base,ODataSettings);
IMPLEMENT_FORWARD_XINTERFACE3( OQueryDescriptor,OWeakObject,OQueryDescriptor_Base,ODataSettings)
//--------------------------------------------------------------------------
void OQueryDescriptor::registerProperties()
{
    // the properties which OCommandBase supplies (it has no own registration, as it's not derived from
    // a OPropertyStateContainer)
    registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND|PropertyAttribute::CONSTRAINED,
                    &m_sElementName, ::getCppuType(&m_sElementName));

    registerProperty(PROPERTY_COMMAND, PROPERTY_ID_COMMAND, PropertyAttribute::BOUND,
                    &m_sCommand, ::getCppuType(&m_sCommand));

    registerProperty(PROPERTY_USE_ESCAPE_PROCESSING, PROPERTY_ID_USE_ESCAPE_PROCESSING, PropertyAttribute::BOUND,
                    &m_bEscapeProcessing, ::getBooleanCppuType());

    registerProperty(PROPERTY_UPDATE_TABLENAME, PROPERTY_ID_UPDATE_TABLENAME, PropertyAttribute::BOUND,
                    &m_sUpdateTableName, ::getCppuType(&m_sUpdateTableName));

    registerProperty(PROPERTY_UPDATE_SCHEMANAME, PROPERTY_ID_UPDATE_SCHEMANAME, PropertyAttribute::BOUND,
                    &m_sUpdateSchemaName, ::getCppuType(&m_sUpdateSchemaName));

    registerProperty(PROPERTY_UPDATE_CATALOGNAME, PROPERTY_ID_UPDATE_CATALOGNAME, PropertyAttribute::BOUND,
                    &m_sUpdateCatalogName, ::getCppuType(&m_sUpdateCatalogName));

    registerProperty(PROPERTY_LAYOUTINFORMATION, PROPERTY_ID_LAYOUTINFORMATION, PropertyAttribute::BOUND,
                    &m_aLayoutInformation, ::getCppuType(&m_aLayoutInformation));
}
// -----------------------------------------------------------------------------
//--------------------------------------------------------------------------
Reference< XPropertySetInfo > SAL_CALL OQueryDescriptor::getPropertySetInfo(  ) throw(RuntimeException)
{
    return createPropertySetInfo( getInfoHelper() ) ;
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OQueryDescriptor::getInfoHelper()
{
    return *getArrayHelper();
}
//--------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OQueryDescriptor::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}

// -----------------------------------------------------------------------------
DBG_NAME(OQueryDescriptor_Base);
//--------------------------------------------------------------------------
OQueryDescriptor_Base::OQueryDescriptor_Base(::osl::Mutex&  _rMutex,::cppu::OWeakObject& _rMySelf)
    :m_bColumnsOutOfDate(sal_True)
    ,m_rMutex(_rMutex)
{
    DBG_CTOR(OQueryDescriptor_Base,NULL);
    m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this);
}
//--------------------------------------------------------------------------
OQueryDescriptor_Base::OQueryDescriptor_Base(const OQueryDescriptor_Base& _rSource,::cppu::OWeakObject& _rMySelf)
    :m_bColumnsOutOfDate(sal_True)
    ,m_rMutex(_rSource.m_rMutex)
{
    DBG_CTOR(OQueryDescriptor_Base,NULL);
    m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this);

    m_sCommand = _rSource.m_sCommand;
    m_bEscapeProcessing = _rSource.m_bEscapeProcessing;
    m_sUpdateTableName = _rSource.m_sUpdateTableName;
    m_sUpdateSchemaName = _rSource.m_sUpdateSchemaName;
    m_sUpdateCatalogName = _rSource.m_sUpdateCatalogName;
    m_aLayoutInformation = _rSource.m_aLayoutInformation;
}

//--------------------------------------------------------------------------
OQueryDescriptor_Base::~OQueryDescriptor_Base()
{
    m_pColumns->acquire();
    m_pColumns->disposing();
    delete m_pColumns;

    DBG_DTOR(OQueryDescriptor_Base,NULL);
}
// -----------------------------------------------------------------------------
sal_Int64 SAL_CALL OQueryDescriptor_Base::getSomething( const Sequence< sal_Int8 >& _rIdentifier ) throw(RuntimeException)
{
    if (_rIdentifier.getLength() != 16)
        return 0;

    if (0 == rtl_compareMemory(getImplementationId().getConstArray(),  _rIdentifier.getConstArray(), 16 ) )
        return reinterpret_cast<sal_Int64>(this);

    return 0;
}
//--------------------------------------------------------------------------
IMPLEMENT_IMPLEMENTATION_ID(OQueryDescriptor_Base)
//--------------------------------------------------------------------------
void OQueryDescriptor_Base::setColumnsOutOfDate( sal_Bool _bOutOfDate )
{
    m_bColumnsOutOfDate = _bOutOfDate;
    if ( !m_bColumnsOutOfDate )
        m_pColumns->setInitialized();
}

//--------------------------------------------------------------------------
void OQueryDescriptor_Base::implAppendColumn( const ::rtl::OUString& _rName, OColumn* _pColumn )
{
    m_pColumns->append( _rName, _pColumn );
}

//--------------------------------------------------------------------------
void OQueryDescriptor_Base::clearColumns( )
{
    m_pColumns->clearColumns();

    setColumnsOutOfDate();
}

//--------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL OQueryDescriptor_Base::getColumns( ) throw (RuntimeException)
{
    MutexGuard aGuard(m_rMutex);

    if ( isColumnsOutOfDate() )
    {
        // clear the current columns
        clearColumns();

        // do this before rebuildColumns. This prevents recursion, e.g. in the case where we
        // have queries with cyclic references:
        // foo := SELECT * FROM bar
        // bar := SELECT * FROM foo
        setColumnsOutOfDate( sal_False );

        // rebuild them
        try
        {
            rebuildColumns();
        }
        catch(...)
        {
            setColumnsOutOfDate( sal_True );
            throw;
        }
    }

    return m_pColumns;
}

//--------------------------------------------------------------------------
::rtl::OUString SAL_CALL OQueryDescriptor_Base::getImplementationName(  ) throw(RuntimeException)
{
    return ::rtl::OUString::createFromAscii("com.sun.star.sdb.OQueryDescriptor");
}

//--------------------------------------------------------------------------
sal_Bool SAL_CALL OQueryDescriptor_Base::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
    return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0;
}

//--------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OQueryDescriptor_Base::getSupportedServiceNames(  ) throw(RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(2);
    aSupported.getArray()[0] = SERVICE_SDB_DATASETTINGS;
    aSupported.getArray()[1] = SERVICE_SDB_QUERYDESCRIPTOR;
    return aSupported;
}
//--------------------------------------------------------------------------
void OQueryDescriptor_Base::disposeColumns()
{
    m_pColumns->disposing();
}

// -----------------------------------------------------------------------------
void OQueryDescriptor_Base::columnAppended( const Reference< XPropertySet >& /*_rxSourceDescriptor*/ )
{
    // not interested in
}

// -----------------------------------------------------------------------------
void OQueryDescriptor_Base::columnDropped(const ::rtl::OUString& /*_sName*/)
{
    // not interested in
}

// -----------------------------------------------------------------------------
Reference< XPropertySet > OQueryDescriptor_Base::createColumnDescriptor()
{
    OSL_ENSURE( false, "OQueryDescriptor_Base::createColumnDescriptor: called why?" );
    return NULL;
}

// -----------------------------------------------------------------------------
void OQueryDescriptor_Base::rebuildColumns( )
{
}

// -----------------------------------------------------------------------------
// IRefreshableColumns
void OQueryDescriptor_Base::refreshColumns()
{
    MutexGuard aGuard( m_rMutex );

    clearColumns();
    rebuildColumns();
}

//------------------------------------------------------------------------------
OColumn* OQueryDescriptor_Base::createColumn(const ::rtl::OUString& _rName) const
{
    return new OTableColumn(_rName);
}
// -----------------------------------------------------------------------------
//........................................................................
}   // namespace dbaccess
//........................................................................

<commit_msg>INTEGRATION: CWS dba24b (1.31.96); FILE MERGED 2007/08/16 06:14:42 oj 1.31.96.1: #i56898# clean up of the class structure<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: querydescriptor.cxx,v $
 *
 *  $Revision: 1.32 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-01 15:02:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _DBA_COREAPI_QUERYDESCRIPTOR_HXX_
#include "querydescriptor.hxx"
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _DBACORE_DEFINITIONCOLUMN_HXX_
#include "definitioncolumn.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::util;
using namespace ::comphelper;
using namespace ::osl;
using namespace ::cppu;

//........................................................................
namespace dbaccess
{
//........................................................................

//==========================================================================
//= OQueryDescriptor
//==========================================================================
DBG_NAME(OQueryDescriptor)
//--------------------------------------------------------------------------
OQueryDescriptor::OQueryDescriptor()
    :OQueryDescriptor_Base(m_aMutex,*this)
    ,ODataSettings(m_aBHelper,sal_True)
{
    DBG_CTOR(OQueryDescriptor,NULL);
    registerProperties();
    ODataSettings::registerPropertiesFor(this);
}

//--------------------------------------------------------------------------
OQueryDescriptor::OQueryDescriptor(const Reference< XPropertySet >& _rxCommandDefinition)
    :OQueryDescriptor_Base(m_aMutex,*this)
    ,ODataSettings(m_aBHelper,sal_True)
{
    DBG_CTOR(OQueryDescriptor,NULL);
    registerProperties();
    ODataSettings::registerPropertiesFor(this);

    osl_incrementInterlockedCount(&m_refCount);

    OSL_ENSURE(_rxCommandDefinition.is(), "OQueryDescriptor_Base::OQueryDescriptor_Base : invalid source property set !");
    try
    {
        ::comphelper::copyProperties(_rxCommandDefinition,this);
    }
    catch(Exception&)
    {
        OSL_ENSURE(sal_False, "OQueryDescriptor_Base::OQueryDescriptor_Base: caught an exception!");
    }
    osl_decrementInterlockedCount(&m_refCount);
}

//--------------------------------------------------------------------------
OQueryDescriptor::OQueryDescriptor(const OQueryDescriptor_Base& _rSource)
    :OQueryDescriptor_Base(_rSource,*this)
    ,ODataSettings(m_aBHelper,sal_True)
{
    DBG_CTOR(OQueryDescriptor,NULL);
    registerProperties();
    ODataSettings::registerPropertiesFor(this);
}
// -----------------------------------------------------------------------------
OQueryDescriptor::~OQueryDescriptor()
{
    DBG_DTOR(OQueryDescriptor,NULL);
}
// -----------------------------------------------------------------------------
IMPLEMENT_TYPEPROVIDER2(OQueryDescriptor,OQueryDescriptor_Base,ODataSettings);
IMPLEMENT_FORWARD_XINTERFACE3( OQueryDescriptor,OWeakObject,OQueryDescriptor_Base,ODataSettings)
//--------------------------------------------------------------------------
void OQueryDescriptor::registerProperties()
{
    // the properties which OCommandBase supplies (it has no own registration, as it's not derived from
    // a OPropertyStateContainer)
    registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND|PropertyAttribute::CONSTRAINED,
                    &m_sElementName, ::getCppuType(&m_sElementName));

    registerProperty(PROPERTY_COMMAND, PROPERTY_ID_COMMAND, PropertyAttribute::BOUND,
                    &m_sCommand, ::getCppuType(&m_sCommand));

    registerProperty(PROPERTY_USE_ESCAPE_PROCESSING, PROPERTY_ID_USE_ESCAPE_PROCESSING, PropertyAttribute::BOUND,
                    &m_bEscapeProcessing, ::getBooleanCppuType());

    registerProperty(PROPERTY_UPDATE_TABLENAME, PROPERTY_ID_UPDATE_TABLENAME, PropertyAttribute::BOUND,
                    &m_sUpdateTableName, ::getCppuType(&m_sUpdateTableName));

    registerProperty(PROPERTY_UPDATE_SCHEMANAME, PROPERTY_ID_UPDATE_SCHEMANAME, PropertyAttribute::BOUND,
                    &m_sUpdateSchemaName, ::getCppuType(&m_sUpdateSchemaName));

    registerProperty(PROPERTY_UPDATE_CATALOGNAME, PROPERTY_ID_UPDATE_CATALOGNAME, PropertyAttribute::BOUND,
                    &m_sUpdateCatalogName, ::getCppuType(&m_sUpdateCatalogName));

    registerProperty(PROPERTY_LAYOUTINFORMATION, PROPERTY_ID_LAYOUTINFORMATION, PropertyAttribute::BOUND,
                    &m_aLayoutInformation, ::getCppuType(&m_aLayoutInformation));
}
// -----------------------------------------------------------------------------
//--------------------------------------------------------------------------
Reference< XPropertySetInfo > SAL_CALL OQueryDescriptor::getPropertySetInfo(  ) throw(RuntimeException)
{
    return createPropertySetInfo( getInfoHelper() ) ;
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OQueryDescriptor::getInfoHelper()
{
    return *getArrayHelper();
}
//--------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OQueryDescriptor::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}

// -----------------------------------------------------------------------------
DBG_NAME(OQueryDescriptor_Base);
//--------------------------------------------------------------------------
OQueryDescriptor_Base::OQueryDescriptor_Base(::osl::Mutex&  _rMutex,::cppu::OWeakObject& _rMySelf)
    :m_bColumnsOutOfDate(sal_True)
    ,m_rMutex(_rMutex)
{
    DBG_CTOR(OQueryDescriptor_Base,NULL);
    m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this);
}
//--------------------------------------------------------------------------
OQueryDescriptor_Base::OQueryDescriptor_Base(const OQueryDescriptor_Base& _rSource,::cppu::OWeakObject& _rMySelf)
    :m_bColumnsOutOfDate(sal_True)
    ,m_rMutex(_rSource.m_rMutex)
{
    DBG_CTOR(OQueryDescriptor_Base,NULL);
    m_pColumns = new OColumns(_rMySelf, m_rMutex, sal_True,::std::vector< ::rtl::OUString>(), this,this);

    m_sCommand = _rSource.m_sCommand;
    m_bEscapeProcessing = _rSource.m_bEscapeProcessing;
    m_sUpdateTableName = _rSource.m_sUpdateTableName;
    m_sUpdateSchemaName = _rSource.m_sUpdateSchemaName;
    m_sUpdateCatalogName = _rSource.m_sUpdateCatalogName;
    m_aLayoutInformation = _rSource.m_aLayoutInformation;
}

//--------------------------------------------------------------------------
OQueryDescriptor_Base::~OQueryDescriptor_Base()
{
    m_pColumns->acquire();
    m_pColumns->disposing();
    delete m_pColumns;

    DBG_DTOR(OQueryDescriptor_Base,NULL);
}
// -----------------------------------------------------------------------------
sal_Int64 SAL_CALL OQueryDescriptor_Base::getSomething( const Sequence< sal_Int8 >& _rIdentifier ) throw(RuntimeException)
{
    if (_rIdentifier.getLength() != 16)
        return 0;

    if (0 == rtl_compareMemory(getImplementationId().getConstArray(),  _rIdentifier.getConstArray(), 16 ) )
        return reinterpret_cast<sal_Int64>(this);

    return 0;
}
//--------------------------------------------------------------------------
IMPLEMENT_IMPLEMENTATION_ID(OQueryDescriptor_Base)
//--------------------------------------------------------------------------
void OQueryDescriptor_Base::setColumnsOutOfDate( sal_Bool _bOutOfDate )
{
    m_bColumnsOutOfDate = _bOutOfDate;
    if ( !m_bColumnsOutOfDate )
        m_pColumns->setInitialized();
}

//--------------------------------------------------------------------------
void OQueryDescriptor_Base::implAppendColumn( const ::rtl::OUString& _rName, OColumn* _pColumn )
{
    m_pColumns->append( _rName, _pColumn );
}

//--------------------------------------------------------------------------
void OQueryDescriptor_Base::clearColumns( )
{
    m_pColumns->clearColumns();

    setColumnsOutOfDate();
}

//--------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL OQueryDescriptor_Base::getColumns( ) throw (RuntimeException)
{
    MutexGuard aGuard(m_rMutex);

    if ( isColumnsOutOfDate() )
    {
        // clear the current columns
        clearColumns();

        // do this before rebuildColumns. This prevents recursion, e.g. in the case where we
        // have queries with cyclic references:
        // foo := SELECT * FROM bar
        // bar := SELECT * FROM foo
        setColumnsOutOfDate( sal_False );

        // rebuild them
        try
        {
            rebuildColumns();
        }
        catch(...)
        {
            setColumnsOutOfDate( sal_True );
            throw;
        }
    }

    return m_pColumns;
}

//--------------------------------------------------------------------------
::rtl::OUString SAL_CALL OQueryDescriptor_Base::getImplementationName(  ) throw(RuntimeException)
{
    return ::rtl::OUString::createFromAscii("com.sun.star.sdb.OQueryDescriptor");
}

//--------------------------------------------------------------------------
sal_Bool SAL_CALL OQueryDescriptor_Base::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
    return ::comphelper::findValue(getSupportedServiceNames(), _rServiceName, sal_True).getLength() != 0;
}

//--------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OQueryDescriptor_Base::getSupportedServiceNames(  ) throw(RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(2);
    aSupported.getArray()[0] = SERVICE_SDB_DATASETTINGS;
    aSupported.getArray()[1] = SERVICE_SDB_QUERYDESCRIPTOR;
    return aSupported;
}
//--------------------------------------------------------------------------
void OQueryDescriptor_Base::disposeColumns()
{
    m_pColumns->disposing();
}

// -----------------------------------------------------------------------------
void OQueryDescriptor_Base::columnAppended( const Reference< XPropertySet >& /*_rxSourceDescriptor*/ )
{
    // not interested in
}

// -----------------------------------------------------------------------------
void OQueryDescriptor_Base::columnDropped(const ::rtl::OUString& /*_sName*/)
{
    // not interested in
}

// -----------------------------------------------------------------------------
Reference< XPropertySet > OQueryDescriptor_Base::createColumnDescriptor()
{
    OSL_ENSURE( false, "OQueryDescriptor_Base::createColumnDescriptor: called why?" );
    return NULL;
}

// -----------------------------------------------------------------------------
void OQueryDescriptor_Base::rebuildColumns( )
{
}

// -----------------------------------------------------------------------------
// IRefreshableColumns
void OQueryDescriptor_Base::refreshColumns()
{
    MutexGuard aGuard( m_rMutex );

    clearColumns();
    rebuildColumns();
}

//------------------------------------------------------------------------------
OColumn* OQueryDescriptor_Base::createColumn(const ::rtl::OUString& _rName) const
{
    return new OTableColumn(_rName);
}
// -----------------------------------------------------------------------------
//........................................................................
}   // namespace dbaccess
//........................................................................

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 Telmo Menezes.
 * telmo@telmomenezes.com
 */

#include "drmap.h"
#include "utils.h"

#include "emd_hat_signatures_interface.hpp"

#include <stdlib.h>
#include <strings.h>
#include <stdio.h>

namespace syn
{

DRMap::DRMap(unsigned int bin_number, double min_val_hor, double max_val_hor,
                double min_val_ver, double max_val_ver)
{
    this->bin_number = bin_number;
    this->min_val_hor = min_val_hor;
    this->max_val_hor = max_val_hor;
    this->min_val_ver = min_val_ver;
    this->max_val_ver = max_val_ver;
    data = (double*)malloc(bin_number * bin_number * sizeof(double));

    clear();
}

DRMap::~DRMap()
{
    free(data);
}

void DRMap::clear()
{
    bzero(data, bin_number * bin_number * sizeof(double));
}

void DRMap::set_value(unsigned int x, unsigned int y, double val)
{
    data[(y * bin_number) + x] = val;
}

void DRMap::inc_value(unsigned int x, unsigned int y)
{
    data[(y * bin_number) + x] += 1;
}

double DRMap::get_value(unsigned int x, unsigned int y)
{
    return data[(y * bin_number) + x];
}

void DRMap::log_scale()
{
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            if(data[(y * bin_number) + x] > 0) {
                data[(y * bin_number) + x] = log(data[(y * bin_number) + x]);
            }
        }
    }
}

void DRMap::normalize()
{
    // find max value
    double max = 0;
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            if(data[(y * bin_number) + x] > max) {
                max = data[(y * bin_number) + x];
            }
        }
    }

    // normalize by max
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            data[(y * bin_number) + x] = data[(y * bin_number) + x] / max;
        }
    }
}

void DRMap::binary()
{
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            if(data[(y * bin_number) + x] > 0) {
                data[(y * bin_number) + x] = 1;
            }
        }
    }
}

double DRMap::total()
{
    double total = 0;

    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            total += data[(y * bin_number) + x];
        }
    }

    return total;
}

double DRMap::simple_dist(DRMap* map)
{
    double dist = 0;
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            dist += fabs(data[(y * bin_number) + x] - map->data[(y * map->bin_number) + x]);
        }
    }
    return dist;
}

double ground_dist(feature_tt* feature1, feature_tt* feature2)
{
    double deltaX = feature1->x - feature2->x;
    double deltaY = feature1->y - feature2->y;
    double dist = sqrt((deltaX * deltaX) + (deltaY * deltaY));
    //double dist = (deltaX * deltaX) + (deltaY * deltaY);
    return dist;
}

signature_tt* get_emd_signature(DRMap* map)
{
    unsigned int n = 0;
    unsigned int bin_number = map->get_bin_number();
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            if (map->get_value(x, y) > 0) {
                n++;
            }
        }
    }

    feature_tt* features = (feature_tt*)malloc(sizeof(feature_tt) * n);
    double* weights = (double*)malloc(sizeof(double) * n);

    unsigned int i = 0;
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            double val = map->get_value(x, y);
            if (val > 0) {
                features[i].x = x;
                features[i].y = y;
                weights[i] = val;
                i++;
            }
        }
    }

    signature_tt* signature = (signature_tt*)malloc(sizeof(signature_tt));
    signature->n = n;
    signature->Features = features;
    signature->Weights = weights;

    return signature;
}

double DRMap::emd_dist(DRMap* map)
{
    printf("totals-> %f; %f\n", total, map->total());

    double infinity = 9999999999.9;

    if (total() == 0) {
        return infinity;
    }
    if (map->total() == 0) {
        return infinity;
    }

    signature_tt* sig1 = get_emd_signature(this);
    signature_tt* sig2 = get_emd_signature(map);

    double dist = emd_hat_signature_interface(sig1, sig2, ground_dist, -1);

    free(sig1->Features);
    free(sig1->Weights);
    free(sig1);
    free(sig2->Features);
    free(sig2->Weights);
    free(sig2);

    return dist;
}

void DRMap::print()
{
    for (unsigned int y = 0; y < bin_number; y++) {
        for (unsigned int x = 0; x < bin_number; x++) {
            printf("%f\t", get_value(x, y));
        }
        printf("\n");
    }
}

}
<commit_msg>degugging emd_dist<commit_after>/*
 * Copyright (C) 2010 Telmo Menezes.
 * telmo@telmomenezes.com
 */

#include "drmap.h"
#include "utils.h"

#include "emd_hat_signatures_interface.hpp"

#include <stdlib.h>
#include <strings.h>
#include <stdio.h>

namespace syn
{

DRMap::DRMap(unsigned int bin_number, double min_val_hor, double max_val_hor,
                double min_val_ver, double max_val_ver)
{
    this->bin_number = bin_number;
    this->min_val_hor = min_val_hor;
    this->max_val_hor = max_val_hor;
    this->min_val_ver = min_val_ver;
    this->max_val_ver = max_val_ver;
    data = (double*)malloc(bin_number * bin_number * sizeof(double));

    clear();
}

DRMap::~DRMap()
{
    free(data);
}

void DRMap::clear()
{
    bzero(data, bin_number * bin_number * sizeof(double));
}

void DRMap::set_value(unsigned int x, unsigned int y, double val)
{
    data[(y * bin_number) + x] = val;
}

void DRMap::inc_value(unsigned int x, unsigned int y)
{
    data[(y * bin_number) + x] += 1;
}

double DRMap::get_value(unsigned int x, unsigned int y)
{
    return data[(y * bin_number) + x];
}

void DRMap::log_scale()
{
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            if(data[(y * bin_number) + x] > 0) {
                data[(y * bin_number) + x] = log(data[(y * bin_number) + x]);
            }
        }
    }
}

void DRMap::normalize()
{
    // find max value
    double max = 0;
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            if(data[(y * bin_number) + x] > max) {
                max = data[(y * bin_number) + x];
            }
        }
    }

    // normalize by max
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            data[(y * bin_number) + x] = data[(y * bin_number) + x] / max;
        }
    }
}

void DRMap::binary()
{
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            if(data[(y * bin_number) + x] > 0) {
                data[(y * bin_number) + x] = 1;
            }
        }
    }
}

double DRMap::total()
{
    double total = 0;

    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            total += data[(y * bin_number) + x];
        }
    }

    return total;
}

double DRMap::simple_dist(DRMap* map)
{
    double dist = 0;
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            dist += fabs(data[(y * bin_number) + x] - map->data[(y * map->bin_number) + x]);
        }
    }
    return dist;
}

double ground_dist(feature_tt* feature1, feature_tt* feature2)
{
    double deltaX = feature1->x - feature2->x;
    double deltaY = feature1->y - feature2->y;
    double dist = sqrt((deltaX * deltaX) + (deltaY * deltaY));
    //double dist = (deltaX * deltaX) + (deltaY * deltaY);
    return dist;
}

signature_tt* get_emd_signature(DRMap* map)
{
    unsigned int n = 0;
    unsigned int bin_number = map->get_bin_number();
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            if (map->get_value(x, y) > 0) {
                n++;
            }
        }
    }

    feature_tt* features = (feature_tt*)malloc(sizeof(feature_tt) * n);
    double* weights = (double*)malloc(sizeof(double) * n);

    unsigned int i = 0;
    for (unsigned int x = 0; x < bin_number; x++) {
        for (unsigned int y = 0; y < bin_number; y++) {
            double val = map->get_value(x, y);
            if (val > 0) {
                features[i].x = x;
                features[i].y = y;
                weights[i] = val;
                i++;
            }
        }
    }

    signature_tt* signature = (signature_tt*)malloc(sizeof(signature_tt));
    signature->n = n;
    signature->Features = features;
    signature->Weights = weights;

    return signature;
}

double DRMap::emd_dist(DRMap* map)
{
    printf("totals-> %f; %f\n", total(), map->total());

    double infinity = 9999999999.9;

    if (total() == 0) {
        return infinity;
    }
    if (map->total() == 0) {
        return infinity;
    }

    signature_tt* sig1 = get_emd_signature(this);
    signature_tt* sig2 = get_emd_signature(map);

    double dist = emd_hat_signature_interface(sig1, sig2, ground_dist, -1);

    free(sig1->Features);
    free(sig1->Weights);
    free(sig1);
    free(sig2->Features);
    free(sig2->Weights);
    free(sig2);

    return dist;
}

void DRMap::print()
{
    for (unsigned int y = 0; y < bin_number; y++) {
        for (unsigned int x = 0; x < bin_number; x++) {
            printf("%f\t", get_value(x, y));
        }
        printf("\n");
    }
}

}
<|endoftext|>


<commit_before>/*
  Q Light Controller Plus
  e131node.cpp

  Copyright (c) Massimo Callegari

  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.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include "e131controller.h"

#include <QDebug>

E131Controller::E131Controller(QString ipaddr, QString macAddress, Type type, quint32 line, QObject *parent)
    : QObject(parent)
{
    m_ipAddr = QHostAddress(ipaddr);
    m_MACAddress = macAddress;
    m_line = line;

    qDebug() << "[E131Controller] type: " << type;
    m_packetizer = new E131Packetizer();
    m_packetSent = 0;
    m_packetReceived = 0;
    m_type = type;
    m_inputRefCount = 0;
    m_outputRefCount = 0;

    m_UdpSocket = new QUdpSocket(this);

    // reset initial DMX values if we're an input
    if (type == Input)
    {
        m_dmxValues.fill(0, 512);
        if (m_UdpSocket->bind(QHostAddress::AnyIPv4, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) == false)
        {
            qDebug() << Q_FUNC_INFO << "Socket input bind failed !!";
            return;
        }
        m_inputRefCount = 1;
    }
    else
    {
        if (m_UdpSocket->bind(m_ipAddr, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) == false)
        {
            qDebug() << Q_FUNC_INFO << "Socket output bind failed !!";
            return;
        }
        m_outputRefCount = 1;
    }

    connect(m_UdpSocket, SIGNAL(readyRead()),
            this, SLOT(processPendingPackets()));
}

E131Controller::~E131Controller()
{
    qDebug() << Q_FUNC_INFO;
    disconnect(m_UdpSocket, SIGNAL(readyRead()),
            this, SLOT(processPendingPackets()));
    m_UdpSocket->close();
}

void E131Controller::setType(Type type)
{
    m_type = type;
}

E131Controller::Type E131Controller::type()
{
    return m_type;
}

void E131Controller::enableUniverse(quint32 universe)
{
    m_multicastAddr[universe] = QHostAddress(QString("239.255.0.%1").arg(universe + 1));
    qDebug() << "[E131Controller] Enable universe:" << universe <<
                ", multicast address:" << m_multicastAddr[universe].toString();
    if (m_type == Input)
        m_UdpSocket->joinMulticastGroup(m_multicastAddr[universe]);
}

quint64 E131Controller::getPacketSentNumber()
{
    return m_packetSent;
}

quint64 E131Controller::getPacketReceivedNumber()
{
    return m_packetReceived;
}

void E131Controller::changeReferenceCount(E131Controller::Type type, int amount)
{
    if (type == Input)
    {
        m_inputRefCount += amount;
        m_dmxValues.resize(m_inputRefCount * 512);
    }
    else
        m_outputRefCount += amount;
}

int E131Controller::referenceCount(E131Controller::Type type)
{
    if (type == Input)
        return m_inputRefCount;
    else
        return m_outputRefCount;
}

QString E131Controller::getNetworkIP()
{
    return m_ipAddr.toString();
}

void E131Controller::sendDmx(const quint32 universe, const QByteArray &data)
{
    QByteArray dmxPacket;
    m_packetizer->setupE131Dmx(dmxPacket, universe, data);
    if (m_multicastAddr.contains(universe) == false)
    {
        m_multicastAddr[universe] = QHostAddress(QString("239.255.0.%1").arg(universe + 1));
        qDebug() << "[E131Controller] Universe:" << universe <<
                    ", multicast address:" << m_multicastAddr[universe].toString() <<
                    "(MAC:" << m_MACAddress << ")";
    }
    qint64 sent = m_UdpSocket->writeDatagram(dmxPacket.data(), dmxPacket.size(),
                                             m_multicastAddr[universe], E131_DEFAULT_PORT);
    if (sent < 0)
    {
        qDebug() << "sendDmx failed";
        qDebug() << "Errno: " << m_UdpSocket->error();
        qDebug() << "Errmgs: " << m_UdpSocket->errorString();
    }
    else
        m_packetSent++;
}

void E131Controller::processPendingPackets()
{
    while (m_UdpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        QHostAddress senderAddress;
        datagram.resize(m_UdpSocket->pendingDatagramSize());
        m_UdpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddress);
        if (senderAddress != m_ipAddr)
        {
            qDebug() << "Received packet with size: " << datagram.size() << ", host: " << senderAddress.toString();
            if (m_packetizer->checkPacket(datagram) == true)
            {
                QByteArray dmxData;
                quint32 universe;
                if (this->type() == Input)
                {
                    m_packetReceived++;
                    if (m_packetizer->fillDMXdata(datagram, dmxData, universe) == true)
                    {
                        if (universe >= (quint32)m_inputRefCount)
                            break;

                        quint32 uniAddr = universe << 9;
                        for (quint32 i = 0; i < (quint32)dmxData.length(); i++)
                        {
                            if (m_dmxValues.at(uniAddr + i) != dmxData.at(i))
                            {
                                m_dmxValues[uniAddr + i] =  dmxData[i];
                                emit valueChanged(universe, m_line, i, (uchar)dmxData.at(i));
                            }
                        }
                    }
                }
            }
        }
    }
}
<commit_msg>Fixed Qt4 build<commit_after>/*
  Q Light Controller Plus
  e131node.cpp

  Copyright (c) Massimo Callegari

  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.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include "e131controller.h"

#include <QDebug>

E131Controller::E131Controller(QString ipaddr, QString macAddress, Type type, quint32 line, QObject *parent)
    : QObject(parent)
{
    m_ipAddr = QHostAddress(ipaddr);
    m_MACAddress = macAddress;
    m_line = line;

    qDebug() << "[E131Controller] type: " << type;
    m_packetizer = new E131Packetizer();
    m_packetSent = 0;
    m_packetReceived = 0;
    m_type = type;
    m_inputRefCount = 0;
    m_outputRefCount = 0;

    m_UdpSocket = new QUdpSocket(this);

    // reset initial DMX values if we're an input
    if (type == Input)
    {
        m_dmxValues.fill(0, 512);
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
        if (m_UdpSocket->bind(QHostAddress::AnyIPv4, E131_DEFAULT_PORT,
                              QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) == false)
#else
        if (m_UdpSocket->bind(QHostAddress::Any, E131_DEFAULT_PORT,
                              QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) == false)
#endif
        {
            qDebug() << Q_FUNC_INFO << "Socket input bind failed !!";
            return;
        }
        m_inputRefCount = 1;
    }
    else
    {
        if (m_UdpSocket->bind(m_ipAddr, E131_DEFAULT_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint) == false)
        {
            qDebug() << Q_FUNC_INFO << "Socket output bind failed !!";
            return;
        }
        m_outputRefCount = 1;
    }

    connect(m_UdpSocket, SIGNAL(readyRead()),
            this, SLOT(processPendingPackets()));
}

E131Controller::~E131Controller()
{
    qDebug() << Q_FUNC_INFO;
    disconnect(m_UdpSocket, SIGNAL(readyRead()),
            this, SLOT(processPendingPackets()));
    m_UdpSocket->close();
}

void E131Controller::setType(Type type)
{
    m_type = type;
}

E131Controller::Type E131Controller::type()
{
    return m_type;
}

void E131Controller::enableUniverse(quint32 universe)
{
    m_multicastAddr[universe] = QHostAddress(QString("239.255.0.%1").arg(universe + 1));
    qDebug() << "[E131Controller] Enable universe:" << universe <<
                ", multicast address:" << m_multicastAddr[universe].toString();
    if (m_type == Input)
        m_UdpSocket->joinMulticastGroup(m_multicastAddr[universe]);
}

quint64 E131Controller::getPacketSentNumber()
{
    return m_packetSent;
}

quint64 E131Controller::getPacketReceivedNumber()
{
    return m_packetReceived;
}

void E131Controller::changeReferenceCount(E131Controller::Type type, int amount)
{
    if (type == Input)
    {
        m_inputRefCount += amount;
        m_dmxValues.resize(m_inputRefCount * 512);
    }
    else
        m_outputRefCount += amount;
}

int E131Controller::referenceCount(E131Controller::Type type)
{
    if (type == Input)
        return m_inputRefCount;
    else
        return m_outputRefCount;
}

QString E131Controller::getNetworkIP()
{
    return m_ipAddr.toString();
}

void E131Controller::sendDmx(const quint32 universe, const QByteArray &data)
{
    QByteArray dmxPacket;
    m_packetizer->setupE131Dmx(dmxPacket, universe, data);
    if (m_multicastAddr.contains(universe) == false)
    {
        m_multicastAddr[universe] = QHostAddress(QString("239.255.0.%1").arg(universe + 1));
        qDebug() << "[E131Controller] Universe:" << universe <<
                    ", multicast address:" << m_multicastAddr[universe].toString() <<
                    "(MAC:" << m_MACAddress << ")";
    }
    qint64 sent = m_UdpSocket->writeDatagram(dmxPacket.data(), dmxPacket.size(),
                                             m_multicastAddr[universe], E131_DEFAULT_PORT);
    if (sent < 0)
    {
        qDebug() << "sendDmx failed";
        qDebug() << "Errno: " << m_UdpSocket->error();
        qDebug() << "Errmgs: " << m_UdpSocket->errorString();
    }
    else
        m_packetSent++;
}

void E131Controller::processPendingPackets()
{
    while (m_UdpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        QHostAddress senderAddress;
        datagram.resize(m_UdpSocket->pendingDatagramSize());
        m_UdpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddress);
        if (senderAddress != m_ipAddr)
        {
            qDebug() << "Received packet with size: " << datagram.size() << ", host: " << senderAddress.toString();
            if (m_packetizer->checkPacket(datagram) == true)
            {
                QByteArray dmxData;
                quint32 universe;
                if (this->type() == Input)
                {
                    m_packetReceived++;
                    if (m_packetizer->fillDMXdata(datagram, dmxData, universe) == true)
                    {
                        if (universe >= (quint32)m_inputRefCount)
                            break;

                        quint32 uniAddr = universe << 9;
                        for (quint32 i = 0; i < (quint32)dmxData.length(); i++)
                        {
                            if (m_dmxValues.at(uniAddr + i) != dmxData.at(i))
                            {
                                m_dmxValues[uniAddr + i] =  dmxData[i];
                                emit valueChanged(universe, m_line, i, (uchar)dmxData.at(i));
                            }
                        }
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#include <vlGraphics/DrawPixels.hpp>
#include <vlGraphics/Actor.hpp>
#include <vlGraphics/Camera.hpp>
#include <vlGraphics/GLBufferObject.hpp>
#include <vlCore/Log.hpp>
#include <map>

using namespace vl;

//-----------------------------------------------------------------------------
// DrawPixels::Pixels
//-----------------------------------------------------------------------------
DrawPixels::Pixels::Pixels()
{
  VL_DEBUG_SET_OBJECT_NAME()
  mAlign = AlignBottom | AlignLeft;
}
//-----------------------------------------------------------------------------
DrawPixels::Pixels::Pixels(ImagePBO* img, int scrx, int scry, int startx, int starty, int width, int height, int alignment)
{
  VL_DEBUG_SET_OBJECT_NAME()

  mAlign = alignment;

  if (width < 0)
    width = img->width()  - startx;

  if (height < 0)
    height = img->height() - starty;

  mImage     = img;
  mPosition  = ivec2(scrx, scry);
  mStart     = ivec2(startx, starty);
  mSize      = ivec2(width, height);
}
//-----------------------------------------------------------------------------
DrawPixels::Pixels::Pixels(const Pixels& other): Object(other)
{
  VL_DEBUG_SET_OBJECT_NAME()

  *this = other;
}
//-----------------------------------------------------------------------------
DrawPixels::Pixels& DrawPixels::Pixels::operator=(const Pixels& other)
{
  mImage = other.mImage;
  mPosition = other.mPosition;
  mStart = other.mStart;
  mSize  = other.mSize;
  mAlign = other.mAlign;
  return *this;
}
//-----------------------------------------------------------------------------
DrawPixels::Pixels::~Pixels()
{
}
//-----------------------------------------------------------------------------
void DrawPixels::Pixels::deletePixelBufferObject()
{
  image()->pixelBufferObject()->deleteGLBufferObject();
}
//-----------------------------------------------------------------------------
bool DrawPixels::Pixels::generatePixelBufferObject(EGLBufferUsage usage, bool discard_local_storage)
{
  VL_CHECK(image())
  if (!image())
    return false;
  image()->pixelBufferObject()->setBufferData( image()->imageBuffer()->bytesUsed(), image()->imageBuffer()->ptr(), usage );
  if (discard_local_storage)
    image()->imageBuffer()->clear();
  return true;
}
//-----------------------------------------------------------------------------
bool DrawPixels::Pixels::hasPixelBufferObject() const
{
  return image()->pixelBufferObject()->handle() != 0;
}
//-----------------------------------------------------------------------------
// DrawPixels
//-----------------------------------------------------------------------------
DrawPixels::DrawPixels()
{
  mUsePixelBufferObject = false;
  mDraws.setAutomaticDelete(false);
}
//-----------------------------------------------------------------------------
void DrawPixels::render_Implementation(const Actor* actor, const Shader*, const Camera* camera, OpenGLContext*) const
{
  VL_CHECK_OGL()

  int viewport[] = { camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height() };

  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  VL_CHECK_OGL();

  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();
  glOrtho( -0.5, viewport[2]-0.5, -0.5, viewport[3]-0.5, -1, +1 ); VL_CHECK_OGL();

  glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT); VL_CHECK_OGL();

  for(int i=0; i<(int)mDraws.size(); ++i)
  {
    const Pixels* cmd = draws()->at(i);

    if (cmd->image() == 0)
      continue;

    const GLBufferObject* glbuf = cmd->image()->pixelBufferObject();

    VL_CHECK( cmd->image() )
    VL_CHECK( glbuf )
    VL_CHECK( glbuf->handle() || cmd->image()->pixels() )
    VL_CHECK( cmd->image()->isValid() )
    VL_CHECK( cmd->mStart.x() >= 0 )
    VL_CHECK( cmd->mStart.y() >= 0 )

    //VL_CHECK( cmd->mStart.x()+cmd->mSize.x() -1 < cmd->image()->width() )
    //VL_CHECK( cmd->mStart.y()+cmd->mSize.y() -1 < cmd->image()->height() )

    int pos_x = cmd->mPosition.x();
    int pos_y = cmd->mPosition.y();

    // alignment

    if (cmd->align() & AlignRight)
      pos_x -= cmd->mSize.x() -1;
    if (cmd->align() & AlignHCenter)
      pos_x -= cmd->mSize.x() / 2;
    if (cmd->align() & AlignTop)
      pos_y -= cmd->mSize.y() -1;
    if (cmd->align() & AlignVCenter)
      pos_y -= cmd->mSize.y() / 2;

    // transform following

    if ( camera && actor && actor->transform() )
    {
      vec4 v(0,0,0,1);
      v = actor->transform()->worldMatrix() * v;

      camera->project(v,v);

      // from screen space to viewport space
      v.x() -= viewport[0];
      v.y() -= viewport[1];

      pos_x += int(v.x() + 0.5);
      pos_y += int(v.y() + 0.5);
    }

    // culling

    if ( pos_x + cmd->mSize.x() -1 < 0 )
      continue;

    if ( pos_y + cmd->mSize.y() -1 < 0 )
      continue;

    if (pos_x > viewport[2] - 1)
      continue;

    if (pos_y > viewport[3] - 1)
      continue;

    // clipping

    int clip_left   = pos_x < 0 ? -pos_x : 0;
    int clip_bottom = pos_y < 0 ? -pos_y : 0;
    int clip_right  = (pos_x+cmd->mSize.x()-1)-( viewport[2]-1 );
    int clip_top    = (pos_y+cmd->mSize.y()-1)-( viewport[3]-1 );

    if (clip_right < 0)
      clip_right = 0;

    if (clip_top < 0)
      clip_top = 0;

    glRasterPos2f( /*0.5f +*/ (float)pos_x + clip_left, /*0.5f +*/ (float)pos_y + clip_bottom );

    // clear the current color, texture, normal
    glColor4f(1.0f,1.0f,1.0f,1.0f);
    glNormal3f(0,0,1.0f);
    glTexCoord3f(0,0,0);
    VL_CHECK_OGL()

    glPixelStorei( GL_UNPACK_ALIGNMENT, cmd->image()->byteAlignment() );
    glPixelStorei( GL_UNPACK_ROW_LENGTH, cmd->image()->width() );
    glPixelStorei( GL_UNPACK_SKIP_PIXELS, cmd->mStart.x() + clip_left );
    glPixelStorei( GL_UNPACK_SKIP_ROWS, cmd->mStart.y() + clip_bottom );
    VL_CHECK_OGL()

    if ( glbuf->handle() )
    {
      VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, glbuf->handle() ); VL_CHECK_OGL()
      glDrawPixels( cmd->mSize.x() -clip_left -clip_right, cmd->mSize.y() -clip_bottom -clip_top, cmd->image()->format(), cmd->image()->type(), 0 );
      VL_CHECK_OGL();
    }
    else
    {
      VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, 0 );
      glDrawPixels( cmd->mSize.x() -clip_left -clip_right, cmd->mSize.y() -clip_bottom -clip_top, cmd->image()->format(), cmd->image()->type(), cmd->image()->pixels() );
      VL_CHECK_OGL();
    }
  }

  VL_CHECK_OGL();

  VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, 0 );

  VL_CHECK_OGL()

  // restores the default values
  glPopClientAttrib();
  VL_CHECK_OGL();

  glMatrixMode(GL_MODELVIEW);
  glPopMatrix(); VL_CHECK_OGL()

  glMatrixMode(GL_PROJECTION);
  glPopMatrix(); VL_CHECK_OGL()
}
//-----------------------------------------------------------------------------
//! deallocate PBOs
void DrawPixels::deletePixelBufferObjects()
{
  VL_CHECK_OGL()
  for(int i=0; i<(int)mDraws.size(); ++i)
  {
    mDraws[i]->image()->pixelBufferObject()->deleteGLBufferObject();
  }
  VL_CHECK_OGL()
}
//-----------------------------------------------------------------------------
void DrawPixels::releaseImages()
{
  for(int i=0; i<(int)mDraws.size(); ++i)
    mDraws[i]->mImage = NULL;
}
//-----------------------------------------------------------------------------
//! generates PBOs only for Pixels objects without a PBO handle
bool DrawPixels::generatePixelBufferObjects(EGLBufferUsage usage, bool discard_local_storage)
{
  if ( !( Has_GL_ARB_pixel_buffer_object||Has_GL_EXT_pixel_buffer_object ) )
    return false;

  // generates PBOs if they have an attached Image

  // avoids to PBO duplicates for the same images
  std::map< ref<Image>, unsigned int> pbomap;

  for(int i=0; i<(int)mDraws.size(); ++i)
  {
    if ( mDraws[i]->hasPixelBufferObject() )
      continue;

    if ( mDraws[i]->mImage.get() == NULL )
      continue;

    mDraws[i]->generatePixelBufferObject(usage, discard_local_storage);
  }
  return true;
}
//-----------------------------------------------------------------------------
void DrawPixels::setUsePixelBufferObject(bool use_pbo)
{
  if ( (Has_GL_ARB_pixel_buffer_object||Has_GL_EXT_pixel_buffer_object) )
    mUsePixelBufferObject = use_pbo;
  else
    mUsePixelBufferObject = false;
}
//-----------------------------------------------------------------------------
<commit_msg>Use floats for glOrtho<commit_after>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#include <vlGraphics/DrawPixels.hpp>
#include <vlGraphics/Actor.hpp>
#include <vlGraphics/Camera.hpp>
#include <vlGraphics/GLBufferObject.hpp>
#include <vlCore/Log.hpp>
#include <map>

using namespace vl;

//-----------------------------------------------------------------------------
// DrawPixels::Pixels
//-----------------------------------------------------------------------------
DrawPixels::Pixels::Pixels()
{
  VL_DEBUG_SET_OBJECT_NAME()
  mAlign = AlignBottom | AlignLeft;
}
//-----------------------------------------------------------------------------
DrawPixels::Pixels::Pixels(ImagePBO* img, int scrx, int scry, int startx, int starty, int width, int height, int alignment)
{
  VL_DEBUG_SET_OBJECT_NAME()

  mAlign = alignment;

  if (width < 0)
    width = img->width()  - startx;

  if (height < 0)
    height = img->height() - starty;

  mImage     = img;
  mPosition  = ivec2(scrx, scry);
  mStart     = ivec2(startx, starty);
  mSize      = ivec2(width, height);
}
//-----------------------------------------------------------------------------
DrawPixels::Pixels::Pixels(const Pixels& other): Object(other)
{
  VL_DEBUG_SET_OBJECT_NAME()

  *this = other;
}
//-----------------------------------------------------------------------------
DrawPixels::Pixels& DrawPixels::Pixels::operator=(const Pixels& other)
{
  mImage = other.mImage;
  mPosition = other.mPosition;
  mStart = other.mStart;
  mSize  = other.mSize;
  mAlign = other.mAlign;
  return *this;
}
//-----------------------------------------------------------------------------
DrawPixels::Pixels::~Pixels()
{
}
//-----------------------------------------------------------------------------
void DrawPixels::Pixels::deletePixelBufferObject()
{
  image()->pixelBufferObject()->deleteGLBufferObject();
}
//-----------------------------------------------------------------------------
bool DrawPixels::Pixels::generatePixelBufferObject(EGLBufferUsage usage, bool discard_local_storage)
{
  VL_CHECK(image())
  if (!image())
    return false;
  image()->pixelBufferObject()->setBufferData( (GLsizeiptr)image()->imageBuffer()->bytesUsed(), image()->imageBuffer()->ptr(), usage );
  if (discard_local_storage)
    image()->imageBuffer()->clear();
  return true;
}
//-----------------------------------------------------------------------------
bool DrawPixels::Pixels::hasPixelBufferObject() const
{
  return image()->pixelBufferObject()->handle() != 0;
}
//-----------------------------------------------------------------------------
// DrawPixels
//-----------------------------------------------------------------------------
DrawPixels::DrawPixels()
{
  mUsePixelBufferObject = false;
  mDraws.setAutomaticDelete(false);
}
//-----------------------------------------------------------------------------
void DrawPixels::render_Implementation(const Actor* actor, const Shader*, const Camera* camera, OpenGLContext*) const
{
  VL_CHECK_OGL()

  int viewport[] = { camera->viewport()->x(), camera->viewport()->y(), camera->viewport()->width(), camera->viewport()->height() };

  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  VL_CHECK_OGL();

  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();
  glOrtho( -0.5f, viewport[2]-0.5f, -0.5f, viewport[3]-0.5f, -1.0f, +1.0f ); VL_CHECK_OGL();

  glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT); VL_CHECK_OGL();

  for(int i=0; i<(int)mDraws.size(); ++i)
  {
    const Pixels* cmd = draws()->at(i);

    if (cmd->image() == 0)
      continue;

    const GLBufferObject* glbuf = cmd->image()->pixelBufferObject();

    VL_CHECK( cmd->image() )
    VL_CHECK( glbuf )
    VL_CHECK( glbuf->handle() || cmd->image()->pixels() )
    VL_CHECK( cmd->image()->isValid() )
    VL_CHECK( cmd->mStart.x() >= 0 )
    VL_CHECK( cmd->mStart.y() >= 0 )

    //VL_CHECK( cmd->mStart.x()+cmd->mSize.x() -1 < cmd->image()->width() )
    //VL_CHECK( cmd->mStart.y()+cmd->mSize.y() -1 < cmd->image()->height() )

    int pos_x = cmd->mPosition.x();
    int pos_y = cmd->mPosition.y();

    // alignment

    if (cmd->align() & AlignRight)
      pos_x -= cmd->mSize.x() -1;
    if (cmd->align() & AlignHCenter)
      pos_x -= cmd->mSize.x() / 2;
    if (cmd->align() & AlignTop)
      pos_y -= cmd->mSize.y() -1;
    if (cmd->align() & AlignVCenter)
      pos_y -= cmd->mSize.y() / 2;

    // transform following

    if ( camera && actor && actor->transform() )
    {
      vec4 v(0,0,0,1);
      v = actor->transform()->worldMatrix() * v;

      camera->project(v,v);

      // from screen space to viewport space
      v.x() -= viewport[0];
      v.y() -= viewport[1];

      pos_x += int(v.x() + 0.5);
      pos_y += int(v.y() + 0.5);
    }

    // culling

    if ( pos_x + cmd->mSize.x() -1 < 0 )
      continue;

    if ( pos_y + cmd->mSize.y() -1 < 0 )
      continue;

    if (pos_x > viewport[2] - 1)
      continue;

    if (pos_y > viewport[3] - 1)
      continue;

    // clipping

    int clip_left   = pos_x < 0 ? -pos_x : 0;
    int clip_bottom = pos_y < 0 ? -pos_y : 0;
    int clip_right  = (pos_x+cmd->mSize.x()-1)-( viewport[2]-1 );
    int clip_top    = (pos_y+cmd->mSize.y()-1)-( viewport[3]-1 );

    if (clip_right < 0)
      clip_right = 0;

    if (clip_top < 0)
      clip_top = 0;

    glRasterPos2f( /*0.5f +*/ (float)pos_x + clip_left, /*0.5f +*/ (float)pos_y + clip_bottom );

    // clear the current color, texture, normal
    glColor4f(1.0f,1.0f,1.0f,1.0f);
    glNormal3f(0,0,1.0f);
    glTexCoord3f(0,0,0);
    VL_CHECK_OGL()

    glPixelStorei( GL_UNPACK_ALIGNMENT, cmd->image()->byteAlignment() );
    glPixelStorei( GL_UNPACK_ROW_LENGTH, cmd->image()->width() );
    glPixelStorei( GL_UNPACK_SKIP_PIXELS, cmd->mStart.x() + clip_left );
    glPixelStorei( GL_UNPACK_SKIP_ROWS, cmd->mStart.y() + clip_bottom );
    VL_CHECK_OGL()

    if ( glbuf->handle() )
    {
      VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, glbuf->handle() ); VL_CHECK_OGL()
      glDrawPixels( cmd->mSize.x() -clip_left -clip_right, cmd->mSize.y() -clip_bottom -clip_top, cmd->image()->format(), cmd->image()->type(), 0 );
      VL_CHECK_OGL();
    }
    else
    {
      VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, 0 );
      glDrawPixels( cmd->mSize.x() -clip_left -clip_right, cmd->mSize.y() -clip_bottom -clip_top, cmd->image()->format(), cmd->image()->type(), cmd->image()->pixels() );
      VL_CHECK_OGL();
    }
  }

  VL_CHECK_OGL();

  VL_glBindBuffer( GL_PIXEL_UNPACK_BUFFER, 0 );

  VL_CHECK_OGL()

  // restores the default values
  glPopClientAttrib();
  VL_CHECK_OGL();

  glMatrixMode(GL_MODELVIEW);
  glPopMatrix(); VL_CHECK_OGL()

  glMatrixMode(GL_PROJECTION);
  glPopMatrix(); VL_CHECK_OGL()
}
//-----------------------------------------------------------------------------
//! deallocate PBOs
void DrawPixels::deletePixelBufferObjects()
{
  VL_CHECK_OGL()
  for(int i=0; i<(int)mDraws.size(); ++i)
  {
    mDraws[i]->image()->pixelBufferObject()->deleteGLBufferObject();
  }
  VL_CHECK_OGL()
}
//-----------------------------------------------------------------------------
void DrawPixels::releaseImages()
{
  for(int i=0; i<(int)mDraws.size(); ++i)
    mDraws[i]->mImage = NULL;
}
//-----------------------------------------------------------------------------
//! generates PBOs only for Pixels objects without a PBO handle
bool DrawPixels::generatePixelBufferObjects(EGLBufferUsage usage, bool discard_local_storage)
{
  if ( !( Has_GL_ARB_pixel_buffer_object||Has_GL_EXT_pixel_buffer_object ) )
    return false;

  // generates PBOs if they have an attached Image

  // avoids to PBO duplicates for the same images
  std::map< ref<Image>, unsigned int> pbomap;

  for(int i=0; i<(int)mDraws.size(); ++i)
  {
    if ( mDraws[i]->hasPixelBufferObject() )
      continue;

    if ( mDraws[i]->mImage.get() == NULL )
      continue;

    mDraws[i]->generatePixelBufferObject(usage, discard_local_storage);
  }
  return true;
}
//-----------------------------------------------------------------------------
void DrawPixels::setUsePixelBufferObject(bool use_pbo)
{
  if ( (Has_GL_ARB_pixel_buffer_object||Has_GL_EXT_pixel_buffer_object) )
    mUsePixelBufferObject = use_pbo;
  else
    mUsePixelBufferObject = false;
}
//-----------------------------------------------------------------------------
<|endoftext|>