<commit_before>/*************************************************************************
 *
 *  $RCSfile: menubtn.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-01-03 17:40:12 $
 *
 *  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 _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_DECOVIEW_HXX
#include <decoview.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <menu.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <timer.hxx>
#endif
#ifndef _SV_MENUBTN_HXX
#include <menubtn.hxx>
#endif

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

#define IMAGEBUTTON_BORDER_OFF1     11
#define IMAGEBUTTON_BORDER_OFF2     16

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

void MenuButton::ImplInitData()
{
    mnDDStyle       = PUSHBUTTON_DROPDOWN_MENUBUTTON;

    mpMenuTimer     = NULL;
    mpMenu          = NULL;
    mpOwnMenu       = NULL;
    mnCurItemId     = 0;
    mnMenuMode      = 0;
}

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

void MenuButton::ImplInit( Window* pParent, WinBits nStyle )
{
    if ( !(nStyle & WB_NOTABSTOP) )
        nStyle |= WB_TABSTOP;

    PushButton::ImplInit( pParent, nStyle );
}

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

void MenuButton::ImplExecuteMenu()
{
    Activate();

    if ( mpMenu )
    {
        Point aPos( 0, 1 );
        Size aSize = GetSizePixel();
        Rectangle aRect( aPos, aSize );
        const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
        if ( !((GetStyle() & (WB_RECTSTYLE | WB_SMALLSTYLE)) ||
             !(rStyleSettings.GetOptions() & STYLE_OPTION_MACSTYLE)) )
        {
            aRect.Left()    += 2;
            aRect.Top()     += 2;
            aRect.Right()   -= 2;
            aRect.Bottom()  -= 2;
        }
        SetPressed( TRUE );
        EndSelection();
        mnCurItemId = mpMenu->Execute( this, aRect, POPUPMENU_EXECUTE_DOWN );
        SetPressed( FALSE );
        if ( mnCurItemId )
        {
            Select();
            mnCurItemId = 0;
        }
    }
}

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

MenuButton::MenuButton( Window* pParent, WinBits nWinBits ) :
    PushButton( WINDOW_MENUBUTTON )
{
    ImplInitData();
    ImplInit( pParent, nWinBits );
}

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

MenuButton::MenuButton( Window* pParent, const ResId& rResId ) :
    PushButton( WINDOW_MENUBUTTON )
{
    ImplInitData();
    rResId.SetRT( RSC_MENUBUTTON );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInit( pParent, nStyle );
    ImplLoadRes( rResId );

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

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

void MenuButton::ImplLoadRes( const ResId& rResId )
{
    Control::ImplLoadRes( rResId );

    ULONG nObjMask = ReadLongRes();

    if ( RSCMENUBUTTON_MENU & nObjMask )
    {
        mpOwnMenu = new PopupMenu( ResId( (RSHEADER_TYPE*)GetClassRes() ) );
        SetPopupMenu( mpOwnMenu );
        IncrementRes( GetObjSizeRes( (RSHEADER_TYPE*)GetClassRes() ) );
    }
}

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

MenuButton::~MenuButton()
{
    if ( mpMenuTimer )
        delete mpMenuTimer;
    if ( mpOwnMenu )
        delete mpOwnMenu;
}

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

IMPL_LINK( MenuButton, ImplMenuTimeoutHdl, Timer*, EMPTYARG )
{
    // Abfragen, ob Button-Benutzung noch aktiv ist, da diese ja auch
    // vorher abgebrochen wurden sein koennte
    if ( IsTracking() )
    {
        if ( !(GetStyle() & WB_NOPOINTERFOCUS) )
            GrabFocus();
        ImplExecuteMenu();
    }

    return 0;
}

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

void MenuButton::MouseButtonDown( const MouseEvent& rMEvt )
{
    if ( mnMenuMode & MENUBUTTON_MENUMODE_TIMED )
    {
        if ( !mpMenuTimer )
        {
            mpMenuTimer = new Timer;
            mpMenuTimer->SetTimeoutHdl( LINK( this, MenuButton, ImplMenuTimeoutHdl ) );
        }

        mpMenuTimer->SetTimeout( GetSettings().GetMouseSettings().GetActionDelay() );
        mpMenuTimer->Start();

        PushButton::MouseButtonDown( rMEvt );
    }
    else
    {
        if ( PushButton::ImplHitTestPushButton( this, rMEvt.GetPosPixel(), 0 ) )
        {
            if ( !(GetStyle() & WB_NOPOINTERFOCUS) )
                GrabFocus();
            ImplExecuteMenu();
        }
    }
}

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

void MenuButton::KeyInput( const KeyEvent& rKEvt )
{
    KeyCode aKeyCode = rKEvt.GetKeyCode();
    USHORT nCode = aKeyCode.GetCode();
    if ( (nCode == KEY_DOWN) && aKeyCode.IsMod2() )
        ImplExecuteMenu();
    else if ( !(mnMenuMode & MENUBUTTON_MENUMODE_TIMED) &&
              !aKeyCode.GetModifier() &&
              ((nCode == KEY_RETURN) || (nCode == KEY_SPACE)) )
        ImplExecuteMenu();
    else
        PushButton::KeyInput( rKEvt );
}

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

void MenuButton::Activate()
{
    maActivateHdl.Call( this );
}

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

void MenuButton::Select()
{
    maSelectHdl.Call( this );
}

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

void MenuButton::SetMenuMode( USHORT nMode )
{
    // Fuer die 5.1-Auslieferung besser noch nicht inline, ansonsten kann
    // diese Funktion zur 6.0 inline werden
    mnMenuMode = nMode;
}

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

void MenuButton::SetPopupMenu( PopupMenu* pNewMenu )
{
    // Fuer die 5.1-Auslieferung besser noch nicht inline, ansonsten kann
    // diese Funktion zur 6.0 inline werden
    mpMenu = pNewMenu;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.272); FILE MERGED 2005/09/05 14:44:43 rt 1.4.272.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: menubtn.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 11:48:40 $
 *
 *  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 _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_DECOVIEW_HXX
#include <decoview.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <menu.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <timer.hxx>
#endif
#ifndef _SV_MENUBTN_HXX
#include <menubtn.hxx>
#endif

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

#define IMAGEBUTTON_BORDER_OFF1     11
#define IMAGEBUTTON_BORDER_OFF2     16

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

void MenuButton::ImplInitData()
{
    mnDDStyle       = PUSHBUTTON_DROPDOWN_MENUBUTTON;

    mpMenuTimer     = NULL;
    mpMenu          = NULL;
    mpOwnMenu       = NULL;
    mnCurItemId     = 0;
    mnMenuMode      = 0;
}

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

void MenuButton::ImplInit( Window* pParent, WinBits nStyle )
{
    if ( !(nStyle & WB_NOTABSTOP) )
        nStyle |= WB_TABSTOP;

    PushButton::ImplInit( pParent, nStyle );
}

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

void MenuButton::ImplExecuteMenu()
{
    Activate();

    if ( mpMenu )
    {
        Point aPos( 0, 1 );
        Size aSize = GetSizePixel();
        Rectangle aRect( aPos, aSize );
        const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
        if ( !((GetStyle() & (WB_RECTSTYLE | WB_SMALLSTYLE)) ||
             !(rStyleSettings.GetOptions() & STYLE_OPTION_MACSTYLE)) )
        {
            aRect.Left()    += 2;
            aRect.Top()     += 2;
            aRect.Right()   -= 2;
            aRect.Bottom()  -= 2;
        }
        SetPressed( TRUE );
        EndSelection();
        mnCurItemId = mpMenu->Execute( this, aRect, POPUPMENU_EXECUTE_DOWN );
        SetPressed( FALSE );
        if ( mnCurItemId )
        {
            Select();
            mnCurItemId = 0;
        }
    }
}

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

MenuButton::MenuButton( Window* pParent, WinBits nWinBits ) :
    PushButton( WINDOW_MENUBUTTON )
{
    ImplInitData();
    ImplInit( pParent, nWinBits );
}

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

MenuButton::MenuButton( Window* pParent, const ResId& rResId ) :
    PushButton( WINDOW_MENUBUTTON )
{
    ImplInitData();
    rResId.SetRT( RSC_MENUBUTTON );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInit( pParent, nStyle );
    ImplLoadRes( rResId );

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

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

void MenuButton::ImplLoadRes( const ResId& rResId )
{
    Control::ImplLoadRes( rResId );

    ULONG nObjMask = ReadLongRes();

    if ( RSCMENUBUTTON_MENU & nObjMask )
    {
        mpOwnMenu = new PopupMenu( ResId( (RSHEADER_TYPE*)GetClassRes() ) );
        SetPopupMenu( mpOwnMenu );
        IncrementRes( GetObjSizeRes( (RSHEADER_TYPE*)GetClassRes() ) );
    }
}

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

MenuButton::~MenuButton()
{
    if ( mpMenuTimer )
        delete mpMenuTimer;
    if ( mpOwnMenu )
        delete mpOwnMenu;
}

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

IMPL_LINK( MenuButton, ImplMenuTimeoutHdl, Timer*, EMPTYARG )
{
    // Abfragen, ob Button-Benutzung noch aktiv ist, da diese ja auch
    // vorher abgebrochen wurden sein koennte
    if ( IsTracking() )
    {
        if ( !(GetStyle() & WB_NOPOINTERFOCUS) )
            GrabFocus();
        ImplExecuteMenu();
    }

    return 0;
}

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

void MenuButton::MouseButtonDown( const MouseEvent& rMEvt )
{
    if ( mnMenuMode & MENUBUTTON_MENUMODE_TIMED )
    {
        if ( !mpMenuTimer )
        {
            mpMenuTimer = new Timer;
            mpMenuTimer->SetTimeoutHdl( LINK( this, MenuButton, ImplMenuTimeoutHdl ) );
        }

        mpMenuTimer->SetTimeout( GetSettings().GetMouseSettings().GetActionDelay() );
        mpMenuTimer->Start();

        PushButton::MouseButtonDown( rMEvt );
    }
    else
    {
        if ( PushButton::ImplHitTestPushButton( this, rMEvt.GetPosPixel(), 0 ) )
        {
            if ( !(GetStyle() & WB_NOPOINTERFOCUS) )
                GrabFocus();
            ImplExecuteMenu();
        }
    }
}

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

void MenuButton::KeyInput( const KeyEvent& rKEvt )
{
    KeyCode aKeyCode = rKEvt.GetKeyCode();
    USHORT nCode = aKeyCode.GetCode();
    if ( (nCode == KEY_DOWN) && aKeyCode.IsMod2() )
        ImplExecuteMenu();
    else if ( !(mnMenuMode & MENUBUTTON_MENUMODE_TIMED) &&
              !aKeyCode.GetModifier() &&
              ((nCode == KEY_RETURN) || (nCode == KEY_SPACE)) )
        ImplExecuteMenu();
    else
        PushButton::KeyInput( rKEvt );
}

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

void MenuButton::Activate()
{
    maActivateHdl.Call( this );
}

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

void MenuButton::Select()
{
    maSelectHdl.Call( this );
}

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

void MenuButton::SetMenuMode( USHORT nMode )
{
    // Fuer die 5.1-Auslieferung besser noch nicht inline, ansonsten kann
    // diese Funktion zur 6.0 inline werden
    mnMenuMode = nMode;
}

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

void MenuButton::SetPopupMenu( PopupMenu* pNewMenu )
{
    // Fuer die 5.1-Auslieferung besser noch nicht inline, ansonsten kann
    // diese Funktion zur 6.0 inline werden
    mpMenu = pNewMenu;
}
<|endoftext|>


<commit_before>//=============================================================================================================
/**
* @file     main.cpp
* @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     December, 2015
*
* @section  LICENSE
*
* Copyright (C) 2015, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    The dipole fit test implementation
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include <fiff/fiff.h>

#include <iostream>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtTest>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace FIFFLIB;

//=============================================================================================================
/**
* DECLARE CLASS TestDipoleFit
*
* @brief The TestDipoleFit class provides dipole fit tests
*
*/
class TestDipoleFit: public QObject
{
    Q_OBJECT

public:
    TestDipoleFit();

private slots:
    void initTestCase();
    void compareData();
    void compareTimes();
    void compareInfo();
    void cleanupTestCase();

private:
    double epsilon;
};

