<commit_before>/*************************************************************************
 *
 *  $RCSfile: threadex.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 17:05:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <threadex.hxx>
#include <svapp.hxx>

using namespace vcl;

ThreadExecutor::ThreadExecutor()
{
    m_aFinish = osl_createCondition();
    m_aThread = NULL;
}

ThreadExecutor::~ThreadExecutor()
{
    osl_destroyCondition( m_aFinish );
    if( m_aThread )
        osl_freeThreadHandle( m_aThread );
}

void ThreadExecutor::worker( void* pInstance )
{
    ThreadExecutor* pThis = ((ThreadExecutor*)pInstance);
    pThis->m_nReturn = pThis->doIt();
    osl_setCondition( pThis->m_aFinish );
}

long ThreadExecutor::execute()
{
    osl_resetCondition( m_aFinish );
    if( m_aThread )
        osl_freeThreadHandle( m_aThread ), m_aThread = NULL;
    m_aThread = osl_createThread( worker, this );
    while( ! osl_checkCondition( m_aFinish ) )
        Application::Reschedule();
    return m_nReturn;
}

SolarThreadExecutor::SolarThreadExecutor()
{
    m_aFinish = osl_createCondition();
}

SolarThreadExecutor::~SolarThreadExecutor()
{
    osl_destroyCondition( m_aFinish );
}

IMPL_LINK( SolarThreadExecutor, worker, void*, pDummy )
{
    m_nReturn = doIt();
    osl_setCondition( m_aFinish );
    return m_nReturn;
}

long SolarThreadExecutor::execute()
{
    if( ::vos::OThread::getCurrentIdentifier() == Application::GetMainThreadIdentifier() )
    {
        m_nReturn = doIt();
        osl_setCondition( m_aFinish );
    }
    else
    {
        osl_resetCondition( m_aFinish );
        Application::PostUserEvent( LINK( this, SolarThreadExecutor, worker ) );
        osl_waitCondition( m_aFinish, NULL );
    }
    return m_nReturn;
}
<commit_msg>changed SolarThreadExecutor to release SolarMutex temporarily to avoid deadlocks<commit_after>/*************************************************************************
 *
 *  $RCSfile: threadex.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: pl $ $Date: 2000-12-05 20:14:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <threadex.hxx>
#include <svapp.hxx>

using namespace vcl;

ThreadExecutor::ThreadExecutor()
{
    m_aFinish = osl_createCondition();
    m_aThread = NULL;
}

ThreadExecutor::~ThreadExecutor()
{
    osl_destroyCondition( m_aFinish );
    if( m_aThread )
        osl_freeThreadHandle( m_aThread );
}

void ThreadExecutor::worker( void* pInstance )
{
    ThreadExecutor* pThis = ((ThreadExecutor*)pInstance);
    pThis->m_nReturn = pThis->doIt();
    osl_setCondition( pThis->m_aFinish );
}

long ThreadExecutor::execute()
{
    osl_resetCondition( m_aFinish );
    if( m_aThread )
        osl_freeThreadHandle( m_aThread ), m_aThread = NULL;
    m_aThread = osl_createThread( worker, this );
    while( ! osl_checkCondition( m_aFinish ) )
        Application::Reschedule();
    return m_nReturn;
}

SolarThreadExecutor::SolarThreadExecutor()
{
    m_aFinish = osl_createCondition();
}

SolarThreadExecutor::~SolarThreadExecutor()
{
    osl_destroyCondition( m_aFinish );
}

IMPL_LINK( SolarThreadExecutor, worker, void*, pDummy )
{
    m_nReturn = doIt();
    osl_setCondition( m_aFinish );
    return m_nReturn;
}

long SolarThreadExecutor::execute()
{
    if( ::vos::OThread::getCurrentIdentifier() == Application::GetMainThreadIdentifier() )
    {
        m_nReturn = doIt();
        osl_setCondition( m_aFinish );
    }
    else
    {
        osl_resetCondition( m_aFinish );
        ULONG nSolarMutexCount = Application::ReleaseSolarMutex();
        Application::PostUserEvent( LINK( this, SolarThreadExecutor, worker ) );
        osl_waitCondition( m_aFinish, NULL );
        if( nSolarMutexCount )
            Application::AcquireSolarMutex( nSolarMutexCount );
    }
    return m_nReturn;
}
<|endoftext|>


<commit_before><commit_msg>refactor PrintDialog to use RenderContex<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <svsys.h>
#include <rtl/process.h>
#include <rtl/ref.hxx>
#include <tools/rc.h>
#include <vcl/window.h>
#include <vcl/salinst.hxx>
#include <vcl/salframe.hxx>
#include <vcl/window.hxx>
#include <vcl/salobj.hxx>
#include <vcl/svdata.hxx>
#include <vcl/sysdata.hxx>
#include <vcl/svapp.hxx>
#include <vcl/syschild.hxx>
#include <vcl/unohelp.hxx>

#ifdef SOLAR_JAVA
#include <jni.h>
#endif

#include <comphelper/processfactory.hxx>
#include <jvmaccess/virtualmachine.hxx>
#include <com/sun/star/java/XJavaVM.hpp>
#include <com/sun/star/java/XJavaThreadRegister_11.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include <vcl/syschild.hxx>

using namespace ::com::sun::star;

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

long ImplSysChildProc( void* pInst, SalObject* /* pObject */,
                       sal_uInt16 nEvent, const void* /* pEvent */ )
{
    SystemChildWindow* pWindow = (SystemChildWindow*)pInst;
    long nRet = 0;

    ImplDelData aDogTag( pWindow );
    switch ( nEvent )
    {
        case SALOBJ_EVENT_GETFOCUS:
            // Focus holen und zwar so, das alle Handler gerufen
            // werden, als ob dieses Fenster den Focus bekommt,
            // ohne das der Frame den Focus wieder klaut
            pWindow->ImplGetFrameData()->mbSysObjFocus = sal_True;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = sal_True;
            pWindow->ToTop( TOTOP_NOGRABFOCUS );
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = sal_False;
            pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = sal_True;
            pWindow->GrabFocus();
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = sal_False;
            break;

        case SALOBJ_EVENT_LOSEFOCUS:
            // Hintenrum einen LoseFocus ausloesen, das der Status
            // der Fenster dem entsprechenden Activate-Status
            // entspricht
            pWindow->ImplGetFrameData()->mbSysObjFocus = sal_False;
            if ( !pWindow->ImplGetFrameData()->mnFocusId )
            {
                pWindow->ImplGetFrameData()->mbStartFocusState = sal_True;
                Application::PostUserEvent( pWindow->ImplGetFrameData()->mnFocusId, LINK( pWindow->ImplGetFrameWindow(), Window, ImplAsyncFocusHdl ) );
            }
            break;

        case SALOBJ_EVENT_TOTOP:
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = sal_True;
            if ( !Application::GetFocusWindow() || pWindow->HasChildPathFocus() )
                pWindow->ToTop( TOTOP_NOGRABFOCUS );
            else
                pWindow->ToTop();
            if( aDogTag.IsDead() )
                break;
            pWindow->GrabFocus();
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = sal_False;
            break;
    }

    return nRet;
}

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

void SystemChildWindow::ImplInitSysChild( Window* pParent, WinBits nStyle, SystemWindowData *pData, sal_Bool bShow )
{
    mpWindowImpl->mpSysObj = ImplGetSVData()->mpDefInst->CreateObject( pParent->ImplGetFrame(), pData, bShow );

    Window::ImplInit( pParent, nStyle, NULL );

    // Wenn es ein richtiges SysChild ist, dann painten wir auch nicht
    if ( GetSystemData() )
    {
        mpWindowImpl->mpSysObj->SetCallback( this, ImplSysChildProc );
        SetParentClipMode( PARENTCLIPMODE_CLIP );
        SetBackground();
    }
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    ImplInitSysChild( pParent, nStyle, NULL );
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle, SystemWindowData *pData, sal_Bool bShow ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    ImplInitSysChild( pParent, nStyle, pData, bShow );
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, const ResId& rResId ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    rResId.SetRT( RSC_WINDOW );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInitSysChild( pParent, nStyle, NULL );
    ImplLoadRes( rResId );

    if ( !(nStyle & WB_HIDE) )
        Show();
}

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

SystemChildWindow::~SystemChildWindow()
{
    Hide();
    if ( mpWindowImpl->mpSysObj )
    {
        ImplGetSVData()->mpDefInst->DestroyObject( mpWindowImpl->mpSysObj );
        mpWindowImpl->mpSysObj = NULL;
    }
}

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

const SystemEnvData* SystemChildWindow::GetSystemData() const
{
    if ( mpWindowImpl->mpSysObj )
        return mpWindowImpl->mpSysObj->GetSystemData();
    else
        return NULL;
}

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

void SystemChildWindow::EnableEraseBackground( sal_Bool bEnable )
{
    if ( mpWindowImpl->mpSysObj )
        mpWindowImpl->mpSysObj->EnableEraseBackground( bEnable );
}

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

sal_Bool SystemChildWindow::IsEraseBackgroundEnabled()
{
    if ( mpWindowImpl->mpSysObj )
        return mpWindowImpl->mpSysObj->IsEraseBackgroundEnabled();
    else
        return sal_False;
}

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

