<commit_before>/*************************************************************************
 *
 *  $RCSfile: transactionmanager.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2003-07-16 17:40:15 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONMANAGER_HXX_
#include <threadhelp/transactionmanager.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported declarations
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  definitions
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short      standard ctor
    @descr      Initialize instance with right start values for correct working.

    @seealso    -

    @param      -
    @return     -

    @onerror    -
*//*-*************************************************************************************************************/
TransactionManager::TransactionManager()
    : m_eWorkingMode      ( E_INIT )
    , m_nTransactionCount ( 0      )
{
    m_aBarrier.open();
}

/*-****************************************************************************************************//**
    @interface  ITransactionManager
    @short      set new working mode
    @descr      These implementation knows for states of working: E_INIT, E_WORK, E_CLOSING, E_CLOSE
                You can step during this ones only from the left to the right side and start at left side again!
                (This is neccessary e.g. for refcounted objects!)
                This call will block till all current existing transactions was finished.
                Follow results occure:
                    E_INIT        :  All requests on this implementation are refused.
                                        It's your decision to react in a right way.

                    E_WORK        :  The object can work now. The full functionality is available.

                    E_BEFORECLOSE :  The object start the closing mechanism ... but sometimes
                                        e.g. the dispose() method need to call some private methods.
                                        These some special methods should use E_SOFTEXCEPTIONS or ignore
                                        E_INCLOSE as returned reason for E_NOEXCEPTIONS to detect this special case!

                    E_CLOSE       :  Object is already dead! All further requests will be refused.
                                        It's your decision to react in a right way.

    @seealso    -

    @param      "eMode", is the new mode - but we don't accept setting mode in wrong order!
    @return     -

    @onerror    We do nothing.
*//*-*****************************************************************************************************/
void  TransactionManager::setWorkingMode( EWorkingMode eMode )
{
    // Safe member access.
    ::osl::ClearableMutexGuard  aAccessGuard( m_aAccessLock );
    sal_Bool                    bWaitFor    = sal_False      ;
    // Change working mode first!
    if  (
            ( m_eWorkingMode == E_INIT        && eMode == E_WORK        ) ||
            ( m_eWorkingMode == E_WORK        && eMode == E_BEFORECLOSE ) ||
            ( m_eWorkingMode == E_BEFORECLOSE && eMode == E_CLOSE       ) ||
            ( m_eWorkingMode == E_CLOSE       && eMode == E_INIT        )
        )
    {
        m_eWorkingMode = eMode;
        if( m_eWorkingMode == E_BEFORECLOSE || m_eWorkingMode == E_CLOSE )
        {
            bWaitFor = sal_True;
        }
    }

    // Wait for current existing transactions then!
    // (Only neccessary for changing to E_BEFORECLOSE or E_CLOSE! ...
    // otherwise; if you wait at setting E_WORK another thrad could finish a acquire-call during our unlock() and wait() call
    // ... and we will wait forever here!!!)
    // Don't forget to release access mutex before.
    aAccessGuard.clear();
    if( bWaitFor == sal_True )
    {
        m_aBarrier.wait();
    }
}

/*-****************************************************************************************************//**
    @interface  ITransactionManager
    @short      get current working mode
    @descr      If you stand in your close() or init() method ... but don't know
                if you called more then ones(!) ... you can use this function to get
                right information.
                e.g:    You have a method init() which is used to change working mode from
                        E_INIT to E_WORK and should be used to initialize some member too ...
                        What should you do:

                            void init( sal_Int32 nValue )
                            {
                                // Reject this call if our transaction manager say: "Object already initialized!"
                                // Otherwise initialize your member.
                                if( m_aTransactionManager.getWorkingMode() == E_INIT )
                                {
                                    // Object is uninitialized ...
                                    // Make member access threadsafe!
                                    ResetableGuard aGuard( m_aMutex );

                                    // Check working mode again .. because anozther instance could be faster.
                                    // (It's possible to set this guard at first of this method too!)
                                    if( m_aTransactionManager.getWorkingMode() == E_INIT )
                                    {
                                        m_aMember = nValue;

                                        // Object is initialized now ... set working mode to E_WORK!
                                        m_aTransactionManager.setWorkingMode( E_WORK );
                                    }
                                }
                            }

    @seealso    method setWorkingMode()

    @param      -
    @return     Current set mode.

    @onerror    No error should occure.
*//*-*****************************************************************************************************/
EWorkingMode TransactionManager::getWorkingMode() const
{
    // Synchronize access to internal member!
    ::osl::MutexGuard aAccessLock( m_aAccessLock );
    return m_eWorkingMode;
}

/*-****************************************************************************************************//**
    @interface  ITransactionManager
    @short      start new transaction
    @descr      A guard should use this method to start a new transaction. He should looks for rejected
                calls to by using parameter eMode and eReason.
                If call was not rejected your transaction will be non breakable during releasing your transaction
                guard! BUT ... your code isn't threadsafe then! It's a transaction manager only ....

    @seealso    method unregisterTransaction()

    @param      "eMode"     ,used to enable/disable throwing exceptions automaticly for rejected calls
    @param      "eReason"   ,reason for rejected calls if eMode=E_NOEXCEPTIONS
    @return     -

    @onerror    -
*//*-*****************************************************************************************************/
void  TransactionManager::registerTransaction( EExceptionMode eMode, ERejectReason& eReason ) throw( css::uno::RuntimeException, css::lang::DisposedException )
{
    // Look for rejected calls first.
    // If call was refused we throw some exceptions or do nothing!
    // It depends from given parameter eMode.
    if( isCallRejected( eReason ) == sal_True )
    {
        impl_throwExceptions( eMode, eReason );
    }

    // BUT if no exception was thrown ... (may be eMode = E_SOFTEXCEPTIONS!)
    // we must register this transaction too!
    // Don't use "else" or a new scope here!!!

    // Safe access to internal member.
    ::osl::MutexGuard aAccessGuard( m_aAccessLock );

    #ifdef ENABLE_MUTEXDEBUG
    LOG_ASSERT2( m_nTransactionCount<0, "TransactionManager::acquire()", "Wrong ref count detected!" )
    #endif

    // Register this new transaction.
    // If it is the first one .. close gate to disable changing of working mode.
    ++m_nTransactionCount;
    if( m_nTransactionCount == 1 )
    {
        m_aBarrier.close();
    }
}

/*-****************************************************************************************************//**
    @interface  ITransactionManager
    @short      finish transaction
    @descr      A guard should call this method to release current transaction.

    @seealso    method registerTransaction()

    @param      -
    @return     -

    @onerror    -
*//*-*****************************************************************************************************/
void  TransactionManager::unregisterTransaction() throw( css::uno::RuntimeException, css::lang::DisposedException )
{
    // This call could not rejected!
    // Safe access to internal member.
    ::osl::MutexGuard aAccessGuard( m_aAccessLock );

    #ifdef ENABLE_MUTEXDEBUG
    LOG_ASSERT2( m_nTransactionCount<=0, "TransactionManager::release()", "Wrong ref count detected!" )
    #endif

    // Deregister this transaction.
    // If it was the last one ... open gate to enable changing of working mode!
    // (see setWorkingMode())

    --m_nTransactionCount;
    if( m_nTransactionCount == 0 )
    {
        m_aBarrier.open();
    }
}

/*-****************************************************************************************************//**
    @interface  ITransactionManager
    @short      look for rejected calls
    @descr      Sometimes user need a possibility to get information about rejected calls
                without starting a transaction!

    @seealso    -

    @param      "eReason" returns reason of a rejected call
    @return     true if call was rejected, false otherwise

    @onerror    We return false.
*//*-*****************************************************************************************************/
sal_Bool  TransactionManager::isCallRejected( ERejectReason& eReason ) const
{
    // This call must safe access to internal member only.
    // Set "possible reason" for return and check reject-state then!
    // User should look for return value first - reason then ...
    ::osl::MutexGuard aAccessGuard( m_aAccessLock );
    switch( m_eWorkingMode )
    {
        case E_INIT        : eReason = E_UNINITIALIZED ;
                                break;
        case E_WORK        : eReason = E_NOREASON      ;
                                break;
        case E_BEFORECLOSE : eReason = E_INCLOSE       ;
                                break;
        case E_CLOSE       : eReason = E_CLOSED        ;
                                break;
    }
    return( eReason!=E_NOREASON );
}

/*-****************************************************************************************************//**
    @short      return a reference to a static manager
    @descr      Sometimes we need the global member! (e.g. in our own static methods)
                We create our own "class global static" member threadsafe.
                It will be created at first call only!
                All other requests use these created one then directly.

    @seealso    -

    @param      -
    @return     A reference to a static member.

    @onerror    No error should occure.
*//*-*****************************************************************************************************/
TransactionManager& TransactionManager::getGlobalTransactionManager()
{
    // Initialize static member only for one time!
    static TransactionManager* pManager = NULL;
    // If these method first called (member not already exist!) ...
    if( pManager == NULL )
    {
        // ... we must create a new one. Protect follow code with the global mutex -
        // It must be - we create a static variable!
        ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
        // We must check our pointer again - because ... another instance of ouer class could be faster then these one!
        if( pManager == NULL )
        {
// [ed] 6/16/02 Avoid static member data on OS X to work around compiler bugs
#if defined(MACOSX) && (__GNUC__ < 3)
            // Create the new manager and set it for return on static variable.
            pManager = new TransactionManager();
#else
            // Create the new manager and set it for return on static variable.
            static TransactionManager aManager;
            pManager = &aManager;
#endif
        }
    }
    // Return new created or already existing object.
    return *pManager;
}

