<commit_before>/*************************************************************************
 *
 *  $RCSfile: tools.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: obo $ $Date: 2004-03-15 12:48:03 $
 *
 *  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 <cstdarg>
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_
#include "java/lang/String.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_
#include "java/lang/Class.hxx"
#endif
#ifndef CONNECTIVITY_java_util_Properties
#include "java/util/Property.hxx"
#endif

#ifndef _COM_SUN_STAR_SDBC_DRIVERPROPERTYINFO_HPP_
#include <com/sun/star/sdbc/DriverPropertyInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//  using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;

void java_util_Properties::setProperty(const ::rtl::OUString key, const ::rtl::OUString& value)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
    jobject out(0);
    if( t.pEnv )
    {
        jvalue args[2];
        // Parameter konvertieren
        args[0].l = convertwchar_tToJavaString(t.pEnv,key);
        args[1].l = convertwchar_tToJavaString(t.pEnv,value);
        // temporaere Variable initialisieren
        char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;";
        char * cMethodName = "setProperty";
        // Java-Call absetzen
        jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l);
            ThrowSQLException(t.pEnv,NULL);
        }
        t.pEnv->DeleteLocalRef((jstring)args[1].l);
        t.pEnv->DeleteLocalRef((jstring)args[0].l);
        ThrowSQLException(t.pEnv,0);
        if(out)
            t.pEnv->DeleteLocalRef(out);
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
}
jclass java_util_Properties::theClass = 0;

java_util_Properties::~java_util_Properties()
{}

jclass java_util_Properties::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/util/Properties" );
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_util_Properties::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}
//--------------------------------------------------------------------------
java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL )
{
    SDBThreadAttach t;
    if( !t.pEnv )
        return;
    // Java-Call fuer den Konstruktor absetzen
    // temporaere Variable initialisieren
    char * cSignature = "()V";
    jobject tempObj;
    jmethodID mID = t.pEnv->GetMethodID( getMyClass(), "<init>", cSignature );OSL_ENSURE(mID,"Unknown method id!");
    tempObj = t.pEnv->NewObject( getMyClass(), mID);
    saveRef( t.pEnv, tempObj );
    t.pEnv->DeleteLocalRef( tempObj );
}

// --------------------------------------------------------------------------------
jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const ::rtl::OUString& _rTemp)
{
    jstring pStr = NULL;
    if (pEnv)
    {
        pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength());
        pEnv->ExceptionClear();
        OSL_ENSURE(pStr,"Could not create a jsstring object!");
    }
    return pStr;
}

// --------------------------------------------------------------------------------
java_util_Properties* connectivity::createStringPropertyArray(JNIEnv *pEnv,const Sequence< PropertyValue >& info )  throw(SQLException, RuntimeException)
{
    java_util_Properties* pProps = new java_util_Properties();
    const PropertyValue* pBegin = info.getConstArray();
    const PropertyValue* pEnd   = pBegin + info.getLength();

    for(;pBegin != pEnd;++pBegin)
    {
        // this is a special property to find the jdbc driver
        if( pBegin->Name.compareToAscii("JavaDriverClass") &&
            pBegin->Name.compareToAscii("CharSet") &&
            pBegin->Name.compareToAscii("AppendTableAlias") &&
            pBegin->Name.compareToAscii("ParameterNameSubstitution") &&
            pBegin->Name.compareToAscii("IsPasswordRequired") &&
            pBegin->Name.compareToAscii("IsAutoRetrievingEnabled") &&
            pBegin->Name.compareToAscii("AutoRetrievingStatement") &&
            pBegin->Name.compareToAscii("AutoIncrementCreation") &&
            pBegin->Name.compareToAscii("Extension") &&
            pBegin->Name.compareToAscii("NoNameLengthLimit") &&
            pBegin->Name.compareToAscii("EnableSQL92Check") &&
            pBegin->Name.compareToAscii("EnableOuterJoinEscape") &&
            pBegin->Name.compareToAscii("BooleanComparisonMode"))
        {
            ::rtl::OUString aStr;
            pBegin->Value >>= aStr;
            pProps->setProperty(pBegin->Name,aStr);
        }
    }
    return pProps;
}
// --------------------------------------------------------------------------------
::rtl::OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str)
{
    ::rtl::OUString aStr;
    if(_Str)
    {
        jboolean bCopy(sal_True);
        const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy);
        jsize len = pEnv->GetStringLength(_Str);
        aStr = ::rtl::OUString(pChar,len);

        if(bCopy)
            pEnv->ReleaseStringChars(_Str,pChar);
        pEnv->DeleteLocalRef(_Str);
    }
    return aStr;
}
// --------------------------------------------------------------------------------
jobject connectivity::XNameAccess2Map(JNIEnv *pEnv,const Reference< ::com::sun::star::container::XNameAccess > & _rMap)
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSeq = _rMap->getElementNames();
    const ::rtl::OUString *pBegin   = aSeq.getConstArray();
    const ::rtl::OUString *pEnd     = pBegin + aSeq.getLength();
    for(;pBegin != pEnd;++pBegin)
    {
    }
    return 0;
}
// -----------------------------------------------------------------------------
sal_Bool connectivity::isExceptionOccured(JNIEnv *pEnv,sal_Bool _bClear)
{
    if ( !pEnv )
        return sal_False;

    jthrowable pThrowable = pEnv->ExceptionOccurred();
    sal_Bool bRet = pThrowable != NULL;
    if ( pThrowable )
    {
        if ( _bClear )
            pEnv->ExceptionClear();
#if OSL_DEBUG_LEVEL > 1
        if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::getMyClass()))
        {

            java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable);
            ::rtl::OUString sError = pException->getMessage();
            delete pException;
        }
#else
        pEnv->DeleteLocalRef(pThrowable);
#endif

    }

    return bRet;
}

<commit_msg>INTEGRATION: CWS insight01 (1.15.14); FILE MERGED 2004/05/28 11:17:25 oj 1.15.14.2: RESYNC: (1.15-1.16); FILE MERGED 2004/04/23 06:25:48 oj 1.15.14.1: new switch to disable catalog and schema<commit_after>/*************************************************************************
 *
 *  $RCSfile: tools.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 17:05:41 $
 *
 *  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 <cstdarg>
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_
#include "java/lang/String.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_
#include "java/lang/Class.hxx"
#endif
#ifndef CONNECTIVITY_java_util_Properties
#include "java/util/Property.hxx"
#endif

#ifndef _COM_SUN_STAR_SDBC_DRIVERPROPERTYINFO_HPP_
#include <com/sun/star/sdbc/DriverPropertyInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//  using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;

void java_util_Properties::setProperty(const ::rtl::OUString key, const ::rtl::OUString& value)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
    jobject out(0);
    if( t.pEnv )
    {
        jvalue args[2];
        // Parameter konvertieren
        args[0].l = convertwchar_tToJavaString(t.pEnv,key);
        args[1].l = convertwchar_tToJavaString(t.pEnv,value);
        // temporaere Variable initialisieren
        char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;";
        char * cMethodName = "setProperty";
        // Java-Call absetzen
        jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l);
            ThrowSQLException(t.pEnv,NULL);
        }
        t.pEnv->DeleteLocalRef((jstring)args[1].l);
        t.pEnv->DeleteLocalRef((jstring)args[0].l);
        ThrowSQLException(t.pEnv,0);
        if(out)
            t.pEnv->DeleteLocalRef(out);
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
}
jclass java_util_Properties::theClass = 0;

java_util_Properties::~java_util_Properties()
{}

jclass java_util_Properties::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/util/Properties" );
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_util_Properties::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}
//--------------------------------------------------------------------------
java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL )
{
    SDBThreadAttach t;
    if( !t.pEnv )
        return;
    // Java-Call fuer den Konstruktor absetzen
    // temporaere Variable initialisieren
    char * cSignature = "()V";
    jobject tempObj;
    jmethodID mID = t.pEnv->GetMethodID( getMyClass(), "<init>", cSignature );OSL_ENSURE(mID,"Unknown method id!");
    tempObj = t.pEnv->NewObject( getMyClass(), mID);
    saveRef( t.pEnv, tempObj );
    t.pEnv->DeleteLocalRef( tempObj );
}

// --------------------------------------------------------------------------------
jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const ::rtl::OUString& _rTemp)
{
    jstring pStr = NULL;
    if (pEnv)
    {
        pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength());
        pEnv->ExceptionClear();
        OSL_ENSURE(pStr,"Could not create a jsstring object!");
    }
    return pStr;
}

// --------------------------------------------------------------------------------
java_util_Properties* connectivity::createStringPropertyArray(JNIEnv *pEnv,const Sequence< PropertyValue >& info )  throw(SQLException, RuntimeException)
{
    java_util_Properties* pProps = new java_util_Properties();
    const PropertyValue* pBegin = info.getConstArray();
    const PropertyValue* pEnd   = pBegin + info.getLength();

    for(;pBegin != pEnd;++pBegin)
    {
        // this is a special property to find the jdbc driver
        if( pBegin->Name.compareToAscii("JavaDriverClass") &&
            pBegin->Name.compareToAscii("CharSet") &&
            pBegin->Name.compareToAscii("AppendTableAlias") &&
            pBegin->Name.compareToAscii("ParameterNameSubstitution") &&
            pBegin->Name.compareToAscii("IsPasswordRequired") &&
            pBegin->Name.compareToAscii("IsAutoRetrievingEnabled") &&
            pBegin->Name.compareToAscii("AutoRetrievingStatement") &&
            pBegin->Name.compareToAscii("UseCatalogInSelect") &&
            pBegin->Name.compareToAscii("UseSchemaInSelect") &&
            pBegin->Name.compareToAscii("AutoIncrementCreation") &&
            pBegin->Name.compareToAscii("Extension") &&
            pBegin->Name.compareToAscii("NoNameLengthLimit") &&
            pBegin->Name.compareToAscii("EnableSQL92Check") &&
            pBegin->Name.compareToAscii("EnableOuterJoinEscape") &&
            pBegin->Name.compareToAscii("BooleanComparisonMode"))
        {
            ::rtl::OUString aStr;
            pBegin->Value >>= aStr;
            pProps->setProperty(pBegin->Name,aStr);
        }
    }
    return pProps;
}
// --------------------------------------------------------------------------------
::rtl::OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str)
{
    ::rtl::OUString aStr;
    if(_Str)
    {
        jboolean bCopy(sal_True);
        const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy);
        jsize len = pEnv->GetStringLength(_Str);
        aStr = ::rtl::OUString(pChar,len);

        if(bCopy)
            pEnv->ReleaseStringChars(_Str,pChar);
        pEnv->DeleteLocalRef(_Str);
    }
    return aStr;
}
// --------------------------------------------------------------------------------
jobject connectivity::XNameAccess2Map(JNIEnv *pEnv,const Reference< ::com::sun::star::container::XNameAccess > & _rMap)
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSeq = _rMap->getElementNames();
    const ::rtl::OUString *pBegin   = aSeq.getConstArray();
    const ::rtl::OUString *pEnd     = pBegin + aSeq.getLength();
    for(;pBegin != pEnd;++pBegin)
    {
    }
    return 0;
}
// -----------------------------------------------------------------------------
sal_Bool connectivity::isExceptionOccured(JNIEnv *pEnv,sal_Bool _bClear)
{
    if ( !pEnv )
        return sal_False;

    jthrowable pThrowable = pEnv->ExceptionOccurred();
    sal_Bool bRet = pThrowable != NULL;
    if ( pThrowable )
    {
        if ( _bClear )
            pEnv->ExceptionClear();
#if OSL_DEBUG_LEVEL > 1
        if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::getMyClass()))
        {

            java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable);
            ::rtl::OUString sError = pException->getMessage();
            delete pException;
        }
#else
        pEnv->DeleteLocalRef(pThrowable);
#endif

    }

    return bRet;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: DCatalog.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:14:25 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_DBASE_CATALOG_HXX_
#define _CONNECTIVITY_DBASE_CATALOG_HXX_

#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif

namespace connectivity
{
    namespace dbase
    {
        class ODbaseConnection;
        class ODbaseCatalog : public file::OFileCatalog
        {
    public:
            virtual void refreshTables();

        public:
            ODbaseCatalog(ODbaseConnection* _pCon);
        };
    }
}
#endif // _CONNECTIVITY_DBASE_CATALOG_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.364); FILE MERGED 2005/09/05 17:25:13 rt 1.1.1.1.364.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DCatalog.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:01:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_DBASE_CATALOG_HXX_
#define _CONNECTIVITY_DBASE_CATALOG_HXX_

#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif

namespace connectivity
{
    namespace dbase
    {
        class ODbaseConnection;
        class ODbaseCatalog : public file::OFileCatalog
        {
    public:
            virtual void refreshTables();

        public:
            ODbaseCatalog(ODbaseConnection* _pCon);
        };
    }
}
#endif // _CONNECTIVITY_DBASE_CATALOG_HXX_

<|endoftext|>


<commit_before>/* Copyright 2013-present Barefoot Networks, 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.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <gtest/gtest.h>

#include <bm/bm_sim/queueing.h>

#include <thread>
#include <memory>
#include <array>
#include <vector>
#include <algorithm>  // for std::count, std::max

using std::unique_ptr;

using std::thread;

using bm::QueueingLogic;
using bm::QueueingLogicRL;
using bm::QueueingLogicPriRL;

struct WorkerMapper {
  WorkerMapper(size_t nb_workers)
      : nb_workers(nb_workers) { }

  size_t operator()(size_t queue_id) const {
    return queue_id % nb_workers;
  }

  size_t nb_workers;
};

struct RndInput {
  size_t queue_id;
  int v;
};

template <class QType>
class QueueingTest : public ::testing::Test {
 protected:
  static constexpr size_t nb_queues = 3u;
  static constexpr size_t nb_workers = 2u;
  static constexpr size_t capacity = 128u;
  static constexpr size_t iterations = 200000;
  // QueueingLogic<T, WorkerMapper> queue;
  QType queue;
  std::vector<RndInput> values;

  QueueingTest()
      : queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers)),
        values(iterations) { }

  virtual void SetUp() {
    for (size_t i = 0; i < iterations; i++) {
      values[i] = {rand() % nb_queues, rand()};
    }
  }

 public:
  void produce();

  // virtual void TearDown() {}
};

typedef std::unique_ptr<int> QEm;

template <typename QType>
void QueueingTest<QType>::produce() {
  for (size_t i = 0; i < iterations; i++) {
    queue.push_front(values[i].queue_id,
                     unique_ptr<int>(new int(values[i].v)));
  }
}

namespace {

template <typename Q>
void produce_if_dropping(Q &queue, size_t iterations, size_t capacity,
                         const std::vector<RndInput> &values) {
  for (size_t i = 0; i < iterations; i++) {
    size_t queue_id = values[i].queue_id;
    // this is to avoid drops
    // kind of makes me question if using type parameterization is really useful
    // for this
    while (queue.size(queue_id) > capacity / 2) {
      // originally, I just had an empty loop, but Valgrind was running forever
      std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    queue.push_front(queue_id, unique_ptr<int>(new int(values[i].v)));
  }
}

}  // namespace

template <>
void QueueingTest<QueueingLogicRL<QEm, WorkerMapper> >::produce() {
  produce_if_dropping(queue, iterations, capacity, values);
}

template <>
void QueueingTest<QueueingLogicPriRL<QEm, WorkerMapper> >::produce() {
  produce_if_dropping(queue, iterations, capacity, values);
}

using testing::Types;

typedef Types<QueueingLogic<QEm, WorkerMapper>,
              QueueingLogicRL<QEm, WorkerMapper>,
              QueueingLogicPriRL<QEm, WorkerMapper> > QueueingTypes;

TYPED_TEST_CASE(QueueingTest, QueueingTypes);

TYPED_TEST(QueueingTest, ProducerConsummer) {
  thread producer_thread(&QueueingTest<TypeParam>::produce, this);

  WorkerMapper mapper(this->nb_workers);

  for (size_t i = 0; i < this->iterations; i++) {
    size_t queue_id;
    size_t expected_queue_id = this->values[i].queue_id;
    unique_ptr<int> v;
    size_t worker_id = mapper(expected_queue_id);
    this->queue.pop_back(worker_id, &queue_id, &v);
    ASSERT_EQ(expected_queue_id, queue_id);
    ASSERT_EQ(this->values[i].v, *v);
  }

  producer_thread.join();
}

class QueueingRLTest : public ::testing::Test {
 protected:
  typedef std::unique_ptr<int> T;
  static constexpr size_t nb_queues = 1u;
  static constexpr size_t nb_workers = 1u;
  static constexpr size_t capacity = 1024u;
  static constexpr size_t iterations = 512u;
  static constexpr uint64_t pps = 100u;
  QueueingLogicRL<T, WorkerMapper> queue;
  std::vector<RndInput> values;

  static_assert(capacity >= iterations,
                "for RL test, capacity needs to be greater or equal to # pkts");

  QueueingRLTest()
      : queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers)),
        values(iterations) { }

  virtual void SetUp() {
    for (size_t i = 0; i < iterations; i++) {
      values[i] = {rand() % nb_queues, rand()};
    }

    queue.set_rate(0u, pps);
  }

 public:
  void produce() {
    for (size_t i = 0; i < iterations; i++) {
      queue.push_front(values[i].queue_id,
                       unique_ptr<int>(new int(values[i].v)));
    }
  }

  // virtual void TearDown() {}
};

TEST_F(QueueingRLTest, RateLimiter) {
  thread producer_thread(&QueueingRLTest::produce, this);

  using std::chrono::duration_cast;
  using std::chrono::milliseconds;
  using clock = std::chrono::high_resolution_clock;

  std::vector<int> times;
  times.reserve(iterations);

  auto start = clock::now();

  for (size_t i = 0; i < iterations; i++) {
    size_t queue_id;
    unique_ptr<int> v;
    this->queue.pop_back(0u, &queue_id, &v);
    ASSERT_EQ(0u, queue_id);
    ASSERT_EQ(values[i].v, *v);

    auto now = clock::now();
    times.push_back(duration_cast<milliseconds>(now - start).count());
  }

  producer_thread.join();

  int elapsed = times.back();
  int expected = (iterations * 1000) / pps;

  ASSERT_GT(elapsed, expected * 0.9);
  ASSERT_LT(elapsed, expected * 1.1);

  // TODO(antonin): better check of times vector?
}

struct RndInputPri {
  size_t queue_id;
  int v;
  size_t priority;
};

class QueueingPriRLTest : public ::testing::Test {
 protected:
  typedef std::unique_ptr<int> T;
  static constexpr size_t nb_queues = 1u;
  static constexpr size_t nb_workers = 1u;
  static constexpr size_t nb_priorities = 2u;
  static constexpr size_t capacity = 200u;
  static constexpr size_t iterations = 1000u;
  static constexpr uint64_t consummer_pps = 50u;
  static constexpr uint64_t producer_pps = 100u;
  QueueingLogicPriRL<T, WorkerMapper> queue;
  std::vector<RndInputPri> values;

  QueueingPriRLTest()
      : queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers),
              nb_priorities),
        values(iterations) { }

  virtual void SetUp() {
    for (size_t i = 0; i < iterations; i++) {
      values[i] = {rand() % nb_queues, rand(), rand() % nb_priorities};
    }
  }

  std::vector<size_t> receive_all() {
    using std::chrono::duration;

    std::vector<size_t> priorities;
    priorities.reserve(iterations);

    while (priorities.size() < capacity || queue.size(0u) > 0) {
      size_t queue_id, priority;
      unique_ptr<int> v;
      this->queue.pop_back(0u, &queue_id, &priority, &v);
      std::this_thread::sleep_for(duration<double>(1. / consummer_pps));
      priorities.push_back(priority);
    }

    return priorities;
  }

 public:
  void produce() {
    using std::chrono::duration;
    for (size_t i = 0; i < iterations; i++) {
      queue.push_front(values[i].queue_id, values[i].priority,
                       unique_ptr<int>(new int(values[i].v)));
      std::this_thread::sleep_for(duration<double>(1. / producer_pps));
    }
  }

  // virtual void TearDown() {}
};

TEST_F(QueueingPriRLTest, Pri) {
  thread producer_thread(&QueueingPriRLTest::produce, this);

  auto priorities = receive_all();

  producer_thread.join();

  size_t priority_0 = std::count(priorities.begin(), priorities.end(), 0);
  size_t priority_1 = priorities.size() - priority_0;

  // if removed, g++ complains that capacity was not defined
  const size_t c = capacity;

  // we have to receive at least capacity P1 elements (they are buffered and
  // dequeued at the end...)
  ASSERT_LT(c, priority_1);

  // most elements should be P0
  // was originally 10%, but replaced it with 20% as the test would fail from
  // time to time
  ASSERT_GT(0.2, (priority_1 - c) / static_cast<double>(priority_0));
}

TEST_F(QueueingPriRLTest, PriRateLimiter) {
  static constexpr size_t rate_pps = consummer_pps / 2u;
  queue.set_rate(0u, rate_pps);

  thread producer_thread(&QueueingPriRLTest::produce, this);

  auto priorities = receive_all();

  producer_thread.join();

  size_t priority_0 = std::count(priorities.begin(), priorities.end(), 0);
  size_t priority_1 = priorities.size() - priority_0;

  size_t diff;
  if (priority_0 < priority_1)
    diff = priority_1 - priority_0;
  else
    diff = priority_0 - priority_1;

  ASSERT_LT(diff, std::max(priority_0, priority_1) * 0.1);
}
<commit_msg>Increase tolerance margin in queueing unit test (#248)<commit_after>/* Copyright 2013-present Barefoot Networks, 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.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <gtest/gtest.h>

#include <bm/bm_sim/queueing.h>

#include <thread>
#include <memory>
#include <array>
#include <vector>
#include <algorithm>  // for std::count, std::max

using std::unique_ptr;

using std::thread;

using bm::QueueingLogic;
using bm::QueueingLogicRL;
using bm::QueueingLogicPriRL;

struct WorkerMapper {
  WorkerMapper(size_t nb_workers)
      : nb_workers(nb_workers) { }

  size_t operator()(size_t queue_id) const {
    return queue_id % nb_workers;
  }

  size_t nb_workers;
};

struct RndInput {
  size_t queue_id;
  int v;
};

template <class QType>
class QueueingTest : public ::testing::Test {
 protected:
  static constexpr size_t nb_queues = 3u;
  static constexpr size_t nb_workers = 2u;
  static constexpr size_t capacity = 128u;
  static constexpr size_t iterations = 200000;
  // QueueingLogic<T, WorkerMapper> queue;
  QType queue;
  std::vector<RndInput> values;

  QueueingTest()
      : queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers)),
        values(iterations) { }

  virtual void SetUp() {
    for (size_t i = 0; i < iterations; i++) {
      values[i] = {rand() % nb_queues, rand()};
    }
  }

 public:
  void produce();

  // virtual void TearDown() {}
};

typedef std::unique_ptr<int> QEm;

template <typename QType>
void QueueingTest<QType>::produce() {
  for (size_t i = 0; i < iterations; i++) {
    queue.push_front(values[i].queue_id,
                     unique_ptr<int>(new int(values[i].v)));
  }
}

namespace {

template <typename Q>
void produce_if_dropping(Q &queue, size_t iterations, size_t capacity,
                         const std::vector<RndInput> &values) {
  for (size_t i = 0; i < iterations; i++) {
    size_t queue_id = values[i].queue_id;
    // this is to avoid drops
    // kind of makes me question if using type parameterization is really useful
    // for this
    while (queue.size(queue_id) > capacity / 2) {
      // originally, I just had an empty loop, but Valgrind was running forever
      std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    queue.push_front(queue_id, unique_ptr<int>(new int(values[i].v)));
  }
}

}  // namespace

template <>
void QueueingTest<QueueingLogicRL<QEm, WorkerMapper> >::produce() {
  produce_if_dropping(queue, iterations, capacity, values);
}

template <>
void QueueingTest<QueueingLogicPriRL<QEm, WorkerMapper> >::produce() {
  produce_if_dropping(queue, iterations, capacity, values);
}

using testing::Types;

typedef Types<QueueingLogic<QEm, WorkerMapper>,
              QueueingLogicRL<QEm, WorkerMapper>,
              QueueingLogicPriRL<QEm, WorkerMapper> > QueueingTypes;

TYPED_TEST_CASE(QueueingTest, QueueingTypes);

TYPED_TEST(QueueingTest, ProducerConsummer) {
  thread producer_thread(&QueueingTest<TypeParam>::produce, this);

  WorkerMapper mapper(this->nb_workers);

  for (size_t i = 0; i < this->iterations; i++) {
    size_t queue_id;
    size_t expected_queue_id = this->values[i].queue_id;
    unique_ptr<int> v;
    size_t worker_id = mapper(expected_queue_id);
    this->queue.pop_back(worker_id, &queue_id, &v);
    ASSERT_EQ(expected_queue_id, queue_id);
    ASSERT_EQ(this->values[i].v, *v);
  }

  producer_thread.join();
}

class QueueingRLTest : public ::testing::Test {
 protected:
  typedef std::unique_ptr<int> T;
  static constexpr size_t nb_queues = 1u;
  static constexpr size_t nb_workers = 1u;
  static constexpr size_t capacity = 1024u;
  static constexpr size_t iterations = 512u;
  static constexpr uint64_t pps = 100u;
  QueueingLogicRL<T, WorkerMapper> queue;
  std::vector<RndInput> values;

  static_assert(capacity >= iterations,
                "for RL test, capacity needs to be greater or equal to # pkts");

  QueueingRLTest()
      : queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers)),
        values(iterations) { }

  virtual void SetUp() {
    for (size_t i = 0; i < iterations; i++) {
      values[i] = {rand() % nb_queues, rand()};
    }

    queue.set_rate(0u, pps);
  }

 public:
  void produce() {
    for (size_t i = 0; i < iterations; i++) {
      queue.push_front(values[i].queue_id,
                       unique_ptr<int>(new int(values[i].v)));
    }
  }

  // virtual void TearDown() {}
};

TEST_F(QueueingRLTest, RateLimiter) {
  thread producer_thread(&QueueingRLTest::produce, this);

  using std::chrono::duration_cast;
  using std::chrono::milliseconds;
  using clock = std::chrono::high_resolution_clock;

  std::vector<int> times;
  times.reserve(iterations);

  auto start = clock::now();

  for (size_t i = 0; i < iterations; i++) {
    size_t queue_id;
    unique_ptr<int> v;
    this->queue.pop_back(0u, &queue_id, &v);
    ASSERT_EQ(0u, queue_id);
    ASSERT_EQ(values[i].v, *v);

    auto now = clock::now();
    times.push_back(duration_cast<milliseconds>(now - start).count());
  }

  producer_thread.join();

  int elapsed = times.back();
  int expected = (iterations * 1000) / pps;

  ASSERT_GT(elapsed, expected * 0.9);
  ASSERT_LT(elapsed, expected * 1.1);

  // TODO(antonin): better check of times vector?
}

struct RndInputPri {
  size_t queue_id;
  int v;
  size_t priority;
};

class QueueingPriRLTest : public ::testing::Test {
 protected:
  typedef std::unique_ptr<int> T;
  static constexpr size_t nb_queues = 1u;
  static constexpr size_t nb_workers = 1u;
  static constexpr size_t nb_priorities = 2u;
  static constexpr size_t capacity = 200u;
  static constexpr size_t iterations = 1000u;
  static constexpr uint64_t consummer_pps = 50u;
  static constexpr uint64_t producer_pps = 100u;
  QueueingLogicPriRL<T, WorkerMapper> queue;
  std::vector<RndInputPri> values;

  QueueingPriRLTest()
      : queue(nb_queues, nb_workers, capacity, WorkerMapper(nb_workers),
              nb_priorities),
        values(iterations) { }

  virtual void SetUp() {
    for (size_t i = 0; i < iterations; i++) {
      values[i] = {rand() % nb_queues, rand(), rand() % nb_priorities};
    }
  }

  std::vector<size_t> receive_all() {
    using std::chrono::duration;

    std::vector<size_t> priorities;
    priorities.reserve(iterations);

    while (priorities.size() < capacity || queue.size(0u) > 0) {
      size_t queue_id, priority;
      unique_ptr<int> v;
      this->queue.pop_back(0u, &queue_id, &priority, &v);
      std::this_thread::sleep_for(duration<double>(1. / consummer_pps));
      priorities.push_back(priority);
    }

    return priorities;
  }

 public:
  void produce() {
    using std::chrono::duration;
    for (size_t i = 0; i < iterations; i++) {
      queue.push_front(values[i].queue_id, values[i].priority,
                       unique_ptr<int>(new int(values[i].v)));
      std::this_thread::sleep_for(duration<double>(1. / producer_pps));
    }
  }

  // virtual void TearDown() {}
};

TEST_F(QueueingPriRLTest, Pri) {
  thread producer_thread(&QueueingPriRLTest::produce, this);

  auto priorities = receive_all();

  producer_thread.join();

  size_t priority_0 = std::count(priorities.begin(), priorities.end(), 0);
  size_t priority_1 = priorities.size() - priority_0;

  // if removed, g++ complains that capacity was not defined
  const size_t c = capacity;

  // we have to receive at least capacity P1 elements (they are buffered and
  // dequeued at the end...)
  ASSERT_LT(c, priority_1);

  // most elements should be P0
  // was originally 10%, but replaced it with 20% as the test would fail from
  // time to time
  ASSERT_GT(0.2, (priority_1 - c) / static_cast<double>(priority_0));
}

TEST_F(QueueingPriRLTest, PriRateLimiter) {
  static constexpr size_t rate_pps = consummer_pps / 2u;
  queue.set_rate(0u, rate_pps);

  thread producer_thread(&QueueingPriRLTest::produce, this);

  auto priorities = receive_all();

  producer_thread.join();

  size_t priority_0 = std::count(priorities.begin(), priorities.end(), 0);
  size_t priority_1 = priorities.size() - priority_0;

  size_t diff;
  if (priority_0 < priority_1)
    diff = priority_1 - priority_0;
  else
    diff = priority_0 - priority_1;

  // was originally 10%, but replaced it with 25% as the test would fail from
  // time to time (on slower machines?)
  ASSERT_LT(diff, std::max(priority_0, priority_1) * 0.25);
}
<|endoftext|>


<commit_before>
#ifndef __SHUTDOWNICON_HXX__
#define __SHUTDOWNICON_HXX__

#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _RTL_STRING_HXX
#include <rtl/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _SFX_SFXUNO_HXX
#include <sfxuno.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif

class ResMgr;

typedef ::cppu::WeakComponentImplHelper3<
    ::com::sun::star::lang::XInitialization,
    ::com::sun::star::frame::XTerminateListener,
    ::com::sun::star::lang::XServiceInfo > ShutdownIconServiceBase;

class ShutdownIcon :    public ShutdownIconServiceBase
{
        ::osl::Mutex    m_aMutex;
        bool            m_bVeto;
        ResMgr          *m_pResMgr;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;

        static ShutdownIcon *pShutdownIcon; // one instance

#ifdef WNT
        void initSystray();
        void deInitSystray();
        static void SetAutostartW32( const ::rtl::OUString& aShortcutName, bool bActivate );
        static bool GetAutostartW32( const ::rtl::OUString& aShortcutName );
        static void EnterModalMode();
        static void LeaveModalMode();

        friend class SfxNotificationListener_Impl;
#endif

    public:
        ShutdownIcon( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > aSMgr );

        virtual ~ShutdownIcon();

        SFX_DECL_XSERVICEINFO

        static ShutdownIcon* getInstance();

        static void terminateDesktop();
        static void addTerminateListener();

        static void FileOpen();
        static void OpenURL( const ::rtl::OUString& aURL, const ::rtl::OUString& rTarget, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& =
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >( 0 ) );
        static void FromTemplate();

        static void SetAutostart( bool bActivate );
        static bool GetAutostart();

        static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >
                    GetWrapperFactory( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSMgr );
        static ::rtl::OUString  GetImplementationName_static();

        ::rtl::OUString GetResString( int id );
        ::rtl::OUString GetUrlDescription( const ::rtl::OUString& aUrl );

        void SetVeto( bool bVeto )  { m_bVeto = bVeto;}
        bool GetVeto()              { return m_bVeto; }

#ifdef WNT
        static bool IsQuickstarterInstalled();
#endif

        // Component Helper - force override
        virtual void SAL_CALL disposing();

        // XEventListener
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
            throw(::com::sun::star::uno::RuntimeException);

        // XTerminateListener
        virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent )
            throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent )
            throw(::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
            throw( ::com::sun::star::uno::Exception );

        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDesktop > m_xDesktop;
};

#endif
<commit_msg>INTEGRATION: CWS gtkquickstart (1.18.430); FILE MERGED 2006/08/07 13:45:00 mmeeks 1.18.430.2: Issue number: i#57872# Submitted by: mmeeks<commit_after>
#ifndef __SHUTDOWNICON_HXX__
#define __SHUTDOWNICON_HXX__

#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _RTL_STRING_HXX
#include <rtl/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_MODULE_HXX_
#include <osl/module.hxx>
#endif
#ifndef _SFX_SFXUNO_HXX
#include <sfxuno.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef INCLUDED_SFX2_DLLAPI_H
#include <sfx2/dllapi.h>
#endif

class ResMgr;

typedef ::cppu::WeakComponentImplHelper3<
    ::com::sun::star::lang::XInitialization,
    ::com::sun::star::frame::XTerminateListener,
    ::com::sun::star::lang::XServiceInfo > ShutdownIconServiceBase;

#if defined(USE_APP_SHORTCUTS)
#define WRITER_URL      "private:factory/swriter"
#define CALC_URL        "private:factory/scalc"
#define IMPRESS_URL     "private:factory/simpress"
#define IMPRESS_WIZARD_URL     "private:factory/simpress?slot=10425"
#define DRAW_URL        "private:factory/sdraw"
#define MATH_URL        "private:factory/smath"
#define BASE_URL        "private:factory/sdatabase?Interactive"
#endif

class SFX2_DLLPUBLIC ShutdownIcon : public ShutdownIconServiceBase
{
        ::osl::Mutex    m_aMutex;
        bool            m_bVeto;
        ResMgr          *m_pResMgr;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;

        static ShutdownIcon *pShutdownIcon; // one instance

        void (*m_pInitSystray)   ();
        void (*m_pDeInitSystray) ();
        ::osl::Module  *m_pPlugin;

        void initSystray();
        void deInitSystray();

        static void EnterModalMode();
        static void LeaveModalMode();
        static rtl::OUString getShortcutName();

        friend class SfxNotificationListener_Impl;

    public:
        ShutdownIcon( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > aSMgr );

        virtual ~ShutdownIcon();

        SFX_DECL_XSERVICEINFO

        static ShutdownIcon* getInstance();

        static void terminateDesktop();
        static void addTerminateListener();

        static void FileOpen();
        static void OpenURL( const ::rtl::OUString& aURL, const ::rtl::OUString& rTarget, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& =
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >( 0 ) );
        static void FromTemplate();

        static void SetAutostart( bool bActivate );
        static bool GetAutostart();
        static bool bModalMode;

        static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >
                    GetWrapperFactory( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSMgr );
        static ::rtl::OUString  GetImplementationName_static();

        ::rtl::OUString GetResString( int id );
        ::rtl::OUString GetUrlDescription( const ::rtl::OUString& aUrl );

        void SetVeto( bool bVeto )  { m_bVeto = bVeto;}
        bool GetVeto()              { return m_bVeto; }

        static bool IsQuickstarterInstalled();

        // Component Helper - force override
        virtual void SAL_CALL disposing();

        // XEventListener
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
            throw(::com::sun::star::uno::RuntimeException);

        // XTerminateListener
        virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent )
            throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent )
            throw(::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
            throw( ::com::sun::star::uno::Exception );

        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDesktop > m_xDesktop;

#ifdef WNT
        static void EnableAutostartW32( const rtl::OUString &aShortcutName );
        static rtl::OUString GetAutostartFolderNameW32();
#endif
};

extern "C" {
#  ifdef WNT
    // builtin win32 systray
    void win32_init_sys_tray();
    void win32_shutdown_sys_tray();
#  endif
    // external plugin systray impl.
    void plugin_init_sys_tray();
    void plugin_shutdown_sys_tray();
}

#endif
<|endoftext|>


<commit_before>#ifndef SILICIUM_MEMORY_SOURCE_HPP
#define SILICIUM_MEMORY_SOURCE_HPP

#include <silicium/source/source.hpp>
#include <vector>
#include <string>
#include <array>

namespace Si
{
	template <class Element>
	struct memory_source SILICIUM_FINAL : source<Element>
	{
		memory_source()
		{
		}

		explicit memory_source(iterator_range<Element const *> elements)
			: m_elements(std::move(elements))
		{
		}

		virtual iterator_range<Element const *> map_next(std::size_t size) SILICIUM_OVERRIDE
		{
			(void)size;
			return m_elements;
		}

		virtual Element *copy_next(iterator_range<Element *> destination) SILICIUM_OVERRIDE
		{
			while (!m_elements.empty() && !destination.empty())
			{
				destination.front() = m_elements.front();
				destination.pop_front();
				m_elements.pop_front();
			}
			return destination.begin();
		}

	private:

		iterator_range<Element const *> m_elements;
	};

	template <class Element>
	memory_source<Element> make_container_source(std::vector<Element> const &container)
	{
		return memory_source<Element>({container.data(), container.data() + container.size()});
	}

	template <class Element, std::size_t N>
	memory_source<Element> make_container_source(std::array<Element, N> const &container)
	{
		return memory_source<Element>({container.data(), container.data() + container.size()});
	}

	template <class Element>
	memory_source<Element> make_container_source(std::basic_string<Element> const &container)
	{
		return memory_source<Element>({container.data(), container.data() + container.size()});
	}

	template <class Element>
	memory_source<Element> make_c_str_source(Element const *c_str)
	{
		return memory_source<Element>(make_iterator_range(c_str, c_str + std::char_traits<Element>::length(c_str)));
	}
}

#endif
<commit_msg>begin to add sources that move the elements<commit_after>#ifndef SILICIUM_MEMORY_SOURCE_HPP
#define SILICIUM_MEMORY_SOURCE_HPP

#include <silicium/source/source.hpp>
#include <vector>
#include <string>
#include <array>

namespace Si
{
	template <class Element>
	struct memory_source SILICIUM_FINAL : source<Element>
	{
		memory_source()
		{
		}

		explicit memory_source(iterator_range<Element const *> elements)
			: m_elements(std::move(elements))
		{
		}

		virtual iterator_range<Element const *> map_next(std::size_t size) SILICIUM_OVERRIDE
		{
			(void)size;
			return m_elements;
		}

		virtual Element *copy_next(iterator_range<Element *> destination) SILICIUM_OVERRIDE
		{
			while (!m_elements.empty() && !destination.empty())
			{
				destination.front() = m_elements.front();
				destination.pop_front();
				m_elements.pop_front();
			}
			return destination.begin();
		}

	private:

		iterator_range<Element const *> m_elements;
	};

	template <class Element>
	struct mutable_memory_source SILICIUM_FINAL : source<Element>
	{
		mutable_memory_source()
		{
		}

		explicit mutable_memory_source(iterator_range<Element *> elements)
			: m_elements(std::move(elements))
		{
		}

		virtual iterator_range<Element const *> map_next(std::size_t size) SILICIUM_OVERRIDE
		{
			boost::ignore_unused_variable_warning(size);
			return {};
		}

		virtual Element *copy_next(iterator_range<Element *> destination) SILICIUM_OVERRIDE
		{
			while (!m_elements.empty() && !destination.empty())
			{
				destination.front() = std::move(m_elements.front());
				destination.pop_front();
				m_elements.pop_front();
			}
			return destination.begin();
		}

	private:

		iterator_range<Element *> m_elements;
	};

	template <class Element>
	memory_source<Element> make_container_source(std::vector<Element> const &container)
	{
		return memory_source<Element>({container.data(), container.data() + container.size()});
	}

	template <class Element, std::size_t N>
	memory_source<Element> make_container_source(std::array<Element, N> const &container)
	{
		return memory_source<Element>({container.data(), container.data() + container.size()});
	}

	template <class Element, std::size_t N>
	mutable_memory_source<Element> make_container_source(std::array<Element, N> &&container)
	{
		return mutable_memory_source<Element>({container.data(), container.data() + container.size()});
	}

	template <class Element>
	memory_source<Element> make_container_source(std::basic_string<Element> const &container)
	{
		return memory_source<Element>({container.data(), container.data() + container.size()});
	}

	template <class Element>
	memory_source<Element> make_c_str_source(Element const *c_str)
	{
		return memory_source<Element>(make_iterator_range(c_str, c_str + std::char_traits<Element>::length(c_str)));
	}
}

#endif
<|endoftext|>


<commit_before>#include "project.h"
/**
 * @brief Project::Project
 * @param id
 * @param name
 */