void SystemChildWindow::ImplTestJavaException( void* pEnv )
{
#ifdef SOLAR_JAVA
    JNIEnv*     pJavaEnv = reinterpret_cast< JNIEnv* >( pEnv );
    jthrowable  jtThrowable = pJavaEnv->ExceptionOccurred();

    if( jtThrowable )
    { // is it a java exception ?
#if OSL_DEBUG_LEVEL > 1
        pJavaEnv->ExceptionDescribe();
#endif // OSL_DEBUG_LEVEL > 1
        pJavaEnv->ExceptionClear();

        jclass          jcThrowable = pJavaEnv->FindClass("java/lang/Throwable");
        jmethodID       jmThrowable_getMessage = pJavaEnv->GetMethodID(jcThrowable, "getMessage", "()Ljava/lang/String;");
        jstring         jsMessage = (jstring) pJavaEnv->CallObjectMethod(jtThrowable, jmThrowable_getMessage);
            ::rtl::OUString ouMessage;

            if(jsMessage)
            {
                const jchar * jcMessage = pJavaEnv->GetStringChars(jsMessage, NULL);
                ouMessage = ::rtl::OUString(jcMessage);
                pJavaEnv->ReleaseStringChars(jsMessage, jcMessage);
            }

            throw uno::RuntimeException(ouMessage, uno::Reference<uno::XInterface>());
    }
#endif // SOLAR_JAVA
}

void SystemChildWindow::SetForwardKey( sal_Bool bEnable )
{
    if ( mpWindowImpl->mpSysObj )
        mpWindowImpl->mpSysObj->SetForwardKey( bEnable );
}

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

sal_IntPtr SystemChildWindow::GetParentWindowHandle( sal_Bool bUseJava )
{
    sal_IntPtr nRet = 0;

#if defined WNT
    nRet = reinterpret_cast< sal_IntPtr >( GetSystemData()->hWnd );
#elif defined QUARTZ
    // FIXME: this is wrong
    nRet = reinterpret_cast< sal_IntPtr >( GetSystemData()->pView );
#elif defined UNX
    if( !bUseJava )
    {
        nRet = (sal_IntPtr) GetSystemData()->aWindow;
    }
#ifdef SOLAR_JAVA
    else
    {
        uno::Reference< lang::XMultiServiceFactory > xFactory( vcl::unohelper::GetMultiServiceFactory() );

        if( xFactory.is() && ( GetSystemData()->aWindow > 0 ) )
        {
            try
            {
                    ::rtl::Reference< ::jvmaccess::VirtualMachine > xVM;
                    uno::Reference< java::XJavaVM >                 xJavaVM( xFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine") ) ), uno::UNO_QUERY );
                    uno::Sequence< sal_Int8 >                       aProcessID( 17 );

                    rtl_getGlobalProcessId( (sal_uInt8*) aProcessID.getArray() );
                    aProcessID[ 16 ] = 0;
                    OSL_ENSURE(sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *), "Pointer cannot be represented as sal_Int64");
                    sal_Int64 nPointer = reinterpret_cast< sal_Int64 >( static_cast< jvmaccess::VirtualMachine * >(0));
                    xJavaVM->getJavaVM(aProcessID) >>= nPointer;
                    xVM = reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);

                    if( xVM.is() )
                    {
                        try
                        {
                                ::jvmaccess::VirtualMachine::AttachGuard    aVMAttachGuard( xVM );
                                JNIEnv*                                     pEnv = aVMAttachGuard.getEnvironment();

                                jclass jcToolkit = pEnv->FindClass("java/awt/Toolkit");
                                ImplTestJavaException(pEnv);

                                jmethodID jmToolkit_getDefaultToolkit = pEnv->GetStaticMethodID( jcToolkit, "getDefaultToolkit", "()Ljava/awt/Toolkit;" );
                                ImplTestJavaException(pEnv);

                                pEnv->CallStaticObjectMethod(jcToolkit, jmToolkit_getDefaultToolkit);
                                ImplTestJavaException(pEnv);

                                jclass jcMotifAppletViewer = pEnv->FindClass("sun/plugin/navig/motif/MotifAppletViewer");
                                if( pEnv->ExceptionOccurred() )
                                {
                                    pEnv->ExceptionClear();

                                    jcMotifAppletViewer = pEnv->FindClass( "sun/plugin/viewer/MNetscapePluginContext");
                                    ImplTestJavaException(pEnv);
                                }

                                jclass jcClassLoader = pEnv->FindClass("java/lang/ClassLoader");
                                ImplTestJavaException(pEnv);

                                jmethodID jmClassLoader_loadLibrary = pEnv->GetStaticMethodID( jcClassLoader, "loadLibrary", "(Ljava/lang/Class;Ljava/lang/String;Z)V");
                                ImplTestJavaException(pEnv);

                                jstring jsplugin = pEnv->NewStringUTF("javaplugin_jni");
                                ImplTestJavaException(pEnv);

                                pEnv->CallStaticVoidMethod(jcClassLoader, jmClassLoader_loadLibrary, jcMotifAppletViewer, jsplugin, JNI_FALSE);
                                ImplTestJavaException(pEnv);

                                jmethodID jmMotifAppletViewer_getWidget = pEnv->GetStaticMethodID( jcMotifAppletViewer, "getWidget", "(IIIII)I" );
                                ImplTestJavaException(pEnv);

                                const Size aSize( GetOutputSizePixel() );
                                jint ji_widget = pEnv->CallStaticIntMethod( jcMotifAppletViewer, jmMotifAppletViewer_getWidget,
                                        GetSystemData()->aWindow, 0, 0, aSize.Width(), aSize.Height() );
                                ImplTestJavaException(pEnv);

                                nRet = static_cast< sal_IntPtr >( ji_widget );
                        }
                        catch( uno::RuntimeException& )
                        {
                        }

                        if( !nRet )
                            nRet = static_cast< sal_IntPtr >( GetSystemData()->aWindow );
                    }
            }
            catch( ... )
            {
            }
        }
    }
#endif // SOLAR_JAVA
#else // WNT || QUARTZ || UNX
#endif

    return nRet;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: silence some warnings<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <svsys.h>
#include <rtl/process.h>
#include <rtl/ref.hxx>
#include <tools/rc.h>
#include <vcl/window.h>
#include <vcl/salinst.hxx>
#include <vcl/salframe.hxx>
#include <vcl/window.hxx>
#include <vcl/salobj.hxx>
#include <vcl/svdata.hxx>
#include <vcl/sysdata.hxx>
#include <vcl/svapp.hxx>
#include <vcl/syschild.hxx>
#include <vcl/unohelp.hxx>

#ifdef SOLAR_JAVA
#include <jni.h>
#endif

#include <comphelper/processfactory.hxx>
#include <jvmaccess/virtualmachine.hxx>
#include <com/sun/star/java/XJavaVM.hpp>
#include <com/sun/star/java/XJavaThreadRegister_11.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include <vcl/syschild.hxx>

using namespace ::com::sun::star;

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

long ImplSysChildProc( void* pInst, SalObject* /* pObject */,
                       sal_uInt16 nEvent, const void* /* pEvent */ )
{
    SystemChildWindow* pWindow = (SystemChildWindow*)pInst;
    long nRet = 0;

    ImplDelData aDogTag( pWindow );
    switch ( nEvent )
    {
        case SALOBJ_EVENT_GETFOCUS:
            // Focus holen und zwar so, das alle Handler gerufen
            // werden, als ob dieses Fenster den Focus bekommt,
            // ohne das der Frame den Focus wieder klaut
            pWindow->ImplGetFrameData()->mbSysObjFocus = sal_True;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = sal_True;
            pWindow->ToTop( TOTOP_NOGRABFOCUS );
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = sal_False;
            pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = sal_True;
            pWindow->GrabFocus();
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = sal_False;
            break;

        case SALOBJ_EVENT_LOSEFOCUS:
            // Hintenrum einen LoseFocus ausloesen, das der Status
            // der Fenster dem entsprechenden Activate-Status
            // entspricht
            pWindow->ImplGetFrameData()->mbSysObjFocus = sal_False;
            if ( !pWindow->ImplGetFrameData()->mnFocusId )
            {
                pWindow->ImplGetFrameData()->mbStartFocusState = sal_True;
                Application::PostUserEvent( pWindow->ImplGetFrameData()->mnFocusId, LINK( pWindow->ImplGetFrameWindow(), Window, ImplAsyncFocusHdl ) );
            }
            break;

        case SALOBJ_EVENT_TOTOP:
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = sal_True;
            if ( !Application::GetFocusWindow() || pWindow->HasChildPathFocus() )
                pWindow->ToTop( TOTOP_NOGRABFOCUS );
            else
                pWindow->ToTop();
            if( aDogTag.IsDead() )
                break;
            pWindow->GrabFocus();
            if( aDogTag.IsDead() )
                break;
            pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = sal_False;
            break;
    }

    return nRet;
}

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

void SystemChildWindow::ImplInitSysChild( Window* pParent, WinBits nStyle, SystemWindowData *pData, sal_Bool bShow )
{
    mpWindowImpl->mpSysObj = ImplGetSVData()->mpDefInst->CreateObject( pParent->ImplGetFrame(), pData, bShow );

    Window::ImplInit( pParent, nStyle, NULL );

    // Wenn es ein richtiges SysChild ist, dann painten wir auch nicht
    if ( GetSystemData() )
    {
        mpWindowImpl->mpSysObj->SetCallback( this, ImplSysChildProc );
        SetParentClipMode( PARENTCLIPMODE_CLIP );
        SetBackground();
    }
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    ImplInitSysChild( pParent, nStyle, NULL );
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle, SystemWindowData *pData, sal_Bool bShow ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    ImplInitSysChild( pParent, nStyle, pData, bShow );
}

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

