<commit_before>/*************************************************************************
 *
 *  $RCSfile: docsh2.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 20:14:49 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif

#pragma hdrstop

#include <svx/xtable.hxx>

#include "scitems.hxx"
#include <tools/gen.hxx>
#include <svtools/ctrltool.hxx>
#include <svx/flstitem.hxx>
#include <svx/drawitem.hxx>
#include <sfx2/printer.hxx>
#include <svtools/smplhint.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdoole2.hxx>
#include <vcl/svapp.hxx>
#include <svx/asiancfg.hxx>
#include <svx/forbiddencharacterstable.hxx>
#include <svx/unolingu.hxx>
#include <rtl/logfile.hxx>

// INCLUDE ---------------------------------------------------------------
/*
#include <svdrwetc.hxx>
#include <svdrwobx.hxx>
#include <sostor.hxx>
*/
#include "drwlayer.hxx"
#include "stlpool.hxx"
#include "docsh.hxx"
#include "docfunc.hxx"
#include "sc.hrc"

using namespace com::sun::star;

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

BOOL __EXPORT ScDocShell::InitNew( const uno::Reference < embed::XStorage >& xStor )
{
    RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::InitNew" );

    BOOL bRet = SfxObjectShell::InitNew( xStor );

    aDocument.MakeTable(0);
    //  zusaetzliche Tabellen werden von der ersten View angelegt,
    //  wenn bIsEmpty dann noch TRUE ist

    if( bRet )
    {
        Size aSize( (long) ( STD_COL_WIDTH           * HMM_PER_TWIPS * OLE_STD_CELLS_X ),
                    (long) ( ScGlobal::nStdRowHeight * HMM_PER_TWIPS * OLE_STD_CELLS_Y ) );
        // hier muss auch der Start angepasst werden
        SetVisAreaOrSize( Rectangle( Point(), aSize ), TRUE );
    }

    // InitOptions sets the document languages, must be called before CreateStandardStyles
    InitOptions();

    aDocument.GetStyleSheetPool()->CreateStandardStyles();
    aDocument.UpdStlShtPtrsFrmNms();

    //  SetDocumentModified ist in Load/InitNew nicht mehr erlaubt!

    InitItems();
    CalcOutputFactor();

    return bRet;
}

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

BOOL ScDocShell::IsEmpty() const
{
    return bIsEmpty;
}

void ScDocShell::ResetEmpty()
{
    bIsEmpty = FALSE;
}

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

void ScDocShell::InitItems()
{
    // AllItemSet fuer Controller mit benoetigten Items fuellen:

    if ( pFontList )
        delete pFontList;

    //  Druck-Optionen werden beim Drucken und evtl. in GetPrinter gesetzt

    pFontList = new FontList( GetPrinter(), Application::GetDefaultDevice() );
    PutItem( SvxFontListItem( pFontList, SID_ATTR_CHAR_FONTLIST ) );

    ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
    if (pDrawLayer)
    {
        PutItem( SvxColorTableItem  ( pDrawLayer->GetColorTable() ) );
        PutItem( SvxGradientListItem( pDrawLayer->GetGradientList() ) );
        PutItem( SvxHatchListItem   ( pDrawLayer->GetHatchList() ) );
        PutItem( SvxBitmapListItem  ( pDrawLayer->GetBitmapList() ) );
        PutItem( SvxDashListItem    ( pDrawLayer->GetDashList() ) );
        PutItem( SvxLineEndListItem ( pDrawLayer->GetLineEndList() ) );

            //  andere Anpassungen nach dem Anlegen des DrawLayers

        pDrawLayer->SetNotifyUndoActionHdl( LINK( pDocFunc, ScDocFunc, NotifyDrawUndo ) );

        //if (SfxObjectShell::HasSbxObject())
        pDrawLayer->UpdateBasic();          // DocShell-Basic in DrawPages setzen
    }
    else
    {
        //  always use global color table instead of local copy
        PutItem( SvxColorTableItem( XColorTable::GetStdColorTable() ) );
    }

    if ( !aDocument.GetForbiddenCharacters().isValid() ||
            !aDocument.IsValidAsianCompression() || !aDocument.IsValidAsianKerning() )
    {
        //  get settings from SvxAsianConfig
        SvxAsianConfig aAsian( sal_False );

        if ( !aDocument.GetForbiddenCharacters().isValid() )
        {
            // set forbidden characters if necessary
            uno::Sequence<lang::Locale> aLocales = aAsian.GetStartEndCharLocales();
            if (aLocales.getLength())
            {
                vos::ORef<SvxForbiddenCharactersTable> xForbiddenTable =
                        new SvxForbiddenCharactersTable( aDocument.GetServiceManager() );

                const lang::Locale* pLocales = aLocales.getConstArray();
                for (sal_Int32 i = 0; i < aLocales.getLength(); i++)
                {
                    i18n::ForbiddenCharacters aForbidden;
                    aAsian.GetStartEndChars( pLocales[i], aForbidden.beginLine, aForbidden.endLine );
                    LanguageType eLang = SvxLocaleToLanguage(pLocales[i]);
                    //pDoc->SetForbiddenCharacters( eLang, aForbidden );

                    xForbiddenTable->SetForbiddenCharacters( eLang, aForbidden );
                }

                aDocument.SetForbiddenCharacters( xForbiddenTable );
            }
        }

        if ( !aDocument.IsValidAsianCompression() )
        {
            // set compression mode from configuration if not already set (e.g. XML import)
            aDocument.SetAsianCompression( aAsian.GetCharDistanceCompression() );
        }

        if ( !aDocument.IsValidAsianKerning() )
        {
            // set asian punctuation kerning from configuration if not already set (e.g. XML import)
            aDocument.SetAsianKerning( !aAsian.IsKerningWesternTextOnly() );    // reversed
        }
    }
}

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

void ScDocShell::ResetDrawObjectShell()
{
    ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
    if (pDrawLayer)
        pDrawLayer->SetObjectShell( NULL );
}

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

void __EXPORT ScDocShell::Activate()
{
}

void __EXPORT ScDocShell::Deactivate()
{
}

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

ScDrawLayer* ScDocShell::MakeDrawLayer()
{
    ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
    if (!pDrawLayer)
    {
        RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::MakeDrawLayer" );

        aDocument.InitDrawLayer(this);
        pDrawLayer = aDocument.GetDrawLayer();
        InitItems();                                            // incl. Undo und Basic
        Broadcast( SfxSimpleHint( SC_HINT_DRWLAYER_NEW ) );
        if (nDocumentLock)
            pDrawLayer->setLock(TRUE);
    }
    return pDrawLayer;
}

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

void ScDocShell::RemoveUnknownObjects()
{
    //  OLE-Objekte loeschen, wenn kein Drawing-Objekt dazu existiert
    //  Loeschen wie in SvPersist::CleanUp

    ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
    uno::Sequence < rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();

        for( sal_Int32 i=0; i<aNames.getLength(); i++ )
        {
            String aObjName = aNames[i];
            BOOL bFound = FALSE;
            if ( pDrawLayer )
            {
                SCTAB nTabCount = static_cast<sal_Int16>(pDrawLayer->GetPageCount());
                for (SCTAB nTab=0; nTab<nTabCount && !bFound; nTab++)
                {
                    SdrPage* pPage = pDrawLayer->GetPage(static_cast<sal_uInt16>(nTab));
                    DBG_ASSERT(pPage,"Page ?");
                    if (pPage)
                    {
                        SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
                        SdrObject* pObject = aIter.Next();
                        while (pObject && !bFound)
                        {
                            // name from InfoObject is PersistName
                            if ( pObject->ISA(SdrOle2Obj) &&
                                    static_cast<SdrOle2Obj*>(pObject)->GetPersistName() == aObjName )
                                bFound = TRUE;
                            pObject = aIter.Next();
                        }
                    }
                }
            }

            if (!bFound)
            {
                //TODO/LATER: hacks not supported anymore
                //DBG_ASSERT(pEle->GetRefCount()==2, "Loeschen von referenziertem Storage");
                GetEmbeddedObjectContainer().RemoveEmbeddedObject( aObjName );
            }
            else
                i++;
        }
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.16.326); FILE MERGED 2005/09/05 15:04:30 rt 1.16.326.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: docsh2.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:45:55 $
 *
 *  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
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif

#pragma hdrstop

#include <svx/xtable.hxx>

#include "scitems.hxx"
#include <tools/gen.hxx>
#include <svtools/ctrltool.hxx>
#include <svx/flstitem.hxx>
#include <svx/drawitem.hxx>
#include <sfx2/printer.hxx>
#include <svtools/smplhint.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdoole2.hxx>
#include <vcl/svapp.hxx>
#include <svx/asiancfg.hxx>
#include <svx/forbiddencharacterstable.hxx>
#include <svx/unolingu.hxx>
#include <rtl/logfile.hxx>

// INCLUDE ---------------------------------------------------------------
/*
#include <svdrwetc.hxx>
#include <svdrwobx.hxx>
#include <sostor.hxx>
*/
#include "drwlayer.hxx"
#include "stlpool.hxx"
#include "docsh.hxx"
#include "docfunc.hxx"
#include "sc.hrc"

using namespace com::sun::star;

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

BOOL __EXPORT ScDocShell::InitNew( const uno::Reference < embed::XStorage >& xStor )
{
    RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::InitNew" );

    BOOL bRet = SfxObjectShell::InitNew( xStor );

    aDocument.MakeTable(0);
    //  zusaetzliche Tabellen werden von der ersten View angelegt,
    //  wenn bIsEmpty dann noch TRUE ist

    if( bRet )
    {
        Size aSize( (long) ( STD_COL_WIDTH           * HMM_PER_TWIPS * OLE_STD_CELLS_X ),
                    (long) ( ScGlobal::nStdRowHeight * HMM_PER_TWIPS * OLE_STD_CELLS_Y ) );
        // hier muss auch der Start angepasst werden
        SetVisAreaOrSize( Rectangle( Point(), aSize ), TRUE );
    }

    // InitOptions sets the document languages, must be called before CreateStandardStyles
    InitOptions();

    aDocument.GetStyleSheetPool()->CreateStandardStyles();
    aDocument.UpdStlShtPtrsFrmNms();

    //  SetDocumentModified ist in Load/InitNew nicht mehr erlaubt!

    InitItems();
    CalcOutputFactor();

    return bRet;
}

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