/*-****************************************************************************************************//**
    @short      throw any exceptions for rejected calls
    @descr      If user whish to use our automaticly exception mode we use this impl-method.
                We check all combinations of eReason and eExceptionMode and throw right exception with some
                descriptions for recipient of it.

    @seealso    method registerTransaction()
    @seealso    enum ERejectReason
    @seealso    enum EExceptionMode

    @param      "eReason" , reason for rejected call
    @param      "eMode"   , exception mode - set by user
    @return     -

    @onerror    -
*//*-*****************************************************************************************************/
void TransactionManager::impl_throwExceptions( EExceptionMode eMode, ERejectReason eReason ) const throw( css::uno::RuntimeException, css::lang::DisposedException )
{
    if( eMode != E_NOEXCEPTIONS )
    {
        switch( eReason )
        {
            case E_UNINITIALIZED   :    if( eMode == E_HARDEXCEPTIONS )
                                        {
                                            // Help programmer to find out, why this exception is thrown!
                                            LOG_ERROR( "TransactionManager...", "Owner instance not right initialized yet. Call was rejected! Normaly it's an algorithm error ... wrong usin of class!" )
                                            //ATTENTION: temp. disabled - till all bad code positions are detected and changed! */
                                            // throw css::uno::RuntimeException( DECLARE_ASCII("TransactionManager...\nOwner instance not right initialized yet. Call was rejected! Normaly it's an algorithm error ... wrong usin of class!\n" ), css::uno::Reference< css::uno::XInterface >() );
                                        }
                                        break;
            case E_INCLOSE         :    if( eMode == E_HARDEXCEPTIONS )
                                        {
                                            // Help programmer to find out, why this exception is thrown!
                                            LOG_ERROR( "TransactionManager...", "Owner instance stand in close method. Call was rejected!" )
                                            throw css::lang::DisposedException( DECLARE_ASCII("TransactionManager...\nOwner instance stand in close method. Call was rejected!\n" ), css::uno::Reference< css::uno::XInterface >() );
                                        }
                                        break;
            case E_CLOSED           :   {
                                            // Help programmer to find out, why this exception is thrown!
                                            LOG_ERROR( "TransactionManager...", "Owner instance already closed. Call was rejected!" )
                                            throw css::lang::DisposedException( DECLARE_ASCII("TransactionManager...\nOwner instance already closed. Call was rejected!\n" ), css::uno::Reference< css::uno::XInterface >() );
                                        }
                                        break;
        }
    }
}

}   //  namespace framework
<commit_msg>INTEGRATION: CWS geordi2q14 (1.5.76); FILE MERGED 2004/01/29 16:05:43 hr 1.5.76.1: #111934#: merge CWS ooo111fix2<commit_after>/*************************************************************************
 *
 *  $RCSfile: transactionmanager.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-02 23:06:16 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONMANAGER_HXX_
#include <threadhelp/transactionmanager.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported declarations
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  definitions
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short      standard ctor
    @descr      Initialize instance with right start values for correct working.

    @seealso    -

    @param      -
    @return     -

    @onerror    -
*//*-*************************************************************************************************************/
TransactionManager::TransactionManager()
    : m_eWorkingMode      ( E_INIT )
    , m_nTransactionCount ( 0      )
{
    m_aBarrier.open();
}

/*-****************************************************************************************************//**
    @interface  ITransactionManager
    @short      set new working mode
    @descr      These implementation knows for states of working: E_INIT, E_WORK, E_CLOSING, E_CLOSE
                You can step during this ones only from the left to the right side and start at left side again!
                (This is neccessary e.g. for refcounted objects!)
                This call will block till all current existing transactions was finished.
                Follow results occure:
                    E_INIT        :  All requests on this implementation are refused.
                                        It's your decision to react in a right way.

                    E_WORK        :  The object can work now. The full functionality is available.

                    E_BEFORECLOSE :  The object start the closing mechanism ... but sometimes
                                        e.g. the dispose() method need to call some private methods.
                                        These some special methods should use E_SOFTEXCEPTIONS or ignore
                                        E_INCLOSE as returned reason for E_NOEXCEPTIONS to detect this special case!

                    E_CLOSE       :  Object is already dead! All further requests will be refused.
                                        It's your decision to react in a right way.

    @seealso    -

    @param      "eMode", is the new mode - but we don't accept setting mode in wrong order!
    @return     -

    @onerror    We do nothing.
*//*-*****************************************************************************************************/
void  TransactionManager::setWorkingMode( EWorkingMode eMode )
{
    // Safe member access.
    ::osl::ClearableMutexGuard  aAccessGuard( m_aAccessLock );
    sal_Bool                    bWaitFor    = sal_False      ;
    // Change working mode first!
    if  (
            ( m_eWorkingMode == E_INIT        && eMode == E_WORK        ) ||
            ( m_eWorkingMode == E_WORK        && eMode == E_BEFORECLOSE ) ||
            ( m_eWorkingMode == E_BEFORECLOSE && eMode == E_CLOSE       ) ||
            ( m_eWorkingMode == E_CLOSE       && eMode == E_INIT        )
        )
    {
        m_eWorkingMode = eMode;
        if( m_eWorkingMode == E_BEFORECLOSE || m_eWorkingMode == E_CLOSE )
        {
            bWaitFor = sal_True;
        }
    }

    // Wait for current existing transactions then!
    // (Only neccessary for changing to E_BEFORECLOSE or E_CLOSE! ...
    // otherwise; if you wait at setting E_WORK another thrad could finish a acquire-call during our unlock() and wait() call
    // ... and we will wait forever here!!!)
    // Don't forget to release access mutex before.
    aAccessGuard.clear();
    if( bWaitFor == sal_True )
    {
        m_aBarrier.wait();
    }
}

/*-****************************************************************************************************//**
    @interface  ITransactionManager
    @short      get current working mode
    @descr      If you stand in your close() or init() method ... but don't know
                if you called more then ones(!) ... you can use this function to get
                right information.
                e.g:    You have a method init() which is used to change working mode from
                        E_INIT to E_WORK and should be used to initialize some member too ...
                        What should you do:

                            void init( sal_Int32 nValue )
                            {
                                // Reject this call if our transaction manager say: "Object already initialized!"
                                // Otherwise initialize your member.
                                if( m_aTransactionManager.getWorkingMode() == E_INIT )
                                {
                                    // Object is uninitialized ...
                                    // Make member access threadsafe!
                                    ResetableGuard aGuard( m_aMutex );

                                    // Check working mode again .. because anozther instance could be faster.
                                    // (It's possible to set this guard at first of this method too!)
                                    if( m_aTransactionManager.getWorkingMode() == E_INIT )
                                    {
                                        m_aMember = nValue;

                                        // Object is initialized now ... set working mode to E_WORK!
                                        m_aTransactionManager.setWorkingMode( E_WORK );
                                    }
                                }
                            }

    @seealso    method setWorkingMode()

    @param      -
    @return     Current set mode.

    @onerror    No error should occure.
*//*-*****************************************************************************************************/
EWorkingMode TransactionManager::getWorkingMode() const
{
    // Synchronize access to internal member!
    ::osl::MutexGuard aAccessLock( m_aAccessLock );
    return m_eWorkingMode;
}

/*-****************************************************************************************************//**
    @interface  ITransactionManager
    @short      start new transaction
    @descr      A guard should use this method to start a new transaction. He should looks for rejected
                calls to by using parameter eMode and eReason.
                If call was not rejected your transaction will be non breakable during releasing your transaction
                guard! BUT ... your code isn't threadsafe then! It's a transaction manager only ....

    @seealso    method unregisterTransaction()

    @param      "eMode"     ,used to enable/disable throwing exceptions automaticly for rejected calls
    @param      "eReason"   ,reason for rejected calls if eMode=E_NOEXCEPTIONS
    @return     -

    @onerror    -
*//*-*****************************************************************************************************/
void  TransactionManager::registerTransaction( EExceptionMode eMode, ERejectReason& eReason ) throw( css::uno::RuntimeException, css::lang::DisposedException )
{
    // Look for rejected calls first.
    // If call was refused we throw some exceptions or do nothing!
    // It depends from given parameter eMode.
    if( isCallRejected( eReason ) == sal_True )
    {
        impl_throwExceptions( eMode, eReason );
    }

    // BUT if no exception was thrown ... (may be eMode = E_SOFTEXCEPTIONS!)
    // we must register this transaction too!
    // Don't use "else" or a new scope here!!!

    // Safe access to internal member.
    ::osl::MutexGuard aAccessGuard( m_aAccessLock );

    #ifdef ENABLE_MUTEXDEBUG
    LOG_ASSERT2( m_nTransactionCount<0, "TransactionManager::acquire()", "Wrong ref count detected!" )
    #endif

    // Register this new transaction.
    // If it is the first one .. close gate to disable changing of working mode.
    ++m_nTransactionCount;
    if( m_nTransactionCount == 1 )
    {
        m_aBarrier.close();
    }
}

/*-****************************************************************************************************//**
    @interface  ITransactionManager
    @short      finish transaction
    @descr      A guard should call this method to release current transaction.

    @seealso    method registerTransaction()

    @param      -
    @return     -

    @onerror    -
*//*-*****************************************************************************************************/
void  TransactionManager::unregisterTransaction() throw( css::uno::RuntimeException, css::lang::DisposedException )
{
    // This call could not rejected!
    // Safe access to internal member.
    ::osl::MutexGuard aAccessGuard( m_aAccessLock );

    #ifdef ENABLE_MUTEXDEBUG
    LOG_ASSERT2( m_nTransactionCount<=0, "TransactionManager::release()", "Wrong ref count detected!" )
    #endif

    // Deregister this transaction.
    // If it was the last one ... open gate to enable changing of working mode!
    // (see setWorkingMode())

    --m_nTransactionCount;
    if( m_nTransactionCount == 0 )
    {
        m_aBarrier.open();
    }
}