Project::Project(ID id, std::string name)
{
    this->files = new ProjFiles();
    this->m_name = name;
    this->m_id = id;
    this->m_videos.clear();
    this->saved = false;
}
/**
 * @brief Project::Project
 */
Project::Project(){
    this->files = new ProjFiles();
    this->m_name = "";
    this->m_id = -1;
    this->m_videos.clear();
}

/**
* @brief Project::add_video
* @param vid
* add given video to project
*/
void Project::add_video(Video* vid)
{
    this->m_videos.push_back(vid);
}
/**
 *  UNSFINISHED
 * @brief operator >>
 * @param is
 * @param proj
 * @return stringstream containing project information
 */
ProjectStream& operator>>(ProjectStream& ps, Project& proj){
    //write files
    //Read project id and name
    ps.projFile >> proj.m_name;

    // read videos
    int vidCounter = 0;
    std::vector<Video*> temp; // used to preserve order ov videos, important for == operator
    ps.videos >> vidCounter;
    if( vidCounter < 0) return ps; // if negative number of videos, loop below will
                                   // be infinite. This is unlikely to happen. but just in case!
    while(vidCounter--){
        Video* v = new Video();
        ps.videos >> *v;
        temp.push_back(v);
    }
    for (auto vidIt = temp.rbegin(); vidIt < temp.rend(); ++vidIt) {  // to preserve order we add videos in reverse
        proj.add_video(*vidIt);
    }
    return ps;
}
/**
 * @brief operator <<
 * @param os
 * @param proj
 * @return stream
 * used for writing videos to file
 */
