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

#ifndef _SVTOOLS_JAVAPTIONS_HXX
#include <javaoptions.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::rtl;

#define C2U(cChar) OUString::createFromAscii(cChar)
#define CFG_READONLY_DEFAULT    sal_False
/* -----------------------------10.04.01 12:39--------------------------------

 ---------------------------------------------------------------------------*/
class SvtExecAppletsItem_Impl : public utl::ConfigItem
{
    sal_Bool  bExecute;
    sal_Bool  bRO;
public:
    SvtExecAppletsItem_Impl();

    virtual void    Commit();

    sal_Bool IsExecuteApplets() const {return bExecute;}
    void     SetExecuteApplets(sal_Bool bSet);
    sal_Bool IsReadOnly() const {return bRO;}
};
/* -----------------------------10.02.2003 07:46------------------------------

 ---------------------------------------------------------------------------*/
void SvtExecAppletsItem_Impl::SetExecuteApplets(sal_Bool bSet)
{
    OSL_ENSURE(!bRO, "SvtExecAppletsItem_Impl::SetExecuteApplets()\nYou tried to write on a readonly value!\n");
    if (!bRO)
    {
        bExecute = bSet;
        SetModified();
    }
}
/* -----------------------------18.05.01 14:44--------------------------------

 ---------------------------------------------------------------------------*/
SvtExecAppletsItem_Impl::SvtExecAppletsItem_Impl() :
        utl::ConfigItem(C2U("Office.Common/Java/Applet")),
        bRO            (CFG_READONLY_DEFAULT            ),
        bExecute       (sal_False                       )
{
    Sequence< OUString > aNames(1);
    aNames.getArray()[0] = C2U("Enable");
    Sequence< Any > aValues = GetProperties(aNames);
    Sequence< sal_Bool > aROStates = GetReadOnlyStates(aNames);
    const Any* pValues = aValues.getConstArray();
    const sal_Bool* pROStates = aROStates.getConstArray();
    if(aValues.getLength() && aROStates.getLength() && pValues[0].hasValue())
    {
        bExecute = *(sal_Bool*)pValues[0].getValue();
        bRO = pROStates[0];
    }
}
void    SvtExecAppletsItem_Impl::Commit()
{
    if (bRO)
        return;

    Sequence< OUString > aNames(1);
    aNames.getArray()[0] = C2U("Enable");
    Sequence< Any > aValues(1);
    aValues.getArray()[0].setValue(&bExecute, ::getBooleanCppuType());
    PutProperties(aNames, aValues);
}

struct SvtJavaOptions_Impl
{
    SvtExecAppletsItem_Impl aExecItem;
    Sequence<OUString>      aPropertyNames;
    sal_Bool                bEnabled;
    sal_Bool                bSecurity;
    sal_Int32               nNetAccess;
    rtl::OUString           sUserClassPath;

    sal_Bool                bROEnabled;
    sal_Bool                bROSecurity;
    sal_Bool                bRONetAccess;
    sal_Bool                bROUserClassPath;

    SvtJavaOptions_Impl() :
        aPropertyNames(4),
        bEnabled            (sal_False),
        bSecurity           (sal_False),
        nNetAccess          (0),
        bROEnabled          (CFG_READONLY_DEFAULT),
        bROSecurity         (CFG_READONLY_DEFAULT),
        bRONetAccess        (CFG_READONLY_DEFAULT),
        bROUserClassPath    (CFG_READONLY_DEFAULT)
        {
            OUString* pNames = aPropertyNames.getArray();
            pNames[0] = C2U("Enable");
            pNames[1] = C2U("Security");
            pNames[2] = C2U("NetAccess");
            pNames[3] = C2U("UserClassPath");
        }
};
/* -----------------------------18.05.01 13:28--------------------------------

 ---------------------------------------------------------------------------*/
SvtJavaOptions::SvtJavaOptions() :
    utl::ConfigItem(C2U("Office.Java/VirtualMachine")),
    pImpl(new SvtJavaOptions_Impl)
{
    Sequence< Any > aValues = GetProperties(pImpl->aPropertyNames);
    Sequence< sal_Bool > aROStates = GetReadOnlyStates(pImpl->aPropertyNames);
    const Any* pValues = aValues.getConstArray();
    const sal_Bool* pROStates = aROStates.getConstArray();
    if ( aValues.getLength() == pImpl->aPropertyNames.getLength() && aROStates.getLength() == pImpl->aPropertyNames.getLength() )
    {
        for ( int nProp = 0; nProp < pImpl->aPropertyNames.getLength(); nProp++ )
        {
            if( pValues[nProp].hasValue() )
            {
                switch ( nProp )
                {
                    case 0: pImpl->bEnabled = *(sal_Bool*)pValues[nProp].getValue(); break;
                    case 1: pImpl->bSecurity = *(sal_Bool*)pValues[nProp].getValue();break;
                    case 2: pValues[nProp] >>= pImpl->nNetAccess; break;
                    case 3: pValues[nProp] >>= pImpl->sUserClassPath; break;
                }
            }
        }
        pImpl->bROEnabled = pROStates[0];
        pImpl->bROSecurity = pROStates[1];
        pImpl->bRONetAccess = pROStates[2];
        pImpl->bROUserClassPath = pROStates[3];
    }
}
/* -----------------------------18.05.01 13:28--------------------------------

 ---------------------------------------------------------------------------*/
SvtJavaOptions::~SvtJavaOptions()
{
    delete pImpl;
}
/*-- 18.05.01 13:28:35---------------------------------------------------

  -----------------------------------------------------------------------*/
void    SvtJavaOptions::Commit()
{
    pImpl->aExecItem.Commit();

    sal_Int32 nOrgCount = pImpl->aPropertyNames.getLength();
    Sequence< OUString > aNames(nOrgCount);
    Sequence< Any > aValues(nOrgCount);
    sal_Int32 nRealCount = 0;

    const Type& rType = ::getBooleanCppuType();
    for(int nProp = 0; nProp < nOrgCount; nProp++)
    {
        switch(nProp)
        {
            case  0:
            {
                if (!pImpl->bROEnabled)
                {
                    aValues[nRealCount].setValue(&pImpl->bEnabled, rType);
                    aNames[nRealCount] = pImpl->aPropertyNames[nProp];
                    ++nRealCount;
                }
            }
            break;
            case  1:
            {
                if (!pImpl->bROSecurity)
                {
                    aValues[nRealCount].setValue(&pImpl->bSecurity, rType);
                    aNames[nRealCount] = pImpl->aPropertyNames[nProp];
                    ++nRealCount;
                }
            }
            break;
            case  2:
            {
                if (!pImpl->bRONetAccess)
                {
                    aValues[nRealCount] <<= pImpl->nNetAccess;
                    aNames[nRealCount] = pImpl->aPropertyNames[nProp];
                    ++nRealCount;
                }
            }
            break;
            case  3:
            {
                if (!pImpl->bROUserClassPath)
                {
                    aValues[nRealCount] <<= pImpl->sUserClassPath;
                    aNames[nRealCount] = pImpl->aPropertyNames[nProp];
                    ++nRealCount;
                }
            }
            break;
        }
    }
    aValues.realloc(nRealCount);
    aNames.realloc(nRealCount);
    PutProperties(aNames,aValues);
}
/*-- 18.05.01 13:28:35---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool        SvtJavaOptions::IsEnabled() const
{
    return pImpl->bEnabled;
}
/*-- 18.05.01 13:28:35---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool        SvtJavaOptions::IsSecurity()const
{
    return pImpl->bSecurity;
}
/*-- 18.05.01 13:28:35---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Int32       SvtJavaOptions::GetNetAccess() const
{
    return pImpl->nNetAccess;
}
/*-- 18.05.01 13:28:36---------------------------------------------------

  -----------------------------------------------------------------------*/
rtl::OUString&  SvtJavaOptions::GetUserClassPath()const
{
    return pImpl->sUserClassPath;
}
/*-- 18.05.01 13:28:37---------------------------------------------------

  -----------------------------------------------------------------------*/
void SvtJavaOptions::SetEnabled(sal_Bool bSet)
{
    OSL_ENSURE(!pImpl->bROEnabled, "SvtJavaOptions::SetEnabled()\nYou tried to write on a readonly value!\n");
    if(!pImpl->bROEnabled && pImpl->bEnabled != bSet)
    {
        pImpl->bEnabled = bSet;
        SetModified();
    }
}
/*-- 18.05.01 13:28:38---------------------------------------------------

  -----------------------------------------------------------------------*/
void SvtJavaOptions::SetSecurity(sal_Bool bSet)
{
    OSL_ENSURE(!pImpl->bROSecurity, "SvtJavaOptions::SetSecurity()\nYou tried to write on a readonly value!\n");
    if(!pImpl->bROSecurity && pImpl->bSecurity != bSet)
    {
        pImpl->bSecurity = bSet;
        SetModified();
    }
}
/*-- 18.05.01 13:28:38---------------------------------------------------

  -----------------------------------------------------------------------*/