SystemChildWindow::SystemChildWindow( Window* pParent, const ResId& rResId ) :
    Window( WINDOW_SYSTEMCHILDWINDOW )
{
    rResId.SetRT( RSC_WINDOW );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInitSysChild( pParent, nStyle, NULL );
    ImplLoadRes( rResId );

    if ( !(nStyle & WB_HIDE) )
        Show();
}

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

SystemChildWindow::~SystemChildWindow()
{
    Hide();
    if ( mpWindowImpl->mpSysObj )
    {
        ImplGetSVData()->mpDefInst->DestroyObject( mpWindowImpl->mpSysObj );
        mpWindowImpl->mpSysObj = NULL;
    }
}

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

const SystemEnvData* SystemChildWindow::GetSystemData() const
{
    if ( mpWindowImpl->mpSysObj )
        return mpWindowImpl->mpSysObj->GetSystemData();
    else
        return NULL;
}

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

void SystemChildWindow::EnableEraseBackground( sal_Bool bEnable )
{
    if ( mpWindowImpl->mpSysObj )
        mpWindowImpl->mpSysObj->EnableEraseBackground( bEnable );
}

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

sal_Bool SystemChildWindow::IsEraseBackgroundEnabled()
{
    if ( mpWindowImpl->mpSysObj )
        return mpWindowImpl->mpSysObj->IsEraseBackgroundEnabled();
    else
        return sal_False;
}

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

void SystemChildWindow::ImplTestJavaException( void* pEnv )
{
#ifdef SOLAR_JAVA
    JNIEnv*     pJavaEnv = reinterpret_cast< JNIEnv* >( pEnv );
    jthrowable  jtThrowable = pJavaEnv->ExceptionOccurred();

    if( jtThrowable )
    { // is it a java exception ?
#if OSL_DEBUG_LEVEL > 1
        pJavaEnv->ExceptionDescribe();
#endif // OSL_DEBUG_LEVEL > 1
        pJavaEnv->ExceptionClear();

        jclass          jcThrowable = pJavaEnv->FindClass("java/lang/Throwable");
        jmethodID       jmThrowable_getMessage = pJavaEnv->GetMethodID(jcThrowable, "getMessage", "()Ljava/lang/String;");
        jstring         jsMessage = (jstring) pJavaEnv->CallObjectMethod(jtThrowable, jmThrowable_getMessage);
            ::rtl::OUString ouMessage;

            if(jsMessage)
            {
                const jchar * jcMessage = pJavaEnv->GetStringChars(jsMessage, NULL);
                ouMessage = ::rtl::OUString(jcMessage);
                pJavaEnv->ReleaseStringChars(jsMessage, jcMessage);
            }

            throw uno::RuntimeException(ouMessage, uno::Reference<uno::XInterface>());
    }
#else
    (void)pEnv;
#endif // SOLAR_JAVA
}

void SystemChildWindow::SetForwardKey( sal_Bool bEnable )
{
    if ( mpWindowImpl->mpSysObj )
        mpWindowImpl->mpSysObj->SetForwardKey( bEnable );
}

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

sal_IntPtr SystemChildWindow::GetParentWindowHandle( sal_Bool bUseJava )
{
    sal_IntPtr nRet = 0;

#if defined WNT
    nRet = reinterpret_cast< sal_IntPtr >( GetSystemData()->hWnd );
#elif defined QUARTZ
    // FIXME: this is wrong
    nRet = reinterpret_cast< sal_IntPtr >( GetSystemData()->pView );
#elif defined UNX
    if( !bUseJava )
    {
        nRet = (sal_IntPtr) GetSystemData()->aWindow;
    }
#ifdef SOLAR_JAVA
    else
    {
        uno::Reference< lang::XMultiServiceFactory > xFactory( vcl::unohelper::GetMultiServiceFactory() );

        if( xFactory.is() && ( GetSystemData()->aWindow > 0 ) )
        {
            try
            {
                    ::rtl::Reference< ::jvmaccess::VirtualMachine > xVM;
                    uno::Reference< java::XJavaVM >                 xJavaVM( xFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine") ) ), uno::UNO_QUERY );
                    uno::Sequence< sal_Int8 >                       aProcessID( 17 );

                    rtl_getGlobalProcessId( (sal_uInt8*) aProcessID.getArray() );
                    aProcessID[ 16 ] = 0;
                    OSL_ENSURE(sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *), "Pointer cannot be represented as sal_Int64");
                    sal_Int64 nPointer = reinterpret_cast< sal_Int64 >( static_cast< jvmaccess::VirtualMachine * >(0));
                    xJavaVM->getJavaVM(aProcessID) >>= nPointer;
                    xVM = reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);

                    if( xVM.is() )
                    {
                        try
                        {
                                ::jvmaccess::VirtualMachine::AttachGuard    aVMAttachGuard( xVM );
                                JNIEnv*                                     pEnv = aVMAttachGuard.getEnvironment();

                                jclass jcToolkit = pEnv->FindClass("java/awt/Toolkit");
                                ImplTestJavaException(pEnv);

                                jmethodID jmToolkit_getDefaultToolkit = pEnv->GetStaticMethodID( jcToolkit, "getDefaultToolkit", "()Ljava/awt/Toolkit;" );
                                ImplTestJavaException(pEnv);

                                pEnv->CallStaticObjectMethod(jcToolkit, jmToolkit_getDefaultToolkit);
                                ImplTestJavaException(pEnv);

                                jclass jcMotifAppletViewer = pEnv->FindClass("sun/plugin/navig/motif/MotifAppletViewer");
                                if( pEnv->ExceptionOccurred() )
                                {
                                    pEnv->ExceptionClear();

                                    jcMotifAppletViewer = pEnv->FindClass( "sun/plugin/viewer/MNetscapePluginContext");
                                    ImplTestJavaException(pEnv);
                                }

                                jclass jcClassLoader = pEnv->FindClass("java/lang/ClassLoader");
                                ImplTestJavaException(pEnv);

                                jmethodID jmClassLoader_loadLibrary = pEnv->GetStaticMethodID( jcClassLoader, "loadLibrary", "(Ljava/lang/Class;Ljava/lang/String;Z)V");
                                ImplTestJavaException(pEnv);

                                jstring jsplugin = pEnv->NewStringUTF("javaplugin_jni");
                                ImplTestJavaException(pEnv);

                                pEnv->CallStaticVoidMethod(jcClassLoader, jmClassLoader_loadLibrary, jcMotifAppletViewer, jsplugin, JNI_FALSE);
                                ImplTestJavaException(pEnv);

                                jmethodID jmMotifAppletViewer_getWidget = pEnv->GetStaticMethodID( jcMotifAppletViewer, "getWidget", "(IIIII)I" );
                                ImplTestJavaException(pEnv);

                                const Size aSize( GetOutputSizePixel() );
                                jint ji_widget = pEnv->CallStaticIntMethod( jcMotifAppletViewer, jmMotifAppletViewer_getWidget,
                                        GetSystemData()->aWindow, 0, 0, aSize.Width(), aSize.Height() );
                                ImplTestJavaException(pEnv);

                                nRet = static_cast< sal_IntPtr >( ji_widget );
                        }
                        catch( uno::RuntimeException& )
                        {
                        }

                        if( !nRet )
                            nRet = static_cast< sal_IntPtr >( GetSystemData()->aWindow );
                    }
            }
            catch( ... )
            {
            }
        }
    }
#endif // SOLAR_JAVA
#else // WNT || QUARTZ || UNX
#endif

    return nRet;
}

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


<commit_before>#include <string>
#include <obs-module.h>
#include "nicookie.h"
#include "nico-live-api.hpp"
#include "nicolive-errno.h"
#include "nicolive-log.h"

namespace
{
char *acquired_session = nullptr;
inline void nicolive_api_set_session(const char *str)
{
	if (acquired_session != nullptr) {
		bfree(acquired_session);
	}
	acquired_session = bstrdup(str);
}
inline void nicolive_api_set_session(const std::string &str)
{
	nicolive_api_set_session(str.c_str());
}
inline const std::string nicolive_api_get_session_nla(const NicoLiveApi &nla)
{
	return nla.getCookie("user_session");
}
}

extern "C" void nicolive_api_clear_session()
{
	if (acquired_session != nullptr) {
		bfree(acquired_session);
		acquired_session = nullptr;
	}
}