BOOL ScDocShell::IsEmpty() const
{
    return bIsEmpty;
}

void ScDocShell::ResetEmpty()
{
    bIsEmpty = FALSE;
}

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

void ScDocShell::InitItems()
{
    // AllItemSet fuer Controller mit benoetigten Items fuellen:

    if ( pFontList )
        delete pFontList;

    //  Druck-Optionen werden beim Drucken und evtl. in GetPrinter gesetzt

    pFontList = new FontList( GetPrinter(), Application::GetDefaultDevice() );
    PutItem( SvxFontListItem( pFontList, SID_ATTR_CHAR_FONTLIST ) );

    ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
    if (pDrawLayer)
    {
        PutItem( SvxColorTableItem  ( pDrawLayer->GetColorTable() ) );
        PutItem( SvxGradientListItem( pDrawLayer->GetGradientList() ) );
        PutItem( SvxHatchListItem   ( pDrawLayer->GetHatchList() ) );
        PutItem( SvxBitmapListItem  ( pDrawLayer->GetBitmapList() ) );
        PutItem( SvxDashListItem    ( pDrawLayer->GetDashList() ) );
        PutItem( SvxLineEndListItem ( pDrawLayer->GetLineEndList() ) );

            //  andere Anpassungen nach dem Anlegen des DrawLayers

        pDrawLayer->SetNotifyUndoActionHdl( LINK( pDocFunc, ScDocFunc, NotifyDrawUndo ) );

        //if (SfxObjectShell::HasSbxObject())
        pDrawLayer->UpdateBasic();          // DocShell-Basic in DrawPages setzen
    }
    else
    {
        //  always use global color table instead of local copy
        PutItem( SvxColorTableItem( XColorTable::GetStdColorTable() ) );
    }

    if ( !aDocument.GetForbiddenCharacters().isValid() ||
            !aDocument.IsValidAsianCompression() || !aDocument.IsValidAsianKerning() )
    {
        //  get settings from SvxAsianConfig
        SvxAsianConfig aAsian( sal_False );

        if ( !aDocument.GetForbiddenCharacters().isValid() )
        {
            // set forbidden characters if necessary
            uno::Sequence<lang::Locale> aLocales = aAsian.GetStartEndCharLocales();
            if (aLocales.getLength())
            {
                vos::ORef<SvxForbiddenCharactersTable> xForbiddenTable =
                        new SvxForbiddenCharactersTable( aDocument.GetServiceManager() );

                const lang::Locale* pLocales = aLocales.getConstArray();
                for (sal_Int32 i = 0; i < aLocales.getLength(); i++)
                {
                    i18n::ForbiddenCharacters aForbidden;
                    aAsian.GetStartEndChars( pLocales[i], aForbidden.beginLine, aForbidden.endLine );
                    LanguageType eLang = SvxLocaleToLanguage(pLocales[i]);
                    //pDoc->SetForbiddenCharacters( eLang, aForbidden );

                    xForbiddenTable->SetForbiddenCharacters( eLang, aForbidden );
                }

                aDocument.SetForbiddenCharacters( xForbiddenTable );
            }
        }

        if ( !aDocument.IsValidAsianCompression() )
        {
            // set compression mode from configuration if not already set (e.g. XML import)
            aDocument.SetAsianCompression( aAsian.GetCharDistanceCompression() );
        }

        if ( !aDocument.IsValidAsianKerning() )
        {
            // set asian punctuation kerning from configuration if not already set (e.g. XML import)
            aDocument.SetAsianKerning( !aAsian.IsKerningWesternTextOnly() );    // reversed
        }
    }
}

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

void ScDocShell::ResetDrawObjectShell()
{
    ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
    if (pDrawLayer)
        pDrawLayer->SetObjectShell( NULL );
}

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

void __EXPORT ScDocShell::Activate()
{
}

void __EXPORT ScDocShell::Deactivate()
{
}

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

ScDrawLayer* ScDocShell::MakeDrawLayer()
{
    ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
    if (!pDrawLayer)
    {
        RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::MakeDrawLayer" );

        aDocument.InitDrawLayer(this);
        pDrawLayer = aDocument.GetDrawLayer();
        InitItems();                                            // incl. Undo und Basic
        Broadcast( SfxSimpleHint( SC_HINT_DRWLAYER_NEW ) );
        if (nDocumentLock)
            pDrawLayer->setLock(TRUE);
    }
    return pDrawLayer;
}

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

void ScDocShell::RemoveUnknownObjects()
{
    //  OLE-Objekte loeschen, wenn kein Drawing-Objekt dazu existiert
    //  Loeschen wie in SvPersist::CleanUp

    ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
    uno::Sequence < rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();

        for( sal_Int32 i=0; i<aNames.getLength(); i++ )
        {
            String aObjName = aNames[i];
            BOOL bFound = FALSE;
            if ( pDrawLayer )
            {
                SCTAB nTabCount = static_cast<sal_Int16>(pDrawLayer->GetPageCount());
                for (SCTAB nTab=0; nTab<nTabCount && !bFound; nTab++)
                {
                    SdrPage* pPage = pDrawLayer->GetPage(static_cast<sal_uInt16>(nTab));
                    DBG_ASSERT(pPage,"Page ?");
                    if (pPage)
                    {
                        SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
                        SdrObject* pObject = aIter.Next();
                        while (pObject && !bFound)
                        {
                            // name from InfoObject is PersistName
                            if ( pObject->ISA(SdrOle2Obj) &&
                                    static_cast<SdrOle2Obj*>(pObject)->GetPersistName() == aObjName )
                                bFound = TRUE;
                            pObject = aIter.Next();
                        }
                    }
                }
            }

            if (!bFound)
            {
                //TODO/LATER: hacks not supported anymore
                //DBG_ASSERT(pEle->GetRefCount()==2, "Loeschen von referenziertem Storage");
                GetEmbeddedObjectContainer().RemoveEmbeddedObject( aObjName );
            }
            else
                i++;
        }
}

<|endoftext|>


<commit_before><commit_msg>Let's not forget to free the SdrOle2Obj instance here.<commit_after><|endoftext|>


<commit_before><commit_msg>fdo#50587: Remove totally mis-placed 'static' keyword.<commit_after><|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2012 Research In Motion
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtBluetooth module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qbluetoothlocaldevice.h"
#include "qbluetoothaddress.h"
#include "qbluetoothlocaldevice_p.h"
#include "qnx/ppshelpers_p.h"

QT_BEGIN_NAMESPACE_BLUETOOTH

QBluetoothLocalDevice::QBluetoothLocalDevice(QObject *parent)
:   QObject(parent)
{
    this->d_ptr = new QBluetoothLocalDevicePrivate(this);
    this->d_ptr->isValidDevice = true; //assume single local device on QNX
}

QBluetoothLocalDevice::QBluetoothLocalDevice(const QBluetoothAddress &address, QObject *parent)
: QObject(parent)
{
    this->d_ptr = new QBluetoothLocalDevicePrivate(this);

    //works since we assume a single local device on QNX
    this->d_ptr->isValidDevice = (QBluetoothLocalDevicePrivate::address() == address);
}

QString QBluetoothLocalDevice::name() const
{
    if (this->d_ptr->isValid())
        return this->d_ptr->name();
    return QString();
}

QBluetoothAddress QBluetoothLocalDevice::address() const
{
    if (this->d_ptr->isValid())
        return this->d_ptr->address();
    return QBluetoothAddress();
}

void QBluetoothLocalDevice::powerOn()
{
    this->d_ptr->powerOn();
}

void QBluetoothLocalDevice::setHostMode(QBluetoothLocalDevice::HostMode mode)
{
    this->d_ptr->setHostMode(mode);
}

QBluetoothLocalDevice::HostMode QBluetoothLocalDevice::hostMode() const
{
    return this->d_ptr->hostMode();
}

QList<QBluetoothHostInfo> QBluetoothLocalDevice::allDevices()
{
    //We only have one device
    QList<QBluetoothHostInfo> localDevices;
    QBluetoothHostInfo hostInfo;
    hostInfo.setName(QBluetoothLocalDevicePrivate::name());
    hostInfo.setAddress(QBluetoothLocalDevicePrivate::address());
    localDevices.append(hostInfo);
    return localDevices;
}

void QBluetoothLocalDevice::requestPairing(const QBluetoothAddress &address, Pairing pairing)
{
    if (address.isNull()) {
        QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
                                  Q_ARG(QBluetoothLocalDevice::Error, QBluetoothLocalDevice::PairingError));
        return;
    }

    const Pairing current_pairing = pairingStatus(address);
    if (current_pairing == pairing) {
        QMetaObject::invokeMethod(this, "pairingFinished", Qt::QueuedConnection, Q_ARG(QBluetoothAddress, address),
                                  Q_ARG(QBluetoothLocalDevice::Pairing, pairing));
        return;
    }
    d_ptr->requestPairing(address, pairing);
}

QBluetoothLocalDevice::Pairing QBluetoothLocalDevice::pairingStatus(const QBluetoothAddress &address) const
{
    if (!isValid())
        return Unpaired;

    QVariant status = ppsRemoteDeviceStatus(address.toString().toLocal8Bit(), "paired");
    if (status.toBool())
        return Paired;
    return Unpaired;
}

void QBluetoothLocalDevice::pairingConfirmation(bool confirmation)
{
    Q_UNUSED(confirmation);
}

QBluetoothLocalDevicePrivate::QBluetoothLocalDevicePrivate(QBluetoothLocalDevice *q)
    : q_ptr(q)
{
    ppsRegisterControl();
    ppsRegisterForEvent(QStringLiteral("access_changed"), this);
    ppsRegisterForEvent(QStringLiteral("pairing_complete"), this);
    ppsRegisterForEvent(QStringLiteral("device_deleted"), this);
}