void SvtJavaOptions::SetNetAccess(sal_Int32 nSet)
{
    OSL_ENSURE(!pImpl->bRONetAccess, "SvtJavaOptions::SetNetAccess()\nYou tried to write on a readonly value!\n");
    if(!pImpl->bRONetAccess && pImpl->nNetAccess != nSet)
    {
        pImpl->nNetAccess = nSet;
        SetModified();
    }
}
/*-- 18.05.01 13:28:38---------------------------------------------------

  -----------------------------------------------------------------------*/
void SvtJavaOptions::SetUserClassPath(const rtl::OUString& rSet)
{
    OSL_ENSURE(!pImpl->bROUserClassPath, "SvtJavaOptions::SetUserClassPath()\nYou tried to write on a readonly value!\n");
    if(!pImpl->bROUserClassPath && pImpl->sUserClassPath != rSet)
    {
        pImpl->sUserClassPath = rSet;
        SetModified();
    }
}

/*-- 18.05.01 14:34:32---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool        SvtJavaOptions::IsExecuteApplets() const
{
    return pImpl->aExecItem.IsExecuteApplets();
}
/*-- 18.05.01 14:34:32---------------------------------------------------

  -----------------------------------------------------------------------*/
void SvtJavaOptions::SetExecuteApplets(sal_Bool bSet)
{
    if(!pImpl->aExecItem.IsReadOnly() && pImpl->aExecItem.IsExecuteApplets() != bSet)
    {
        pImpl->aExecItem.SetExecuteApplets(bSet);
        SetModified();
    }
}
/*--10.02.2003 08:40---------------------------------------------------

-----------------------------------------------------------------------*/
sal_Bool SvtJavaOptions::IsReadOnly( EOption eOption ) const
{
    sal_Bool bRO = sal_True;
    switch(eOption)
    {
        case E_ENABLED :
            bRO = pImpl->bROEnabled;
            break;
        case E_SECURITY :
            bRO = pImpl->bROSecurity;
            break;
        case E_NETACCESS :
            bRO = pImpl->bRONetAccess;
            break;
        case E_USERCLASSPATH :
            bRO = pImpl->bROUserClassPath;
            break;
        case E_EXECUTEAPPLETS :
            bRO = pImpl->aExecItem.IsReadOnly();
            break;
    }
    return bRO;
}
<commit_msg>INTEGRATION: CWS perform06 (1.5.60); FILE MERGED 2005/10/25 08:04:04 as 1.5.60.1: #i56589# hold config items alive till office die<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: javaoptions.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-11-11 08:51:11 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef GCC
#pragma hdrstop
#endif

#ifndef _SVTOOLS_JAVAPTIONS_HXX
#include <javaoptions.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#include <rtl/logfile.hxx>

using namespace ::com::sun::star::uno;
using namespace ::rtl;

#define C2U(cChar) OUString::createFromAscii(cChar)
#define CFG_READONLY_DEFAULT    sal_False
/* -----------------------------10.04.01 12:39--------------------------------

 ---------------------------------------------------------------------------*/
class SvtExecAppletsItem_Impl : public utl::ConfigItem
{
    sal_Bool  bExecute;
    sal_Bool  bRO;
public:
    SvtExecAppletsItem_Impl();

    virtual void    Commit();

    sal_Bool IsExecuteApplets() const {return bExecute;}
    void     SetExecuteApplets(sal_Bool bSet);
    sal_Bool IsReadOnly() const {return bRO;}
};
/* -----------------------------10.02.2003 07:46------------------------------

 ---------------------------------------------------------------------------*/
void SvtExecAppletsItem_Impl::SetExecuteApplets(sal_Bool bSet)
{
    OSL_ENSURE(!bRO, "SvtExecAppletsItem_Impl::SetExecuteApplets()\nYou tried to write on a readonly value!\n");
    if (!bRO)
    {
        bExecute = bSet;
        SetModified();
    }
}
/* -----------------------------18.05.01 14:44--------------------------------

 ---------------------------------------------------------------------------*/
SvtExecAppletsItem_Impl::SvtExecAppletsItem_Impl() :
        utl::ConfigItem(C2U("Office.Common/Java/Applet")),
        bRO            (CFG_READONLY_DEFAULT            ),
        bExecute       (sal_False                       )
{
    RTL_LOGFILE_CONTEXT(aLog, "svtools (???) SvtExecAppletsItem_Impl::SvtExecAppletsItem_Impl()");

    Sequence< OUString > aNames(1);
    aNames.getArray()[0] = C2U("Enable");
    Sequence< Any > aValues = GetProperties(aNames);
    Sequence< sal_Bool > aROStates = GetReadOnlyStates(aNames);
    const Any* pValues = aValues.getConstArray();
    const sal_Bool* pROStates = aROStates.getConstArray();
    if(aValues.getLength() && aROStates.getLength() && pValues[0].hasValue())
    {
        bExecute = *(sal_Bool*)pValues[0].getValue();
        bRO = pROStates[0];
    }
}
void    SvtExecAppletsItem_Impl::Commit()
{
    if (bRO)
        return;

    Sequence< OUString > aNames(1);
    aNames.getArray()[0] = C2U("Enable");
    Sequence< Any > aValues(1);
    aValues.getArray()[0].setValue(&bExecute, ::getBooleanCppuType());
    PutProperties(aNames, aValues);
}

struct SvtJavaOptions_Impl
{
    SvtExecAppletsItem_Impl aExecItem;
    Sequence<OUString>      aPropertyNames;
    sal_Bool                bEnabled;
    sal_Bool                bSecurity;
    sal_Int32               nNetAccess;
    rtl::OUString           sUserClassPath;

    sal_Bool                bROEnabled;
    sal_Bool                bROSecurity;
    sal_Bool                bRONetAccess;
    sal_Bool                bROUserClassPath;

    SvtJavaOptions_Impl() :
        aPropertyNames(4),
        bEnabled            (sal_False),
        bSecurity           (sal_False),
        nNetAccess          (0),
        bROEnabled          (CFG_READONLY_DEFAULT),
        bROSecurity         (CFG_READONLY_DEFAULT),
        bRONetAccess        (CFG_READONLY_DEFAULT),
        bROUserClassPath    (CFG_READONLY_DEFAULT)
        {
            OUString* pNames = aPropertyNames.getArray();
            pNames[0] = C2U("Enable");
            pNames[1] = C2U("Security");
            pNames[2] = C2U("NetAccess");
            pNames[3] = C2U("UserClassPath");
        }
};
/* -----------------------------18.05.01 13:28--------------------------------

 ---------------------------------------------------------------------------*/
SvtJavaOptions::SvtJavaOptions() :
    utl::ConfigItem(C2U("Office.Java/VirtualMachine")),
    pImpl(new SvtJavaOptions_Impl)
{
    RTL_LOGFILE_CONTEXT(aLog, "svtools (???) SvtJavaOptions::SvtJavaOptions()");

    Sequence< Any > aValues = GetProperties(pImpl->aPropertyNames);
    Sequence< sal_Bool > aROStates = GetReadOnlyStates(pImpl->aPropertyNames);
    const Any* pValues = aValues.getConstArray();
    const sal_Bool* pROStates = aROStates.getConstArray();
    if ( aValues.getLength() == pImpl->aPropertyNames.getLength() && aROStates.getLength() == pImpl->aPropertyNames.getLength() )
    {
        for ( int nProp = 0; nProp < pImpl->aPropertyNames.getLength(); nProp++ )
        {
            if( pValues[nProp].hasValue() )
            {
                switch ( nProp )
                {
                    case 0: pImpl->bEnabled = *(sal_Bool*)pValues[nProp].getValue(); break;
                    case 1: pImpl->bSecurity = *(sal_Bool*)pValues[nProp].getValue();break;
                    case 2: pValues[nProp] >>= pImpl->nNetAccess; break;
                    case 3: pValues[nProp] >>= pImpl->sUserClassPath; break;
                }
            }
        }
        pImpl->bROEnabled = pROStates[0];
        pImpl->bROSecurity = pROStates[1];
        pImpl->bRONetAccess = pROStates[2];
        pImpl->bROUserClassPath = pROStates[3];
    }
}
/* -----------------------------18.05.01 13:28--------------------------------

 ---------------------------------------------------------------------------*/
SvtJavaOptions::~SvtJavaOptions()
{
    delete pImpl;
}
/*-- 18.05.01 13:28:35---------------------------------------------------

  -----------------------------------------------------------------------*/