ProjectStream& operator<<(ProjectStream &ps, const Project& proj){
    //write name and id;
    ps.projFile << proj.m_name.c_str() << " ";
    //write videos
    int vidcounter = proj.m_videos.size();
    ps.videos << vidcounter << " ";
    for(auto vid = proj.m_videos.rbegin(); vid != proj.m_videos.rend(); ++vid){
        Video* v = *vid;
        ps.videos << *v << " ";
        vidcounter++;
    }
    return ps;
}
/**
 * @brief operator ==
 * @param proj
 * @param proj2
 * @return if projects are same TRUE else False
 */
bool operator==(Project proj, Project proj2){
    bool videoEquals =  std::equal(proj.m_videos.begin(), proj.m_videos.end(),
               proj2.m_videos.begin(),
               [](const Video* v, const Video* v2){return *v == *v2;}); // lambda function comparing using video==
                                                                        // by dereferencing pointers in vector
    return *proj.files == *proj2.files && //probably unnecessary as projfiles have projname followed by default suffix
           proj.m_name == proj2.m_name &&
           videoEquals;
}

/**
 * @brief operator ==
 * @param pf
 * @param pf2
 * @retur
 * may not be needed but works as intended,
 */
bool operator==(ProjFiles pf, ProjFiles pf2){
    return  true;pf.dir == pf2.dir &&
            pf.f_proj == pf2.f_proj &&
            pf.f_videos == pf2.f_videos &&
            // Not used in current implementation
            pf.f_analysis == pf2.f_analysis &&
            pf.f_drawings == pf2.f_drawings;

}
/**
 * @brief operator <<
 * @param ps
 * @param pf
 * @return ps
 * Writes a projectfile object to projectstream
 * @deprecated
 * Shouldnt be needed, ids useless and filenames are standard.
 */