/*-****************************************************************************************************//**
    @interface  ITransactionManager
    @short      look for rejected calls
    @descr      Sometimes user need a possibility to get information about rejected calls
                without starting a transaction!

    @seealso    -

    @param      "eReason" returns reason of a rejected call
    @return     true if call was rejected, false otherwise

    @onerror    We return false.
*//*-*****************************************************************************************************/
sal_Bool  TransactionManager::isCallRejected( ERejectReason& eReason ) const
{
    // This call must safe access to internal member only.
    // Set "possible reason" for return and check reject-state then!
    // User should look for return value first - reason then ...
    ::osl::MutexGuard aAccessGuard( m_aAccessLock );
    switch( m_eWorkingMode )
    {
        case E_INIT        : eReason = E_UNINITIALIZED ;
                                break;
        case E_WORK        : eReason = E_NOREASON      ;
                                break;
        case E_BEFORECLOSE : eReason = E_INCLOSE       ;
                                break;
        case E_CLOSE       : eReason = E_CLOSED        ;
                                break;
    }
    return( eReason!=E_NOREASON );
}

/*-****************************************************************************************************//**
    @short      return a reference to a static manager
    @descr      Sometimes we need the global member! (e.g. in our own static methods)
                We create our own "class global static" member threadsafe.
                It will be created at first call only!
                All other requests use these created one then directly.

    @seealso    -

    @param      -
    @return     A reference to a static member.

    @onerror    No error should occure.
*//*-*****************************************************************************************************/
TransactionManager& TransactionManager::getGlobalTransactionManager()
{
    // Initialize static member only for one time!
    static TransactionManager* pManager = NULL;
    // If these method first called (member not already exist!) ...
    if( pManager == NULL )
    {
        // ... we must create a new one. Protect follow code with the global mutex -
        // It must be - we create a static variable!
        ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
        // We must check our pointer again - because ... another instance of ouer class could be faster then these one!
        if( pManager == NULL )
        {
            // Create the new manager and set it for return on static variable.
            static TransactionManager aManager;
            pManager = &aManager;
        }
    }
    // Return new created or already existing object.
    return *pManager;
}

/*-****************************************************************************************************//**
    @short      throw any exceptions for rejected calls
    @descr      If user whish to use our automaticly exception mode we use this impl-method.
                We check all combinations of eReason and eExceptionMode and throw right exception with some
                descriptions for recipient of it.

    @seealso    method registerTransaction()
    @seealso    enum ERejectReason
    @seealso    enum EExceptionMode

    @param      "eReason" , reason for rejected call
    @param      "eMode"   , exception mode - set by user
    @return     -

    @onerror    -
*//*-*****************************************************************************************************/
void TransactionManager::impl_throwExceptions( EExceptionMode eMode, ERejectReason eReason ) const throw( css::uno::RuntimeException, css::lang::DisposedException )
{
    if( eMode != E_NOEXCEPTIONS )
    {
        switch( eReason )
        {
            case E_UNINITIALIZED   :    if( eMode == E_HARDEXCEPTIONS )
                                        {
                                            // Help programmer to find out, why this exception is thrown!
                                            LOG_ERROR( "TransactionManager...", "Owner instance not right initialized yet. Call was rejected! Normaly it's an algorithm error ... wrong usin of class!" )
                                            //ATTENTION: temp. disabled - till all bad code positions are detected and changed! */
                                            // throw css::uno::RuntimeException( DECLARE_ASCII("TransactionManager...\nOwner instance not right initialized yet. Call was rejected! Normaly it's an algorithm error ... wrong usin of class!\n" ), css::uno::Reference< css::uno::XInterface >() );
                                        }
                                        break;
            case E_INCLOSE         :    if( eMode == E_HARDEXCEPTIONS )
                                        {
                                            // Help programmer to find out, why this exception is thrown!
                                            LOG_ERROR( "TransactionManager...", "Owner instance stand in close method. Call was rejected!" )
                                            throw css::lang::DisposedException( DECLARE_ASCII("TransactionManager...\nOwner instance stand in close method. Call was rejected!\n" ), css::uno::Reference< css::uno::XInterface >() );
                                        }
                                        break;
            case E_CLOSED           :   {
                                            // Help programmer to find out, why this exception is thrown!
                                            LOG_ERROR( "TransactionManager...", "Owner instance already closed. Call was rejected!" )
                                            throw css::lang::DisposedException( DECLARE_ASCII("TransactionManager...\nOwner instance already closed. Call was rejected!\n" ), css::uno::Reference< css::uno::XInterface >() );
                                        }
                                        break;
        }
    }
}

}   //  namespace framework
<|endoftext|>


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

// MOOSE includes
#include "ComputeMaterialsObjectThread.h"
#include "NonlinearSystem.h"
#include "Problem.h"
#include "FEProblem.h"
#include "MaterialPropertyStorage.h"
#include "MaterialData.h"
#include "Assembly.h"
#include "AuxKernel.h"
#include "Material.h"

#include "libmesh/threads.h"
#include "libmesh/quadrature.h"

ComputeMaterialsObjectThread::ComputeMaterialsObjectThread(
    FEProblemBase & fe_problem,
    std::vector<std::shared_ptr<MaterialData>> & material_data,
    std::vector<std::shared_ptr<MaterialData>> & bnd_material_data,
    std::vector<std::shared_ptr<MaterialData>> & neighbor_material_data,
    MaterialPropertyStorage & material_props,
    MaterialPropertyStorage & bnd_material_props,
    MaterialPropertyStorage & neighbor_material_props,
    std::vector<std::unique_ptr<Assembly>> & assembly)
  : ThreadedElementLoop<ConstElemRange>(fe_problem),
    _fe_problem(fe_problem),
    _nl(fe_problem.getNonlinearSystemBase()),
    _material_data(material_data),
    _bnd_material_data(bnd_material_data),
    _neighbor_material_data(neighbor_material_data),
    _material_props(material_props),
    _bnd_material_props(bnd_material_props),
    _neighbor_material_props(neighbor_material_props),
    _materials(_fe_problem.getRegularMaterialsWarehouse()),
    _interface_materials(_fe_problem.getInterfaceMaterialsWarehouse()),
    _discrete_materials(_fe_problem.getDiscreteMaterialWarehouse()),
    _assembly(assembly),
    _need_internal_side_material(false),
    _has_stateful_props(_material_props.hasStatefulProperties()),
    _has_bnd_stateful_props(_bnd_material_props.hasStatefulProperties()),
    _has_neighbor_stateful_props(_neighbor_material_props.hasStatefulProperties())
{
}

// Splitting Constructor
ComputeMaterialsObjectThread::ComputeMaterialsObjectThread(ComputeMaterialsObjectThread & x,
                                                           Threads::split split)
  : ThreadedElementLoop<ConstElemRange>(x, split),
    _fe_problem(x._fe_problem),
    _nl(x._nl),
    _material_data(x._material_data),
    _bnd_material_data(x._bnd_material_data),
    _neighbor_material_data(x._neighbor_material_data),
    _material_props(x._material_props),
    _bnd_material_props(x._bnd_material_props),
    _neighbor_material_props(x._neighbor_material_props),
    _materials(x._materials),
    _interface_materials(x._interface_materials),
    _discrete_materials(x._discrete_materials),
    _assembly(x._assembly),
    _need_internal_side_material(x._need_internal_side_material),
    _has_stateful_props(_material_props.hasStatefulProperties()),
    _has_bnd_stateful_props(_bnd_material_props.hasStatefulProperties()),
    _has_neighbor_stateful_props(_neighbor_material_props.hasStatefulProperties())
{
}

void
ComputeMaterialsObjectThread::subdomainChanged()
{
  _need_internal_side_material = _fe_problem.needSubdomainMaterialOnSide(_subdomain, _tid);
  _fe_problem.subdomainSetup(_subdomain, _tid);

  std::set<MooseVariableFEBase *> needed_moose_vars;
  _materials.updateVariableDependency(needed_moose_vars, _tid);
  _fe_problem.setActiveElementalMooseVariables(needed_moose_vars, _tid);

  std::set<TagID> needed_fe_var_vector_tags;
  _materials.updateBlockFEVariableCoupledVectorTagDependency(
      _subdomain, needed_fe_var_vector_tags, _tid);
  _fe_problem.setActiveFEVariableCoupleableVectorTags(needed_fe_var_vector_tags, _tid);
}

void
ComputeMaterialsObjectThread::onElement(const Elem * elem)
{
  if (_materials.hasActiveBlockObjects(_subdomain, _tid) ||
      _discrete_materials.hasActiveBlockObjects(_subdomain, _tid))
  {
    _fe_problem.prepare(elem, _tid);
    _fe_problem.reinitElem(elem, _tid);

    unsigned int n_points = _assembly[_tid]->qRule()->n_points();
    _material_data[_tid]->resize(n_points);

    if (_has_stateful_props)
    {
      if (_discrete_materials.hasActiveBlockObjects(_subdomain, _tid))
        _material_props.initStatefulProps(
            *_material_data[_tid],
            _discrete_materials.getActiveBlockObjects(_subdomain, _tid),
            n_points,
            *elem);
      if (_materials.hasActiveBlockObjects(_subdomain, _tid))
        _material_props.initStatefulProps(*_material_data[_tid],
                                          _materials.getActiveBlockObjects(_subdomain, _tid),
                                          n_points,
                                          *elem);
    }
  }
}