void    SvtJavaOptions::Commit()
{
    pImpl->aExecItem.Commit();

    sal_Int32 nOrgCount = pImpl->aPropertyNames.getLength();
    Sequence< OUString > aNames(nOrgCount);
    Sequence< Any > aValues(nOrgCount);
    sal_Int32 nRealCount = 0;

    const Type& rType = ::getBooleanCppuType();
    for(int nProp = 0; nProp < nOrgCount; nProp++)
    {
        switch(nProp)
        {
            case  0:
            {
                if (!pImpl->bROEnabled)
                {
                    aValues[nRealCount].setValue(&pImpl->bEnabled, rType);
                    aNames[nRealCount] = pImpl->aPropertyNames[nProp];
                    ++nRealCount;
                }
            }
            break;
            case  1:
            {
                if (!pImpl->bROSecurity)
                {
                    aValues[nRealCount].setValue(&pImpl->bSecurity, rType);
                    aNames[nRealCount] = pImpl->aPropertyNames[nProp];
                    ++nRealCount;
                }
            }
            break;
            case  2:
            {
                if (!pImpl->bRONetAccess)
                {
                    aValues[nRealCount] <<= pImpl->nNetAccess;
                    aNames[nRealCount] = pImpl->aPropertyNames[nProp];
                    ++nRealCount;
                }
            }
            break;
            case  3:
            {
                if (!pImpl->bROUserClassPath)
                {
                    aValues[nRealCount] <<= pImpl->sUserClassPath;
                    aNames[nRealCount] = pImpl->aPropertyNames[nProp];
                    ++nRealCount;
                }
            }
            break;
        }
    }
    aValues.realloc(nRealCount);
    aNames.realloc(nRealCount);
    PutProperties(aNames,aValues);
}
/*-- 18.05.01 13:28:35---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool        SvtJavaOptions::IsEnabled() const
{
    return pImpl->bEnabled;
}
/*-- 18.05.01 13:28:35---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool        SvtJavaOptions::IsSecurity()const
{
    return pImpl->bSecurity;
}
/*-- 18.05.01 13:28:35---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Int32       SvtJavaOptions::GetNetAccess() const
{
    return pImpl->nNetAccess;
}
/*-- 18.05.01 13:28:36---------------------------------------------------

  -----------------------------------------------------------------------*/
rtl::OUString&  SvtJavaOptions::GetUserClassPath()const
{
    return pImpl->sUserClassPath;
}
/*-- 18.05.01 13:28:37---------------------------------------------------

  -----------------------------------------------------------------------*/
void SvtJavaOptions::SetEnabled(sal_Bool bSet)
{
    OSL_ENSURE(!pImpl->bROEnabled, "SvtJavaOptions::SetEnabled()\nYou tried to write on a readonly value!\n");
    if(!pImpl->bROEnabled && pImpl->bEnabled != bSet)
    {
        pImpl->bEnabled = bSet;
        SetModified();
    }
}
/*-- 18.05.01 13:28:38---------------------------------------------------

  -----------------------------------------------------------------------*/
void SvtJavaOptions::SetSecurity(sal_Bool bSet)
{
    OSL_ENSURE(!pImpl->bROSecurity, "SvtJavaOptions::SetSecurity()\nYou tried to write on a readonly value!\n");
    if(!pImpl->bROSecurity && pImpl->bSecurity != bSet)
    {
        pImpl->bSecurity = bSet;
        SetModified();
    }
}
/*-- 18.05.01 13:28:38---------------------------------------------------

  -----------------------------------------------------------------------*/
void SvtJavaOptions::SetNetAccess(sal_Int32 nSet)
{
    OSL_ENSURE(!pImpl->bRONetAccess, "SvtJavaOptions::SetNetAccess()\nYou tried to write on a readonly value!\n");
    if(!pImpl->bRONetAccess && pImpl->nNetAccess != nSet)
    {
        pImpl->nNetAccess = nSet;
        SetModified();
    }
}
/*-- 18.05.01 13:28:38---------------------------------------------------

  -----------------------------------------------------------------------*/
void SvtJavaOptions::SetUserClassPath(const rtl::OUString& rSet)
{
    OSL_ENSURE(!pImpl->bROUserClassPath, "SvtJavaOptions::SetUserClassPath()\nYou tried to write on a readonly value!\n");
    if(!pImpl->bROUserClassPath && pImpl->sUserClassPath != rSet)
    {
        pImpl->sUserClassPath = rSet;
        SetModified();
    }
}

/*-- 18.05.01 14:34:32---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool        SvtJavaOptions::IsExecuteApplets() const
{
    return pImpl->aExecItem.IsExecuteApplets();
}
/*-- 18.05.01 14:34:32---------------------------------------------------

  -----------------------------------------------------------------------*/
void SvtJavaOptions::SetExecuteApplets(sal_Bool bSet)
{
    if(!pImpl->aExecItem.IsReadOnly() && pImpl->aExecItem.IsExecuteApplets() != bSet)
    {
        pImpl->aExecItem.SetExecuteApplets(bSet);
        SetModified();
    }
}
/*--10.02.2003 08:40---------------------------------------------------

-----------------------------------------------------------------------*/
sal_Bool SvtJavaOptions::IsReadOnly( EOption eOption ) const
{
    sal_Bool bRO = sal_True;
    switch(eOption)
    {
        case E_ENABLED :
            bRO = pImpl->bROEnabled;
            break;
        case E_SECURITY :
            bRO = pImpl->bROSecurity;
            break;
        case E_NETACCESS :
            bRO = pImpl->bRONetAccess;
            break;
        case E_USERCLASSPATH :
            bRO = pImpl->bROUserClassPath;
            break;
        case E_EXECUTEAPPLETS :
            bRO = pImpl->aExecItem.IsReadOnly();
            break;
    }
    return bRO;
}
<|endoftext|>


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

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

#ifndef SVTOOLS_TOOLTIPLBOX_HXX
#include "tooltiplbox.hxx"
#endif

#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif

// ============================================================================

namespace svtools {

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

void lcl_ToolTipLBox_ShowToolTip( ListBox& rListBox, const HelpEvent& rHEvt )
{
    // only show tooltip if helpmode is BALLOON or QUICK
    if ( !( rHEvt.GetMode() & HELPMODE_BALLOON ) && !( rHEvt.GetMode() & HELPMODE_QUICK ) )
    {
        // else call base class method
        rListBox.ListBox::RequestHelp( rHEvt );
        return ;
    }

    // find the list box entry the mouse points to
    Point aMousePos( rListBox.ScreenToOutputPixel( rHEvt.GetMousePosPixel() ) );

    sal_uInt16 nTop = rListBox.GetTopEntry();
    sal_uInt16 nBottom = nTop + rListBox.GetDisplayLineCount();

    sal_uInt16 nPos;
    for( nPos = nTop; nPos < nBottom; ++nPos )
    {
        Rectangle aItemRect( rListBox.GetBoundingRectangle( nPos ) );
        if( (aItemRect.Top() <= aMousePos.Y()) && (aMousePos.Y() <= aItemRect.Bottom()) )
            break;
    }

    // show text content of the entry, if it does not fit
    if( nPos < nBottom )
    {
        String aHelpText( rListBox.GetEntry( nPos ) );
        if( rListBox.GetTextWidth( aHelpText ) > rListBox.GetOutputSizePixel().Width() )
        {
            Point aLBoxPos( rListBox.OutputToScreenPixel( Point( 0, 0 ) ) );
            Size aLBoxSize( rListBox.GetSizePixel() );
            Rectangle aLBoxRect( aLBoxPos, aLBoxSize );

            if( rHEvt.GetMode() == HELPMODE_BALLOON )
                Help::ShowBalloon( &rListBox, aLBoxRect.Center(), aLBoxRect, aHelpText );
            else
                Help::ShowQuickHelp( &rListBox, aLBoxRect, aHelpText );
        }
    }
}

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

ToolTipListBox::ToolTipListBox( Window* pParent, WinBits nStyle ) :
    ListBox( pParent, nStyle )
{
}

ToolTipListBox::ToolTipListBox( Window* pParent, const ResId& rResId ) :
    ListBox( pParent, rResId )
{
}

void ToolTipListBox::RequestHelp( const HelpEvent& rHEvt )
{
    lcl_ToolTipLBox_ShowToolTip( *this, rHEvt );
}

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

ToolTipMultiListBox::ToolTipMultiListBox( Window* pParent, WinBits nStyle ) :
    MultiListBox( pParent, nStyle )
{
}

ToolTipMultiListBox::ToolTipMultiListBox( Window* pParent, const ResId& rResId ) :
    MultiListBox( pParent, rResId )
{
}

void ToolTipMultiListBox::RequestHelp( const HelpEvent& rHEvt )
{
    lcl_ToolTipLBox_ShowToolTip( *this, rHEvt );
}

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

} // namespace svtools