extern "C" const char *nicolive_api_get_session() { return acquired_session; }
extern "C" const char *nicolive_api_get_session_login(
    const char *mail, const char *password)
{
	if (mail == nullptr) {
		nicolive_errno = NICOLIVE_ERROR_NO_MAIL_ADDRESS;
		return nullptr;
	}
	if (mail[0] == '\0') {
		nicolive_errno = NICOLIVE_ERROR_EMPTY_MAIL_ADDRESS;
		return nullptr;
	}
	if (password == nullptr) {
		nicolive_errno = NICOLIVE_ERROR_NO_PASSWORD;
		return nullptr;
	}
	if (password[0] == '\0') {
		nicolive_errno = NICOLIVE_ERROR_EMPTY_PASSWORD;
		return nullptr;
	}

	std::string mail_str(mail);
	std::string password_str(password);
	NicoLiveApi nla;
	if (nla.loginSiteNicolive(mail_str, password_str)) {
		nicolive_errno = NICOLIVE_ERROR_LOGIN_SUCCESSFUL;
		nicolive_api_set_session(nicolive_api_get_session_nla(nla));
	} else {
		nicolive_errno = NICOLIVE_ERROR_LOGIN_FAILURE;
		nicolive_api_clear_session();
	}
	return acquired_session;
}
extern "C" const char *nicolive_api_get_session_app(int app)
{
	nicookie_errno = 0;
	const char *session = nicookie_get_session(app);
	if (session != nullptr) {
		nicolive_errno = NICOLIVE_ERROR_COOKIE_ACQUISITION_SUCCESSFUL;
		nicolive_api_set_session(session);
	} else {
		nicolive_errno = NICOLIVE_ERROR_NICOOKIE | nicookie_errno;
		nicolive_api_clear_session();
	}
	return acquired_session;
}

extern "C" bool nicolive_api_check_session(const char *session)
{
	if (session == nullptr) {
		nicolive_errno = NICOLIVE_ERROR_NO_USER_SESSION;
		return false;
	}
	if (session[0] == '\0') {
		nicolive_errno = NICOLIVE_ERROR_EMPTY_USER_SESSION;
		return false;
	}

	std::string session_str(session);
	NicoLiveApi nla;
	nla.setCookie("user_session", session_str);
	const std::string statusXpath = "/getpublishstatus/@status";
	const std::string errorCodeXpath =
	    "/getpublishstatus/error/code/text()";
	std::unordered_map<std::string, std::vector<std::string>> data;
	data[statusXpath] = std::vector<std::string>();
	data[errorCodeXpath] = std::vector<std::string>();
	bool result = nla.getPublishStatus(&data);

	if (!result) return false;
	if (data[statusXpath].empty()) return false;
	std::string &status = data[statusXpath][0];
	if (status == "ok") return true;
	if (status == "fail" && !data[errorCodeXpath].empty() &&
	    data[errorCodeXpath][0] == "notfound")
		return true;
	return false;
}

extern "C" bool nicolive_api_check_login(const char *mail, const char *password)
{
	const char *session = nicolive_api_get_session_login(mail, password);
	if (session != nullptr) {
		return nicolive_api_check_session(session);
	} else {
		return false;
	}
}

extern "C" bool nicolive_api_check_app(int app)
{
	const char *session = nicolive_api_get_session_app(app);
	if (session != nullptr) {
		return nicolive_api_check_session(session);
	} else {
		return false;
	}
}
<commit_msg>エラーセットを追加<commit_after>#include <string>
#include <obs-module.h>
#include "nicookie.h"
#include "nico-live-api.hpp"
#include "nicolive-errno.h"
#include "nicolive-log.h"

namespace
{
char *acquired_session = nullptr;
inline void nicolive_api_set_session(const char *str)
{
	if (acquired_session != nullptr) {
		bfree(acquired_session);
	}
	acquired_session = bstrdup(str);
}
inline void nicolive_api_set_session(const std::string &str)
{
	nicolive_api_set_session(str.c_str());
}
inline const std::string nicolive_api_get_session_nla(const NicoLiveApi &nla)
{
	return nla.getCookie("user_session");
}
}

extern "C" void nicolive_api_clear_session()
{
	if (acquired_session != nullptr) {
		bfree(acquired_session);
		acquired_session = nullptr;
	}
}

extern "C" const char *nicolive_api_get_session() { return acquired_session; }
extern "C" const char *nicolive_api_get_session_login(
    const char *mail, const char *password)
{
	if (mail == nullptr) {
		nicolive_errno = NICOLIVE_ERROR_NO_MAIL_ADDRESS;
		return nullptr;
	}
	if (mail[0] == '\0') {
		nicolive_errno = NICOLIVE_ERROR_EMPTY_MAIL_ADDRESS;
		return nullptr;
	}
	if (password == nullptr) {
		nicolive_errno = NICOLIVE_ERROR_NO_PASSWORD;
		return nullptr;
	}
	if (password[0] == '\0') {
		nicolive_errno = NICOLIVE_ERROR_EMPTY_PASSWORD;
		return nullptr;
	}

	std::string mail_str(mail);
	std::string password_str(password);
	NicoLiveApi nla;
	if (nla.loginSiteNicolive(mail_str, password_str)) {
		nicolive_errno = NICOLIVE_ERROR_LOGIN_SUCCESSFUL;
		nicolive_api_set_session(nicolive_api_get_session_nla(nla));
	} else {
		nicolive_errno = NICOLIVE_ERROR_LOGIN_FAILURE;
		nicolive_api_clear_session();
	}
	return acquired_session;
}
extern "C" const char *nicolive_api_get_session_app(int app)
{
	nicookie_errno = 0;
	const char *session = nicookie_get_session(app);
	if (session != nullptr) {
		nicolive_errno = NICOLIVE_ERROR_COOKIE_ACQUISITION_SUCCESSFUL;
		nicolive_api_set_session(session);
	} else {
		nicolive_errno = NICOLIVE_ERROR_NICOOKIE | nicookie_errno;
		nicolive_api_clear_session();
	}
	return acquired_session;
}

extern "C" bool nicolive_api_check_session(const char *session)
{
	if (session == nullptr) {
		nicolive_errno = NICOLIVE_ERROR_NO_USER_SESSION;
		return false;
	}
	if (session[0] == '\0') {
		nicolive_errno = NICOLIVE_ERROR_EMPTY_USER_SESSION;
		return false;
	}

	std::string session_str(session);
	NicoLiveApi nla;
	nla.setCookie("user_session", session_str);
	const std::string statusXpath = "/getpublishstatus/@status";
	const std::string errorCodeXpath =
	    "/getpublishstatus/error/code/text()";
	std::unordered_map<std::string, std::vector<std::string>> data;
	data[statusXpath] = std::vector<std::string>();
	data[errorCodeXpath] = std::vector<std::string>();
	bool result = nla.getPublishStatus(&data);

	if (!result) {
		nicolive_errno = NICOLIVE_ERROR_ACCESS_ERROR;
		return false;
	}
	if (data[statusXpath].empty()) {
		// FIXME: access error? service down?
		nicolive_errno = NICOLIVE_ERROR_ACCESS_ERROR;
		return false;
	}

	std::string &status = data[statusXpath].front();

	if (status == "ok") {
		nicolive_errno = NICOLIVE_ERROR_VALID_USER_SESSION;
		return true;
	}

	if (status == "fail") {
		std::string error_code(data[errorCodeXpath].empty()
					   ? data[errorCodeXpath].front()
					   : "");
		if (error_code == "notfound" ||
		    error_code == "permison_denied") {
			nicolive_errno = NICOLIVE_ERROR_VALID_USER_SESSION;
			return true;
		}
	}
	nicolive_errno = NICOLIVE_ERROR_INVALID_USER_SESSION;
	return false;
}

extern "C" bool nicolive_api_check_login(const char *mail, const char *password)
{
	const char *session = nicolive_api_get_session_login(mail, password);
	if (session != nullptr) {
		return nicolive_api_check_session(session);
	} else {
		return false;
	}
}

extern "C" bool nicolive_api_check_app(int app)
{
	const char *session = nicolive_api_get_session_app(app);
	if (session != nullptr) {
		return nicolive_api_check_session(session);
	} else {
		return false;
	}
}
<|endoftext|>


<commit_before>/**
 * Clever programming language
 * Copyright (c) Clever Team
 *
 * This file is distributed under the MIT license. See LICENSE for details.
 */

#include "core/value.h"
#include "core/vm.h"
#include "types/array.h"
#include "types/function.h"

