<commit_before>/*************************************************************************
 *
 *  $RCSfile: VCollection.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: oj $ $Date: 2001-02-23 14:55:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>

#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_DESCRIPTOR_HXX_
#include "connectivity/sdbcx/VDescriptor.hxx"
#endif
#ifndef _COMPHELPER_ENUMHELPER_HXX_
#include <comphelper/enumhelper.hxx>
#endif
#ifndef _COMPHELPER_CONTAINER_HXX_
#include <comphelper/container.hxx>
#endif

using namespace connectivity::sdbcx;
using namespace connectivity;
using namespace comphelper;
using namespace ::cppu;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::util;

IMPLEMENT_SERVICE_INFO(OCollection,"com.sun.star.sdbcx.VContainer" , "com.sun.star.sdbcx.Container")

OCollection::OCollection(::cppu::OWeakObject& _rParent,sal_Bool _bCase, ::osl::Mutex& _rMutex,const ::std::vector< ::rtl::OUString> &_rVector)
                     : m_rParent(_rParent)
                     ,m_rMutex(_rMutex)
                     ,m_aContainerListeners(_rMutex)
                     ,m_aRefreshListeners(_rMutex)
                     ,m_aNameMap(_bCase)
{
    for(::std::vector< ::rtl::OUString>::const_iterator i=_rVector.begin(); i != _rVector.end();++i)
        m_aElements.push_back(m_aNameMap.insert(m_aNameMap.begin(), ObjectMap::value_type(*i,::com::sun::star::uno::WeakReference< ::com::sun::star::container::XNamed >())));
}
// -------------------------------------------------------------------------
OCollection::~OCollection()
{
}

// -------------------------------------------------------------------------
void OCollection::clear_NoDispose()
{
    ::osl::MutexGuard aGuard(m_rMutex);
    m_aNameMap.clear();
    m_aElements.clear();
}

// -------------------------------------------------------------------------
void OCollection::disposing(void)
{
    m_aContainerListeners.disposeAndClear(EventObject(static_cast<XWeak*>(this)));
    m_aRefreshListeners.disposeAndClear(EventObject(static_cast<XWeak*>(this)));

    ::osl::MutexGuard aGuard(m_rMutex);
    for( ObjectIter aIter = m_aNameMap.begin(); aIter != m_aNameMap.end(); ++aIter)
    {
        if((*aIter).second.is())
        {
            Reference< XComponent > xComp2((*aIter).second, UNO_QUERY);
            if(xComp2.is())
                xComp2->dispose();

            (*aIter).second = Reference< XNamed >();
        }
    }
    m_aElements.clear();
    m_aNameMap.clear();
}
// -------------------------------------------------------------------------
Any SAL_CALL OCollection::getByIndex( sal_Int32 Index ) throw(IndexOutOfBoundsException, WrappedTargetException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    if (Index < 0 || Index >= getCount())
        throw IndexOutOfBoundsException(::rtl::OUString::valueOf(Index),*this);

    ObjectIter aIter = m_aElements[Index];
    Reference< XNamed > xName = (*aIter).second;
    if(!(*aIter).second.is())
    {
        xName = createObject((*aIter).first);
        (*aIter).second = xName;
    }

    return makeAny( Reference< XPropertySet >(xName,UNO_QUERY));
}
// -------------------------------------------------------------------------
Any SAL_CALL OCollection::getByName( const ::rtl::OUString& aName ) throw(NoSuchElementException, WrappedTargetException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);

    ObjectIter aIter = m_aNameMap.find(aName);
    if(aIter == m_aNameMap.end())
        throw NoSuchElementException(aName,*this);
    Reference< XNamed > xName = (*aIter).second;
    if(!(*aIter).second.is())
    {
        xName = createObject(aIter->first);
        (*aIter).second = xName;
    }

    return makeAny( Reference< XPropertySet >(xName,UNO_QUERY));
}
// -------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OCollection::getElementNames(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    sal_Int32 nLen = getCount();
    Sequence< ::rtl::OUString > aNameList(nLen);

    sal_Int32 i=0;
    ::rtl::OUString* pStringArray = aNameList.getArray();
    //  for( ::std::map< ::rtl::OUString, Object_BASE, ::comphelper::UStringLess> ::const_iterator aIter = m_aNameMap.begin(); aIter != m_aNameMap.end(); ++aIter)
    for(::std::vector< ObjectIter >::const_iterator aIter = m_aElements.begin(); aIter != m_aElements.end();++aIter)
        pStringArray[i++] = (*aIter)->first;

    return aNameList;
}
// -------------------------------------------------------------------------
void SAL_CALL OCollection::refresh(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    for( ::std::map< ::rtl::OUString, Object_BASE, ::comphelper::UStringLess>::iterator aIter = m_aNameMap.begin(); aIter != m_aNameMap.end(); ++aIter)
    {
        if((*aIter).second.is())
        {
            Reference< XComponent > xComp2((*aIter).second, UNO_QUERY);
            if(xComp2.is())
                xComp2->dispose();

            (*aIter).second = Reference< XNamed >();
        }
    }
    m_aNameMap.clear();
    m_aElements.clear();

    impl_refresh();
    EventObject aEvt(static_cast<XWeak*>(this));
    NOTIFY_LISTENERS(m_aRefreshListeners, XRefreshListener, refreshed, aEvt);
}
// -------------------------------------------------------------------------
// XDataDescriptorFactory
Reference< XPropertySet > SAL_CALL OCollection::createDataDescriptor(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);

    return createEmptyObject();
}
// -------------------------------------------------------------------------
// XAppend
void SAL_CALL OCollection::appendByDescriptor( const Reference< XPropertySet >& descriptor ) throw(SQLException, ElementExistException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);

    Reference< XNamed > xName(descriptor,UNO_QUERY);
    if(xName.is())
    {
        if(m_aNameMap.find(xName->getName()) != m_aNameMap.end())
            throw ElementExistException(xName->getName(),*this);

        Reference<XUnoTunnel> xTunnel(descriptor,UNO_QUERY);
        if(xTunnel.is())
        {
            ODescriptor* pDescriptor = (ODescriptor*)xTunnel->getSomething(ODescriptor::getUnoTunnelImplementationId());
            if(pDescriptor)
                pDescriptor->setNew(sal_False);
        }
        m_aElements.push_back(m_aNameMap.insert(m_aNameMap.begin(), ObjectMap::value_type(xName->getName(),WeakReference< XNamed >(xName))));
        // notify our container listeners
        ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(xName->getName()), makeAny(xName), Any());
        OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
        while (aListenerLoop.hasMoreElements())
            static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent);
    }
}
// -------------------------------------------------------------------------
// XDrop
void SAL_CALL OCollection::dropByName( const ::rtl::OUString& elementName ) throw(SQLException, NoSuchElementException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);

    ObjectMap::iterator aIter = m_aNameMap.find(elementName);
    if( aIter == m_aNameMap.end())
        throw NoSuchElementException(elementName,*this);

    for(::std::vector< ObjectIter >::size_type i=0;i<m_aElements.size();++i)
    {
        if(m_aElements[i] == aIter)
        {
            m_aElements.erase(m_aElements.begin()+i);
            m_aNameMap.erase(aIter);
            break; // no duplicates possible
        }
    }
    // notify our container listeners
    ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(elementName), Any(), Any());
        // note that xExistent may be empty, in case somebody removed the data source while it is not alive at this moment
    OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
    while (aListenerLoop.hasMoreElements())
        static_cast<XContainerListener*>(aListenerLoop.next())->elementRemoved(aEvent);
}
// -------------------------------------------------------------------------
void SAL_CALL OCollection::dropByIndex( sal_Int32 index ) throw(SQLException, IndexOutOfBoundsException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    if(index <0 || index > getCount())
        throw IndexOutOfBoundsException(::rtl::OUString(),*this);

    ::rtl::OUString elementName = m_aElements[index]->first;
    m_aNameMap.erase(m_aElements[index]);
    m_aElements.erase(m_aElements.begin()+index);
    // notify our container listeners
    ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(elementName), Any(), Any());
        // note that xExistent may be empty, in case somebody removed the data source while it is not alive at this moment
    OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
    while (aListenerLoop.hasMoreElements())
        static_cast<XContainerListener*>(aListenerLoop.next())->elementRemoved(aEvent);
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OCollection::findColumn( const ::rtl::OUString& columnName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    ObjectIter aIter = m_aNameMap.find(columnName);
    if(aIter == m_aNameMap.end())
        throw ::com::sun::star::sdbc::SQLException();

    return m_aElements.size() - (m_aElements.end() - ::std::find(m_aElements.begin(),m_aElements.end(),aIter)) +1; // because cloumns start at one
}
// -------------------------------------------------------------------------
Reference< XEnumeration > SAL_CALL OCollection::createEnumeration(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    return new OEnumerationByIndex( static_cast< XIndexAccess*>(this));
}
// -----------------------------------------------------------------------------
void SAL_CALL OCollection::addContainerListener( const Reference< XContainerListener >& _rxListener ) throw(RuntimeException)
{
    m_aContainerListeners.addInterface(_rxListener);
}

//------------------------------------------------------------------------------
void SAL_CALL OCollection::removeContainerListener( const Reference< XContainerListener >& _rxListener ) throw(RuntimeException)
{
    m_aContainerListeners.removeInterface(_rxListener);
}
// -----------------------------------------------------------------------------

<commit_msg>#84625# dispose object when dropping<commit_after>/*************************************************************************
 *
 *  $RCSfile: VCollection.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: oj $ $Date: 2001-03-12 13:51:27 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>

#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_DESCRIPTOR_HXX_
#include "connectivity/sdbcx/VDescriptor.hxx"
#endif
#ifndef _COMPHELPER_ENUMHELPER_HXX_
#include <comphelper/enumhelper.hxx>
#endif
#ifndef _COMPHELPER_CONTAINER_HXX_
#include <comphelper/container.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif

using namespace connectivity::sdbcx;
using namespace connectivity;
using namespace comphelper;
using namespace ::cppu;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::util;

IMPLEMENT_SERVICE_INFO(OCollection,"com.sun.star.sdbcx.VContainer" , "com.sun.star.sdbcx.Container")

OCollection::OCollection(::cppu::OWeakObject& _rParent,sal_Bool _bCase, ::osl::Mutex& _rMutex,const ::std::vector< ::rtl::OUString> &_rVector)
                     : m_rParent(_rParent)
                     ,m_rMutex(_rMutex)
                     ,m_aContainerListeners(_rMutex)
                     ,m_aRefreshListeners(_rMutex)
                     ,m_aNameMap(_bCase)
{
    for(::std::vector< ::rtl::OUString>::const_iterator i=_rVector.begin(); i != _rVector.end();++i)
        m_aElements.push_back(m_aNameMap.insert(m_aNameMap.begin(), ObjectMap::value_type(*i,::com::sun::star::uno::WeakReference< ::com::sun::star::container::XNamed >())));
}
// -------------------------------------------------------------------------
OCollection::~OCollection()
{
}

// -------------------------------------------------------------------------
void OCollection::clear_NoDispose()
{
    ::osl::MutexGuard aGuard(m_rMutex);
    m_aNameMap.clear();
    m_aElements.clear();
}

// -------------------------------------------------------------------------
void OCollection::disposing(void)
{
    m_aContainerListeners.disposeAndClear(EventObject(static_cast<XWeak*>(this)));
    m_aRefreshListeners.disposeAndClear(EventObject(static_cast<XWeak*>(this)));

    ::osl::MutexGuard aGuard(m_rMutex);
    for( ObjectIter aIter = m_aNameMap.begin(); aIter != m_aNameMap.end(); ++aIter)
    {
        if((*aIter).second.is())
        {
            ::comphelper::disposeComponent(aIter->second);
            (*aIter).second = Reference< XNamed >();
        }
    }
    m_aElements.clear();
    m_aNameMap.clear();
}
// -------------------------------------------------------------------------
Any SAL_CALL OCollection::getByIndex( sal_Int32 Index ) throw(IndexOutOfBoundsException, WrappedTargetException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    if (Index < 0 || Index >= getCount())
        throw IndexOutOfBoundsException(::rtl::OUString::valueOf(Index),*this);

    ObjectIter aIter = m_aElements[Index];
    Reference< XNamed > xName = (*aIter).second;
    if(!(*aIter).second.is())
    {
        xName = createObject((*aIter).first);
        (*aIter).second = xName;
    }

    return makeAny( Reference< XPropertySet >(xName,UNO_QUERY));
}
// -------------------------------------------------------------------------
Any SAL_CALL OCollection::getByName( const ::rtl::OUString& aName ) throw(NoSuchElementException, WrappedTargetException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);

    ObjectIter aIter = m_aNameMap.find(aName);
    if(aIter == m_aNameMap.end())
        throw NoSuchElementException(aName,*this);
    Reference< XNamed > xName = (*aIter).second;
    if(!(*aIter).second.is())
    {
        xName = createObject(aIter->first);
        (*aIter).second = xName;
    }

    return makeAny( Reference< XPropertySet >(xName,UNO_QUERY));
}
// -------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OCollection::getElementNames(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    sal_Int32 nLen = getCount();
    Sequence< ::rtl::OUString > aNameList(nLen);

    sal_Int32 i=0;
    ::rtl::OUString* pStringArray = aNameList.getArray();
    //  for( ::std::map< ::rtl::OUString, Object_BASE, ::comphelper::UStringLess> ::const_iterator aIter = m_aNameMap.begin(); aIter != m_aNameMap.end(); ++aIter)
    for(::std::vector< ObjectIter >::const_iterator aIter = m_aElements.begin(); aIter != m_aElements.end();++aIter)
        pStringArray[i++] = (*aIter)->first;

    return aNameList;
}
// -------------------------------------------------------------------------
void SAL_CALL OCollection::refresh(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    for( ::std::map< ::rtl::OUString, Object_BASE, ::comphelper::UStringLess>::iterator aIter = m_aNameMap.begin(); aIter != m_aNameMap.end(); ++aIter)
    {
        if((*aIter).second.is())
        {
            ::comphelper::disposeComponent(aIter->second);
            (*aIter).second = Reference< XNamed >();
        }
    }
    m_aNameMap.clear();
    m_aElements.clear();

    impl_refresh();
    EventObject aEvt(static_cast<XWeak*>(this));
    NOTIFY_LISTENERS(m_aRefreshListeners, XRefreshListener, refreshed, aEvt);
}
// -------------------------------------------------------------------------
// XDataDescriptorFactory
Reference< XPropertySet > SAL_CALL OCollection::createDataDescriptor(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);

    return createEmptyObject();
}
// -------------------------------------------------------------------------
// XAppend
void SAL_CALL OCollection::appendByDescriptor( const Reference< XPropertySet >& descriptor ) throw(SQLException, ElementExistException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);

    Reference< XNamed > xName(descriptor,UNO_QUERY);
    if(xName.is())
    {
        if(m_aNameMap.find(xName->getName()) != m_aNameMap.end())
            throw ElementExistException(xName->getName(),*this);

        Reference<XUnoTunnel> xTunnel(descriptor,UNO_QUERY);
        if(xTunnel.is())
        {
            ODescriptor* pDescriptor = (ODescriptor*)xTunnel->getSomething(ODescriptor::getUnoTunnelImplementationId());
            if(pDescriptor)
                pDescriptor->setNew(sal_False);
        }
        m_aElements.push_back(m_aNameMap.insert(m_aNameMap.begin(), ObjectMap::value_type(xName->getName(),WeakReference< XNamed >(xName))));
        // notify our container listeners
        ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(xName->getName()), makeAny(xName), Any());
        OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
        while (aListenerLoop.hasMoreElements())
            static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent);
    }
}
// -------------------------------------------------------------------------
// XDrop
void SAL_CALL OCollection::dropByName( const ::rtl::OUString& elementName ) throw(SQLException, NoSuchElementException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);

    ObjectMap::iterator aIter = m_aNameMap.find(elementName);
    if( aIter == m_aNameMap.end())
        throw NoSuchElementException(elementName,*this);

    for(::std::vector< ObjectIter >::size_type i=0;i<m_aElements.size();++i)
    {
        if(m_aElements[i] == aIter)
        {
            ::comphelper::disposeComponent(aIter->second);

            m_aElements.erase(m_aElements.begin()+i);
            m_aNameMap.erase(aIter);
            break; // no duplicates possible
        }
    }
    // notify our container listeners
    ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(elementName), Any(), Any());
        // note that xExistent may be empty, in case somebody removed the data source while it is not alive at this moment
    OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
    while (aListenerLoop.hasMoreElements())
        static_cast<XContainerListener*>(aListenerLoop.next())->elementRemoved(aEvent);
}
// -------------------------------------------------------------------------
void SAL_CALL OCollection::dropByIndex( sal_Int32 index ) throw(SQLException, IndexOutOfBoundsException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    if(index <0 || index > getCount())
        throw IndexOutOfBoundsException(::rtl::OUString(),*this);

    ::comphelper::disposeComponent(m_aElements[index]->second);
    ::rtl::OUString elementName = m_aElements[index]->first;
    m_aNameMap.erase(m_aElements[index]);
    m_aElements.erase(m_aElements.begin()+index);
    // notify our container listeners
    ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(elementName), Any(), Any());
        // note that xExistent may be empty, in case somebody removed the data source while it is not alive at this moment
    OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
    while (aListenerLoop.hasMoreElements())
        static_cast<XContainerListener*>(aListenerLoop.next())->elementRemoved(aEvent);
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OCollection::findColumn( const ::rtl::OUString& columnName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    ObjectIter aIter = m_aNameMap.find(columnName);
    if(aIter == m_aNameMap.end())
        throw ::com::sun::star::sdbc::SQLException();

    return m_aElements.size() - (m_aElements.end() - ::std::find(m_aElements.begin(),m_aElements.end(),aIter)) +1; // because cloumns start at one
}
// -------------------------------------------------------------------------
Reference< XEnumeration > SAL_CALL OCollection::createEnumeration(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_rMutex);
    return new OEnumerationByIndex( static_cast< XIndexAccess*>(this));
}
// -----------------------------------------------------------------------------
void SAL_CALL OCollection::addContainerListener( const Reference< XContainerListener >& _rxListener ) throw(RuntimeException)
{
    m_aContainerListeners.addInterface(_rxListener);
}

//------------------------------------------------------------------------------
void SAL_CALL OCollection::removeContainerListener( const Reference< XContainerListener >& _rxListener ) throw(RuntimeException)
{
    m_aContainerListeners.removeInterface(_rxListener);
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>// source: ./examples/ex4.cpp
#include <qpp.h>
using namespace qpp;

int main()
{
    cmat rho = st.pb00; // projector onto the Bell state (|00>+|11>)/sqrt(2)
    std::cout << "Initial state:\n";
    std::cout << disp(rho) << std::endl;

    // partial transpose of first subsystem
    cmat rhoTA = ptranspose(rho, {0});
    std::cout << "Eigenvalues of the partial transpose of Bell-0 state are:\n";
    std::cout << disp(transpose(hevals(rhoTA))) << std::endl;

    std::cout << "Measurement channel with 2 Kraus operators:\n";
    std::vector<cmat> Ks {st.pz0, st.pz1}; // 2 Kraus operators
    std::cout << disp(Ks[0]) << "\n    and \n" << disp(Ks[1]) << std::endl;

    std::cout << "Superoperator matrix of the channel:\n";
    std::cout << disp(super(Ks)) << std::endl;

    std::cout << "Choi matrix of the channel:\n";
    std::cout << disp(choi(Ks)) << std::endl;

    // apply the channel onto the first subsystem
    cmat rhoOut = apply(rho, Ks, {0});
    std::cout << "After applying the measurement channel on the first qubit:\n";
    std::cout << disp(rhoOut) << std::endl;

    // take the partial trace over the second subsystem
    cmat rhoA = ptrace(rhoOut, {1});
    std::cout << "After partially tracing down the second subsystem:\n";
    std::cout << disp(rhoA) << std::endl;
}<commit_msg>commit<commit_after>// Quantum operations
// Source: ./examples/ex4.cpp
#include <qpp.h>
using namespace qpp;

int main()
{
    cmat rho = st.pb00; // projector onto the Bell state (|00>+|11>)/sqrt(2)
    std::cout << "Initial state:\n";
    std::cout << disp(rho) << std::endl;

    // partial transpose of first subsystem
    cmat rhoTA = ptranspose(rho, {0});
    std::cout << "Eigenvalues of the partial transpose of Bell-0 state are:\n";
    std::cout << disp(transpose(hevals(rhoTA))) << std::endl;

    std::cout << "Measurement channel with 2 Kraus operators:\n";
    std::vector<cmat> Ks {st.pz0, st.pz1}; // 2 Kraus operators
    std::cout << disp(Ks[0]) << "\n    and \n" << disp(Ks[1]) << std::endl;

    std::cout << "Superoperator matrix of the channel:\n";
    std::cout << disp(super(Ks)) << std::endl;

    std::cout << "Choi matrix of the channel:\n";
    std::cout << disp(choi(Ks)) << std::endl;

    // apply the channel onto the first subsystem
    cmat rhoOut = apply(rho, Ks, {0});
    std::cout << "After applying the measurement channel on the first qubit:\n";
    std::cout << disp(rhoOut) << std::endl;

    // take the partial trace over the second subsystem
    cmat rhoA = ptrace(rhoOut, {1});
    std::cout << "After partially tracing down the second subsystem:\n";
    std::cout << disp(rhoA) << std::endl;
}<|endoftext|>


<commit_before>//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "xsapi/system.h"
#include "local_config.h"
#include "xbox_system_factory.h"
#include "Utils.h"

using namespace std;
using namespace Platform;
using namespace Windows::Storage;
using namespace Windows::Foundation;
using namespace xbox::services;

NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_BEGIN

#if !TV_API
xbox_live_result<void> local_config::read()
{
    std::lock_guard<std::mutex> guard(m_jsonConfigLock);
    if (m_jsonConfig.size() > 0)
    {
        return xbox_live_result<void>();
    }

    Windows::ApplicationModel::Package^ package = Windows::ApplicationModel::Package::Current;
    Windows::Storage::StorageFolder^ installedLocation = package->InstalledLocation;
    string_t configPath = string_t(installedLocation->Path->Data()) + _T("\\xboxservices.config");

    string_t fileData = utils::read_file_to_string(configPath);
    if( !fileData.empty() )
    {
        std::error_code err;
        m_jsonConfig = web::json::value::parse(fileData, err);
        if (!err)
        {
            return xbox_live_result<void>();
        }
        else
        {
            return xbox_live_result<void>(
                std::make_error_code(xbox::services::xbox_live_error_code::invalid_config),
                "Invalid config file"
                );
        }
    }
    else
    {
        return xbox_live_result<void>(
            std::make_error_code(xbox::services::xbox_live_error_code::invalid_config),
            "ERROR: Could not find xboxservices.config"
            );
    }
}

string_t local_config::get_value_from_local_storage(
    _In_ const string_t& name
    )
{
    try
    {
        ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings;

        auto values = localSettings->Values;
        String^ key = ref new String(name.c_str());
        String^ value = nullptr;

        if (values->HasKey(key))
        {
            value = safe_cast<String^>(key);
        }

        if (!value)
        {
            return L"";
        }
        else
        {
            return value->Data();
        }
    }
    catch (Exception^ ex)
    {
        return L"";
    }
}

xbox_live_result<void> local_config::write_value_to_local_storage(_In_ const string_t& name, _In_ const string_t& value)
{
    try
    {
        ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings;

        auto values = localSettings->Values;
        values->Insert(
            ref new Platform::String(name.c_str()),
            dynamic_cast<PropertyValue^>(PropertyValue::CreateString(ref new Platform::String(value.c_str())))
            );
        return xbox_live_result<void>();
    }
    catch (Exception^ ex)
    {
        xbox_live_error_code err = utils::convert_exception_to_xbox_live_error_code();
        return xbox_live_result<void>(err, "write_value_to_local_storage exception");
    }
}

xbox_live_result<void> local_config::delete_value_from_local_storage(
    _In_ const string_t& name
    )
{
    try
    {
        ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings;
        localSettings->Values->Remove(ref new Platform::String(name.c_str()));
        return xbox_live_result<void>();
    }
    catch (Exception^ ex)
    {
        xbox_live_error_code err = utils::convert_exception_to_xbox_live_error_code();
        return xbox_live_result<void>(err, "delete_value_from_local_storage exception");
    }
}

#endif

NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_END

<commit_msg>Changing config location for sidecar builds (#17)<commit_after>//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "xsapi/system.h"
#include "local_config.h"
#include "xbox_system_factory.h"
#include "Utils.h"

using namespace std;
using namespace Platform;
using namespace Windows::Storage;
using namespace Windows::Foundation;
using namespace xbox::services;

NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_BEGIN

#if !TV_API
xbox_live_result<void> local_config::read()
{
    std::lock_guard<std::mutex> guard(m_jsonConfigLock);
    if (m_jsonConfig.size() > 0)
    {
        return xbox_live_result<void>();
    }

#if XSAPI_SIDECAR
    string_t configPath = _T("xboxservices.config");
#else
    Windows::ApplicationModel::Package^ package = Windows::ApplicationModel::Package::Current;
    Windows::Storage::StorageFolder^ installedLocation = package->InstalledLocation;
    string_t configPath = string_t(installedLocation->Path->Data()) + _T("\\xboxservices.config");
#endif

    string_t fileData = utils::read_file_to_string(configPath);
    if( !fileData.empty() )
    {
        std::error_code err;
        m_jsonConfig = web::json::value::parse(fileData, err);
        if (!err)
        {
            return xbox_live_result<void>();
        }
        else
        {
            return xbox_live_result<void>(
                std::make_error_code(xbox::services::xbox_live_error_code::invalid_config),
                "Invalid config file"
                );
        }
    }
    else
    {
        return xbox_live_result<void>(
            std::make_error_code(xbox::services::xbox_live_error_code::invalid_config),
            "ERROR: Could not find xboxservices.config"
            );
    }
}

string_t local_config::get_value_from_local_storage(
    _In_ const string_t& name
    )
{
    try
    {
        ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings;

        auto values = localSettings->Values;
        String^ key = ref new String(name.c_str());
        String^ value = nullptr;

        if (values->HasKey(key))
        {
            value = safe_cast<String^>(key);
        }

        if (!value)
        {
            return L"";
        }
        else
        {
            return value->Data();
        }
    }
    catch (Exception^ ex)
    {
        return L"";
    }
}

xbox_live_result<void> local_config::write_value_to_local_storage(_In_ const string_t& name, _In_ const string_t& value)
{
    try
    {
        ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings;

        auto values = localSettings->Values;
        values->Insert(
            ref new Platform::String(name.c_str()),
            dynamic_cast<PropertyValue^>(PropertyValue::CreateString(ref new Platform::String(value.c_str())))
            );
        return xbox_live_result<void>();
    }
    catch (Exception^ ex)
    {
        xbox_live_error_code err = utils::convert_exception_to_xbox_live_error_code();
        return xbox_live_result<void>(err, "write_value_to_local_storage exception");
    }
}

xbox_live_result<void> local_config::delete_value_from_local_storage(
    _In_ const string_t& name
    )
{
    try
    {
        ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings;
        localSettings->Values->Remove(ref new Platform::String(name.c_str()));
        return xbox_live_result<void>();
    }
    catch (Exception^ ex)
    {
        xbox_live_error_code err = utils::convert_exception_to_xbox_live_error_code();
        return xbox_live_result<void>(err, "delete_value_from_local_storage exception");
    }
}

#endif

NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_END

<|endoftext|>


<commit_before>#include "ScreenBase.h"
#include <kvs/ColorImage>
#include <kvs/OpenGL>
#include <cstdio>

namespace
{

template <typename T>
inline void Flip( T* data, const size_t width, const size_t height, const size_t ncomps )
{
    // NOTE: Gallium softpipe driver doesn't support "upside-down" rendering
    // which would be needed for the OSMESA_Y_UP=TRUE case. Therefore, the
    // rendering pixel data read backed from GPU with glReadPixels need to be
    // flipped. In the current implementation, it is necessary to specify the
    // gallium driver "softpipe" or "llvmpipe" by environment parameter
    // 'KVS_OSMESA_GALLIUM_DRIVER'.
    // e.g.) export KVS_OSMESA_GALLIUM_DRIVER=softpipe
    //
    const char* driver( std::getenv( "KVS_OSMESA_GALLIUM_DRIVER" ) );
    if ( !driver ) return;

    const bool y_down = ( kvs::osmesa::Context::GetYAxisDirection() == 0 );
    if ( std::string( driver ) == "softpipe" && y_down )
    {
        const size_t stride = width * ncomps;

        T* pdata = data;
        const size_t end_line = height / 2;
        for ( size_t i = 0; i < end_line; i++ )
        {
            T* src = pdata + ( i * stride );
            T* dst = pdata + ( ( height - i - 1 ) * stride );
            for ( size_t j = 0; j < stride; j++ )
            {
                std::swap( *src, *dst );
                src++; dst++;
            }
        }
    }
}

}

namespace kvs
{

namespace osmesa
{

ScreenBase::ScreenBase()
{
}

ScreenBase::~ScreenBase()
{
}

kvs::ValueArray<kvs::UInt8> ScreenBase::readbackColorBuffer( GLenum mode ) const
{
    kvs::OpenGL::SetReadBuffer( mode );
    kvs::OpenGL::SetPixelStorageMode( GL_PACK_ALIGNMENT, GLint(1) );

    const size_t width = this->width();
    const size_t height = this->height();
    kvs::ValueArray<kvs::UInt8> buffer( width * height * 4 );
    kvs::OpenGL::ReadPixels( 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data() );
   ::Flip( buffer.data(), width, height, 4 );

    return buffer;
}

kvs::ValueArray<kvs::Real32> ScreenBase::readbackDepthBuffer( GLenum mode ) const
{
    kvs::OpenGL::SetReadBuffer( mode );
    kvs::OpenGL::SetPixelStorageMode( GL_PACK_ALIGNMENT, GLint(1) );

    const size_t width = this->width();
    const size_t height = this->height();
    kvs::ValueArray<kvs::Real32> buffer( width * height );
    kvs::OpenGL::ReadPixels( 0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, buffer.data() );
    ::Flip( buffer.data(), width, height, 1 );

    return buffer;
}

void ScreenBase::create()
{
    // Create OSMesa context
    const GLenum format = OSMESA_RGBA;
    const GLint depth_bits = 24;
    const GLint stencil_bits = 0;
    const GLint accum_bits = 0;
    m_context.create( format, depth_bits, stencil_bits, accum_bits );
    if ( !m_context.isValid() )
    {
        kvsMessageError( "Cannot create OSMesa context." );
        return;
    }

    // Create OSMesa drawing surface
    const GLsizei width = GLsizei( BaseClass::width() );
    const GLsizei height = GLsizei( BaseClass::height() );
    m_surface.create( width, height, format );

    // Bind the context to the surface
    if ( !m_context.makeCurrent( m_surface ) )
    {
        kvsMessageError( "Cannot bind buffer." );
        return;
    }

    // Y coordinates increase downward
    kvs::osmesa::Context::SetYAxisDirectionToDown();

    this->initializeEvent();
}

void ScreenBase::show()
{
    if ( !m_context.isValid() ) { this->create(); }
}

void ScreenBase::redraw()
{
    this->draw();
}

void ScreenBase::draw()
{
    if ( !m_context.isValid() ) { this->create(); }
    this->paintEvent();
}

kvs::ColorImage ScreenBase::capture() const
{
    const size_t width = BaseClass::width();
    const size_t height = BaseClass::height();

    // RGBA to RGB
    const kvs::ValueArray<kvs::UInt8>& buffer = m_surface.buffer();
    kvs::ValueArray<kvs::UInt8> pixels( width * height * 3 );
    for ( size_t i = 0; i < width * height; i++ )
    {
        pixels[ 3 * i + 0 ] = buffer[ 4 * i + 0 ];
        pixels[ 3 * i + 1 ] = buffer[ 4 * i + 1 ];
        pixels[ 3 * i + 2 ] = buffer[ 4 * i + 2 ];
    }

    return kvs::ColorImage( width, height, pixels );
}

} // end of namespace osmesa

} // end of namespace kvs
<commit_msg>Modified.<commit_after>#include "ScreenBase.h"
#include <kvs/ColorImage>
#include <kvs/OpenGL>
#include <cstdio>

namespace
{

template <typename T>
inline void Flip( T* data, const size_t width, const size_t height, const size_t ncomps )
{
    // NOTE: Gallium softpipe driver doesn't support "upside-down" rendering
    // which would be needed for the OSMESA_Y_UP=TRUE case. Therefore, the
    // rendering pixel data read backed from GPU with glReadPixels need to be
    // flipped. In the current implementation, it is necessary to specify the
    // gallium driver "softpipe" or "llvmpipe" by environment parameter
    // 'KVS_OSMESA_GALLIUM_DRIVER'.
    // e.g.) export KVS_OSMESA_GALLIUM_DRIVER=softpipe
    //
    const char* driver( std::getenv( "KVS_OSMESA_GALLIUM_DRIVER" ) );
    if ( !driver ) return;

    const bool y_down = ( kvs::osmesa::Context::GetYAxisDirection() == 0 );
    if ( std::string( driver ) == "softpipe" && y_down )
    {
        const size_t stride = width * ncomps;

        T* pdata = data;
        const size_t end_line = height / 2;
        for ( size_t i = 0; i < end_line; i++ )
        {
            T* src = pdata + ( i * stride );
            T* dst = pdata + ( ( height - i - 1 ) * stride );
            for ( size_t j = 0; j < stride; j++ )
            {
                std::swap( *src, *dst );
                src++; dst++;
            }
        }
    }
}

}

namespace kvs
{

namespace osmesa
{

ScreenBase::ScreenBase()
{
}

ScreenBase::~ScreenBase()
{
}

kvs::ValueArray<kvs::UInt8> ScreenBase::readbackColorBuffer( GLenum mode ) const
{
    kvs::OpenGL::SetReadBuffer( mode );
    kvs::OpenGL::SetPixelStorageMode( GL_PACK_ALIGNMENT, GLint(1) );

    const size_t width = this->width();
    const size_t height = this->height();
    kvs::ValueArray<kvs::UInt8> buffer( width * height * 4 );
    kvs::OpenGL::ReadPixels( 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data() );
    ::Flip( buffer.data(), width, height, 4 );

    return buffer;
}

kvs::ValueArray<kvs::Real32> ScreenBase::readbackDepthBuffer( GLenum mode ) const
{
    kvs::OpenGL::SetReadBuffer( mode );
    kvs::OpenGL::SetPixelStorageMode( GL_PACK_ALIGNMENT, GLint(1) );

    const size_t width = this->width();
    const size_t height = this->height();
    kvs::ValueArray<kvs::Real32> buffer( width * height );
    kvs::OpenGL::ReadPixels( 0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, buffer.data() );
    ::Flip( buffer.data(), width, height, 1 );

    return buffer;
}

void ScreenBase::create()
{
    // Create OSMesa context
    const GLenum format = OSMESA_RGBA;
    const GLint depth_bits = 24;
    const GLint stencil_bits = 0;
    const GLint accum_bits = 0;
    m_context.create( format, depth_bits, stencil_bits, accum_bits );
    if ( !m_context.isValid() )
    {
        kvsMessageError() << "Cannot create OSMesa context." << std::endl;
        return;
    }

    // Create OSMesa drawing surface
    const GLsizei width = GLsizei( BaseClass::width() );
    const GLsizei height = GLsizei( BaseClass::height() );
    m_surface.create( width, height, format );

    // Bind the context to the surface
    if ( !m_context.makeCurrent( m_surface ) )
    {
        kvsMessageError() << "Cannot bind OSMesa context." << std::endl;
        return;
    }

    // Y coordinates increase downward
    kvs::osmesa::Context::SetYAxisDirectionToDown();

    this->initializeEvent();
}

void ScreenBase::show()
{
    if ( !m_context.isValid() ) { this->create(); }
}

void ScreenBase::redraw()
{
    this->draw();
}

void ScreenBase::draw()
{
    if ( !m_context.isValid() ) { this->create(); }
    this->paintEvent();
}

kvs::ColorImage ScreenBase::capture() const
{
    const size_t width = BaseClass::width();
    const size_t height = BaseClass::height();

    // RGBA to RGB
    const kvs::ValueArray<kvs::UInt8>& buffer = m_surface.buffer();
    kvs::ValueArray<kvs::UInt8> pixels( width * height * 3 );
    for ( size_t i = 0; i < width * height; i++ )
    {
        pixels[ 3 * i + 0 ] = buffer[ 4 * i + 0 ];
        pixels[ 3 * i + 1 ] = buffer[ 4 * i + 1 ];
        pixels[ 3 * i + 2 ] = buffer[ 4 * i + 2 ];
    }

    return kvs::ColorImage( width, height, pixels );
}

} // end of namespace osmesa

} // end of namespace kvs
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
using namespace std;

typedef unsigned int uint;

uint GetNum(const string &str, uint index)
{
	uint temp_value = 0;

	if (index < str.length())
	{
		temp_value = str[str.length() - 1 - index] - '0';
	}
	return temp_value;
}

string Add(const string &left, const string &right)
{
	uint carry_bit = 0;
	string result = left.size() >= right.size() ? left : right;

	for (uint i = 0; i < left.size() || i < right.size(); i++)
	{
		uint temp_value = GetNum(left, i) + GetNum(right, i) + carry_bit;

		carry_bit = temp_value / 10;

		temp_value = temp_value % 10;
		result[result.length() - 1 - i] = temp_value + '0';
	}

	if (carry_bit > 0)
	{
		result.insert(result.begin(), carry_bit + '0');
	}

	cout << ">:" <<  result << "\n";

	return result;
}<commit_msg>modify codekata_1<commit_after>#include <iostream>
#include <string>
using namespace std;

#define  NumToStr(x)  (x + '0')

typedef unsigned int uint;

uint GetNum(const string &str, uint index)
{
	uint temp_value = 0;

	if (index < str.length())
	{
		temp_value = str[str.length() - 1 - index] - '0';
	}
	return temp_value;
}

string Add(const string &left, const string &right)
{
	uint carry_bit = 0;
	string result = left.size() >= right.size() ? left : right;

	for (uint i = 0; i < left.size() || i < right.size(); i++)
	{
		uint temp_value = GetNum(left, i) + GetNum(right, i) + carry_bit;

		carry_bit = temp_value / 10;

		temp_value = temp_value % 10;
		result[result.length() - 1 - i] = NumToStr(temp_value);
	}

	if (carry_bit > 0)
	{
		result.insert(result.begin(), NumToStr(carry_bit));
	}

	cout << ">:" <<  result << "\n";

	return result;
}<|endoftext|>


<commit_before>//******************************************************************************
// FILE : function_matrix_transpose.cpp
//
// LAST MODIFIED : 7 October 2004
//
// DESCRIPTION :
//==============================================================================

#if defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)
#include "computed_variable/function_matrix_transpose_implementation.cpp"
#else // defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)
#include "computed_variable/function_matrix_transpose.hpp"
#endif // defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)

#if !defined (AIX)
template<>
Function_handle Function_variable_matrix_transpose<Scalar>::evaluate_derivative(
	std::list<Function_variable_handle>& independent_variables)
//******************************************************************************
// LAST MODIFIED : 7 October 2004
//
// DESCRIPTION :
// ???DB.  To be done
//==============================================================================
{
	boost::intrusive_ptr< Function_matrix_transpose<Scalar> >
		function_matrix_transpose;
	Function_handle result(0);
	Function_size_type order;

	if ((function_matrix_transpose=boost::dynamic_pointer_cast<
		Function_matrix_transpose<Scalar>,Function>(function()))&&
		(0<(order=independent_variables.size())))
	{
		Function_size_type number_of_columns,number_of_dependent_values,
			number_of_independent_values,number_of_rows;
		boost::intrusive_ptr< Function_matrix<Scalar> > derivative,matrix;

		if ((matrix=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
			Function>(function_matrix_transpose->matrix_private->evaluate()))&&
			(row_private<=(number_of_rows=matrix->number_of_columns()))&&
			(column_private<=(number_of_columns=matrix->number_of_rows()))&&
			(derivative=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
			Function>(function_matrix_transpose->matrix_private->
			evaluate_derivative(independent_variables)))&&
			(number_of_rows*number_of_columns==
			(number_of_dependent_values=derivative->number_of_rows())))
		{
			Function_size_type dependent_row,i,j;

			number_of_independent_values=derivative->number_of_columns();
			if (0==row_private)
			{
				if (0==column_private)
				{
					Matrix result_matrix(number_of_dependent_values,
						number_of_independent_values);

					for (i=1;i<=number_of_dependent_values;i++)
					{
						dependent_row=((i-1)%number_of_rows)*number_of_columns+
							(i-1)/number_of_rows;
						for (j=1;j<=number_of_independent_values;j++)
						{
							result_matrix(dependent_row,j-1)=(*derivative)(i,j);
						}
					}
					result=Function_handle(new Function_matrix<Scalar>(result_matrix));
				}
				else
				{
					Matrix result_matrix(number_of_rows,number_of_independent_values);

					dependent_row=(column_private-1)*number_of_rows+1;
					for (i=0;i<number_of_rows;i++)
					{
						for (j=1;j<=number_of_independent_values;j++)
						{
							result_matrix(i,j-1)=(*derivative)(dependent_row,j);
						}
						dependent_row++;
					}
					result=Function_handle(new Function_matrix<Scalar>(result_matrix));
				}
			}
			else
			{
				if (0==column_private)
				{
					Matrix result_matrix(number_of_columns,number_of_independent_values);

					dependent_row=row_private;
					for (i=0;i<number_of_columns;i++)
					{
						for (j=1;j<=number_of_independent_values;j++)
						{
							result_matrix(i,j-1)=(*derivative)(dependent_row,j);
						}
						dependent_row += number_of_rows;
					}
					result=Function_handle(new Function_matrix<Scalar>(result_matrix));
				}
				else
				{
					Matrix result_matrix(1,number_of_independent_values);

					dependent_row=(column_private-1)*number_of_rows+row_private;
					for (j=1;j<=number_of_independent_values;j++)
					{
						result_matrix(0,j-1)=(*derivative)(dependent_row,j);
					}
					result=Function_handle(new Function_matrix<Scalar>(result_matrix));
				}
			}
		}
	}

	return (result);
}

template<>
bool Function_matrix_transpose<Scalar>::evaluate_derivative(Scalar& derivative,
	Function_variable_handle atomic_variable,
	std::list<Function_variable_handle>& atomic_independent_variables)
//******************************************************************************
// LAST MODIFIED : 7 October 2004
//
// DESCRIPTION :
//==============================================================================
{
	bool result;
	boost::intrusive_ptr< Function_variable_matrix_transpose<Scalar> >
		atomic_variable_matrix_transpose;

	result=false;
	if ((atomic_variable_matrix_transpose=boost::dynamic_pointer_cast<
		Function_variable_matrix_transpose<Scalar>,Function_variable>(
		atomic_variable))&&equivalent(Function_handle(this),
		atomic_variable_matrix_transpose->function())&&
		(0<atomic_variable_matrix_transpose->row())&&
		(0<atomic_variable_matrix_transpose->column())&&
		(0<atomic_independent_variables.size()))
	{
		boost::intrusive_ptr< Function_matrix<Scalar> > derivative_matrix=
			boost::dynamic_pointer_cast<Function_matrix<Scalar>,Function>(
			atomic_variable_matrix_transpose->evaluate_derivative(
			atomic_independent_variables));

		if (derivative_matrix)
		{
			result=true;
			derivative=(*derivative_matrix)(1,1);
		}
	}

	return (result);
}
#endif // !defined (AIX)
<commit_msg>Removed unused variable<commit_after>//******************************************************************************
// FILE : function_matrix_transpose.cpp
//
// LAST MODIFIED : 18 October 2004
//
// DESCRIPTION :
//==============================================================================

#if defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)
#include "computed_variable/function_matrix_transpose_implementation.cpp"
#else // defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)
#include "computed_variable/function_matrix_transpose.hpp"
#endif // defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)

#if !defined (AIX)
template<>
Function_handle Function_variable_matrix_transpose<Scalar>::evaluate_derivative(
	std::list<Function_variable_handle>& independent_variables)
//******************************************************************************
// LAST MODIFIED : 18 October 2004
//
// DESCRIPTION :
// ???DB.  To be done
//==============================================================================
{
	boost::intrusive_ptr< Function_matrix_transpose<Scalar> >
		function_matrix_transpose;
	Function_handle result(0);

	if ((function_matrix_transpose=boost::dynamic_pointer_cast<
		Function_matrix_transpose<Scalar>,Function>(function()))&&
		(0<independent_variables.size()))
	{
		Function_size_type number_of_columns,number_of_dependent_values,
			number_of_independent_values,number_of_rows;
		boost::intrusive_ptr< Function_matrix<Scalar> > derivative,matrix;

		if ((matrix=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
			Function>(function_matrix_transpose->matrix_private->evaluate()))&&
			(row_private<=(number_of_rows=matrix->number_of_columns()))&&
			(column_private<=(number_of_columns=matrix->number_of_rows()))&&
			(derivative=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
			Function>(function_matrix_transpose->matrix_private->
			evaluate_derivative(independent_variables)))&&
			(number_of_rows*number_of_columns==
			(number_of_dependent_values=derivative->number_of_rows())))
		{
			Function_size_type dependent_row,i,j;

			number_of_independent_values=derivative->number_of_columns();
			if (0==row_private)
			{
				if (0==column_private)
				{
					Matrix result_matrix(number_of_dependent_values,
						number_of_independent_values);

					for (i=1;i<=number_of_dependent_values;i++)
					{
						dependent_row=((i-1)%number_of_rows)*number_of_columns+
							(i-1)/number_of_rows;
						for (j=1;j<=number_of_independent_values;j++)
						{
							result_matrix(dependent_row,j-1)=(*derivative)(i,j);
						}
					}
					result=Function_handle(new Function_matrix<Scalar>(result_matrix));
				}
				else
				{
					Matrix result_matrix(number_of_rows,number_of_independent_values);

					dependent_row=(column_private-1)*number_of_rows+1;
					for (i=0;i<number_of_rows;i++)
					{
						for (j=1;j<=number_of_independent_values;j++)
						{
							result_matrix(i,j-1)=(*derivative)(dependent_row,j);
						}
						dependent_row++;
					}
					result=Function_handle(new Function_matrix<Scalar>(result_matrix));
				}
			}
			else
			{
				if (0==column_private)
				{
					Matrix result_matrix(number_of_columns,number_of_independent_values);

					dependent_row=row_private;
					for (i=0;i<number_of_columns;i++)
					{
						for (j=1;j<=number_of_independent_values;j++)
						{
							result_matrix(i,j-1)=(*derivative)(dependent_row,j);
						}
						dependent_row += number_of_rows;
					}
					result=Function_handle(new Function_matrix<Scalar>(result_matrix));
				}
				else
				{
					Matrix result_matrix(1,number_of_independent_values);

					dependent_row=(column_private-1)*number_of_rows+row_private;
					for (j=1;j<=number_of_independent_values;j++)
					{
						result_matrix(0,j-1)=(*derivative)(dependent_row,j);
					}
					result=Function_handle(new Function_matrix<Scalar>(result_matrix));
				}
			}
		}
	}

	return (result);
}

template<>
bool Function_matrix_transpose<Scalar>::evaluate_derivative(Scalar& derivative,
	Function_variable_handle atomic_variable,
	std::list<Function_variable_handle>& atomic_independent_variables)
//******************************************************************************
// LAST MODIFIED : 7 October 2004
//
// DESCRIPTION :
//==============================================================================
{
	bool result;
	boost::intrusive_ptr< Function_variable_matrix_transpose<Scalar> >
		atomic_variable_matrix_transpose;

	result=false;
	if ((atomic_variable_matrix_transpose=boost::dynamic_pointer_cast<
		Function_variable_matrix_transpose<Scalar>,Function_variable>(
		atomic_variable))&&equivalent(Function_handle(this),
		atomic_variable_matrix_transpose->function())&&
		(0<atomic_variable_matrix_transpose->row())&&
		(0<atomic_variable_matrix_transpose->column())&&
		(0<atomic_independent_variables.size()))
	{
		boost::intrusive_ptr< Function_matrix<Scalar> > derivative_matrix=
			boost::dynamic_pointer_cast<Function_matrix<Scalar>,Function>(
			atomic_variable_matrix_transpose->evaluate_derivative(
			atomic_independent_variables));

		if (derivative_matrix)
		{
			result=true;
			derivative=(*derivative_matrix)(1,1);
		}
	}

	return (result);
}
#endif // !defined (AIX)
<|endoftext|>


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Graphics/OsgTextRepresentation.h"

#include <osg/Geode>
#include <osg/Drawable>
#include <osg/PositionAttitudeTransform>
#include <osgText/Text>

#include "SurgSim/Framework/ApplicationData.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/SharedInstance.h"
#include "SurgSim/Graphics/OsgConversions.h"
#include "SurgSim/Graphics/OsgFont.h"
#include "SurgSim/Graphics/OsgMaterial.h"
#include "SurgSim/Graphics/OsgUniform.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"

using SurgSim::Math::makeRigidTransform;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::Vector3d;

namespace SurgSim
{
namespace Graphics
{

namespace
{
std::shared_ptr<Graphics::OsgMaterial> createDefaultMaterial()
{
	auto material = Graphics::buildMaterial("Shaders/unlit_texture.vert", "Shaders/unlit_text.frag");
	material->setName("unlittext");
	std::string path;
	SURGSIM_ASSERT(Framework::Runtime::getApplicationData()->tryFindFile("Textures/white.png", &path))
			<< "Could not find default texture 'Textures/white.png'";
	auto texture = std::make_shared<Graphics::OsgTexture2d>();
	SURGSIM_ASSERT(texture->loadImage(path)) << "Loading failed for texture at " << path;
	auto textureUniform = std::make_shared<Graphics::OsgTextureUniform<Graphics::OsgTexture2d>>("texture");

	textureUniform->set(texture);
	material->addUniform(textureUniform);
	return material;
}

}

SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Graphics::OsgTextRepresentation, OsgTextRepresentation);

OsgTextRepresentation::OsgTextRepresentation(const std::string& name) :
	Representation(name),
	OsgRepresentation(name),
	TextRepresentation(name),
	m_geode(new osg::Geode),
	m_textNode(new osgText::Text),
	m_needUpdate(true)
{
	m_textNode->setDataVariance(osg::Object::DYNAMIC);
	m_textNode->setUseDisplayList(false);
	m_characterSize = m_textNode->getCharacterHeight();
	m_geode->addDrawable(m_textNode);

	m_transform->addChild(m_geode);
	m_transform->setCullingActive(false);

	// Try to find default font, if this fails OSG will fall back to its own default, only a warning warranted
	auto font = std::make_shared<OsgFont>();
	try
	{
		font->load("Fonts/Vera.ttf");
	}
	catch (std::exception e)
	{
		SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getLogger("Graphics"))
				<< "Could not set the font Fonts/Vera.ttf, the default will be used";
	}

	m_font = font;
	setUseScreenSpace(true);
}

OsgTextRepresentation::~OsgTextRepresentation()
{
}

void OsgTextRepresentation::setLocation(double x, double y)
{
	setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(x, y, 0.0)));
}

void OsgTextRepresentation::getLocation(double* x, double* y) const
{
	SURGSIM_ASSERT(x !=  nullptr && y != nullptr) << "Cannot use a nullptr as an output parameter.";
	Vector3d position = getLocalPose().translation();

	*x = position.x();
	*y = position.y();
}

void OsgTextRepresentation::setText(const std::string& text)
{
	boost::mutex::scoped_lock lock(m_parameterMutex);
	m_text = text;
	m_needUpdate = true;
}

std::string OsgTextRepresentation::getText() const
{
	return m_text;
}

void OsgTextRepresentation::doUpdate(double dt)
{
	{
		boost::mutex::scoped_lock lock(m_parameterMutex);
		if (m_needUpdate)
		{
			// Osg will catch which ones have been updated, no need for more fine grained control.
			// Each of these may trigger an operation that rebuilds the internal structure of the text drawable
			// which may cause problems with the render
			m_textNode->setFont(m_font->getOsgFont());
			m_textNode->setText(m_text);
			m_textNode->setCharacterSize(m_characterSize);
			m_textNode->setMaximumWidth(m_optionalWidth.hasValue() ? m_optionalWidth.getValue() : 0.0);
			m_needUpdate = false;
		}
	}
	if (isUsingScreenSpace())
	{
		m_transform->setAttitude(osg::Quat(0.0, 0.0, 0.0, 1.0));
	}
}

bool OsgTextRepresentation::doInitialize()
{

	bool result = true;

	// if the material was preassigned, don't create a default one
	if (getMaterial() == nullptr)
	{
		setMaterial(OsgTextRepresentation::getDefaultMaterial());
		m_textNode->getOrCreateStateSet()->addUniform(new osg::Uniform("texture", 0));
	}

	return result;

}

void OsgTextRepresentation::loadFont(const std::string& fileName)
{
	auto newFont = std::make_shared<OsgFont>();
	newFont->load(fileName);
	setFont(newFont);
}

void OsgTextRepresentation::setFont(std::shared_ptr<SurgSim::Framework::Asset> font)
{
	SURGSIM_ASSERT(! isInitialized()) << "Can't set font after text has been initialized.";
	SURGSIM_ASSERT(font != nullptr) << "Can't use nullptr font.";

	auto osgFont = std::dynamic_pointer_cast<OsgFont>(font);

	SURGSIM_ASSERT(osgFont != nullptr)
			<< "Font has to be OsgFont, instead it was " << font->getClassName();
	{
		boost::mutex::scoped_lock lock(m_parameterMutex);
		m_font = osgFont;
		m_needUpdate = true;
	}
}

std::shared_ptr<Font> OsgTextRepresentation::getFont() const
{
	return m_font;
}

void OsgTextRepresentation::setOptionalMaximumWidth(SurgSim::DataStructures::OptionalValue<double> maximum)
{
	boost::mutex::scoped_lock lock(m_parameterMutex);
	m_optionalWidth = maximum;
	m_needUpdate = true;
}

SurgSim::DataStructures::OptionalValue<double> OsgTextRepresentation::getOptionalMaximumWidth()
{
	return m_optionalWidth;
}

std::shared_ptr<SurgSim::Graphics::OsgMaterial> OsgTextRepresentation::getDefaultMaterial()
{

	static Framework::SharedInstance<OsgMaterial> shared(createDefaultMaterial);
	return shared.get();
}

void OsgTextRepresentation::setDrawBackground(bool value)
{
	int drawMode = osgText::TextBase::TEXT;
	if (value)
	{
		drawMode |= osgText::TextBase::FILLEDBOUNDINGBOX;
	}

	m_textNode->setDrawMode(drawMode);
}

bool OsgTextRepresentation::isDrawingBackground() const
{
	return (m_textNode->getDrawMode() & osgText::TextBase::FILLEDBOUNDINGBOX) != 0;
}

void OsgTextRepresentation::setBackgroundColor(Math::Vector4d color)
{
	m_textNode->setBoundingBoxColor(toOsg(color));
}

Math::Vector4d OsgTextRepresentation::getBackgroundColor()
{
	Math::Vector4d result = fromOsg(m_textNode->getBoundingBoxColor()).cast<double>();
	return result;
}

void OsgTextRepresentation::setBackgroundMargin(double margin)
{
	m_textNode->setBoundingBoxMargin(static_cast<float>(margin));
}

double OsgTextRepresentation::getBackgroundMargin() const
{
	return m_textNode->getBoundingBoxMargin();
}

void OsgTextRepresentation::setUseScreenSpace(bool value)
{
	if (value == true)
	{
		removeGroupReference(Representation::DefaultGroupName);
		addGroupReference(Representation::DefaultHudGroupName);
		m_transform->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
		m_textNode->setCharacterSizeMode(osgText::TextBase::SCREEN_COORDS);
	}
	else
	{
		removeGroupReference(Representation::DefaultHudGroupName);
		addGroupReference(Representation::DefaultGroupName);
		m_transform->setReferenceFrame(osg::Transform::RELATIVE_RF);
		m_textNode->setCharacterSizeMode(osgText::TextBase::OBJECT_COORDS);
	}
}

bool OsgTextRepresentation::isUsingScreenSpace() const
{
	auto references = getGroupReferences();
	auto found = std::find(references.begin(), references.end(), Representation::DefaultHudGroupName);
	return (found != references.end());
}

void OsgTextRepresentation::setMaximumWidth(double width)
{
	boost::mutex::scoped_lock lock(m_parameterMutex);
	if (width > 0.0)
	{
		m_optionalWidth.setValue(width);
	}
	else
	{
		m_optionalWidth.invalidate();
	}
	m_needUpdate = true;
}

double OsgTextRepresentation::getMaximumWidth()
{
	return m_optionalWidth.hasValue() ? m_optionalWidth.getValue() : 0.0;
}

void OsgTextRepresentation::setFontSize(double size)
{
	boost::mutex::scoped_lock lock(m_parameterMutex);
	m_characterSize = size;
	m_needUpdate = true;
}

double OsgTextRepresentation::getFontSize() const
{
	return m_characterSize;
}

void OsgTextRepresentation::setColor(SurgSim::Math::Vector4d color)
{
	m_textNode->setColor(toOsg(color));
}

SurgSim::Math::Vector4d  OsgTextRepresentation::getColor() const
{
	SurgSim::Math::Vector4d result = fromOsg(m_textNode->getColor()).cast<double>();
	return result;
}

}; // Graphics
}; // SurgSim
<commit_msg>Fix errorhandling in loading of shared material<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Graphics/OsgTextRepresentation.h"

#include <osg/Geode>
#include <osg/Drawable>
#include <osg/PositionAttitudeTransform>
#include <osgText/Text>

#include "SurgSim/Framework/ApplicationData.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/SharedInstance.h"
#include "SurgSim/Graphics/OsgConversions.h"
#include "SurgSim/Graphics/OsgFont.h"
#include "SurgSim/Graphics/OsgMaterial.h"
#include "SurgSim/Graphics/OsgUniform.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"

using SurgSim::Math::makeRigidTransform;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::Vector3d;

namespace SurgSim
{
namespace Graphics
{

namespace
{
std::shared_ptr<Graphics::OsgMaterial> createDefaultMaterial()
{
	auto logger = Framework::Logger::getLogger("Graphics/OsgTextRepresentation");
	auto material = Graphics::buildMaterial("Shaders/unlit_texture.vert", "Shaders/unlit_text.frag");
	if (material != nullptr)
	{
		material->setName("unlittext");
		std::string path;

		if (!Framework::Runtime::getApplicationData()->tryFindFile("Textures/white.png", &path))
		{
			SURGSIM_LOG_WARNING(logger) << "Could not find default texture for text background, text rectangles "
										<< "might be compromised. (Textures/white.png)";
			return material;
		}

		auto texture = std::make_shared<Graphics::OsgTexture2d>();
		auto textureUniform = std::make_shared<Graphics::OsgTextureUniform<Graphics::OsgTexture2d>>("texture");
		if (!texture->loadImage(path))
		{
			SURGSIM_LOG_WARNING(logger) << "Could not load default texture for text background, text rectangles "
										<< "might be compromised. (" << path << ")";
			return material;
		}

		textureUniform->set(texture);
		material->addUniform(textureUniform);
	}
	else
	{
		SURGSIM_LOG_ONCE(Framework::Logger::getDefaultLogger(), WARNING)
				<< "Could not find default shaders for text. Text display will be compromised.";
		material = std::make_shared<Graphics::OsgMaterial>("unlittext");
	}

	return material;

}

}

SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Graphics::OsgTextRepresentation, OsgTextRepresentation);

OsgTextRepresentation::OsgTextRepresentation(const std::string& name) :
	Representation(name),
	OsgRepresentation(name),
	TextRepresentation(name),
	m_geode(new osg::Geode),
	m_textNode(new osgText::Text),
	m_needUpdate(true)
{
	m_textNode->setDataVariance(osg::Object::DYNAMIC);
	m_textNode->setUseDisplayList(false);
	m_characterSize = m_textNode->getCharacterHeight();
	m_geode->addDrawable(m_textNode);

	m_transform->addChild(m_geode);
	m_transform->setCullingActive(false);

	// Try to find default font, if this fails OSG will fall back to its own default, only a warning warranted
	auto font = std::make_shared<OsgFont>();
	try
	{
		font->load("Fonts/Vera.ttf");
	}
	catch (std::exception e)
	{
		SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getLogger("Graphics"))
				<< "Could not set the font Fonts/Vera.ttf, the default will be used";
	}

	m_font = font;
	setUseScreenSpace(true);
}

OsgTextRepresentation::~OsgTextRepresentation()
{
}

void OsgTextRepresentation::setLocation(double x, double y)
{
	setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(x, y, 0.0)));
}

void OsgTextRepresentation::getLocation(double* x, double* y) const
{
	SURGSIM_ASSERT(x !=  nullptr && y != nullptr) << "Cannot use a nullptr as an output parameter.";
	Vector3d position = getLocalPose().translation();

	*x = position.x();
	*y = position.y();
}

void OsgTextRepresentation::setText(const std::string& text)
{
	boost::mutex::scoped_lock lock(m_parameterMutex);
	m_text = text;
	m_needUpdate = true;
}

std::string OsgTextRepresentation::getText() const
{
	return m_text;
}

void OsgTextRepresentation::doUpdate(double dt)
{
	{
		boost::mutex::scoped_lock lock(m_parameterMutex);
		if (m_needUpdate)
		{
			// Osg will catch which ones have been updated, no need for more fine grained control.
			// Each of these may trigger an operation that rebuilds the internal structure of the text drawable
			// which may cause problems with the render
			m_textNode->setFont(m_font->getOsgFont());
			m_textNode->setText(m_text);
			m_textNode->setCharacterSize(m_characterSize);
			m_textNode->setMaximumWidth(m_optionalWidth.hasValue() ? m_optionalWidth.getValue() : 0.0);
			m_needUpdate = false;
		}
	}
	if (isUsingScreenSpace())
	{
		m_transform->setAttitude(osg::Quat(0.0, 0.0, 0.0, 1.0));
	}
}

bool OsgTextRepresentation::doInitialize()
{

	bool result = true;

	// if the material was preassigned, don't create a default one
	if (getMaterial() == nullptr)
	{
		setMaterial(OsgTextRepresentation::getDefaultMaterial());
		m_textNode->getOrCreateStateSet()->addUniform(new osg::Uniform("texture", 0));
	}

	return result;

}

void OsgTextRepresentation::loadFont(const std::string& fileName)
{
	auto newFont = std::make_shared<OsgFont>();
	newFont->load(fileName);
	setFont(newFont);
}

void OsgTextRepresentation::setFont(std::shared_ptr<SurgSim::Framework::Asset> font)
{
	SURGSIM_ASSERT(! isInitialized()) << "Can't set font after text has been initialized.";
	SURGSIM_ASSERT(font != nullptr) << "Can't use nullptr font.";

	auto osgFont = std::dynamic_pointer_cast<OsgFont>(font);

	SURGSIM_ASSERT(osgFont != nullptr)
			<< "Font has to be OsgFont, instead it was " << font->getClassName();
	{
		boost::mutex::scoped_lock lock(m_parameterMutex);
		m_font = osgFont;
		m_needUpdate = true;
	}
}

std::shared_ptr<Font> OsgTextRepresentation::getFont() const
{
	return m_font;
}

void OsgTextRepresentation::setOptionalMaximumWidth(SurgSim::DataStructures::OptionalValue<double> maximum)
{
	boost::mutex::scoped_lock lock(m_parameterMutex);
	m_optionalWidth = maximum;
	m_needUpdate = true;
}

SurgSim::DataStructures::OptionalValue<double> OsgTextRepresentation::getOptionalMaximumWidth()
{
	return m_optionalWidth;
}

std::shared_ptr<SurgSim::Graphics::OsgMaterial> OsgTextRepresentation::getDefaultMaterial()
{

	static Framework::SharedInstance<OsgMaterial> shared(createDefaultMaterial);
	return shared.get();
}

void OsgTextRepresentation::setDrawBackground(bool value)
{
	int drawMode = osgText::TextBase::TEXT;
	if (value)
	{
		drawMode |= osgText::TextBase::FILLEDBOUNDINGBOX;
	}

	m_textNode->setDrawMode(drawMode);
}

bool OsgTextRepresentation::isDrawingBackground() const
{
	return (m_textNode->getDrawMode() & osgText::TextBase::FILLEDBOUNDINGBOX) != 0;
}

void OsgTextRepresentation::setBackgroundColor(Math::Vector4d color)
{
	m_textNode->setBoundingBoxColor(toOsg(color));
}

Math::Vector4d OsgTextRepresentation::getBackgroundColor()
{
	Math::Vector4d result = fromOsg(m_textNode->getBoundingBoxColor()).cast<double>();
	return result;
}

void OsgTextRepresentation::setBackgroundMargin(double margin)
{
	m_textNode->setBoundingBoxMargin(static_cast<float>(margin));
}

double OsgTextRepresentation::getBackgroundMargin() const
{
	return m_textNode->getBoundingBoxMargin();
}

void OsgTextRepresentation::setUseScreenSpace(bool value)
{
	if (value == true)
	{
		removeGroupReference(Representation::DefaultGroupName);
		addGroupReference(Representation::DefaultHudGroupName);
		m_transform->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
		m_textNode->setCharacterSizeMode(osgText::TextBase::SCREEN_COORDS);
	}
	else
	{
		removeGroupReference(Representation::DefaultHudGroupName);
		addGroupReference(Representation::DefaultGroupName);
		m_transform->setReferenceFrame(osg::Transform::RELATIVE_RF);
		m_textNode->setCharacterSizeMode(osgText::TextBase::OBJECT_COORDS);
	}
}

bool OsgTextRepresentation::isUsingScreenSpace() const
{
	auto references = getGroupReferences();
	auto found = std::find(references.begin(), references.end(), Representation::DefaultHudGroupName);
	return (found != references.end());
}

void OsgTextRepresentation::setMaximumWidth(double width)
{
	boost::mutex::scoped_lock lock(m_parameterMutex);
	if (width > 0.0)
	{
		m_optionalWidth.setValue(width);
	}
	else
	{
		m_optionalWidth.invalidate();
	}
	m_needUpdate = true;
}

double OsgTextRepresentation::getMaximumWidth()
{
	return m_optionalWidth.hasValue() ? m_optionalWidth.getValue() : 0.0;
}

void OsgTextRepresentation::setFontSize(double size)
{
	boost::mutex::scoped_lock lock(m_parameterMutex);
	m_characterSize = size;
	m_needUpdate = true;
}

double OsgTextRepresentation::getFontSize() const
{
	return m_characterSize;
}

void OsgTextRepresentation::setColor(SurgSim::Math::Vector4d color)
{
	m_textNode->setColor(toOsg(color));
}

SurgSim::Math::Vector4d  OsgTextRepresentation::getColor() const
{
	SurgSim::Math::Vector4d result = fromOsg(m_textNode->getColor()).cast<double>();
	return result;
}

}; // Graphics
}; // SurgSim
<|endoftext|>


<commit_before>/*
 * METISGraphReader.cpp
 *
 *  Created on: 17.01.2013
 *      Author: Christian Staudt (christian.staudt@kit.edu)
 */