// ============================================================================

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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include "tooltiplbox.hxx"
#include <vcl/help.hxx>

// ============================================================================

namespace svtools {

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

void lcl_ToolTipLBox_ShowToolTip( ListBox& rListBox, const HelpEvent& rHEvt )
{
    // only show tooltip if helpmode is BALLOON or QUICK
    if ( !( rHEvt.GetMode() & HELPMODE_BALLOON ) && !( rHEvt.GetMode() & HELPMODE_QUICK ) )
    {
        // else call base class method
        rListBox.ListBox::RequestHelp( rHEvt );
        return ;
    }

    // find the list box entry the mouse points to
    Point aMousePos( rListBox.ScreenToOutputPixel( rHEvt.GetMousePosPixel() ) );

    sal_uInt16 nTop = rListBox.GetTopEntry();
    sal_uInt16 nBottom = nTop + rListBox.GetDisplayLineCount();

    sal_uInt16 nPos;
    for( nPos = nTop; nPos < nBottom; ++nPos )
    {
        Rectangle aItemRect( rListBox.GetBoundingRectangle( nPos ) );
        if( (aItemRect.Top() <= aMousePos.Y()) && (aMousePos.Y() <= aItemRect.Bottom()) )
            break;
    }

    // show text content of the entry, if it does not fit
    if( nPos < nBottom )
    {
        String aHelpText( rListBox.GetEntry( nPos ) );
        if( rListBox.GetTextWidth( aHelpText ) > rListBox.GetOutputSizePixel().Width() )
        {
            Point aLBoxPos( rListBox.OutputToScreenPixel( Point( 0, 0 ) ) );
            Size aLBoxSize( rListBox.GetSizePixel() );
            Rectangle aLBoxRect( aLBoxPos, aLBoxSize );

            if( rHEvt.GetMode() == HELPMODE_BALLOON )
                Help::ShowBalloon( &rListBox, aLBoxRect.Center(), aLBoxRect, aHelpText );
            else
                Help::ShowQuickHelp( &rListBox, aLBoxRect, aHelpText );
        }
    }
}

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

ToolTipListBox::ToolTipListBox( Window* pParent, WinBits nStyle ) :
    ListBox( pParent, nStyle )
{
}

ToolTipListBox::ToolTipListBox( Window* pParent, const ResId& rResId ) :
    ListBox( pParent, rResId )
{
}

void ToolTipListBox::RequestHelp( const HelpEvent& rHEvt )
{
    lcl_ToolTipLBox_ShowToolTip( *this, rHEvt );
}

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

ToolTipMultiListBox::ToolTipMultiListBox( Window* pParent, WinBits nStyle ) :
    MultiListBox( pParent, nStyle )
{
}

ToolTipMultiListBox::ToolTipMultiListBox( Window* pParent, const ResId& rResId ) :
    MultiListBox( pParent, rResId )
{
}

void ToolTipMultiListBox::RequestHelp( const HelpEvent& rHEvt )
{
    lcl_ToolTipLBox_ShowToolTip( *this, rHEvt );
}

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

} // namespace svtools

// ============================================================================

<|endoftext|>


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

#ifndef SVX_DATABASELOCATIONINPUT_HXX
#define SVX_DATABASELOCATIONINPUT_HXX

#include "svx/svxdllapi.h"

/** === begin UNO includes === **/
/** === end UNO includes === **/

class PushButton;
class String;
namespace svt { class OFileURLControl; }
namespace comphelper { class ComponentContext; }

#include <memory>

//........................................................................
namespace svx
{
//........................................................................

    //====================================================================
    //= DatabaseLocationInputController
    //====================================================================
    class DatabaseLocationInputController_Impl;
    /** helper class to control controls needed to input a database location

        If you allow, in your dialog, to save a database document, then you usually
        have a OFileURLControl for inputting the actual location, and a push button
        to browse for a location.

        This helper class controls such two UI elements.
    */
    class SVX_DLLPUBLIC DatabaseLocationInputController
    {
    public:
        DatabaseLocationInputController(
            const ::comphelper::ComponentContext&   _rContext,
            ::svt::OFileURLControl&                 _rLocationInput,
            PushButton&                             _rBrowseButton
        );
        ~DatabaseLocationInputController();

        /** sets the given URL at the input control, after translating it into a system path
        */
        void    setURL( const String& _rURL );

        /** returns the current database location, in form of an URL (not a system path)
        */
        String  getURL() const;

        /** prepares committing the database location entered in the input field

            Effectively, this method checks whether the file in the location already
            exists, and if so, it asks the user whether to overwrite it.

            If the method is called multiple times, this check only happens when the location
            changed since the last call.
        */
        bool    prepareCommit();

    private:
        ::std::auto_ptr< DatabaseLocationInputController_Impl >
                m_pImpl;
    };

//........................................................................
} // namespace svx
//........................................................................

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

#ifndef SVX_DATABASELOCATIONINPUT_HXX
#define SVX_DATABASELOCATIONINPUT_HXX

#include "svx/svxdllapi.h"

/** === begin UNO includes === **/
/** === end UNO includes === **/

class PushButton;
class String;
namespace svt { class OFileURLControl; }
namespace comphelper { class ComponentContext; }

#include <memory>

//........................................................................
namespace svx
{
//........................................................................

    //====================================================================
    //= DatabaseLocationInputController
    //====================================================================
    class DatabaseLocationInputController_Impl;
    /** helper class to control controls needed to input a database location

        If you allow, in your dialog, to save a database document, then you usually
        have a OFileURLControl for inputting the actual location, and a push button
        to browse for a location.

        This helper class controls such two UI elements.
    */
    class SVX_DLLPUBLIC DatabaseLocationInputController
    {
    public:
        DatabaseLocationInputController(
            const ::comphelper::ComponentContext&   _rContext,
            ::svt::OFileURLControl&                 _rLocationInput,
            PushButton&                             _rBrowseButton
        );
        ~DatabaseLocationInputController();

        /** sets the given URL at the input control, after translating it into a system path
        */
        void    setURL( const String& _rURL );

        /** returns the current database location, in form of an URL (not a system path)
        */
        String  getURL() const;

        /** prepares committing the database location entered in the input field

            Effectively, this method checks whether the file in the location already
            exists, and if so, it asks the user whether to overwrite it.

            If the method is called multiple times, this check only happens when the location
            changed since the last call.
        */
        bool    prepareCommit();

    private:
        ::std::auto_ptr< DatabaseLocationInputController_Impl >
                m_pImpl;
    };

//........................................................................
} // namespace svx
//........................................................................

#endif // SVX_DATABASELOCATIONINPUT_HXX
<|endoftext|>


<commit_before>#include "taichi/analysis/mesh_bls_analyzer.h"

#include "taichi/system/profiler.h"
#include "taichi/ir/analysis.h"