namespace clever {

void* ArrayType::allocData(CLEVER_TYPE_CTOR_ARGS) const
{
	ArrayObject* arr = new ArrayObject();
	ValueVector& vec = arr->getData();

	for (size_t i = 0, j = args->size(); i < j; ++i) {
		vec.push_back(args->at(i)->clone());
	}

	return arr;
}

void ArrayType::deallocData(void* data)
{
	ArrayObject* arr = static_cast<ArrayObject*>(data);
	ValueVector& vec = arr->getData();

	for (size_t i = 0, j = vec.size(); i < j; ++i) {
		vec[i]->delRef();
	}

	delete arr;
}

void ArrayType::dump(const void* value, std::ostream& out) const
{
	Value::DataValue* data = static_cast<Value::DataValue*>(const_cast<void*>(value));
	ValueVector& vec = (static_cast<ArrayObject*>(data->obj->getObj()))->getData();

	out << "[";

	for (size_t i = 0, j = vec.size(); i < j; ++i) {
		vec.at(i)->dump(out);
		if (i < j-1) {
			out << ", ";
		}
	}

	out << "]";
}

// void Array::append([arg, ... ])
CLEVER_METHOD(ArrayType::append)
{
	if (args.size()) {
		ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

		for (size_t i = 0, j = args.size(); i < j; ++i) {
			vec.push_back(args[i]->clone());
		}
	}
	result->setNull();
}

// int Array::size()
CLEVER_METHOD(ArrayType::size)
{
	if (!clever_check_no_args()) {
		return;
	}

	result->setInt((CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData().size());
}

// mixed Array::at(int position)
CLEVER_METHOD(ArrayType::at)
{
	if (!clever_check_args("i")) {
		return;
	}

	ValueVector& arr = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

	if (args[0]->getInt() < 0
		|| arr.size() <= size_t(args[0]->getInt())) {
		result->setNull();
		return;
	}

	result->copy(arr.at(args[0]->getInt()));
}

// void Array::reserve(int size)
CLEVER_METHOD(ArrayType::reserve)
{
	if (!clever_check_args("i")) {
		return;
	}

	ArrayObject* arr = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS());

	result->setNull();

	if (args[0]->getInt() < 0) {
		return;
	}

	arr->getData().reserve(args[0]->getInt());
}

// Array Array::reverse()
// Returns the reverse of this array
CLEVER_METHOD(ArrayType::reverse)
{
	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();
	ValueVector::reverse_iterator it(vec.rbegin()), end(vec.rend());
	ValueVector rev;

	while (it != end){
		rev.push_back((*it));
		it++;
	}

	CLEVER_RETURN_ARRAY(CLEVER_ARRAY_TYPE->allocData(&rev));
}

// mixed Array.shift()
// Removes and returns the first element of the array
CLEVER_METHOD(ArrayType::shift)
{
	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

	if (!vec.size()) {
		result->setNull();
		return;
	}

	result->copy(vec[0]);

	ValueVector(vec.begin()+1, vec.end()).swap(vec);
}

// mixed Array.pop()
// Removes and returns the last element of the array
CLEVER_METHOD(ArrayType::pop)
{
	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

	if (!vec.size()) {
		result->setNull();
		return;
	}

	result->copy(vec[vec.size()-1]);

	ValueVector(vec.begin(), vec.end()-1).swap(vec);
}

// Array Array.range(int start, int end)
// Returns a range as a new array
CLEVER_METHOD(ArrayType::range)
{
	if (!clever_check_args("ii")) {
		return;
	}

	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

	if (!vec.size()){
		result->setNull();
		return;
	}

	long bounds[3] = {CLEVER_ARG_INT(0), CLEVER_ARG_INT(1), (long) vec.size()};
	ValueVector ran;

	bool reverse = (bounds[0] > bounds[1]);
	while((reverse ? (bounds[1] <= bounds[0]) : (bounds[0] <= bounds[1]))) {
		if ((bounds[0] < 0 || bounds[1] < 0) ||
			(bounds[0] > bounds[2]) || (bounds[1] > bounds[2])) {
			break;
		}

		ran.push_back(vec[bounds[0]]);

		if (reverse) {
			--bounds[0];
		} else { ++bounds[0]; }
	}

	CLEVER_RETURN_ARRAY(CLEVER_ARRAY_TYPE->allocData(&ran));
}

// Array Array::each(function)
// Calls function once for each element in the array, passing the element as the only parameter to function
// The return values from function are returned in the same order as the array
CLEVER_METHOD(ArrayType::each)
{
	if (!clever_check_args("f")) {
		return;
	}

	Function* func = static_cast<Function*>(args[0]->getObj());
	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();
	ValueVector results;

	for (size_t i = 0; i < vec.size(); i++) {
		ValueVector tmp_args;

		tmp_args.push_back(vec[i]);

		results.push_back(const_cast<VM*>(vm)->runFunction(func, &tmp_args));
	}

	CLEVER_RETURN_ARRAY(CLEVER_ARRAY_TYPE->allocData(&results));

	for (size_t i = 0, j = results.size(); i < j; ++i) {
		results[i]->delRef();
	}
}

// mixed Array.erase(int position)
// Removes from this array the element at position, returning the value
CLEVER_METHOD(ArrayType::erase)
{
	if (!clever_check_args("i")) {
		return;
	}

	size_t length;
	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

	if (!(length = vec.size())) {
		result->setNull();
		return;
	}

	if ((args[0]->getInt()) >= 0 &&
		(size_t(args[0]->getInt()) < length)) {

		result->copy(vec[args[0]->getInt()]);

		vec[args[0]->getInt()]->delRef();

		vec.erase(vec.begin()+args[0]->getInt());
	}
}

// Type initialization
CLEVER_TYPE_INIT(ArrayType::init)
{
	addMethod(new Function("append",  (MethodPtr) &ArrayType::append));
	addMethod(new Function("size",    (MethodPtr) &ArrayType::size));
	addMethod(new Function("at",      (MethodPtr) &ArrayType::at));
	addMethod(new Function("reserve", (MethodPtr) &ArrayType::reserve));
	addMethod(new Function("reverse", (MethodPtr) &ArrayType::reverse));
	addMethod(new Function("each",    (MethodPtr) &ArrayType::each));
	addMethod(new Function("shift",   (MethodPtr) &ArrayType::shift));
	addMethod(new Function("pop",     (MethodPtr) &ArrayType::pop));
	addMethod(new Function("range",   (MethodPtr) &ArrayType::range));
	addMethod(new Function("erase",	  (MethodPtr) &ArrayType::erase));
}

} // clever
<commit_msg>fix memory leak on pop/shift<commit_after>/**
 * Clever programming language
 * Copyright (c) Clever Team
 *
 * This file is distributed under the MIT license. See LICENSE for details.
 */

#include "core/value.h"
#include "core/vm.h"
#include "types/array.h"
#include "types/function.h"

namespace clever {

void* ArrayType::allocData(CLEVER_TYPE_CTOR_ARGS) const
{
	ArrayObject* arr = new ArrayObject();
	ValueVector& vec = arr->getData();

	for (size_t i = 0, j = args->size(); i < j; ++i) {
		vec.push_back(args->at(i)->clone());
	}

	return arr;
}

void ArrayType::deallocData(void* data)
{
	ArrayObject* arr = static_cast<ArrayObject*>(data);
	ValueVector& vec = arr->getData();

	for (size_t i = 0, j = vec.size(); i < j; ++i) {
		vec[i]->delRef();
	}

	delete arr;
}

void ArrayType::dump(const void* value, std::ostream& out) const
{
	Value::DataValue* data = static_cast<Value::DataValue*>(const_cast<void*>(value));
	ValueVector& vec = (static_cast<ArrayObject*>(data->obj->getObj()))->getData();

	out << "[";

	for (size_t i = 0, j = vec.size(); i < j; ++i) {
		vec.at(i)->dump(out);
		if (i < j-1) {
			out << ", ";
		}
	}

	out << "]";
}

// void Array::append([arg, ... ])
CLEVER_METHOD(ArrayType::append)
{
	if (args.size()) {
		ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

		for (size_t i = 0, j = args.size(); i < j; ++i) {
			vec.push_back(args[i]->clone());
		}
	}
	result->setNull();
}

// int Array::size()
CLEVER_METHOD(ArrayType::size)
{
	if (!clever_check_no_args()) {
		return;
	}

	result->setInt((CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData().size());
}

// mixed Array::at(int position)
CLEVER_METHOD(ArrayType::at)
{
	if (!clever_check_args("i")) {
		return;
	}

	ValueVector& arr = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

	if (args[0]->getInt() < 0
		|| arr.size() <= size_t(args[0]->getInt())) {
		result->setNull();
		return;
	}

	result->copy(arr.at(args[0]->getInt()));
}

// void Array::reserve(int size)
CLEVER_METHOD(ArrayType::reserve)
{
	if (!clever_check_args("i")) {
		return;
	}

	ArrayObject* arr = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS());

	result->setNull();

	if (args[0]->getInt() < 0) {
		return;
	}

	arr->getData().reserve(args[0]->getInt());
}

// Array Array::reverse()
// Returns the reverse of this array
CLEVER_METHOD(ArrayType::reverse)
{
	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();
	ValueVector::reverse_iterator it(vec.rbegin()), end(vec.rend());
	ValueVector rev;

	while (it != end){
		rev.push_back((*it));
		it++;
	}

	CLEVER_RETURN_ARRAY(CLEVER_ARRAY_TYPE->allocData(&rev));
}

// mixed Array.shift()
// Removes and returns the first element of the array
CLEVER_METHOD(ArrayType::shift)
{
	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

	if (!vec.size()) {
		result->setNull();
		return;
	}

	result->copy(
		vec[0]
	);
	vec[0]->delRef();

	ValueVector(vec.begin()+1, vec.end()).swap(vec);
}

// mixed Array.pop()
// Removes and returns the last element of the array
CLEVER_METHOD(ArrayType::pop)
{
	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

	if (!vec.size()) {
		result->setNull();
		return;
	}

	result->copy(
		vec[vec.size()-1]
	);
	vec[vec.size()-1]->delRef();

	ValueVector(vec.begin(), vec.end()-1).swap(vec);
}

// Array Array.range(int start, int end)
// Returns a range as a new array
CLEVER_METHOD(ArrayType::range)
{
	if (!clever_check_args("ii")) {
		return;
	}

	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

	if (!vec.size()){
		result->setNull();
		return;
	}

	long bounds[3] = {CLEVER_ARG_INT(0), CLEVER_ARG_INT(1), (long) vec.size()};
	ValueVector ran;

	bool reverse = (bounds[0] > bounds[1]);
	while((reverse ? (bounds[1] <= bounds[0]) : (bounds[0] <= bounds[1]))) {
		if ((bounds[0] < 0 || bounds[1] < 0) ||
			(bounds[0] > bounds[2]) || (bounds[1] > bounds[2])) {
			break;
		}

		ran.push_back(vec[bounds[0]]);

		if (reverse) {
			--bounds[0];
		} else { ++bounds[0]; }
	}

	CLEVER_RETURN_ARRAY(CLEVER_ARRAY_TYPE->allocData(&ran));
}

// Array Array::each(function)
// Calls function once for each element in the array, passing the element as the only parameter to function
// The return values from function are returned in the same order as the array
CLEVER_METHOD(ArrayType::each)
{
	if (!clever_check_args("f")) {
		return;
	}

	Function* func = static_cast<Function*>(args[0]->getObj());
	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();
	ValueVector results;

	for (size_t i = 0; i < vec.size(); i++) {
		ValueVector tmp_args;

		tmp_args.push_back(vec[i]);

		results.push_back(const_cast<VM*>(vm)->runFunction(func, &tmp_args));
	}

	CLEVER_RETURN_ARRAY(CLEVER_ARRAY_TYPE->allocData(&results));

	for (size_t i = 0, j = results.size(); i < j; ++i) {
		results[i]->delRef();
	}
}

// mixed Array.erase(int position)
// Removes from this array the element at position, returning the value
CLEVER_METHOD(ArrayType::erase)
{
	if (!clever_check_args("i")) {
		return;
	}

	size_t length;
	ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();

	if (!(length = vec.size())) {
		result->setNull();
		return;
	}

	if ((args[0]->getInt()) >= 0 &&
		(size_t(args[0]->getInt()) < length)) {

		result->copy(vec[args[0]->getInt()]);

		vec[args[0]->getInt()]->delRef();

		vec.erase(vec.begin()+args[0]->getInt());
	}
}

// Type initialization
CLEVER_TYPE_INIT(ArrayType::init)
{
	addMethod(new Function("append",  (MethodPtr) &ArrayType::append));
	addMethod(new Function("size",    (MethodPtr) &ArrayType::size));
	addMethod(new Function("at",      (MethodPtr) &ArrayType::at));
	addMethod(new Function("reserve", (MethodPtr) &ArrayType::reserve));
	addMethod(new Function("reverse", (MethodPtr) &ArrayType::reverse));
	addMethod(new Function("each",    (MethodPtr) &ArrayType::each));
	addMethod(new Function("shift",   (MethodPtr) &ArrayType::shift));
	addMethod(new Function("pop",     (MethodPtr) &ArrayType::pop));
	addMethod(new Function("range",   (MethodPtr) &ArrayType::range));
	addMethod(new Function("erase",	  (MethodPtr) &ArrayType::erase));
}

} // clever
<|endoftext|>