QBluetoothLocalDevicePrivate::~QBluetoothLocalDevicePrivate()
{
    ppsUnregisterControl(this);
    ppsUnregisterForEvent(QStringLiteral("access_changed"), this);
    ppsUnregisterForEvent(QStringLiteral("pairing_complete"), this);
    ppsUnregisterForEvent(QStringLiteral("device_deleted"), this);
}

bool QBluetoothLocalDevicePrivate::isValid() const
{
    return isValidDevice;
}

QBluetoothAddress QBluetoothLocalDevicePrivate::address()
{
    return QBluetoothAddress(ppsReadSetting("btaddr").toString());
}

QString QBluetoothLocalDevicePrivate::name()
{
    return ppsReadSetting("name").toString();
}

void QBluetoothLocalDevicePrivate::powerOn()
{
    if (isValid())
        ppsSendControlMessage("radio_init", this);
}

void QBluetoothLocalDevicePrivate::powerOff()
{
    if (isValid())
        ppsSendControlMessage("radio_shutdown", this);
}

void QBluetoothLocalDevicePrivate::setHostMode(QBluetoothLocalDevice::HostMode mode)
{
    if (!isValid())
        return;

    QBluetoothLocalDevice::HostMode currentHostMode = hostMode();
    if (currentHostMode == mode){
        return;
    }
    //If the device is in PowerOff state and the profile is changed then the power has to be turned on
    if (currentHostMode == QBluetoothLocalDevice::HostPoweredOff) {
        qBBBluetoothDebug() << "Powering on";
        powerOn();
    }

    if (mode == QBluetoothLocalDevice::HostPoweredOff) {
        powerOff();
    }
    else if (mode == QBluetoothLocalDevice::HostDiscoverable) { //General discoverable and connectable.
        setAccess(1);
    }
    else if (mode == QBluetoothLocalDevice::HostConnectable) { //Connectable but not discoverable.
        setAccess(3);
    }
    else if (mode == QBluetoothLocalDevice::HostDiscoverableLimitedInquiry) { //Limited discoverable and connectable.
        setAccess(2);
    }
}

void QBluetoothLocalDevicePrivate::requestPairing(const QBluetoothAddress &address,
                                                  QBluetoothLocalDevice::Pairing pairing)
{
    if (pairing == QBluetoothLocalDevice::Paired || pairing == QBluetoothLocalDevice::AuthorizedPaired) {
        ppsSendControlMessage("initiate_pairing", QStringLiteral("{\"addr\":\"%1\"}").arg(address.toString()),
                          this);
    } else {
        ppsSendControlMessage("remove_device", QStringLiteral("{\"addr\":\"%1\"}").arg(address.toString()),
                          this);
    }
}

QBluetoothLocalDevice::HostMode QBluetoothLocalDevicePrivate::hostMode() const
{
    if (!isValid())
        return QBluetoothLocalDevice::HostPoweredOff;

    if (!ppsReadSetting("enabled").toBool())
        return QBluetoothLocalDevice::HostPoweredOff;

    int hostMode = ppsReadSetting("accessibility").toInt();

    if (hostMode == 1) //General discoverable and connectable.
        return QBluetoothLocalDevice::HostDiscoverable;
    else if (hostMode == 3)  //Connectable but not discoverable.
        return QBluetoothLocalDevice::HostConnectable;
    else if (hostMode == 2)  //Limited discoverable and connectable.
        return QBluetoothLocalDevice::HostDiscoverableLimitedInquiry;
    else
        return QBluetoothLocalDevice::HostPoweredOff;
}

extern int __newHostMode;

void QBluetoothLocalDevicePrivate::setAccess(int access)
{
    if (!ppsReadSetting("enabled").toBool()) { //We cannot set the host mode until BT is fully powered up
        __newHostMode = access;
    } else {
        ppsSendControlMessage("set_access", QStringLiteral("{\"access\":%1}").arg(access), 0);

    }
}

void QBluetoothLocalDevicePrivate::controlReply(ppsResult result)
{
    qBBBluetoothDebug() << Q_FUNC_INFO << result.msg << result.dat;
    if (!result.errorMsg.isEmpty()) {
        qWarning() << Q_FUNC_INFO << result.errorMsg;
        if (result.msg == QStringLiteral("initiate_pairing"))
            q_ptr->error(QBluetoothLocalDevice::PairingError);
        else
            q_ptr->error(QBluetoothLocalDevice::UnknownError);
    }
}

void QBluetoothLocalDevicePrivate::controlEvent(ppsResult result)
{
    qBBBluetoothDebug() << Q_FUNC_INFO << "Control Event" << result.msg;
    if (result.msg == QStringLiteral("access_changed")) {
        if (__newHostMode == -1 && result.dat.size() > 1 &&
                result.dat.first() == QStringLiteral("level")) {
            QBluetoothLocalDevice::HostMode newHostMode = hostMode();
            qBBBluetoothDebug() << "New Host mode" << newHostMode;
            Q_EMIT q_ptr->hostModeStateChanged(newHostMode);
        }
    } else if (result.msg == QStringLiteral("pairing_complete")) {
        qBBBluetoothDebug() << "pairing completed";
        if (result.dat.contains(QStringLiteral("addr"))) {
            const QBluetoothAddress address = QBluetoothAddress(
                        result.dat.at(result.dat.indexOf(QStringLiteral("addr")) + 1));

            QBluetoothLocalDevice::Pairing pairingStatus = QBluetoothLocalDevice::Paired;

            if (result.dat.contains(QStringLiteral("trusted")) &&
                    result.dat.at(result.dat.indexOf(QStringLiteral("trusted")) + 1) == QStringLiteral("true")) {
                pairingStatus = QBluetoothLocalDevice::AuthorizedPaired;
            }
            qBBBluetoothDebug() << "pairing completed" << address.toString();
            Q_EMIT q_ptr->pairingFinished(address, pairingStatus);
        }
    } else if (result.msg == QStringLiteral("device_deleted")) {
        qBBBluetoothDebug() << "device deleted";
        if (result.dat.contains(QStringLiteral("addr"))) {
            const QBluetoothAddress address = QBluetoothAddress(
                        result.dat.at(result.dat.indexOf(QStringLiteral("addr")) + 1));
            Q_EMIT q_ptr->pairingFinished(address, QBluetoothLocalDevice::Unpaired);
        }
    }
}