ProjectStream& operator<<(ProjectStream &ps,const ProjFiles& pf){
//    ps.projFile << pf.f_analysis << " ";
//    ps.projFile << pf.f_drawings << " ";
//    ps.projFile << pf.f_videos << " ";
    return ps;

}
/**
 * @brief operator >>
 * @param ps
 * @param pf
 * @return ps
 * Reads files from a ProjFiles struct to a ProjectStream
 */
ProjectStream& operator>>(ProjectStream &ps, ProjFiles& pf){
    std::string dummy;

    ps.projFile >> pf.f_proj;
    ps.projFile >> pf.dir;
    ps.projFile >> pf.f_analysis;
    ps.projFile >> pf.f_drawings;
    ps.projFile >> pf.f_videos;
    return ps;
}
<commit_msg>uncommented code and added commment explaining its (non-use)<commit_after>#include "project.h"
/**
 * @brief Project::Project
 * @param id
 * @param name
 */
Project::Project(ID id, std::string name)
{
    this->files = new ProjFiles();
    this->m_name = name;
    this->m_id = id;
    this->m_videos.clear();
    this->saved = false;
}
/**
 * @brief Project::Project
 */
Project::Project(){
    this->files = new ProjFiles();
    this->m_name = "";
    this->m_id = -1;
    this->m_videos.clear();
}