#include "METISGraphReader.h"
#include "METISParser.h"
#include "../auxiliary/Enforce.h"
#include "../auxiliary/Log.h"
#include "../auxiliary/StringTools.h"

namespace NetworKit {

Graph METISGraphReader::read(const std::string& path) {

	METISParser parser(path);

	std::tuple<count, count, index, count> header = parser.getHeader();
	count n = std::get<0>(header);
	count m = std::get<1>(header);
	index fmt = std::get<2>(header);
	count ncon = std::get<3>(header);

	bool weighted;
	if (fmt % 10 == 1) {
		weighted = true;
		DEBUG("graph has been identified as weighted");
	} else {
		weighted = false;
	}
	count ignoreFirst = 0;
	if (fmt / 10 == 1) {
		DEBUG("first ",ncon," value(s) will be ignored");
		ignoreFirst = ncon;
	}

	Graph G(n, weighted);
	std::string graphName = Aux::StringTools::split(Aux::StringTools::split(path, '/').back(), '.').front();

	G.setName(graphName);

	INFO("\n[BEGIN] reading graph G(n=", n, ", m=", m, ") from METIS file: ", graphName);	// progress bar follows

	double p = 0.0; // percentage for progress bar
	node u = 0; // begin with 0
	count edgeCounter = 0;
	if (weighted == 0) {
		while (parser.hasNext() && u < n) {
			std::vector<node> adjacencies = parser.getNext(ignoreFirst);
			edgeCounter += adjacencies.size();
			for (index i=0; i < adjacencies.size(); i++) {
				if (adjacencies[i] == 0) {
					ERROR("METIS Node ID should not be 0, edge ignored.");
					continue;
				}
				node v = adjacencies[i] - 1; 	// METIS-indices are 1-based
				Aux::Checkers::Enforcer::enforce(v >= 0 && v < n);
				if (u <= v) { // self-loops are allowed
					G.addEdge(u, v);
				}
			}
			u++; // next node
			if ((u % ((n + 10)/10)) == 0) {
				p = ((double) (u-1) / (double) n) * 100;
				DEBUG(p, "% ");
			}
		}
	} else {
		while (parser.hasNext() && u < n) {

			std::vector<std::pair<node,double>> adjacencies = parser.getNextWithWeights(ignoreFirst);
			edgeCounter += adjacencies.size();
			DEBUG("node ",u," has ",adjacencies.size()," edges");
			for (index i=0; i < adjacencies.size(); i++) {
				if (adjacencies[i].first == 0) {
					ERROR("METIS Node ID should not be 0, edge ignored.");
					continue;
				}
				node v = adjacencies[i].first- 1; 	// METIS-indices are 1-based
				double weight = adjacencies[i].second;
				Aux::Checkers::Enforcer::enforce(v >= 0 && v < n);
				if (u <= v && weight > 0) { // self-loops are allowed
					G.addEdge(u, v);
					G.setWeight(u, v, adjacencies[i].second);
					TRACE("(",u,",",v,",",adjacencies[i].second,")");
					assert(adjacencies[i].second > 0);
				}
			}
			u += 1; // next node
			if ((u % ((n + 10)/10)) == 0) {
				p = ((double) (u-1) / (double) n) * 100;
				DEBUG(p, "% ");
			}
		}
	}
	if (G.numberOfEdges() != m) {
		ERROR("METIS file is corrupted: actual number of added edges doesn't match the specifed number of edges");
	}
	if (edgeCounter / m != 2) {
		WARN("METIS file is corrupted: not every edge is listed twice");
	}

	INFO("\n[DONE]\n");
	G.shrinkToFit();
	return G;
}

} /* namespace NetworKit */
<commit_msg>METISGraphReader: allow arbitrary edge weights (and not just positive)<commit_after>/*
 * METISGraphReader.cpp
 *
 *  Created on: 17.01.2013
 *      Author: Christian Staudt (christian.staudt@kit.edu)
 */