<commit_before>/* This software is released under the BSD License.
 |
 | Copyright (c) 2014-2015, Kevin P. Barry [ta0kira@gmail.com]
 | 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.
 |
 | - Neither the name  of the  Locking Container Project  nor  the names  of its
 |   contributors may be  used to endorse or promote products  derived from this
 |   software without specific prior written permission.
 |
 | THIS SOFTWARE IS  PROVIDED BY THE COPYRIGHT HOLDERS AND  CONTRIBUTORS "AS IS"
 | AND ANY  EXPRESS OR IMPLIED  WARRANTIES,  INCLUDING, BUT  NOT LIMITED TO, THE
 | IMPLIED WARRANTIES OF  MERCHANTABILITY  AND FITNESS FOR A  PARTICULAR PURPOSE
 | ARE DISCLAIMED.  IN  NO EVENT SHALL  THE COPYRIGHT  OWNER  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.
 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

/* This file provides a template class that protects access to an object with
 * locks of various types. Conventional mutex-protection methods are susceptible
 * to bugs caused by forgetting (or neglecting) to lock/unlock the mutex. This
 * class eliminates the need to remember because the only access to the
 * protected object is via a proxy object that holds the lock until the
 * reference count of the proxy reaches 0 (like a shared pointer).
 *
 * This header contains one main class 'locking_container <class, class>', where
 * the first argument is the type of object being protected, and the second is
 * the type of lock to be used. A few lock choices are provided. See
 * locks.hpp for more information.
 *
 * Each lock type has a corresponding 'lock_auth' specialization for use with
 * deadlock prevention. All of them have (somewhat) identical behavior to their
 * corresponding lock types, as far as how many read and write locks can be held
 * at a given time. See lock-auth.hpp for more information.
 *
 * If you want both deadlock prevention and the ability for threads to hold
 * a write lock plus one or more other locks at the same time, you can create a
 * 'null_container' for use by all threads when obtaining locks for any object.
 * The behavior will be transparent until a thread requests a "multi-lock" by
 * attempting to obtain a write lock on the 'null_container'. This will block
 * all future locks on the objects, allowing the thread in question to lock as
 * many objects as it needs to. To access this behavior, use 'get_write_multi'
 * and 'get_read_multi' instead of 'get_write_auth' and 'get_read_auth', passing
 * the 'null_container' as the first argument.
 *
 * Other notes:
 *
 *   - You must enable C++11 (or higher) when using this header.
 *
 *   - You might need to link your executable with libpthread after compiling.
 *
 *   - To copy a container, you must first get a proxy from it, then construct
 *     the copy with the corresponding object. To assign one container to
 *     another, you must first get proxies to both objects. (The
 *     'try_copy_container' global functions manage the latter automatically.)
 *     Because of this, you cannot copy a 'const' container because there is no
 *     'const' way to get a proxy.
 */

/*! \file locking-container.hpp
 *  \brief C++ container for data protection in multithreaded programs.
 *  \author Kevin P. Barry
 */

#ifndef locking_container_hpp
#define locking_container_hpp

#include <assert.h>

#include "locks.hpp"
#include "lock-auth.hpp"
#include "object-proxy.hpp"
#include "null-container.hpp"

/*! \class locking_container_base
    \brief Base class for \ref locking_container.
 */

template <class Type>
class locking_container_base {
public:
  typedef Type                      type;
  typedef object_proxy <type>       write_proxy;
  typedef object_proxy <const type> read_proxy;
  typedef lock_auth_base::auth_type auth_type;

  /** @name Accessor Functions
  *
  */
  //@{

  /*! \brief Retrieve a writable proxy to the contained object.
   *
   * @see object_proxy
   * \attention Always check that the returned object contains a valid
   * pointer with object_proxy::operator!. The reference will always be
   * invalid if a lock hasn't been obtained.
   * \attention The returned object should only be passed by value, and it
   * should only be passed within the same thread that
   * \ref locking_container::get_write was called from. This is because the
   * proxy object uses reference counting that isn't reentrant.
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline write_proxy get_write(bool block = true) {
    return this->get_write_auth(NULL, block);
  }

  /*! \brief Retrieve a read-only proxy to the contained object.
   *
   * @see get_write
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline read_proxy get_read(bool block = true) {
    return this->get_read_auth(NULL, block);
  }

  /*! \brief Retrieve a writable proxy to the contained object using deadlock
   *  prevention.
   *
   * @see get_write
   * \param authorization Authorization object to prevent deadlocks.
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline write_proxy get_write_auth(auth_type &authorization, bool block = true) {
    return this->get_write_auth(authorization.get(), block);
  }

  /*! \brief Retrieve a read-only proxy to the contained object using deadlock
   *  prevention.
   *
   * @see get_write
   * \param authorization Authorization object to prevent deadlocks.
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline read_proxy get_read_auth(auth_type &authorization, bool block = true) {
    return this->get_read_auth(authorization.get(), block);
  }

  virtual write_proxy get_write_auth(lock_auth_base *authorization, bool block = true) = 0;
  virtual read_proxy  get_read_auth(lock_auth_base *authorization, bool block = true)  = 0;

  /*! \brief Retrieve a writable proxy to the contained object using deadlock
   *  prevention and multiple locking functionality.
   *
   * @see get_write_auth
   * \param multi_lock Multi-lock object to manage multiple locks.
   * \param authorization Authorization object to prevent deadlocks.
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline write_proxy get_write_multi(null_container_base &multi_lock,
    lock_auth_base *authorization, bool block = true) {
    return this->get_write_multi(multi_lock.get_lock_object(), authorization, block);
  }

  /*! \brief Retrieve a read-only proxy to the contained object using deadlock
   *  prevention and multiple locking functionality.
   *
   * @see get_write_auth
   * \param multi_lock Multi-lock object to manage multiple locks.
   * \param authorization Authorization object to prevent deadlocks.
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline read_proxy get_read_multi(null_container_base &multi_lock,
    lock_auth_base *authorization, bool block = true) {
    return this->get_read_multi(multi_lock.get_lock_object(), authorization, block);
  }

  /*! @see get_write_multi.*/
  inline write_proxy get_write_multi(null_container_base &multi_lock,
    auth_type &authorization, bool block = true) {
    return this->get_write_multi(multi_lock, authorization.get(), block);
  }

  /*! @see get_read_multi.*/
  inline read_proxy get_read_multi(null_container_base &multi_lock,
    auth_type &authorization, bool block = true) {
    return this->get_read_multi(multi_lock, authorization.get(), block);
  }

  //@}

  virtual auth_type get_new_auth() const {
    return auth_type();
  }

  virtual inline ~locking_container_base() {}

protected:
  virtual write_proxy get_write_multi(lock_base */*multi_lock*/,
    lock_auth_base */*authorization*/, bool /*block*/) {
    return write_proxy();
  }

  virtual read_proxy get_read_multi(lock_base */*multi_lock*/,
    lock_auth_base */*authorization*/, bool /*block*/) {
    return read_proxy();
  }
};