/**
* @brief Project::add_video
* @param vid
* add given video to project
*/
void Project::add_video(Video* vid)
{
    this->m_videos.push_back(vid);
}
/**
 *  UNSFINISHED
 * @brief operator >>
 * @param is
 * @param proj
 * @return stringstream containing project information
 */
ProjectStream& operator>>(ProjectStream& ps, Project& proj){
    //write files
    //Read project id and name
    ps.projFile >> proj.m_name;

    // read videos
    int vidCounter = 0;
    std::vector<Video*> temp; // used to preserve order ov videos, important for == operator
    ps.videos >> vidCounter;
    if( vidCounter < 0) return ps; // if negative number of videos, loop below will
                                   // be infinite. This is unlikely to happen. but just in case!
    while(vidCounter--){
        Video* v = new Video();
        ps.videos >> *v;
        temp.push_back(v);
    }
    for (auto vidIt = temp.rbegin(); vidIt < temp.rend(); ++vidIt) {  // to preserve order we add videos in reverse
        proj.add_video(*vidIt);
    }
    return ps;
}
/**
 * @brief operator <<
 * @param os
 * @param proj
 * @return stream
 * used for writing videos to file
 */
ProjectStream& operator<<(ProjectStream &ps, const Project& proj){
    //write name and id;
    ps.projFile << proj.m_name.c_str() << " ";
    //write videos
    int vidcounter = proj.m_videos.size();
    ps.videos << vidcounter << " ";
    for(auto vid = proj.m_videos.rbegin(); vid != proj.m_videos.rend(); ++vid){
        Video* v = *vid;
        ps.videos << *v << " ";
        vidcounter++;
    }
    return ps;
}
/**
 * @brief operator ==
 * @param proj
 * @param proj2
 * @return if projects are same TRUE else False
 */