QT_END_NAMESPACE_BLUETOOTH
<commit_msg>QNX: Emiting HostPoweredOff when BT is shut down<commit_after>/***************************************************************************
**
** Copyright (C) 2012 Research In Motion
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtBluetooth module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qbluetoothlocaldevice.h"
#include "qbluetoothaddress.h"
#include "qbluetoothlocaldevice_p.h"
#include "qnx/ppshelpers_p.h"

QT_BEGIN_NAMESPACE_BLUETOOTH

QBluetoothLocalDevice::QBluetoothLocalDevice(QObject *parent)
:   QObject(parent)
{
    this->d_ptr = new QBluetoothLocalDevicePrivate(this);
    this->d_ptr->isValidDevice = true; //assume single local device on QNX
}

QBluetoothLocalDevice::QBluetoothLocalDevice(const QBluetoothAddress &address, QObject *parent)
: QObject(parent)
{
    this->d_ptr = new QBluetoothLocalDevicePrivate(this);

    //works since we assume a single local device on QNX
    this->d_ptr->isValidDevice = (QBluetoothLocalDevicePrivate::address() == address);
}

QString QBluetoothLocalDevice::name() const
{
    if (this->d_ptr->isValid())
        return this->d_ptr->name();
    return QString();
}

QBluetoothAddress QBluetoothLocalDevice::address() const
{
    if (this->d_ptr->isValid())
        return this->d_ptr->address();
    return QBluetoothAddress();
}

void QBluetoothLocalDevice::powerOn()
{
    this->d_ptr->powerOn();
}

void QBluetoothLocalDevice::setHostMode(QBluetoothLocalDevice::HostMode mode)
{
    this->d_ptr->setHostMode(mode);
}

QBluetoothLocalDevice::HostMode QBluetoothLocalDevice::hostMode() const
{
    return this->d_ptr->hostMode();
}

QList<QBluetoothHostInfo> QBluetoothLocalDevice::allDevices()
{
    //We only have one device
    QList<QBluetoothHostInfo> localDevices;
    QBluetoothHostInfo hostInfo;
    hostInfo.setName(QBluetoothLocalDevicePrivate::name());
    hostInfo.setAddress(QBluetoothLocalDevicePrivate::address());
    localDevices.append(hostInfo);
    return localDevices;
}

void QBluetoothLocalDevice::requestPairing(const QBluetoothAddress &address, Pairing pairing)
{
    if (address.isNull()) {
        QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
                                  Q_ARG(QBluetoothLocalDevice::Error, QBluetoothLocalDevice::PairingError));
        return;
    }

    const Pairing current_pairing = pairingStatus(address);
    if (current_pairing == pairing) {
        QMetaObject::invokeMethod(this, "pairingFinished", Qt::QueuedConnection, Q_ARG(QBluetoothAddress, address),
                                  Q_ARG(QBluetoothLocalDevice::Pairing, pairing));
        return;
    }
    d_ptr->requestPairing(address, pairing);
}

QBluetoothLocalDevice::Pairing QBluetoothLocalDevice::pairingStatus(const QBluetoothAddress &address) const
{
    if (!isValid())
        return Unpaired;

    QVariant status = ppsRemoteDeviceStatus(address.toString().toLocal8Bit(), "paired");
    if (status.toBool())
        return Paired;
    return Unpaired;
}

void QBluetoothLocalDevice::pairingConfirmation(bool confirmation)
{
    Q_UNUSED(confirmation);
}

QBluetoothLocalDevicePrivate::QBluetoothLocalDevicePrivate(QBluetoothLocalDevice *q)
    : q_ptr(q)
{
    ppsRegisterControl();
    ppsRegisterForEvent(QStringLiteral("access_changed"), this);
    ppsRegisterForEvent(QStringLiteral("pairing_complete"), this);
    ppsRegisterForEvent(QStringLiteral("device_deleted"), this);
    ppsRegisterForEvent(QStringLiteral("radio_shutdown"), this);
}

QBluetoothLocalDevicePrivate::~QBluetoothLocalDevicePrivate()
{
    ppsUnregisterControl(this);
    ppsUnregisterForEvent(QStringLiteral("access_changed"), this);
    ppsUnregisterForEvent(QStringLiteral("pairing_complete"), this);
    ppsUnregisterForEvent(QStringLiteral("device_deleted"), this);
    ppsUnregisterForEvent(QStringLiteral("radio_shutdown"), this);
}

bool QBluetoothLocalDevicePrivate::isValid() const
{
    return isValidDevice;
}

QBluetoothAddress QBluetoothLocalDevicePrivate::address()
{
    return QBluetoothAddress(ppsReadSetting("btaddr").toString());
}

QString QBluetoothLocalDevicePrivate::name()
{
    return ppsReadSetting("name").toString();
}

void QBluetoothLocalDevicePrivate::powerOn()
{
    if (isValid())
        ppsSendControlMessage("radio_init", this);
}

void QBluetoothLocalDevicePrivate::powerOff()
{
    if (isValid())
        ppsSendControlMessage("radio_shutdown", this);
}

void QBluetoothLocalDevicePrivate::setHostMode(QBluetoothLocalDevice::HostMode mode)
{
    if (!isValid())
        return;

    QBluetoothLocalDevice::HostMode currentHostMode = hostMode();
    if (currentHostMode == mode){
        return;
    }
    //If the device is in PowerOff state and the profile is changed then the power has to be turned on
    if (currentHostMode == QBluetoothLocalDevice::HostPoweredOff) {
        qBBBluetoothDebug() << "Powering on";
        powerOn();
    }

    if (mode == QBluetoothLocalDevice::HostPoweredOff) {
        powerOff();
    }
    else if (mode == QBluetoothLocalDevice::HostDiscoverable) { //General discoverable and connectable.
        setAccess(1);
    }
    else if (mode == QBluetoothLocalDevice::HostConnectable) { //Connectable but not discoverable.
        setAccess(3);
    }
    else if (mode == QBluetoothLocalDevice::HostDiscoverableLimitedInquiry) { //Limited discoverable and connectable.
        setAccess(2);
    }
}

void QBluetoothLocalDevicePrivate::requestPairing(const QBluetoothAddress &address,
                                                  QBluetoothLocalDevice::Pairing pairing)
{
    if (pairing == QBluetoothLocalDevice::Paired || pairing == QBluetoothLocalDevice::AuthorizedPaired) {
        ppsSendControlMessage("initiate_pairing", QStringLiteral("{\"addr\":\"%1\"}").arg(address.toString()),
                          this);
    } else {
        ppsSendControlMessage("remove_device", QStringLiteral("{\"addr\":\"%1\"}").arg(address.toString()),
                          this);
    }
}

QBluetoothLocalDevice::HostMode QBluetoothLocalDevicePrivate::hostMode() const
{
    if (!isValid())
        return QBluetoothLocalDevice::HostPoweredOff;

    if (!ppsReadSetting("enabled").toBool())
        return QBluetoothLocalDevice::HostPoweredOff;

    int hostMode = ppsReadSetting("accessibility").toInt();

    if (hostMode == 1) //General discoverable and connectable.
        return QBluetoothLocalDevice::HostDiscoverable;
    else if (hostMode == 3)  //Connectable but not discoverable.
        return QBluetoothLocalDevice::HostConnectable;
    else if (hostMode == 2)  //Limited discoverable and connectable.
        return QBluetoothLocalDevice::HostDiscoverableLimitedInquiry;
    else
        return QBluetoothLocalDevice::HostPoweredOff;
}

extern int __newHostMode;

void QBluetoothLocalDevicePrivate::setAccess(int access)
{
    if (!ppsReadSetting("enabled").toBool()) { //We cannot set the host mode until BT is fully powered up
        __newHostMode = access;
    } else {
        ppsSendControlMessage("set_access", QStringLiteral("{\"access\":%1}").arg(access), 0);

    }
}

void QBluetoothLocalDevicePrivate::controlReply(ppsResult result)
{
    qBBBluetoothDebug() << Q_FUNC_INFO << result.msg << result.dat;
    if (!result.errorMsg.isEmpty()) {
        qWarning() << Q_FUNC_INFO << result.errorMsg;
        if (result.msg == QStringLiteral("initiate_pairing"))
            q_ptr->error(QBluetoothLocalDevice::PairingError);
        else
            q_ptr->error(QBluetoothLocalDevice::UnknownError);
    }
}

void QBluetoothLocalDevicePrivate::controlEvent(ppsResult result)
{
    qBBBluetoothDebug() << Q_FUNC_INFO << "Control Event" << result.msg;
    if (result.msg == QStringLiteral("access_changed")) {
        if (__newHostMode == -1 && result.dat.size() > 1 &&
                result.dat.first() == QStringLiteral("level")) {
            QBluetoothLocalDevice::HostMode newHostMode = hostMode();
            qBBBluetoothDebug() << "New Host mode" << newHostMode;
            Q_EMIT q_ptr->hostModeStateChanged(newHostMode);
        }
    } else if (result.msg == QStringLiteral("pairing_complete")) {
        qBBBluetoothDebug() << "pairing completed";
        if (result.dat.contains(QStringLiteral("addr"))) {
            const QBluetoothAddress address = QBluetoothAddress(
                        result.dat.at(result.dat.indexOf(QStringLiteral("addr")) + 1));

            QBluetoothLocalDevice::Pairing pairingStatus = QBluetoothLocalDevice::Paired;

            if (result.dat.contains(QStringLiteral("trusted")) &&
                    result.dat.at(result.dat.indexOf(QStringLiteral("trusted")) + 1) == QStringLiteral("true")) {
                pairingStatus = QBluetoothLocalDevice::AuthorizedPaired;
            }
            qBBBluetoothDebug() << "pairing completed" << address.toString();
            Q_EMIT q_ptr->pairingFinished(address, pairingStatus);
        }
    } else if (result.msg == QStringLiteral("device_deleted")) {
        qBBBluetoothDebug() << "device deleted";
        if (result.dat.contains(QStringLiteral("addr"))) {
            const QBluetoothAddress address = QBluetoothAddress(
                        result.dat.at(result.dat.indexOf(QStringLiteral("addr")) + 1));
            Q_EMIT q_ptr->pairingFinished(address, QBluetoothLocalDevice::Unpaired);
        }
    } else if (result.msg == QStringLiteral("radio_shutdown")) {
        qBBBluetoothDebug() << "radio shutdown";
        Q_EMIT q_ptr->hostModeStateChanged(QBluetoothLocalDevice::HostPoweredOff);
    }
}

QT_END_NAMESPACE_BLUETOOTH
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <exception>
#include <test/unit/lang/utility.hpp>

TEST(langParserStatement2Grammar, addConditionalCondition) {
  test_parsable("conditional_condition_good");
  test_throws("conditional_condition_bad_1",
              "conditions in if-else");
  test_throws("conditional_condition_bad_2",
              "conditions in if-else");
}

TEST(langParserStatementGrammar, validateIntExpr2) {
  test_parsable("validate_int_expr2_good");
  test_throws("validate_int_expr2_bad1",
              "expression denoting integer required");
  test_throws("validate_int_expr2_bad2",
              "expression denoting integer required");
  test_throws("validate_int_expr2_bad3",
              "dimension declaration requires expression denoting integer");
  test_throws("validate_int_expr2_bad4",
              "expression denoting integer required");
}

TEST(langParserStatementGrammar, validateAllowSample) {
  test_throws("validate_allow_sample_bad1",
              "Sampling statements (~) and increment_log_prob() are");
  test_throws("validate_allow_sample_bad2",
              "Sampling statements (~) and increment_log_prob() are");
  test_throws("validate_allow_sample_bad3",
              "Sampling statements (~) and increment_log_prob() are");
}

TEST(langParserStatementGrammar, targetIncrement) {
  test_parsable("increment-target");
}

TEST(langParserStatementGrammar, targetReserved) {
  test_throws("target-reserved",
              "variable identifier (name) may not be reserved word");
  test_throws("target-reserved",
              "found identifier=target");
}

TEST(langParserStatementGrammar, deprecateIncrementLogProb) {
  test_warning("deprecate-increment-log-prob",
               "Warning (non-fatal): increment_log_prob(...);"
               " is deprecated and will be removed in the future.");
  test_warning("deprecate-increment-log-prob",
               "  Use target += ...; instead.");
}

TEST(langParserStatementGrammarDef, jacobianAdjustmentWarning) {
  test_parsable("validate_jacobian_warning_good");
  test_warning("validate_jacobian_warning1",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
  test_warning("validate_jacobian_warning2",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
  test_warning("validate_jacobian_warning3",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
  test_warning("validate_jacobian_warning4",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
  test_warning("validate_jacobian_warning5",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
  test_warning("validate_jacobian_warning6",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
}

TEST(langParserStatementGrammarDef, jacobianUserFacing) {
  test_warning("validate_jacobian_warning_user",
               "exp(y[1]) ~ normal(...)");
}

TEST(langParserStatementGrammarDef, comparisonsInBoundsTest) {
  test_parsable("validate_bounds_comparison");
  EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_bounds1.stan"),
               std::invalid_argument);
}

TEST(langParserStatementGrammar, validateAssignmentTypes) {
  test_throws("bad_var_assignment_type1",
              "mismatch in assignment");
  test_throws("bad_var_assignment_type2",
              "mismatch in assignment");
  test_throws("bad_var_assignment_vec_arr",
              "mismatch in assignment");
}

TEST(langParserStatementGrammar, assignRealToIntMessage) {
  test_throws("assign_real_to_int",
              "Base type mismatch in assignment");
}

TEST(langParserStatementGrammar, useCdfWithSamplingNotation) {
  test_throws("cdf-sample",
              "CDF and CCDF functions may not be used with sampling notation.");
  test_throws("ccdf-sample",
              "CDF and CCDF functions may not be used with sampling notation.");
  test_throws("multiply_sample",
              "Only distribution names can be used with sampling (~) notation");
  test_throws("binomial_coefficient_sample",
              "Only distribution names can be used with sampling (~) notation");
}

TEST(langParserStatementGrammar, targetFunGetLpDeprecated) {
  test_warning("get-lp-deprecate",
               "Warning (non-fatal): get_lp() function deprecated.");
  test_warning("get-lp-deprecate",
               "  It will be removed in a future release.");
  test_warning("get-lp-deprecate",
               "  Use target() instead.");
  test_throws("get-lp-target-data",
              "Function target() or functions suffixed with _lp only"
              " allowed in transformed parameter block");
  test_throws("get-lp-target-data",
              "Found function = target or get_lp"
              " in block = transformed data");
  test_parsable("get-lp-target");
}

TEST(langParserStatementGrammar, removeLpDoubleUnderscore) {
  test_throws("lp-error",
              "ERROR (fatal):  Use of lp__ is no longer supported.");
  test_throws("lp-error",
              "  Use target += ... statement to increment log density.");
  test_throws("lp-error",
              "  Use target() function to get log density.");
}

TEST(langParserStatementGrammar, plusEqualsGood) {
  test_parsable("compound-assign/plus_equals_prim");
  test_parsable("compound-assign/plus_equals_container");
  test_parsable("compound-assign/plus_equals_manual");
}

TEST(langParserStatementGrammar, minusEqualsGood) {
  test_parsable("compound-assign/minus_equals_prim");
  test_parsable("compound-assign/minus_equals_container");
  test_parsable("compound-assign/minus_equals_manual");
}

TEST(langParserStatementGrammar, multiplyEqualsGood) {
  test_parsable("compound-assign/multiply_equals_prim");
  test_parsable("compound-assign/multiply_equals_container");
  test_parsable("compound-assign/multiply_equals_manual");
}

TEST(langParserStatementGrammar, divideEqualsGood) {
  test_parsable("compound-assign/divide_equals_prim");
  test_parsable("compound-assign/divide_equals_container");
  test_parsable("compound-assign/divide_equals_manual");
}

TEST(langParserStatementGrammar, eltOpEqualsGood) {
  test_parsable("compound-assign/elt_multiply_equals");
  test_parsable("compound-assign/elt_divide_equals");
}

TEST(langParserStatementGrammar, plusEqualsBad) {
  test_throws("compound-assign/plus_equals_bad_var_lhs","does not exist");
  test_throws("compound-assign/plus_equals_bad_var_lhs2",
              "Cannot assign to variable outside of declaration block");
  test_throws("compound-assign/plus_equals_bad_lhs_idxs",
              "Too many indexes for variable");
  test_throws("compound-assign/plus_equals_bad_var_rhs",
              "does not exist");
  test_throws("compound-assign/plus_equals_type_mismatch",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_type_mismatch2",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_matrix_array",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_matrix_array2",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_prim_array",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_row_vec_array",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_row_vec_array",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_bad_init",
              "PARSER EXPECTED: \";\"");
}

TEST(langParserStatementGrammar, timesEqualsBad) {
  test_throws("compound-assign/times_equals_matrix_array",
              "Cannot apply operator '*='");
}

TEST(langParserStatementGrammar, eltOpEqualsBad) {
  test_throws("compound-assign/elt_times_equals_prim",
              "Cannot apply element-wise operation to scalar");
  test_throws("compound-assign/elt_divide_equals_prim",
              "Cannot apply element-wise operation to scalar");
}
<commit_msg>fixed test that started failing for silly reason after I changed the error messaging of for loops<commit_after>#include <gtest/gtest.h>
#include <exception>
#include <test/unit/lang/utility.hpp>

TEST(langParserStatement2Grammar, addConditionalCondition) {
  test_parsable("conditional_condition_good");
  test_throws("conditional_condition_bad_1",
              "conditions in if-else");
  test_throws("conditional_condition_bad_2",
              "conditions in if-else");
}

TEST(langParserStatementGrammar, validateIntExpr2) {
  test_parsable("validate_int_expr2_good");
  test_throws("validate_int_expr2_bad1",
              "loop must be over container or range");
  test_throws("validate_int_expr2_bad2",
              "loop must be over container or range");
  test_throws("validate_int_expr2_bad3",
              "dimension declaration requires expression denoting integer");
  test_throws("validate_int_expr2_bad4",
              "loop must be over container or range");
}

TEST(langParserStatementGrammar, validateAllowSample) {
  test_throws("validate_allow_sample_bad1",
              "Sampling statements (~) and increment_log_prob() are");
  test_throws("validate_allow_sample_bad2",
              "Sampling statements (~) and increment_log_prob() are");
  test_throws("validate_allow_sample_bad3",
              "Sampling statements (~) and increment_log_prob() are");
}

TEST(langParserStatementGrammar, targetIncrement) {
  test_parsable("increment-target");
}

TEST(langParserStatementGrammar, targetReserved) {
  test_throws("target-reserved",
              "variable identifier (name) may not be reserved word");
  test_throws("target-reserved",
              "found identifier=target");
}

TEST(langParserStatementGrammar, deprecateIncrementLogProb) {
  test_warning("deprecate-increment-log-prob",
               "Warning (non-fatal): increment_log_prob(...);"
               " is deprecated and will be removed in the future.");
  test_warning("deprecate-increment-log-prob",
               "  Use target += ...; instead.");
}

TEST(langParserStatementGrammarDef, jacobianAdjustmentWarning) {
  test_parsable("validate_jacobian_warning_good");
  test_warning("validate_jacobian_warning1",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
  test_warning("validate_jacobian_warning2",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
  test_warning("validate_jacobian_warning3",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
  test_warning("validate_jacobian_warning4",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
  test_warning("validate_jacobian_warning5",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
  test_warning("validate_jacobian_warning6",
               "you need to include a target += statement with"
               " the log absolute determinant of the Jacobian of the transform.");
}

TEST(langParserStatementGrammarDef, jacobianUserFacing) {
  test_warning("validate_jacobian_warning_user",
               "exp(y[1]) ~ normal(...)");
}

TEST(langParserStatementGrammarDef, comparisonsInBoundsTest) {
  test_parsable("validate_bounds_comparison");
  EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_bounds1.stan"),
               std::invalid_argument);
}

TEST(langParserStatementGrammar, validateAssignmentTypes) {
  test_throws("bad_var_assignment_type1",
              "mismatch in assignment");
  test_throws("bad_var_assignment_type2",
              "mismatch in assignment");
  test_throws("bad_var_assignment_vec_arr",
              "mismatch in assignment");
}

TEST(langParserStatementGrammar, assignRealToIntMessage) {
  test_throws("assign_real_to_int",
              "Base type mismatch in assignment");
}

TEST(langParserStatementGrammar, useCdfWithSamplingNotation) {
  test_throws("cdf-sample",
              "CDF and CCDF functions may not be used with sampling notation.");
  test_throws("ccdf-sample",
              "CDF and CCDF functions may not be used with sampling notation.");
  test_throws("multiply_sample",
              "Only distribution names can be used with sampling (~) notation");
  test_throws("binomial_coefficient_sample",
              "Only distribution names can be used with sampling (~) notation");
}

TEST(langParserStatementGrammar, targetFunGetLpDeprecated) {
  test_warning("get-lp-deprecate",
               "Warning (non-fatal): get_lp() function deprecated.");
  test_warning("get-lp-deprecate",
               "  It will be removed in a future release.");
  test_warning("get-lp-deprecate",
               "  Use target() instead.");
  test_throws("get-lp-target-data",
              "Function target() or functions suffixed with _lp only"
              " allowed in transformed parameter block");
  test_throws("get-lp-target-data",
              "Found function = target or get_lp"
              " in block = transformed data");
  test_parsable("get-lp-target");
}

TEST(langParserStatementGrammar, removeLpDoubleUnderscore) {
  test_throws("lp-error",
              "ERROR (fatal):  Use of lp__ is no longer supported.");
  test_throws("lp-error",
              "  Use target += ... statement to increment log density.");
  test_throws("lp-error",
              "  Use target() function to get log density.");
}

TEST(langParserStatementGrammar, plusEqualsGood) {
  test_parsable("compound-assign/plus_equals_prim");
  test_parsable("compound-assign/plus_equals_container");
  test_parsable("compound-assign/plus_equals_manual");
}

TEST(langParserStatementGrammar, minusEqualsGood) {
  test_parsable("compound-assign/minus_equals_prim");
  test_parsable("compound-assign/minus_equals_container");
  test_parsable("compound-assign/minus_equals_manual");
}

TEST(langParserStatementGrammar, multiplyEqualsGood) {
  test_parsable("compound-assign/multiply_equals_prim");
  test_parsable("compound-assign/multiply_equals_container");
  test_parsable("compound-assign/multiply_equals_manual");
}

TEST(langParserStatementGrammar, divideEqualsGood) {
  test_parsable("compound-assign/divide_equals_prim");
  test_parsable("compound-assign/divide_equals_container");
  test_parsable("compound-assign/divide_equals_manual");
}

TEST(langParserStatementGrammar, eltOpEqualsGood) {
  test_parsable("compound-assign/elt_multiply_equals");
  test_parsable("compound-assign/elt_divide_equals");
}

TEST(langParserStatementGrammar, plusEqualsBad) {
  test_throws("compound-assign/plus_equals_bad_var_lhs","does not exist");
  test_throws("compound-assign/plus_equals_bad_var_lhs2",
              "Cannot assign to variable outside of declaration block");
  test_throws("compound-assign/plus_equals_bad_lhs_idxs",
              "Too many indexes for variable");
  test_throws("compound-assign/plus_equals_bad_var_rhs",
              "does not exist");
  test_throws("compound-assign/plus_equals_type_mismatch",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_type_mismatch2",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_matrix_array",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_matrix_array2",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_prim_array",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_row_vec_array",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_row_vec_array",
              "Cannot apply operator '+='");
  test_throws("compound-assign/plus_equals_bad_init",
              "PARSER EXPECTED: \";\"");
}

TEST(langParserStatementGrammar, timesEqualsBad) {
  test_throws("compound-assign/times_equals_matrix_array",
              "Cannot apply operator '*='");
}

TEST(langParserStatementGrammar, eltOpEqualsBad) {
  test_throws("compound-assign/elt_times_equals_prim",
              "Cannot apply element-wise operation to scalar");
  test_throws("compound-assign/elt_divide_equals_prim",
              "Cannot apply element-wise operation to scalar");
}
<|endoftext|>


<commit_before>//
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// deqp_libtester_main.cpp: Entry point for tester DLL.

#include <cstdio>
#include <iostream>

#include "angle_deqp_libtester.h"
#include "deMath.h"
#include "deUniquePtr.hpp"
#include "tcuApp.hpp"
#include "tcuCommandLine.hpp"
#include "tcuDefs.hpp"
#include "tcuPlatform.hpp"
#include "tcuRandomOrderExecutor.h"
#include "tcuResource.hpp"
#include "tcuTestLog.hpp"

// Located in tcuMain.cc in dEQP's sources.
int main(int argc, const char* argv[]);
tcu::Platform *createPlatform();

namespace
{

tcu::Platform *g_platform = nullptr;
tcu::CommandLine *g_cmdLine = nullptr;
tcu::DirArchive *g_archive = nullptr;
tcu::TestLog *g_log = nullptr;
tcu::TestContext *g_testCtx = nullptr;
tcu::TestPackageRoot *g_root = nullptr;
tcu::RandomOrderExecutor *g_executor = nullptr;

}

// Exported to the tester app.
ANGLE_LIBTESTER_EXPORT int deqp_libtester_main(int argc, const char *argv[])
{
    return main(argc, argv);
}

ANGLE_LIBTESTER_EXPORT void deqp_libtester_init_platform(int argc, char **argv, const char *deqpDataDir)
{
    try
    {
#if (DE_OS != DE_OS_WIN32)
        // Set stdout to line-buffered mode (will be fully buffered by default if stdout is pipe).
        setvbuf(stdout, DE_NULL, _IOLBF, 4 * 1024);
#endif
        g_platform = createPlatform();

        if (!deSetRoundingMode(DE_ROUNDINGMODE_TO_NEAREST))
        {
            throw std::exception("Failed to set floating point rounding mode.");
        }

        // TODO(jmadill): filter arguments
        g_cmdLine = new tcu::CommandLine(1, argv);
        g_archive = new tcu::DirArchive(deqpDataDir);
        g_log = new tcu::TestLog(g_cmdLine->getLogFileName(), g_cmdLine->getLogFlags());
        g_testCtx = new tcu::TestContext(*g_platform, *g_archive, *g_log, *g_cmdLine, DE_NULL);
        g_root = new tcu::TestPackageRoot(*g_testCtx, tcu::TestPackageRegistry::getSingleton());
        g_executor = new tcu::RandomOrderExecutor(*g_root, *g_testCtx);
    }
    catch (const std::exception& e)
    {
        tcu::die("%s", e.what());
    }
}

ANGLE_LIBTESTER_EXPORT void deqp_libtester_shutdown_platform()
{
    delete g_executor;
    delete g_root;
    delete g_testCtx;
    delete g_log;
    delete g_archive;
    delete g_cmdLine;
    delete g_platform;
}

ANGLE_LIBTESTER_EXPORT bool deqp_libtester_run(const char *caseName)
{
    if (!g_platform)
    {
        return false;
    }

    try
    {
        // Poll platform events
        const bool platformOk = g_platform->processEvents();

        if (platformOk)
        {
            const tcu::TestStatus &result = g_executor->execute(caseName);
            switch (result.getCode())
            {
                case QP_TEST_RESULT_PASS:
                case QP_TEST_RESULT_NOT_SUPPORTED:
                    return true;
                case QP_TEST_RESULT_QUALITY_WARNING:
                    std::cout << "Quality warning! " << result.getDescription() << std::endl;
                    return true;
                case QP_TEST_RESULT_COMPATIBILITY_WARNING:
                    std::cout << "Compatiblity warning! " << result.getDescription() << std::endl;
                    return true;
                default:
                    return false;
            }
        }
        else
        {
            std::cout << "Aborted test!" << std::endl;
        }
    }
    catch (const std::exception &e)
    {
        std::cout << "Exception running test: " << e.what() << std::endl;
    }

    return false;
}
<commit_msg>Fix compilation of libtester_main on Linux<commit_after>//
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// deqp_libtester_main.cpp: Entry point for tester DLL.

#include <cstdio>
#include <iostream>

#include "angle_deqp_libtester.h"
#include "deMath.h"
#include "deUniquePtr.hpp"
#include "tcuApp.hpp"
#include "tcuCommandLine.hpp"
#include "tcuDefs.hpp"
#include "tcuPlatform.hpp"
#include "tcuRandomOrderExecutor.h"
#include "tcuResource.hpp"
#include "tcuTestLog.hpp"

// Located in tcuMain.cc in dEQP's sources.
int main(int argc, const char* argv[]);
tcu::Platform *createPlatform();

namespace
{

tcu::Platform *g_platform = nullptr;
tcu::CommandLine *g_cmdLine = nullptr;
tcu::DirArchive *g_archive = nullptr;
tcu::TestLog *g_log = nullptr;
tcu::TestContext *g_testCtx = nullptr;
tcu::TestPackageRoot *g_root = nullptr;
tcu::RandomOrderExecutor *g_executor = nullptr;

}

// Exported to the tester app.
ANGLE_LIBTESTER_EXPORT int deqp_libtester_main(int argc, const char *argv[])
{
    return main(argc, argv);
}

ANGLE_LIBTESTER_EXPORT void deqp_libtester_init_platform(int argc, char **argv, const char *deqpDataDir)
{
    try
    {
#if (DE_OS != DE_OS_WIN32)
        // Set stdout to line-buffered mode (will be fully buffered by default if stdout is pipe).
        setvbuf(stdout, DE_NULL, _IOLBF, 4 * 1024);
#endif
        g_platform = createPlatform();

        if (!deSetRoundingMode(DE_ROUNDINGMODE_TO_NEAREST))
        {
            throw std::runtime_error("Failed to set floating point rounding mode.");
        }

        // TODO(jmadill): filter arguments
        g_cmdLine = new tcu::CommandLine(1, argv);
        g_archive = new tcu::DirArchive(deqpDataDir);
        g_log = new tcu::TestLog(g_cmdLine->getLogFileName(), g_cmdLine->getLogFlags());
        g_testCtx = new tcu::TestContext(*g_platform, *g_archive, *g_log, *g_cmdLine, DE_NULL);
        g_root = new tcu::TestPackageRoot(*g_testCtx, tcu::TestPackageRegistry::getSingleton());
        g_executor = new tcu::RandomOrderExecutor(*g_root, *g_testCtx);
    }
    catch (const std::exception& e)
    {
        tcu::die("%s", e.what());
    }
}

ANGLE_LIBTESTER_EXPORT void deqp_libtester_shutdown_platform()
{
    delete g_executor;
    delete g_root;
    delete g_testCtx;
    delete g_log;
    delete g_archive;
    delete g_cmdLine;
    delete g_platform;
}

ANGLE_LIBTESTER_EXPORT bool deqp_libtester_run(const char *caseName)
{
    if (!g_platform)
    {
        return false;
    }

    try
    {
        // Poll platform events
        const bool platformOk = g_platform->processEvents();

        if (platformOk)
        {
            const tcu::TestStatus &result = g_executor->execute(caseName);
            switch (result.getCode())
            {
                case QP_TEST_RESULT_PASS:
                case QP_TEST_RESULT_NOT_SUPPORTED:
                    return true;
                case QP_TEST_RESULT_QUALITY_WARNING:
                    std::cout << "Quality warning! " << result.getDescription() << std::endl;
                    return true;
                case QP_TEST_RESULT_COMPATIBILITY_WARNING:
                    std::cout << "Compatiblity warning! " << result.getDescription() << std::endl;
                    return true;
                default:
                    return false;
            }
        }
        else
        {
            std::cout << "Aborted test!" << std::endl;
        }
    }
    catch (const std::exception &e)
    {
        std::cout << "Exception running test: " << e.what() << std::endl;
    }

    return false;
}
<|endoftext|>


<commit_before>/*
 * Author: Martin Schreiber <SchreiberX@gmail.com>
 */