namespace taichi {
namespace lang {

MeshBLSAnalyzer::MeshBLSAnalyzer(OffloadedStmt *for_stmt,
                                 MeshBLSCaches *caches,
                                 bool auto_mesh_local,
                                 const CompileConfig &config)
    : for_stmt_(for_stmt),
      caches_(caches),
      auto_mesh_local_(auto_mesh_local),
      config_(config) {
  TI_AUTO_PROF;
  allow_undefined_visitor = true;
  invoke_default_visitor = false;
}

void MeshBLSAnalyzer::record_access(Stmt *stmt, AccessFlag flag) {
  if (!analysis_ok_) {
    return;
  }
  if (!stmt->is<GlobalPtrStmt>())
    return;  // local alloca
  auto ptr = stmt->as<GlobalPtrStmt>();
  if (ptr->indices.size() != std::size_t(1) ||
      !ptr->indices[0]->is<MeshIndexConversionStmt>())
    return;
  auto conv = ptr->indices[0]->as<MeshIndexConversionStmt>();
  auto element_type = conv->idx_type;
  auto conv_type = conv->conv_type;
  auto idx = conv->idx;
  if (conv_type == mesh::ConvType::g2r)
    return;
  for (int l = 0; l < stmt->width(); l++) {
    auto snode = ptr->snodes[l];
    if (!caches_->has(snode)) {
      if (auto_mesh_local_ &&
          (flag == AccessFlag::accumulate ||
           (flag == AccessFlag::read && config_.arch == Arch::cuda)) &&
          (!idx->is<LoopIndexStmt>() ||
           !idx->as<LoopIndexStmt>()->is_mesh_index())) {
        caches_->insert(snode);
      } else {
        continue;
      }
    }

    if (!caches_->access(snode, element_type, conv_type, flag,
                         idx->as<MeshRelationAccessStmt>()->neighbor_idx)) {
      analysis_ok_ = false;
      break;
    }
  }
}

void MeshBLSAnalyzer::visit(GlobalLoadStmt *stmt) {
  TI_ASSERT(stmt->width() == 1);  // TODO: support vectorization
  record_access(stmt->src, AccessFlag::read);
}

void MeshBLSAnalyzer::visit(GlobalStoreStmt *stmt) {
  TI_ASSERT(stmt->width() == 1);  // TODO: support vectorization
  record_access(stmt->dest, AccessFlag::write);
}

void MeshBLSAnalyzer::visit(AtomicOpStmt *stmt) {
  if (stmt->op_type == AtomicOpType::add) {
    record_access(stmt->dest, AccessFlag::accumulate);
  }
}

void MeshBLSAnalyzer::visit(Stmt *stmt) {
  TI_ASSERT(!stmt->is_container_statement());
}

bool MeshBLSAnalyzer::run() {
  const auto &block = for_stmt_->body;

  for (int i = 0; i < (int)block->statements.size(); i++) {
    block->statements[i]->accept(this);
  }

  return analysis_ok_;
}

namespace irpass {
namespace analysis {

std::unique_ptr<MeshBLSCaches> initialize_mesh_local_attribute(
    OffloadedStmt *offload,
    bool auto_mesh_local,
    const CompileConfig &config) {
  TI_AUTO_PROF
  TI_ASSERT(offload->task_type == OffloadedTaskType::mesh_for);
  std::unique_ptr<MeshBLSCaches> caches;
  caches = std::make_unique<MeshBLSCaches>();
  for (auto snode : offload->mem_access_opt.get_snodes_with_flag(
           SNodeAccessFlag::mesh_local)) {
    caches->insert(snode);
  }

  MeshBLSAnalyzer bls_analyzer(offload, caches.get(), auto_mesh_local, config);
  bool analysis_ok = bls_analyzer.run();
  if (!analysis_ok) {
    TI_ERROR("Mesh BLS analysis failed !");
  }
  return caches;
}

}  // namespace analysis
}  // namespace irpass

}  // namespace lang
}  // namespace taichi
<commit_msg>[lang] Quick fix for mesh_local analyzer (#4529)<commit_after>#include "taichi/analysis/mesh_bls_analyzer.h"

#include "taichi/system/profiler.h"
#include "taichi/ir/analysis.h"

namespace taichi {
namespace lang {

MeshBLSAnalyzer::MeshBLSAnalyzer(OffloadedStmt *for_stmt,
                                 MeshBLSCaches *caches,
                                 bool auto_mesh_local,
                                 const CompileConfig &config)
    : for_stmt_(for_stmt),
      caches_(caches),
      auto_mesh_local_(auto_mesh_local),
      config_(config) {
  TI_AUTO_PROF;
  allow_undefined_visitor = true;
  invoke_default_visitor = false;
}

void MeshBLSAnalyzer::record_access(Stmt *stmt, AccessFlag flag) {
  if (!analysis_ok_) {
    return;
  }
  if (!stmt->is<GlobalPtrStmt>())
    return;  // local alloca
  auto ptr = stmt->as<GlobalPtrStmt>();
  if (ptr->indices.size() != std::size_t(1) ||
      !ptr->indices[0]->is<MeshIndexConversionStmt>())
    return;
  auto conv = ptr->indices[0]->as<MeshIndexConversionStmt>();
  auto element_type = conv->idx_type;
  auto conv_type = conv->conv_type;
  auto idx = conv->idx;
  if (conv_type == mesh::ConvType::g2r)
    return;
  for (int l = 0; l < stmt->width(); l++) {
    auto snode = ptr->snodes[l];
    if (!caches_->has(snode)) {
      if (auto_mesh_local_ &&
          (flag == AccessFlag::accumulate ||
           (flag == AccessFlag::read && config_.arch == Arch::cuda)) &&
          (!idx->is<LoopIndexStmt>() ||
           !idx->as<LoopIndexStmt>()->is_mesh_index())) {
        caches_->insert(snode);
      } else {
        continue;
      }
    }
    if (idx->is<MeshRelationAccessStmt>()) {
      if (!caches_->access(snode, element_type, conv_type, flag,
                           idx->as<MeshRelationAccessStmt>()->neighbor_idx)) {
        analysis_ok_ = false;
        break;
      }
    } else {
      // No optimization for front-end attribute access
    }
  }
}

void MeshBLSAnalyzer::visit(GlobalLoadStmt *stmt) {
  TI_ASSERT(stmt->width() == 1);  // TODO: support vectorization
  record_access(stmt->src, AccessFlag::read);
}

void MeshBLSAnalyzer::visit(GlobalStoreStmt *stmt) {
  TI_ASSERT(stmt->width() == 1);  // TODO: support vectorization
  record_access(stmt->dest, AccessFlag::write);
}

void MeshBLSAnalyzer::visit(AtomicOpStmt *stmt) {
  if (stmt->op_type == AtomicOpType::add) {
    record_access(stmt->dest, AccessFlag::accumulate);
  }
}

void MeshBLSAnalyzer::visit(Stmt *stmt) {
  TI_ASSERT(!stmt->is_container_statement());
}

bool MeshBLSAnalyzer::run() {
  const auto &block = for_stmt_->body;

  for (int i = 0; i < (int)block->statements.size(); i++) {
    block->statements[i]->accept(this);
  }

  return analysis_ok_;
}

namespace irpass {
namespace analysis {

std::unique_ptr<MeshBLSCaches> initialize_mesh_local_attribute(
    OffloadedStmt *offload,
    bool auto_mesh_local,
    const CompileConfig &config) {
  TI_AUTO_PROF
  TI_ASSERT(offload->task_type == OffloadedTaskType::mesh_for);
  std::unique_ptr<MeshBLSCaches> caches;
  caches = std::make_unique<MeshBLSCaches>();
  for (auto snode : offload->mem_access_opt.get_snodes_with_flag(
           SNodeAccessFlag::mesh_local)) {
    caches->insert(snode);
  }

  MeshBLSAnalyzer bls_analyzer(offload, caches.get(), auto_mesh_local, config);
  bool analysis_ok = bls_analyzer.run();
  if (!analysis_ok) {
    TI_ERROR("Mesh BLS analysis failed !");
  }
  return caches;
}

}  // namespace analysis
}  // namespace irpass

}  // namespace lang
}  // namespace taichi
<|endoftext|>


<commit_before>#include <vector>
#include <thread>
#include <atomic>
#include "scene.h"
#include "samplers/sampler.h"
#include "render/render_target.h"
#include "render/camera.h"
#include "geometry/geometry.h"
#include "linalg/ray.h"
#include "linalg/transform.h"
#include "driver.h"

Worker::Worker(Scene &scene, BlockQueue &queue)
	: scene(scene), queue(queue), status(STATUS::NOT_STARTED)
{}
Worker::Worker(Worker &&w) : scene(w.scene), queue(w.queue),
	thread(std::move(w.thread)), status(w.status.load(std::memory_order_acquire))
{}
void Worker::render(){
	status.store(STATUS::WORKING, std::memory_order_release);
	Node &root = scene.get_root();
	RenderTarget &target = scene.get_render_target();
	Camera &camera = scene.get_camera();
	//Counter so we can check if we've been canceled, check after 32 pixels
	int check_cancel = 0;
	while (true){
		Sampler sampler = queue.get_block();
		if (!sampler.has_samples()){
			break;
		}
		while (sampler.has_samples()){
			std::array<float, 2> s = sampler.get_sample();
			Ray ray = camera.generate_ray(s[0], s[1]);
			HitInfo hitinfo;
			if (intersect_nodes(root, ray, hitinfo)){
				Colorf color;
				const Material *mat = hitinfo.node->get_material();
				if (mat){
					color = mat->shade(ray, hitinfo, scene.get_light_cache());
				}
				else {
					color = Colorf{0.4, 0.4, 0.4};
				}
				color.normalize();
				target.write_pixel(s[0], s[1], color);
				target.write_depth(s[0], s[1], ray.max_t);
			}
			++check_cancel;
			if (check_cancel >= 32){
				check_cancel = 0;
				int canceled = STATUS::CANCELED;
				if (status.compare_exchange_strong(canceled, STATUS::DONE, std::memory_order_acq_rel)){
					return;
				}
			}
		}
	}
	status.store(STATUS::DONE, std::memory_order_release);
}
bool Worker::intersect_nodes(Node &node, Ray &ray, HitInfo &hitinfo){
	bool hit = false;
	//Transform the ray into this nodes space
	Ray node_space = ray;
	auto &inv_transform = node.get_inv_transform();
	inv_transform(ray, node_space);
	//Test this node then its children
	if (node.get_geometry()){
		hit = node.get_geometry()->intersect(node_space, hitinfo);
		if (hit){
			hitinfo.node = &node;
		}
	}
	for (auto &c : node.get_children()){
		hit = intersect_nodes(*c, node_space, hitinfo) || hit;
	}
	if (hit){
		auto &transform = node.get_transform();
		transform(hitinfo.point, hitinfo.point);
		transform(hitinfo.normal, hitinfo.normal);
		ray.max_t = node_space.max_t;
	}
	return hit;
}
Driver::Driver(Scene &scene, int nworkers, int blocks) : scene(scene),
	queue(Sampler{0, scene.get_render_target().get_width(),
		0, scene.get_render_target().get_height()}, blocks)
{
	for (int i = 0; i < nworkers; ++i){
		workers.emplace_back(Worker{scene, queue});
	}
}
Driver::~Driver(){
	//Tell all the threads to cancel
	cancel();
}
void Driver::render(){
	//Run through and launch each thread
	for (auto &w : workers){
		w.thread = std::thread(&Worker::render, std::ref(w));
	}
}
bool Driver::done(){
	//Check which workers have finished and join them, if all are done
	//report that we're done
	bool all_done = true;
	for (auto &w : workers){
		int status = w.status.load(std::memory_order_acquire);
		if (status == STATUS::DONE){
			w.thread.join();
			w.status.store(STATUS::JOINED, std::memory_order_release);
		}
		else if (status != STATUS::JOINED){
			all_done = false;
		}
	}
	return all_done;
}
void Driver::cancel(){
	//Inform all the threads they should quit
	for (auto &w : workers){
		int status = STATUS::WORKING;
		if (w.status.compare_exchange_strong(status, STATUS::CANCELED, std::memory_order_acq_rel)){
			w.thread.join();
			w.status.store(STATUS::JOINED, std::memory_order_release);
		}
		else if (status == STATUS::DONE){
			w.thread.join();
			w.status.store(STATUS::JOINED, std::memory_order_release);
		}
	}
}
const Scene& Driver::get_scene() const {
	return scene;
}

<commit_msg>Comment clarification<commit_after>#include <vector>
#include <thread>
#include <atomic>
#include "scene.h"
#include "samplers/sampler.h"
#include "render/render_target.h"
#include "render/camera.h"
#include "geometry/geometry.h"
#include "linalg/ray.h"
#include "linalg/transform.h"
#include "driver.h"

Worker::Worker(Scene &scene, BlockQueue &queue)
	: scene(scene), queue(queue), status(STATUS::NOT_STARTED)
{}
Worker::Worker(Worker &&w) : scene(w.scene), queue(w.queue),
	thread(std::move(w.thread)), status(w.status.load(std::memory_order_acquire))
{}
void Worker::render(){
	status.store(STATUS::WORKING, std::memory_order_release);
	Node &root = scene.get_root();
	RenderTarget &target = scene.get_render_target();
	Camera &camera = scene.get_camera();
	//Counter so we can check if we've been canceled, check after every 32 pixels rendered
	int check_cancel = 0;
	while (true){
		Sampler sampler = queue.get_block();
		if (!sampler.has_samples()){
			break;
		}
		while (sampler.has_samples()){
			std::array<float, 2> s = sampler.get_sample();
			Ray ray = camera.generate_ray(s[0], s[1]);
			HitInfo hitinfo;
			if (intersect_nodes(root, ray, hitinfo)){
				Colorf color;
				const Material *mat = hitinfo.node->get_material();
				if (mat){
					color = mat->shade(ray, hitinfo, scene.get_light_cache());
				}
				else {
					color = Colorf{0.4, 0.4, 0.4};
				}
				color.normalize();
				target.write_pixel(s[0], s[1], color);
				target.write_depth(s[0], s[1], ray.max_t);
			}
			++check_cancel;
			if (check_cancel >= 32){
				check_cancel = 0;
				int canceled = STATUS::CANCELED;
				if (status.compare_exchange_strong(canceled, STATUS::DONE, std::memory_order_acq_rel)){
					return;
				}
			}
		}
	}
	status.store(STATUS::DONE, std::memory_order_release);
}
bool Worker::intersect_nodes(Node &node, Ray &ray, HitInfo &hitinfo){
	bool hit = false;
	//Transform the ray into this nodes space
	Ray node_space = ray;
	auto &inv_transform = node.get_inv_transform();
	inv_transform(ray, node_space);
	//Test this node then its children
	if (node.get_geometry()){
		hit = node.get_geometry()->intersect(node_space, hitinfo);
		if (hit){
			hitinfo.node = &node;
		}
	}
	for (auto &c : node.get_children()){
		hit = intersect_nodes(*c, node_space, hitinfo) || hit;
	}
	if (hit){
		auto &transform = node.get_transform();
		transform(hitinfo.point, hitinfo.point);
		transform(hitinfo.normal, hitinfo.normal);
		ray.max_t = node_space.max_t;
	}
	return hit;
}
Driver::Driver(Scene &scene, int nworkers, int blocks) : scene(scene),
	queue(Sampler{0, scene.get_render_target().get_width(),
		0, scene.get_render_target().get_height()}, blocks)
{
	for (int i = 0; i < nworkers; ++i){
		workers.emplace_back(Worker{scene, queue});
	}
}
Driver::~Driver(){
	//Tell all the threads to cancel
	cancel();
}
void Driver::render(){
	//Run through and launch each thread
	for (auto &w : workers){
		w.thread = std::thread(&Worker::render, std::ref(w));
	}
}
bool Driver::done(){
	//Check which workers have finished and join them, if all are done
	//report that we're done
	bool all_done = true;
	for (auto &w : workers){
		int status = w.status.load(std::memory_order_acquire);
		if (status == STATUS::DONE){
			w.thread.join();
			w.status.store(STATUS::JOINED, std::memory_order_release);
		}
		else if (status != STATUS::JOINED){
			all_done = false;
		}
	}
	return all_done;
}
void Driver::cancel(){
	//Inform all the threads they should quit
	for (auto &w : workers){
		int status = STATUS::WORKING;
		if (w.status.compare_exchange_strong(status, STATUS::CANCELED, std::memory_order_acq_rel)){
			w.thread.join();
			w.status.store(STATUS::JOINED, std::memory_order_release);
		}
		else if (status == STATUS::DONE){
			w.thread.join();
			w.status.store(STATUS::JOINED, std::memory_order_release);
		}
	}
}
const Scene& Driver::get_scene() const {
	return scene;
}

<|endoftext|>


<commit_before>#include <v8.h>
#include <node.h>
#include <cstring>
#include <stdlib.h>
#include <dbus/dbus.h>

#include "encoder.h"

namespace Encoder {

	using namespace node;
	using namespace v8;
	using namespace std;

	const char *GetSignatureFromV8Type(Handle<Value>& value)
	{
		if (value->IsTrue() || value->IsFalse() || value->IsBoolean() ) {
			return const_cast<char*>(DBUS_TYPE_BOOLEAN_AS_STRING);
		} else if (value->IsInt32()) {
			return const_cast<char*>(DBUS_TYPE_INT32_AS_STRING);
		} else if (value->IsUint32()) {
			return const_cast<char*>(DBUS_TYPE_UINT32_AS_STRING);
		} else if (value->IsNumber()) {
			return const_cast<char*>(DBUS_TYPE_DOUBLE_AS_STRING);
		} else if (value->IsString()) {
			return const_cast<char*>(DBUS_TYPE_STRING_AS_STRING);
		} else if (value->IsArray()) {
			return const_cast<char*>(DBUS_TYPE_ARRAY_AS_STRING DBUS_TYPE_VARIANT_AS_STRING);
		} else if (value->IsObject()) {
			return const_cast<char*>(DBUS_TYPE_ARRAY_AS_STRING
				DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
				DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
				DBUS_DICT_ENTRY_END_CHAR_AS_STRING);
		} else {
			return NULL;
		}
	}

	bool EncodeObject(Handle<Value> value, DBusMessageIter *iter, const char *signature)
	{
		HandleScope scope;
		DBusSignatureIter siter;
		int type;

		// Get type of current value
		dbus_signature_iter_init(&siter, signature);
		type = dbus_signature_iter_get_current_type(&siter);

		switch(type) {
		case DBUS_TYPE_BOOLEAN:
		{
			dbus_bool_t data = value->BooleanValue();

			if (!dbus_message_iter_append_basic(iter, type, &data)) {
				printf("Failed to encode boolean value\n");
				return false;
			}

			break;
		}

		case DBUS_TYPE_INT16:
		case DBUS_TYPE_INT32:
		case DBUS_TYPE_INT64:
		case DBUS_TYPE_UINT16:
		case DBUS_TYPE_UINT32:
		case DBUS_TYPE_UINT64:
		case DBUS_TYPE_BYTE:
		{
			dbus_uint64_t data = value->IntegerValue();

			if (!dbus_message_iter_append_basic(iter, type, &data)) {
				printf("Failed to encode numeric value\n");
				return false;
			}

			break;
		}

		case DBUS_TYPE_STRING:
		case DBUS_TYPE_OBJECT_PATH:
		case DBUS_TYPE_SIGNATURE:
		{
			String::Utf8Value data_val(value->ToString());
			char *data = strdup(*data_val);

			if (!dbus_message_iter_append_basic(iter, type, &data)) {
				dbus_free(data);
				printf("Failed to encode string value\n");
				return false;
			}

			dbus_free(data);

			break;
		}

		case DBUS_TYPE_DOUBLE:
		{
			double data = value->NumberValue();

			if (!dbus_message_iter_append_basic(iter, type, &data)) {
				printf("Failed to encode double value\n");
				return false;
			}

			break;
		}

		case DBUS_TYPE_ARRAY:
		{
			if (!value->IsObject()) {
				printf("Failed to encode dictionary\n");
				return false;
			}

			DBusMessageIter subIter;
			DBusSignatureIter arraySiter;
			char *array_sig = NULL;

			// Getting signature of array object
			dbus_signature_iter_recurse(&siter, &arraySiter);
			array_sig = dbus_signature_iter_get_signature(&arraySiter);

			// Open array container to process elements in there
			if (!dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, array_sig, &subIter)) {
				dbus_free(array_sig);
				printf("Can't open container for Array type\n");
				return false;
			}

			// It's a dictionary
			if (dbus_signature_iter_get_element_type(&siter) == DBUS_TYPE_DICT_ENTRY) {

				dbus_free(array_sig);

				Handle<Object> value_object = value->ToObject();
				DBusSignatureIter dictSubSiter;

				// Getting sub-signature object
				dbus_signature_iter_recurse(&arraySiter, &dictSubSiter);
				dbus_signature_iter_next(&dictSubSiter);
				char *sig = dbus_signature_iter_get_signature(&dictSubSiter);

				// process each elements
				Handle<Array> prop_names = value_object->GetPropertyNames();
				unsigned int len = prop_names->Length();

				bool failed = false;
				for (unsigned int i = 0; i < len; ++i) {
					DBusMessageIter dict_iter;

					// Open dict entry container
					if (!dbus_message_iter_open_container(&subIter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_iter)) {
						printf("Can't open container for DICT-ENTRY\n");
						failed = true;
						break;
					}

					// Getting the key and value
					Handle<Value> prop_key = prop_names->Get(i);
					Handle<Value> prop_value = value_object->Get(prop_key);

					// Append the key
					char *prop_key_str = strdup(*String::Utf8Value(prop_key->ToString()));
					dbus_message_iter_append_basic(&dict_iter, DBUS_TYPE_STRING, &prop_key_str);
					dbus_free(prop_key_str);

					// Append the value
					if (!EncodeObject(prop_value, &dict_iter, sig)) {
						dbus_message_iter_close_container(&subIter, &dict_iter);
						printf("Failed to encode element of dictionary\n");
						failed = true;
						break;
					}

					dbus_message_iter_close_container(&subIter, &dict_iter);
				}

				dbus_free(sig);
				dbus_message_iter_close_container(iter, &subIter);

				if (failed)
					return false;

				break;
			}

			if (!value->IsArray()) {
				printf("Failed to encode array object\n");
				return false;
			}

			// process each elements
			Handle<Array> arrayData = Handle<Array>::Cast(value);
			for (unsigned int i = 0; i < arrayData->Length(); ++i) {
				Local<Value> arrayItem = arrayData->Get(i);
				if (!EncodeObject(arrayItem, &subIter, array_sig))
					break;
			}

			dbus_message_iter_close_container(iter, &subIter);
			dbus_free(array_sig);

			break;
		}

		case DBUS_TYPE_VARIANT:
		{
			DBusMessageIter subIter;

			const char *var_sig = GetSignatureFromV8Type(value);

			if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, var_sig, &subIter)) {
				printf("Can't open contianer for VARIANT type\n");
				return false;
			}

			if (!EncodeObject(value, &subIter, var_sig)) {
				dbus_message_iter_close_container(iter, &subIter);
				return false;
			}

			dbus_message_iter_close_container(iter, &subIter);

			break;
		}
		case DBUS_TYPE_STRUCT:
		{
			DBusMessageIter subIter;
			DBusSignatureIter structSiter;

			// Open array container to process elements in there
			if (!dbus_message_iter_open_container(iter, DBUS_TYPE_STRUCT, NULL, &subIter)) {
				printf("Can't open container for Struct type\n");
				return false;
			}

			Handle<Object> value_object = value->ToObject();

			// Getting sub-signature object
			dbus_signature_iter_recurse(&siter, &structSiter);

			// process each elements
			Handle<Array> prop_names = value_object->GetPropertyNames();
			unsigned int len = prop_names->Length();

			for (unsigned int i = 0; i < len; ++i) {

				char *sig = dbus_signature_iter_get_signature(&structSiter);

				Handle<Value> prop_key = prop_names->Get(i);

				if (!EncodeObject(value_object->Get(prop_key), &subIter, sig)) {
					dbus_free(sig);
					printf("Failed to encode element of dictionary\n");
					return false;
				}

				dbus_free(sig);

				if (!dbus_signature_iter_next(&structSiter))
					break;
			}

			dbus_message_iter_close_container(iter, &subIter);

			break;
		}

		}

		return true;
	}

}