bool operator==(Project proj, Project proj2){
    bool videoEquals =  std::equal(proj.m_videos.begin(), proj.m_videos.end(),
               proj2.m_videos.begin(),
               [](const Video* v, const Video* v2){return *v == *v2;}); // lambda function comparing using video==
                                                                        // by dereferencing pointers in vector
    return *proj.files == *proj2.files && //probably unnecessary as projfiles have projname followed by default suffix
           proj.m_name == proj2.m_name &&
           videoEquals;
}

/**
 * @brief operator ==
 * @param pf
 * @param pf2
 * @retur
 * may not be needed but works as intended,
 */
bool operator==(ProjFiles pf, ProjFiles pf2){
    return  pf.dir == pf2.dir &&
            pf.f_proj == pf2.f_proj &&
            pf.f_videos == pf2.f_videos &&
            // Not used in current implementation
            pf.f_analysis == pf2.f_analysis &&
            pf.f_drawings == pf2.f_drawings;

}
/**
 * @brief operator <<
 * @param ps
 * @param pf
 * @return ps
 * Writes a projectfile object to projectstream
 * @deprecated
 * Shouldnt be needed, ids useless and filenames are standard.
 * isnt currently used but works as intended.
 * kept just in case.
 */
ProjectStream& operator<<(ProjectStream &ps,const ProjFiles& pf){
    ps.projFile << pf.f_analysis << " ";
    ps.projFile << pf.f_drawings << " ";
    ps.projFile << pf.f_videos << " ";
    return ps;

}
/**
 * @brief operator >>
 * @param ps
 * @param pf
 * @return ps
 * Reads files from a ProjFiles struct to a ProjectStream
 * Shouldnt be needed, ids useless and filenames are standard.
 * isnt currently used but works as intended.
 * kept just in case.
 */
ProjectStream& operator>>(ProjectStream &ps, ProjFiles& pf){
    std::string dummy;
    ps.projFile >> pf.f_analysis;
    ps.projFile >> pf.f_drawings;
    ps.projFile >> pf.f_videos;
    return ps;
}
<|endoftext|>


<commit_before>#include "TensorData.h"

#include <iostream>
#include <sstream>
#include <iomanip>

#include <SmurffCpp/ConstVMatrixExprIterator.hpp>

using namespace Eigen;
using namespace smurff;

//convert array of coordinates to [nnz x nmodes] matrix
MatrixXui32 toMatrixNew(const std::vector<std::uint32_t>& columns, std::uint64_t nnz, std::uint64_t nmodes)
{
   MatrixXui32 idx(nnz, nmodes);
   for (std::uint64_t row = 0; row < nnz; row++)
   {
      for (std::uint64_t col = 0; col < nmodes; col++)
      {
         idx(row, col) = columns[col * nnz + row];
      }
   }
   return idx;
}

TensorData::TensorData(const smurff::TensorConfig& tc)
   : m_dims(tc.getDims()),
     m_nnz(tc.getNNZ()),
     m_Y(std::make_shared<std::vector<std::shared_ptr<SparseMode> > >())
{
   //combine coordinates into [nnz x nmodes] matrix
   MatrixXui32 idx = toMatrixNew(tc.getColumns(), tc.getNNZ(), tc.getNModes());

   for (std::uint64_t mode = 0; mode < tc.getNModes(); mode++)
   {
      m_Y->push_back(std::make_shared<SparseMode>(idx, tc.getValues(), mode, m_dims[mode]));
   }

   std::uint64_t totalSize = std::accumulate(m_dims.begin(), m_dims.end(), (std::uint64_t)1, std::multiplies<std::uint64_t>());
   this->name = totalSize == m_nnz ? "TensorData [fully known]" : "TensorData [with NAs]";
}

std::shared_ptr<SparseMode> TensorData::Y(std::uint64_t mode) const
{
   return m_Y->operator[](mode);
}

void TensorData::init_pre()
{
   //no logic here
}

double TensorData::sum() const
{
   double esum = 0.0;

   std::shared_ptr<SparseMode> sview = Y(0);

   #pragma omp parallel for schedule(dynamic, 4) reduction(+:esum)
   for(std::uint64_t n = 0; n < sview->getNPlanes(); n++) //go through each hyperplane
   {
      for(std::uint64_t j = sview->beginPlane(n); j < sview->endPlane(n); j++) //go through each item in the plane
      {
         esum += sview->getValues()[j];
      }
   }

   return esum;
}

std::uint64_t TensorData::nmode() const
{
   return m_dims.size();
}

std::uint64_t TensorData::nnz() const
{
   return m_nnz;
}

std::uint64_t TensorData::nna() const
{
   return size() - this->nnz();
}

PVec<> TensorData::dim() const
{
   std::vector<int> pvec_dims;
   for(auto& d : m_dims)
      pvec_dims.push_back(static_cast<int>(d));
   return PVec<>(pvec_dims);
}

double TensorData::train_rmse(const SubModel& model) const
{
   return std::sqrt(sumsq(model) / this->nnz());
}

//d is an index of column in U matrix
//this function selects d'th hyperplane from mode`th SparseMode
//it does j multiplications
//where each multiplication is a cwiseProduct of columns from each V matrix
void TensorData::getMuLambda(const SubModel& model, uint32_t mode, int d, Eigen::VectorXd& rr, Eigen::MatrixXd& MM) const
{
   std::shared_ptr<SparseMode> sview = Y(mode); //get tensor rotation for mode

   auto V0 = model.CVbegin(mode); //get first V matrix
   for (std::uint64_t j = sview->beginPlane(d); j < sview->endPlane(d); j++) //go through hyperplane in tensor rotation
   {
      VectorXd col = (*V0).col(sview->getIndices()(j, 0)); //create a copy of m'th column from V (m = 0)
      auto V = model.CVbegin(mode); //get V matrices for mode
      for (std::uint64_t m = 1; m < sview->getNCoords(); m++) //go through each coordinate of value
      {
         ++V; //inc iterator prior to access since we are starting from m = 1
         col.noalias() = col.cwiseProduct((*V).col(sview->getIndices()(j, m))); //multiply by m'th column from V
      }
      MM.triangularView<Eigen::Lower>() += noise()->getAlpha() * col * col.transpose(); // MM = MM + (col * colT) * alpha (where col = product of columns in each V)

      auto pos = sview->pos(d, j);
      double noisy_val = noise()->sample(model, pos, sview->getValues()[j]);
      rr.noalias() += col * noisy_val; // rr = rr + (col * value) * alpha (where value = j'th value of Y)
   }
}

void TensorData::update_pnm(const SubModel& model, uint32_t mode)
{
   //do not need to cache VV here
}

double TensorData::sumsq(const SubModel& model) const
{
   double sumsq = 0.0;

   std::shared_ptr<SparseMode> sview = Y(0);

   #pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq)
   for(std::uint64_t h = 0; h < sview->getNPlanes(); h++) //go through each hyperplane
   {
      for(std::uint64_t n = 0; n < sview->nItemsOnPlane(h); n++) //go through each item in the hyperplane
      {
         auto item = sview->item(h, n);
         double pred = model.predict(item.first);
         sumsq += std::pow(pred - item.second, 2);
      }
   }

   return sumsq;
}

double TensorData::var_total() const
{
   double cwise_mean = this->sum() / this->nnz();
   double se = 0.0;

   std::shared_ptr<SparseMode> sview = Y(0);

   #pragma omp parallel for schedule(dynamic, 4) reduction(+:se)
   for(std::uint64_t h = 0; h < sview->getNPlanes(); h++) //go through each hyperplane
   {
      for(std::uint64_t n = 0; n < sview->nItemsOnPlane(h); n++) //go through each item in the hyperplane
      {
         auto item = sview->item(h, n);
         se += std::pow(item.second - cwise_mean, 2);
      }
   }

   double var = se / this->nnz();
   if (var <= 0.0 || std::isnan(var))
   {
      // if var cannot be computed using 1.0
      var = 1.0;
   }

   return var;
}

std::pair<PVec<>, double> TensorData::item(std::uint64_t mode, std::uint64_t hyperplane, std::uint64_t item) const
{
   if(mode >= m_Y->size())
   {
      THROWERROR("Invalid mode");
   }

   return m_Y->at(mode)->item(hyperplane, item);
}

PVec<> TensorData::pos(std::uint64_t mode, std::uint64_t hyperplane, std::uint64_t item) const
{
   if(mode >= m_Y->size())
   {
      THROWERROR("Invalid mode");
   }

   return m_Y->at(mode)->pos(hyperplane, item);
}

std::ostream& TensorData::info(std::ostream& os, std::string indent)
{
   Data::info(os, indent);
   double train_fill_rate = 100. * nnz() / size();

   os << indent << "Size: " << nnz() << " [";

   for (std::size_t i = 0; i < m_dims.size() - 1; i++)
   {
      os << m_dims[i] << " x ";
   }

   os << m_dims.back() << "] (" << std::fixed << std::setprecision(2) << train_fill_rate << "%)\n";

   return os;
}
<commit_msg>fix bug in TensorData in getMuLambda. previously - only lower triangle of MM matrix was calculated.<commit_after>#include "TensorData.h"

#include <iostream>
#include <sstream>
#include <iomanip>

#include <SmurffCpp/ConstVMatrixExprIterator.hpp>