void
ComputeMaterialsObjectThread::onBoundary(const Elem * elem,
                                         unsigned int side,
                                         BoundaryID bnd_id,
                                         const Elem * /*lower_d_elem = nullptr*/)
{
  if (_fe_problem.needBoundaryMaterialOnSide(bnd_id, _tid))
  {
    _fe_problem.reinitElemFace(elem, side, bnd_id, _tid);
    unsigned int face_n_points = _assembly[_tid]->qRuleFace()->n_points();

    _bnd_material_data[_tid]->resize(face_n_points);

    if (_has_bnd_stateful_props)
    {
      // Face Materials
      if (_discrete_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
        _bnd_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _discrete_materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
            face_n_points,
            *elem,
            side);
      if (_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
        _bnd_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
            face_n_points,
            *elem,
            side);

      // Boundary Materials
      if (_discrete_materials.hasActiveBoundaryObjects(bnd_id, _tid))
        _bnd_material_props.initStatefulProps(*_bnd_material_data[_tid],
                                              _materials.getActiveBoundaryObjects(bnd_id, _tid),
                                              face_n_points,
                                              *elem,
                                              side);
      if (_materials.hasActiveBoundaryObjects(bnd_id, _tid))
        _bnd_material_props.initStatefulProps(*_bnd_material_data[_tid],
                                              _materials.getActiveBoundaryObjects(bnd_id, _tid),
                                              face_n_points,
                                              *elem,
                                              side);
    }
  }
}

void
ComputeMaterialsObjectThread::onInternalSide(const Elem * elem, unsigned int side)
{
  if (_need_internal_side_material)
  {
    const Elem * neighbor = elem->neighbor_ptr(side);

    _fe_problem.reinitElemNeighborAndLowerD(elem, side, _tid);
    unsigned int face_n_points = _assembly[_tid]->qRuleFace()->n_points();
    _bnd_material_data[_tid]->resize(face_n_points);
    _neighbor_material_data[_tid]->resize(face_n_points);

    if (_has_bnd_stateful_props)
    {
      if (_discrete_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
        _bnd_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _discrete_materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
            face_n_points,
            *elem,
            side);
      if (_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
        _bnd_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
            face_n_points,
            *elem,
            side);
    }

    unsigned int neighbor_side = neighbor->which_neighbor_am_i(_assembly[_tid]->elem());

    if (_has_neighbor_stateful_props)
    {
      // Neighbor Materials
      if (_discrete_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(
              neighbor->subdomain_id(), _tid))
        _neighbor_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _discrete_materials[Moose::NEIGHBOR_MATERIAL_DATA].getActiveBlockObjects(
                neighbor->subdomain_id(), _tid),
            face_n_points,
            *elem,
            side);
      if (_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(neighbor->subdomain_id(),
                                                                          _tid))
        _neighbor_material_props.initStatefulProps(
            *_neighbor_material_data[_tid],
            _materials[Moose::NEIGHBOR_MATERIAL_DATA].getActiveBlockObjects(
                neighbor->subdomain_id(), _tid),
            face_n_points,
            *neighbor,
            neighbor_side);
    }
  }
}

void
ComputeMaterialsObjectThread::onInterface(const Elem * elem, unsigned int side, BoundaryID bnd_id)
{
  if (_fe_problem.needInterfaceMaterialOnSide(bnd_id, _tid))
  {
    _assembly[_tid]->reinit(elem, side);
    unsigned int face_n_points = _assembly[_tid]->qRuleFace()->n_points();
    _bnd_material_data[_tid]->resize(face_n_points);
    _neighbor_material_data[_tid]->resize(face_n_points);

    if (_has_bnd_stateful_props)
    {
      // Face Materials
      if (_discrete_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
        _bnd_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _discrete_materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
            face_n_points,
            *elem,
            side);

      if (_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
        _bnd_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
            face_n_points,
            *elem,
            side);

      // Boundary Materials
      if (_discrete_materials.hasActiveBoundaryObjects(bnd_id, _tid))
        _bnd_material_props.initStatefulProps(*_bnd_material_data[_tid],
                                              _materials.getActiveBoundaryObjects(bnd_id, _tid),
                                              face_n_points,
                                              *elem,
                                              side);

      if (_materials.hasActiveBoundaryObjects(bnd_id, _tid))
        _bnd_material_props.initStatefulProps(*_bnd_material_data[_tid],
                                              _materials.getActiveBoundaryObjects(bnd_id, _tid),
                                              face_n_points,
                                              *elem,
                                              side);
    }

    const Elem * neighbor = elem->neighbor_ptr(side);
    unsigned int neighbor_side = neighbor->which_neighbor_am_i(_assembly[_tid]->elem());

    // Do we have neighbor stateful properties or do we have stateful interface material properties?
    // If either then we need to reinit the neighbor, so at least at a minimum _neighbor_elem isn't
    // NULL!
    if (neighbor->active() &&
        (_has_neighbor_stateful_props ||
         (_has_bnd_stateful_props && _interface_materials.hasActiveBoundaryObjects(bnd_id, _tid))))
      _fe_problem.reinitNeighbor(elem, side, _tid);

    if (_has_neighbor_stateful_props && neighbor->active())
    {
      // Neighbor Materials
      if (_discrete_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(
              neighbor->subdomain_id(), _tid))
        _neighbor_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _discrete_materials[Moose::NEIGHBOR_MATERIAL_DATA].getActiveBlockObjects(
                neighbor->subdomain_id(), _tid),
            face_n_points,
            *elem,
            side);

      if (_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(neighbor->subdomain_id(),
                                                                          _tid))
        _neighbor_material_props.initStatefulProps(
            *_neighbor_material_data[_tid],
            _materials[Moose::NEIGHBOR_MATERIAL_DATA].getActiveBlockObjects(
                neighbor->subdomain_id(), _tid),
            face_n_points,
            *neighbor,
            neighbor_side);
    }

    // Interface Materials. Make sure we do these after neighbors
    if (_has_bnd_stateful_props && _interface_materials.hasActiveBoundaryObjects(bnd_id, _tid))
      _bnd_material_props.initStatefulProps(
          *_bnd_material_data[_tid],
          _interface_materials.getActiveBoundaryObjects(bnd_id, _tid),
          face_n_points,
          *elem,
          side);
  }
}

void
ComputeMaterialsObjectThread::join(const ComputeMaterialsObjectThread & /*y*/)
{
}

void
ComputeMaterialsObjectThread::post()
{
  _fe_problem.clearActiveElementalMooseVariables(_tid);
}
<commit_msg>Do early return to reduce indentation<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

// MOOSE includes
#include "ComputeMaterialsObjectThread.h"
#include "NonlinearSystem.h"
#include "Problem.h"
#include "FEProblem.h"
#include "MaterialPropertyStorage.h"
#include "MaterialData.h"
#include "Assembly.h"
#include "AuxKernel.h"
#include "Material.h"

#include "libmesh/threads.h"
#include "libmesh/quadrature.h"

ComputeMaterialsObjectThread::ComputeMaterialsObjectThread(
    FEProblemBase & fe_problem,
    std::vector<std::shared_ptr<MaterialData>> & material_data,
    std::vector<std::shared_ptr<MaterialData>> & bnd_material_data,
    std::vector<std::shared_ptr<MaterialData>> & neighbor_material_data,
    MaterialPropertyStorage & material_props,
    MaterialPropertyStorage & bnd_material_props,
    MaterialPropertyStorage & neighbor_material_props,
    std::vector<std::unique_ptr<Assembly>> & assembly)
  : ThreadedElementLoop<ConstElemRange>(fe_problem),
    _fe_problem(fe_problem),
    _nl(fe_problem.getNonlinearSystemBase()),
    _material_data(material_data),
    _bnd_material_data(bnd_material_data),
    _neighbor_material_data(neighbor_material_data),
    _material_props(material_props),
    _bnd_material_props(bnd_material_props),
    _neighbor_material_props(neighbor_material_props),
    _materials(_fe_problem.getRegularMaterialsWarehouse()),
    _interface_materials(_fe_problem.getInterfaceMaterialsWarehouse()),
    _discrete_materials(_fe_problem.getDiscreteMaterialWarehouse()),
    _assembly(assembly),
    _need_internal_side_material(false),
    _has_stateful_props(_material_props.hasStatefulProperties()),
    _has_bnd_stateful_props(_bnd_material_props.hasStatefulProperties()),
    _has_neighbor_stateful_props(_neighbor_material_props.hasStatefulProperties())
{
}

// Splitting Constructor
ComputeMaterialsObjectThread::ComputeMaterialsObjectThread(ComputeMaterialsObjectThread & x,
                                                           Threads::split split)
  : ThreadedElementLoop<ConstElemRange>(x, split),
    _fe_problem(x._fe_problem),
    _nl(x._nl),
    _material_data(x._material_data),
    _bnd_material_data(x._bnd_material_data),
    _neighbor_material_data(x._neighbor_material_data),
    _material_props(x._material_props),
    _bnd_material_props(x._bnd_material_props),
    _neighbor_material_props(x._neighbor_material_props),
    _materials(x._materials),
    _interface_materials(x._interface_materials),
    _discrete_materials(x._discrete_materials),
    _assembly(x._assembly),
    _need_internal_side_material(x._need_internal_side_material),
    _has_stateful_props(_material_props.hasStatefulProperties()),
    _has_bnd_stateful_props(_bnd_material_props.hasStatefulProperties()),
    _has_neighbor_stateful_props(_neighbor_material_props.hasStatefulProperties())
{
}

void
ComputeMaterialsObjectThread::subdomainChanged()
{
  _need_internal_side_material = _fe_problem.needSubdomainMaterialOnSide(_subdomain, _tid);
  _fe_problem.subdomainSetup(_subdomain, _tid);

  std::set<MooseVariableFEBase *> needed_moose_vars;
  _materials.updateVariableDependency(needed_moose_vars, _tid);
  _fe_problem.setActiveElementalMooseVariables(needed_moose_vars, _tid);

  std::set<TagID> needed_fe_var_vector_tags;
  _materials.updateBlockFEVariableCoupledVectorTagDependency(
      _subdomain, needed_fe_var_vector_tags, _tid);
  _fe_problem.setActiveFEVariableCoupleableVectorTags(needed_fe_var_vector_tags, _tid);
}