#include "METISGraphReader.h"
#include "METISParser.h"
#include "../auxiliary/Enforce.h"
#include "../auxiliary/Log.h"
#include "../auxiliary/StringTools.h"

namespace NetworKit {

Graph METISGraphReader::read(const std::string& path) {

	METISParser parser(path);

	std::tuple<count, count, index, count> header = parser.getHeader();
	count n = std::get<0>(header);
	count m = std::get<1>(header);
	index fmt = std::get<2>(header);
	count ncon = std::get<3>(header);

	bool weighted;
	if (fmt % 10 == 1) {
		weighted = true;
		DEBUG("graph has been identified as weighted");
	} else {
		weighted = false;
	}
	count ignoreFirst = 0;
	if (fmt / 10 == 1) {
		DEBUG("first ",ncon," value(s) will be ignored");
		ignoreFirst = ncon;
	}

	Graph G(n, weighted);
	std::string graphName = Aux::StringTools::split(Aux::StringTools::split(path, '/').back(), '.').front();

	G.setName(graphName);

	INFO("\n[BEGIN] reading graph G(n=", n, ", m=", m, ") from METIS file: ", graphName);	// progress bar follows

	double p = 0.0; // percentage for progress bar
	node u = 0; // begin with 0
	count edgeCounter = 0;
	if (weighted == 0) {
		while (parser.hasNext() && u < n) {
			std::vector<node> adjacencies = parser.getNext(ignoreFirst);
			edgeCounter += adjacencies.size();
			for (index i=0; i < adjacencies.size(); i++) {
				if (adjacencies[i] == 0) {
					ERROR("METIS Node ID should not be 0, edge ignored.");
					continue;
				}
				node v = adjacencies[i] - 1; 	// METIS-indices are 1-based
				Aux::Checkers::Enforcer::enforce(v >= 0 && v < n);
				if (u <= v) { // self-loops are allowed
					G.addEdge(u, v);
				}
			}
			u++; // next node
			if ((u % ((n + 10)/10)) == 0) {
				p = ((double) (u-1) / (double) n) * 100;
				DEBUG(p, "% ");
			}
		}
	} else {
		while (parser.hasNext() && u < n) {

			std::vector<std::pair<node,double>> adjacencies = parser.getNextWithWeights(ignoreFirst);
			edgeCounter += adjacencies.size();
			DEBUG("node ",u," has ",adjacencies.size()," edges");
			for (index i=0; i < adjacencies.size(); i++) {
				if (adjacencies[i].first == 0) {
					ERROR("METIS Node ID should not be 0, edge ignored.");
					continue;
				}
				node v = adjacencies[i].first- 1; 	// METIS-indices are 1-based
				double weight = adjacencies[i].second;
				Aux::Checkers::Enforcer::enforce(v >= 0 && v < n);
				if (u <= v) { // self-loops are allowed
					G.addEdge(u, v, weight);
					TRACE("(",u,",",v,",",adjacencies[i].second,")");
				}
			}
			u += 1; // next node
			if ((u % ((n + 10)/10)) == 0) {
				p = ((double) (u-1) / (double) n) * 100;
				DEBUG(p, "% ");
			}
		}
	}
	if (G.numberOfEdges() != m) {
		ERROR("METIS file is corrupted: actual number of added edges doesn't match the specifed number of edges");
	}
	if (edgeCounter / m != 2) {
		WARN("METIS file is corrupted: not every edge is listed twice");
	}

	INFO("\n[DONE]\n");
	G.shrinkToFit();
	return G;
}

} /* namespace NetworKit */
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkReviewPrintTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkThresholdMaximumConnectedComponentsImageFilter.h"