/*! \class locking_container
 *  \brief C++ container class with automatic unlocking, concurrent reads, and
 *  deadlock prevention.
 *
 * Each instance of this class contains a lock and an encapsulated object of
 * the type denoted by the template parameter. The
 * \ref locking_container::get_write and \ref locking_container::get_read
 * functions provide a proxy object (see \ref object_proxy) that automatically
 * locks and unlocks the lock to simplify code that accesses the encapsulated
 * object.
 */

template <class Type, class Lock = rw_lock>
class locking_container : public locking_container_base <Type> {
private:
  typedef lock_auth <Lock> auth_base_type;

public:
  typedef locking_container_base <Type> base;
  using typename base::type;
  using typename base::write_proxy;
  using typename base::read_proxy;
  using typename base::auth_type;
  //NOTE: this is needed so that the 'lock_auth_base' variants are pulled in
  using base::get_write_auth;
  using base::get_read_auth;
  using base::get_write_multi;
  using base::get_read_multi;

  /*! \brief Constructor.
   *
   * \param Object Object to copy as contained object.
   */
  explicit locking_container(const type &Object = type()) : contained(Object) {}

private:
  locking_container(const locking_container&);
  locking_container &operator = (const locking_container&);

public:
  /** @name Accessor Functions
  *
  */
  //@{

  /*! @see locking_container_base::get_write_auth.*/
  inline write_proxy get_write_auth(lock_auth_base *authorization, bool block = true) {
    return this->get_write_multi(NULL, authorization, block);
  }

  /*! @see locking_container_base::get_read_auth.*/
  inline read_proxy get_read_auth(lock_auth_base *authorization, bool block = true) {
    return this->get_read_multi(NULL, authorization, block);
  }

  //@}

  /** @name New Authorization Objects
  *
  */
  //@{

  /*! Get a new authorization object.*/
  virtual auth_type get_new_auth() const {
    return locking_container::new_auth();
  }

  /*! Get a new authorization object.*/
  static auth_type new_auth() {
    return auth_type(new auth_base_type);
  }

  //@}

private:
  inline write_proxy get_write_multi(lock_base *multi_lock, lock_auth_base *authorization, bool block = true) {
    //NOTE: no read/write choice is given here!
    return write_proxy(&contained, &locks, authorization, block, multi_lock);
  }

  inline read_proxy get_read_multi(lock_base *multi_lock, lock_auth_base *authorization,
    bool block = true) {
    return read_proxy(&contained, &locks, authorization, true, block, multi_lock);
  }

  type contained;
  Lock locks;
};

/*! \brief Attempt to copy one container's contents into another.
 *
 * @note This will attempt to obtain locks for both containers, and will fail if
 * either lock operation fails.
 *
 * \param left container being assigned to
 * \param right container being assigned
 * \param authorization authorization object
 * \param block whether or not to block when locking the containers
 * \return success or failure, based entirely on locking success
 */
template <class Type1, class Type2>
inline bool try_copy_container(locking_container_base <Type1> &left,
  locking_container_base <Type2> &right, lock_auth_base *authorization,
  bool block = true) {
  typename locking_container_base <Type1> ::write_proxy write =
    left.get_write_auth(authorization, block);
  if (!write) return false;

  typename locking_container_base <Type2> ::read_proxy read =
    right.get_read_auth(authorization, block);
  if (!read) return false;

  *write = *read;
  return true;
}

/*! Attempt to copy one container's contents into another.*/
template <class Type1, class Type2>
inline bool try_copy_container(locking_container_base <Type1> &left,
  locking_container_base <Type2> &right, bool block = true) {
  return try_copy_container(left, right, NULL, block);
}

/*! Attempt to copy one container's contents into another.*/
template <class Type1, class Type2>
inline bool try_copy_container(locking_container_base <Type1> &left,
  locking_container_base <Type2> &right, lock_auth_base::auth_type &authorization,
  bool block = true) {
  return try_copy_container(left, right, authorization.get(), block);
}

/*! \brief Attempt to copy one container's contents into another.
 *
 * @note This will attempt to obtain locks for both containers using the
 * \ref null_container_base object, and will fail if either lock operation
 * fails.
 * \attention This will only work if no other thread holds a lock on either of
 * the containers.
 * \attention If Trymulti_lock is false, his will fail if the caller doesn't have a
 * write lock on the \ref null_container_base passed.
 *
 * \param left container being assigned to
 * \param right container being assigned
 * \param multi_lock multi-lock tracking object
 * \param authorization authorization object
 * \param block whether or not to block when locking the containers
 * \param Trymulti_lock whether or not to attempt a write lock on multi_lock
 * \return success or failure, based entirely on locking success
 */
template <class Type1, class Type2>
inline bool try_copy_container(locking_container_base <Type1> &left,
  locking_container_base <Type2> &right, null_container_base &multi_lock,
  lock_auth_base *authorization, bool block = true, bool Trymulti_lock = true) {
  null_container::write_proxy multi;
  if (Trymulti_lock && !(multi = multi_lock.get_write_auth(authorization, block))) return false;

  typename locking_container_base <Type1> ::write_proxy write =
    left.get_write_multi(multi_lock, authorization, block);
  if (!write) return false;

  typename locking_container_base <Type2> ::read_proxy read =
    right.get_read_multi(multi_lock, authorization, block);
  if (!read) return false;

  if (Trymulti_lock) multi.clear();

  *write = *read;
  return true;
}

/*! Attempt to copy one container's contents into another.*/
template <class Type1, class Type2>
inline bool try_copy_container(locking_container_base <Type1> &left,
  locking_container_base <Type2> &right, null_container_base &multi_lock,
  lock_auth_base::auth_type &authorization, bool block = true, bool Trymulti_lock = true) {
  return try_copy_container(left, right, multi_lock, authorization.get(), block, Trymulti_lock);
}

#endif //locking_container_hpp
<commit_msg>silly update to whitespace around commented-out argument names<commit_after>/* This software is released under the BSD License.
 |
 | Copyright (c) 2014-2015, Kevin P. Barry [ta0kira@gmail.com]
 | 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.
 |
 | - Neither the name  of the  Locking Container Project  nor  the names  of its
 |   contributors may be  used to endorse or promote products  derived from this
 |   software without specific prior written permission.
 |
 | THIS SOFTWARE IS  PROVIDED BY THE COPYRIGHT HOLDERS AND  CONTRIBUTORS "AS IS"
 | AND ANY  EXPRESS OR IMPLIED  WARRANTIES,  INCLUDING, BUT  NOT LIMITED TO, THE
 | IMPLIED WARRANTIES OF  MERCHANTABILITY  AND FITNESS FOR A  PARTICULAR PURPOSE
 | ARE DISCLAIMED.  IN  NO EVENT SHALL  THE COPYRIGHT  OWNER  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.
 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

/* This file provides a template class that protects access to an object with
 * locks of various types. Conventional mutex-protection methods are susceptible
 * to bugs caused by forgetting (or neglecting) to lock/unlock the mutex. This
 * class eliminates the need to remember because the only access to the
 * protected object is via a proxy object that holds the lock until the
 * reference count of the proxy reaches 0 (like a shared pointer).
 *
 * This header contains one main class 'locking_container <class, class>', where
 * the first argument is the type of object being protected, and the second is
 * the type of lock to be used. A few lock choices are provided. See
 * locks.hpp for more information.
 *
 * Each lock type has a corresponding 'lock_auth' specialization for use with
 * deadlock prevention. All of them have (somewhat) identical behavior to their
 * corresponding lock types, as far as how many read and write locks can be held
 * at a given time. See lock-auth.hpp for more information.
 *
 * If you want both deadlock prevention and the ability for threads to hold
 * a write lock plus one or more other locks at the same time, you can create a
 * 'null_container' for use by all threads when obtaining locks for any object.
 * The behavior will be transparent until a thread requests a "multi-lock" by
 * attempting to obtain a write lock on the 'null_container'. This will block
 * all future locks on the objects, allowing the thread in question to lock as
 * many objects as it needs to. To access this behavior, use 'get_write_multi'
 * and 'get_read_multi' instead of 'get_write_auth' and 'get_read_auth', passing
 * the 'null_container' as the first argument.
 *
 * Other notes:
 *
 *   - You must enable C++11 (or higher) when using this header.
 *
 *   - You might need to link your executable with libpthread after compiling.
 *
 *   - To copy a container, you must first get a proxy from it, then construct
 *     the copy with the corresponding object. To assign one container to
 *     another, you must first get proxies to both objects. (The
 *     'try_copy_container' global functions manage the latter automatically.)
 *     Because of this, you cannot copy a 'const' container because there is no
 *     'const' way to get a proxy.
 */

/*! \file locking-container.hpp
 *  \brief C++ container for data protection in multithreaded programs.
 *  \author Kevin P. Barry
 */

#ifndef locking_container_hpp
#define locking_container_hpp

#include <assert.h>

#include "locks.hpp"
#include "lock-auth.hpp"
#include "object-proxy.hpp"
#include "null-container.hpp"

/*! \class locking_container_base
    \brief Base class for \ref locking_container.
 */

template <class Type>
class locking_container_base {
public:
  typedef Type                      type;
  typedef object_proxy <type>       write_proxy;
  typedef object_proxy <const type> read_proxy;
  typedef lock_auth_base::auth_type auth_type;

  /** @name Accessor Functions
  *
  */
  //@{