<commit_msg>some fixes<commit_after>#include <v8.h>
#include <node.h>
#include <cstring>
#include <stdlib.h>
#include <dbus/dbus.h>

#include "encoder.h"

namespace Encoder {

	using namespace node;
	using namespace v8;
	using namespace std;

	const char *GetSignatureFromV8Type(Handle<Value>& value)
	{
		if (value->IsTrue() || value->IsFalse() || value->IsBoolean() ) {
			return const_cast<char*>(DBUS_TYPE_BOOLEAN_AS_STRING);
		} else if (value->IsInt32()) {
			return const_cast<char*>(DBUS_TYPE_INT32_AS_STRING);
		} else if (value->IsUint32()) {
			return const_cast<char*>(DBUS_TYPE_UINT32_AS_STRING);
		} else if (value->IsNumber()) {
			return const_cast<char*>(DBUS_TYPE_DOUBLE_AS_STRING);
		} else if (value->IsString()) {
			return const_cast<char*>(DBUS_TYPE_STRING_AS_STRING);
		} else if (value->IsArray()) {
			return const_cast<char*>(DBUS_TYPE_ARRAY_AS_STRING DBUS_TYPE_VARIANT_AS_STRING);
		} else if (value->IsObject()) {
			return const_cast<char*>(DBUS_TYPE_ARRAY_AS_STRING
				DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
				DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
				DBUS_DICT_ENTRY_END_CHAR_AS_STRING);
		} else {
			return NULL;
		}
	}