void
ComputeMaterialsObjectThread::onElement(const Elem * elem)
{
  if (_materials.hasActiveBlockObjects(_subdomain, _tid) ||
      _discrete_materials.hasActiveBlockObjects(_subdomain, _tid))
  {
    _fe_problem.prepare(elem, _tid);
    _fe_problem.reinitElem(elem, _tid);

    unsigned int n_points = _assembly[_tid]->qRule()->n_points();
    _material_data[_tid]->resize(n_points);

    if (_has_stateful_props)
    {
      if (_discrete_materials.hasActiveBlockObjects(_subdomain, _tid))
        _material_props.initStatefulProps(
            *_material_data[_tid],
            _discrete_materials.getActiveBlockObjects(_subdomain, _tid),
            n_points,
            *elem);
      if (_materials.hasActiveBlockObjects(_subdomain, _tid))
        _material_props.initStatefulProps(*_material_data[_tid],
                                          _materials.getActiveBlockObjects(_subdomain, _tid),
                                          n_points,
                                          *elem);
    }
  }
}

void
ComputeMaterialsObjectThread::onBoundary(const Elem * elem,
                                         unsigned int side,
                                         BoundaryID bnd_id,
                                         const Elem * /*lower_d_elem = nullptr*/)
{
  if (_fe_problem.needBoundaryMaterialOnSide(bnd_id, _tid))
  {
    _fe_problem.reinitElemFace(elem, side, bnd_id, _tid);
    unsigned int face_n_points = _assembly[_tid]->qRuleFace()->n_points();

    _bnd_material_data[_tid]->resize(face_n_points);

    if (_has_bnd_stateful_props)
    {
      // Face Materials
      if (_discrete_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
        _bnd_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _discrete_materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
            face_n_points,
            *elem,
            side);
      if (_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
        _bnd_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
            face_n_points,
            *elem,
            side);

      // Boundary Materials
      if (_discrete_materials.hasActiveBoundaryObjects(bnd_id, _tid))
        _bnd_material_props.initStatefulProps(*_bnd_material_data[_tid],
                                              _materials.getActiveBoundaryObjects(bnd_id, _tid),
                                              face_n_points,
                                              *elem,
                                              side);
      if (_materials.hasActiveBoundaryObjects(bnd_id, _tid))
        _bnd_material_props.initStatefulProps(*_bnd_material_data[_tid],
                                              _materials.getActiveBoundaryObjects(bnd_id, _tid),
                                              face_n_points,
                                              *elem,
                                              side);
    }
  }
}

void
ComputeMaterialsObjectThread::onInternalSide(const Elem * elem, unsigned int side)
{
  if (_need_internal_side_material)
  {
    const Elem * neighbor = elem->neighbor_ptr(side);

    _fe_problem.reinitElemNeighborAndLowerD(elem, side, _tid);
    unsigned int face_n_points = _assembly[_tid]->qRuleFace()->n_points();
    _bnd_material_data[_tid]->resize(face_n_points);
    _neighbor_material_data[_tid]->resize(face_n_points);

    if (_has_bnd_stateful_props)
    {
      if (_discrete_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
        _bnd_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _discrete_materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
            face_n_points,
            *elem,
            side);
      if (_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
        _bnd_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
            face_n_points,
            *elem,
            side);
    }

    unsigned int neighbor_side = neighbor->which_neighbor_am_i(_assembly[_tid]->elem());

    if (_has_neighbor_stateful_props)
    {
      // Neighbor Materials
      if (_discrete_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(
              neighbor->subdomain_id(), _tid))
        _neighbor_material_props.initStatefulProps(
            *_bnd_material_data[_tid],
            _discrete_materials[Moose::NEIGHBOR_MATERIAL_DATA].getActiveBlockObjects(
                neighbor->subdomain_id(), _tid),
            face_n_points,
            *elem,
            side);
      if (_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(neighbor->subdomain_id(),
                                                                          _tid))
        _neighbor_material_props.initStatefulProps(
            *_neighbor_material_data[_tid],
            _materials[Moose::NEIGHBOR_MATERIAL_DATA].getActiveBlockObjects(
                neighbor->subdomain_id(), _tid),
            face_n_points,
            *neighbor,
            neighbor_side);
    }
  }
}