  /*! \brief Retrieve a writable proxy to the contained object.
   *
   * @see object_proxy
   * \attention Always check that the returned object contains a valid
   * pointer with object_proxy::operator!. The reference will always be
   * invalid if a lock hasn't been obtained.
   * \attention The returned object should only be passed by value, and it
   * should only be passed within the same thread that
   * \ref locking_container::get_write was called from. This is because the
   * proxy object uses reference counting that isn't reentrant.
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline write_proxy get_write(bool block = true) {
    return this->get_write_auth(NULL, block);
  }

  /*! \brief Retrieve a read-only proxy to the contained object.
   *
   * @see get_write
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline read_proxy get_read(bool block = true) {
    return this->get_read_auth(NULL, block);
  }

  /*! \brief Retrieve a writable proxy to the contained object using deadlock
   *  prevention.
   *
   * @see get_write
   * \param authorization Authorization object to prevent deadlocks.
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline write_proxy get_write_auth(auth_type &authorization, bool block = true) {
    return this->get_write_auth(authorization.get(), block);
  }

  /*! \brief Retrieve a read-only proxy to the contained object using deadlock
   *  prevention.
   *
   * @see get_write
   * \param authorization Authorization object to prevent deadlocks.
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline read_proxy get_read_auth(auth_type &authorization, bool block = true) {
    return this->get_read_auth(authorization.get(), block);
  }

  virtual write_proxy get_write_auth(lock_auth_base *authorization, bool block = true) = 0;
  virtual read_proxy  get_read_auth(lock_auth_base *authorization, bool block = true)  = 0;

  /*! \brief Retrieve a writable proxy to the contained object using deadlock
   *  prevention and multiple locking functionality.
   *
   * @see get_write_auth
   * \param multi_lock Multi-lock object to manage multiple locks.
   * \param authorization Authorization object to prevent deadlocks.
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline write_proxy get_write_multi(null_container_base &multi_lock,
    lock_auth_base *authorization, bool block = true) {
    return this->get_write_multi(multi_lock.get_lock_object(), authorization, block);
  }

  /*! \brief Retrieve a read-only proxy to the contained object using deadlock
   *  prevention and multiple locking functionality.
   *
   * @see get_write_auth
   * \param multi_lock Multi-lock object to manage multiple locks.
   * \param authorization Authorization object to prevent deadlocks.
   * \param block Should the call block for a lock?
   *
   * \return proxy object
   */
  inline read_proxy get_read_multi(null_container_base &multi_lock,
    lock_auth_base *authorization, bool block = true) {
    return this->get_read_multi(multi_lock.get_lock_object(), authorization, block);
  }

  /*! @see get_write_multi.*/
  inline write_proxy get_write_multi(null_container_base &multi_lock,
    auth_type &authorization, bool block = true) {
    return this->get_write_multi(multi_lock, authorization.get(), block);
  }

  /*! @see get_read_multi.*/
  inline read_proxy get_read_multi(null_container_base &multi_lock,
    auth_type &authorization, bool block = true) {
    return this->get_read_multi(multi_lock, authorization.get(), block);
  }

  //@}

  virtual auth_type get_new_auth() const {
    return auth_type();
  }

  virtual inline ~locking_container_base() {}

protected:
  virtual write_proxy get_write_multi(lock_base* /*multi_lock*/,
    lock_auth_base* /*authorization*/, bool /*block*/) {
    return write_proxy();
  }

  virtual read_proxy get_read_multi(lock_base* /*multi_lock*/,
    lock_auth_base* /*authorization*/, bool /*block*/) {
    return read_proxy();
  }
};

/*! \class locking_container
 *  \brief C++ container class with automatic unlocking, concurrent reads, and
 *  deadlock prevention.
 *
 * Each instance of this class contains a lock and an encapsulated object of
 * the type denoted by the template parameter. The
 * \ref locking_container::get_write and \ref locking_container::get_read
 * functions provide a proxy object (see \ref object_proxy) that automatically
 * locks and unlocks the lock to simplify code that accesses the encapsulated
 * object.
 */

template <class Type, class Lock = rw_lock>
class locking_container : public locking_container_base <Type> {
private:
  typedef lock_auth <Lock> auth_base_type;

public:
  typedef locking_container_base <Type> base;
  using typename base::type;
  using typename base::write_proxy;
  using typename base::read_proxy;
  using typename base::auth_type;
  //NOTE: this is needed so that the 'lock_auth_base' variants are pulled in
  using base::get_write_auth;
  using base::get_read_auth;
  using base::get_write_multi;
  using base::get_read_multi;

  /*! \brief Constructor.
   *
   * \param Object Object to copy as contained object.
   */
  explicit locking_container(const type &Object = type()) : contained(Object) {}

private:
  locking_container(const locking_container&);
  locking_container &operator = (const locking_container&);

public:
  /** @name Accessor Functions
  *
  */
  //@{

  /*! @see locking_container_base::get_write_auth.*/
  inline write_proxy get_write_auth(lock_auth_base *authorization, bool block = true) {
    return this->get_write_multi(NULL, authorization, block);
  }

  /*! @see locking_container_base::get_read_auth.*/
  inline read_proxy get_read_auth(lock_auth_base *authorization, bool block = true) {
    return this->get_read_multi(NULL, authorization, block);
  }

  //@}

  /** @name New Authorization Objects
  *
  */
  //@{

  /*! Get a new authorization object.*/
  virtual auth_type get_new_auth() const {
    return locking_container::new_auth();
  }

  /*! Get a new authorization object.*/
  static auth_type new_auth() {
    return auth_type(new auth_base_type);
  }

  //@}

private:
  inline write_proxy get_write_multi(lock_base *multi_lock, lock_auth_base *authorization, bool block = true) {
    //NOTE: no read/write choice is given here!
    return write_proxy(&contained, &locks, authorization, block, multi_lock);
  }

  inline read_proxy get_read_multi(lock_base *multi_lock, lock_auth_base *authorization,
    bool block = true) {
    return read_proxy(&contained, &locks, authorization, true, block, multi_lock);
  }

  type contained;
  Lock locks;
};

/*! \brief Attempt to copy one container's contents into another.
 *
 * @note This will attempt to obtain locks for both containers, and will fail if
 * either lock operation fails.
 *
 * \param left container being assigned to
 * \param right container being assigned
 * \param authorization authorization object
 * \param block whether or not to block when locking the containers
 * \return success or failure, based entirely on locking success
 */
template <class Type1, class Type2>
inline bool try_copy_container(locking_container_base <Type1> &left,
  locking_container_base <Type2> &right, lock_auth_base *authorization,
  bool block = true) {
  typename locking_container_base <Type1> ::write_proxy write =
    left.get_write_auth(authorization, block);
  if (!write) return false;

  typename locking_container_base <Type2> ::read_proxy read =
    right.get_read_auth(authorization, block);
  if (!read) return false;

  *write = *read;
  return true;
}

/*! Attempt to copy one container's contents into another.*/
template <class Type1, class Type2>
inline bool try_copy_container(locking_container_base <Type1> &left,
  locking_container_base <Type2> &right, bool block = true) {
  return try_copy_container(left, right, NULL, block);
}

/*! Attempt to copy one container's contents into another.*/
template <class Type1, class Type2>
inline bool try_copy_container(locking_container_base <Type1> &left,
  locking_container_base <Type2> &right, lock_auth_base::auth_type &authorization,
  bool block = true) {
  return try_copy_container(left, right, authorization.get(), block);
}

/*! \brief Attempt to copy one container's contents into another.
 *
 * @note This will attempt to obtain locks for both containers using the
 * \ref null_container_base object, and will fail if either lock operation
 * fails.
 * \attention This will only work if no other thread holds a lock on either of
 * the containers.
 * \attention If Trymulti_lock is false, his will fail if the caller doesn't have a
 * write lock on the \ref null_container_base passed.
 *
 * \param left container being assigned to
 * \param right container being assigned
 * \param multi_lock multi-lock tracking object
 * \param authorization authorization object
 * \param block whether or not to block when locking the containers
 * \param Trymulti_lock whether or not to attempt a write lock on multi_lock
 * \return success or failure, based entirely on locking success
 */
template <class Type1, class Type2>
inline bool try_copy_container(locking_container_base <Type1> &left,
  locking_container_base <Type2> &right, null_container_base &multi_lock,
  lock_auth_base *authorization, bool block = true, bool Trymulti_lock = true) {
  null_container::write_proxy multi;
  if (Trymulti_lock && !(multi = multi_lock.get_write_auth(authorization, block))) return false;

  typename locking_container_base <Type1> ::write_proxy write =
    left.get_write_multi(multi_lock, authorization, block);
  if (!write) return false;

  typename locking_container_base <Type2> ::read_proxy read =
    right.get_read_multi(multi_lock, authorization, block);
  if (!read) return false;

  if (Trymulti_lock) multi.clear();

  *write = *read;
  return true;
}

/*! Attempt to copy one container's contents into another.*/
template <class Type1, class Type2>
inline bool try_copy_container(locking_container_base <Type1> &left,
  locking_container_base <Type2> &right, null_container_base &multi_lock,
  lock_auth_base::auth_type &authorization, bool block = true, bool Trymulti_lock = true) {
  return try_copy_container(left, right, multi_lock, authorization.get(), block, Trymulti_lock);
}

#endif //locking_container_hpp
<|endoftext|>