	bool EncodeObject(Handle<Value> value, DBusMessageIter *iter, const char *signature)
	{
		HandleScope scope;
		DBusSignatureIter siter;
		int type;

		// Get type of current value
		dbus_signature_iter_init(&siter, signature);
		type = dbus_signature_iter_get_current_type(&siter);

		switch(type) {
		case DBUS_TYPE_BOOLEAN:
		{
			dbus_bool_t data = value->BooleanValue();

			if (!dbus_message_iter_append_basic(iter, type, &data)) {
				printf("Failed to encode boolean value\n");
				return false;
			}

			break;
		}

		case DBUS_TYPE_INT16:
		case DBUS_TYPE_INT32:
		case DBUS_TYPE_INT64:
		case DBUS_TYPE_UINT16:
		case DBUS_TYPE_UINT32:
		case DBUS_TYPE_UINT64:
		case DBUS_TYPE_BYTE:
		{
			dbus_uint64_t data = value->IntegerValue();

			if (!dbus_message_iter_append_basic(iter, type, &data)) {
				printf("Failed to encode numeric value\n");
				return false;
			}

			break;
		}

		case DBUS_TYPE_STRING:
		case DBUS_TYPE_OBJECT_PATH:
		case DBUS_TYPE_SIGNATURE:
		{
			char *data = strdup(*String::Utf8Value(value->ToString()));

			if (!dbus_message_iter_append_basic(iter, type, &data)) {
				dbus_free(data);
				printf("Failed to encode string value\n");
				return false;
			}

			dbus_free(data);

			break;
		}

		case DBUS_TYPE_DOUBLE:
		{
			double data = value->NumberValue();

			if (!dbus_message_iter_append_basic(iter, type, &data)) {
				printf("Failed to encode double value\n");
				return false;
			}

			break;
		}

		case DBUS_TYPE_ARRAY:
		{
			if (!value->IsObject()) {
				printf("Failed to encode dictionary\n");
				return false;
			}

			DBusMessageIter subIter;
			DBusSignatureIter arraySiter;
			char *array_sig = NULL;

			// Getting signature of array object
			dbus_signature_iter_recurse(&siter, &arraySiter);
			array_sig = dbus_signature_iter_get_signature(&arraySiter);

			// Open array container to process elements in there
			if (!dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, array_sig, &subIter)) {
				dbus_free(array_sig);
				printf("Can't open container for Array type\n");
				return false;
			}

			// It's a dictionary
			if (dbus_signature_iter_get_element_type(&siter) == DBUS_TYPE_DICT_ENTRY) {

				dbus_free(array_sig);

				Handle<Object> value_object = value->ToObject();
				DBusSignatureIter dictSubSiter;

				// Getting sub-signature object
				dbus_signature_iter_recurse(&arraySiter, &dictSubSiter);
				dbus_signature_iter_next(&dictSubSiter);
				char *sig = dbus_signature_iter_get_signature(&dictSubSiter);

				// process each elements
				Handle<Array> prop_names = value_object->GetPropertyNames();
				unsigned int len = prop_names->Length();

				bool failed = false;
				for (unsigned int i = 0; i < len; ++i) {
					DBusMessageIter dict_iter;

					// Open dict entry container
					if (!dbus_message_iter_open_container(&subIter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_iter)) {
						printf("Can't open container for DICT-ENTRY\n");
						failed = true;
						break;
					}

					// Getting the key and value
					Handle<Value> prop_key = prop_names->Get(i);
					Handle<Value> prop_value = value_object->Get(prop_key);

					// Append the key
					char *prop_key_str = strdup(*String::Utf8Value(prop_key->ToString()));
					dbus_message_iter_append_basic(&dict_iter, DBUS_TYPE_STRING, &prop_key_str);
					dbus_free(prop_key_str);

					// Append the value
					if (!EncodeObject(prop_value, &dict_iter, sig)) {
						dbus_message_iter_close_container(&subIter, &dict_iter);
						printf("Failed to encode element of dictionary\n");
						failed = true;
						break;
					}

					dbus_message_iter_close_container(&subIter, &dict_iter);
				}

				dbus_free(sig);
				dbus_message_iter_close_container(iter, &subIter);

				if (failed)
					return false;

				break;
			}

			if (!value->IsArray()) {
				printf("Failed to encode array object\n");
				return false;
			}

			// process each elements
			Handle<Array> arrayData = Handle<Array>::Cast(value);
			for (unsigned int i = 0; i < arrayData->Length(); ++i) {
				Local<Value> arrayItem = arrayData->Get(i);
				if (!EncodeObject(arrayItem, &subIter, array_sig))
					break;
			}

			dbus_message_iter_close_container(iter, &subIter);
			dbus_free(array_sig);

			break;
		}

		case DBUS_TYPE_VARIANT:
		{
			DBusMessageIter subIter;

			const char *var_sig = GetSignatureFromV8Type(value);

			if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, var_sig, &subIter)) {
				printf("Can't open contianer for VARIANT type\n");
				return false;
			}