void
ComputeMaterialsObjectThread::onInterface(const Elem * elem, unsigned int side, BoundaryID bnd_id)
{
  if (!_fe_problem.needInterfaceMaterialOnSide(bnd_id, _tid))
    return;

  _assembly[_tid]->reinit(elem, side);
  unsigned int face_n_points = _assembly[_tid]->qRuleFace()->n_points();
  _bnd_material_data[_tid]->resize(face_n_points);
  _neighbor_material_data[_tid]->resize(face_n_points);

  if (_has_bnd_stateful_props)
  {
    // Face Materials
    if (_discrete_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
      _bnd_material_props.initStatefulProps(
          *_bnd_material_data[_tid],
          _discrete_materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
          face_n_points,
          *elem,
          side);

    if (_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(_subdomain, _tid))
      _bnd_material_props.initStatefulProps(
          *_bnd_material_data[_tid],
          _materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(_subdomain, _tid),
          face_n_points,
          *elem,
          side);

    // Boundary Materials
    if (_discrete_materials.hasActiveBoundaryObjects(bnd_id, _tid))
      _bnd_material_props.initStatefulProps(*_bnd_material_data[_tid],
                                            _materials.getActiveBoundaryObjects(bnd_id, _tid),
                                            face_n_points,
                                            *elem,
                                            side);

    if (_materials.hasActiveBoundaryObjects(bnd_id, _tid))
      _bnd_material_props.initStatefulProps(*_bnd_material_data[_tid],
                                            _materials.getActiveBoundaryObjects(bnd_id, _tid),
                                            face_n_points,
                                            *elem,
                                            side);
  }

  const Elem * neighbor = elem->neighbor_ptr(side);
  unsigned int neighbor_side = neighbor->which_neighbor_am_i(_assembly[_tid]->elem());

  // Do we have neighbor stateful properties or do we have stateful interface material properties?
  // If either then we need to reinit the neighbor, so at least at a minimum _neighbor_elem isn't
  // NULL!
  if (neighbor->active() &&
      (_has_neighbor_stateful_props ||
       (_has_bnd_stateful_props && _interface_materials.hasActiveBoundaryObjects(bnd_id, _tid))))
    _fe_problem.reinitNeighbor(elem, side, _tid);

  if (_has_neighbor_stateful_props && neighbor->active())
  {
    // Neighbor Materials
    if (_discrete_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(
            neighbor->subdomain_id(), _tid))
      _neighbor_material_props.initStatefulProps(
          *_bnd_material_data[_tid],
          _discrete_materials[Moose::NEIGHBOR_MATERIAL_DATA].getActiveBlockObjects(
              neighbor->subdomain_id(), _tid),
          face_n_points,
          *elem,
          side);

    if (_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(neighbor->subdomain_id(),
                                                                        _tid))
      _neighbor_material_props.initStatefulProps(
          *_neighbor_material_data[_tid],
          _materials[Moose::NEIGHBOR_MATERIAL_DATA].getActiveBlockObjects(neighbor->subdomain_id(),
                                                                          _tid),
          face_n_points,
          *neighbor,
          neighbor_side);
  }

  // Interface Materials. Make sure we do these after neighbors
  if (_has_bnd_stateful_props && _interface_materials.hasActiveBoundaryObjects(bnd_id, _tid))
    _bnd_material_props.initStatefulProps(
        *_bnd_material_data[_tid],
        _interface_materials.getActiveBoundaryObjects(bnd_id, _tid),
        face_n_points,
        *elem,
        side);
}

void
ComputeMaterialsObjectThread::join(const ComputeMaterialsObjectThread & /*y*/)
{
}

void
ComputeMaterialsObjectThread::post()
{
  _fe_problem.clearActiveElementalMooseVariables(_tid);
}
<|endoftext|>


<commit_before>#ifndef K3_RUNTIME_LITERALS_H
#define K3_RUNTIME_LITERALS_H

#include <list>
#include <map>
#include <vector>

#include "boost/asio.hpp"
#include "boost/fusion/include/std_pair.hpp"
#include "boost/spirit/include/qi.hpp"

#include "BaseTypes.hpp"
#include "Common.hpp"

using std::list;
using std::map;
using std::pair;

namespace K3 {
  namespace qi = boost::spirit::qi;

  template <class iterator>
  class shallow: public qi::grammar<iterator, qi::space_type, string()> {
   public:
    shallow(): shallow::base_type(start) {
      start = qi::raw[indirection | option | angles | braces | brackets | parens | quotes | other];

      indirection = qi::lit("ind") >> start;
      option = qi::lit("none") | qi::lit("some") >> start;

      angles = '<' >> *(qi::char_ - '>') >> '>';
      braces = '{' >> *(qi::char_ - '}') >> '}';
      brackets = '[' >> *(qi::char_ - ']') >> ']';
      parens = '(' >> *(qi::char_ - ')') >> ')';
      quotes = '"' >> *(escape - '"') >> '"';
      other = *(qi::char_ - ',');

      escape = '\\' >> qi::char_ | qi::char_;
    }

   private:
    qi::rule<iterator, qi::space_type, string()> start;

    qi::rule<iterator, qi::space_type> indirection;
    qi::rule<iterator, qi::space_type> option;

    qi::rule<iterator, qi::space_type> angles;
    qi::rule<iterator, qi::space_type> braces;
    qi::rule<iterator, qi::space_type> brackets;
    qi::rule<iterator, qi::space_type> parens;
    qi::rule<iterator, qi::space_type> quotes;
    qi::rule<iterator, qi::space_type> other;

    qi::rule<iterator, qi::space_type> escape;
  };

  template <class iterator>
  class literal: public qi::grammar<iterator, map<string, string>(), qi::space_type> {
   public:
    literal(): literal::base_type(start) {

      start = binding % ',';
      binding = key >> ':' >> value;

      key = qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z0-9_");
    }

   private:
    qi::rule<iterator, map<string, string>(), qi::space_type> start;
    qi::rule<iterator, pair<string, string>(), qi::space_type> binding;
    qi::rule<iterator, string(), qi::space_type> key;
    shallow<iterator> value;
  };

  // Built-in literal patchers.

  template <class T> struct patcher;
  template <class T, size_t i, size_t n> struct tuple_patcher;

  template <class T> struct patcher {
    static void patch(string, T&);
  };

  template <> struct patcher<unit_t> {
    static void patch(std::string, unit_t&) {}
  };

  template <> struct patcher<bool> {
    static void patch(string s, bool& b) {
      qi::parse(begin(s), end(s), qi::bool_[([&b] (bool q) { b = q; })]);
    }
  };

  template <> struct patcher<int> {
    static void patch(string s, int& i) {
      qi::parse(begin(s), end(s), qi::int_[([&i] (int j) { i = j; })]);
    }
  };

  template <> struct patcher<long> {
    static void patch(string s, long& i) {
      qi::parse(begin(s), end(s), qi::long_[([&i] (int j) { i = j; })]);
    }
  };

  template <> struct patcher<double> {
    static void patch(string s, double& d) {
      qi::parse(begin(s), end(s), qi::double_[([&d] (double f) { d = f; })]);
    }
  };

  template <> struct patcher<Str> {
    static void patch(string s, Str st) {
      string s2(st.c_str());
      patch(s, s2);
    }
  };

  template <> struct patcher<string> {
    static void patch(string s, string& t) {
      string r;

      if (qi::parse(begin(s), end(s), ('"' >> *(('\\' >> qi::char_) | (qi::char_ - '"')) >> '"'), r)) {
        t = r;
      } else if
        (qi::parse(begin(s), end(s), ('\'' >> *(('\\' >> qi::char_) | (qi::char_ - '\'')) >> '\''), r)) {
        t = r;
      }
    }
  };

  template <> struct patcher<unsigned short> {
    static void patch(string s, unsigned short& u) {
      qi::parse(std::begin(s), std::end(s), qi::ushort_, u);
    }
  };

  template <> struct patcher<boost::asio::ip::address> {
    static void patch(string s, boost::asio::ip::address& a) {
      a = boost::asio::ip::address::from_string(s);
    }
  };

  template <class T> struct patcher<shared_ptr<T>> {
    static void patch(string s, shared_ptr<T> p) {
      shallow<string::iterator> _shallow;

      shared_ptr<T> tp = make_shared<T>(T());

      qi::rule<string::iterator, qi::space_type> ind_rule
        = qi::lit("ind") >> _shallow[([&tp] (string t) { patcher<T>::patch(t, *tp); })];
      qi::rule<string::iterator, qi::space_type> opt_rule
        = qi::lit("none")[([&p, &tp] () { tp = p = nullptr; })]
        | qi::lit("some") >> _shallow[([&tp] (string t) { patcher<T>::patch(t, *tp); })];

      qi::phrase_parse(begin(s), end(s), ind_rule | opt_rule, qi::space);

      if (tp) {
        p = tp;
      }
    }
  };

  template <class T> struct patcher<shared_ptr<list<T>>> {
    static void patch(string s, shared_ptr<list<T>>& p) {
      shallow<string::iterator> _shallow;
      list<T> lp;
      qi::rule<string::iterator, qi::space_type> item_rule
        = _shallow[([&lp] (string t) { lp.push_back(T()); patcher<T>::patch(t, lp.back()); })];

      qi::rule<string::iterator, qi::space_type> list_rule = '[' >> (item_rule % ',') >> ']';

      if (qi::phrase_parse(begin(s), end(s), list_rule, qi::space)) {
        p = make_shared<list<T>>(lp);
      }
    }
  };

  template <class ... Ts> struct patcher<tuple<Ts...>> {
    static void patch(string s, tuple<Ts...>& t) {
      list<string> v;
      shallow<string::iterator> _shallow;

      qi::rule<string::iterator, qi::space_type, list<string>()> tuple_rule = '(' >> (_shallow % ',') >> ')';

      qi::rule<string::iterator, qi::space_type, string()> ip_rule = qi::raw[(qi::int_ % '.')];
      qi::rule<string::iterator, qi::space_type, string()> port_rule = qi::raw[qi::int_];
      qi::rule<string::iterator, qi::space_type, list<string>()> address_rule
        = '<' >> ip_rule >> ':' >> port_rule >> '>';

      qi::phrase_parse(begin(s), end(s), tuple_rule | address_rule, qi::space, v);
      tuple_patcher<tuple<Ts...>, 0, sizeof...(Ts)>::patch(v, t);
    }
  };

  template <class T, size_t i> struct tuple_patcher<T, i, i> {
    static void patch(list<string>&, T&) {}
  };

  template <class T, size_t i, size_t n> struct tuple_patcher {
    static void patch(list<string>& v, T& t) {
      if (v.empty()) {
        return;
      }

      patcher<typename std::tuple_element<i, T>::type>::patch(v.front(), std::get<i>(t));

      v.pop_front();
      tuple_patcher<T, i + 1, n>::patch(v, t);
    }
  };

  template <template <class> class C, class E> struct collection_patcher {
    static void patch(string s, C<E>& c) {
      shared_ptr<list<E>> tmp_dsp = nullptr;
      patcher<shared_ptr<list<E>>>::patch(s, tmp_dsp);

      if (tmp_dsp) {
        C<E> new_c;
        for (E e: *tmp_dsp) {
          new_c.insert(e);
        }

        c = new_c;
      }
    }
  };

  map<string, string> parse_bindings(string s);

  template <class T>
  void do_patch(string s, T& t) {
    patcher<T>::patch(s, t);
  }

  void match_patchers(map<string, string>& m, map<string, std::function<void(string)>>& f);

  string preprocess_argv(int argc, char** argv);
}

#endif
<commit_msg>Fix literal patching for base_string.<commit_after>#ifndef K3_RUNTIME_LITERALS_H
#define K3_RUNTIME_LITERALS_H

#include <list>
#include <map>
#include <vector>

#include "boost/asio.hpp"
#include "boost/fusion/include/std_pair.hpp"
#include "boost/spirit/include/qi.hpp"

#include "BaseTypes.hpp"
#include "BaseString.hpp"
#include "Common.hpp"

using std::list;
using std::map;
using std::pair;

namespace K3 {
  namespace qi = boost::spirit::qi;

  template <class iterator>
  class shallow: public qi::grammar<iterator, qi::space_type, string()> {
   public:
    shallow(): shallow::base_type(start) {
      start = qi::raw[indirection | option | angles | braces | brackets | parens | quotes | other];

      indirection = qi::lit("ind") >> start;
      option = qi::lit("none") | qi::lit("some") >> start;

      angles = '<' >> *(qi::char_ - '>') >> '>';
      braces = '{' >> *(qi::char_ - '}') >> '}';
      brackets = '[' >> *(qi::char_ - ']') >> ']';
      parens = '(' >> *(qi::char_ - ')') >> ')';
      quotes = '"' >> *(escape - '"') >> '"';
      other = *(qi::char_ - ',');

      escape = '\\' >> qi::char_ | qi::char_;
    }

   private:
    qi::rule<iterator, qi::space_type, string()> start;

    qi::rule<iterator, qi::space_type> indirection;
    qi::rule<iterator, qi::space_type> option;

    qi::rule<iterator, qi::space_type> angles;
    qi::rule<iterator, qi::space_type> braces;
    qi::rule<iterator, qi::space_type> brackets;
    qi::rule<iterator, qi::space_type> parens;
    qi::rule<iterator, qi::space_type> quotes;
    qi::rule<iterator, qi::space_type> other;

    qi::rule<iterator, qi::space_type> escape;
  };

  template <class iterator>
  class literal: public qi::grammar<iterator, map<string, string>(), qi::space_type> {
   public:
    literal(): literal::base_type(start) {

      start = binding % ',';
      binding = key >> ':' >> value;

      key = qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z0-9_");
    }

   private:
    qi::rule<iterator, map<string, string>(), qi::space_type> start;
    qi::rule<iterator, pair<string, string>(), qi::space_type> binding;
    qi::rule<iterator, string(), qi::space_type> key;
    shallow<iterator> value;
  };

  // Built-in literal patchers.

  template <class T> struct patcher;
  template <class T, size_t i, size_t n> struct tuple_patcher;

  template <class T> struct patcher {
    static void patch(string, T&);
  };

  template <> struct patcher<unit_t> {
    static void patch(std::string, unit_t&) {}
  };

  template <> struct patcher<bool> {
    static void patch(string s, bool& b) {
      qi::parse(begin(s), end(s), qi::bool_[([&b] (bool q) { b = q; })]);
    }
  };

  template <> struct patcher<int> {
    static void patch(string s, int& i) {
      qi::parse(begin(s), end(s), qi::int_[([&i] (int j) { i = j; })]);
    }
  };

  template <> struct patcher<long> {
    static void patch(string s, long& i) {
      qi::parse(begin(s), end(s), qi::long_[([&i] (int j) { i = j; })]);
    }
  };

  template <> struct patcher<double> {
    static void patch(string s, double& d) {
      qi::parse(begin(s), end(s), qi::double_[([&d] (double f) { d = f; })]);
    }
  };

  template <> struct patcher<K3::base_string> {
    static void patch(string s, K3::base_string st) {
      string s2(st.c_str());
      patch(s, s2);
    }
  };

  template <> struct patcher<string> {
    static void patch(string s, string& t) {
      string r;

      if (qi::parse(begin(s), end(s), ('"' >> *(('\\' >> qi::char_) | (qi::char_ - '"')) >> '"'), r)) {
        t = r;
      } else if
        (qi::parse(begin(s), end(s), ('\'' >> *(('\\' >> qi::char_) | (qi::char_ - '\'')) >> '\''), r)) {
        t = r;
      }
    }
  };

  template <> struct patcher<unsigned short> {
    static void patch(string s, unsigned short& u) {
      qi::parse(std::begin(s), std::end(s), qi::ushort_, u);
    }
  };

  template <> struct patcher<boost::asio::ip::address> {
    static void patch(string s, boost::asio::ip::address& a) {
      a = boost::asio::ip::address::from_string(s);
    }
  };

  template <class T> struct patcher<shared_ptr<T>> {
    static void patch(string s, shared_ptr<T> p) {
      shallow<string::iterator> _shallow;

      shared_ptr<T> tp = make_shared<T>(T());

      qi::rule<string::iterator, qi::space_type> ind_rule
        = qi::lit("ind") >> _shallow[([&tp] (string t) { patcher<T>::patch(t, *tp); })];
      qi::rule<string::iterator, qi::space_type> opt_rule
        = qi::lit("none")[([&p, &tp] () { tp = p = nullptr; })]
        | qi::lit("some") >> _shallow[([&tp] (string t) { patcher<T>::patch(t, *tp); })];

      qi::phrase_parse(begin(s), end(s), ind_rule | opt_rule, qi::space);

      if (tp) {
        p = tp;
      }
    }
  };

  template <class T> struct patcher<shared_ptr<list<T>>> {
    static void patch(string s, shared_ptr<list<T>>& p) {
      shallow<string::iterator> _shallow;
      list<T> lp;
      qi::rule<string::iterator, qi::space_type> item_rule
        = _shallow[([&lp] (string t) { lp.push_back(T()); patcher<T>::patch(t, lp.back()); })];

      qi::rule<string::iterator, qi::space_type> list_rule = '[' >> (item_rule % ',') >> ']';

      if (qi::phrase_parse(begin(s), end(s), list_rule, qi::space)) {
        p = make_shared<list<T>>(lp);
      }
    }
  };

  template <class ... Ts> struct patcher<tuple<Ts...>> {
    static void patch(string s, tuple<Ts...>& t) {
      list<string> v;
      shallow<string::iterator> _shallow;

      qi::rule<string::iterator, qi::space_type, list<string>()> tuple_rule = '(' >> (_shallow % ',') >> ')';

      qi::rule<string::iterator, qi::space_type, string()> ip_rule = qi::raw[(qi::int_ % '.')];
      qi::rule<string::iterator, qi::space_type, string()> port_rule = qi::raw[qi::int_];
      qi::rule<string::iterator, qi::space_type, list<string>()> address_rule
        = '<' >> ip_rule >> ':' >> port_rule >> '>';

      qi::phrase_parse(begin(s), end(s), tuple_rule | address_rule, qi::space, v);
      tuple_patcher<tuple<Ts...>, 0, sizeof...(Ts)>::patch(v, t);
    }
  };

  template <class T, size_t i> struct tuple_patcher<T, i, i> {
    static void patch(list<string>&, T&) {}
  };

  template <class T, size_t i, size_t n> struct tuple_patcher {
    static void patch(list<string>& v, T& t) {
      if (v.empty()) {
        return;
      }

      patcher<typename std::tuple_element<i, T>::type>::patch(v.front(), std::get<i>(t));

      v.pop_front();
      tuple_patcher<T, i + 1, n>::patch(v, t);
    }
  };

  template <template <class> class C, class E> struct collection_patcher {
    static void patch(string s, C<E>& c) {
      shared_ptr<list<E>> tmp_dsp = nullptr;
      patcher<shared_ptr<list<E>>>::patch(s, tmp_dsp);

      if (tmp_dsp) {
        C<E> new_c;
        for (E e: *tmp_dsp) {
          new_c.insert(e);
        }

        c = new_c;
      }
    }
  };

  map<string, string> parse_bindings(string s);

  template <class T>
  void do_patch(string s, T& t) {
    patcher<T>::patch(s, t);
  }

  void match_patchers(map<string, string>& m, map<string, std::function<void(string)>>& f);

  string preprocess_argv(int argc, char** argv);
}

#endif
<|endoftext|>


<commit_before>//
// Description: Widget that local variables of the gdb inferior
//
// Copyright (c) 2010 Kåre Särs <kare.sars@iki.fi>
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Library General Public
//  License version 2 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
//  Library General Public License for more details.
//
//  You should have received a copy of the GNU Library General Public License
//  along with this library; see the file COPYING.LIB.  If not, write to
//  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
//  Boston, MA 02110-1301, USA.

#include "localsview.h"
#include <QLabel>
#include <QDebug>
#include <klocalizedstring.h>

LocalsView::LocalsView(QWidget *parent)
:   QTreeWidget(parent), m_allAdded(true)
{
    QStringList headers;
    headers << i18n("Symbol");
    headers << i18n("Value");
    setHeaderLabels(headers);
    setAutoScroll(false);
}

LocalsView::~LocalsView()
{
}

void LocalsView::showEvent(QShowEvent *)
{
    emit localsVisible(true);
}

void LocalsView::hideEvent(QHideEvent *)
{
    emit localsVisible(false);
}

void LocalsView::createWrappedItem(QTreeWidgetItem *parent, const QString &name, const QString &value)
{
    QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList(name));
    QLabel *label = new QLabel(value);
    label->setWordWrap(true);
    setItemWidget(item, 1, label);
    item->setData(1, Qt::UserRole, value);
}