int main(int , char* [])
{
  typedef itk::Image<float,2> InputType;
  typedef itk::Image<float,2> OutputType;
  typedef itk::Image<unsigned short,2> UShortImageType;
  typedef itk::Image<unsigned char,2> CharType;

  typedef itk::Vector<float,2> VectorType;
  typedef itk::Image<VectorType, 2> VectorImageType;

  itk::ThresholdMaximumConnectedComponentsImageFilter<InputType>::Pointer ThresholdMaximumConnectedComponentsImageFilterObj =
  itk::ThresholdMaximumConnectedComponentsImageFilter<InputType,InputType>::New();
  std:: cout << "-------------ThresholdMaximumConnectedComponentsImageFilter " << ThresholdMaximumConnectedComponentsImageFilterObj;

  return 0;

}
<commit_msg>COMP: The ThresholdMaximumConnectedComponentsImageFilter has a single template       parameter, not two.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkReviewPrintTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkThresholdMaximumConnectedComponentsImageFilter.h"

int main(int , char* [])
{
  typedef itk::Image<float,2> InputType;
  typedef itk::Image<float,2> OutputType;
  typedef itk::Image<unsigned short,2> UShortImageType;
  typedef itk::Image<unsigned char,2> CharType;

  typedef itk::Vector<float,2> VectorType;
  typedef itk::Image<VectorType, 2> VectorImageType;

  itk::ThresholdMaximumConnectedComponentsImageFilter<InputType>::Pointer ThresholdMaximumConnectedComponentsImageFilterObj =
  itk::ThresholdMaximumConnectedComponentsImageFilter<InputType>::New();
  std:: cout << "-------------ThresholdMaximumConnectedComponentsImageFilter " << ThresholdMaximumConnectedComponentsImageFilterObj;

  return 0;

}
<|endoftext|>