#include "test_sphere_sph_operators/SphereTestSolutions_Gaussian.hpp"
#include <sweet/SimulationVariables.hpp>
#include <sweet/MemBlockAlloc.hpp>
#include <sweet/sphere/SphereData_Config.hpp>
#include <sweet/sphere/SphereData_SpectralComplex.hpp>
#include <sweet/sphere/SphereOperators_SphereDataComplex.hpp>
#include <sweet/SWEETError.hpp>

SimulationVariables simVars;

SphereData_Config sphereDataConfigInstance;
SphereData_Config *sphereDataConfig = &sphereDataConfigInstance;

void test_header(const std::string &i_str)
{
	std::cout << "**********************************************" << std::endl;
	std::cout << i_str << std::endl;
	//std::cout << "**********************************************" << std::endl;
}

void run_tests()
{
	simVars.outputConfig();

	//double eps = 1e-10;
	double eps = 1e-8;
	eps *= std::sqrt(sphereDataConfig->spectral_modes_n_max)*std::sqrt(sphereDataConfig->spectral_modes_m_max);
	std::cout << "Using max allowed error of " << eps << std::endl;

	// Use earth radius of 1
	simVars.sim.sphere_radius = 1.0;
	SphereOperators_SphereDataComplex op(sphereDataConfig, &(simVars.sim));

	if (true)
	{
		double lambda_c = 3.0*M_PI/2.0;
		double theta_c = 0;
		double a = 6.37122e6;

		double R = a/3.0;
		double u0 = (2.0*M_PI*a)/(12.0*24.0*60.0*60.0);

		double alpha[] = {0, M_PI/3, M_PI/2};

		{
			test_header("Testing divergence freeness (non-Robert)");

			for (int i = 0; i < sizeof(alpha)/sizeof(double); i++)
			{
				double advection_rotation_angle = alpha[i];

				std::cout << "Using rotation angle " << advection_rotation_angle << std::endl;

				SphereData_PhysicalComplex u(sphereDataConfig);
				u.physical_update_lambda(
					[&](double i_lon, double i_lat, std::complex<double> &io_data)
					{
						double i_theta = i_lat;
						double i_lambda = i_lon;
						io_data =
								u0*(
									std::cos(i_theta)*std::cos(advection_rotation_angle) +
									std::sin(i_theta)*std::cos(i_lambda)*std::sin(advection_rotation_angle)
							);
					}
				);

				SphereData_PhysicalComplex v(sphereDataConfig);
				v.physical_update_lambda(
					[&](double i_lon, double i_lat, std::complex<double> &io_data)
					{
						//double i_phi = i_lat;
						double i_lambda = i_lon;
						io_data =
							-u0*(
									std::sin(i_lambda)*std::sin(advection_rotation_angle)
							);
					}
				);

				SphereData_SpectralComplex vort(sphereDataConfig);
				SphereData_SpectralComplex div(sphereDataConfig);
				op.uv_to_vrtdiv(u, v, vort, div);

				double div_max_error = div.toPhys().physical_reduce_max_abs();
				std::cout << " + div_max_error: " << div_max_error << std::endl;

				if (div_max_error > eps)
					SWEETError(" + ERROR! max error exceeds threshold");
			}
		}
	}

	{
		SphereTestSolutions_Gaussian testSolutions;

		if (true)
		{
			test_header("Testing Multiplication (a*b) with b=123.0");

			SphereData_SpectralComplex data(sphereDataConfig);
			SphereData_PhysicalComplex data_phys(sphereDataConfig);

			data_phys.physical_update_lambda(
				[&](double x, double y, std::complex<double> &io_data)
				{
					io_data = y;
				}
			);

			data.loadSphereDataPhysical(data_phys);
			data = data*123.0;

			SphereData_SpectralComplex data2(sphereDataConfig);
			SphereData_PhysicalComplex data2_phys(sphereDataConfig);
			data2_phys.physical_update_lambda(
				[&](double x, double y, std::complex<double> &io_data)
				{
					io_data = y*123.0;
				}
			);
			data2.loadSphereDataPhysical(data2_phys);

			double div_max_error = (data-data2).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}

		{
			SphereTestSolutions_Gaussian testSolutions;

			if (true)
			{
				test_header("Testing Multiplication (a *= b) with b=123.0");

				SphereData_SpectralComplex data(sphereDataConfig);
				SphereData_PhysicalComplex data_phys(sphereDataConfig);
				data_phys.physical_update_lambda(
						[&](double x, double y, std::complex<double> &io_data)
						{
							io_data = y;
						}
				);
				data.loadSphereDataPhysical(data_phys);

				data *= 123.0;

				SphereData_SpectralComplex data2(sphereDataConfig);
				SphereData_PhysicalComplex data2_phys(sphereDataConfig);
				data2_phys.physical_update_lambda(
					[&](double x, double y, std::complex<double> &io_data)
					{
						io_data = y*123.0;
					}
				);
				data2.loadSphereDataPhysical(data2_phys);

				double div_max_error = (data-data2).toPhys().physical_reduce_max_abs();
				std::cout << " + div_max_error: " << div_max_error << std::endl;

				if (div_max_error > eps)
					SWEETError(" + ERROR! max error exceeds threshold");
			}
		}

		if (true)
		{
			test_header("Testing add (a+b) operation with 123.0");

			SphereData_SpectralComplex data(sphereDataConfig);
			SphereData_PhysicalComplex data_phys(sphereDataConfig);
			data_phys.physical_update_lambda(
					[&](double x, double y, std::complex<double> &io_data)
					{
						io_data = y;
					}
			);

			data.loadSphereDataPhysical(data_phys);
			data = data + 123.0;

			SphereData_SpectralComplex data2(sphereDataConfig);
			SphereData_PhysicalComplex data2_phys(sphereDataConfig);
			data2_phys.physical_update_lambda(
					[&](double x, double y, std::complex<double> &io_data)
					{
						io_data = y+123.0;
					}
			);
			data2.loadSphereDataPhysical(data2_phys);

			double div_max_error = (data-data2).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}

		if (true)
		{
			test_header("Testing add (a+=b) operation with 123.0");

			SphereData_SpectralComplex data(sphereDataConfig);
			SphereData_PhysicalComplex data_phys(sphereDataConfig);
			data_phys.physical_update_lambda(
					[&](double x, double y, std::complex<double> &io_data)
					{
						io_data = y;
					}
			);
			data.loadSphereDataPhysical(data_phys);

			data += 123.0;

			SphereData_SpectralComplex data2(sphereDataConfig);
			SphereData_PhysicalComplex data2_phys(sphereDataConfig);
			data2_phys.physical_update_lambda(
					[&](double x, double y, std::complex<double> &io_data)
					{
						io_data = y+123.0;
					}
			);
			data2.loadSphereDataPhysical(data2_phys);

			double div_max_error = (data-data2).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}

		if (true)
		{
			test_header("Testing Gaussian latitude coordinates");

			SphereData_SpectralComplex h(sphereDataConfig);
			SphereData_PhysicalComplex h_phys(sphereDataConfig);
			h_phys.physical_update_lambda_gaussian_grid(
					[&](double a, double b, std::complex<double> &c)
					{
						double val;
						testSolutions.test_function__grid_gaussian(a,b,val);
						c = val;
					}
			);
			h.loadSphereDataPhysical(h_phys);

			SphereData_SpectralComplex hphi(sphereDataConfig);
			SphereData_PhysicalComplex hphi_phys(sphereDataConfig);
			hphi_phys.physical_update_lambda(
					[&](double a, double b, std::complex<double> &c)
					{
						double val;
						testSolutions.test_function_phi__grid_phi(a,b,val);
						c = val;
					}
			);
			hphi.loadSphereDataPhysical(hphi_phys);

			double div_max_error = (h-hphi).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}

		if (true)
		{
			test_header("Testing multiplication with Gaussian latitude");

			// mu*F(\lambda,\mu)
			SphereData_SpectralComplex h(sphereDataConfig);
			SphereData_PhysicalComplex h_phys(sphereDataConfig);
			h_phys.physical_update_lambda_gaussian_grid(
					[&](double a, double b, std::complex<double> &c)
					{
						double val;
						testSolutions.test_function__grid_gaussian(a,b,val);
						c = val;
					}
			);
			h.loadSphereDataPhysical(h_phys);
			h = op.mu(h);

			SphereData_SpectralComplex result(sphereDataConfig);
			SphereData_PhysicalComplex result_phys(sphereDataConfig);
			result_phys.physical_update_lambda_gaussian_grid(
					[&](double a, double b, std::complex<double> &c)
					{
						double val;
						testSolutions.correct_result_mu__grid_gaussian(a,b,val);
						c = val;
					}
			);
			result.loadSphereDataPhysical(result_phys);

			double div_max_error = (h-result).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}

		if (true)
		{
			test_header("Testing multiplication with pow2 of Gaussian latitude");

			// mu*mu*F(\lambda,\mu)
			SphereData_SpectralComplex h(sphereDataConfig);
			SphereData_PhysicalComplex h_phys(sphereDataConfig);
			h_phys.physical_update_lambda_gaussian_grid(
					[&](double a, double b, std::complex<double> &c)
					{
						double val;
						testSolutions.test_function__grid_gaussian(a,b,val);
						c = val;
					}
			);
			h.loadSphereDataPhysical(h_phys);
			h = op.mu2(h);

			SphereData_SpectralComplex result(sphereDataConfig);
			SphereData_PhysicalComplex result_phys(sphereDataConfig);
			result_phys.physical_update_lambda_gaussian_grid(
					[&](double lat, double mu, std::complex<double> &i_data)
					{
						double val;
						testSolutions.test_function__grid_gaussian(lat, mu, val);
						i_data = val;
						i_data *= mu*mu;
					}
			);
			result.loadSphereDataPhysical(result_phys);

			double div_max_error = (h-result).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}
	}
};