void LocalsView::createWrappedItem(QTreeWidget *parent, const QString &name, const QString &value)
{
    QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList(name));
    QLabel *label = new QLabel(value);
    label->setWordWrap(true);
    setItemWidget(item, 1, label);
}

void LocalsView::addLocal(const QString &vString)
{
    static QRegExp isValue(QStringLiteral("(\\S*)\\s=\\s(.*)"));
    static QRegExp isStruct(QStringLiteral("\\{\\S*\\s=\\s.*"));
    static QRegExp isStartPartial(QStringLiteral("\\S*\\s=\\s\\S*\\s=\\s\\{"));
    static QRegExp isPrettyQList(QStringLiteral("\\s*\\[\\S*\\]\\s=\\s\\S*"));
    static QRegExp isPrettyValue(QStringLiteral("(\\S*)\\s=\\s(\\S*)\\s=\\s(.*)"));
    static QRegExp isThisValue(QStringLiteral("\\$\\d+"));

    if (m_allAdded) {
        clear();
        m_allAdded = false;
    }

    if (vString.isEmpty()) {
        m_allAdded = true;
        return;
    }
    if (isStartPartial.exactMatch(vString)) {
        m_local = vString;
        return;
    }
    if (isPrettyQList.exactMatch(vString)) {
        m_local += vString.trimmed();
        if (m_local.endsWith(QLatin1Char(','))) m_local += QLatin1Char(' ');
        return;
    }
    if (vString == QLatin1String("}")) {
        m_local += vString;
    }

    QStringList symbolAndValue;
    QString value;

    if (m_local.isEmpty()) {
        if (vString == QLatin1String("No symbol table info available.")) {
            return; /* this is not an error */
        }
        if (!isValue.exactMatch(vString)) {
            qDebug() << "Could not parse:" << vString;
            return;
        }
        symbolAndValue << isValue.cap(1);
        // check out for "print *this"
        if (isThisValue.exactMatch(symbolAndValue[0])) {
            symbolAndValue[0] = QLatin1String("*this");
        }
        value = isValue.cap(2);
    }
    else {
        if (!isPrettyValue.exactMatch(m_local)) {
            qDebug() << "Could not parse:" << m_local;
            m_local.clear();
            return;
        }
        symbolAndValue << isPrettyValue.cap(1) << isPrettyValue.cap(2);
        value = isPrettyValue.cap(3);
    }

    QTreeWidgetItem *item;
    if (value[0] == QLatin1Char('{')) {
        if (value[1] == QLatin1Char('{')) {
            item = new QTreeWidgetItem(this, symbolAndValue);
            addArray(item, value.mid(1, value.size()-2));
        }
        else {
            if (isStruct.exactMatch(value)) {
                item = new QTreeWidgetItem(this, symbolAndValue);
                addStruct(item, value.mid(1, value.size()-2));
            }
            else {
                createWrappedItem(this, symbolAndValue[0], value);
            }
        }
    }
    else {
        createWrappedItem(this, symbolAndValue[0], value);
    }

    m_local.clear();
}

void LocalsView::addStruct(QTreeWidgetItem *parent, const QString &vString)
{
    static QRegExp isArray(QStringLiteral("\\{\\.*\\s=\\s.*"));
    static QRegExp isStruct(QStringLiteral("\\.*\\s=\\s.*"));
    QTreeWidgetItem *item;
    QStringList symbolAndValue;
    QString subValue;
    int start = 0;
    int end;
    while (start < vString.size()) {
        // Symbol
        symbolAndValue.clear();
        end = vString.indexOf(QStringLiteral(" = "), start);
        if (end < 0) {
            // error situation -> bail out
            createWrappedItem(parent, QString(), vString.right(start));
            break;
        }
        symbolAndValue << vString.mid(start, end-start);
        //qDebug() << symbolAndValue;
        // Value
        start = end + 3;
        end = start;
        if (vString[start] == QLatin1Char('{')) {
            start++;
            end++;
            int count = 1;
            bool inComment = false;
            // search for the matching }
            while(end < vString.size()) {
                if (!inComment) {
                    if (vString[end] == QLatin1Char('"')) inComment = true;
                    else if (vString[end] == QLatin1Char('}')) count--;
                    else if (vString[end] == QLatin1Char('{')) count++;
                    if (count == 0) break;
                }
                else {
                    if ((vString[end] == QLatin1Char('"')) && (vString[end-1] != QLatin1Char('\\'))) {
                        inComment = false;
                    }
                }
                end++;
            }
            subValue = vString.mid(start, end-start);
            if (isArray.exactMatch(subValue)) {
                item = new QTreeWidgetItem(parent, symbolAndValue);
                addArray(item, subValue);
            }
            else if (isStruct.exactMatch(subValue)) {
                item = new QTreeWidgetItem(parent, symbolAndValue);
                addStruct(item, subValue);
            }
            else {
                createWrappedItem(parent, symbolAndValue[0], vString.mid(start, end-start));
            }
            start = end + 3; // },_
        }
        else {
            // look for the end of the value in the vString
            bool inComment = false;
            while(end < vString.size()) {
                if (!inComment) {
                    if (vString[end] == QLatin1Char('"')) inComment = true;
                    else if (vString[end] == QLatin1Char(',')) break;
                }
                else {
                    if ((vString[end] == QLatin1Char('"')) && (vString[end-1] != QLatin1Char('\\'))) {
                        inComment = false;
                    }
                }
                end++;
            }
            createWrappedItem(parent, symbolAndValue[0], vString.mid(start, end-start));
            start = end + 2; // ,_
        }
    }
}