using namespace Eigen;
using namespace smurff;

//convert array of coordinates to [nnz x nmodes] matrix
MatrixXui32 toMatrixNew(const std::vector<std::uint32_t>& columns, std::uint64_t nnz, std::uint64_t nmodes)
{
   MatrixXui32 idx(nnz, nmodes);
   for (std::uint64_t row = 0; row < nnz; row++)
   {
      for (std::uint64_t col = 0; col < nmodes; col++)
      {
         idx(row, col) = columns[col * nnz + row];
      }
   }
   return idx;
}

TensorData::TensorData(const smurff::TensorConfig& tc)
   : m_dims(tc.getDims()),
     m_nnz(tc.getNNZ()),
     m_Y(std::make_shared<std::vector<std::shared_ptr<SparseMode> > >())
{
   //combine coordinates into [nnz x nmodes] matrix
   MatrixXui32 idx = toMatrixNew(tc.getColumns(), tc.getNNZ(), tc.getNModes());

   for (std::uint64_t mode = 0; mode < tc.getNModes(); mode++)
   {
      m_Y->push_back(std::make_shared<SparseMode>(idx, tc.getValues(), mode, m_dims[mode]));
   }

   std::uint64_t totalSize = std::accumulate(m_dims.begin(), m_dims.end(), (std::uint64_t)1, std::multiplies<std::uint64_t>());
   this->name = totalSize == m_nnz ? "TensorData [fully known]" : "TensorData [with NAs]";
}

std::shared_ptr<SparseMode> TensorData::Y(std::uint64_t mode) const
{
   return m_Y->operator[](mode);
}

void TensorData::init_pre()
{
   //no logic here
}

double TensorData::sum() const
{
   double esum = 0.0;

   std::shared_ptr<SparseMode> sview = Y(0);

   #pragma omp parallel for schedule(dynamic, 4) reduction(+:esum)
   for(std::uint64_t n = 0; n < sview->getNPlanes(); n++) //go through each hyperplane
   {
      for(std::uint64_t j = sview->beginPlane(n); j < sview->endPlane(n); j++) //go through each item in the plane
      {
         esum += sview->getValues()[j];
      }
   }

   return esum;
}

std::uint64_t TensorData::nmode() const
{
   return m_dims.size();
}

std::uint64_t TensorData::nnz() const
{
   return m_nnz;
}

std::uint64_t TensorData::nna() const
{
   return size() - this->nnz();
}

PVec<> TensorData::dim() const
{
   std::vector<int> pvec_dims;
   for(auto& d : m_dims)
      pvec_dims.push_back(static_cast<int>(d));
   return PVec<>(pvec_dims);
}

double TensorData::train_rmse(const SubModel& model) const
{
   return std::sqrt(sumsq(model) / this->nnz());
}

//d is an index of column in U matrix
//this function selects d'th hyperplane from mode`th SparseMode
//it does j multiplications
//where each multiplication is a cwiseProduct of columns from each V matrix
void TensorData::getMuLambda(const SubModel& model, uint32_t mode, int d, Eigen::VectorXd& rr, Eigen::MatrixXd& MM) const
{
   std::shared_ptr<SparseMode> sview = Y(mode); //get tensor rotation for mode

   auto V0 = model.CVbegin(mode); //get first V matrix
   for (std::uint64_t j = sview->beginPlane(d); j < sview->endPlane(d); j++) //go through hyperplane in tensor rotation
   {
      VectorXd col = (*V0).col(sview->getIndices()(j, 0)); //create a copy of m'th column from V (m = 0)
      auto V = model.CVbegin(mode); //get V matrices for mode
      for (std::uint64_t m = 1; m < sview->getNCoords(); m++) //go through each coordinate of value
      {
         ++V; //inc iterator prior to access since we are starting from m = 1
         col.noalias() = col.cwiseProduct((*V).col(sview->getIndices()(j, m))); //multiply by m'th column from V
      }
      MM.triangularView<Eigen::Lower>() += noise()->getAlpha() * col * col.transpose(); // MM = MM + (col * colT) * alpha (where col = product of columns in each V)

      auto pos = sview->pos(d, j);
      double noisy_val = noise()->sample(model, pos, sview->getValues()[j]);
      rr.noalias() += col * noisy_val; // rr = rr + (col * value) * alpha (where value = j'th value of Y)
   }

   MM.triangularView<Upper>() = MM.transpose();
}

void TensorData::update_pnm(const SubModel& model, uint32_t mode)
{
   //do not need to cache VV here
}

double TensorData::sumsq(const SubModel& model) const
{
   double sumsq = 0.0;

   std::shared_ptr<SparseMode> sview = Y(0);

   #pragma omp parallel for schedule(dynamic, 4) reduction(+:sumsq)
   for(std::uint64_t h = 0; h < sview->getNPlanes(); h++) //go through each hyperplane
   {
      for(std::uint64_t n = 0; n < sview->nItemsOnPlane(h); n++) //go through each item in the hyperplane
      {
         auto item = sview->item(h, n);
         double pred = model.predict(item.first);
         sumsq += std::pow(pred - item.second, 2);
      }
   }

   return sumsq;
}

double TensorData::var_total() const
{
   double cwise_mean = this->sum() / this->nnz();
   double se = 0.0;

   std::shared_ptr<SparseMode> sview = Y(0);

   #pragma omp parallel for schedule(dynamic, 4) reduction(+:se)
   for(std::uint64_t h = 0; h < sview->getNPlanes(); h++) //go through each hyperplane
   {
      for(std::uint64_t n = 0; n < sview->nItemsOnPlane(h); n++) //go through each item in the hyperplane
      {
         auto item = sview->item(h, n);
         se += std::pow(item.second - cwise_mean, 2);
      }
   }

   double var = se / this->nnz();
   if (var <= 0.0 || std::isnan(var))
   {
      // if var cannot be computed using 1.0
      var = 1.0;
   }

   return var;
}

std::pair<PVec<>, double> TensorData::item(std::uint64_t mode, std::uint64_t hyperplane, std::uint64_t item) const
{
   if(mode >= m_Y->size())
   {
      THROWERROR("Invalid mode");
   }

   return m_Y->at(mode)->item(hyperplane, item);
}

PVec<> TensorData::pos(std::uint64_t mode, std::uint64_t hyperplane, std::uint64_t item) const
{
   if(mode >= m_Y->size())
   {
      THROWERROR("Invalid mode");
   }

   return m_Y->at(mode)->pos(hyperplane, item);
}

std::ostream& TensorData::info(std::ostream& os, std::string indent)
{
   Data::info(os, indent);
   double train_fill_rate = 100. * nnz() / size();

   os << indent << "Size: " << nnz() << " [";

   for (std::size_t i = 0; i < m_dims.size() - 1; i++)
   {
      os << m_dims[i] << " x ";
   }

   os << m_dims.back() << "] (" << std::fixed << std::setprecision(2) << train_fill_rate << "%)\n";

   return os;
}
<|endoftext|>