//*************************************************************************************************************

TestDipoleFit::TestDipoleFit()
: epsilon(0.000001)
{
}

//*************************************************************************************************************

void TestDipoleFit::initTestCase()
{
    qDebug() << "Epsilon" << epsilon;

    QFile t_fileIn("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
    QFile t_fileOut("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short_test_rwr_out.fif");

    //
    //   Make sure test folder exists
    //
    QFileInfo t_fileOutInfo(t_fileOut);
    QDir().mkdir(t_fileOutInfo.path());

    //*********************************************************************************************************
    // First Read & Write
    //*********************************************************************************************************

    printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read & Write >>>>>>>>>>>>>>>>>>>>>>>>>\n");

    printf("<<<<<<<<<<<<<<<<<<<<<<<<< Read & Write Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");

    //*********************************************************************************************************
    // Second Read
    //*********************************************************************************************************

    printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read Again >>>>>>>>>>>>>>>>>>>>>>>>>\n");

    printf("<<<<<<<<<<<<<<<<<<<<<<<<< Read Again Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
}

//*************************************************************************************************************

void TestDipoleFit::compareData()
{

//    QVERIFY( data_diff.sum() < epsilon );
}

//*************************************************************************************************************

void TestDipoleFit::compareTimes()
{

//    QVERIFY( times_diff.sum() < epsilon );
}

//*************************************************************************************************************

void TestDipoleFit::compareInfo()
{
//    //Sampling frequency
//    std::cout << "[1] Sampling Frequency Check\n";
//    QVERIFY( first_in_raw.info.sfreq == second_in_raw.info.sfreq );

//    //Projection
//    std::cout << "[2] Projection Check\n";
//    QVERIFY( first_in_raw.info.projs.size() == second_in_raw.info.projs.size() );

//    for( qint32 i = 0; i < first_in_raw.info.projs.size(); ++i )
//    {
//        std::cout << "Projector " << i << std::endl;
//        MatrixXd tmp = first_in_raw.info.projs[i].data->data - second_in_raw.info.projs[i].data->data;
//        QVERIFY( tmp.sum() < epsilon );
//    }

//    //Compensators
//    std::cout << "[3] Compensator Check\n";
//    QVERIFY( first_in_raw.info.comps.size() == second_in_raw.info.comps.size() );

//    for( qint32 i = 0; i < first_in_raw.info.comps.size(); ++i )
//    {
//        std::cout << "Compensator " << i << std::endl;
//        MatrixXd tmp = first_in_raw.info.comps[i].data->data - second_in_raw.info.comps[i].data->data;
//        QVERIFY( tmp.sum() < epsilon );
//    }
}

//*************************************************************************************************************

void TestDipoleFit::cleanupTestCase()
{
}

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

QTEST_APPLESS_MAIN(TestDipoleFit)
#include "test_fiff_rwr.moc"
<commit_msg>fixed moc include<commit_after>//=============================================================================================================
/**
* @file     main.cpp
* @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     December, 2015
*
* @section  LICENSE
*
* Copyright (C) 2015, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    The dipole fit test implementation
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include <fiff/fiff.h>

#include <iostream>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtTest>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace FIFFLIB;

//=============================================================================================================
/**
* DECLARE CLASS TestDipoleFit
*
* @brief The TestDipoleFit class provides dipole fit tests
*
*/
class TestDipoleFit: public QObject
{
    Q_OBJECT

public:
    TestDipoleFit();

private slots:
    void initTestCase();
    void compareData();
    void compareTimes();
    void compareInfo();
    void cleanupTestCase();

private:
    double epsilon;
};

//*************************************************************************************************************

TestDipoleFit::TestDipoleFit()
: epsilon(0.000001)
{
}

//*************************************************************************************************************

void TestDipoleFit::initTestCase()
{
    qDebug() << "Epsilon" << epsilon;

    QFile t_fileIn("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
    QFile t_fileOut("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short_test_rwr_out.fif");

    //
    //   Make sure test folder exists
    //
    QFileInfo t_fileOutInfo(t_fileOut);
    QDir().mkdir(t_fileOutInfo.path());

    //*********************************************************************************************************
    // First Read & Write
    //*********************************************************************************************************

    printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read & Write >>>>>>>>>>>>>>>>>>>>>>>>>\n");

    printf("<<<<<<<<<<<<<<<<<<<<<<<<< Read & Write Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");

    //*********************************************************************************************************
    // Second Read
    //*********************************************************************************************************

    printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read Again >>>>>>>>>>>>>>>>>>>>>>>>>\n");

    printf("<<<<<<<<<<<<<<<<<<<<<<<<< Read Again Finished <<<<<<<<<<<<<<<<<<<<<<<<<\n");
}

//*************************************************************************************************************

void TestDipoleFit::compareData()
{

//    QVERIFY( data_diff.sum() < epsilon );
}

//*************************************************************************************************************

void TestDipoleFit::compareTimes()
{

//    QVERIFY( times_diff.sum() < epsilon );
}

//*************************************************************************************************************

void TestDipoleFit::compareInfo()
{
//    //Sampling frequency
//    std::cout << "[1] Sampling Frequency Check\n";
//    QVERIFY( first_in_raw.info.sfreq == second_in_raw.info.sfreq );

//    //Projection
//    std::cout << "[2] Projection Check\n";
//    QVERIFY( first_in_raw.info.projs.size() == second_in_raw.info.projs.size() );

//    for( qint32 i = 0; i < first_in_raw.info.projs.size(); ++i )
//    {
//        std::cout << "Projector " << i << std::endl;
//        MatrixXd tmp = first_in_raw.info.projs[i].data->data - second_in_raw.info.projs[i].data->data;
//        QVERIFY( tmp.sum() < epsilon );
//    }

//    //Compensators
//    std::cout << "[3] Compensator Check\n";
//    QVERIFY( first_in_raw.info.comps.size() == second_in_raw.info.comps.size() );

//    for( qint32 i = 0; i < first_in_raw.info.comps.size(); ++i )
//    {
//        std::cout << "Compensator " << i << std::endl;
//        MatrixXd tmp = first_in_raw.info.comps[i].data->data - second_in_raw.info.comps[i].data->data;
//        QVERIFY( tmp.sum() < epsilon );
//    }
}

//*************************************************************************************************************

void TestDipoleFit::cleanupTestCase()
{
}

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

QTEST_APPLESS_MAIN(TestDipoleFit)
#include "test_dipole_fit.moc"
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>

#include <QDebug>

#include <qrfcommserver.h>
#include <qbluetoothsocket.h>

QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QBluetooth::SecurityFlags);

// Max time to wait for connection
static const int MaxConnectTime = 60 * 1000;   // 1 minute in ms

class tst_QRfcommServer : public QObject
{
    Q_OBJECT

public:
    tst_QRfcommServer();
    ~tst_QRfcommServer();

private slots:
    void initTestCase();

    void tst_construction();

    void tst_listen_data();
    void tst_listen();

    void tst_pendingConnections_data();
    void tst_pendingConnections();

    void tst_receive_data();
    void tst_receive();

    void tst_secureFlags();
};

tst_QRfcommServer::tst_QRfcommServer()
{
}

tst_QRfcommServer::~tst_QRfcommServer()
{
}

void tst_QRfcommServer::initTestCase()
{
    qRegisterMetaType<QBluetooth::SecurityFlags>("QBluetooth::SecurityFlags");
}

void tst_QRfcommServer::tst_construction()
{
    {
        QRfcommServer server;

        QVERIFY(!server.isListening());
        QCOMPARE(server.maxPendingConnections(), 1);
        QVERIFY(!server.hasPendingConnections());
        QVERIFY(server.nextPendingConnection() == 0);
        QVERIFY(server.serverAddress().isNull());
        QCOMPARE(server.serverPort(), quint16(0));
    }
}

void tst_QRfcommServer::tst_listen_data()
{
    QTest::addColumn<QBluetoothAddress>("address");
    QTest::addColumn<quint16>("port");

    QTest::newRow("default") << QBluetoothAddress() << quint16(0);
    QTest::newRow("specified address") << QBluetoothAddress("00:11:B1:08:AD:B8") << quint16(0);
    QTest::newRow("specified port") << QBluetoothAddress() << quint16(10);
    QTest::newRow("specified address/port") << QBluetoothAddress("00:11:B1:08:AD:B8") << quint16(10);
}

void tst_QRfcommServer::tst_listen()
{
    QFETCH(QBluetoothAddress, address);
    QFETCH(quint16, port);

    {
        QRfcommServer server;

        bool result = server.listen(address, port);

        QVERIFY(result);
        QVERIFY(server.isListening());

        if (!address.isNull())
            QCOMPARE(server.serverAddress(), address);
        else
            QVERIFY(!server.serverAddress().isNull());

        if (port != 0)
            QCOMPARE(server.serverPort(), port);
        else
            QVERIFY(server.serverPort() != 0);

        QCOMPARE(server.maxPendingConnections(), 1);

        QVERIFY(!server.hasPendingConnections());
        QVERIFY(server.nextPendingConnection() == 0);

        server.close();

        QVERIFY(!server.isListening());

        QVERIFY(server.serverAddress().isNull());
        QVERIFY(server.serverPort() == 0);

        QVERIFY(!server.hasPendingConnections());
        QVERIFY(server.nextPendingConnection() == 0);
    }
}

void tst_QRfcommServer::tst_pendingConnections_data()
{
    QTest::addColumn<int>("maxConnections");

    QTest::newRow("1 connection") << 1;
    //QTest::newRow("2 connections") << 2;
}

void tst_QRfcommServer::tst_pendingConnections()
{
    QFETCH(int, maxConnections);

    {
        QRfcommServer server;

        server.setMaxPendingConnections(maxConnections);

        bool result = server.listen();

        QVERIFY(result);
        QVERIFY(server.isListening());

        qDebug() << "Listening on RFCOMM channel:" << server.serverPort();

        QCOMPARE(server.maxPendingConnections(), maxConnections);

        QVERIFY(!server.hasPendingConnections());
        QVERIFY(server.nextPendingConnection() == 0);

        {
            /* wait for maxConnections simultaneous connections */
            qDebug() << "Waiting for" << maxConnections << "simultaneous connections.";

            QSignalSpy connectionSpy(&server, SIGNAL(newConnection()));

            int connectTime = MaxConnectTime;
            while (connectionSpy.count() < maxConnections && connectTime > 0) {
                QTest::qWait(1000);
                connectTime -= 1000;
            }

            QList<QBluetoothSocket *> sockets;
            while (server.hasPendingConnections())
                sockets.append(server.nextPendingConnection());

            QCOMPARE(connectionSpy.count(), maxConnections);
            QCOMPARE(sockets.count(), maxConnections);

            foreach (QBluetoothSocket *socket, sockets) {
                qDebug() << socket->state();
                QVERIFY(socket->state() == QBluetoothSocket::ConnectedState);
                QVERIFY(socket->openMode() == QIODevice::ReadWrite);
            }

            QVERIFY(!server.hasPendingConnections());
            QVERIFY(server.nextPendingConnection() == 0);

            while (!sockets.isEmpty()) {
                QBluetoothSocket *socket = sockets.takeFirst();
                socket->close();
                delete socket;
            }
        }

        server.close();
    }
}

void tst_QRfcommServer::tst_receive_data()
{
    QTest::addColumn<QByteArray>("expected");

    QTest::newRow("test") << QByteArray("hello\r\n");
}

void tst_QRfcommServer::tst_receive()
{
    QFETCH(QByteArray, expected);

    QRfcommServer server;

    bool result = server.listen();

    QVERIFY(result);

    qDebug() << "Listening on RFCOMM channel:" << server.serverPort();

    int connectTime = MaxConnectTime;
    while (!server.hasPendingConnections() && connectTime > 0) {
        QTest::qWait(1000);
        connectTime -= 1000;
    }

    QVERIFY(server.hasPendingConnections());

    QBluetoothSocket *socket = server.nextPendingConnection();

    QVERIFY(socket->state() == QBluetoothSocket::ConnectedState);
    QVERIFY(socket->openMode() == QIODevice::ReadWrite);

    QSignalSpy readyReadSpy(socket, SIGNAL(readyRead()));

    int readyReadTime = 60000;
    while (readyReadSpy.isEmpty() && readyReadTime > 0) {
        QTest::qWait(1000);
        readyReadTime -= 1000;
    }

    QVERIFY(!readyReadSpy.isEmpty());

    const QByteArray data = socket->readAll();

    QCOMPARE(data, expected);
}

void tst_QRfcommServer::tst_secureFlags()
{
    QRfcommServer server;
    QCOMPARE(server.securityFlags(), QBluetooth::NoSecurity);

    server.setSecurityFlags(QBluetooth::Encryption);
    QCOMPARE(server.securityFlags(), QBluetooth::Encryption);
}

QTEST_MAIN(tst_QRfcommServer)

#include "tst_qrfcommserver.moc"
<commit_msg>Symbian: make some modification qrfcommserver testscases<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>

#include <QDebug>

#include <qrfcommserver.h>
#include <qbluetoothsocket.h>
#include <qbluetoothlocaldevice.h>

QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QBluetooth::SecurityFlags);

// Max time to wait for connection
static const int MaxConnectTime = 60 * 1000;   // 1 minute in ms

class tst_QRfcommServer : public QObject
{
    Q_OBJECT

public:
    tst_QRfcommServer();
    ~tst_QRfcommServer();

private slots:
    void initTestCase();

    void tst_construction();

    void tst_listen_data();
    void tst_listen();

    void tst_pendingConnections_data();
    void tst_pendingConnections();

    void tst_receive_data();
    void tst_receive();

    void tst_secureFlags();
private:
    QBluetoothLocalDevice localDevice;
};

tst_QRfcommServer::tst_QRfcommServer()
{
    localDevice.powerOn();
}

tst_QRfcommServer::~tst_QRfcommServer()
{
}

void tst_QRfcommServer::initTestCase()
{
    qRegisterMetaType<QBluetooth::SecurityFlags>("QBluetooth::SecurityFlags");
}

void tst_QRfcommServer::tst_construction()
{
    {
        QRfcommServer server;

        QVERIFY(!server.isListening());
        QCOMPARE(server.maxPendingConnections(), 1);
        QVERIFY(!server.hasPendingConnections());
        QVERIFY(server.nextPendingConnection() == 0);
        QVERIFY(server.serverAddress().isNull());
        QCOMPARE(server.serverPort(), quint16(0));
    }
}

void tst_QRfcommServer::tst_listen_data()
{
    QTest::addColumn<QBluetoothAddress>("address");
    QTest::addColumn<quint16>("port");

    QTest::newRow("default") << QBluetoothAddress() << quint16(0);
#ifdef Q_OS_SYMBIAN
    //use localdevice address for listen address.
    QTest::newRow("specified address") << localDevice.address() << quint16(0);
    QTest::newRow("specified port") << QBluetoothAddress() << quint16(20);
    QTest::newRow("specified address/port") << localDevice.address() << quint16(21);
#else
    QTest::newRow("specified address") << QBluetoothAddress("00:11:B1:08:AD:B8") << quint16(0);
    QTest::newRow("specified port") << QBluetoothAddress() << quint16(10);
    QTest::newRow("specified address/port") << QBluetoothAddress("00:11:B1:08:AD:B8") << quint16(10);
#endif
}

void tst_QRfcommServer::tst_listen()
{
    QFETCH(QBluetoothAddress, address);
    QFETCH(quint16, port);

    {
        QRfcommServer server;

        bool result = server.listen(address, port);
        QTest::qWait(1000);

        QVERIFY(result);
        QVERIFY(server.isListening());

        if (!address.isNull())
            QCOMPARE(server.serverAddress(), address);
#ifndef Q_OS_SYMBIAN
// In Symbian there is only one bluetoothdevice per device and its address is returned always.
        else
            QVERIFY(!server.serverAddress().isNull());
#endif
        qDebug()<<"Server Port="<<server.serverPort();
        if (port != 0)
            QCOMPARE(server.serverPort(), port);
        else
            QVERIFY(server.serverPort() != 0);

        QCOMPARE(server.maxPendingConnections(), 1);

        QVERIFY(!server.hasPendingConnections());
        QVERIFY(server.nextPendingConnection() == 0);

        server.close();
        QTest::qWait(500);

        QVERIFY(!server.isListening());

        QVERIFY(server.serverAddress().isNull());
        QVERIFY(server.serverPort() == 0);

        QVERIFY(!server.hasPendingConnections());
        QVERIFY(server.nextPendingConnection() == 0);
    }
}

void tst_QRfcommServer::tst_pendingConnections_data()
{
    QTest::addColumn<int>("maxConnections");

    QTest::newRow("1 connection") << 1;
    //QTest::newRow("2 connections") << 2;
}

void tst_QRfcommServer::tst_pendingConnections()
{
    QFETCH(int, maxConnections);

    {
        QRfcommServer server;

        server.setMaxPendingConnections(maxConnections);

        bool result = server.listen();

        QVERIFY(result);
        QVERIFY(server.isListening());

        qDebug() << "Listening on RFCOMM channel:" << server.serverPort();

        QCOMPARE(server.maxPendingConnections(), maxConnections);

        QVERIFY(!server.hasPendingConnections());
        QVERIFY(server.nextPendingConnection() == 0);

        {
            /* wait for maxConnections simultaneous connections */
            qDebug() << "Waiting for" << maxConnections << "simultaneous connections.";

            QSignalSpy connectionSpy(&server, SIGNAL(newConnection()));

            int connectTime = MaxConnectTime;
            while (connectionSpy.count() < maxConnections && connectTime > 0) {
                QTest::qWait(1000);
                connectTime -= 1000;
            }

            QList<QBluetoothSocket *> sockets;
            while (server.hasPendingConnections())
                sockets.append(server.nextPendingConnection());

            QCOMPARE(connectionSpy.count(), maxConnections);
            QCOMPARE(sockets.count(), maxConnections);

            foreach (QBluetoothSocket *socket, sockets) {
                qDebug() << socket->state();
                QVERIFY(socket->state() == QBluetoothSocket::ConnectedState);
                QVERIFY(socket->openMode() == QIODevice::ReadWrite);
            }

            QVERIFY(!server.hasPendingConnections());
            QVERIFY(server.nextPendingConnection() == 0);

            while (!sockets.isEmpty()) {
                QBluetoothSocket *socket = sockets.takeFirst();
                socket->close();
                delete socket;
            }
        }

        server.close();
    }
}

void tst_QRfcommServer::tst_receive_data()
{
    QTest::addColumn<QByteArray>("expected");

    QTest::newRow("test") << QByteArray("hello\r\n");
}

void tst_QRfcommServer::tst_receive()
{
    QFETCH(QByteArray, expected);

    QRfcommServer server;

    bool result = server.listen();

    QVERIFY(result);

    qDebug() << "Listening on RFCOMM channel:" << server.serverPort();

    int connectTime = MaxConnectTime;
    while (!server.hasPendingConnections() && connectTime > 0) {
        QTest::qWait(1000);
        connectTime -= 1000;
    }

    QVERIFY(server.hasPendingConnections());

    QBluetoothSocket *socket = server.nextPendingConnection();

    QVERIFY(socket->state() == QBluetoothSocket::ConnectedState);
    QVERIFY(socket->openMode() == QIODevice::ReadWrite);

    QSignalSpy readyReadSpy(socket, SIGNAL(readyRead()));

    int readyReadTime = 60000;
    while (readyReadSpy.isEmpty() && readyReadTime > 0) {
        QTest::qWait(1000);
        readyReadTime -= 1000;
    }

    QVERIFY(!readyReadSpy.isEmpty());

    const QByteArray data = socket->readAll();

    QCOMPARE(data, expected);
}

void tst_QRfcommServer::tst_secureFlags()
{
    QRfcommServer server;
    QCOMPARE(server.securityFlags(), QBluetooth::NoSecurity);

    server.setSecurityFlags(QBluetooth::Encryption);
    QCOMPARE(server.securityFlags(), QBluetooth::Encryption);
}

QTEST_MAIN(tst_QRfcommServer)

#include "tst_qrfcommserver.moc"
<|endoftext|>


<commit_before>
#include "loop.h"

#include "config.h"
#include "output.h"
#include "mode.h"
#include "configmonitor.h"
#include "edid.h"

#include <QX11Info>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>

#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>

using namespace KScreen;

Loop::Loop(QObject* parent): QObject(parent)
{
    start();
}

Loop::~Loop()
{

}

void Loop::start()
{
    qDebug() << "START";
    QDateTime date = QDateTime::currentDateTime();
    m_config = Config::current();
    qDebug() << "Took: " << date.secsTo(QDateTime::currentDateTime());
    ConfigMonitor::instance()->addConfig(m_config);
    connect(ConfigMonitor::instance(), SIGNAL(configurationChanged()), SLOT(printConfig()));

    //config->outputs()[65]->setCurrentMode(70);
    //Config::setConfig(config);
}

void Loop::printConfig()
{
//     KScreen *screen = KScreen::self();
//     qDebug() << "Backend: " << screen->backend();

    qDebug() << "\n============================================================\n"
                "============================================================\n"
                "============================================================\n";

    qDebug() << "Screen:";
    qDebug() << "maxSize:" << m_config->screen()->maxSize();
    qDebug() << "minSize:" << m_config->screen()->minSize();
    qDebug() << "currentSize:" << m_config->screen()->currentSize();

    OutputList outputs = m_config->outputs();
    OutputList outputEnabled;
    Q_FOREACH(Output *output, outputs) {
        qDebug() << "Id: " << output->id();
        qDebug() << "Name: " << output->name();
        qDebug() << "Type: " << output->type();
        qDebug() << "Connected: " << output->isConnected();
        qDebug() << "Enabled: " << output->isEnabled();
        qDebug() << "Primary: " << output->isPrimary();
        qDebug() << "Rotation: " << output->rotation();
        qDebug() << "Pos: " << output->pos();
        if (output->currentMode()) {
            qDebug() << "Size: " << output->mode(output->currentMode())->size();
        }
        qDebug() << "Clones: " << output->clones().isEmpty();
        qDebug() << "Mode: " << output->currentMode();
        qDebug() << "Preferred mode: " << output->preferredMode();
        qDebug() << "Modes: ";

        ModeList modes = output->modes();
        Q_FOREACH(Mode* mode, modes) {
            qDebug() << "\t" << mode->id() << "  " << mode->name() << " " << mode->size() << " " << mode->refreshRate();
        }

        Edid* edid = output->edid();
    qDebug() << "EDID Info: ";
    if (edid != 0) {
        qDebug() << "\tDevice ID: " << edid->deviceId();
        qDebug() << "\tName: " << edid->name();
        qDebug() << "\tVendor: " << edid->vendor();
        qDebug() << "\tSerial: " << edid->serial();
        qDebug() << "\tEISA ID: " << edid->eisaId();
        qDebug() << "\tHash: " << edid->hash();
        qDebug() << "\tWidth: " << edid->width();
        qDebug() << "\tHeight: " << edid->height();
        qDebug() << "\tGamma: " << edid->gamma();
        qDebug() << "\tRed: " << edid->red();
        qDebug() << "\tGreen: " << edid->green();
        qDebug() << "\tBlue: " << edid->blue();
        qDebug() << "\tWhite: " << edid->white();
    } else {
        qDebug() << "\tUnavailable";
    }

        if (output->isEnabled()) {
            outputEnabled.insert(output->id(), output);
        }
        qDebug() << "\n-----------------------------------------------------\n";
    }
}
#include <loop.moc>
<commit_msg>Debug message & coding style improvement in kscreen-console<commit_after>
#include "loop.h"

#include "config.h"
#include "output.h"
#include "mode.h"
#include "configmonitor.h"
#include "edid.h"

#include <QX11Info>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>

#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>

using namespace KScreen;

Loop::Loop(QObject* parent): QObject(parent)
{
    start();
}

Loop::~Loop()
{

}

void Loop::start()
{
    qDebug() << "START";
    QDateTime date = QDateTime::currentDateTime();
    m_config = Config::current();
    qDebug() << "Config::current() took" << date.msecsTo(QDateTime::currentDateTime()) << "milliseconds";
    ConfigMonitor::instance()->addConfig(m_config);
    connect(ConfigMonitor::instance(), SIGNAL(configurationChanged()), SLOT(printConfig()));

    //config->outputs()[65]->setCurrentMode(70);
    //Config::setConfig(config);
}

void Loop::printConfig()
{
//     KScreen *screen = KScreen::self();
//     qDebug() << "Backend: " << screen->backend();

    qDebug() << "\n============================================================\n"
                "============================================================\n"
                "============================================================\n";

    qDebug() << "Screen:";
    qDebug() << "maxSize:" << m_config->screen()->maxSize();
    qDebug() << "minSize:" << m_config->screen()->minSize();
    qDebug() << "currentSize:" << m_config->screen()->currentSize();

    OutputList outputs = m_config->outputs();
    OutputList outputEnabled;
    Q_FOREACH(Output *output, outputs) {
        qDebug() << "\n-----------------------------------------------------\n";
        qDebug() << "Id: " << output->id();
        qDebug() << "Name: " << output->name();
        qDebug() << "Type: " << output->type();
        qDebug() << "Connected: " << output->isConnected();
        qDebug() << "Enabled: " << output->isEnabled();
        qDebug() << "Primary: " << output->isPrimary();
        qDebug() << "Rotation: " << output->rotation();
        qDebug() << "Pos: " << output->pos();
        if (output->currentMode()) {
            qDebug() << "Size: " << output->mode(output->currentMode())->size();
        }
        qDebug() << "Clones: " << output->clones().isEmpty();
        qDebug() << "Mode: " << output->currentMode();
        qDebug() << "Preferred mode: " << output->preferredMode();
        qDebug() << "Modes: ";

        ModeList modes = output->modes();
        Q_FOREACH(Mode* mode, modes) {
            qDebug() << "\t" << mode->id() << "  " << mode->name() << " " << mode->size() << " " << mode->refreshRate();
        }

        Edid* edid = output->edid();
        qDebug() << "EDID Info: ";
        if (edid != 0) {
            qDebug() << "\tDevice ID: " << edid->deviceId();
            qDebug() << "\tName: " << edid->name();
            qDebug() << "\tVendor: " << edid->vendor();
            qDebug() << "\tSerial: " << edid->serial();
            qDebug() << "\tEISA ID: " << edid->eisaId();
            qDebug() << "\tHash: " << edid->hash();
            qDebug() << "\tWidth: " << edid->width();
            qDebug() << "\tHeight: " << edid->height();
            qDebug() << "\tGamma: " << edid->gamma();
            qDebug() << "\tRed: " << edid->red();
            qDebug() << "\tGreen: " << edid->green();
            qDebug() << "\tBlue: " << edid->blue();
            qDebug() << "\tWhite: " << edid->white();
        } else {
            qDebug() << "\tUnavailable";
        }

        if (output->isEnabled()) {
            outputEnabled.insert(output->id(), output);
        }
    }
}
#include <loop.moc>
<|endoftext|>


<commit_before>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen
 *
 * 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 OR COPYRIGHT HOLDERS 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 "global_managers.hpp"

#include "thread_group.hpp"
#include "filesystem.hpp"
#include "event.hpp"
#include "ui_manager.hpp"
#include "common_renderer_data.hpp"
#include <thread>

#ifdef HAVE_GRANITE_AUDIO
#include "audio_interface.hpp"
#include "audio_mixer.hpp"
#include "audio_events.hpp"
#endif

#ifdef HAVE_GRANITE_PHYSICS
#include "physics_system.hpp"
#endif

namespace Granite
{
namespace Global
{

// Could use unique_ptr here, but would be nice to avoid global ctor/dtor.
struct GlobalManagers
{
	Filesystem *filesystem;
	EventManager *event_manager;
	ThreadGroup *thread_group;
	UI::UIManager *ui_manager;
	CommonRendererData *common_renderer_data;
#ifdef HAVE_GRANITE_AUDIO
	Audio::Backend *audio_backend;
	Audio::Mixer *audio_mixer;
#endif
#ifdef HAVE_GRANITE_PHYSICS
	PhysicsSystem *physics;
#endif
};

static GlobalManagers global_managers;

Filesystem *filesystem()
{
	if (!global_managers.filesystem)
	{
		LOGI("Filesystem was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.filesystem = new Filesystem;
	}

	return global_managers.filesystem;
}

EventManager *event_manager()
{
	if (!global_managers.event_manager)
	{
		LOGI("Event manager was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.event_manager = new EventManager;
	}

	return global_managers.event_manager;
}

ThreadGroup *thread_group()
{
	if (!global_managers.thread_group)
	{
		LOGI("Thread group was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.thread_group = new ThreadGroup;
		global_managers.thread_group->start(std::thread::hardware_concurrency());
	}

	return global_managers.thread_group;
}

UI::UIManager *ui_manager()
{
	if (!global_managers.ui_manager)
	{
		LOGI("UI manager was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.ui_manager = new UI::UIManager;
	}

	return global_managers.ui_manager;
}

CommonRendererData *common_renderer_data()
{
	if (!global_managers.common_renderer_data)
	{
		LOGI("Common GPU data was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.common_renderer_data = new CommonRendererData;
	}

	return global_managers.common_renderer_data;
}

#ifdef HAVE_GRANITE_AUDIO
Audio::Backend *audio_backend() { return global_managers.audio_backend; }
Audio::Mixer *audio_mixer() { return global_managers.audio_mixer; }

void install_audio_system(Audio::Backend *backend, Audio::Mixer *mixer)
{
	delete global_managers.audio_mixer;
	global_managers.audio_mixer = mixer;

	delete global_managers.audio_backend;
	global_managers.audio_backend = backend;
}
#endif

#ifdef HAVE_GRANITE_PHYSICS
PhysicsSystem *physics()
{
	if (!global_managers.physics)
	{
		LOGI("Physics system was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.physics = new PhysicsSystem;
	}

	return global_managers.physics;
}
#endif

void init(ManagerFeatureFlags flags)
{
	if (flags & MANAGER_FEATURE_EVENT_BIT)
	{
		if (!global_managers.event_manager)
			global_managers.event_manager = new EventManager;
	}

	if (flags & MANAGER_FEATURE_FILESYSTEM_BIT)
	{
		if (!global_managers.filesystem)
			global_managers.filesystem = new Filesystem;
	}

	if (flags & MANAGER_FEATURE_THREAD_GROUP_BIT)
	{
		if (!global_managers.thread_group)
		{
			global_managers.thread_group = new ThreadGroup;
			global_managers.thread_group->start(std::thread::hardware_concurrency());
		}
	}

	if (flags & MANAGER_FEATURE_UI_MANAGER_BIT)
	{
		if (!global_managers.ui_manager)
			global_managers.ui_manager = new UI::UIManager;
	}

	if (flags & MANAGER_FEATURE_COMMON_RENDERER_DATA_BIT)
	{
		if (!global_managers.common_renderer_data)
			global_managers.common_renderer_data = new CommonRendererData;
	}

	if (flags & MANAGER_FEATURE_PHYSICS_BIT)
	{
		if (!global_managers.physics)
			global_managers.physics = new PhysicsSystem;
	}

#ifdef HAVE_GRANITE_AUDIO
	if (!global_managers.audio_mixer)
		global_managers.audio_mixer = new Audio::Mixer;
	if (!global_managers.audio_backend)
		global_managers.audio_backend = Audio::create_default_audio_backend(*global_managers.audio_mixer, 44100.0f, 2);
#endif
}

void deinit()
{
#ifdef HAVE_GRANITE_AUDIO
	if (global_managers.audio_backend)
		global_managers.audio_backend->stop();

	delete global_managers.audio_backend;
	delete global_managers.audio_mixer;
	global_managers.audio_backend = nullptr;
	global_managers.audio_mixer = nullptr;
#endif

#ifdef HAVE_GRANITE_PHYSICS
	delete global_managers.physics;
#endif

	delete global_managers.common_renderer_data;
	delete global_managers.ui_manager;
	delete global_managers.thread_group;
	delete global_managers.filesystem;
	delete global_managers.event_manager;

	global_managers.common_renderer_data = nullptr;
	global_managers.filesystem = nullptr;
	global_managers.event_manager = nullptr;
	global_managers.thread_group = nullptr;
	global_managers.ui_manager = nullptr;
}

void start_audio_system()
{
#ifdef HAVE_GRANITE_AUDIO
	if (!global_managers.audio_backend)
		return;

	if (!global_managers.audio_backend->start())
	{
		LOGE("Failed to start audio subsystem!\n");
		return;
	}

	if (global_managers.event_manager)
		global_managers.event_manager->enqueue_latched<Audio::MixerStartEvent>(*global_managers.audio_mixer);
#endif
}

void stop_audio_system()
{
#ifdef HAVE_GRANITE_AUDIO
	if (!global_managers.audio_backend)
		return;

	if (!global_managers.audio_backend->stop())
		LOGE("Failed to stop audio subsystem!\n");
	if (global_managers.event_manager)
		global_managers.event_manager->dequeue_latched(Audio::MixerStartEvent::get_type_id());
#endif
}

}
}

<commit_msg>Fix non-physics build.<commit_after>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen
 *
 * 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 OR COPYRIGHT HOLDERS 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 "global_managers.hpp"

#include "thread_group.hpp"
#include "filesystem.hpp"
#include "event.hpp"
#include "ui_manager.hpp"
#include "common_renderer_data.hpp"
#include <thread>

#ifdef HAVE_GRANITE_AUDIO
#include "audio_interface.hpp"
#include "audio_mixer.hpp"
#include "audio_events.hpp"
#endif

#ifdef HAVE_GRANITE_PHYSICS
#include "physics_system.hpp"
#endif

namespace Granite
{
namespace Global
{

// Could use unique_ptr here, but would be nice to avoid global ctor/dtor.
struct GlobalManagers
{
	Filesystem *filesystem;
	EventManager *event_manager;
	ThreadGroup *thread_group;
	UI::UIManager *ui_manager;
	CommonRendererData *common_renderer_data;
#ifdef HAVE_GRANITE_AUDIO
	Audio::Backend *audio_backend;
	Audio::Mixer *audio_mixer;
#endif
#ifdef HAVE_GRANITE_PHYSICS
	PhysicsSystem *physics;
#endif
};

static GlobalManagers global_managers;

Filesystem *filesystem()
{
	if (!global_managers.filesystem)
	{
		LOGI("Filesystem was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.filesystem = new Filesystem;
	}

	return global_managers.filesystem;
}

EventManager *event_manager()
{
	if (!global_managers.event_manager)
	{
		LOGI("Event manager was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.event_manager = new EventManager;
	}

	return global_managers.event_manager;
}

ThreadGroup *thread_group()
{
	if (!global_managers.thread_group)
	{
		LOGI("Thread group was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.thread_group = new ThreadGroup;
		global_managers.thread_group->start(std::thread::hardware_concurrency());
	}

	return global_managers.thread_group;
}

UI::UIManager *ui_manager()
{
	if (!global_managers.ui_manager)
	{
		LOGI("UI manager was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.ui_manager = new UI::UIManager;
	}

	return global_managers.ui_manager;
}

CommonRendererData *common_renderer_data()
{
	if (!global_managers.common_renderer_data)
	{
		LOGI("Common GPU data was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.common_renderer_data = new CommonRendererData;
	}

	return global_managers.common_renderer_data;
}

#ifdef HAVE_GRANITE_AUDIO
Audio::Backend *audio_backend() { return global_managers.audio_backend; }
Audio::Mixer *audio_mixer() { return global_managers.audio_mixer; }

void install_audio_system(Audio::Backend *backend, Audio::Mixer *mixer)
{
	delete global_managers.audio_mixer;
	global_managers.audio_mixer = mixer;

	delete global_managers.audio_backend;
	global_managers.audio_backend = backend;
}
#endif

#ifdef HAVE_GRANITE_PHYSICS
PhysicsSystem *physics()
{
	if (!global_managers.physics)
	{
		LOGI("Physics system was not initialized. Lazily initializing. This is not thread safe!\n");
		global_managers.physics = new PhysicsSystem;
	}

	return global_managers.physics;
}
#endif

void init(ManagerFeatureFlags flags)
{
	if (flags & MANAGER_FEATURE_EVENT_BIT)
	{
		if (!global_managers.event_manager)
			global_managers.event_manager = new EventManager;
	}

	if (flags & MANAGER_FEATURE_FILESYSTEM_BIT)
	{
		if (!global_managers.filesystem)
			global_managers.filesystem = new Filesystem;
	}

	if (flags & MANAGER_FEATURE_THREAD_GROUP_BIT)
	{
		if (!global_managers.thread_group)
		{
			global_managers.thread_group = new ThreadGroup;
			global_managers.thread_group->start(std::thread::hardware_concurrency());
		}
	}

	if (flags & MANAGER_FEATURE_UI_MANAGER_BIT)
	{
		if (!global_managers.ui_manager)
			global_managers.ui_manager = new UI::UIManager;
	}

	if (flags & MANAGER_FEATURE_COMMON_RENDERER_DATA_BIT)
	{
		if (!global_managers.common_renderer_data)
			global_managers.common_renderer_data = new CommonRendererData;
	}

#ifdef HAVE_GRANITE_PHYSICS
	if (flags & MANAGER_FEATURE_PHYSICS_BIT)
	{
		if (!global_managers.physics)
			global_managers.physics = new PhysicsSystem;
	}
#endif

#ifdef HAVE_GRANITE_AUDIO
	if (!global_managers.audio_mixer)
		global_managers.audio_mixer = new Audio::Mixer;
	if (!global_managers.audio_backend)
		global_managers.audio_backend = Audio::create_default_audio_backend(*global_managers.audio_mixer, 44100.0f, 2);
#endif
}

void deinit()
{
#ifdef HAVE_GRANITE_AUDIO
	if (global_managers.audio_backend)
		global_managers.audio_backend->stop();

	delete global_managers.audio_backend;
	delete global_managers.audio_mixer;
	global_managers.audio_backend = nullptr;
	global_managers.audio_mixer = nullptr;
#endif

#ifdef HAVE_GRANITE_PHYSICS
	delete global_managers.physics;
#endif

	delete global_managers.common_renderer_data;
	delete global_managers.ui_manager;
	delete global_managers.thread_group;
	delete global_managers.filesystem;
	delete global_managers.event_manager;

	global_managers.common_renderer_data = nullptr;
	global_managers.filesystem = nullptr;
	global_managers.event_manager = nullptr;
	global_managers.thread_group = nullptr;
	global_managers.ui_manager = nullptr;
}

void start_audio_system()
{
#ifdef HAVE_GRANITE_AUDIO
	if (!global_managers.audio_backend)
		return;

	if (!global_managers.audio_backend->start())
	{
		LOGE("Failed to start audio subsystem!\n");
		return;
	}

	if (global_managers.event_manager)
		global_managers.event_manager->enqueue_latched<Audio::MixerStartEvent>(*global_managers.audio_mixer);
#endif
}

void stop_audio_system()
{
#ifdef HAVE_GRANITE_AUDIO
	if (!global_managers.audio_backend)
		return;

	if (!global_managers.audio_backend->stop())
		LOGE("Failed to stop audio subsystem!\n");
	if (global_managers.event_manager)
		global_managers.event_manager->dequeue_latched(Audio::MixerStartEvent::get_type_id());
#endif
}

}
}

<|endoftext|>


<commit_before>#include "mbed.h"
#include "crypto.h"
#include "default_random_seed.h"
#include "psa_prot_internal_storage.h"

int mbed_default_seed_read(unsigned char *buf, size_t buf_len)
{
    struct psa_its_info_t info = {0, 0};
    size_t actual_size = buf_len;
    psa_its_get_info(MBED_RANDOM_SEED_ITS_UID, &info);
    if (info.size < buf_len)
    {
        actual_size = info.size;
    }
    psa_its_status_t rc = psa_its_get(MBED_RANDOM_SEED_ITS_UID, 0, actual_size, buf);
    /* Make sure that in case of an error the value will be negative
     * Mbed TLS errors are negative values */
    rc  = rc < 0 ? rc : (-1 * rc);
    return (rc);
}

int mbed_default_seed_write(unsigned char *buf, size_t buf_len)
{
    psa_its_status_t rc = psa_its_set(MBED_RANDOM_SEED_ITS_UID, buf_len, buf, 0);
    /* Make sure that in case of an error the value will be negative
     * Mbed TLS errors are negative values */
    rc  = rc < 0 ? rc : (-1 * rc);
    return (rc);
}

<commit_msg>change MBEDTLS_RANDOM_SEED_ITS_UID  define to be PSA_CRYPTO_ITS_RANDOM_SEED_UID<commit_after>#include "mbed.h"
#include "crypto.h"
#include "default_random_seed.h"
#include "psa_prot_internal_storage.h"

int mbed_default_seed_read(unsigned char *buf, size_t buf_len)
{
    struct psa_its_info_t info = {0, 0};
    size_t actual_size = buf_len;
    psa_its_get_info(PSA_CRYPTO_ITS_RANDOM_SEED_UID, &info);
    if (info.size < buf_len)
    {
        actual_size = info.size;
    }
    psa_its_status_t rc = psa_its_get(PSA_CRYPTO_ITS_RANDOM_SEED_UID, 0, actual_size, buf);
    /* Make sure that in case of an error the value will be negative
     * Mbed TLS errors are negative values */
    rc  = rc < 0 ? rc : (-1 * rc);
    return (rc);
}

int mbed_default_seed_write(unsigned char *buf, size_t buf_len)
{
    psa_its_status_t rc = psa_its_set(PSA_CRYPTO_ITS_RANDOM_SEED_UID, buf_len, buf, 0);
    /* Make sure that in case of an error the value will be negative
     * Mbed TLS errors are negative values */
    rc  = rc < 0 ? rc : (-1 * rc);
    return (rc);
}

<|endoftext|>


<commit_before>#include <ppltasks.h>
#include <pplawait.h>
#include <stdio.h>

using namespace Microsoft::Azure::Devices::Client;
using namespace Platform;
using namespace concurrency;

//
// String containing Hostname, Device Id & Device Key in the format:
// "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"
//
// Note: this connection string is specific to the device "$deviceId$". To configure other devices,
// see information on iothub-explorer at http://aka.ms/iothubgetstartedVSCS
//
static const wchar_t* connection_string = L"HostName=$iotHubUri$;DeviceId=$deviceId$;SharedAccessKey=$deviceKey$";

//
// To monitor messages sent to device "$deviceId$" use iothub-explorer as follows:
//    iothub-explorer HostName=$iotHubUri$;SharedAccessKeyName=service;SharedAccessKey=$servicePrimaryKey$ monitor-events "$deviceId$"
//

task<void> send_device_to_cloud_message()
{
    auto deviceClient = DeviceClient::CreateFromConnectionString(ref new Platform::String(connection_string), TransportType::Http1);

    std::string message = "Hello from C++!";

    auto pbuffer = ref new Platform::Array<byte>((unsigned char*)message.data(), message.length());
    auto eventMessage = ref new Message(pbuffer);
    return create_task(deviceClient->SendEventAsync(eventMessage)).then([] {
        OutputDebugString(L"message sent successfully\n");
    });
}

task<std::string> receive_cloud_to_device_message()
{
    auto deviceClient = DeviceClient::CreateFromConnectionString(ref new Platform::String(connection_string), TransportType::Http1);

    while (true)
    {
        auto receivedMessage = await deviceClient->ReceiveAsync();

        if (receivedMessage != nullptr)
        {
            auto bytes = receivedMessage->GetBytes();
            auto messageData = bytes->Data;
            auto len = bytes->Length;

            std::string str((char*)messageData, len);

            await deviceClient->CompleteAsync(receivedMessage);

            return str;
        }

        //  Note: In this sample, the polling interval is set to
        //  10 seconds to enable you to see messages as they are sent.
        //  To enable an IoT solution to scale, you should extend this
        //  interval. For example, to scale to 1 million devices, set
        //  the polling interval to 25 minutes.
        //  For further information, see
        //  https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging

        await create_task([] { std::this_thread::sleep_for(std::chrono::seconds(10)); });
    }
}
<commit_msg>Guard await code with _RESUMABLE_FUNCTIONS_SUPPORTED<commit_after>#include <ppltasks.h>
#include <pplawait.h>
#include <stdio.h>

using namespace Microsoft::Azure::Devices::Client;
using namespace Platform;
using namespace concurrency;

//
// String containing Hostname, Device Id & Device Key in the format:
// "HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"
//
// Note: this connection string is specific to the device "$deviceId$". To configure other devices,
// see information on iothub-explorer at http://aka.ms/iothubgetstartedVSCS
//
static const wchar_t* connection_string = L"HostName=$iotHubUri$;DeviceId=$deviceId$;SharedAccessKey=$deviceKey$";

//
// To monitor messages sent to device "$deviceId$" use iothub-explorer as follows:
//    iothub-explorer HostName=$iotHubUri$;SharedAccessKeyName=service;SharedAccessKey=$servicePrimaryKey$ monitor-events "$deviceId$"
//

task<void> send_device_to_cloud_message()
{
    auto deviceClient = DeviceClient::CreateFromConnectionString(ref new Platform::String(connection_string), TransportType::Http1);

    std::string message = "Hello from C++!";

    auto pbuffer = ref new Platform::Array<byte>((unsigned char*)message.data(), message.length());
    auto eventMessage = ref new Message(pbuffer);
    return create_task(deviceClient->SendEventAsync(eventMessage)).then([] {
        OutputDebugString(L"message sent successfully\n");
    });
}

#ifdef _RESUMABLE_FUNCTIONS_SUPPORTED
task<std::string> receive_cloud_to_device_message()
{
    auto deviceClient = DeviceClient::CreateFromConnectionString(ref new Platform::String(connection_string), TransportType::Http1);

    while (true)
    {
        auto receivedMessage = await deviceClient->ReceiveAsync();

        if (receivedMessage != nullptr)
        {
            auto bytes = receivedMessage->GetBytes();
            auto messageData = bytes->Data;
            auto len = bytes->Length;

            std::string str((char*)messageData, len);

            await deviceClient->CompleteAsync(receivedMessage);

            return str;
        }

        //  Note: In this sample, the polling interval is set to
        //  10 seconds to enable you to see messages as they are sent.
        //  To enable an IoT solution to scale, you should extend this
        //  interval. For example, to scale to 1 million devices, set
        //  the polling interval to 25 minutes.
        //  For further information, see
        //  https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging

        await create_task([] { std::this_thread::sleep_for(std::chrono::seconds(10)); });
    }
}
#endif
<|endoftext|>


<commit_before>#define HAS_VTK 1

#include "LaShellShellIntersectionMultiArray.h"
#include <numeric>

/*
*      Author:
*      Dr. Rashed Karim
*      Department of Biomedical Engineering, King's College London
*      Email: rashed 'dot' karim @kcl.ac.uk
*      Copyright (c) 2017
*
*
*		Copies scalars with multiarray support from source to target
*       Provides two options for copy - closest point along surface normal, point id
*/
int main(int argc, char * argv[])
{
	char* input_f1, *input_f2,  *output_f;
	bool use_point_id = false;
	bool foundArgs1 = false, foundArgs2 = false, foundArgs3=false;

	if (argc >= 1)
	{
		for (int i = 1; i < argc; i++) {
			if (i + 1 != argc) {
				if (string(argv[i]) == "-source") {
					input_f1 = argv[i + 1];
					foundArgs1 = true;
				}
				else if (string(argv[i]) == "-target") {
					input_f2 = argv[i + 1];
					foundArgs2 = true;
				}

				else if (string(argv[i]) == "-o") {
					output_f = argv[i + 1];
					foundArgs3 = true;
				}

			}
            else if (string(argv[i])== "--pointid")
            {
                use_point_id = true;
            }

		}
	}

	if (!(foundArgs1 && foundArgs2 && foundArgs3))
	{
		cerr << "Cheeck your parameters\n\nUsage:"
			"\nCopies the target scalars to source\nbased on vertex normals by default or point id\n\n"
			"\n(Mandatory)\n\t-source <source_mesh_vtk> \n\t-target <target_mesh_vtk> \n\t-o <output_vtk>\n"
            "\n\t--pointid <use point id for copy, source and target must be exact same meshes"<< endl;

		exit(1);
	}
	else
	{
		LaShell* source = new LaShell(input_f1);
		LaShell* target = new LaShell(input_f2);
		LaShell* la_out = new LaShell(input_f2);

		LaShellShellIntersectionMultiArray* wt = new LaShellShellIntersectionMultiArray();
		wt->SetInputData(source);
		wt->SetInputData2(target);

		if (!use_point_id) {
			cout << "\n\nUsing point normals for copying scalars ...." << endl;
			wt->SetCopyScalarsUsingNormal();

		}
		else {
			cout << "\n\nUsing point normals for copying scalars ...." << endl;
            wt->SetCopyScalarsUsingPointid();
		}

		wt->Update();

		la_out = wt->GetOutput();

		la_out->ExportVTK(output_f);
	}

}<commit_msg>some comments<commit_after>#define HAS_VTK 1

#include "LaShellShellIntersectionMultiArray.h"
#include <numeric>

/*
*      Author:
*      Dr. Rashed Karim
*      Department of Biomedical Engineering, King's College London
*      Email: rashed 'dot' karim @kcl.ac.uk
*      Copyright (c) 2017
*
*
*		Copies scalars with multiarray support from source to target
*       Provides two options for copy - closest point along surface normal, point id
*		Warning; Assumes that scalars in source mesh are as Doubles. This is the lowest common denominator
*		able to fit all other numeric types float, int and long.
*/
int main(int argc, char * argv[])
{
	char* input_f1, *input_f2,  *output_f;
	bool use_point_id = false;
	bool foundArgs1 = false, foundArgs2 = false, foundArgs3=false;

	if (argc >= 1)
	{
		for (int i = 1; i < argc; i++) {
			if (i + 1 != argc) {
				if (string(argv[i]) == "-source") {
					input_f1 = argv[i + 1];
					foundArgs1 = true;
				}
				else if (string(argv[i]) == "-target") {
					input_f2 = argv[i + 1];
					foundArgs2 = true;
				}

				else if (string(argv[i]) == "-o") {
					output_f = argv[i + 1];
					foundArgs3 = true;
				}

			}
            else if (string(argv[i])== "--pointid")
            {
                use_point_id = true;
            }

		}
	}

	if (!(foundArgs1 && foundArgs2 && foundArgs3))
	{
		cerr << "Cheeck your parameters\n\nUsage:"
			"\nCopies the target scalars to source\nbased on vertex normals by default or point id\n\n"
			"\n(Mandatory)\n\t-source <source_mesh_vtk> \n\t-target <target_mesh_vtk> \n\t-o <output_vtk>\n"
            "\n\t--pointid <use point id for copy, source and target must be exact same meshes"<< endl;

		exit(1);
	}
	else
	{
		LaShell* source = new LaShell(input_f1);
		LaShell* target = new LaShell(input_f2);
		LaShell* la_out = new LaShell(input_f2);

		LaShellShellIntersectionMultiArray* wt = new LaShellShellIntersectionMultiArray();
		wt->SetInputData(source);
		wt->SetInputData2(target);

		if (!use_point_id) {
			cout << "\n\nUsing point normals for copying scalars ...." << endl;
			wt->SetCopyScalarsUsingNormal();

		}
		else {
			cout << "\n\nUsing point normals for copying scalars ...." << endl;
            wt->SetCopyScalarsUsingPointid();
		}

		wt->Update();

		la_out = wt->GetOutput();

		la_out->ExportVTK(output_f);
	}

}<|endoftext|>


<commit_before>#include "nxtKitInterpreterPlugin.h"

#include <QtWidgets/QApplication>

#include <twoDModel/engine/twoDModelEngineFacade.h>

using namespace nxt;
using namespace qReal;

const Id robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode");
const Id subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram");

NxtKitInterpreterPlugin::NxtKitInterpreterPlugin()
	: mUsbRealRobotModel(kitId(), "nxtKitUsbRobot") // todo: somewhere generate robotId for each robot
	, mBluetoothRealRobotModel(kitId(), "nxtKitBluetoothRobot")
	, mTwoDRobotModel(mUsbRealRobotModel)
	, mBlocksFactory(new blocks::NxtBlocksFactory)
{
	mAdditionalPreferences = new NxtAdditionalPreferences(mBluetoothRealRobotModel.name());

	auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(mTwoDRobotModel);

	mTwoDRobotModel.setEngine(modelEngine->engine());
	mTwoDModel.reset(modelEngine);

	connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged
			, &mUsbRealRobotModel, &robotModel::real::RealRobotModel::rereadSettings);
	connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged
			, &mBluetoothRealRobotModel, &robotModel::real::RealRobotModel::rereadSettings);
	connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged
			, &mTwoDRobotModel, &robotModel::twoD::TwoDRobotModel::rereadSettings);
}

NxtKitInterpreterPlugin::~NxtKitInterpreterPlugin()
{
	if (mOwnsAdditionalPreferences) {
		delete mAdditionalPreferences;
	}

	if (mOwnsBlocksFactory) {
		delete mBlocksFactory;
	}
}

void NxtKitInterpreterPlugin::init(const kitBase::KitPluginConfigurator &configurator)
{
	connect(&configurator.eventsForKitPlugin(), &kitBase::EventsForKitPluginInterface::robotModelChanged
			, [this](const QString &modelName) { mCurrentlySelectedModelName = modelName; });

	connect(&configurator.qRealConfigurator().systemEvents(), &qReal::SystemEvents::activeTabChanged
			, this, &NxtKitInterpreterPlugin::onActiveTabChanged);

	qReal::gui::MainWindowInterpretersInterface &interpretersInterface
			= configurator.qRealConfigurator().mainWindowInterpretersInterface();
	connect(&mUsbRealRobotModel, &robotModel::real::RealRobotModel::errorOccured
			, [&interpretersInterface](const QString &message) {
				interpretersInterface.errorReporter()->addError(message);
	});
	connect(&mBluetoothRealRobotModel, &robotModel::real::RealRobotModel::errorOccured
			, [&interpretersInterface](const QString &message) {
				interpretersInterface.errorReporter()->addError(message);
	});
	mUsbRealRobotModel.checkConnection();
	mBluetoothRealRobotModel.checkConnection();

	mTwoDModel->init(configurator.eventsForKitPlugin()
			, configurator.qRealConfigurator().systemEvents()
			, configurator.qRealConfigurator().graphicalModelApi()
			, configurator.qRealConfigurator().logicalModelApi()
			, interpretersInterface
			, configurator.interpreterControl());

}

QString NxtKitInterpreterPlugin::kitId() const
{
	return "nxtKit";
}

QString NxtKitInterpreterPlugin::friendlyKitName() const
{
	return tr("Lego NXT");
}

QList<kitBase::robotModel::RobotModelInterface *> NxtKitInterpreterPlugin::robotModels()
{
	return {&mUsbRealRobotModel, &mBluetoothRealRobotModel, &mTwoDRobotModel};
}

kitBase::blocksBase::BlocksFactoryInterface *NxtKitInterpreterPlugin::blocksFactoryFor(
		const kitBase::robotModel::RobotModelInterface *model)
{
	Q_UNUSED(model);
	mOwnsBlocksFactory = false;
	return mBlocksFactory;
}

kitBase::robotModel::RobotModelInterface *NxtKitInterpreterPlugin::defaultRobotModel()
{
	return &mTwoDRobotModel;
}

QList<kitBase::AdditionalPreferences *> NxtKitInterpreterPlugin::settingsWidgets()
{
	mOwnsAdditionalPreferences = false;
	return {mAdditionalPreferences};
}

QList<qReal::ActionInfo> NxtKitInterpreterPlugin::customActions()
{
	return { mTwoDModel->showTwoDModelWidgetActionInfo() };
}

QList<HotKeyActionInfo> NxtKitInterpreterPlugin::hotKeyActions()
{
	mTwoDModel->showTwoDModelWidgetActionInfo().action()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));

	HotKeyActionInfo d2ModelActionInfo("Interpreter.Show2dModelForNxt", tr("Show 2d model")
			, mTwoDModel->showTwoDModelWidgetActionInfo().action());

	return { d2ModelActionInfo };
}

QString NxtKitInterpreterPlugin::defaultSettingsFile() const
{
	return ":/nxtDefaultSettings.ini";
}

QIcon NxtKitInterpreterPlugin::iconForFastSelector(
		const kitBase::robotModel::RobotModelInterface &robotModel) const
{
	return &robotModel == &mUsbRealRobotModel
			? QIcon(":/icons/switch-real-nxt-usb.svg")
			: &robotModel == &mBluetoothRealRobotModel
					? QIcon(":/icons/switch-real-nxt-bluetooth.svg")
					: QIcon(":/icons/switch-2d.svg");
}

kitBase::DevicesConfigurationProvider * NxtKitInterpreterPlugin::devicesConfigurationProvider()
{
	return &mTwoDModel->devicesConfigurationProvider();
}

void NxtKitInterpreterPlugin::onActiveTabChanged(const TabInfo &info)
{
	const Id type = info.rootDiagramId().type();
	const bool enabled = type == robotDiagramType || type == subprogramDiagramType
			&& mCurrentlySelectedModelName == mTwoDRobotModel.name();
	mTwoDModel->showTwoDModelWidgetActionInfo().action()->setVisible(enabled);
}
<commit_msg>Fixed extra NXT 2D model action visible in all modes<commit_after>#include "nxtKitInterpreterPlugin.h"

#include <QtWidgets/QApplication>

#include <twoDModel/engine/twoDModelEngineFacade.h>

using namespace nxt;
using namespace qReal;

const Id robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode");
const Id subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram");

NxtKitInterpreterPlugin::NxtKitInterpreterPlugin()
	: mUsbRealRobotModel(kitId(), "nxtKitUsbRobot") // todo: somewhere generate robotId for each robot
	, mBluetoothRealRobotModel(kitId(), "nxtKitBluetoothRobot")
	, mTwoDRobotModel(mUsbRealRobotModel)
	, mBlocksFactory(new blocks::NxtBlocksFactory)
{
	mAdditionalPreferences = new NxtAdditionalPreferences(mBluetoothRealRobotModel.name());

	auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(mTwoDRobotModel);

	mTwoDRobotModel.setEngine(modelEngine->engine());
	mTwoDModel.reset(modelEngine);

	connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged
			, &mUsbRealRobotModel, &robotModel::real::RealRobotModel::rereadSettings);
	connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged
			, &mBluetoothRealRobotModel, &robotModel::real::RealRobotModel::rereadSettings);
	connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged
			, &mTwoDRobotModel, &robotModel::twoD::TwoDRobotModel::rereadSettings);
}

NxtKitInterpreterPlugin::~NxtKitInterpreterPlugin()
{
	if (mOwnsAdditionalPreferences) {
		delete mAdditionalPreferences;
	}

	if (mOwnsBlocksFactory) {
		delete mBlocksFactory;
	}
}

void NxtKitInterpreterPlugin::init(const kitBase::KitPluginConfigurator &configurator)
{
	connect(&configurator.eventsForKitPlugin(), &kitBase::EventsForKitPluginInterface::robotModelChanged
			, [this](const QString &modelName) { mCurrentlySelectedModelName = modelName; });

	connect(&configurator.qRealConfigurator().systemEvents(), &qReal::SystemEvents::activeTabChanged
			, this, &NxtKitInterpreterPlugin::onActiveTabChanged);

	qReal::gui::MainWindowInterpretersInterface &interpretersInterface
			= configurator.qRealConfigurator().mainWindowInterpretersInterface();
	connect(&mUsbRealRobotModel, &robotModel::real::RealRobotModel::errorOccured
			, [&interpretersInterface](const QString &message) {
				interpretersInterface.errorReporter()->addError(message);
	});
	connect(&mBluetoothRealRobotModel, &robotModel::real::RealRobotModel::errorOccured
			, [&interpretersInterface](const QString &message) {
				interpretersInterface.errorReporter()->addError(message);
	});
	mUsbRealRobotModel.checkConnection();
	mBluetoothRealRobotModel.checkConnection();

	mTwoDModel->init(configurator.eventsForKitPlugin()
			, configurator.qRealConfigurator().systemEvents()
			, configurator.qRealConfigurator().graphicalModelApi()
			, configurator.qRealConfigurator().logicalModelApi()
			, interpretersInterface
			, configurator.interpreterControl());

}

QString NxtKitInterpreterPlugin::kitId() const
{
	return "nxtKit";
}

QString NxtKitInterpreterPlugin::friendlyKitName() const
{
	return tr("Lego NXT");
}

QList<kitBase::robotModel::RobotModelInterface *> NxtKitInterpreterPlugin::robotModels()
{
	return {&mUsbRealRobotModel, &mBluetoothRealRobotModel, &mTwoDRobotModel};
}

kitBase::blocksBase::BlocksFactoryInterface *NxtKitInterpreterPlugin::blocksFactoryFor(
		const kitBase::robotModel::RobotModelInterface *model)
{
	Q_UNUSED(model);
	mOwnsBlocksFactory = false;
	return mBlocksFactory;
}

kitBase::robotModel::RobotModelInterface *NxtKitInterpreterPlugin::defaultRobotModel()
{
	return &mTwoDRobotModel;
}

QList<kitBase::AdditionalPreferences *> NxtKitInterpreterPlugin::settingsWidgets()
{
	mOwnsAdditionalPreferences = false;
	return {mAdditionalPreferences};
}

QList<qReal::ActionInfo> NxtKitInterpreterPlugin::customActions()
{
	return { mTwoDModel->showTwoDModelWidgetActionInfo() };
}

QList<HotKeyActionInfo> NxtKitInterpreterPlugin::hotKeyActions()
{
	mTwoDModel->showTwoDModelWidgetActionInfo().action()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));

	HotKeyActionInfo d2ModelActionInfo("Interpreter.Show2dModelForNxt", tr("Show 2d model")
			, mTwoDModel->showTwoDModelWidgetActionInfo().action());

	return { d2ModelActionInfo };
}

QString NxtKitInterpreterPlugin::defaultSettingsFile() const
{
	return ":/nxtDefaultSettings.ini";
}

QIcon NxtKitInterpreterPlugin::iconForFastSelector(
		const kitBase::robotModel::RobotModelInterface &robotModel) const
{
	return &robotModel == &mUsbRealRobotModel
			? QIcon(":/icons/switch-real-nxt-usb.svg")
			: &robotModel == &mBluetoothRealRobotModel
					? QIcon(":/icons/switch-real-nxt-bluetooth.svg")
					: QIcon(":/icons/switch-2d.svg");
}

kitBase::DevicesConfigurationProvider * NxtKitInterpreterPlugin::devicesConfigurationProvider()
{
	return &mTwoDModel->devicesConfigurationProvider();
}

void NxtKitInterpreterPlugin::onActiveTabChanged(const TabInfo &info)
{
	const Id type = info.rootDiagramId().type();
	const bool enabled = (type == robotDiagramType || type == subprogramDiagramType)
			&& mCurrentlySelectedModelName == mTwoDRobotModel.name();
	mTwoDModel->showTwoDModelWidgetActionInfo().action()->setVisible(enabled);
}
<|endoftext|>


<commit_before>#include "anti_aliasing_fxaa.h"
#include "pathos/shader/shader_program.h"
#include "pathos/render/render_device.h"
#include "pathos/render/scene_render_targets.h"
#include "pathos/util/engine_util.h"

namespace pathos {

	struct UBO_FXAA {
		static constexpr uint32 BINDING_SLOT = 1;

		vector4 fxaaConsoleRcpFrameOpt;
		vector4 fxaaConsoleRcpFrameOpt2;
		vector4 fxaaConsole360RcpFrameOpt2;
		vector4 fxaaConsole360ConstDir;
		vector2 fxaaQualityRcpFrame;
		float fxaaQualitySubpix;
		float fxaaQualityEdgeThreshold;
		float fxaaQualityEdgeThresholdMin;
		float fxaaConsoleEdgeSharpness;
		float fxaaConsoleEdgeThreshold;
		float fxaaConsoleEdgeThresholdMin;
	};

	class FXAAPassVS : public ShaderStage {
	public:
		FXAAPassVS() : ShaderStage(GL_VERTEX_SHADER, "FXAAPassVS") {
			setFilepath("fullscreen_quad.glsl");
		}
	};

	class FXAAPassFS : public ShaderStage {
	public:
		FXAAPassFS() : ShaderStage(GL_FRAGMENT_SHADER, "FXAAPassFS") {
			addDefine("FXAA_PC 1");
			addDefine("FXAA_GLSL_130 1");
			addDefine("FXAA_GREEN_AS_LUMA 1");
			addDefine("FXAA_QUALITY__PRESET 23");
			setFilepath("fxaa_fs.glsl");
		}
	};

	DEFINE_SHADER_PROGRAM2(FXAAProgram, FXAAPassVS, FXAAPassFS);

}

namespace pathos {

	void FXAA::initializeResources(RenderCommandList& cmdList) {
		ubo.init<UBO_FXAA>();

		gRenderDevice->createFramebuffers(1, &fbo);
		cmdList.namedFramebufferDrawBuffer(fbo, GL_COLOR_ATTACHMENT0);
		cmdList.objectLabel(GL_FRAMEBUFFER, fbo, -1, "FBO_FXAA");
	}

	void FXAA::releaseResources(RenderCommandList& cmdList) {
		gRenderDevice->deleteFramebuffers(1, &fbo);

		markDestroyed();
	}

	void FXAA::renderPostProcess(RenderCommandList& cmdList, PlaneGeometry* fullscreenQuad) {
		SCOPED_DRAW_EVENT(FXAA);

		const GLuint input0 = getInput(EPostProcessInput::PPI_0); // toneMappingResult
		const GLuint output0 = getOutput(EPostProcessOutput::PPO_0); // sceneFinal or backbuffer

		SceneRenderTargets& sceneContext = *cmdList.sceneRenderTargets;

		// #note-fxaa: See the FXAA pixel shader for details
		float sharpness = 0.5f;
		float subpix = 0.75f;
		float edge_threshold = 0.166f;
		float edge_threshold_min = 0.0f; // 0.0833f;
		float console_edge_sharpness = 8.0f;
		float console_edge_threshold = 0.125f;
		float console_edge_threshold_min = 0.05f;

		vector2 inv_size(1.0f / (float)sceneContext.sceneWidth, 1.0f / (float)sceneContext.sceneHeight);
		vector4 inv_size_4(-inv_size.x, -inv_size.y, inv_size.x, inv_size.y);
		vector4 sharp_param = sharpness * inv_size_4;
		vector4 sharp2_param = 2.0f * inv_size_4;
		vector4 sharp3_param = vector4(8.0f, 8.0f, -4.0f, -4.0f) * inv_size_4;

		ShaderProgram& program = FIND_SHADER_PROGRAM(FXAAProgram);
		cmdList.useProgram(program.getGLName());

		UBO_FXAA uboData;
		uboData.fxaaQualityRcpFrame          = vector2(inv_size.x, inv_size.y);
		uboData.fxaaConsoleRcpFrameOpt	     = vector4(sharp_param.x, sharp_param.y, sharp_param.z, sharp_param.w);
		uboData.fxaaConsoleRcpFrameOpt2	     = vector4(sharp2_param.x, sharp2_param.y, sharp2_param.z, sharp2_param.w);
		uboData.fxaaConsole360RcpFrameOpt2   = vector4(sharp3_param.x, sharp3_param.y, sharp3_param.z, sharp3_param.w);
		uboData.fxaaQualitySubpix			 = subpix;
		uboData.fxaaQualityEdgeThreshold	 = edge_threshold;
		uboData.fxaaQualityEdgeThresholdMin  = edge_threshold_min;
		uboData.fxaaConsoleEdgeSharpness	 = console_edge_sharpness;
		uboData.fxaaConsoleEdgeThreshold	 = console_edge_threshold;
		uboData.fxaaConsoleEdgeThresholdMin  = console_edge_threshold_min;
		uboData.fxaaConsole360ConstDir	     = vector4(1.0f, -1.0f, 0.25f, -0.25f);
		ubo.update(cmdList, UBO_FXAA::BINDING_SLOT, &uboData);

		if (output0 == 0) {
			cmdList.bindFramebuffer(GL_FRAMEBUFFER, 0);
		} else {
			cmdList.bindFramebuffer(GL_FRAMEBUFFER, fbo);
			cmdList.namedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, output0, 0);

			pathos::checkFramebufferStatus(cmdList, fbo, "fxaa");
		}

		cmdList.textureParameteri(input0, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		cmdList.textureParameteri(input0, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		cmdList.bindTextureUnit(0, input0);

		fullscreenQuad->activate_position_uv(cmdList);
		fullscreenQuad->activateIndexBuffer(cmdList);
		fullscreenQuad->drawPrimitive(cmdList);
	}

}
<commit_msg>Fix missing cmdList.viewport() call in FXAA.<commit_after>#include "anti_aliasing_fxaa.h"
#include "pathos/shader/shader_program.h"
#include "pathos/render/render_device.h"
#include "pathos/render/scene_render_targets.h"
#include "pathos/util/engine_util.h"

namespace pathos {

	struct UBO_FXAA {
		static constexpr uint32 BINDING_SLOT = 1;

		vector4 fxaaConsoleRcpFrameOpt;
		vector4 fxaaConsoleRcpFrameOpt2;
		vector4 fxaaConsole360RcpFrameOpt2;
		vector4 fxaaConsole360ConstDir;
		vector2 fxaaQualityRcpFrame;
		float fxaaQualitySubpix;
		float fxaaQualityEdgeThreshold;
		float fxaaQualityEdgeThresholdMin;
		float fxaaConsoleEdgeSharpness;
		float fxaaConsoleEdgeThreshold;
		float fxaaConsoleEdgeThresholdMin;
	};

	class FXAAPassVS : public ShaderStage {
	public:
		FXAAPassVS() : ShaderStage(GL_VERTEX_SHADER, "FXAAPassVS") {
			setFilepath("fullscreen_quad.glsl");
		}
	};

	class FXAAPassFS : public ShaderStage {
	public:
		FXAAPassFS() : ShaderStage(GL_FRAGMENT_SHADER, "FXAAPassFS") {
			addDefine("FXAA_PC", 1);
			addDefine("FXAA_GLSL_130", 1);
			addDefine("FXAA_GREEN_AS_LUMA", 1);
			addDefine("FXAA_QUALITY__PRESET", 23);
			setFilepath("fxaa_fs.glsl");
		}
	};

	DEFINE_SHADER_PROGRAM2(Program_FXAA, FXAAPassVS, FXAAPassFS);

}

namespace pathos {

	void FXAA::initializeResources(RenderCommandList& cmdList) {
		ubo.init<UBO_FXAA>();

		gRenderDevice->createFramebuffers(1, &fbo);
		cmdList.namedFramebufferDrawBuffer(fbo, GL_COLOR_ATTACHMENT0);
		cmdList.objectLabel(GL_FRAMEBUFFER, fbo, -1, "FBO_FXAA");
	}

	void FXAA::releaseResources(RenderCommandList& cmdList) {
		gRenderDevice->deleteFramebuffers(1, &fbo);

		markDestroyed();
	}

	void FXAA::renderPostProcess(RenderCommandList& cmdList, PlaneGeometry* fullscreenQuad) {
		SCOPED_DRAW_EVENT(FXAA);

		const GLuint input0 = getInput(EPostProcessInput::PPI_0); // toneMappingResult
		const GLuint output0 = getOutput(EPostProcessOutput::PPO_0); // sceneFinal or backbuffer

		SceneRenderTargets& sceneContext = *cmdList.sceneRenderTargets;

		// #note-fxaa: See the FXAA pixel shader for details
		float sharpness = 0.5f;
		float subpix = 0.75f;
		float edge_threshold = 0.166f;
		float edge_threshold_min = 0.0f; // 0.0833f;
		float console_edge_sharpness = 8.0f;
		float console_edge_threshold = 0.125f;
		float console_edge_threshold_min = 0.05f;

		vector2 inv_size(1.0f / (float)sceneContext.sceneWidth, 1.0f / (float)sceneContext.sceneHeight);
		vector4 inv_size_4(-inv_size.x, -inv_size.y, inv_size.x, inv_size.y);
		vector4 sharp_param = sharpness * inv_size_4;
		vector4 sharp2_param = 2.0f * inv_size_4;
		vector4 sharp3_param = vector4(8.0f, 8.0f, -4.0f, -4.0f) * inv_size_4;

		ShaderProgram& program = FIND_SHADER_PROGRAM(Program_FXAA);
		cmdList.useProgram(program.getGLName());

		UBO_FXAA uboData;
		uboData.fxaaQualityRcpFrame          = vector2(inv_size.x, inv_size.y);
		uboData.fxaaConsoleRcpFrameOpt	     = vector4(sharp_param.x, sharp_param.y, sharp_param.z, sharp_param.w);
		uboData.fxaaConsoleRcpFrameOpt2	     = vector4(sharp2_param.x, sharp2_param.y, sharp2_param.z, sharp2_param.w);
		uboData.fxaaConsole360RcpFrameOpt2   = vector4(sharp3_param.x, sharp3_param.y, sharp3_param.z, sharp3_param.w);
		uboData.fxaaQualitySubpix			 = subpix;
		uboData.fxaaQualityEdgeThreshold	 = edge_threshold;
		uboData.fxaaQualityEdgeThresholdMin  = edge_threshold_min;
		uboData.fxaaConsoleEdgeSharpness	 = console_edge_sharpness;
		uboData.fxaaConsoleEdgeThreshold	 = console_edge_threshold;
		uboData.fxaaConsoleEdgeThresholdMin  = console_edge_threshold_min;
		uboData.fxaaConsole360ConstDir	     = vector4(1.0f, -1.0f, 0.25f, -0.25f);
		ubo.update(cmdList, UBO_FXAA::BINDING_SLOT, &uboData);

		if (output0 == 0) {
			cmdList.bindFramebuffer(GL_FRAMEBUFFER, 0);
		} else {
			cmdList.bindFramebuffer(GL_FRAMEBUFFER, fbo);
			cmdList.namedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, output0, 0);

			pathos::checkFramebufferStatus(cmdList, fbo, "fxaa");
		}

		cmdList.viewport(0, 0, sceneContext.sceneWidth, sceneContext.sceneHeight);

		cmdList.textureParameteri(input0, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		cmdList.textureParameteri(input0, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		cmdList.bindTextureUnit(0, input0);

		fullscreenQuad->activate_position_uv(cmdList);
		fullscreenQuad->activateIndexBuffer(cmdList);
		fullscreenQuad->drawPrimitive(cmdList);
	}

}
<|endoftext|>