			if (!EncodeObject(value, &subIter, var_sig)) {
				dbus_message_iter_close_container(iter, &subIter);
				return false;
			}

			dbus_message_iter_close_container(iter, &subIter);

			break;
		}
		case DBUS_TYPE_STRUCT:
		{
			DBusMessageIter subIter;
			DBusSignatureIter structSiter;

			// Open array container to process elements in there
			if (!dbus_message_iter_open_container(iter, DBUS_TYPE_STRUCT, NULL, &subIter)) {
				printf("Can't open container for Struct type\n");
				return false;
			}

			Handle<Object> value_object = value->ToObject();

			// Getting sub-signature object
			dbus_signature_iter_recurse(&siter, &structSiter);

			// process each elements
			Handle<Array> prop_names = value_object->GetPropertyNames();
			unsigned int len = prop_names->Length();

			for (unsigned int i = 0; i < len; ++i) {

				char *sig = dbus_signature_iter_get_signature(&structSiter);

				Handle<Value> prop_key = prop_names->Get(i);

				if (!EncodeObject(value_object->Get(prop_key), &subIter, sig)) {
					dbus_free(sig);
					printf("Failed to encode element of dictionary\n");
					return false;
				}

				dbus_free(sig);

				if (!dbus_signature_iter_next(&structSiter))
					break;
			}

			dbus_message_iter_close_container(iter, &subIter);

			break;
		}

		}

		return true;
	}

}

<|endoftext|>


<commit_before>#include "engine.h"

#include <iostream>

namespace wake
{
    static void error_callback(int err, const char* description)
    {
        std::cout << "GLFW error: " << description << std::endl;
    }

    Engine& Engine::get()
    {
        static Engine instance;
        return instance;
    }

    bool Engine::startup()
    {
        glfwSetErrorCallback(&error_callback);
        if (!glfwInit())
        {
            std::cout << "Unable to initialize GLFW." << std::endl;
            return false;
        }

        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

        glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

        window = glfwCreateWindow(800, 600, "Wake", nullptr, nullptr);
        if (window == nullptr)
        {
            std::cout << "Unable to create window." << std::endl;
            glfwTerminate();

            return false;
        }

        glfwMakeContextCurrent(window);
		glfwSwapInterval(1);

        if (glewInit() != GLEW_OK)
        {
            std::cout << "Unable to initialize GLEW." << std::endl;
            glfwTerminate();

            return false;
        }

        return true;
    }

    bool Engine::shutdown()
    {
        glfwTerminate();
        window = nullptr;

        return true;
    }

	bool Engine::run()
	{
        if (running)
        {
            std::cout << "Cannot run() while already running!" << std::endl;
            return false;
        }

		if (!window)
		{
			std::cout << "Cannot run engine with uninitialized window (did startup succeed?)" << std::endl;
			return false;
		}

        running = true;

        double lastTime = glfwGetTime();

		while (running && !glfwWindowShouldClose(window))
		{
            double frameTime = glfwGetTime() - lastTime;
            lastTime = glfwGetTime();

			TickEvent.call(frameTime);

			glfwSwapBuffers(window);
			glfwPollEvents();
		}

        running = false;

        QuitEvent.call();

		return true;
	}

    bool Engine::isRunning() const
    {
        return running;
    }

    void Engine::stop()
    {
        running = false;
    }

    double Engine::getTime() const
    {
        return glfwGetTime();
    }

	Engine::Engine()
    {

    }

    Engine::Engine(const Engine& other)
    {

    }

    Engine& Engine::operator=(const Engine& other)
    {
        return *this;
    }

    Engine::~Engine()
    {

    }
}<commit_msg>use opengl 3.3 minimum<commit_after>#include "engine.h"

#include <iostream>

namespace wake
{
    static void error_callback(int err, const char* description)
    {
        std::cout << "GLFW error: " << description << std::endl;
    }

    Engine& Engine::get()
    {
        static Engine instance;
        return instance;
    }

    bool Engine::startup()
    {
        glfwSetErrorCallback(&error_callback);
        if (!glfwInit())
        {
            std::cout << "Unable to initialize GLFW." << std::endl;
            return false;
        }

        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

        glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

        window = glfwCreateWindow(800, 600, "Wake", nullptr, nullptr);
        if (window == nullptr)
        {
            std::cout << "Unable to create window." << std::endl;
            glfwTerminate();

            return false;
        }

        glfwMakeContextCurrent(window);
		glfwSwapInterval(1);

        if (glewInit() != GLEW_OK)
        {
            std::cout << "Unable to initialize GLEW." << std::endl;
            glfwTerminate();

            return false;
        }

        return true;
    }

    bool Engine::shutdown()
    {
        glfwTerminate();
        window = nullptr;

        return true;
    }

	bool Engine::run()
	{
        if (running)
        {
            std::cout << "Cannot run() while already running!" << std::endl;
            return false;
        }

		if (!window)
		{
			std::cout << "Cannot run engine with uninitialized window (did startup succeed?)" << std::endl;
			return false;
		}

        running = true;

        double lastTime = glfwGetTime();

		while (running && !glfwWindowShouldClose(window))
		{
            double frameTime = glfwGetTime() - lastTime;
            lastTime = glfwGetTime();

			TickEvent.call(frameTime);

			glfwSwapBuffers(window);
			glfwPollEvents();
		}

        running = false;

        QuitEvent.call();

		return true;
	}

    bool Engine::isRunning() const
    {
        return running;
    }

    void Engine::stop()
    {
        running = false;
    }

    double Engine::getTime() const
    {
        return glfwGetTime();
    }

	Engine::Engine()
    {

    }

    Engine::Engine(const Engine& other)
    {

    }

    Engine& Engine::operator=(const Engine& other)
    {
        return *this;
    }

    Engine::~Engine()
    {

    }
}
<|endoftext|>