int main(
		int i_argc,
		char *const i_argv[]
)
{
	/*
	 * Initialize NUMA block allocator
	 */
	MemBlockAlloc numaBlockAlloc;

	if (!simVars.setupFromMainParameters(i_argc, i_argv))
		return -1;

	if (simVars.disc.space_res_spectral[0] == 0)
		SWEETError("Set number of spectral modes to use SPH!");

	if (simVars.disc.space_res_physical[0] <= 0)
	{
		sphereDataConfigInstance.setupAutoPhysicalSpace(
						simVars.disc.space_res_spectral[0],
						simVars.disc.space_res_spectral[1],
						&simVars.disc.space_res_physical[0],
						&simVars.disc.space_res_physical[1],
						simVars.misc.reuse_spectral_transformation_plans
				);
	}
	else
	{
		sphereDataConfigInstance.setup(
						simVars.disc.space_res_spectral[0],
						simVars.disc.space_res_spectral[1],
						simVars.disc.space_res_physical[0],
						simVars.disc.space_res_physical[1],
						simVars.misc.reuse_spectral_transformation_plans
				);
	}

	run_tests();

	std::cout << "All test successful" << std::endl;
}

<commit_msg>Fix MemBlockAlloc constructor call<commit_after>/*
 * Author: Martin Schreiber <SchreiberX@gmail.com>
 */