<commit_before>/***********************************************************************
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"

#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
template <typename T>
const float OgreRenderTarget<T>::d_yfov_tan = 0.267949192431123f;

//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
                                      Ogre::RenderSystem& rs) :
    d_owner(owner),
    d_renderSystem(rs),
    d_area(0, 0, 0, 0),
    d_renderTarget(0),
    d_viewport(0),
    d_ogreViewportDimensions(0, 0, 0, 0),
    d_matrix(Ogre::Matrix4::IDENTITY),
    d_matrixValid(false),
    d_viewportValid(false),
    d_viewDistance(0)
{
}

//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
    delete d_viewport;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
    buffer.draw();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
    queue.draw();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
    d_area = area;
    setOgreViewportDimensions(area);

    d_matrixValid = false;

    RenderTargetEventArgs args(this);
    T::fireEvent(RenderTarget::EventAreaChanged, args);
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
    d_ogreViewportDimensions = area;

    if (d_viewport)
        updateOgreViewportDimensions(d_viewport->getTarget());

    d_viewportValid = false;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
                                            const Ogre::RenderTarget* const rt)
{
    if (rt)
    {
        if(d_viewport)
            d_viewport->setDimensions(
            d_ogreViewportDimensions.left() / rt->getWidth(),
            d_ogreViewportDimensions.top() / rt->getHeight(),
            d_ogreViewportDimensions.getWidth() / rt->getWidth(),
            d_ogreViewportDimensions.getHeight() / rt->getHeight());
    }
}

//----------------------------------------------------------------------------//
template <typename T>
const Rectf& OgreRenderTarget<T>::getArea() const
{
    return d_area;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
    if (!d_matrixValid)
        updateMatrix();

    if (!d_viewportValid)
        updateViewport();

    d_renderSystem._setViewport(d_viewport);

    d_owner.setProjectionMatrix(d_matrix);
    d_owner.setViewMatrix(Ogre::Matrix4::IDENTITY);

    RenderTarget::activate();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
    // currently nothing to do in the basic case
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
                                         const glm::vec2& p_in,
                                         glm::vec2& p_out) const
{
    if (!d_matrixValid)
        updateMatrix();

    const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);

    const Ogre::Real midx = d_area.getWidth() * 0.5f;
    const Ogre::Real midy = d_area.getHeight() * 0.5f;

    // viewport matrix
    const Ogre::Matrix4 vpmat(
        midx,    0,    0,    d_area.left() + midx,
         0,    -midy,  0,    d_area.top() + midy,
         0,      0,    1,    0,
         0,      0,    0,    1
    );

    // matrices used for projecting and unprojecting points

    const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat);
    const Ogre::Matrix4 unproj(proj.inverse());

    Ogre::Vector3 in;

    // unproject the ends of the ray
    in.x = midx;
    in.y = midy;
    in.z = -d_viewDistance;
    const Ogre::Vector3 r1(unproj * in);
    in.x = p_in.x;
    in.y = p_in.y;
    in.z = 0;
    // calculate vector of picking ray
    const Ogre::Vector3 rv(r1 - unproj * in);

    // project points to orientate them with GeometryBuffer plane
    in.x = 0.0;
    in.y = 0.0;
    const Ogre::Vector3 p1(proj * in);
    in.x = 1.0;
    in.y = 0.0;
    const Ogre::Vector3 p2(proj * in);
    in.x = 0.0;
    in.y = 1.0;
    const Ogre::Vector3 p3(proj * in);

    // calculate the plane normal
    const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
    // calculate distance from origin
    const Ogre::Real plen = pn.length();
    const Ogre::Real dist = -(p1.x * (pn.x / plen) +
                              p1.y * (pn.y / plen) +
                              p1.z * (pn.z / plen));

    // calculate intersection of ray and plane
    const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
    const Ogre::Real tmp = pn_dot_rv != 0.0 ?
                            (pn.dotProduct(r1) + dist) / pn_dot_rv :
                            0.0f;

    p_out.x = static_cast<float>(r1.x - rv.x * tmp);
    p_out.y = static_cast<float>(r1.y - rv.y * tmp);
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
    // Now with updated code from OpenGL renderer

    const float w = d_area.getWidth();
    const float h = d_area.getHeight();

    // We need to check if width or height are zero and act accordingly to prevent running into issues
    // with divisions by zero which would lead to undefined values, as well as faulty clipping planes
    // This is mostly important for avoiding asserts
    const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);

    const float aspect = widthAndHeightNotZero ? w / h : 1.0f;
    const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;
    const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;
    d_viewDistance = midx / (aspect * 0.267949192431123f);

    const float nearZ = d_viewDistance * 0.5f;
    const float farZ = d_viewDistance * 2.0f;
    const float nr_sub_far = nearZ - farZ;

    Ogre::Matrix4 tmp(Ogre::Matrix4::ZERO);
    tmp[0][0] = 3.732050808f / aspect;
    tmp[0][3] = -d_viewDistance;
    tmp[1][1] = -3.732050808f;
    tmp[1][3] = d_viewDistance;
    tmp[2][2] = -((farZ + nearZ) / nr_sub_far);
    tmp[3][2] = 1.0f;
    tmp[3][3] = d_viewDistance;

    d_renderSystem._convertProjectionMatrix(tmp, d_matrix);

    d_matrixValid = true;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
    if (!d_viewport)
    {
#ifdef CEGUI_USE_OGRE_COMPOSITOR2

        d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
        d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2

        updateOgreViewportDimensions(d_renderTarget);
    }

    d_viewport->_updateDimensions();

    d_viewportValid = true;
}

//----------------------------------------------------------------------------//
template <typename T>
Renderer& OgreRenderTarget<T>::getOwner()
{
    return d_owner;
}

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

} // End of  CEGUI namespace section
<commit_msg>MOD: Adding missing activationCounter reset<commit_after>/***********************************************************************
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"

#include <OgreRenderSystem.h>
#include <OgreCamera.h>
#include <OgreViewport.h>

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
template <typename T>
const float OgreRenderTarget<T>::d_yfov_tan = 0.267949192431123f;

//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner,
                                      Ogre::RenderSystem& rs) :
    d_owner(owner),
    d_renderSystem(rs),
    d_area(0, 0, 0, 0),
    d_renderTarget(0),
    d_viewport(0),
    d_ogreViewportDimensions(0, 0, 0, 0),
    d_matrix(Ogre::Matrix4::IDENTITY),
    d_matrixValid(false),
    d_viewportValid(false),
    d_viewDistance(0)
{
}

//----------------------------------------------------------------------------//
template <typename T>
OgreRenderTarget<T>::~OgreRenderTarget()
{
    delete d_viewport;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer)
{
    buffer.draw();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::draw(const RenderQueue& queue)
{
    queue.draw();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setArea(const Rectf& area)
{
    d_area = area;
    setOgreViewportDimensions(area);

    d_matrixValid = false;

    RenderTargetEventArgs args(this);
    T::fireEvent(RenderTarget::EventAreaChanged, args);
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area)
{
    d_ogreViewportDimensions = area;

    if (d_viewport)
        updateOgreViewportDimensions(d_viewport->getTarget());

    d_viewportValid = false;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateOgreViewportDimensions(
                                            const Ogre::RenderTarget* const rt)
{
    if (rt)
    {
        if(d_viewport)
            d_viewport->setDimensions(
            d_ogreViewportDimensions.left() / rt->getWidth(),
            d_ogreViewportDimensions.top() / rt->getHeight(),
            d_ogreViewportDimensions.getWidth() / rt->getWidth(),
            d_ogreViewportDimensions.getHeight() / rt->getHeight());
    }
}

//----------------------------------------------------------------------------//
template <typename T>
const Rectf& OgreRenderTarget<T>::getArea() const
{
    return d_area;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::activate()
{
    if (!d_matrixValid)
        updateMatrix();

    if (!d_viewportValid)
        updateViewport();

    d_renderSystem._setViewport(d_viewport);

    d_owner.setProjectionMatrix(d_matrix);
    d_owner.setViewMatrix(Ogre::Matrix4::IDENTITY);

    RenderTarget::activate();
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::deactivate()
{
    // currently nothing to do in the basic case
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,
                                         const glm::vec2& p_in,
                                         glm::vec2& p_out) const
{
    if (!d_matrixValid)
        updateMatrix();

    const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff);

    const Ogre::Real midx = d_area.getWidth() * 0.5f;
    const Ogre::Real midy = d_area.getHeight() * 0.5f;

    // viewport matrix
    const Ogre::Matrix4 vpmat(
        midx,    0,    0,    d_area.left() + midx,
         0,    -midy,  0,    d_area.top() + midy,
         0,      0,    1,    0,
         0,      0,    0,    1
    );

    // matrices used for projecting and unprojecting points

    const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat);
    const Ogre::Matrix4 unproj(proj.inverse());

    Ogre::Vector3 in;

    // unproject the ends of the ray
    in.x = midx;
    in.y = midy;
    in.z = -d_viewDistance;
    const Ogre::Vector3 r1(unproj * in);
    in.x = p_in.x;
    in.y = p_in.y;
    in.z = 0;
    // calculate vector of picking ray
    const Ogre::Vector3 rv(r1 - unproj * in);

    // project points to orientate them with GeometryBuffer plane
    in.x = 0.0;
    in.y = 0.0;
    const Ogre::Vector3 p1(proj * in);
    in.x = 1.0;
    in.y = 0.0;
    const Ogre::Vector3 p2(proj * in);
    in.x = 0.0;
    in.y = 1.0;
    const Ogre::Vector3 p3(proj * in);

    // calculate the plane normal
    const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1));
    // calculate distance from origin
    const Ogre::Real plen = pn.length();
    const Ogre::Real dist = -(p1.x * (pn.x / plen) +
                              p1.y * (pn.y / plen) +
                              p1.z * (pn.z / plen));

    // calculate intersection of ray and plane
    const Ogre::Real pn_dot_rv = pn.dotProduct(rv);
    const Ogre::Real tmp = pn_dot_rv != 0.0 ?
                            (pn.dotProduct(r1) + dist) / pn_dot_rv :
                            0.0f;

    p_out.x = static_cast<float>(r1.x - rv.x * tmp);
    p_out.y = static_cast<float>(r1.y - rv.y * tmp);
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateMatrix() const
{
    // Now with updated code from OpenGL renderer

    const float w = d_area.getWidth();
    const float h = d_area.getHeight();

    // We need to check if width or height are zero and act accordingly to prevent running into issues
    // with divisions by zero which would lead to undefined values, as well as faulty clipping planes
    // This is mostly important for avoiding asserts
    const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);

    const float aspect = widthAndHeightNotZero ? w / h : 1.0f;
    const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;
    const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;
    d_viewDistance = midx / (aspect * 0.267949192431123f);

    const float nearZ = d_viewDistance * 0.5f;
    const float farZ = d_viewDistance * 2.0f;
    const float nr_sub_far = nearZ - farZ;

    Ogre::Matrix4 tmp(Ogre::Matrix4::ZERO);
    tmp[0][0] = 3.732050808f / aspect;
    tmp[0][3] = -d_viewDistance;
    tmp[1][1] = -3.732050808f;
    tmp[1][3] = d_viewDistance;
    tmp[2][2] = -((farZ + nearZ) / nr_sub_far);
    tmp[3][2] = 1.0f;
    tmp[3][3] = d_viewDistance;

    d_renderSystem._convertProjectionMatrix(tmp, d_matrix);

    d_matrixValid = true;
    //! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices
    RenderTarget::d_activationCounter = -1;
}

//----------------------------------------------------------------------------//
template <typename T>
void OgreRenderTarget<T>::updateViewport()
{
    if (!d_viewport)
    {
#ifdef CEGUI_USE_OGRE_COMPOSITOR2

        d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
        d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2

        updateOgreViewportDimensions(d_renderTarget);
    }

    d_viewport->_updateDimensions();

    d_viewportValid = true;
}

//----------------------------------------------------------------------------//
template <typename T>
Renderer& OgreRenderTarget<T>::getOwner()
{
    return d_owner;
}

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

} // End of  CEGUI namespace section
<|endoftext|>