void LocalsView::addArray(QTreeWidgetItem *parent, const QString &vString)
{
    // getting here we have this kind of string:
    // "{...}" or "{...}, {...}" or ...
    QTreeWidgetItem *item;
    int count = 1;
    bool inComment = false;
    int index = 0;
    int start = 1;
    int end = 1;

    while (end < vString.size()) {
        if (!inComment) {
            if (vString[end] == QLatin1Char('"')) inComment = true;
            else if (vString[end] == QLatin1Char('}')) count--;
            else if (vString[end] == QLatin1Char('{')) count++;
            if (count == 0) {
                QStringList name;
                name << QStringLiteral("[%1]").arg(index);
                index++;
                item = new QTreeWidgetItem(parent, name);
                addStruct(item, vString.mid(start, end-start));
                end += 4; // "}, {"
                start = end;
                count = 1;
            }
        }
        else {
            if ((vString[end] == QLatin1Char('"')) && (vString[end-1] != QLatin1Char('\\'))) {
                inComment = false;
            }
        }
        end++;
    }
}

<commit_msg>Fix crash on unexpected gdb output<commit_after>//
// Description: Widget that local variables of the gdb inferior
//
// Copyright (c) 2010 Kåre Särs <kare.sars@iki.fi>
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Library General Public
//  License version 2 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
//  Library General Public License for more details.
//
//  You should have received a copy of the GNU Library General Public License
//  along with this library; see the file COPYING.LIB.  If not, write to
//  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
//  Boston, MA 02110-1301, USA.

#include "localsview.h"
#include <QLabel>
#include <QDebug>
#include <klocalizedstring.h>

LocalsView::LocalsView(QWidget *parent)
:   QTreeWidget(parent), m_allAdded(true)
{
    QStringList headers;
    headers << i18n("Symbol");
    headers << i18n("Value");
    setHeaderLabels(headers);
    setAutoScroll(false);
}

LocalsView::~LocalsView()
{
}

void LocalsView::showEvent(QShowEvent *)
{
    emit localsVisible(true);
}

void LocalsView::hideEvent(QHideEvent *)
{
    emit localsVisible(false);
}

void LocalsView::createWrappedItem(QTreeWidgetItem *parent, const QString &name, const QString &value)
{
    QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList(name));
    QLabel *label = new QLabel(value);
    label->setWordWrap(true);
    setItemWidget(item, 1, label);
    item->setData(1, Qt::UserRole, value);
}

void LocalsView::createWrappedItem(QTreeWidget *parent, const QString &name, const QString &value)
{
    QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList(name));
    QLabel *label = new QLabel(value);
    label->setWordWrap(true);
    setItemWidget(item, 1, label);
}

void LocalsView::addLocal(const QString &vString)
{
    static QRegExp isValue(QStringLiteral("(\\S*)\\s=\\s(.*)"));
    static QRegExp isStruct(QStringLiteral("\\{\\S*\\s=\\s.*"));
    static QRegExp isStartPartial(QStringLiteral("\\S*\\s=\\s\\S*\\s=\\s\\{"));
    static QRegExp isPrettyQList(QStringLiteral("\\s*\\[\\S*\\]\\s=\\s\\S*"));
    static QRegExp isPrettyValue(QStringLiteral("(\\S*)\\s=\\s(\\S*)\\s=\\s(.*)"));
    static QRegExp isThisValue(QStringLiteral("\\$\\d+"));

    if (m_allAdded) {
        clear();
        m_allAdded = false;
    }

    if (vString.isEmpty()) {
        m_allAdded = true;
        return;
    }
    if (isStartPartial.exactMatch(vString)) {
        m_local = vString;
        return;
    }
    if (isPrettyQList.exactMatch(vString)) {
        m_local += vString.trimmed();
        if (m_local.endsWith(QLatin1Char(','))) m_local += QLatin1Char(' ');
        return;
    }
    if (vString == QLatin1String("}")) {
        m_local += vString;
    }

    QStringList symbolAndValue;
    QString value;

    if (m_local.isEmpty()) {
        if (vString == QLatin1String("No symbol table info available.")) {
            return; /* this is not an error */
        }
        if (!isValue.exactMatch(vString)) {
            qDebug() << "Could not parse:" << vString;
            return;
        }
        symbolAndValue << isValue.cap(1);
        // check out for "print *this"
        if (isThisValue.exactMatch(symbolAndValue[0])) {
            symbolAndValue[0] = QLatin1String("*this");
        }
        value = isValue.cap(2);
    }
    else {
        if (!isPrettyValue.exactMatch(m_local)) {
            qDebug() << "Could not parse:" << m_local;
            m_local.clear();
            return;
        }
        symbolAndValue << isPrettyValue.cap(1) << isPrettyValue.cap(2);
        value = isPrettyValue.cap(3);
    }

    QTreeWidgetItem *item;
    if (value[0] == QLatin1Char('{')) {
        if (value[1] == QLatin1Char('{')) {
            item = new QTreeWidgetItem(this, symbolAndValue);
            addArray(item, value.mid(1, value.size()-2));
        }
        else {
            if (isStruct.exactMatch(value)) {
                item = new QTreeWidgetItem(this, symbolAndValue);
                addStruct(item, value.mid(1, value.size()-2));
            }
            else {
                createWrappedItem(this, symbolAndValue[0], value);
            }
        }
    }
    else {
        createWrappedItem(this, symbolAndValue[0], value);
    }

    m_local.clear();
}

void LocalsView::addStruct(QTreeWidgetItem *parent, const QString &vString)
{
    static QRegExp isArray(QStringLiteral("\\{\\.*\\s=\\s.*"));
    static QRegExp isStruct(QStringLiteral("\\.*\\s=\\s.*"));
    QTreeWidgetItem *item;
    QStringList symbolAndValue;
    QString subValue;
    int start = 0;
    int end;
    while (start < vString.size()) {
        // Symbol
        symbolAndValue.clear();
        end = vString.indexOf(QStringLiteral(" = "), start);
        if (end < 0) {
            // error situation -> bail out
            createWrappedItem(parent, QString(), vString.right(start));
            break;
        }
        symbolAndValue << vString.mid(start, end-start);
        //qDebug() << symbolAndValue;
        // Value
        start = end + 3;
        end = start;
        if (start < 0 || start >= vString.size()) {
            qDebug() << vString << start;
            break;
        }
        if (vString[start] == QLatin1Char('{')) {
            start++;
            end++;
            int count = 1;
            bool inComment = false;
            // search for the matching }
            while(end < vString.size()) {
                if (!inComment) {
                    if (vString[end] == QLatin1Char('"')) inComment = true;
                    else if (vString[end] == QLatin1Char('}')) count--;
                    else if (vString[end] == QLatin1Char('{')) count++;
                    if (count == 0) break;
                }
                else {
                    if ((vString[end] == QLatin1Char('"')) && (vString[end-1] != QLatin1Char('\\'))) {
                        inComment = false;
                    }
                }
                end++;
            }
            subValue = vString.mid(start, end-start);
            if (isArray.exactMatch(subValue)) {
                item = new QTreeWidgetItem(parent, symbolAndValue);
                addArray(item, subValue);
            }
            else if (isStruct.exactMatch(subValue)) {
                item = new QTreeWidgetItem(parent, symbolAndValue);
                addStruct(item, subValue);
            }
            else {
                createWrappedItem(parent, symbolAndValue[0], vString.mid(start, end-start));
            }
            start = end + 3; // },_
        }
        else {
            // look for the end of the value in the vString
            bool inComment = false;
            while(end < vString.size()) {
                if (!inComment) {
                    if (vString[end] == QLatin1Char('"')) inComment = true;
                    else if (vString[end] == QLatin1Char(',')) break;
                }
                else {
                    if ((vString[end] == QLatin1Char('"')) && (vString[end-1] != QLatin1Char('\\'))) {
                        inComment = false;
                    }
                }
                end++;
            }
            createWrappedItem(parent, symbolAndValue[0], vString.mid(start, end-start));
            start = end + 2; // ,_
        }
    }
}

void LocalsView::addArray(QTreeWidgetItem *parent, const QString &vString)
{
    // getting here we have this kind of string:
    // "{...}" or "{...}, {...}" or ...
    QTreeWidgetItem *item;
    int count = 1;
    bool inComment = false;
    int index = 0;
    int start = 1;
    int end = 1;

    while (end < vString.size()) {
        if (!inComment) {
            if (vString[end] == QLatin1Char('"')) inComment = true;
            else if (vString[end] == QLatin1Char('}')) count--;
            else if (vString[end] == QLatin1Char('{')) count++;
            if (count == 0) {
                QStringList name;
                name << QStringLiteral("[%1]").arg(index);
                index++;
                item = new QTreeWidgetItem(parent, name);
                addStruct(item, vString.mid(start, end-start));
                end += 4; // "}, {"
                start = end;
                count = 1;
            }
        }
        else {
            if ((vString[end] == QLatin1Char('"')) && (vString[end-1] != QLatin1Char('\\'))) {
                inComment = false;
            }
        }
        end++;
    }
}

<|endoftext|>