#include "test_sphere_sph_operators/SphereTestSolutions_Gaussian.hpp"
#include <sweet/SimulationVariables.hpp>
#include <sweet/MemBlockAlloc.hpp>
#include <sweet/sphere/SphereData_Config.hpp>
#include <sweet/sphere/SphereData_SpectralComplex.hpp>
#include <sweet/sphere/SphereOperators_SphereDataComplex.hpp>
#include <sweet/SWEETError.hpp>

SphereData_Config sphereDataConfigInstance;
SphereData_Config *sphereDataConfig = &sphereDataConfigInstance;

void test_header(const std::string &i_str)
{
	std::cout << "**********************************************" << std::endl;
	std::cout << i_str << std::endl;
	//std::cout << "**********************************************" << std::endl;
}

void run_tests()
{
	simVars.outputConfig();

	//double eps = 1e-10;
	double eps = 1e-8;
	eps *= std::sqrt(sphereDataConfig->spectral_modes_n_max)*std::sqrt(sphereDataConfig->spectral_modes_m_max);
	std::cout << "Using max allowed error of " << eps << std::endl;

	// Use earth radius of 1
	simVars.sim.sphere_radius = 1.0;
	SphereOperators_SphereDataComplex op(sphereDataConfig, &(simVars.sim));

	if (true)
	{
		double lambda_c = 3.0*M_PI/2.0;
		double theta_c = 0;
		double a = 6.37122e6;

		double R = a/3.0;
		double u0 = (2.0*M_PI*a)/(12.0*24.0*60.0*60.0);

		double alpha[] = {0, M_PI/3, M_PI/2};

		{
			test_header("Testing divergence freeness (non-Robert)");

			for (int i = 0; i < sizeof(alpha)/sizeof(double); i++)
			{
				double advection_rotation_angle = alpha[i];

				std::cout << "Using rotation angle " << advection_rotation_angle << std::endl;

				SphereData_PhysicalComplex u(sphereDataConfig);
				u.physical_update_lambda(
					[&](double i_lon, double i_lat, std::complex<double> &io_data)
					{
						double i_theta = i_lat;
						double i_lambda = i_lon;
						io_data =
								u0*(
									std::cos(i_theta)*std::cos(advection_rotation_angle) +
									std::sin(i_theta)*std::cos(i_lambda)*std::sin(advection_rotation_angle)
							);
					}
				);

				SphereData_PhysicalComplex v(sphereDataConfig);
				v.physical_update_lambda(
					[&](double i_lon, double i_lat, std::complex<double> &io_data)
					{
						//double i_phi = i_lat;
						double i_lambda = i_lon;
						io_data =
							-u0*(
									std::sin(i_lambda)*std::sin(advection_rotation_angle)
							);
					}
				);

				SphereData_SpectralComplex vort(sphereDataConfig);
				SphereData_SpectralComplex div(sphereDataConfig);
				op.uv_to_vrtdiv(u, v, vort, div);

				double div_max_error = div.toPhys().physical_reduce_max_abs();
				std::cout << " + div_max_error: " << div_max_error << std::endl;

				if (div_max_error > eps)
					SWEETError(" + ERROR! max error exceeds threshold");
			}
		}
	}

	{
		SphereTestSolutions_Gaussian testSolutions;

		if (true)
		{
			test_header("Testing Multiplication (a*b) with b=123.0");

			SphereData_SpectralComplex data(sphereDataConfig);
			SphereData_PhysicalComplex data_phys(sphereDataConfig);

			data_phys.physical_update_lambda(
				[&](double x, double y, std::complex<double> &io_data)
				{
					io_data = y;
				}
			);

			data.loadSphereDataPhysical(data_phys);
			data = data*123.0;

			SphereData_SpectralComplex data2(sphereDataConfig);
			SphereData_PhysicalComplex data2_phys(sphereDataConfig);
			data2_phys.physical_update_lambda(
				[&](double x, double y, std::complex<double> &io_data)
				{
					io_data = y*123.0;
				}
			);
			data2.loadSphereDataPhysical(data2_phys);

			double div_max_error = (data-data2).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}

		{
			SphereTestSolutions_Gaussian testSolutions;

			if (true)
			{
				test_header("Testing Multiplication (a *= b) with b=123.0");

				SphereData_SpectralComplex data(sphereDataConfig);
				SphereData_PhysicalComplex data_phys(sphereDataConfig);
				data_phys.physical_update_lambda(
						[&](double x, double y, std::complex<double> &io_data)
						{
							io_data = y;
						}
				);
				data.loadSphereDataPhysical(data_phys);

				data *= 123.0;

				SphereData_SpectralComplex data2(sphereDataConfig);
				SphereData_PhysicalComplex data2_phys(sphereDataConfig);
				data2_phys.physical_update_lambda(
					[&](double x, double y, std::complex<double> &io_data)
					{
						io_data = y*123.0;
					}
				);
				data2.loadSphereDataPhysical(data2_phys);

				double div_max_error = (data-data2).toPhys().physical_reduce_max_abs();
				std::cout << " + div_max_error: " << div_max_error << std::endl;

				if (div_max_error > eps)
					SWEETError(" + ERROR! max error exceeds threshold");
			}
		}

		if (true)
		{
			test_header("Testing add (a+b) operation with 123.0");

			SphereData_SpectralComplex data(sphereDataConfig);
			SphereData_PhysicalComplex data_phys(sphereDataConfig);
			data_phys.physical_update_lambda(
					[&](double x, double y, std::complex<double> &io_data)
					{
						io_data = y;
					}
			);

			data.loadSphereDataPhysical(data_phys);
			data = data + 123.0;

			SphereData_SpectralComplex data2(sphereDataConfig);
			SphereData_PhysicalComplex data2_phys(sphereDataConfig);
			data2_phys.physical_update_lambda(
					[&](double x, double y, std::complex<double> &io_data)
					{
						io_data = y+123.0;
					}
			);
			data2.loadSphereDataPhysical(data2_phys);

			double div_max_error = (data-data2).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}

		if (true)
		{
			test_header("Testing add (a+=b) operation with 123.0");

			SphereData_SpectralComplex data(sphereDataConfig);
			SphereData_PhysicalComplex data_phys(sphereDataConfig);
			data_phys.physical_update_lambda(
					[&](double x, double y, std::complex<double> &io_data)
					{
						io_data = y;
					}
			);
			data.loadSphereDataPhysical(data_phys);

			data += 123.0;

			SphereData_SpectralComplex data2(sphereDataConfig);
			SphereData_PhysicalComplex data2_phys(sphereDataConfig);
			data2_phys.physical_update_lambda(
					[&](double x, double y, std::complex<double> &io_data)
					{
						io_data = y+123.0;
					}
			);
			data2.loadSphereDataPhysical(data2_phys);

			double div_max_error = (data-data2).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}

		if (true)
		{
			test_header("Testing Gaussian latitude coordinates");

			SphereData_SpectralComplex h(sphereDataConfig);
			SphereData_PhysicalComplex h_phys(sphereDataConfig);
			h_phys.physical_update_lambda_gaussian_grid(
					[&](double a, double b, std::complex<double> &c)
					{
						double val;
						testSolutions.test_function__grid_gaussian(a,b,val);
						c = val;
					}
			);
			h.loadSphereDataPhysical(h_phys);

			SphereData_SpectralComplex hphi(sphereDataConfig);
			SphereData_PhysicalComplex hphi_phys(sphereDataConfig);
			hphi_phys.physical_update_lambda(
					[&](double a, double b, std::complex<double> &c)
					{
						double val;
						testSolutions.test_function_phi__grid_phi(a,b,val);
						c = val;
					}
			);
			hphi.loadSphereDataPhysical(hphi_phys);

			double div_max_error = (h-hphi).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}

		if (true)
		{
			test_header("Testing multiplication with Gaussian latitude");

			// mu*F(\lambda,\mu)
			SphereData_SpectralComplex h(sphereDataConfig);
			SphereData_PhysicalComplex h_phys(sphereDataConfig);
			h_phys.physical_update_lambda_gaussian_grid(
					[&](double a, double b, std::complex<double> &c)
					{
						double val;
						testSolutions.test_function__grid_gaussian(a,b,val);
						c = val;
					}
			);
			h.loadSphereDataPhysical(h_phys);
			h = op.mu(h);

			SphereData_SpectralComplex result(sphereDataConfig);
			SphereData_PhysicalComplex result_phys(sphereDataConfig);
			result_phys.physical_update_lambda_gaussian_grid(
					[&](double a, double b, std::complex<double> &c)
					{
						double val;
						testSolutions.correct_result_mu__grid_gaussian(a,b,val);
						c = val;
					}
			);
			result.loadSphereDataPhysical(result_phys);

			double div_max_error = (h-result).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}

		if (true)
		{
			test_header("Testing multiplication with pow2 of Gaussian latitude");

			// mu*mu*F(\lambda,\mu)
			SphereData_SpectralComplex h(sphereDataConfig);
			SphereData_PhysicalComplex h_phys(sphereDataConfig);
			h_phys.physical_update_lambda_gaussian_grid(
					[&](double a, double b, std::complex<double> &c)
					{
						double val;
						testSolutions.test_function__grid_gaussian(a,b,val);
						c = val;
					}
			);
			h.loadSphereDataPhysical(h_phys);
			h = op.mu2(h);

			SphereData_SpectralComplex result(sphereDataConfig);
			SphereData_PhysicalComplex result_phys(sphereDataConfig);
			result_phys.physical_update_lambda_gaussian_grid(
					[&](double lat, double mu, std::complex<double> &i_data)
					{
						double val;
						testSolutions.test_function__grid_gaussian(lat, mu, val);
						i_data = val;
						i_data *= mu*mu;
					}
			);
			result.loadSphereDataPhysical(result_phys);

			double div_max_error = (h-result).toPhys().physical_reduce_max_abs();
			std::cout << " + div_max_error: " << div_max_error << std::endl;

			if (div_max_error > eps)
				SWEETError(" + ERROR! max error exceeds threshold");
		}
	}
};

int main(
		int i_argc,
		char *const i_argv[]
)
{
	SimulationVariables simVars;

	if (!simVars.setupFromMainParameters(i_argc, i_argv))
		return -1;

	if (simVars.disc.space_res_spectral[0] == 0)
		SWEETError("Set number of spectral modes to use SPH!");

	if (simVars.disc.space_res_physical[0] <= 0)
	{
		sphereDataConfigInstance.setupAutoPhysicalSpace(
						simVars.disc.space_res_spectral[0],
						simVars.disc.space_res_spectral[1],
						&simVars.disc.space_res_physical[0],
						&simVars.disc.space_res_physical[1],
						simVars.misc.reuse_spectral_transformation_plans
				);
	}
	else
	{
		sphereDataConfigInstance.setup(
						simVars.disc.space_res_spectral[0],
						simVars.disc.space_res_spectral[1],
						simVars.disc.space_res_physical[0],
						simVars.disc.space_res_physical[1],
						simVars.misc.reuse_spectral_transformation_plans
				);
	}

	run_tests();

	std::cout << "All test successful" << std::endl;
}

<|endoftext|>