text stringlengths 54 60.6k |
|---|
<commit_before>/*************************************************************************
*
* $RCSfile: brwview.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: oj $ $Date: 2002-05-02 07:10:09 $
*
* 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 _SBX_BRWVIEW_HXX
#include "brwview.hxx"
#endif
#ifndef _SBA_GRID_HXX
#include "sbagrid.hxx"
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
#ifndef DBACCESS_UI_DBTREEVIEW_HXX
#include "dbtreeview.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_RESOURCE_HRC_
#include "dbu_resource.hrc"
#endif
#ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_
#include <com/sun/star/form/XLoadable.hpp>
#endif
#ifndef _SBA_BWRCTRLR_HXX
#include "brwctrlr.hxx"
#endif
#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XControlContainer.hpp>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
using namespace dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::form;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
namespace
{
sal_Bool isGrabVclControlFocusAllowed(const UnoDataBrowserView* _pView)
{
sal_Bool bGrabFocus = sal_False;
SbaGridControl* pVclControl = _pView->getVclControl();
Reference< ::com::sun::star::awt::XControl > xGrid = _pView->getGridControl();
if (pVclControl && xGrid.is())
{
bGrabFocus = sal_True;
if(!pVclControl->HasChildPathFocus())
{
Reference<XChild> xChild(xGrid->getModel(),UNO_QUERY);
Reference<XLoadable> xLoad;
if(xChild.is())
xLoad = Reference<XLoadable>(xChild->getParent(),UNO_QUERY);
bGrabFocus = xLoad.is() && xLoad->isLoaded();
}
}
return bGrabFocus;
}
}
//==================================================================
//= UnoDataBrowserView
//==================================================================
// -------------------------------------------------------------------------
UnoDataBrowserView::UnoDataBrowserView( Window* pParent,
IController* _pController,
const Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rFactory)
:ODataView(pParent,_pController,_rFactory)
,m_pVclControl(NULL)
,m_pSplitter(NULL)
,m_pTreeView(NULL)
,m_pStatus(NULL)
{
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::Construct(const Reference< ::com::sun::star::awt::XControlModel >& xModel)
{
try
{
ODataView::Construct();
// our UNO representation
m_xMe = VCLUnoHelper::CreateControlContainer(this);
// create the (UNO-) control
m_xGrid = new SbaXGridControl(getORB());
DBG_ASSERT(m_xGrid.is(), "UnoDataBrowserView::Construct : could not create a grid control !");
// in design mode (for the moment)
m_xGrid->setDesignMode(sal_True);
Reference< ::com::sun::star::awt::XWindow > xGridWindow(m_xGrid, UNO_QUERY);
xGridWindow->setVisible(sal_True);
xGridWindow->setEnable(sal_True);
// introduce the model to the grid
m_xGrid->setModel(xModel);
// introduce the container (me) to the grid
Reference< ::com::sun::star::beans::XPropertySet > xModelSet(xModel, UNO_QUERY);
getContainer()->addControl(::comphelper::getString(xModelSet->getPropertyValue(PROPERTY_NAME)), m_xGrid);
// get the VCL-control
m_pVclControl = NULL;
Reference< ::com::sun::star::awt::XWindowPeer > xPeer = m_xGrid->getPeer();
if (xPeer.is())
{
SbaXGridPeer* pPeer = SbaXGridPeer::getImplementation(xPeer);
if (pPeer)
m_pVclControl = static_cast<SbaGridControl*>(pPeer->GetWindow());
::dbaui::notifySystemWindow(this,m_pVclControl,::comphelper::mem_fun(&TaskPaneList::AddWindow));
}
DBG_ASSERT(m_pVclControl != NULL, "UnoDataBrowserView::Construct : no real grid control !");
}
catch(Exception&)
{
::comphelper::disposeComponent(m_xGrid);
throw;
}
}
// -------------------------------------------------------------------------
UnoDataBrowserView::~UnoDataBrowserView()
{
::dbaui::notifySystemWindow(this,m_pVclControl,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));
m_pVclControl = NULL;
delete m_pSplitter;
m_pSplitter = NULL;
setTreeView(NULL);
if ( m_pStatus )
{
delete m_pStatus;
m_pStatus = NULL;
}
::comphelper::disposeComponent(m_xGrid);
::comphelper::disposeComponent(m_xMe);
}
// -----------------------------------------------------------------------------
IMPL_LINK( UnoDataBrowserView, SplitHdl, void*, p )
{
long nTest = m_pSplitter->GetPosPixel().Y();
m_pSplitter->SetPosPixel( Point( m_pSplitter->GetSplitPosPixel(), m_pSplitter->GetPosPixel().Y() ) );
Resize();
return 0L;
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::setSplitter(Splitter* _pSplitter)
{
m_pSplitter = _pSplitter;
m_pSplitter->SetSplitHdl( LINK( this, UnoDataBrowserView, SplitHdl ) );
LINK( this, UnoDataBrowserView, SplitHdl ).Call(m_pSplitter);
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::setTreeView(DBTreeView* _pTreeView)
{
if (m_pTreeView != _pTreeView)
{
if (m_pTreeView)
{
::dbaui::notifySystemWindow(this,m_pTreeView,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));
Window* pDeleteIt = m_pTreeView;
m_pTreeView = NULL;
delete pDeleteIt;
}
m_pTreeView = _pTreeView;
if ( m_pTreeView )
::dbaui::notifySystemWindow(this,m_pTreeView,::comphelper::mem_fun(&TaskPaneList::AddWindow));
}
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::showStatus( const String& _rStatus )
{
if (0 == _rStatus.Len())
hideStatus();
else
{
if (!m_pStatus)
m_pStatus = new FixedText(this);
m_pStatus->SetText(_rStatus);
m_pStatus->Show();
Resize();
Update();
}
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::hideStatus()
{
if (!m_pStatus || !m_pStatus->IsVisible())
// nothing to do
return;
m_pStatus->Hide();
Resize();
Update();
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::resizeDocumentView(Rectangle& _rPlayground)
{
Point aSplitPos;
Size aSplitSize;
Point aPlaygroundPos( _rPlayground.TopLeft() );
Size aPlaygroundSize( _rPlayground.GetSize() );
if (m_pTreeView && m_pTreeView->IsVisible() && m_pSplitter)
{
// calculate the splitter pos and size
aSplitPos = m_pSplitter->GetPosPixel();
aSplitPos.Y() = aPlaygroundPos.Y();
aSplitSize = m_pSplitter->GetOutputSizePixel();
aSplitSize.Height() = aPlaygroundSize.Height();
if( ( aSplitPos.X() + aSplitSize.Width() ) > ( aPlaygroundSize.Width() ))
aSplitPos.X() = aPlaygroundSize.Width() - aSplitSize.Width();
if( aSplitPos.X() <= aPlaygroundPos.X() )
aSplitPos.X() = aPlaygroundPos.X() + sal_Int32(aPlaygroundSize.Width() * 0.2);
// the tree pos and size
Point aTreeViewPos( aPlaygroundPos );
Size aTreeViewSize( aSplitPos.X(), aPlaygroundSize.Height() );
// the status pos and size
if (m_pStatus && m_pStatus->IsVisible())
{
Size aStatusSize(aPlaygroundPos.X(), GetTextHeight() + 2);
aStatusSize = LogicToPixel(aStatusSize, MAP_APPFONT);
aStatusSize.Width() = aTreeViewSize.Width() - 2 - 2;
Point aStatusPos( aPlaygroundPos.X() + 2, aTreeViewPos.Y() + aTreeViewSize.Height() - aStatusSize.Height() );
m_pStatus->SetPosSizePixel( aStatusPos, aStatusSize );
aTreeViewSize.Height() -= aStatusSize.Height();
}
// set the size of treelistbox
m_pTreeView->SetPosSizePixel( aTreeViewPos, aTreeViewSize );
//set the size of the splitter
m_pSplitter->SetPosSizePixel( aSplitPos, Size( aSplitSize.Width(), aPlaygroundSize.Height() ) );
m_pSplitter->SetDragRectPixel( _rPlayground );
}
// set the size of grid control
Reference< ::com::sun::star::awt::XWindow > xGridAsWindow(m_xGrid, UNO_QUERY);
if (xGridAsWindow.is())
xGridAsWindow->setPosSize( aSplitPos.X() + aSplitSize.Width(), aPlaygroundPos.Y(),
aPlaygroundSize.Width() - aSplitSize.Width() - aSplitPos.X(), aPlaygroundSize.Height(), ::com::sun::star::awt::PosSize::POSSIZE);
// just for completeness: there is no space left, we occupied it all ...
_rPlayground.SetPos( _rPlayground.BottomRight() );
_rPlayground.SetSize( Size( 0, 0 ) );
}
//------------------------------------------------------------------
sal_uInt16 UnoDataBrowserView::Model2ViewPos(sal_uInt16 nPos) const
{
return m_pVclControl ? m_pVclControl->GetViewColumnPos(m_pVclControl->GetColumnIdFromModelPos(nPos)) : -1;
}
//------------------------------------------------------------------
sal_uInt16 UnoDataBrowserView::View2ModelPos(sal_uInt16 nPos) const
{
return m_pVclControl ? m_pVclControl->GetModelColumnPos(m_pVclControl->GetColumnIdFromViewPos(nPos)) : -1;
}
//------------------------------------------------------------------
sal_uInt16 UnoDataBrowserView::ViewColumnCount() const
{
return m_pVclControl ? m_pVclControl->GetViewColCount() : 0;
}
//------------------------------------------------------------------
void UnoDataBrowserView::GetFocus()
{
ODataView::GetFocus();
if( m_pTreeView && m_pTreeView->IsVisible() && !m_pTreeView->HasChildPathFocus())
m_pTreeView->GrabFocus();
else if (m_pVclControl && m_xGrid.is())
{
sal_Bool bGrabFocus = sal_False;
if(!m_pVclControl->HasChildPathFocus())
{
bGrabFocus = isGrabVclControlFocusAllowed(this);
if( bGrabFocus )
m_pVclControl->GrabFocus();
}
if(!bGrabFocus && m_pTreeView && m_pTreeView->IsVisible() )
m_pTreeView->GrabFocus();
}
}
// -------------------------------------------------------------------------
long UnoDataBrowserView::PreNotify( NotifyEvent& rNEvt )
{
long nDone = 0L;
if(rNEvt.GetType() == EVENT_KEYINPUT)
{
sal_Bool bGrabAllowed = isGrabVclControlFocusAllowed(this);
if ( bGrabAllowed )
{
const KeyEvent* pKeyEvt = rNEvt.GetKeyEvent();
const KeyCode& rKeyCode = pKeyEvt->GetKeyCode();
if( rKeyCode == KeyCode(KEY_E,TRUE,TRUE,FALSE) )
{
if ( m_pTreeView && m_pVclControl && m_pTreeView->HasChildPathFocus() )
m_pVclControl->GrabFocus();
nDone = 1L;
}
}
}
return nDone ? nDone : ODataView::PreNotify(rNEvt);
}
// -----------------------------------------------------------------------------
BrowserViewStatusDisplay::BrowserViewStatusDisplay( UnoDataBrowserView* _pView, const String& _rStatus )
:m_pView(_pView)
{
if (m_pView)
m_pView->showStatus(_rStatus);
}
// -----------------------------------------------------------------------------
BrowserViewStatusDisplay::~BrowserViewStatusDisplay( )
{
if (m_pView)
m_pView->showStatus(String());
}
// -----------------------------------------------------------------------------
<commit_msg>#101214# enable ctrl+shift+e also to switch back fromgrid to treeview<commit_after>/*************************************************************************
*
* $RCSfile: brwview.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: oj $ $Date: 2002-07-11 10:01:56 $
*
* 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 _SBX_BRWVIEW_HXX
#include "brwview.hxx"
#endif
#ifndef _SBA_GRID_HXX
#include "sbagrid.hxx"
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
#ifndef DBACCESS_UI_DBTREEVIEW_HXX
#include "dbtreeview.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_RESOURCE_HRC_
#include "dbu_resource.hrc"
#endif
#ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_
#include <com/sun/star/form/XLoadable.hpp>
#endif
#ifndef _SBA_BWRCTRLR_HXX
#include "brwctrlr.hxx"
#endif
#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XControlContainer.hpp>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
using namespace dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::form;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
namespace
{
sal_Bool isGrabVclControlFocusAllowed(const UnoDataBrowserView* _pView)
{
sal_Bool bGrabFocus = sal_False;
SbaGridControl* pVclControl = _pView->getVclControl();
Reference< ::com::sun::star::awt::XControl > xGrid = _pView->getGridControl();
if (pVclControl && xGrid.is())
{
bGrabFocus = sal_True;
if(!pVclControl->HasChildPathFocus())
{
Reference<XChild> xChild(xGrid->getModel(),UNO_QUERY);
Reference<XLoadable> xLoad;
if(xChild.is())
xLoad = Reference<XLoadable>(xChild->getParent(),UNO_QUERY);
bGrabFocus = xLoad.is() && xLoad->isLoaded();
}
}
return bGrabFocus;
}
}
//==================================================================
//= UnoDataBrowserView
//==================================================================
// -------------------------------------------------------------------------
UnoDataBrowserView::UnoDataBrowserView( Window* pParent,
IController* _pController,
const Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rFactory)
:ODataView(pParent,_pController,_rFactory)
,m_pVclControl(NULL)
,m_pSplitter(NULL)
,m_pTreeView(NULL)
,m_pStatus(NULL)
{
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::Construct(const Reference< ::com::sun::star::awt::XControlModel >& xModel)
{
try
{
ODataView::Construct();
// our UNO representation
m_xMe = VCLUnoHelper::CreateControlContainer(this);
// create the (UNO-) control
m_xGrid = new SbaXGridControl(getORB());
DBG_ASSERT(m_xGrid.is(), "UnoDataBrowserView::Construct : could not create a grid control !");
// in design mode (for the moment)
m_xGrid->setDesignMode(sal_True);
Reference< ::com::sun::star::awt::XWindow > xGridWindow(m_xGrid, UNO_QUERY);
xGridWindow->setVisible(sal_True);
xGridWindow->setEnable(sal_True);
// introduce the model to the grid
m_xGrid->setModel(xModel);
// introduce the container (me) to the grid
Reference< ::com::sun::star::beans::XPropertySet > xModelSet(xModel, UNO_QUERY);
getContainer()->addControl(::comphelper::getString(xModelSet->getPropertyValue(PROPERTY_NAME)), m_xGrid);
// get the VCL-control
m_pVclControl = NULL;
Reference< ::com::sun::star::awt::XWindowPeer > xPeer = m_xGrid->getPeer();
if (xPeer.is())
{
SbaXGridPeer* pPeer = SbaXGridPeer::getImplementation(xPeer);
if (pPeer)
m_pVclControl = static_cast<SbaGridControl*>(pPeer->GetWindow());
::dbaui::notifySystemWindow(this,m_pVclControl,::comphelper::mem_fun(&TaskPaneList::AddWindow));
}
DBG_ASSERT(m_pVclControl != NULL, "UnoDataBrowserView::Construct : no real grid control !");
}
catch(Exception&)
{
::comphelper::disposeComponent(m_xGrid);
throw;
}
}
// -------------------------------------------------------------------------
UnoDataBrowserView::~UnoDataBrowserView()
{
::dbaui::notifySystemWindow(this,m_pVclControl,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));
m_pVclControl = NULL;
delete m_pSplitter;
m_pSplitter = NULL;
setTreeView(NULL);
if ( m_pStatus )
{
delete m_pStatus;
m_pStatus = NULL;
}
::comphelper::disposeComponent(m_xGrid);
::comphelper::disposeComponent(m_xMe);
}
// -----------------------------------------------------------------------------
IMPL_LINK( UnoDataBrowserView, SplitHdl, void*, p )
{
long nTest = m_pSplitter->GetPosPixel().Y();
m_pSplitter->SetPosPixel( Point( m_pSplitter->GetSplitPosPixel(), m_pSplitter->GetPosPixel().Y() ) );
Resize();
return 0L;
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::setSplitter(Splitter* _pSplitter)
{
m_pSplitter = _pSplitter;
m_pSplitter->SetSplitHdl( LINK( this, UnoDataBrowserView, SplitHdl ) );
LINK( this, UnoDataBrowserView, SplitHdl ).Call(m_pSplitter);
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::setTreeView(DBTreeView* _pTreeView)
{
if (m_pTreeView != _pTreeView)
{
if (m_pTreeView)
{
::dbaui::notifySystemWindow(this,m_pTreeView,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));
Window* pDeleteIt = m_pTreeView;
m_pTreeView = NULL;
delete pDeleteIt;
}
m_pTreeView = _pTreeView;
if ( m_pTreeView )
::dbaui::notifySystemWindow(this,m_pTreeView,::comphelper::mem_fun(&TaskPaneList::AddWindow));
}
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::showStatus( const String& _rStatus )
{
if (0 == _rStatus.Len())
hideStatus();
else
{
if (!m_pStatus)
m_pStatus = new FixedText(this);
m_pStatus->SetText(_rStatus);
m_pStatus->Show();
Resize();
Update();
}
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::hideStatus()
{
if (!m_pStatus || !m_pStatus->IsVisible())
// nothing to do
return;
m_pStatus->Hide();
Resize();
Update();
}
// -------------------------------------------------------------------------
void UnoDataBrowserView::resizeDocumentView(Rectangle& _rPlayground)
{
Point aSplitPos;
Size aSplitSize;
Point aPlaygroundPos( _rPlayground.TopLeft() );
Size aPlaygroundSize( _rPlayground.GetSize() );
if (m_pTreeView && m_pTreeView->IsVisible() && m_pSplitter)
{
// calculate the splitter pos and size
aSplitPos = m_pSplitter->GetPosPixel();
aSplitPos.Y() = aPlaygroundPos.Y();
aSplitSize = m_pSplitter->GetOutputSizePixel();
aSplitSize.Height() = aPlaygroundSize.Height();
if( ( aSplitPos.X() + aSplitSize.Width() ) > ( aPlaygroundSize.Width() ))
aSplitPos.X() = aPlaygroundSize.Width() - aSplitSize.Width();
if( aSplitPos.X() <= aPlaygroundPos.X() )
aSplitPos.X() = aPlaygroundPos.X() + sal_Int32(aPlaygroundSize.Width() * 0.2);
// the tree pos and size
Point aTreeViewPos( aPlaygroundPos );
Size aTreeViewSize( aSplitPos.X(), aPlaygroundSize.Height() );
// the status pos and size
if (m_pStatus && m_pStatus->IsVisible())
{
Size aStatusSize(aPlaygroundPos.X(), GetTextHeight() + 2);
aStatusSize = LogicToPixel(aStatusSize, MAP_APPFONT);
aStatusSize.Width() = aTreeViewSize.Width() - 2 - 2;
Point aStatusPos( aPlaygroundPos.X() + 2, aTreeViewPos.Y() + aTreeViewSize.Height() - aStatusSize.Height() );
m_pStatus->SetPosSizePixel( aStatusPos, aStatusSize );
aTreeViewSize.Height() -= aStatusSize.Height();
}
// set the size of treelistbox
m_pTreeView->SetPosSizePixel( aTreeViewPos, aTreeViewSize );
//set the size of the splitter
m_pSplitter->SetPosSizePixel( aSplitPos, Size( aSplitSize.Width(), aPlaygroundSize.Height() ) );
m_pSplitter->SetDragRectPixel( _rPlayground );
}
// set the size of grid control
Reference< ::com::sun::star::awt::XWindow > xGridAsWindow(m_xGrid, UNO_QUERY);
if (xGridAsWindow.is())
xGridAsWindow->setPosSize( aSplitPos.X() + aSplitSize.Width(), aPlaygroundPos.Y(),
aPlaygroundSize.Width() - aSplitSize.Width() - aSplitPos.X(), aPlaygroundSize.Height(), ::com::sun::star::awt::PosSize::POSSIZE);
// just for completeness: there is no space left, we occupied it all ...
_rPlayground.SetPos( _rPlayground.BottomRight() );
_rPlayground.SetSize( Size( 0, 0 ) );
}
//------------------------------------------------------------------
sal_uInt16 UnoDataBrowserView::Model2ViewPos(sal_uInt16 nPos) const
{
return m_pVclControl ? m_pVclControl->GetViewColumnPos(m_pVclControl->GetColumnIdFromModelPos(nPos)) : -1;
}
//------------------------------------------------------------------
sal_uInt16 UnoDataBrowserView::View2ModelPos(sal_uInt16 nPos) const
{
return m_pVclControl ? m_pVclControl->GetModelColumnPos(m_pVclControl->GetColumnIdFromViewPos(nPos)) : -1;
}
//------------------------------------------------------------------
sal_uInt16 UnoDataBrowserView::ViewColumnCount() const
{
return m_pVclControl ? m_pVclControl->GetViewColCount() : 0;
}
//------------------------------------------------------------------
void UnoDataBrowserView::GetFocus()
{
ODataView::GetFocus();
if( m_pTreeView && m_pTreeView->IsVisible() && !m_pTreeView->HasChildPathFocus())
m_pTreeView->GrabFocus();
else if (m_pVclControl && m_xGrid.is())
{
sal_Bool bGrabFocus = sal_False;
if(!m_pVclControl->HasChildPathFocus())
{
bGrabFocus = isGrabVclControlFocusAllowed(this);
if( bGrabFocus )
m_pVclControl->GrabFocus();
}
if(!bGrabFocus && m_pTreeView && m_pTreeView->IsVisible() )
m_pTreeView->GrabFocus();
}
}
// -------------------------------------------------------------------------
long UnoDataBrowserView::PreNotify( NotifyEvent& rNEvt )
{
long nDone = 0L;
if(rNEvt.GetType() == EVENT_KEYINPUT)
{
sal_Bool bGrabAllowed = isGrabVclControlFocusAllowed(this);
if ( bGrabAllowed )
{
const KeyEvent* pKeyEvt = rNEvt.GetKeyEvent();
const KeyCode& rKeyCode = pKeyEvt->GetKeyCode();
if( rKeyCode == KeyCode(KEY_E,TRUE,TRUE,FALSE) )
{
if ( m_pTreeView && m_pVclControl && m_pTreeView->HasChildPathFocus() )
m_pVclControl->GrabFocus();
else if ( m_pTreeView && m_pVclControl && m_pVclControl->HasChildPathFocus() )
m_pTreeView->GrabFocus();
nDone = 1L;
}
}
}
return nDone ? nDone : ODataView::PreNotify(rNEvt);
}
// -----------------------------------------------------------------------------
BrowserViewStatusDisplay::BrowserViewStatusDisplay( UnoDataBrowserView* _pView, const String& _rStatus )
:m_pView(_pView)
{
if (m_pView)
m_pView->showStatus(_rStatus);
}
// -----------------------------------------------------------------------------
BrowserViewStatusDisplay::~BrowserViewStatusDisplay( )
{
if (m_pView)
m_pView->showStatus(String());
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: sqledit.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: fs $ $Date: 2001-08-23 14:47:34 $
*
* 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 DBAUI_SQLEDIT_HXX
#include "sqledit.hxx"
#endif
#ifndef DBAUI_QUERYVIEW_TEXT_HXX
#include "QueryTextView.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include "dbaccess_helpid.hrc"
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef DBAUI_UNDOSQLEDIT_HXX
#include "undosqledit.hxx"
#endif
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#include "QueryDesignView.hxx"
#endif
//////////////////////////////////////////////////////////////////////////
// OSqlEdit
//------------------------------------------------------------------------------
using namespace dbaui;
DBG_NAME(OSqlEdit);
OSqlEdit::OSqlEdit( OQueryTextView* pParent, WinBits nWinStyle ) :
MultiLineEdit( pParent, nWinStyle )
,m_bAccelAction( sal_False )
,m_bStopTimer(sal_False )
,m_pView(pParent)
{
DBG_CTOR(OSqlEdit,NULL);
SetHelpId( HID_CTL_QRYSQLEDIT );
SetModifyHdl( LINK(this, OSqlEdit, ModifyHdl) );
m_timerUndoActionCreation.SetTimeout(1000);
m_timerUndoActionCreation.SetTimeoutHdl(LINK(this, OSqlEdit, OnUndoActionTimer));
m_timerInvalidate.SetTimeout(200);
m_timerInvalidate.SetTimeoutHdl(LINK(this, OSqlEdit, OnInvalidateTimer));
m_timerInvalidate.Start();
}
//------------------------------------------------------------------------------
OSqlEdit::~OSqlEdit()
{
if (m_timerUndoActionCreation.IsActive())
m_timerUndoActionCreation.Stop();
DBG_DTOR(OSqlEdit,NULL);
}
//------------------------------------------------------------------------------
void OSqlEdit::KeyInput( const KeyEvent& rKEvt )
{
DBG_CHKTHIS(OSqlEdit,NULL);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);
// Ist dies ein Cut, Copy, Paste Event?
KeyFuncType aKeyFunc = rKEvt.GetKeyCode().GetFunction();
if( (aKeyFunc==KEYFUNC_CUT)||(aKeyFunc==KEYFUNC_COPY)||(aKeyFunc==KEYFUNC_PASTE) )
m_bAccelAction = sal_True;
MultiLineEdit::KeyInput( rKEvt );
if( m_bAccelAction )
m_bAccelAction = sal_False;
}
//------------------------------------------------------------------------------
sal_Bool OSqlEdit::IsInAccelAct()
{
DBG_CHKTHIS(OSqlEdit,NULL);
// Das Cut, Copy, Paste per Accel. fuehrt neben der Aktion im Edit im View
// auch die entsprechenden Slots aus. Die Aktionen finden also zweimal statt.
// Um dies zu verhindern, kann im View beim SlotExec diese Funktion
// aufgerufen werden.
return m_bAccelAction;
}
//------------------------------------------------------------------------------
void OSqlEdit::GetFocus()
{
DBG_CHKTHIS(OSqlEdit,NULL);
m_strOrigText = GetText();
MultiLineEdit::GetFocus();
}
//------------------------------------------------------------------------------
IMPL_LINK(OSqlEdit, OnUndoActionTimer, void*, EMPTYARG)
{
String aText = GetText();
if(aText != m_strOrigText)
{
SfxUndoManager* pUndoMgr = m_pView->getContainerWindow()->getDesignView()->getController()->getUndoMgr();
OSqlEditUndoAct* pUndoAct = new OSqlEditUndoAct( this );
pUndoAct->SetOriginalText( m_strOrigText );
pUndoMgr->AddUndoAction( pUndoAct );
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_UNDO);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_REDO);
m_strOrigText = aText;
}
return 0L;
}
//------------------------------------------------------------------------------
IMPL_LINK(OSqlEdit, OnInvalidateTimer, void*, EMPTYARG)
{
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);
if(!m_bStopTimer)
m_timerInvalidate.Start();
return 0L;
}
//------------------------------------------------------------------------------
IMPL_LINK(OSqlEdit, ModifyHdl, void*, EMPTYTAG)
{
if (m_timerUndoActionCreation.IsActive())
m_timerUndoActionCreation.Stop();
m_timerUndoActionCreation.Start();
if (!m_pView->getContainerWindow()->getDesignView()->getController()->isModified())
m_pView->getContainerWindow()->getDesignView()->getController()->setModified( sal_True );
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_SBA_QRY_EXECUTE);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);
m_lnkTextModifyHdl.Call(NULL);
return 0;
}
//------------------------------------------------------------------------------
void OSqlEdit::OverloadedSetText(const String& rNewText)
{
DBG_CHKTHIS(OSqlEdit,NULL);
if (m_timerUndoActionCreation.IsActive())
{ // die noch anstehenden Undo-Action erzeugen
m_timerUndoActionCreation.Stop();
LINK(this, OSqlEdit, OnUndoActionTimer).Call(NULL);
}
MultiLineEdit::SetText(rNewText);
m_strOrigText = rNewText;
}
// -----------------------------------------------------------------------------
void OSqlEdit::stopTimer()
{
m_bStopTimer = sal_True;
if (m_timerInvalidate.IsActive())
m_timerInvalidate.Stop();
}
// -----------------------------------------------------------------------------
void OSqlEdit::startTimer()
{
m_bStopTimer = sal_False;
if (!m_timerInvalidate.IsActive())
m_timerInvalidate.Start();
}
//==============================================================================
<commit_msg>INTEGRATION: CWS insight01 (1.5.126); FILE MERGED 2004/07/15 10:52:33 oj 1.5.126.2: add chkthis macros 2004/07/09 14:05:15 oj 1.5.126.1: resource changes<commit_after>/*************************************************************************
*
* $RCSfile: sqledit.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2004-08-02 15:36:57 $
*
* 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 DBAUI_SQLEDIT_HXX
#include "sqledit.hxx"
#endif
#ifndef DBAUI_QUERYVIEW_TEXT_HXX
#include "QueryTextView.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include "dbaccess_helpid.hrc"
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef DBAUI_UNDOSQLEDIT_HXX
#include "undosqledit.hxx"
#endif
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#include "QueryDesignView.hxx"
#endif
//////////////////////////////////////////////////////////////////////////
// OSqlEdit
//------------------------------------------------------------------------------
using namespace dbaui;
DBG_NAME(OSqlEdit);
OSqlEdit::OSqlEdit( OQueryTextView* pParent, WinBits nWinStyle ) :
MultiLineEdit( pParent, nWinStyle )
,m_bAccelAction( sal_False )
,m_bStopTimer(sal_False )
,m_pView(pParent)
{
DBG_CTOR(OSqlEdit,NULL);
SetHelpId( HID_CTL_QRYSQLEDIT );
SetModifyHdl( LINK(this, OSqlEdit, ModifyHdl) );
m_timerUndoActionCreation.SetTimeout(1000);
m_timerUndoActionCreation.SetTimeoutHdl(LINK(this, OSqlEdit, OnUndoActionTimer));
m_timerInvalidate.SetTimeout(200);
m_timerInvalidate.SetTimeoutHdl(LINK(this, OSqlEdit, OnInvalidateTimer));
m_timerInvalidate.Start();
}
//------------------------------------------------------------------------------
OSqlEdit::~OSqlEdit()
{
DBG_DTOR(OSqlEdit,NULL);
if (m_timerUndoActionCreation.IsActive())
m_timerUndoActionCreation.Stop();
}
//------------------------------------------------------------------------------
void OSqlEdit::KeyInput( const KeyEvent& rKEvt )
{
DBG_CHKTHIS(OSqlEdit,NULL);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);
// Ist dies ein Cut, Copy, Paste Event?
KeyFuncType aKeyFunc = rKEvt.GetKeyCode().GetFunction();
if( (aKeyFunc==KEYFUNC_CUT)||(aKeyFunc==KEYFUNC_COPY)||(aKeyFunc==KEYFUNC_PASTE) )
m_bAccelAction = sal_True;
MultiLineEdit::KeyInput( rKEvt );
if( m_bAccelAction )
m_bAccelAction = sal_False;
}
//------------------------------------------------------------------------------
sal_Bool OSqlEdit::IsInAccelAct()
{
DBG_CHKTHIS(OSqlEdit,NULL);
// Das Cut, Copy, Paste per Accel. fuehrt neben der Aktion im Edit im View
// auch die entsprechenden Slots aus. Die Aktionen finden also zweimal statt.
// Um dies zu verhindern, kann im View beim SlotExec diese Funktion
// aufgerufen werden.
return m_bAccelAction;
}
//------------------------------------------------------------------------------
void OSqlEdit::GetFocus()
{
DBG_CHKTHIS(OSqlEdit,NULL);
m_strOrigText =GetText();
MultiLineEdit::GetFocus();
}
//------------------------------------------------------------------------------
IMPL_LINK(OSqlEdit, OnUndoActionTimer, void*, EMPTYARG)
{
String aText =GetText();
if(aText != m_strOrigText)
{
SfxUndoManager* pUndoMgr = m_pView->getContainerWindow()->getDesignView()->getController()->getUndoMgr();
OSqlEditUndoAct* pUndoAct = new OSqlEditUndoAct( this );
pUndoAct->SetOriginalText( m_strOrigText );
pUndoMgr->AddUndoAction( pUndoAct );
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_UNDO);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_REDO);
m_strOrigText =aText;
}
return 0L;
}
//------------------------------------------------------------------------------
IMPL_LINK(OSqlEdit, OnInvalidateTimer, void*, EMPTYARG)
{
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);
if(!m_bStopTimer)
m_timerInvalidate.Start();
return 0L;
}
//------------------------------------------------------------------------------
IMPL_LINK(OSqlEdit, ModifyHdl, void*, EMPTYTAG)
{
if (m_timerUndoActionCreation.IsActive())
m_timerUndoActionCreation.Stop();
m_timerUndoActionCreation.Start();
if (!m_pView->getContainerWindow()->getDesignView()->getController()->isModified())
m_pView->getContainerWindow()->getDesignView()->getController()->setModified( sal_True );
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_SBA_QRY_EXECUTE);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);
m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);
m_lnkTextModifyHdl.Call(NULL);
return 0;
}
//------------------------------------------------------------------------------
void OSqlEdit::OverloadedSetText(const String& rNewText)
{
DBG_CHKTHIS(OSqlEdit,NULL);
if (m_timerUndoActionCreation.IsActive())
{ // die noch anstehenden Undo-Action erzeugen
m_timerUndoActionCreation.Stop();
LINK(this, OSqlEdit, OnUndoActionTimer).Call(NULL);
}
MultiLineEdit::SetText(rNewText);
m_strOrigText =rNewText;
}
// -----------------------------------------------------------------------------
void OSqlEdit::stopTimer()
{
m_bStopTimer = sal_True;
if (m_timerInvalidate.IsActive())
m_timerInvalidate.Stop();
}
// -----------------------------------------------------------------------------
void OSqlEdit::startTimer()
{
m_bStopTimer = sal_False;
if (!m_timerInvalidate.IsActive())
m_timerInvalidate.Start();
}
//==============================================================================
<|endoftext|> |
<commit_before>#include "app/view/layout_hierarchy.h"
#include "core/epi/disposed.h"
#include "core/epi/visibility.h"
#include "core/util/holder_util.h"
#include "graphics/base/size.h"
#include "graphics/inf/renderer.h"
#include "app/base/event.h"
#include "app/inf/layout.h"
#include "app/view/view.h"
namespace ark {
LayoutHierarchy::Slot::Slot(const sp<Renderer>& renderer, bool layoutRequested)
: _x(0), _y(0), _layout_width(0), _layout_height(0), _layout_requested(layoutRequested), _renderer(renderer), _view(renderer.as<View>()), _layout_event_listener(renderer.as<LayoutEventListener>()),
_disposed(renderer.as<Disposed>()), _visibility(renderer.as<Visibility>())
{
DASSERT(_renderer);
}
void LayoutHierarchy::Slot::traverse(const Holder::Visitor& visitor)
{
if(_view)
HolderUtil::visit(_view, visitor);
else
HolderUtil::visit(_renderer, visitor);
}
bool LayoutHierarchy::Slot::isDisposed() const
{
return _disposed && _disposed->val();
}
bool LayoutHierarchy::Slot::layoutRequested() const
{
return _layout_requested;
}
void LayoutHierarchy::Slot::updateLayout()
{
if(_view)
{
_layout_width = _view->size()->width();
_layout_height = _view->size()->height();
}
_layout_requested = false;
}
void LayoutHierarchy::Slot::doPlace(Layout::Context& ctx, float clientHeight, const sp<Layout>& layout)
{
if(_view)
{
const sp<LayoutParam>& layoutParam = _view->layoutParam();
DASSERT(layoutParam);
if(layoutParam->display() == LayoutParam::DISPLAY_BLOCK)
{
const Rect& margins = layoutParam->margins();
const Rect target = layout->place(ctx, layoutParam);
_y = clientHeight - layoutParam->contentHeight() - target.top() - margins.top();
_x = target.left() + margins.left();
}
}
}
void LayoutHierarchy::Slot::doWrapContentPlace(Layout::Context& ctx, const sp<Layout>& layout, Rect& contentRect) const
{
if(_view)
{
const sp<LayoutParam>& layoutParam = _view->layoutParam();
DASSERT(layoutParam);
if(layoutParam->display() == LayoutParam::DISPLAY_BLOCK)
{
const Rect rect = layout->place(ctx, layoutParam);
contentRect.setLeft(std::min(contentRect.left(), rect.left()));
contentRect.setTop(std::min(contentRect.top(), rect.top()));
contentRect.setRight(std::max(contentRect.right(), rect.right()));
contentRect.setBottom(std::max(contentRect.bottom(), rect.bottom()));
}
}
}
void LayoutHierarchy::Slot::doLayoutEnd(const Rect& p)
{
if(_view)
{
_x += p.left();
_y -= p.top();
}
updateLayout();
}
void LayoutHierarchy::Slot::render(RenderRequest& renderRequest, const V3& position)
{
if(!_layout_requested)
{
_renderer->render(renderRequest, position + V3(_x, _y, 0));
if(_view)
_layout_requested = _layout_width != _view->size()->width() || _layout_height != _view->size()->height();
}
}
bool LayoutHierarchy::Slot::onEventDispatch(const Event& event, float x, float y)
{
if(_view && (!_visibility || _visibility->val()))
{
const sp<LayoutParam>& layoutParam = _view->layoutParam();
const Rect target(x + _x, y + _y, x + _x + layoutParam->contentWidth(), y + _y + layoutParam->contentHeight());
const Event viewEvent(event.action(), event.x() - _x - x, event.y() - _y - y, event.timestamp(), event.code());
const bool ptin = event.ptin(target);
if(_layout_event_listener)
return _layout_event_listener->onEvent(event, target.left(), target.top(), ptin);
return _view->dispatchEvent(viewEvent, ptin);
}
return false;
}
sp<LayoutParam> LayoutHierarchy::Slot::getLayoutParam() const
{
return _view ? static_cast<sp<LayoutParam>>(_view->layoutParam()) : nullptr;
}
LayoutHierarchy::LayoutHierarchy(const sp<Layout>& layout)
: _layout(layout)
{
}
void LayoutHierarchy::traverse(const Holder::Visitor& visitor)
{
for(const sp<Slot>& i : _slots)
i->traverse(visitor);
for(const sp<Slot>& i : _incremental)
i->traverse(visitor);
}
void LayoutHierarchy::render(RenderRequest& renderRequest, const V3& position) const
{
for(const sp<Slot>& i: _slots)
i->render(renderRequest, position);
}
bool LayoutHierarchy::onEvent(const Event& event, float x, float y) const
{
Event::Action action = event.action();
if(action == Event::ACTION_MOVE || action == Event::ACTION_UP || action == Event::ACTION_DOWN)
{
for(auto iter =_slots.rbegin(); iter != _slots.rend(); ++iter)
if((*iter)->onEventDispatch(event, x, y))
return true;
}
return false;
}
bool LayoutHierarchy::isLayoutNeeded(const LayoutParam& layoutParam)
{
bool layoutNeeded = false;
for(auto iter = _slots.begin(); iter != _slots.end(); ++iter)
{
const sp<Slot>& i = *iter;
if(i->isDisposed())
{
iter = _slots.erase(iter);
if(iter == _slots.end())
return true;
continue;
}
layoutNeeded = layoutNeeded || i->layoutRequested();
}
const V3 newLayoutSize = layoutParam.size()->val();
if(newLayoutSize != _layout_size)
{
_layout_size = newLayoutSize;
return true;
}
return layoutNeeded;
}
std::vector<sp<LayoutParam>> LayoutHierarchy::getLayoutParams() const
{
std::vector<sp<LayoutParam>> layoutParams;
for(const sp<Slot>& i : _slots)
{
sp<LayoutParam> lp = i->getLayoutParam();
if(lp && lp->display() == LayoutParam::DISPLAY_BLOCK)
layoutParams.push_back(std::move(lp));
}
return layoutParams;
}
void LayoutHierarchy::updateLayout(LayoutParam& layoutParam)
{
if(_incremental.size())
{
for(const sp<Slot>& i : _incremental)
_slots.push_back(i);
_incremental.clear();
}
if(isLayoutNeeded(layoutParam))
{
if(_layout)
{
Layout::Context ctx(layoutParam, [this]() {
return this->getLayoutParams();
});
if(layoutParam.isWrapContent())
doWrapContentLayout(ctx, layoutParam);
_layout->begin(ctx, layoutParam);
for(const sp<Slot>& i: _slots)
i->doPlace(ctx, layoutParam.contentHeight(), _layout);
const Rect p = _layout->end(ctx);
for(const sp<Slot>& i : _slots)
i->doLayoutEnd(p);
}
else
for(const sp<Slot>& i : _slots)
i->updateLayout();
}
}
void LayoutHierarchy::doWrapContentLayout(Layout::Context& ctx, LayoutParam& layoutParam)
{
LayoutParam lp(layoutParam);
Rect clientRect;
_layout->begin(ctx, lp);
for(const sp<Slot>& i: _slots)
i->doWrapContentPlace(ctx, _layout, clientRect);
_layout->end(ctx);
layoutParam.setContentWidth(clientRect.width());
layoutParam.setContentHeight(clientRect.height());
}
void LayoutHierarchy::addRenderer(const sp<Renderer>& renderer)
{
DASSERT(renderer);
_incremental.push_back(sp<LayoutHierarchy::Slot>::make(renderer, static_cast<bool>(_layout)));
}
}
<commit_msg>Layout bugfix<commit_after>#include "app/view/layout_hierarchy.h"
#include "core/epi/disposed.h"
#include "core/epi/visibility.h"
#include "core/util/holder_util.h"
#include "graphics/base/size.h"
#include "graphics/inf/renderer.h"
#include "app/base/event.h"
#include "app/inf/layout.h"
#include "app/view/view.h"
namespace ark {
LayoutHierarchy::Slot::Slot(const sp<Renderer>& renderer, bool layoutRequested)
: _x(0), _y(0), _layout_width(0), _layout_height(0), _layout_requested(layoutRequested), _renderer(renderer), _view(renderer.as<View>()), _layout_event_listener(renderer.as<LayoutEventListener>()),
_disposed(renderer.as<Disposed>()), _visibility(renderer.as<Visibility>())
{
DASSERT(_renderer);
}
void LayoutHierarchy::Slot::traverse(const Holder::Visitor& visitor)
{
if(_view)
HolderUtil::visit(_view, visitor);
else
HolderUtil::visit(_renderer, visitor);
}
bool LayoutHierarchy::Slot::isDisposed() const
{
return _disposed && _disposed->val();
}
bool LayoutHierarchy::Slot::layoutRequested() const
{
return _layout_requested;
}
void LayoutHierarchy::Slot::updateLayout()
{
if(_view)
{
_layout_width = _view->size()->width();
_layout_height = _view->size()->height();
}
_layout_requested = false;
}
void LayoutHierarchy::Slot::doPlace(Layout::Context& ctx, float clientHeight, const sp<Layout>& layout)
{
if(_view)
{
const sp<LayoutParam>& layoutParam = _view->layoutParam();
DASSERT(layoutParam);
if(layoutParam->display() == LayoutParam::DISPLAY_BLOCK)
{
const Rect& margins = layoutParam->margins();
const Rect target = layout->place(ctx, layoutParam);
_y = clientHeight - layoutParam->contentHeight() - target.top() - margins.top();
_x = target.left() + margins.left();
}
}
}
void LayoutHierarchy::Slot::doWrapContentPlace(Layout::Context& ctx, const sp<Layout>& layout, Rect& contentRect) const
{
if(_view)
{
const sp<LayoutParam>& layoutParam = _view->layoutParam();
DASSERT(layoutParam);
if(layoutParam->display() == LayoutParam::DISPLAY_BLOCK)
{
const Rect rect = layout->place(ctx, layoutParam);
contentRect.setLeft(std::min(contentRect.left(), rect.left()));
contentRect.setTop(std::min(contentRect.top(), rect.top()));
contentRect.setRight(std::max(contentRect.right(), rect.right()));
contentRect.setBottom(std::max(contentRect.bottom(), rect.bottom()));
}
}
}
void LayoutHierarchy::Slot::doLayoutEnd(const Rect& p)
{
if(_view)
{
_x += p.left();
_y -= p.top();
}
updateLayout();
}
void LayoutHierarchy::Slot::render(RenderRequest& renderRequest, const V3& position)
{
if(!_layout_requested)
{
_renderer->render(renderRequest, position + V3(_x, _y, 0));
if(_view)
_layout_requested = _layout_width != _view->size()->width() || _layout_height != _view->size()->height();
}
}
bool LayoutHierarchy::Slot::onEventDispatch(const Event& event, float x, float y)
{
if(_view && (!_visibility || _visibility->val()))
{
const sp<LayoutParam>& layoutParam = _view->layoutParam();
const Rect target(x + _x, y + _y, x + _x + layoutParam->contentWidth(), y + _y + layoutParam->contentHeight());
const Event viewEvent(event.action(), event.x() - _x - x, event.y() - _y - y, event.timestamp(), event.code());
const bool ptin = event.ptin(target);
if(_layout_event_listener)
return _layout_event_listener->onEvent(event, target.left(), target.top(), ptin);
return _view->dispatchEvent(viewEvent, ptin);
}
return false;
}
sp<LayoutParam> LayoutHierarchy::Slot::getLayoutParam() const
{
return _view ? static_cast<sp<LayoutParam>>(_view->layoutParam()) : nullptr;
}
LayoutHierarchy::LayoutHierarchy(const sp<Layout>& layout)
: _layout(layout)
{
}
void LayoutHierarchy::traverse(const Holder::Visitor& visitor)
{
for(const sp<Slot>& i : _slots)
i->traverse(visitor);
for(const sp<Slot>& i : _incremental)
i->traverse(visitor);
}
void LayoutHierarchy::render(RenderRequest& renderRequest, const V3& position) const
{
for(const sp<Slot>& i: _slots)
i->render(renderRequest, position);
}
bool LayoutHierarchy::onEvent(const Event& event, float x, float y) const
{
Event::Action action = event.action();
if(action == Event::ACTION_MOVE || action == Event::ACTION_UP || action == Event::ACTION_DOWN)
{
for(auto iter =_slots.rbegin(); iter != _slots.rend(); ++iter)
if((*iter)->onEventDispatch(event, x, y))
return true;
}
return false;
}
bool LayoutHierarchy::isLayoutNeeded(const LayoutParam& layoutParam)
{
bool layoutNeeded = false;
for(auto iter = _slots.begin(); iter != _slots.end(); )
{
const sp<Slot>& i = *iter;
if(i->isDisposed())
{
iter = _slots.erase(iter);
layoutNeeded = true;
}
else
++iter;
layoutNeeded = layoutNeeded || i->layoutRequested();
}
const V3 newLayoutSize = layoutParam.size()->val();
if(newLayoutSize != _layout_size)
{
_layout_size = newLayoutSize;
return true;
}
return layoutNeeded;
}
std::vector<sp<LayoutParam>> LayoutHierarchy::getLayoutParams() const
{
std::vector<sp<LayoutParam>> layoutParams;
for(const sp<Slot>& i : _slots)
{
sp<LayoutParam> lp = i->getLayoutParam();
if(lp && lp->display() == LayoutParam::DISPLAY_BLOCK)
layoutParams.push_back(std::move(lp));
}
return layoutParams;
}
void LayoutHierarchy::updateLayout(LayoutParam& layoutParam)
{
if(_incremental.size())
{
for(const sp<Slot>& i : _incremental)
_slots.push_back(i);
_incremental.clear();
}
if(isLayoutNeeded(layoutParam))
{
if(_layout)
{
Layout::Context ctx(layoutParam, [this]() {
return this->getLayoutParams();
});
if(layoutParam.isWrapContent())
doWrapContentLayout(ctx, layoutParam);
_layout->begin(ctx, layoutParam);
for(const sp<Slot>& i: _slots)
i->doPlace(ctx, layoutParam.contentHeight(), _layout);
const Rect p = _layout->end(ctx);
for(const sp<Slot>& i : _slots)
i->doLayoutEnd(p);
}
else
for(const sp<Slot>& i : _slots)
i->updateLayout();
}
}
void LayoutHierarchy::doWrapContentLayout(Layout::Context& ctx, LayoutParam& layoutParam)
{
LayoutParam lp(layoutParam);
Rect clientRect;
_layout->begin(ctx, lp);
for(const sp<Slot>& i: _slots)
i->doWrapContentPlace(ctx, _layout, clientRect);
_layout->end(ctx);
layoutParam.setContentWidth(clientRect.width());
layoutParam.setContentHeight(clientRect.height());
}
void LayoutHierarchy::addRenderer(const sp<Renderer>& renderer)
{
DASSERT(renderer);
_incremental.push_back(sp<LayoutHierarchy::Slot>::make(renderer, static_cast<bool>(_layout)));
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: WTypeSelect.hxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: ihi $ $Date: 2007-11-21 16:02:37 $
*
* 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 DBAUI_WIZ_TYPESELECT_HXX
#define DBAUI_WIZ_TYPESELECT_HXX
#ifndef DBAUI_WIZ_TABBPAGE_HXX
#include "WTabPage.hxx"
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef DBAUI_FIELDDESCRIPTIONCONTROL_HXX
#include "FieldDescControl.hxx"
#endif
#ifndef DBAUI_TYPEINFO_HXX
#include "TypeInfo.hxx"
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
class SvStream;
class SvParser;
namespace dbaui
{
class OTableDesignHelpBar;
// =============================================================================================
// OWizTypeSelectControl
// =============================================================================================
class OWizTypeSelectControl : public OFieldDescControl
{
protected:
virtual void ActivateAggregate( EControlType eType );
virtual void DeactivateAggregate( EControlType eType );
virtual void CellModified(long nRow, sal_uInt16 nColId );
virtual ::com::sun::star::lang::Locale GetLocale() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > GetFormatter() const;
virtual TOTypeInfoSP getTypeInfo(sal_Int32 _nPos);
virtual const OTypeInfoMap* getTypeInfo() const;
virtual sal_Bool isAutoIncrementValueEnabled() const;
virtual ::rtl::OUString getAutoIncrementValue() const;
public:
OWizTypeSelectControl(Window* pParent, const ResId& rResId,OTableDesignHelpBar* pHelpBar=NULL);
virtual ~OWizTypeSelectControl();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> getMetaData();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection();
};
// ========================================================
// Wizard Page: OWizTypeSelectList
// definiert nur das ::com::sun::star::ucb::Command f"ur das Contextmenu
// ========================================================
class OWizTypeSelectList : public MultiListBox
{
sal_Bool m_bPKey;
sal_Bool IsPrimaryKeyAllowed() const;
void setPrimaryKey( OFieldDescription* _pFieldDescr,
sal_uInt16 _nPos,
sal_Bool _bSet=sal_False);
protected:
virtual long PreNotify( NotifyEvent& rNEvt );
public:
OWizTypeSelectList( Window* pParent, WinBits nStyle = WB_BORDER ) : MultiListBox(pParent,nStyle) {};
OWizTypeSelectList( Window* pParent, const ResId& rResId ) : MultiListBox(pParent,rResId) {};
void SetPKey(sal_Bool bPKey) { m_bPKey = bPKey; }
};
// ========================================================
// Wizard Page: OWizTypeSelect
// Dient als Basis Klasse fuer unterschiedliche Kopiereigenschaften
// FillColumnList wird aufgerufen, wenn der Button AUTO ausgeloest wird.
// ========================================================
class OWizTypeSelect : public OWizardPage
{
friend class OWizTypeSelectControl;
friend class OWizTypeSelectList;
DECL_LINK( ColumnSelectHdl, MultiListBox* );
DECL_LINK( ButtonClickHdl, Button * );
protected:
OWizTypeSelectList m_lbColumnNames;
FixedLine m_flColumns;
OWizTypeSelectControl m_aTypeControl;
FixedLine m_flAutoType;
FixedText m_ftAuto;
NumericField m_etAuto;
PushButton m_pbAuto;
Image m_imgPKey;
SvStream* m_pParserStream; // stream to read the tokens from or NULL
::rtl::OUString m_sAutoIncrementValue;
sal_Int32 m_nDisplayRow;
sal_Bool m_bAutoIncrementEnabled;
sal_Bool m_bDuplicateName;
void fillColumnList(sal_uInt32 nRows);
virtual SvParser* createReader(sal_Int32 _nRows) = 0;
void EnableAuto(sal_Bool bEnable);
public:
virtual void Reset ( );
virtual void ActivatePage( );
virtual void Resize();
virtual sal_Bool LeavePage();
virtual String GetTitle() const;
OWizTypeSelect(Window* pParent,SvStream* _pStream = NULL);
virtual ~OWizTypeSelect();
inline void setDisplayRow(sal_Int32 _nRow) { m_nDisplayRow = _nRow - 1; }
inline void setDuplicateName(sal_Bool _bDuplicateName) { m_bDuplicateName = _bDuplicateName; }
};
}
#endif // DBAUI_WIZ_TYPESELECT_HXX
<commit_msg>INTEGRATION: CWS dba24d (1.14.88); FILE MERGED 2007/12/01 13:41:11 fs 1.14.88.2: RESYNC: (1.14-1.15); FILE MERGED 2007/11/08 14:21:04 fs 1.14.88.1: #i81658# re-factoring of the Copy Table wizard<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: WTypeSelect.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: rt $ $Date: 2008-01-30 08:49:15 $
*
* 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 DBAUI_WIZ_TYPESELECT_HXX
#define DBAUI_WIZ_TYPESELECT_HXX
#include "FieldDescControl.hxx"
#include "TypeInfo.hxx"
#include "WTabPage.hxx"
#include <vcl/button.hxx>
#include <vcl/field.hxx>
#include <vcl/fixed.hxx>
#include <vcl/lstbox.hxx>
class SvStream;
class SvParser;
namespace dbaui
{
class OTableDesignHelpBar;
// =============================================================================================
// OWizTypeSelectControl
// =============================================================================================
class OWizTypeSelectControl : public OFieldDescControl
{
protected:
virtual void ActivateAggregate( EControlType eType );
virtual void DeactivateAggregate( EControlType eType );
virtual void CellModified(long nRow, sal_uInt16 nColId );
virtual ::com::sun::star::lang::Locale GetLocale() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > GetFormatter() const;
virtual TOTypeInfoSP getTypeInfo(sal_Int32 _nPos);
virtual const OTypeInfoMap* getTypeInfo() const;
virtual sal_Bool isAutoIncrementValueEnabled() const;
virtual ::rtl::OUString getAutoIncrementValue() const;
public:
OWizTypeSelectControl(Window* pParent, const ResId& rResId,OTableDesignHelpBar* pHelpBar=NULL);
virtual ~OWizTypeSelectControl();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> getMetaData();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection();
};
// ========================================================
// Wizard Page: OWizTypeSelectList
// definiert nur das ::com::sun::star::ucb::Command f"ur das Contextmenu
// ========================================================
class OWizTypeSelectList : public MultiListBox
{
sal_Bool m_bPKey;
sal_Bool IsPrimaryKeyAllowed() const;
void setPrimaryKey( OFieldDescription* _pFieldDescr,
sal_uInt16 _nPos,
sal_Bool _bSet=sal_False);
protected:
virtual long PreNotify( NotifyEvent& rNEvt );
public:
OWizTypeSelectList( Window* pParent, WinBits nStyle = WB_BORDER ) : MultiListBox(pParent,nStyle) {};
OWizTypeSelectList( Window* pParent, const ResId& rResId ) : MultiListBox(pParent,rResId) {};
void SetPKey(sal_Bool bPKey) { m_bPKey = bPKey; }
};
// ========================================================
// Wizard Page: OWizTypeSelect
// Dient als Basis Klasse fuer unterschiedliche Kopiereigenschaften
// FillColumnList wird aufgerufen, wenn der Button AUTO ausgeloest wird.
// ========================================================
class OWizTypeSelect : public OWizardPage
{
friend class OWizTypeSelectControl;
friend class OWizTypeSelectList;
DECL_LINK( ColumnSelectHdl, MultiListBox* );
DECL_LINK( ButtonClickHdl, Button * );
protected:
OWizTypeSelectList m_lbColumnNames;
FixedLine m_flColumns;
OWizTypeSelectControl m_aTypeControl;
FixedLine m_flAutoType;
FixedText m_ftAuto;
NumericField m_etAuto;
PushButton m_pbAuto;
Image m_imgPKey;
SvStream* m_pParserStream; // stream to read the tokens from or NULL
::rtl::OUString m_sAutoIncrementValue;
sal_Int32 m_nDisplayRow;
sal_Bool m_bAutoIncrementEnabled;
sal_Bool m_bDuplicateName;
void fillColumnList(sal_uInt32 nRows);
virtual SvParser* createReader(sal_Int32 _nRows) = 0;
void EnableAuto(sal_Bool bEnable);
public:
virtual void Reset ( );
virtual void ActivatePage( );
virtual void Resize();
virtual sal_Bool LeavePage();
virtual String GetTitle() const;
OWizTypeSelect(Window* pParent, SvStream* _pStream = NULL );
virtual ~OWizTypeSelect();
inline void setDisplayRow(sal_Int32 _nRow) { m_nDisplayRow = _nRow - 1; }
inline void setDuplicateName(sal_Bool _bDuplicateName) { m_bDuplicateName = _bDuplicateName; }
};
// ========================================================
typedef OWizTypeSelect* (*TypeSelectionPageFactory)( Window*, SvStream& );
}
#endif // DBAUI_WIZ_TYPESELECT_HXX
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#include "arch/x86/insts/microldstop.hh"
#include <string>
namespace X86ISA
{
std::string LdStOp::generateDisassembly(Addr pc,
const SymbolTable *symtab) const
{
std::stringstream response;
printMnemonic(response, instMnem, mnemonic);
printDestReg(response, 0, dataSize);
response << ", ";
printSegment(response, segment);
ccprintf(response, ":[%d*", scale);
printSrcReg(response, 0, addressSize);
response << " + ";
printSrcReg(response, 1, addressSize);
ccprintf(response, " + %#x]", disp);
return response.str();
}
}
<commit_msg>X86: Hide the irrelevant portions of the address components for load and store microops.<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#include "arch/x86/insts/microldstop.hh"
#include <string>
namespace X86ISA
{
std::string LdStOp::generateDisassembly(Addr pc,
const SymbolTable *symtab) const
{
std::stringstream response;
bool someAddr = false;
printMnemonic(response, instMnem, mnemonic);
if(flags[IsLoad])
printDestReg(response, 0, dataSize);
else
printSrcReg(response, 2, dataSize);
response << ", ";
printSegment(response, segment);
response << ":[";
if(scale != 0 && _srcRegIdx[0] != ZeroReg)
{
if(scale != 1)
ccprintf(response, "%d*", scale);
printSrcReg(response, 0, addressSize);
someAddr = true;
}
if(_srcRegIdx[1] != ZeroReg)
{
if(someAddr)
response << " + ";
printSrcReg(response, 1, addressSize);
someAddr = true;
}
if(disp != 0)
{
if(someAddr)
response << " + ";
ccprintf(response, "%#x", disp);
someAddr = true;
}
if(!someAddr)
response << "0";
response << "]";
return response.str();
}
}
<|endoftext|> |
<commit_before>
#include <list>
#include <map>
#include <python2.7/Python.h>
#include <set>
#include "AnalysisProcessor.h"
#include "pin.H"
#define CB_BEFORE 0
#define CB_AFTER 1
extern AnalysisProcessor ap;
/* NameSapce for all Python Bindings variables */
namespace PyTritonOptions {
/* Debug configurations */
bool dumpStats = false;
bool dumpTrace = false;
/* Execution configurations */
char *startAnalysisFromSymbol = NULL;
std::set<uint64_t> startAnalysisFromAddr;
std::set<uint64_t> stopAnalysisFromAddr;
/* Callback configurations */
PyObject *callbackBefore = NULL; // Before the instruction processing
PyObject *callbackAfter = NULL; // After the instruction processing
/* Taint configurations */
std::map<uint64_t, std::list<uint64_t>> taintRegFromAddr; // <addr, [reg1, reg2]>
std::map<uint64_t, std::list<uint64_t>> untaintRegFromAddr; // <addr, [reg1, reg2]>
std::map<uint64_t, std::list<uint64_t>> taintMemFromAddr; // <addr, [mem1, mem2]>
std::map<uint64_t, std::list<uint64_t>> untaintMemFromAddr; // <addr, [mem1, mem2]>
};
static char Triton_addCallback_doc[] = "Add a callback for each instruction instrumented";
static PyObject *Triton_addCallback(PyObject *self, PyObject *args)
{
PyObject *function;
PyObject *flag;
/* Extract arguments */
PyArg_ParseTuple(args, "O|O", &function, &flag);
if (!PyCallable_Check(function)){
PyErr_Format(PyExc_TypeError, "addCallback(): expected a function callback as first argument");
PyErr_Print();
exit(-1);
}
/* Check if the second arg is CB_BEFORE or CB_AFTER */
if (!PyLong_Check(flag) && !PyInt_Check(flag)) {
PyErr_Format(PyExc_TypeError, "addCallback(): expected an integer as second argument");
PyErr_Print();
exit(-1);
}
if (PyLong_AsLong(flag) == CB_BEFORE)
PyTritonOptions::callbackBefore = function;
else if ((PyLong_AsLong(flag) == CB_AFTER))
PyTritonOptions::callbackAfter = function;
else {
PyErr_Format(PyExc_TypeError, "addCallback(): expected CB_BEFORE or CB_AFTER as second argument");
PyErr_Print();
exit(-1);
}
return Py_None;
}
static char Triton_dumpTrace_doc[] = "Dump the trace at the end of the execution";
static PyObject *Triton_dumpTrace(PyObject *self, PyObject *flag)
{
if (!PyBool_Check(flag)){
PyErr_Format(PyExc_TypeError, "dumpTrace(): expected a boolean");
PyErr_Print();
exit(-1);
}
PyTritonOptions::dumpTrace = (flag == Py_True);
return Py_None;
}
static char Triton_dumpStats_doc[] = "Dump statistics at the end of the execution";
static PyObject *Triton_dumpStats(PyObject *self, PyObject *flag)
{
if (!PyBool_Check(flag)){
PyErr_Format(PyExc_TypeError, "dumpStats(): expected a boolean");
PyErr_Print();
exit(-1);
}
PyTritonOptions::dumpStats = (flag == Py_True);
return Py_None;
}
static char Triton_isMemTainted_doc[] = "Check if the memory is tainted";
static PyObject *Triton_isMemTainted(PyObject *self, PyObject *mem)
{
if (!PyLong_Check(mem) && !PyInt_Check(mem)){
PyErr_Format(PyExc_TypeError, "isMemTainted(): expected an address (integer) as argument");
PyErr_Print();
exit(-1);
}
if (ap.isMemTainted(PyInt_AsLong(mem)) == true)
return Py_True;
return Py_False;
}
static char Triton_isRegTainted_doc[] = "Check if the register is tainted";
static PyObject *Triton_isRegTainted(PyObject *self, PyObject *reg)
{
if (!PyLong_Check(reg) && !PyInt_Check(reg)){
PyErr_Format(PyExc_TypeError, "isRegTainted(): expected a reg (integer) as argument");
PyErr_Print();
exit(-1);
}
if (ap.isRegTainted(PyInt_AsLong(reg)) == true)
return Py_True;
return Py_False;
}
static char Triton_opcodeToString_doc[] = "Returns a string with the opcode of the instruction";
static PyObject *Triton_opcodeToString(PyObject *self, PyObject *opcode)
{
if (!PyLong_Check(opcode) && !PyInt_Check(opcode)){
PyErr_Format(PyExc_TypeError, "opcodeToString(): expected an opcode (integer) as argument");
PyErr_Print();
exit(-1);
}
return Py_BuildValue("s", OPCODE_StringShort(PyInt_AsLong(opcode)).c_str());
}
static char Triton_runProgram_doc[] = "Start the Pin instrumentation";
static PyObject *Triton_runProgram(PyObject *self, PyObject *noarg)
{
// Never returns - Rock 'n roll baby \o/
PIN_StartProgram();
return Py_None;
}
static char Triton_startAnalysisFromSymbol_doc[] = "Start the symbolic execution from a specific name point";
static PyObject *Triton_startAnalysisFromSymbol(PyObject *self, PyObject *name)
{
if (!PyString_Check(name)){
PyErr_Format(PyExc_TypeError, "startAnalysisFromSymbol(): expected a string as argument");
PyErr_Print();
exit(-1);
}
PyTritonOptions::startAnalysisFromSymbol = PyString_AsString(name);
return Py_None;
}
static char Triton_startAnalysisFromAddr_doc[] = "Start the symbolic execution from a specific address";
static PyObject *Triton_startAnalysisFromAddr(PyObject *self, PyObject *addr)
{
if (!PyLong_Check(addr) && !PyInt_Check(addr)){
PyErr_Format(PyExc_TypeError, "startAnalysisFromAddr(): expected an address as argument");
PyErr_Print();
exit(-1);
}
PyTritonOptions::startAnalysisFromAddr.insert(PyLong_AsLong(addr));
return Py_None;
}
static char Triton_stopAnalysisFromAddr_doc[] = "Stop the symbolic execution from a specific address";
static PyObject *Triton_stopAnalysisFromAddr(PyObject *self, PyObject *addr)
{
if (!PyLong_Check(addr) && !PyInt_Check(addr)){
PyErr_Format(PyExc_TypeError, "stopAnalysisFromAddr(): expected an address");
PyErr_Print();
exit(-1);
}
PyTritonOptions::stopAnalysisFromAddr.insert(PyLong_AsLong(addr));
return Py_None;
}
static char Triton_taintRegFromAddr_doc[] = "Taint specific registers from an address";
static PyObject *Triton_taintRegFromAddr(PyObject *self, PyObject *args)
{
PyObject *addr;
PyObject *regs;
std::list<uint64_t> regsList;
/* Extract arguments */
PyArg_ParseTuple(args, "O|O", &addr, ®s);
/* Check if the first arg (addr) is a integer */
if (!PyLong_Check(addr) && !PyInt_Check(addr)) {
PyErr_Format(PyExc_TypeError, "taintRegFromAddr(): expected an address as first argument");
PyErr_Print();
exit(-1);
}
/* Check if the second arg (regs) is a list */
if (!PyList_Check(regs)) {
PyErr_Format(PyExc_TypeError, "taintRegFromAddr(): expected a list as second argument");
PyErr_Print();
exit(-1);
}
/* Check if the regs list contains only integer item and craft a std::list */
for (Py_ssize_t i = 0; i < PyList_Size(regs); i++){
PyObject *item = PyList_GetItem(regs, i);
if (!PyLong_Check(item) && !PyInt_Check(item)){
PyErr_Format(PyExc_TypeError, "taintRegFromAddr(): The second argument must be a list of integer");
PyErr_Print();
exit(-1);
}
regsList.push_back(PyLong_AsLong(item));
}
/* Update taint configuration */
PyTritonOptions::taintRegFromAddr.insert(std::pair<uint64_t, std::list<uint64_t>>(PyLong_AsLong(addr), regsList));
return Py_None;
}
static char Triton_untaintRegFromAddr_doc[] = "Untaint specific registers from an address";
static PyObject *Triton_untaintRegFromAddr(PyObject *self, PyObject *args)
{
PyObject *addr;
PyObject *regs;
std::list<uint64_t> regsList;
/* Extract arguments */
PyArg_ParseTuple(args, "O|O", &addr, ®s);
/* Check if the first arg (addr) is a integer */
if (!PyLong_Check(addr) && !PyInt_Check(addr)) {
PyErr_Format(PyExc_TypeError, "untaintRegFromAddr(): expected an address as first argument");
PyErr_Print();
exit(-1);
}
/* Check if the second arg (regs) is a list */
if (!PyList_Check(regs)) {
PyErr_Format(PyExc_TypeError, "untaintRegFromAddr(): expected a list as second argument");
PyErr_Print();
exit(-1);
}
/* Check if the regs list contains only integer item and craft a std::list */
for (Py_ssize_t i = 0; i < PyList_Size(regs); i++){
PyObject *item = PyList_GetItem(regs, i);
if (!PyLong_Check(item) && !PyInt_Check(item)){
PyErr_Format(PyExc_TypeError, "untaintRegFromAddr(): The second argument must be a list of integer");
PyErr_Print();
exit(-1);
}
regsList.push_back(PyLong_AsLong(item));
}
/* Update taint configuration */
PyTritonOptions::untaintRegFromAddr.insert(std::pair<uint64_t, std::list<uint64_t>>(PyLong_AsLong(addr), regsList));
return Py_None;
}
PyMethodDef pythonCallbacks[] = {
{"addCallback", Triton_addCallback, METH_VARARGS, Triton_addCallback_doc},
{"dumpStats", Triton_dumpStats, METH_O, Triton_dumpStats_doc},
{"dumpTrace", Triton_dumpTrace, METH_O, Triton_dumpTrace_doc},
{"isMemTainted", Triton_isMemTainted, METH_O, Triton_isMemTainted_doc},
{"isRegTainted", Triton_isRegTainted, METH_O, Triton_isRegTainted_doc},
{"opcodeToString", Triton_opcodeToString, METH_O, Triton_opcodeToString_doc},
{"runProgram", Triton_runProgram, METH_NOARGS, Triton_runProgram_doc},
{"startAnalysisFromAddr", Triton_startAnalysisFromAddr, METH_O, Triton_startAnalysisFromAddr_doc},
{"startAnalysisFromSymbol", Triton_startAnalysisFromSymbol, METH_O, Triton_startAnalysisFromSymbol_doc},
{"stopAnalysisFromAddr", Triton_stopAnalysisFromAddr, METH_O, Triton_stopAnalysisFromAddr_doc},
{"taintRegFromAddr", Triton_taintRegFromAddr, METH_VARARGS, Triton_taintRegFromAddr_doc},
{"untaintRegFromAddr", Triton_untaintRegFromAddr, METH_VARARGS, Triton_untaintRegFromAddr_doc},
{NULL, NULL, 0, NULL}
};
<commit_msg>Export taintReg() and untaintReg() into Python bindings<commit_after>
#include <list>
#include <map>
#include <python2.7/Python.h>
#include <set>
#include "AnalysisProcessor.h"
#include "pin.H"
#define CB_BEFORE 0
#define CB_AFTER 1
extern AnalysisProcessor ap;
/* NameSapce for all Python Bindings variables */
namespace PyTritonOptions {
/* Debug configurations */
bool dumpStats = false;
bool dumpTrace = false;
/* Execution configurations */
char *startAnalysisFromSymbol = NULL;
std::set<uint64_t> startAnalysisFromAddr;
std::set<uint64_t> stopAnalysisFromAddr;
/* Callback configurations */
PyObject *callbackBefore = NULL; // Before the instruction processing
PyObject *callbackAfter = NULL; // After the instruction processing
/* Taint configurations */
std::map<uint64_t, std::list<uint64_t>> taintRegFromAddr; // <addr, [reg1, reg2]>
std::map<uint64_t, std::list<uint64_t>> untaintRegFromAddr; // <addr, [reg1, reg2]>
std::map<uint64_t, std::list<uint64_t>> taintMemFromAddr; // <addr, [mem1, mem2]>
std::map<uint64_t, std::list<uint64_t>> untaintMemFromAddr; // <addr, [mem1, mem2]>
};
static char Triton_addCallback_doc[] = "Add a callback for each instruction instrumented";
static PyObject *Triton_addCallback(PyObject *self, PyObject *args)
{
PyObject *function;
PyObject *flag;
/* Extract arguments */
PyArg_ParseTuple(args, "O|O", &function, &flag);
if (!PyCallable_Check(function)){
PyErr_Format(PyExc_TypeError, "addCallback(): expected a function callback as first argument");
PyErr_Print();
exit(-1);
}
/* Check if the second arg is CB_BEFORE or CB_AFTER */
if (!PyLong_Check(flag) && !PyInt_Check(flag)) {
PyErr_Format(PyExc_TypeError, "addCallback(): expected an integer as second argument");
PyErr_Print();
exit(-1);
}
if (PyLong_AsLong(flag) == CB_BEFORE)
PyTritonOptions::callbackBefore = function;
else if ((PyLong_AsLong(flag) == CB_AFTER))
PyTritonOptions::callbackAfter = function;
else {
PyErr_Format(PyExc_TypeError, "addCallback(): expected CB_BEFORE or CB_AFTER as second argument");
PyErr_Print();
exit(-1);
}
return Py_None;
}
static char Triton_dumpTrace_doc[] = "Dump the trace at the end of the execution";
static PyObject *Triton_dumpTrace(PyObject *self, PyObject *flag)
{
if (!PyBool_Check(flag)){
PyErr_Format(PyExc_TypeError, "dumpTrace(): expected a boolean");
PyErr_Print();
exit(-1);
}
PyTritonOptions::dumpTrace = (flag == Py_True);
return Py_None;
}
static char Triton_dumpStats_doc[] = "Dump statistics at the end of the execution";
static PyObject *Triton_dumpStats(PyObject *self, PyObject *flag)
{
if (!PyBool_Check(flag)){
PyErr_Format(PyExc_TypeError, "dumpStats(): expected a boolean");
PyErr_Print();
exit(-1);
}
PyTritonOptions::dumpStats = (flag == Py_True);
return Py_None;
}
static char Triton_isMemTainted_doc[] = "Check if the memory is tainted";
static PyObject *Triton_isMemTainted(PyObject *self, PyObject *mem)
{
if (!PyLong_Check(mem) && !PyInt_Check(mem)){
PyErr_Format(PyExc_TypeError, "isMemTainted(): expected an address (integer) as argument");
PyErr_Print();
exit(-1);
}
if (ap.isMemTainted(PyInt_AsLong(mem)) == true)
return Py_True;
return Py_False;
}
static char Triton_isRegTainted_doc[] = "Check if the register is tainted";
static PyObject *Triton_isRegTainted(PyObject *self, PyObject *reg)
{
if (!PyLong_Check(reg) && !PyInt_Check(reg)){
PyErr_Format(PyExc_TypeError, "isRegTainted(): expected a reg id (integer) as argument");
PyErr_Print();
exit(-1);
}
if (ap.isRegTainted(PyInt_AsLong(reg)) == true)
return Py_True;
return Py_False;
}
static char Triton_opcodeToString_doc[] = "Returns a string with the opcode of the instruction";
static PyObject *Triton_opcodeToString(PyObject *self, PyObject *opcode)
{
if (!PyLong_Check(opcode) && !PyInt_Check(opcode)){
PyErr_Format(PyExc_TypeError, "opcodeToString(): expected an opcode (integer) as argument");
PyErr_Print();
exit(-1);
}
return Py_BuildValue("s", OPCODE_StringShort(PyInt_AsLong(opcode)).c_str());
}
static char Triton_runProgram_doc[] = "Start the Pin instrumentation";
static PyObject *Triton_runProgram(PyObject *self, PyObject *noarg)
{
// Never returns - Rock 'n roll baby \o/
PIN_StartProgram();
return Py_None;
}
static char Triton_startAnalysisFromSymbol_doc[] = "Start the symbolic execution from a specific name point";
static PyObject *Triton_startAnalysisFromSymbol(PyObject *self, PyObject *name)
{
if (!PyString_Check(name)){
PyErr_Format(PyExc_TypeError, "startAnalysisFromSymbol(): expected a string as argument");
PyErr_Print();
exit(-1);
}
PyTritonOptions::startAnalysisFromSymbol = PyString_AsString(name);
return Py_None;
}
static char Triton_startAnalysisFromAddr_doc[] = "Start the symbolic execution from a specific address";
static PyObject *Triton_startAnalysisFromAddr(PyObject *self, PyObject *addr)
{
if (!PyLong_Check(addr) && !PyInt_Check(addr)){
PyErr_Format(PyExc_TypeError, "startAnalysisFromAddr(): expected an address as argument");
PyErr_Print();
exit(-1);
}
PyTritonOptions::startAnalysisFromAddr.insert(PyLong_AsLong(addr));
return Py_None;
}
static char Triton_stopAnalysisFromAddr_doc[] = "Stop the symbolic execution from a specific address";
static PyObject *Triton_stopAnalysisFromAddr(PyObject *self, PyObject *addr)
{
if (!PyLong_Check(addr) && !PyInt_Check(addr)){
PyErr_Format(PyExc_TypeError, "stopAnalysisFromAddr(): expected an address");
PyErr_Print();
exit(-1);
}
PyTritonOptions::stopAnalysisFromAddr.insert(PyLong_AsLong(addr));
return Py_None;
}
static char Triton_taintReg_doc[] = "Taint a register";
static PyObject *Triton_taintReg(PyObject *self, PyObject *reg)
{
if (!PyLong_Check(reg) && !PyInt_Check(reg)){
PyErr_Format(PyExc_TypeError, "taintReg(): expected a reg id (integer) as argument");
PyErr_Print();
exit(-1);
}
ap.taintReg(PyInt_AsLong(reg));
return Py_None;
}
static char Triton_taintRegFromAddr_doc[] = "Taint specific registers from an address";
static PyObject *Triton_taintRegFromAddr(PyObject *self, PyObject *args)
{
PyObject *addr;
PyObject *regs;
std::list<uint64_t> regsList;
/* Extract arguments */
PyArg_ParseTuple(args, "O|O", &addr, ®s);
/* Check if the first arg (addr) is a integer */
if (!PyLong_Check(addr) && !PyInt_Check(addr)) {
PyErr_Format(PyExc_TypeError, "taintRegFromAddr(): expected an address as first argument");
PyErr_Print();
exit(-1);
}
/* Check if the second arg (regs) is a list */
if (!PyList_Check(regs)) {
PyErr_Format(PyExc_TypeError, "taintRegFromAddr(): expected a list as second argument");
PyErr_Print();
exit(-1);
}
/* Check if the regs list contains only integer item and craft a std::list */
for (Py_ssize_t i = 0; i < PyList_Size(regs); i++){
PyObject *item = PyList_GetItem(regs, i);
if (!PyLong_Check(item) && !PyInt_Check(item)){
PyErr_Format(PyExc_TypeError, "taintRegFromAddr(): The second argument must be a list of reg id (integer)");
PyErr_Print();
exit(-1);
}
regsList.push_back(PyLong_AsLong(item));
}
/* Update taint configuration */
PyTritonOptions::taintRegFromAddr.insert(std::pair<uint64_t, std::list<uint64_t>>(PyLong_AsLong(addr), regsList));
return Py_None;
}
static char Triton_untaintReg_doc[] = "Untaint a register";
static PyObject *Triton_untaintReg(PyObject *self, PyObject *reg)
{
if (!PyLong_Check(reg) && !PyInt_Check(reg)){
PyErr_Format(PyExc_TypeError, "untaintReg(): expected a reg id (integer) as argument");
PyErr_Print();
exit(-1);
}
ap.untaintReg(PyInt_AsLong(reg));
return Py_None;
}
static char Triton_untaintRegFromAddr_doc[] = "Untaint specific registers from an address";
static PyObject *Triton_untaintRegFromAddr(PyObject *self, PyObject *args)
{
PyObject *addr;
PyObject *regs;
std::list<uint64_t> regsList;
/* Extract arguments */
PyArg_ParseTuple(args, "O|O", &addr, ®s);
/* Check if the first arg (addr) is a integer */
if (!PyLong_Check(addr) && !PyInt_Check(addr)) {
PyErr_Format(PyExc_TypeError, "untaintRegFromAddr(): expected an address as first argument");
PyErr_Print();
exit(-1);
}
/* Check if the second arg (regs) is a list */
if (!PyList_Check(regs)) {
PyErr_Format(PyExc_TypeError, "untaintRegFromAddr(): expected a list as second argument");
PyErr_Print();
exit(-1);
}
/* Check if the regs list contains only integer item and craft a std::list */
for (Py_ssize_t i = 0; i < PyList_Size(regs); i++){
PyObject *item = PyList_GetItem(regs, i);
if (!PyLong_Check(item) && !PyInt_Check(item)){
PyErr_Format(PyExc_TypeError, "untaintRegFromAddr(): The second argument must be a list of reg id (integer)");
PyErr_Print();
exit(-1);
}
regsList.push_back(PyLong_AsLong(item));
}
/* Update taint configuration */
PyTritonOptions::untaintRegFromAddr.insert(std::pair<uint64_t, std::list<uint64_t>>(PyLong_AsLong(addr), regsList));
return Py_None;
}
PyMethodDef pythonCallbacks[] = {
{"addCallback", Triton_addCallback, METH_VARARGS, Triton_addCallback_doc},
{"dumpStats", Triton_dumpStats, METH_O, Triton_dumpStats_doc},
{"dumpTrace", Triton_dumpTrace, METH_O, Triton_dumpTrace_doc},
{"isMemTainted", Triton_isMemTainted, METH_O, Triton_isMemTainted_doc},
{"isRegTainted", Triton_isRegTainted, METH_O, Triton_isRegTainted_doc},
{"opcodeToString", Triton_opcodeToString, METH_O, Triton_opcodeToString_doc},
{"runProgram", Triton_runProgram, METH_NOARGS, Triton_runProgram_doc},
{"startAnalysisFromAddr", Triton_startAnalysisFromAddr, METH_O, Triton_startAnalysisFromAddr_doc},
{"startAnalysisFromSymbol", Triton_startAnalysisFromSymbol, METH_O, Triton_startAnalysisFromSymbol_doc},
{"stopAnalysisFromAddr", Triton_stopAnalysisFromAddr, METH_O, Triton_stopAnalysisFromAddr_doc},
{"taintReg", Triton_taintReg, METH_O, Triton_taintReg_doc},
{"taintRegFromAddr", Triton_taintRegFromAddr, METH_VARARGS, Triton_taintRegFromAddr_doc},
{"untaintReg", Triton_untaintReg, METH_O, Triton_untaintReg_doc},
{"untaintRegFromAddr", Triton_untaintRegFromAddr, METH_VARARGS, Triton_untaintRegFromAddr_doc},
{NULL, NULL, 0, NULL}
};
<|endoftext|> |
<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP
#define IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP
#include <cstdint>
#include <sys/shm.h>
namespace iox
{
namespace posix
{
class UnixDomainSocket;
}
namespace platform
{
constexpr uint64_t IOX_MAX_FILENAME_LENGTH = 255U;
constexpr uint64_t IOX_MAX_PATH_LENGTH = 1023U;
constexpr bool IOX_SHM_WRITE_ZEROS_ON_CREATION = true;
constexpr uint64_t IOX_MAX_SHM_NAME_LENGTH = SHM_NAME_MAX;
constexpr const char IOX_PATH_SEPARATORS[] = "/";
constexpr uint64_t IOX_UDS_SOCKET_MAX_MESSAGE_SIZE = 2048;
constexpr const char IOX_UDS_SOCKET_PATH_PREFIX[] = "/tmp/";
constexpr const char IOX_LOCK_FILE_PATH_PREFIX[] = "/tmp/";
using IoxIpcChannelType = iox::posix::UnixDomainSocket;
} // namespace platform
} // namespace iox
#endif // IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP
<commit_msg>iox-#33 Use MAX_SHM_NAME_LENGTH value from windows in mac<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP
#define IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP
#include <cstdint>
namespace iox
{
namespace posix
{
class UnixDomainSocket;
}
namespace platform
{
constexpr uint64_t IOX_MAX_FILENAME_LENGTH = 255U;
constexpr uint64_t IOX_MAX_PATH_LENGTH = 1023U;
constexpr bool IOX_SHM_WRITE_ZEROS_ON_CREATION = true;
// it should be SHM_NAME_MAX but it is unknown in which header this define
// is defined
constexpr uint64_t IOX_MAX_SHM_NAME_LENGTH = 255U;
constexpr const char IOX_PATH_SEPARATORS[] = "/";
constexpr uint64_t IOX_UDS_SOCKET_MAX_MESSAGE_SIZE = 2048;
constexpr const char IOX_UDS_SOCKET_PATH_PREFIX[] = "/tmp/";
constexpr const char IOX_LOCK_FILE_PATH_PREFIX[] = "/tmp/";
using IoxIpcChannelType = iox::posix::UnixDomainSocket;
} // namespace platform
} // namespace iox
#endif // IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/memTracker.h"
MemTracker::MemTracker(bool useMemTracking) {
tracking = useMemTracking;
}
MemTracker::~MemTracker() {}
// Add alloc informations to the list.
void MemTracker::addTrack(DWORD addr, DWORD asize, const char *fname, DWORD lnum) {
AllocInfo info;
strncpy(info.file, fname, MAX_LENGHT_FILE-1);
info.address = addr;
info.line = lnum;
info.size = asize;
allocList.add(info);
}
// Remove alloc informations from the list by the given address.
void MemTracker::removeTrack(DWORD addr) {
int size = allocList.size();
if (!size)
return;
if ( addr == ((AllocInfo*)allocList.front())->address ) {
allocList.remove(0);
return;
}
else {
int i;
for (i=1; i<size; i++) {
if ( addr == ((AllocInfo*)allocList.next())->address ) {
allocList.remove(i);
break;
}
}
}
}
// To print final results of memory allocations.
void MemTracker::dumpUnfreed() {
DWORD totalSize = 0;
AllocInfo *info;
int i;
disableMemTracker();
int size = allocList.size();
LOG.debug("-------------------- MEMORY LEAKS: ------------------------");
LOG.debug("-----------------------------------------------------------");
LOG.debug("%d leaks found!", size);
info = (AllocInfo*)allocList.front();
LOG.debug("addr: %lx - size:%3ld, file: %s:%d", info->address, info->size, info->file, info->line);
for(i=1; i<size; i++) {
info = (AllocInfo*)allocList.next();
LOG.debug("addr: %lx - size:%3ld, file: %s:%d", info->address, info->size, info->file, info->line);
totalSize += info->size;
}
LOG.debug("Total Unfreed: %d bytes", totalSize);
LOG.debug("-----------------------------------------------------------\n");
allocList.clear();
}
//
// Functions to enable/disable tracking of memory leaks.
// Note: need to disable trackers when calling add/removeTracker
// to avoid loops into new/delete operators!
//
void MemTracker::enableMemTracker() {
tracking = TRUE;
}
void MemTracker::disableMemTracker() {
tracking = FALSE;
}
// Are we tracking memory leaks?
bool MemTracker::isMemTracking() {
return tracking;
}
// -------------------------------------------------
// not used
ArrayElement* AllocInfo::clone() {
AllocInfo* ret = new AllocInfo();
ret->address = address;
ret->size = size;
ret->line = line;
strncpy(ret->file, file, MAX_LENGHT_FILE-1);
return ret;
}
<commit_msg>correction to MemTracker<commit_after>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/memTracker.h"
MemTracker::MemTracker(bool useMemTracking) {
tracking = useMemTracking;
}
MemTracker::~MemTracker() {}
// Add alloc informations to the list.
void MemTracker::addTrack(DWORD addr, DWORD asize, const char *fname, DWORD lnum) {
AllocInfo info;
strncpy(info.file, fname, MAX_LENGHT_FILE-1);
info.address = addr;
info.line = lnum;
info.size = asize;
allocList.add(info);
}
// Remove alloc informations from the list by the given address.
void MemTracker::removeTrack(DWORD addr) {
int size = allocList.size();
if (!size)
return;
if ( addr == ((AllocInfo*)allocList.front())->address ) {
allocList.remove(0);
return;
}
else {
int i;
for (i=1; i<size; i++) {
if ( addr == ((AllocInfo*)allocList.next())->address ) {
allocList.remove(i);
break;
}
}
}
}
// To print final results of memory allocations.
void MemTracker::dumpUnfreed() {
DWORD totalSize = 0;
AllocInfo *info;
int i;
disableMemTracker();
int size = allocList.size();
LOG.debug("-------------------- MEMORY LEAKS: ------------------------");
LOG.debug("-----------------------------------------------------------");
LOG.debug("%d leaks found!", size);
info = (AllocInfo*)allocList.front();
LOG.debug("addr: %lx - size:%3ld, file: %s:%d", info->address, info->size, info->file, info->line);
totalSize += info->size;
for(i=1; i<size; i++) {
info = (AllocInfo*)allocList.next();
LOG.debug("addr: %lx - size:%3ld, file: %s:%d", info->address, info->size, info->file, info->line);
totalSize += info->size;
}
LOG.debug("Total Unfreed: %d bytes", totalSize);
LOG.debug("-----------------------------------------------------------\n");
allocList.clear();
}
//
// Functions to enable/disable tracking of memory leaks.
// Note: need to disable trackers when calling add/removeTracker
// to avoid loops into new/delete operators!
//
void MemTracker::enableMemTracker() {
tracking = TRUE;
}
void MemTracker::disableMemTracker() {
tracking = FALSE;
}
// Are we tracking memory leaks?
bool MemTracker::isMemTracking() {
return tracking;
}
// -------------------------------------------------
// not used
ArrayElement* AllocInfo::clone() {
AllocInfo* ret = new AllocInfo();
ret->address = address;
ret->size = size;
ret->line = line;
strncpy(ret->file, file, MAX_LENGHT_FILE-1);
return ret;
}
<|endoftext|> |
<commit_before>/*
* This file is part of the µOS++ distribution.
* (https://github.com/micro-os-plus)
* Copyright (c) 2016 Liviu Ionescu.
*
* µOS++ is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 3.
*
* µOS++ 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 program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmsis-plus/rtos/os.h>
#include <cmsis-plus/diag/trace.h>
#include <cmsis-plus/rtos/port/os-decls.h>
#include <cmsis-plus/rtos/port/os-inlines.h>
// ----------------------------------------------------------------------------
#include <cassert>
#include <cerrno>
#include <cstdlib>
// ----------------------------------------------------------------------------
namespace os
{
namespace rtos
{
static Systick_clock::rep __systick_now;
static Realtime_clock::rep __rtc_now;
} /* namespace rtos */
} /* namespace os */
// ----------------------------------------------------------------------------
void
os_systick_handler (void)
{
using namespace os::rtos;
// Prevent scheduler actions before starting it.
if (scheduler::started ())
{
os_impl_systick_handler ();
}
__systick_now++;
#if !defined(OS_INCLUDE_REALTIME_CLOCK_DRIVER)
static uint32_t ticks = Systick_clock::frequency_hz;
if (--ticks == 0)
{
ticks = Systick_clock::frequency_hz;
os_rtc_handler ();
}
#endif
}
void
os_rtc_handler (void)
{
using namespace os::rtos;
// Prevent scheduler actions before starting it.
if (scheduler::started ())
{
os_impl_rtc_handler ();
}
++__rtc_now;
}
void __attribute__((weak))
os_impl_systick_handler (void)
{
// TODO
}
void __attribute__((weak))
os_impl_rtc_handler (void)
{
// TODO
}
// ----------------------------------------------------------------------------
namespace os
{
namespace rtos
{
#pragma GCC diagnostic push
// TODO: remove it when fully implemented
//#pragma GCC diagnostic ignored "-Wunused-parameter"
// ======================================================================
/**
* @details
*
* @note Can be invoked from Interrupt Service Routines.
*/
Systick_clock::rep
Systick_clock::now (void)
{
Critical_section_irq cs; // ---- Critical section -----
// Prevent inconsistent values using the critical section.
return __systick_now;
}
/**
* @details
* Return the very accurate current time, using the internal
* SysTick cycle counter, which, at 100 MHz and 1000 ticks/sec
* allows a 10 ns resolution.
*
* The function adjust for border conditions, when the SysTick
* counter is reloaded during the call.
*
* @note Can be invoked from Interrupt Service Routines.
*/
Systick_clock::rep
Systick_clock::now (current_t* details)
{
assert(details != nullptr);
// The core frequency can be returned right away, since
// is not expected to change during this call.
details->core_frequency_hz = SystemCoreClock;
// The timer reload value, it is the divisor - 1.
uint32_t load = SysTick->LOAD;
// Can also be returned right away.
details->divisor = load + 1;
// The ticks and cycles must be read atomically, use a critical
// section and adjust for border condition, when the event
// came exactly after entering the critical section.
uint64_t ticks;
uint32_t val;
{
Critical_section_irq cs; // ----- Critical section -----
// Sample ticks counter inside critical section.
ticks = __systick_now;
// Initial sample of the decrementing counter.
// Might happen before the event, will be used as such.
val = SysTick->VAL;
// Check overflow. If the exception is pending, it means the
// ticks counter was not yet updated, but the counter was reloaded.
if (SysTick->CTRL & SCB_ICSR_PENDSTSET_Msk)
{
// Sample the decrementing counter again to validate the
// initial sample.
uint32_t val_update = SysTick->VAL;
if (val_update > val)
{
// The second sample is more accurate.
val = val_update;
}
ticks++; // Adjust to next tick.
}
}
details->cycles = load - val;
details->ticks = ticks;
return ticks;
}
/**
* @details
* Put the current thread to sleep, until the next n-th
* SysTick occurs. Depending when the call is issued, the
* first tick counted may be very short.
*
* @warning Cannot be invoked from Interrupt Service Routines.
*/
result_t
Systick_clock::sleep_for (Systick_clock::sleep_rep ticks)
{
os_assert_err(!scheduler::in_handler_mode (), EPERM);
trace::printf ("Systick_clock::sleep_for(%d_ticks)\n", ticks);
#if defined(OS_INCLUDE_PORT_RTOS_SYSTICK_CLOCK_SLEEP_FOR)
return port::Systick_clock::sleep_for (ticks);
#else
// TODO
return result::ok;
#endif
}
/**
* @details
*
* @note Can be invoked from Interrupt Service Routines.
*/
Realtime_clock::rep
Realtime_clock::now (void)
{
return __rtc_now;
}
/**
* @details
* Put the current thread to sleep, until the next n-th
* RTC second occurs. Depending when the call is issued, the
* first second counted may be very short.
*
* @warning Cannot be invoked from Interrupt Service Routines.
*/
result_t
Realtime_clock::sleep_for (Realtime_clock::sleep_rep secs)
{
os_assert_err(!scheduler::in_handler_mode (), EPERM);
trace::printf ("Realtime_clock::sleep_for(%ds)\n", secs);
// TODO
__rtc_now += secs;
return result::ok;
}
#pragma GCC diagnostic pop
} /* namespace rtos */
} /* namespace os */
<commit_msg>os-clocks: add RTC:initialize()<commit_after>/*
* This file is part of the µOS++ distribution.
* (https://github.com/micro-os-plus)
* Copyright (c) 2016 Liviu Ionescu.
*
* µOS++ is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 3.
*
* µOS++ 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 program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmsis-plus/rtos/os.h>
#include <cmsis-plus/diag/trace.h>
#include <cmsis-plus/rtos/port/os-decls.h>
#include <cmsis-plus/rtos/port/os-inlines.h>
// ----------------------------------------------------------------------------
#include <cassert>
#include <cerrno>
#include <cstdlib>
// ----------------------------------------------------------------------------
namespace os
{
namespace rtos
{
static Systick_clock::rep __systick_now;
static Realtime_clock::rep __rtc_now;
} /* namespace rtos */
} /* namespace os */
// ----------------------------------------------------------------------------
void
os_systick_handler (void)
{
using namespace os::rtos;
// Prevent scheduler actions before starting it.
if (scheduler::started ())
{
os_impl_systick_handler ();
}
__systick_now++;
#if !defined(OS_INCLUDE_REALTIME_CLOCK_DRIVER)
static uint32_t ticks = Systick_clock::frequency_hz;
if (--ticks == 0)
{
ticks = Systick_clock::frequency_hz;
os_rtc_handler ();
}
#endif
}
void
os_rtc_handler (void)
{
using namespace os::rtos;
// Prevent scheduler actions before starting it.
if (scheduler::started ())
{
os_impl_rtc_handler ();
}
++__rtc_now;
}
void __attribute__((weak))
os_impl_systick_handler (void)
{
// TODO
}
void __attribute__((weak))
os_impl_rtc_handler (void)
{
// TODO
}
// ----------------------------------------------------------------------------
namespace os
{
namespace rtos
{
#pragma GCC diagnostic push
// TODO: remove it when fully implemented
//#pragma GCC diagnostic ignored "-Wunused-parameter"
// ======================================================================
/**
* @details
*
* @note Can be invoked from Interrupt Service Routines.
*/
Systick_clock::rep
Systick_clock::now (void)
{
Critical_section_irq cs; // ---- Critical section -----
// Prevent inconsistent values using the critical section.
return __systick_now;
}
/**
* @details
* Return the very accurate current time, using the internal
* SysTick cycle counter, which, at 100 MHz and 1000 ticks/sec
* allows a 10 ns resolution.
*
* The function adjust for border conditions, when the SysTick
* counter is reloaded during the call.
*
* @note Can be invoked from Interrupt Service Routines.
*/
Systick_clock::rep
Systick_clock::now (current_t* details)
{
assert(details != nullptr);
// The core frequency can be returned right away, since
// is not expected to change during this call.
details->core_frequency_hz = SystemCoreClock;
// The timer reload value, it is the divisor - 1.
uint32_t load = SysTick->LOAD;
// Can also be returned right away.
details->divisor = load + 1;
// The ticks and cycles must be read atomically, use a critical
// section and adjust for border condition, when the event
// came exactly after entering the critical section.
uint64_t ticks;
uint32_t val;
{
Critical_section_irq cs; // ----- Critical section -----
// Sample ticks counter inside critical section.
ticks = __systick_now;
// Initial sample of the decrementing counter.
// Might happen before the event, will be used as such.
val = SysTick->VAL;
// Check overflow. If the exception is pending, it means the
// ticks counter was not yet updated, but the counter was reloaded.
if (SysTick->CTRL & SCB_ICSR_PENDSTSET_Msk)
{
// Sample the decrementing counter again to validate the
// initial sample.
uint32_t val_update = SysTick->VAL;
if (val_update > val)
{
// The second sample is more accurate.
val = val_update;
}
ticks++; // Adjust to next tick.
}
}
details->cycles = load - val;
details->ticks = ticks;
return ticks;
}
/**
* @details
* Put the current thread to sleep, until the next n-th
* SysTick occurs. Depending when the call is issued, the
* first tick counted may be very short.
*
* @warning Cannot be invoked from Interrupt Service Routines.
*/
result_t
Systick_clock::sleep_for (Systick_clock::sleep_rep ticks)
{
os_assert_err(!scheduler::in_handler_mode (), EPERM);
trace::printf ("Systick_clock::sleep_for(%d_ticks)\n", ticks);
#if defined(OS_INCLUDE_PORT_RTOS_SYSTICK_CLOCK_SLEEP_FOR)
return port::Systick_clock::sleep_for (ticks);
#else
// TODO
return result::ok;
#endif
}
/**
* @details
* Must be called only once, during inits.
*
* @warning Cannot be invoked from Interrupt Service Routines.
*/
result_t
Realtime_clock::initialize (void)
{
os_assert_err(!scheduler::in_handler_mode (), EPERM);
// TODO: Use the RTC driver to initialise the seconds to epoch.
return result::ok;
}
/**
* @details
*
* @note Can be invoked from Interrupt Service Routines.
*/
Realtime_clock::rep
Realtime_clock::now (void)
{
return __rtc_now;
}
/**
* @details
* Put the current thread to sleep, until the next n-th
* RTC second occurs. Depending when the call is issued, the
* first second counted may be very short.
*
* @warning Cannot be invoked from Interrupt Service Routines.
*/
result_t
Realtime_clock::sleep_for (Realtime_clock::sleep_rep secs)
{
os_assert_err(!scheduler::in_handler_mode (), EPERM);
trace::printf ("Realtime_clock::sleep_for(%ds)\n", secs);
// TODO
__rtc_now += secs;
return result::ok;
}
#pragma GCC diagnostic pop
} /* namespace rtos */
} /* namespace os */
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <Halide.h>
using namespace Halide;
int main(int argc, char **argv) {
Var x, y;
Func pred("pred");
pred(x, y) = x < y;
Func selector("selector");
selector(x, y) = select(pred(x, y), 1, 0);
// Load a vector of 8 bools
pred.compute_root();
selector.compute_root().vectorize(x, 8);
RDom range(0, 100, 0, 100);
int32_t result = evaluate<int32_t>(lambda(sum(selector(range.x, range.y))));
assert(result == 4950);
printf("Success!\n");
return 0;
}
<commit_msg>Had this under two names. Delete the less descriptive one.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, Oculus VR, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
// ----------------------------------------------------------------------
// RakNet version 1.0
// Filename Ping.cpp
// Very basic chat engine example
// ----------------------------------------------------------------------
#include "MessageIdentifiers.h"
#include "RakPeerInterface.h"
#include "RakPeerInterface.h"
#include "RakNetTypes.h"
#include "GetTime.h"
#include "BitStream.h"
#include <assert.h>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include "Gets.h"
#ifdef WIN32
#include "Kbhit.h"
#else
#include "Kbhit.h"
#endif
int main(void)
{
// Pointers to the interfaces of our server and client.
// Note we can easily have both in the same program
RakNet::RakPeerInterface *client=RakNet::RakPeerInterface::GetInstance();
RakNet::RakPeerInterface *server=RakNet::RakPeerInterface::GetInstance();
int i = server->GetNumberOfAddresses();
// Holds packets
RakNet::Packet* p;
// Record the first client that connects to us so we can pass it to the ping function
RakNet::SystemAddress clientID=RakNet::UNASSIGNED_SYSTEM_ADDRESS;
bool packetFromServer;
char portstring[30];
printf("This is a sample of how to send offline pings and get offline ping\n");
printf("responses.\n");
printf("Difficulty: Beginner\n\n");
// A server
puts("Enter the server port to listen on");
Gets(portstring,sizeof(portstring));
if (portstring[0]==0)
strcpy(portstring,"60000");
// Enumeration data
puts("Enter offline ping response data (for return by a LAN discovery for example)");
puts("Hit enter for none.");
char enumData[512];
Gets(enumData,sizeof(enumData));
if (enumData[0])
server->SetOfflinePingResponse(enumData, (const unsigned int) strlen(enumData)+1);
puts("Starting server.");
// The server has to be started to respond to pings.
RakNet::SocketDescriptor socketDescriptor(atoi(portstring),0);
bool b = server->Startup(2, &socketDescriptor, 1)==RakNet::RAKNET_STARTED;
server->SetMaximumIncomingConnections(2);
if (b)
puts("Server started, waiting for connections.");
else
{
puts("Server failed to start. Terminating.");
exit(1);
}
socketDescriptor.port=0;
client->Startup(1,&socketDescriptor, 1);
puts("'q' to quit, any other key to send a ping from the client.");
char buff[256];
// Loop for input
while (1)
{
if (kbhit())
{
// Holds user data
char ip[64], serverPort[30], clientPort[30];
if (Gets(buff,sizeof(buff))&&(buff[0]=='q'))
break;
else
{
// Get our input
puts("Enter the client port to listen on, or 0");
Gets(clientPort,sizeof(clientPort));
if (clientPort[0]==0)
strcpy(clientPort, "0");
puts("Enter IP to ping");
Gets(ip, sizeof(ip));
if (ip[0]==0)
strcpy(ip, "127.0.0.1");
puts("Enter the port to ping");
Gets(serverPort,sizeof(serverPort));
if (serverPort[0]==0)
strcpy(serverPort, "60000");
client->Ping(ip, atoi(serverPort), false);
puts("Pinging");
}
}
// Get a packet from either the server or the client
p = server->Receive();
if (p==0)
{
packetFromServer=false;
p = client->Receive();
}
else
packetFromServer=true;
if (p==0)
continue;
// Check if this is a network message packet
switch (p->data[0])
{
case ID_UNCONNECTED_PONG:
{
unsigned int dataLength;
RakNet::TimeMS time;
RakNet::BitStream bsIn(p->data,p->length,false);
bsIn.IgnoreBytes(1);
bsIn.Read(time);
dataLength = p->length - sizeof(unsigned char) - sizeof(RakNet::TimeMS);
printf("ID_UNCONNECTED_PONG from SystemAddress %s.\n", p->systemAddress.ToString(true));
printf("Time is %i\n",time);
printf("Ping is %i\n", (unsigned int)(RakNet::GetTimeMS()-time));
printf("Data is %i bytes long.\n", dataLength);
if (dataLength > 0)
printf("Data is %s\n", p->data+sizeof(unsigned char)+sizeof(RakNet::TimeMS));
// In this sample since the client is not running a game we can save CPU cycles by
// Stopping the network threads after receiving the pong.
client->Shutdown(100);
}
break;
case ID_UNCONNECTED_PING:
break;
case ID_UNCONNECTED_PING_OPEN_CONNECTIONS:
break;
}
// We're done with the packet
if (packetFromServer)
server->DeallocatePacket(p);
else
client->DeallocatePacket(p);
}
// We're done with the network
RakNet::RakPeerInterface::DestroyInstance(server);
RakNet::RakPeerInterface::DestroyInstance(client);
return 0;
}
<commit_msg>Update ping.<commit_after>/*
* Copyright (c) 2014, Oculus VR, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
// ----------------------------------------------------------------------
// RakNet version 1.0
// Filename Ping.cpp
// Very basic chat engine example
// ----------------------------------------------------------------------
#include "MessageIdentifiers.h"
#include "RakPeerInterface.h"
#include "RakPeerInterface.h"
#include "RakNetTypes.h"
#include "GetTime.h"
#include "BitStream.h"
#include <assert.h>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include "Gets.h"
#ifdef WIN32
#include "Kbhit.h"
#else
#include "Kbhit.h"
#endif
int main(void)
{
// Pointers to the interfaces of our server and client.
// Note we can easily have both in the same program
RakNet::RakPeerInterface *client=RakNet::RakPeerInterface::GetInstance();
RakNet::RakPeerInterface *server=RakNet::RakPeerInterface::GetInstance();
int i = server->GetNumberOfAddresses();
// Holds packets
RakNet::Packet* p;
// Record the first client that connects to us so we can pass it to the ping function
RakNet::SystemAddress clientID=RakNet::UNASSIGNED_SYSTEM_ADDRESS;
bool packetFromServer;
char portstring[30];
printf("This is a sample of how to send offline pings and get offline ping\n");
printf("responses.\n");
printf("Difficulty: Beginner\n\n");
// A server
puts("Enter the server port to listen on");
Gets(portstring,sizeof(portstring));
if (portstring[0]==0)
strcpy(portstring,"60000");
// Enumeration data
puts("Enter offline ping response data (for return by a LAN discovery for example)");
puts("Hit enter for none.");
char enumData[512];
Gets(enumData,sizeof(enumData));
if (enumData[0])
server->SetOfflinePingResponse(enumData, (const unsigned int) strlen(enumData)+1);
puts("Starting server.");
// The server has to be started to respond to pings.
RakNet::SocketDescriptor socketDescriptor(atoi(portstring),0);
bool b = server->Startup(2, &socketDescriptor, 1)==RakNet::StartupResult::RAKNET_STARTED;
server->SetMaximumIncomingConnections(2);
if (b)
puts("Server started, waiting for connections.");
else
{
puts("Server failed to start. Terminating.");
exit(1);
}
socketDescriptor.port=0;
client->Startup(1,&socketDescriptor, 1);
puts("'q' to quit, any other key to send a ping from the client.");
char buff[256];
// Loop for input
while (1)
{
if (kbhit())
{
// Holds user data
char ip[64], serverPort[30], clientPort[30];
if (Gets(buff,sizeof(buff))&&(buff[0]=='q'))
break;
else
{
// Get our input
puts("Enter the client port to listen on, or 0");
Gets(clientPort,sizeof(clientPort));
if (clientPort[0]==0)
strcpy(clientPort, "0");
puts("Enter IP to ping");
Gets(ip, sizeof(ip));
if (ip[0]==0)
strcpy(ip, "127.0.0.1");
puts("Enter the port to ping");
Gets(serverPort,sizeof(serverPort));
if (serverPort[0]==0)
strcpy(serverPort, "60000");
client->Ping(ip, atoi(serverPort), false);
puts("Pinging");
}
}
// Get a packet from either the server or the client
p = server->Receive();
if (p==0)
{
packetFromServer=false;
p = client->Receive();
}
else
packetFromServer=true;
if (p==0)
continue;
// Check if this is a network message packet
switch (p->data[0])
{
case ID_UNCONNECTED_PONG:
{
unsigned int dataLength;
RakNet::TimeMS time;
RakNet::BitStream bsIn(p->data,p->length,false);
bsIn.IgnoreBytes(1);
bsIn.Read(time);
dataLength = p->length - sizeof(unsigned char) - sizeof(RakNet::TimeMS);
printf("ID_UNCONNECTED_PONG from SystemAddress %s.\n", p->systemAddress.ToString(true));
printf("Time is %i\n",time);
printf("Ping is %i\n", (unsigned int)(RakNet::GetTimeMS()-time));
printf("Data is %i bytes long.\n", dataLength);
if (dataLength > 0)
printf("Data is %s\n", p->data+sizeof(unsigned char)+sizeof(RakNet::TimeMS));
// In this sample since the client is not running a game we can save CPU cycles by
// Stopping the network threads after receiving the pong.
client->Shutdown(100);
}
break;
case ID_UNCONNECTED_PING:
break;
case ID_UNCONNECTED_PING_OPEN_CONNECTIONS:
break;
}
// We're done with the packet
if (packetFromServer)
server->DeallocatePacket(p);
else
client->DeallocatePacket(p);
}
// We're done with the network
RakNet::RakPeerInterface::DestroyInstance(server);
RakNet::RakPeerInterface::DestroyInstance(client);
return 0;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2009, Asmodehn's Corp.
* 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 the Asmodehn's Corp. 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.
*
*/
#include "header.hh"
int main ( int argc, char* argv[] )
{
return displayXX("test");
}
<commit_msg>changed header include command<commit_after>/**
* Copyright (c) 2009, Asmodehn's Corp.
* 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 the Asmodehn's Corp. 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.
*
*/
#include "ProjectA/header.hh"
int main ( int argc, char* argv[] )
{
return A_display("test A");
}
<|endoftext|> |
<commit_before>#include "vm/test/test.hpp"
/* Project */
#include "vm.hpp"
#include "message.hpp"
#include "builtin/array.hpp"
#include "builtin/module.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/string.hpp"
#include "builtin/symbol.hpp"
/* Testee */
#include "builtin/nativemethod.hpp"
#include "subtend/ruby.h"
/* Re-reset */
#undef Qfalse
#undef Qtrue
#undef Qnil
#undef Qundef
#define Qfalse RBX_Qfalse
#define Qtrue RBX_Qtrue
#define Qnil RBX_Qnil
#define Qundef RBX_Qundef
#define Sfalse ((VALUE)6L)
#define Strue ((VALUE)10L)
#define Snil ((VALUE)14L)
#define Sundef ((VALUE)18L)
/* From vm/objectmemory.hpp */
#undef ALLOC_N
#define ALLOC_N(type, size) ((type*)calloc(size, sizeof(type)))
static NativeMethodContext* hidden_context = NULL;
static Array* hidden_ruby_array = NULL;
static Object* hidden_receiver = NULL;
static int hidden_argc = 0;
static Handle* hidden_c_array = NULL;
using namespace rubinius;
extern "C" {
Handle minus_three_arity(Handle ruby_array)
{
hidden_context = NativeMethodContext::current();
hidden_ruby_array = as<Array>(hidden_context->object_from(ruby_array));
Object* first = hidden_ruby_array->get(hidden_context->state(), 0);
return hidden_context->handle_for(first);
}
Handle minus_two_arity(Handle receiver, Handle ruby_array)
{
hidden_context = NativeMethodContext::current();
hidden_receiver = hidden_context->object_from(receiver);
hidden_ruby_array = as<Array>(hidden_context->object_from(ruby_array));
Object* first = hidden_ruby_array->get(hidden_context->state(), 0);
return hidden_context->handle_for(first);
}
Handle minus_one_arity(int argc, Handle* args, Handle receiver)
{
hidden_context = NativeMethodContext::current();
hidden_argc = argc;
hidden_c_array = args;
hidden_receiver = hidden_context->object_from(receiver);
return args[0];
}
Handle one_arg(Handle receiver, Handle arg1)
{
hidden_context = NativeMethodContext::current();
hidden_receiver = hidden_context->object_from(receiver);
return hidden_context->handle_for(Fixnum::from(1));
}
Handle two_arg(Handle receiver, Handle arg1, Handle arg2)
{
hidden_context = NativeMethodContext::current();
hidden_receiver = hidden_context->object_from(receiver);
return hidden_context->handle_for(Fixnum::from(2));
}
Handle three_arg(Handle receiver, Handle arg1, Handle arg2, Handle arg3)
{
hidden_context = NativeMethodContext::current();
hidden_receiver = hidden_context->object_from(receiver);
return hidden_context->handle_for(Fixnum::from(3));
}
Handle four_arg(Handle receiver, Handle arg1, Handle arg2, Handle arg3, Handle arg4)
{
hidden_context = NativeMethodContext::current();
hidden_receiver = hidden_context->object_from(receiver);
return hidden_context->handle_for(Fixnum::from(4));
}
Handle five_arg(Handle receiver, Handle arg1, Handle arg2, Handle arg3, Handle arg4, Handle arg5)
{
hidden_context = NativeMethodContext::current();
hidden_receiver = hidden_context->object_from(receiver);
return hidden_context->handle_for(Fixnum::from(5));
}
Handle funcaller2(Handle receiver, Handle array, Handle obj)
{
hidden_context = NativeMethodContext::current();
Symbol* method = hidden_context->state()->symbol("blah");
Handle args[1];
args[0] = obj;
/* Handle ret = */ rb_funcall2(array, reinterpret_cast<ID>(method), 1, args);
return obj;
}
}
class TestSubtend : public CxxTest::TestSuite
{
public:
VM* my_state;
Task* my_task;
Message* my_message;
Module* my_module;
void setUp() {
my_state = new VM(65536 * 1000);
my_task = Task::create(my_state);
my_message = new Message(my_state);
my_module = Module::create(my_state);
my_message->set_caller(my_task->active());
}
void tearDown() {
hidden_context = NULL;
hidden_ruby_array = NULL;
hidden_argc = 0;
hidden_c_array = NULL;
delete my_message;
delete my_state;
}
/* Tests */
void test_ruby_to_c_call_with_args_as_ruby_array()
{
Array* args = Array::create(my_state, 10);
Array* control = Array::create(my_state, 10);
for (std::size_t i = 0; i < 10; ++i) {
Object* obj = my_state->new_object<Object>(my_state->globals.object.get());
args->set(my_state, i, obj);
control->set(my_state, i, obj);
}
my_message->set_arguments(my_state, args);
my_message->name = my_state->symbol("__subtend_fake_test_method__");
NativeMethod* method = NativeMethod::create(my_state,
String::create(my_state, __FILE__),
my_module,
my_message->name,
&minus_three_arity,
Fixnum::from(ARGS_IN_RUBY_ARRAY));
my_message->method = method;
bool ret = method->execute(my_state, my_task, *my_message);
TS_ASSERT_EQUALS(ret, true);
TS_ASSERT_DIFFERS(hidden_context, static_cast<NativeMethodContext*>(NULL));
TS_ASSERT_EQUALS(hidden_ruby_array, args);
for (std::size_t i = 0; i < 10; ++i) {
TS_ASSERT_EQUALS(hidden_ruby_array->get(my_state, i), control->get(my_state, i));
}
TS_ASSERT_EQUALS(hidden_context->return_value(), hidden_ruby_array->get(my_state, 0));
}
void test_ruby_to_c_call_with_receiver_and_args_as_ruby_array()
{
Array* args = Array::create(my_state, 10);
Array* control = Array::create(my_state, 10);
for (std::size_t i = 0; i < 10; ++i) {
Object* obj = my_state->new_object<Object>(my_state->globals.object.get());
args->set(my_state, i, obj);
control->set(my_state, i, obj);
}
Object* receiver = my_state->new_object<Object>(my_state->globals.object.get());
my_message->recv = receiver;
my_message->set_arguments(my_state, args);
my_message->name = my_state->symbol("__subtend_fake_test_method__");
NativeMethod* method = NativeMethod::create(my_state,
String::create(my_state, __FILE__),
my_module,
my_message->name,
&minus_two_arity,
Fixnum::from(RECEIVER_PLUS_ARGS_IN_RUBY_ARRAY));
my_message->method = method;
bool ret = method->execute(my_state, my_task, *my_message);
TS_ASSERT_EQUALS(ret, true);
TS_ASSERT_DIFFERS(hidden_context, static_cast<NativeMethodContext*>(NULL));
TS_ASSERT_EQUALS(hidden_receiver, receiver);
TS_ASSERT_EQUALS(hidden_ruby_array, args);
for (std::size_t i = 0; i < 10; ++i) {
TS_ASSERT_EQUALS(hidden_ruby_array->get(my_state, i), control->get(my_state, i));
}
TS_ASSERT_EQUALS(hidden_context->return_value(), hidden_ruby_array->get(my_state, 0));
}
void test_ruby_to_c_call_with_arg_count_args_in_c_array_plus_receiver()
{
Array* args = Array::create(my_state, 10);
Array* control = Array::create(my_state, 10);
for (std::size_t i = 0; i < 10; ++i) {
Object* obj = my_state->new_object<Object>(my_state->globals.object.get());
args->set(my_state, i, obj);
control->set(my_state, i, obj);
}
Object* receiver = my_state->new_object<Object>(my_state->globals.object.get());
my_message->recv = receiver;
my_message->set_arguments(my_state, args);
my_message->name = my_state->symbol("__subtend_fake_test_method__");
NativeMethod* method = NativeMethod::create(my_state,
String::create(my_state, __FILE__),
my_module,
my_message->name,
&minus_one_arity,
Fixnum::from(ARG_COUNT_ARGS_IN_C_ARRAY_PLUS_RECEIVER));
my_message->method = method;
bool ret = method->execute(my_state, my_task, *my_message);
TS_ASSERT_EQUALS(ret, true);
TS_ASSERT_DIFFERS(hidden_context, static_cast<NativeMethodContext*>(NULL));
TS_ASSERT_EQUALS(hidden_receiver, receiver);
TS_ASSERT_EQUALS(hidden_argc, 10);
for (std::size_t i = 0; i < 10; ++i) {
TS_ASSERT_EQUALS(hidden_context->object_from(hidden_c_array[i]), control->get(my_state, i));
}
TS_ASSERT_EQUALS(hidden_context->return_value(), control->get(my_state, 0));
}
/* TODO: Should check object identities too? */
void test_ruby_to_c_call_with_recv_plus_one()
{
int arg_count = 1;
Array* args = Array::create(my_state, arg_count);
Array* control = Array::create(my_state, arg_count);
for (int i = 0; i < arg_count; ++i) {
Object* obj = my_state->new_object<Object>(my_state->globals.object.get());
args->set(my_state, i, obj);
control->set(my_state, i, obj);
}
Object* receiver = my_state->new_object<Object>(my_state->globals.object.get());
my_message->recv = receiver;
my_message->set_arguments(my_state, args);
my_message->name = my_state->symbol("__subtend_fake_test_method__");
NativeMethod* method = NativeMethod::create(my_state,
String::create(my_state, __FILE__),
my_module,
my_message->name,
&one_arg,
Fixnum::from(arg_count));
my_message->method = method;
method->execute(my_state, my_task, *my_message);
TS_ASSERT_EQUALS(hidden_receiver, receiver);
TS_ASSERT_EQUALS(as<Fixnum>(hidden_context->return_value())->to_int(), arg_count);
}
void test_ruby_to_c_call_clears_caller_stack()
{
Task* task = Task::create(my_state, 2);
task->push(Fixnum::from(4));
MethodContext* top = task->active();
TS_ASSERT_EQUALS(top->calculate_sp(), 0);
Object* receiver = my_state->new_object<Object>(my_state->globals.object.get());
my_message->recv = receiver;
my_message->use_from_task(task, 1);
my_message->name = my_state->symbol("__subtend_fake_test_method__");
my_message->stack = 1;
NativeMethod* method = NativeMethod::create(my_state,
String::create(my_state, __FILE__),
my_module,
my_message->name,
&one_arg,
Fixnum::from(1));
my_message->method = method;
method->execute(my_state, task, *my_message);
TS_ASSERT_EQUALS(task->active(), top);
TS_ASSERT_EQUALS(top->calculate_sp(), 0);
TS_ASSERT_EQUALS(hidden_receiver, receiver);
TS_ASSERT_EQUALS(as<Fixnum>(hidden_context->return_value())->to_int(), 1);
TS_ASSERT_EQUALS(as<Fixnum>(top->pop())->to_int(), 1);
}
void test_ruby_to_c_call_with_recv_plus_two()
{
int arg_count = 2;
Array* args = Array::create(my_state, arg_count);
Array* control = Array::create(my_state, arg_count);
for (int i = 0; i < arg_count; ++i) {
Object* obj = my_state->new_object<Object>(my_state->globals.object.get());
args->set(my_state, i, obj);
control->set(my_state, i, obj);
}
Object* receiver = my_state->new_object<Object>(my_state->globals.object.get());
my_message->recv = receiver;
my_message->set_arguments(my_state, args);
my_message->name = my_state->symbol("__subtend_fake_test_method__");
NativeMethod* method = NativeMethod::create(my_state,
String::create(my_state, __FILE__),
my_module,
my_message->name,
&two_arg,
Fixnum::from(arg_count));
my_message->method = method;
method->execute(my_state, my_task, *my_message);
TS_ASSERT_EQUALS(hidden_receiver, receiver);
TS_ASSERT_EQUALS(as<Fixnum>(hidden_context->return_value())->to_int(), arg_count);
}
void test_ruby_to_c_call_with_recv_plus_three()
{
int arg_count = 3;
Array* args = Array::create(my_state, arg_count);
Array* control = Array::create(my_state, arg_count);
for (int i = 0; i < arg_count; ++i) {
Object* obj = my_state->new_object<Object>(my_state->globals.object.get());
args->set(my_state, i, obj);
control->set(my_state, i, obj);
}
Object* receiver = my_state->new_object<Object>(my_state->globals.object.get());
my_message->recv = receiver;
my_message->set_arguments(my_state, args);
my_message->name = my_state->symbol("__subtend_fake_test_method__");
NativeMethod* method = NativeMethod::create(my_state,
String::create(my_state, __FILE__),
my_module,
my_message->name,
&three_arg,
Fixnum::from(arg_count));
my_message->method = method;
method->execute(my_state, my_task, *my_message);
TS_ASSERT_EQUALS(hidden_receiver, receiver);
TS_ASSERT_EQUALS(as<Fixnum>(hidden_context->return_value())->to_int(), arg_count);
}
void test_ruby_to_c_call_with_recv_plus_four()
{
int arg_count = 4;
Array* args = Array::create(my_state, arg_count);
Array* control = Array::create(my_state, arg_count);
for (int i = 0; i < arg_count; ++i) {
Object* obj = my_state->new_object<Object>(my_state->globals.object.get());
args->set(my_state, i, obj);
control->set(my_state, i, obj);
}
Object* receiver = my_state->new_object<Object>(my_state->globals.object.get());
my_message->recv = receiver;
my_message->set_arguments(my_state, args);
my_message->name = my_state->symbol("__subtend_fake_test_method__");
NativeMethod* method = NativeMethod::create(my_state,
String::create(my_state, __FILE__),
my_module,
my_message->name,
&four_arg,
Fixnum::from(arg_count));
my_message->method = method;
method->execute(my_state, my_task, *my_message);
TS_ASSERT_EQUALS(hidden_receiver, receiver);
TS_ASSERT_EQUALS(as<Fixnum>(hidden_context->return_value())->to_int(), arg_count);
}
void test_ruby_to_c_call_with_recv_plus_five()
{
int arg_count = 5;
Array* args = Array::create(my_state, arg_count);
Array* control = Array::create(my_state, arg_count);
for (int i = 0; i < arg_count; ++i) {
Object* obj = my_state->new_object<Object>(my_state->globals.object.get());
args->set(my_state, i, obj);
control->set(my_state, i, obj);
}
Object* receiver = my_state->new_object<Object>(my_state->globals.object.get());
my_message->recv = receiver;
my_message->set_arguments(my_state, args);
my_message->name = my_state->symbol("__subtend_fake_test_method__");
NativeMethod* method = NativeMethod::create(my_state,
String::create(my_state, __FILE__),
my_module,
my_message->name,
&five_arg,
Fixnum::from(arg_count));
my_message->method = method;
method->execute(my_state, my_task, *my_message);
TS_ASSERT_EQUALS(hidden_receiver, receiver);
TS_ASSERT_EQUALS(as<Fixnum>(hidden_context->return_value())->to_int(), arg_count);
}
void test_rb_funcall()
{
/* No actual Ruby code involved.. */
CompiledMethod* target = CompiledMethod::create(my_state);
target->iseq(my_state, InstructionSequence::create(my_state, 1));
target->iseq()->opcodes()->put(my_state, 0, Fixnum::from(InstructionSequence::insn_ret));
target->total_args(my_state, Fixnum::from(1));
target->required_args(my_state, target->total_args());
target->stack_size(my_state, Fixnum::from(1));
Symbol* name = my_state->symbol("blah");
my_state->globals.true_class.get()->method_table()->store(my_state, name, target);
target->formalize(my_state);
Array* args = Array::create(my_state, 2);
Object* obj = my_state->new_object<Object>(my_state->globals.object.get());
args->set(my_state, 0, Qtrue);
args->set(my_state, 1, obj);
Object* receiver = my_state->new_object<Object>(my_state->globals.object.get());
my_message->recv = receiver;
my_message->set_arguments(my_state, args);
my_message->name = my_state->symbol("__subtend_fake_funcall_test_method__");
NativeMethod* method = NativeMethod::create(my_state,
String::create(my_state, __FILE__),
my_module,
my_message->name,
&funcaller2,
Fixnum::from(2));
my_message->method = method;
/* This only loads the cm. */
method->execute(my_state, my_task, *my_message);
my_task->active()->vmm->run(my_task->active()->vmm, my_task, my_task->active());
TS_ASSERT_EQUALS(obj, my_task->active()->top());
/* TODO: Need some more reasonable tests here? */
}
};
<commit_msg>Removed old subtend VM tests.<commit_after><|endoftext|> |
<commit_before>/*
* RustEditor: Plugin to add Rust language support to QtCreator IDE.
* Copyright (C) 2015 Davide Ghilardi
*
* This file is part of RustEditor.
*
* RustEditor is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* RustEditor 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 RustEditor. If not, see <http://www.gnu.org/licenses/>.
*/
#include "configuration.h"
#include <QSettings>
#include <QFileInfo>
#include <utils/environment.h>
#include <utils/fileutils.h>
#include <coreplugin/icore.h>
namespace {
const QLatin1String SETTINGS_GROUP("RustEditorConfiguration");
const QLatin1String RUST_SRC_ENV("RUST_SRC_PATH");
const QLatin1String RUST_SRC_DEF("/usr/src/rust");
const QLatin1String RACER_PATH_DEF("/usr/bin");
}
using namespace RustEditor::Internal;
Configuration *Configuration::cfg_instance = NULL;
Configuration::Configuration(QObject *parent):
QObject(parent)
{
load();
cfg_instance = this;
}
Configuration *Configuration::getInstancePtr()
{
Q_ASSERT(cfg_instance != NULL);
return cfg_instance;
}
const Settings &Configuration::getSettingsPtr()
{
return cfg_instance->rusteditorSettings;
}
void Configuration::setSettings(const Settings &newSettings)
{
cfg_instance->rusteditorSettings = newSettings;
cfg_instance->save();
}
void Configuration::load()
{
bool saveSettings = false;
QSettings *qtCreatorSettings = Core::ICore::settings();
qtCreatorSettings->beginGroup(SETTINGS_GROUP);
rusteditorSettings.load(*qtCreatorSettings);
Utils::FileName rustSrcPath = cfgPathLookup(rusteditorSettings.rustSrcPath(), Utils::FileName::fromString(RUST_SRC_DEF), RUST_SRC_ENV, saveSettings);
rusteditorSettings.setRustSrcPath(rustSrcPath);
Utils::FileName racerPath = cfgPathLookup(rusteditorSettings.racerPath(), Utils::FileName::fromString(RACER_PATH_DEF), QLatin1String(""), saveSettings);
rusteditorSettings.setRacerPath(racerPath);
qtCreatorSettings->endGroup();
if (saveSettings)
save();
}
void Configuration::save()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SETTINGS_GROUP);
rusteditorSettings.save(*settings);
settings->endGroup();
}
Utils::FileName Configuration::cfgPathLookup(const Utils::FileName &cfg, const Utils::FileName &def, const QString &envKey, bool &save)
{
Utils::FileName result;
if (cfg.isEmpty()) {
Utils::Environment env = Utils::Environment::systemEnvironment();
if (!envKey.isEmpty()){
Utils::FileName location = env.searchInPath(envKey);
QFileInfo fi = location.toFileInfo();
if (fi.exists() && fi.isDir()) result = location;
else result = def;
}else{
result = def;
}
}else{
result = cfg;
}
save = save || (result != cfg);
return result;
}
<commit_msg>Modified default rust source dir<commit_after>/*
* RustEditor: Plugin to add Rust language support to QtCreator IDE.
* Copyright (C) 2015 Davide Ghilardi
*
* This file is part of RustEditor.
*
* RustEditor is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* RustEditor 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 RustEditor. If not, see <http://www.gnu.org/licenses/>.
*/
#include "configuration.h"
#include <QSettings>
#include <QFileInfo>
#include <utils/environment.h>
#include <utils/fileutils.h>
#include <coreplugin/icore.h>
namespace {
const QLatin1String SETTINGS_GROUP("RustEditorConfiguration");
const QLatin1String RUST_SRC_ENV("RUST_SRC_PATH");
const QLatin1String RUST_SRC_DEF("/usr/src/rust/src");
const QLatin1String RACER_PATH_DEF("/usr/bin");
}
using namespace RustEditor::Internal;
Configuration *Configuration::cfg_instance = NULL;
Configuration::Configuration(QObject *parent):
QObject(parent)
{
load();
cfg_instance = this;
}
Configuration *Configuration::getInstancePtr()
{
Q_ASSERT(cfg_instance != NULL);
return cfg_instance;
}
const Settings &Configuration::getSettingsPtr()
{
return cfg_instance->rusteditorSettings;
}
void Configuration::setSettings(const Settings &newSettings)
{
cfg_instance->rusteditorSettings = newSettings;
cfg_instance->save();
}
void Configuration::load()
{
bool saveSettings = false;
QSettings *qtCreatorSettings = Core::ICore::settings();
qtCreatorSettings->beginGroup(SETTINGS_GROUP);
rusteditorSettings.load(*qtCreatorSettings);
Utils::FileName rustSrcPath = cfgPathLookup(rusteditorSettings.rustSrcPath(), Utils::FileName::fromString(RUST_SRC_DEF), RUST_SRC_ENV, saveSettings);
rusteditorSettings.setRustSrcPath(rustSrcPath);
Utils::FileName racerPath = cfgPathLookup(rusteditorSettings.racerPath(), Utils::FileName::fromString(RACER_PATH_DEF), QLatin1String(""), saveSettings);
rusteditorSettings.setRacerPath(racerPath);
qtCreatorSettings->endGroup();
if (saveSettings)
save();
}
void Configuration::save()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SETTINGS_GROUP);
rusteditorSettings.save(*settings);
settings->endGroup();
}
Utils::FileName Configuration::cfgPathLookup(const Utils::FileName &cfg, const Utils::FileName &def, const QString &envKey, bool &save)
{
Utils::FileName result;
if (cfg.isEmpty()) {
Utils::Environment env = Utils::Environment::systemEnvironment();
if (!envKey.isEmpty()){
Utils::FileName location = env.searchInPath(envKey);
QFileInfo fi = location.toFileInfo();
if (fi.exists() && fi.isDir()) result = location;
else result = def;
}else{
result = def;
}
}else{
result = cfg;
}
save = save || (result != cfg);
return result;
}
<|endoftext|> |
<commit_before>/*!
* \file int_path.hpp
* \brief file int_path.hpp
*
* Copyright 2017 by Intel.
*
* Contact: kevin.rogovin@intel.com
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <kevin.rogovin@intel.com>
*
*/
#pragma once
#include <fastuidraw/util/util.hpp>
#include <fastuidraw/util/c_array.hpp>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/reference_counted.hpp>
#include <fastuidraw/util/fastuidraw_memory.hpp>
#include <fastuidraw/path.hpp>
#include <fastuidraw/text/glyph_render_data_curve_pair.hpp>
#include <fastuidraw/text/glyph_render_data_distance_field.hpp>
#include "array2d.hpp"
#include "bounding_box.hpp"
#include "util_private.hpp"
namespace fastuidraw
{
namespace detail
{
class IntBezierCurve
{
public:
template<typename T>
class transformation
{
public:
transformation(T sc = T(1), vecN<T, 2> tr = vecN<T, 2>(T(0))):
m_scale(sc),
m_translate(tr)
{}
T
scale(void) const
{
return m_scale;
}
vecN<T, 2>
translate(void) const
{
return m_translate;
}
template<typename U>
transformation<U>
cast(void) const
{
return transformation<U>(U(m_scale), vecN<U, 2>(m_translate));
}
vecN<T, 2>
operator()(vecN<T, 2> p) const
{
return m_translate + m_scale * p;
}
private:
T m_scale;
vecN<T, 2> m_translate;
};
class ID_t
{
public:
ID_t(void):
m_contourID(-1),
m_curveID(-1)
{}
unsigned int m_contourID;
unsigned int m_curveID;
};
IntBezierCurve(const ID_t &pID, const IntBezierCurve &curve):
m_ID(pID),
m_control_pts(curve.m_control_pts),
m_num_control_pts(curve.m_num_control_pts),
m_as_polynomial_fcn(curve.m_as_polynomial_fcn),
m_derivatives_cancel(curve.m_derivatives_cancel),
m_bb(curve.m_bb)
{
}
IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &pt1):
m_ID(pID),
m_control_pts(pt0, pt1, ivec2(), ivec2()),
m_num_control_pts(2)
{
process_control_pts();
}
IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct,
const ivec2 &pt1):
m_ID(pID),
m_control_pts(pt0, ct, pt1, ivec2()),
m_num_control_pts(3)
{
process_control_pts();
}
IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct0,
const ivec2 &ct1, const ivec2 &pt1):
m_ID(pID),
m_control_pts(pt0, ct0, ct1, pt1),
m_num_control_pts(4)
{
process_control_pts();
}
~IntBezierCurve()
{}
const ID_t&
ID(void) const
{
return m_ID;
}
const_c_array<ivec2>
control_pts(void) const
{
return const_c_array<ivec2>(m_control_pts.c_ptr(), m_num_control_pts);
}
const BoundingBox<int>&
bounding_box(void) const
{
return m_bb;
}
BoundingBox<int>
bounding_box(const transformation<int> &tr) const
{
BoundingBox<int> R;
R.union_point(tr(m_bb.min_point()));
R.union_point(tr(m_bb.max_point()));
return R;
}
static
bool
are_ordered_neighbors(const IntBezierCurve &curve0,
const IntBezierCurve &curve1)
{
return curve0.control_pts().back() == curve1.control_pts().front();
}
int
degree(void) const
{
FASTUIDRAWassert(m_num_control_pts > 0);
return m_num_control_pts - 1;
}
const_c_array<vec2>
derivatives_cancel(void) const
{
return const_c_array<vec2>(m_derivatives_cancel.c_ptr(),
m_num_derivatives_cancel);
}
const_c_array<int>
as_polynomial(int coord) const
{
return const_c_array<int>(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);
}
vecN<const_c_array<int>, 2>
as_polynomial(void) const
{
return vecN<const_c_array<int>, 2>(as_polynomial(0), as_polynomial(1));
}
vec2
eval(float t) const;
private:
void
process_control_pts(void);
void
compute_derivatives_cancel_pts(void);
c_array<int>
as_polynomial(int coord)
{
return c_array<int>(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);
}
ID_t m_ID;
vecN<ivec2, 4> m_control_pts;
unsigned int m_num_control_pts;
vecN<ivec4, 2> m_as_polynomial_fcn;
// where dx/dt +- dy/dt = 0
vecN<vec2, 6> m_derivatives_cancel;
unsigned int m_num_derivatives_cancel;
BoundingBox<int> m_bb;
};
class IntContour
{
public:
IntContour(void)
{}
void
add_curve(const IntBezierCurve &curve)
{
FASTUIDRAWassert(m_curves.empty() || IntBezierCurve::are_ordered_neighbors(m_curves.back(), curve));
m_curves.push_back(curve);
}
bool
closed(void)
{
return !m_curves.empty()
&& IntBezierCurve::are_ordered_neighbors(m_curves.back(), m_curves.front());
}
const std::vector<IntBezierCurve>&
curves(void) const
{
return m_curves;
}
const IntBezierCurve&
curve(unsigned int curveID) const
{
FASTUIDRAWassert(curveID < m_curves.size());
return m_curves[curveID];
}
/* Filter the Contour as follows:
1. Collapse any curves that are within a texel
2. Curves of tiny curvature are realized as a line
3. Cubics are broken into quadratics
The transformation tr is -NOT- applied to the contour,
it is used as the transformation from IntContour
coordinates to texel coordinates. The value of texel_size
gives the size of a texel with the texel at (0, 0)
starting at (0, 0) [in texel coordinates].
*/
void
filter(float curvature_collapse,
const IntBezierCurve::transformation<int> &tr, ivec2 texel_size);
void
add_to_path(const IntBezierCurve::transformation<float> &tr, Path *dst) const;
private:
std::vector<IntBezierCurve> m_curves;
};
class IntPath
{
public:
IntPath(void)
{}
void
move_to(const ivec2 &pt);
void
line_to(const ivec2 &pt);
void
conic_to(const ivec2 &control_pt, const ivec2 &pt);
void
cubic_to(const ivec2 &control_pt0, const ivec2 &control_pt1, const ivec2 &pt);
bool
empty(void) const
{
return m_contours.empty();
}
/* Add this IntPath with a transforamtion tr applied to it to a
pre-exising (and possibly empty) Path.
\param tr transformation to apply to data of path
*/
void
add_to_path(const IntBezierCurve::transformation<float> &tr, Path *dst) const;
/* Filter the Path as follows:
1. Collapse any curves that are within a texel
2. Curves of tiny curvature are realized as a line
3. Cubics are broken into quadratics
The transformation tr is -NOT- applied to the path,
it is used as the transformation from IntContour
coordinates to texel coordinates. The value of texel_size
gives the size of a texel with the texel at (0, 0)
starting at (0, 0) [in texel coordinates].
*/
void
filter(float curvature_collapse,
const IntBezierCurve::transformation<int> &tr,
ivec2 texel_size);
/* Compute distance field data, where distance values are
sampled at the center of each texel; the caller needs to
make sure that the path with the transformation tr applied
is entirely within the region [0, W] x [0, H] where
(W, H) = texel_size * image_sz.
\param texel_size the size of each texel in coordinates
AFTER tr is applied
\param image_sz size of the distance field to make
\param tr transformation to apply to data of path
*/
void
extract_render_data(const ivec2 &texel_size, const ivec2 &image_sz,
float max_distance,
IntBezierCurve::transformation<int> tr,
GlyphRenderDataDistanceField *dst) const;
/* Compute curve-pair render data. The caller should have applied
filter() before calling to reduce cubics and collapse tiny
curves; also, the caller needs to make sure that the path
with the transformation tr applied is entirely within the
region [0, W] x [0, H] where (W, H) = texel_size * image_sz.
\param texel_size the size of each texel in coordinates
AFTER tr is applied
\param image_sz size of the distance field to make
\param tr transformation to apply to data of path
*/
void
extract_render_data(const ivec2 &texel_size, const ivec2 &image_sz,
IntBezierCurve::transformation<int> tr,
GlyphRenderDataCurvePair *dst) const;
private:
IntBezierCurve::ID_t
computeID(void);
fastuidraw::ivec2 m_last_pt;
std::vector<IntContour> m_contours;
};
} //namespace fastuidraw
} //namespace detail
<commit_msg>fastuidraw/private/int_path: add comparison operator to IntBezierCurve::ID_t<commit_after>/*!
* \file int_path.hpp
* \brief file int_path.hpp
*
* Copyright 2017 by Intel.
*
* Contact: kevin.rogovin@intel.com
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <kevin.rogovin@intel.com>
*
*/
#pragma once
#include <vector>
#include <fastuidraw/util/util.hpp>
#include <fastuidraw/util/c_array.hpp>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/reference_counted.hpp>
#include <fastuidraw/util/fastuidraw_memory.hpp>
#include <fastuidraw/path.hpp>
#include <fastuidraw/text/glyph_render_data_curve_pair.hpp>
#include <fastuidraw/text/glyph_render_data_distance_field.hpp>
#include "array2d.hpp"
#include "bounding_box.hpp"
#include "util_private.hpp"
namespace fastuidraw
{
namespace detail
{
class IntBezierCurve
{
public:
template<typename T>
class transformation
{
public:
transformation(T sc = T(1), vecN<T, 2> tr = vecN<T, 2>(T(0))):
m_scale(sc),
m_translate(tr)
{}
T
scale(void) const
{
return m_scale;
}
vecN<T, 2>
translate(void) const
{
return m_translate;
}
template<typename U>
transformation<U>
cast(void) const
{
return transformation<U>(U(m_scale), vecN<U, 2>(m_translate));
}
vecN<T, 2>
operator()(vecN<T, 2> p) const
{
return m_translate + m_scale * p;
}
private:
T m_scale;
vecN<T, 2> m_translate;
};
class ID_t
{
public:
ID_t(void):
m_contourID(-1),
m_curveID(-1)
{}
bool
operator<(const ID_t &rhs) const
{
return m_contourID == rhs.m_contourID
|| (m_contourID == rhs.m_contourID
&& m_curveID << rhs.m_curveID);
}
unsigned int m_contourID;
unsigned int m_curveID;
};
IntBezierCurve(const ID_t &pID, const IntBezierCurve &curve):
m_ID(pID),
m_control_pts(curve.m_control_pts),
m_num_control_pts(curve.m_num_control_pts),
m_as_polynomial_fcn(curve.m_as_polynomial_fcn),
m_derivatives_cancel(curve.m_derivatives_cancel),
m_bb(curve.m_bb)
{
}
IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &pt1):
m_ID(pID),
m_control_pts(pt0, pt1, ivec2(), ivec2()),
m_num_control_pts(2)
{
process_control_pts();
}
IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct,
const ivec2 &pt1):
m_ID(pID),
m_control_pts(pt0, ct, pt1, ivec2()),
m_num_control_pts(3)
{
process_control_pts();
}
IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct0,
const ivec2 &ct1, const ivec2 &pt1):
m_ID(pID),
m_control_pts(pt0, ct0, ct1, pt1),
m_num_control_pts(4)
{
process_control_pts();
}
~IntBezierCurve()
{}
const ID_t&
ID(void) const
{
return m_ID;
}
const_c_array<ivec2>
control_pts(void) const
{
return const_c_array<ivec2>(m_control_pts.c_ptr(), m_num_control_pts);
}
const BoundingBox<int>&
bounding_box(void) const
{
return m_bb;
}
BoundingBox<int>
bounding_box(const transformation<int> &tr) const
{
BoundingBox<int> R;
R.union_point(tr(m_bb.min_point()));
R.union_point(tr(m_bb.max_point()));
return R;
}
static
bool
are_ordered_neighbors(const IntBezierCurve &curve0,
const IntBezierCurve &curve1)
{
return curve0.control_pts().back() == curve1.control_pts().front();
}
int
degree(void) const
{
FASTUIDRAWassert(m_num_control_pts > 0);
return m_num_control_pts - 1;
}
const_c_array<vec2>
derivatives_cancel(void) const
{
return const_c_array<vec2>(m_derivatives_cancel.c_ptr(),
m_num_derivatives_cancel);
}
const_c_array<int>
as_polynomial(int coord) const
{
return const_c_array<int>(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);
}
vecN<const_c_array<int>, 2>
as_polynomial(void) const
{
return vecN<const_c_array<int>, 2>(as_polynomial(0), as_polynomial(1));
}
vec2
eval(float t) const;
private:
void
process_control_pts(void);
void
compute_derivatives_cancel_pts(void);
c_array<int>
as_polynomial(int coord)
{
return c_array<int>(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);
}
ID_t m_ID;
vecN<ivec2, 4> m_control_pts;
unsigned int m_num_control_pts;
vecN<ivec4, 2> m_as_polynomial_fcn;
// where dx/dt +- dy/dt = 0
vecN<vec2, 6> m_derivatives_cancel;
unsigned int m_num_derivatives_cancel;
BoundingBox<int> m_bb;
};
class IntContour
{
public:
IntContour(void)
{}
void
add_curve(const IntBezierCurve &curve)
{
FASTUIDRAWassert(m_curves.empty() || IntBezierCurve::are_ordered_neighbors(m_curves.back(), curve));
m_curves.push_back(curve);
}
bool
closed(void)
{
return !m_curves.empty()
&& IntBezierCurve::are_ordered_neighbors(m_curves.back(), m_curves.front());
}
const std::vector<IntBezierCurve>&
curves(void) const
{
return m_curves;
}
const IntBezierCurve&
curve(unsigned int curveID) const
{
FASTUIDRAWassert(curveID < m_curves.size());
return m_curves[curveID];
}
/* Filter the Contour as follows:
1. Collapse any curves that are within a texel
2. Curves of tiny curvature are realized as a line
3. Cubics are broken into quadratics
The transformation tr is -NOT- applied to the contour,
it is used as the transformation from IntContour
coordinates to texel coordinates. The value of texel_size
gives the size of a texel with the texel at (0, 0)
starting at (0, 0) [in texel coordinates].
*/
void
filter(float curvature_collapse,
const IntBezierCurve::transformation<int> &tr, ivec2 texel_size);
void
add_to_path(const IntBezierCurve::transformation<float> &tr, Path *dst) const;
private:
std::vector<IntBezierCurve> m_curves;
};
class IntPath
{
public:
IntPath(void)
{}
void
move_to(const ivec2 &pt);
void
line_to(const ivec2 &pt);
void
conic_to(const ivec2 &control_pt, const ivec2 &pt);
void
cubic_to(const ivec2 &control_pt0, const ivec2 &control_pt1, const ivec2 &pt);
bool
empty(void) const
{
return m_contours.empty();
}
/* Add this IntPath with a transforamtion tr applied to it to a
pre-exising (and possibly empty) Path.
\param tr transformation to apply to data of path
*/
void
add_to_path(const IntBezierCurve::transformation<float> &tr, Path *dst) const;
/* Filter the Path as follows:
1. Collapse any curves that are within a texel
2. Curves of tiny curvature are realized as a line
3. Cubics are broken into quadratics
The transformation tr is -NOT- applied to the path,
it is used as the transformation from IntContour
coordinates to texel coordinates. The value of texel_size
gives the size of a texel with the texel at (0, 0)
starting at (0, 0) [in texel coordinates].
*/
void
filter(float curvature_collapse,
const IntBezierCurve::transformation<int> &tr,
ivec2 texel_size);
/* Compute distance field data, where distance values are
sampled at the center of each texel; the caller needs to
make sure that the path with the transformation tr applied
is entirely within the region [0, W] x [0, H] where
(W, H) = texel_size * image_sz.
\param texel_size the size of each texel in coordinates
AFTER tr is applied
\param image_sz size of the distance field to make
\param tr transformation to apply to data of path
*/
void
extract_render_data(const ivec2 &texel_size, const ivec2 &image_sz,
float max_distance,
IntBezierCurve::transformation<int> tr,
GlyphRenderDataDistanceField *dst) const;
/* Compute curve-pair render data. The caller should have applied
filter() before calling to reduce cubics and collapse tiny
curves; also, the caller needs to make sure that the path
with the transformation tr applied is entirely within the
region [0, W] x [0, H] where (W, H) = texel_size * image_sz.
\param texel_size the size of each texel in coordinates
AFTER tr is applied
\param image_sz size of the distance field to make
\param tr transformation to apply to data of path
*/
void
extract_render_data(const ivec2 &texel_size, const ivec2 &image_sz,
IntBezierCurve::transformation<int> tr,
GlyphRenderDataCurvePair *dst) const;
private:
IntBezierCurve::ID_t
computeID(void);
fastuidraw::ivec2 m_last_pt;
std::vector<IntContour> m_contours;
};
} //namespace fastuidraw
} //namespace detail
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "../testhelpers.h"
#include "../tracker_direct_common.h"
#include <QtTest/QtTest>
#include <QtSparql/QtSparql>
class tst_QSparqlTrackerDirectConcurrency : public QObject
{
Q_OBJECT
public:
tst_QSparqlTrackerDirectConcurrency();
virtual ~tst_QSparqlTrackerDirectConcurrency();
private:
private slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
void sameConnection_selectQueries();
void sameConnection_selectQueries_data();
//void sameConnection_updateQueries();
void sameConnection_multipleThreads_selectQueries();
void sameConnection_multipleThreads_selectQueries_data();
//void sameConnection_multipleThreads_updateQueries();
// multpleConnections tests will all be multi threaded
//void multipleConnections_selectQueries();
//void multipleConnections_updateQueries();
private:
QSharedPointer<QSignalSpy> dataReadySpy;
};
namespace {
class SignalObject : public QObject
{
Q_OBJECT
public:
SignalObject() : position(0) {}
~SignalObject()
{
// delete the signal mappers that were created
foreach(QSignalMapper* map, signalMaps) {
delete map;
}
}
QSet<QSparqlResult*> pendingResults;
int position;
QList<QSignalMapper* > signalMaps;
QList<QPair<int, int> > resultRanges;
void append(QSparqlResult *r, QPair<int, int> range)
{
QSignalMapper *dataReadyMapper = new QSignalMapper();
QSignalMapper *finishedMapper = new QSignalMapper();
dataReadyMapper->setMapping(r, position);
finishedMapper->setMapping(r, position);
position++;
connect(r, SIGNAL(dataReady(int)), dataReadyMapper, SLOT(map()));
connect(dataReadyMapper, SIGNAL(mapped(int)), this, SLOT(onDataReady(int)));
connect(r, SIGNAL(finished()), finishedMapper, SLOT(map()));
connect(finishedMapper, SIGNAL(mapped(int)), this, SLOT(onFinished(int)));
resultList.append(r);
resultRanges.append(range);
pendingResults.insert(r);
// keep track of the signal mappers to delete later
signalMaps.append(dataReadyMapper);
signalMaps.append(finishedMapper);
}
QList<QSparqlResult*> resultList;
bool waitForAllFinished(int silenceTimeoutMs)
{
QTime timeoutTimer;
timeoutTimer.start();
bool timeout = false;
while (!pendingResults.empty() && !timeout) {
const int pendingResultsCountBefore = pendingResults.count();
QTest::qWait(silenceTimeoutMs / 10);
if (pendingResults.count() < pendingResultsCountBefore) {
timeoutTimer.restart();
}
else if (timeoutTimer.elapsed() > silenceTimeoutMs) {
timeout = true;
}
}
return !timeout;
}
public Q_SLOTS:
void onDataReady(int listPos)
{
QSparqlResult *result = resultList.at(listPos);
while (result->next()) {
// just do something pointless with the result
result->value(1).toInt();
result->value(0).toString();
}
}
void onFinished(int listPos)
{
QPair<int, int> resultRange = resultRanges.at(listPos);
QSparqlResult* result = resultList.at(listPos);
int expectedResultSize = (resultRange.second - resultRange.first) + 1;
QCOMPARE(expectedResultSize, result->size());
// the results should have been fully nexted in the data ready function
QCOMPARE(result->pos(), (int)QSparql::AfterLastRow);
// go back through the results and validate that they are in range
int resultCount = 0;
while (result->previous()) {
//we don't know the order, so just ensure the result is within range
QVERIFY(result->value(1).toInt() <= resultRange.second && result->value(1).toInt() >= resultRange.first);
resultCount++;
}
// now make sure the results counted match the size
QCOMPARE(resultCount, expectedResultSize);
pendingResults.remove(result);
}
};
class ThreadObject : public QObject
{
Q_OBJECT
public:
QSparqlConnection *connection;
SignalObject *signalObject;
QList<QSparqlResult*> resultList;
bool deleteConnection;
bool deleteSignalObject;
int numQueries;
int testDataSize;
ThreadObject()
: connection(0), signalObject(0), deleteConnection(false), deleteSignalObject(false)
{
}
~ThreadObject()
{
}
void cleanup()
{
if (deleteConnection) {
delete connection;
} else {
// if we were passed a connection, delete the results
// here to avoid leaking them
foreach(QSparqlResult* result, resultList)
delete result;
}
if (deleteSignalObject)
delete signalObject;
}
void setParameters(int numQueries, int testDataSize)
{
this->numQueries = numQueries;
this->testDataSize = testDataSize;
}
void setConnection(QSparqlConnection* connection)
{
this->connection = connection;
}
void setSignalObject(SignalObject* signalObject)
{
this->signalObject = signalObject;
}
void waitForFinished()
{
signalObject->waitForAllFinished(8000);
}
public Q_SLOTS:
void startQueries()
{
if (!connection) {
this->connection = new QSparqlConnection("QTRACKER_DIRECT");
deleteConnection = true;
}
if (!signalObject) {
this->signalObject = new SignalObject();
deleteSignalObject = true;
}
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
// store the result ranges we are going to use
QList<QPair<int, int> > resultRanges;
// first result will read everything
resultRanges.append(qMakePair(1, testDataSize));
for (int i=1;i<numQueries;i++) {
// high + 1) - low) + low
int low = qrand() % ((testDataSize) - 1) + 1;
int high = qrand() % ((testDataSize+1) - low) + low;
resultRanges.append(qMakePair(low, high));
}
for (int i=0;i<numQueries;i++) {
QPair<int, int> resultRange = resultRanges.at(i);
QSparqlQuery select(QString("select ?u ?t {?u a nmm:MusicPiece;"
"nmm:trackNumber ?t;"
"nie:isLogicalPartOf <qsparql-tracker-direct-tests-concurrency-stress>"
"FILTER ( ?t >=%1 && ?t <=%2 ) }").arg(resultRange.first).arg(resultRange.second));
QSparqlResult *result = connection->exec(select);
resultList.append(result);
signalObject->append(result, resultRange);
}
waitForFinished();
cleanup();
this->thread()->quit();
}
};
} //end namespace
tst_QSparqlTrackerDirectConcurrency::tst_QSparqlTrackerDirectConcurrency()
{
}
tst_QSparqlTrackerDirectConcurrency::~tst_QSparqlTrackerDirectConcurrency()
{
}
void tst_QSparqlTrackerDirectConcurrency::initTestCase()
{
// For running the test without installing the plugins. Should work in
// normal and vpath builds.
QCoreApplication::addLibraryPath("../../../plugins");
}
void tst_QSparqlTrackerDirectConcurrency::cleanupTestCase()
{
}
void tst_QSparqlTrackerDirectConcurrency::init()
{
}
void tst_QSparqlTrackerDirectConcurrency::cleanup()
{
}
void tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries()
{
QFETCH(int, testDataAmount);
QFETCH(int, numQueries);
QFETCH(int, maxThreadCount);
QSparqlConnectionOptions options;
options.setDataReadyInterval(500);
options.setMaxThreadCount(maxThreadCount);
const QString testTag("<qsparql-tracker-direct-tests-concurrency-stress>");
QScopedPointer<TestData> testData(createTestData(testDataAmount, "<qsparql-tracker-direct-tests>", testTag));
QTest::qWait(2000);
QVERIFY( testData->isOK() );
// seed the random number generator
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
// store the result ranges we are going to use
QList<QPair<int, int> > resultRanges;
// first result will read everything
resultRanges.append(qMakePair(1, 3000));
for (int i=1;i<numQueries;i++) {
// high + 1) - low) + low
int low = qrand() % ((testDataAmount) - 1) + 1;
int high = qrand() % ((testDataAmount+1) - low) + low;
resultRanges.append(qMakePair(low, high));
}
QSparqlConnection conn("QTRACKER_DIRECT", options);
SignalObject signalObject;
for (int i=0;i<numQueries;i++) {
QPair<int, int> resultRange = resultRanges.at(i);
QSparqlQuery select(QString("select ?u ?t {?u a nmm:MusicPiece;"
"nmm:trackNumber ?t;"
"nie:isLogicalPartOf <qsparql-tracker-direct-tests-concurrency-stress>"
"FILTER ( ?t >=%1 && ?t <=%2 ) }").arg(resultRange.first).arg(resultRange.second));
QSparqlResult *result = conn.exec(select);
signalObject.append(result, resultRange);
}
QVERIFY(signalObject.waitForAllFinished(8000));
}
void tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries_data()
{
QTest::addColumn<int>("testDataAmount");
QTest::addColumn<int>("numQueries");
QTest::addColumn<int>("maxThreadCount");
QTest::newRow("3000 items, 10 queries, 4 Threads") <<
3000 << 10 << 4;
QTest::newRow("3000 items, 100 queries, 4 Threads") <<
3000 << 100 << 4;
QTest::newRow("3000 items, 10 queries, 1 Thread") <<
3000 << 10 << 1;
QTest::newRow("3000 items, 100 queries, 1 Thread") <<
3000 << 100 << 1;
}
void tst_QSparqlTrackerDirectConcurrency::sameConnection_multipleThreads_selectQueries()
{
QFETCH(int, testDataAmount);
QFETCH(int, numQueries);
QFETCH(int, numThreads);
QSparqlConnection connection("QTRACKER_DIRECT");
const QString testTag("<qsparql-tracker-direct-tests-concurrency-stress>");
QScopedPointer<TestData> testData(createTestData(testDataAmount, "<qsparql-tracker-direct-tests>", testTag));
QTest::qWait(2000);
QVERIFY( testData->isOK() );
QList<QThread*> createdThreads;
QList<ThreadObject*> threadObjects;
for (int i=0;i<numThreads;i++) {
QThread *newThread = new QThread();
createdThreads.append(newThread);
ThreadObject *threadObject = new ThreadObject();
threadObjects.append(threadObject);
threadObject->setConnection(&connection);
threadObject->setParameters(numQueries, testDataAmount);
threadObject->moveToThread(newThread);
// connec the threads started signal to the slot that does the work
QObject::connect(newThread, SIGNAL(started()), threadObject, SLOT(startQueries()));
}
// start all the threads
foreach(QThread* thread, createdThreads) {
thread->start();
}
// wait for all the threads then delete
// TODO: add timer so we don't wait forever
foreach(QThread* thread, createdThreads) {
while (!thread->isFinished())
QTest::qWait(500);
delete thread;
}
//cleanup
foreach(ThreadObject *threadObject, threadObjects)
delete threadObject;
}
void tst_QSparqlTrackerDirectConcurrency::sameConnection_multipleThreads_selectQueries_data()
{
QTest::addColumn<int>("testDataAmount");
QTest::addColumn<int>("numQueries");
QTest::addColumn<int>("numThreads");
QTest::newRow("3000 items, 10 queries, 2 Threads") <<
3000 << 10 << 2;
QTest::newRow("3000 items, 100 queries, 2 Threads") <<
3000 << 100 << 2;
QTest::newRow("3000 items, 10 queries, 10 Threads") <<
3000 << 10 << 10;
QTest::newRow("3000 items, 100 queries, 10 Threads") <<
3000 << 100 << 10;
}
QTEST_MAIN( tst_QSparqlTrackerDirectConcurrency )
#include "tst_qsparql_tracker_direct_concurrency.moc"
<commit_msg>Add a test for multiple connections/threads with select queries<commit_after>/****************************************************************************
**
** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "../testhelpers.h"
#include "../tracker_direct_common.h"
#include <QtTest/QtTest>
#include <QtSparql/QtSparql>
class tst_QSparqlTrackerDirectConcurrency : public QObject
{
Q_OBJECT
public:
tst_QSparqlTrackerDirectConcurrency();
virtual ~tst_QSparqlTrackerDirectConcurrency();
private:
private slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
void sameConnection_selectQueries();
void sameConnection_selectQueries_data();
//void sameConnection_updateQueries();
void sameConnection_multipleThreads_selectQueries();
void sameConnection_multipleThreads_selectQueries_data();
//void sameConnection_multipleThreads_updateQueries();
// multpleConnections tests will all be multi threaded
void multipleConnections_selectQueries();
void multipleConnections_selectQueries_data();
//void multipleConnections_updateQueries();
private:
QSharedPointer<QSignalSpy> dataReadySpy;
};
namespace {
class SignalObject : public QObject
{
Q_OBJECT
public:
SignalObject() : position(0) {}
~SignalObject()
{
// delete the signal mappers that were created
foreach(QSignalMapper* map, signalMaps) {
delete map;
}
}
QSet<QSparqlResult*> pendingResults;
int position;
QList<QSignalMapper* > signalMaps;
QList<QPair<int, int> > resultRanges;
void append(QSparqlResult *r, QPair<int, int> range)
{
QSignalMapper *dataReadyMapper = new QSignalMapper();
QSignalMapper *finishedMapper = new QSignalMapper();
dataReadyMapper->setMapping(r, position);
finishedMapper->setMapping(r, position);
position++;
connect(r, SIGNAL(dataReady(int)), dataReadyMapper, SLOT(map()));
connect(dataReadyMapper, SIGNAL(mapped(int)), this, SLOT(onDataReady(int)));
connect(r, SIGNAL(finished()), finishedMapper, SLOT(map()));
connect(finishedMapper, SIGNAL(mapped(int)), this, SLOT(onFinished(int)));
resultList.append(r);
resultRanges.append(range);
pendingResults.insert(r);
// keep track of the signal mappers to delete later
signalMaps.append(dataReadyMapper);
signalMaps.append(finishedMapper);
}
QList<QSparqlResult*> resultList;
bool waitForAllFinished(int silenceTimeoutMs)
{
QTime timeoutTimer;
timeoutTimer.start();
bool timeout = false;
while (!pendingResults.empty() && !timeout) {
const int pendingResultsCountBefore = pendingResults.count();
QTest::qWait(silenceTimeoutMs / 10);
if (pendingResults.count() < pendingResultsCountBefore) {
timeoutTimer.restart();
}
else if (timeoutTimer.elapsed() > silenceTimeoutMs) {
timeout = true;
}
}
return !timeout;
}
public Q_SLOTS:
void onDataReady(int listPos)
{
QSparqlResult *result = resultList.at(listPos);
while (result->next()) {
// just do something pointless with the result
result->value(1).toInt();
result->value(0).toString();
}
}
void onFinished(int listPos)
{
QPair<int, int> resultRange = resultRanges.at(listPos);
QSparqlResult* result = resultList.at(listPos);
int expectedResultSize = (resultRange.second - resultRange.first) + 1;
QCOMPARE(expectedResultSize, result->size());
// the results should have been fully nexted in the data ready function
QCOMPARE(result->pos(), (int)QSparql::AfterLastRow);
// go back through the results and validate that they are in range
int resultCount = 0;
while (result->previous()) {
//we don't know the order, so just ensure the result is within range
QVERIFY(result->value(1).toInt() <= resultRange.second && result->value(1).toInt() >= resultRange.first);
resultCount++;
}
// now make sure the results counted match the size
QCOMPARE(resultCount, expectedResultSize);
pendingResults.remove(result);
}
};
class ThreadObject : public QObject
{
Q_OBJECT
public:
QSparqlConnection *connection;
SignalObject *signalObject;
QList<QSparqlResult*> resultList;
bool deleteConnection;
bool deleteSignalObject;
int numQueries;
int testDataSize;
ThreadObject()
: connection(0), signalObject(0), deleteConnection(false), deleteSignalObject(false)
{
}
~ThreadObject()
{
}
void cleanup()
{
if (deleteConnection) {
delete connection;
} else {
// if we were passed a connection, delete the results
// here to avoid leaking them
foreach(QSparqlResult* result, resultList)
delete result;
}
if (deleteSignalObject)
delete signalObject;
}
void setParameters(int numQueries, int testDataSize)
{
this->numQueries = numQueries;
this->testDataSize = testDataSize;
}
void setConnection(QSparqlConnection* connection)
{
this->connection = connection;
}
void setSignalObject(SignalObject* signalObject)
{
this->signalObject = signalObject;
}
void waitForFinished()
{
signalObject->waitForAllFinished(8000);
}
public Q_SLOTS:
void startQueries()
{
if (!connection) {
this->connection = new QSparqlConnection("QTRACKER_DIRECT");
deleteConnection = true;
}
if (!signalObject) {
this->signalObject = new SignalObject();
deleteSignalObject = true;
}
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
// store the result ranges we are going to use
QList<QPair<int, int> > resultRanges;
// first result will read everything
resultRanges.append(qMakePair(1, testDataSize));
for (int i=1;i<numQueries;i++) {
// high + 1) - low) + low
int low = qrand() % ((testDataSize) - 1) + 1;
int high = qrand() % ((testDataSize+1) - low) + low;
resultRanges.append(qMakePair(low, high));
}
for (int i=0;i<numQueries;i++) {
QPair<int, int> resultRange = resultRanges.at(i);
QSparqlQuery select(QString("select ?u ?t {?u a nmm:MusicPiece;"
"nmm:trackNumber ?t;"
"nie:isLogicalPartOf <qsparql-tracker-direct-tests-concurrency-stress>"
"FILTER ( ?t >=%1 && ?t <=%2 ) }").arg(resultRange.first).arg(resultRange.second));
QSparqlResult *result = connection->exec(select);
resultList.append(result);
signalObject->append(result, resultRange);
}
waitForFinished();
cleanup();
this->thread()->quit();
}
};
} //end namespace
tst_QSparqlTrackerDirectConcurrency::tst_QSparqlTrackerDirectConcurrency()
{
}
tst_QSparqlTrackerDirectConcurrency::~tst_QSparqlTrackerDirectConcurrency()
{
}
void tst_QSparqlTrackerDirectConcurrency::initTestCase()
{
// For running the test without installing the plugins. Should work in
// normal and vpath builds.
QCoreApplication::addLibraryPath("../../../plugins");
}
void tst_QSparqlTrackerDirectConcurrency::cleanupTestCase()
{
}
void tst_QSparqlTrackerDirectConcurrency::init()
{
}
void tst_QSparqlTrackerDirectConcurrency::cleanup()
{
}
void tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries()
{
QFETCH(int, testDataAmount);
QFETCH(int, numQueries);
QFETCH(int, maxThreadCount);
QSparqlConnectionOptions options;
options.setDataReadyInterval(500);
options.setMaxThreadCount(maxThreadCount);
const QString testTag("<qsparql-tracker-direct-tests-concurrency-stress>");
QScopedPointer<TestData> testData(createTestData(testDataAmount, "<qsparql-tracker-direct-tests>", testTag));
QTest::qWait(2000);
QVERIFY( testData->isOK() );
// seed the random number generator
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
// store the result ranges we are going to use
QList<QPair<int, int> > resultRanges;
// first result will read everything
resultRanges.append(qMakePair(1, 3000));
for (int i=1;i<numQueries;i++) {
// high + 1) - low) + low
int low = qrand() % ((testDataAmount) - 1) + 1;
int high = qrand() % ((testDataAmount+1) - low) + low;
resultRanges.append(qMakePair(low, high));
}
QSparqlConnection conn("QTRACKER_DIRECT", options);
SignalObject signalObject;
for (int i=0;i<numQueries;i++) {
QPair<int, int> resultRange = resultRanges.at(i);
QSparqlQuery select(QString("select ?u ?t {?u a nmm:MusicPiece;"
"nmm:trackNumber ?t;"
"nie:isLogicalPartOf <qsparql-tracker-direct-tests-concurrency-stress>"
"FILTER ( ?t >=%1 && ?t <=%2 ) }").arg(resultRange.first).arg(resultRange.second));
QSparqlResult *result = conn.exec(select);
signalObject.append(result, resultRange);
}
QVERIFY(signalObject.waitForAllFinished(8000));
}
void tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries_data()
{
QTest::addColumn<int>("testDataAmount");
QTest::addColumn<int>("numQueries");
QTest::addColumn<int>("maxThreadCount");
QTest::newRow("3000 items, 10 queries, 4 Threads") <<
3000 << 10 << 4;
QTest::newRow("3000 items, 100 queries, 4 Threads") <<
3000 << 100 << 4;
QTest::newRow("3000 items, 10 queries, 1 Thread") <<
3000 << 10 << 1;
QTest::newRow("3000 items, 100 queries, 1 Thread") <<
3000 << 100 << 1;
}
void tst_QSparqlTrackerDirectConcurrency::sameConnection_multipleThreads_selectQueries()
{
QFETCH(int, testDataAmount);
QFETCH(int, numQueries);
QFETCH(int, numThreads);
QSparqlConnection connection("QTRACKER_DIRECT");
const QString testTag("<qsparql-tracker-direct-tests-concurrency-stress>");
QScopedPointer<TestData> testData(createTestData(testDataAmount, "<qsparql-tracker-direct-tests>", testTag));
QTest::qWait(2000);
QVERIFY( testData->isOK() );
QList<QThread*> createdThreads;
QList<ThreadObject*> threadObjects;
for (int i=0;i<numThreads;i++) {
QThread *newThread = new QThread();
createdThreads.append(newThread);
ThreadObject *threadObject = new ThreadObject();
threadObjects.append(threadObject);
threadObject->setConnection(&connection);
threadObject->setParameters(numQueries, testDataAmount);
threadObject->moveToThread(newThread);
// connec the threads started signal to the slot that does the work
QObject::connect(newThread, SIGNAL(started()), threadObject, SLOT(startQueries()));
}
// start all the threads
foreach(QThread* thread, createdThreads) {
thread->start();
}
// wait for all the threads then delete
// TODO: add timer so we don't wait forever
foreach(QThread* thread, createdThreads) {
while (!thread->isFinished())
QTest::qWait(500);
delete thread;
}
//cleanup
foreach(ThreadObject *threadObject, threadObjects)
delete threadObject;
}
void tst_QSparqlTrackerDirectConcurrency::sameConnection_multipleThreads_selectQueries_data()
{
QTest::addColumn<int>("testDataAmount");
QTest::addColumn<int>("numQueries");
QTest::addColumn<int>("numThreads");
QTest::newRow("3000 items, 10 queries, 2 Threads") <<
3000 << 10 << 2;
QTest::newRow("3000 items, 100 queries, 2 Threads") <<
3000 << 100 << 2;
QTest::newRow("3000 items, 10 queries, 10 Threads") <<
3000 << 10 << 10;
QTest::newRow("3000 items, 100 queries, 10 Threads") <<
3000 << 100 << 10;
}
void tst_QSparqlTrackerDirectConcurrency::multipleConnections_selectQueries()
{
QFETCH(int, testDataAmount);
QFETCH(int, numQueries);
QFETCH(int, numThreads);
QSparqlConnection connection("QTRACKER_DIRECT");
const QString testTag("<qsparql-tracker-direct-tests-concurrency-stress>");
QScopedPointer<TestData> testData(createTestData(testDataAmount, "<qsparql-tracker-direct-tests>", testTag));
QTest::qWait(2000);
QVERIFY( testData->isOK() );
QList<QThread*> createdThreads;
QList<ThreadObject*> threadObjects;
for (int i=0;i<numThreads;i++) {
QThread *newThread = new QThread();
createdThreads.append(newThread);
ThreadObject *threadObject = new ThreadObject();
threadObjects.append(threadObject);
threadObject->setParameters(numQueries, testDataAmount);
threadObject->moveToThread(newThread);
// connec the threads started signal to the slot that does the work
QObject::connect(newThread, SIGNAL(started()), threadObject, SLOT(startQueries()));
}
// start all the threads
foreach(QThread* thread, createdThreads) {
thread->start();
}
// wait for all the threads then delete
// TODO: add timer so we don't wait forever
foreach(QThread* thread, createdThreads) {
while (!thread->isFinished())
QTest::qWait(500);
delete thread;
}
//cleanup
foreach(ThreadObject *threadObject, threadObjects)
delete threadObject;
}
void tst_QSparqlTrackerDirectConcurrency::multipleConnections_selectQueries_data()
{
qDebug() << "This data function has been called....";
QTest::addColumn<int>("testDataAmount");
QTest::addColumn<int>("numQueries");
QTest::addColumn<int>("numThreads");
QTest::newRow("3000 items, 10 queries, 2 Threads") <<
3000 << 10 << 2;
QTest::newRow("3000 items, 100 queries, 2 Threads") <<
3000 << 100 << 2;
QTest::newRow("3000 items, 10 queries, 10 Threads") <<
3000 << 10 << 10;
QTest::newRow("3000 items, 100 queries, 10 Threads") <<
3000 << 100 << 10;
}
QTEST_MAIN( tst_QSparqlTrackerDirectConcurrency )
#include "tst_qsparql_tracker_direct_concurrency.moc"
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "ServerImpl.h"
#include <osvr/Connection/Connection.h>
#include <osvr/PluginHost/RegistrationContext.h>
#include <osvr/Util/MessageKeys.h>
#include <osvr/Connection/MessageType.h>
// Library/third-party includes
// - none
// Standard includes
#include <stdexcept>
#include <functional>
namespace osvr {
namespace server {
ServerImpl::ServerImpl(connection::ConnectionPtr const &conn)
: m_conn(conn), m_ctx(make_shared<pluginhost::RegistrationContext>()),
m_running(false) {
if (!m_conn) {
throw std::logic_error(
"Can't pass a null ConnectionPtr into Server constructor!");
}
osvr::connection::Connection::storeConnection(*m_ctx, m_conn);
if (!m_sysDevice) {
m_sysDevice = connection::DeviceToken::createVirtualDevice(
util::messagekeys::systemSender(), m_conn);
}
if (!m_routingMessageType) {
m_routingMessageType =
m_conn->registerMessageType(util::messagekeys::routingData());
}
}
ServerImpl::~ServerImpl() { stop(); }
void ServerImpl::start() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_running = true;
// Use a lambda to run the loop.
m_thread = boost::thread([&] {
bool keepRunning = true;
::util::LoopGuard guard(m_run);
do {
keepRunning = this->loop();
} while (keepRunning);
m_ctx.reset();
m_conn.reset();
m_running = false;
});
m_run.signalAndWaitForStart();
}
void ServerImpl::startAndAwaitShutdown() {
start();
m_thread.join();
}
void ServerImpl::stop() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_run.signalAndWaitForShutdown();
m_thread.join();
m_thread = boost::thread();
}
void ServerImpl::signalStop() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_run.signalShutdown();
}
void ServerImpl::loadPlugin(std::string const &pluginName) {
m_callControlled(std::bind(&pluginhost::RegistrationContext::loadPlugin,
m_ctx, pluginName));
}
void ServerImpl::instantiateDriver(std::string const &plugin,
std::string const &driver,
std::string const ¶ms) {
m_ctx->instantiateDriver(plugin, driver, params);
}
void ServerImpl::triggerHardwareDetect() {
m_callControlled(std::bind(
&pluginhost::RegistrationContext::triggerHardwareDetect, m_ctx));
}
void ServerImpl::registerMainloopMethod(MainloopMethod f) {
if (f) {
m_mainloopMethods.push_back(f);
}
}
bool ServerImpl::loop() {
m_conn->process();
for (auto &f : m_mainloopMethods) {
f();
}
/// @todo do queued things in here?
/// @todo configurable waiting?
m_thread.yield();
return m_run.shouldContinue();
}
template <typename Callable>
inline void ServerImpl::m_callControlled(Callable f) {
boost::unique_lock<boost::mutex> lock(m_runControl);
if (m_running) {
/// @todo not yet implemented
throw std::logic_error("not yet implemented");
}
f();
}
} // namespace server
} // namespace osvr<commit_msg>callControlled in server is OK if we're running as long as we're in the right thread.<commit_after>/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "ServerImpl.h"
#include <osvr/Connection/Connection.h>
#include <osvr/PluginHost/RegistrationContext.h>
#include <osvr/Util/MessageKeys.h>
#include <osvr/Connection/MessageType.h>
// Library/third-party includes
// - none
// Standard includes
#include <stdexcept>
#include <functional>
namespace osvr {
namespace server {
ServerImpl::ServerImpl(connection::ConnectionPtr const &conn)
: m_conn(conn), m_ctx(make_shared<pluginhost::RegistrationContext>()),
m_running(false) {
if (!m_conn) {
throw std::logic_error(
"Can't pass a null ConnectionPtr into Server constructor!");
}
osvr::connection::Connection::storeConnection(*m_ctx, m_conn);
if (!m_sysDevice) {
m_sysDevice = connection::DeviceToken::createVirtualDevice(
util::messagekeys::systemSender(), m_conn);
}
if (!m_routingMessageType) {
m_routingMessageType =
m_conn->registerMessageType(util::messagekeys::routingData());
}
}
ServerImpl::~ServerImpl() { stop(); }
void ServerImpl::start() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_running = true;
// Use a lambda to run the loop.
m_thread = boost::thread([&] {
bool keepRunning = true;
::util::LoopGuard guard(m_run);
do {
keepRunning = this->loop();
} while (keepRunning);
m_ctx.reset();
m_conn.reset();
m_running = false;
});
m_run.signalAndWaitForStart();
}
void ServerImpl::startAndAwaitShutdown() {
start();
m_thread.join();
}
void ServerImpl::stop() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_run.signalAndWaitForShutdown();
m_thread.join();
m_thread = boost::thread();
}
void ServerImpl::signalStop() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_run.signalShutdown();
}
void ServerImpl::loadPlugin(std::string const &pluginName) {
m_callControlled(std::bind(&pluginhost::RegistrationContext::loadPlugin,
m_ctx, pluginName));
}
void ServerImpl::instantiateDriver(std::string const &plugin,
std::string const &driver,
std::string const ¶ms) {
m_ctx->instantiateDriver(plugin, driver, params);
}
void ServerImpl::triggerHardwareDetect() {
m_callControlled(std::bind(
&pluginhost::RegistrationContext::triggerHardwareDetect, m_ctx));
}
void ServerImpl::registerMainloopMethod(MainloopMethod f) {
if (f) {
m_mainloopMethods.push_back(f);
}
}
bool ServerImpl::loop() {
m_conn->process();
for (auto &f : m_mainloopMethods) {
f();
}
/// @todo do queued things in here?
/// @todo configurable waiting?
m_thread.yield();
return m_run.shouldContinue();
}
template <typename Callable>
inline void ServerImpl::m_callControlled(Callable f) {
boost::unique_lock<boost::mutex> lock(m_runControl);
if (m_running && boost::this_thread::get_id() != m_thread.get_id()) {
/// @todo callControlled after the run loop started from outside the
/// run loop's thread is not yet implemented
throw std::logic_error("not yet implemented");
}
f();
}
} // namespace server
} // namespace osvr<|endoftext|> |
<commit_before>/**
* \ file UniversalFixedDelayLineFilter.cpp
*/
#include <ATK/Delay/UniversalFixedDelayLineFilter.h>
#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>
#define PROCESSSIZE (1024*64)
BOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line100_delay50_test )
{
boost::scoped_array<float> data(new float[PROCESSSIZE]);
for(std::int64_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000);
}
ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
boost::scoped_array<float> outdata(new float[PROCESSSIZE]);
ATK::UniversalFixedDelayLineFilter<float> filter(100);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_delay(50);
ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(1);
output.process(49);
output.process(51);
output.process(PROCESSSIZE - 1 - 49 -51);
for(std::int64_t i = 0; i < 50; ++i)
{
BOOST_REQUIRE_EQUAL(0, outdata[i]);
}
for(std::int64_t i = 50; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_EQUAL(data[i - 50], outdata[i]);
}
}
<commit_msg>Testing additional options in the delay line<commit_after>/**
* \ file UniversalFixedDelayLineFilter.cpp
*/
#include <ATK/Delay/UniversalFixedDelayLineFilter.h>
#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>
#define PROCESSSIZE (1024*64)
BOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line100_delay50_test )
{
boost::scoped_array<float> data(new float[PROCESSSIZE]);
for(std::int64_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000);
}
ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
boost::scoped_array<float> outdata(new float[PROCESSSIZE]);
ATK::UniversalFixedDelayLineFilter<float> filter(100);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_delay(50);
ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(49);
output.process(1);
output.process(51);
output.process(PROCESSSIZE - 1 - 49 -51);
for(std::int64_t i = 0; i < 50; ++i)
{
BOOST_REQUIRE_EQUAL(0, outdata[i]);
}
for(std::int64_t i = 50; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_EQUAL(data[i - 50], outdata[i]);
}
}
BOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line25_delay24_blend_1_feedforward_1_feedback_0_test )
{
boost::scoped_array<float> data(new float[PROCESSSIZE]);
for(std::int64_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000);
}
ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
boost::scoped_array<float> outdata(new float[PROCESSSIZE]);
ATK::UniversalFixedDelayLineFilter<float> filter(25);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_delay(24);
filter.set_blend(1);
filter.set_feedback(0);
filter.set_feedforward(1);
ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(49);
output.process(1);
output.process(51);
output.process(PROCESSSIZE - 1 - 49 -51);
for(std::int64_t i = 24; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_SMALL(outdata[i], 0.0001f);
}
}
BOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line25_delay24_blend_0_feedforward_0_feedback_1_test )
{
boost::scoped_array<float> data(new float[PROCESSSIZE]);
for(std::int64_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000);
}
ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
boost::scoped_array<float> outdata(new float[PROCESSSIZE]);
ATK::UniversalFixedDelayLineFilter<float> filter(25);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_delay(24);
filter.set_blend(0);
filter.set_feedback(1);
filter.set_feedforward(0);
ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(49);
output.process(1);
output.process(51);
output.process(PROCESSSIZE - 1 - 49 -51);
for(std::int64_t i = 24; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_SMALL(outdata[i], 0.0001f);
}
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "ServerImpl.h"
#include <osvr/Connection/Connection.h>
#include <osvr/PluginHost/RegistrationContext.h>
#include <osvr/Util/MessageKeys.h>
#include <osvr/Connection/MessageType.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
// - none
// Standard includes
#include <stdexcept>
#include <functional>
namespace osvr {
namespace server {
ServerImpl::ServerImpl(connection::ConnectionPtr const &conn)
: m_conn(conn), m_ctx(make_shared<pluginhost::RegistrationContext>()),
m_running(false) {
if (!m_conn) {
throw std::logic_error(
"Can't pass a null ConnectionPtr into Server constructor!");
}
osvr::connection::Connection::storeConnection(*m_ctx, m_conn);
if (!m_sysDevice) {
m_sysDevice = connection::DeviceToken::createVirtualDevice(
util::messagekeys::systemSender(), m_conn);
}
if (!m_routingMessageType) {
m_routingMessageType =
m_conn->registerMessageType(util::messagekeys::routingData());
}
m_conn->registerConnectionHandler(
std::bind(&ServerImpl::triggerHardwareDetect, std::ref(*this)));
m_conn->registerConnectionHandler(
std::bind(&ServerImpl::m_sendRoutes, std::ref(*this)));
}
ServerImpl::~ServerImpl() { stop(); }
void ServerImpl::start() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_running = true;
// Use a lambda to run the loop.
m_thread = boost::thread([&] {
bool keepRunning = true;
::util::LoopGuard guard(m_run);
do {
keepRunning = this->loop();
} while (keepRunning);
m_ctx.reset();
m_conn.reset();
m_running = false;
});
m_run.signalAndWaitForStart();
}
void ServerImpl::startAndAwaitShutdown() {
start();
awaitShutdown();
}
void ServerImpl::awaitShutdown() { m_thread.join(); }
void ServerImpl::stop() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_run.signalAndWaitForShutdown();
m_thread.join();
m_thread = boost::thread();
}
void ServerImpl::signalStop() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_run.signalShutdown();
}
void ServerImpl::loadPlugin(std::string const &pluginName) {
m_callControlled(std::bind(&pluginhost::RegistrationContext::loadPlugin,
m_ctx, pluginName));
}
void ServerImpl::instantiateDriver(std::string const &plugin,
std::string const &driver,
std::string const ¶ms) {
m_ctx->instantiateDriver(plugin, driver, params);
}
void ServerImpl::triggerHardwareDetect() {
OSVR_DEV_VERBOSE("Performing hardware auto-detection.");
m_callControlled(std::bind(
&pluginhost::RegistrationContext::triggerHardwareDetect, m_ctx));
}
void ServerImpl::registerMainloopMethod(MainloopMethod f) {
if (f) {
m_callControlled([&] { m_mainloopMethods.push_back(f); });
}
}
bool ServerImpl::loop() {
bool shouldContinue;
{
/// @todo More elegant way of running queued things than grabbing a
/// mutex each time through?
boost::unique_lock<boost::mutex> lock(m_mainThreadMutex);
m_conn->process();
for (auto &f : m_mainloopMethods) {
f();
}
shouldContinue = m_run.shouldContinue();
}
/// @todo configurable waiting?
m_thread.yield();
return shouldContinue;
}
bool ServerImpl::addRoute(std::string const &routingDirective) {
bool wasNew;
m_callControlled([&] { wasNew = m_routes.addRoute(routingDirective); });
return wasNew;
}
std::string ServerImpl::getRoutes(bool styled) const {
std::string ret;
m_callControlled([&] { ret = m_routes.getRoutes(styled); });
return ret;
}
std::string ServerImpl::getSource(std::string const &destination) const {
std::string ret;
m_callControlled([&] { ret = m_routes.getSource(destination); });
return ret;
}
void ServerImpl::m_sendRoutes() {
std::string message = getRoutes(false);
OSVR_DEV_VERBOSE("Transmitting " << m_routes.size()
<< " routes to the client.");
m_sysDevice->sendData(m_routingMessageType.get(), message.c_str(),
message.size());
}
} // namespace server
} // namespace osvr<commit_msg>Don't have a nested callControlled when sending routes.<commit_after>/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "ServerImpl.h"
#include <osvr/Connection/Connection.h>
#include <osvr/PluginHost/RegistrationContext.h>
#include <osvr/Util/MessageKeys.h>
#include <osvr/Connection/MessageType.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
// - none
// Standard includes
#include <stdexcept>
#include <functional>
namespace osvr {
namespace server {
ServerImpl::ServerImpl(connection::ConnectionPtr const &conn)
: m_conn(conn), m_ctx(make_shared<pluginhost::RegistrationContext>()),
m_running(false) {
if (!m_conn) {
throw std::logic_error(
"Can't pass a null ConnectionPtr into Server constructor!");
}
osvr::connection::Connection::storeConnection(*m_ctx, m_conn);
if (!m_sysDevice) {
m_sysDevice = connection::DeviceToken::createVirtualDevice(
util::messagekeys::systemSender(), m_conn);
}
if (!m_routingMessageType) {
m_routingMessageType =
m_conn->registerMessageType(util::messagekeys::routingData());
}
m_conn->registerConnectionHandler(
std::bind(&ServerImpl::triggerHardwareDetect, std::ref(*this)));
m_conn->registerConnectionHandler(
std::bind(&ServerImpl::m_sendRoutes, std::ref(*this)));
}
ServerImpl::~ServerImpl() { stop(); }
void ServerImpl::start() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_running = true;
// Use a lambda to run the loop.
m_thread = boost::thread([&] {
bool keepRunning = true;
::util::LoopGuard guard(m_run);
do {
keepRunning = this->loop();
} while (keepRunning);
m_ctx.reset();
m_conn.reset();
m_running = false;
});
m_run.signalAndWaitForStart();
}
void ServerImpl::startAndAwaitShutdown() {
start();
awaitShutdown();
}
void ServerImpl::awaitShutdown() { m_thread.join(); }
void ServerImpl::stop() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_run.signalAndWaitForShutdown();
m_thread.join();
m_thread = boost::thread();
}
void ServerImpl::signalStop() {
boost::unique_lock<boost::mutex> lock(m_runControl);
m_run.signalShutdown();
}
void ServerImpl::loadPlugin(std::string const &pluginName) {
m_callControlled(std::bind(&pluginhost::RegistrationContext::loadPlugin,
m_ctx, pluginName));
}
void ServerImpl::instantiateDriver(std::string const &plugin,
std::string const &driver,
std::string const ¶ms) {
m_ctx->instantiateDriver(plugin, driver, params);
}
void ServerImpl::triggerHardwareDetect() {
OSVR_DEV_VERBOSE("Performing hardware auto-detection.");
m_callControlled(std::bind(
&pluginhost::RegistrationContext::triggerHardwareDetect, m_ctx));
}
void ServerImpl::registerMainloopMethod(MainloopMethod f) {
if (f) {
m_callControlled([&] { m_mainloopMethods.push_back(f); });
}
}
bool ServerImpl::loop() {
bool shouldContinue;
{
/// @todo More elegant way of running queued things than grabbing a
/// mutex each time through?
boost::unique_lock<boost::mutex> lock(m_mainThreadMutex);
m_conn->process();
for (auto &f : m_mainloopMethods) {
f();
}
shouldContinue = m_run.shouldContinue();
}
/// @todo configurable waiting?
m_thread.yield();
return shouldContinue;
}
bool ServerImpl::addRoute(std::string const &routingDirective) {
bool wasNew;
m_callControlled([&] { wasNew = m_routes.addRoute(routingDirective); });
return wasNew;
}
std::string ServerImpl::getRoutes(bool styled) const {
std::string ret;
m_callControlled([&] { ret = m_routes.getRoutes(styled); });
return ret;
}
std::string ServerImpl::getSource(std::string const &destination) const {
std::string ret;
m_callControlled([&] { ret = m_routes.getSource(destination); });
return ret;
}
void ServerImpl::m_sendRoutes() {
std::string message = m_routes.getRoutes();
OSVR_DEV_VERBOSE("Transmitting " << m_routes.size()
<< " routes to the client.");
m_sysDevice->sendData(m_routingMessageType.get(), message.c_str(),
message.size());
}
} // namespace server
} // namespace osvr<|endoftext|> |
<commit_before>// Arguments: Doubles, Doubles, Doubles, Doubles
#include <stan/math/prim.hpp>
using stan::math::var;
using std::numeric_limits;
using std::vector;
class AgradDistributionsStudentT : public AgradDistributionTest {
public:
void valid_values(vector<vector<double> >& parameters,
vector<double>& log_prob) {
vector<double> param(4);
param[0] = 1.0; // y
param[1] = 1.0; // nu
param[2] = 0.0; // mu
param[3] = 1.0; // sigma
parameters.push_back(param);
log_prob.push_back(-1.837877066409345339082); // expected log_prob
param[0] = -3.0; // y
param[1] = 2.0; // nu
param[2] = 0.0; // mu
param[3] = 1.0; // sigma
parameters.push_back(param);
log_prob.push_back(-3.596842909197555560041); // expected log_prob
}
void invalid_values(vector<size_t>& index, vector<double>& value) {
// y
// nu
index.push_back(1U);
value.push_back(0.0);
index.push_back(1U);
value.push_back(-1.0);
index.push_back(1U);
value.push_back(numeric_limits<double>::infinity());
index.push_back(1U);
value.push_back(-numeric_limits<double>::infinity());
// mu
index.push_back(2U);
value.push_back(numeric_limits<double>::infinity());
index.push_back(2U);
value.push_back(-numeric_limits<double>::infinity());
// sigma
index.push_back(3U);
value.push_back(0.0);
index.push_back(3U);
value.push_back(-1.0);
index.push_back(3U);
value.push_back(numeric_limits<double>::infinity());
index.push_back(3U);
value.push_back(-numeric_limits<double>::infinity());
}
template <class T_y, class T_dof, class T_loc, class T_scale, typename T4,
typename T5>
typename stan::return_type<T_y, T_dof, T_loc, T_scale>::type log_prob(
const T_y& y, const T_dof& nu, const T_loc& mu, const T_scale& sigma,
const T4&, const T5&) {
return stan::math::student_t_log(y, nu, mu, sigma);
}
template <bool propto, class T_y, class T_dof, class T_loc, class T_scale,
typename T4, typename T5>
typename stan::return_type<T_y, T_dof, T_loc, T_scale>::type log_prob(
const T_y& y, const T_dof& nu, const T_loc& mu, const T_scale& sigma,
const T4&, const T5&) {
return stan::math::student_t_log<propto>(y, nu, mu, sigma);
}
template <class T_y, class T_dof, class T_loc, class T_scale, typename T4,
typename T5>
typename stan::return_type<T_y, T_dof, T_loc, T_scale>::type
log_prob_function(const T_y& y, const T_dof& nu, const T_loc& mu,
const T_scale& sigma, const T4&, const T5&) {
using boost::math::lgamma;
using stan::math::log1p;
using stan::math::LOG_SQRT_PI;
using stan::math::square;
using std::log;
return lgamma((nu + 1.0) / 2.0) - lgamma(nu / 2.0) - LOG_SQRT_PI
- 0.5 * log(nu) - log(sigma)
- ((nu + 1.0) / 2.0) * log1p(square(((y - mu) / sigma)) / nu);
}
};
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>// Arguments: Doubles, Doubles, Doubles, Doubles
#include <stan/math/prim.hpp>
using stan::math::var;
using std::numeric_limits;
using std::vector;
class AgradDistributionsStudentT : public AgradDistributionTest {
public:
void valid_values(vector<vector<double> >& parameters,
vector<double>& log_prob) {
vector<double> param(4);
param[0] = 1.0; // y
param[1] = 1.0; // nu
param[2] = 0.0; // mu
param[3] = 1.0; // sigma
parameters.push_back(param);
log_prob.push_back(-1.837877066409345339082); // expected log_prob
param[0] = -3.0; // y
param[1] = 2.0; // nu
param[2] = 0.0; // mu
param[3] = 1.0; // sigma
parameters.push_back(param);
log_prob.push_back(-3.596842909197555560041); // expected log_prob
}
void invalid_values(vector<size_t>& index, vector<double>& value) {
// y
// nu
index.push_back(1U);
value.push_back(0.0);
index.push_back(1U);
value.push_back(-1.0);
index.push_back(1U);
value.push_back(numeric_limits<double>::infinity());
index.push_back(1U);
value.push_back(-numeric_limits<double>::infinity());
// mu
index.push_back(2U);
value.push_back(numeric_limits<double>::infinity());
index.push_back(2U);
value.push_back(-numeric_limits<double>::infinity());
// sigma
index.push_back(3U);
value.push_back(0.0);
index.push_back(3U);
value.push_back(-1.0);
index.push_back(3U);
value.push_back(numeric_limits<double>::infinity());
index.push_back(3U);
value.push_back(-numeric_limits<double>::infinity());
}
template <class T_y, class T_dof, class T_loc, class T_scale, typename T4,
typename T5>
typename stan::return_type<T_y, T_dof, T_loc, T_scale>::type log_prob(
const T_y& y, const T_dof& nu, const T_loc& mu, const T_scale& sigma,
const T4&, const T5&) {
return stan::math::student_t_log(y, nu, mu, sigma);
}
template <bool propto, class T_y, class T_dof, class T_loc, class T_scale,
typename T4, typename T5>
typename stan::return_type<T_y, T_dof, T_loc, T_scale>::type log_prob(
const T_y& y, const T_dof& nu, const T_loc& mu, const T_scale& sigma,
const T4&, const T5&) {
return stan::math::student_t_log<propto>(y, nu, mu, sigma);
}
template <class T_y, class T_dof, class T_loc, class T_scale, typename T4,
typename T5>
typename stan::return_type<T_y, T_dof, T_loc, T_scale>::type
log_prob_function(const T_y& y, const T_dof& nu, const T_loc& mu,
const T_scale& sigma, const T4&, const T5&) {
using boost::math::lgamma;
using stan::math::LOG_SQRT_PI;
using stan::math::log1p;
using stan::math::square;
using std::log;
return lgamma((nu + 1.0) / 2.0) - lgamma(nu / 2.0) - LOG_SQRT_PI
- 0.5 * log(nu) - log(sigma)
- ((nu + 1.0) / 2.0) * log1p(square(((y - mu) / sigma)) / nu);
}
};
<|endoftext|> |
<commit_before>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 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
// C++ Includes -----------------------------------
// Local Includes -----------------------------------
#include "elem.h"
#include "mesh_base.h"
#include "parallel.h"
#include "partitioner.h"
// ------------------------------------------------------------
// Partitioner implementation
void Partitioner::partition (MeshBase& mesh,
const unsigned int n)
{
// For now we don't repartition in parallel
if (!mesh.is_serial())
return;
// Set the number of partitions in the mesh
mesh.set_n_partitions()=n;
// Call the partitioning function
this->_do_partition(mesh,n);
// Set the node's processor ids
Partitioner::set_node_processor_ids(mesh);
}
void Partitioner::repartition (MeshBase& mesh,
const unsigned int n)
{
// Set the number of partitions in the mesh
mesh.set_n_partitions()=n;
// Call the partitioning function
this->_do_repartition(mesh,n);
// Set the node's processor ids
Partitioner::set_node_processor_ids(mesh);
}
void Partitioner::single_partition (MeshBase& mesh)
{
// Loop over all the elements and assign them to processor 0.
MeshBase::element_iterator elem_it = mesh.elements_begin();
const MeshBase::element_iterator elem_end = mesh.elements_end();
for ( ; elem_it != elem_end; ++elem_it)
(*elem_it)->processor_id() = 0;
// For a single partition, all the nodes are on processor 0
MeshBase::node_iterator node_it = mesh.nodes_begin();
const MeshBase::node_iterator node_end = mesh.nodes_end();
for ( ; node_it != node_end; ++node_it)
(*node_it)->processor_id() = 0;
}
void Partitioner::set_node_processor_ids(MeshBase& mesh)
{
// This function must be run on all processors at once
parallel_only();
// Unset any previously-set node processor ids
// (maybe from previous partitionings).
MeshBase::node_iterator node_it = mesh.nodes_begin();
const MeshBase::node_iterator node_end = mesh.nodes_end();
for ( ; node_it != node_end; ++node_it)
{
Node *node = *node_it;
assert(node);
node->invalidate_processor_id();
}
// Loop over all the active elements
MeshBase::element_iterator elem_it = mesh.active_elements_begin();
const MeshBase::element_iterator elem_end = mesh.active_elements_end();
for ( ; elem_it != elem_end; ++elem_it)
{
Elem* elem = *elem_it;
assert(elem);
// For each node, set the processor ID to the min of
// its current value and this Element's processor id.
for (unsigned int n=0; n<elem->n_nodes(); ++n)
elem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(),
elem->processor_id());
}
// And loop over the subactive elements, but don't reassign
// nodes that are already active on another processor.
MeshBase::element_iterator sub_it = mesh.subactive_elements_begin();
const MeshBase::element_iterator sub_end = mesh.subactive_elements_end();
for ( ; sub_it != sub_end; ++sub_it)
{
Elem* elem = *sub_it;
assert(elem);
for (unsigned int n=0; n<elem->n_nodes(); ++n)
if (elem->get_node(n)->processor_id() == DofObject::invalid_processor_id)
elem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(),
elem->processor_id());
}
// At this point, if we're in parallel, all our own processor ids
// should be correct, but ghost nodes may be incorrect. However,
// our tenative processor ids will let us know who to ask.
// Loop over all the nodes, count the ones on each processor
std::vector<unsigned int>
ghost_objects_from_proc(libMesh::n_processors(), 0);
node_it = mesh.nodes_begin();
for ( ; node_it != node_end; ++node_it)
{
Node *node = *node_it;
assert(node);
unsigned int obj_procid = node->processor_id();
assert(obj_procid != DofObject::invalid_processor_id);
ghost_objects_from_proc[obj_procid]++;
}
// Request sets to send to each processor
std::vector<std::vector<unsigned int> >
requested_ids(libMesh::n_processors());
// We know how many objects live on each processor, so reserve()
// space for each.
for (unsigned int p=0; p != libMesh::n_processors(); ++p)
if (p != libMesh::processor_id())
requested_ids[p].reserve(ghost_objects_from_proc[p]);
node_it = mesh.nodes_begin();
for ( ; node_it != node_end; ++node_it)
{
Node *node = *node_it;
requested_ids[node->processor_id()].push_back(node->id());
}
// Next set ghost object ids from other processors
for (unsigned int p=1; p != libMesh::n_processors(); ++p)
{
// Trade my requests with processor procup and procdown
unsigned int procup = (libMesh::processor_id() + p) %
libMesh::n_processors();
unsigned int procdown = (libMesh::n_processors() +
libMesh::processor_id() - p) %
libMesh::n_processors();
std::vector<unsigned int> request_to_fill;
Parallel::send_receive(procup, requested_ids[procup],
procdown, request_to_fill);
// Fill those requests
std::vector<unsigned int> new_ids(request_to_fill.size());
for (unsigned int i=0; i != request_to_fill.size(); ++i)
{
Node *node = mesh.node_ptr(request_to_fill[i]);
assert(node);
new_ids[i] = node->processor_id();
}
// Trade back the results
std::vector<unsigned int> filled_request;
Parallel::send_receive(procdown, new_ids,
procup, filled_request);
assert(filled_request.size() == requested_ids[procup].size());
// And copy the id changes we've now been informed of
for (unsigned int i=0; i != filled_request.size(); ++i)
{
Node *node = mesh.node_ptr(requested_ids[procup][i]);
assert(filled_request[i] < libMesh::n_processors());
node->processor_id(filled_request[i]);
}
}
}
<commit_msg>do not partition into more pieces than we have active elements<commit_after>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 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
// C++ Includes -----------------------------------
// Local Includes -----------------------------------
#include "elem.h"
#include "mesh_base.h"
#include "parallel.h"
#include "partitioner.h"
// ------------------------------------------------------------
// Partitioner implementation
void Partitioner::partition (MeshBase& mesh,
const unsigned int n)
{
// For now we don't repartition in parallel
if (!mesh.is_serial())
return;
// we cannot partition into more pieces than we have
// active elements!
const unsigned int n_parts =
std::min(mesh.n_active_elem(), n);
// Set the number of partitions in the mesh
mesh.set_n_partitions()=n_parts;
// Call the partitioning function
this->_do_partition(mesh,n_parts);
// Set the node's processor ids
Partitioner::set_node_processor_ids(mesh);
}
void Partitioner::repartition (MeshBase& mesh,
const unsigned int n)
{
// we cannot partition into more pieces than we have
// active elements!
const unsigned int n_parts =
std::min(mesh.n_active_elem(), n);
// Set the number of partitions in the mesh
mesh.set_n_partitions()=n_parts;
// Call the partitioning function
this->_do_repartition(mesh,n_parts);
// Set the node's processor ids
Partitioner::set_node_processor_ids(mesh);
}
void Partitioner::single_partition (MeshBase& mesh)
{
// Loop over all the elements and assign them to processor 0.
MeshBase::element_iterator elem_it = mesh.elements_begin();
const MeshBase::element_iterator elem_end = mesh.elements_end();
for ( ; elem_it != elem_end; ++elem_it)
(*elem_it)->processor_id() = 0;
// For a single partition, all the nodes are on processor 0
MeshBase::node_iterator node_it = mesh.nodes_begin();
const MeshBase::node_iterator node_end = mesh.nodes_end();
for ( ; node_it != node_end; ++node_it)
(*node_it)->processor_id() = 0;
}
void Partitioner::set_node_processor_ids(MeshBase& mesh)
{
// This function must be run on all processors at once
parallel_only();
// Unset any previously-set node processor ids
// (maybe from previous partitionings).
MeshBase::node_iterator node_it = mesh.nodes_begin();
const MeshBase::node_iterator node_end = mesh.nodes_end();
for ( ; node_it != node_end; ++node_it)
{
Node *node = *node_it;
assert(node);
node->invalidate_processor_id();
}
// Loop over all the active elements
MeshBase::element_iterator elem_it = mesh.active_elements_begin();
const MeshBase::element_iterator elem_end = mesh.active_elements_end();
for ( ; elem_it != elem_end; ++elem_it)
{
Elem* elem = *elem_it;
assert(elem);
// For each node, set the processor ID to the min of
// its current value and this Element's processor id.
for (unsigned int n=0; n<elem->n_nodes(); ++n)
elem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(),
elem->processor_id());
}
// And loop over the subactive elements, but don't reassign
// nodes that are already active on another processor.
MeshBase::element_iterator sub_it = mesh.subactive_elements_begin();
const MeshBase::element_iterator sub_end = mesh.subactive_elements_end();
for ( ; sub_it != sub_end; ++sub_it)
{
Elem* elem = *sub_it;
assert(elem);
for (unsigned int n=0; n<elem->n_nodes(); ++n)
if (elem->get_node(n)->processor_id() == DofObject::invalid_processor_id)
elem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(),
elem->processor_id());
}
// At this point, if we're in parallel, all our own processor ids
// should be correct, but ghost nodes may be incorrect. However,
// our tenative processor ids will let us know who to ask.
// Loop over all the nodes, count the ones on each processor
std::vector<unsigned int>
ghost_objects_from_proc(libMesh::n_processors(), 0);
node_it = mesh.nodes_begin();
for ( ; node_it != node_end; ++node_it)
{
Node *node = *node_it;
assert(node);
unsigned int obj_procid = node->processor_id();
assert(obj_procid != DofObject::invalid_processor_id);
ghost_objects_from_proc[obj_procid]++;
}
// Request sets to send to each processor
std::vector<std::vector<unsigned int> >
requested_ids(libMesh::n_processors());
// We know how many objects live on each processor, so reserve()
// space for each.
for (unsigned int p=0; p != libMesh::n_processors(); ++p)
if (p != libMesh::processor_id())
requested_ids[p].reserve(ghost_objects_from_proc[p]);
node_it = mesh.nodes_begin();
for ( ; node_it != node_end; ++node_it)
{
Node *node = *node_it;
requested_ids[node->processor_id()].push_back(node->id());
}
// Next set ghost object ids from other processors
for (unsigned int p=1; p != libMesh::n_processors(); ++p)
{
// Trade my requests with processor procup and procdown
unsigned int procup = (libMesh::processor_id() + p) %
libMesh::n_processors();
unsigned int procdown = (libMesh::n_processors() +
libMesh::processor_id() - p) %
libMesh::n_processors();
std::vector<unsigned int> request_to_fill;
Parallel::send_receive(procup, requested_ids[procup],
procdown, request_to_fill);
// Fill those requests
std::vector<unsigned int> new_ids(request_to_fill.size());
for (unsigned int i=0; i != request_to_fill.size(); ++i)
{
Node *node = mesh.node_ptr(request_to_fill[i]);
assert(node);
new_ids[i] = node->processor_id();
}
// Trade back the results
std::vector<unsigned int> filled_request;
Parallel::send_receive(procdown, new_ids,
procup, filled_request);
assert(filled_request.size() == requested_ids[procup].size());
// And copy the id changes we've now been informed of
for (unsigned int i=0; i != filled_request.size(); ++i)
{
Node *node = mesh.node_ptr(requested_ids[procup][i]);
assert(filled_request[i] < libMesh::n_processors());
node->processor_id(filled_request[i]);
}
}
}
<|endoftext|> |
<commit_before>#ifndef ENTT_SIGNAL_SIGH_HPP
#define ENTT_SIGNAL_SIGH_HPP
#include <algorithm>
#include <utility>
#include <vector>
#include <functional>
#include <type_traits>
#include "../config/config.h"
#include "delegate.hpp"
#include "fwd.hpp"
namespace entt {
/**
* @brief Unmanaged signal handler declaration.
*
* Primary template isn't defined on purpose. All the specializations give a
* compile-time error unless the template parameter is a function type.
*
* @tparam Function A valid function type.
* @tparam Collector Type of collector to use, if any.
*/
template<typename Function>
struct sigh;
/**
* @brief Sink implementation.
*
* Primary template isn't defined on purpose. All the specializations give a
* compile-time error unless the template parameter is a function type.
*
* @tparam Function A valid function type.
*/
template<typename Function>
class sink;
/**
* @brief Sink implementation.
*
* A sink is an opaque object used to connect listeners to signals.<br/>
* The function type for a listener is the one of the signal to which it
* belongs.
*
* The clear separation between a signal and a sink permits to store the former
* as private data member without exposing the publish functionality to the
* users of a class.
*
* @tparam Ret Return type of a function type.
* @tparam Args Types of arguments of a function type.
*/
template<typename Ret, typename... Args>
class sink<Ret(Args...)> {
/*! @brief A signal is allowed to create sinks. */
template<typename>
friend struct sigh;
sink(std::vector<delegate<Ret(Args...)>> *ref) ENTT_NOEXCEPT
: calls{ref}
{}
public:
/**
* @brief Returns false if at least a listener is connected to the sink.
* @return True if the sink has no listeners connected, false otherwise.
*/
bool empty() const ENTT_NOEXCEPT {
return calls->empty();
}
/**
* @brief Connects a free function to a signal.
*
* The signal handler performs checks to avoid multiple connections for free
* functions.
*
* @tparam Function A valid free function pointer.
*/
template<auto Function>
void connect() {
disconnect<Function>();
delegate<Ret(Args...)> delegate{};
delegate.template connect<Function>();
calls->emplace_back(std::move(delegate));
}
/**
* @brief Connects a member function or a free function with payload to a
* signal.
*
* The signal isn't responsible for the connected object or the payload.
* Users must always guarantee that the lifetime of the instance overcomes
* the one of the delegate. On the other side, the signal handler performs
* checks to avoid multiple connections for the same function.<br/>
* When used to connect a free function with payload, its signature must be
* such that the instance is the first argument before the ones used to
* define the delegate itself.
*
* @tparam Candidate Member or free function to connect to the signal.
* @tparam Type Type of class or type of payload.
* @param value_or_instance A valid pointer that fits the purpose.
*/
template<auto Candidate, typename Type>
void connect(Type *value_or_instance) {
disconnect<Candidate>(value_or_instance);
delegate<Ret(Args...)> delegate{};
delegate.template connect<Candidate>(value_or_instance);
calls->emplace_back(std::move(delegate));
}
/**
* @brief Disconnects a free function from a signal.
* @tparam Function A valid free function pointer.
*/
template<auto Function>
void disconnect() {
delegate<Ret(Args...)> delegate{};
delegate.template connect<Function>();
calls->erase(std::remove(calls->begin(), calls->end(), std::move(delegate)), calls->end());
}
/**
* @brief Disconnects a member function or a free function with payload from
* a signal.
* @tparam Candidate Member or free function to disconnect from the signal.
* @tparam Type Type of class or type of payload.
* @param value_or_instance A valid pointer that fits the purpose.
*/
template<auto Candidate, typename Type>
void disconnect(Type *value_or_instance) {
delegate<Ret(Args...)> delegate{};
delegate.template connect<Candidate>(value_or_instance);
calls->erase(std::remove_if(calls->begin(), calls->end(), [delegate](const auto &other) {
return other == delegate && other.instance() == delegate.instance();
}), calls->end());
}
/**
* @brief Disconnects member functions or free functions based on an
* instance or specific payload.
* @param value_or_instance A valid pointer that fits the purpose.
*/
void disconnect(const void *value_or_instance) {
calls->erase(std::remove_if(calls->begin(), calls->end(), [value_or_instance](const auto &delegate) {
return value_or_instance == delegate.instance();
}), calls->end());
}
/*! @brief Disconnects all the listeners from a signal. */
void disconnect() {
calls->clear();
}
private:
std::vector<delegate<Ret(Args...)>> *calls;
};
/**
* @brief Unmanaged signal handler definition.
*
* Unmanaged signal handler. It works directly with naked pointers to classes
* and pointers to member functions as well as pointers to free functions. Users
* of this class are in charge of disconnecting instances before deleting them.
*
* This class serves mainly two purposes:
*
* * Creating signals to use later to notify a bunch of listeners.
* * Collecting results from a set of functions like in a voting system.
*
* @tparam Ret Return type of a function type.
* @tparam Args Types of arguments of a function type.
*/
template<typename Ret, typename... Args>
struct sigh<Ret(Args...)> {
/*! @brief Unsigned integer type. */
using size_type = typename std::vector<delegate<Ret(Args...)>>::size_type;
/*! @brief Sink type. */
using sink_type = entt::sink<Ret(Args...)>;
/**
* @brief Instance type when it comes to connecting member functions.
* @tparam Class Type of class to which the member function belongs.
*/
template<typename Class>
using instance_type = Class *;
/**
* @brief Number of listeners connected to the signal.
* @return Number of listeners currently connected.
*/
size_type size() const ENTT_NOEXCEPT {
return calls.size();
}
/**
* @brief Returns false if at least a listener is connected to the signal.
* @return True if the signal has no listeners connected, false otherwise.
*/
bool empty() const ENTT_NOEXCEPT {
return calls.empty();
}
/**
* @brief Returns a sink object for the given signal.
*
* A sink is an opaque object used to connect listeners to signals.<br/>
* The function type for a listener is the one of the signal to which it
* belongs. The order of invocation of the listeners isn't guaranteed.
*
* @return A temporary sink object.
*/
sink_type sink() ENTT_NOEXCEPT {
return { &calls };
}
/**
* @brief Triggers a signal.
*
* All the listeners are notified. Order isn't guaranteed.
*
* @param args Arguments to use to invoke listeners.
*/
void publish(Args... args) const {
for(auto pos = calls.size(); pos; --pos) {
calls[pos-1](args...);
}
}
/**
* @brief Collects return values from the listeners.
*
* The collector must expose a call operator with the following properties:
*
* * The return type is either `void` or such that it's convertible to
* `bool`. In the second case, a true value will stop the iteration.
* * The list of parameters is empty if `Ret` is `void`, otherwise it
* contains a single element such that `Ret` is convertible to it.
*
* @tparam Func Type of collector to use, if any.
* @param func A valid function object.
* @param args Arguments to use to invoke listeners.
*/
template<typename Func>
void collect(Func func, Args... args) const {
bool stop = false;
for(auto pos = calls.size(); pos && !stop; --pos) {
if constexpr(std::is_void_v<Ret>) {
if constexpr(std::is_invocable_r_v<bool, Func>) {
calls[pos-1](args...);
stop = func();
} else {
calls[pos-1](args...);
func();
}
} else {
if constexpr(std::is_invocable_r_v<bool, Func, Ret>) {
stop = func(calls[pos-1](args...));
} else {
func(calls[pos-1](args...));
}
}
}
}
/**
* @brief Swaps listeners between the two signals.
* @param lhs A valid signal object.
* @param rhs A valid signal object.
*/
friend void swap(sigh &lhs, sigh &rhs) {
using std::swap;
swap(lhs.calls, rhs.calls);
}
private:
std::vector<delegate<Ret(Args...)>> calls;
};
}
#endif // ENTT_SIGNAL_SIGH_HPP
<commit_msg>cleanup<commit_after>#ifndef ENTT_SIGNAL_SIGH_HPP
#define ENTT_SIGNAL_SIGH_HPP
#include <algorithm>
#include <utility>
#include <vector>
#include <functional>
#include <type_traits>
#include "../config/config.h"
#include "delegate.hpp"
#include "fwd.hpp"
namespace entt {
/**
* @brief Unmanaged signal handler declaration.
*
* Primary template isn't defined on purpose. All the specializations give a
* compile-time error unless the template parameter is a function type.
*
* @tparam Function A valid function type.
*/
template<typename Function>
struct sigh;
/**
* @brief Sink implementation.
*
* Primary template isn't defined on purpose. All the specializations give a
* compile-time error unless the template parameter is a function type.
*
* @tparam Function A valid function type.
*/
template<typename Function>
class sink;
/**
* @brief Sink implementation.
*
* A sink is an opaque object used to connect listeners to signals.<br/>
* The function type for a listener is the one of the signal to which it
* belongs.
*
* The clear separation between a signal and a sink permits to store the former
* as private data member without exposing the publish functionality to the
* users of a class.
*
* @tparam Ret Return type of a function type.
* @tparam Args Types of arguments of a function type.
*/
template<typename Ret, typename... Args>
class sink<Ret(Args...)> {
/*! @brief A signal is allowed to create sinks. */
template<typename>
friend struct sigh;
sink(std::vector<delegate<Ret(Args...)>> *ref) ENTT_NOEXCEPT
: calls{ref}
{}
public:
/**
* @brief Returns false if at least a listener is connected to the sink.
* @return True if the sink has no listeners connected, false otherwise.
*/
bool empty() const ENTT_NOEXCEPT {
return calls->empty();
}
/**
* @brief Connects a free function to a signal.
*
* The signal handler performs checks to avoid multiple connections for free
* functions.
*
* @tparam Function A valid free function pointer.
*/
template<auto Function>
void connect() {
disconnect<Function>();
delegate<Ret(Args...)> delegate{};
delegate.template connect<Function>();
calls->emplace_back(std::move(delegate));
}
/**
* @brief Connects a member function or a free function with payload to a
* signal.
*
* The signal isn't responsible for the connected object or the payload.
* Users must always guarantee that the lifetime of the instance overcomes
* the one of the delegate. On the other side, the signal handler performs
* checks to avoid multiple connections for the same function.<br/>
* When used to connect a free function with payload, its signature must be
* such that the instance is the first argument before the ones used to
* define the delegate itself.
*
* @tparam Candidate Member or free function to connect to the signal.
* @tparam Type Type of class or type of payload.
* @param value_or_instance A valid pointer that fits the purpose.
*/
template<auto Candidate, typename Type>
void connect(Type *value_or_instance) {
disconnect<Candidate>(value_or_instance);
delegate<Ret(Args...)> delegate{};
delegate.template connect<Candidate>(value_or_instance);
calls->emplace_back(std::move(delegate));
}
/**
* @brief Disconnects a free function from a signal.
* @tparam Function A valid free function pointer.
*/
template<auto Function>
void disconnect() {
delegate<Ret(Args...)> delegate{};
delegate.template connect<Function>();
calls->erase(std::remove(calls->begin(), calls->end(), std::move(delegate)), calls->end());
}
/**
* @brief Disconnects a member function or a free function with payload from
* a signal.
* @tparam Candidate Member or free function to disconnect from the signal.
* @tparam Type Type of class or type of payload.
* @param value_or_instance A valid pointer that fits the purpose.
*/
template<auto Candidate, typename Type>
void disconnect(Type *value_or_instance) {
delegate<Ret(Args...)> delegate{};
delegate.template connect<Candidate>(value_or_instance);
calls->erase(std::remove_if(calls->begin(), calls->end(), [delegate](const auto &other) {
return other == delegate && other.instance() == delegate.instance();
}), calls->end());
}
/**
* @brief Disconnects member functions or free functions based on an
* instance or specific payload.
* @param value_or_instance A valid pointer that fits the purpose.
*/
void disconnect(const void *value_or_instance) {
calls->erase(std::remove_if(calls->begin(), calls->end(), [value_or_instance](const auto &delegate) {
return value_or_instance == delegate.instance();
}), calls->end());
}
/*! @brief Disconnects all the listeners from a signal. */
void disconnect() {
calls->clear();
}
private:
std::vector<delegate<Ret(Args...)>> *calls;
};
/**
* @brief Unmanaged signal handler definition.
*
* Unmanaged signal handler. It works directly with naked pointers to classes
* and pointers to member functions as well as pointers to free functions. Users
* of this class are in charge of disconnecting instances before deleting them.
*
* This class serves mainly two purposes:
*
* * Creating signals to use later to notify a bunch of listeners.
* * Collecting results from a set of functions like in a voting system.
*
* @tparam Ret Return type of a function type.
* @tparam Args Types of arguments of a function type.
*/
template<typename Ret, typename... Args>
struct sigh<Ret(Args...)> {
/*! @brief Unsigned integer type. */
using size_type = typename std::vector<delegate<Ret(Args...)>>::size_type;
/*! @brief Sink type. */
using sink_type = entt::sink<Ret(Args...)>;
/**
* @brief Instance type when it comes to connecting member functions.
* @tparam Class Type of class to which the member function belongs.
*/
template<typename Class>
using instance_type = Class *;
/**
* @brief Number of listeners connected to the signal.
* @return Number of listeners currently connected.
*/
size_type size() const ENTT_NOEXCEPT {
return calls.size();
}
/**
* @brief Returns false if at least a listener is connected to the signal.
* @return True if the signal has no listeners connected, false otherwise.
*/
bool empty() const ENTT_NOEXCEPT {
return calls.empty();
}
/**
* @brief Returns a sink object for the given signal.
*
* A sink is an opaque object used to connect listeners to signals.<br/>
* The function type for a listener is the one of the signal to which it
* belongs. The order of invocation of the listeners isn't guaranteed.
*
* @return A temporary sink object.
*/
sink_type sink() ENTT_NOEXCEPT {
return { &calls };
}
/**
* @brief Triggers a signal.
*
* All the listeners are notified. Order isn't guaranteed.
*
* @param args Arguments to use to invoke listeners.
*/
void publish(Args... args) const {
for(auto pos = calls.size(); pos; --pos) {
calls[pos-1](args...);
}
}
/**
* @brief Collects return values from the listeners.
*
* The collector must expose a call operator with the following properties:
*
* * The return type is either `void` or such that it's convertible to
* `bool`. In the second case, a true value will stop the iteration.
* * The list of parameters is empty if `Ret` is `void`, otherwise it
* contains a single element such that `Ret` is convertible to it.
*
* @tparam Func Type of collector to use, if any.
* @param func A valid function object.
* @param args Arguments to use to invoke listeners.
*/
template<typename Func>
void collect(Func func, Args... args) const {
bool stop = false;
for(auto pos = calls.size(); pos && !stop; --pos) {
if constexpr(std::is_void_v<Ret>) {
if constexpr(std::is_invocable_r_v<bool, Func>) {
calls[pos-1](args...);
stop = func();
} else {
calls[pos-1](args...);
func();
}
} else {
if constexpr(std::is_invocable_r_v<bool, Func, Ret>) {
stop = func(calls[pos-1](args...));
} else {
func(calls[pos-1](args...));
}
}
}
}
/**
* @brief Swaps listeners between the two signals.
* @param lhs A valid signal object.
* @param rhs A valid signal object.
*/
friend void swap(sigh &lhs, sigh &rhs) {
using std::swap;
swap(lhs.calls, rhs.calls);
}
private:
std::vector<delegate<Ret(Args...)>> calls;
};
}
#endif // ENTT_SIGNAL_SIGH_HPP
<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_debug.h"
static char *_FileName_ = __FILE__;
static struct hostent *host_ptr = NULL;
static char hostname[MAXHOSTNAMELEN];
static char full_hostname[MAXHOSTNAMELEN];
static unsigned int ip_addr;
static int hostnames_initialized = 0;
static void init_hostnames();
// Return our hostname in a static data buffer.
char *
my_hostname()
{
if( ! hostnames_initialized ) {
init_hostnames();
}
return hostname;
}
// Return our full hostname (with domain) in a static data buffer.
char*
my_full_hostname()
{
if( ! hostnames_initialized ) {
init_hostnames();
}
return full_hostname;
}
// Return the host-ordered, unsigned int version of our hostname.
unsigned int
my_ip_addr()
{
if( ! hostnames_initialized ) {
init_hostnames();
}
return ip_addr;
}
void
init_hostnames()
{
char* tmp;
// Get our local hostname, and strip off the domain if
// gethostname returns it.
if( gethostname(hostname, sizeof(hostname)) == 0 ) {
tmp = strchr( hostname, '.' );
if( tmp ) {
*tmp = '\0';
}
} else {
EXCEPT( "gethostname failed, errno = %d",
#ifndef WIN32
errno );
#else
WSAGetLastError() );
#endif
}
// Look up our official host information
if( (host_ptr = gethostbyname(hostname)) == NULL ) {
EXCEPT( "gethostbyname(%s) failed, errno = %d", hostname, errno );
}
// Grab our ip_addr and fully qualified hostname
memcpy( &ip_addr, host_ptr->h_addr, (size_t)host_ptr->h_length );
ip_addr = ntohl( ip_addr );
strcpy( full_hostname, host_ptr->h_name );
hostnames_initialized = TRUE;
}
<commit_msg>+ We now malloc the space we need instead of using fixed length buffers. + We're much smarter about finding my_full_hostname, even in the face of misconfigured machines. If it's not where it should be, we search through the host aliases, and even call res_init() to find the default domain name that the resolver thinks it should use. Ideally, we'd do an inverse query to DNS to be sure.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_debug.h"
static char *_FileName_ = __FILE__;
static struct hostent *host_ptr = NULL;
static char* hostname = NULL;
static char* full_hostname = NULL;
static unsigned int ip_addr;
static int hostnames_initialized = 0;
static void init_hostnames();
extern "C" {
// Return our hostname in a static data buffer.
char *
my_hostname()
{
if( ! hostnames_initialized ) {
init_hostnames();
}
return hostname;
}
// Return our full hostname (with domain) in a static data buffer.
char*
my_full_hostname()
{
if( ! hostnames_initialized ) {
init_hostnames();
}
return full_hostname;
}
// Return the host-ordered, unsigned int version of our hostname.
unsigned int
my_ip_addr()
{
if( ! hostnames_initialized ) {
init_hostnames();
}
return ip_addr;
}
} /* extern "C" */
#if !defined(WIN32)
#include <arpa/nameser.h>
#include <resolv.h>
#endif
void
init_hostnames()
{
char *tmp, hostbuf[MAXHOSTNAMELEN];
int i;
if( hostname ) {
free( hostname );
}
if( full_hostname ) {
free( full_hostname );
full_hostname = NULL;
}
// Get our local hostname, and strip off the domain if
// gethostname returns it.
if( gethostname(hostbuf, sizeof(hostbuf)) == 0 ) {
if( (tmp = strchr(hostbuf, '.')) ) {
// There's a '.' in the hostname, assume we've got the
// full hostname here, save it, and trim the domain
// off and save that as the hostname.
full_hostname = strdup( hostbuf );
*tmp = '\0';
}
hostname = strdup( hostbuf );
} else {
EXCEPT( "gethostname failed, errno = %d",
#ifndef WIN32
errno );
#else
WSAGetLastError() );
#endif
}
// Look up our official host information
if( (host_ptr = gethostbyname(hostbuf)) == NULL ) {
EXCEPT( "gethostbyname(%s) failed, errno = %d", hostbuf, errno );
}
// Grab our ip_addr
memcpy( &ip_addr, host_ptr->h_addr, (size_t)host_ptr->h_length );
ip_addr = ntohl( ip_addr );
// If we don't have our full_hostname yet, try to find it.
if( ! full_hostname ) {
// See if it's correct in the hostent we've got.
if( (tmp = strchr(host_ptr->h_name, '.')) ) {
// There's a '.' in the "name", use that as full.
full_hostname = strdup( host_ptr->h_name );
}
}
if( ! full_hostname ) {
// We still haven't found it yet, try all the aliases
// until we find one with a '.'
for( i=0; host_ptr->h_aliases[i], !full_hostname; i++ ) {
if( (tmp = strchr(host_ptr->h_aliases[i], '.')) ) {
full_hostname = strdup( host_ptr->h_aliases[i] );
}
}
}
#if !defined( WIN32 ) /* I'm not sure how to do this on NT */
if( ! full_hostname ) {
// We still haven't found it yet, try to use the
// resolver. *sigh*
res_init();
if( _res.defdname ) {
// We know our default domain name, append that.
strcat( hostbuf, "." );
strcat( hostbuf, _res.defdname );
full_hostname = strdup( hostbuf );
}
}
#endif /* WIN32 */
if( ! full_hostname ) {
// Still can't find it, just give up.
full_hostname = strdup( hostname );
}
hostnames_initialized = TRUE;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/platform_thread.h"
#include "webrtc/base/atomicops.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/base/trace_event.h"
#if defined(WEBRTC_LINUX)
#include <sys/prctl.h>
#include <sys/syscall.h>
#endif
namespace rtc {
PlatformThreadId CurrentThreadId() {
PlatformThreadId ret;
#if defined(WEBRTC_WIN)
ret = GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
ret = pthread_mach_thread_np(pthread_self());
#elif defined(WEBRTC_LINUX)
ret = syscall(__NR_gettid);
#elif defined(WEBRTC_ANDROID)
ret = gettid();
#else
// Default implementation for nacl and solaris.
ret = reinterpret_cast<pid_t>(pthread_self());
#endif
#endif // defined(WEBRTC_POSIX)
RTC_DCHECK(ret);
return ret;
}
PlatformThreadRef CurrentThreadRef() {
#if defined(WEBRTC_WIN)
return GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
return pthread_self();
#endif
}
bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
#if defined(WEBRTC_WIN)
return a == b;
#elif defined(WEBRTC_POSIX)
return pthread_equal(a, b);
#endif
}
void SetCurrentThreadName(const char* name) {
#if defined(WEBRTC_WIN)
struct {
DWORD dwType;
LPCSTR szName;
DWORD dwThreadID;
DWORD dwFlags;
} threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};
__try {
::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
reinterpret_cast<ULONG_PTR*>(&threadname_info));
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
pthread_setname_np(name);
#endif
}
namespace {
#if defined(WEBRTC_WIN)
void CALLBACK RaiseFlag(ULONG_PTR param) {
*reinterpret_cast<bool*>(param) = true;
}
#else
struct ThreadAttributes {
ThreadAttributes() { pthread_attr_init(&attr); }
~ThreadAttributes() { pthread_attr_destroy(&attr); }
pthread_attr_t* operator&() { return &attr; }
pthread_attr_t attr;
};
#endif // defined(WEBRTC_WIN)
}
PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
void* obj,
const char* thread_name)
: run_function_deprecated_(func),
obj_(obj),
name_(thread_name ? thread_name : "webrtc") {
RTC_DCHECK(func);
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::PlatformThread(ThreadRunFunction func,
void* obj,
const char* thread_name,
ThreadPriority priority /*= kNormalPriority*/)
: run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
RTC_DCHECK(func);
RTC_DCHECK(!name_.empty());
// TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::~PlatformThread() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
RTC_DCHECK(!thread_);
RTC_DCHECK(!thread_id_);
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
DWORD WINAPI PlatformThread::StartThread(void* param) {
// The GetLastError() function only returns valid results when it is called
// after a Win32 API function that returns a "failed" result. A crash dump
// contains the result from GetLastError() and to make sure it does not
// falsely report a Windows error we call SetLastError here.
::SetLastError(ERROR_SUCCESS);
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#else
void* PlatformThread::StartThread(void* param) {
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#endif // defined(WEBRTC_WIN)
void PlatformThread::Start() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(!thread_) << "Thread already started?";
#if defined(WEBRTC_WIN)
stop_ = false;
// See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
// Set the reserved stack stack size to 1M, which is the default on Windows
// and Linux.
thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
RTC_CHECK(thread_) << "CreateThread failed";
RTC_DCHECK(thread_id_);
#else
ThreadAttributes attr;
// Set the stack stack size to 1M.
pthread_attr_setstacksize(&attr, 1024 * 1024);
RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::IsRunning() const {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
return thread_ != nullptr;
#else
return thread_ != 0;
#endif // defined(WEBRTC_WIN)
}
PlatformThreadRef PlatformThread::GetThreadRef() const {
#if defined(WEBRTC_WIN)
return thread_id_;
#else
return thread_;
#endif // defined(WEBRTC_WIN)
}
void PlatformThread::Stop() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
if (!IsRunning())
return;
#if defined(WEBRTC_WIN)
// Set stop_ to |true| on the worker thread.
bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
// Queuing the APC can fail if the thread is being terminated.
RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
WaitForSingleObject(thread_, INFINITE);
CloseHandle(thread_);
thread_ = nullptr;
thread_id_ = 0;
#else
if (!run_function_)
RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
if (!run_function_)
AtomicOps::ReleaseStore(&stop_flag_, 0);
thread_ = 0;
#endif // defined(WEBRTC_WIN)
spawned_thread_checker_.DetachFromThread();
}
// TODO(tommi): Deprecate the loop behavior in PlatformThread.
// * Introduce a new callback type that returns void.
// * Remove potential for a busy loop in PlatformThread.
// * Delegate the responsibility for how to stop the thread, to the
// implementation that actually uses the thread.
// All implementations will need to be aware of how the thread should be stopped
// and encouraging a busy polling loop, can be costly in terms of power and cpu.
void PlatformThread::Run() {
// Attach the worker thread checker to this thread.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
rtc::SetCurrentThreadName(name_.c_str());
if (run_function_) {
SetPriority(priority_);
run_function_(obj_);
return;
}
// TODO(tommi): Delete the rest of this function when looping isn't supported.
#if RTC_DCHECK_IS_ON
// These constants control the busy loop detection algorithm below.
// |kMaxLoopCount| controls the limit for how many times we allow the loop
// to run within a period, before DCHECKing.
// |kPeriodToMeasureMs| controls how long that period is.
static const int kMaxLoopCount = 1000;
static const int kPeriodToMeasureMs = 100;
int64_t loop_stamps[kMaxLoopCount] = {};
int64_t sequence_nr = 0;
#endif
do {
TRACE_EVENT1("webrtc", "PlatformThread::Run", "name", name_.c_str());
// The interface contract of Start/Stop is that for a successful call to
// Start, there should be at least one call to the run function. So we
// call the function before checking |stop_|.
if (!run_function_deprecated_(obj_))
break;
#if RTC_DCHECK_IS_ON
auto id = sequence_nr % kMaxLoopCount;
loop_stamps[id] = rtc::TimeMillis();
if (sequence_nr > kMaxLoopCount) {
auto compare_id = (id + 1) % kMaxLoopCount;
auto diff = loop_stamps[id] - loop_stamps[compare_id];
RTC_DCHECK_GE(diff, 0);
if (diff < kPeriodToMeasureMs) {
RTC_NOTREACHED() << "This thread is too busy: " << name_ << " " << diff
<< "ms sequence=" << sequence_nr << " "
<< loop_stamps[id] << " vs " << loop_stamps[compare_id]
<< ", " << id << " vs " << compare_id;
}
}
++sequence_nr;
#endif
#if defined(WEBRTC_WIN)
// Alertable sleep to permit RaiseFlag to run and update |stop_|.
SleepEx(0, true);
} while (!stop_);
#else
#if defined(WEBRTC_MAC)
sched_yield();
#else
static const struct timespec ts_null = {0};
nanosleep(&ts_null, nullptr);
#endif
} while (!AtomicOps::AcquireLoad(&stop_flag_));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::SetPriority(ThreadPriority priority) {
#if RTC_DCHECK_IS_ON
if (run_function_) {
// The non-deprecated way of how this function gets called, is that it must
// be called on the worker thread itself.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
} else {
// In the case of deprecated use of this method, it must be called on the
// same thread as the PlatformThread object is constructed on.
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
}
#endif
#if defined(WEBRTC_WIN)
return SetThreadPriority(thread_, priority) != FALSE;
#elif defined(__native_client__)
// Setting thread priorities is not supported in NaCl.
return true;
#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
// TODO(tommi): Switch to the same mechanism as Chromium uses for changing
// thread priorities.
return true;
#else
#ifdef WEBRTC_THREAD_RR
const int policy = SCHED_RR;
#else
const int policy = SCHED_FIFO;
#endif
const int min_prio = sched_get_priority_min(policy);
const int max_prio = sched_get_priority_max(policy);
if (min_prio == -1 || max_prio == -1) {
return false;
}
if (max_prio - min_prio <= 2)
return false;
// Convert webrtc priority to system priorities:
sched_param param;
const int top_prio = max_prio - 1;
const int low_prio = min_prio + 1;
switch (priority) {
case kLowPriority:
param.sched_priority = low_prio;
break;
case kNormalPriority:
// The -1 ensures that the kHighPriority is always greater or equal to
// kNormalPriority.
param.sched_priority = (low_prio + top_prio - 1) / 2;
break;
case kHighPriority:
param.sched_priority = std::max(top_prio - 2, low_prio);
break;
case kHighestPriority:
param.sched_priority = std::max(top_prio - 1, low_prio);
break;
case kRealtimePriority:
param.sched_priority = top_prio;
break;
}
return pthread_setschedparam(thread_, policy, ¶m) == 0;
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
return QueueUserAPC(function, thread_, data) != FALSE;
}
#endif
} // namespace rtc
<commit_msg>Add a missing DCHECK to PlatformThread::SetPriority. This DCHECK is for the 'new and improved' way of setting thread priority. What could happen is that code that's migrating over to the new method might still have a lingering SetPriority call, that could incorrectly bind the 'spawned_thread_checker_' to the construction thread.<commit_after>/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/platform_thread.h"
#include "webrtc/base/atomicops.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/base/trace_event.h"
#if defined(WEBRTC_LINUX)
#include <sys/prctl.h>
#include <sys/syscall.h>
#endif
namespace rtc {
PlatformThreadId CurrentThreadId() {
PlatformThreadId ret;
#if defined(WEBRTC_WIN)
ret = GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
ret = pthread_mach_thread_np(pthread_self());
#elif defined(WEBRTC_LINUX)
ret = syscall(__NR_gettid);
#elif defined(WEBRTC_ANDROID)
ret = gettid();
#else
// Default implementation for nacl and solaris.
ret = reinterpret_cast<pid_t>(pthread_self());
#endif
#endif // defined(WEBRTC_POSIX)
RTC_DCHECK(ret);
return ret;
}
PlatformThreadRef CurrentThreadRef() {
#if defined(WEBRTC_WIN)
return GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
return pthread_self();
#endif
}
bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
#if defined(WEBRTC_WIN)
return a == b;
#elif defined(WEBRTC_POSIX)
return pthread_equal(a, b);
#endif
}
void SetCurrentThreadName(const char* name) {
#if defined(WEBRTC_WIN)
struct {
DWORD dwType;
LPCSTR szName;
DWORD dwThreadID;
DWORD dwFlags;
} threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};
__try {
::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
reinterpret_cast<ULONG_PTR*>(&threadname_info));
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
pthread_setname_np(name);
#endif
}
namespace {
#if defined(WEBRTC_WIN)
void CALLBACK RaiseFlag(ULONG_PTR param) {
*reinterpret_cast<bool*>(param) = true;
}
#else
struct ThreadAttributes {
ThreadAttributes() { pthread_attr_init(&attr); }
~ThreadAttributes() { pthread_attr_destroy(&attr); }
pthread_attr_t* operator&() { return &attr; }
pthread_attr_t attr;
};
#endif // defined(WEBRTC_WIN)
}
PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
void* obj,
const char* thread_name)
: run_function_deprecated_(func),
obj_(obj),
name_(thread_name ? thread_name : "webrtc") {
RTC_DCHECK(func);
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::PlatformThread(ThreadRunFunction func,
void* obj,
const char* thread_name,
ThreadPriority priority /*= kNormalPriority*/)
: run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
RTC_DCHECK(func);
RTC_DCHECK(!name_.empty());
// TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::~PlatformThread() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
RTC_DCHECK(!thread_);
RTC_DCHECK(!thread_id_);
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
DWORD WINAPI PlatformThread::StartThread(void* param) {
// The GetLastError() function only returns valid results when it is called
// after a Win32 API function that returns a "failed" result. A crash dump
// contains the result from GetLastError() and to make sure it does not
// falsely report a Windows error we call SetLastError here.
::SetLastError(ERROR_SUCCESS);
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#else
void* PlatformThread::StartThread(void* param) {
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#endif // defined(WEBRTC_WIN)
void PlatformThread::Start() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(!thread_) << "Thread already started?";
#if defined(WEBRTC_WIN)
stop_ = false;
// See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
// Set the reserved stack stack size to 1M, which is the default on Windows
// and Linux.
thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
RTC_CHECK(thread_) << "CreateThread failed";
RTC_DCHECK(thread_id_);
#else
ThreadAttributes attr;
// Set the stack stack size to 1M.
pthread_attr_setstacksize(&attr, 1024 * 1024);
RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::IsRunning() const {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
return thread_ != nullptr;
#else
return thread_ != 0;
#endif // defined(WEBRTC_WIN)
}
PlatformThreadRef PlatformThread::GetThreadRef() const {
#if defined(WEBRTC_WIN)
return thread_id_;
#else
return thread_;
#endif // defined(WEBRTC_WIN)
}
void PlatformThread::Stop() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
if (!IsRunning())
return;
#if defined(WEBRTC_WIN)
// Set stop_ to |true| on the worker thread.
bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
// Queuing the APC can fail if the thread is being terminated.
RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
WaitForSingleObject(thread_, INFINITE);
CloseHandle(thread_);
thread_ = nullptr;
thread_id_ = 0;
#else
if (!run_function_)
RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
if (!run_function_)
AtomicOps::ReleaseStore(&stop_flag_, 0);
thread_ = 0;
#endif // defined(WEBRTC_WIN)
spawned_thread_checker_.DetachFromThread();
}
// TODO(tommi): Deprecate the loop behavior in PlatformThread.
// * Introduce a new callback type that returns void.
// * Remove potential for a busy loop in PlatformThread.
// * Delegate the responsibility for how to stop the thread, to the
// implementation that actually uses the thread.
// All implementations will need to be aware of how the thread should be stopped
// and encouraging a busy polling loop, can be costly in terms of power and cpu.
void PlatformThread::Run() {
// Attach the worker thread checker to this thread.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
rtc::SetCurrentThreadName(name_.c_str());
if (run_function_) {
SetPriority(priority_);
run_function_(obj_);
return;
}
// TODO(tommi): Delete the rest of this function when looping isn't supported.
#if RTC_DCHECK_IS_ON
// These constants control the busy loop detection algorithm below.
// |kMaxLoopCount| controls the limit for how many times we allow the loop
// to run within a period, before DCHECKing.
// |kPeriodToMeasureMs| controls how long that period is.
static const int kMaxLoopCount = 1000;
static const int kPeriodToMeasureMs = 100;
int64_t loop_stamps[kMaxLoopCount] = {};
int64_t sequence_nr = 0;
#endif
do {
TRACE_EVENT1("webrtc", "PlatformThread::Run", "name", name_.c_str());
// The interface contract of Start/Stop is that for a successful call to
// Start, there should be at least one call to the run function. So we
// call the function before checking |stop_|.
if (!run_function_deprecated_(obj_))
break;
#if RTC_DCHECK_IS_ON
auto id = sequence_nr % kMaxLoopCount;
loop_stamps[id] = rtc::TimeMillis();
if (sequence_nr > kMaxLoopCount) {
auto compare_id = (id + 1) % kMaxLoopCount;
auto diff = loop_stamps[id] - loop_stamps[compare_id];
RTC_DCHECK_GE(diff, 0);
if (diff < kPeriodToMeasureMs) {
RTC_NOTREACHED() << "This thread is too busy: " << name_ << " " << diff
<< "ms sequence=" << sequence_nr << " "
<< loop_stamps[id] << " vs " << loop_stamps[compare_id]
<< ", " << id << " vs " << compare_id;
}
}
++sequence_nr;
#endif
#if defined(WEBRTC_WIN)
// Alertable sleep to permit RaiseFlag to run and update |stop_|.
SleepEx(0, true);
} while (!stop_);
#else
#if defined(WEBRTC_MAC)
sched_yield();
#else
static const struct timespec ts_null = {0};
nanosleep(&ts_null, nullptr);
#endif
} while (!AtomicOps::AcquireLoad(&stop_flag_));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::SetPriority(ThreadPriority priority) {
#if RTC_DCHECK_IS_ON
if (run_function_) {
// The non-deprecated way of how this function gets called, is that it must
// be called on the worker thread itself.
RTC_DCHECK(!thread_checker_.CalledOnValidThread());
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
} else {
// In the case of deprecated use of this method, it must be called on the
// same thread as the PlatformThread object is constructed on.
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
}
#endif
#if defined(WEBRTC_WIN)
return SetThreadPriority(thread_, priority) != FALSE;
#elif defined(__native_client__)
// Setting thread priorities is not supported in NaCl.
return true;
#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
// TODO(tommi): Switch to the same mechanism as Chromium uses for changing
// thread priorities.
return true;
#else
#ifdef WEBRTC_THREAD_RR
const int policy = SCHED_RR;
#else
const int policy = SCHED_FIFO;
#endif
const int min_prio = sched_get_priority_min(policy);
const int max_prio = sched_get_priority_max(policy);
if (min_prio == -1 || max_prio == -1) {
return false;
}
if (max_prio - min_prio <= 2)
return false;
// Convert webrtc priority to system priorities:
sched_param param;
const int top_prio = max_prio - 1;
const int low_prio = min_prio + 1;
switch (priority) {
case kLowPriority:
param.sched_priority = low_prio;
break;
case kNormalPriority:
// The -1 ensures that the kHighPriority is always greater or equal to
// kNormalPriority.
param.sched_priority = (low_prio + top_prio - 1) / 2;
break;
case kHighPriority:
param.sched_priority = std::max(top_prio - 2, low_prio);
break;
case kHighestPriority:
param.sched_priority = std::max(top_prio - 1, low_prio);
break;
case kRealtimePriority:
param.sched_priority = top_prio;
break;
}
return pthread_setschedparam(thread_, policy, ¶m) == 0;
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
return QueueUserAPC(function, thread_, data) != FALSE;
}
#endif
} // namespace rtc
<|endoftext|> |
<commit_before>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* synexts/lang_item.cpp
* - Binds language items to #[lang_item] tagged items
*/
#include <synext.hpp>
#include "../common.hpp"
#include "../ast/ast.hpp"
#include "../ast/crate.hpp"
void handle_lang_item(const Span& sp, AST::Crate& crate, const AST::Path& path, const ::std::string& name, AST::eItemType type)
{
if(name == "phantom_fn") {
// - Just save path
}
else if( name == "send" ) {
// Don't care, Send is fully library in mrustc
// - Needed for `static`
}
else if( name == "sync" ) {
// Don't care, Sync is fully library in mrustc
// - Needed for `static`
}
else if( name == "sized" ) {
DEBUG("Bind 'sized' to " << path);
}
else if( name == "copy" ) {
DEBUG("Bind 'copy' to " << path);
}
// ops traits
else if( name == "drop" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "add" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "sub" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "mul" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "div" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "rem" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "neg" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "not" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitand" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitor" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitxor" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "shl" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "shr" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "add_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "sub_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "div_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "rem_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "mul_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitand_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitor_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitxor_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "shl_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "shr_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "index" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "deref" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "index_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "deref_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "fn" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "fn_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "fn_once" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "eq" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "ord" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "unsize" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "coerce_unsized" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "iterator" ) { /* mrustc just desugars? */ }
else if( name == "debug_trait" ) { /* TODO: Poke derive() with this */ }
// Structs
else if( name == "non_zero" ) { }
else if( name == "phantom_data" ) { }
else if( name == "range_full" ) { }
else if( name == "range" ) { }
else if( name == "range_from" ) { }
else if( name == "range_to" ) { }
else if( name == "unsafe_cell" ) { }
// Functions
else if( name == "panic" ) { }
else if( name == "panic_bounds_check" ) { }
else if( name == "panic_fmt" ) { }
else if( name == "str_eq" ) { }
// - builtin `box` support
else if( name == "exchange_malloc" ) { }
else if( name == "exchange_free" ) { }
else if( name == "box_free" ) { }
else if( name == "owned_box" ) { }
else {
ERROR(sp, E0000, "Unknown language item '" << name << "'");
}
auto rv = crate.m_lang_items.insert( ::std::make_pair( name, ::AST::Path(path) ) );
if( !rv.second ) {
ERROR(sp, E0000, "Duplicate definition of language item '" << name << "'");
}
}
class Decorator_LangItem:
public ExpandDecorator
{
public:
AttrStage stage() const override { return AttrStage::EarlyPost; }
void handle(const Span& sp, const AST::MetaItem& attr, AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item& i) const override
{
TU_MATCH_DEF(::AST::Item, (i), (e),
(
TODO(sp, "Unknown item type with #[lang=\""<<attr<<"\"] attached at " << path);
),
(Function,
handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_FN);
),
(Struct,
handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_STRUCT);
),
(Trait,
handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_TRAIT);
)
)
}
void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, const AST::Module& mod, AST::ImplDef& impl) const override {
const ::std::string& name = mi.string();
if( name == "i8" ) {}
else if( name == "u8" ) {}
else if( name == "i16" ) {}
else if( name == "u16" ) {}
else if( name == "i32" ) {}
else if( name == "u32" ) {}
else if( name == "i64" ) {}
else if( name == "u64" ) {}
else if( name == "isize" ) {}
else if( name == "usize" ) {}
else if( name == "const_ptr" ) {}
else if( name == "mut_ptr" ) {}
// rustc_unicode
else if( name == "char" ) {}
// collections
else if( name == "str" ) {}
else if( name == "slice" ) {}
// std - interestingly
else if( name == "f32" ) {}
else if( name == "f64" ) {}
else {
ERROR(sp, E0000, "Unknown lang item '" << name << "' on impl");
}
// TODO: Somehow annotate these impls to allow them to provide inherents?
// - mrustc is lazy and inefficient, so these don't matter :)
}
};
STATIC_DECORATOR("lang", Decorator_LangItem)
<commit_msg>Expand lang - "start"<commit_after>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* synexts/lang_item.cpp
* - Binds language items to #[lang_item] tagged items
*/
#include <synext.hpp>
#include "../common.hpp"
#include "../ast/ast.hpp"
#include "../ast/crate.hpp"
void handle_lang_item(const Span& sp, AST::Crate& crate, const AST::Path& path, const ::std::string& name, AST::eItemType type)
{
if(name == "phantom_fn") {
// - Just save path
}
else if( name == "send" ) {
// Don't care, Send is fully library in mrustc
// - Needed for `static`
}
else if( name == "sync" ) {
// Don't care, Sync is fully library in mrustc
// - Needed for `static`
}
else if( name == "sized" ) {
DEBUG("Bind 'sized' to " << path);
}
else if( name == "copy" ) {
DEBUG("Bind 'copy' to " << path);
}
// ops traits
else if( name == "drop" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "add" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "sub" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "mul" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "div" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "rem" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "neg" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "not" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitand" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitor" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitxor" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "shl" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "shr" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "add_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "sub_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "div_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "rem_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "mul_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitand_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitor_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "bitxor_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "shl_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "shr_assign" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "index" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "deref" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "index_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "deref_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "fn" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "fn_mut" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "fn_once" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "eq" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "ord" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "unsize" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "coerce_unsized" ) { DEBUG("Bind '"<<name<<"' to " << path); }
else if( name == "iterator" ) { /* mrustc just desugars? */ }
else if( name == "debug_trait" ) { /* TODO: Poke derive() with this */ }
// Structs
else if( name == "non_zero" ) { }
else if( name == "phantom_data" ) { }
else if( name == "range_full" ) { }
else if( name == "range" ) { }
else if( name == "range_from" ) { }
else if( name == "range_to" ) { }
else if( name == "unsafe_cell" ) { }
// Functions
else if( name == "panic" ) { }
else if( name == "panic_bounds_check" ) { }
else if( name == "panic_fmt" ) { }
else if( name == "str_eq" ) { }
// - builtin `box` support
else if( name == "exchange_malloc" ) { }
else if( name == "exchange_free" ) { }
else if( name == "box_free" ) { }
else if( name == "owned_box" ) { }
// - start
else if( name == "start" ) { }
else {
ERROR(sp, E0000, "Unknown language item '" << name << "'");
}
auto rv = crate.m_lang_items.insert( ::std::make_pair( name, ::AST::Path(path) ) );
if( !rv.second ) {
ERROR(sp, E0000, "Duplicate definition of language item '" << name << "' - " << rv.first->second << " and " << path);
}
}
class Decorator_LangItem:
public ExpandDecorator
{
public:
AttrStage stage() const override { return AttrStage::EarlyPost; }
void handle(const Span& sp, const AST::MetaItem& attr, AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item& i) const override
{
TU_MATCH_DEF(::AST::Item, (i), (e),
(
TODO(sp, "Unknown item type with #[lang=\""<<attr<<"\"] attached at " << path);
),
(Function,
handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_FN);
),
(Struct,
handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_STRUCT);
),
(Trait,
handle_lang_item(sp, crate, path, attr.string(), AST::ITEM_TRAIT);
)
)
}
void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, const AST::Module& mod, AST::ImplDef& impl) const override {
const ::std::string& name = mi.string();
if( name == "i8" ) {}
else if( name == "u8" ) {}
else if( name == "i16" ) {}
else if( name == "u16" ) {}
else if( name == "i32" ) {}
else if( name == "u32" ) {}
else if( name == "i64" ) {}
else if( name == "u64" ) {}
else if( name == "isize" ) {}
else if( name == "usize" ) {}
else if( name == "const_ptr" ) {}
else if( name == "mut_ptr" ) {}
// rustc_unicode
else if( name == "char" ) {}
// collections
else if( name == "str" ) {}
else if( name == "slice" ) {}
// std - interestingly
else if( name == "f32" ) {}
else if( name == "f64" ) {}
else {
ERROR(sp, E0000, "Unknown lang item '" << name << "' on impl");
}
// TODO: Somehow annotate these impls to allow them to provide inherents?
// - mrustc is lazy and inefficient, so these don't matter :)
}
};
STATIC_DECORATOR("lang", Decorator_LangItem)
<|endoftext|> |
<commit_before>#include "Sketch.h"
#include "chr/gl/draw/Sphere.h"
using namespace std;
using namespace chr;
using namespace gl;
using namespace draw;
using namespace path;
constexpr float R1 = 6;
constexpr float R2 = 300;
constexpr float TURNS = 20;
constexpr float DD1 = 1.0f;
constexpr float DD2 = 3.0f;
constexpr int NUM_SPHERES = 1000;
constexpr float SWELL_FACTOR = 0.125f;
Sketch::Sketch()
:
shader(InputSource::resource("Shader.vert"), InputSource::resource("Shader.frag"))
{}
void Sketch::setup()
{
texture = Texture::ImageRequest("checker.png")
.setFlags(image::FLAGS_RBGA)
.setFilters(GL_NEAREST, GL_NEAREST);
batch
.setShader(shader)
.setShaderColor(0.25f, 1.0f, 0.0f, 1)
.setTexture(texture);
Sphere()
.setFrontFace(CW)
.setSectorCount(20)
.setStackCount(10)
.setRadius(5)
.append(batch, Matrix());
instanceBuffer = InstanceBuffer(GL_DYNAMIC_DRAW);
spiral.setup(surface, R1, R2, TURNS, DD1, DD2, 10 * NUM_SPHERES, 10);
// ---
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
void Sketch::resize()
{
camera
.setFov(45)
.setClip(0.1f, 1000.0f)
.setWindowSize(windowInfo.size);
}
void Sketch::update()
{
spiral.update(surface, clock()->getTime(), SWELL_FACTOR);
}
void Sketch::draw()
{
glClearColor(0.4f, 0.8f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// ---
camera.getViewMatrix()
.setIdentity()
.translate(0, 0, -300)
.rotateX(115 * D2R)
.rotateY(0);
State()
.setShaderMatrix<VIEW>(camera.getViewMatrix())
.setShaderMatrix<PROJECTION>(camera.getProjectionMatrix())
.setShaderUniform("u_light_position", camera.getEyePosition())
.setShaderUniform("u_light_color", glm::vec3(1.0, 1.0, 1.0))
.setShaderUniform("u_light_intensity", 1.0f)
.setShaderUniform("u_ambient_color", glm::vec3(0, 0, 0))
.setShaderUniform("u_specular_color", glm::vec3(1, 1, 1))
.setShaderUniform("u_shininess", 25.0f)
.setShaderUniform("u_has_texture", true)
.setShaderUniform("u_has_color", true) // i.e. do not use diffuse color but vertex color instead
.apply();
threadSpiral(instanceBuffer, spiral.path, 10);
batch.flush(instanceBuffer);
State()
.setShaderMatrix<MVP>(camera.getViewProjectionMatrix())
.apply();
}
void Sketch::threadSpiral(InstanceBuffer &instanceBuffer, const FollowablePath3D &path, float spacing)
{
instanceBuffer.clearMatrices();
float offset = 0;
Matrix matrix;
for (int i = 0; i < NUM_SPHERES; i++)
{
auto value = path.offsetToValue(offset);
value.applyToMatrix(matrix);
instanceBuffer.addMatrix(matrix);
offset += spacing;
}
}
<commit_msg>TestingDynamicInstancing: Re-indenting<commit_after>#include "Sketch.h"
#include "chr/gl/draw/Sphere.h"
using namespace std;
using namespace chr;
using namespace gl;
using namespace draw;
using namespace path;
constexpr float R1 = 6;
constexpr float R2 = 300;
constexpr float TURNS = 20;
constexpr float DD1 = 1.0f;
constexpr float DD2 = 3.0f;
constexpr int NUM_SPHERES = 1000;
constexpr float SWELL_FACTOR = 0.125f;
Sketch::Sketch()
:
shader(InputSource::resource("Shader.vert"), InputSource::resource("Shader.frag"))
{}
void Sketch::setup()
{
texture = Texture::ImageRequest("checker.png")
.setFlags(image::FLAGS_RBGA)
.setFilters(GL_NEAREST, GL_NEAREST);
batch
.setShader(shader)
.setShaderColor(0.25f, 1.0f, 0.0f, 1)
.setTexture(texture);
Sphere()
.setFrontFace(CW)
.setSectorCount(20)
.setStackCount(10)
.setRadius(5)
.append(batch, Matrix());
instanceBuffer = InstanceBuffer(GL_DYNAMIC_DRAW);
spiral.setup(surface, R1, R2, TURNS, DD1, DD2, 10 * NUM_SPHERES, 10);
// ---
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
void Sketch::resize()
{
camera
.setFov(45)
.setClip(0.1f, 1000.0f)
.setWindowSize(windowInfo.size);
}
void Sketch::update()
{
spiral.update(surface, clock()->getTime(), SWELL_FACTOR);
}
void Sketch::draw()
{
glClearColor(0.4f, 0.8f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// ---
camera.getViewMatrix()
.setIdentity()
.translate(0, 0, -300)
.rotateX(115 * D2R)
.rotateY(0);
State()
.setShaderMatrix<VIEW>(camera.getViewMatrix())
.setShaderMatrix<PROJECTION>(camera.getProjectionMatrix())
.setShaderUniform("u_light_position", camera.getEyePosition())
.setShaderUniform("u_light_color", glm::vec3(1.0, 1.0, 1.0))
.setShaderUniform("u_light_intensity", 1.0f)
.setShaderUniform("u_ambient_color", glm::vec3(0, 0, 0))
.setShaderUniform("u_specular_color", glm::vec3(1, 1, 1))
.setShaderUniform("u_shininess", 25.0f)
.setShaderUniform("u_has_texture", true)
.setShaderUniform("u_has_color", true) // i.e. do not use diffuse color but vertex color instead
.apply();
threadSpiral(instanceBuffer, spiral.path, 10);
batch.flush(instanceBuffer);
State()
.setShaderMatrix<MVP>(camera.getViewProjectionMatrix())
.apply();
}
void Sketch::threadSpiral(InstanceBuffer &instanceBuffer, const FollowablePath3D &path, float spacing)
{
instanceBuffer.clearMatrices();
float offset = 0;
Matrix matrix;
for (int i = 0; i < NUM_SPHERES; i++)
{
auto value = path.offsetToValue(offset);
value.applyToMatrix(matrix);
instanceBuffer.addMatrix(matrix);
offset += spacing;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkIntensityWindowingImageFilter.h"
#include "itkRandomImageSource.h"
int itkIntensityWindowingImageFilterTest(int, char* [] )
{
std::cout << "itkIntensityWindowingImageFilterTest Start" << std::endl;
typedef itk::Image<float,3> TestInputImage;
typedef itk::Image<float,3> TestOutputImage;
TestInputImage::RegionType region;
TestInputImage::SizeType size; size.Fill(64);
TestInputImage::IndexType index; index.Fill(0);
region.SetIndex (index);
region.SetSize (size);
typedef itk::IntensityWindowingImageFilter<TestInputImage,TestOutputImage> FilterType;
FilterType::Pointer filter = FilterType::New();
// Now generate a real image
typedef itk::RandomImageSource<TestInputImage> SourceType;
SourceType::Pointer source = SourceType::New();
TestInputImage::SizeValueType randomSize[3] = {17, 8, 20};
// Set up source
source->SetSize(randomSize);
double minValue = -128.0;
double maxValue = 127.0;
source->SetMin( static_cast< TestInputImage::PixelType >( minValue ) );
source->SetMax( static_cast< TestInputImage::PixelType >( maxValue ) );
filter->SetInput(source->GetOutput());
const double desiredMinimum = -1.0;
const double desiredMaximum = 1.0;
const float windowMinimum = -50.0f;
const float windowMaximum = 50.0f;
filter->SetOutputMinimum( desiredMinimum );
filter->SetOutputMaximum( desiredMaximum );
filter->SetWindowMinimum( windowMinimum );
filter->SetWindowMaximum( windowMaximum );
std::cout << "Window minimum:maximum = " << windowMinimum << ":" << windowMaximum << ", equivalent window:level = " << filter->GetWindow() << ":" << filter->GetLevel() << std::endl;
try
{
filter->UpdateLargestPossibleRegion();
filter->SetFunctor(filter->GetFunctor());
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e;
return -1;
}
typedef itk::MinimumMaximumImageCalculator< TestOutputImage > CalculatorType;
CalculatorType::Pointer calculator = CalculatorType::New();
calculator->SetImage( filter->GetOutput() );
calculator->Compute();
const double tolerance = 1e-7;
const double obtainedMinimum = calculator->GetMinimum();
const double obtainedMaximum = calculator->GetMaximum();
if( itk::Math::abs( obtainedMinimum - desiredMinimum ) > tolerance )
{
std::cerr << "Error in minimum" << std::endl;
std::cerr << "Expected minimum = " << desiredMinimum << std::endl;
std::cerr << "Obtained minimum = " << obtainedMinimum << std::endl;
return EXIT_FAILURE;
}
if( itk::Math::abs( obtainedMaximum - desiredMaximum ) > tolerance )
{
std::cerr << "Error in maximum" << std::endl;
std::cerr << "Expected maximum = " << desiredMaximum << std::endl;
std::cerr << "Obtained maximum = " << obtainedMaximum << std::endl;
return EXIT_FAILURE;
}
const float window = 50.0f;
const float level = 50.0f;
filter->SetWindowLevel( window, level );
std::cout << "Window:level = "
<< filter->GetWindow() << ":"
<< filter->GetLevel()
<< ", equivalent window minimum:maximum = "
<< filter->GetWindowMinimum()
<< ":" << filter->GetWindowMaximum() << std::endl;
try
{
filter->UpdateLargestPossibleRegion();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e;
return -1;
}
calculator->Compute();
const double obtainedMinimum2 = calculator->GetMinimum();
const double obtainedMaximum2 = calculator->GetMaximum();
if( itk::Math::abs( obtainedMinimum2 - desiredMinimum ) > tolerance )
{
std::cerr << "Error in minimum" << std::endl;
std::cerr << "Expected minimum = " << desiredMinimum << std::endl;
std::cerr << "Obtained minimum = " << obtainedMinimum2 << std::endl;
return EXIT_FAILURE;
}
if( itk::Math::abs( obtainedMaximum2 - desiredMaximum ) > tolerance )
{
std::cerr << "Error in maximum" << std::endl;
std::cerr << "Expected maximum = " << desiredMaximum << std::endl;
std::cerr << "Obtained maximum = " << obtainedMaximum2 << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test PASSED ! " << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>STYLE: Improve the itkIntensityWindowingImageFilter test style<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkIntensityWindowingImageFilter.h"
#include "itkRandomImageSource.h"
int itkIntensityWindowingImageFilterTest(int, char* [] )
{
std::cout << "Testing itk::IntensityWindowingImageFilter class" << std::endl;
const unsigned int Dimension = 3;
typedef float PixelType;
typedef itk::Image< PixelType, Dimension > TestInputImage;
typedef itk::Image< PixelType, Dimension > TestOutputImage;
TestInputImage::RegionType region;
TestInputImage::SizeType size; size.Fill(64);
TestInputImage::IndexType index; index.Fill(0);
region.SetIndex (index);
region.SetSize (size);
typedef itk::IntensityWindowingImageFilter< TestInputImage, TestOutputImage > FilterType;
FilterType::Pointer filter = FilterType::New();
// Now generate a real image
typedef itk::RandomImageSource<TestInputImage> SourceType;
SourceType::Pointer source = SourceType::New();
TestInputImage::SizeValueType randomSize[3] = {17, 8, 20};
// Set up source
source->SetSize(randomSize);
double minValue = -128.0;
double maxValue = 127.0;
source->SetMin( static_cast< TestInputImage::PixelType >( minValue ) );
source->SetMax( static_cast< TestInputImage::PixelType >( maxValue ) );
filter->SetInput(source->GetOutput());
const double desiredMinimum = -1.0;
const double desiredMaximum = 1.0;
const float windowMinimum = -50.0f;
const float windowMaximum = 50.0f;
filter->SetOutputMinimum( desiredMinimum );
filter->SetOutputMaximum( desiredMaximum );
filter->SetWindowMinimum( windowMinimum );
filter->SetWindowMaximum( windowMaximum );
std::cout << "Window minimum:maximum = "
<< windowMinimum << ":" << windowMaximum
<< ", equivalent window:level = "
<< filter->GetWindow() << ":" << filter->GetLevel() << std::endl;
try
{
filter->UpdateLargestPossibleRegion();
filter->SetFunctor(filter->GetFunctor());
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e;
return -1;
}
typedef itk::MinimumMaximumImageCalculator< TestOutputImage > CalculatorType;
CalculatorType::Pointer calculator = CalculatorType::New();
calculator->SetImage( filter->GetOutput() );
calculator->Compute();
const double tolerance = 1e-7;
const double obtainedMinimum = calculator->GetMinimum();
const double obtainedMaximum = calculator->GetMaximum();
if( itk::Math::abs( obtainedMinimum - desiredMinimum ) > tolerance )
{
std::cerr << "Error in minimum" << std::endl;
std::cerr << "Expected minimum = " << desiredMinimum << std::endl;
std::cerr << "Obtained minimum = " << obtainedMinimum << std::endl;
return EXIT_FAILURE;
}
if( itk::Math::abs( obtainedMaximum - desiredMaximum ) > tolerance )
{
std::cerr << "Error in maximum" << std::endl;
std::cerr << "Expected maximum = " << desiredMaximum << std::endl;
std::cerr << "Obtained maximum = " << obtainedMaximum << std::endl;
return EXIT_FAILURE;
}
const float window = 50.0f;
const float level = 50.0f;
filter->SetWindowLevel( window, level );
std::cout << "Window:level = "
<< filter->GetWindow() << ":"
<< filter->GetLevel()
<< ", equivalent window minimum:maximum = "
<< filter->GetWindowMinimum()
<< ":" << filter->GetWindowMaximum() << std::endl;
try
{
filter->UpdateLargestPossibleRegion();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e;
return -1;
}
calculator->Compute();
const double obtainedMinimum2 = calculator->GetMinimum();
const double obtainedMaximum2 = calculator->GetMaximum();
if( itk::Math::abs( obtainedMinimum2 - desiredMinimum ) > tolerance )
{
std::cerr << "Error in minimum" << std::endl;
std::cerr << "Expected minimum = " << desiredMinimum << std::endl;
std::cerr << "Obtained minimum = " << obtainedMinimum2 << std::endl;
return EXIT_FAILURE;
}
if( itk::Math::abs( obtainedMaximum2 - desiredMaximum ) > tolerance )
{
std::cerr << "Error in maximum" << std::endl;
std::cerr << "Expected maximum = " << desiredMaximum << std::endl;
std::cerr << "Obtained maximum = " << obtainedMaximum2 << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test PASSED ! " << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstdlib>
#include <vector>
#include <stdexcept>
#include <functional>
#include "math/vector3.hpp"
//#include "projection.hpp"
//#include "integrator.hpp"
// this needs to be improved to be able to have different precisions
// and perhaps different color systems (if applicable)
struct color
{
float r, g, b, a;
};
// A screen raster, which holds a pixel buffer
struct Raster
{
Raster(size_t width, size_t height)
: m_width(width), m_height(height)
{
m_data.resize(m_width * m_height);
}
const color *operator[](size_t y) const
{ return &m_data[y * m_width]; }
color *operator[](size_t y)
{ return &m_data[y * m_width]; }
size_t width() const { return m_width; }
size_t height() const { return m_height; }
private:
std::vector<color> m_data;
const size_t m_width, m_height;
};
template <typename RasterTy, typename IntegratorTy>
void render(RasterTy &raster, IntegratorTy &&integrator)
{
// this is where the rendering happens:
// 1. project a camera ray for every pixel
// (according to some subpixel sampling distribution)
// 2. integrate the camera ray to assign a color
// 3. post-process as needed
// 4. output the rest
// this is just a test render
for (size_t y = 0; y < raster.height(); ++y) {
for (size_t x = 0; x < raster.width(); ++x) {
float px = ((float)x / raster.width() - 0.5f) * 2;
float py = ((float)y / raster.height() - 0.5f) * 2;
math::float3 cam_dir = normalize(math::float3(px, py, 0.5f));
math::float3 cam_pos(0, 0, 0);
math::float3 color = integrator(cam_pos, cam_dir);
raster[y][x].r = color.x;
raster[y][x].g = color.y;
raster[y][x].b = color.z;
}
}
}
<commit_msg>Resize can be replaced with constructor, more elegant.<commit_after>#pragma once
#include <cstdlib>
#include <vector>
#include <stdexcept>
#include <functional>
#include "math/vector3.hpp"
//#include "projection.hpp"
//#include "integrator.hpp"
// this needs to be improved to be able to have different precisions
// and perhaps different color systems (if applicable)
struct color
{
float r, g, b, a;
};
// A screen raster, which holds a pixel buffer
struct Raster
{
Raster(size_t width, size_t height)
: m_width(width), m_height(height), m_data(width * height)
{
}
const color *operator[](size_t y) const
{ return &m_data[y * m_width]; }
color *operator[](size_t y)
{ return &m_data[y * m_width]; }
size_t width() const { return m_width; }
size_t height() const { return m_height; }
private:
const size_t m_width, m_height;
std::vector<color> m_data;
};
template <typename RasterTy, typename IntegratorTy>
void render(RasterTy &raster, IntegratorTy &&integrator)
{
// this is where the rendering happens:
// 1. project a camera ray for every pixel
// (according to some subpixel sampling distribution)
// 2. integrate the camera ray to assign a color
// 3. post-process as needed
// 4. output the rest
// this is just a test render
for (size_t y = 0; y < raster.height(); ++y) {
for (size_t x = 0; x < raster.width(); ++x) {
float px = ((float)x / raster.width() - 0.5f) * 2;
float py = ((float)y / raster.height() - 0.5f) * 2;
math::float3 cam_dir = normalize(math::float3(px, py, 0.5f));
math::float3 cam_pos(0, 0, 0);
math::float3 color = integrator(cam_pos, cam_dir);
raster[y][x].r = color.x;
raster[y][x].g = color.y;
raster[y][x].b = color.z;
}
}
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* common headers */
#include "common.h"
/* interface headers */
#include "EvdevJoystick.h"
#ifdef HAVE_LINUX_INPUT_H
/* system headers */
#include <vector>
#include <string>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>
/* implementation headers */
#include "ErrorHandler.h"
#define test_bit(nr, addr) \
(((1UL << ((nr) & 31)) & (((const unsigned int *) addr)[(nr) >> 5])) != 0)
bool EvdevJoystick::isEvdevAvailable()
{
/* Test whether this driver should be used without actually
* loading it. Will return false if no event devices can be
* located, or if it has been specifically disabled by setting
* the environment variable BZFLAG_ENABLE_EVDEV=0
*/
char *envvar = getenv("BZFLAG_ENABLE_EVDEV");
if (envvar)
return atoi(envvar) != 0;
std::map<std::string,EvdevJoystickInfo> joysticks;
scanForJoysticks(joysticks);
return !joysticks.empty();
}
EvdevJoystick::EvdevJoystick()
{
joystickfd = 0;
currentJoystick = NULL;
ff_rumble = new struct ff_effect;
scanForJoysticks(joysticks);
}
EvdevJoystick::~EvdevJoystick()
{
initJoystick("");
delete ff_rumble;
}
void EvdevJoystick::scanForJoysticks(std::map<std::string,
EvdevJoystickInfo> &joysticks)
{
joysticks.clear();
const std::string inputdirName = "/dev/input";
DIR* inputdir = opendir(inputdirName.c_str());
if (!inputdir)
return;
struct dirent *dent;
while ((dent = readdir(inputdir))) {
EvdevJoystickInfo info;
/* Does it look like an event device? */
if (strncmp(dent->d_name, "event", 5))
continue;
/* Can we open it? */
info.filename = inputdirName + "/" + dent->d_name;
int fd = open(info.filename.c_str(), O_RDWR);
if (!fd)
continue;
/* Does it look like a joystick? */
if (!(collectJoystickBits(fd, info) && isJoystick(info))) {
close(fd);
continue;
}
/* Can we get its name? */
char jsname[128];
if (ioctl(fd, EVIOCGNAME(sizeof(jsname)-1), jsname) < 0) {
close(fd);
continue;
}
jsname[sizeof(jsname)-1] = '\0';
close(fd);
/* Yay, add it to our map.
*
* FIXME: we can't handle multiple joysticks with the same name yet.
* This could be fixed by disambiguating jsname if it already
* exists in 'joysticks', but the user would still have a hard
* time knowing which device to pick.
*/
joysticks[jsname] = info;
}
closedir(inputdir);
}
bool EvdevJoystick::collectJoystickBits(int fd, struct EvdevJoystickInfo &info)
{
/* Collect all the bitfields we're interested in from an event device
* at the given file descriptor.
*/
if (ioctl(fd, EVIOCGBIT(0, sizeof(info.evbit)), info.evbit) < 0)
return false;
if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(info.keybit)), info.keybit) < 0)
return false;
if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(info.absbit)), info.absbit) < 0)
return false;
if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(info.ffbit)), info.ffbit) < 0)
return false;
/* Collect information about our absolute axes */
int axis;
for (axis=0; axis<2; axis++) {
if (ioctl(fd, EVIOCGABS(axis + ABS_X), &info.axis_info[axis]) < 0)
return false;
}
return true;
}
bool EvdevJoystick::isJoystick(struct EvdevJoystickInfo &info)
{
/* Look at the capability bitfields in the given EvdevJoystickInfo, and
* decide whether the device is indeed a joystick. This uses the same criteria
* that SDL does- it at least needs X and Y axes, and one joystick-like button.
*/
if (!test_bit(EV_KEY, info.evbit))
return false;
if (!(test_bit(BTN_TRIGGER, info.keybit) ||
test_bit(BTN_A, info.keybit) ||
test_bit(BTN_1, info.keybit)))
return false;
if (!test_bit(EV_ABS, info.evbit))
return false;
if (!(test_bit(ABS_X, info.absbit) &&
test_bit(ABS_Y, info.absbit)))
return false;
return true;
}
void EvdevJoystick::initJoystick(const char* joystickName)
{
/* Close the previous joystick */
ffResetRumble();
if (joystickfd > 0)
close(joystickfd);
currentJoystick = NULL;
joystickfd = 0;
if (!strcmp(joystickName, "off") || !strcmp(joystickName, "")) {
/* No joystick configured, we're done */
return;
}
std::map<std::string,EvdevJoystickInfo>::iterator iter;
iter = joysticks.find(joystickName);
if (iter == joysticks.end()) {
printError("The selected joystick no longer exists.");
return;
}
/* Looks like we might have a valid joystick, try to open it */
EvdevJoystickInfo *info = &iter->second;
joystickfd = open(info->filename.c_str(), O_RDWR | O_NONBLOCK);
if (joystickfd > 0) {
/* Yay, it worked */
currentJoystick = info;
}
else {
printError("Error opening the selected joystick.");
}
buttons = 0;
}
bool EvdevJoystick::joystick() const
{
return currentJoystick != NULL;
}
void EvdevJoystick::poll()
{
/* Read as many input events as are available, and update our current state
*/
struct input_event ev;
while (read(joystickfd, &ev, sizeof(ev)) > 0) {
switch (ev.type) {
case EV_ABS:
switch (ev.code) {
case ABS_X: currentJoystick->axis_info[0].value = ev.value; break;
case ABS_Y: currentJoystick->axis_info[1].value = ev.value; break;
}
break;
case EV_KEY:
setButton(mapButton(ev.code), ev.value);
break;
}
}
}
int EvdevJoystick::mapButton(int bit_num)
{
/* Given an evdev button number, map it back to a small integer that most
* people would consider the button's actual number. This also ensures
* that we can fit all buttons in "buttons" as long as the number of buttons
* is less than the architecture's word size ;)
*
* We just scan through the joystick's keybits, counting how many
* set bits we encounter before this one. If the indicated bit isn't
* set in keybits, this is a bad event and we return -1.
* If this linear scan becomes a noticeable performance drain, this could
* easily be precomputed and stored in an std:map.
*/
int i;
int button_num = 0;
const int total_bits = sizeof(currentJoystick->keybit)*sizeof(unsigned long)*8;
for (i=0; i<total_bits; i++) {
if (i == bit_num)
return button_num;
if (test_bit(i, currentJoystick->keybit))
button_num++;
}
return -1;
}
void EvdevJoystick::setButton(int button_num, int state)
{
if (button_num >= 0) {
int mask = 1<<button_num;
if (state)
buttons |= mask;
else
buttons &= ~mask;
}
}
void EvdevJoystick::getJoy(int& x, int& y)
{
if (currentJoystick) {
poll();
int axes[2];
int axis;
int value;
for (axis=0; axis<2; axis++) {
/* Each axis gets scaled from evdev's reported minimum
* and maximum into bzflag's [-1000, 1000] range.
*/
value = currentJoystick->axis_info[axis].value;
value -= currentJoystick->axis_info[axis].minimum;
value = value * 2000 / (currentJoystick->axis_info[axis].maximum -
currentJoystick->axis_info[axis].minimum);
value -= 1000;
/* No cheating by modifying joystick drivers, or using some that rate
* their maximum and minimum conservatively like the input spec allows.
*/
if (value < -1000) value = -1000;
if (value > 1000) value = 1000;
/* All the cool kids are doing it... */
value = (value * abs(value)) / 1000;
axes[axis] = value;
}
x = axes[0];
y = axes[1];
}
else {
x = y = 0;
}
}
unsigned long EvdevJoystick::getJoyButtons()
{
if (currentJoystick) {
poll();
return buttons;
}
else {
return 0;
}
}
void EvdevJoystick::getJoyDevices(std::vector<std::string>
&list) const
{
std::map<std::string,EvdevJoystickInfo>::const_iterator i;
for (i = joysticks.begin(); i != joysticks.end(); ++i)
list.push_back(i->first);
}
bool EvdevJoystick::ffHasRumble() const
{
#ifdef HAVE_FF_EFFECT_RUMBLE
if (!currentJoystick)
return false;
else
return test_bit(EV_FF, currentJoystick->evbit) &&
test_bit(FF_RUMBLE, currentJoystick->ffbit);
#else
return false;
#endif
}
void EvdevJoystick::ffResetRumble()
{
#ifdef HAVE_FF_EFFECT_RUMBLE
/* Erase old effects before closing a device,
* if we had any, then initialize the ff_rumble struct.
*/
if (ffHasRumble() && ff_rumble->id != -1) {
/* Stop the effect first */
struct input_event event;
event.type = EV_FF;
event.code = ff_rumble->id;
event.value = 0;
write(joystickfd, &event, sizeof(event));
/* Erase the downloaded effect */
ioctl(joystickfd, EVIOCRMFF, ff_rumble->id);
}
/* Reinit the ff_rumble struct. It starts out with
* an id of -1, prompting the driver to assign us one.
* Once that happens, we stick with the same effect slot
* as long as we have the device open.
*/
memset(ff_rumble, 0, sizeof(*ff_rumble));
ff_rumble->type = FF_RUMBLE;
ff_rumble->id = -1;
#endif
}
#ifdef HAVE_FF_EFFECT_RUMBLE
void EvdevJoystick::ffRumble(int count,
float delay, float duration,
float strong_motor,
float weak_motor)
{
if (!ffHasRumble())
return;
/* Stop the previous effect we were playing, if any */
if (ff_rumble->id != -1) {
struct input_event event;
event.type = EV_FF;
event.code = ff_rumble->id;
event.value = 0;
write(joystickfd, &event, sizeof(event));
}
if (count > 0) {
/* Download an updated effect */
ff_rumble->u.rumble.strong_magnitude = (int) (0xFFFF * strong_motor + 0.5);
ff_rumble->u.rumble.weak_magnitude = (int) (0xFFFF * weak_motor + 0.5);
ff_rumble->replay.length = (int) (duration * 1000 + 0.5);
ff_rumble->replay.delay = (int) (delay * 1000 + 0.5);
ioctl(joystickfd, EVIOCSFF, ff_rumble);
/* Play it the indicated number of times */
struct input_event event;
event.type = EV_FF;
event.code = ff_rumble->id;
event.value = count;
write(joystickfd, &event, sizeof(event));
}
}
#else
void EvdevJoystick::ffRumble(int, float, float, float, float)
{
}
#endif
#endif /* HAVE_LINUX_INPUT_H */
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Some event driver are bugged, so prefer disabling it via BZDB forever<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* common headers */
#include "common.h"
/* interface headers */
#include "EvdevJoystick.h"
#ifdef HAVE_LINUX_INPUT_H
/* system headers */
#include <vector>
#include <string>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>
/* implementation headers */
#include "ErrorHandler.h"
#include "StateDatabase.h"
#define test_bit(nr, addr) \
(((1UL << ((nr) & 31)) & (((const unsigned int *) addr)[(nr) >> 5])) != 0)
bool EvdevJoystick::isEvdevAvailable()
{
/* Test whether this driver should be used without actually
* loading it. Will return false if no event devices can be
* located, or if it has been specifically disabled by setting
* the environment variable BZFLAG_ENABLE_EVDEV=0
*/
if (BZDB.isSet("enable_evdev") && !BZDB.isTrue("enable_evdev"))
return false;
std::map<std::string,EvdevJoystickInfo> joysticks;
scanForJoysticks(joysticks);
return !joysticks.empty();
}
EvdevJoystick::EvdevJoystick()
{
joystickfd = 0;
currentJoystick = NULL;
ff_rumble = new struct ff_effect;
scanForJoysticks(joysticks);
}
EvdevJoystick::~EvdevJoystick()
{
initJoystick("");
delete ff_rumble;
}
void EvdevJoystick::scanForJoysticks(std::map<std::string,
EvdevJoystickInfo> &joysticks)
{
joysticks.clear();
const std::string inputdirName = "/dev/input";
DIR* inputdir = opendir(inputdirName.c_str());
if (!inputdir)
return;
struct dirent *dent;
while ((dent = readdir(inputdir))) {
EvdevJoystickInfo info;
/* Does it look like an event device? */
if (strncmp(dent->d_name, "event", 5))
continue;
/* Can we open it? */
info.filename = inputdirName + "/" + dent->d_name;
int fd = open(info.filename.c_str(), O_RDWR);
if (!fd)
continue;
/* Does it look like a joystick? */
if (!(collectJoystickBits(fd, info) && isJoystick(info))) {
close(fd);
continue;
}
/* Can we get its name? */
char jsname[128];
if (ioctl(fd, EVIOCGNAME(sizeof(jsname)-1), jsname) < 0) {
close(fd);
continue;
}
jsname[sizeof(jsname)-1] = '\0';
close(fd);
/* Yay, add it to our map.
*
* FIXME: we can't handle multiple joysticks with the same name yet.
* This could be fixed by disambiguating jsname if it already
* exists in 'joysticks', but the user would still have a hard
* time knowing which device to pick.
*/
joysticks[jsname] = info;
}
closedir(inputdir);
}
bool EvdevJoystick::collectJoystickBits(int fd, struct EvdevJoystickInfo &info)
{
/* Collect all the bitfields we're interested in from an event device
* at the given file descriptor.
*/
if (ioctl(fd, EVIOCGBIT(0, sizeof(info.evbit)), info.evbit) < 0)
return false;
if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(info.keybit)), info.keybit) < 0)
return false;
if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(info.absbit)), info.absbit) < 0)
return false;
if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(info.ffbit)), info.ffbit) < 0)
return false;
/* Collect information about our absolute axes */
int axis;
for (axis=0; axis<2; axis++) {
if (ioctl(fd, EVIOCGABS(axis + ABS_X), &info.axis_info[axis]) < 0)
return false;
}
return true;
}
bool EvdevJoystick::isJoystick(struct EvdevJoystickInfo &info)
{
/* Look at the capability bitfields in the given EvdevJoystickInfo, and
* decide whether the device is indeed a joystick. This uses the same criteria
* that SDL does- it at least needs X and Y axes, and one joystick-like button.
*/
if (!test_bit(EV_KEY, info.evbit))
return false;
if (!(test_bit(BTN_TRIGGER, info.keybit) ||
test_bit(BTN_A, info.keybit) ||
test_bit(BTN_1, info.keybit)))
return false;
if (!test_bit(EV_ABS, info.evbit))
return false;
if (!(test_bit(ABS_X, info.absbit) &&
test_bit(ABS_Y, info.absbit)))
return false;
return true;
}
void EvdevJoystick::initJoystick(const char* joystickName)
{
/* Close the previous joystick */
ffResetRumble();
if (joystickfd > 0)
close(joystickfd);
currentJoystick = NULL;
joystickfd = 0;
if (!strcmp(joystickName, "off") || !strcmp(joystickName, "")) {
/* No joystick configured, we're done */
return;
}
std::map<std::string,EvdevJoystickInfo>::iterator iter;
iter = joysticks.find(joystickName);
if (iter == joysticks.end()) {
printError("The selected joystick no longer exists.");
return;
}
/* Looks like we might have a valid joystick, try to open it */
EvdevJoystickInfo *info = &iter->second;
joystickfd = open(info->filename.c_str(), O_RDWR | O_NONBLOCK);
if (joystickfd > 0) {
/* Yay, it worked */
currentJoystick = info;
}
else {
printError("Error opening the selected joystick.");
}
buttons = 0;
}
bool EvdevJoystick::joystick() const
{
return currentJoystick != NULL;
}
void EvdevJoystick::poll()
{
/* Read as many input events as are available, and update our current state
*/
struct input_event ev;
while (read(joystickfd, &ev, sizeof(ev)) > 0) {
switch (ev.type) {
case EV_ABS:
switch (ev.code) {
case ABS_X: currentJoystick->axis_info[0].value = ev.value; break;
case ABS_Y: currentJoystick->axis_info[1].value = ev.value; break;
}
break;
case EV_KEY:
setButton(mapButton(ev.code), ev.value);
break;
}
}
}
int EvdevJoystick::mapButton(int bit_num)
{
/* Given an evdev button number, map it back to a small integer that most
* people would consider the button's actual number. This also ensures
* that we can fit all buttons in "buttons" as long as the number of buttons
* is less than the architecture's word size ;)
*
* We just scan through the joystick's keybits, counting how many
* set bits we encounter before this one. If the indicated bit isn't
* set in keybits, this is a bad event and we return -1.
* If this linear scan becomes a noticeable performance drain, this could
* easily be precomputed and stored in an std:map.
*/
int i;
int button_num = 0;
const int total_bits = sizeof(currentJoystick->keybit)*sizeof(unsigned long)*8;
for (i=0; i<total_bits; i++) {
if (i == bit_num)
return button_num;
if (test_bit(i, currentJoystick->keybit))
button_num++;
}
return -1;
}
void EvdevJoystick::setButton(int button_num, int state)
{
if (button_num >= 0) {
int mask = 1<<button_num;
if (state)
buttons |= mask;
else
buttons &= ~mask;
}
}
void EvdevJoystick::getJoy(int& x, int& y)
{
if (currentJoystick) {
poll();
int axes[2];
int axis;
int value;
for (axis=0; axis<2; axis++) {
/* Each axis gets scaled from evdev's reported minimum
* and maximum into bzflag's [-1000, 1000] range.
*/
value = currentJoystick->axis_info[axis].value;
value -= currentJoystick->axis_info[axis].minimum;
value = value * 2000 / (currentJoystick->axis_info[axis].maximum -
currentJoystick->axis_info[axis].minimum);
value -= 1000;
/* No cheating by modifying joystick drivers, or using some that rate
* their maximum and minimum conservatively like the input spec allows.
*/
if (value < -1000) value = -1000;
if (value > 1000) value = 1000;
/* All the cool kids are doing it... */
value = (value * abs(value)) / 1000;
axes[axis] = value;
}
x = axes[0];
y = axes[1];
}
else {
x = y = 0;
}
}
unsigned long EvdevJoystick::getJoyButtons()
{
if (currentJoystick) {
poll();
return buttons;
}
else {
return 0;
}
}
void EvdevJoystick::getJoyDevices(std::vector<std::string>
&list) const
{
std::map<std::string,EvdevJoystickInfo>::const_iterator i;
for (i = joysticks.begin(); i != joysticks.end(); ++i)
list.push_back(i->first);
}
bool EvdevJoystick::ffHasRumble() const
{
#ifdef HAVE_FF_EFFECT_RUMBLE
if (!currentJoystick)
return false;
else
return test_bit(EV_FF, currentJoystick->evbit) &&
test_bit(FF_RUMBLE, currentJoystick->ffbit);
#else
return false;
#endif
}
void EvdevJoystick::ffResetRumble()
{
#ifdef HAVE_FF_EFFECT_RUMBLE
/* Erase old effects before closing a device,
* if we had any, then initialize the ff_rumble struct.
*/
if (ffHasRumble() && ff_rumble->id != -1) {
/* Stop the effect first */
struct input_event event;
event.type = EV_FF;
event.code = ff_rumble->id;
event.value = 0;
write(joystickfd, &event, sizeof(event));
/* Erase the downloaded effect */
ioctl(joystickfd, EVIOCRMFF, ff_rumble->id);
}
/* Reinit the ff_rumble struct. It starts out with
* an id of -1, prompting the driver to assign us one.
* Once that happens, we stick with the same effect slot
* as long as we have the device open.
*/
memset(ff_rumble, 0, sizeof(*ff_rumble));
ff_rumble->type = FF_RUMBLE;
ff_rumble->id = -1;
#endif
}
#ifdef HAVE_FF_EFFECT_RUMBLE
void EvdevJoystick::ffRumble(int count,
float delay, float duration,
float strong_motor,
float weak_motor)
{
if (!ffHasRumble())
return;
/* Stop the previous effect we were playing, if any */
if (ff_rumble->id != -1) {
struct input_event event;
event.type = EV_FF;
event.code = ff_rumble->id;
event.value = 0;
write(joystickfd, &event, sizeof(event));
}
if (count > 0) {
/* Download an updated effect */
ff_rumble->u.rumble.strong_magnitude = (int) (0xFFFF * strong_motor + 0.5);
ff_rumble->u.rumble.weak_magnitude = (int) (0xFFFF * weak_motor + 0.5);
ff_rumble->replay.length = (int) (duration * 1000 + 0.5);
ff_rumble->replay.delay = (int) (delay * 1000 + 0.5);
ioctl(joystickfd, EVIOCSFF, ff_rumble);
/* Play it the indicated number of times */
struct input_event event;
event.type = EV_FF;
event.code = ff_rumble->id;
event.value = count;
write(joystickfd, &event, sizeof(event));
}
}
#else
void EvdevJoystick::ffRumble(int, float, float, float, float)
{
}
#endif
#endif /* HAVE_LINUX_INPUT_H */
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "gitcommand.h"
#include "gitconstants.h"
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/synchronousprocess.h>
#include <QtCore/QDebug>
#include <QtCore/QProcess>
#include <QtCore/QFuture>
#include <QtCore/QtConcurrentRun>
#include <QtCore/QFileInfo>
#include <QtCore/QCoreApplication>
Q_DECLARE_METATYPE(QVariant)
namespace Git {
namespace Internal {
static QString msgTermination(int exitCode, const QString &binaryPath, const QStringList &args)
{
QString cmd = QFileInfo(binaryPath).baseName();
if (!args.empty()) {
cmd += QLatin1Char(' ');
cmd += args.front();
}
return exitCode ?
QCoreApplication::translate("GitCommand", "\n'%1' failed (exit code %2).\n").arg(cmd).arg(exitCode) :
QCoreApplication::translate("GitCommand", "\n'%1' completed (exit code %2).\n").arg(cmd).arg(exitCode);
}
GitCommand::Job::Job(const QStringList &a, int t) :
arguments(a),
timeout(t)
{
// Finished cookie is emitted via queued slot, needs metatype
static const int qvMetaId = qRegisterMetaType<QVariant>();
Q_UNUSED(qvMetaId)
}
GitCommand::GitCommand(const QStringList &binary,
const QString &workingDirectory,
const QStringList &environment,
const QVariant &cookie) :
m_binaryPath(binary.front()),
m_basicArguments(binary),
m_workingDirectory(workingDirectory),
m_environment(environment),
m_cookie(cookie),
m_reportTerminationMode(NoReport)
{
m_basicArguments.pop_front();
}
GitCommand::TerminationReportMode GitCommand::reportTerminationMode() const
{
return m_reportTerminationMode;
}
void GitCommand::setTerminationReportMode(TerminationReportMode m)
{
m_reportTerminationMode = m;
}
void GitCommand::addJob(const QStringList &arguments, int timeout)
{
m_jobs.push_back(Job(arguments, timeout));
}
void GitCommand::execute()
{
if (Git::Constants::debug)
qDebug() << "GitCommand::execute" << m_workingDirectory << m_jobs.size();
if (m_jobs.empty())
return;
// For some reason QtConcurrent::run() only works on this
QFuture<void> task = QtConcurrent::run(this, &GitCommand::run);
const QString taskName = QLatin1String("Git ") + m_jobs.front().arguments.at(0);
Core::ICore::instance()->progressManager()->addTask(task, taskName,
QLatin1String("Git.action"));
}
QString GitCommand::msgTimeout(int seconds)
{
return tr("Error: Git timed out after %1s.").arg(seconds);
}
void GitCommand::run()
{
if (Git::Constants::debug)
qDebug() << "GitCommand::run" << m_workingDirectory << m_jobs.size();
QProcess process;
if (!m_workingDirectory.isEmpty())
process.setWorkingDirectory(m_workingDirectory);
process.setEnvironment(m_environment);
QByteArray stdOut;
QByteArray stdErr;
QString error;
const int count = m_jobs.size();
int exitCode = -1;
bool ok = true;
for (int j = 0; j < count; j++) {
if (Git::Constants::debug)
qDebug() << "GitCommand::run" << j << '/' << count << m_jobs.at(j).arguments;
process.start(m_binaryPath, m_basicArguments + m_jobs.at(j).arguments);
if(!process.waitForStarted()) {
ok = false;
error += QString::fromLatin1("Error: \"%1\" could not be started: %2").arg(m_binaryPath, process.errorString());
break;
}
process.closeWriteChannel();
const int timeOutSeconds = m_jobs.at(j).timeout;
if (!Utils::SynchronousProcess::readDataFromProcess(process, timeOutSeconds * 1000,
&stdOut, &stdErr)) {
Utils::SynchronousProcess::stopProcess(process);
ok = false;
error += msgTimeout(timeOutSeconds);
break;
}
error += QString::fromLocal8Bit(stdErr);
exitCode = process.exitCode();
switch (m_reportTerminationMode) {
case NoReport:
break;
case ReportStdout:
stdOut += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments).toUtf8();
break;
case ReportStderr:
error += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments);
break;
}
}
// Special hack: Always produce output for diff
if (ok && stdOut.isEmpty() && m_jobs.front().arguments.at(0) == QLatin1String("diff")) {
stdOut += "The file does not differ from HEAD";
} else {
// @TODO: Remove, see below
if (ok && m_jobs.front().arguments.at(0) == QLatin1String("status"))
removeColorCodes(&stdOut);
}
if (ok && !stdOut.isEmpty())
emit outputData(stdOut);
if (!error.isEmpty())
emit errorText(error);
emit finished(ok, exitCode, m_cookie);
if (ok)
emit success();
// As it is used asynchronously, we need to delete ourselves
this->deleteLater();
}
// Clean output from carriage return and ANSI color codes.
// @TODO: Remove once all relevant commands support "--no-color",
//("status" is missing it as of git 1.6.2)
void GitCommand::removeColorCodes(QByteArray *data)
{
// Remove ansi color codes that look like "ESC[<stuff>m"
const QByteArray ansiColorEscape("\033[");
int escapePos = 0;
while (true) {
const int nextEscapePos = data->indexOf(ansiColorEscape, escapePos);
if (nextEscapePos == -1)
break;
const int endEscapePos = data->indexOf('m', nextEscapePos + ansiColorEscape.size());
if (endEscapePos != -1) {
data->remove(nextEscapePos, endEscapePos - nextEscapePos + 1);
escapePos = nextEscapePos;
} else {
escapePos = nextEscapePos + ansiColorEscape.size();
}
}
}
void GitCommand::setCookie(const QVariant &cookie)
{
m_cookie = cookie;
}
QVariant GitCommand::cookie() const
{
return m_cookie;
}
} // namespace Internal
} // namespace Git
<commit_msg>Git: Fix misleading status message.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "gitcommand.h"
#include "gitconstants.h"
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/synchronousprocess.h>
#include <QtCore/QDebug>
#include <QtCore/QProcess>
#include <QtCore/QFuture>
#include <QtCore/QtConcurrentRun>
#include <QtCore/QFileInfo>
#include <QtCore/QCoreApplication>
Q_DECLARE_METATYPE(QVariant)
namespace Git {
namespace Internal {
static QString msgTermination(int exitCode, const QString &binaryPath, const QStringList &args)
{
QString cmd = QFileInfo(binaryPath).baseName();
if (!args.empty()) {
cmd += QLatin1Char(' ');
cmd += args.front();
}
return exitCode ?
QCoreApplication::translate("GitCommand", "\n'%1' failed (exit code %2).\n").arg(cmd).arg(exitCode) :
QCoreApplication::translate("GitCommand", "\n'%1' completed (exit code %2).\n").arg(cmd).arg(exitCode);
}
GitCommand::Job::Job(const QStringList &a, int t) :
arguments(a),
timeout(t)
{
// Finished cookie is emitted via queued slot, needs metatype
static const int qvMetaId = qRegisterMetaType<QVariant>();
Q_UNUSED(qvMetaId)
}
GitCommand::GitCommand(const QStringList &binary,
const QString &workingDirectory,
const QStringList &environment,
const QVariant &cookie) :
m_binaryPath(binary.front()),
m_basicArguments(binary),
m_workingDirectory(workingDirectory),
m_environment(environment),
m_cookie(cookie),
m_reportTerminationMode(NoReport)
{
m_basicArguments.pop_front();
}
GitCommand::TerminationReportMode GitCommand::reportTerminationMode() const
{
return m_reportTerminationMode;
}
void GitCommand::setTerminationReportMode(TerminationReportMode m)
{
m_reportTerminationMode = m;
}
void GitCommand::addJob(const QStringList &arguments, int timeout)
{
m_jobs.push_back(Job(arguments, timeout));
}
void GitCommand::execute()
{
if (Git::Constants::debug)
qDebug() << "GitCommand::execute" << m_workingDirectory << m_jobs.size();
if (m_jobs.empty())
return;
// For some reason QtConcurrent::run() only works on this
QFuture<void> task = QtConcurrent::run(this, &GitCommand::run);
const QString taskName = QLatin1String("Git ") + m_jobs.front().arguments.at(0);
Core::ICore::instance()->progressManager()->addTask(task, taskName,
QLatin1String("Git.action"));
}
QString GitCommand::msgTimeout(int seconds)
{
return tr("Error: Git timed out after %1s.").arg(seconds);
}
void GitCommand::run()
{
if (Git::Constants::debug)
qDebug() << "GitCommand::run" << m_workingDirectory << m_jobs.size();
QProcess process;
if (!m_workingDirectory.isEmpty())
process.setWorkingDirectory(m_workingDirectory);
process.setEnvironment(m_environment);
QByteArray stdOut;
QByteArray stdErr;
QString error;
const int count = m_jobs.size();
int exitCode = -1;
bool ok = true;
for (int j = 0; j < count; j++) {
if (Git::Constants::debug)
qDebug() << "GitCommand::run" << j << '/' << count << m_jobs.at(j).arguments;
process.start(m_binaryPath, m_basicArguments + m_jobs.at(j).arguments);
if(!process.waitForStarted()) {
ok = false;
error += QString::fromLatin1("Error: \"%1\" could not be started: %2").arg(m_binaryPath, process.errorString());
break;
}
process.closeWriteChannel();
const int timeOutSeconds = m_jobs.at(j).timeout;
if (!Utils::SynchronousProcess::readDataFromProcess(process, timeOutSeconds * 1000,
&stdOut, &stdErr)) {
Utils::SynchronousProcess::stopProcess(process);
ok = false;
error += msgTimeout(timeOutSeconds);
break;
}
error += QString::fromLocal8Bit(stdErr);
exitCode = process.exitCode();
switch (m_reportTerminationMode) {
case NoReport:
break;
case ReportStdout:
stdOut += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments).toUtf8();
break;
case ReportStderr:
error += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments);
break;
}
}
// Special hack: Always produce output for diff
if (ok && stdOut.isEmpty() && m_jobs.front().arguments.at(0) == QLatin1String("diff")) {
stdOut += "No difference to HEAD";
} else {
// @TODO: Remove, see below
if (ok && m_jobs.front().arguments.at(0) == QLatin1String("status"))
removeColorCodes(&stdOut);
}
if (ok && !stdOut.isEmpty())
emit outputData(stdOut);
if (!error.isEmpty())
emit errorText(error);
emit finished(ok, exitCode, m_cookie);
if (ok)
emit success();
// As it is used asynchronously, we need to delete ourselves
this->deleteLater();
}
// Clean output from carriage return and ANSI color codes.
// @TODO: Remove once all relevant commands support "--no-color",
//("status" is missing it as of git 1.6.2)
void GitCommand::removeColorCodes(QByteArray *data)
{
// Remove ansi color codes that look like "ESC[<stuff>m"
const QByteArray ansiColorEscape("\033[");
int escapePos = 0;
while (true) {
const int nextEscapePos = data->indexOf(ansiColorEscape, escapePos);
if (nextEscapePos == -1)
break;
const int endEscapePos = data->indexOf('m', nextEscapePos + ansiColorEscape.size());
if (endEscapePos != -1) {
data->remove(nextEscapePos, endEscapePos - nextEscapePos + 1);
escapePos = nextEscapePos;
} else {
escapePos = nextEscapePos + ansiColorEscape.size();
}
}
}
void GitCommand::setCookie(const QVariant &cookie)
{
m_cookie = cookie;
}
QVariant GitCommand::cookie() const
{
return m_cookie;
}
} // namespace Internal
} // namespace Git
<|endoftext|> |
<commit_before>#include "SkFontHost.h"
#include <math.h>
// define this to use pre-compiled tables for gamma. This is slightly faster,
// and doesn't create any RW global memory, but means we cannot change the
// gamma at runtime.
#define USE_PREDEFINED_GAMMA_TABLES
#ifndef USE_PREDEFINED_GAMMA_TABLES
// define this if you want to spew out the "C" code for the tables, given
// the current values for SK_BLACK_GAMMA and SK_WHITE_GAMMA.
#define DUMP_GAMMA_TABLESx
#endif
///////////////////////////////////////////////////////////////////////////////
#ifdef USE_PREDEFINED_GAMMA_TABLES
#include "sk_predefined_gamma.h"
#else // use writable globals for gamma tables
static bool gGammaIsBuilt;
static uint8_t gBlackGamma[256], gWhiteGamma[256];
#define SK_BLACK_GAMMA (1.4f)
#define SK_WHITE_GAMMA (1/1.4f)
static void build_power_table(uint8_t table[], float ee)
{
// printf("------ build_power_table %g\n", ee);
for (int i = 0; i < 256; i++)
{
float x = i / 255.f;
// printf(" %d %g", i, x);
x = powf(x, ee);
// printf(" %g", x);
int xx = SkScalarRound(SkFloatToScalar(x * 255));
// printf(" %d\n", xx);
table[i] = SkToU8(xx);
}
}
#ifdef DUMP_GAMMA_TABLES
#include "SkString.h"
static void dump_a_table(const char name[], const uint8_t table[],
float gamma) {
SkDebugf("\n");
SkDebugf("\/\/ Gamma table for %g\n", gamma);
SkDebugf("static const uint8_t %s[] = {\n", name);
for (int y = 0; y < 16; y++) {
SkString line, tmp;
for (int x = 0; x < 16; x++) {
tmp.printf("0x%02X, ", *table++);
line.append(tmp);
}
SkDebugf(" %s\n", line.c_str());
}
SkDebugf("};\n");
}
#endif
#endif
///////////////////////////////////////////////////////////////////////////////
void SkFontHost::GetGammaTables(const uint8_t* tables[2])
{
#ifndef USE_PREDEFINED_GAMMA_TABLES
if (!gGammaIsBuilt)
{
build_power_table(gBlackGamma, SK_BLACK_GAMMA);
build_power_table(gWhiteGamma, SK_WHITE_GAMMA);
gGammaIsBuilt = true;
#ifdef DUMP_GAMMA_TABLES
dump_a_table("gBlackGamma", gBlackGamma, SK_BLACK_GAMMA);
dump_a_table("gWhiteGamma", gWhiteGamma, SK_WHITE_GAMMA);
#endif
}
#endif
tables[0] = gBlackGamma;
tables[1] = gWhiteGamma;
}
// If the luminance is <= this value, then apply the black gamma table
#define BLACK_GAMMA_THRESHOLD 0x40
// If the luminance is >= this value, then apply the white gamma table
#define WHITE_GAMMA_THRESHOLD 0xC0
int SkFontHost::ComputeGammaFlag(const SkPaint& paint)
{
if (paint.getShader() == NULL)
{
SkColor c = paint.getColor();
int r = SkColorGetR(c);
int g = SkColorGetG(c);
int b = SkColorGetB(c);
int luminance = (r * 2 + g * 5 + b) >> 3;
if (luminance <= BLACK_GAMMA_THRESHOLD)
{
// printf("------ black gamma for [%d %d %d]\n", r, g, b);
return SkScalerContext::kGammaForBlack_Flag;
}
if (luminance >= WHITE_GAMMA_THRESHOLD)
{
// printf("------ white gamma for [%d %d %d]\n", r, g, b);
return SkScalerContext::kGammaForWhite_Flag;
}
}
return 0;
}
<commit_msg>allow the gamma to be changed at runtime<commit_after>#include "SkFontHost.h"
#include <math.h>
// define this to use pre-compiled tables for gamma. This is slightly faster,
// and doesn't create any RW global memory, but means we cannot change the
// gamma at runtime.
//#define USE_PREDEFINED_GAMMA_TABLES
#ifndef USE_PREDEFINED_GAMMA_TABLES
// define this if you want to spew out the "C" code for the tables, given
// the current values for SK_BLACK_GAMMA and SK_WHITE_GAMMA.
#define DUMP_GAMMA_TABLESx
#endif
///////////////////////////////////////////////////////////////////////////////
#include "SkGraphics.h"
// declared here, so we can link against it elsewhere
void skia_set_text_gamma(float blackGamma, float whiteGamma);
#ifdef USE_PREDEFINED_GAMMA_TABLES
#include "sk_predefined_gamma.h"
void skia_set_text_gamma(float blackGamma, float whiteGamma) {}
#else // use writable globals for gamma tables
static void build_power_table(uint8_t table[], float ee)
{
SkDebugf("------ build_power_table %g\n", ee);
for (int i = 0; i < 256; i++)
{
float x = i / 255.f;
// printf(" %d %g", i, x);
x = powf(x, ee);
// printf(" %g", x);
int xx = SkScalarRound(SkFloatToScalar(x * 255));
// printf(" %d\n", xx);
table[i] = SkToU8(xx);
}
}
static bool gGammaIsBuilt;
static uint8_t gBlackGamma[256], gWhiteGamma[256];
static float gBlackGammaCoeff = 1.4f;
static float gWhiteGammaCoeff = 1/1.4f;
void skia_set_text_gamma(float blackGamma, float whiteGamma) {
gBlackGammaCoeff = blackGamma;
gWhiteGammaCoeff = whiteGamma;
gGammaIsBuilt = false;
SkGraphics::SetFontCacheUsed(0);
build_power_table(gBlackGamma, gBlackGammaCoeff);
build_power_table(gWhiteGamma, gWhiteGammaCoeff);
}
#ifdef DUMP_GAMMA_TABLES
#include "SkString.h"
static void dump_a_table(const char name[], const uint8_t table[],
float gamma) {
SkDebugf("\n");
SkDebugf("\/\/ Gamma table for %g\n", gamma);
SkDebugf("static const uint8_t %s[] = {\n", name);
for (int y = 0; y < 16; y++) {
SkString line, tmp;
for (int x = 0; x < 16; x++) {
tmp.printf("0x%02X, ", *table++);
line.append(tmp);
}
SkDebugf(" %s\n", line.c_str());
}
SkDebugf("};\n");
}
#endif
#endif
///////////////////////////////////////////////////////////////////////////////
void SkFontHost::GetGammaTables(const uint8_t* tables[2])
{
#ifndef USE_PREDEFINED_GAMMA_TABLES
if (!gGammaIsBuilt)
{
build_power_table(gBlackGamma, gBlackGammaCoeff);
build_power_table(gWhiteGamma, gWhiteGammaCoeff);
gGammaIsBuilt = true;
#ifdef DUMP_GAMMA_TABLES
dump_a_table("gBlackGamma", gBlackGamma, gBlackGammaCoeff);
dump_a_table("gWhiteGamma", gWhiteGamma, gWhiteGammaCoeff);
#endif
}
#endif
tables[0] = gBlackGamma;
tables[1] = gWhiteGamma;
}
// If the luminance is <= this value, then apply the black gamma table
#define BLACK_GAMMA_THRESHOLD 0x40
// If the luminance is >= this value, then apply the white gamma table
#define WHITE_GAMMA_THRESHOLD 0xC0
int SkFontHost::ComputeGammaFlag(const SkPaint& paint)
{
if (paint.getShader() == NULL)
{
SkColor c = paint.getColor();
int r = SkColorGetR(c);
int g = SkColorGetG(c);
int b = SkColorGetB(c);
int luminance = (r * 2 + g * 5 + b) >> 3;
if (luminance <= BLACK_GAMMA_THRESHOLD)
{
// printf("------ black gamma for [%d %d %d]\n", r, g, b);
return SkScalerContext::kGammaForBlack_Flag;
}
if (luminance >= WHITE_GAMMA_THRESHOLD)
{
// printf("------ white gamma for [%d %d %d]\n", r, g, b);
return SkScalerContext::kGammaForWhite_Flag;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/// Gets a shared vector for a row
SHAREDVECTORN row(unsigned i)
{
// get the starting offset
const unsigned OFFSET = data() - _data.get();
SHAREDVECTORN v;
v._data = _data;
v._start = OFFSET + i;
v._inc = leading_dim();
v._len = _columns;
return v;
}
/// Gets a constant shared vector for a row
CONST_SHAREDVECTORN row(unsigned i) const
{
// get the starting offset
const unsigned OFFSET = data() - _data.get();
CONST_SHAREDVECTORN v;
v._data = _data;
v._start = OFFSET + i;
v._inc = leading_dim();
v._len = _columns;
return v;
}
/// Gets a shared vector for a column
SHAREDVECTORN column(unsigned i)
{
// get the starting offset
const unsigned OFFSET = data() - _data.get();
SHAREDVECTORN v;
v._data = _data;
v._start = OFFSET + leading_dim() * i;
v._inc = 1;
v._len = _rows;
return v;
}
/// Gets a shared vector for a column
CONST_SHAREDVECTORN column(unsigned i) const
{
// get the starting offset
const unsigned OFFSET = data() - _data.get();
CONST_SHAREDVECTORN v;
v._data = _data;
v._start = OFFSET + leading_dim() * i;
v._inc = 1;
v._len = _rows;
return v;
}
/// Gets a block as a shared matrix
SHAREDMATRIXN block(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end)
{
#ifndef NEXCEPT
if (row_end < row_start || row_end > _rows || col_end < col_start || col_end > _columns)
throw InvalidIndexException();
#endif
// determine the offset
const unsigned OFFSET = data() - _data.get();
SHAREDMATRIXN m;
m._data = _data;
m._rows = row_end - row_start;
m._columns = col_end - col_start;
m._ld = leading_dim();
m._start = OFFSET + m._ld * col_start + row_start;
return m;
}
/// Gets a block as a constant shared matrix
CONST_SHAREDMATRIXN block(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) const
{
#ifndef NEXCEPT
if (row_end < row_start || row_end > _rows || col_end < col_start || col_end > _columns)
throw InvalidIndexException();
#endif
// determine the offset
const unsigned OFFSET = data() - _data.get();
CONST_SHAREDMATRIXN m;
m._data = _data;
m._rows = row_end - row_start;
m._columns = col_end - col_start;
m._ld = leading_dim();
m._start = OFFSET + m._ld * col_start + row_start;
return m;
}
/// Get an iterator to the beginning
ITERATOR begin()
{
ITERATOR i;
i._count = 0;
i._sz = _rows*_columns;
i._ld = leading_dim();
i._rows = _rows;
i._columns = _columns;
i._data_start = i._current_data = data();
return i;
}
/// Get an iterator to the end
ITERATOR end()
{
ITERATOR i;
i._sz = _rows*_columns;
i._count = i._sz;
i._ld = leading_dim();
i._rows = _rows;
i._columns = _columns;
i._data_start = data();
i._current_data = data() + i._ld*i._columns;
return i;
}
/// Get an iterator to the beginning
CONST_ITERATOR begin() const
{
CONST_ITERATOR i;
i._count = 0;
i._sz = _rows*_columns;
i._ld = leading_dim();
i._rows = _rows;
i._columns = _columns;
i._data_start = i._current_data = data();
return i;
}
/// Get an iterator to the end
CONST_ITERATOR end() const
{
CONST_ITERATOR i;
i._sz = _rows*_columns;
i._count = i._sz;
i._ld = leading_dim();
i._rows = _rows;
i._columns = _columns;
i._data_start = data();
i._current_data = data() + i._ld*i._columns;
return i;
}
/// Sets a matrix from a vector
template <class V>
XMATRIXN& set(const V& v, Transposition trans)
{
#ifndef NEXCEPT
if (sizeof(data()) != sizeof(v.data()))
throw DataMismatchException();
#endif
// resize the matrix
if (trans == eNoTranspose)
resize(v.size(), 1);
else
resize(1, v.size());
if (_rows > 0 && _columns > 0)
CBLAS::copy(v.size(), v.data(), 1, _data.get(), 1);
return *this;
}
/// Determines the transpose of a matrix and stores the result in a given matrix
template <class M>
static M& transpose(const XMATRIXN& m, M& result)
{
#ifndef NEXCEPT
if (sizeof(m.data()) != sizeof(result.data()))
throw DataMismatchException();
#endif
// resize the result
result.resize(m.columns(), m.rows());
const REAL* mdata = m.data();
REAL* rdata = result.data();
for (unsigned i=0; i< m.rows(); i++)
for (unsigned j=0; j< m.columns(); j++)
rdata[i*result.leading_dim()+j] = mdata[j*m.leading_dim()+i];
return result;
}
/// Adds m to *this in place
template <class M>
XMATRIXN& operator+=(const M& m)
{
#ifndef NEXCEPT
if (_rows != m.rows() || _columns != m.columns())
throw MissizeException();
if (sizeof(data()) != sizeof(m.data()))
throw DataMismatchException();
#endif
if (_rows > 0 && _columns > 0)
std::transform(begin(), end(), m.begin(), begin(), std::plus<REAL>());
return *this;
}
/// Subtracts m from *this in place
template <class M>
XMATRIXN& operator-=(const M& m)
{
#ifndef NEXCEPT
if (_rows != m.rows() || _columns != m.columns())
throw MissizeException();
if (sizeof(data()) != sizeof(m.data()))
throw DataMismatchException();
#endif
if (_rows > 0 && _columns > 0)
std::transform(begin(), end(), m.begin(), begin(), std::minus<REAL>());
return *this;
}
/// Multiplies the diagonal matrix formed from d by the matrix m
template <class V, class W>
static W& diag_mult(const V& d, const XMATRIXN& m, W& result)
{
#ifndef NEXCEPT
if (d.size() != m.rows())
throw MissizeException();
if (sizeof(d.data()) != sizeof(m.data()))
throw DataMismatchException();
#endif
result.resize(d.size(), m.columns());
for (unsigned i=0; i< m.columns(); i++)
std::transform(d.begin(), d.end(), m.begin()+m.rows()*i, result.begin()+result.rows()*i, std::multiplies<REAL>());
return result;
}
/// Multiplies the diagonal matrix formed from d by the matrix transpose(m)
template <class V, class W>
static W& diag_mult_transpose(const V& d, const XMATRIXN& m, W& result)
{
#ifndef NEXCEPT
if (d.size() != m.columns())
throw MissizeException();
if (sizeof(d.data()) != sizeof(m.data()))
throw DataMismatchException();
#endif
// copy the transpose of m to the result
XMATRIXN::transpose(m, result);
// do the specified number of times
for (unsigned i=0; i< m.rows(); i++)
CBLAS::scal(d.size(), d[i], result.begin()+i, result.rows());
return result;
}
/// Multiplies the diagonal matrix formed from d by the vector v
template <class V, class U, class W>
static W& diag_mult(const V& d, const U& v, W& result)
{
#ifndef NEXCEPT
if (d.size() != v.size())
throw MissizeException();
if (sizeof(d.data()) != sizeof(v.data()))
throw DataMismatchException();
if (sizeof(d.data()) != sizeof(result.data()))
throw DataMismatchException();
#endif
result.resize(d.size());
std::transform(d.begin(), d.end(), v.begin(), result.begin(), std::multiplies<REAL>());
return result;
}
<commit_msg>Fixed compile bug in MatrixN::diag_mult_transpose()?<commit_after>/// Gets a shared vector for a row
SHAREDVECTORN row(unsigned i)
{
// get the starting offset
const unsigned OFFSET = data() - _data.get();
SHAREDVECTORN v;
v._data = _data;
v._start = OFFSET + i;
v._inc = leading_dim();
v._len = _columns;
return v;
}
/// Gets a constant shared vector for a row
CONST_SHAREDVECTORN row(unsigned i) const
{
// get the starting offset
const unsigned OFFSET = data() - _data.get();
CONST_SHAREDVECTORN v;
v._data = _data;
v._start = OFFSET + i;
v._inc = leading_dim();
v._len = _columns;
return v;
}
/// Gets a shared vector for a column
SHAREDVECTORN column(unsigned i)
{
// get the starting offset
const unsigned OFFSET = data() - _data.get();
SHAREDVECTORN v;
v._data = _data;
v._start = OFFSET + leading_dim() * i;
v._inc = 1;
v._len = _rows;
return v;
}
/// Gets a shared vector for a column
CONST_SHAREDVECTORN column(unsigned i) const
{
// get the starting offset
const unsigned OFFSET = data() - _data.get();
CONST_SHAREDVECTORN v;
v._data = _data;
v._start = OFFSET + leading_dim() * i;
v._inc = 1;
v._len = _rows;
return v;
}
/// Gets a block as a shared matrix
SHAREDMATRIXN block(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end)
{
#ifndef NEXCEPT
if (row_end < row_start || row_end > _rows || col_end < col_start || col_end > _columns)
throw InvalidIndexException();
#endif
// determine the offset
const unsigned OFFSET = data() - _data.get();
SHAREDMATRIXN m;
m._data = _data;
m._rows = row_end - row_start;
m._columns = col_end - col_start;
m._ld = leading_dim();
m._start = OFFSET + m._ld * col_start + row_start;
return m;
}
/// Gets a block as a constant shared matrix
CONST_SHAREDMATRIXN block(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) const
{
#ifndef NEXCEPT
if (row_end < row_start || row_end > _rows || col_end < col_start || col_end > _columns)
throw InvalidIndexException();
#endif
// determine the offset
const unsigned OFFSET = data() - _data.get();
CONST_SHAREDMATRIXN m;
m._data = _data;
m._rows = row_end - row_start;
m._columns = col_end - col_start;
m._ld = leading_dim();
m._start = OFFSET + m._ld * col_start + row_start;
return m;
}
/// Get an iterator to the beginning
ITERATOR begin()
{
ITERATOR i;
i._count = 0;
i._sz = _rows*_columns;
i._ld = leading_dim();
i._rows = _rows;
i._columns = _columns;
i._data_start = i._current_data = data();
return i;
}
/// Get an iterator to the end
ITERATOR end()
{
ITERATOR i;
i._sz = _rows*_columns;
i._count = i._sz;
i._ld = leading_dim();
i._rows = _rows;
i._columns = _columns;
i._data_start = data();
i._current_data = data() + i._ld*i._columns;
return i;
}
/// Get an iterator to the beginning
CONST_ITERATOR begin() const
{
CONST_ITERATOR i;
i._count = 0;
i._sz = _rows*_columns;
i._ld = leading_dim();
i._rows = _rows;
i._columns = _columns;
i._data_start = i._current_data = data();
return i;
}
/// Get an iterator to the end
CONST_ITERATOR end() const
{
CONST_ITERATOR i;
i._sz = _rows*_columns;
i._count = i._sz;
i._ld = leading_dim();
i._rows = _rows;
i._columns = _columns;
i._data_start = data();
i._current_data = data() + i._ld*i._columns;
return i;
}
/// Sets a matrix from a vector
template <class V>
XMATRIXN& set(const V& v, Transposition trans)
{
#ifndef NEXCEPT
if (sizeof(data()) != sizeof(v.data()))
throw DataMismatchException();
#endif
// resize the matrix
if (trans == eNoTranspose)
resize(v.size(), 1);
else
resize(1, v.size());
if (_rows > 0 && _columns > 0)
CBLAS::copy(v.size(), v.data(), 1, _data.get(), 1);
return *this;
}
/// Determines the transpose of a matrix and stores the result in a given matrix
template <class M>
static M& transpose(const XMATRIXN& m, M& result)
{
#ifndef NEXCEPT
if (sizeof(m.data()) != sizeof(result.data()))
throw DataMismatchException();
#endif
// resize the result
result.resize(m.columns(), m.rows());
const REAL* mdata = m.data();
REAL* rdata = result.data();
for (unsigned i=0; i< m.rows(); i++)
for (unsigned j=0; j< m.columns(); j++)
rdata[i*result.leading_dim()+j] = mdata[j*m.leading_dim()+i];
return result;
}
/// Adds m to *this in place
template <class M>
XMATRIXN& operator+=(const M& m)
{
#ifndef NEXCEPT
if (_rows != m.rows() || _columns != m.columns())
throw MissizeException();
if (sizeof(data()) != sizeof(m.data()))
throw DataMismatchException();
#endif
if (_rows > 0 && _columns > 0)
std::transform(begin(), end(), m.begin(), begin(), std::plus<REAL>());
return *this;
}
/// Subtracts m from *this in place
template <class M>
XMATRIXN& operator-=(const M& m)
{
#ifndef NEXCEPT
if (_rows != m.rows() || _columns != m.columns())
throw MissizeException();
if (sizeof(data()) != sizeof(m.data()))
throw DataMismatchException();
#endif
if (_rows > 0 && _columns > 0)
std::transform(begin(), end(), m.begin(), begin(), std::minus<REAL>());
return *this;
}
/// Multiplies the diagonal matrix formed from d by the matrix m
template <class V, class W>
static W& diag_mult(const V& d, const XMATRIXN& m, W& result)
{
#ifndef NEXCEPT
if (d.size() != m.rows())
throw MissizeException();
if (sizeof(d.data()) != sizeof(m.data()))
throw DataMismatchException();
#endif
result.resize(d.size(), m.columns());
for (unsigned i=0; i< m.columns(); i++)
std::transform(d.begin(), d.end(), m.begin()+m.rows()*i, result.begin()+result.rows()*i, std::multiplies<REAL>());
return result;
}
/// Multiplies the diagonal matrix formed from d by the matrix transpose(m)
template <class V, class W>
static W& diag_mult_transpose(const V& d, const XMATRIXN& m, W& result)
{
#ifndef NEXCEPT
if (d.size() != m.columns())
throw MissizeException();
if (sizeof(d.data()) != sizeof(m.data()))
throw DataMismatchException();
#endif
// copy the transpose of m to the result
XMATRIXN::transpose(m, result);
// do the specified number of times
for (unsigned i=0; i< m.rows(); i++)
CBLAS::scal(d.size(), d[i], result.data()+i, result.lda());
return result;
}
/// Multiplies the diagonal matrix formed from d by the vector v
template <class V, class U, class W>
static W& diag_mult(const V& d, const U& v, W& result)
{
#ifndef NEXCEPT
if (d.size() != v.size())
throw MissizeException();
if (sizeof(d.data()) != sizeof(v.data()))
throw DataMismatchException();
if (sizeof(d.data()) != sizeof(result.data()))
throw DataMismatchException();
#endif
result.resize(d.size());
std::transform(d.begin(), d.end(), v.begin(), result.begin(), std::multiplies<REAL>());
return result;
}
<|endoftext|> |
<commit_before>/****************************************************************************
* Copyright (C) 2012-2015 by Savoir-Faire Linux *
* Author : Alexandre Lision <alexandre.lision@savoirfairelinux.com> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* 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 General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "directrenderer.h"
#include <QtCore/QDebug>
#include <QtCore/QMutex>
#include <QtCore/QThread>
#include <QtCore/QTime>
#include <QtCore/QTimer>
#include <cstring>
#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME 0
#endif
#include "private/videorenderermanager.h"
#include "video/resolution.h"
#include "private/videorenderer_p.h"
namespace Video {
class DirectRendererPrivate : public QObject
{
Q_OBJECT
public:
DirectRendererPrivate(Video::DirectRenderer* parent);
private:
// Video::DirectRenderer* q_ptr;
};
}
Video::DirectRendererPrivate::DirectRendererPrivate(Video::DirectRenderer* parent) : QObject(parent)/*, q_ptr(parent)*/
{
}
///Constructor
Video::DirectRenderer::DirectRenderer(const QByteArray& id, const QSize& res): Renderer(id, res), d_ptr(new DirectRendererPrivate(this))
{
setObjectName("Video::DirectRenderer:"+id);
}
///Destructor
Video::DirectRenderer::~DirectRenderer()
{
}
void Video::DirectRenderer::startRendering()
{
Video::Renderer::d_ptr->m_isRendering = true;
emit started();
}
void Video::DirectRenderer::stopRendering ()
{
Video::Renderer::d_ptr->m_isRendering = false;
emit stopped();
}
void Video::DirectRenderer::onNewFrame(const std::shared_ptr<std::vector<unsigned char> >& frame, int w, int h)
{
if (!isRendering()) {
return;
}
Video::Renderer::d_ptr->m_pSize.setWidth(w);
Video::Renderer::d_ptr->m_pSize.setHeight(h);
Video::Renderer::d_ptr->m_pSFrame = frame;
emit frameUpdated();
}
Video::Renderer::ColorSpace Video::DirectRenderer::colorSpace() const
{
return Video::Renderer::ColorSpace::RGBA;
}
#include <directrenderer.moc>
<commit_msg>video: return the correct colorspace<commit_after>/****************************************************************************
* Copyright (C) 2012-2015 by Savoir-Faire Linux *
* Author : Alexandre Lision <alexandre.lision@savoirfairelinux.com> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* 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 General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "directrenderer.h"
#include <QtCore/QDebug>
#include <QtCore/QMutex>
#include <QtCore/QThread>
#include <QtCore/QTime>
#include <QtCore/QTimer>
#include <cstring>
#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME 0
#endif
#include "private/videorenderermanager.h"
#include "video/resolution.h"
#include "private/videorenderer_p.h"
namespace Video {
class DirectRendererPrivate : public QObject
{
Q_OBJECT
public:
DirectRendererPrivate(Video::DirectRenderer* parent);
private:
// Video::DirectRenderer* q_ptr;
};
}
Video::DirectRendererPrivate::DirectRendererPrivate(Video::DirectRenderer* parent) : QObject(parent)/*, q_ptr(parent)*/
{
}
///Constructor
Video::DirectRenderer::DirectRenderer(const QByteArray& id, const QSize& res): Renderer(id, res), d_ptr(new DirectRendererPrivate(this))
{
setObjectName("Video::DirectRenderer:"+id);
}
///Destructor
Video::DirectRenderer::~DirectRenderer()
{
}
void Video::DirectRenderer::startRendering()
{
Video::Renderer::d_ptr->m_isRendering = true;
emit started();
}
void Video::DirectRenderer::stopRendering ()
{
Video::Renderer::d_ptr->m_isRendering = false;
emit stopped();
}
void Video::DirectRenderer::onNewFrame(const std::shared_ptr<std::vector<unsigned char> >& frame, int w, int h)
{
if (!isRendering()) {
return;
}
Video::Renderer::d_ptr->m_pSize.setWidth(w);
Video::Renderer::d_ptr->m_pSize.setHeight(h);
Video::Renderer::d_ptr->m_pSFrame = frame;
emit frameUpdated();
}
Video::Renderer::ColorSpace Video::DirectRenderer::colorSpace() const
{
#ifdef Q_OS_DARWIN
return Video::Renderer::ColorSpace::RGBA;
#else
return Video::Renderer::ColorSpace::BGRA;
#endif
}
#include <directrenderer.moc>
<|endoftext|> |
<commit_before>#ifndef OSRM_CONTRACTOR_FILES_HPP
#define OSRM_CONTRACTOR_FILES_HPP
#include "contractor/query_graph.hpp"
#include "util/serialization.hpp"
#include "storage/io.hpp"
namespace osrm
{
namespace contractor
{
namespace files
{
// reads .osrm.hsgr file
template<storage::Ownership Ownership>
inline void readGraph(const boost::filesystem::path &path,
unsigned &checksum,
detail::QueryGraph<Ownership> &graph)
{
const auto fingerprint = storage::io::FileReader::VerifyFingerprint;
storage::io::FileReader reader{path, fingerprint};
reader.ReadInto(checksum);
util::serialization::read(reader, graph);
}
// writes .osrm.hsgr file
template<storage::Ownership Ownership>
inline void writeGraph(const boost::filesystem::path &path,
unsigned checksum,
const detail::QueryGraph<Ownership> &graph)
{
const auto fingerprint = storage::io::FileWriter::GenerateFingerprint;
storage::io::FileWriter writer{path, fingerprint};
writer.WriteOne(checksum);
util::serialization::write(writer, graph);
}
}
}
}
#endif
<commit_msg>Fix readGraph to not use UseSharedMemory<commit_after>#ifndef OSRM_CONTRACTOR_FILES_HPP
#define OSRM_CONTRACTOR_FILES_HPP
#include "contractor/query_graph.hpp"
#include "util/serialization.hpp"
#include "storage/io.hpp"
namespace osrm
{
namespace contractor
{
namespace files
{
// reads .osrm.hsgr file
template <typename QueryGraphT>
inline void readGraph(const boost::filesystem::path &path, unsigned &checksum, QueryGraphT &graph)
{
static_assert(std::is_same<QueryGraphView, QueryGraphT>::value ||
std::is_same<QueryGraph, QueryGraphT>::value,
"graph must be of type QueryGraph<>");
const auto fingerprint = storage::io::FileReader::VerifyFingerprint;
storage::io::FileReader reader{path, fingerprint};
reader.ReadInto(checksum);
util::serialization::read(reader, graph);
}
// writes .osrm.hsgr file
template <typename QueryGraphT>
inline void
writeGraph(const boost::filesystem::path &path, unsigned checksum, const QueryGraphT &graph)
{
static_assert(std::is_same<QueryGraphView, QueryGraphT>::value ||
std::is_same<QueryGraph, QueryGraphT>::value,
"graph must be of type QueryGraph<>");
const auto fingerprint = storage::io::FileWriter::GenerateFingerprint;
storage::io::FileWriter writer{path, fingerprint};
writer.WriteOne(checksum);
util::serialization::write(writer, graph);
}
}
}
}
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_IMAGE_ANY_HPP
#define MAPNIK_IMAGE_ANY_HPP
#include <mapnik/image.hpp>
#include <mapnik/image_null.hpp>
#include <mapnik/util/variant.hpp>
namespace mapnik {
using image_base = util::variant<image_null,
image_rgba8,
image_gray8,
image_gray8s,
image_gray16,
image_gray16s,
image_gray32,
image_gray32s,
image_gray32f,
image_gray64,
image_gray64s,
image_gray64f>;
struct MAPNIK_DECL image_any : image_base
{
image_any() = default;
image_any(int width,
int height,
image_dtype type = image_dtype_rgba8,
bool initialize = true,
bool premultiplied = false,
bool painted = false);
template <typename T>
image_any(T && data) noexcept
: image_base(std::move(data)) {}
unsigned char const* bytes() const;
unsigned char* bytes();
std::size_t width() const;
std::size_t height() const;
bool get_premultiplied() const;
bool painted() const;
std::size_t size() const;
std::size_t row_size() const;
double get_offset() const;
double get_scaling() const;
image_dtype get_dtype() const;
void set_offset(double val);
void set_scaling(double val);
};
MAPNIK_DECL image_any create_image_any(int width,
int height,
image_dtype type = image_dtype_rgba8,
bool initialize = true,
bool premultiplied = false,
bool painted = false);
} // end mapnik ns
#endif // MAPNIK_IMAGE_ANY_HPP
<commit_msg>fix variable shadowing in image_any<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_IMAGE_ANY_HPP
#define MAPNIK_IMAGE_ANY_HPP
#include <mapnik/image.hpp>
#include <mapnik/image_null.hpp>
#include <mapnik/util/variant.hpp>
namespace mapnik {
using image_base = util::variant<image_null,
image_rgba8,
image_gray8,
image_gray8s,
image_gray16,
image_gray16s,
image_gray32,
image_gray32s,
image_gray32f,
image_gray64,
image_gray64s,
image_gray64f>;
struct MAPNIK_DECL image_any : image_base
{
image_any() = default;
image_any(int width,
int height,
image_dtype type = image_dtype_rgba8,
bool initialize = true,
bool premultiplied = false,
bool painted = false);
template <typename T>
image_any(T && _data) noexcept
: image_base(std::move(_data)) {}
unsigned char const* bytes() const;
unsigned char* bytes();
std::size_t width() const;
std::size_t height() const;
bool get_premultiplied() const;
bool painted() const;
std::size_t size() const;
std::size_t row_size() const;
double get_offset() const;
double get_scaling() const;
image_dtype get_dtype() const;
void set_offset(double val);
void set_scaling(double val);
};
MAPNIK_DECL image_any create_image_any(int width,
int height,
image_dtype type = image_dtype_rgba8,
bool initialize = true,
bool premultiplied = false,
bool painted = false);
} // end mapnik ns
#endif // MAPNIK_IMAGE_ANY_HPP
<|endoftext|> |
<commit_before>#ifndef INCLUDED_U5E_UTF32_NATIVE_HPP
#define INCLUDED_U5E_UTF32_NATIVE_HPP
#include <type_traits>
#include <u5e/encoding_assertion.hpp>
#include <u5e/codepoint.hpp>
namespace u5e {
/**
* u5e::utf32_native
*
* The native utf32 encoding is built with the native 32 bit
* integer type. It is specially more useful for cases where
* you need to do extensive manipulation on text, since it
* allows you to have constant random access time.
*/
template <typename BUFFERTYPE>
class utf32_native {
encoding_assertion<BUFFERTYPE, int> _assertion;
public:
// value_type is always codepoint
typedef codepoint value_type;
// pointer to encoded_buffer
typedef utf32_native<BUFFERTYPE>* pointer;
// const pointer to encoded_buffer
typedef const utf32_native<BUFFERTYPE>* const_pointer;
// reference to encoded_buffer
typedef utf32_native<BUFFERTYPE>& reference;
// size type is always size_t, regardless of encoding, in order to
// isolate the knowledge of the encoding from the user code
typedef std::size_t size_type;
// difference type is always ptrdiff_t, regardrless of encoding,
// in order to isolate the knowledge of the encoding from the user
// code
typedef std::ptrdiff_t difference_type;
// since this is the native utf32, we can just delegate this
typedef typename BUFFERTYPE::iterator iterator;
typedef typename BUFFERTYPE::reverse_iterator reverse_iterator;
typedef typename BUFFERTYPE::const_iterator const_iterator;
typedef typename BUFFERTYPE::const_reverse_iterator const_reverse_iterator;
/**
* Constructors
*/
utf32_native() = default;
utf32_native(const BUFFERTYPE& raw_buffer)
: raw_buffer(raw_buffer) { };
utf32_native<BUFFERTYPE>& operator=(const utf32_native<BUFFERTYPE> &other) = delete;
inline iterator begin() {
return iterator(raw_buffer.begin());
}
inline iterator end() {
return iterator(raw_buffer.end());
}
private:
// raw buffer as specified by the storage type
BUFFERTYPE raw_buffer;
};
}
#endif
<commit_msg>add cbegin/cend to utf32_native<commit_after>#ifndef INCLUDED_U5E_UTF32_NATIVE_HPP
#define INCLUDED_U5E_UTF32_NATIVE_HPP
#include <type_traits>
#include <u5e/encoding_assertion.hpp>
#include <u5e/codepoint.hpp>
namespace u5e {
/**
* u5e::utf32_native
*
* The native utf32 encoding is built with the native 32 bit
* integer type. It is specially more useful for cases where
* you need to do extensive manipulation on text, since it
* allows you to have constant random access time.
*/
template <typename BUFFERTYPE>
class utf32_native {
encoding_assertion<BUFFERTYPE, int> _assertion;
public:
// value_type is always codepoint
typedef codepoint value_type;
// pointer to encoded_buffer
typedef utf32_native<BUFFERTYPE>* pointer;
// const pointer to encoded_buffer
typedef const utf32_native<BUFFERTYPE>* const_pointer;
// reference to encoded_buffer
typedef utf32_native<BUFFERTYPE>& reference;
// size type is always size_t, regardless of encoding, in order to
// isolate the knowledge of the encoding from the user code
typedef std::size_t size_type;
// difference type is always ptrdiff_t, regardrless of encoding,
// in order to isolate the knowledge of the encoding from the user
// code
typedef std::ptrdiff_t difference_type;
// since this is the native utf32, we can just delegate this
typedef typename BUFFERTYPE::iterator iterator;
typedef typename BUFFERTYPE::reverse_iterator reverse_iterator;
typedef typename BUFFERTYPE::const_iterator const_iterator;
typedef typename BUFFERTYPE::const_reverse_iterator const_reverse_iterator;
/**
* Constructors
*/
utf32_native() = default;
utf32_native(const BUFFERTYPE& raw_buffer)
: raw_buffer(raw_buffer) { };
utf32_native<BUFFERTYPE>& operator=(const utf32_native<BUFFERTYPE> &other) = delete;
inline iterator begin() {
return iterator(raw_buffer.begin());
}
inline iterator end() {
return iterator(raw_buffer.end());
}
inline const_iterator cbegin() {
return const_iterator(raw_buffer.cbegin());
}
inline const_iterator cend() {
return const_iterator(raw_buffer.cend());
}
private:
// raw buffer as specified by the storage type
BUFFERTYPE raw_buffer;
};
}
#endif
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------
/// \file test_helper.hpp
//----------------------------------------------------------------------------
/// \brief Unit test helping routines.
//----------------------------------------------------------------------------
// Author: Serge Aleynikov
// Created: 2010-01-06
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
***** END LICENSE BLOCK *****
*/
#ifndef _UTXX_TEST_HELPER_HPP_
#define _UTXX_TEST_HELPER_HPP_
#include <boost/test/unit_test.hpp>
#define BOOST_CURRENT_TEST_NAME \
boost::unit_test::framework::current_test_case().p_name->c_str()
#define UTXX_REQUIRE_NO_THROW(Expr) \
try { Expr; } \
catch (std::exception const& e) { \
BOOST_MESSAGE(e.what()); \
BOOST_REQUIRE_NO_THROW(Expr); \
}
#define UTXX_CHECK_NO_THROW(Expr) \
try { Expr; } \
catch (std::exception const& e) { \
BOOST_MESSAGE(e.what()); \
BOOST_CHECK_NO_THROW(Expr); \
}
namespace utxx {
inline long env(const char* a_var, long a_default) {
const char* p = getenv(a_var);
return p ? atoi(p) : a_default;
}
inline bool get_test_argv(const std::string& a_opt,
const std::string& a_long_opt = "") {
int argc = boost::unit_test::framework::master_test_suite().argc;
char** argv = boost::unit_test::framework::master_test_suite().argv;
if (a_opt.empty() && a_long_opt.empty()) return false;
auto same = [=](const std::string& a, int i) {
return !a.empty() && a == argv[i];
};
for (int i=1; i < argc; i++) {
if (same(a_opt, i)) return true;
if (same(a_long_opt, i)) return true;
}
return false;
}
inline bool get_test_argv(const std::string& a_opt,
const std::string& a_long_opt,
std::string& a_value) {
int argc = boost::unit_test::framework::master_test_suite().argc;
char** argv = boost::unit_test::framework::master_test_suite().argv;
if (a_opt.empty() && a_long_opt.empty()) return false;
auto same = [=](const std::string& a, int i) {
return !a.empty() && a == argv[i] &&
(i < argc-1 && argv[i+1][i] != '-');
};
for (int i=1; i < argc; i++) {
if (same(a_opt, i)) { a_value = argv[++i]; return true; }
if (same(a_long_opt, i)) { a_value = argv[++i]; return true; }
}
return false;
}
} // namespace utxx::test
#endif // _UTXX_TEST_HELPER_HPP_
<commit_msg>Add include with unit_test parameters<commit_after>//----------------------------------------------------------------------------
/// \file test_helper.hpp
//----------------------------------------------------------------------------
/// \brief Unit test helping routines.
//----------------------------------------------------------------------------
// Author: Serge Aleynikov
// Created: 2010-01-06
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
***** END LICENSE BLOCK *****
*/
#pragma once
#include <boost/test/unit_test.hpp>
#include <boost/test/detail/unit_test_parameters.hpp>
#define BOOST_CURRENT_TEST_NAME \
boost::unit_test::framework::current_test_case().p_name->c_str()
#define UTXX_REQUIRE_NO_THROW(Expr) \
try { Expr; } \
catch (std::exception const& e) { \
BOOST_MESSAGE(e.what()); \
BOOST_REQUIRE_NO_THROW(Expr); \
}
#define UTXX_CHECK_NO_THROW(Expr) \
try { Expr; } \
catch (std::exception const& e) { \
BOOST_MESSAGE(e.what()); \
BOOST_CHECK_NO_THROW(Expr); \
}
namespace utxx {
inline long env(const char* a_var, long a_default) {
const char* p = getenv(a_var);
return p ? atoi(p) : a_default;
}
inline bool get_test_argv(const std::string& a_opt,
const std::string& a_long_opt = "") {
int argc = boost::unit_test::framework::master_test_suite().argc;
char** argv = boost::unit_test::framework::master_test_suite().argv;
if (a_opt.empty() && a_long_opt.empty()) return false;
auto same = [=](const std::string& a, int i) {
return !a.empty() && a == argv[i];
};
for (int i=1; i < argc; i++) {
if (same(a_opt, i)) return true;
if (same(a_long_opt, i)) return true;
}
return false;
}
inline bool get_test_argv(const std::string& a_opt,
const std::string& a_long_opt,
std::string& a_value) {
int argc = boost::unit_test::framework::master_test_suite().argc;
char** argv = boost::unit_test::framework::master_test_suite().argv;
if (a_opt.empty() && a_long_opt.empty()) return false;
auto same = [=](const std::string& a, int i) {
return !a.empty() && a == argv[i] &&
(i < argc-1 && argv[i+1][i] != '-');
};
for (int i=1; i < argc; i++) {
if (same(a_opt, i)) { a_value = argv[++i]; return true; }
if (same(a_long_opt, i)) { a_value = argv[++i]; return true; }
}
return false;
}
} // namespace utxx::test<|endoftext|> |
<commit_before>/**
* @file lldockcontrol.cpp
* @brief Creates a panel of a specific kind for a toast
*
* $LicenseInfo:firstyear=2000&license=viewergpl$
*
* Copyright (c) 2000-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "lldockcontrol.h"
#include "lldockablefloater.h"
LLDockControl::LLDockControl(LLView* dockWidget, LLFloater* dockableFloater,
const LLUIImagePtr& dockTongue, DocAt dockAt, get_allowed_rect_callback_t get_allowed_rect_callback) :
mDockWidget(dockWidget), mDockableFloater(dockableFloater), mDockTongue(dockTongue)
{
mDockAt = dockAt;
if (dockableFloater->isDocked())
{
on();
}
else
{
off();
}
if (!(get_allowed_rect_callback))
{
mGetAllowedRectCallback = boost::bind(&LLDockControl::getAllowedRect, this, _1);
}
else
{
mGetAllowedRectCallback = get_allowed_rect_callback;
}
if (dockWidget != NULL)
{
repositionDockable();
}
if (mDockWidget != NULL)
{
mDockWidgetVisible = isDockVisible();
}
else
{
mDockWidgetVisible = false;
}
}
LLDockControl::~LLDockControl()
{
}
void LLDockControl::setDock(LLView* dockWidget)
{
mDockWidget = dockWidget;
if (mDockWidget != NULL)
{
repositionDockable();
mDockWidgetVisible = isDockVisible();
}
else
{
mDockWidgetVisible = false;
}
}
void LLDockControl::getAllowedRect(LLRect& rect)
{
rect = mDockableFloater->getRootView()->getRect();
}
void LLDockControl::repositionDockable()
{
LLRect dockRect = mDockWidget->calcScreenRect();
LLRect rootRect;
mGetAllowedRectCallback(rootRect);
// recalculate dockable position if dock position changed, dock visibility changed,
// root view rect changed or recalculation is forced
if (mPrevDockRect != dockRect || mDockWidgetVisible != isDockVisible()
|| mRootRect != rootRect || mRecalculateDocablePosition)
{
// undock dockable and off() if dock not visible
if (!isDockVisible())
{
mDockableFloater->setDocked(false);
// force off() since dockable may not have dockControll at this time
off();
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if(dockable_floater != NULL)
{
dockable_floater->onDockHidden();
}
}
else
{
if(mEnabled)
{
moveDockable();
}
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if(dockable_floater != NULL)
{
dockable_floater->onDockShown();
}
}
mPrevDockRect = dockRect;
mRootRect = rootRect;
mRecalculateDocablePosition = false;
mDockWidgetVisible = isDockVisible();
}
}
bool LLDockControl::isDockVisible()
{
bool res = true;
if (mDockWidget != NULL)
{
//we should check all hierarchy
res = mDockWidget->isInVisibleChain();
if (res)
{
LLRect dockRect = mDockWidget->calcScreenRect();
switch (mDockAt)
{
case LEFT: // to keep compiler happy
break;
case TOP:
// check is dock inside parent rect
LLRect dockParentRect =
mDockWidget->getParent()->calcScreenRect();
if (dockRect.mRight <= dockParentRect.mLeft
|| dockRect.mLeft >= dockParentRect.mRight)
{
res = false;
}
break;
}
}
}
return res;
}
void LLDockControl::moveDockable()
{
// calculate new dockable position
LLRect dockRect = mDockWidget->calcScreenRect();
LLRect rootRect;
mGetAllowedRectCallback(rootRect);
bool use_tongue = false;
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if (dockable_floater != NULL)
{
use_tongue = dockable_floater->getUseTongue();
}
LLRect dockableRect = mDockableFloater->calcScreenRect();
S32 x = 0;
S32 y = 0;
LLRect dockParentRect;
switch (mDockAt)
{
case LEFT:
x = dockRect.mLeft;
y = dockRect.mTop + mDockTongue->getHeight() + dockableRect.getHeight();
// check is dockable inside root view rect
if (x < rootRect.mLeft)
{
x = rootRect.mLeft;
}
if (x + dockableRect.getWidth() > rootRect.mRight)
{
x = rootRect.mRight - dockableRect.getWidth();
}
mDockTongueX = x + dockableRect.getWidth()/2 - mDockTongue->getWidth() / 2;
mDockTongueY = dockRect.mTop;
break;
case TOP:
x = dockRect.getCenterX() - dockableRect.getWidth() / 2;
y = dockRect.mTop + dockableRect.getHeight();
// unique docking used with dock tongue, so add tongue height o the Y coordinate
if (use_tongue)
{
y += mDockTongue->getHeight();
}
// check is dockable inside root view rect
if (x < rootRect.mLeft)
{
x = rootRect.mLeft;
}
if (x + dockableRect.getWidth() > rootRect.mRight)
{
x = rootRect.mRight - dockableRect.getWidth();
}
// calculate dock tongue position
dockParentRect = mDockWidget->getParent()->calcScreenRect();
if (dockRect.getCenterX() < dockParentRect.mLeft)
{
mDockTongueX = dockParentRect.mLeft - mDockTongue->getWidth() / 2;
}
else if (dockRect.getCenterX() > dockParentRect.mRight)
{
mDockTongueX = dockParentRect.mRight - mDockTongue->getWidth() / 2;;
}
else
{
mDockTongueX = dockRect.getCenterX() - mDockTongue->getWidth() / 2;
}
mDockTongueY = dockRect.mTop;
break;
}
// move dockable
dockableRect.setLeftTopAndSize(x, y, dockableRect.getWidth(),
dockableRect.getHeight());
LLRect localDocableParentRect;
mDockableFloater->getParent()->screenRectToLocal(dockableRect,
&localDocableParentRect);
mDockableFloater->setRect(localDocableParentRect);
mDockableFloater->screenPointToLocal(mDockTongueX, mDockTongueY,
&mDockTongueX, &mDockTongueY);
}
void LLDockControl::on()
{
if (isDockVisible())
{
mEnabled = true;
mRecalculateDocablePosition = true;
}
}
void LLDockControl::off()
{
mEnabled = false;
}
void LLDockControl::forceRecalculatePosition()
{
mRecalculateDocablePosition = true;
}
void LLDockControl::drawToungue()
{
bool use_tongue = false;
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if (dockable_floater != NULL)
{
use_tongue = dockable_floater->getUseTongue();
}
if (mEnabled && use_tongue)
{
mDockTongue->draw(mDockTongueX, mDockTongueY);
}
}
<commit_msg>CID-344<commit_after>/**
* @file lldockcontrol.cpp
* @brief Creates a panel of a specific kind for a toast
*
* $LicenseInfo:firstyear=2000&license=viewergpl$
*
* Copyright (c) 2000-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "lldockcontrol.h"
#include "lldockablefloater.h"
LLDockControl::LLDockControl(LLView* dockWidget, LLFloater* dockableFloater,
const LLUIImagePtr& dockTongue, DocAt dockAt, get_allowed_rect_callback_t get_allowed_rect_callback) :
mDockWidget(dockWidget),
mDockableFloater(dockableFloater),
mDockTongue(dockTongue),
mDockTongueX(0),
mDockTongueY(0)
{
mDockAt = dockAt;
if (dockableFloater->isDocked())
{
on();
}
else
{
off();
}
if (!(get_allowed_rect_callback))
{
mGetAllowedRectCallback = boost::bind(&LLDockControl::getAllowedRect, this, _1);
}
else
{
mGetAllowedRectCallback = get_allowed_rect_callback;
}
if (dockWidget != NULL)
{
repositionDockable();
}
if (mDockWidget != NULL)
{
mDockWidgetVisible = isDockVisible();
}
else
{
mDockWidgetVisible = false;
}
}
LLDockControl::~LLDockControl()
{
}
void LLDockControl::setDock(LLView* dockWidget)
{
mDockWidget = dockWidget;
if (mDockWidget != NULL)
{
repositionDockable();
mDockWidgetVisible = isDockVisible();
}
else
{
mDockWidgetVisible = false;
}
}
void LLDockControl::getAllowedRect(LLRect& rect)
{
rect = mDockableFloater->getRootView()->getRect();
}
void LLDockControl::repositionDockable()
{
LLRect dockRect = mDockWidget->calcScreenRect();
LLRect rootRect;
mGetAllowedRectCallback(rootRect);
// recalculate dockable position if dock position changed, dock visibility changed,
// root view rect changed or recalculation is forced
if (mPrevDockRect != dockRect || mDockWidgetVisible != isDockVisible()
|| mRootRect != rootRect || mRecalculateDocablePosition)
{
// undock dockable and off() if dock not visible
if (!isDockVisible())
{
mDockableFloater->setDocked(false);
// force off() since dockable may not have dockControll at this time
off();
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if(dockable_floater != NULL)
{
dockable_floater->onDockHidden();
}
}
else
{
if(mEnabled)
{
moveDockable();
}
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if(dockable_floater != NULL)
{
dockable_floater->onDockShown();
}
}
mPrevDockRect = dockRect;
mRootRect = rootRect;
mRecalculateDocablePosition = false;
mDockWidgetVisible = isDockVisible();
}
}
bool LLDockControl::isDockVisible()
{
bool res = true;
if (mDockWidget != NULL)
{
//we should check all hierarchy
res = mDockWidget->isInVisibleChain();
if (res)
{
LLRect dockRect = mDockWidget->calcScreenRect();
switch (mDockAt)
{
case LEFT: // to keep compiler happy
break;
case TOP:
// check is dock inside parent rect
LLRect dockParentRect =
mDockWidget->getParent()->calcScreenRect();
if (dockRect.mRight <= dockParentRect.mLeft
|| dockRect.mLeft >= dockParentRect.mRight)
{
res = false;
}
break;
}
}
}
return res;
}
void LLDockControl::moveDockable()
{
// calculate new dockable position
LLRect dockRect = mDockWidget->calcScreenRect();
LLRect rootRect;
mGetAllowedRectCallback(rootRect);
bool use_tongue = false;
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if (dockable_floater != NULL)
{
use_tongue = dockable_floater->getUseTongue();
}
LLRect dockableRect = mDockableFloater->calcScreenRect();
S32 x = 0;
S32 y = 0;
LLRect dockParentRect;
switch (mDockAt)
{
case LEFT:
x = dockRect.mLeft;
y = dockRect.mTop + mDockTongue->getHeight() + dockableRect.getHeight();
// check is dockable inside root view rect
if (x < rootRect.mLeft)
{
x = rootRect.mLeft;
}
if (x + dockableRect.getWidth() > rootRect.mRight)
{
x = rootRect.mRight - dockableRect.getWidth();
}
mDockTongueX = x + dockableRect.getWidth()/2 - mDockTongue->getWidth() / 2;
mDockTongueY = dockRect.mTop;
break;
case TOP:
x = dockRect.getCenterX() - dockableRect.getWidth() / 2;
y = dockRect.mTop + dockableRect.getHeight();
// unique docking used with dock tongue, so add tongue height o the Y coordinate
if (use_tongue)
{
y += mDockTongue->getHeight();
}
// check is dockable inside root view rect
if (x < rootRect.mLeft)
{
x = rootRect.mLeft;
}
if (x + dockableRect.getWidth() > rootRect.mRight)
{
x = rootRect.mRight - dockableRect.getWidth();
}
// calculate dock tongue position
dockParentRect = mDockWidget->getParent()->calcScreenRect();
if (dockRect.getCenterX() < dockParentRect.mLeft)
{
mDockTongueX = dockParentRect.mLeft - mDockTongue->getWidth() / 2;
}
else if (dockRect.getCenterX() > dockParentRect.mRight)
{
mDockTongueX = dockParentRect.mRight - mDockTongue->getWidth() / 2;;
}
else
{
mDockTongueX = dockRect.getCenterX() - mDockTongue->getWidth() / 2;
}
mDockTongueY = dockRect.mTop;
break;
}
// move dockable
dockableRect.setLeftTopAndSize(x, y, dockableRect.getWidth(),
dockableRect.getHeight());
LLRect localDocableParentRect;
mDockableFloater->getParent()->screenRectToLocal(dockableRect,
&localDocableParentRect);
mDockableFloater->setRect(localDocableParentRect);
mDockableFloater->screenPointToLocal(mDockTongueX, mDockTongueY,
&mDockTongueX, &mDockTongueY);
}
void LLDockControl::on()
{
if (isDockVisible())
{
mEnabled = true;
mRecalculateDocablePosition = true;
}
}
void LLDockControl::off()
{
mEnabled = false;
}
void LLDockControl::forceRecalculatePosition()
{
mRecalculateDocablePosition = true;
}
void LLDockControl::drawToungue()
{
bool use_tongue = false;
LLDockableFloater* dockable_floater =
dynamic_cast<LLDockableFloater*> (mDockableFloater);
if (dockable_floater != NULL)
{
use_tongue = dockable_floater->getUseTongue();
}
if (mEnabled && use_tongue)
{
mDockTongue->draw(mDockTongueX, mDockTongueY);
}
}
<|endoftext|> |
<commit_before>#include "providers/LinkResolver.hpp"
#include "common/Common.hpp"
#include "common/NetworkRequest.hpp"
#include <QString>
namespace chatterino {
void LinkResolver::getLinkInfo(const QString url,
std::function<void(QString)> successCallback)
{
QString requestUrl("https://api.betterttv.net/2/link_resolver/" +
QUrl::toPercentEncoding(url, "", "/:"));
NetworkRequest request(requestUrl);
request.setCaller(QThread::currentThread());
request.setTimeout(30000);
request.onSuccess([successCallback](auto result) mutable -> Outcome {
auto root = result.parseJson();
/* When tooltip is not a string, in this case,
onError runs before onSuccess,
so there is no point in doing "if" condition. */
auto tooltip = root.value("tooltip").toString();
successCallback(QUrl::fromPercentEncoding(tooltip.toUtf8()));
return Success;
});
request.onError([successCallback](auto result) {
successCallback("No link info found");
return true;
});
request.execute();
}
} // namespace chatterino
<commit_msg>Run away from BTTV API.<commit_after>#include "providers/LinkResolver.hpp"
#include "common/Common.hpp"
#include "common/NetworkRequest.hpp"
#include <QString>
namespace chatterino {
void LinkResolver::getLinkInfo(const QString url,
std::function<void(QString)> successCallback)
{
QString requestUrl("https://braize.pajlada.com/chatterino/link_resolver/" +
QUrl::toPercentEncoding(url, "", "/:"));
NetworkRequest request(requestUrl);
request.setCaller(QThread::currentThread());
request.setTimeout(30000);
request.onSuccess([successCallback](auto result) mutable -> Outcome {
auto root = result.parseJson();
/* When tooltip is not a string, in this case,
onError runs before onSuccess,
so there is no point in doing "if" condition. */
auto tooltip = root.value("tooltip").toString();
successCallback(QUrl::fromPercentEncoding(tooltip.toUtf8()));
return Success;
});
request.onError([successCallback](auto result) {
successCallback("No link info found");
return true;
});
request.execute();
}
} // namespace chatterino
<|endoftext|> |
<commit_before>/* test_junctions_creator.cc -- Unit-tests for the JunctionsCreator class
Copyright (c) 2015, The Griffith Lab
Author: Avinash Ramu <aramu@genome.wustl.edu>
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 <gtest/gtest.h>
#include <sstream>
#include <stdexcept>
#include "junctions_creator.h"
class JunctionsCreateTest : public ::testing::Test {
public:
JunctionsCreator jc1;
};
TEST_F(JunctionsCreateTest, ParseInput) {
int argc = 2;
char * argv[] = {"create", "test_input.bam"};
int ret = jc1.parse_options(argc, argv);
string expected_bam("test_input.bam");
ASSERT_EQ(expected_bam, jc1.get_bam());
ASSERT_EQ(0, ret);
}
TEST_F(JunctionsCreateTest, ParseNoInput) {
int argc = 1;
char * argv[] = {"create"};
ASSERT_THROW(jc1.parse_options(argc, argv), std::runtime_error);
}
TEST_F(JunctionsCreateTest, ParseIncorrectOption) {
int argc = 2;
char * argv[] = {"create", "-k", "24", "test_input.bam"};
ASSERT_THROW(jc1.parse_options(argc, argv), std::runtime_error);
}
TEST_F(JunctionsCreateTest, Usage) {
ostringstream out, out2;
out << "\nUsage:\t\t" << "regtools junctions create [options] indexed_alignments.bam";
out << "\nOptions:";
out << "\t" << "-a INT\tMinimum anchor length. Junctions which satisfy a minimum "
"anchor length on both sides are reported. [8]";
out << "\n\t\t" << "-i INT\tMinimum intron length. [70]";
out << "\n\t\t" << "-I INT\tMaximum intron length. [500000]";
out << "\n\t\t" << "-o FILE\tThe file to write output to. [STDOUT]";
out << "\n\t\t" << "-r STR\tThe region to identify junctions "
"in \"chr:start-end\" format. Entire BAM by default.";
out << "\n";
j1.usage(out2);
ASSERT_EQ(out.str(), out2.str()) << "Error parsing as expected";
}
<commit_msg>Rename j1 to jc1<commit_after>/* test_junctions_creator.cc -- Unit-tests for the JunctionsCreator class
Copyright (c) 2015, The Griffith Lab
Author: Avinash Ramu <aramu@genome.wustl.edu>
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 <gtest/gtest.h>
#include <sstream>
#include <stdexcept>
#include "junctions_creator.h"
class JunctionsCreateTest : public ::testing::Test {
public:
JunctionsCreator jc1;
};
TEST_F(JunctionsCreateTest, ParseInput) {
int argc = 2;
char * argv[] = {"create", "test_input.bam"};
int ret = jc1.parse_options(argc, argv);
string expected_bam("test_input.bam");
ASSERT_EQ(expected_bam, jc1.get_bam());
ASSERT_EQ(0, ret);
}
TEST_F(JunctionsCreateTest, ParseNoInput) {
int argc = 1;
char * argv[] = {"create"};
ASSERT_THROW(jc1.parse_options(argc, argv), std::runtime_error);
}
TEST_F(JunctionsCreateTest, ParseIncorrectOption) {
int argc = 2;
char * argv[] = {"create", "-k", "24", "test_input.bam"};
ASSERT_THROW(jc1.parse_options(argc, argv), std::runtime_error);
}
TEST_F(JunctionsCreateTest, Usage) {
ostringstream out, out2;
out << "\nUsage:\t\t" << "regtools junctions create [options] indexed_alignments.bam";
out << "\nOptions:";
out << "\t" << "-a INT\tMinimum anchor length. Junctions which satisfy a minimum "
"anchor length on both sides are reported. [8]";
out << "\n\t\t" << "-i INT\tMinimum intron length. [70]";
out << "\n\t\t" << "-I INT\tMaximum intron length. [500000]";
out << "\n\t\t" << "-o FILE\tThe file to write output to. [STDOUT]";
out << "\n\t\t" << "-r STR\tThe region to identify junctions "
"in \"chr:start-end\" format. Entire BAM by default.";
out << "\n";
jc1.usage(out2);
ASSERT_EQ(out.str(), out2.str()) << "Error parsing as expected";
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include "allocators.h"
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("Bitcoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your bitcoins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
<commit_msg>Consistent lettering<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include "allocators.h"
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("Bitcoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your bitcoins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016-2018 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/rpcnestedtests.h>
#include <fs.h>
#include <interfaces/node.h>
#include <rpc/server.h>
#include <qt/rpcconsole.h>
#include <test/setup_common.h>
#include <univalue.h>
#include <util/system.h>
#include <QDir>
#include <QtGlobal>
static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)
{
if (request.fHelp) {
return "help message";
}
return request.params.write(0, 0);
}
static const CRPCCommand vRPCCommands[] =
{
{ "test", "rpcNestedTest", &rpcNestedTest_rpc, {} },
};
void RPCNestedTests::rpcNestedTests()
{
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
//mempool.setSanityCheck(1.0);
LogInstance().DisconnectTestLogger(); // Already started by the common test setup, so stop it to avoid interference
TestingSetup test;
if (RPCIsInWarmup(nullptr)) SetRPCWarmupFinished();
std::string result;
std::string result2;
std::string filtered;
auto node = interfaces::MakeNode();
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(*node, result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
RPCConsole::RPCParseCommandLine(nullptr, result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signrawtransactionwithkey(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransactionwithkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
}
<commit_msg>Add missing ECC_Stop(); in GUI rpcnestedtests.cpp<commit_after>// Copyright (c) 2016-2018 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/rpcnestedtests.h>
#include <fs.h>
#include <interfaces/node.h>
#include <rpc/server.h>
#include <qt/rpcconsole.h>
#include <test/setup_common.h>
#include <univalue.h>
#include <util/system.h>
#include <QDir>
#include <QtGlobal>
static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)
{
if (request.fHelp) {
return "help message";
}
return request.params.write(0, 0);
}
static const CRPCCommand vRPCCommands[] =
{
{ "test", "rpcNestedTest", &rpcNestedTest_rpc, {} },
};
void RPCNestedTests::rpcNestedTests()
{
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
//mempool.setSanityCheck(1.0);
ECC_Stop(); // Already started by the common test setup, so stop it to avoid interference
LogInstance().DisconnectTestLogger();
TestingSetup test;
if (RPCIsInWarmup(nullptr)) SetRPCWarmupFinished();
std::string result;
std::string result2;
std::string filtered;
auto node = interfaces::MakeNode();
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child containing the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(*node, result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(*node, result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parameters is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(*node, result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
RPCConsole::RPCParseCommandLine(nullptr, result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "signrawtransactionwithkey(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransactionwithkey(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(nullptr, result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
}
<|endoftext|> |
<commit_before>/**
* @file
*/
#pragma once
#include "bi/data/Frame.hpp"
#include "bi/data/Iterator.hpp"
#include "bi/data/copy.hpp"
#include "bi/data/constant.hpp"
#include <cstring>
namespace bi {
/**
* Array. Combines underlying data and a frame describing the shape of that
* data. Allows the construction of views of the data, where a view indexes
* either an individual element or some range of elements.
*
* @ingroup library
*
* @tparam Type Value type.
* @tparam Frame Frame type.
*/
template<class Type, class Frame = EmptyFrame>
class Array {
template<class Type1, class Frame1>
friend class Array;
/**
* @internal These are declare ahead due to some issues with clang++ around
* the return type of operator(), which in turn calls viewReturn().
*/
protected:
/**
* Frame.
*/
Frame frame;
/**
* Value.
*/
Type* ptr;
/**
* Do we own the underlying buffer?
*/
bool own;
/**
* Copy from another array.
*/
template<class Frame1>
void copy(const Array<Type,Frame1>& o) {
/* pre-condition */
assert(frame.conforms(o.frame));
int_t block = common_view(frame.block(), o.frame.block()).size();
auto iter1 = begin();
auto end1 = end();
auto iter2 = o.begin();
auto end2 = o.end();
for (; iter1 != end1; iter1 += block, iter2 += block) {
std::memcpy(&(*iter1), &(*iter2), block * sizeof(Type));
}
assert(iter2 == end2);
}
/**
* Return value of view when result is an array.
*/
template<class View1, class Frame1>
Array<Type,Frame1> viewReturn(const View1& view, const Frame1& frame) {
return Array<Type,Frame1>(ptr + frame.serial(view), frame);
}
template<class View1, class Frame1>
Array<const Type,Frame1> viewReturn(const View1& view,
const Frame1& frame) const {
return Array<const Type,Frame1>(ptr + frame.serial(view), frame);
}
/**
* Return value of view when result is a scalar.
*/
template<class View1>
Type& viewReturn(const View1& view, const EmptyFrame& frame) {
return ptr[frame.serial(view)];
}
template<class View1>
const Type& viewReturn(const View1& view, const EmptyFrame& frame) const {
return ptr[frame.serial(view)];
}
public:
/**
* Constructor with new allocation.
*
* @tparam ...Args Arbitrary types.
*
* @param frame Frame.
* @param args Optional constructor arguments.
*
* Memory is allocated for the array, and is freed on destruction.
*/
template<class ... Args>
Array(const Frame& frame, Args ... args) :
frame(frame) {
create(&ptr, frame);
fill(ptr, frame, args...);
}
/**
* Constructor with existing allocation.
*
* @tparam Frame Frame type.
*
* @param ptr Existing allocation.
* @param frame Frame.
*/
Array(Type* ptr, const Frame& frame) :
frame(frame),
ptr(ptr),
own(false) {
//
}
/**
* Copy constructor.
*/
Array(const Array<Type,Frame>& o) :
frame(o.frame) {
create(&ptr, frame);
fill(ptr, frame);
own = true;
*this = o;
}
/**
* Move constructor.
*/
// Array(Array<Type,Frame> && o) :
// frame(o.frame),
// ptr(o.ptr),
// own(o.own) {
// o.own = false; // ownership moves
// }
/**
* Destructor.
*/
~Array() {
if (own) {
release(ptr, frame);
}
}
/**
* Copy assignment. The frames of the two arrays must conform.
*/
Array<Type,Frame>& operator=(const Array<Type,Frame>& o) {
/* pre-condition */
assert(frame.conforms(o.frame));
if (ptr != o.ptr) {
copy(o);
}
return *this;
}
/**
* Move assignment. The frames of the two arrays must conform.
*/
// Array<Type,Frame>& operator=(Array<Type,Frame> && o) {
// /* pre-condition */
// assert(frame.conforms(o.frame));
//
// if (ptr == o.ptr) {
// /* just take ownership */
// if (!own) {
// std::swap(own, o.own);
// }
// } else {
// /* copy assignment */
// copy(o);
// }
// return *this;
// }
/**
* Generic assignment. The frames of the two arrays must conform.
*/
template<class Frame1>
Array<Type,Frame>& operator=(const Array<Type,Frame1>& o) {
/* pre-condition */
assert(frame.conforms(o.frame));
copy(o);
return *this;
}
/**
* View operator.
*
* @tparam View1 View type.
*
* @param o View.
*
* @return The new array.
*
* @internal The decltype use for the return type here seems necessary,
* clang++ is otherwise giving these a const return type.
*/
template<class View1>
auto operator()(
const View1& view) -> decltype(viewReturn(view, this->frame(view))) {
return viewReturn(view, frame(view));
}
/**
* View operator.
*/
template<class View1>
auto operator()(
const View1& view) const -> decltype(viewReturn(view, this->frame(view))) {
return viewReturn(view, frame(view));
}
/**
* @name Selections
*/
//@{
/**
* Access the first element.
*/
Type& front() {
return *ptr;
}
/**
* Access the first element.
*/
const Type& front() const {
return *ptr;
}
/**
* Access the last element.
*/
Type& back() {
return ptr + frame.lead - 1;
}
/**
* Access the last element.
*/
const Type& back() const {
return ptr + frame.lead - 1;
}
//@}
/**
* @name Queries
*/
//@{
/**
* Get the length of the @p i th dimension.
*/
int_t length(const int i) const {
return frame.length(i);
}
/**
* Get the stride of the @p i th dimension.
*/
int_t stride(const int i) const {
return frame.stride(i);
}
/**
* Get the lead of the @p i th dimension.
*/
int_t lead(const int i) const {
return frame.lead(i);
}
/**
* Raw pointer to underlying buffer.
*/
Type* buf() {
return ptr;
}
/**
* Raw pointer to underlying buffer.
*/
Type* const buf() const {
return ptr;
}
//@}
/**
* @name Collections
*/
//@{
/**
* Get lengths.
*
* @tparam Integer Integer type.
*
* @param[out] out Array assumed to have at least count() elements.
*/
template<class Integer>
void lengths(Integer* out) const {
frame.lengths(out);
}
/**
* Get strides.
*
* @tparam Integer Integer type.
*
* @param[out] out Array assumed to have at least count() elements.
*/
template<class Integer>
void strides(Integer* out) const {
frame.strides(out);
}
/**
* Get leads.
*
* @tparam Integer Integer type.
*
* @param[out] out Array assumed to have at least count() elements.
*/
template<class Integer>
void leads(Integer* out) const {
frame.leads(out);
}
//@}
/**
* @name Reductions
*/
//@{
/**
* Number of spans in the frame.
*/
static constexpr int count() {
return Frame::count();
}
/**
* Are all elements stored contiguously in memory?
*/
bool contiguous() const {
return frame.contiguous();
}
//@}
/**
* @name Iteration
*/
//@{
/**
* Iterator pointing to the first element.
*
* Iterators are used to access the elements of an array sequentially.
* Elements are visited in the order in which they are stored in memory;
* the rightmost dimension is the fastest moving (for a matrix, this is
* "row major" order).
*
* The idiom of iterator usage is as for the STL.
*/
Iterator<Type,Frame> begin() {
return Iterator<Type,Frame>(ptr, frame);
}
/**
* Iterator pointing to the first element.
*/
Iterator<const Type,Frame> begin() const {
return Iterator<const Type,Frame>(ptr, frame);
}
/**
* Iterator pointing to one beyond the last element.
*/
Iterator<Type,Frame> end() {
return begin() + frame.size();
}
/**
* Iterator pointing to one beyond the last element.
*/
Iterator<const Type,Frame> end() const {
return begin() + frame.size();
}
};
/**
* Default array for `D` dimensions.
*/
template<class Type, int D>
using DefaultArray = Array<Type,typename DefaultFrame<D>::type>;
}
<commit_msg>Reintroduced move constructor and move assignment for arrays.<commit_after>/**
* @file
*/
#pragma once
#include "bi/data/Frame.hpp"
#include "bi/data/Iterator.hpp"
#include "bi/data/copy.hpp"
#include "bi/data/constant.hpp"
#include <cstring>
namespace bi {
/**
* Array. Combines underlying data and a frame describing the shape of that
* data. Allows the construction of views of the data, where a view indexes
* either an individual element or some range of elements.
*
* @ingroup library
*
* @tparam Type Value type.
* @tparam Frame Frame type.
*/
template<class Type, class Frame = EmptyFrame>
class Array {
template<class Type1, class Frame1>
friend class Array;
/**
* @internal These are declare ahead due to some issues with clang++ around
* the return type of operator(), which in turn calls viewReturn().
*/
protected:
/**
* Frame.
*/
Frame frame;
/**
* Value.
*/
Type* ptr;
/**
* Do we own the underlying buffer?
*/
bool own;
/**
* Copy from another array.
*/
template<class Frame1>
void copy(const Array<Type,Frame1>& o) {
/* pre-condition */
assert(frame.conforms(o.frame));
int_t block = common_view(frame.block(), o.frame.block()).size();
auto iter1 = begin();
auto end1 = end();
auto iter2 = o.begin();
auto end2 = o.end();
for (; iter1 != end1; iter1 += block, iter2 += block) {
std::memcpy(&(*iter1), &(*iter2), block * sizeof(Type));
}
assert(iter2 == end2);
}
/**
* Return value of view when result is an array.
*/
template<class View1, class Frame1>
Array<Type,Frame1> viewReturn(const View1& view, const Frame1& frame) {
return Array<Type,Frame1>(ptr + frame.serial(view), frame);
}
template<class View1, class Frame1>
Array<const Type,Frame1> viewReturn(const View1& view,
const Frame1& frame) const {
return Array<const Type,Frame1>(ptr + frame.serial(view), frame);
}
/**
* Return value of view when result is a scalar.
*/
template<class View1>
Type& viewReturn(const View1& view, const EmptyFrame& frame) {
return ptr[frame.serial(view)];
}
template<class View1>
const Type& viewReturn(const View1& view, const EmptyFrame& frame) const {
return ptr[frame.serial(view)];
}
public:
/**
* Constructor with new allocation.
*
* @tparam ...Args Arbitrary types.
*
* @param frame Frame.
* @param args Optional constructor arguments.
*
* Memory is allocated for the array, and is freed on destruction.
*/
template<class ... Args>
Array(const Frame& frame, Args ... args) :
frame(frame) {
create(&ptr, frame);
fill(ptr, frame, args...);
}
/**
* Constructor with existing allocation.
*
* @tparam Frame Frame type.
*
* @param ptr Existing allocation.
* @param frame Frame.
*/
Array(Type* ptr, const Frame& frame) :
frame(frame),
ptr(ptr),
own(false) {
//
}
/**
* Copy constructor.
*/
Array(const Array<Type,Frame>& o) :
frame(o.frame) {
create(&ptr, frame);
fill(ptr, frame);
own = true;
*this = o;
}
/**
* Move constructor.
*/
Array(Array<Type,Frame> && o) :
frame(o.frame),
ptr(o.ptr),
own(o.own) {
o.own = false; // ownership moves
}
/**
* Destructor.
*/
~Array() {
if (own) {
release(ptr, frame);
}
}
/**
* Copy assignment. The frames of the two arrays must conform.
*/
Array<Type,Frame>& operator=(const Array<Type,Frame>& o) {
/* pre-condition */
assert(frame.conforms(o.frame));
if (ptr != o.ptr) {
copy(o);
}
return *this;
}
/**
* Move assignment. The frames of the two arrays must conform.
*/
Array<Type,Frame>& operator=(Array<Type,Frame> && o) {
/* pre-condition */
assert(frame.conforms(o.frame));
if (ptr == o.ptr) {
/* just take ownership */
if (!own) {
std::swap(own, o.own);
}
} else {
/* copy assignment; note that we cannot simply move, even if this
* object owns its buffer, as there may exist non-owning arrays
* with the same buffer */
copy(o);
}
return *this;
}
/**
* Generic assignment. The frames of the two arrays must conform.
*/
template<class Frame1>
Array<Type,Frame>& operator=(const Array<Type,Frame1>& o) {
/* pre-condition */
assert(frame.conforms(o.frame));
copy(o);
return *this;
}
/**
* View operator.
*
* @tparam View1 View type.
*
* @param o View.
*
* @return The new array.
*
* @internal The decltype use for the return type here seems necessary,
* clang++ is otherwise giving these a const return type.
*/
template<class View1>
auto operator()(
const View1& view) -> decltype(viewReturn(view, this->frame(view))) {
return viewReturn(view, frame(view));
}
/**
* View operator.
*/
template<class View1>
auto operator()(
const View1& view) const -> decltype(viewReturn(view, this->frame(view))) {
return viewReturn(view, frame(view));
}
/**
* @name Selections
*/
//@{
/**
* Access the first element.
*/
Type& front() {
return *ptr;
}
/**
* Access the first element.
*/
const Type& front() const {
return *ptr;
}
/**
* Access the last element.
*/
Type& back() {
return ptr + frame.lead - 1;
}
/**
* Access the last element.
*/
const Type& back() const {
return ptr + frame.lead - 1;
}
//@}
/**
* @name Queries
*/
//@{
/**
* Get the length of the @p i th dimension.
*/
int_t length(const int i) const {
return frame.length(i);
}
/**
* Get the stride of the @p i th dimension.
*/
int_t stride(const int i) const {
return frame.stride(i);
}
/**
* Get the lead of the @p i th dimension.
*/
int_t lead(const int i) const {
return frame.lead(i);
}
/**
* Raw pointer to underlying buffer.
*/
Type* buf() {
return ptr;
}
/**
* Raw pointer to underlying buffer.
*/
Type* const buf() const {
return ptr;
}
//@}
/**
* @name Collections
*/
//@{
/**
* Get lengths.
*
* @tparam Integer Integer type.
*
* @param[out] out Array assumed to have at least count() elements.
*/
template<class Integer>
void lengths(Integer* out) const {
frame.lengths(out);
}
/**
* Get strides.
*
* @tparam Integer Integer type.
*
* @param[out] out Array assumed to have at least count() elements.
*/
template<class Integer>
void strides(Integer* out) const {
frame.strides(out);
}
/**
* Get leads.
*
* @tparam Integer Integer type.
*
* @param[out] out Array assumed to have at least count() elements.
*/
template<class Integer>
void leads(Integer* out) const {
frame.leads(out);
}
//@}
/**
* @name Reductions
*/
//@{
/**
* Number of spans in the frame.
*/
static constexpr int count() {
return Frame::count();
}
/**
* Are all elements stored contiguously in memory?
*/
bool contiguous() const {
return frame.contiguous();
}
//@}
/**
* @name Iteration
*/
//@{
/**
* Iterator pointing to the first element.
*
* Iterators are used to access the elements of an array sequentially.
* Elements are visited in the order in which they are stored in memory;
* the rightmost dimension is the fastest moving (for a matrix, this is
* "row major" order).
*
* The idiom of iterator usage is as for the STL.
*/
Iterator<Type,Frame> begin() {
return Iterator<Type,Frame>(ptr, frame);
}
/**
* Iterator pointing to the first element.
*/
Iterator<const Type,Frame> begin() const {
return Iterator<const Type,Frame>(ptr, frame);
}
/**
* Iterator pointing to one beyond the last element.
*/
Iterator<Type,Frame> end() {
return begin() + frame.size();
}
/**
* Iterator pointing to one beyond the last element.
*/
Iterator<const Type,Frame> end() const {
return begin() + frame.size();
}
};
/**
* Default array for `D` dimensions.
*/
template<class Type, int D>
using DefaultArray = Array<Type,typename DefaultFrame<D>::type>;
}
<|endoftext|> |
<commit_before>/*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/*
These routines are used to implement the OS level authentication scheme.
Returns codes of 0 indicate success, others are iRODS error codes.
*/
#include <stdlib.h>
#include <stdio.h>
#include <limits>
#ifndef windows_platform
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#endif
#include "rods.hpp"
#include "rcGlobalExtern.hpp"
#include "authenticate.hpp"
extern "C" {
int
osauthVerifyResponse( char *challenge, char *username, char *response ) {
#if defined(OS_AUTH)
static char fname[] = "osauthVerifyResponse";
char authenticator[16]; /* MD5 hash */
char md5buffer[CHALLENGE_LEN + MAX_PASSWORD_LEN + 2];
char md5digest[RESPONSE_LEN + 2];
int uid, status, i;
char *keybuf;
int key_len;
MD5_CTX ctx;
uid = osauthGetUid( username );
if ( uid == -1 ) {
return SYS_USER_RETRIEVE_ERR;
}
/* read the key from the key file */
if ( ( status = osauthGetKey( &keybuf, &key_len ) ) ) {
rodsLogError( LOG_ERROR, status,
"%s: error retrieving key.", fname );
return status;
}
/* generate the authenticator */
status = osauthGenerateAuthenticator( username, uid, challenge,
keybuf, key_len,
authenticator, 16 );
if ( status ) {
rodsLog( LOG_ERROR,
"%s: could not generate the authenticator", fname );
free( keybuf );
return status;
}
free( keybuf );
/* now append this hash with the challenge, and
take the md5 sum of that */
memset( md5buffer, 0, sizeof( md5buffer ) );
memset( md5digest, 0, sizeof( md5digest ) );
memcpy( md5buffer, challenge, CHALLENGE_LEN );
memcpy( md5buffer + CHALLENGE_LEN, authenticator, 16 );
MD5Init( &ctx );
MD5Update( &ctx, ( unsigned char* )md5buffer, CHALLENGE_LEN + MAX_PASSWORD_LEN );
MD5Final( ( unsigned char* )md5digest, &ctx );
for ( i = 0; i < RESPONSE_LEN; i++ ) {
/* make sure 'string' doesn't end early
(this matches client digest generation). */
if ( md5digest[i] == '\0' ) {
md5digest[i]++;
}
}
/* compare the calculated digest to the client response */
for ( i = 0; i < RESPONSE_LEN; i++ ) {
if ( response[i] != md5digest[i] ) {
rodsLog( LOG_ERROR, "%s: calculated digest doesn't match client response",
fname );
return CAT_INVALID_AUTHENTICATION;
}
}
return 0;
#else /* defined OS_AUTH */
if ( ProcessType == CLIENT_PT ) {
return OSAUTH_NOT_BUILT_INTO_CLIENT;
}
else {
return OSAUTH_NOT_BUILT_INTO_SERVER;
}
#endif
}
/*
* osauthGenerateAuthenticator - this functions creates
* an authenticator from the passed in parameters. The
* parameters are concatenated together, and then an
* md5 hash is generated and provided in the output
* parameter. Returns 0 on success, error code on error.
*/
int
osauthGenerateAuthenticator( char *username, int uid,
char *challenge, char *key, int key_len,
char *authenticator, int authenticator_len ) {
#if defined(OS_AUTH)
static char fname[] = "osauthGenerateAuthenticator";
char *buffer, *bufp;
int buflen;
char md5digest[16];
MD5_CTX ctx;
if ( authenticator == NULL ||
authenticator_len < 16 ) {
return USER_INPUT_OPTION_ERR;
}
/* calculate buffer size and allocate */
buflen = username ? strlen( username ) : 0;
buflen += sizeof( uid ) + CHALLENGE_LEN + key_len;
buffer = ( char* )malloc( buflen );
if ( buffer == NULL ) {
rodsLog( LOG_ERROR,
"%s: could not allocate memory buffer. errno = %d",
fname, errno );
return SYS_MALLOC_ERR;
}
/* concatenate the input parameters */
bufp = buffer;
if ( username && strlen( username ) ) {
memcpy( bufp, username, strlen( username ) );
bufp += strlen( username );
}
#if defined(OS_AUTH_NO_UID)
uid = 0;
#endif
memcpy( bufp, &uid, sizeof( uid ) );
bufp += sizeof( uid );
if ( challenge ) {
memcpy( bufp, challenge, CHALLENGE_LEN );
bufp += CHALLENGE_LEN;
}
if ( key ) {
memcpy( bufp, key, key_len );
}
/* generate an MD5 hash of the buffer, and copy it
to the output parameter authenticator */
MD5Init( &ctx );
MD5Update( &ctx, ( unsigned char* )buffer, buflen );
MD5Final( ( unsigned char* )md5digest, &ctx );
memcpy( authenticator, md5digest, 16 );
return 0;
#else /* defined OS_AUTH */
if ( ProcessType == CLIENT_PT ) {
return OSAUTH_NOT_BUILT_INTO_CLIENT;
}
else {
return OSAUTH_NOT_BUILT_INTO_SERVER;
}
#endif
}
/*
* osauthGetKey - read key from OS_AUTH_KEYFILE
*
* The return parameters include a malloc'ed buffer in
* *key that is the responsibility of the caller to free.
* The length of the buffer is in *key_len.
*/
int
osauthGetKey( char **key, int *key_len ) {
#if defined(OS_AUTH)
static char fname[] = "osauthGetKey";
char *keyfile, *keybuf;
int buflen, key_fd, nb;
if ( key == NULL || key_len == NULL ) {
return USER__NULL_INPUT_ERR;
}
keyfile = getenv( "irodsOsAuthKeyfile" );
if ( keyfile == NULL || *keyfile == '\0' ) {
keyfile = OS_AUTH_KEYFILE;
}
key_fd = open( keyfile, O_RDONLY, 0 );
if ( key_fd < 0 ) {
rodsLog( LOG_ERROR,
"%s: couldn't open %s for reading. errno = %d",
fname, keyfile, errno );
free( keybuf );
return FILE_OPEN_ERR;
}
off_t lseek_return = lseek( key_fd, 0, SEEK_END );
int errsv = errno;
if ( ( off_t )-1 == lseek_return ) {
fprintf( stderr, "SEEK_END lseek failed with error %d.\n", errsv );
close( key_fd );
return UNIX_FILE_LSEEK_ERR;
}
if ( lseek_return > std::numeric_limits<long long>::max() ) {
fprintf( stderr, "file of size %ju is too large for a long long.\n", ( uintmax_t )lseek_return );
close( key_fd );
return UNIX_FILE_LSEEK_ERR;
}
buflen = lseek_return;
lseek_return = lseek( key_fd, 0, SEEK_SET );
errsv = errno;
if ( ( off_t )-1 == lseek_return ) {
fprintf( stderr, "SEEK_SET lseek failed with error %d.\n", errsv );
close( key_fd );
return UNIX_FILE_LSEEK_ERR;
}
keybuf = ( char* )malloc( buflen );
if ( keybuf == NULL ) {
rodsLog( LOG_ERROR,
"%s: could not allocate memory for key buffer. errno = %d",
fname, errno );
return SYS_MALLOC_ERR;
}
nb = read( key_fd, keybuf, buflen );
if ( nb < 0 ) {
rodsLog( LOG_ERROR,
"%s: couldn't read key from %s. errno = %d",
fname, keyfile, errno );
free( keybuf );
return FILE_READ_ERR;
}
close( key_fd );
*key_len = buflen;
*key = keybuf;
return 0;
#else /* defined OS_AUTH */
if ( ProcessType == CLIENT_PT ) {
return OSAUTH_NOT_BUILT_INTO_CLIENT;
}
else {
return OSAUTH_NOT_BUILT_INTO_SERVER;
}
#endif
}
/*
* osauthGetAuth - this function runs the OS_AUTH_CMD command to
* retrieve an authenticator for the calling user.
*/
int
osauthGetAuth( char *challenge,
char *username,
char *authenticator,
int authenticator_buflen ) {
#if defined(OS_AUTH)
static char fname[] = "osauthGetAuth";
int pipe1[2], pipe2[2];
pid_t childPid;
int childStatus = 0;
int child_stdin, child_stdout, nb;
int buflen, challenge_len = CHALLENGE_LEN;
char buffer[128];
if ( challenge == NULL || username == NULL || authenticator == NULL ) {
return USER__NULL_INPUT_ERR;
}
if ( pipe( pipe1 ) < 0 ) {
rodsLog( LOG_ERROR, "%s: pipe1 create failed. errno = %d",
fname, errno );
return SYS_PIPE_ERROR - errno;
}
if ( pipe( pipe2 ) < 0 ) {
rodsLog( LOG_ERROR, "%s: pipe2 create failed. errno = %d",
fname, errno );
close( pipe1[0] );
close( pipe1[1] );
return SYS_PIPE_ERROR - errno;
}
childPid = RODS_FORK();
if ( childPid < 0 ) {
rodsLog( LOG_ERROR, "%s: RODS_FORK failed. errno = %d",
fname, errno );
close( pipe1[0] );
close( pipe1[1] );
close( pipe2[0] );
close( pipe2[1] );
return SYS_FORK_ERROR;
}
else if ( childPid == 0 ) {
/* in the child process */
/* pipe1 will be for child's stdin */
close( pipe1[1] );
dup2( pipe1[0], 0 );
/* pipe2 will be for child's stdout */
close( pipe2[0] );
dup2( pipe2[1], 1 );
/* set the username in an environment variable */
setenv( OS_AUTH_ENV_USER, username, 1 );
/* run the OS_AUTH_CMD */
execlp( OS_AUTH_CMD, OS_AUTH_CMD, ( char* )NULL );
rodsLog( LOG_ERROR, "%s: child execl %s failed. errno = %d",
fname, OS_AUTH_CMD, errno );
}
else {
/* in the parent process */
close( pipe1[0] );
child_stdin = pipe1[1]; /* parent writes to child's stdin */
close( pipe2[1] );
child_stdout = pipe2[0]; /* parent reads from child's stdout */
/* send the challenge to the OS_AUTH_CMD program on its stdin */
nb = write( child_stdin, &challenge_len, sizeof( challenge_len ) );
if ( nb < 0 ) {
rodsLog( LOG_ERROR,
"%s: error writing challenge_len to %s. errno = %d",
fname, OS_AUTH_CMD, errno );
close( child_stdin );
close( child_stdout );
return SYS_PIPE_ERROR - errno;
}
nb = write( child_stdin, challenge, challenge_len );
if ( nb < 0 ) {
rodsLog( LOG_ERROR,
"%s: error writing challenge to %s. errno = %d",
fname, OS_AUTH_CMD, errno );
close( child_stdin );
close( child_stdout );
return SYS_PIPE_ERROR - errno;
}
/* read the response */
buflen = read( child_stdout, buffer, 128 );
if ( buflen < 0 ) {
rodsLog( LOG_ERROR, "%s: error reading from %s. errno = %d",
fname, OS_AUTH_CMD, errno );
close( child_stdin );
close( child_stdout );
return SYS_PIPE_ERROR - errno;
}
close( child_stdin );
close( child_stdout );
if ( waitpid( childPid, &childStatus, 0 ) < 0 ) {
rodsLog( LOG_ERROR, "%s: waitpid error. errno = %d",
fname, errno );
return EXEC_CMD_ERROR;
}
if ( WIFEXITED( childStatus ) ) {
if ( WEXITSTATUS( childStatus ) ) {
rodsLog( LOG_ERROR,
"%s: command failed: %s", fname, buffer );
return EXEC_CMD_ERROR;
}
}
else {
rodsLog( LOG_ERROR,
"%s: some error running %s", fname, OS_AUTH_CMD );
}
/* authenticator is in buffer now */
if ( buflen > authenticator_buflen ) {
rodsLog( LOG_ERROR,
"%s: not enough space in return buffer for authenticator", fname );
return EXEC_CMD_OUTPUT_TOO_LARGE;
}
memcpy( authenticator, buffer, buflen );
}
return 0;
#else /* defined OS_AUTH */
if ( ProcessType == CLIENT_PT ) {
return OSAUTH_NOT_BUILT_INTO_CLIENT;
}
else {
return OSAUTH_NOT_BUILT_INTO_SERVER;
}
#endif
}
/*
* osauthGetUid - looks up the given username using getpwnam
* and returns the user's uid if successful, or -1 if not.
*/
int
osauthGetUid( char *username ) {
static char fname[] = "osauthGetUid";
struct passwd *pwent;
errno = 0;
pwent = getpwnam( username );
if ( pwent == NULL ) {
if ( errno ) {
rodsLog( LOG_ERROR,
"%s: error calling getpwnam for %s. errno = %d",
fname, username ? username : "", errno );
return -1;
}
else {
rodsLog( LOG_ERROR,
"%s: no such user %s", fname, username );
return -1;
}
}
return pwent->pw_uid;
}
/*
* osauthGetUsername - looks up the user identified by
* the uid determined by getuid(). Places the username
* in the provided username buffer and returns the uid
* on success, or -1 if not.
*/
int
osauthGetUsername( char *username, int username_len ) {
static char fname[] = "osauthGetUsername";
struct passwd *pwent;
int uid;
uid = getuid();
errno = 0;
pwent = getpwuid( uid );
if ( pwent == NULL ) {
if ( errno ) {
rodsLog( LOG_ERROR,
"%s: error calling getpwuid for uid %d. errno = %d",
fname, uid, errno );
return -1;
}
else {
rodsLog( LOG_ERROR, "%s: no user with uid %d",
fname, uid );
return -1;
}
}
if ( ( unsigned int )username_len <= strlen( pwent->pw_name ) ) {
rodsLog( LOG_ERROR, "%s: username input buffer too small (%d <= %d)",
fname, username_len, strlen( pwent->pw_name ) );
return -1;
}
strcpy( username, pwent->pw_name );
return uid;
}
} // extern "C"
<commit_msg>[#858] initialized pointer before use<commit_after>/*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/*
These routines are used to implement the OS level authentication scheme.
Returns codes of 0 indicate success, others are iRODS error codes.
*/
#include <stdlib.h>
#include <stdio.h>
#include <limits>
#ifndef windows_platform
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#endif
#include "rods.hpp"
#include "rcGlobalExtern.hpp"
#include "authenticate.hpp"
extern "C" {
int
osauthVerifyResponse( char *challenge, char *username, char *response ) {
#if defined(OS_AUTH)
static char fname[] = "osauthVerifyResponse";
char authenticator[16]; /* MD5 hash */
char md5buffer[CHALLENGE_LEN + MAX_PASSWORD_LEN + 2];
char md5digest[RESPONSE_LEN + 2];
int uid, status, i;
char *keybuf = NULL;
int key_len;
MD5_CTX ctx;
uid = osauthGetUid( username );
if ( uid == -1 ) {
return SYS_USER_RETRIEVE_ERR;
}
/* read the key from the key file */
if ( ( status = osauthGetKey( &keybuf, &key_len ) ) ) {
rodsLogError( LOG_ERROR, status,
"%s: error retrieving key.", fname );
return status;
}
/* generate the authenticator */
status = osauthGenerateAuthenticator( username, uid, challenge,
keybuf, key_len,
authenticator, 16 );
if ( status ) {
rodsLog( LOG_ERROR,
"%s: could not generate the authenticator", fname );
free( keybuf );
return status;
}
free( keybuf );
/* now append this hash with the challenge, and
take the md5 sum of that */
memset( md5buffer, 0, sizeof( md5buffer ) );
memset( md5digest, 0, sizeof( md5digest ) );
memcpy( md5buffer, challenge, CHALLENGE_LEN );
memcpy( md5buffer + CHALLENGE_LEN, authenticator, 16 );
MD5Init( &ctx );
MD5Update( &ctx, ( unsigned char* )md5buffer, CHALLENGE_LEN + MAX_PASSWORD_LEN );
MD5Final( ( unsigned char* )md5digest, &ctx );
for ( i = 0; i < RESPONSE_LEN; i++ ) {
/* make sure 'string' doesn't end early
(this matches client digest generation). */
if ( md5digest[i] == '\0' ) {
md5digest[i]++;
}
}
/* compare the calculated digest to the client response */
for ( i = 0; i < RESPONSE_LEN; i++ ) {
if ( response[i] != md5digest[i] ) {
rodsLog( LOG_ERROR, "%s: calculated digest doesn't match client response",
fname );
return CAT_INVALID_AUTHENTICATION;
}
}
return 0;
#else /* defined OS_AUTH */
if ( ProcessType == CLIENT_PT ) {
return OSAUTH_NOT_BUILT_INTO_CLIENT;
}
else {
return OSAUTH_NOT_BUILT_INTO_SERVER;
}
#endif
}
/*
* osauthGenerateAuthenticator - this functions creates
* an authenticator from the passed in parameters. The
* parameters are concatenated together, and then an
* md5 hash is generated and provided in the output
* parameter. Returns 0 on success, error code on error.
*/
int
osauthGenerateAuthenticator( char *username, int uid,
char *challenge, char *key, int key_len,
char *authenticator, int authenticator_len ) {
#if defined(OS_AUTH)
static char fname[] = "osauthGenerateAuthenticator";
char *buffer, *bufp;
int buflen;
char md5digest[16];
MD5_CTX ctx;
if ( authenticator == NULL ||
authenticator_len < 16 ) {
return USER_INPUT_OPTION_ERR;
}
/* calculate buffer size and allocate */
buflen = username ? strlen( username ) : 0;
buflen += sizeof( uid ) + CHALLENGE_LEN + key_len;
buffer = ( char* )malloc( buflen );
if ( buffer == NULL ) {
rodsLog( LOG_ERROR,
"%s: could not allocate memory buffer. errno = %d",
fname, errno );
return SYS_MALLOC_ERR;
}
/* concatenate the input parameters */
bufp = buffer;
if ( username && strlen( username ) ) {
memcpy( bufp, username, strlen( username ) );
bufp += strlen( username );
}
#if defined(OS_AUTH_NO_UID)
uid = 0;
#endif
memcpy( bufp, &uid, sizeof( uid ) );
bufp += sizeof( uid );
if ( challenge ) {
memcpy( bufp, challenge, CHALLENGE_LEN );
bufp += CHALLENGE_LEN;
}
if ( key ) {
memcpy( bufp, key, key_len );
}
/* generate an MD5 hash of the buffer, and copy it
to the output parameter authenticator */
MD5Init( &ctx );
MD5Update( &ctx, ( unsigned char* )buffer, buflen );
MD5Final( ( unsigned char* )md5digest, &ctx );
memcpy( authenticator, md5digest, 16 );
return 0;
#else /* defined OS_AUTH */
if ( ProcessType == CLIENT_PT ) {
return OSAUTH_NOT_BUILT_INTO_CLIENT;
}
else {
return OSAUTH_NOT_BUILT_INTO_SERVER;
}
#endif
}
/*
* osauthGetKey - read key from OS_AUTH_KEYFILE
*
* The return parameters include a malloc'ed buffer in
* *key that is the responsibility of the caller to free.
* The length of the buffer is in *key_len.
*/
int
osauthGetKey( char **key, int *key_len ) {
#if defined(OS_AUTH)
static char fname[] = "osauthGetKey";
char *keyfile;
int buflen, key_fd, nb;
if ( key == NULL || key_len == NULL ) {
return USER__NULL_INPUT_ERR;
}
keyfile = getenv( "irodsOsAuthKeyfile" );
if ( keyfile == NULL || *keyfile == '\0' ) {
keyfile = OS_AUTH_KEYFILE;
}
key_fd = open( keyfile, O_RDONLY, 0 );
if ( key_fd < 0 ) {
rodsLog( LOG_ERROR,
"%s: couldn't open %s for reading. errno = %d",
fname, keyfile, errno );
return FILE_OPEN_ERR;
}
off_t lseek_return = lseek( key_fd, 0, SEEK_END );
int errsv = errno;
if ( ( off_t )-1 == lseek_return ) {
fprintf( stderr, "SEEK_END lseek failed with error %d.\n", errsv );
close( key_fd );
return UNIX_FILE_LSEEK_ERR;
}
if ( lseek_return > std::numeric_limits<long long>::max() ) {
fprintf( stderr, "file of size %ju is too large for a long long.\n", ( uintmax_t )lseek_return );
close( key_fd );
return UNIX_FILE_LSEEK_ERR;
}
buflen = lseek_return;
lseek_return = lseek( key_fd, 0, SEEK_SET );
errsv = errno;
if ( ( off_t )-1 == lseek_return ) {
fprintf( stderr, "SEEK_SET lseek failed with error %d.\n", errsv );
close( key_fd );
return UNIX_FILE_LSEEK_ERR;
}
char * keybuf = ( char* )malloc( buflen );
if ( keybuf == NULL ) {
rodsLog( LOG_ERROR,
"%s: could not allocate memory for key buffer. errno = %d",
fname, errno );
return SYS_MALLOC_ERR;
}
nb = read( key_fd, keybuf, buflen );
if ( nb < 0 ) {
rodsLog( LOG_ERROR,
"%s: couldn't read key from %s. errno = %d",
fname, keyfile, errno );
free( keybuf );
return FILE_READ_ERR;
}
close( key_fd );
*key_len = buflen;
*key = keybuf;
return 0;
#else /* defined OS_AUTH */
if ( ProcessType == CLIENT_PT ) {
return OSAUTH_NOT_BUILT_INTO_CLIENT;
}
else {
return OSAUTH_NOT_BUILT_INTO_SERVER;
}
#endif
}
/*
* osauthGetAuth - this function runs the OS_AUTH_CMD command to
* retrieve an authenticator for the calling user.
*/
int
osauthGetAuth( char *challenge,
char *username,
char *authenticator,
int authenticator_buflen ) {
#if defined(OS_AUTH)
static char fname[] = "osauthGetAuth";
int pipe1[2], pipe2[2];
pid_t childPid;
int childStatus = 0;
int child_stdin, child_stdout, nb;
int buflen, challenge_len = CHALLENGE_LEN;
char buffer[128];
if ( challenge == NULL || username == NULL || authenticator == NULL ) {
return USER__NULL_INPUT_ERR;
}
if ( pipe( pipe1 ) < 0 ) {
rodsLog( LOG_ERROR, "%s: pipe1 create failed. errno = %d",
fname, errno );
return SYS_PIPE_ERROR - errno;
}
if ( pipe( pipe2 ) < 0 ) {
rodsLog( LOG_ERROR, "%s: pipe2 create failed. errno = %d",
fname, errno );
close( pipe1[0] );
close( pipe1[1] );
return SYS_PIPE_ERROR - errno;
}
childPid = RODS_FORK();
if ( childPid < 0 ) {
rodsLog( LOG_ERROR, "%s: RODS_FORK failed. errno = %d",
fname, errno );
close( pipe1[0] );
close( pipe1[1] );
close( pipe2[0] );
close( pipe2[1] );
return SYS_FORK_ERROR;
}
else if ( childPid == 0 ) {
/* in the child process */
/* pipe1 will be for child's stdin */
close( pipe1[1] );
dup2( pipe1[0], 0 );
/* pipe2 will be for child's stdout */
close( pipe2[0] );
dup2( pipe2[1], 1 );
/* set the username in an environment variable */
setenv( OS_AUTH_ENV_USER, username, 1 );
/* run the OS_AUTH_CMD */
execlp( OS_AUTH_CMD, OS_AUTH_CMD, ( char* )NULL );
rodsLog( LOG_ERROR, "%s: child execl %s failed. errno = %d",
fname, OS_AUTH_CMD, errno );
}
else {
/* in the parent process */
close( pipe1[0] );
child_stdin = pipe1[1]; /* parent writes to child's stdin */
close( pipe2[1] );
child_stdout = pipe2[0]; /* parent reads from child's stdout */
/* send the challenge to the OS_AUTH_CMD program on its stdin */
nb = write( child_stdin, &challenge_len, sizeof( challenge_len ) );
if ( nb < 0 ) {
rodsLog( LOG_ERROR,
"%s: error writing challenge_len to %s. errno = %d",
fname, OS_AUTH_CMD, errno );
close( child_stdin );
close( child_stdout );
return SYS_PIPE_ERROR - errno;
}
nb = write( child_stdin, challenge, challenge_len );
if ( nb < 0 ) {
rodsLog( LOG_ERROR,
"%s: error writing challenge to %s. errno = %d",
fname, OS_AUTH_CMD, errno );
close( child_stdin );
close( child_stdout );
return SYS_PIPE_ERROR - errno;
}
/* read the response */
buflen = read( child_stdout, buffer, 128 );
if ( buflen < 0 ) {
rodsLog( LOG_ERROR, "%s: error reading from %s. errno = %d",
fname, OS_AUTH_CMD, errno );
close( child_stdin );
close( child_stdout );
return SYS_PIPE_ERROR - errno;
}
close( child_stdin );
close( child_stdout );
if ( waitpid( childPid, &childStatus, 0 ) < 0 ) {
rodsLog( LOG_ERROR, "%s: waitpid error. errno = %d",
fname, errno );
return EXEC_CMD_ERROR;
}
if ( WIFEXITED( childStatus ) ) {
if ( WEXITSTATUS( childStatus ) ) {
rodsLog( LOG_ERROR,
"%s: command failed: %s", fname, buffer );
return EXEC_CMD_ERROR;
}
}
else {
rodsLog( LOG_ERROR,
"%s: some error running %s", fname, OS_AUTH_CMD );
}
/* authenticator is in buffer now */
if ( buflen > authenticator_buflen ) {
rodsLog( LOG_ERROR,
"%s: not enough space in return buffer for authenticator", fname );
return EXEC_CMD_OUTPUT_TOO_LARGE;
}
memcpy( authenticator, buffer, buflen );
}
return 0;
#else /* defined OS_AUTH */
if ( ProcessType == CLIENT_PT ) {
return OSAUTH_NOT_BUILT_INTO_CLIENT;
}
else {
return OSAUTH_NOT_BUILT_INTO_SERVER;
}
#endif
}
/*
* osauthGetUid - looks up the given username using getpwnam
* and returns the user's uid if successful, or -1 if not.
*/
int
osauthGetUid( char *username ) {
static char fname[] = "osauthGetUid";
struct passwd *pwent;
errno = 0;
pwent = getpwnam( username );
if ( pwent == NULL ) {
if ( errno ) {
rodsLog( LOG_ERROR,
"%s: error calling getpwnam for %s. errno = %d",
fname, username ? username : "", errno );
return -1;
}
else {
rodsLog( LOG_ERROR,
"%s: no such user %s", fname, username );
return -1;
}
}
return pwent->pw_uid;
}
/*
* osauthGetUsername - looks up the user identified by
* the uid determined by getuid(). Places the username
* in the provided username buffer and returns the uid
* on success, or -1 if not.
*/
int
osauthGetUsername( char *username, int username_len ) {
static char fname[] = "osauthGetUsername";
struct passwd *pwent;
int uid;
uid = getuid();
errno = 0;
pwent = getpwuid( uid );
if ( pwent == NULL ) {
if ( errno ) {
rodsLog( LOG_ERROR,
"%s: error calling getpwuid for uid %d. errno = %d",
fname, uid, errno );
return -1;
}
else {
rodsLog( LOG_ERROR, "%s: no user with uid %d",
fname, uid );
return -1;
}
}
if ( ( unsigned int )username_len <= strlen( pwent->pw_name ) ) {
rodsLog( LOG_ERROR, "%s: username input buffer too small (%d <= %d)",
fname, username_len, strlen( pwent->pw_name ) );
return -1;
}
strcpy( username, pwent->pw_name );
return uid;
}
} // extern "C"
<|endoftext|> |
<commit_before><commit_msg>chore(root): add stub for logger builder include<commit_after>#pragma once
namespace blackhole {
} // namespace blackhole
<|endoftext|> |
<commit_before>#pragma once
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include "common.hpp"
#include "components/logger.hpp"
#include "components/x11/xresources.hpp"
#include "utils/file.hpp"
#include "utils/string.hpp"
LEMONBUDDY_NS
#define GET_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name, var)
#define REQ_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name)
using ptree = boost::property_tree::ptree;
DEFINE_ERROR(value_error);
DEFINE_ERROR(key_error);
class config {
public:
/**
* Construct config
*/
explicit config(const logger& logger, const xresource_manager& xrm)
: m_logger(logger), m_xrm(xrm) {}
/**
* Load configuration and validate bar section
*
* This is done outside the constructor due to boost::di noexcept
*/
void load(string file, string barname) {
m_file = file;
m_current_bar = barname;
if (!file_util::exists(file))
throw application_error("Could not find config file: " + file);
try {
boost::property_tree::read_ini(file, m_ptree);
} catch (const std::exception& e) {
throw application_error(e.what());
}
auto bars = defined_bars();
if (std::find(bars.begin(), bars.end(), m_current_bar) == bars.end())
throw application_error("Undefined bar: " + m_current_bar);
if (has_env("XDG_CONFIG_HOME"))
file = string_util::replace(file, read_env("XDG_CONFIG_HOME"), "$XDG_CONFIG_HOME");
if (has_env("HOME"))
file = string_util::replace(file, read_env("HOME"), "~");
m_logger.trace("config: Loaded %s", file);
m_logger.trace("config: Current bar section: [%s]", bar_section());
}
/**
* Get path of loaded file
*/
string filepath() const {
return m_file;
}
/**
* Get the section name of the bar in use
*/
string bar_section() const {
return "bar/" + m_current_bar;
}
/**
* Get a list of defined bar sections in the current config
*/
vector<string> defined_bars() const {
vector<string> bars;
for (auto&& p : m_ptree) {
if (p.first.compare(0, 4, "bar/") == 0)
bars.emplace_back(p.first.substr(4));
}
return bars;
}
/**
* Build path used to find a parameter in the given section
*/
string build_path(const string& section, const string& key) const {
return section + "." + key;
}
/**
* Get parameter for the current bar by name
*/
template <typename T>
T get(string key) const {
return get<T>(bar_section(), key);
}
/**
* Get value of a variable by section and parameter name
*/
template <typename T>
T get(string section, string key) const {
auto val = m_ptree.get_optional<T>(build_path(section, key));
if (val == boost::none)
throw key_error("Missing parameter [" + section + "." + key + "]");
auto str_val = m_ptree.get<string>(build_path(section, key));
return dereference_var<T>(section, key, str_val, val.get());
}
/**
* Get value of a variable by section and parameter name
* with a default value in case the parameter isn't defined
*/
template <typename T>
T get(string section, string key, T default_value) const {
auto val = m_ptree.get_optional<T>(build_path(section, key));
auto str_val = m_ptree.get_optional<string>(build_path(section, key));
return dereference_var<T>(
section, key, str_val.get_value_or(""), val.get_value_or(default_value));
}
/**
* Get list of values for the current bar by name
*/
template <typename T>
T get_list(string key) const {
return get_list<T>(bar_section(), key);
}
/**
* Get list of values by section and parameter name
*/
template <typename T>
vector<T> get_list(string section, string key) const {
vector<T> vec;
optional<T> value;
while ((value = m_ptree.get_optional<T>(
build_path(section, key) + "-" + to_string(vec.size()))) != boost::none) {
auto str_val = m_ptree.get<string>(build_path(section, key) + "-" + to_string(vec.size()));
vec.emplace_back(dereference_var<T>(section, key, str_val, value.get()));
}
if (vec.empty())
throw key_error("Missing parameter [" + section + "." + key + "-0]");
return vec;
}
/**
* Get list of values by section and parameter name
* with a default list in case the list isn't defined
*/
template <typename T>
vector<T> get_list(string section, string key, vector<T> default_value) const {
vector<T> vec;
optional<T> value;
while ((value = m_ptree.get_optional<T>(
build_path(section, key) + "-" + to_string(vec.size()))) != boost::none) {
auto str_val = m_ptree.get<string>(build_path(section, key) + "-" + to_string(vec.size()));
vec.emplace_back(dereference_var<T>(section, key, str_val, value.get()));
}
if (vec.empty())
return default_value;
else
return vec;
}
/**
* Configure injection module
*/
template <typename T = const config&>
static di::injector<T> configure() {
return di::make_injector(logger::configure(), xresource_manager::configure());
}
protected:
/**
* Find value of a config parameter defined as a reference
* variable using ${section.param} or ${env:VAR}
* ${self.key} may be used to reference the current bar section
*
* @deprecated: ${BAR.key} has been replaced with ${self.key}
* but the former is kept to avoid breaking current configs
*/
template <typename T>
T dereference_var(string ref_section, string ref_key, string var, const T ref_val) const {
auto n = var.find("${");
auto m = var.find("}");
if (n != 0 || m != var.length() - 1)
return ref_val;
auto path = var.substr(2, m - 2);
if (path.find("env:") == 0) {
if (has_env(path.substr(4).c_str()))
return boost::lexical_cast<T>(read_env(path.substr(4).c_str()));
return ref_val;
}
if (path.find("xrdb:") == 0) {
if (std::is_same<string, T>())
return boost::lexical_cast<T>(m_xrm.get_string(path.substr(5)));
else if (std::is_same<float, T>())
return boost::lexical_cast<T>(m_xrm.get_float(path.substr(5)));
else if (std::is_same<int, T>())
return boost::lexical_cast<T>(m_xrm.get_int(path.substr(5)));
}
auto ref_path = build_path(ref_section, ref_key);
if ((n = path.find(".")) == string::npos)
throw value_error("Invalid reference defined at [" + ref_path + "]");
auto section = path.substr(0, n);
section = string_util::replace(section, "BAR", bar_section());
section = string_util::replace(section, "self", bar_section());
auto key = path.substr(n + 1, path.length() - n - 1);
auto val = m_ptree.get_optional<T>(build_path(section, key));
if (val == boost::none)
throw value_error("Unexisting reference defined at [" + ref_path + "]");
auto str_val = m_ptree.get<string>(build_path(section, key));
return dereference_var<T>(section, key, str_val, val.get());
}
private:
const logger& m_logger;
const xresource_manager& m_xrm;
ptree m_ptree;
string m_file;
string m_current_bar;
};
LEMONBUDDY_NS_END
<commit_msg>fix(config): Test type and not value<commit_after>#pragma once
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include "common.hpp"
#include "components/logger.hpp"
#include "components/x11/xresources.hpp"
#include "utils/file.hpp"
#include "utils/string.hpp"
LEMONBUDDY_NS
#define GET_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name, var)
#define REQ_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name)
using ptree = boost::property_tree::ptree;
DEFINE_ERROR(value_error);
DEFINE_ERROR(key_error);
class config {
public:
/**
* Construct config
*/
explicit config(const logger& logger, const xresource_manager& xrm)
: m_logger(logger), m_xrm(xrm) {}
/**
* Load configuration and validate bar section
*
* This is done outside the constructor due to boost::di noexcept
*/
void load(string file, string barname) {
m_file = file;
m_current_bar = barname;
if (!file_util::exists(file))
throw application_error("Could not find config file: " + file);
try {
boost::property_tree::read_ini(file, m_ptree);
} catch (const std::exception& e) {
throw application_error(e.what());
}
auto bars = defined_bars();
if (std::find(bars.begin(), bars.end(), m_current_bar) == bars.end())
throw application_error("Undefined bar: " + m_current_bar);
if (has_env("XDG_CONFIG_HOME"))
file = string_util::replace(file, read_env("XDG_CONFIG_HOME"), "$XDG_CONFIG_HOME");
if (has_env("HOME"))
file = string_util::replace(file, read_env("HOME"), "~");
m_logger.trace("config: Loaded %s", file);
m_logger.trace("config: Current bar section: [%s]", bar_section());
}
/**
* Get path of loaded file
*/
string filepath() const {
return m_file;
}
/**
* Get the section name of the bar in use
*/
string bar_section() const {
return "bar/" + m_current_bar;
}
/**
* Get a list of defined bar sections in the current config
*/
vector<string> defined_bars() const {
vector<string> bars;
for (auto&& p : m_ptree) {
if (p.first.compare(0, 4, "bar/") == 0)
bars.emplace_back(p.first.substr(4));
}
return bars;
}
/**
* Build path used to find a parameter in the given section
*/
string build_path(const string& section, const string& key) const {
return section + "." + key;
}
/**
* Get parameter for the current bar by name
*/
template <typename T>
T get(string key) const {
return get<T>(bar_section(), key);
}
/**
* Get value of a variable by section and parameter name
*/
template <typename T>
T get(string section, string key) const {
auto val = m_ptree.get_optional<T>(build_path(section, key));
if (val == boost::none)
throw key_error("Missing parameter [" + section + "." + key + "]");
auto str_val = m_ptree.get<string>(build_path(section, key));
return dereference_var<T>(section, key, str_val, val.get());
}
/**
* Get value of a variable by section and parameter name
* with a default value in case the parameter isn't defined
*/
template <typename T>
T get(string section, string key, T default_value) const {
auto val = m_ptree.get_optional<T>(build_path(section, key));
auto str_val = m_ptree.get_optional<string>(build_path(section, key));
return dereference_var<T>(
section, key, str_val.get_value_or(""), val.get_value_or(default_value));
}
/**
* Get list of values for the current bar by name
*/
template <typename T>
T get_list(string key) const {
return get_list<T>(bar_section(), key);
}
/**
* Get list of values by section and parameter name
*/
template <typename T>
vector<T> get_list(string section, string key) const {
vector<T> vec;
optional<T> value;
while ((value = m_ptree.get_optional<T>(
build_path(section, key) + "-" + to_string(vec.size()))) != boost::none) {
auto str_val = m_ptree.get<string>(build_path(section, key) + "-" + to_string(vec.size()));
vec.emplace_back(dereference_var<T>(section, key, str_val, value.get()));
}
if (vec.empty())
throw key_error("Missing parameter [" + section + "." + key + "-0]");
return vec;
}
/**
* Get list of values by section and parameter name
* with a default list in case the list isn't defined
*/
template <typename T>
vector<T> get_list(string section, string key, vector<T> default_value) const {
vector<T> vec;
optional<T> value;
while ((value = m_ptree.get_optional<T>(
build_path(section, key) + "-" + to_string(vec.size()))) != boost::none) {
auto str_val = m_ptree.get<string>(build_path(section, key) + "-" + to_string(vec.size()));
vec.emplace_back(dereference_var<T>(section, key, str_val, value.get()));
}
if (vec.empty())
return default_value;
else
return vec;
}
/**
* Configure injection module
*/
template <typename T = const config&>
static di::injector<T> configure() {
return di::make_injector(logger::configure(), xresource_manager::configure());
}
protected:
/**
* Find value of a config parameter defined as a reference
* variable using ${section.param} or ${env:VAR}
* ${self.key} may be used to reference the current bar section
*
* @deprecated: ${BAR.key} has been replaced with ${self.key}
* but the former is kept to avoid breaking current configs
*/
template <typename T>
T dereference_var(string ref_section, string ref_key, string var, const T ref_val) const {
auto n = var.find("${");
auto m = var.find("}");
if (n != 0 || m != var.length() - 1)
return ref_val;
auto path = var.substr(2, m - 2);
if (path.find("env:") == 0) {
if (has_env(path.substr(4).c_str()))
return boost::lexical_cast<T>(read_env(path.substr(4).c_str()));
return ref_val;
}
if (path.find("xrdb:") == 0) {
if (std::is_same<string, T>::value)
return boost::lexical_cast<T>(m_xrm.get_string(path.substr(5)));
else if (std::is_same<float, T>::value)
return boost::lexical_cast<T>(m_xrm.get_float(path.substr(5)));
else if (std::is_same<int, T>::value)
return boost::lexical_cast<T>(m_xrm.get_int(path.substr(5)));
return ref_val;
}
auto ref_path = build_path(ref_section, ref_key);
if ((n = path.find(".")) == string::npos)
throw value_error("Invalid reference defined at [" + ref_path + "]");
auto section = path.substr(0, n);
section = string_util::replace(section, "BAR", bar_section());
section = string_util::replace(section, "self", bar_section());
auto key = path.substr(n + 1, path.length() - n - 1);
auto val = m_ptree.get_optional<T>(build_path(section, key));
if (val == boost::none)
throw value_error("Unexisting reference defined at [" + ref_path + "]");
auto str_val = m_ptree.get<string>(build_path(section, key));
return dereference_var<T>(section, key, str_val, val.get());
}
private:
const logger& m_logger;
const xresource_manager& m_xrm;
ptree m_ptree;
string m_file;
string m_current_bar;
};
LEMONBUDDY_NS_END
<|endoftext|> |
<commit_before>#pragma once
/*
* Covariant Script Version Info
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2018 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*
* Version Format:
* 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1
* | | | |
* | | Minor Status
* | Major
* Master
*
*/
#define COVSCRIPT_VERSION_NUM 3,0,1,2
#define COVSCRIPT_VERSION_STR "3.0.1 Acipenser sinensis(Stable) Build 2"
#define COVSCRIPT_STD_VERSION 190101
#define COVSCRIPT_ABI_VERSION 190101
#if defined(_WIN32) || defined(WIN32)
#define COVSCRIPT_PLATFORM_WIN32
#endif
<commit_msg>Update version.hpp<commit_after>#pragma once
/*
* Covariant Script Version Info
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2018 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*
* Version Format:
* 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1
* | | | |
* | | Minor Status
* | Major
* Master
*
*/
#define COVSCRIPT_VERSION_NUM 3,0,2,2
#define COVSCRIPT_VERSION_STR "3.0.2 Acipenser sinensis(Unstable) Build 2"
#define COVSCRIPT_STD_VERSION 190101
#define COVSCRIPT_ABI_VERSION 190101
#if defined(_WIN32) || defined(WIN32)
#define COVSCRIPT_PLATFORM_WIN32
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#ifndef MethodMock_h__
#define MethodMock_h__
#include <vector>
#include <functional>
#include <atomic>
#include <tuple>
#include "mockutils/TupleDispatcher.hpp"
#include "fakeit/DomainObjects.hpp"
#include "fakeit/ActualInvocation.hpp"
#include "fakeit/Behavior.hpp"
namespace fakeit {
static std::atomic_int invocationOrdinal;
template<typename R, typename ... arglist>
struct MethodInvocationMock: public ActualInvocation<arglist...>::Matcher, public MethodInvocationHandler<R, arglist...> {
virtual std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> getMatcher()= 0;
};
class finally {
private:
std::function<void()> finallyClause;
finally(const finally &);
finally& operator=(const finally &);
public:
explicit finally(std::function<void()> f) :
finallyClause(f) {
}
~finally() {
finallyClause();
}
};
class NoMoreRecordedBehaviorException : public std::exception {
};
template<typename R, typename ... arglist>
struct RecordedMethodBody: public MethodInvocationHandler<R, arglist...> {
RecordedMethodBody(Method & method): method(method) {
clear();
}
void AppendDo(std::function<R(arglist...)> method) {
std::shared_ptr<Behavior<R, arglist...>> doMock = std::shared_ptr<Behavior<R, arglist...>> { new Repeat<R, arglist...>(
method) };
AppendDo(doMock);
}
void LastDo(std::function<R(arglist...)> method) {
std::shared_ptr<Behavior<R, arglist...>> doMock = std::shared_ptr<Behavior<R, arglist...>> { new Repeat<R, arglist...>(
method) };
LastDo(doMock);
}
void AppendDo(std::shared_ptr<Behavior<R, arglist...> > doMock) {
append(doMock);
}
void LastDo(std::shared_ptr<Behavior<R, arglist...> > doMock) {
append(doMock);
behaviorMocks.pop_back();
}
R handleMethodInvocation(arglist&... args) override {
std::shared_ptr<Behavior<R, arglist...>> behavior = behaviorMocks.front();
std::function < void() > finallyClause = [&]()->void {
if (behavior->isDone())
behaviorMocks.erase(behaviorMocks.begin());
};
finally onExit(finallyClause);
return behavior->invoke(args...);
}
private:
struct ThrowUnexpectedMethodCall: public Behavior<R, arglist...> {
virtual ~ThrowUnexpectedMethodCall() = default;
virtual R invoke(arglist&... args) override {
NoMoreRecordedBehaviorException e;
throw e;
}
virtual bool isDone() override {
return false;
}
};
Method & method;
void append(std::shared_ptr<Behavior<R, arglist...>> mock) {
behaviorMocks.insert(behaviorMocks.end() - 1, mock);
}
void clear() {
behaviorMocks.clear();
auto doMock = std::shared_ptr<Behavior<R, arglist...>> { new ThrowUnexpectedMethodCall() };
behaviorMocks.push_back(doMock);
}
std::vector<std::shared_ptr<Behavior<R, arglist...>>>behaviorMocks;
};
template<typename R, typename ... arglist>
struct MethodInvocationMockBase: public virtual MethodInvocationMock<R, arglist...> {
MethodInvocationMockBase(const Method& method, std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> matcher,
std::shared_ptr<MethodInvocationHandler<R, arglist...>> invocationHandler) :
method(method), matcher { matcher }, invocationHandler { invocationHandler } {
}
R handleMethodInvocation(arglist&... args) override {
return invocationHandler->handleMethodInvocation(args...);
}
virtual bool matches(ActualInvocation<arglist...>& actualInvocation) {
return matcher->matches(actualInvocation);
}
std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> getMatcher() override {
return matcher;
}
private:
const Method& method;
std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> matcher;
std::shared_ptr<MethodInvocationHandler<R, arglist...>> invocationHandler;
};
template<typename ... arglist>
struct ExpectedArgumentsInvocationMatcher: public ActualInvocation<arglist...>::Matcher {
ExpectedArgumentsInvocationMatcher(const arglist&... args) :
expectedArguments(args...) {
}
virtual bool matches(ActualInvocation<arglist...>& invocation) override {
if (invocation.getActualMatcher().get() == this)
return true;
return matches(invocation.getActualArguments());
}
private:
virtual bool matches(const std::tuple<arglist...>& actualArgs) {
return expectedArguments == actualArgs;
}
const std::tuple<arglist...> expectedArguments;
};
template<typename ... arglist>
struct UserDefinedInvocationMatcher: public ActualInvocation<arglist...>::Matcher {
UserDefinedInvocationMatcher(std::function<bool(arglist...)> matcher) :
matcher { matcher } {
}
virtual bool matches(ActualInvocation<arglist...>& invocation) override {
if (invocation.getActualMatcher().get() == this)
return true;
return matches(invocation.getActualArguments());
}
private:
virtual bool matches(const std::tuple<arglist...>& actualArgs) {
return invoke<arglist...>(matcher, std::tuple<arglist...> { actualArgs });
}
std::function<bool(arglist...)> matcher;
};
template<typename ... arglist>
struct DefaultInvocationMatcher: public ActualInvocation<arglist...>::Matcher {
DefaultInvocationMatcher() {
}
virtual bool matches(ActualInvocation<arglist...>& invocation) override {
return matches(invocation.getActualArguments());
}
private:
virtual bool matches(const std::tuple<arglist...>& actualArgs) {
return true;
}
};
template<typename C, typename R, typename ... arglist>
class MethodMock: public virtual MethodInvocationHandler<R, arglist...>, public virtual ActualInvocationsSource {
class MethodImpl : public Method {
std::string _name;
public:
MethodImpl(std::string name):_name(name){}
virtual std::string name() const override {
return _name;
}
void setName(const std::string& name){
_name = name;
}
};
MockObject<C>& mock;
R (C::*vMethod)(arglist...);
MethodImpl method;
std::vector<std::shared_ptr<MethodInvocationMock<R, arglist...>>>methodInvocationMocks;
std::vector<std::shared_ptr<ActualInvocation<arglist...>>> actualInvocations;
std::shared_ptr<MethodInvocationMockBase<R, arglist...>> buildMethodInvocationMock(
std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> invocationMatcher,
std::shared_ptr<MethodInvocationHandler<R, arglist...>> invocationHandler) {
return std::shared_ptr<MethodInvocationMockBase<R, arglist...>> {
new MethodInvocationMockBase<R, arglist...>(this->getMethod(), invocationMatcher,
invocationHandler)};
}
std::shared_ptr<MethodInvocationMock<R, arglist...>> getMethodInvocationMockForActualArgs(ActualInvocation<arglist...>& invocation) {
for (auto i = methodInvocationMocks.rbegin(); i != methodInvocationMocks.rend(); ++i) {
if ((*i)->matches(invocation)) {
return (*i);
}
}
return nullptr;
}
public:
MethodMock(MockObject<C>& mock, R (C::*vMethod)(arglist...)) :
mock(mock), vMethod(vMethod), method{typeid(vMethod).name()} {
}
virtual ~MethodMock() {
}
Method& getMethod() {
return method;
}
void stubMethodInvocation(std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> invocationMatcher,
std::shared_ptr<MethodInvocationHandler<R, arglist...>> invocationHandler) {
auto mock = buildMethodInvocationMock(invocationMatcher, invocationHandler);
methodInvocationMocks.push_back(mock);
}
void clear() {
methodInvocationMocks.clear();
}
R handleMethodInvocation(arglist&... args) override {
int ordinal = invocationOrdinal++;
auto actualInvoaction = std::shared_ptr<ActualInvocation<arglist...>> { new ActualInvocation<arglist...>(ordinal, this->getMethod(),
args...) };
auto methodInvocationMock = getMethodInvocationMockForActualArgs(*actualInvoaction);
if (!methodInvocationMock) {
UnexpectedMethodCallException e(this->method);
FakeIt::log(e);
throw e;
}
auto matcher = methodInvocationMock->getMatcher();
actualInvoaction->setActualMatcher(matcher);
actualInvocations.push_back(actualInvoaction);
try {
return methodInvocationMock->handleMethodInvocation(args...);
} catch (NoMoreRecordedBehaviorException&){
UnexpectedMethodCallException e(this->method);
FakeIt::log(e);
throw e;
}
}
std::vector<std::shared_ptr<ActualInvocation<arglist...>> > getActualInvocations(
typename ActualInvocation<arglist...>::Matcher& matcher) {
std::vector < std::shared_ptr<ActualInvocation<arglist...>> > result;
for (auto actualInvocation : actualInvocations) {
if (matcher.matches(*actualInvocation)) {
result.push_back(actualInvocation);
}
}
return result;
}
void getActualInvocations(std::unordered_set<Invocation*>& into) const {
for (auto invocation : actualInvocations) {
into.insert(invocation.get());
}
}
void setMethodDetails(const std::string& mockName, const std::string& methodName) {
const std::string fullName {mockName + "." + methodName};
method.setName(fullName);
}
};
}
#endif // MethodMock_h__
<commit_msg>Refactor. Improve class names.<commit_after>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#ifndef MethodMock_h__
#define MethodMock_h__
#include <vector>
#include <functional>
#include <atomic>
#include <tuple>
#include "mockutils/TupleDispatcher.hpp"
#include "fakeit/DomainObjects.hpp"
#include "fakeit/ActualInvocation.hpp"
#include "fakeit/Behavior.hpp"
namespace fakeit {
static std::atomic_int invocationOrdinal;
template<typename R, typename ... arglist>
struct MethodInvocationMock: public ActualInvocation<arglist...>::Matcher, public MethodInvocationHandler<R, arglist...> {
virtual ~MethodInvocationMock() = default;
virtual std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> getMatcher()= 0;
};
class finally {
private:
std::function<void()> finallyClause;
finally(const finally &);
finally& operator=(const finally &);
public:
explicit finally(std::function<void()> f) :
finallyClause(f) {
}
~finally() {
finallyClause();
}
};
class NoMoreRecordedBehaviorException : public std::exception {
};
template<typename R, typename ... arglist>
struct RecordedMethodBody: public MethodInvocationHandler<R, arglist...> {
RecordedMethodBody(Method & method): method(method) {
clear();
}
void AppendDo(std::function<R(arglist...)> method) {
std::shared_ptr<Behavior<R, arglist...>> doMock = std::shared_ptr<Behavior<R, arglist...>> { new Repeat<R, arglist...>(
method) };
AppendDo(doMock);
}
void LastDo(std::function<R(arglist...)> method) {
std::shared_ptr<Behavior<R, arglist...>> doMock = std::shared_ptr<Behavior<R, arglist...>> { new Repeat<R, arglist...>(
method) };
LastDo(doMock);
}
void AppendDo(std::shared_ptr<Behavior<R, arglist...> > doMock) {
append(doMock);
}
void LastDo(std::shared_ptr<Behavior<R, arglist...> > doMock) {
append(doMock);
behaviorMocks.pop_back();
}
R handleMethodInvocation(arglist&... args) override {
std::shared_ptr<Behavior<R, arglist...>> behavior = behaviorMocks.front();
std::function < void() > finallyClause = [&]()->void {
if (behavior->isDone())
behaviorMocks.erase(behaviorMocks.begin());
};
finally onExit(finallyClause);
return behavior->invoke(args...);
}
private:
struct NoMoreRecordedBehavior: public Behavior<R, arglist...> {
virtual ~NoMoreRecordedBehavior() = default;
virtual R invoke(arglist&... args) override {
NoMoreRecordedBehaviorException e;
throw e;
}
virtual bool isDone() override {
return false;
}
};
Method & method;
void append(std::shared_ptr<Behavior<R, arglist...>> mock) {
behaviorMocks.insert(behaviorMocks.end() - 1, mock);
}
void clear() {
behaviorMocks.clear();
auto doMock = std::shared_ptr<Behavior<R, arglist...>> { new NoMoreRecordedBehavior() };
behaviorMocks.push_back(doMock);
}
std::vector<std::shared_ptr<Behavior<R, arglist...>>>behaviorMocks;
};
template<typename R, typename ... arglist>
struct MethodInvocationMockBase: public virtual MethodInvocationMock<R, arglist...> {
virtual ~MethodInvocationMockBase() = default;
MethodInvocationMockBase(const Method& method, std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> matcher,
std::shared_ptr<MethodInvocationHandler<R, arglist...>> invocationHandler) :
method(method), matcher { matcher }, invocationHandler { invocationHandler } {
}
R handleMethodInvocation(arglist&... args) override {
return invocationHandler->handleMethodInvocation(args...);
}
virtual bool matches(ActualInvocation<arglist...>& actualInvocation) {
return matcher->matches(actualInvocation);
}
std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> getMatcher() override {
return matcher;
}
private:
const Method& method;
std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> matcher;
std::shared_ptr<MethodInvocationHandler<R, arglist...>> invocationHandler;
};
template<typename ... arglist>
struct ExpectedArgumentsInvocationMatcher: public ActualInvocation<arglist...>::Matcher {
virtual ~ExpectedArgumentsInvocationMatcher() = default;
ExpectedArgumentsInvocationMatcher(const arglist&... args) :
expectedArguments(args...) {
}
virtual bool matches(ActualInvocation<arglist...>& invocation) override {
if (invocation.getActualMatcher().get() == this)
return true;
return matches(invocation.getActualArguments());
}
private:
virtual bool matches(const std::tuple<arglist...>& actualArgs) {
return expectedArguments == actualArgs;
}
const std::tuple<arglist...> expectedArguments;
};
template<typename ... arglist>
struct UserDefinedInvocationMatcher: public ActualInvocation<arglist...>::Matcher {
virtual ~UserDefinedInvocationMatcher() = default;
UserDefinedInvocationMatcher(std::function<bool(arglist...)> matcher) :
matcher { matcher } {
}
virtual bool matches(ActualInvocation<arglist...>& invocation) override {
if (invocation.getActualMatcher().get() == this)
return true;
return matches(invocation.getActualArguments());
}
private:
virtual bool matches(const std::tuple<arglist...>& actualArgs) {
return invoke<arglist...>(matcher, std::tuple<arglist...> { actualArgs });
}
std::function<bool(arglist...)> matcher;
};
template<typename ... arglist>
struct DefaultInvocationMatcher: public ActualInvocation<arglist...>::Matcher {
virtual ~DefaultInvocationMatcher() = default;
DefaultInvocationMatcher() {
}
virtual bool matches(ActualInvocation<arglist...>& invocation) override {
return matches(invocation.getActualArguments());
}
private:
virtual bool matches(const std::tuple<arglist...>& actualArgs) {
return true;
}
};
template<typename C, typename R, typename ... arglist>
class MethodMock: public virtual MethodInvocationHandler<R, arglist...>, public virtual ActualInvocationsSource {
class MethodImpl : public Method {
std::string _name;
public:
MethodImpl(std::string name):_name(name){}
virtual std::string name() const override {
return _name;
}
void setName(const std::string& name){
_name = name;
}
};
MockObject<C>& mock;
R (C::*vMethod)(arglist...);
MethodImpl method;
std::vector<std::shared_ptr<MethodInvocationMock<R, arglist...>>>methodInvocationMocks;
std::vector<std::shared_ptr<ActualInvocation<arglist...>>> actualInvocations;
std::shared_ptr<MethodInvocationMockBase<R, arglist...>> buildMethodInvocationMock(
std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> invocationMatcher,
std::shared_ptr<MethodInvocationHandler<R, arglist...>> invocationHandler) {
return std::shared_ptr<MethodInvocationMockBase<R, arglist...>> {
new MethodInvocationMockBase<R, arglist...>(this->getMethod(), invocationMatcher,
invocationHandler)};
}
std::shared_ptr<MethodInvocationMock<R, arglist...>> getMethodInvocationMockForActualArgs(ActualInvocation<arglist...>& invocation) {
for (auto i = methodInvocationMocks.rbegin(); i != methodInvocationMocks.rend(); ++i) {
if ((*i)->matches(invocation)) {
return (*i);
}
}
return nullptr;
}
public:
MethodMock(MockObject<C>& mock, R (C::*vMethod)(arglist...)) :
mock(mock), vMethod(vMethod), method{typeid(vMethod).name()} {
}
virtual ~MethodMock() {
}
Method& getMethod() {
return method;
}
void stubMethodInvocation(std::shared_ptr<typename ActualInvocation<arglist...>::Matcher> invocationMatcher,
std::shared_ptr<MethodInvocationHandler<R, arglist...>> invocationHandler) {
auto mock = buildMethodInvocationMock(invocationMatcher, invocationHandler);
methodInvocationMocks.push_back(mock);
}
void clear() {
methodInvocationMocks.clear();
}
R handleMethodInvocation(arglist&... args) override {
int ordinal = invocationOrdinal++;
auto actualInvoaction = std::shared_ptr<ActualInvocation<arglist...>> { new ActualInvocation<arglist...>(ordinal, this->getMethod(),
args...) };
auto methodInvocationMock = getMethodInvocationMockForActualArgs(*actualInvoaction);
if (!methodInvocationMock) {
UnexpectedMethodCallException e(this->method);
FakeIt::log(e);
throw e;
}
auto matcher = methodInvocationMock->getMatcher();
actualInvoaction->setActualMatcher(matcher);
actualInvocations.push_back(actualInvoaction);
try {
return methodInvocationMock->handleMethodInvocation(args...);
} catch (NoMoreRecordedBehaviorException&){
UnexpectedMethodCallException e(this->method);
FakeIt::log(e);
throw e;
}
}
std::vector<std::shared_ptr<ActualInvocation<arglist...>> > getActualInvocations(
typename ActualInvocation<arglist...>::Matcher& matcher) {
std::vector < std::shared_ptr<ActualInvocation<arglist...>> > result;
for (auto actualInvocation : actualInvocations) {
if (matcher.matches(*actualInvocation)) {
result.push_back(actualInvocation);
}
}
return result;
}
void getActualInvocations(std::unordered_set<Invocation*>& into) const {
for (auto invocation : actualInvocations) {
into.insert(invocation.get());
}
}
void setMethodDetails(const std::string& mockName, const std::string& methodName) {
const std::string fullName {mockName + "." + methodName};
method.setName(fullName);
}
};
}
#endif // MethodMock_h__
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_METAWRITER_HPP
#define MAPNIK_METAWRITER_HPP
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/ctrans.hpp>
#include <mapnik/projection.hpp>
// boost
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
#include <boost/concept_check.hpp>
// stl
#include <set>
#include <string>
namespace mapnik {
class text_placement_info;
class text_path;
/** Implementation of std::map that also returns const& for operator[]. */
class metawriter_property_map
{
public:
typedef std::map<std::string, UnicodeString> property_map;
typedef property_map::const_iterator const_iterator;
metawriter_property_map() :
m_(),
not_found_() {}
UnicodeString const& operator[](std::string const& key) const;
UnicodeString& operator[](std::string const& key) {return m_[key];}
std::map<std::string, UnicodeString>::const_iterator find(std::string const& key) const
{
return m_.find(key);
}
std::map<std::string, UnicodeString>::const_iterator end() const
{
return m_.end();
}
UnicodeString const& get(std::string const& key) const
{
return (*this)[key];
}
private:
property_map m_;
UnicodeString not_found_;
};
/** All properties to be output by a metawriter. */
class metawriter_properties : public std::set<std::string>
{
public:
metawriter_properties(boost::optional<std::string> str);
metawriter_properties() {}
template <class InputIterator> metawriter_properties(
InputIterator first, InputIterator last) : std::set<std::string>(first, last) {}
std::string to_string() const;
};
/** Abstract baseclass for all metawriter classes. */
class metawriter
{
public:
typedef coord_transform<CoordTransform,geometry_type> path_type;
metawriter(metawriter_properties dflt_properties) :
dflt_properties_(dflt_properties),
width_(0),
height_(0) {}
virtual ~metawriter() {}
/** Output a rectangular area.
* \param box Area (in pixel coordinates)
* \param feature The feature being processed
* \param prj_trans Projection transformation
* \param t Coordinate transformation
* \param properties List of properties to output
*/
virtual void add_box(box2d<double> const& box, Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_text(boost::ptr_vector<text_path> &placements,
box2d<double> const& extents,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_polygon(path_type & path,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_line(path_type & path,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
/** Start processing.
* Write file header, init database connection, ...
*
* \param properties metawriter_property_map object with userdefined values.
* Useful for setting filename etc.
*/
virtual void start(metawriter_property_map const& properties)
{
boost::ignore_unused_variable_warning(properties);
}
/** Stop processing.
* Write file footer, close database connection, ...
*/
virtual void stop() {}
/** Set output size (pixels).
* All features that are completely outside this size are discarded.
*/
void set_size(int width, int height) { width_ = width; height_ = height; }
/** Set Map object's srs. */
virtual void set_map_srs(projection const& proj) { /* Not required when working with image coordinates. */ }
/** Return the list of default properties. */
metawriter_properties const& get_default_properties() const { return dflt_properties_;}
protected:
metawriter_properties dflt_properties_;
/** Output width (pixels). */
int width_;
/** Output height (pixels). */
int height_;
};
/** Shared pointer to metawriter object. */
typedef boost::shared_ptr<metawriter> metawriter_ptr;
/** Metawriter object + properties. */
typedef std::pair<metawriter_ptr, metawriter_properties> metawriter_with_properties;
}
#endif // MAPNIK_METAWRITER_HPP
<commit_msg>+ fix unused parameter warning<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_METAWRITER_HPP
#define MAPNIK_METAWRITER_HPP
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/ctrans.hpp>
#include <mapnik/projection.hpp>
// boost
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
#include <boost/concept_check.hpp>
// stl
#include <set>
#include <string>
namespace mapnik {
class text_placement_info;
class text_path;
/** Implementation of std::map that also returns const& for operator[]. */
class metawriter_property_map
{
public:
typedef std::map<std::string, UnicodeString> property_map;
typedef property_map::const_iterator const_iterator;
metawriter_property_map() :
m_(),
not_found_() {}
UnicodeString const& operator[](std::string const& key) const;
UnicodeString& operator[](std::string const& key) {return m_[key];}
std::map<std::string, UnicodeString>::const_iterator find(std::string const& key) const
{
return m_.find(key);
}
std::map<std::string, UnicodeString>::const_iterator end() const
{
return m_.end();
}
UnicodeString const& get(std::string const& key) const
{
return (*this)[key];
}
private:
property_map m_;
UnicodeString not_found_;
};
/** All properties to be output by a metawriter. */
class metawriter_properties : public std::set<std::string>
{
public:
metawriter_properties(boost::optional<std::string> str);
metawriter_properties() {}
template <class InputIterator> metawriter_properties(
InputIterator first, InputIterator last) : std::set<std::string>(first, last) {}
std::string to_string() const;
};
/** Abstract baseclass for all metawriter classes. */
class metawriter
{
public:
typedef coord_transform<CoordTransform,geometry_type> path_type;
metawriter(metawriter_properties dflt_properties) :
dflt_properties_(dflt_properties),
width_(0),
height_(0) {}
virtual ~metawriter() {}
/** Output a rectangular area.
* \param box Area (in pixel coordinates)
* \param feature The feature being processed
* \param prj_trans Projection transformation
* \param t Coordinate transformation
* \param properties List of properties to output
*/
virtual void add_box(box2d<double> const& box, Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_text(boost::ptr_vector<text_path> &placements,
box2d<double> const& extents,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_polygon(path_type & path,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
virtual void add_line(path_type & path,
Feature const& feature,
CoordTransform const& t,
metawriter_properties const& properties)=0;
/** Start processing.
* Write file header, init database connection, ...
*
* \param properties metawriter_property_map object with userdefined values.
* Useful for setting filename etc.
*/
virtual void start(metawriter_property_map const& properties)
{
boost::ignore_unused_variable_warning(properties);
}
/** Stop processing.
* Write file footer, close database connection, ...
*/
virtual void stop() {}
/** Set output size (pixels).
* All features that are completely outside this size are discarded.
*/
void set_size(int width, int height) { width_ = width; height_ = height; }
/** Set Map object's srs. */
virtual void set_map_srs(projection const& proj)
{
boost::ignore_unused_variable_warning(proj);
}
/** Return the list of default properties. */
metawriter_properties const& get_default_properties() const { return dflt_properties_;}
protected:
metawriter_properties dflt_properties_;
/** Output width (pixels). */
int width_;
/** Output height (pixels). */
int height_;
};
/** Shared pointer to metawriter object. */
typedef boost::shared_ptr<metawriter> metawriter_ptr;
/** Metawriter object + properties. */
typedef std::pair<metawriter_ptr, metawriter_properties> metawriter_with_properties;
}
#endif // MAPNIK_METAWRITER_HPP
<|endoftext|> |
<commit_before>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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.
******************************************************************************/
#ifndef NOMLIB_MATH_SIZE2_HEADERS
#define NOMLIB_MATH_SIZE2_HEADERS
#include <iostream>
#include <algorithm>
#include "nomlib/config.hpp"
// FIXME: The following declaration is necessary in order to avoid a very
// nasty compiling conflict that can happen under Windows anytime the
// windef.h header file is included (commonly from windows.h), due to min and
// max macros being declared there. This is why macros are evil.
//
// http://support.microsoft.com/kb/143208
// http://stackoverflow.com/questions/5004858/stdmin-gives-error
#if defined( NOM_PLATFORM_WINDOWS )
#undef min
#undef max
#endif
namespace nom {
/// \brief Delimiter character to use with << operator
const std::string SIZE2_DELIMITER = ", ";
/// \brief Size coordinates (width & height) container
template <typename T>
struct Size2
{
/// Default constructor; initialize values to Size2<T>::null
Size2 ( void ) :
w ( -1 ),
h ( -1 )
{
//NOM_LOG_TRACE(NOM);
}
/// Destructor
~Size2 ( void )
{
//NOM_LOG_TRACE(NOM);
}
/// Constructor variant for initializing width & height at construction
Size2 ( T w, T h ) :
w ( w ),
h ( h )
{
//NOM_LOG_TRACE(NOM);
}
/// \brief Construct an object using a specified value for both members.
Size2( T factor )
{
this->w = factor;
this->h = factor;
}
/// \brief Copy constructor
///
/// \remarks The explicit keyword here will result in compile-time errors
/// in any instance that it finds incompatible casting occurring, such as if
/// you try to down-cast a Size2<int> to a Size2<float>.
template <typename U>
explicit Size2 ( const Size2<U>& copy ) :
w { static_cast<T> ( copy.w ) },
h { static_cast<T> ( copy.h ) }
{
this->w = static_cast<T> ( copy.w );
this->h = static_cast<T> ( copy.h );
}
/// \brief Compare two Size2 objects and return the larger width and height
/// of the two objects.
template <typename U>
Size2 max( const Size2<U>& rhs )
{
return Size2<T>( std::max( this->w, rhs.w ), std::max( this->h, rhs.h ) );
}
/// \brief Compare two Size2 objects and return the smaller width and height
/// of the two objects.
template <typename U>
Size2 min( const Size2<U>& rhs )
{
return Size2<T>( std::min( this->w, rhs.w ), std::min( this->h, rhs.h ) );
}
/// \brief Transpose width and height dimensions.
void swap( void )
{
std::swap( this->w, this->h );
}
/// \brief Null value
///
/// \remarks Null value implementation depends on signed (negative) numbers.
static const Size2 null;
/// \brief Zero value constant.
static const Size2 zero;
/// Represents the width coordinate point
T w;
/// Represents the height coordinate point
T h;
};
/// Pretty print a Size2 object using the following formatting:
///
/// <Size2.x>, <Size2.y>
///
/// An example print:
///
/// 128, 144
template <typename T>
inline std::ostream& operator <<( std::ostream& os, const Size2<T>& pos )
{
os
<< pos.w
<< SIZE2_DELIMITER
<< pos.h;
return os;
}
template <typename T>
inline bool operator ==( const Size2<T>& lhs, const Size2<T>& rhs )
{
return ( lhs.w == rhs.w ) && ( lhs.h == rhs.h );
}
template <typename T>
inline bool operator !=( const Size2<T>& lhs, const Size2<T>& rhs )
{
return ! ( lhs == rhs );
}
/// \brief Method overload of binary operator + (Addition)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \returns Addition of both objects.
template <typename T>
inline Size2<T> operator +( const Size2<T>& lhs, const Size2<T>& rhs )
{
return Size2<T> (
lhs.w + rhs.w,
lhs.h + rhs.h
);
}
/// \brief Method overload of binary operator ++ (Addition by 1)
///
/// \param rhs Right operand.
///
/// \returns Addition of the right operand.
template <typename T>
inline Size2<T> operator ++( const Size2<T>& rhs )
{
return Size2<T> (
++rhs.w,
++rhs.h
);
}
/// \brief Method overload of binary operator - (subtraction)
///
/// \param rhs Right operand.
///
/// \returns Opposite of the object.
template <typename T>
inline Size2<T> operator -( const Size2<T>& rhs )
{
return Size2<T> (
-rhs.w
-rhs.h
);
}
/// \brief Method overload of binary operator - (subtraction)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \returns Subtraction of both objects.
template <typename T>
inline Size2<T> operator -( const Size2<T>& lhs, const Size2<T>& rhs )
{
return Size2<T> (
lhs.w - rhs.w,
lhs.h - rhs.h
);
}
/// \brief Method overload of binary operator -- (subtraction by 1)
///
/// \param rhs Right operand.
///
/// \returns Subtraction of the right operand.
template <typename T>
inline Size2<T> operator --( const Size2<T>& rhs )
{
return Size2<T> (
--rhs.w,
--rhs.h
);
}
/// \brief Method overload of binary operator * (Multiplication)
///
/// \param rhs Left operand.
/// \param rhs Right operand.
///
/// \returns Multiplication of the right operand.
template <typename T>
inline Size2<T> operator *( const Size2<T>& lhs, const Size2<T>& rhs )
{
return Size2<T> ( lhs.w * rhs.w,
lhs.h * rhs.h
);
}
/// \brief Method overload of binary operator += (Addition)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \remarks Addition of both objects; result is assigned to the left
/// operand.
///
/// \returns Reference to left operand,
template <typename T>
inline Size2<T>& operator +=( Size2<T>& lhs, const Size2<T>& rhs )
{
lhs.w += rhs.w;
lhs.h += rhs.h;
return lhs;
}
/// \brief Method overload of binary operator -= (Subtraction)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \remarks Subtraction of both objects; result is assigned to the left
/// operand.
///
/// \returns Reference to left operand.
template <typename T>
inline Size2<T>& operator -=( Size2<T>& lhs, const Size2<T>& rhs )
{
lhs.w -= rhs.w;
lhs.h -= rhs.h;
return lhs;
}
/// \brief Method overload of binary operator *= (Multiplication)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \remarks Multiplication of both objects; result is assigned to the
/// left operand.
///
/// \returns Reference to left operand.
template <typename T>
inline Size2<T>& operator *=( Size2<T>& lhs, const Size2<T>& rhs )
{
lhs.w *= rhs.w;
lhs.h *= rhs.h;
return lhs;
}
/// \brief Method overload of binary operator /= (Division)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \remarks Division of both objects; result is assigned to the
/// left operand.
///
/// \returns Reference to left operand.
template <typename T>
inline Size2<T>& operator /=( Size2<T>& lhs, const Size2<T>& rhs )
{
lhs.w /= rhs.w;
lhs.h /= rhs.h;
return lhs;
}
/// \brief Lesser than comparison operator.
///
/// \param lhs Left operand.
/// \param rhs Right operand.
template <typename T>
inline bool operator <( const Size2<T> lhs, const Size2<T>& rhs )
{
return ( lhs.w < rhs.w ) && ( lhs.h < rhs.h );
}
/// \brief Greater than or equal to comparison operator.
///
/// \param lhs Left operand.
/// \param rhs Right operand.
template <typename T>
inline bool operator >( const Size2<T>& lhs, const Size2<T>& rhs )
{
return ( rhs.w < lhs.w ) && ( rhs.h < lhs.h );
}
/// \brief Lesser than or equal to comparison operator.
///
/// \param lhs Left operand.
/// \param rhs Right operand.
template <typename T>
inline bool operator <=( const Size2<T>& lhs, const Size2<T>& rhs )
{
return ( lhs.w <= rhs.w ) && ( lhs.h <= rhs.h );
}
/// \brief Greater than or equal to comparison operator.
///
/// \param lhs Left operand.
/// \param rhs Right operand.
template <typename T>
inline bool operator >=( const Size2<T>& lhs, const Size2<T>& rhs )
{
return ( rhs.w <= lhs.w ) && ( rhs.h <= lhs.h );
}
/// Size2 object defined using signed integers
typedef Size2<int> Size2i;
/// Size2 object defined using floating point numbers
typedef Size2<float> Size2f;
/// Size2 object defined using double-precision floating point numbers
typedef Size2<double> Size2d;
} // namespace nom
#endif // include guard defined
<commit_msg>Introduce Size2 division operator<commit_after>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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.
******************************************************************************/
#ifndef NOMLIB_MATH_SIZE2_HEADERS
#define NOMLIB_MATH_SIZE2_HEADERS
#include <iostream>
#include <algorithm>
#include "nomlib/config.hpp"
// FIXME: The following declaration is necessary in order to avoid a very
// nasty compiling conflict that can happen under Windows anytime the
// windef.h header file is included (commonly from windows.h), due to min and
// max macros being declared there. This is why macros are evil.
//
// http://support.microsoft.com/kb/143208
// http://stackoverflow.com/questions/5004858/stdmin-gives-error
#if defined( NOM_PLATFORM_WINDOWS )
#undef min
#undef max
#endif
namespace nom {
/// \brief Delimiter character to use with << operator
const std::string SIZE2_DELIMITER = ", ";
/// \brief Size coordinates (width & height) container
template <typename T>
struct Size2
{
/// Default constructor; initialize values to Size2<T>::null
Size2 ( void ) :
w ( -1 ),
h ( -1 )
{
//NOM_LOG_TRACE(NOM);
}
/// Destructor
~Size2 ( void )
{
//NOM_LOG_TRACE(NOM);
}
/// Constructor variant for initializing width & height at construction
Size2 ( T w, T h ) :
w ( w ),
h ( h )
{
//NOM_LOG_TRACE(NOM);
}
/// \brief Construct an object using a specified value for both members.
Size2( T factor )
{
this->w = factor;
this->h = factor;
}
/// \brief Copy constructor
///
/// \remarks The explicit keyword here will result in compile-time errors
/// in any instance that it finds incompatible casting occurring, such as if
/// you try to down-cast a Size2<int> to a Size2<float>.
template <typename U>
explicit Size2 ( const Size2<U>& copy ) :
w { static_cast<T> ( copy.w ) },
h { static_cast<T> ( copy.h ) }
{
this->w = static_cast<T> ( copy.w );
this->h = static_cast<T> ( copy.h );
}
/// \brief Compare two Size2 objects and return the larger width and height
/// of the two objects.
template <typename U>
Size2 max( const Size2<U>& rhs )
{
return Size2<T>( std::max( this->w, rhs.w ), std::max( this->h, rhs.h ) );
}
/// \brief Compare two Size2 objects and return the smaller width and height
/// of the two objects.
template <typename U>
Size2 min( const Size2<U>& rhs )
{
return Size2<T>( std::min( this->w, rhs.w ), std::min( this->h, rhs.h ) );
}
/// \brief Transpose width and height dimensions.
void swap( void )
{
std::swap( this->w, this->h );
}
/// \brief Null value
///
/// \remarks Null value implementation depends on signed (negative) numbers.
static const Size2 null;
/// \brief Zero value constant.
static const Size2 zero;
/// Represents the width coordinate point
T w;
/// Represents the height coordinate point
T h;
};
/// Pretty print a Size2 object using the following formatting:
///
/// <Size2.x>, <Size2.y>
///
/// An example print:
///
/// 128, 144
template <typename T>
inline std::ostream& operator <<( std::ostream& os, const Size2<T>& pos )
{
os
<< pos.w
<< SIZE2_DELIMITER
<< pos.h;
return os;
}
template <typename T>
inline bool operator ==( const Size2<T>& lhs, const Size2<T>& rhs )
{
return ( lhs.w == rhs.w ) && ( lhs.h == rhs.h );
}
template <typename T>
inline bool operator !=( const Size2<T>& lhs, const Size2<T>& rhs )
{
return ! ( lhs == rhs );
}
/// \brief Method overload of binary operator + (Addition)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \returns Addition of both objects.
template <typename T>
inline Size2<T> operator +( const Size2<T>& lhs, const Size2<T>& rhs )
{
return Size2<T> (
lhs.w + rhs.w,
lhs.h + rhs.h
);
}
/// \brief Method overload of binary operator ++ (Addition by 1)
///
/// \param rhs Right operand.
///
/// \returns Addition of the right operand.
template <typename T>
inline Size2<T> operator ++( const Size2<T>& rhs )
{
return Size2<T> (
++rhs.w,
++rhs.h
);
}
/// \brief Method overload of binary operator - (subtraction)
///
/// \param rhs Right operand.
///
/// \returns Opposite of the object.
template <typename T>
inline Size2<T> operator -( const Size2<T>& rhs )
{
return Size2<T> (
-rhs.w
-rhs.h
);
}
/// \brief Method overload of binary operator - (subtraction)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \returns Subtraction of both objects.
template <typename T>
inline Size2<T> operator -( const Size2<T>& lhs, const Size2<T>& rhs )
{
return Size2<T> (
lhs.w - rhs.w,
lhs.h - rhs.h
);
}
/// \brief Method overload of binary operator -- (subtraction by 1)
///
/// \param rhs Right operand.
///
/// \returns Subtraction of the right operand.
template <typename T>
inline Size2<T> operator --( const Size2<T>& rhs )
{
return Size2<T> (
--rhs.w,
--rhs.h
);
}
/// \brief Method overload of binary operator * (Multiplication)
///
/// \param rhs Left operand.
/// \param rhs Right operand.
///
/// \returns Multiplication of the right operand.
template <typename T>
inline Size2<T> operator *( const Size2<T>& lhs, const Size2<T>& rhs )
{
return Size2<T> ( lhs.w * rhs.w,
lhs.h * rhs.h
);
}
/// \brief Method overload of binary operator += (Addition)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \remarks Addition of both objects; result is assigned to the left
/// operand.
///
/// \returns Reference to left operand,
template <typename T>
inline Size2<T>& operator +=( Size2<T>& lhs, const Size2<T>& rhs )
{
lhs.w += rhs.w;
lhs.h += rhs.h;
return lhs;
}
/// \brief Method overload of binary operator -= (Subtraction)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \remarks Subtraction of both objects; result is assigned to the left
/// operand.
///
/// \returns Reference to left operand.
template <typename T>
inline Size2<T>& operator -=( Size2<T>& lhs, const Size2<T>& rhs )
{
lhs.w -= rhs.w;
lhs.h -= rhs.h;
return lhs;
}
/// \brief Method overload of binary operator *= (Multiplication)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \remarks Multiplication of both objects; result is assigned to the
/// left operand.
///
/// \returns Reference to left operand.
template <typename T>
inline Size2<T>& operator *=( Size2<T>& lhs, const Size2<T>& rhs )
{
lhs.w *= rhs.w;
lhs.h *= rhs.h;
return lhs;
}
/// \brief Method overload of binary operator /= (Division assignment)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \remarks Division of both objects; result is assigned to the
/// left operand.
///
/// \returns Reference to left operand.
template <typename T>
inline Size2<T>& operator /=( Size2<T>& lhs, const Size2<T>& rhs )
{
lhs.w /= rhs.w;
lhs.h /= rhs.h;
return lhs;
}
/// \brief Method overload of binary operator / (Division)
///
/// \param lhs Left operand.
/// \param rhs Right operand.
///
/// \returns Size2 template type returned by value
template <typename T>
inline Size2<T> operator /( const Size2<T>& lhs, const Size2<T>& rhs )
{
Size2<T> ret;
ret.w = lhs.w / rhs.w;
ret.h = lhs.h / rhs.h;
return ret;
}
/// \brief Lesser than comparison operator.
///
/// \param lhs Left operand.
/// \param rhs Right operand.
template <typename T>
inline bool operator <( const Size2<T> lhs, const Size2<T>& rhs )
{
return ( lhs.w < rhs.w ) && ( lhs.h < rhs.h );
}
/// \brief Greater than or equal to comparison operator.
///
/// \param lhs Left operand.
/// \param rhs Right operand.
template <typename T>
inline bool operator >( const Size2<T>& lhs, const Size2<T>& rhs )
{
return ( rhs.w < lhs.w ) && ( rhs.h < lhs.h );
}
/// \brief Lesser than or equal to comparison operator.
///
/// \param lhs Left operand.
/// \param rhs Right operand.
template <typename T>
inline bool operator <=( const Size2<T>& lhs, const Size2<T>& rhs )
{
return ( lhs.w <= rhs.w ) && ( lhs.h <= rhs.h );
}
/// \brief Greater than or equal to comparison operator.
///
/// \param lhs Left operand.
/// \param rhs Right operand.
template <typename T>
inline bool operator >=( const Size2<T>& lhs, const Size2<T>& rhs )
{
return ( rhs.w <= lhs.w ) && ( rhs.h <= lhs.h );
}
/// Size2 object defined using signed integers
typedef Size2<int> Size2i;
/// Size2 object defined using floating point numbers
typedef Size2<float> Size2f;
/// Size2 object defined using double-precision floating point numbers
typedef Size2<double> Size2d;
} // namespace nom
#endif // include guard defined
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------
/// \file variant_tree.hpp
//----------------------------------------------------------------------------
/// \brief This file contains a tree class that can hold variant values.
//----------------------------------------------------------------------------
// Author: Serge Aleynikov
// Created: 2010-07-10
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file may be included in various open-source projects.
Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
***** END LICENSE BLOCK *****
*/
#ifndef _UTIL_VARIANT_TREE_HPP_
#define _UTIL_VARIANT_TREE_HPP_
#include <util/variant.hpp>
#include <util/typeinfo.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/throw_exception.hpp>
namespace boost {
namespace property_tree {
// Custom translator that works with util::variant instead of std::string.
// This translator is used to read/write values from files.
template <>
struct translator_between<util::variant, std::string>
{
typedef translator_between<util::variant, std::string> type;
typedef std::string external_type;
typedef util::variant internal_type;
boost::optional<external_type> get_value(const internal_type& value) const {
return boost::optional<external_type>(
value.type() == internal_type::TYPE_NULL ? "" : value.to_string());
}
boost::optional<internal_type> put_value(const external_type& value) const {
try {
long n = lexical_cast<long>(value);
for(external_type::const_iterator it=value.begin(), end=value.end(); it!=end; ++it)
if (*it < '0' || *it > '9')
throw false;
return boost::optional<internal_type>(n);
} catch (...) {}
try {
double n = lexical_cast<double>(value);
return boost::optional<internal_type>(n);
} catch (...) {}
if (value == "true" || value == "false")
return boost::optional<internal_type>(value[0] == 't');
return boost::optional<internal_type>(value);
}
};
} // namespace property_tree
} // namespace boost
namespace util {
namespace detail {
// Custom translator that works with variant instead of std::string
// This translator is used to get/put values through explicit get/put calls.
template <class Ext>
struct variant_translator
{
typedef Ext external_type;
typedef variant internal_type;
/*
typedef boost::mpl::joint_view<variant::int_types,
boost::mpl::vector<bool,double>
> valid_non_string_types;
*/
typedef variant::valid_types valid_types;
external_type get_value(const internal_type& value) const {
return value.get<external_type>();
}
template<typename T>
typename boost::disable_if<
boost::is_same<
boost::mpl::end<valid_types>::type,
boost::mpl::find<variant::valid_types, T>
>,
internal_type>::type
put_value(T value) const {
return variant(value);
}
};
typedef boost::property_tree::basic_ptree<
std::string, // Key type
variant, // Data type
std::less<std::string> // Key comparison
> basic_variant_tree;
} // namespace detail
class variant_tree : public detail::basic_variant_tree
{
typedef detail::basic_variant_tree base;
typedef variant_tree self_type;
public:
typedef boost::property_tree::ptree_bad_path bad_path;
typedef std::pair<const std::string, base> value_type;
variant_tree() {}
variant_tree(const detail::basic_variant_tree& a_rhs)
: detail::basic_variant_tree(a_rhs)
{}
variant_tree(const variant_tree& a_rhs)
: detail::basic_variant_tree(a_rhs)
{}
template <typename Source>
static void read_info(Source& src, variant_tree& tree) {
boost::property_tree::info_parser::read_info(src, static_cast<base&>(tree));
boost::property_tree::translator_between<util::variant, std::string> tr;
translate_data(tr, tree);
}
template <typename T>
static void translate_data(T& tr, base& tree) {
for (variant_tree::iterator it=tree.begin(); it != tree.end(); it++)
translate_data(tr, it->second);
tree.data() = *tr.put_value(tree.get_value<std::string>());
}
template <typename Target>
static void write_info(Target& tar, variant_tree& tree) {
boost::property_tree::info_parser::write_info(tar, static_cast<base&>(tree));
}
template <typename Target, typename Settings>
static void write_info(Target& tar, variant_tree& tree, const Settings& tt) {
boost::property_tree::info_parser::write_info(tar, static_cast<base&>(tree), tt);
}
template <class T>
T get_value() const {
using boost::throw_exception;
if(boost::optional<T> o =
base::get_value_optional<T>(detail::variant_translator<T>())) {
return *o;
}
BOOST_PROPERTY_TREE_THROW(boost::property_tree::ptree_bad_data(
std::string("conversion of data to type \"") +
typeid(T).name() + "\" failed", base::data()));
}
template <class T>
T get_value(const T& default_value) const {
return base::get_value(default_value, detail::variant_translator<T>());
}
std::string get_value(const char* default_value) const {
return base::get_value(std::string(default_value),
detail::variant_translator<std::string>());
}
template <class T>
boost::optional<T> get_value_optional() const {
return base::get_value(detail::variant_translator<T>());
}
template <class T>
void put_value(const T& value) {
base::put_value(value, detail::variant_translator<T>());
}
template <class T>
T get(const path_type& path) const {
try {
return base::get_child(path).BOOST_NESTED_TEMPLATE
get_value<T>(detail::variant_translator<T>());
} catch (boost::bad_get& e) {
std::stringstream s;
s << "Cannot convert value to type '" << type_to_string<T>() << "'";
throw bad_path(s.str(), path);
}
}
template <class T>
T get(const path_type& path, const T& default_value) const {
try {
return base::get(path, default_value, detail::variant_translator<T>());
} catch (boost::bad_get& e) {
throw bad_path("Wrong or missing value type", path);
}
}
std::string get(const path_type& path, const char* default_value) const {
return base::get(path, std::string(default_value),
detail::variant_translator<std::string>());
}
template <class T>
boost::optional<T> get_optional(const path_type& path) const {
return base::get_optional(path, detail::variant_translator<T>());
}
template <class T>
void put(const path_type& path, const T& value) {
base::put(path, value, detail::variant_translator<T>());
}
template <class T>
self_type& add(const path_type& path, const T& value) {
return static_cast<self_type&>(
base::add(path, value, detail::variant_translator<T>()));
}
void swap(variant_tree& rhs) {
base::swap(static_cast<base&>(rhs));
}
void swap(boost::property_tree::basic_ptree<
std::string, variant, std::less<std::string> >& rhs) {
base::swap(rhs);
}
self_type &get_child(const path_type &path) {
return static_cast<self_type&>(base::get_child(path));
}
/** Get the child at the given path, or throw @c ptree_bad_path. */
const self_type &get_child(const path_type &path) const {
return static_cast<const self_type&>(base::get_child(path));
}
/** Get the child at the given path, or return @p default_value. */
self_type &get_child(const path_type &path, self_type &default_value) {
return static_cast<self_type&>(base::get_child(path, default_value));
}
/** Get the child at the given path, or return @p default_value. */
const self_type &get_child(const path_type &path,
const self_type &default_value) const {
return static_cast<const self_type&>(base::get_child(path, default_value));
}
/** Get the child at the given path, or return boost::null. */
boost::optional<self_type &> get_child_optional(const path_type &path) {
boost::optional<base&> o = base::get_child_optional(path);
if (!o)
return boost::optional<self_type&>();
return boost::optional<self_type&>(static_cast<self_type&>(*o));
}
/** Get the child at the given path, or return boost::null. */
boost::optional<const self_type &>
get_child_optional(const path_type &path) const {
boost::optional<const base&> o = base::get_child_optional(path);
if (!o)
return boost::optional<const self_type&>();
return boost::optional<const self_type&>(static_cast<const self_type&>(*o));
}
self_type &put_child(const path_type &path, const self_type &value) {
return static_cast<self_type&>(base::put_child(path, value));
}
};
} // namespace util
#endif // _UTIL_VARIANT_TREE_HPP_
<commit_msg>translate method made protected<commit_after>//----------------------------------------------------------------------------
/// \file variant_tree.hpp
//----------------------------------------------------------------------------
/// \brief This file contains a tree class that can hold variant values.
//----------------------------------------------------------------------------
// Author: Serge Aleynikov
// Created: 2010-07-10
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file may be included in various open-source projects.
Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
***** END LICENSE BLOCK *****
*/
#ifndef _UTIL_VARIANT_TREE_HPP_
#define _UTIL_VARIANT_TREE_HPP_
#include <util/variant.hpp>
#include <util/typeinfo.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/throw_exception.hpp>
namespace boost {
namespace property_tree {
// Custom translator that works with util::variant instead of std::string.
// This translator is used to read/write values from files.
template <>
struct translator_between<util::variant, std::string>
{
typedef translator_between<util::variant, std::string> type;
typedef std::string external_type;
typedef util::variant internal_type;
boost::optional<external_type> get_value(const internal_type& value) const {
return boost::optional<external_type>(
value.type() == internal_type::TYPE_NULL ? "" : value.to_string());
}
boost::optional<internal_type> put_value(const external_type& value) const {
try {
long n = lexical_cast<long>(value);
for(external_type::const_iterator it=value.begin(), end=value.end(); it!=end; ++it)
if (*it < '0' || *it > '9')
throw false;
return boost::optional<internal_type>(n);
} catch (...) {}
try {
double n = lexical_cast<double>(value);
return boost::optional<internal_type>(n);
} catch (...) {}
if (value == "true" || value == "false")
return boost::optional<internal_type>(value[0] == 't');
return boost::optional<internal_type>(value);
}
};
} // namespace property_tree
} // namespace boost
namespace util {
namespace detail {
// Custom translator that works with variant instead of std::string
// This translator is used to get/put values through explicit get/put calls.
template <class Ext>
struct variant_translator
{
typedef Ext external_type;
typedef variant internal_type;
/*
typedef boost::mpl::joint_view<variant::int_types,
boost::mpl::vector<bool,double>
> valid_non_string_types;
*/
typedef variant::valid_types valid_types;
external_type get_value(const internal_type& value) const {
return value.get<external_type>();
}
template<typename T>
typename boost::disable_if<
boost::is_same<
boost::mpl::end<valid_types>::type,
boost::mpl::find<variant::valid_types, T>
>,
internal_type>::type
put_value(T value) const {
return variant(value);
}
};
typedef boost::property_tree::basic_ptree<
std::string, // Key type
variant, // Data type
std::less<std::string> // Key comparison
> basic_variant_tree;
} // namespace detail
class variant_tree : public detail::basic_variant_tree
{
typedef detail::basic_variant_tree base;
typedef variant_tree self_type;
public:
typedef boost::property_tree::ptree_bad_path bad_path;
typedef std::pair<const std::string, base> value_type;
variant_tree() {}
variant_tree(const detail::basic_variant_tree& a_rhs)
: detail::basic_variant_tree(a_rhs)
{}
variant_tree(const variant_tree& a_rhs)
: detail::basic_variant_tree(a_rhs)
{}
template <typename Source>
static void read_info(Source& src, variant_tree& tree) {
boost::property_tree::info_parser::read_info(src, static_cast<base&>(tree));
boost::property_tree::translator_between<util::variant, std::string> tr;
translate_data(tr, tree);
}
template <typename Target>
static void write_info(Target& tar, variant_tree& tree) {
boost::property_tree::info_parser::write_info(tar, static_cast<base&>(tree));
}
template <typename Target, typename Settings>
static void write_info(Target& tar, variant_tree& tree, const Settings& tt) {
boost::property_tree::info_parser::write_info(tar, static_cast<base&>(tree), tt);
}
template <class T>
T get_value() const {
using boost::throw_exception;
if(boost::optional<T> o =
base::get_value_optional<T>(detail::variant_translator<T>())) {
return *o;
}
BOOST_PROPERTY_TREE_THROW(boost::property_tree::ptree_bad_data(
std::string("conversion of data to type \"") +
typeid(T).name() + "\" failed", base::data()));
}
template <class T>
T get_value(const T& default_value) const {
return base::get_value(default_value, detail::variant_translator<T>());
}
std::string get_value(const char* default_value) const {
return base::get_value(std::string(default_value),
detail::variant_translator<std::string>());
}
template <class T>
boost::optional<T> get_value_optional() const {
return base::get_value(detail::variant_translator<T>());
}
template <class T>
void put_value(const T& value) {
base::put_value(value, detail::variant_translator<T>());
}
template <class T>
T get(const path_type& path) const {
try {
return base::get_child(path).BOOST_NESTED_TEMPLATE
get_value<T>(detail::variant_translator<T>());
} catch (boost::bad_get& e) {
std::stringstream s;
s << "Cannot convert value to type '" << type_to_string<T>() << "'";
throw bad_path(s.str(), path);
}
}
template <class T>
T get(const path_type& path, const T& default_value) const {
try {
return base::get(path, default_value, detail::variant_translator<T>());
} catch (boost::bad_get& e) {
throw bad_path("Wrong or missing value type", path);
}
}
std::string get(const path_type& path, const char* default_value) const {
return base::get(path, std::string(default_value),
detail::variant_translator<std::string>());
}
template <class T>
boost::optional<T> get_optional(const path_type& path) const {
return base::get_optional(path, detail::variant_translator<T>());
}
template <class T>
void put(const path_type& path, const T& value) {
base::put(path, value, detail::variant_translator<T>());
}
template <class T>
self_type& add(const path_type& path, const T& value) {
return static_cast<self_type&>(
base::add(path, value, detail::variant_translator<T>()));
}
void swap(variant_tree& rhs) {
base::swap(static_cast<base&>(rhs));
}
void swap(boost::property_tree::basic_ptree<
std::string, variant, std::less<std::string> >& rhs) {
base::swap(rhs);
}
self_type &get_child(const path_type &path) {
return static_cast<self_type&>(base::get_child(path));
}
/** Get the child at the given path, or throw @c ptree_bad_path. */
const self_type &get_child(const path_type &path) const {
return static_cast<const self_type&>(base::get_child(path));
}
/** Get the child at the given path, or return @p default_value. */
self_type &get_child(const path_type &path, self_type &default_value) {
return static_cast<self_type&>(base::get_child(path, default_value));
}
/** Get the child at the given path, or return @p default_value. */
const self_type &get_child(const path_type &path,
const self_type &default_value) const {
return static_cast<const self_type&>(base::get_child(path, default_value));
}
/** Get the child at the given path, or return boost::null. */
boost::optional<self_type &> get_child_optional(const path_type &path) {
boost::optional<base&> o = base::get_child_optional(path);
if (!o)
return boost::optional<self_type&>();
return boost::optional<self_type&>(static_cast<self_type&>(*o));
}
/** Get the child at the given path, or return boost::null. */
boost::optional<const self_type &>
get_child_optional(const path_type &path) const {
boost::optional<const base&> o = base::get_child_optional(path);
if (!o)
return boost::optional<const self_type&>();
return boost::optional<const self_type&>(static_cast<const self_type&>(*o));
}
self_type &put_child(const path_type &path, const self_type &value) {
return static_cast<self_type&>(base::put_child(path, value));
}
protected:
template <typename T>
static void translate_data(T& tr, base& tree) {
for (variant_tree::iterator it=tree.begin(); it != tree.end(); it++)
translate_data(tr, it->second);
tree.data() = *tr.put_value(tree.get_value<std::string>());
}
};
} // namespace util
#endif // _UTIL_VARIANT_TREE_HPP_
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------
/// \file signal_block.hpp
/// \author Serge ALeynikov <saleyn@gmail.com>
/// \author Peter Simons <simons@cryp.to> (signal_block/unblock)
//----------------------------------------------------------------------------
/// \brief Signal blocking class.
//----------------------------------------------------------------------------
// Copyright (c) 2014 Serge Aleynikov <saleyn@gmail.com>
// Copyright (c) 2010 Peter Simons <simons@cryp.to> (signal_block/unblock)
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (c) 2014 Serge Aleynikov
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
***** END LICENSE BLOCK *****
*/
#pragma once
#include <boost/noncopyable.hpp>
#include <utxx/error.hpp>
#include <signal.h>
namespace utxx
{
/// Block all POSIX signals in the current scope.
/// \sa signal_unblock
class signal_block : private boost::noncopyable {
sigset_t m_orig_mask;
bool m_restore;
static sigset_t full() { sigset_t s; ::sigfillset(&s); return s; }
static sigset_t empty() { sigset_t s; ::sigemptyset(&s); return s; }
public:
explicit signal_block(bool a_block = true, bool a_restore = true)
: signal_block(a_block ? full() : empty(), a_restore)
{}
explicit signal_block(sigset_t const& a_block, bool a_restore = true)
: m_restore(a_restore)
{
if (sigisemptyset(&a_block))
::sigemptyset(&m_orig_mask);
else
block();
}
void block() {
sigset_t block_all;
if (::sigfillset(&block_all) < 0)
UTXX_THROW_IO_ERROR(errno, "sigfillset(3)");
if (::sigprocmask(SIG_SETMASK, &block_all, &m_orig_mask))
UTXX_THROW_IO_ERROR(errno, "sigprocmask(2)");
}
~signal_block() {
if (!sigisemptyset(&m_orig_mask) && m_restore)
::sigprocmask(SIG_SETMASK, &m_orig_mask, static_cast<sigset_t*>(0));
}
};
/// Unblock all POSIX signals in the current scope.
/// \sa signal_block
class signal_unblock : private boost::noncopyable {
sigset_t m_orig_mask;
bool m_restore;
public:
signal_unblock(bool a_restore = true)
: m_restore(a_restore)
{
sigset_t l_unblock_all;
if (::sigemptyset(&l_unblock_all) < 0)
UTXX_THROW_IO_ERROR(errno, "sigfillset(3)");
if (::sigprocmask(SIG_SETMASK, &l_unblock_all, &m_orig_mask))
UTXX_THROW_IO_ERROR(errno, "sigprocmask(2)");
}
~signal_unblock() {
if (m_restore)
::sigprocmask(SIG_SETMASK, &m_orig_mask, static_cast<sigset_t*>(0));
}
};
/// Get a list of all known signal names.
/// @return list of char strings that can be iterated until NULL.
const char** sig_names();
/// Total number of "well-known" signal names in the sig_names() array
static constexpr size_t sig_names_count() { return 64; }
/// Get the name of an OS signal number.
/// @return signal name or "<UNDEFINED>" if the name is not defined.
const char* sig_name(int a_signum);
/// Convert signal set to string
std::string sig_members(const sigset_t& a_set);
/// Initialize a signal set from an argument list
template <class... Signals>
sigset_t sig_init_set(Signals&&... args) {
sigset_t sset;
sigemptyset(&sset);
int sigs[] = { args... };
for (uint i=0; i < sizeof...(Signals); ++i)
if (sigaddset(&sset, sigs[i]) < 0)
UTXX_THROW_IO_ERROR(errno, "Error in sigaddset[", sigs[i], ']');
return sset;
}
/// Parse a string containing pipe/comma/column/space delimited signal names.
/// The signal names are case insensitive and not required to begin with "SIG".
sigset_t sig_members_parse(const std::string& a_signals, src_info&& a_si);
/// Convert a vector of integer signal numbers to sigset
sigset_t sig_vector_to_set(const std::vector<int>& a_signals);
/// Return a formatted string containing current signals
inline std::string curr_signals_to_str(utxx::src_info&& si = utxx::src_info(), bool decode=false) {
sigset_t old;
char res[1024], buf[64];
if (sigprocmask(SIG_SETMASK, NULL, &old) < 0)
strcpy(buf, "<error>");
else
snprintf(buf, sizeof(buf), "%lx", reinterpret_cast<uint64_t&>(old));
auto n = snprintf(res, sizeof(res), "%sPID: %d SigMask: %s",
si.empty() ? "" : si.to_string("[","] ").c_str(), getpid(), res);
if (decode)
snprintf(res+n, sizeof(res)-n, " %s", utxx::sig_members(old).c_str());
return res;
}
} // namespace utxx
<commit_msg>Fix bug<commit_after>//----------------------------------------------------------------------------
/// \file signal_block.hpp
/// \author Serge ALeynikov <saleyn@gmail.com>
/// \author Peter Simons <simons@cryp.to> (signal_block/unblock)
//----------------------------------------------------------------------------
/// \brief Signal blocking class.
//----------------------------------------------------------------------------
// Copyright (c) 2014 Serge Aleynikov <saleyn@gmail.com>
// Copyright (c) 2010 Peter Simons <simons@cryp.to> (signal_block/unblock)
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (c) 2014 Serge Aleynikov
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
***** END LICENSE BLOCK *****
*/
#pragma once
#include <boost/noncopyable.hpp>
#include <utxx/error.hpp>
#include <signal.h>
namespace utxx
{
/// Block all POSIX signals in the current scope.
/// \sa signal_unblock
class signal_block : private boost::noncopyable {
sigset_t m_orig_mask;
bool m_restore;
static sigset_t full() { sigset_t s; ::sigfillset(&s); return s; }
static sigset_t empty() { sigset_t s; ::sigemptyset(&s); return s; }
public:
explicit signal_block(bool a_block = true, bool a_restore = true)
: signal_block(a_block ? full() : empty(), a_restore)
{}
explicit signal_block(sigset_t const& a_block, bool a_restore = true)
: m_restore(a_restore)
{
if (sigisemptyset(&a_block))
::sigemptyset(&m_orig_mask);
else
block();
}
void block() {
sigset_t block_all;
if (::sigfillset(&block_all) < 0)
UTXX_THROW_IO_ERROR(errno, "sigfillset(3)");
if (::sigprocmask(SIG_SETMASK, &block_all, &m_orig_mask))
UTXX_THROW_IO_ERROR(errno, "sigprocmask(2)");
}
~signal_block() {
if (!sigisemptyset(&m_orig_mask) && m_restore)
::sigprocmask(SIG_SETMASK, &m_orig_mask, static_cast<sigset_t*>(0));
}
};
/// Unblock all POSIX signals in the current scope.
/// \sa signal_block
class signal_unblock : private boost::noncopyable {
sigset_t m_orig_mask;
bool m_restore;
public:
signal_unblock(bool a_restore = true)
: m_restore(a_restore)
{
sigset_t l_unblock_all;
if (::sigemptyset(&l_unblock_all) < 0)
UTXX_THROW_IO_ERROR(errno, "sigfillset(3)");
if (::sigprocmask(SIG_SETMASK, &l_unblock_all, &m_orig_mask))
UTXX_THROW_IO_ERROR(errno, "sigprocmask(2)");
}
~signal_unblock() {
if (m_restore)
::sigprocmask(SIG_SETMASK, &m_orig_mask, static_cast<sigset_t*>(0));
}
};
/// Get a list of all known signal names.
/// @return list of char strings that can be iterated until NULL.
const char** sig_names();
/// Total number of "well-known" signal names in the sig_names() array
static constexpr size_t sig_names_count() { return 64; }
/// Get the name of an OS signal number.
/// @return signal name or "<UNDEFINED>" if the name is not defined.
const char* sig_name(int a_signum);
/// Convert signal set to string
std::string sig_members(const sigset_t& a_set);
/// Initialize a signal set from an argument list
template <class... Signals>
sigset_t sig_init_set(Signals&&... args) {
sigset_t sset;
sigemptyset(&sset);
int sigs[] = { args... };
for (uint i=0; i < sizeof...(Signals); ++i)
if (sigaddset(&sset, sigs[i]) < 0)
UTXX_THROW_IO_ERROR(errno, "Error in sigaddset[", sigs[i], ']');
return sset;
}
/// Parse a string containing pipe/comma/column/space delimited signal names.
/// The signal names are case insensitive and not required to begin with "SIG".
sigset_t sig_members_parse(const std::string& a_signals, src_info&& a_si);
/// Convert a vector of integer signal numbers to sigset
sigset_t sig_vector_to_set(const std::vector<int>& a_signals);
/// Return a formatted string containing current signals
inline std::string curr_signals_to_str(utxx::src_info&& si = utxx::src_info(), bool decode=false) {
sigset_t old;
char res[1024], buf[64];
if (sigprocmask(SIG_SETMASK, NULL, &old) < 0)
strcpy(buf, "<error>");
else
snprintf(buf, sizeof(buf), "%lx", reinterpret_cast<uint64_t&>(old));
auto n = snprintf(res, sizeof(res), "%sPID: %d SigMask: %s",
si.empty() ? "" : si.to_string("[","] ").c_str(), getpid(), buf);
if (decode)
snprintf(res+n, sizeof(res)-n, " %s", utxx::sig_members(old).c_str());
return res;
}
} // namespace utxx
<|endoftext|> |
<commit_before>//============================================================================
// vSMC/include/vsmc/core/monitor.hpp
//----------------------------------------------------------------------------
// vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// 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.
//
// 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 HOLDER 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.
//============================================================================
#ifndef VSMC_CORE_MONITOR_HPP
#define VSMC_CORE_MONITOR_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/utility/aligned_memory.hpp>
#if VSMC_HAS_MKL
#include <vsmc/utility/mkl.hpp>
#endif
#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(func) \
VSMC_RUNTIME_ASSERT( \
(id < dim()), "**Monitor::" #func "** INVALID ID NUMBER ARGUMENT")
#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(func) \
VSMC_RUNTIME_ASSERT((iter < iter_size()), \
"**Monitor::" #func "** INVALID ITERATION NUMBER ARGUMENT")
#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_FUNCTOR(func, caller, name) \
VSMC_RUNTIME_ASSERT(static_cast<bool>(func), \
"**Monitor::" #caller "** INVALID " #name " OBJECT")
namespace vsmc
{
/// \brief Monitor for Monte Carlo integration
/// \ingroup Core
template <typename T>
class Monitor
{
public:
typedef T value_type;
typedef std::function<void(
std::size_t, std::size_t, const Particle<T> &, double *)> eval_type;
/// \brief Construct a Monitor with an evaluation object
///
/// \param dim The dimension of the Monitor, i.e., the number of variables
/// \param eval The evaluation object of type Monitor::eval_type
/// \param record_only The Monitor only records results instead of
/// calculating them itself
/// \param stage The stage of the Monitor. A Monitor may be evaluated
/// after
/// all steps that move the particles but before any resampling
/// (`MonitorMove`), or the possible resampling step but before any MCMC
/// steps (`MonitorResample`), all after all MCMC steps (`MonitorMCMC`).
/// If
/// a Monitor is present during initialization, then the initialization
/// are
/// taken as the step that moves particles, and both `MonitorResample` and
/// `MonitorMCMC` are considered after the possible resampling.
///
/// The evaluation object has the signature
/// ~~~{.cpp}
/// void eval (std::size_t iter, std::size_t dim, const Particle<T>
/// &particle, double *result)
/// ~~~
/// where the first three arguments are passed in by the Sampler at the
/// end of each iteration. The evaluation occurs after the possible MCMC
/// moves. The output parameter `result` shall contain the results of the
/// evaluation.
///
/// If `record_only` is true, then the monitor only records the values
/// stored in `result`. Otherwise, the behavior is explained below
///
/// The array `result` is of length `particle.size() * dim`, and it
/// represents a row major matrix of dimension `particle.size()` by `dim`,
/// say \f$R\f$. Let \f$W\f$ be the vector of the normalized weights. The
/// Monitor will be respoinsible to compute the importance sampling
/// estimate \f$r = R^TW\f$ and record it. For example, say the purpose of
/// the Monitor is to record the importance sampling estimates of
/// \f$E[h(X)]\f$ where \f$h(X) = (h_1(X),\dots,h_d(X))\f$. Then `result`
/// shall contain the evaluation of \f$h(X_i)\f$ for each \f$i\f$ from `0`
/// to `particle.size() - 1` in the order
/// \f$(h_1(X_0), \dots, h_d(X_0), h_1(X_1), \dots, h_d(X_1), \dots)\f$.
///
/// After each evaluation, the iteration number `iter` and the imporatance
/// sampling estimates are recorded and can be retrived by `index()` and
/// `record()`.
explicit Monitor(std::size_t dim, const eval_type &eval,
bool record_only = false, MonitorStage stage = MonitorMCMC)
: dim_(dim)
, eval_(eval)
, recording_(true)
, record_only_(record_only)
, stage_(stage)
, name_(dim)
{
}
/// \brief The dimension of the Monitor
std::size_t dim() const { return dim_; }
/// \brief If this is a record only Monitor
bool record_only() const { return record_only_; }
/// \brief The stage of the Montior
MonitorStage stage() const { return stage_; }
/// \brief The number of iterations has been recorded
///
/// \details
/// This is not necessarily the same as Sampler<T>::iter_size. For
/// example, a Monitor can be added only after a certain time point of the
/// sampler's iterations. Also the Monitor can be turned off for a period
/// during the iterations.
std::size_t iter_size() const { return index_.size(); }
/// \brief Reserve space for a specified number of iterations
void reserve(std::size_t num)
{
index_.reserve(num);
record_.reserve(dim_ * num);
}
/// \brief Whether the evaluation object is valid
bool empty() const { return !static_cast<bool>(eval_); }
/// \brief Read and write access to the names of variables
///
/// \details
/// By default, each variable of a Monitor is unnamed and the returned
/// string is empty. However, the user can selectively set the names of
/// each variable. This effect how Sampler will print the headers of the
/// summary table.
std::string &name(std::size_t id)
{
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(name);
return name_[id];
}
/// \brief Read only access to the names of variables
const std::string &name(std::size_t id) const
{
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(name);
return name_[id];
}
/// \brief Get the iteration index of the sampler of a given Monitor
/// iteration
///
/// \details
/// For example, if a Monitor is only added to the sampler at the
/// sampler's iteration `siter`. Then `index(0)` will be `siter` and so
/// on. If the Monitor is added before the sampler's initialization and
/// continued to be evaluated during the iterations without calling
/// `turnoff()`, then iter(iter) shall just be `iter`.
std::size_t index(std::size_t iter) const
{
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(index);
return index_[iter];
}
/// \brief Get the latest Monte Carlo integration record of a given
/// variable
///
/// \details
/// For a `dim` dimension Monitor, `id` shall be 0 to `dim` - 1
double record(std::size_t id) const
{
std::size_t iter = iter_size() ? iter_size() - 1 : iter_size();
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(record);
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(record);
return record_[iter * dim_ + id];
}
/// \brief Get the Monte Carlo integration record of a given variable and
/// the Monitor iteration
///
/// \details
/// For a `dim` dimension Monitor, `id` shall be 0 to `dim` - 1
double record(std::size_t id, std::size_t iter) const
{
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(record);
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(record);
return record_[iter * dim_ + id];
}
/// \brief Read the index history through an output iterator
template <typename OutputIter>
void read_index(OutputIter first) const
{
std::copy(index_.begin(), index_.end(), first);
}
/// \brief Read only access to the raw data of the index vector
const std::size_t *index_data() const { return index_.data(); }
/// \brief Read only access to the raw data of records (a row major
/// matrix)
const double *record_data() const { return record_.data(); }
/// \brief Read only access to the raw data of records for a given
/// Monitor iteration
const double *record_data(std::size_t iter) const
{
return record_.data() + iter * dim_;
}
/// \brief Read the record history for a given variable through an output
/// iterator
template <typename OutputIter>
void read_record(std::size_t id, OutputIter first) const
{
const std::size_t N = iter_size();
const double *riter = record_.data() + id;
for (std::size_t i = 0; i != N; ++i, ++first, riter += dim_)
*first = *riter;
}
/// \brief Read the record history of all variables through an array of
/// output iterators
///
/// \param first An iterator of container of output iterators
template <typename OutputIterIter>
void read_record_matrix(OutputIterIter first) const
{
for (std::size_t d = 0; d != dim_; ++d, ++first)
read_record(d, *first);
}
/// \brief Read the record history of all variables through an output
/// iterator
///
/// \param first The output iterator
///
/// For example, say `first` is of type `double *`, then if `order ==
/// ColMajor`, then, `first[j * iter_size() + i] == record(i, j)`.
/// Otherwise, if `order == RowMajor`, then `first[i * dim() + j] ==
/// record(i, j)`. That is, the output is an `iter_size()` by `dim()`
/// matrix, with the usual meaning of column or row major order.
template <MatrixOrder Order, typename OutputIter>
void read_record_matrix(OutputIter first) const
{
const std::size_t N = iter_size();
if (Order == ColMajor) {
for (std::size_t d = 0; d != dim_; ++d) {
const double *riter = record_.data() + d;
for (std::size_t i = 0; i != N; ++i, ++first, riter += dim_)
*first = *riter;
}
}
if (Order == RowMajor)
std::copy(record_.begin(), record_.end(), first);
}
/// \brief Set a new evaluation object of type eval_type
void set_eval(const eval_type &new_eval) { eval_ = new_eval; }
/// \brief Perform the evaluation for a given iteration and a Particle<T>
/// object.
///
/// \details
/// This function is called by a Sampler at the end of each
/// iteration. It does nothing if `recording()` returns `false`. Otherwise
/// it use the user defined evaluation object to compute results. When a
/// Monitor is constructed, `recording()` always returns `true`. It can be
/// turned off by `turn_off()` and turned on later by `turn_on()`.
void eval(
std::size_t iter, const Particle<T> &particle, MonitorStage stage)
{
if (!recording_)
return;
if (stage != stage_)
return;
VSMC_RUNTIME_ASSERT_CORE_MONITOR_FUNCTOR(eval_, eval, EVALUATION);
result_.resize(dim_);
if (record_only_) {
eval_(iter, dim_, particle, result_.data());
push_back(iter);
return;
}
const std::size_t N = static_cast<std::size_t>(particle.size());
buffer_.resize(N * dim_);
eval_(iter, dim_, particle, buffer_.data());
#if VSMC_HAS_MKL
if (ss_task_.ptr() == nullptr) {
MKL_INT p = static_cast<MKL_INT>(dim_);
MKL_INT n = static_cast<MKL_INT>(N);
MKL_INT xstorage = VSL_SS_MATRIX_STORAGE_COLS;
ss_task_.reset(
&p, &n, &xstorage, buffer_.data(), result_.data(), nullptr);
}
::vsldSSCompute(ss_task_.ptr(), VSL_SS_MEAN, VSL_SS_METHOD_FAST);
#ifdef VSMC_CBLAS_INT
::cblas_dgemv(::CblasColMajor, ::CblasNoTrans,
static_cast<VSMC_CBLAS_INT>(dim_), static_cast<VSMC_CBLAS_INT>(N),
1, buffer_.data(), static_cast<VSMC_CBLAS_INT>(dim_),
particle.weight_set().weight_data(), 1, 0, result_.data(), 1);
#else // VSMC_CBLAS_INT
const double *wptr = particle.weight_set().weight_data();
const double *bptr = buffer_.data();
std::fill(result_.begin(), result_.end(), 0.0);
for (std::size_t i = 0; i != N; ++i)
for (std::size_t d = 0; d != dim_; ++d, ++bptr)
result_[d] += particle.weight_set().weight(i) * (*bptr);
#endif // VSMC_CBLAS_INT
#endif // VSMC_HAS_MKL
push_back(iter);
}
/// \brief Clear all records of the index and integrations
void clear()
{
index_.clear();
record_.clear();
}
/// \brief Whether the Monitor is actively recording results
bool recording() const { return recording_; }
/// \brief Turn on the recording
void turn_on() { recording_ = true; }
/// \brief Turn off the recording
void turn_off() { recording_ = false; }
private:
std::size_t dim_;
eval_type eval_;
bool recording_;
bool record_only_;
MonitorStage stage_;
std::vector<std::string> name_;
std::vector<std::size_t> index_;
AlignedVector<double> record_;
AlignedVector<double> result_;
AlignedVector<double> buffer_;
#if VSMC_HAS_MKL
MKLSSTask<double> ss_task_;
#endif
void push_back(std::size_t iter)
{
index_.push_back(iter);
record_.insert(record_.end(), result_.begin(), result_.end());
}
}; // class Monitor
} // namespace vsmc
#endif // VSMC_CORE_MONITOR_HPP
<commit_msg>Fix Monitor eval<commit_after>//============================================================================
// vSMC/include/vsmc/core/monitor.hpp
//----------------------------------------------------------------------------
// vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// 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.
//
// 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 HOLDER 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.
//============================================================================
#ifndef VSMC_CORE_MONITOR_HPP
#define VSMC_CORE_MONITOR_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/utility/aligned_memory.hpp>
#if VSMC_HAS_MKL
#include <vsmc/utility/mkl.hpp>
#endif
#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(func) \
VSMC_RUNTIME_ASSERT( \
(id < dim()), "**Monitor::" #func "** INVALID ID NUMBER ARGUMENT")
#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(func) \
VSMC_RUNTIME_ASSERT((iter < iter_size()), \
"**Monitor::" #func "** INVALID ITERATION NUMBER ARGUMENT")
#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_FUNCTOR(func, caller, name) \
VSMC_RUNTIME_ASSERT(static_cast<bool>(func), \
"**Monitor::" #caller "** INVALID " #name " OBJECT")
namespace vsmc
{
/// \brief Monitor for Monte Carlo integration
/// \ingroup Core
template <typename T>
class Monitor
{
public:
typedef T value_type;
typedef std::function<void(
std::size_t, std::size_t, const Particle<T> &, double *)> eval_type;
/// \brief Construct a Monitor with an evaluation object
///
/// \param dim The dimension of the Monitor, i.e., the number of variables
/// \param eval The evaluation object of type Monitor::eval_type
/// \param record_only The Monitor only records results instead of
/// calculating them itself
/// \param stage The stage of the Monitor. A Monitor may be evaluated
/// after
/// all steps that move the particles but before any resampling
/// (`MonitorMove`), or the possible resampling step but before any MCMC
/// steps (`MonitorResample`), all after all MCMC steps (`MonitorMCMC`).
/// If
/// a Monitor is present during initialization, then the initialization
/// are
/// taken as the step that moves particles, and both `MonitorResample` and
/// `MonitorMCMC` are considered after the possible resampling.
///
/// The evaluation object has the signature
/// ~~~{.cpp}
/// void eval (std::size_t iter, std::size_t dim, const Particle<T>
/// &particle, double *result)
/// ~~~
/// where the first three arguments are passed in by the Sampler at the
/// end of each iteration. The evaluation occurs after the possible MCMC
/// moves. The output parameter `result` shall contain the results of the
/// evaluation.
///
/// If `record_only` is true, then the monitor only records the values
/// stored in `result`. Otherwise, the behavior is explained below
///
/// The array `result` is of length `particle.size() * dim`, and it
/// represents a row major matrix of dimension `particle.size()` by `dim`,
/// say \f$R\f$. Let \f$W\f$ be the vector of the normalized weights. The
/// Monitor will be respoinsible to compute the importance sampling
/// estimate \f$r = R^TW\f$ and record it. For example, say the purpose of
/// the Monitor is to record the importance sampling estimates of
/// \f$E[h(X)]\f$ where \f$h(X) = (h_1(X),\dots,h_d(X))\f$. Then `result`
/// shall contain the evaluation of \f$h(X_i)\f$ for each \f$i\f$ from `0`
/// to `particle.size() - 1` in the order
/// \f$(h_1(X_0), \dots, h_d(X_0), h_1(X_1), \dots, h_d(X_1), \dots)\f$.
///
/// After each evaluation, the iteration number `iter` and the imporatance
/// sampling estimates are recorded and can be retrived by `index()` and
/// `record()`.
explicit Monitor(std::size_t dim, const eval_type &eval,
bool record_only = false, MonitorStage stage = MonitorMCMC)
: dim_(dim)
, eval_(eval)
, recording_(true)
, record_only_(record_only)
, stage_(stage)
, name_(dim)
{
}
/// \brief The dimension of the Monitor
std::size_t dim() const { return dim_; }
/// \brief If this is a record only Monitor
bool record_only() const { return record_only_; }
/// \brief The stage of the Montior
MonitorStage stage() const { return stage_; }
/// \brief The number of iterations has been recorded
///
/// \details
/// This is not necessarily the same as Sampler<T>::iter_size. For
/// example, a Monitor can be added only after a certain time point of the
/// sampler's iterations. Also the Monitor can be turned off for a period
/// during the iterations.
std::size_t iter_size() const { return index_.size(); }
/// \brief Reserve space for a specified number of iterations
void reserve(std::size_t num)
{
index_.reserve(num);
record_.reserve(dim_ * num);
}
/// \brief Whether the evaluation object is valid
bool empty() const { return !static_cast<bool>(eval_); }
/// \brief Read and write access to the names of variables
///
/// \details
/// By default, each variable of a Monitor is unnamed and the returned
/// string is empty. However, the user can selectively set the names of
/// each variable. This effect how Sampler will print the headers of the
/// summary table.
std::string &name(std::size_t id)
{
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(name);
return name_[id];
}
/// \brief Read only access to the names of variables
const std::string &name(std::size_t id) const
{
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(name);
return name_[id];
}
/// \brief Get the iteration index of the sampler of a given Monitor
/// iteration
///
/// \details
/// For example, if a Monitor is only added to the sampler at the
/// sampler's iteration `siter`. Then `index(0)` will be `siter` and so
/// on. If the Monitor is added before the sampler's initialization and
/// continued to be evaluated during the iterations without calling
/// `turnoff()`, then iter(iter) shall just be `iter`.
std::size_t index(std::size_t iter) const
{
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(index);
return index_[iter];
}
/// \brief Get the latest Monte Carlo integration record of a given
/// variable
///
/// \details
/// For a `dim` dimension Monitor, `id` shall be 0 to `dim` - 1
double record(std::size_t id) const
{
std::size_t iter = iter_size() ? iter_size() - 1 : iter_size();
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(record);
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(record);
return record_[iter * dim_ + id];
}
/// \brief Get the Monte Carlo integration record of a given variable and
/// the Monitor iteration
///
/// \details
/// For a `dim` dimension Monitor, `id` shall be 0 to `dim` - 1
double record(std::size_t id, std::size_t iter) const
{
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(record);
VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(record);
return record_[iter * dim_ + id];
}
/// \brief Read the index history through an output iterator
template <typename OutputIter>
void read_index(OutputIter first) const
{
std::copy(index_.begin(), index_.end(), first);
}
/// \brief Read only access to the raw data of the index vector
const std::size_t *index_data() const { return index_.data(); }
/// \brief Read only access to the raw data of records (a row major
/// matrix)
const double *record_data() const { return record_.data(); }
/// \brief Read only access to the raw data of records for a given
/// Monitor iteration
const double *record_data(std::size_t iter) const
{
return record_.data() + iter * dim_;
}
/// \brief Read the record history for a given variable through an output
/// iterator
template <typename OutputIter>
void read_record(std::size_t id, OutputIter first) const
{
const std::size_t N = iter_size();
const double *riter = record_.data() + id;
for (std::size_t i = 0; i != N; ++i, ++first, riter += dim_)
*first = *riter;
}
/// \brief Read the record history of all variables through an array of
/// output iterators
///
/// \param first An iterator of container of output iterators
template <typename OutputIterIter>
void read_record_matrix(OutputIterIter first) const
{
for (std::size_t d = 0; d != dim_; ++d, ++first)
read_record(d, *first);
}
/// \brief Read the record history of all variables through an output
/// iterator
///
/// \param first The output iterator
///
/// For example, say `first` is of type `double *`, then if `order ==
/// ColMajor`, then, `first[j * iter_size() + i] == record(i, j)`.
/// Otherwise, if `order == RowMajor`, then `first[i * dim() + j] ==
/// record(i, j)`. That is, the output is an `iter_size()` by `dim()`
/// matrix, with the usual meaning of column or row major order.
template <MatrixOrder Order, typename OutputIter>
void read_record_matrix(OutputIter first) const
{
const std::size_t N = iter_size();
if (Order == ColMajor) {
for (std::size_t d = 0; d != dim_; ++d) {
const double *riter = record_.data() + d;
for (std::size_t i = 0; i != N; ++i, ++first, riter += dim_)
*first = *riter;
}
}
if (Order == RowMajor)
std::copy(record_.begin(), record_.end(), first);
}
/// \brief Set a new evaluation object of type eval_type
void set_eval(const eval_type &new_eval) { eval_ = new_eval; }
/// \brief Perform the evaluation for a given iteration and a Particle<T>
/// object.
///
/// \details
/// This function is called by a Sampler at the end of each
/// iteration. It does nothing if `recording()` returns `false`. Otherwise
/// it use the user defined evaluation object to compute results. When a
/// Monitor is constructed, `recording()` always returns `true`. It can be
/// turned off by `turn_off()` and turned on later by `turn_on()`.
void eval(
std::size_t iter, const Particle<T> &particle, MonitorStage stage)
{
if (!recording_)
return;
if (stage != stage_)
return;
VSMC_RUNTIME_ASSERT_CORE_MONITOR_FUNCTOR(eval_, eval, EVALUATION);
result_.resize(dim_);
if (record_only_) {
eval_(iter, dim_, particle, result_.data());
push_back(iter);
return;
}
const std::size_t N = static_cast<std::size_t>(particle.size());
buffer_.resize(N * dim_);
eval_(iter, dim_, particle, buffer_.data());
#if VSMC_HAS_MKL
MKL_INT p = static_cast<MKL_INT>(dim_);
MKL_INT n = static_cast<MKL_INT>(N);
MKL_INT xstorage = VSL_SS_MATRIX_STORAGE_COLS;
const double *const x = buffer_.data();
const double *const w = particle.weight_set().weight_data();
const double *const s = result_.data();
if (ss_task_.get() == nullptr)
ss_task_.reset(&p, &n, &xstorage, x, w);
::vsliSSEditTask(ss_task_.ptr(), VSL_SS_ED_DIMEN, &p);
::vsliSSEditTask(ss_task_.ptr(), VSL_SS_ED_OBSERV_N, &n);
::vsliSSEditTask(ss_task_.ptr(), VSL_SS_ED_OBSERV_STORAGE, &xstorage);
::vsldSSEditTask(ss_task_.ptr(), VSL_SS_ED_OBSERV, x);
::vsldSSEditTask(ss_task_.ptr(), VSL_SS_ED_WEIGHTS, w);
::vsldSSEditTask(ss_task_.ptr(), VSL_SS_ED_SUM, s);
::vsldSSCompute(ss_task_.ptr(), VSL_SS_SUM, VSL_SS_METHOD_FAST);
#else // VSMC_HAS_MKL
#ifdef VSMC_CBLAS_INT
::cblas_dgemv(::CblasColMajor, ::CblasNoTrans,
static_cast<VSMC_CBLAS_INT>(dim_), static_cast<VSMC_CBLAS_INT>(N),
1, buffer_.data(), static_cast<VSMC_CBLAS_INT>(dim_),
particle.weight_set().weight_data(), 1, 0, result_.data(), 1);
#else // VSMC_CBLAS_INT
const double *wptr = particle.weight_set().weight_data();
const double *bptr = buffer_.data();
std::fill(result_.begin(), result_.end(), 0.0);
for (std::size_t i = 0; i != N; ++i)
for (std::size_t d = 0; d != dim_; ++d, ++bptr)
result_[d] += particle.weight_set().weight(i) * (*bptr);
#endif // VSMC_CBLAS_INT
#endif // VSMC_HAS_MKL
push_back(iter);
}
/// \brief Clear all records of the index and integrations
void clear()
{
index_.clear();
record_.clear();
}
/// \brief Whether the Monitor is actively recording results
bool recording() const { return recording_; }
/// \brief Turn on the recording
void turn_on() { recording_ = true; }
/// \brief Turn off the recording
void turn_off() { recording_ = false; }
private:
std::size_t dim_;
eval_type eval_;
bool recording_;
bool record_only_;
MonitorStage stage_;
std::vector<std::string> name_;
std::vector<std::size_t> index_;
AlignedVector<double> record_;
AlignedVector<double> result_;
AlignedVector<double> buffer_;
#if VSMC_HAS_MKL
MKLSSTask<double> ss_task_;
#endif
void push_back(std::size_t iter)
{
index_.push_back(iter);
record_.insert(record_.end(), result_.begin(), result_.end());
}
}; // class Monitor
} // namespace vsmc
#endif // VSMC_CORE_MONITOR_HPP
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file main.cpp
* @author Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;
* @since 0.1.0
* @date February, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Ruben Dörfel. 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 Test for fitHpi function in inverse library.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <utils/generics/applicationlogger.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <fiff/fiff.h>
#include <fiff/fiff_info.h>
#include <fiff/fiff_dig_point_set.h>
#include <inverse/hpiFit/hpifit.h>
#include <inverse/hpiFit/hpifitdata.h>
#include <utils/ioutils.h>
#include <utils/mnemath.h>
#include <fwd/fwd_coil_set.h>
#include <Eigen/Dense>
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>
#include <QDebug>
#include <QtTest>
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace INVERSELIB;
using namespace Eigen;
//=============================================================================================================
/**
* DECLARE CLASS TestHpiFit
*
* @brief The TestHpiFit class provides hpi fit verifivcation tests
*
*/
class TestHpiFit: public QObject
{
Q_OBJECT
public:
TestHpiFit();
private slots:
void initTestCase();
void testDataPrepatationFinished();
void compareFrequencies();
void compareTranslation();
void compareRotation();
void compareAngle();
void compareMove();
void compareDetect();
void compareTime();
void cleanupTestCase();
private:
double dErrorTrans = 0.0003;
double dErrorQuat = 0.002;
double dErrorTime = 0.00000001;
double dErrorAngle = 0.1;
double dErrorDetect = 0.0;
bool mDataPreparationFinishedCorrectly;
MatrixXd mRefPos;
MatrixXd mHpiPos;
MatrixXd mRefResult;
MatrixXd mHpiResult;
QVector<int> vFreqs;
};
//=============================================================================================================
TestHpiFit::TestHpiFit()
: dErrorTrans(0.0003),
dErrorQuat(0.002),
dErrorTime(0.00000001),
dErrorAngle(0.1),
dErrorDetect(0.0),
mDataPreparationFinishedCorrectly(false)
{
}
//=============================================================================================================
void TestHpiFit::initTestCase()
{
qInstallMessageHandler(ApplicationLogger::customLogWriter);
qInfo() << "Error Translation" << dErrorTrans;
qInfo() << "Error Quaternion" << dErrorQuat;
QFile t_fileIn(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/test_hpiFit_raw.fif");
// Make sure test folder exists
QFileInfo t_fileInInfo(t_fileIn);
QDir().mkdir(t_fileInInfo.path());
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read Raw and HPI fit >>>>>>>>>>>>>>>>>>>>>>>>>\n");
// Setup for reading the raw data
FiffRawData raw;
raw = FiffRawData(t_fileIn);
QSharedPointer<FiffInfo> pFiffInfo = QSharedPointer<FIFFLIB::FiffInfo>(new FiffInfo(raw.info));
// Only filter MEG channels
RowVectorXi picks = raw.info.pick_types(true, false, false);
RowVectorXd cals;
FiffCoordTrans devHeadT = pFiffInfo->dev_head_t;
// Set up the reading parameters
fiff_int_t from;
fiff_int_t to;
fiff_int_t first = raw.first_samp;
fiff_int_t last = raw.last_samp;
MatrixXd mData, mTimes;
float quantum_sec = 0.2f; //read and write in 200 ms junks
fiff_int_t quantum = ceil(quantum_sec*pFiffInfo->sfreq);
// Read Quaternion File from maxfilter and calculated movements/rotations with python
IOUtils::read_eigen_matrix(mRefPos, QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/ref_hpiFit_pos.txt");
IOUtils::read_eigen_matrix(mRefResult, QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/ref_angle_move.txt");
mHpiResult = mRefResult;
// define thresholds for big head movement detection
float threshRot = 2.0f;
float threshTrans = 0.002f;
// Setup informations for HPI fit
vFreqs = {154,158,161,166};
QVector<double> vError;
VectorXd vGoF;
FiffDigPointSet fittedPointSet;
Eigen::MatrixXd mProjectors = Eigen::MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size());
QString sHPIResourceDir = QCoreApplication::applicationDirPath() + "/HPIFittingDebug";
bool bDoDebug = true;
HPIFit HPI = HPIFit(pFiffInfo, true);
// bring frequencies into right order
from = first + mRefPos(0,0)*pFiffInfo->sfreq;
to = from + quantum;
if(!raw.read_raw_segment(mData, mTimes, from, to)) {
qCritical("error during read_raw_segment");
}
qInfo() << "[done]";
qInfo() << "Order Frequecies: ...";
HPI.findOrder(mData,
mProjectors,
pFiffInfo->dev_head_t,
vFreqs,
vError,
vGoF,
fittedPointSet,
pFiffInfo);
qInfo() << "[done]";
for(int i = 0; i < mRefPos.rows(); i++) {
from = first + mRefPos(i,0)*pFiffInfo->sfreq;
to = from + quantum;
if (to > last) {
to = last;
}
qInfo() << "Reading...";
if(!raw.read_raw_segment(mData, mTimes, from, to)) {
qWarning("error during read_raw_segment\n");
}
qInfo() << "HPI-Fit...";
HPI.fitHPI(mData,
mProjectors,
pFiffInfo->dev_head_t,
vFreqs,
vError,
vGoF,
fittedPointSet,
pFiffInfo,
bDoDebug = 0,
sHPIResourceDir,
200,
1e-5f);
qInfo() << "[done]\n";
if(MNEMath::compareTransformation(devHeadT.trans, pFiffInfo->dev_head_t.trans, threshRot, threshTrans)) {
mHpiResult(i,2) = 1;
}
HPIFit::storeHeadPosition(mRefPos(i,0), pFiffInfo->dev_head_t.trans, mHpiPos, vGoF, vError);
mHpiResult(i,0) = devHeadT.translationTo(pFiffInfo->dev_head_t.trans);
mHpiResult(i,1) = devHeadT.angleTo(pFiffInfo->dev_head_t.trans);
}
mDataPreparationFinishedCorrectly = true;
// For debug: position file for HPIFit
// UTILSLIB::IOUtils::write_eigen_matrix(mHpiPos, QCoreApplication::applicationDirPath() + "/MNE-sample-data/mHpiPos.txt");
}
//=============================================================================================================
void TestHpiFit::testDataPrepatationFinished()
{
QVERIFY(mDataPreparationFinishedCorrectly);
}
//=============================================================================================================
void TestHpiFit::compareFrequencies()
{
QVector<int> vFreqRef {166, 154, 161, 158};
QVERIFY(vFreqRef == vFreqs);
}
//=============================================================================================================
void TestHpiFit::compareTranslation()
{
RowVector3d vDiffTrans;
vDiffTrans(0) = (mRefPos.col(4)-mHpiPos.col(4)).mean();
vDiffTrans(1) = (mRefPos.col(5)-mHpiPos.col(5)).mean();
vDiffTrans(2) = (mRefPos.col(6)-mHpiPos.col(6)).mean();
qDebug() << "ErrorTrans x: " << std::abs(vDiffTrans(0));
qDebug() << "ErrorTrans y: " << std::abs(vDiffTrans(1));
qDebug() << "ErrorTrans z: " << std::abs(vDiffTrans(2));
QVERIFY(std::abs(vDiffTrans(0)) < dErrorTrans);
QVERIFY(std::abs(vDiffTrans(1)) < dErrorTrans);
QVERIFY(std::abs(vDiffTrans(2)) < dErrorTrans);
}
//=============================================================================================================
void TestHpiFit::compareRotation()
{
RowVector3d vDiffQuat;
vDiffQuat(0) = (mRefPos.col(1)-mHpiPos.col(1)).mean();
vDiffQuat(1) = (mRefPos.col(2)-mHpiPos.col(2)).mean();
vDiffQuat(2) = (mRefPos.col(3)-mHpiPos.col(3)).mean();
qDebug() << "ErrorQuat q1: " <<std::abs(vDiffQuat(0));
qDebug() << "ErrorQuat q2: " <<std::abs(vDiffQuat(1));
qDebug() << "ErrorQuat q3: " <<std::abs(vDiffQuat(2));
QVERIFY(std::abs(vDiffQuat(0)) < dErrorQuat);
QVERIFY(std::abs(vDiffQuat(1)) < dErrorQuat);
QVERIFY(std::abs(vDiffQuat(2)) < dErrorQuat);
}
//=============================================================================================================
void TestHpiFit::compareMove()
{
float fDiffMove = (mRefResult.col(0)-mHpiResult.col(0)).mean();
fDiffMove = std::abs(fDiffMove);
qDebug() << "DiffMove: [m]" << fDiffMove;
QVERIFY(std::abs(fDiffMove) < dErrorTrans);
}
//=============================================================================================================
void TestHpiFit::compareAngle()
{
float fDiffAngle = (mRefResult.col(1)-mRefResult.col(1)).mean();
fDiffAngle = std::abs(fDiffAngle);
qDebug() << "DiffAngle: [degree]" << fDiffAngle;
QVERIFY(std::abs(fDiffAngle) < dErrorAngle);
}
//=============================================================================================================
void TestHpiFit::compareDetect()
{
float fDiffCompare = (mRefResult.col(2)-mRefResult.col(2)).mean();
fDiffCompare = std::abs(fDiffCompare);
qDebug() << "DiffCompare: " << fDiffCompare;
QVERIFY(std::abs(fDiffCompare) == dErrorDetect);
}
//=============================================================================================================
void TestHpiFit::compareTime()
{
MatrixXd mDiff = MatrixXd::Zero(mRefPos.rows(),1);
mDiff.col(0) = mRefPos.col(0)-mHpiPos.col(0);
float fDiffTime = mDiff.col(0).mean();
qDebug() << "ErrorTime: " << fDiffTime;
QVERIFY(std::abs(fDiffTime) < dErrorTime);
}
//=============================================================================================================
void TestHpiFit::cleanupTestCase()
{
}
//=============================================================================================================
// MAIN
//=============================================================================================================
QTEST_GUILESS_MAIN(TestHpiFit)
#include "test_hpiFit.moc"
<commit_msg>delete unnecessary variable in test_hpi<commit_after>//=============================================================================================================
/**
* @file main.cpp
* @author Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;
* @since 0.1.0
* @date February, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Ruben Dörfel. 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 Test for fitHpi function in inverse library.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <utils/generics/applicationlogger.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <fiff/fiff.h>
#include <fiff/fiff_info.h>
#include <fiff/fiff_dig_point_set.h>
#include <inverse/hpiFit/hpifit.h>
#include <inverse/hpiFit/hpifitdata.h>
#include <utils/ioutils.h>
#include <utils/mnemath.h>
#include <fwd/fwd_coil_set.h>
#include <Eigen/Dense>
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>
#include <QDebug>
#include <QtTest>
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace INVERSELIB;
using namespace Eigen;
//=============================================================================================================
/**
* DECLARE CLASS TestHpiFit
*
* @brief The TestHpiFit class provides hpi fit verifivcation tests
*
*/
class TestHpiFit: public QObject
{
Q_OBJECT
public:
TestHpiFit();
private slots:
void initTestCase();
void compareFrequencies();
void compareTranslation();
void compareRotation();
void compareAngle();
void compareMove();
void compareDetect();
void compareTime();
void cleanupTestCase();
private:
double dErrorTrans = 0.0003;
double dErrorQuat = 0.002;
double dErrorTime = 0.00000001;
double dErrorAngle = 0.1;
double dErrorDetect = 0.0;
MatrixXd mRefPos;
MatrixXd mHpiPos;
MatrixXd mRefResult;
MatrixXd mHpiResult;
QVector<int> vFreqs;
};
//=============================================================================================================
TestHpiFit::TestHpiFit()
: dErrorTrans(0.0003),
dErrorQuat(0.002),
dErrorTime(0.00000001),
dErrorAngle(0.1),
dErrorDetect(0.0)
{
}
//=============================================================================================================
void TestHpiFit::initTestCase()
{
qInstallMessageHandler(ApplicationLogger::customLogWriter);
qInfo() << "Error Translation" << dErrorTrans;
qInfo() << "Error Quaternion" << dErrorQuat;
QFile t_fileIn(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/test_hpiFit_raw.fif");
// Make sure test folder exists
QFileInfo t_fileInInfo(t_fileIn);
QDir().mkdir(t_fileInInfo.path());
printf(">>>>>>>>>>>>>>>>>>>>>>>>> Read Raw and HPI fit >>>>>>>>>>>>>>>>>>>>>>>>>\n");
// Setup for reading the raw data
FiffRawData raw;
raw = FiffRawData(t_fileIn);
QSharedPointer<FiffInfo> pFiffInfo = QSharedPointer<FIFFLIB::FiffInfo>(new FiffInfo(raw.info));
// Only filter MEG channels
RowVectorXi picks = raw.info.pick_types(true, false, false);
RowVectorXd cals;
FiffCoordTrans devHeadT = pFiffInfo->dev_head_t;
// Set up the reading parameters
fiff_int_t from;
fiff_int_t to;
fiff_int_t first = raw.first_samp;
fiff_int_t last = raw.last_samp;
MatrixXd mData, mTimes;
float quantum_sec = 0.2f; //read and write in 200 ms junks
fiff_int_t quantum = ceil(quantum_sec*pFiffInfo->sfreq);
// Read Quaternion File from maxfilter and calculated movements/rotations with python
IOUtils::read_eigen_matrix(mRefPos, QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/ref_hpiFit_pos.txt");
IOUtils::read_eigen_matrix(mRefResult, QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/ref_angle_move.txt");
mHpiResult = mRefResult;
// define thresholds for big head movement detection
float threshRot = 2.0f;
float threshTrans = 0.002f;
// Setup informations for HPI fit
vFreqs = {154,158,161,166};
QVector<double> vError;
VectorXd vGoF;
FiffDigPointSet fittedPointSet;
Eigen::MatrixXd mProjectors = Eigen::MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size());
QString sHPIResourceDir = QCoreApplication::applicationDirPath() + "/HPIFittingDebug";
bool bDoDebug = true;
HPIFit HPI = HPIFit(pFiffInfo, true);
// bring frequencies into right order
from = first + mRefPos(0,0)*pFiffInfo->sfreq;
to = from + quantum;
if(!raw.read_raw_segment(mData, mTimes, from, to)) {
qCritical("error during read_raw_segment");
}
qInfo() << "[done]";
qInfo() << "Order Frequecies: ...";
HPI.findOrder(mData,
mProjectors,
pFiffInfo->dev_head_t,
vFreqs,
vError,
vGoF,
fittedPointSet,
pFiffInfo);
qInfo() << "[done]";
for(int i = 0; i < mRefPos.rows(); i++) {
from = first + mRefPos(i,0)*pFiffInfo->sfreq;
to = from + quantum;
if (to > last) {
to = last;
}
qInfo() << "Reading...";
if(!raw.read_raw_segment(mData, mTimes, from, to)) {
qWarning("error during read_raw_segment\n");
}
qInfo() << "HPI-Fit...";
HPI.fitHPI(mData,
mProjectors,
pFiffInfo->dev_head_t,
vFreqs,
vError,
vGoF,
fittedPointSet,
pFiffInfo,
bDoDebug = 0,
sHPIResourceDir,
200,
1e-5f);
qInfo() << "[done]\n";
if(MNEMath::compareTransformation(devHeadT.trans, pFiffInfo->dev_head_t.trans, threshRot, threshTrans)) {
mHpiResult(i,2) = 1;
}
HPIFit::storeHeadPosition(mRefPos(i,0), pFiffInfo->dev_head_t.trans, mHpiPos, vGoF, vError);
mHpiResult(i,0) = devHeadT.translationTo(pFiffInfo->dev_head_t.trans);
mHpiResult(i,1) = devHeadT.angleTo(pFiffInfo->dev_head_t.trans);
}
// For debug: position file for HPIFit
// UTILSLIB::IOUtils::write_eigen_matrix(mHpiPos, QCoreApplication::applicationDirPath() + "/MNE-sample-data/mHpiPos.txt");
}
//=============================================================================================================
void TestHpiFit::compareFrequencies()
{
QVector<int> vFreqRef {166, 154, 161, 158};
QVERIFY(vFreqRef == vFreqs);
}
//=============================================================================================================
void TestHpiFit::compareTranslation()
{
RowVector3d vDiffTrans;
vDiffTrans(0) = (mRefPos.col(4)-mHpiPos.col(4)).mean();
vDiffTrans(1) = (mRefPos.col(5)-mHpiPos.col(5)).mean();
vDiffTrans(2) = (mRefPos.col(6)-mHpiPos.col(6)).mean();
qDebug() << "ErrorTrans x: " << std::abs(vDiffTrans(0));
qDebug() << "ErrorTrans y: " << std::abs(vDiffTrans(1));
qDebug() << "ErrorTrans z: " << std::abs(vDiffTrans(2));
QVERIFY(std::abs(vDiffTrans(0)) < dErrorTrans);
QVERIFY(std::abs(vDiffTrans(1)) < dErrorTrans);
QVERIFY(std::abs(vDiffTrans(2)) < dErrorTrans);
}
//=============================================================================================================
void TestHpiFit::compareRotation()
{
RowVector3d vDiffQuat;
vDiffQuat(0) = (mRefPos.col(1)-mHpiPos.col(1)).mean();
vDiffQuat(1) = (mRefPos.col(2)-mHpiPos.col(2)).mean();
vDiffQuat(2) = (mRefPos.col(3)-mHpiPos.col(3)).mean();
qDebug() << "ErrorQuat q1: " <<std::abs(vDiffQuat(0));
qDebug() << "ErrorQuat q2: " <<std::abs(vDiffQuat(1));
qDebug() << "ErrorQuat q3: " <<std::abs(vDiffQuat(2));
QVERIFY(std::abs(vDiffQuat(0)) < dErrorQuat);
QVERIFY(std::abs(vDiffQuat(1)) < dErrorQuat);
QVERIFY(std::abs(vDiffQuat(2)) < dErrorQuat);
}
//=============================================================================================================
void TestHpiFit::compareMove()
{
float fDiffMove = (mRefResult.col(0)-mHpiResult.col(0)).mean();
fDiffMove = std::abs(fDiffMove);
qDebug() << "DiffMove: [m]" << fDiffMove;
QVERIFY(std::abs(fDiffMove) < dErrorTrans);
}
//=============================================================================================================
void TestHpiFit::compareAngle()
{
float fDiffAngle = (mRefResult.col(1)-mRefResult.col(1)).mean();
fDiffAngle = std::abs(fDiffAngle);
qDebug() << "DiffAngle: [degree]" << fDiffAngle;
QVERIFY(std::abs(fDiffAngle) < dErrorAngle);
}
//=============================================================================================================
void TestHpiFit::compareDetect()
{
float fDiffCompare = (mRefResult.col(2)-mRefResult.col(2)).mean();
fDiffCompare = std::abs(fDiffCompare);
qDebug() << "DiffCompare: " << fDiffCompare;
QVERIFY(std::abs(fDiffCompare) == dErrorDetect);
}
//=============================================================================================================
void TestHpiFit::compareTime()
{
MatrixXd mDiff = MatrixXd::Zero(mRefPos.rows(),1);
mDiff.col(0) = mRefPos.col(0)-mHpiPos.col(0);
float fDiffTime = mDiff.col(0).mean();
qDebug() << "ErrorTime: " << fDiffTime;
QVERIFY(std::abs(fDiffTime) < dErrorTime);
}
//=============================================================================================================
void TestHpiFit::cleanupTestCase()
{
}
//=============================================================================================================
// MAIN
//=============================================================================================================
QTEST_GUILESS_MAIN(TestHpiFit)
#include "test_hpiFit.moc"
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// transaction_test.cpp
//
// Identification: tests/concurrency/transaction_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "harness.h"
#include "concurrency/transaction_tests_util.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Transaction Tests
//===--------------------------------------------------------------------===//
class TransactionTests : public PelotonTest {};
std::vector<ConcurrencyType> TEST_TYPES = {
// CONCURRENCY_TYPE_OCC
CONCURRENCY_TYPE_2PL};
void TransactionTest(concurrency::TransactionManager *txn_manager) {
uint64_t thread_id = TestingHarness::GetInstance().GetThreadId();
for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) {
txn_manager->BeginTransaction();
if (thread_id % 2 == 0) {
std::chrono::microseconds sleep_time(1);
std::this_thread::sleep_for(sleep_time);
}
if (txn_itr % 25 != 0) {
txn_manager->CommitTransaction();
} else {
txn_manager->AbortTransaction();
}
}
}
void DirtyWriteTest(ConcurrencyType test_type) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(test_type);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T1 updates (0, ?) to (0, 1)
// T2 updates (0, ?) to (0, 2)
// T1 commits
// T2 commits
scheduler.AddUpdate(0, 0, 1);
scheduler.AddUpdate(1, 0, 2);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
auto &schedules = scheduler.schedules;
// T1 and T2 can't both succeed
EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_SUCCESS);
// For MVCC, actually one and only one T should succeed?
EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_ABORTED) ||
(schedules[0].txn_result == RESULT_ABORTED &&
schedules[1].txn_result == RESULT_SUCCESS));
schedules.clear();
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddUpdate(0, 0, 1);
scheduler.AddUpdate(1, 0, 2);
scheduler.AddCommit(1);
scheduler.AddCommit(0);
scheduler.Run();
auto &schedules = scheduler.schedules;
// T1 and T2 can't both succeed
EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_SUCCESS);
// For MVCC, actually one and only one T should succeed?
EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_ABORTED) ||
(schedules[0].txn_result == RESULT_ABORTED &&
schedules[1].txn_result == RESULT_SUCCESS));
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T0 delete (0, ?)
// T1 update (0, ?) to (0, 3)
// T0 commit
// T1 commit
scheduler.AddDelete(0, 0);
scheduler.AddUpdate(1, 0, 3);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
auto &schedules = scheduler.schedules;
// T1 and T2 can't both succeed
EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_SUCCESS);
// For MVCC, actually one and only one T should succeed?
EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_ABORTED) ||
(schedules[0].txn_result == RESULT_ABORTED &&
schedules[1].txn_result == RESULT_SUCCESS));
schedules.clear();
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T0 delete (1, ?)
// T1 delete (1, ?)
// T0 commit
// T1 commit
scheduler.AddDelete(0, 1);
scheduler.AddDelete(1, 1);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
auto &schedules = scheduler.schedules;
// T1 and T2 can't both succeed
EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_SUCCESS);
// For MVCC, actually one and only one T should succeed?
EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_ABORTED) ||
(schedules[0].txn_result == RESULT_ABORTED &&
schedules[1].txn_result == RESULT_SUCCESS));
schedules.clear();
}
}
void DirtyReadTest(ConcurrencyType TEST_TYPE) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T1 updates (0, ?) to (0, 1)
// T2 reads (0, ?)
// T1 commit
// T2 commit
scheduler.AddUpdate(0, 0, 1);
scheduler.AddRead(1, 0);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T1 updates (0, ?) to (0, 1)
// T2 reads (0, ?)
// T2 commit
// T1 commit
scheduler.AddUpdate(0, 0, 1);
scheduler.AddRead(1, 0);
scheduler.AddCommit(1);
scheduler.AddCommit(0);
scheduler.Run();
EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T0 delete (0, ?)
// T1 read (0, ?)
// T0 commit
// T1 commit
scheduler.AddDelete(0, 0);
scheduler.AddRead(1, 0);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
}
void FuzzyReadTest(ConcurrencyType TEST_TYPE) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
// T0 read 0
// T1 update (0, 0) to (0, 1)
// T1 commit
// T0 commit
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddUpdate(1, 0, 1);
scheduler.AddCommit(1);
scheduler.AddCommit(0);
scheduler.Run();
LOG_TRACE("%lu", scheduler.schedules.size());
EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
{
// T0 read 0
// T1 update (0, 0) to (0, 1)
// T0 commit
// T1 commit
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddUpdate(1, 0, 1);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
{
// T0 read 0
// T1 delete 0
// T0 commit
// T1 commit
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddDelete(1, 0);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
}
void PhantomTest(ConcurrencyType TEST_TYPE) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddScan(0, 0);
scheduler.AddInsert(1, 5, 0);
scheduler.AddCommit(1);
scheduler.AddCommit(0);
scheduler.Run();
EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddScan(0, 0);
scheduler.AddDelete(1, 4);
scheduler.AddCommit(1);
scheduler.AddCommit(0);
scheduler.Run();
EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
}
}
void WriteSkewTest(ConcurrencyType TEST_TYPE) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddUpdate(0, 1, 1);
scheduler.AddRead(1, 0);
scheduler.AddUpdate(1, 1, 2);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
// Can't all success
EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddUpdate(0, 1, 1);
scheduler.AddRead(1, 0);
scheduler.AddCommit(0);
scheduler.AddUpdate(1, 1, 2);
scheduler.AddCommit(1);
scheduler.Run();
// First txn should success
EXPECT_TRUE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
RESULT_ABORTED == scheduler.schedules[1].txn_result);
}
}
void ReadSkewTest(ConcurrencyType test_type) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(test_type);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddUpdate(1, 0, 1);
scheduler.AddUpdate(1, 1, 1);
scheduler.AddCommit(1);
scheduler.AddRead(0, 1);
scheduler.AddCommit(0);
scheduler.Run();
EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
}
TEST_F(TransactionTests, TransactionTest) {
for (auto test_type : TEST_TYPES) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(test_type);
LaunchParallelTest(8, TransactionTest, &txn_manager);
std::cout << "next Commit Id :: " << txn_manager.GetNextCommitId() << "\n";
}
}
TEST_F(TransactionTests, AbortTest) {
for (auto test_type : TEST_TYPES) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(test_type);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddUpdate(0, 0, 100);
scheduler.AddAbort(0);
scheduler.AddRead(1, 0);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
EXPECT_EQ(0, scheduler.schedules[1].results[0]);
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddInsert(0, 100, 0);
scheduler.AddAbort(0);
scheduler.AddRead(1, 100);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
EXPECT_EQ(-1, scheduler.schedules[1].results[0]);
}
}
}
TEST_F(TransactionTests, SerializableTest) {
for (auto test_type : TEST_TYPES) {
DirtyWriteTest(test_type);
DirtyReadTest(test_type);
FuzzyReadTest(test_type);
WriteSkewTest(test_type);
ReadSkewTest(test_type);
// PhantomTes();
}
}
} // End test namespace
} // End peloton namespace
<commit_msg>txn test is too strict<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// transaction_test.cpp
//
// Identification: tests/concurrency/transaction_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "harness.h"
#include "concurrency/transaction_tests_util.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Transaction Tests
//===--------------------------------------------------------------------===//
class TransactionTests : public PelotonTest {};
std::vector<ConcurrencyType> TEST_TYPES = {
// CONCURRENCY_TYPE_OCC
CONCURRENCY_TYPE_2PL};
void TransactionTest(concurrency::TransactionManager *txn_manager) {
uint64_t thread_id = TestingHarness::GetInstance().GetThreadId();
for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) {
txn_manager->BeginTransaction();
if (thread_id % 2 == 0) {
std::chrono::microseconds sleep_time(1);
std::this_thread::sleep_for(sleep_time);
}
if (txn_itr % 25 != 0) {
txn_manager->CommitTransaction();
} else {
txn_manager->AbortTransaction();
}
}
}
void DirtyWriteTest(ConcurrencyType test_type) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(test_type);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T1 updates (0, ?) to (0, 1)
// T2 updates (0, ?) to (0, 2)
// T1 commits
// T2 commits
scheduler.AddUpdate(0, 0, 1);
scheduler.AddUpdate(1, 0, 2);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
auto &schedules = scheduler.schedules;
// T1 and T2 can't both succeed
EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_SUCCESS);
// For MVCC, actually one and only one T should succeed?
EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_ABORTED) ||
(schedules[0].txn_result == RESULT_ABORTED &&
schedules[1].txn_result == RESULT_SUCCESS));
schedules.clear();
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddUpdate(0, 0, 1);
scheduler.AddUpdate(1, 0, 2);
scheduler.AddCommit(1);
scheduler.AddCommit(0);
scheduler.Run();
auto &schedules = scheduler.schedules;
// T1 and T2 can't both succeed
EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_SUCCESS);
// For MVCC, actually one and only one T should succeed?
EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_ABORTED) ||
(schedules[0].txn_result == RESULT_ABORTED &&
schedules[1].txn_result == RESULT_SUCCESS));
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T0 delete (0, ?)
// T1 update (0, ?) to (0, 3)
// T0 commit
// T1 commit
scheduler.AddDelete(0, 0);
scheduler.AddUpdate(1, 0, 3);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
auto &schedules = scheduler.schedules;
// T1 and T2 can't both succeed
EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_SUCCESS);
// For MVCC, actually one and only one T should succeed?
EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_ABORTED) ||
(schedules[0].txn_result == RESULT_ABORTED &&
schedules[1].txn_result == RESULT_SUCCESS));
schedules.clear();
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T0 delete (1, ?)
// T1 delete (1, ?)
// T0 commit
// T1 commit
scheduler.AddDelete(0, 1);
scheduler.AddDelete(1, 1);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
auto &schedules = scheduler.schedules;
// T1 and T2 can't both succeed
EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_SUCCESS);
// For MVCC, actually one and only one T should succeed?
EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
schedules[1].txn_result == RESULT_ABORTED) ||
(schedules[0].txn_result == RESULT_ABORTED &&
schedules[1].txn_result == RESULT_SUCCESS));
schedules.clear();
}
}
void DirtyReadTest(ConcurrencyType TEST_TYPE) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T1 updates (0, ?) to (0, 1)
// T2 reads (0, ?)
// T1 commit
// T2 commit
scheduler.AddUpdate(0, 0, 1);
scheduler.AddRead(1, 0);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T1 updates (0, ?) to (0, 1)
// T2 reads (0, ?)
// T2 commit
// T1 commit
scheduler.AddUpdate(0, 0, 1);
scheduler.AddRead(1, 0);
scheduler.AddCommit(1);
scheduler.AddCommit(0);
scheduler.Run();
EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
// T0 delete (0, ?)
// T1 read (0, ?)
// T0 commit
// T1 commit
scheduler.AddDelete(0, 0);
scheduler.AddRead(1, 0);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
}
void FuzzyReadTest(ConcurrencyType TEST_TYPE) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
// T0 read 0
// T1 update (0, 0) to (0, 1)
// T1 commit
// T0 commit
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddUpdate(1, 0, 1);
scheduler.AddCommit(1);
scheduler.AddCommit(0);
scheduler.Run();
LOG_TRACE("%lu", scheduler.schedules.size());
EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
{
// T0 read 0
// T1 update (0, 0) to (0, 1)
// T0 commit
// T1 commit
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddUpdate(1, 0, 1);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
{
// T0 read 0
// T1 delete 0
// T0 commit
// T1 commit
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddDelete(1, 0);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
}
void PhantomTest(ConcurrencyType TEST_TYPE) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddScan(0, 0);
scheduler.AddInsert(1, 5, 0);
scheduler.AddCommit(1);
scheduler.AddCommit(0);
scheduler.Run();
EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddScan(0, 0);
scheduler.AddDelete(1, 4);
scheduler.AddCommit(1);
scheduler.AddCommit(0);
scheduler.Run();
EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
}
}
void WriteSkewTest(ConcurrencyType TEST_TYPE) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddUpdate(0, 1, 1);
scheduler.AddRead(1, 0);
scheduler.AddUpdate(1, 1, 2);
scheduler.AddCommit(0);
scheduler.AddCommit(1);
scheduler.Run();
// Can't all success
EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddUpdate(0, 1, 1);
scheduler.AddRead(1, 0);
scheduler.AddCommit(0);
scheduler.AddUpdate(1, 1, 2);
scheduler.AddCommit(1);
scheduler.Run();
// First txn should success
EXPECT_TRUE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
RESULT_ABORTED == scheduler.schedules[1].txn_result);
}
}
void ReadSkewTest(ConcurrencyType test_type) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(test_type);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddRead(0, 0);
scheduler.AddUpdate(1, 0, 1);
scheduler.AddUpdate(1, 1, 1);
scheduler.AddCommit(1);
scheduler.AddRead(0, 1);
scheduler.AddCommit(0);
scheduler.Run();
EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
RESULT_SUCCESS == scheduler.schedules[1].txn_result);
}
}
TEST_F(TransactionTests, TransactionTest) {
for (auto test_type : TEST_TYPES) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(test_type);
LaunchParallelTest(8, TransactionTest, &txn_manager);
std::cout << "next Commit Id :: " << txn_manager.GetNextCommitId() << "\n";
}
}
TEST_F(TransactionTests, AbortTest) {
for (auto test_type : TEST_TYPES) {
auto &txn_manager =
concurrency::TransactionManagerFactory::GetInstance(test_type);
std::unique_ptr<storage::DataTable> table(
TransactionTestsUtil::CreateTable());
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddUpdate(0, 0, 100);
scheduler.AddAbort(0);
scheduler.AddRead(1, 0);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
EXPECT_EQ(0, scheduler.schedules[1].results[0]);
}
{
TransactionScheduler scheduler(2, table.get(), &txn_manager);
scheduler.AddInsert(0, 100, 0);
scheduler.AddAbort(0);
scheduler.AddRead(1, 100);
scheduler.AddCommit(1);
scheduler.Run();
EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
EXPECT_EQ(-1, scheduler.schedules[1].results[0]);
}
}
}
TEST_F(TransactionTests, SerializableTest) {
for (auto test_type : TEST_TYPES) {
DirtyWriteTest(test_type);
DirtyReadTest(test_type);
FuzzyReadTest(test_type);
WriteSkewTest(test_type);
ReadSkewTest(test_type);
// PhantomTes();
}
}
} // End test namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix3 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.
*
* For more details, see http://www.mrtrix.org/
*/
#include "gui/mrview/sync/syncmanager.h"
#include "gui/mrview/window.h"
#include <iostream>
#include <vector>
#include <memory> //shared_ptr
#include "gui/mrview/sync/enums.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Sync
{
SyncManager::SyncManager() : QObject(0)
{
try
{
ips = new InterprocessCommunicator();//will throw exception if it fails to set up a server
connect(ips, SIGNAL(SyncDataReceived(std::vector<std::shared_ptr<QByteArray>>)), this, SLOT(OnIPSDataReceived(std::vector<std::shared_ptr<QByteArray>>)));
}
catch (...)
{
ips = 0;
WARN("Sync set up failed.");
}
}
/**
* Returns true if this is in a state which is not appropriate to connect a window
*/
bool SyncManager::GetInErrorState()
{
return ips == 0;
}
/**
* Sets the window to connect to. Code currently assumes this only occurs once. Also check GetInErrorState() before calling
*/
void SyncManager::SetWindow(MR::GUI::MRView::Window* wind)
{
if (GetInErrorState())
{
throw Exception("Attempt to set window while in an error state");
}
win = wind;
connect(win, SIGNAL(focusChanged()), this, SLOT(OnWindowFocusChanged()));
}
/**
* Receives a signal from window that the focus has changed
*/
void SyncManager::OnWindowFocusChanged()
{
if (win->sync_focus_on())
{
Eigen::Vector3f foc = win->focus();
SendData(DataKey::WindowFocus, ToQByteArray(foc));
}
}
/**
* Sends a signal to other processes to sync to a given key/value
*/
bool SyncManager::SendData(DataKey code, QByteArray dat)
{
QByteArray data;
char codeAsChar[4];
InterprocessCommunicator::Int32ToChar(codeAsChar, (int)code);
data.insert(0, codeAsChar, 4);
data.insert(4, dat, dat.size());
return ips->SendData(data);
}
/**
* Receives a signal from another process that a value to sync has changed
*/
void SyncManager::OnIPSDataReceived(std::vector<std::shared_ptr<QByteArray>> all_messages)
{
//WARNING This code assumes that the order of syncing operations does not matter
//We have a list of messages found
//Categorise these. Only keep the last value sent for each message type, or we will change to an old value and then update other processes to this old value
std::shared_ptr<QByteArray> winFocus = 0;
for (size_t i = 0; i < all_messages.size(); i++)
{
std::shared_ptr<QByteArray> data = all_messages[i];
if (data->size() < 4)
{
DEBUG("Bad data received to syncmanager: too short");
continue;
}
int idOfDataEntry = InterprocessCommunicator::CharTo32bitNum(data->data());
switch (idOfDataEntry)
{
case (int)DataKey::WindowFocus:
{
//This message has window focus information to sync with
winFocus = data;
break;
}
default:
{
DEBUG("Unknown data key received: " + idOfDataEntry);
break;
}
}
}
if (winFocus && win->sync_focus_on())
{
//We received 1+ signals to change our window focus
unsigned int offset = 4;//we have already read 4 bytes, above
//Read three single point floats
if (winFocus->size() != (int)(offset + 12)) //cast to int to avoid compiler warning
{
DEBUG("Bad data received to sync manager: wrong length (window focus)");
}
else
{
Eigen::Vector3f vec = FromQByteArray(*winFocus, offset);
//Check if already set to this value - Basic OOP: don't trust window to check things are changed before emitting a signal that the value has changed!
Eigen::Vector3f win_vec = win->focus();
if (win_vec[0] != vec[0] || win_vec[1] != vec[1] || win_vec[2] != vec[2])
{
//Send to window
win->set_focus(vec);
}
}
}
//Redraw the window.
win->updateGL();
}
/**
* Serialises a Vector3f as a QByteArray
*/
QByteArray SyncManager::ToQByteArray(Eigen::Vector3f data)
{
char a[12];
memcpy(a, &data, 12);
QByteArray q;
q.insert(0, a, 12); //don't use the constructor; it ignores any data after hitting a \0
return q;
}
/**
* Deserialises a Vector3f from a QByteArray
*/
Eigen::Vector3f SyncManager::FromQByteArray(QByteArray data, unsigned int offset)
{
Eigen::Vector3f read;
memcpy(&read, data.data() + offset, 12);
return read;
}
}
}
}
}<commit_msg>Fixed compiler warning appearing on OSX. Tested on Ubuntu 12.04 (Virtual Box) + Qt 4.8, Windows 10 + Qt 5.9.2, and OSX Darwin + Qt 5.10.1<commit_after>/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix3 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.
*
* For more details, see http://www.mrtrix.org/
*/
#include "gui/mrview/sync/syncmanager.h"
#include "gui/mrview/window.h"
#include <iostream>
#include <vector>
#include <memory> //shared_ptr
#include "gui/mrview/sync/enums.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Sync
{
SyncManager::SyncManager() : QObject(0)
{
try
{
ips = new InterprocessCommunicator();//will throw exception if it fails to set up a server
connect(ips, SIGNAL(SyncDataReceived(std::vector<std::shared_ptr<QByteArray>>)), this, SLOT(OnIPSDataReceived(std::vector<std::shared_ptr<QByteArray>>)));
}
catch (...)
{
ips = 0;
WARN("Sync set up failed.");
}
}
/**
* Returns true if this is in a state which is not appropriate to connect a window
*/
bool SyncManager::GetInErrorState()
{
return ips == 0;
}
/**
* Sets the window to connect to. Code currently assumes this only occurs once. Also check GetInErrorState() before calling
*/
void SyncManager::SetWindow(MR::GUI::MRView::Window* wind)
{
if (GetInErrorState())
{
throw Exception("Attempt to set window while in an error state");
}
win = wind;
connect(win, SIGNAL(focusChanged()), this, SLOT(OnWindowFocusChanged()));
}
/**
* Receives a signal from window that the focus has changed
*/
void SyncManager::OnWindowFocusChanged()
{
if (win->sync_focus_on())
{
Eigen::Vector3f foc = win->focus();
SendData(DataKey::WindowFocus, ToQByteArray(foc));
}
}
/**
* Sends a signal to other processes to sync to a given key/value
*/
bool SyncManager::SendData(DataKey code, QByteArray dat)
{
QByteArray data;
char codeAsChar[4];
InterprocessCommunicator::Int32ToChar(codeAsChar, (int)code);
data.insert(0, codeAsChar, 4);
data.insert(4, dat, dat.size());
return ips->SendData(data);
}
/**
* Receives a signal from another process that a value to sync has changed
*/
void SyncManager::OnIPSDataReceived(std::vector<std::shared_ptr<QByteArray>> all_messages)
{
//WARNING This code assumes that the order of syncing operations does not matter
//We have a list of messages found
//Categorise these. Only keep the last value sent for each message type, or we will change to an old value and then update other processes to this old value
std::shared_ptr<QByteArray> winFocus = 0;
for (size_t i = 0; i < all_messages.size(); i++)
{
std::shared_ptr<QByteArray> data = all_messages[i];
if (data->size() < 4)
{
DEBUG("Bad data received to syncmanager: too short");
continue;
}
int idOfDataEntry = InterprocessCommunicator::CharTo32bitNum(data->data());
switch (idOfDataEntry)
{
case (int)DataKey::WindowFocus:
{
//This message has window focus information to sync with
winFocus = data;
break;
}
default:
{
DEBUG("Unknown data key received: " + std::to_string(idOfDataEntry));
break;
}
}
}
if (winFocus && win->sync_focus_on())
{
//We received 1+ signals to change our window focus
unsigned int offset = 4;//we have already read 4 bytes, above
//Read three single point floats
if (winFocus->size() != (int)(offset + 12)) //cast to int to avoid compiler warning
{
DEBUG("Bad data received to sync manager: wrong length (window focus)");
}
else
{
Eigen::Vector3f vec = FromQByteArray(*winFocus, offset);
//Check if already set to this value - Basic OOP: don't trust window to check things are changed before emitting a signal that the value has changed!
Eigen::Vector3f win_vec = win->focus();
if (win_vec[0] != vec[0] || win_vec[1] != vec[1] || win_vec[2] != vec[2])
{
//Send to window
win->set_focus(vec);
}
}
}
//Redraw the window.
win->updateGL();
}
/**
* Serialises a Vector3f as a QByteArray
*/
QByteArray SyncManager::ToQByteArray(Eigen::Vector3f data)
{
char a[12];
memcpy(a, &data, 12);
QByteArray q;
q.insert(0, a, 12); //don't use the constructor; it ignores any data after hitting a \0
return q;
}
/**
* Deserialises a Vector3f from a QByteArray
*/
Eigen::Vector3f SyncManager::FromQByteArray(QByteArray data, unsigned int offset)
{
Eigen::Vector3f read;
memcpy(&read, data.data() + offset, 12);
return read;
}
}
}
}
}<|endoftext|> |
<commit_before>
#include <stddef.h> // Чтобы определить NULL
///////// Включения основного модуля module.h
#include "Module.h"
#include "Function_module.h"
#include <math.h>
#include <iostream>
#include <time.h> // для Рандомайзера
using namespace std;
// Опишу функцию вне класса чтобы можно было применять cout
FunctionResult* MathFunctionModule::executeFunction(regval functionId, regval *args){
cout << "Func executed" << endl;
if (!functionId) {
return NULL;
}
// эта конструкция чтобы создать заранее объект указатель на который будем возвращать
char ch4 = '1'; // имя надо будет поменять или просто что-то поменять. Но пока символ оставим в покое и буем работать с result.
rez = new FunctionResult(ch4);
// Уже не тестовое задание пробуем описать
switch (functionId) {
//первая функция pow - квадрат. 1-й аргумент возводимое, второй - степень.
case 1:
{
//C приведением типов
double arg1,arg2,resOfPow;
arg1=*args;
arg2=*(args+1);
resOfPow=pow(arg1,arg2);
rez->result = (int) resOfPow;
// Все сделали и выходим из свича
break;
}
case 2: // ABS модуль числа
{
/*C приведением типов*/
int resOfabs;
resOfabs = abs(*args);
rez->result = resOfabs;
// Все сделали и выходим из свича
break;
}
case 3: // FMOD Остаток от деления
{
int resOfmod;
resOfmod = (int) fmod(*args,*(args +1));
rez->result = resOfmod;
// Все сделали и выходим из свича
break;
}
case 4: // DIV Целочисленное деление
int resOfdiv;
resOfdiv = ( *args - (int)fmod(*args, *(args + 1)) ) / (*(args+1));
rez->result = resOfdiv;
// Все сделали и выходим из свича
break;
case 5: // Корень 2-й степени
{
int resOfsqrt;
resOfsqrt = (int) sqrt(*args);
rez->result = resOfsqrt;
// Все сделали и выходим из свича
break;
}
case 6: // Рандомное целое число
{
int resOfrand;
resOfrand = rand()%(*args) + (*(args+1)) ;
rez->result = resOfrand;
// Все сделали и выходим из свича
break;
}
case 7: // Синус
{
int resOfsin;
resOfsin = (int) (1000 * sin(*args)) ;
rez->result = resOfsin;
// Все сделали и выходим из свича
break;
}
case 8: // Косинус
{
int resOfcos;
resOfcos = (int)(1000 * cos(*args));
rez->result = resOfcos;
// Все сделали и выходим из свича
break;
}
case 9: // Тангенс
{
int resOftan;
resOftan = (int)(1000 * tan(*args));
rez->result = resOftan;
// Все сделали и выходим из свича
break;
}
case 10: // АркСинус
{
int resOfasin;
resOfasin = (int)(1000 * asin(*args));
rez->result = resOfasin;
// Все сделали и выходим из свича
break;
}
case 11: // АркКосинус
{
int resOfacos;
resOfacos = (int)(1000 * acos(*args));
rez->result = resOfacos;
// Все сделали и выходим из свича
break;
}
case 12: // АркТангенс
{
int resOfatan;
resOfatan = (int)(1000 * atan(*args));
rez->result = resOfatan;
// Все сделали и выходим из свича
break;
}
case 13: // Экспонента
{
int resOfexp;
resOfexp = (int) exp(*args);
rez->result = resOfexp;
// Все сделали и выходим из свича
break;
}
case 14: // Логарифм Натуральный
{
int resOflog;
resOflog = (int)log(*args);
rez->result = resOflog;
// Все сделали и выходим из свича
break;
}
case 15: // Десятичный логарифм
{
int resOflog10;
resOflog10 = (int)log10(*args);
rez->result = resOflog10;
// Все сделали и выходим из свича
break;
}
}; // Конец switch
return rez;
};
int main(){
int test;
test = 1;
cout << test << endl;
regval *arg1;
regval x;
x = 1;
arg1 = &x;
regval TwoArgs[] = {2,3};
regval absTestMas[] = { -14 };
regval fmodTestMas[] = { 7, 4 };
regval divTestMas[] = { 9, 4 };
regval randTestMas[] = { 10, 1 };
regval SiCoTanTestMas[] = {1};
MathFunctionModule newObject;
FunctionResult *FRobject;
// проверка возведения в степень
FRobject = newObject.executeFunction(1, TwoArgs); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject << endl;
cout << FRobject->type << endl;
cout << FRobject->result << endl;
// Проверка получения абсолютной величины
FRobject = newObject.executeFunction(2, absTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject << endl;
cout << FRobject->type << endl;
cout << FRobject->result << endl;
// Проверка остатка от деления
FRobject = newObject.executeFunction(3, fmodTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject << endl;
cout << FRobject->type << endl;
cout << FRobject->result << endl;
// Проверка целочисленного деления на том же массиве
FRobject = newObject.executeFunction(4, divTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject << endl;
cout << FRobject->type << endl;
cout << FRobject->result << endl;
cout << "- - - " << newObject.executeFunction(4, divTestMas)->result + newObject.executeFunction(4, divTestMas)->result << endl;
// Проверка Установка рандомайзера. не важно что передаем в аргументах
FRobject = newObject.executeFunction(5, divTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject << endl;
cout << FRobject->type << endl;
cout << FRobject->result << endl;
// Проверяем рандомайзер
FRobject = newObject.executeFunction(6, randTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject->result << endl;
FRobject = newObject.executeFunction(6, randTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject->result << endl;
return 0;
}
<commit_msg>update executeFunctions<commit_after>
#include <stddef.h> // Чтобы определить NULL
///////// Включения основного модуля module.h
#include "Module.h"
#include "Function_module.h"
#include <math.h>
#include <iostream>
#include <time.h> // для Рандомайзера
using namespace std;
// Опишу функцию вне класса чтобы можно было применять cout
FunctionResult* MathFunctionModule::executeFunction(regval functionId, regval *args){
cout << "Func executed" << endl;
if (!functionId) {
return NULL;
}
// эта конструкция чтобы создать заранее объект указатель на который будем возвращать
char ch4 = '1'; // имя надо будет поменять или просто что-то поменять. Но пока символ оставим в покое и буем работать с result.
rez = new FunctionResult(ch4);
// Уже не тестовое задание пробуем описать
switch (functionId) {
//первая функция pow - квадрат. 1-й аргумент возводимое, второй - степень.
case 1: // Тут вопрос про приведение типов
{
//C приведением типов
double arg1,arg2,resOfPow;
arg1=*args;
arg2=*(args+1);
resOfPow=pow(arg1,arg2);
rez->result = (int) resOfPow;
// Все сделали и выходим из свича
break;
}
case 2: // ABS модуль числа
{
/*C приведением типов*/
int resOfabs;
resOfabs = abs(*args);
rez->result = resOfabs;
// Все сделали и выходим из свича
break;
}
case 3: // FMOD Остаток от деления
{
int resOfmod;
resOfmod = (int) fmod(*args,*(args +1));
rez->result = resOfmod;
// Все сделали и выходим из свича
break;
}
case 4: // DIV Целочисленное деление
int resOfdiv;
resOfdiv = ( *args - (int)fmod(*args, *(args + 1)) ) / (*(args+1));
rez->result = resOfdiv;
// Все сделали и выходим из свича
break;
case 5: // Корень 2-й степени Результат будем выводить умноженным на 1000, потому что растет медленно(меняется медленно)
{
int resOfsqrt;
resOfsqrt = (int) (1000 * sqrt(*args));
rez->result = resOfsqrt;
// Все сделали и выходим из свича
break;
}
case 6: // Рандомное целое число
{
int resOfrand;
resOfrand = rand()%(*args) + (*(args+1)) ;
rez->result = resOfrand;
// Все сделали и выходим из свича
break;
}
case 7: // Синус Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах
{
int resOfsin;
resOfsin = (int) (1000 * sin(*args/1000)) ;
rez->result = resOfsin;
// Все сделали и выходим из свича
break;
}
case 8: // Косинус Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах
{
int resOfcos;
resOfcos = (int)(1000 * cos(*args/1000));
rez->result = resOfcos;
// Все сделали и выходим из свича
break;
}
case 9: // Тангенс Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах
{
int resOftan;
resOftan = (int)(1000 * tan(*args / 1000));
rez->result = resOftan;
// Все сделали и выходим из свича
break;
}
case 10: // АркСинус Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах
{
int resOfasin;
resOfasin = (int)(1000 * asin(*args / 1000));
rez->result = resOfasin;
// Все сделали и выходим из свича
break;
}
case 11: // АркКосинус Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах
{
int resOfacos;
resOfacos = (int)(1000 * acos(*args / 1000));
rez->result = resOfacos;
// Все сделали и выходим из свича
break;
}
case 12: // АркТангенс Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах
{
int resOfatan;
resOfatan = (int)(1000 * atan(*args / 1000));
rez->result = resOfatan;
// Все сделали и выходим из свича
break;
}
case 13: // Экспонента Растет быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000
{
int resOfexp;
resOfexp = (int)exp(*args / 1000);
rez->result = resOfexp;
// Все сделали и выходим из свича
break;
}
case 14: // Логарифм Натуральный Растет медленно поэтому вывод умножим на 1000
{
int resOflog;
resOflog = (int)( 1000* log(*args));
rez->result = resOflog;
// Все сделали и выходим из свича
break;
}
case 15: // Десятичный логарифм Растет медленно поэтому вывод умножим на 1000
{
int resOflog10;
resOflog10 = (int) (1000 * log10(*args));
rez->result = resOflog10;
// Все сделали и выходим из свича
break;
}
}; // Конец switch
return rez;
};
int main(){
int test;
test = 1;
cout << test << endl;
regval *arg1;
regval x;
x = 1;
arg1 = &x;
regval TwoArgs[] = {2,3};
regval absTestMas[] = { -14 };
regval fmodTestMas[] = { 7, 4 };
regval divTestMas[] = { 9, 4 };
regval randTestMas[] = { 10, 1 };
regval SiCoTanTestMas[] = {1};
MathFunctionModule newObject;
FunctionResult *FRobject;
// проверка возведения в степень
FRobject = newObject.executeFunction(1, TwoArgs); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject << endl;
cout << FRobject->type << endl;
cout << FRobject->result << endl;
// Проверка получения абсолютной величины
FRobject = newObject.executeFunction(2, absTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject << endl;
cout << FRobject->type << endl;
cout << FRobject->result << endl;
// Проверка остатка от деления
FRobject = newObject.executeFunction(3, fmodTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject << endl;
cout << FRobject->type << endl;
cout << FRobject->result << endl;
// Проверка целочисленного деления на том же массиве
FRobject = newObject.executeFunction(4, divTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject << endl;
cout << FRobject->type << endl;
cout << FRobject->result << endl;
cout << "- - - " << newObject.executeFunction(4, divTestMas)->result + newObject.executeFunction(4, divTestMas)->result << endl;
// Проверка Установка рандомайзера. не важно что передаем в аргументах
FRobject = newObject.executeFunction(5, divTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject << endl;
cout << FRobject->type << endl;
cout << FRobject->result << endl;
// Проверяем рандомайзер
FRobject = newObject.executeFunction(6, randTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject->result << endl;
FRobject = newObject.executeFunction(6, randTestMas); // не забываем что этот объект ссылается на свойство newObject.
cout << FRobject->result << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <boost/format.hpp>
#include "log.h"
#include "common.h"
#include "mem_vec_store.h"
#include "bulk_operate.h"
#include "local_vec_store.h"
#include "mem_matrix_store.h"
#include "NUMA_vector.h"
namespace fm
{
namespace detail
{
mem_vec_store::ptr mem_vec_store::create(size_t length, int num_nodes,
const scalar_type &type)
{
if (num_nodes < 0)
return smp_vec_store::create(length, type);
else
return NUMA_vec_store::create(length, num_nodes, type);
}
bool mem_vec_store::copy_from(const char *buf, size_t num_bytes)
{
if (get_raw_arr() == NULL)
return false;
if (num_bytes % get_entry_size() != 0
|| num_bytes / get_entry_size() != get_length())
return false;
memcpy(get_raw_arr(), buf, num_bytes);
return true;
}
smp_vec_store::smp_vec_store(size_t length, const scalar_type &type): mem_vec_store(
length, type), data(length * type.get_size())
{
this->arr = data.get_raw();
}
smp_vec_store::smp_vec_store(const detail::raw_data_array &data,
const scalar_type &type): mem_vec_store(
data.get_num_bytes() / type.get_size(), type)
{
this->data = data;
this->arr = this->data.get_raw();
}
smp_vec_store::ptr smp_vec_store::create(const detail::raw_data_array &data,
const scalar_type &type)
{
if (data.get_num_bytes() % type.get_size() != 0) {
BOOST_LOG_TRIVIAL(error)
<< "The data array has a wrong number of bytes";
return smp_vec_store::ptr();
}
return ptr(new smp_vec_store(data, type));
}
smp_vec_store::ptr smp_vec_store::get(const smp_vec_store &idxs) const
{
if (idxs.get_type() != get_scalar_type<off_t>()) {
BOOST_LOG_TRIVIAL(error) << "The index vector isn't of the off_t type";
return smp_vec_store::ptr();
}
smp_vec_store::ptr ret = smp_vec_store::create(idxs.get_length(), get_type());
int num_threads = get_num_omp_threads();
size_t part_len = ceil(((double) idxs.get_length()) / num_threads);
#pragma omp parallel for
for (int k = 0; k < num_threads; k++) {
size_t start = k * part_len;
size_t end = std::min((k + 1) * part_len, idxs.get_length());
size_t local_len = end >= start ? end - start : 0;
if (local_len == 0)
continue;
std::vector<const char *> src_locs(local_len);
for (size_t i = 0; i < local_len; i++) {
off_t idx = idxs.get<off_t>(i + start);
// Check if it's out of the range.
if (idx < 0 && (size_t) idx >= this->get_length()) {
BOOST_LOG_TRIVIAL(error)
<< boost::format("%1% is out of range") % idx;
continue;
}
src_locs[i] = this->get(idx);
}
get_type().get_sg().gather(src_locs,
ret->arr + start * ret->get_entry_size());
}
return ret;
}
bool smp_vec_store::append(std::vector<vec_store::const_ptr>::const_iterator vec_it,
std::vector<vec_store::const_ptr>::const_iterator vec_end)
{
// Get the total size of the result vector.
size_t tot_res_size = this->get_length();
for (auto it = vec_it; it != vec_end; it++) {
tot_res_size += (*it)->get_length();
if (!(*it)->is_in_mem()) {
BOOST_LOG_TRIVIAL(error)
<< "Not support appending an ext-mem vector to an in-mem vector";
return false;
}
if (get_type() != (*it)->get_type()) {
BOOST_LOG_TRIVIAL(error) << "The two vectors don't have the same type";
return false;
}
}
// Merge all results to a single vector.
off_t loc = this->get_length() + get_sub_start();
this->resize(tot_res_size);
for (auto it = vec_it; it != vec_end; it++) {
assert(loc + (*it)->get_length() <= this->get_length());
assert((*it)->is_in_mem());
const mem_vec_store &mem_vec = static_cast<const mem_vec_store &>(**it);
bool ret = data.set_sub_arr(loc * get_entry_size(),
mem_vec.get_raw_arr(), mem_vec.get_length() * get_entry_size());
assert(ret);
loc += (*it)->get_length();
}
return true;
}
bool smp_vec_store::append(const vec_store &vec)
{
if (!vec.is_in_mem()) {
BOOST_LOG_TRIVIAL(error) << "The input vector isn't in memory";
return false;
}
if (get_type() != vec.get_type()) {
BOOST_LOG_TRIVIAL(error) << "The two vectors don't have the same type";
return false;
}
// TODO We might want to over expand a little, so we don't need to copy
// the memory again and again.
// TODO if this is a sub_vector, what should we do?
assert(get_sub_start() == 0);
off_t loc = this->get_length() + get_sub_start();
this->resize(vec.get_length() + get_length());
assert(loc + vec.get_length() <= this->get_length());
const mem_vec_store &mem_vec = static_cast<const mem_vec_store &>(vec);
assert(mem_vec.get_raw_arr());
return data.set_sub_arr(loc * get_entry_size(), mem_vec.get_raw_arr(),
mem_vec.get_length() * get_entry_size());
}
bool smp_vec_store::resize(size_t new_length)
{
if (new_length == get_length())
return true;
size_t tot_len = data.get_num_bytes() / get_type().get_size();
// We don't want to reallocate memory when shrinking the vector.
if (new_length < tot_len) {
return vec_store::resize(new_length);
}
// Keep the old information of the vector.
detail::raw_data_array old_data = data;
char *old_arr = arr;
size_t old_length = get_length();
size_t real_length = old_length;
if (real_length == 0)
real_length = 1;
for (; real_length < new_length; real_length *= 2);
this->data = detail::raw_data_array(real_length * get_type().get_size());
this->arr = this->data.get_raw();
memcpy(arr, old_arr, std::min(old_length, new_length) * get_entry_size());
return vec_store::resize(new_length);
}
bool smp_vec_store::expose_sub_vec(off_t start, size_t length)
{
size_t tot_len = data.get_num_bytes() / get_type().get_size();
if (start + length > tot_len) {
exit(1);
BOOST_LOG_TRIVIAL(error) << "expose_sub_vec: out of range";
return false;
}
resize(length);
arr = data.get_raw() + start * get_entry_size();
return true;
}
vec_store::ptr smp_vec_store::deep_copy() const
{
assert(get_raw_arr() == data.get_raw());
detail::raw_data_array data = this->data.deep_copy();
return smp_vec_store::create(data, get_type());
}
vec_store::ptr smp_vec_store::sort_with_index()
{
smp_vec_store::ptr indexes = smp_vec_store::create(get_length(),
get_scalar_type<off_t>());
get_type().get_sorter().sort_with_index(arr,
(off_t *) indexes->arr, get_length(), false);
return indexes;
}
void smp_vec_store::set_data(const set_vec_operate &op)
{
// I assume this is column-wise matrix.
// TODO parallel.
op.set(arr, get_length(), 0);
}
void smp_vec_store::set(const std::vector<const char *> &locs)
{
assert(locs.size() <= get_length());
get_type().get_sg().gather(locs, arr);
}
local_vec_store::ptr smp_vec_store::get_portion(off_t loc, size_t size)
{
if (loc + size > get_length()) {
BOOST_LOG_TRIVIAL(error) << "the portion is out of boundary";
return local_vec_store::ptr();
}
return local_vec_store::ptr(new local_ref_vec_store(get(loc),
loc, size, get_type(), -1));
}
local_vec_store::const_ptr smp_vec_store::get_portion(off_t loc,
size_t size) const
{
if (loc + size > get_length()) {
BOOST_LOG_TRIVIAL(error) << "the portion is out of boundary";
return local_vec_store::ptr();
}
return local_vec_store::ptr(new local_cref_vec_store(get(loc),
loc, size, get_type(), -1));
}
size_t smp_vec_store::get_portion_size() const
{
return 64 * 1024;
}
matrix_store::const_ptr smp_vec_store::conv2mat(size_t nrow, size_t ncol,
bool byrow) const
{
assert(arr == data.get_raw());
if (get_length() < nrow * ncol) {
BOOST_LOG_TRIVIAL(error)
<< "The vector doesn't have enough elements";
return matrix_store::ptr();
}
if (byrow)
return mem_row_matrix_store::create(data, nrow, ncol, get_type());
else
return mem_col_matrix_store::create(data, nrow, ncol, get_type());
}
template<>
vec_store::ptr create_vec_store<double>(double start, double end,
double stride)
{
// The result of division may generate a real number slightly smaller than
// what we want because of the representation precision in the machine.
// When we convert the real number to an integer, we may find the number
// is smaller than exepcted. We need to add a very small number to
// the real number to correct the problem.
// TODO is it the right way to correct the problem?
long n = (end - start) / stride + 1e-9;
if (n < 0) {
BOOST_LOG_TRIVIAL(error) <<"wrong sign in 'by' argument";
return vec_store::ptr();
}
// We need to count the start element.
n++;
detail::smp_vec_store::ptr v = detail::smp_vec_store::create(n,
get_scalar_type<double>());
v->set_data(seq_set_vec_operate<double>(n, start, stride));
return v;
}
}
}
<commit_msg>[Matrix]: fix a bug in deep copy a mem vectore store.<commit_after>/*
* Copyright 2015 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <boost/format.hpp>
#include "log.h"
#include "common.h"
#include "mem_vec_store.h"
#include "bulk_operate.h"
#include "local_vec_store.h"
#include "mem_matrix_store.h"
#include "NUMA_vector.h"
namespace fm
{
namespace detail
{
mem_vec_store::ptr mem_vec_store::create(size_t length, int num_nodes,
const scalar_type &type)
{
if (num_nodes < 0)
return smp_vec_store::create(length, type);
else
return NUMA_vec_store::create(length, num_nodes, type);
}
bool mem_vec_store::copy_from(const char *buf, size_t num_bytes)
{
if (get_raw_arr() == NULL)
return false;
if (num_bytes % get_entry_size() != 0
|| num_bytes / get_entry_size() != get_length())
return false;
memcpy(get_raw_arr(), buf, num_bytes);
return true;
}
smp_vec_store::smp_vec_store(size_t length, const scalar_type &type): mem_vec_store(
length, type), data(length * type.get_size())
{
this->arr = data.get_raw();
}
smp_vec_store::smp_vec_store(const detail::raw_data_array &data,
const scalar_type &type): mem_vec_store(
data.get_num_bytes() / type.get_size(), type)
{
assert(data.get_num_bytes() % type.get_size() == 0);
this->data = data;
this->arr = this->data.get_raw();
}
smp_vec_store::ptr smp_vec_store::create(const detail::raw_data_array &data,
const scalar_type &type)
{
if (data.get_num_bytes() % type.get_size() != 0) {
BOOST_LOG_TRIVIAL(error)
<< "The data array has a wrong number of bytes";
return smp_vec_store::ptr();
}
return ptr(new smp_vec_store(data, type));
}
smp_vec_store::ptr smp_vec_store::get(const smp_vec_store &idxs) const
{
if (idxs.get_type() != get_scalar_type<off_t>()) {
BOOST_LOG_TRIVIAL(error) << "The index vector isn't of the off_t type";
return smp_vec_store::ptr();
}
smp_vec_store::ptr ret = smp_vec_store::create(idxs.get_length(), get_type());
int num_threads = get_num_omp_threads();
size_t part_len = ceil(((double) idxs.get_length()) / num_threads);
#pragma omp parallel for
for (int k = 0; k < num_threads; k++) {
size_t start = k * part_len;
size_t end = std::min((k + 1) * part_len, idxs.get_length());
size_t local_len = end >= start ? end - start : 0;
if (local_len == 0)
continue;
std::vector<const char *> src_locs(local_len);
for (size_t i = 0; i < local_len; i++) {
off_t idx = idxs.get<off_t>(i + start);
// Check if it's out of the range.
if (idx < 0 && (size_t) idx >= this->get_length()) {
BOOST_LOG_TRIVIAL(error)
<< boost::format("%1% is out of range") % idx;
continue;
}
src_locs[i] = this->get(idx);
}
get_type().get_sg().gather(src_locs,
ret->arr + start * ret->get_entry_size());
}
return ret;
}
bool smp_vec_store::append(std::vector<vec_store::const_ptr>::const_iterator vec_it,
std::vector<vec_store::const_ptr>::const_iterator vec_end)
{
// Get the total size of the result vector.
size_t tot_res_size = this->get_length();
for (auto it = vec_it; it != vec_end; it++) {
tot_res_size += (*it)->get_length();
if (!(*it)->is_in_mem()) {
BOOST_LOG_TRIVIAL(error)
<< "Not support appending an ext-mem vector to an in-mem vector";
return false;
}
if (get_type() != (*it)->get_type()) {
BOOST_LOG_TRIVIAL(error) << "The two vectors don't have the same type";
return false;
}
}
// Merge all results to a single vector.
off_t loc = this->get_length() + get_sub_start();
this->resize(tot_res_size);
for (auto it = vec_it; it != vec_end; it++) {
assert(loc + (*it)->get_length() <= this->get_length());
assert((*it)->is_in_mem());
const mem_vec_store &mem_vec = static_cast<const mem_vec_store &>(**it);
bool ret = data.set_sub_arr(loc * get_entry_size(),
mem_vec.get_raw_arr(), mem_vec.get_length() * get_entry_size());
assert(ret);
loc += (*it)->get_length();
}
return true;
}
bool smp_vec_store::append(const vec_store &vec)
{
if (!vec.is_in_mem()) {
BOOST_LOG_TRIVIAL(error) << "The input vector isn't in memory";
return false;
}
if (get_type() != vec.get_type()) {
BOOST_LOG_TRIVIAL(error) << "The two vectors don't have the same type";
return false;
}
// TODO We might want to over expand a little, so we don't need to copy
// the memory again and again.
// TODO if this is a sub_vector, what should we do?
assert(get_sub_start() == 0);
off_t loc = this->get_length() + get_sub_start();
this->resize(vec.get_length() + get_length());
assert(loc + vec.get_length() <= this->get_length());
const mem_vec_store &mem_vec = static_cast<const mem_vec_store &>(vec);
assert(mem_vec.get_raw_arr());
return data.set_sub_arr(loc * get_entry_size(), mem_vec.get_raw_arr(),
mem_vec.get_length() * get_entry_size());
}
bool smp_vec_store::resize(size_t new_length)
{
if (new_length == get_length())
return true;
size_t tot_len = data.get_num_bytes() / get_type().get_size();
// We don't want to reallocate memory when shrinking the vector.
if (new_length < tot_len) {
return vec_store::resize(new_length);
}
// Keep the old information of the vector.
detail::raw_data_array old_data = data;
char *old_arr = arr;
size_t old_length = get_length();
size_t real_length = old_length;
if (real_length == 0)
real_length = 1;
for (; real_length < new_length; real_length *= 2);
this->data = detail::raw_data_array(real_length * get_type().get_size());
this->arr = this->data.get_raw();
memcpy(arr, old_arr, std::min(old_length, new_length) * get_entry_size());
return vec_store::resize(new_length);
}
bool smp_vec_store::expose_sub_vec(off_t start, size_t length)
{
size_t tot_len = data.get_num_bytes() / get_type().get_size();
if (start + length > tot_len) {
exit(1);
BOOST_LOG_TRIVIAL(error) << "expose_sub_vec: out of range";
return false;
}
resize(length);
arr = data.get_raw() + start * get_entry_size();
return true;
}
vec_store::ptr smp_vec_store::deep_copy() const
{
assert(get_raw_arr() == data.get_raw());
detail::raw_data_array copy = this->data.deep_copy();
smp_vec_store::ptr ret = smp_vec_store::create(copy, get_type());
ret->resize(this->get_length());
return ret;
}
vec_store::ptr smp_vec_store::sort_with_index()
{
smp_vec_store::ptr indexes = smp_vec_store::create(get_length(),
get_scalar_type<off_t>());
get_type().get_sorter().sort_with_index(arr,
(off_t *) indexes->arr, get_length(), false);
return indexes;
}
void smp_vec_store::set_data(const set_vec_operate &op)
{
// I assume this is column-wise matrix.
// TODO parallel.
op.set(arr, get_length(), 0);
}
void smp_vec_store::set(const std::vector<const char *> &locs)
{
assert(locs.size() <= get_length());
get_type().get_sg().gather(locs, arr);
}
local_vec_store::ptr smp_vec_store::get_portion(off_t loc, size_t size)
{
if (loc + size > get_length()) {
BOOST_LOG_TRIVIAL(error) << "the portion is out of boundary";
return local_vec_store::ptr();
}
return local_vec_store::ptr(new local_ref_vec_store(get(loc),
loc, size, get_type(), -1));
}
local_vec_store::const_ptr smp_vec_store::get_portion(off_t loc,
size_t size) const
{
if (loc + size > get_length()) {
BOOST_LOG_TRIVIAL(error) << "the portion is out of boundary";
return local_vec_store::ptr();
}
return local_vec_store::ptr(new local_cref_vec_store(get(loc),
loc, size, get_type(), -1));
}
size_t smp_vec_store::get_portion_size() const
{
return 64 * 1024;
}
matrix_store::const_ptr smp_vec_store::conv2mat(size_t nrow, size_t ncol,
bool byrow) const
{
assert(arr == data.get_raw());
if (get_length() < nrow * ncol) {
BOOST_LOG_TRIVIAL(error)
<< "The vector doesn't have enough elements";
return matrix_store::ptr();
}
if (byrow)
return mem_row_matrix_store::create(data, nrow, ncol, get_type());
else
return mem_col_matrix_store::create(data, nrow, ncol, get_type());
}
template<>
vec_store::ptr create_vec_store<double>(double start, double end,
double stride)
{
// The result of division may generate a real number slightly smaller than
// what we want because of the representation precision in the machine.
// When we convert the real number to an integer, we may find the number
// is smaller than exepcted. We need to add a very small number to
// the real number to correct the problem.
// TODO is it the right way to correct the problem?
long n = (end - start) / stride + 1e-9;
if (n < 0) {
BOOST_LOG_TRIVIAL(error) <<"wrong sign in 'by' argument";
return vec_store::ptr();
}
// We need to count the start element.
n++;
detail::smp_vec_store::ptr v = detail::smp_vec_store::create(n,
get_scalar_type<double>());
v->set_data(seq_set_vec_operate<double>(n, start, stride));
return v;
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shapetransitionfactory.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:41:10 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <canvas/debug.hxx>
#include <transitionfactory.hxx>
#include <transitiontools.hxx>
#include <parametricpolypolygonfactory.hxx>
#include <animationfactory.hxx>
#include <clippingfunctor.hxx>
#include <com/sun/star/animations/TransitionType.hpp>
#include <com/sun/star/animations/TransitionSubType.hpp>
#ifndef BOOST_BIND_HPP_INCLUDED
#include <boost/bind.hpp>
#endif
using namespace ::com::sun::star;
namespace presentation {
namespace internal {
/***************************************************
*** ***
*** Shape Transition Effects ***
*** ***
***************************************************/
namespace {
class ClippingAnimation : public NumberAnimation
{
public:
ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const LayerManagerSharedPtr& rLayerManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn );
~ClippingAnimation();
// Animation interface
// -------------------
virtual void start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer );
virtual void end();
// NumberAnimation interface
// -----------------------
virtual bool operator()( double nValue );
virtual double getUnderlyingValue() const;
private:
void end_();
AnimatableShapeSharedPtr mpShape;
ShapeAttributeLayerSharedPtr mpAttrLayer;
LayerManagerSharedPtr mpLayerManager;
ClippingFunctor maClippingFunctor;
bool mbSpriteActive;
};
ClippingAnimation::ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const LayerManagerSharedPtr& rLayerManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn ) :
mpShape(),
mpAttrLayer(),
mpLayerManager( rLayerManager ),
maClippingFunctor( rPolygon,
rTransitionInfo,
bDirectionForward,
bModeIn ),
mbSpriteActive(false)
{
ENSURE_AND_THROW(
rLayerManager.get(),
"ClippingAnimation::ClippingAnimation(): Invalid LayerManager" );
}
ClippingAnimation::~ClippingAnimation()
{
end_();
}
void ClippingAnimation::start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer )
{
OSL_ENSURE( !mpShape.get(),
"ClippingAnimation::start(): Shape already set" );
OSL_ENSURE( !mpAttrLayer.get(),
"ClippingAnimation::start(): Attribute layer already set" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
ENSURE_AND_THROW( rShape.get(),
"ClippingAnimation::start(): Invalid shape" );
ENSURE_AND_THROW( rAttrLayer.get(),
"ClippingAnimation::start(): Invalid attribute layer" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
if( !mbSpriteActive )
{
mpLayerManager->enterAnimationMode( mpShape );
mbSpriteActive = true;
}
}
void ClippingAnimation::end()
{
end_();
}
void ClippingAnimation::end_()
{
if( mbSpriteActive )
{
mbSpriteActive = false;
mpLayerManager->leaveAnimationMode( mpShape );
if( mpShape->isUpdateNecessary() )
mpLayerManager->notifyShapeUpdate( mpShape );
}
}
bool ClippingAnimation::operator()( double nValue )
{
ENSURE_AND_RETURN(
mpAttrLayer.get() && mpShape.get(),
"ClippingAnimation::operator(): Invalid ShapeAttributeLayer" );
// set new clip
mpAttrLayer->setClip( maClippingFunctor( nValue,
mpShape->getDOMBounds().getRange() ) );
if( mpShape->isUpdateNecessary() )
mpLayerManager->notifyShapeUpdate( mpShape );
return true;
}
double ClippingAnimation::getUnderlyingValue() const
{
ENSURE_AND_THROW(
mpAttrLayer.get(),
"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer" );
return 0.0; // though this should be used in concert with
// ActivitiesFactory::createSimpleActivity, better
// explicitely name our start value.
// Permissible range for operator() above is [0,1]
}
} // anon namespace
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const LayerManagerSharedPtr& rLayerManager,
uno::Reference< animations::XTransitionFilter > const& xTransition )
{
return createShapeTransition( rParms,
rShape,
rLayerManager,
xTransition,
xTransition->getTransition(),
xTransition->getSubtype() );
}
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const LayerManagerSharedPtr& rLayerManager,
::com::sun::star::uno::Reference<
::com::sun::star::animations::XTransitionFilter > const& xTransition,
sal_Int16 nType,
sal_Int16 nSubType )
{
ENSURE_AND_THROW(
xTransition.is(),
"TransitionFactory::createShapeTransition(): Invalid XTransition" );
const TransitionInfo* pTransitionInfo(
getTransitionInfo( nType, nSubType ) );
AnimationActivitySharedPtr pGeneratedActivity;
if( pTransitionInfo != NULL )
{
switch( pTransitionInfo->meTransitionClass )
{
default:
case TransitionInfo::TRANSITION_INVALID:
OSL_ENSURE( false,
"TransitionFactory::createShapeTransition(): Invalid transition type. "
"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!" );
return AnimationActivitySharedPtr();
case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:
{
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
nType, nSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rLayerManager,
*pTransitionInfo,
xTransition->getDirection(),
xTransition->getMode() ) ),
true );
}
break;
case TransitionInfo::TRANSITION_SPECIAL:
{
switch( nType )
{
case animations::TransitionType::RANDOM:
{
// select randomly one of the effects from the
// TransitionFactoryTable
const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );
ENSURE_AND_THROW( pRandomTransitionInfo != NULL,
"TransitionFactory::createShapeTransition(): Got invalid random transition info" );
ENSURE_AND_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,
"TransitionFactory::createShapeTransition(): Got random again for random input!" );
// and recurse
pGeneratedActivity = createShapeTransition( rParms,
rShape,
rLayerManager,
xTransition,
pRandomTransitionInfo->mnTransitionType,
pRandomTransitionInfo->mnTransitionSubType );
}
break;
// TODO(F3): Implement slidewipe for shape
case animations::TransitionType::SLIDEWIPE:
{
sal_Int16 nBarWipeSubType(0);
bool bDirectionForward(true);
// map slidewipe to BARWIPE, for now
switch( nSubType )
{
case animations::TransitionSubType::FROMLEFT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMRIGHT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = false;
break;
case animations::TransitionSubType::FROMTOP:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMBOTTOM:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = false;
break;
default:
ENSURE_AND_THROW( false,
"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE" );
break;
}
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
animations::TransitionType::BARWIPE,
nBarWipeSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rLayerManager,
*getTransitionInfo( animations::TransitionType::BARWIPE,
nBarWipeSubType ),
bDirectionForward,
xTransition->getMode() ) ),
true );
}
break;
default:
{
// TODO(F1): Check whether there's anything left, anyway,
// for _shape_ transitions. AFAIK, there are no special
// effects for shapes...
// for now, map all to fade effect
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
AnimationFactory::createNumberPropertyAnimation(
::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("Opacity") ),
rShape,
rLayerManager ),
xTransition->getMode() );
}
break;
}
}
break;
}
}
if( !pGeneratedActivity.get() )
{
// No animation generated, maybe no table entry for given
// transition?
OSL_TRACE(
"TransitionFactory::createShapeTransition(): Unknown type/subtype (%d/%d) "
"combination encountered",
xTransition->getTransition(),
xTransition->getSubtype() );
OSL_ENSURE(
false,
"TransitionFactory::createShapeTransition(): Unknown type/subtype "
"combination encountered" );
}
return pGeneratedActivity;
}
}
}
<commit_msg>INTEGRATION: CWS presfixes09 (1.5.10); FILE MERGED 2006/10/18 19:59:09 thb 1.5.10.5: RESYNC: (1.5-1.6); FILE MERGED 2006/04/24 13:25:33 thb 1.5.10.4: #i53194# Unified include statements (local headers always have double quotes; external headers angle brackets); reverted EventMultiplexer pause events to shared_ptr; removed EventMultiplexer::removeViewHandler(), since the handler is held weakly, anyway. 2006/04/12 20:40:08 thb 1.5.10.3: #i37778# Replaced all shared_ptr.get() != NULL places with the more elegant automatic-conversion-to-bool version (at least where the compiler tolerated that) 2006/03/24 18:23:25 thb 1.5.10.2: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006/03/06 22:14:32 thb 1.5.10.1: #i53194# #i55294# #i59324# Overhauled IntrinsicAnimationActivity; fixes GIF animation import; corrected rehearse timings sprite size; several cosmetic changes (removed external header guards); prepared scene for sprite prio<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shapetransitionfactory.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2006-12-13 15:45:03 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
#include <canvas/debug.hxx>
#include <comphelper/anytostring.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <com/sun/star/animations/TransitionType.hpp>
#include <com/sun/star/animations/TransitionSubType.hpp>
#include "transitionfactory.hxx"
#include "transitiontools.hxx"
#include "parametricpolypolygonfactory.hxx"
#include "animationfactory.hxx"
#include "clippingfunctor.hxx"
#include <boost/bind.hpp>
using namespace ::com::sun::star;
namespace slideshow {
namespace internal {
/***************************************************
*** ***
*** Shape Transition Effects ***
*** ***
***************************************************/
namespace {
class ClippingAnimation : public NumberAnimation
{
public:
ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const LayerManagerSharedPtr& rLayerManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn );
~ClippingAnimation();
// Animation interface
// -------------------
virtual void start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer );
virtual void end();
// NumberAnimation interface
// -----------------------
virtual bool operator()( double nValue );
virtual double getUnderlyingValue() const;
private:
void end_();
AnimatableShapeSharedPtr mpShape;
ShapeAttributeLayerSharedPtr mpAttrLayer;
LayerManagerSharedPtr mpLayerManager;
ClippingFunctor maClippingFunctor;
bool mbSpriteActive;
};
ClippingAnimation::ClippingAnimation(
const ParametricPolyPolygonSharedPtr& rPolygon,
const LayerManagerSharedPtr& rLayerManager,
const TransitionInfo& rTransitionInfo,
bool bDirectionForward,
bool bModeIn ) :
mpShape(),
mpAttrLayer(),
mpLayerManager( rLayerManager ),
maClippingFunctor( rPolygon,
rTransitionInfo,
bDirectionForward,
bModeIn ),
mbSpriteActive(false)
{
ENSURE_AND_THROW(
rLayerManager,
"ClippingAnimation::ClippingAnimation(): Invalid LayerManager" );
}
ClippingAnimation::~ClippingAnimation()
{
try
{
end_();
}
catch (uno::Exception &) {
OSL_ENSURE( false, rtl::OUStringToOString(
comphelper::anyToString(
cppu::getCaughtException() ),
RTL_TEXTENCODING_UTF8 ).getStr() );
}
}
void ClippingAnimation::start( const AnimatableShapeSharedPtr& rShape,
const ShapeAttributeLayerSharedPtr& rAttrLayer )
{
OSL_ENSURE( !mpShape,
"ClippingAnimation::start(): Shape already set" );
OSL_ENSURE( !mpAttrLayer,
"ClippingAnimation::start(): Attribute layer already set" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
ENSURE_AND_THROW( rShape,
"ClippingAnimation::start(): Invalid shape" );
ENSURE_AND_THROW( rAttrLayer,
"ClippingAnimation::start(): Invalid attribute layer" );
mpShape = rShape;
mpAttrLayer = rAttrLayer;
if( !mbSpriteActive )
{
mpLayerManager->enterAnimationMode( mpShape );
mbSpriteActive = true;
}
}
void ClippingAnimation::end()
{
end_();
}
void ClippingAnimation::end_()
{
if( mbSpriteActive )
{
mbSpriteActive = false;
mpLayerManager->leaveAnimationMode( mpShape );
if( mpShape->isUpdateNecessary() )
mpLayerManager->notifyShapeUpdate( mpShape );
}
}
bool ClippingAnimation::operator()( double nValue )
{
ENSURE_AND_RETURN(
mpAttrLayer && mpShape,
"ClippingAnimation::operator(): Invalid ShapeAttributeLayer" );
// set new clip
mpAttrLayer->setClip( maClippingFunctor( nValue,
mpShape->getDOMBounds().getRange() ) );
if( mpShape->isUpdateNecessary() )
mpLayerManager->notifyShapeUpdate( mpShape );
return true;
}
double ClippingAnimation::getUnderlyingValue() const
{
ENSURE_AND_THROW(
mpAttrLayer,
"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer" );
return 0.0; // though this should be used in concert with
// ActivitiesFactory::createSimpleActivity, better
// explicitely name our start value.
// Permissible range for operator() above is [0,1]
}
} // anon namespace
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const LayerManagerSharedPtr& rLayerManager,
uno::Reference< animations::XTransitionFilter > const& xTransition )
{
return createShapeTransition( rParms,
rShape,
rLayerManager,
xTransition,
xTransition->getTransition(),
xTransition->getSubtype() );
}
AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
const ActivitiesFactory::CommonParameters& rParms,
const AnimatableShapeSharedPtr& rShape,
const LayerManagerSharedPtr& rLayerManager,
::com::sun::star::uno::Reference<
::com::sun::star::animations::XTransitionFilter > const& xTransition,
sal_Int16 nType,
sal_Int16 nSubType )
{
ENSURE_AND_THROW(
xTransition.is(),
"TransitionFactory::createShapeTransition(): Invalid XTransition" );
const TransitionInfo* pTransitionInfo(
getTransitionInfo( nType, nSubType ) );
AnimationActivitySharedPtr pGeneratedActivity;
if( pTransitionInfo != NULL )
{
switch( pTransitionInfo->meTransitionClass )
{
default:
case TransitionInfo::TRANSITION_INVALID:
OSL_ENSURE( false,
"TransitionFactory::createShapeTransition(): Invalid transition type. "
"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!" );
return AnimationActivitySharedPtr();
case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:
{
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
nType, nSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rLayerManager,
*pTransitionInfo,
xTransition->getDirection(),
xTransition->getMode() ) ),
true );
}
break;
case TransitionInfo::TRANSITION_SPECIAL:
{
switch( nType )
{
case animations::TransitionType::RANDOM:
{
// select randomly one of the effects from the
// TransitionFactoryTable
const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );
ENSURE_AND_THROW( pRandomTransitionInfo != NULL,
"TransitionFactory::createShapeTransition(): Got invalid random transition info" );
ENSURE_AND_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,
"TransitionFactory::createShapeTransition(): Got random again for random input!" );
// and recurse
pGeneratedActivity = createShapeTransition( rParms,
rShape,
rLayerManager,
xTransition,
pRandomTransitionInfo->mnTransitionType,
pRandomTransitionInfo->mnTransitionSubType );
}
break;
// TODO(F3): Implement slidewipe for shape
case animations::TransitionType::SLIDEWIPE:
{
sal_Int16 nBarWipeSubType(0);
bool bDirectionForward(true);
// map slidewipe to BARWIPE, for now
switch( nSubType )
{
case animations::TransitionSubType::FROMLEFT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMRIGHT:
nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
bDirectionForward = false;
break;
case animations::TransitionSubType::FROMTOP:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = true;
break;
case animations::TransitionSubType::FROMBOTTOM:
nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
bDirectionForward = false;
break;
default:
ENSURE_AND_THROW( false,
"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE" );
break;
}
// generate parametric poly-polygon
ParametricPolyPolygonSharedPtr pPoly(
ParametricPolyPolygonFactory::createClipPolyPolygon(
animations::TransitionType::BARWIPE,
nBarWipeSubType ) );
// create a clip activity from that
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
NumberAnimationSharedPtr(
new ClippingAnimation(
pPoly,
rLayerManager,
*getTransitionInfo( animations::TransitionType::BARWIPE,
nBarWipeSubType ),
bDirectionForward,
xTransition->getMode() ) ),
true );
}
break;
default:
{
// TODO(F1): Check whether there's anything left, anyway,
// for _shape_ transitions. AFAIK, there are no special
// effects for shapes...
// for now, map all to fade effect
pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
rParms,
AnimationFactory::createNumberPropertyAnimation(
::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("Opacity") ),
rShape,
rLayerManager ),
xTransition->getMode() );
}
break;
}
}
break;
}
}
if( !pGeneratedActivity )
{
// No animation generated, maybe no table entry for given
// transition?
OSL_TRACE(
"TransitionFactory::createShapeTransition(): Unknown type/subtype (%d/%d) "
"combination encountered",
xTransition->getTransition(),
xTransition->getSubtype() );
OSL_ENSURE(
false,
"TransitionFactory::createShapeTransition(): Unknown type/subtype "
"combination encountered" );
}
return pGeneratedActivity;
}
}
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2014 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_FUNCTION_NAME_HH
#define CQL3_FUNCTION_NAME_HH
#include "core/sstring.hh"
#include "db/system_keyspace.hh"
#include <iostream>
#include <functional>
namespace cql3 {
namespace functions {
class function_name final {
public:
const sstring keyspace;
const sstring name;
static function_name native_function(sstring name) {
return function_name(db::system_keyspace::NAME, name);
}
function_name(sstring keyspace, sstring name)
: keyspace(std::move(keyspace)), name(std::move(name)) {
}
function_name as_native_function() const {
return native_function(name);
}
bool has_keyspace() const {
return !keyspace.empty();
}
bool operator==(const function_name& x) const {
return keyspace == x.keyspace && name == x.name;
}
};
inline
std::ostream& operator<<(std::ostream& os, const function_name& fn) {
if (!fn.keyspace.empty()) {
os << fn.keyspace << ".";
}
return os << fn.name;
}
}
}
namespace std {
template <>
struct hash<cql3::functions::function_name> {
size_t operator()(const cql3::functions::function_name& x) const {
return std::hash<sstring>()(x.keyspace) ^ std::hash<sstring>()(x.name);
}
};
}
#endif
<commit_msg>cql3: make function_name friendlier to ANTLR<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2014 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_FUNCTION_NAME_HH
#define CQL3_FUNCTION_NAME_HH
#include "core/sstring.hh"
#include "db/system_keyspace.hh"
#include <iostream>
#include <functional>
namespace cql3 {
namespace functions {
class function_name final {
public:
sstring keyspace;
sstring name;
static function_name native_function(sstring name) {
return function_name(db::system_keyspace::NAME, name);
}
function_name() = default; // for ANTLR
function_name(sstring keyspace, sstring name)
: keyspace(std::move(keyspace)), name(std::move(name)) {
}
function_name as_native_function() const {
return native_function(name);
}
bool has_keyspace() const {
return !keyspace.empty();
}
bool operator==(const function_name& x) const {
return keyspace == x.keyspace && name == x.name;
}
};
inline
std::ostream& operator<<(std::ostream& os, const function_name& fn) {
if (!fn.keyspace.empty()) {
os << fn.keyspace << ".";
}
return os << fn.name;
}
}
}
namespace std {
template <>
struct hash<cql3::functions::function_name> {
size_t operator()(const cql3::functions::function_name& x) const {
return std::hash<sstring>()(x.keyspace) ^ std::hash<sstring>()(x.name);
}
};
}
#endif
<|endoftext|> |
<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "highlevel_feature_extractor.h"
#include <rcsc/common/server_param.h>
using namespace rcsc;
HighLevelFeatureExtractor::HighLevelFeatureExtractor(int num_teammates,
int num_opponents,
bool playing_offense) :
FeatureExtractor(num_teammates, num_opponents, playing_offense)
{
assert(numTeammates >= 0);
assert(numOpponents >= 0);
numFeatures = num_basic_features + features_per_teammate * numTeammates
+ features_per_opponent * numOpponents;
numFeatures+=2; // action status, stamina
feature_vec.resize(numFeatures);
}
HighLevelFeatureExtractor::~HighLevelFeatureExtractor() {}
const std::vector<float>&
HighLevelFeatureExtractor::ExtractFeatures(const rcsc::WorldModel& wm,
bool last_action_status) {
featIndx = 0;
const ServerParam& SP = ServerParam::i();
const SelfObject& self = wm.self();
const Vector2D& self_pos = self.pos();
const float self_ang = self.body().radian();
const PlayerPtrCont& teammates = wm.teammatesFromSelf();
const PlayerPtrCont& opponents = wm.opponentsFromSelf();
float maxR = sqrtf(SP.pitchHalfLength() * SP.pitchHalfLength()
+ SP.pitchHalfWidth() * SP.pitchHalfWidth());
// features about self pos
// Allow the agent to go 10% over the playfield in any direction
float tolerance_x = .1 * SP.pitchHalfLength();
float tolerance_y = .1 * SP.pitchHalfWidth();
// Feature[0]: X-postion
if (playingOffense) {
addNormFeature(self_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(self_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
// Feature[1]: Y-Position
addNormFeature(self_pos.y, -SP.pitchHalfWidth() - tolerance_y,
SP.pitchHalfWidth() + tolerance_y);
// Feature[2]: Self Angle
addNormFeature(self_ang, -M_PI, M_PI);
float r;
float th;
// Features about the ball
Vector2D ball_pos = wm.ball().pos();
angleDistToPoint(self_pos, ball_pos, th, r);
// Feature[3] and [4]: (x,y) postition of the ball
if (playingOffense) {
addNormFeature(ball_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(ball_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
addNormFeature(ball_pos.y, -SP.pitchHalfWidth() - tolerance_y, SP.pitchHalfWidth() + tolerance_y);
// Feature[5]: Able to kick
addNormFeature(self.isKickable(), false, true);
// Features about distance to goal center
Vector2D goalCenter(SP.pitchHalfLength(), 0);
if (!playingOffense) {
goalCenter.assign(-SP.pitchHalfLength(), 0);
}
angleDistToPoint(self_pos, goalCenter, th, r);
// Feature[6]: Goal Center Distance
addNormFeature(r, 0, maxR);
// Feature[7]: Angle to goal center
addNormFeature(th, -M_PI, M_PI);
// Feature[8]: largest open goal angle
addNormFeature(calcLargestGoalAngle(wm, self_pos), 0, M_PI);
// Feature[9]: Dist to our closest opp
if (numOpponents > 0) {
calcClosestOpp(wm, self_pos, th, r);
addNormFeature(r, 0, maxR);
} else {
addFeature(FEAT_INVALID);
}
// Features[9 - 9+T]: teammate's open angle to goal
int detected_teammates = 0;
for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject* teammate = *it;
if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {
addNormFeature(calcLargestGoalAngle(wm, teammate->pos()), 0, M_PI);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
// Features[9+T - 9+2T]: teammates' dists to closest opps
if (numOpponents > 0) {
detected_teammates = 0;
for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject* teammate = *it;
if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {
calcClosestOpp(wm, teammate->pos(), th, r);
addNormFeature(r, 0, maxR);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
} else { // If no opponents, add invalid features
for (int i=0; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
}
// Features [9+2T - 9+3T]: open angle to teammates
detected_teammates = 0;
for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject* teammate = *it;
if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {
addNormFeature(calcLargestTeammateAngle(wm, self_pos, teammate->pos()),0,M_PI);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
// Features [9+3T - 9+6T]: x, y, unum of teammates
detected_teammates = 0;
for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject* teammate = *it;
if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {
if (playingOffense) {
addNormFeature(teammate->pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(teammate->pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
addNormFeature(teammate->pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);
addFeature(teammate->unum());
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
// Features [9+6T - 9+6T+3O]: x, y, unum of opponents
int detected_opponents = 0;
for (PlayerPtrCont::const_iterator it = opponents.begin(); it != opponents.end(); ++it) {
const PlayerObject* opponent = *it;
if (valid(opponent) && opponent->unum() > 0 && detected_opponents < numOpponents) {
if (playingOffense) {
addNormFeature(opponent->pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(opponent->pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
addNormFeature(opponent->pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);
addFeature(opponent->unum());
detected_opponents++;
}
}
// Add zero features for any missing opponents
for (int i=detected_opponents; i<numOpponents; ++i) {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
if (last_action_status) {
addFeature(FEAT_MAX);
} else {
addFeature(FEAT_MIN);
}
addNormFeature(self.stamina(), 0., observedStaminaMax);
assert(featIndx == numFeatures);
// checkFeatures();
return feature_vec;
}
bool HighLevelFeatureExtractor::valid(const rcsc::PlayerObject* player) {
if (!player) {return false;} //avoid segfaults
const rcsc::Vector2D& pos = player->pos();
if (!player->posValid()) {
return false;
}
return pos.isValid();
}
<commit_msg>Update highlevel_feature_extractor.cpp<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "highlevel_feature_extractor.h"
#include <rcsc/common/server_param.h>
using namespace rcsc;
HighLevelFeatureExtractor::HighLevelFeatureExtractor(int num_teammates,
int num_opponents,
bool playing_offense) :
FeatureExtractor(num_teammates, num_opponents, playing_offense)
{
assert(numTeammates >= 0);
assert(numOpponents >= 0);
numFeatures = num_basic_features + features_per_teammate * numTeammates
+ features_per_opponent * numOpponents;
numFeatures+=2; // action status, stamina
feature_vec.resize(numFeatures);
}
HighLevelFeatureExtractor::~HighLevelFeatureExtractor() {}
const std::vector<float>&
HighLevelFeatureExtractor::ExtractFeatures(const rcsc::WorldModel& wm,
bool last_action_status) {
featIndx = 0;
const ServerParam& SP = ServerParam::i();
const SelfObject& self = wm.self();
const Vector2D& self_pos = self.pos();
const float self_ang = self.body().radian();
const PlayerPtrCont& teammates = wm.teammatesFromSelf();
const PlayerPtrCont& opponents = wm.opponentsFromSelf();
float maxR = sqrtf(SP.pitchHalfLength() * SP.pitchHalfLength()
+ SP.pitchWidth() * SP.pitchWidth());
// features about self pos
// Allow the agent to go 10% over the playfield in any direction
float tolerance_x = .1 * SP.pitchHalfLength();
float tolerance_y = .1 * SP.pitchHalfWidth();
// Feature[0]: X-postion
if (playingOffense) {
addNormFeature(self_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(self_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
// Feature[1]: Y-Position
addNormFeature(self_pos.y, -SP.pitchHalfWidth() - tolerance_y,
SP.pitchHalfWidth() + tolerance_y);
// Feature[2]: Self Angle
addNormFeature(self_ang, -M_PI, M_PI);
float r;
float th;
// Features about the ball
Vector2D ball_pos = wm.ball().pos();
angleDistToPoint(self_pos, ball_pos, th, r);
// Feature[3] and [4]: (x,y) postition of the ball
if (playingOffense) {
addNormFeature(ball_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(ball_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
addNormFeature(ball_pos.y, -SP.pitchHalfWidth() - tolerance_y, SP.pitchHalfWidth() + tolerance_y);
// Feature[5]: Able to kick
addNormFeature(self.isKickable(), false, true);
// Features about distance to goal center
Vector2D goalCenter(SP.pitchHalfLength(), 0);
if (!playingOffense) {
goalCenter.assign(-SP.pitchHalfLength(), 0);
}
angleDistToPoint(self_pos, goalCenter, th, r);
// Feature[6]: Goal Center Distance
addNormFeature(r, 0, maxR);
// Feature[7]: Angle to goal center
addNormFeature(th, -M_PI, M_PI);
// Feature[8]: largest open goal angle
addNormFeature(calcLargestGoalAngle(wm, self_pos), 0, M_PI);
// Feature[9]: Dist to our closest opp
if (numOpponents > 0) {
calcClosestOpp(wm, self_pos, th, r);
addNormFeature(r, 0, maxR);
} else {
addFeature(FEAT_INVALID);
}
// Features[9 - 9+T]: teammate's open angle to goal
int detected_teammates = 0;
for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject* teammate = *it;
if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {
addNormFeature(calcLargestGoalAngle(wm, teammate->pos()), 0, M_PI);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
// Features[9+T - 9+2T]: teammates' dists to closest opps
if (numOpponents > 0) {
detected_teammates = 0;
for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject* teammate = *it;
if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {
calcClosestOpp(wm, teammate->pos(), th, r);
addNormFeature(r, 0, maxR);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
} else { // If no opponents, add invalid features
for (int i=0; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
}
// Features [9+2T - 9+3T]: open angle to teammates
detected_teammates = 0;
for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject* teammate = *it;
if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {
addNormFeature(calcLargestTeammateAngle(wm, self_pos, teammate->pos()),0,M_PI);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
// Features [9+3T - 9+6T]: x, y, unum of teammates
detected_teammates = 0;
for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject* teammate = *it;
if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {
if (playingOffense) {
addNormFeature(teammate->pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(teammate->pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
addNormFeature(teammate->pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);
addFeature(teammate->unum());
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
// Features [9+6T - 9+6T+3O]: x, y, unum of opponents
int detected_opponents = 0;
for (PlayerPtrCont::const_iterator it = opponents.begin(); it != opponents.end(); ++it) {
const PlayerObject* opponent = *it;
if (valid(opponent) && opponent->unum() > 0 && detected_opponents < numOpponents) {
if (playingOffense) {
addNormFeature(opponent->pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(opponent->pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
addNormFeature(opponent->pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);
addFeature(opponent->unum());
detected_opponents++;
}
}
// Add zero features for any missing opponents
for (int i=detected_opponents; i<numOpponents; ++i) {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
if (last_action_status) {
addFeature(FEAT_MAX);
} else {
addFeature(FEAT_MIN);
}
addNormFeature(self.stamina(), 0., observedStaminaMax);
assert(featIndx == numFeatures);
// checkFeatures();
return feature_vec;
}
bool HighLevelFeatureExtractor::valid(const rcsc::PlayerObject* player) {
if (!player) {return false;} //avoid segfaults
const rcsc::Vector2D& pos = player->pos();
if (!player->posValid()) {
return false;
}
return pos.isValid();
}
<|endoftext|> |
<commit_before>#include "../MDFILU_test.h"
int
main(int argc, char *argv[])
{
// #ifdef VERBOSE_OUTPUT
// debugStream.open("debug.out");
// #endif
Utilities::MPI::MPI_InitFinalize mpi_initialization(
argc, argv, ::numbers::invalid_unsigned_int);
const global_index_type degree(10);
const unsigned int estimated_row_length(10);
SourceMatrix system_matrix(degree,
degree,
/*max_entries_per_row*/ estimated_row_length);
// Set value for system_matrix
const bool use_sparse_matrix(true);
if (use_sparse_matrix)
{
std::ifstream fin("sparse_matrix.dat");
while (true)
{
global_index_type i, j;
data_type value;
fin >> i >> j >> value;
if (fin.eof())
{
break;
}
system_matrix.set(i, j, value);
}
fin.close();
}
else
{
std::ifstream fin("matrix.dat");
for (global_index_type i = 0; i < degree; ++i)
for (global_index_type j = 0; j < degree; ++j)
{
data_type value;
fin >> value;
system_matrix.set(i, j, value);
}
fin.close();
}
system_matrix.compress(VectorOperation::insert);
{
// Out put system_matrix
std::ofstream fout("matrix.out");
system_matrix.print(fout);
fout.close();
}
MDFILU mdfilu(system_matrix, estimated_row_length, 20);
// Out put LU
{
std::ofstream fout("LU.out");
mdfilu.get_LU().print(fout);
fout.close();
}
// Test the MDFILU class by multiplying LU back
// For now the sparsity pattern is ignored.
{
const data_type tolerance(1e-12);
DynamicMatrix A(degree, degree, estimated_row_length);
// Compute LD*U
for (global_index_type i = 0; i < degree; ++i)
{
const global_index_type i_row = mdfilu.get_permutation()[i];
for (global_index_type j = 0; j < degree; ++j)
{
const global_index_type j_col = mdfilu.get_permutation()[j];
data_type value = 0;
global_index_type vmult_max_index = 0;
// Diagonal values of L is always 1 thus not been stored.
// Recover its effect manually.
if (j >= i)
{
value = mdfilu.get_LU().el(i_row, j_col);
vmult_max_index = i;
}
else
{
vmult_max_index = j + 1;
}
for (global_index_type k = 0; k < vmult_max_index; ++k)
{
const global_index_type k_permuted =
mdfilu.get_permutation()[k];
value += mdfilu.get_LU().el(i_row, k_permuted) *
mdfilu.get_LU().el(k_permuted, j_col);
}
if (std::abs(value) > tolerance)
{
A.set(i_row, j_col, value);
}
}
}
std::ofstream fout("A.out");
A.print(fout);
fout.close();
}
// Report number of new fill-ins
{
std::ofstream fout("apply.out");
fout << "\nNumber of new fill-ins: " << mdfilu.number_of_new_fill_ins()
<< std::endl
<< std::endl;
fout.close();
}
// Apply LU and (LU)^-1 to a vector
MDFVector v(degree);
{
const data_type a[degree] = {6, 10, 9, 5, 2, 5, 7, 3, 6, 3};
for (global_index_type i = 0; i < degree; ++i)
{
v[i] = a[i];
}
}
// Cache initial transpose status
const bool use_tranpose_init_stats = mdfilu.UseTranspose();
//--------- Deal.II native Vector ---------//
mdfilu.SetUseTranspose(false);
{
MDFVector o(v);
mdfilu.apply(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout.precision(3);
fout << std::scientific;
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "Vector (LU)*v:" << std::endl;
fout << o << std::endl << std::endl;
fout.close();
}
{
MDFVector o(v);
mdfilu.apply_inverse(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout.precision(3);
fout << std::scientific;
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "Vector ((LU)^-1)*v:" << std::endl;
fout << o << std::endl << std::endl;
fout.close();
}
mdfilu.SetUseTranspose(true);
{
MDFVector o(v);
mdfilu.apply(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout.precision(3);
fout << std::scientific;
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "Vector ((LU)^T)*v:" << std::endl;
fout << o << std::endl << std::endl;
fout.close();
}
{
MDFVector o(v);
mdfilu.apply_inverse(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout.precision(3);
fout << std::scientific;
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "Vector (((LU)^-1)^T)*v:" << std::endl;
fout << o << std::endl << std::endl;
fout.close();
}
// Set flags
mdfilu.SetUseTranspose(use_tranpose_init_stats);
//[END]// //--------- Deal.II native Vector ---------//
//--------- Deal.II wrapped Trilinos Vector ---------//
mdfilu.SetUseTranspose(false);
{
NSVector o;
o = v;
mdfilu.apply(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout << "Vector v:" << std::endl;
fout << v;
fout << "NSVector (LU)*v:" << std::endl;
fout.precision(3);
fout << std::scientific;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
fout.close();
}
{
NSVector o;
o = v;
mdfilu.apply_inverse(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout << "Vector v:" << std::endl;
fout << v;
fout << "NSVector ((LU)^-1)*v:" << std::endl;
fout.precision(3);
fout << std::scientific;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
fout.close();
}
mdfilu.SetUseTranspose(true);
{
NSVector o;
o = v;
mdfilu.apply(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout << "Vector v:" << std::endl;
fout << v;
fout << "NSVector ((LU)^T)*v:" << std::endl;
fout.precision(3);
fout << std::scientific;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
fout.close();
}
{
NSVector o;
o = v;
mdfilu.apply_inverse(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout << "Vector v:" << std::endl;
fout << v;
fout << "NSVector (((LU)^-1)^T)*v:" << std::endl;
fout.precision(3);
fout << std::scientific;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
fout.close();
}
mdfilu.SetUseTranspose(use_tranpose_init_stats);
//[END]// //--------- Deal.II wrapped Trilinos Vector ---------//
//--------- Finally, Preconditioner test ---------//
{
// No preconditioner first
Epetra_Vector o(system_matrix.trilinos_matrix().DomainMap());
Epetra_Vector b(View,
system_matrix.trilinos_matrix().RangeMap(),
v.begin());
AztecOO solver;
solver.SetAztecOption(AZ_output, AZ_none);
solver.SetAztecOption(AZ_solver, AZ_gmres);
solver.SetLHS(&o);
solver.SetRHS(&b);
solver.SetAztecOption(AZ_precond, AZ_none);
solver.SetUserMatrix(
const_cast<Epetra_CrsMatrix *>(&system_matrix.trilinos_matrix()));
const unsigned int max_iterations = 1000;
const double linear_residual = 1e-8;
solver.Iterate(max_iterations, linear_residual);
std::ofstream fout("apply.out", std::fstream::app);
fout << "GMRES Solved Ax=v without preconditioner:" << std::endl;
fout << "NumIters: " << solver.NumIters() << std::endl;
fout << "TrueResidual: " << solver.TrueResidual() << std::endl;
fout.precision(3);
fout << std::scientific;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
fout.close();
}
{
// No preconditioner first
Epetra_Vector o(system_matrix.trilinos_matrix().DomainMap());
Epetra_Vector b(View,
system_matrix.trilinos_matrix().RangeMap(),
v.begin());
AztecOO solver;
solver.SetAztecOption(AZ_output, AZ_none);
solver.SetAztecOption(AZ_solver, AZ_gmres);
solver.SetLHS(&o);
solver.SetRHS(&b);
solver.SetUserMatrix(
const_cast<Epetra_CrsMatrix *>(&system_matrix.trilinos_matrix()));
mdfilu.SetUseTranspose(false);
solver.SetPrecOperator(&mdfilu);
const unsigned int max_iterations = 1000;
const double linear_residual = 1e-8;
solver.Iterate(max_iterations, linear_residual);
std::ofstream fout("apply.out", std::fstream::app);
fout << "GMRES Solved Ax=v with MDFILU preconditioner:" << std::endl;
fout << "NumIters: " << solver.NumIters() << std::endl;
fout << "TrueResidual: " << solver.TrueResidual() << std::endl;
fout.precision(3);
fout << std::scientific;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
fout.close();
}
mdfilu.SetUseTranspose(use_tranpose_init_stats);
//[END]// //--------- Finally, Preconditioner test ---------//
// #ifdef VERBOSE_OUTPUT
// debugStream.close();
// #endif
return (system("cat A.out apply.out LU.out matrix.out > output.out"));
}
<commit_msg>fix regTests module_MDFILU case002000 due to trilinos vector interface change<commit_after>#include "../MDFILU_test.h"
int
main(int argc, char *argv[])
{
// #ifdef VERBOSE_OUTPUT
// debugStream.open("debug.out");
// #endif
Utilities::MPI::MPI_InitFinalize mpi_initialization(
argc, argv, ::numbers::invalid_unsigned_int);
const global_index_type degree(10);
const unsigned int estimated_row_length(10);
SourceMatrix system_matrix(degree,
degree,
/*max_entries_per_row*/ estimated_row_length);
// Set value for system_matrix
const bool use_sparse_matrix(true);
if (use_sparse_matrix)
{
std::ifstream fin("sparse_matrix.dat");
while (true)
{
global_index_type i, j;
data_type value;
fin >> i >> j >> value;
if (fin.eof())
{
break;
}
system_matrix.set(i, j, value);
}
fin.close();
}
else
{
std::ifstream fin("matrix.dat");
for (global_index_type i = 0; i < degree; ++i)
for (global_index_type j = 0; j < degree; ++j)
{
data_type value;
fin >> value;
system_matrix.set(i, j, value);
}
fin.close();
}
system_matrix.compress(VectorOperation::insert);
{
// Out put system_matrix
std::ofstream fout("matrix.out");
system_matrix.print(fout);
fout.close();
}
MDFILU mdfilu(system_matrix, estimated_row_length, 20);
// Out put LU
{
std::ofstream fout("LU.out");
mdfilu.get_LU().print(fout);
fout.close();
}
// Test the MDFILU class by multiplying LU back
// For now the sparsity pattern is ignored.
{
const data_type tolerance(1e-12);
DynamicMatrix A(degree, degree, estimated_row_length);
// Compute LD*U
for (global_index_type i = 0; i < degree; ++i)
{
const global_index_type i_row = mdfilu.get_permutation()[i];
for (global_index_type j = 0; j < degree; ++j)
{
const global_index_type j_col = mdfilu.get_permutation()[j];
data_type value = 0;
global_index_type vmult_max_index = 0;
// Diagonal values of L is always 1 thus not been stored.
// Recover its effect manually.
if (j >= i)
{
value = mdfilu.get_LU().el(i_row, j_col);
vmult_max_index = i;
}
else
{
vmult_max_index = j + 1;
}
for (global_index_type k = 0; k < vmult_max_index; ++k)
{
const global_index_type k_permuted =
mdfilu.get_permutation()[k];
value += mdfilu.get_LU().el(i_row, k_permuted) *
mdfilu.get_LU().el(k_permuted, j_col);
}
if (std::abs(value) > tolerance)
{
A.set(i_row, j_col, value);
}
}
}
std::ofstream fout("A.out");
A.print(fout);
fout.close();
}
// Report number of new fill-ins
{
std::ofstream fout("apply.out");
fout << "\nNumber of new fill-ins: " << mdfilu.number_of_new_fill_ins()
<< std::endl
<< std::endl;
fout.close();
}
// Apply LU and (LU)^-1 to a vector
MDFVector v(degree);
{
const data_type a[degree] = {6, 10, 9, 5, 2, 5, 7, 3, 6, 3};
for (global_index_type i = 0; i < degree; ++i)
{
v[i] = a[i];
}
}
// Cache initial transpose status
const bool use_tranpose_init_stats = mdfilu.UseTranspose();
//--------- Deal.II native Vector ---------//
mdfilu.SetUseTranspose(false);
{
MDFVector o(v);
mdfilu.apply(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout.precision(3);
fout << std::scientific;
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "Vector (LU)*v:" << std::endl;
fout << o << std::endl << std::endl;
fout.close();
}
{
MDFVector o(v);
mdfilu.apply_inverse(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout.precision(3);
fout << std::scientific;
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "Vector ((LU)^-1)*v:" << std::endl;
fout << o << std::endl << std::endl;
fout.close();
}
mdfilu.SetUseTranspose(true);
{
MDFVector o(v);
mdfilu.apply(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout.precision(3);
fout << std::scientific;
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "Vector ((LU)^T)*v:" << std::endl;
fout << o << std::endl << std::endl;
fout.close();
}
{
MDFVector o(v);
mdfilu.apply_inverse(o, o);
std::ofstream fout("apply.out", std::fstream::app);
fout.precision(3);
fout << std::scientific;
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "Vector (((LU)^-1)^T)*v:" << std::endl;
fout << o << std::endl << std::endl;
fout.close();
}
// Set flags
mdfilu.SetUseTranspose(use_tranpose_init_stats);
//[END]// //--------- Deal.II native Vector ---------//
//--------- Deal.II wrapped Trilinos Vector ---------//
{
mdfilu.SetUseTranspose(false);
std::ofstream fout("apply.out", std::fstream::app);
fout.precision(3);
fout << std::scientific;
IndexSet idxset(degree);
idxset.add_range(0, degree);
NSVector o(idxset);
o = v;
mdfilu.apply(o, o);
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "NSVector (LU)*v:" << std::endl;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
o = v;
mdfilu.apply_inverse(o, o);
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "NSVector ((LU)^-1)*v:" << std::endl;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
// Begain transplose
mdfilu.SetUseTranspose(true);
o = v;
mdfilu.apply(o, o);
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "NSVector ((LU)^T)*v:" << std::endl;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
o = v;
mdfilu.apply_inverse(o, o);
fout << "Vector v:" << std::endl;
fout << v << std::endl;
fout << "NSVector (((LU)^-1)^T)*v:" << std::endl;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
fout.close();
}
mdfilu.SetUseTranspose(use_tranpose_init_stats);
//[END]// //--------- Deal.II wrapped Trilinos Vector ---------//
//--------- Finally, Preconditioner test ---------//
{
// No preconditioner first
Epetra_Vector o(system_matrix.trilinos_matrix().DomainMap());
Epetra_Vector b(View,
system_matrix.trilinos_matrix().RangeMap(),
v.begin());
AztecOO solver;
solver.SetAztecOption(AZ_output, AZ_none);
solver.SetAztecOption(AZ_solver, AZ_gmres);
solver.SetLHS(&o);
solver.SetRHS(&b);
solver.SetAztecOption(AZ_precond, AZ_none);
solver.SetUserMatrix(
const_cast<Epetra_CrsMatrix *>(&system_matrix.trilinos_matrix()));
const unsigned int max_iterations = 1000;
const double linear_residual = 1e-8;
solver.Iterate(max_iterations, linear_residual);
std::ofstream fout("apply.out", std::fstream::app);
fout << "GMRES Solved Ax=v without preconditioner:" << std::endl;
fout << "NumIters: " << solver.NumIters() << std::endl;
fout << "TrueResidual: " << solver.TrueResidual() << std::endl;
fout.precision(3);
fout << std::scientific;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
fout.close();
}
{
// No preconditioner first
Epetra_Vector o(system_matrix.trilinos_matrix().DomainMap());
Epetra_Vector b(View,
system_matrix.trilinos_matrix().RangeMap(),
v.begin());
AztecOO solver;
solver.SetAztecOption(AZ_output, AZ_none);
solver.SetAztecOption(AZ_solver, AZ_gmres);
solver.SetLHS(&o);
solver.SetRHS(&b);
solver.SetUserMatrix(
const_cast<Epetra_CrsMatrix *>(&system_matrix.trilinos_matrix()));
mdfilu.SetUseTranspose(false);
solver.SetPrecOperator(&mdfilu);
const unsigned int max_iterations = 1000;
const double linear_residual = 1e-8;
solver.Iterate(max_iterations, linear_residual);
std::ofstream fout("apply.out", std::fstream::app);
fout << "GMRES Solved Ax=v with MDFILU preconditioner:" << std::endl;
fout << "NumIters: " << solver.NumIters() << std::endl;
fout << "TrueResidual: " << solver.TrueResidual() << std::endl;
fout.precision(3);
fout << std::scientific;
for (global_index_type i = 0; i < degree; ++i)
{
fout << o[i] << ' ';
}
fout << std::endl << std::endl;
fout.close();
}
mdfilu.SetUseTranspose(use_tranpose_init_stats);
//[END]// //--------- Finally, Preconditioner test ---------//
// #ifdef VERBOSE_OUTPUT
// debugStream.close();
// #endif
return (system("cat A.out apply.out LU.out matrix.out > output.out"));
}
<|endoftext|> |
<commit_before>#include<iostream>
#include"opencv2/highgui/highgui.hpp"
#include"opencv2/imgproc/imgproc.hpp"
#include"opencv2/core/core.hpp"
#include <fstream>
using namespace cv;
using namespace std;
//Input Mat, and Scalar bounds for thresholding.
Mat src;
Scalar upperBound;
Scalar lowerBound;
//Mode variables. Defaulted at -1 for checking.
int colorMode=-1; //0 for HSV, 1 for RGB.
int inputMode=-1; //0 FOr webcam, 1 for video file.
//File path variables
int videoFilePath;
//capture variables;
bool capture = false;
int captureNum= 0;
ofstream outCenter;
ofstream outMoment;
ofstream outMouse;
int mouseX;
int mouseY;
void onMove(int, void *);
void onClickOriginal(int, int, int, int, void *);
void saveFrame(Mat, Mat, int);
void centerMoment(Mat, int &, int &);
void centerFind(Mat, int &, int &);
int main(int argc, char ** argv){
//Input parsing to select color mode, input mode and anything else needed.
if(argc > 1){
int num=1;
while(num < argc){
string input= argv[num];
//Help text.
if(input == "-help" || input == "-h" || input == "-H"){
cout<<"Available options for v5:"<<endl;
cout<<"-w Use a webcam input"<<endl;
cout<<"-f Use a video file (Follow with a valid file path)"<<endl;
cout<<"-HSV Use HSV images and values to preform thresholding"<<endl;
cout<<"-RGB Use RGB images and values to preofrm thresholding"<<endl;
}
else if(input == "-w" || input == "-W"){
inputMode=0;
}
else if(input == "-v" || input == "-V"){
if((num+1) <argc){
inputMode=1;
videoFilePath=num+1;
num++;
}
else
cout<<"Please follow -v with a path to a video file.";
}
else if(input== "-HSV" || input == "-hsv"){
colorMode=0;
}
else if(input== "-RGB" || input == "-rgb"){
colorMode=1;
}
else{
cout<<"Unrecognized option"<<endl;
}
num++;
}
}
//If there is no input, simply use defaults: webcam input and HSV color mode.
else{
colorMode= 0;
inputMode= 0;
}
if(colorMode ==-1)
colorMode=0;
if(inputMode == -1)
inputMode = 0;
//Input completed, now we move to the real stuff.
//Open the selected input.
VideoCapture cap;
if(inputMode ==0)
cap.open(0);
else if(inputMode ==1)
cap.open(argv[videoFilePath]);
//If some error happens with video input, show an error message.
if(!cap.isOpened()){
cerr<< "Was unable to open video input."<<endl;
if(inputMode ==1)
cerr<<"Filepath inputed ="<<argv[videoFilePath]<<endl<<"Please input a valid filepath."<<endl;
else
cerr<<"Please check your input method."<<endl;
return -1;
}
//Create our three windows for control of the threshold, display of the original image, and the display of the thresholded image.
namedWindow("Control", CV_WINDOW_AUTOSIZE);
namedWindow("Thresholded", CV_WINDOW_AUTOSIZE);
namedWindow("Original", CV_WINDOW_AUTOSIZE);
//Variables for holding the trackbar values. We need 6, whether we're using HSV or RGB, though the max values for the hiA variable are different.
int lowA =0;
int hiA;
if(colorMode == 0)
hiA = 179;
else if(colorMode ==1)
hiA = 255;
int lowB= 0;
int hiB = 255;
int lowC = 0;
int hiC = 255;
//Initial values for the threshold ranges.
lowerBound = Scalar(lowA, lowB, lowC);
upperBound = Scalar(hiA, hiB, hiC);
//Create relevent trackbars based on colorMode.
if(colorMode == 0){
createTrackbar("Low H", "Control", &lowA, 179, onMove, (void*) (0));
createTrackbar("High H", "Control", &hiA, 179, onMove, (void*) (1));
createTrackbar("Low S", "Control", &lowB, 255, onMove, (void*) (2));
createTrackbar("High S", "Control", &hiB, 255, onMove, (void*) (3));
createTrackbar("Low V", "Control", &lowC, 255, onMove, (void*) (4));
createTrackbar("High V", "Control", &hiC, 255, onMove, (void*) (5));
}
else if(colorMode == 1){
createTrackbar("Low R", "Control", &lowA, 255, onMove, (void*) (0));
createTrackbar("High R", "Control", &hiA, 255, onMove, (void*) (1));
createTrackbar("Low G", "Control", &lowB, 255, onMove, (void*) (2));
createTrackbar("High G", "Control", &hiB, 255, onMove, (void*) (3));
createTrackbar("Low B", "Control", &lowC, 255, onMove, (void*) (4));
createTrackbar("High B", "Control", &hiC, 255, onMove, (void*) (5));
}
setMouseCallback("Original", onClickOriginal, NULL);
int frameNum = 0;
int blobX=-1;
int blobY=-1;
//Loop runs until you can't get another frame from the video source, or a user presses escape.
while(true){
bool success = cap.read(src);
if(!success){
cerr<<"Cannot read frame from video stream"<<endl;
break;
}
//Do color conversion based on colorMOde
Mat colorImg;
if(colorMode == 0)
cvtColor(src, colorImg, COLOR_BGR2HSV);
else if(colorMode == 1)
colorImg=src;
Mat thresholdedImg;
inRange(colorImg, lowerBound, upperBound, thresholdedImg);
//morphological opening
erode(thresholdedImg,thresholdedImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
dilate(thresholdedImg, thresholdedImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
//morphological closing
dilate(thresholdedImg, thresholdedImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
erode(thresholdedImg, thresholdedImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
centerMoment(thresholdedImg,blobX, blobY);
//centerFind(thresholdedImg,0, 0);
rectangle(src, Point(blobX +50, blobY+50), Point(blobX-50, blobY-50),Scalar(93, 240, 76), CV_FILLED, 8,0);
//Show images.
imshow("Original", src);
imshow("Thresholded", thresholdedImg);
//Set trackbar variables to reflect any changes that may have happened to the thresholder values.
if(colorMode ==0){
setTrackbarPos("Low H", "Control", lowerBound[0]);
setTrackbarPos("High H", "Control", upperBound[0]);
setTrackbarPos("Low S", "Control", lowerBound[1]);
setTrackbarPos("High S", "Control", upperBound[1]);
setTrackbarPos("Low V", "Control", lowerBound[2]);
setTrackbarPos("High V", "Control", upperBound[2]);
}
else if(colorMode == 1){
setTrackbarPos("Low R", "Control", lowerBound[0]);
setTrackbarPos("High R", "Control", upperBound[0]);
setTrackbarPos("Low G", "Control", lowerBound[1]);
setTrackbarPos("High G", "Control", upperBound[1]);
setTrackbarPos("Low B", "Control", lowerBound[2]);
setTrackbarPos("High B", "Control", upperBound[2]);
}
//If user presses ESC, quit stream.
if(waitKey(5) ==27){
cerr<<"Video Stream Ended"<<endl;
break;
}
//Begin data capture if user presses C.
else if(waitKey(5) == 99){
cout<<"BEGINING DATA CAPTURE. PLEASE MOUSEOVER CENTER LINE"<<endl;
capture = true;
outCenter.open("./data/captures/center.dat");
outMoment.open("./data/captures/moment.dat");
outMouse.open("./data/captures/mouse.dat");
}
//End data capture if user presses E.
else if(waitKey(5) == 101){
cout<<"ENDING DATA CAPTURE. ANALYSIS WILL BE COMPLETE AT PROGRAM END"<<endl;
capture = false;
captureNum = 0;
outCenter.close();
outMoment.close();
outMouse.close();
}
//Set threshold values to defaults if user presses Enter
else if(waitKey(5) == 13){
cout<<"RESETING THRESHOLDS TO DEFAULTS"<<endl;
lowerBound = Scalar(0,0,0);
if(colorMode ==0)
upperBound = Scalar(179, 255, 255);
else if(colorMode ==1)
upperBound = Scalar(255, 255, 255);
}
//Save frames if user presses s.
else if(waitKey(5) ==115){
cout<<"SAVING FRAMES "<<frameNum<<endl;
saveFrame(src, thresholdedImg, frameNum);
frameNum++;
}
if(capture)
outMouse<<captureNum<<" "<<mouseX<<" "<<mouseY<<endl;
captureNum++;
}
return 0;
}
//handler for the control trackbars.
void onMove(int val, void * userdata){
int num = *((int*)&userdata);
//Userdata holds the index that we want tos set, so just set the scalar accordingly.
if(num ==0)
lowerBound = Scalar(val, lowerBound[1], lowerBound[2]);
else if(num ==1)
upperBound = Scalar(val, upperBound[1], upperBound[2]);
else if(num ==2)
lowerBound = Scalar(lowerBound[0], val, lowerBound[2]);
else if(num ==3)
upperBound = Scalar(upperBound[0], val, upperBound[2]);
else if(num ==4)
lowerBound = Scalar(lowerBound[0], lowerBound[1], val);
else if(num ==5)
upperBound = Scalar(upperBound[0], upperBound[1], val);
}
//Handles onclick events for the "original" window.
void onClickOriginal(int event, int x, int y, int flags, void * userdata){
//If the left mouse is clicked,get the average HSV or RGB values from the area and use them for a new set of threshold ranges.
mouseX = x;
mouseY = y;
if(event == EVENT_LBUTTONDOWN){
Mat COLORimg;
if(colorMode == 0)
cvtColor(src, COLORimg, COLOR_BGR2HSV);
else
COLORimg=src;
Mat ROI= COLORimg (Rect ((x-5), (y-5), 10, 10));
Scalar ROImean= mean(ROI);
//For HSV, use ranges H(14), S(60), V(80).
if(colorMode ==0){
lowerBound = Scalar(ROImean[0] - 7, ROImean[1] - 30, ROImean[2] -40);
upperBound = Scalar(ROImean[0] +7, ROImean[1] +30, ROImean[2] +40);
}
//For RGB, use ranges R(20), G(20), B(20). (NEEDS REVISION)
else if(colorMode ==1){
lowerBound = Scalar(ROImean[0] -10, ROImean[1] -10, ROImean[2] -10);
upperBound = Scalar(ROImean[0] +10, ROImean[1] +10, ROImean[2] +10);
}
}
}
/*
Save the orignal and thresholded frames after generating a unique filename.
*/
void saveFrame(Mat imgOriginal, Mat imgThresholded, int frameNum){
String path= "./data/images/";
String ext= ".png";
String number;
ostringstream convert;
convert << frameNum;
number= convert.str();
String original= path+"original";
String threshed= path+"thresholed";
original=original+number;
threshed=threshed+number;
original=original+ext;
threshed=threshed+ext;
vector<int> params;
params.push_back(CV_IMWRITE_PNG_COMPRESSION);
params.push_back(9);
if(!imwrite(original, imgOriginal, params))
cerr<<"Failed to write original"<<endl;
if(!imwrite(threshed, imgThresholded, params))
cerr<<"Failed to write thresholded"<<endl;
}
void centerMoment(Mat img, int & x, int & y){
Moments oMoments=moments(img);
double dM01= oMoments.m01;
double dM10= oMoments.m10;
double area= oMoments.m00;
if(area > 10000){
x =dM10/area;
y= dM01/area;
}
if(capture)
outMoment<<captureNum<<" "<<x<<" "<<y<<endl;
}
void centerFind(Mat img, int & x, int & y){
uchar a, b, c;
int firstX, lastX;
int firstY, lastY;
firstY= -1;
lastY=-1;
for(int i =0; i<img.rows; i++){
Vec3b * pixel = img.ptr<Vec3b>(i);
firstX= -1;
lastX = -1;
for(int j = 0; j<img.cols; j++){
a=pixel[j][0];
b=pixel[j][1];
c=pixel[j][2];
int A= (int) a;
int B = (int) b;
int C= (int) c;
if((a >0 || b>0 || c>0) && capture){
if(firstX == -1)
firstX =j;
else
lastX = j;
if(firstY == -1)
firstY= i;
else
lastY=i;
}
}
}
x = (lastX-firstX)/2 +firstX;
y = (lastY - firstY)/2 +firstY;
}
<commit_msg>transparent rectangle..which crashes if it cant track.<commit_after>#include<iostream>
#include"opencv2/highgui/highgui.hpp"
#include"opencv2/imgproc/imgproc.hpp"
#include"opencv2/core/core.hpp"
#include <fstream>
using namespace cv;
using namespace std;
//Input Mat, and Scalar bounds for thresholding.
Mat src;
Scalar upperBound;
Scalar lowerBound;
//Mode variables. Defaulted at -1 for checking.
int colorMode=-1; //0 for HSV, 1 for RGB.
int inputMode=-1; //0 FOr webcam, 1 for video file.
//File path variables
int videoFilePath;
//capture variables;
bool capture = false;
int captureNum= 0;
ofstream outCenter;
ofstream outMoment;
ofstream outMouse;
int mouseX;
int mouseY;
bool thresholdSet = false;
void onMove(int, void *);
void onClickOriginal(int, int, int, int, void *);
void saveFrame(Mat, Mat, int);
void centerMoment(Mat, int &, int &);
void centerFind(Mat, int &, int &);
int main(int argc, char ** argv){
//Input parsing to select color mode, input mode and anything else needed.
if(argc > 1){
int num=1;
while(num < argc){
string input= argv[num];
//Help text.
if(input == "-help" || input == "-h" || input == "-H"){
cout<<"Available options for v5:"<<endl;
cout<<"-w Use a webcam input"<<endl;
cout<<"-f Use a video file (Follow with a valid file path)"<<endl;
cout<<"-HSV Use HSV images and values to preform thresholding"<<endl;
cout<<"-RGB Use RGB images and values to preofrm thresholding"<<endl;
}
else if(input == "-w" || input == "-W"){
inputMode=0;
}
else if(input == "-v" || input == "-V"){
if((num+1) <argc){
inputMode=1;
videoFilePath=num+1;
num++;
}
else
cout<<"Please follow -v with a path to a video file.";
}
else if(input== "-HSV" || input == "-hsv"){
colorMode=0;
}
else if(input== "-RGB" || input == "-rgb"){
colorMode=1;
}
else{
cout<<"Unrecognized option"<<endl;
}
num++;
}
}
//If there is no input, simply use defaults: webcam input and HSV color mode.
else{
colorMode= 0;
inputMode= 0;
}
if(colorMode ==-1)
colorMode=0;
if(inputMode == -1)
inputMode = 0;
//Input completed, now we move to the real stuff.
//Open the selected input.
VideoCapture cap;
if(inputMode ==0)
cap.open(0);
else if(inputMode ==1)
cap.open(argv[videoFilePath]);
//If some error happens with video input, show an error message.
if(!cap.isOpened()){
cerr<< "Was unable to open video input."<<endl;
if(inputMode ==1)
cerr<<"Filepath inputed ="<<argv[videoFilePath]<<endl<<"Please input a valid filepath."<<endl;
else
cerr<<"Please check your input method."<<endl;
return -1;
}
//Create our three windows for control of the threshold, display of the original image, and the display of the thresholded image.
namedWindow("Control", CV_WINDOW_AUTOSIZE);
namedWindow("Thresholded", CV_WINDOW_AUTOSIZE);
namedWindow("Original", CV_WINDOW_AUTOSIZE);
//Variables for holding the trackbar values. We need 6, whether we're using HSV or RGB, though the max values for the hiA variable are different.
int lowA =0;
int hiA;
if(colorMode == 0)
hiA = 179;
else if(colorMode ==1)
hiA = 255;
int lowB= 0;
int hiB = 255;
int lowC = 0;
int hiC = 255;
//Initial values for the threshold ranges.
lowerBound = Scalar(lowA, lowB, lowC);
upperBound = Scalar(hiA, hiB, hiC);
//Create relevent trackbars based on colorMode.
if(colorMode == 0){
createTrackbar("Low H", "Control", &lowA, 179, onMove, (void*) (0));
createTrackbar("High H", "Control", &hiA, 179, onMove, (void*) (1));
createTrackbar("Low S", "Control", &lowB, 255, onMove, (void*) (2));
createTrackbar("High S", "Control", &hiB, 255, onMove, (void*) (3));
createTrackbar("Low V", "Control", &lowC, 255, onMove, (void*) (4));
createTrackbar("High V", "Control", &hiC, 255, onMove, (void*) (5));
}
else if(colorMode == 1){
createTrackbar("Low R", "Control", &lowA, 255, onMove, (void*) (0));
createTrackbar("High R", "Control", &hiA, 255, onMove, (void*) (1));
createTrackbar("Low G", "Control", &lowB, 255, onMove, (void*) (2));
createTrackbar("High G", "Control", &hiB, 255, onMove, (void*) (3));
createTrackbar("Low B", "Control", &lowC, 255, onMove, (void*) (4));
createTrackbar("High B", "Control", &hiC, 255, onMove, (void*) (5));
}
setMouseCallback("Original", onClickOriginal, NULL);
int frameNum = 0;
int blobX=-1;
int blobY=-1;
//Loop runs until you can't get another frame from the video source, or a user presses escape.
while(true){
bool success = cap.read(src);
if(!success){
cerr<<"Cannot read frame from video stream"<<endl;
break;
}
//Do color conversion based on colorMOde
Mat colorImg;
if(colorMode == 0)
cvtColor(src, colorImg, COLOR_BGR2HSV);
else if(colorMode == 1)
colorImg=src;
Mat thresholdedImg;
inRange(colorImg, lowerBound, upperBound, thresholdedImg);
//morphological opening
erode(thresholdedImg,thresholdedImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
dilate(thresholdedImg, thresholdedImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
//morphological closing
dilate(thresholdedImg, thresholdedImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
erode(thresholdedImg, thresholdedImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
centerMoment(thresholdedImg,blobX, blobY);
//centerFind(thresholdedImg,0, 0);
if(thresholdSet ){
Mat roi = src(Rect(Point(blobX -50, blobY-50), Point(blobX+50, blobY+50)));
Mat color(roi.size(), CV_8UC3, Scalar(0, 255, 43));
double alpha = 0.3;
addWeighted(color, alpha, roi, 1.0 - alpha , 0.0, roi);
}
//Show images.
imshow("Original", src);
imshow("Thresholded", thresholdedImg);
//Set trackbar variables to reflect any changes that may have happened to the thresholder values.
if(colorMode ==0){
setTrackbarPos("Low H", "Control", lowerBound[0]);
setTrackbarPos("High H", "Control", upperBound[0]);
setTrackbarPos("Low S", "Control", lowerBound[1]);
setTrackbarPos("High S", "Control", upperBound[1]);
setTrackbarPos("Low V", "Control", lowerBound[2]);
setTrackbarPos("High V", "Control", upperBound[2]);
}
else if(colorMode == 1){
setTrackbarPos("Low R", "Control", lowerBound[0]);
setTrackbarPos("High R", "Control", upperBound[0]);
setTrackbarPos("Low G", "Control", lowerBound[1]);
setTrackbarPos("High G", "Control", upperBound[1]);
setTrackbarPos("Low B", "Control", lowerBound[2]);
setTrackbarPos("High B", "Control", upperBound[2]);
}
//If user presses ESC, quit stream.
if(waitKey(5) ==27){
cerr<<"Video Stream Ended"<<endl;
break;
}
//Begin data capture if user presses C.
else if(waitKey(5) == 99){
cout<<"BEGINING DATA CAPTURE. PLEASE MOUSEOVER CENTER LINE"<<endl;
capture = true;
outCenter.open("./data/captures/center.dat");
outMoment.open("./data/captures/moment.dat");
outMouse.open("./data/captures/mouse.dat");
}
//End data capture if user presses E.
else if(waitKey(5) == 101){
cout<<"ENDING DATA CAPTURE. ANALYSIS WILL BE COMPLETE AT PROGRAM END"<<endl;
capture = false;
captureNum = 0;
outCenter.close();
outMoment.close();
outMouse.close();
}
//Set threshold values to defaults if user presses Enter
else if(waitKey(5) == 13){
cout<<"RESETING THRESHOLDS TO DEFAULTS"<<endl;
lowerBound = Scalar(0,0,0);
if(colorMode ==0)
upperBound = Scalar(179, 255, 255);
else if(colorMode ==1)
upperBound = Scalar(255, 255, 255);
thresholdSet =false;
}
//Save frames if user presses s.
else if(waitKey(5) ==115){
cout<<"SAVING FRAMES "<<frameNum<<endl;
saveFrame(src, thresholdedImg, frameNum);
frameNum++;
}
if(capture)
outMouse<<captureNum<<" "<<mouseX<<" "<<mouseY<<endl;
captureNum++;
}
return 0;
}
//handler for the control trackbars.
void onMove(int val, void * userdata){
int num = *((int*)&userdata);
//Userdata holds the index that we want tos set, so just set the scalar accordingly.
if(num ==0)
lowerBound = Scalar(val, lowerBound[1], lowerBound[2]);
else if(num ==1)
upperBound = Scalar(val, upperBound[1], upperBound[2]);
else if(num ==2)
lowerBound = Scalar(lowerBound[0], val, lowerBound[2]);
else if(num ==3)
upperBound = Scalar(upperBound[0], val, upperBound[2]);
else if(num ==4)
lowerBound = Scalar(lowerBound[0], lowerBound[1], val);
else if(num ==5)
upperBound = Scalar(upperBound[0], upperBound[1], val);
}
//Handles onclick events for the "original" window.
void onClickOriginal(int event, int x, int y, int flags, void * userdata){
//If the left mouse is clicked,get the average HSV or RGB values from the area and use them for a new set of threshold ranges.
mouseX = x;
mouseY = y;
if(event == EVENT_LBUTTONDOWN){
Mat COLORimg;
if(colorMode == 0)
cvtColor(src, COLORimg, COLOR_BGR2HSV);
else
COLORimg=src;
Mat ROI= COLORimg (Rect ((x-5), (y-5), 10, 10));
Scalar ROImean= mean(ROI);
//For HSV, use ranges H(14), S(60), V(80).
if(colorMode ==0){
lowerBound = Scalar(ROImean[0] - 7, ROImean[1] - 30, ROImean[2] -40);
upperBound = Scalar(ROImean[0] +7, ROImean[1] +30, ROImean[2] +40);
}
//For RGB, use ranges R(20), G(20), B(20). (NEEDS REVISION)
else if(colorMode ==1){
lowerBound = Scalar(ROImean[0] -10, ROImean[1] -10, ROImean[2] -10);
upperBound = Scalar(ROImean[0] +10, ROImean[1] +10, ROImean[2] +10);
}
thresholdSet=true;
}
}
/*
Save the orignal and thresholded frames after generating a unique filename.
*/
void saveFrame(Mat imgOriginal, Mat imgThresholded, int frameNum){
String path= "./data/images/";
String ext= ".png";
String number;
ostringstream convert;
convert << frameNum;
number= convert.str();
String original= path+"original";
String threshed= path+"thresholed";
original=original+number;
threshed=threshed+number;
original=original+ext;
threshed=threshed+ext;
vector<int> params;
params.push_back(CV_IMWRITE_PNG_COMPRESSION);
params.push_back(9);
if(!imwrite(original, imgOriginal, params))
cerr<<"Failed to write original"<<endl;
if(!imwrite(threshed, imgThresholded, params))
cerr<<"Failed to write thresholded"<<endl;
}
void centerMoment(Mat img, int & x, int & y){
Moments oMoments=moments(img);
double dM01= oMoments.m01;
double dM10= oMoments.m10;
double area= oMoments.m00;
if(area > 10000){
x =dM10/area;
y= dM01/area;
}
if(capture)
outMoment<<captureNum<<" "<<x<<" "<<y<<endl;
}
void centerFind(Mat img, int & x, int & y){
uchar a, b, c;
int firstX, lastX;
int firstY, lastY;
firstY= -1;
lastY=-1;
for(int i =0; i<img.rows; i++){
Vec3b * pixel = img.ptr<Vec3b>(i);
firstX= -1;
lastX = -1;
for(int j = 0; j<img.cols; j++){
a=pixel[j][0];
b=pixel[j][1];
c=pixel[j][2];
int A= (int) a;
int B = (int) b;
int C= (int) c;
if((a >0 || b>0 || c>0) && capture){
if(firstX == -1)
firstX =j;
else
lastX = j;
if(firstY == -1)
firstY= i;
else
lastY=i;
}
}
}
x = (lastX-firstX)/2 +firstX;
y = (lastY - firstY)/2 +firstY;
}
<|endoftext|> |
<commit_before>#ifndef ALGO_HPP
#define ALGO_HPP
#include "ptree.hpp"
#include "equivalence.hpp"
#include "ztree.hpp"
#include "khash.hh"
namespace tree {
////////////////////////////////////////////////////////////////////////////////
// Central algorithm and stuff
////////////////////////////////////////////////////////////////////////////////
// porta il sottolbero radicato in x in una catena sinistra o destra a seconda di type
// (algoritmi LEFT e RIGHT). Restituisce -1 in caso di errore, oppure 0 se l'albero e' nullo
template<class T>
T list ( ptree<T>& a, T i, equivalence_info<T>& eqinfo, rotation_type type = LEFT ) {
if ( i == EMPTY ) return 0;
a.get_structure( eqinfo );
T total = 0;
while ( i != EMPTY ) {
T next = i;
T j = i;
while ( ( type == RIGHT && ( a[j].left() && eqinfo[a[j].left()] == EMPTY ) ) ||
( type == LEFT && ( a[j].right() && eqinfo[a[j].right()] == EMPTY ) ) ) {
next = ( type == LEFT ) ? a[j].right() : a[j].left();
a.rotate( j, type );
++total;
j = next;
}
// l'ultimo nodo che ho ruotato (oppure i invariato) e' quello da cui devo scendere
i = ( type == LEFT ) ? a.base()[next].left() : a.base()[next].right();
}
return total;
}
// processing basato sull'algoritmo CENTRAL
template<class T>
T central ( ptree<T>& a, ptree<T>& b ) {
assert( a.size() == b.size() );
equivalence_info<T> eqinfo( a.size() );
T total = 0;
// cerco il nodo con c(x) massimo
T cmax = 0, rx = 2 * a.size() + 1;
T selected = a.best_c( b, eqinfo, cmax, rx, greater<T>() );
if ( cmax == 0 )
return total;
// porto il nodo selezionato alla radice in entrambi gli alberi
total += a.to_root( selected );
total += b.to_root( selected );
// applico gli algoritmi left e right ai sottoalberi
total += list( a, a.base()[selected].right(), eqinfo, LEFT );
total += list( b, b.base()[selected].right(), eqinfo.inverse(), LEFT );
total += list( a, a.base()[selected].left(), eqinfo, RIGHT );
total += list( b, b.base()[selected].left(), eqinfo.inverse(), RIGHT );
return total;
}
template<class T>
T centralfirststep ( ptree<T>& a, ptree<T>& b, equivalence_info<T>& eqinfo ) {
//cout << "centralfirststep()" << endl;
assert( a.size() == b.size() );
T total = 0;
// cerco il nodo con c(x) massimo
T cmax = 0, rx = 2 * a.size() + 1;
T selected = a.best_c( b, eqinfo, cmax, rx, greater<T>() );
if ( cmax == 0 || selected == EMPTY )
return total;
//cout << "selected node " << selected << " with cmax = " << cmax << endl;
// porto il nodo selezionato alla radice in entrambi gli alberi
total += a.to_root( selected );
total += b.to_root( selected );
return total;
}
template<class T>
T movebestr ( ptree<T>& a, ptree<T>& b, equivalence_info<T>& eqinfo ) {
assert( a.size() == b.size() );
T total = 0;
// cerco il nodo con r(x) minimo
T rx = 2 * a.size() + 1;
T selected = a.best_r( b, eqinfo, rx, less<T>() );
if ( rx == 0 || selected == EMPTY )
return total;
//cout << "selected node " << selected << " with rx = " << rx << endl;
// porto il nodo selezionato alla radice in entrambi gli alberi
total += a.to_root( selected );
total += b.to_root( selected );
return total;
}
////////////////////////////////////////////////////////////////////////////////
// New algorithm and stuff
////////////////////////////////////////////////////////////////////////////////
template<class T>
bool has_equivalent ( ptree<T>& a, ptree<T>& b ) {
assert( a.size() == b.size() );
equivalence_info<T> eqinfo( a.size() );
return a.equal_subtrees( b, eqinfo ) != 0;
}
template<class T>
T newalgo_r ( ptree<T>& a, ptree<T>& b, equivalence_info<T>& eqinfo ) {
assert( a.size() == b.size() );
//printf( "a.root() = %d, b.root() = %d, size = %d\n", a.root(), b.root(), a.size() );
if ( a.size() == 0 || a.size() == 1 )
return 0;
T total = 0;
a.equal_subtrees( b, eqinfo ); // aggiorno gli intervalli
total += k_equivalent(a, b, 1, eqinfo); // stacco nodi k-equivalenti
a.equal_subtrees( b, eqinfo ); // riaggiorno
total += centralfirststep( a, b, eqinfo ); // porto un nodo a radice
a.equal_subtrees( b, eqinfo ); // riaggiorno (in particolare i figli)
ptree<T> al = a.left();
ptree<T> bl = b.left();
ptree<T> ar = a.right();
ptree<T> br = b.right();
return total + newalgo_r( al, bl, eqinfo ) + newalgo_r( ar, br, eqinfo );
}
template<class T>
T newalgo ( ptree<T>& a, ptree<T>& b ) {
//cout << "newalgo()\n";
equivalence_info<T> eqinfo( a.size() );
return newalgo_r( a, b, eqinfo );
}
template<class T>
T mix_r ( ptree<T>& a, ptree<T>& b, equivalence_info<T>& eqinfo ) {
assert( a.size() == b.size() );
if ( a.size() == 0 || a.size() == 1 )
return 0;
T total = 0;
a.equal_subtrees( b, eqinfo ); // aggiorno gli intervalli
//print<T>(a,b);
//cout << eqinfo << endl;
total += k_equivalent(a, b, 1, eqinfo); // stacco nodi k-equivalenti
a.equal_subtrees( b, eqinfo ); // riaggiorno
total += movebestr( a, b, eqinfo ); // porto un nodo a radice
a.equal_subtrees( b, eqinfo ); // riaggiorno (in particolare i figli)
ptree<T> al = a.left();
ptree<T> bl = b.left();
ptree<T> ar = a.right();
ptree<T> br = b.right();
return total + mix_r( al, bl, eqinfo ) + mix_r( ar, br, eqinfo );
}
template<class T>
T mix ( ptree<T>& a, ptree<T>& b ) {
//cout << "mix()\n";
equivalence_info<T> eqinfo( a.size() );
return mix_r( a, b, eqinfo );
}
template<class T>
bool k_equivalent_r ( ptree<T>& a, ptree<T>& b, T k, equivalence_info<T>& eqinfo, T before ) {
if ( k == 0 ) {
T after = a.equal_subtrees( b, eqinfo );
T threshold = 1;
if ( after - before >= threshold )
return true; // keep
else
return false;
}
for ( T i = a.minimum(); i <= a.maximum(); ++i ) {
if ( i == a.root() ) continue;
/*if( a.equal_subtrees( b, eqinfo ) != before ) {
print<T>(a,b,eqinfo);
printf( "now is %d, was %d\n", a.equal_subtrees( b, eqinfo ), before );
cout << eqinfo << endl;
exit(1);
}*/
if ( eqinfo[i] != EMPTY ) continue;
T father = a[i].father();
a.up( i );
bool keep = k_equivalent_r( a, b, k-1, eqinfo, before );
if ( keep ) {
//cout << "kept rotation up of " << i << endl;
//print<T>(a,b,eqinfo);
return true; // keep
}
a.rotate( father, i );
//printf( "restored rotation up of %d [%d, %d, %d]\n", i, a.minimum(), a.root(), a.maximum() );
}
return false;
}
template<class T>
T k_equivalent ( ptree<T>& a, ptree<T>& b, T k, equivalence_info<T>& eqinfo ) {
//cout << "k_equivalent()" << endl;
T total = 0;
for ( T t = 1; t <= k; ) {
T before = a.equal_subtrees( b, eqinfo );
/*cout << eqinfo << endl;
a.debug();
b.debug();
print<T>(a,b,eqinfo);*/
bool something = k_equivalent_r( a, b, t, eqinfo, before );
if ( !something )
assert ( a.equal_subtrees(b, eqinfo) == before );
if ( !something )
something = k_equivalent_r( b, a, t, eqinfo.inverse(), before );
if ( !something ) // increase t
++t;
else {
total += t; // t remain the same (try to search again)
}
}
return total;
}
template<class T>
class unordered_set : public khset_t<T> {};
size_t distance ( const ztree<N>& a, const ztree<N>& b, size_t& visited ) {
visited = 0;
if ( a == b ) return 0;
unordered_set<unsigned long> queued;
deque<ztree<N> > q;
q.push_back( a );
queued.insert( (int) a.to_ulong() );
// During BFS I scan sequentially all nodes at distance d, exploring the next level d+1.
// I set two extremes for two sets:
// [0,left) contains the nodes at distance d, d-1, d-2.. 0 from the source node a
// [left,right) contains the nodes at distance d+1 from a
// When [0,left) = [0,0) means that I have exhausted all the nodes at distance d, d-1..
// that means I generated all the nodes on the next level, so I can increase the distance
// from the source.
int left = 1; // Initially I have node a at distance 0 from a, so [0,left) must contain only node 0
int right = 1; // The right limit is the left limit: I have no known node at distance 1
size_t d = 0; // distance from a in the current level
bool found = false;
while( q.size() != 0 ) {
size_t occupied = q.size() * sizeof( ztree<N> ) + queued.size() * sizeof( unsigned long );
if ( occupied > visited ) visited = occupied;
// select first node in the deque and generates its outcoming star
for ( unsigned int i = 1; i <= N; ++i ) {
ztree<N> newone = q.front();
newone ^ i;
// if I already queued (or visited) this node I simply skip it
if ( queued.find( newone.to_ulong() ) != queued.end() )
continue;
// if I found it, exit from the loops
if ( newone == b ) {
found = true;
break;
}
// otherwise put the new node in the deque and to the hashtable
q.push_back( newone );
queued.insert( newone.to_ulong() );
right++;
}
if ( found ) break;
// effectively pop the first element, after visiting him
q.pop_front();
--right;
// start processing elements at the next level?
if ( --left == 0 ) {
left = right;
++d;
}
}
if (!found) {
cerr << "Fatal error.\n";
//cout << queued.count( a.to_ulong() ) << " " << queued.count( b.to_ulong() ) << endl;
exit( 1 );
}
//visited = queued.size();
return d + 1;
}
} // namespace tree
#endif // ALGO_HPP
<commit_msg>removed debug lines<commit_after>#ifndef ALGO_HPP
#define ALGO_HPP
#include "ptree.hpp"
#include "equivalence.hpp"
#include "ztree.hpp"
#include "khash.hh"
namespace tree {
////////////////////////////////////////////////////////////////////////////////
// Central algorithm and stuff
////////////////////////////////////////////////////////////////////////////////
// porta il sottolbero radicato in x in una catena sinistra o destra a seconda di type
// (algoritmi LEFT e RIGHT). Restituisce -1 in caso di errore, oppure 0 se l'albero e' nullo
template<class T>
T list ( ptree<T>& a, T i, equivalence_info<T>& eqinfo, rotation_type type = LEFT ) {
if ( i == EMPTY ) return 0;
a.get_structure( eqinfo );
T total = 0;
while ( i != EMPTY ) {
T next = i;
T j = i;
while ( ( type == RIGHT && ( a[j].left() && eqinfo[a[j].left()] == EMPTY ) ) ||
( type == LEFT && ( a[j].right() && eqinfo[a[j].right()] == EMPTY ) ) ) {
next = ( type == LEFT ) ? a[j].right() : a[j].left();
a.rotate( j, type );
++total;
j = next;
}
// l'ultimo nodo che ho ruotato (oppure i invariato) e' quello da cui devo scendere
i = ( type == LEFT ) ? a.base()[next].left() : a.base()[next].right();
}
return total;
}
// processing basato sull'algoritmo CENTRAL
template<class T>
T central ( ptree<T>& a, ptree<T>& b ) {
assert( a.size() == b.size() );
equivalence_info<T> eqinfo( a.size() );
T total = 0;
// cerco il nodo con c(x) massimo
T cmax = 0, rx = 2 * a.size() + 1;
T selected = a.best_c( b, eqinfo, cmax, rx, greater<T>() );
if ( cmax == 0 )
return total;
// porto il nodo selezionato alla radice in entrambi gli alberi
total += a.to_root( selected );
total += b.to_root( selected );
// applico gli algoritmi left e right ai sottoalberi
total += list( a, a.base()[selected].right(), eqinfo, LEFT );
total += list( b, b.base()[selected].right(), eqinfo.inverse(), LEFT );
total += list( a, a.base()[selected].left(), eqinfo, RIGHT );
total += list( b, b.base()[selected].left(), eqinfo.inverse(), RIGHT );
return total;
}
template<class T>
T centralfirststep ( ptree<T>& a, ptree<T>& b, equivalence_info<T>& eqinfo ) {
//cout << "centralfirststep()" << endl;
assert( a.size() == b.size() );
T total = 0;
// cerco il nodo con c(x) massimo
T cmax = 0, rx = 2 * a.size() + 1;
T selected = a.best_c( b, eqinfo, cmax, rx, greater<T>() );
if ( cmax == 0 || selected == EMPTY )
return total;
//cout << "selected node " << selected << " with cmax = " << cmax << endl;
// porto il nodo selezionato alla radice in entrambi gli alberi
total += a.to_root( selected );
total += b.to_root( selected );
return total;
}
template<class T>
T movebestr ( ptree<T>& a, ptree<T>& b, equivalence_info<T>& eqinfo ) {
assert( a.size() == b.size() );
T total = 0;
// cerco il nodo con r(x) minimo
T rx = 2 * a.size() + 1;
T selected = a.best_r( b, eqinfo, rx, less<T>() );
if ( rx == 0 || selected == EMPTY )
return total;
//cout << "selected node " << selected << " with rx = " << rx << endl;
// porto il nodo selezionato alla radice in entrambi gli alberi
total += a.to_root( selected );
total += b.to_root( selected );
return total;
}
////////////////////////////////////////////////////////////////////////////////
// New algorithm and stuff
////////////////////////////////////////////////////////////////////////////////
template<class T>
bool has_equivalent ( ptree<T>& a, ptree<T>& b ) {
assert( a.size() == b.size() );
equivalence_info<T> eqinfo( a.size() );
return a.equal_subtrees( b, eqinfo ) != 0;
}
template<class T>
T newalgo_r ( ptree<T>& a, ptree<T>& b, equivalence_info<T>& eqinfo ) {
assert( a.size() == b.size() );
if ( a.size() == 0 || a.size() == 1 )
return 0;
T total = 0;
a.equal_subtrees( b, eqinfo ); // aggiorno gli intervalli
total += k_equivalent(a, b, 1, eqinfo); // stacco nodi k-equivalenti
a.equal_subtrees( b, eqinfo ); // riaggiorno
total += centralfirststep( a, b, eqinfo ); // porto un nodo a radice
a.equal_subtrees( b, eqinfo ); // riaggiorno (in particolare i figli)
ptree<T> al = a.left();
ptree<T> bl = b.left();
ptree<T> ar = a.right();
ptree<T> br = b.right();
return total + newalgo_r( al, bl, eqinfo ) + newalgo_r( ar, br, eqinfo );
}
template<class T>
T newalgo ( ptree<T>& a, ptree<T>& b ) {
//cout << "newalgo()\n";
equivalence_info<T> eqinfo( a.size() );
return newalgo_r( a, b, eqinfo );
}
template<class T>
T mix_r ( ptree<T>& a, ptree<T>& b, equivalence_info<T>& eqinfo ) {
assert( a.size() == b.size() );
if ( a.size() == 0 || a.size() == 1 )
return 0;
T total = 0;
a.equal_subtrees( b, eqinfo ); // aggiorno gli intervalli
total += k_equivalent(a, b, 1, eqinfo); // stacco nodi k-equivalenti
a.equal_subtrees( b, eqinfo ); // riaggiorno
total += movebestr( a, b, eqinfo ); // porto un nodo a radice
a.equal_subtrees( b, eqinfo ); // riaggiorno (in particolare i figli)
ptree<T> al = a.left();
ptree<T> bl = b.left();
ptree<T> ar = a.right();
ptree<T> br = b.right();
return total + mix_r( al, bl, eqinfo ) + mix_r( ar, br, eqinfo );
}
template<class T>
T mix ( ptree<T>& a, ptree<T>& b ) {
equivalence_info<T> eqinfo( a.size() );
return mix_r( a, b, eqinfo );
}
template<class T>
bool k_equivalent_r ( ptree<T>& a, ptree<T>& b, T k, equivalence_info<T>& eqinfo, T before ) {
if ( k == 0 ) {
T after = a.equal_subtrees( b, eqinfo );
T threshold = 1;
if ( after - before >= threshold )
return true; // keep
else
return false;
}
for ( T i = a.minimum(); i <= a.maximum(); ++i ) {
if ( i == a.root() ) continue;
if ( eqinfo[i] != EMPTY ) continue;
T father = a[i].father();
a.up( i );
bool keep = k_equivalent_r( a, b, k-1, eqinfo, before );
if ( keep )
return true; // keep
a.rotate( father, i );
}
return false;
}
template<class T>
T k_equivalent ( ptree<T>& a, ptree<T>& b, T k, equivalence_info<T>& eqinfo ) {
T total = 0;
for ( T t = 1; t <= k; ) {
T before = a.equal_subtrees( b, eqinfo );
bool something = k_equivalent_r( a, b, t, eqinfo, before );
if ( !something )
assert ( a.equal_subtrees(b, eqinfo) == before );
if ( !something )
something = k_equivalent_r( b, a, t, eqinfo.inverse(), before );
if ( !something ) // increase t
++t;
else {
total += t; // t remain the same (try to search again)
}
}
return total;
}
template<class T>
class unordered_set : public khset_t<T> {};
size_t distance ( const ztree<N>& a, const ztree<N>& b, size_t& visited ) {
visited = 0;
if ( a == b ) return 0;
unordered_set<unsigned long> queued;
deque<ztree<N> > q;
q.push_back( a );
queued.insert( (int) a.to_ulong() );
// During BFS I scan sequentially all nodes at distance d, exploring the next level d+1.
// I set two extremes for two sets:
// [0,left) contains the nodes at distance d, d-1, d-2.. 0 from the source node a
// [left,right) contains the nodes at distance d+1 from a
// When [0,left) = [0,0) means that I have exhausted all the nodes at distance d, d-1..
// that means I generated all the nodes on the next level, so I can increase the distance
// from the source.
int left = 1; // Initially I have node a at distance 0 from a, so [0,left) must contain only node 0
int right = 1; // The right limit is the left limit: I have no known node at distance 1
size_t d = 0; // distance from a in the current level
bool found = false;
while( q.size() != 0 ) {
size_t occupied = q.size() * sizeof( ztree<N> ) + queued.size() * sizeof( unsigned long );
if ( occupied > visited ) visited = occupied;
// select first node in the deque and generates its outcoming star
for ( unsigned int i = 1; i <= N; ++i ) {
ztree<N> newone = q.front();
newone ^ i;
// if I already queued (or visited) this node I simply skip it
if ( queued.find( newone.to_ulong() ) != queued.end() )
continue;
// if I found it, exit from the loops
if ( newone == b ) {
found = true;
break;
}
// otherwise put the new node in the deque and to the hashtable
q.push_back( newone );
queued.insert( newone.to_ulong() );
right++;
}
if ( found ) break;
// effectively pop the first element, after visiting him
q.pop_front();
--right;
// start processing elements at the next level?
if ( --left == 0 ) {
left = right;
++d;
}
}
if (!found) {
cerr << "Fatal error.\n";
//cout << queued.count( a.to_ulong() ) << " " << queued.count( b.to_ulong() ) << endl;
exit( 1 );
}
//visited = queued.size();
return d + 1;
}
} // namespace tree
#endif // ALGO_HPP
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "kudu/clock/hybrid_clock.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
#include <gflags/gflags.h>
#include <gflags/gflags_declare.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "kudu/clock/mock_ntp.h"
#include "kudu/clock/time_service.h"
#include "kudu/common/timestamp.h"
#include "kudu/gutil/casts.h"
#include "kudu/gutil/ref_counted.h"
#include "kudu/gutil/strings/join.h"
#include "kudu/util/atomic.h"
#include "kudu/util/monotime.h"
#include "kudu/util/random.h"
#include "kudu/util/random_util.h"
#include "kudu/util/scoped_cleanup.h"
#include "kudu/util/status.h"
#include "kudu/util/test_macros.h"
#include "kudu/util/test_util.h"
#include "kudu/util/thread.h"
DECLARE_bool(inject_unsync_time_errors);
DECLARE_string(time_source);
using std::string;
using std::vector;
namespace kudu {
namespace clock {
class HybridClockTest : public KuduTest {
public:
HybridClockTest()
: clock_(new HybridClock) {
}
void SetUp() override {
KuduTest::SetUp();
ASSERT_OK(clock_->Init());
}
protected:
scoped_refptr<HybridClock> clock_;
};
clock::MockNtp* mock_ntp(HybridClock* clock) {
return down_cast<clock::MockNtp*>(clock->time_service());
}
TEST(MockHybridClockTest, TestMockedSystemClock) {
google::FlagSaver saver;
FLAGS_time_source = "mock";
scoped_refptr<HybridClock> clock(new HybridClock);
ASSERT_OK(clock->Init());
Timestamp timestamp;
uint64_t max_error_usec;
clock->NowWithError(×tamp, &max_error_usec);
ASSERT_EQ(timestamp.ToUint64(), 0);
ASSERT_EQ(max_error_usec, 0);
// If we read the clock again we should see the logical component be incremented.
clock->NowWithError(×tamp, &max_error_usec);
ASSERT_EQ(timestamp.ToUint64(), 1);
// Now set an arbitrary time and check that is the time returned by the clock.
uint64_t time = 1234 * 1000;
uint64_t error = 100 * 1000;
mock_ntp(clock.get())->SetMockClockWallTimeForTests(time);
mock_ntp(clock.get())->SetMockMaxClockErrorForTests(error);
clock->NowWithError(×tamp, &max_error_usec);
ASSERT_EQ(timestamp.ToUint64(),
HybridClock::TimestampFromMicrosecondsAndLogicalValue(time, 0).ToUint64());
ASSERT_EQ(max_error_usec, error);
// Perform another read, we should observe the logical component increment, again.
clock->NowWithError(×tamp, &max_error_usec);
ASSERT_EQ(timestamp.ToUint64(),
HybridClock::TimestampFromMicrosecondsAndLogicalValue(time, 1).ToUint64());
}
// Test that, if the rate at which the clock is read is greater than the maximum
// resolution of the logical counter (12 bits in our implementation), it properly
// "overflows" into the physical portion of the clock, and maintains all ordering
// guarantees even as the physical clock continues to increase.
//
// This is a regression test for KUDU-1345.
TEST(MockHybridClockTest, TestClockDealsWithWrapping) {
google::FlagSaver saver;
FLAGS_time_source = "mock";
scoped_refptr<HybridClock> clock(new HybridClock);
ASSERT_OK(clock->Init());
mock_ntp(clock.get())->SetMockClockWallTimeForTests(1000);
Timestamp prev = clock->Now();
// Update the clock from 10us in the future
ASSERT_OK(clock->Update(HybridClock::TimestampFromMicroseconds(1010)));
// Now read the clock value enough times so that the logical value wraps
// over, and should increment the _physical_ portion of the clock.
for (int i = 0; i < 10000; i++) {
Timestamp now = clock->Now();
ASSERT_GT(now.value(), prev.value());
prev = now;
}
ASSERT_EQ(1012, HybridClock::GetPhysicalValueMicros(prev));
// Advance the time microsecond by microsecond, and ensure the clock never
// goes backwards.
for (int time = 1001; time < 1020; time++) {
mock_ntp(clock.get())->SetMockClockWallTimeForTests(time);
Timestamp now = clock->Now();
// Clock should run strictly forwards.
ASSERT_GT(now.value(), prev.value());
// Additionally, once the physical time surpasses the logical time, we should
// be running on the physical clock. Otherwise, we should stick with the physical
// time we had rolled forward to above.
if (time > 1012) {
ASSERT_EQ(time, HybridClock::GetPhysicalValueMicros(now));
} else {
ASSERT_EQ(1012, HybridClock::GetPhysicalValueMicros(now));
}
prev = now;
}
}
// Test that two subsequent time reads are monotonically increasing.
TEST_F(HybridClockTest, TestNow_ValuesIncreaseMonotonically) {
const Timestamp now1 = clock_->Now();
const Timestamp now2 = clock_->Now();
ASSERT_LT(now1.value(), now2.value());
}
// Tests the clock updates with the incoming value if it is higher.
TEST_F(HybridClockTest, TestUpdate_LogicalValueIncreasesByAmount) {
Timestamp now = clock_->Now();
uint64_t now_micros = HybridClock::GetPhysicalValueMicros(now);
// increase the logical value
uint64_t logical = HybridClock::GetLogicalValue(now);
logical += 10;
// increase the physical value so that we're sure the clock will take this
// one, 200 msecs should be more than enough.
now_micros += 200000;
Timestamp now_increased = HybridClock::TimestampFromMicrosecondsAndLogicalValue(now_micros,
logical);
ASSERT_OK(clock_->Update(now_increased));
Timestamp now2 = clock_->Now();
ASSERT_EQ(logical + 1, HybridClock::GetLogicalValue(now2));
ASSERT_EQ(HybridClock::GetPhysicalValueMicros(now) + 200000,
HybridClock::GetPhysicalValueMicros(now2));
}
// Test that the incoming event is in the past, i.e. less than now - max_error
TEST_F(HybridClockTest, TestWaitUntilAfter_TestCase1) {
MonoTime no_deadline;
MonoTime before = MonoTime::Now();
Timestamp past_ts;
uint64_t max_error;
clock_->NowWithError(&past_ts, &max_error);
// make the event 3 * the max. possible error in the past
Timestamp past_ts_changed = HybridClock::AddPhysicalTimeToTimestamp(
past_ts,
MonoDelta::FromMicroseconds(-3 * static_cast<int64_t>(max_error)));
ASSERT_OK(clock_->WaitUntilAfter(past_ts_changed, no_deadline));
MonoTime after = MonoTime::Now();
MonoDelta delta = after - before;
// The delta should be close to 0, but it takes some time for the hybrid
// logical clock to decide that it doesn't need to wait.
ASSERT_LT(delta.ToMicroseconds(), 25000);
}
// The normal case for transactions. Obtain a timestamp and then wait until
// we're sure that tx_latest < now_earliest.
TEST_F(HybridClockTest, TestWaitUntilAfter_TestCase2) {
MonoTime before = MonoTime::Now();
// we do no time adjustment, this event should fall right within the possible
// error interval
Timestamp past_ts;
uint64_t past_max_error;
clock_->NowWithError(&past_ts, &past_max_error);
// Make sure the error is at least a small number of microseconds, to ensure
// that we always have to wait.
past_max_error = std::max(past_max_error, static_cast<uint64_t>(20));
Timestamp wait_until = HybridClock::AddPhysicalTimeToTimestamp(
past_ts,
MonoDelta::FromMicroseconds(past_max_error));
Timestamp current_ts;
uint64_t current_max_error;
clock_->NowWithError(¤t_ts, ¤t_max_error);
// Check waiting with a deadline which already expired.
{
MonoTime deadline = before;
Status s = clock_->WaitUntilAfter(wait_until, deadline);
ASSERT_TRUE(s.IsTimedOut()) << s.ToString();
}
// Wait with a deadline well in the future. This should succeed.
{
MonoTime deadline = before + MonoDelta::FromSeconds(60);
ASSERT_OK(clock_->WaitUntilAfter(wait_until, deadline));
}
MonoTime after = MonoTime::Now();
MonoDelta delta = after - before;
// In the common case current_max_error >= past_max_error and we should have waited
// 2 * past_max_error, but if the clock's error is reset between the two reads we might
// have waited less time, but always more than 'past_max_error'.
if (current_max_error >= past_max_error) {
ASSERT_GE(delta.ToMicroseconds(), 2 * past_max_error);
} else {
ASSERT_GE(delta.ToMicroseconds(), past_max_error);
}
}
TEST_F(HybridClockTest, TestIsAfter) {
Timestamp ts1 = clock_->Now();
ASSERT_TRUE(clock_->IsAfter(ts1));
// Update the clock in the future, make sure it still
// handles "IsAfter" properly even when it's running in
// "logical" mode.
Timestamp now_increased = HybridClock::TimestampFromMicroseconds(
HybridClock::GetPhysicalValueMicros(ts1) + 1 * 1000 * 1000);
ASSERT_OK(clock_->Update(now_increased));
Timestamp ts2 = clock_->Now();
ASSERT_TRUE(clock_->IsAfter(ts1));
ASSERT_TRUE(clock_->IsAfter(ts2));
}
// Thread which loops polling the clock and updating it slightly
// into the future.
void StresserThread(HybridClock* clock, AtomicBool* stop) {
Random rng(GetRandomSeed32());
Timestamp prev(0);
while (!stop->Load()) {
Timestamp t = clock->Now();
CHECK_GT(t.value(), prev.value());
prev = t;
// Add a random bit of offset to the clock, and perform an update.
Timestamp new_ts = HybridClock::AddPhysicalTimeToTimestamp(
t, MonoDelta::FromMicroseconds(rng.Uniform(10000)));
CHECK_OK(clock->Update(new_ts));
}
}
// Regression test for KUDU-953: if threads are updating and polling the
// clock concurrently, the clock should still never run backwards.
TEST_F(HybridClockTest, TestClockDoesntGoBackwardsWithUpdates) {
vector<scoped_refptr<kudu::Thread>> threads;
AtomicBool stop(false);
SCOPED_CLEANUP({
stop.Store(true);
for (const auto& t : threads) {
t->Join();
}
});
for (int i = 0; i < 4; i++) {
scoped_refptr<Thread> thread;
ASSERT_OK(Thread::Create("test", "stresser",
&StresserThread, clock_.get(), &stop,
&thread));
threads.push_back(thread);
}
SleepFor(MonoDelta::FromSeconds(1));
}
TEST_F(HybridClockTest, TestGetPhysicalComponentDifference) {
Timestamp now1 = HybridClock::TimestampFromMicrosecondsAndLogicalValue(100, 100);
SleepFor(MonoDelta::FromMilliseconds(1));
Timestamp now2 = HybridClock::TimestampFromMicrosecondsAndLogicalValue(200, 0);
MonoDelta delta = clock_->GetPhysicalComponentDifference(now2, now1);
MonoDelta negative_delta = clock_->GetPhysicalComponentDifference(now1, now2);
ASSERT_EQ(100, delta.ToMicroseconds());
ASSERT_EQ(-100, negative_delta.ToMicroseconds());
}
TEST_F(HybridClockTest, TestRideOverNtpInterruption) {
Timestamp timestamps[3];
uint64_t max_error_usec[3];
// Get the clock once, with a working NTP.
clock_->NowWithError(×tamps[0], &max_error_usec[0]);
// Try to read the clock again a second later, but with an error
// injected. It should extrapolate from the first read.
SleepFor(MonoDelta::FromSeconds(1));
FLAGS_inject_unsync_time_errors = true;
clock_->NowWithError(×tamps[1], &max_error_usec[1]);
// The new clock reading should be a second or longer from the
// first one, since SleepFor guarantees sleeping at least as long
// as specified.
MonoDelta phys_diff = clock_->GetPhysicalComponentDifference(
timestamps[1], timestamps[0]);
ASSERT_GE(phys_diff.ToSeconds(), 1);
// The new clock reading should have higher error than the first.
// The error should have increased based on the clock skew.
int64_t error_diff = max_error_usec[1] - max_error_usec[0];
ASSERT_NEAR(error_diff, clock_->time_service()->skew_ppm() * phys_diff.ToSeconds(),
10);
// Now restore the ability to read the system clock, and
// read it again.
FLAGS_inject_unsync_time_errors = false;
clock_->NowWithError(×tamps[2], &max_error_usec[2]);
ASSERT_LT(timestamps[0].ToUint64(), timestamps[1].ToUint64());
ASSERT_LT(timestamps[1].ToUint64(), timestamps[2].ToUint64());
}
#ifndef __APPLE__
TEST_F(HybridClockTest, TestNtpDiagnostics) {
vector<string> log;
clock_->time_service()->DumpDiagnostics(&log);
string s = JoinStrings(log, "\n");
SCOPED_TRACE(s);
ASSERT_STR_MATCHES(s, "(ntp_gettime\\(\\) returns code |chronyc -n tracking)");
ASSERT_STR_MATCHES(s, "(ntpq -n |chronyc -n sources)");
}
#endif
} // namespace clock
} // namespace kudu
<commit_msg>[test] fix HybridClockTest.TestWaitUntilAfter_TestCase2<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "kudu/clock/hybrid_clock.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
#include <gflags/gflags.h>
#include <gflags/gflags_declare.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "kudu/clock/mock_ntp.h"
#include "kudu/clock/time_service.h"
#include "kudu/common/timestamp.h"
#include "kudu/gutil/casts.h"
#include "kudu/gutil/ref_counted.h"
#include "kudu/gutil/strings/join.h"
#include "kudu/util/atomic.h"
#include "kudu/util/monotime.h"
#include "kudu/util/random.h"
#include "kudu/util/random_util.h"
#include "kudu/util/scoped_cleanup.h"
#include "kudu/util/status.h"
#include "kudu/util/test_macros.h"
#include "kudu/util/test_util.h"
#include "kudu/util/thread.h"
DECLARE_bool(inject_unsync_time_errors);
DECLARE_string(time_source);
using std::string;
using std::vector;
namespace kudu {
namespace clock {
class HybridClockTest : public KuduTest {
public:
HybridClockTest()
: clock_(new HybridClock) {
}
void SetUp() override {
KuduTest::SetUp();
ASSERT_OK(clock_->Init());
}
protected:
scoped_refptr<HybridClock> clock_;
};
clock::MockNtp* mock_ntp(HybridClock* clock) {
return down_cast<clock::MockNtp*>(clock->time_service());
}
TEST(MockHybridClockTest, TestMockedSystemClock) {
google::FlagSaver saver;
FLAGS_time_source = "mock";
scoped_refptr<HybridClock> clock(new HybridClock);
ASSERT_OK(clock->Init());
Timestamp timestamp;
uint64_t max_error_usec;
clock->NowWithError(×tamp, &max_error_usec);
ASSERT_EQ(timestamp.ToUint64(), 0);
ASSERT_EQ(max_error_usec, 0);
// If we read the clock again we should see the logical component be incremented.
clock->NowWithError(×tamp, &max_error_usec);
ASSERT_EQ(timestamp.ToUint64(), 1);
// Now set an arbitrary time and check that is the time returned by the clock.
uint64_t time = 1234 * 1000;
uint64_t error = 100 * 1000;
mock_ntp(clock.get())->SetMockClockWallTimeForTests(time);
mock_ntp(clock.get())->SetMockMaxClockErrorForTests(error);
clock->NowWithError(×tamp, &max_error_usec);
ASSERT_EQ(timestamp.ToUint64(),
HybridClock::TimestampFromMicrosecondsAndLogicalValue(time, 0).ToUint64());
ASSERT_EQ(max_error_usec, error);
// Perform another read, we should observe the logical component increment, again.
clock->NowWithError(×tamp, &max_error_usec);
ASSERT_EQ(timestamp.ToUint64(),
HybridClock::TimestampFromMicrosecondsAndLogicalValue(time, 1).ToUint64());
}
// Test that, if the rate at which the clock is read is greater than the maximum
// resolution of the logical counter (12 bits in our implementation), it properly
// "overflows" into the physical portion of the clock, and maintains all ordering
// guarantees even as the physical clock continues to increase.
//
// This is a regression test for KUDU-1345.
TEST(MockHybridClockTest, TestClockDealsWithWrapping) {
google::FlagSaver saver;
FLAGS_time_source = "mock";
scoped_refptr<HybridClock> clock(new HybridClock);
ASSERT_OK(clock->Init());
mock_ntp(clock.get())->SetMockClockWallTimeForTests(1000);
Timestamp prev = clock->Now();
// Update the clock from 10us in the future
ASSERT_OK(clock->Update(HybridClock::TimestampFromMicroseconds(1010)));
// Now read the clock value enough times so that the logical value wraps
// over, and should increment the _physical_ portion of the clock.
for (int i = 0; i < 10000; i++) {
Timestamp now = clock->Now();
ASSERT_GT(now.value(), prev.value());
prev = now;
}
ASSERT_EQ(1012, HybridClock::GetPhysicalValueMicros(prev));
// Advance the time microsecond by microsecond, and ensure the clock never
// goes backwards.
for (int time = 1001; time < 1020; time++) {
mock_ntp(clock.get())->SetMockClockWallTimeForTests(time);
Timestamp now = clock->Now();
// Clock should run strictly forwards.
ASSERT_GT(now.value(), prev.value());
// Additionally, once the physical time surpasses the logical time, we should
// be running on the physical clock. Otherwise, we should stick with the physical
// time we had rolled forward to above.
if (time > 1012) {
ASSERT_EQ(time, HybridClock::GetPhysicalValueMicros(now));
} else {
ASSERT_EQ(1012, HybridClock::GetPhysicalValueMicros(now));
}
prev = now;
}
}
// Test that two subsequent time reads are monotonically increasing.
TEST_F(HybridClockTest, TestNow_ValuesIncreaseMonotonically) {
const Timestamp now1 = clock_->Now();
const Timestamp now2 = clock_->Now();
ASSERT_LT(now1.value(), now2.value());
}
// Tests the clock updates with the incoming value if it is higher.
TEST_F(HybridClockTest, TestUpdate_LogicalValueIncreasesByAmount) {
Timestamp now = clock_->Now();
uint64_t now_micros = HybridClock::GetPhysicalValueMicros(now);
// increase the logical value
uint64_t logical = HybridClock::GetLogicalValue(now);
logical += 10;
// increase the physical value so that we're sure the clock will take this
// one, 200 msecs should be more than enough.
now_micros += 200000;
Timestamp now_increased = HybridClock::TimestampFromMicrosecondsAndLogicalValue(now_micros,
logical);
ASSERT_OK(clock_->Update(now_increased));
Timestamp now2 = clock_->Now();
ASSERT_EQ(logical + 1, HybridClock::GetLogicalValue(now2));
ASSERT_EQ(HybridClock::GetPhysicalValueMicros(now) + 200000,
HybridClock::GetPhysicalValueMicros(now2));
}
// Test that the incoming event is in the past, i.e. less than now - max_error
TEST_F(HybridClockTest, TestWaitUntilAfter_TestCase1) {
MonoTime no_deadline;
MonoTime before = MonoTime::Now();
Timestamp past_ts;
uint64_t max_error;
clock_->NowWithError(&past_ts, &max_error);
// make the event 3 * the max. possible error in the past
Timestamp past_ts_changed = HybridClock::AddPhysicalTimeToTimestamp(
past_ts,
MonoDelta::FromMicroseconds(-3 * static_cast<int64_t>(max_error)));
ASSERT_OK(clock_->WaitUntilAfter(past_ts_changed, no_deadline));
MonoTime after = MonoTime::Now();
MonoDelta delta = after - before;
// The delta should be close to 0, but it takes some time for the hybrid
// logical clock to decide that it doesn't need to wait.
ASSERT_LT(delta.ToMicroseconds(), 25000);
}
// The normal case for transactions. Obtain a timestamp and then wait until
// we're sure that tx_latest < now_earliest.
TEST_F(HybridClockTest, TestWaitUntilAfter_TestCase2) {
const MonoTime before = MonoTime::Now();
// we do no time adjustment, this event should fall right within the possible
// error interval
Timestamp past_ts;
uint64_t past_max_error;
clock_->NowWithError(&past_ts, &past_max_error);
// Make sure the error is at least a small number of microseconds, to ensure
// that we always have to wait.
past_max_error = std::max(past_max_error, static_cast<uint64_t>(2000));
Timestamp wait_until = HybridClock::AddPhysicalTimeToTimestamp(
past_ts,
MonoDelta::FromMicroseconds(past_max_error));
Timestamp current_ts;
uint64_t current_max_error;
clock_->NowWithError(¤t_ts, ¤t_max_error);
// Check waiting with a deadline which already expired.
{
MonoTime deadline = before;
Status s = clock_->WaitUntilAfter(wait_until, deadline);
ASSERT_TRUE(s.IsTimedOut()) << s.ToString();
}
// Wait with a deadline well in the future. This should succeed.
{
MonoTime deadline = before + MonoDelta::FromSeconds(60);
ASSERT_OK(clock_->WaitUntilAfter(wait_until, deadline));
}
MonoTime after = MonoTime::Now();
MonoDelta delta = after - before;
// In the common case current_max_error >= past_max_error and we should have waited
// 2 * past_max_error, but if the clock's error is reset between the two reads we might
// have waited less time, but always more than 'past_max_error'.
if (current_max_error >= past_max_error) {
ASSERT_GE(delta.ToMicroseconds(), 2 * past_max_error);
} else {
ASSERT_GE(delta.ToMicroseconds(), past_max_error);
}
}
TEST_F(HybridClockTest, TestIsAfter) {
Timestamp ts1 = clock_->Now();
ASSERT_TRUE(clock_->IsAfter(ts1));
// Update the clock in the future, make sure it still
// handles "IsAfter" properly even when it's running in
// "logical" mode.
Timestamp now_increased = HybridClock::TimestampFromMicroseconds(
HybridClock::GetPhysicalValueMicros(ts1) + 1 * 1000 * 1000);
ASSERT_OK(clock_->Update(now_increased));
Timestamp ts2 = clock_->Now();
ASSERT_TRUE(clock_->IsAfter(ts1));
ASSERT_TRUE(clock_->IsAfter(ts2));
}
// Thread which loops polling the clock and updating it slightly
// into the future.
void StresserThread(HybridClock* clock, AtomicBool* stop) {
Random rng(GetRandomSeed32());
Timestamp prev(0);
while (!stop->Load()) {
Timestamp t = clock->Now();
CHECK_GT(t.value(), prev.value());
prev = t;
// Add a random bit of offset to the clock, and perform an update.
Timestamp new_ts = HybridClock::AddPhysicalTimeToTimestamp(
t, MonoDelta::FromMicroseconds(rng.Uniform(10000)));
CHECK_OK(clock->Update(new_ts));
}
}
// Regression test for KUDU-953: if threads are updating and polling the
// clock concurrently, the clock should still never run backwards.
TEST_F(HybridClockTest, TestClockDoesntGoBackwardsWithUpdates) {
vector<scoped_refptr<kudu::Thread>> threads;
AtomicBool stop(false);
SCOPED_CLEANUP({
stop.Store(true);
for (const auto& t : threads) {
t->Join();
}
});
for (int i = 0; i < 4; i++) {
scoped_refptr<Thread> thread;
ASSERT_OK(Thread::Create("test", "stresser",
&StresserThread, clock_.get(), &stop,
&thread));
threads.push_back(thread);
}
SleepFor(MonoDelta::FromSeconds(1));
}
TEST_F(HybridClockTest, TestGetPhysicalComponentDifference) {
Timestamp now1 = HybridClock::TimestampFromMicrosecondsAndLogicalValue(100, 100);
SleepFor(MonoDelta::FromMilliseconds(1));
Timestamp now2 = HybridClock::TimestampFromMicrosecondsAndLogicalValue(200, 0);
MonoDelta delta = clock_->GetPhysicalComponentDifference(now2, now1);
MonoDelta negative_delta = clock_->GetPhysicalComponentDifference(now1, now2);
ASSERT_EQ(100, delta.ToMicroseconds());
ASSERT_EQ(-100, negative_delta.ToMicroseconds());
}
TEST_F(HybridClockTest, TestRideOverNtpInterruption) {
Timestamp timestamps[3];
uint64_t max_error_usec[3];
// Get the clock once, with a working NTP.
clock_->NowWithError(×tamps[0], &max_error_usec[0]);
// Try to read the clock again a second later, but with an error
// injected. It should extrapolate from the first read.
SleepFor(MonoDelta::FromSeconds(1));
FLAGS_inject_unsync_time_errors = true;
clock_->NowWithError(×tamps[1], &max_error_usec[1]);
// The new clock reading should be a second or longer from the
// first one, since SleepFor guarantees sleeping at least as long
// as specified.
MonoDelta phys_diff = clock_->GetPhysicalComponentDifference(
timestamps[1], timestamps[0]);
ASSERT_GE(phys_diff.ToSeconds(), 1);
// The new clock reading should have higher error than the first.
// The error should have increased based on the clock skew.
int64_t error_diff = max_error_usec[1] - max_error_usec[0];
ASSERT_NEAR(error_diff, clock_->time_service()->skew_ppm() * phys_diff.ToSeconds(),
10);
// Now restore the ability to read the system clock, and
// read it again.
FLAGS_inject_unsync_time_errors = false;
clock_->NowWithError(×tamps[2], &max_error_usec[2]);
ASSERT_LT(timestamps[0].ToUint64(), timestamps[1].ToUint64());
ASSERT_LT(timestamps[1].ToUint64(), timestamps[2].ToUint64());
}
#ifndef __APPLE__
TEST_F(HybridClockTest, TestNtpDiagnostics) {
vector<string> log;
clock_->time_service()->DumpDiagnostics(&log);
string s = JoinStrings(log, "\n");
SCOPED_TRACE(s);
ASSERT_STR_MATCHES(s, "(ntp_gettime\\(\\) returns code |chronyc -n tracking)");
ASSERT_STR_MATCHES(s, "(ntpq -n |chronyc -n sources)");
}
#endif
} // namespace clock
} // namespace kudu
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include "Myexception.h"
#include "chain.h"
using namespace std;
void chain :: readAndStoreFromFile(char* fileName)
{
//This function reads integers from the file given by fileName then store them in the chain
ifstream in;
in.open(filename.c_str());
if (!in) return; // file doesn't exist
int line;
while(in >> line) {
insert(listSize, line);
}
/*int line;
while(std::getline(data, line))
std::stringstream str(line);
std::string text;
std::getline(str,text,'=');
double value;
str >> value;
}*/
}
void chain :: eraseModuloValue(int theInt)
{
//This function erases all the entries from the list which are multiple of theInt
for(int i=0; i<listSize; i++) {
int value = *this->get(i);
if (value/theInt > 0 && value != theInt) remove(i);
}
}
void chain :: oddAndEvenOrdering()
{
//This function reorders the list such a way that all odd numbers precede all even numbers.
//Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.
}
void chain :: reverse()
{
//Reverses the list
}
chain :: chain(int initialCapacity)
{
//Constructor
if(initialCapacity < 1)
{
ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
firstNode = NULL;
listSize = 0;
}
chain :: ~chain()
{
//Destructor. Delete all nodes in chain
while(firstNode != NULL)
{
//delete firstNode
chainNode* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
int* chain :: get(int theIndex) const
{
//Return element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return NULL;
}
chainNode* currentNode = firstNode;
for(int i=0;i<theIndex;i++)
currentNode = currentNode->next;
return ¤tNode->element;
}
int chain :: indexOf(const int& theElement) const
{
//Return index of first occurrence of theElement.
//Return -1 of theElement not in list.
chainNode* currentNode = firstNode;
int index = 0;
while(currentNode != NULL && currentNode->element != theElement)
{
//move to the next node
currentNode = currentNode->next;
index++;
}
//make sure we found matching element
if(currentNode == NULL)
return -1;
else
return index;
}
void chain :: erase(int theIndex)
{
//Delete the element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
chainNode* deleteNode;
if(theIndex == 0)
{
//remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
else
{
//use p to get to predecessor of desired node
chainNode* p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
deleteNode = p->next;
p->next = p->next->next; //remove deleteNode from chain
}
listSize--;
delete deleteNode;
}
void chain :: insert(int theIndex, const int& theElement)
{
//Insert theElement so that its index is theIndex.
try{
if (theIndex < 0 || theIndex > listSize)
{// invalid index
ostringstream s;
s << "index = " << theIndex << " size = " << listSize;
throw illegalIndex(s.str());
}
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
if(theIndex == 0)
//insert at front
firstNode = new chainNode(theElement, firstNode);
else
{
chainNode *p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
//insert after p
p->next = new chainNode(theElement, p->next);
}
listSize++;
}
void chain :: output() const
{
//Put the list into the output.
for(int i=0;i<listSize;i++)
cout << *this->get(i) << " ";
cout<<endl;
}
void chain::checkIndex(int theIndex) const
{
// Verify that theIndex is between 0 and
// listSize - 1.
if (theIndex < 0 || theIndex >= listSize){
ostringstream s;
s << "index = " << theIndex << " size = "
<< listSize<<", the input index is invalid";
throw illegalIndex(s.str());
}
}
<commit_msg>Update chain.cpp<commit_after>#include <iostream>
#include <sstream>
#include "Myexception.h"
#include "chain.h"
using namespace std;
void chain :: readAndStoreFromFile(char* fileName)
{
//This function reads integers from the file given by fileName then store them in the chain
/*ifstream in;
ifstream infile("input.txt");
stringstream
in.open(filename.c_str());
if (!in) return; // file doesn't exist
int line;
while(in >> line) {
insert(listSize, line);
}*/
ifstream infile(fileName.c_str()) ;
string line;
while(getline(infile, line)) {
istringstream iss(line);
int n;
iss > n;
}
/*int line;
while(std::getline(data, line))
std::stringstream str(line);
std::string text;
std::getline(str,text,'=');
double value;
str >> value;
}*/
}
void chain :: eraseModuloValue(int theInt)
{
//This function erases all the entries from the list which are multiple of theInt
for(int i=0; i<listSize; i++) {
int value = *this->get(i);
if (value/theInt > 0 && value != theInt) remove(i);
}
}
void chain :: oddAndEvenOrdering()
{
//This function reorders the list such a way that all odd numbers precede all even numbers.
//Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.
}
void chain :: reverse()
{
//Reverses the list
}
chain :: chain(int initialCapacity)
{
//Constructor
if(initialCapacity < 1)
{
ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
firstNode = NULL;
listSize = 0;
}
chain :: ~chain()
{
//Destructor. Delete all nodes in chain
while(firstNode != NULL)
{
//delete firstNode
chainNode* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
int* chain :: get(int theIndex) const
{
//Return element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return NULL;
}
chainNode* currentNode = firstNode;
for(int i=0;i<theIndex;i++)
currentNode = currentNode->next;
return ¤tNode->element;
}
int chain :: indexOf(const int& theElement) const
{
//Return index of first occurrence of theElement.
//Return -1 of theElement not in list.
chainNode* currentNode = firstNode;
int index = 0;
while(currentNode != NULL && currentNode->element != theElement)
{
//move to the next node
currentNode = currentNode->next;
index++;
}
//make sure we found matching element
if(currentNode == NULL)
return -1;
else
return index;
}
void chain :: erase(int theIndex)
{
//Delete the element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
chainNode* deleteNode;
if(theIndex == 0)
{
//remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
else
{
//use p to get to predecessor of desired node
chainNode* p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
deleteNode = p->next;
p->next = p->next->next; //remove deleteNode from chain
}
listSize--;
delete deleteNode;
}
void chain :: insert(int theIndex, const int& theElement)
{
//Insert theElement so that its index is theIndex.
try{
if (theIndex < 0 || theIndex > listSize)
{// invalid index
ostringstream s;
s << "index = " << theIndex << " size = " << listSize;
throw illegalIndex(s.str());
}
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
if(theIndex == 0)
//insert at front
firstNode = new chainNode(theElement, firstNode);
else
{
chainNode *p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
//insert after p
p->next = new chainNode(theElement, p->next);
}
listSize++;
}
void chain :: output() const
{
//Put the list into the output.
for(int i=0;i<listSize;i++)
cout << *this->get(i) << " ";
cout<<endl;
}
void chain::checkIndex(int theIndex) const
{
// Verify that theIndex is between 0 and
// listSize - 1.
if (theIndex < 0 || theIndex >= listSize){
ostringstream s;
s << "index = " << theIndex << " size = "
<< listSize<<", the input index is invalid";
throw illegalIndex(s.str());
}
}
<|endoftext|> |
<commit_before>/* descriptor.cpp
Copyright (c) 2015, Nikolaj Schlej. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHWARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*/
#include "descriptor.h"
// Calculate address of data structure addressed by descriptor address format
// 8 bit base or limit
const UINT8* calculateAddress8(const UINT8* baseAddress, const UINT8 baseOrLimit)
{
return baseAddress + baseOrLimit * 0x10;
}
// 16 bit base or limit
const UINT8* calculateAddress16(const UINT8* baseAddress, const UINT16 baseOrLimit)
{
return baseAddress + baseOrLimit * 0x1000;
}
// Calculate offset of region using its base
UINT32 calculateRegionOffset(const UINT16 base)
{
return base * 0x1000;
}
//Calculate size of region using its base and limit
UINT32 calculateRegionSize(const UINT16 base, const UINT16 limit)
{
if (limit)
return (limit + 1 - base) * 0x1000;
return 0;
}
// Return human-readable chip name for given JEDEC ID
UString jedecIdToUString(UINT8 vendorId, UINT8 deviceId0, UINT8 deviceId1)
{
UINT32 jedecId = (UINT32)deviceId1 + ((UINT32)deviceId0 << 8) + ((UINT32)vendorId << 16);
switch (jedecId) {
// Winbond
case 0xEF3013: return UString("Winbond W25X40");
case 0xEF3014: return UString("Winbond W25X80");
case 0xEF3015: return UString("Winbond W25X16");
case 0xEF3016: return UString("Winbond W25X32");
case 0xEF3017: return UString("Winbond W25X64");
case 0xEF4013: return UString("Winbond W25Q40");
case 0xEF4014: return UString("Winbond W25Q80");
case 0xEF4015: return UString("Winbond W25Q16");
case 0xEF4016: return UString("Winbond W25Q32");
case 0xEF4017: return UString("Winbond W25Q64");
case 0xEF4018: return UString("Winbond W25Q128");
case 0xEF4019: return UString("Winbond W25Q256");
case 0xEF6015: return UString("Winbond W25Q16");
case 0xEF6016: return UString("Winbond W25Q32");
case 0xEF6017: return UString("Winbond W25Q64");
case 0xEF6018: return UString("Winbond W25Q128");
// Macronix
case 0xC22013: return UString("Macronix MX25L40");
case 0xC22014: return UString("Macronix MX25L80");
case 0xC22015:
case 0xC22415:
case 0xC22515: return UString("Macronix MX25L16");
case 0xC22016:
case 0xC22535: return UString("Macronix MX25U16");
case 0xC22536: return UString("Macronix MX25U32");
case 0xC22537: return UString("Macronix MX25U64");
case 0xC22538: return UString("Macronix MX25U128");
case 0xC22539: return UString("Macronix MX25U256");
case 0xC25E16: return UString("Macronix MX25L32");
case 0xC22017:
case 0xC29517: return UString("Macronix MX25L64");
case 0xC22018: return UString("Macronix MX25L128");
case 0xC22019: return UString("Macronix MX25L256");
// Micron
case 0x202014: return UString("Micron M25P80");
case 0x202015: return UString("Micron M25P16");
case 0x202016: return UString("Micron M25P32");
case 0x202017: return UString("Micron M25P64");
case 0x202018: return UString("Micron M25P128");
case 0x204011: return UString("Micron M45PE10");
case 0x204012: return UString("Micron M45PE20");
case 0x204013: return UString("Micron M45PE40");
case 0x204014: return UString("Micron M45PE80");
case 0x204015: return UString("Micron M45PE16");
case 0x207114: return UString("Micron M25PX80");
case 0x207115: return UString("Micron M25PX16");
case 0x207116: return UString("Micron M25PX32");
case 0x207117: return UString("Micron M25PX64");
case 0x208011: return UString("Micron M25PE10");
case 0x208012: return UString("Micron M25PE20");
case 0x208013: return UString("Micron M25PE40");
case 0x208014: return UString("Micron M25PE80");
case 0x208015: return UString("Micron M25PE16");
case 0x20BA15: return UString("Micron N25Q016");
case 0x20BA16: return UString("Micron N25Q032");
case 0x20BA17: return UString("Micron N25Q064");
case 0x20BA18: return UString("Micron N25Q128");
case 0x20BA19: return UString("Micron N25Q256");
case 0x20BA20: return UString("Micron N25Q512");
case 0x20BA21: return UString("Micron N25Q00A");
case 0x20BB15: return UString("Micron N25Q016");
case 0x20BB16: return UString("Micron N25Q032");
case 0x20BB17: return UString("Micron N25Q064");
case 0x20BB18: return UString("Micron MT25Q128");
case 0x20BB19: return UString("Micron MT25Q256");
case 0x20BB20: return UString("Micron MT25Q512");
// Intel
case 0x898911: return UString("Intel 25F160S33B8");
case 0x898912: return UString("Intel 25F320S33B8");
case 0x898913: return UString("Intel 25F640S33B8");
case 0x898915: return UString("Intel 25F160S33T8");
case 0x898916: return UString("Intel 25F320S33T8");
case 0x898917: return UString("Intel 25F640S33T8");
// Atmel
case 0x1F4500: return UString("Atmel AT26DF081");
case 0x1F4501: return UString("Atmel AT26DF081A");
case 0x1F4502: return UString("Atmel AT25DF081");
case 0x1F4600: return UString("Atmel AT26DF161");
case 0x1F4601: return UString("Atmel AT26DF161A");
case 0x1F4602: return UString("Atmel AT25DF161");
case 0x1F8600: return UString("Atmel AT25DQ161");
case 0x1F4700: return UString("Atmel AT25DF321");
case 0x1F4701: return UString("Atmel AT25DF321A");
case 0x1F4800: return UString("Atmel AT25DF641");
case 0x1F8800: return UString("Atmel AT25DQ641");
// Microchip
case 0xBF2541: return UString("Microchip SST25VF016B");
case 0xBF254A: return UString("Microchip SST25VF032B");
case 0xBF258D: return UString("Microchip SST25VF040B");
case 0xBF258E: return UString("Microchip SST25VF080B");
case 0xBF254B: return UString("Microchip SST25VF064C");
// EON
case 0x1C3013: return UString("EON EN25Q40");
case 0x1C3014: return UString("EON EN25Q80");
case 0x1C3015: return UString("EON EN25Q16");
case 0x1C3016: return UString("EON EN25Q32");
case 0x1C3017: return UString("EON EN25Q64");
case 0x1C3018: return UString("EON EN25Q128");
case 0x1C3114: return UString("EON EN25F80");
case 0x1C3115: return UString("EON EN25F16");
case 0x1C3116: return UString("EON EN25F32");
case 0x1C3117: return UString("EON EN25F64");
case 0x1C7015: return UString("EON EN25QH16");
case 0x1C7016: return UString("EON EN25QH32");
case 0x1C7017: return UString("EON EN25QH64");
case 0x1C7018: return UString("EON EN25QH128");
case 0x1C7019: return UString("EON EN25QH256");
// GigaDevice
case 0xC84014: return UString("GigaDevice GD25x80");
case 0xC84015: return UString("GigaDevice GD25x16");
case 0xC84016: return UString("GigaDevice GD25x32");
case 0xC84017: return UString("GigaDevice GD25x64");
case 0xC84018: return UString("GigaDevice GD25x128");
case 0xC86017: return UString("GigaDevice GD25Lx64");
case 0xC86018: return UString("GigaDevice GD25Lx128");
// Fidelix
case 0xF83215: return UString("Fidelix FM25Q16");
case 0xF83216: return UString("Fidelix FM25Q32");
case 0xF83217: return UString("Fidelix FM25Q64");
case 0xF83218: return UString("Fidelix FM25Q128");
// Spansion
case 0x014015: return UString("Spansion S25FL116K");
case 0x014016: return UString("Spansion S25FL132K");
case 0x014017: return UString("Spansion S25FL164K");
// Amic
case 0x373015: return UString("Amic A25L016");
case 0x373016: return UString("Amic A25L032");
case 0x374016: return UString("Amic A25L032A");
// PMC
case 0x9DF713: return UString("PMC Pm25LV080B");
case 0x9DF714: return UString("PMC Pm25LV016B");
case 0x9DF744: return UString("PMC Pm25LQ080C");
case 0x9DF745: return UString("PMC Pm25LQ016C");
case 0x9DF746: return UString("PMC Pm25LQ032C");
case 0x9DF77B: return UString("PMC Pm25LV512A");
case 0x9DF77C: return UString("PMC Pm25LV010A");
case 0x9DF77D: return UString("PMC Pm25LV020");
case 0x9DF77E: return UString("PMC Pm25LV040");
// ISSI
case 0x9D6017: return UString("ISSI Ix25LP064");
case 0x9D6018: return UString("ISSI Ix25LP128");
case 0x9D7018: return UString("ISSI Ix25WP128");
}
return UString("Unknown");
}
<commit_msg>Add more chip IDs, thank you Google<commit_after>/* descriptor.cpp
Copyright (c) 2015, Nikolaj Schlej. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHWARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*/
#include "descriptor.h"
// Calculate address of data structure addressed by descriptor address format
// 8 bit base or limit
const UINT8* calculateAddress8(const UINT8* baseAddress, const UINT8 baseOrLimit)
{
return baseAddress + baseOrLimit * 0x10;
}
// 16 bit base or limit
const UINT8* calculateAddress16(const UINT8* baseAddress, const UINT16 baseOrLimit)
{
return baseAddress + baseOrLimit * 0x1000;
}
// Calculate offset of region using its base
UINT32 calculateRegionOffset(const UINT16 base)
{
return base * 0x1000;
}
//Calculate size of region using its base and limit
UINT32 calculateRegionSize(const UINT16 base, const UINT16 limit)
{
if (limit)
return (limit + 1 - base) * 0x1000;
return 0;
}
// Return human-readable chip name for given JEDEC ID
UString jedecIdToUString(UINT8 vendorId, UINT8 deviceId0, UINT8 deviceId1)
{
UINT32 jedecId = (UINT32)deviceId1 + ((UINT32)deviceId0 << 8) + ((UINT32)vendorId << 16);
switch (jedecId) {
// Winbond
case 0xEF3013: return UString("Winbond W25X40");
case 0xEF3014: return UString("Winbond W25X80");
case 0xEF3015: return UString("Winbond W25X16");
case 0xEF3016: return UString("Winbond W25X32");
case 0xEF3017: return UString("Winbond W25X64");
case 0xEF4013: return UString("Winbond W25Q40");
case 0xEF4014: return UString("Winbond W25Q80");
case 0xEF4015: return UString("Winbond W25Q16");
case 0xEF4016: return UString("Winbond W25Q32");
case 0xEF4017: return UString("Winbond W25Q64");
case 0xEF4018: return UString("Winbond W25Q128");
case 0xEF4019: return UString("Winbond W25Q256");
case 0xEF6011: return UString("Winbond W25Q10");
case 0xEF6012: return UString("Winbond W25Q20");
case 0xEF6013: return UString("Winbond W25Q40");
case 0xEF6014: return UString("Winbond W25Q80");
case 0xEF6015: return UString("Winbond W25Q16");
case 0xEF6016: return UString("Winbond W25Q32");
case 0xEF6017: return UString("Winbond W25Q64");
case 0xEF6018: return UString("Winbond W25Q128");
// Macronix
case 0xC22013: return UString("Macronix MX25L40");
case 0xC22014: return UString("Macronix MX25L80");
case 0xC22015:
case 0xC22415:
case 0xC22515: return UString("Macronix MX25L16");
case 0xC22016:
case 0xC22535: return UString("Macronix MX25U16");
case 0xC2201A: return UString("Macronix MX66L512");
case 0xC22536: return UString("Macronix MX25U32");
case 0xC22537: return UString("Macronix MX25U64");
case 0xC22538: return UString("Macronix MX25U128");
case 0xC22539: return UString("Macronix MX25U256");
case 0xC25E16: return UString("Macronix MX25L32");
case 0xC22017:
case 0xC29517:
case 0xC22617: return UString("Macronix MX25L64");
case 0xC22018:
case 0xC22618: return UString("Macronix MX25L128");
case 0xC22019: return UString("Macronix MX25L256");
// Micron
case 0x202014: return UString("Micron M25P80");
case 0x202015: return UString("Micron M25P16");
case 0x202016: return UString("Micron M25P32");
case 0x202017: return UString("Micron M25P64");
case 0x202018: return UString("Micron M25P128");
case 0x204011: return UString("Micron M45PE10");
case 0x204012: return UString("Micron M45PE20");
case 0x204013: return UString("Micron M45PE40");
case 0x204014: return UString("Micron M45PE80");
case 0x204015: return UString("Micron M45PE16");
case 0x207114: return UString("Micron M25PX80");
case 0x207115: return UString("Micron M25PX16");
case 0x207116: return UString("Micron M25PX32");
case 0x207117: return UString("Micron M25PX64");
case 0x208011: return UString("Micron M25PE10");
case 0x208012: return UString("Micron M25PE20");
case 0x208013: return UString("Micron M25PE40");
case 0x208014: return UString("Micron M25PE80");
case 0x208015: return UString("Micron M25PE16");
case 0x20BA15: return UString("Micron N25Q016");
case 0x20BA16: return UString("Micron N25Q032");
case 0x20BA17: return UString("Micron N25Q064");
case 0x20BA18: return UString("Micron N25Q128");
case 0x20BA19: return UString("Micron N25Q256");
case 0x20BA20: return UString("Micron N25Q512");
case 0x20BA21: return UString("Micron N25Q00A");
case 0x20BB15: return UString("Micron N25Q016");
case 0x20BB16: return UString("Micron N25Q032");
case 0x20BB17: return UString("Micron N25Q064");
case 0x20BB18: return UString("Micron MT25Q128");
case 0x20BB19: return UString("Micron MT25Q256");
case 0x20BB20: return UString("Micron MT25Q512");
// Intel
case 0x898911: return UString("Intel 25F160S33B8");
case 0x898912: return UString("Intel 25F320S33B8");
case 0x898913: return UString("Intel 25F640S33B8");
case 0x898915: return UString("Intel 25F160S33T8");
case 0x898916: return UString("Intel 25F320S33T8");
case 0x898917: return UString("Intel 25F640S33T8");
// Atmel
case 0x1F3217: return UString("Atmel AT25SF641");
case 0x1F4216: return UString("Atmel AT25SL321");
case 0x1F4218: return UString("Atmel AT25SL128A");
case 0x1F4317: return UString("Atmel AT25SL641");
case 0x1F4500: return UString("Atmel AT26DF081");
case 0x1F4501: return UString("Atmel AT26DF081A");
case 0x1F4502: return UString("Atmel AT25DF081");
case 0x1F4600: return UString("Atmel AT26DF161");
case 0x1F4601: return UString("Atmel AT26DF161A");
case 0x1F4602: return UString("Atmel AT25DF161");
case 0x1F8600: return UString("Atmel AT25DQ161");
case 0x1F4700: return UString("Atmel AT25DF321");
case 0x1F4701: return UString("Atmel AT25DF321A");
case 0x1F4800: return UString("Atmel AT25DF641");
case 0x1F8800: return UString("Atmel AT25DQ641");
// Microchip
case 0xBF2541: return UString("Microchip SST25VF016B");
case 0xBF254A: return UString("Microchip SST25VF032B");
case 0xBF258D: return UString("Microchip SST25VF040B");
case 0xBF258E: return UString("Microchip SST25VF080B");
case 0xBF254B: return UString("Microchip SST25VF064C");
// EON
case 0x1C3013: return UString("EON EN25Q40");
case 0x1C3014: return UString("EON EN25Q80");
case 0x1C3015: return UString("EON EN25Q16");
case 0x1C3016: return UString("EON EN25Q32");
case 0x1C3017: return UString("EON EN25Q64");
case 0x1C3018: return UString("EON EN25Q128");
case 0x1C3114: return UString("EON EN25F80");
case 0x1C3115: return UString("EON EN25F16");
case 0x1C3116: return UString("EON EN25F32");
case 0x1C3117: return UString("EON EN25F64");
case 0x1C7014: return UString("EON EN25QH80");
case 0x1C7015: return UString("EON EN25QH16");
case 0x1C7016: return UString("EON EN25QH32");
case 0x1C7017: return UString("EON EN25QH64");
case 0x1C7018: return UString("EON EN25QH128");
case 0x1C7019: return UString("EON EN25QH256");
// GigaDevice
case 0xC84014: return UString("GigaDevice GD25x80");
case 0xC84015: return UString("GigaDevice GD25x16");
case 0xC84016: return UString("GigaDevice GD25x32");
case 0xC84017: return UString("GigaDevice GD25x64");
case 0xC84018: return UString("GigaDevice GD25x128");
case 0xC84019: return UString("GigaDevice GD25x256C");
case 0xC86017: return UString("GigaDevice GD25Lx64");
case 0xC86018: return UString("GigaDevice GD25Lx128");
case 0xC86019: return UString("GigaDevice GD25LQ256C");
// Fidelix
case 0xF83215: return UString("Fidelix FM25Q16");
case 0xF83216: return UString("Fidelix FM25Q32");
case 0xF83217: return UString("Fidelix FM25Q64");
case 0xF83218: return UString("Fidelix FM25Q128");
// Spansion
case 0x014015: return UString("Spansion S25FL116K");
case 0x014016: return UString("Spansion S25FL132K");
case 0x014017: return UString("Spansion S25FL164K");
// Amic
case 0x373015: return UString("Amic A25L016");
case 0x373016: return UString("Amic A25L032");
case 0x374016: return UString("Amic A25L032A");
// PMC
case 0x9DF713: return UString("PMC Pm25LV080B");
case 0x9DF714: return UString("PMC Pm25LV016B");
case 0x9DF744: return UString("PMC Pm25LQ080C");
case 0x9DF745: return UString("PMC Pm25LQ016C");
case 0x9DF746: return UString("PMC Pm25LQ032C");
case 0x9DF77B: return UString("PMC Pm25LV512A");
case 0x9DF77C: return UString("PMC Pm25LV010A");
case 0x9DF77D: return UString("PMC Pm25LV020");
case 0x9DF77E: return UString("PMC Pm25LV040");
// ISSI
case 0x9D6017: return UString("ISSI Ix25LP064");
case 0x9D6018: return UString("ISSI Ix25LP128");
case 0x9D6019: return UString("ISSI Ix25LP256");
case 0x9D7017: return UString("ISSI Ix25WP064");
case 0x9D7018: return UString("ISSI Ix25WP128");
case 0x9D7019: return UString("ISSI Ix25WP256");
}
return UString("Unknown");
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <regex>
#include "logging/logger.h"
#include "sequence/io/ptb_parser.h"
namespace meta
{
namespace sequence
{
std::vector<sequence> extract_sequences(const std::string& filename)
{
std::regex regex{"=====+\\s*$"};
std::vector<sequence> results;
std::ifstream file{filename};
std::string line;
sequence seq;
while (std::getline(file, line))
{
if (seq.size() > 0)
{
if (std::regex_match(line, regex))
{
results.emplace_back(std::move(seq));
continue;
}
if (line.length() == 0)
{
if (seq[seq.size() - 1].tag() == tag_t{"."})
results.emplace_back(std::move(seq));
continue;
}
}
std::stringstream ss{line};
std::string word;
while (ss >> word)
{
if (word == "]" || word == "[")
continue;
auto pos = word.rfind('/');
if (pos == word.npos)
{
LOG(warning) << "could not find '/' in word/tag pair" << ENDLG;
continue;
}
auto sym = symbol_t{word.substr(0, pos)};
auto tag = tag_t{word.substr(pos + 1)};
seq.add_observation({sym, tag});
}
}
if (seq.size() > 0)
results.emplace_back(std::move(seq));
return results;
}
}
}
<commit_msg>Fix bug where the regex was unused in extract_sequences.<commit_after>#include <fstream>
#include <regex>
#include "logging/logger.h"
#include "sequence/io/ptb_parser.h"
namespace meta
{
namespace sequence
{
std::vector<sequence> extract_sequences(const std::string& filename)
{
std::regex regex{"=====+\\s*$"};
std::vector<sequence> results;
std::ifstream file{filename};
std::string line;
sequence seq;
while (std::getline(file, line))
{
// blank line
if (line.length() == 0)
{
if (seq.size() > 0)
{
if (seq[seq.size() - 1].tag() == tag_t{"."})
results.emplace_back(std::move(seq));
}
continue;
}
// paragraph divider
if (std::regex_match(line, regex))
{
if (seq.size() > 0)
results.emplace_back(std::move(seq));
continue;
}
std::stringstream ss{line};
std::string word;
while (ss >> word)
{
if (word == "]" || word == "[")
continue;
auto pos = word.rfind('/');
if (pos == word.npos)
{
LOG(warning) << "could not find '/' in word/tag pair" << ENDLG;
LOG(warning) << "word/tag pair is: " << word << ENDLG;
continue;
}
auto sym = symbol_t{word.substr(0, pos)};
auto tag = tag_t{word.substr(pos + 1)};
seq.add_observation({sym, tag});
}
}
if (seq.size() > 0)
results.emplace_back(std::move(seq));
return results;
}
}
}
<|endoftext|> |
<commit_before>//
// shared_statement.cc for saw
// Made by nicuveo <crucuny@gmail.com>
//
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Includes
#include <iostream>
#include "shared/shared_statement.hh"
#include "error.hh"
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Implementation
namespace saw
{
// -tors
SharedStatement::SharedStatement(Database db, const char* statement)
: row_index_(-1)
{
check(db, sqlite3_prepare_v2(db.raw_data(), statement, -1, &data_, 0));
resize(sqlite3_column_count(data_));
}
SharedStatement::~SharedStatement()
{
sqlite3_finalize(data_);
}
// mutators
bool
SharedStatement::step(const Statement& parent)
{
Database db = parent.database();
row_invalidity_.raise();
switch (sqlite3_step(data()))
{
case SQLITE_DONE:
reset();
return false;
case SQLITE_ROW:
row_ = Row(parent, ++row_index_, row_invalidity_);
return true;
default:
check(db, reset());
}
return false;
}
int
SharedStatement::reset()
{
row_ = Row();
row_index_ = -1;
return sqlite3_reset(data_);
}
// helpers
std::string
SharedStatement::fetch(int i) const
{
return sqlite3_column_name(data(), i);
}
}
<commit_msg>Removed useless include.<commit_after>//
// shared_statement.cc for saw
// Made by nicuveo <crucuny@gmail.com>
//
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Includes
#include "shared/shared_statement.hh"
#include "error.hh"
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Implementation
namespace saw
{
// -tors
SharedStatement::SharedStatement(Database db, const char* statement)
: row_index_(-1)
{
check(db, sqlite3_prepare_v2(db.raw_data(), statement, -1, &data_, 0));
resize(sqlite3_column_count(data_));
}
SharedStatement::~SharedStatement()
{
sqlite3_finalize(data_);
}
// mutators
bool
SharedStatement::step(const Statement& parent)
{
Database db = parent.database();
row_invalidity_.raise();
switch (sqlite3_step(data()))
{
case SQLITE_DONE:
reset();
return false;
case SQLITE_ROW:
row_ = Row(parent, ++row_index_, row_invalidity_);
return true;
default:
check(db, reset());
}
return false;
}
int
SharedStatement::reset()
{
row_ = Row();
row_index_ = -1;
return sqlite3_reset(data_);
}
// helpers
std::string
SharedStatement::fetch(int i) const
{
return sqlite3_column_name(data(), i);
}
}
<|endoftext|> |
<commit_before>#include "ys_sockdata.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
#include <string.h>
namespace ys {
sock_module::sock_module(char* host, int port) {
struct sockaddr_in local;
bzero(&local, sizeof(local));
local.sin_family = AF_INET;
local.sin_port = htons(port);
inet_pton(AF_INET, host, &local.sin_addr);
if ((listen.sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
return -1;
}
if (-1 == bind(lsock, (struct sockaddr*)&local, sizeof(local))) {
return -1;
}
if (-1 == listen(lsock, LISTEN_NUM)) {
return -1;
}
listen.sock = lsock;
listen.pos = -1;
listen.close = 0;
connList = 0;
}
sock_module::~sock_module() {
}
void sock_module::prepare(struct pollfd *psock, int& nsock) {
connect_meta* p = connList;
int pos = nsock;
if (!listen.close) {
psock[pos].fd = listen.sock;
listen.pos = pos;
psock[pos++].events = POLLIN;
}
while (p) {
if (p->close) {
p = p->link;
continue;
}
psock[pos].fd = p->sock;
p->pos = pos;
psock[pos].events = POLLERR | POLLHUP;
pthread_mutex_lock(&p->lock);
if (p->getStateCanRead()) {
psock[pos].events |= POLLIN;
}
if (p->getStateCanWrite()) {
psock[pos].events |= POLLOUT;
}
pos ++;
p = p->link;
}
nsock = pos;
}
void sock_module::process(struct pollfd *psock) {
processL(psock);
processC(psock);
}
void sock_module::processL(struct pollfd * psock) {
if (listen.pos < 0 || !(psock[listen.pos] & POLLIN)) {
return;
}
int dsock = accept(listen.sock, (struct sockaddr*)0, 0);
if (dsock < 0) {
printf ("error!\n");
}
else {
connect_meta* tmp = new connect_meta();
tmp->sock = dsock;
tmp->pos = -1;
tmp->close = 0;
tmp->state = 0;
tmp->setStateCanRead();
tmp->setStateCanWrite();
tmp->link = connList;
connList->link = tmp;
}
}
void sock_module::processC(struct pollfd * psodk) {
connect_meta *cusor = connList;
while (cusor) {
if (cusor->pos < 0) {
cusor = cusor->link;
continue;
}
if (psodk[cusor->pos].revents & POLLERR ||
psodk[cusor->pos].revents & POLLHUP) {
close (cusor->sock);
cusor->close = 1;
}
if (psodk[cusor->pos].revents
if (psodk[cusor->pos].revents & POLLIN) {
cusor->setStateNoRead();
readEvent event = new readEvent();
event->args = (void*)cusor;
// TODO
}
if (psodk[cusor->pos].revents & POLLOUT) {
cusor->setStateNoWrite();
writeEvent event = new writeEvent();
event->args = (void*)cusor;
// TODO
}
cusor = cusor->link;
}
connect_meta **delcusor = connList;
while (*delcusor) {
if (1 == (*delcusor)->close) {
connect_meta *tmp = *delcusor;
*delcusor = (*delcusor)->link;
delete tmp;
}
else {
delcusor = &(*delcusor)->link;
}
}
}
}
<commit_msg>format<commit_after>#include "ys_sockdata.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
#include <string.h>
namespace ys {
sock_module::sock_module(char* host, int port) {
struct sockaddr_in local;
bzero(&local, sizeof(local));
local.sin_family = AF_INET;
local.sin_port = htons(port);
inet_pton(AF_INET, host, &local.sin_addr);
if ((listen.sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
return -1;
}
if (-1 == bind(lsock, (struct sockaddr*)&local, sizeof(local))) {
return -1;
}
if (-1 == listen(lsock, LISTEN_NUM)) {
return -1;
}
listen.sock = lsock;
listen.pos = -1;
listen.close = 0;
connList = 0;
}
sock_module::~sock_module() {
}
void sock_module::prepare(struct pollfd *psock, int& nsock) {
connect_meta* p = connList;
int pos = nsock;
if (!listen.close) {
psock[pos].fd = listen.sock;
listen.pos = pos;
psock[pos++].events = POLLIN;
}
while (p) {
if (p->close) {
p = p->link;
continue;
}
psock[pos].fd = p->sock;
p->pos = pos;
psock[pos].events = POLLERR | POLLHUP;
pthread_mutex_lock(&p->lock);
if (p->getStateCanRead()) {
psock[pos].events |= POLLIN;
}
if (p->getStateCanWrite()) {
psock[pos].events |= POLLOUT;
}
pos ++;
p = p->link;
}
nsock = pos;
}
void sock_module::process(struct pollfd *psock) {
processL(psock);
processC(psock);
}
void sock_module::processL(struct pollfd * psock) {
if (listen.pos < 0 || !(psock[listen.pos] & POLLIN)) {
return;
}
int dsock = accept(listen.sock, (struct sockaddr*)0, 0);
if (dsock < 0) {
printf ("error!\n");
}
else {
connect_meta* tmp = new connect_meta();
tmp->sock = dsock;
tmp->pos = -1;
tmp->close = 0;
tmp->state = 0;
tmp->setStateCanRead();
tmp->setStateCanWrite();
tmp->link = connList;
connList->link = tmp;
}
}
void sock_module::processC(struct pollfd * psodk) {
connect_meta *cusor = connList;
while (cusor) {
if (cusor->pos < 0) {
cusor = cusor->link;
continue;
}
if (psodk[cusor->pos].revents & POLLERR ||
psodk[cusor->pos].revents & POLLHUP) {
close (cusor->sock);
cusor->close = 1;
}
if (psodk[cusor->pos].revents & POLLIN) {
cusor->setStateNoRead();
readEvent event = new readEvent();
event->args = (void*)cusor;
// TODO
}
if (psodk[cusor->pos].revents & POLLOUT) {
cusor->setStateNoWrite();
writeEvent event = new writeEvent();
event->args = (void*)cusor;
// TODO
}
cusor = cusor->link;
}
connect_meta **delcusor = connList;
while (*delcusor) {
if (1 == (*delcusor)->close) {
connect_meta *tmp = *delcusor;
*delcusor = (*delcusor)->link;
delete tmp;
}
else {
delcusor = &(*delcusor)->link;
}
}
}
}
<|endoftext|> |
<commit_before>#include "start_game_state.hpp"
#include "game_state.hpp"
#include "main_menu_state.hpp"
#include "logger.hpp"
#include "exception.hpp"
static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
namespace Quoridor {
std::string StartGameState::name_("Start Game");
StartGameState::StartGameState(std::shared_ptr<StateManager> stm)
: stm_(stm), player_types_(), player_num_(2)
{
win_ = std::shared_ptr<CEGUI::Window>(
CEGUI::WindowManager::getSingleton().
loadLayoutFromFile("start_game.layout"),
[=](CEGUI::Window *w) {
BOOST_LOG_SEV(lg, boost::log::trivial::debug) << "removing window " << w;
CEGUI::WindowManager::getSingleton().destroyWindow(w);
}
);
init_player_num_();
subscribe_for_events_();
player_types_.push_back("fake");
player_types_.push_back("fake");
}
StartGameState::~StartGameState()
{
BOOST_LOG_SEV(lg, boost::log::trivial::debug) << "destroying state " << name_;
}
std::shared_ptr<CEGUI::Window> StartGameState::window() const
{
return win_;
}
const std::string &StartGameState::name() const
{
return name_;
}
void StartGameState::init_player_num_()
{
CEGUI::Combobox *cbpn = static_cast<CEGUI::Combobox*>(win_->getChild("playerNum"));
std::vector<std::pair<int, std::string>> num_str_list = {
{2, "two players"},
{4, "four players"}
};
for (auto num : num_str_list) {
auto item = new CEGUI::ListboxTextItem(num.second);
item->setUserData(reinterpret_cast<void*>(num.first));
cbpn->addItem(item);
}
if (auto item = cbpn->getListboxItemFromIndex(0)) {
cbpn->setItemSelectState(item, true);
update_player_num_();
}
else {
throw Exception("failed to set player number");
}
}
int StartGameState::update_player_num_()
{
CEGUI::Combobox *cbpn = static_cast<CEGUI::Combobox*>(win_->getChild("playerNum"));
if (auto item = cbpn->getSelectedItem()) {
player_num_ = reinterpret_cast<uintptr_t>(item->getUserData());
BOOST_LOG_SEV(lg, boost::log::trivial::info)
<< "set player number to " << player_num_;
set_player_list_();
return 0;
}
return -1;
}
void StartGameState::set_player_list_()
{
CEGUI::DefaultWindow *plist_win = static_cast<CEGUI::DefaultWindow*>(
win_->getChild("playerList"));
for (size_t i = 0; i < player_num_; ++i) {
auto ptype_win = CEGUI::WindowManager::getSingleton().createWindow("GlossySerpent/Combobox");
ptype_win->setPosition(CEGUI::UVector2(
CEGUI::UDim(0, 20),
CEGUI::UDim(0.1 * i, 0)));
ptype_win->setSize(CEGUI::USize(
CEGUI::UDim(0.5, 20),
CEGUI::UDim(0.8, 0)));
plist_win->addChild(ptype_win);
}
}
void StartGameState::subscribe_for_events_()
{
win_->getChild("startGame")->subscribeEvent(
CEGUI::Window::EventMouseClick,
CEGUI::Event::Subscriber(
&StartGameState::handle_start_game_, this
)
);
win_->getChild("returnToMainMenu")->subscribeEvent(
CEGUI::Window::EventMouseClick,
CEGUI::Event::Subscriber(
&StartGameState::handle_return_, this
)
);
win_->getChild("playerNum")->subscribeEvent(
CEGUI::Combobox::EventListSelectionAccepted,
CEGUI::Event::Subscriber(
&StartGameState::handle_player_num_, this
)
);
}
bool StartGameState::handle_start_game_(const CEGUI::EventArgs &/* e */)
{
BOOST_LOG_SEV(lg, boost::log::trivial::info) << "starting game";
stm_->change_state(std::shared_ptr<IState>(new GameState(stm_, player_types_)));
return true;
}
bool StartGameState::handle_return_(const CEGUI::EventArgs &/* e */)
{
BOOST_LOG_SEV(lg, boost::log::trivial::info) << "returning to main menu";
stm_->change_state(std::shared_ptr<IState>(new MainMenuState(stm_)));
return true;
}
bool StartGameState::handle_player_num_(const CEGUI::EventArgs &/* e */)
{
BOOST_LOG_SEV(lg, boost::log::trivial::info) << "changing player number";
if (update_player_num_() == 0) {
return true;
}
return false;
}
} /* namespace Quoridor */
<commit_msg>Set player types empty on init<commit_after>#include "start_game_state.hpp"
#include "game_state.hpp"
#include "main_menu_state.hpp"
#include "logger.hpp"
#include "exception.hpp"
static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
namespace Quoridor {
std::string StartGameState::name_("Start Game");
StartGameState::StartGameState(std::shared_ptr<StateManager> stm)
: stm_(stm), player_types_(), player_num_(0)
{
win_ = std::shared_ptr<CEGUI::Window>(
CEGUI::WindowManager::getSingleton().
loadLayoutFromFile("start_game.layout"),
[=](CEGUI::Window *w) {
BOOST_LOG_SEV(lg, boost::log::trivial::debug) << "removing window " << w;
CEGUI::WindowManager::getSingleton().destroyWindow(w);
}
);
init_player_num_();
subscribe_for_events_();
}
StartGameState::~StartGameState()
{
BOOST_LOG_SEV(lg, boost::log::trivial::debug) << "destroying state " << name_;
}
std::shared_ptr<CEGUI::Window> StartGameState::window() const
{
return win_;
}
const std::string &StartGameState::name() const
{
return name_;
}
void StartGameState::init_player_num_()
{
CEGUI::Combobox *cbpn = static_cast<CEGUI::Combobox*>(win_->getChild("playerNum"));
std::vector<std::pair<int, std::string>> num_str_list = {
{2, "two players"},
{4, "four players"}
};
for (auto num : num_str_list) {
auto item = new CEGUI::ListboxTextItem(num.second);
item->setUserData(reinterpret_cast<void*>(num.first));
cbpn->addItem(item);
}
if (auto item = cbpn->getListboxItemFromIndex(0)) {
cbpn->setItemSelectState(item, true);
update_player_num_();
}
else {
throw Exception("failed to set player number");
}
}
int StartGameState::update_player_num_()
{
CEGUI::Combobox *cbpn = static_cast<CEGUI::Combobox*>(win_->getChild("playerNum"));
if (auto item = cbpn->getSelectedItem()) {
player_num_ = reinterpret_cast<uintptr_t>(item->getUserData());
BOOST_LOG_SEV(lg, boost::log::trivial::info)
<< "set player number to " << player_num_;
set_player_list_();
return 0;
}
return -1;
}
void StartGameState::set_player_list_()
{
CEGUI::DefaultWindow *plist_win = static_cast<CEGUI::DefaultWindow*>(
win_->getChild("playerList"));
for (size_t i = 0; i < player_num_; ++i) {
auto ptype_win = CEGUI::WindowManager::getSingleton().createWindow("GlossySerpent/Combobox");
ptype_win->setPosition(CEGUI::UVector2(
CEGUI::UDim(0, 20),
CEGUI::UDim(0.1 * i, 0)));
ptype_win->setSize(CEGUI::USize(
CEGUI::UDim(0.5, 20),
CEGUI::UDim(0.8, 0)));
plist_win->addChild(ptype_win);
}
}
void StartGameState::subscribe_for_events_()
{
win_->getChild("startGame")->subscribeEvent(
CEGUI::Window::EventMouseClick,
CEGUI::Event::Subscriber(
&StartGameState::handle_start_game_, this
)
);
win_->getChild("returnToMainMenu")->subscribeEvent(
CEGUI::Window::EventMouseClick,
CEGUI::Event::Subscriber(
&StartGameState::handle_return_, this
)
);
win_->getChild("playerNum")->subscribeEvent(
CEGUI::Combobox::EventListSelectionAccepted,
CEGUI::Event::Subscriber(
&StartGameState::handle_player_num_, this
)
);
}
bool StartGameState::handle_start_game_(const CEGUI::EventArgs &/* e */)
{
BOOST_LOG_SEV(lg, boost::log::trivial::info) << "starting game";
stm_->change_state(std::shared_ptr<IState>(new GameState(stm_, player_types_)));
return true;
}
bool StartGameState::handle_return_(const CEGUI::EventArgs &/* e */)
{
BOOST_LOG_SEV(lg, boost::log::trivial::info) << "returning to main menu";
stm_->change_state(std::shared_ptr<IState>(new MainMenuState(stm_)));
return true;
}
bool StartGameState::handle_player_num_(const CEGUI::EventArgs &/* e */)
{
BOOST_LOG_SEV(lg, boost::log::trivial::info) << "changing player number";
if (update_player_num_() == 0) {
return true;
}
return false;
}
} /* namespace Quoridor */
<|endoftext|> |
<commit_before>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
#include <Rocket/Core.h>
#include "client.h"
#include "rocket.h"
#include "../qcommon/q_unicode.h"
using namespace Rocket::Core::Input;
static std::map< int, int > keyMap;
static bool init = false;
void Rocket_InitKeys( void )
{
keyMap[ K_TAB ] = KI_TAB;
keyMap[ K_ENTER ] = KI_RETURN;
keyMap[ K_ESCAPE ] = KI_ESCAPE;
keyMap[ K_SPACE ] = KI_SPACE;
keyMap[ K_BACKSPACE ] = KI_BACK;
keyMap[ K_COMMAND ] = KI_LWIN;
keyMap[ K_CAPSLOCK ] = KI_CAPITAL;
keyMap[ K_POWER ] = KI_POWER;
keyMap[ K_PAUSE ] = KI_PAUSE;
keyMap[ K_UPARROW ] = KI_UP;
keyMap[ K_DOWNARROW ] = KI_DOWN;
keyMap[ K_LEFTARROW ] = KI_LEFT;
keyMap[ K_RIGHTARROW ] = KI_RIGHT;
keyMap[ K_ALT ] = KI_LMETA;
keyMap[ K_CTRL ] = KI_LCONTROL;
keyMap[ K_SHIFT ] = KI_LSHIFT;
keyMap[ K_INS ] = KI_INSERT;
keyMap[ K_DEL ] = KI_DELETE;
keyMap[ K_PGDN ] = KI_NEXT;
keyMap[ K_PGUP ] = KI_PRIOR;
keyMap[ K_HOME ] = KI_HOME;
keyMap[ K_END ] = KI_END;
keyMap[ K_F1 ] = KI_F1;
keyMap[ K_F2 ] = KI_F2;
keyMap[ K_F3 ] = KI_F3;
keyMap[ K_F4 ] = KI_F4;
keyMap[ K_F5 ] = KI_F5;
keyMap[ K_F6 ] = KI_F6;
keyMap[ K_F7 ] = KI_F7;
keyMap[ K_F8 ] = KI_F8;
keyMap[ K_F9 ] = KI_F9;
keyMap[ K_F10 ] = KI_F10;
keyMap[ K_F11 ] = KI_F11;
keyMap[ K_F12 ] = KI_F12;
keyMap[ K_F13 ] = KI_F13;
keyMap[ K_F14 ] = KI_F14;
keyMap[ K_F15 ] = KI_F15;
keyMap[ K_KP_HOME ] = KI_NUMPAD7;
keyMap[ K_KP_UPARROW ] = KI_NUMPAD8;
keyMap[ K_KP_PGUP ] = KI_NUMPAD9;
keyMap[ K_KP_LEFTARROW ] = KI_NUMPAD4;
keyMap[ K_KP_5 ] = KI_NUMPAD5;
keyMap[ K_KP_RIGHTARROW ] = KI_NUMPAD6;
keyMap[ K_KP_END ] = KI_NUMPAD1;
keyMap[ K_KP_DOWNARROW ] = KI_NUMPAD2;
keyMap[ K_KP_PGDN ] = KI_NUMPAD3;
keyMap[ K_KP_ENTER ] = KI_NUMPADENTER;
keyMap[ K_KP_INS ] = KI_NUMPAD0;
keyMap[ K_KP_DEL ] = KI_DECIMAL;
keyMap[ K_KP_SLASH ] = KI_DIVIDE;
keyMap[ K_KP_MINUS ] = KI_SUBTRACT;
keyMap[ K_KP_PLUS ] = KI_ADD;
keyMap[ K_KP_NUMLOCK ] = KI_NUMLOCK;
keyMap[ K_KP_STAR ] = KI_MULTIPLY;
// keyMap[ K_KP_EQUALS ] = KI_KP_EQUALS;
keyMap[ K_SUPER ] = KI_LWIN;
// keyMap[ K_COMPOSE ] = KI_COMPOSE;
// keyMap[ K_MODE ] = KI_MODE;
keyMap[ K_HELP ] = KI_HELP;
keyMap[ K_PRINT ] = KI_PRINT;
// keyMap[ K_SYSREQ ] = KI_SYSREQ;
keyMap[ K_SCROLLOCK ] = KI_SCROLL;
// keyMap[ K_BREAK ] = KI_BREAK;
keyMap[ K_MENU ] = KI_APPS;
// keyMap[ K_EURO ] = KI_EURO;
// keyMap[ K_UNDO ] = KI_UNDO;
// Corresponds to 0 - 9
for ( int i = '0'; i < '9' + 1; ++i )
{
keyMap[ i ] = KI_0 + ( i - '0' );
}
// Corresponds to a - z
for ( int i = 'a'; i < 'z' + 1; ++i )
{
keyMap[ i ] = KI_A + ( i - 'a' );
}
// Other keyMap that out of ascii order and are handled separately
keyMap[ ';' ] = KI_OEM_1; // US standard keyboard; the ';:' key.
keyMap[ '=' ] = KI_OEM_PLUS; // Any region; the '=+' key.
keyMap[ ',' ] = KI_OEM_COMMA; // Any region; the ',<' key.
keyMap[ '-' ] = KI_OEM_MINUS; // Any region; the '-_' key.
keyMap[ '.' ] = KI_OEM_PERIOD; // Any region; the '.>' key.
keyMap[ '/' ] = KI_OEM_2; // Any region; the '/?' key.
keyMap[ '`' ] = KI_OEM_3; // Any region; the '`~' key.
keyMap[ K_CONSOLE ] = KI_OEM_3;
keyMap[ '[' ] = KI_OEM_4; // US standard keyboard; the '[{' key.
keyMap[ '\\' ] = KI_OEM_5; // US standard keyboard; the '\|' key.
keyMap[ ']' ] = KI_OEM_6; // US standard keyboard; the ']}' key.
keyMap[ '\'' ] = KI_OEM_7; // US standard keyboard; the ''"' key.
init = true;
}
KeyIdentifier Rocket_FromQuake( int key )
{
if ( !init )
{
Com_Log( LOG_WARN, "Tried to convert keyMap before key array initialized." );
return KI_UNKNOWN;
}
std::map< int, int >::iterator it;
it = keyMap.find( key );
if ( it != keyMap.end() )
{
return static_cast< KeyIdentifier >( it->second );
}
Com_Logf( LOG_WARN, "Rocket_FromQuake: Could not find keynum %d", key );
return KI_UNKNOWN;
}
keyNum_t Rocket_ToQuake( int key )
{
if ( !init )
{
Com_Log( LOG_WARN, "Tried to convert keyMap before key array initialized." );
return K_NONE;
}
std::map< int, int >::iterator it;
for ( it = keyMap.begin(); it != keyMap.end(); ++it )
{
if ( it->second == key )
{
return static_cast< keyNum_t>( it->first );
}
}
Com_Logf( LOG_WARN, "Rocket_ToQuake: Could not find keynum %d", key );
return K_NONE;
}
KeyModifier Rocket_GetKeyModifiers( void )
{
int mod = 0;
if ( Key_IsDown( K_CTRL ) )
{
mod |= KM_CTRL;
}
if ( Key_IsDown( K_SHIFT ) )
{
mod |= KM_SHIFT;
}
if ( Key_IsDown( K_ALT ) )
{
mod |= KM_ALT;
}
if ( Key_IsDown( K_SUPER ) )
{
mod |= KM_META;
}
if ( Key_IsDown( K_CAPSLOCK ) )
{
mod |= KM_CAPSLOCK;
}
if ( Sys_IsNumLockDown() )
{
mod |= KM_NUMLOCK;
}
return static_cast< KeyModifier >( mod );
}
void Rocket_ProcessMouseClick( int button, qboolean down )
{
if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )
{
return;
}
int idx = 0;
if ( button <= K_MOUSE5 )
{
idx = button - K_MOUSE1;
}
else
{
idx = button - K_AUX1 + 5; // Start at 5 because of K_MOUSE5
}
if ( down )
{
menuContext->ProcessMouseButtonDown( idx, Rocket_GetKeyModifiers() );
}
else
{
menuContext->ProcessMouseButtonUp( idx, Rocket_GetKeyModifiers() );
}
}
#define MOUSEWHEEL_DELTA 5
void Rocket_ProcessKeyInput( int key, qboolean down )
{
if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )
{
return;
}
// Our input system sends mouse events as key presses.
if ( ( key >= K_MOUSE1 && key <= K_MOUSE5 ) || ( key >= K_AUX1 && key <= K_AUX16 ) )
{
Rocket_ProcessMouseClick( key, down );
return;
}
if ( ( key == K_MWHEELDOWN || key == K_MWHEELUP ) )
{
// Our input system sends an up event right after a down event
// We only want to catch one of these.
if ( !down )
{
return;
}
menuContext->ProcessMouseWheel( key == K_MWHEELDOWN ? MOUSEWHEEL_DELTA : -MOUSEWHEEL_DELTA, Rocket_GetKeyModifiers() );
return;
}
if ( down )
{
menuContext->ProcessKeyDown( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );
}
else
{
menuContext->ProcessKeyUp( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );
}
}
int utf8_to_ucs2( const unsigned char *input )
{
if ( input[0] == 0 )
return -1;
if ( input[0] < 0x80 )
{
return input[0];
}
if ( ( input[0] & 0xE0 ) == 0xE0 )
{
if ( input[1] == 0 || input[2] == 0 )
return -1;
return
( input[0] & 0x0F ) << 12 |
( input[1] & 0x3F ) << 6 |
( input[2] & 0x3F );
}
if ( ( input[0] & 0xC0 ) == 0xC0 )
{
if ( input[1] == 0 )
return -1;
return
( input[0] & 0x1F ) << 6 |
( input[1] & 0x3F );
}
return -1;
}
void Rocket_ProcessTextInput( int key )
{
if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )
{
return;
}
//
// ignore any non printable chars
//
const char *s = Q_UTF8_Unstore( key );
if ( ( unsigned char )*s < 32 || ( unsigned char )*s == 0x7f )
{
return;
}
menuContext->ProcessTextInput( utf8_to_ucs2( ( unsigned char* )s ) );
}
void Rocket_MouseMove( int x, int y )
{
if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )
{
return;
}
menuContext->ProcessMouseMove( x, y, Rocket_GetKeyModifiers() );
}
<commit_msg>Don't inject input to rocket when it doesn't have focus<commit_after>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
#include <Rocket/Core.h>
#include "client.h"
#include "rocket.h"
#include "../qcommon/q_unicode.h"
using namespace Rocket::Core::Input;
static std::map< int, int > keyMap;
static bool init = false;
void Rocket_InitKeys( void )
{
keyMap[ K_TAB ] = KI_TAB;
keyMap[ K_ENTER ] = KI_RETURN;
keyMap[ K_ESCAPE ] = KI_ESCAPE;
keyMap[ K_SPACE ] = KI_SPACE;
keyMap[ K_BACKSPACE ] = KI_BACK;
keyMap[ K_COMMAND ] = KI_LWIN;
keyMap[ K_CAPSLOCK ] = KI_CAPITAL;
keyMap[ K_POWER ] = KI_POWER;
keyMap[ K_PAUSE ] = KI_PAUSE;
keyMap[ K_UPARROW ] = KI_UP;
keyMap[ K_DOWNARROW ] = KI_DOWN;
keyMap[ K_LEFTARROW ] = KI_LEFT;
keyMap[ K_RIGHTARROW ] = KI_RIGHT;
keyMap[ K_ALT ] = KI_LMETA;
keyMap[ K_CTRL ] = KI_LCONTROL;
keyMap[ K_SHIFT ] = KI_LSHIFT;
keyMap[ K_INS ] = KI_INSERT;
keyMap[ K_DEL ] = KI_DELETE;
keyMap[ K_PGDN ] = KI_NEXT;
keyMap[ K_PGUP ] = KI_PRIOR;
keyMap[ K_HOME ] = KI_HOME;
keyMap[ K_END ] = KI_END;
keyMap[ K_F1 ] = KI_F1;
keyMap[ K_F2 ] = KI_F2;
keyMap[ K_F3 ] = KI_F3;
keyMap[ K_F4 ] = KI_F4;
keyMap[ K_F5 ] = KI_F5;
keyMap[ K_F6 ] = KI_F6;
keyMap[ K_F7 ] = KI_F7;
keyMap[ K_F8 ] = KI_F8;
keyMap[ K_F9 ] = KI_F9;
keyMap[ K_F10 ] = KI_F10;
keyMap[ K_F11 ] = KI_F11;
keyMap[ K_F12 ] = KI_F12;
keyMap[ K_F13 ] = KI_F13;
keyMap[ K_F14 ] = KI_F14;
keyMap[ K_F15 ] = KI_F15;
keyMap[ K_KP_HOME ] = KI_NUMPAD7;
keyMap[ K_KP_UPARROW ] = KI_NUMPAD8;
keyMap[ K_KP_PGUP ] = KI_NUMPAD9;
keyMap[ K_KP_LEFTARROW ] = KI_NUMPAD4;
keyMap[ K_KP_5 ] = KI_NUMPAD5;
keyMap[ K_KP_RIGHTARROW ] = KI_NUMPAD6;
keyMap[ K_KP_END ] = KI_NUMPAD1;
keyMap[ K_KP_DOWNARROW ] = KI_NUMPAD2;
keyMap[ K_KP_PGDN ] = KI_NUMPAD3;
keyMap[ K_KP_ENTER ] = KI_NUMPADENTER;
keyMap[ K_KP_INS ] = KI_NUMPAD0;
keyMap[ K_KP_DEL ] = KI_DECIMAL;
keyMap[ K_KP_SLASH ] = KI_DIVIDE;
keyMap[ K_KP_MINUS ] = KI_SUBTRACT;
keyMap[ K_KP_PLUS ] = KI_ADD;
keyMap[ K_KP_NUMLOCK ] = KI_NUMLOCK;
keyMap[ K_KP_STAR ] = KI_MULTIPLY;
// keyMap[ K_KP_EQUALS ] = KI_KP_EQUALS;
keyMap[ K_SUPER ] = KI_LWIN;
// keyMap[ K_COMPOSE ] = KI_COMPOSE;
// keyMap[ K_MODE ] = KI_MODE;
keyMap[ K_HELP ] = KI_HELP;
keyMap[ K_PRINT ] = KI_PRINT;
// keyMap[ K_SYSREQ ] = KI_SYSREQ;
keyMap[ K_SCROLLOCK ] = KI_SCROLL;
// keyMap[ K_BREAK ] = KI_BREAK;
keyMap[ K_MENU ] = KI_APPS;
// keyMap[ K_EURO ] = KI_EURO;
// keyMap[ K_UNDO ] = KI_UNDO;
// Corresponds to 0 - 9
for ( int i = '0'; i < '9' + 1; ++i )
{
keyMap[ i ] = KI_0 + ( i - '0' );
}
// Corresponds to a - z
for ( int i = 'a'; i < 'z' + 1; ++i )
{
keyMap[ i ] = KI_A + ( i - 'a' );
}
// Other keyMap that out of ascii order and are handled separately
keyMap[ ';' ] = KI_OEM_1; // US standard keyboard; the ';:' key.
keyMap[ '=' ] = KI_OEM_PLUS; // Any region; the '=+' key.
keyMap[ ',' ] = KI_OEM_COMMA; // Any region; the ',<' key.
keyMap[ '-' ] = KI_OEM_MINUS; // Any region; the '-_' key.
keyMap[ '.' ] = KI_OEM_PERIOD; // Any region; the '.>' key.
keyMap[ '/' ] = KI_OEM_2; // Any region; the '/?' key.
keyMap[ '`' ] = KI_OEM_3; // Any region; the '`~' key.
keyMap[ K_CONSOLE ] = KI_OEM_3;
keyMap[ '[' ] = KI_OEM_4; // US standard keyboard; the '[{' key.
keyMap[ '\\' ] = KI_OEM_5; // US standard keyboard; the '\|' key.
keyMap[ ']' ] = KI_OEM_6; // US standard keyboard; the ']}' key.
keyMap[ '\'' ] = KI_OEM_7; // US standard keyboard; the ''"' key.
init = true;
}
KeyIdentifier Rocket_FromQuake( int key )
{
if ( !init )
{
Com_Log( LOG_WARN, "Tried to convert keyMap before key array initialized." );
return KI_UNKNOWN;
}
std::map< int, int >::iterator it;
it = keyMap.find( key );
if ( it != keyMap.end() )
{
return static_cast< KeyIdentifier >( it->second );
}
Com_Logf( LOG_WARN, "Rocket_FromQuake: Could not find keynum %d", key );
return KI_UNKNOWN;
}
keyNum_t Rocket_ToQuake( int key )
{
if ( !init )
{
Com_Log( LOG_WARN, "Tried to convert keyMap before key array initialized." );
return K_NONE;
}
std::map< int, int >::iterator it;
for ( it = keyMap.begin(); it != keyMap.end(); ++it )
{
if ( it->second == key )
{
return static_cast< keyNum_t>( it->first );
}
}
Com_Logf( LOG_WARN, "Rocket_ToQuake: Could not find keynum %d", key );
return K_NONE;
}
KeyModifier Rocket_GetKeyModifiers( void )
{
int mod = 0;
if ( Key_IsDown( K_CTRL ) )
{
mod |= KM_CTRL;
}
if ( Key_IsDown( K_SHIFT ) )
{
mod |= KM_SHIFT;
}
if ( Key_IsDown( K_ALT ) )
{
mod |= KM_ALT;
}
if ( Key_IsDown( K_SUPER ) )
{
mod |= KM_META;
}
if ( Key_IsDown( K_CAPSLOCK ) )
{
mod |= KM_CAPSLOCK;
}
if ( Sys_IsNumLockDown() )
{
mod |= KM_NUMLOCK;
}
return static_cast< KeyModifier >( mod );
}
void Rocket_ProcessMouseClick( int button, qboolean down )
{
if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )
{
return;
}
int idx = 0;
if ( button <= K_MOUSE5 )
{
idx = button - K_MOUSE1;
}
else
{
idx = button - K_AUX1 + 5; // Start at 5 because of K_MOUSE5
}
if ( down )
{
menuContext->ProcessMouseButtonDown( idx, Rocket_GetKeyModifiers() );
}
else
{
menuContext->ProcessMouseButtonUp( idx, Rocket_GetKeyModifiers() );
}
}
#define MOUSEWHEEL_DELTA 5
void Rocket_ProcessKeyInput( int key, qboolean down )
{
if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )
{
return;
}
// Our input system sends mouse events as key presses.
if ( ( key >= K_MOUSE1 && key <= K_MOUSE5 ) || ( key >= K_AUX1 && key <= K_AUX16 ) )
{
Rocket_ProcessMouseClick( key, down );
return;
}
if ( ( key == K_MWHEELDOWN || key == K_MWHEELUP ) )
{
// Our input system sends an up event right after a down event
// We only want to catch one of these.
if ( !down )
{
return;
}
menuContext->ProcessMouseWheel( key == K_MWHEELDOWN ? MOUSEWHEEL_DELTA : -MOUSEWHEEL_DELTA, Rocket_GetKeyModifiers() );
return;
}
if ( down )
{
menuContext->ProcessKeyDown( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );
}
else
{
menuContext->ProcessKeyUp( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );
}
}
int utf8_to_ucs2( const unsigned char *input )
{
if ( input[0] == 0 )
return -1;
if ( input[0] < 0x80 )
{
return input[0];
}
if ( ( input[0] & 0xE0 ) == 0xE0 )
{
if ( input[1] == 0 || input[2] == 0 )
return -1;
return
( input[0] & 0x0F ) << 12 |
( input[1] & 0x3F ) << 6 |
( input[2] & 0x3F );
}
if ( ( input[0] & 0xC0 ) == 0xC0 )
{
if ( input[1] == 0 )
return -1;
return
( input[0] & 0x1F ) << 6 |
( input[1] & 0x3F );
}
return -1;
}
void Rocket_ProcessTextInput( int key )
{
if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )
{
return;
}
//
// ignore any non printable chars
//
const char *s = Q_UTF8_Unstore( key );
if ( ( unsigned char )*s < 32 || ( unsigned char )*s == 0x7f )
{
return;
}
menuContext->ProcessTextInput( utf8_to_ucs2( ( unsigned char* )s ) );
}
void Rocket_MouseMove( int x, int y )
{
if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )
{
return;
}
menuContext->ProcessMouseMove( x, y, Rocket_GetKeyModifiers() );
}
<|endoftext|> |
<commit_before>//
// Copyright Silvin Lubecki 2010
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef OPENCLAM_FOR_EACH_HPP_INCLUDED
#define OPENCLAM_FOR_EACH_HPP_INCLUDED
#include "kernel.hpp"
#include <memory>
namespace openclam
{
namespace detail
{
template< class RandomAccessIterator, class Kernel >
void for_each_dispatch( RandomAccessIterator& first, RandomAccessIterator& last, Kernel& k, std::random_access_iterator_tag )
{
k( &*first, std::distance( first, last ) );
}
template< class InputIterator, class Kernel >
void for_each_dispatch( InputIterator& first, InputIterator& last, Kernel& k, std::input_iterator_tag )
{
std::vector< InputIterator::value_type* > data_references;
std::vector< InputIterator::value_type > data;
for( ; first != last; ++first )
{
data.push_back( *first );
data_references.push_back( &*first );
}
k( &data[ 0 ], data.size() );
for( unsigned int i = 0; i < data.size(); ++i )
*data_references[ i ] = data[ i ];
}
}
template< class InputIterator, class Kernel >
void for_each( InputIterator first, InputIterator last, Kernel& k )
{
typename std::iterator_traits< InputIterator >::iterator_category category;
detail::for_each_dispatch( first, last, k, category );
}
}
#endif // #ifndef OPENCLAM_CONTEXT_HPP_INCLUDED
<commit_msg>clean up<commit_after>//
// Copyright Silvin Lubecki 2010
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef OPENCLAM_FOR_EACH_HPP_INCLUDED
#define OPENCLAM_FOR_EACH_HPP_INCLUDED
#include <memory>
namespace openclam
{
namespace detail
{
template< class RandomAccessIterator, class Kernel >
void for_each_dispatch( RandomAccessIterator& first, RandomAccessIterator& last, Kernel& k, std::random_access_iterator_tag )
{
k( &*first, std::distance( first, last ) );
}
template< class InputIterator, class Kernel >
void for_each_dispatch( InputIterator& first, InputIterator& last, Kernel& k, std::input_iterator_tag )
{
std::vector< InputIterator::value_type* > data_references;
std::vector< InputIterator::value_type > data;
for( ; first != last; ++first )
{
data.push_back( *first );
data_references.push_back( &*first );
}
k( &data[ 0 ], data.size() );
for( unsigned int i = 0; i < data.size(); ++i )
*data_references[ i ] = data[ i ];
}
}
template< class InputIterator, class Kernel >
void for_each( InputIterator first, InputIterator last, Kernel& k )
{
typename std::iterator_traits< InputIterator >::iterator_category category;
detail::for_each_dispatch( first, last, k, category );
}
}
#endif // #ifndef OPENCLAM_CONTEXT_HPP_INCLUDED
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.io>
* - Laura Schlimmer <laura@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/sql/qtree/JoinNode.h>
#include <eventql/sql/qtree/ColumnReferenceNode.h>
#include <eventql/sql/qtree/QueryTreeUtil.h>
#include "eventql/eventql.h"
namespace csql {
JoinNode::JoinNode(
JoinType join_type,
RefPtr<QueryTreeNode> base_table,
RefPtr<QueryTreeNode> joined_table) :
join_type_(join_type),
base_table_(base_table),
joined_table_(joined_table) {
addChild(&base_table_);
addChild(&joined_table_);
}
JoinNode::JoinNode(
JoinType join_type,
RefPtr<QueryTreeNode> base_table,
RefPtr<QueryTreeNode> joined_table,
Vector<RefPtr<SelectListNode>> select_list,
Option<RefPtr<ValueExpressionNode>> where_expr,
Option<RefPtr<ValueExpressionNode>> join_cond) :
join_type_(join_type),
base_table_(base_table),
joined_table_(joined_table),
select_list_(select_list),
where_expr_(where_expr),
join_cond_(join_cond) {
for (const auto& sl : select_list_) {
column_names_.emplace_back(sl->columnName());
}
addChild(&base_table_);
addChild(&joined_table_);
}
JoinNode::JoinNode(
const JoinNode& other) :
join_type_(other.join_type_),
base_table_(other.base_table_->deepCopy()),
joined_table_(other.joined_table_->deepCopy()),
input_map_(other.input_map_),
column_names_(other.column_names_),
join_cond_(other.join_cond_) {
for (const auto& e : other.select_list_) {
select_list_.emplace_back(e->deepCopyAs<SelectListNode>());
}
if (!other.where_expr_.isEmpty()) {
where_expr_ = Some(
other.where_expr_.get()->deepCopyAs<ValueExpressionNode>());
}
addChild(&base_table_);
addChild(&joined_table_);
}
JoinType JoinNode::joinType() const {
return join_type_;
}
RefPtr<QueryTreeNode> JoinNode::baseTable() const {
return base_table_;
}
RefPtr<QueryTreeNode> JoinNode::joinedTable() const {
return joined_table_;
}
Vector<RefPtr<SelectListNode>> JoinNode::selectList() const {
return select_list_;
}
Vector<String> JoinNode::getResultColumns() const {
return column_names_;
}
Vector<QualifiedColumn> JoinNode::getAvailableColumns() const {
Vector<QualifiedColumn> cols;
for (const auto& c :
base_table_.asInstanceOf<TableExpressionNode>()->getAvailableColumns()) {
cols.emplace_back(c);
}
for (const auto& c :
joined_table_.asInstanceOf<TableExpressionNode>()->getAvailableColumns()) {
cols.emplace_back(c);
}
return cols;
}
size_t JoinNode::getComputedColumnIndex(
const String& column_name,
bool allow_add /* = false */) {
for (int i = 0; i < column_names_.size(); ++i) {
if (column_names_[i] == column_name) {
return i;
}
}
auto input_idx = getInputColumnIndex(column_name);
if (input_idx != size_t(-1)) {
auto slnode = new SelectListNode(
new ColumnReferenceNode(input_idx, getInputColumnType(input_idx)));
slnode->setAlias(column_name);
select_list_.emplace_back(slnode);
return select_list_.size() - 1;
}
return -1; // FIXME
}
size_t JoinNode::getNumComputedColumns() const {
return select_list_.size();
}
SType JoinNode::getColumnType(size_t idx) const {
assert(idx < select_list_.size());
return select_list_[idx]->expression()->getReturnType();
}
size_t JoinNode::getInputColumnIndex(
const String& column_name,
bool allow_add /* = false */) {
for (int i = 0; i < input_map_.size(); ++i) {
if (input_map_[i].column == column_name) {
return i;
}
}
auto base_table_idx = base_table_
.asInstanceOf<TableExpressionNode>()
->getComputedColumnIndex(column_name, allow_add);
auto joined_table_idx = joined_table_
.asInstanceOf<TableExpressionNode>()
->getComputedColumnIndex(column_name, allow_add);
if (base_table_idx != size_t(-1) && joined_table_idx != size_t(-1)) {
RAISEF(
kRuntimeError,
"ambiguous column reference: '$0'",
column_name);
}
if (base_table_idx != size_t(-1)) {
input_map_.emplace_back(InputColumnRef{
.column = column_name,
.table_idx = 0,
.column_idx = base_table_idx
});
return input_map_.size() - 1;
}
if (joined_table_idx != size_t(-1)) {
input_map_.emplace_back(InputColumnRef{
.column = column_name,
.table_idx = 1,
.column_idx = joined_table_idx
});
return input_map_.size() - 1;
}
return -1;
}
Option<RefPtr<ValueExpressionNode>> JoinNode::whereExpression() const {
return where_expr_;
}
Option<RefPtr<ValueExpressionNode>> JoinNode::joinCondition() const {
return join_cond_;
}
RefPtr<QueryTreeNode> JoinNode::deepCopy() const {
return new JoinNode(*this);
}
const Vector<JoinNode::InputColumnRef>& JoinNode::inputColumnMap() const {
return input_map_;
}
String JoinNode::toString() const {
auto str = StringUtil::format(
"(join (base-table $0) (joined-table $0) (select-list",
base_table_->toString(),
joined_table_->toString());
for (const auto& e : select_list_) {
str += " " + e->toString();
}
str += ")";
if (!where_expr_.isEmpty()) {
str += StringUtil::format(" (where $0)", where_expr_.get()->toString());
}
if (!join_cond_.isEmpty()) {
str += StringUtil::format(" (join-cond $0)", join_cond_.get()->toString());
}
str += ")";
return str;
};
void JoinNode::encode(
QueryTreeCoder* coder,
const JoinNode& node,
OutputStream* os) {
os->appendUInt8((uint8_t) node.join_type_);
os->appendVarUInt(node.select_list_.size());
for (const auto& e : node.select_list_) {
coder->encode(e.get(), os);
}
uint8_t flags = 0;
if (!node.where_expr_.isEmpty()) {
flags |= kHasWhereExprFlag;
}
if (!node.join_cond_.isEmpty()) {
flags |= kHasJoinExprFlag;
}
os->appendUInt8(flags);
if (!node.where_expr_.isEmpty()) {
coder->encode(node.where_expr_.get().get(), os);
}
if (!node.join_cond_.isEmpty()) {
coder->encode(node.join_cond_.get().get(), os);
}
coder->encode(node.base_table_.get(), os);
coder->encode(node.joined_table_.get(), os);
}
RefPtr<QueryTreeNode> JoinNode::decode (
QueryTreeCoder* coder,
InputStream* is) {
auto join_type = (JoinType) is->readUInt8();
Vector<RefPtr<SelectListNode>> select_list;
auto select_list_size = is->readVarUInt();
for (auto i = 0; i < select_list_size; ++i) {
select_list.emplace_back(coder->decode(is).asInstanceOf<SelectListNode>());
}
Option<RefPtr<ValueExpressionNode>> where_expr;
Option<RefPtr<ValueExpressionNode>> join_cond;
auto flags = is->readUInt8();
if ((flags & kHasWhereExprFlag) > 0) {
where_expr = coder->decode(is).asInstanceOf<ValueExpressionNode>();
}
if ((flags & kHasJoinExprFlag) > 0) {
join_cond = coder->decode(is).asInstanceOf<ValueExpressionNode>();
}
auto base_tbl = coder->decode(is);
auto joined_tbl = coder->decode(is);
return new JoinNode(
join_type,
base_tbl,
joined_tbl,
select_list,
where_expr,
join_cond);
}
} // namespace csql
<commit_msg>implement new JoinNode methods<commit_after>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.io>
* - Laura Schlimmer <laura@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/sql/qtree/JoinNode.h>
#include <eventql/sql/qtree/ColumnReferenceNode.h>
#include <eventql/sql/qtree/QueryTreeUtil.h>
#include "eventql/eventql.h"
namespace csql {
JoinNode::JoinNode(
JoinType join_type,
RefPtr<QueryTreeNode> base_table,
RefPtr<QueryTreeNode> joined_table) :
join_type_(join_type),
base_table_(base_table),
joined_table_(joined_table) {
addChild(&base_table_);
addChild(&joined_table_);
}
JoinNode::JoinNode(
JoinType join_type,
RefPtr<QueryTreeNode> base_table,
RefPtr<QueryTreeNode> joined_table,
Vector<RefPtr<SelectListNode>> select_list,
Option<RefPtr<ValueExpressionNode>> where_expr,
Option<RefPtr<ValueExpressionNode>> join_cond) :
join_type_(join_type),
base_table_(base_table),
joined_table_(joined_table),
select_list_(select_list),
where_expr_(where_expr),
join_cond_(join_cond) {
for (const auto& sl : select_list_) {
column_names_.emplace_back(sl->columnName());
}
addChild(&base_table_);
addChild(&joined_table_);
}
JoinNode::JoinNode(
const JoinNode& other) :
join_type_(other.join_type_),
base_table_(other.base_table_->deepCopy()),
joined_table_(other.joined_table_->deepCopy()),
input_map_(other.input_map_),
column_names_(other.column_names_),
join_cond_(other.join_cond_) {
for (const auto& e : other.select_list_) {
select_list_.emplace_back(e->deepCopyAs<SelectListNode>());
}
if (!other.where_expr_.isEmpty()) {
where_expr_ = Some(
other.where_expr_.get()->deepCopyAs<ValueExpressionNode>());
}
addChild(&base_table_);
addChild(&joined_table_);
}
JoinType JoinNode::joinType() const {
return join_type_;
}
void JoinNode::setJoinType(JoinType type) {
join_type_ = type;
}
RefPtr<QueryTreeNode> JoinNode::baseTable() const {
return base_table_;
}
RefPtr<QueryTreeNode> JoinNode::joinedTable() const {
return joined_table_;
}
Vector<RefPtr<SelectListNode>> JoinNode::selectList() const {
return select_list_;
}
void JoinNode::addSelectList(RefPtr<SelectListNode> sl) {
column_names_.emplace_back(sl->columnName());
select_list_.emplace_back(sl);
}
Vector<String> JoinNode::getResultColumns() const {
return column_names_;
}
Vector<QualifiedColumn> JoinNode::getAvailableColumns() const {
Vector<QualifiedColumn> cols;
for (const auto& c :
base_table_.asInstanceOf<TableExpressionNode>()->getAvailableColumns()) {
cols.emplace_back(c);
}
for (const auto& c :
joined_table_.asInstanceOf<TableExpressionNode>()->getAvailableColumns()) {
cols.emplace_back(c);
}
return cols;
}
size_t JoinNode::getComputedColumnIndex(
const String& column_name,
bool allow_add /* = false */) {
for (int i = 0; i < column_names_.size(); ++i) {
if (column_names_[i] == column_name) {
return i;
}
}
auto input_idx = getInputColumnIndex(column_name);
if (input_idx != size_t(-1)) {
auto slnode = new SelectListNode(
new ColumnReferenceNode(input_idx, getInputColumnType(input_idx)));
slnode->setAlias(column_name);
select_list_.emplace_back(slnode);
return select_list_.size() - 1;
}
return -1; // FIXME
}
size_t JoinNode::getNumComputedColumns() const {
return select_list_.size();
}
SType JoinNode::getColumnType(size_t idx) const {
assert(idx < select_list_.size());
return select_list_[idx]->expression()->getReturnType();
}
size_t JoinNode::getInputColumnIndex(
const String& column_name,
bool allow_add /* = false */) {
for (int i = 0; i < input_map_.size(); ++i) {
if (input_map_[i].column == column_name) {
return i;
}
}
auto base_table_idx = base_table_
.asInstanceOf<TableExpressionNode>()
->getComputedColumnIndex(column_name, allow_add);
auto joined_table_idx = joined_table_
.asInstanceOf<TableExpressionNode>()
->getComputedColumnIndex(column_name, allow_add);
if (base_table_idx != size_t(-1) && joined_table_idx != size_t(-1)) {
RAISEF(
kRuntimeError,
"ambiguous column reference: '$0'",
column_name);
}
if (base_table_idx != size_t(-1)) {
input_map_.emplace_back(InputColumnRef{
.column = column_name,
.table_idx = 0,
.column_idx = base_table_idx
});
return input_map_.size() - 1;
}
if (joined_table_idx != size_t(-1)) {
input_map_.emplace_back(InputColumnRef{
.column = column_name,
.table_idx = 1,
.column_idx = joined_table_idx
});
return input_map_.size() - 1;
}
return -1;
}
SType JoinNode::getInputColumnType(size_t idx) const {
if (idx >= input_map_.size()) {
RAISEF(
kRuntimeError,
"invalid column index: '$0'",
idx);
}
switch (input_map_[idx].table_idx) {
case 0:
return base_table_.asInstanceOf<TableExpressionNode>()->getColumnType(
input_map_[idx].column_idx);
case 1:
return joined_table_.asInstanceOf<TableExpressionNode>()->getColumnType(
input_map_[idx].column_idx);
default:
return SType::NIL;
}
}
std::pair<size_t, SType> JoinNode::getInputColumnInfo(
const String& column_name,
bool allow_add) {
auto idx = getInputColumnIndex(column_name, allow_add);
if (idx == size_t(-1)) {
return std::make_pair(idx, SType::NIL);
} else {
return std::make_pair(idx, getInputColumnType(idx));
}
}
Option<RefPtr<ValueExpressionNode>> JoinNode::whereExpression() const {
return where_expr_;
}
void JoinNode::setWhereExpression(RefPtr<ValueExpressionNode> expr) {
where_expr_ = Some(expr);
}
Option<RefPtr<ValueExpressionNode>> JoinNode::joinCondition() const {
return join_cond_;
}
void JoinNode::setJoinCondition(RefPtr<ValueExpressionNode> expr) {
join_cond_ = Some(expr);
}
RefPtr<QueryTreeNode> JoinNode::deepCopy() const {
return new JoinNode(*this);
}
const Vector<JoinNode::InputColumnRef>& JoinNode::inputColumnMap() const {
return input_map_;
}
String JoinNode::toString() const {
auto str = StringUtil::format(
"(join (base-table $0) (joined-table $0) (select-list",
base_table_->toString(),
joined_table_->toString());
for (const auto& e : select_list_) {
str += " " + e->toString();
}
str += ")";
if (!where_expr_.isEmpty()) {
str += StringUtil::format(" (where $0)", where_expr_.get()->toString());
}
if (!join_cond_.isEmpty()) {
str += StringUtil::format(" (join-cond $0)", join_cond_.get()->toString());
}
str += ")";
return str;
};
void JoinNode::encode(
QueryTreeCoder* coder,
const JoinNode& node,
OutputStream* os) {
os->appendUInt8((uint8_t) node.join_type_);
os->appendVarUInt(node.select_list_.size());
for (const auto& e : node.select_list_) {
coder->encode(e.get(), os);
}
uint8_t flags = 0;
if (!node.where_expr_.isEmpty()) {
flags |= kHasWhereExprFlag;
}
if (!node.join_cond_.isEmpty()) {
flags |= kHasJoinExprFlag;
}
os->appendUInt8(flags);
if (!node.where_expr_.isEmpty()) {
coder->encode(node.where_expr_.get().get(), os);
}
if (!node.join_cond_.isEmpty()) {
coder->encode(node.join_cond_.get().get(), os);
}
coder->encode(node.base_table_.get(), os);
coder->encode(node.joined_table_.get(), os);
}
RefPtr<QueryTreeNode> JoinNode::decode (
QueryTreeCoder* coder,
InputStream* is) {
auto join_type = (JoinType) is->readUInt8();
Vector<RefPtr<SelectListNode>> select_list;
auto select_list_size = is->readVarUInt();
for (auto i = 0; i < select_list_size; ++i) {
select_list.emplace_back(coder->decode(is).asInstanceOf<SelectListNode>());
}
Option<RefPtr<ValueExpressionNode>> where_expr;
Option<RefPtr<ValueExpressionNode>> join_cond;
auto flags = is->readUInt8();
if ((flags & kHasWhereExprFlag) > 0) {
where_expr = coder->decode(is).asInstanceOf<ValueExpressionNode>();
}
if ((flags & kHasJoinExprFlag) > 0) {
join_cond = coder->decode(is).asInstanceOf<ValueExpressionNode>();
}
auto base_tbl = coder->decode(is);
auto joined_tbl = coder->decode(is);
return new JoinNode(
join_type,
base_tbl,
joined_tbl,
select_list,
where_expr,
join_cond);
}
} // namespace csql
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <cassert>
#include <boost/shared_ptr.hpp>
#include "gen-cpp/DataHub.h"
#include <thrift/transport/THttpClient.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>
/**
* Sample DataHub C++ Client
*
* @author anantb
* @author stephentu
* @date 11/07/2013
*
*/
using namespace std;
using namespace boost;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace datahub;
int main () {
try {
shared_ptr<THttpClient> transport(new THttpClient("datahub.csail.mit.edu", 80, "/service"));
shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
DataHubClient client(protocol);
transport->open();
double version = client.get_version();
cout << version << endl;
ConnectionParams params = ConnectionParams();
params.__set_user("anantb");
params.__set_password("anant");
Connection conn;
client.open_connection(conn, params);
ResultSet res;
client.execute_sql(
res, conn, "select * from anantb.test.demo", vector<string>());
for(vector<Tuple>::const_iterator tuple_it = res.tuples.begin();
tuple_it != res.tuples.end();
++tuple_it) {
for(vector<string>::const_iterator cell_it = (*tuple_it).cells.begin();
cell_it != (*tuple_it).cells.end();
++cell_it) {
cout << *cell_it << "\t";
}
cout << std::endl;
}
transport->close();
} catch (TException &tx) {
cout << "ERROR: " << tx.what();
}
return 0;
}
<commit_msg>cpp sample<commit_after>#include <unistd.h>
#include <cassert>
#include <boost/shared_ptr.hpp>
#include "gen-cpp/DataHub.h"
#include <thrift/transport/THttpClient.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>
/**
* Sample DataHub C++ Client
*
* @author anantb
* @author stephentu
* @date 11/07/2013
*
*/
using namespace std;
using namespace boost;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace datahub;
int main () {
try {
shared_ptr<THttpClient> transport(
new THttpClient("datahub.csail.mit.edu", 80, "/service"));
shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
DataHubClient client(protocol);
transport->open();
double version = client.get_version();
cout << "Version: " << version << endl;
ConnectionParams params = ConnectionParams();
params.__set_user("anantb");
params.__set_password("anant");
Connection conn;
client.open_connection(conn, params);
ResultSet res;
client.execute_sql(
res, conn, "select * from anantb.test.demo", vector<string>());
// print field names
for(vector<string>::const_iterator field_it = res.field_names.begin();
field_it != res.field_names.end();
++field_it) {
cout << *field_it << "\t";
}
// print tuple values
for(vector<Tuple>::const_iterator tuple_it = res.tuples.begin();
tuple_it != res.tuples.end();
++tuple_it) {
for(vector<string>::const_iterator cell_it = (*tuple_it).cells.begin();
cell_it != (*tuple_it).cells.end();
++cell_it) {
cout << *cell_it << "\t";
}
cout << std::endl;
}
transport->close();
} catch (TException &tx) {
cout << "ERROR: " << tx.what();
}
return 0;
}
<|endoftext|> |
<commit_before>#include "MatrixSlicingTest.h"
#include <matrix/Matrix.h>
#include <matrix/MatrixHelper.h>
#include <matrix/MatrixSlice.h>
#include <algorithm>
#include <cstddef>
const size_t ROWS = 910;
const size_t COLS = 735;
const size_t NODE_COUNTS[] = { 3, 1, 2, 3, 5, 7, 12, 25, 80, 110 };
typedef Matrix<float> TestGrid;
using namespace std;
typedef MatrixSlicer::SliceList SliceList;
ostream& operator<<(ostream& stream, const MatrixSlice& slice)
{
return stream
<< "("
<< slice.getStartX() << ", "
<< slice.getStartY() << ", "
<< slice.getColumns() << ", "
<< slice.getRows() << ")";
}
ostream& operator<<(ostream& stream, const SliceList& slices)
{
stream << "[";
bool first = true;
for (const auto& slice : slices)
{
if (!first)
stream << ", ";
stream << slice;
first = false;
}
stream << "]";
return stream;
}
BenchmarkResult makeUniformRatings(size_t number)
{
BenchmarkResult ratings;
for (size_t i=0; i<number; ++i)
{
ratings[i] = 100/number;
}
return ratings;
}
TestGrid setupTestGrid(size_t rows, size_t cols)
{
TestGrid testGrid(rows, cols);
MatrixHelper::fill(testGrid, [](){ return 0.0f; });
return testGrid;
}
string makeErrorMsg(size_t nodeCount, const MatrixSlice& slice)
{
stringstream errorMsg;
errorMsg
<< " out of bounds. Nodes: "
<< nodeCount << ", Slice: " << slice;
return errorMsg.str();
}
void applySliceToTestGrid(const MatrixSlice& slice, TestGrid* grid, size_t nodeCount)
{
for (size_t i=0; i<slice.getRows(); ++i)
{
for (size_t j=0; j<slice.getColumns(); ++j)
{
auto row = i + slice.getStartY();
auto col = j + slice.getStartX();
ASSERT_LT(row, grid->rows()) << "Row" << makeErrorMsg(nodeCount, slice);
ASSERT_LT(col, grid->columns()) << "Column" << makeErrorMsg(nodeCount, slice);
(*grid)(row, col) += 1.0f;
}
}
}
TestGrid fillTestGrid(size_t rows, size_t cols, const SliceList& slices, const BenchmarkResult& ratings)
{
TestGrid testGrid = setupTestGrid(rows, cols);
for (const MatrixSlice& slice : slices)
{
applySliceToTestGrid(slice, &testGrid, ratings.size());
if (testing::Test::HasFatalFailure()) break;
}
return testGrid;
}
TestGrid makeTestGrid(size_t nodeCount, const MatrixSlicer& slicer)
{
auto ratings = makeUniformRatings(nodeCount);
auto slices = slicer.sliceAndDice(ratings, ROWS, COLS);
return fillTestGrid(ROWS, COLS, slices, ratings);
}
void checkTestGrid(const TestGrid& testGrid, const SliceList& slices)
{
for(size_t i=0; i<ROWS; ++i)
{
for (size_t j=0; j<COLS; ++j)
{
ASSERT_GT(testGrid(i, j), 0.0f)
<< "Slices incomplete at (" << i
<< ", " << j << "). Slices: " << slices;
ASSERT_LT(testGrid(i, j), 2.0f)
<< "Slices overlap at (" << i
<< ", " << j << "). Slices: " << slices;
}
}
}
TEST_F(MatrixSlicingTest, SingleNodeKeepsWholeMatrixTest)
{
auto slices = slicer.sliceAndDice({{0, 0}}, ROWS, COLS);
ASSERT_EQ(slices.size(), (size_t)1);
auto slice = slices[0];
EXPECT_EQ(slice.getStartX(), (size_t)0);
EXPECT_EQ(slice.getStartY(), (size_t)0);
EXPECT_EQ(slice.getRows(), ROWS);
EXPECT_EQ(slice.getColumns(), COLS);
}
TEST_F(MatrixSlicingTest, OneSlicePerNodeTest)
{
for (size_t count : NODE_COUNTS)
{
auto slices = slicer.sliceAndDice(makeUniformRatings(count), ROWS, COLS);
EXPECT_EQ(slices.size(), count);
}
}
TEST_F(MatrixSlicingTest, ValidSlicesTest)
{
for (size_t count : NODE_COUNTS)
{
auto ratings = makeUniformRatings(count);
auto slices = slicer.sliceAndDice(ratings, ROWS, COLS);
TestGrid testGrid = fillTestGrid(ROWS, COLS, slices, ratings);
if (HasFatalFailure()) return;
checkTestGrid(testGrid, slices);
if (HasFatalFailure()) return;
}
}
<commit_msg>Removed bogus node count from NODE_COUNTS<commit_after>#include "MatrixSlicingTest.h"
#include <matrix/Matrix.h>
#include <matrix/MatrixHelper.h>
#include <matrix/MatrixSlice.h>
#include <algorithm>
#include <cstddef>
const size_t ROWS = 910;
const size_t COLS = 735;
const size_t NODE_COUNTS[] = { 1, 2, 3, 5, 7, 12, 25, 80, 110, 127 };
typedef Matrix<float> TestGrid;
using namespace std;
typedef MatrixSlicer::SliceList SliceList;
ostream& operator<<(ostream& stream, const MatrixSlice& slice)
{
return stream
<< "("
<< slice.getStartX() << ", "
<< slice.getStartY() << ", "
<< slice.getColumns() << ", "
<< slice.getRows() << ")";
}
ostream& operator<<(ostream& stream, const SliceList& slices)
{
stream << "[";
bool first = true;
for (const auto& slice : slices)
{
if (!first)
stream << ", ";
stream << slice;
first = false;
}
stream << "]";
return stream;
}
BenchmarkResult makeUniformRatings(size_t number)
{
BenchmarkResult ratings;
for (size_t i=0; i<number; ++i)
{
ratings[i] = 100/number;
}
return ratings;
}
TestGrid setupTestGrid(size_t rows, size_t cols)
{
TestGrid testGrid(rows, cols);
MatrixHelper::fill(testGrid, [](){ return 0.0f; });
return testGrid;
}
string makeErrorMsg(size_t nodeCount, const MatrixSlice& slice)
{
stringstream errorMsg;
errorMsg
<< " out of bounds. Nodes: "
<< nodeCount << ", Slice: " << slice;
return errorMsg.str();
}
void applySliceToTestGrid(const MatrixSlice& slice, TestGrid* grid, size_t nodeCount)
{
for (size_t i=0; i<slice.getRows(); ++i)
{
for (size_t j=0; j<slice.getColumns(); ++j)
{
auto row = i + slice.getStartY();
auto col = j + slice.getStartX();
ASSERT_LT(row, grid->rows()) << "Row" << makeErrorMsg(nodeCount, slice);
ASSERT_LT(col, grid->columns()) << "Column" << makeErrorMsg(nodeCount, slice);
(*grid)(row, col) += 1.0f;
}
}
}
TestGrid fillTestGrid(size_t rows, size_t cols, const SliceList& slices, const BenchmarkResult& ratings)
{
TestGrid testGrid = setupTestGrid(rows, cols);
for (const MatrixSlice& slice : slices)
{
applySliceToTestGrid(slice, &testGrid, ratings.size());
if (testing::Test::HasFatalFailure()) break;
}
return testGrid;
}
TestGrid makeTestGrid(size_t nodeCount, const MatrixSlicer& slicer)
{
auto ratings = makeUniformRatings(nodeCount);
auto slices = slicer.sliceAndDice(ratings, ROWS, COLS);
return fillTestGrid(ROWS, COLS, slices, ratings);
}
void checkTestGrid(const TestGrid& testGrid, const SliceList& slices)
{
for(size_t i=0; i<ROWS; ++i)
{
for (size_t j=0; j<COLS; ++j)
{
ASSERT_GT(testGrid(i, j), 0.0f)
<< "Slices incomplete at (" << i
<< ", " << j << "). Slices: " << slices;
ASSERT_LT(testGrid(i, j), 2.0f)
<< "Slices overlap at (" << i
<< ", " << j << "). Slices: " << slices;
}
}
}
TEST_F(MatrixSlicingTest, SingleNodeKeepsWholeMatrixTest)
{
auto slices = slicer.sliceAndDice({{0, 0}}, ROWS, COLS);
ASSERT_EQ(slices.size(), (size_t)1);
auto slice = slices[0];
EXPECT_EQ(slice.getStartX(), (size_t)0);
EXPECT_EQ(slice.getStartY(), (size_t)0);
EXPECT_EQ(slice.getRows(), ROWS);
EXPECT_EQ(slice.getColumns(), COLS);
}
TEST_F(MatrixSlicingTest, OneSlicePerNodeTest)
{
for (size_t count : NODE_COUNTS)
{
auto slices = slicer.sliceAndDice(makeUniformRatings(count), ROWS, COLS);
EXPECT_EQ(slices.size(), count);
}
}
TEST_F(MatrixSlicingTest, ValidSlicesTest)
{
for (size_t count : NODE_COUNTS)
{
auto ratings = makeUniformRatings(count);
auto slices = slicer.sliceAndDice(ratings, ROWS, COLS);
TestGrid testGrid = fillTestGrid(ROWS, COLS, slices, ratings);
if (HasFatalFailure()) return;
checkTestGrid(testGrid, slices);
if (HasFatalFailure()) return;
}
}
<|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 "liblocationwrapper_p.h"
using namespace std;
QTM_BEGIN_NAMESPACE
Q_GLOBAL_STATIC(LiblocationWrapper, LocationEngine)
LiblocationWrapper *LiblocationWrapper::instance()
{
return LocationEngine();
}
LiblocationWrapper::~LiblocationWrapper()
{
if (locationDevice)
g_object_unref(locationDevice);
if (locationControl)
g_object_unref(locationControl);
}
bool LiblocationWrapper::inited()
{
int retval = false;
if (!(locationState & LiblocationWrapper::Inited)) {
g_type_init();
locationControl = location_gpsd_control_get_default();
if (locationControl) {
g_object_set(G_OBJECT(locationControl),
"preferred-method", LOCATION_METHOD_USER_SELECTED,
"preferred-interval", LOCATION_INTERVAL_1S,
NULL);
locationDevice =
(LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE,
NULL);
if (locationDevice) {
errorHandlerId =
g_signal_connect(G_OBJECT(locationControl), "error-verbose",
G_CALLBACK(&locationError),
static_cast<void*>(this));
posChangedId =
g_signal_connect(G_OBJECT(locationDevice), "changed",
G_CALLBACK(&locationChanged),
static_cast<void*>(this));
locationState = LiblocationWrapper::Inited;
retval = true;
startcounter = 0;
}
}
} else {
retval = true;
}
return retval;
}
void LiblocationWrapper::locationError(LocationGPSDevice *device,
gint errorCode, gpointer data)
{
Q_UNUSED(device);
QString locationError;
switch (errorCode) {
case LOCATION_ERROR_USER_REJECTED_DIALOG:
locationError = "User didn't enable requested methods";
break;
case LOCATION_ERROR_USER_REJECTED_SETTINGS:
locationError = "User changed settings, which disabled location.";
break;
case LOCATION_ERROR_BT_GPS_NOT_AVAILABLE:
locationError = "Problems with BT GPS";
break;
case LOCATION_ERROR_METHOD_NOT_ALLOWED_IN_OFFLINE_MODE:
locationError = "Requested method is not allowed in offline mode";
break;
case LOCATION_ERROR_SYSTEM:
locationError = "System error.";
break;
default:
locationError = "Unknown error.";
}
qDebug() << "Location error:" << locationError;
LiblocationWrapper *object;
object = (LiblocationWrapper *)data;
emit object->error();
}
void LiblocationWrapper::locationChanged(LocationGPSDevice *device,
gpointer data)
{
QGeoPositionInfo posInfo;
QGeoCoordinate coordinate;
QGeoSatelliteInfo satInfo;
int satellitesInUseCount = 0;
LiblocationWrapper *object;
if (!data || !device) {
return;
}
object = (LiblocationWrapper *)data;
if (device) {
if (device->fix) {
if (device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) {
posInfo.setTimestamp(QDateTime::fromTime_t(device->fix->time));
}
if (device->fix->fields & LOCATION_GPS_DEVICE_LATLONG_SET) {
coordinate.setLatitude(device->fix->latitude);
coordinate.setLongitude(device->fix->longitude);
posInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy,
device->fix->eph);
posInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy,
device->fix->epv);
}
if (device->fix->fields & LOCATION_GPS_DEVICE_ALTITUDE_SET) {
coordinate.setAltitude(device->fix->altitude);
}
if (device->fix->fields & LOCATION_GPS_DEVICE_SPEED_SET) {
posInfo.setAttribute(QGeoPositionInfo::GroundSpeed,
device->fix->speed);
}
if (device->fix->fields & LOCATION_GPS_DEVICE_CLIMB_SET) {
posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed,
device->fix->climb);
}
if (device->fix->fields & LOCATION_GPS_DEVICE_TRACK_SET) {
posInfo.setAttribute(QGeoPositionInfo::Direction,
device->fix->track);
}
}
if (device->satellites_in_view) {
QList<QGeoSatelliteInfo> satsInView;
QList<QGeoSatelliteInfo> satsInUse;
unsigned int i;
for (i=0;i<device->satellites->len;i++) {
LocationGPSDeviceSatellite *satData =
(LocationGPSDeviceSatellite *)g_ptr_array_index(device->satellites,
i);
satInfo.setSignalStrength(satData->signal_strength);
satInfo.setPrnNumber(satData->prn);
satInfo.setAttribute(QGeoSatelliteInfo::Elevation,
satData->elevation);
satInfo.setAttribute(QGeoSatelliteInfo::Azimuth,
satData->azimuth);
satsInView.append(satInfo);
if (satData->in_use) {
satellitesInUseCount++;
satsInUse.append(satInfo);
}
}
if (!satsInView.isEmpty())
object->satellitesInViewUpdated(satsInView);
if (!satsInUse.isEmpty())
object->satellitesInUseUpdated(satsInUse);
}
}
posInfo.setCoordinate(coordinate);
if ((device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) &&
((device->fix->mode == LOCATION_GPS_DEVICE_MODE_3D) ||
(device->fix->mode == LOCATION_GPS_DEVICE_MODE_2D))) {
object->setLocation(posInfo, true);
} else {
object->setLocation(posInfo, false);
}
}
void LiblocationWrapper::setLocation(const QGeoPositionInfo &update,
bool locationValid)
{
validLastSatUpdate = locationValid;
lastSatUpdate = update;
}
QGeoPositionInfo LiblocationWrapper::position() {
return lastSatUpdate;
}
bool LiblocationWrapper::fixIsValid()
{
return validLastSatUpdate;
}
QGeoPositionInfo LiblocationWrapper::lastKnownPosition(bool fromSatellitePositioningMethodsOnly) const
{
QGeoPositionInfo posInfo;
QGeoCoordinate coordinate;
double time;
double latitude;
double longitude;
double altitude;
double speed;
double track;
double climb;
GConfItem lastKnownPositionTime("/system/nokia/location/lastknown/time");
GConfItem lastKnownPositionLatitude("/system/nokia/location/lastknown/latitude");
GConfItem lastKnownPositionLongitude("/system/nokia/location/lastknown/longitude");
GConfItem lastKnownPositionAltitude("/system/nokia/location/lastknown/altitude");
GConfItem lastKnownPositionSpeed("/system/nokia/location/lastknown/speed");
GConfItem lastKnownPositionTrack("/system/nokia/location/lastknown/track");
GConfItem lastKnownPositionClimb("/system/nokia/location/lastknown/climb");
if (validLastSatUpdate)
return lastSatUpdate;
if (!fromSatellitePositioningMethodsOnly)
if (validLastUpdate)
return lastUpdate;
time = lastKnownPositionTime.value().toDouble();
latitude = lastKnownPositionLatitude.value().toDouble();
longitude = lastKnownPositionLongitude.value().toDouble();
altitude = lastKnownPositionAltitude.value().toDouble();
speed = lastKnownPositionSpeed.value().toDouble();
track = lastKnownPositionTrack.value().toDouble();
climb = lastKnownPositionClimb.value().toDouble();
if (longitude && latitude) {
coordinate.setLongitude(longitude);
coordinate.setLatitude(latitude);
if (altitude) {
coordinate.setAltitude(altitude);
}
posInfo.setCoordinate(coordinate);
}
if (speed) {
posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, speed);
}
if (track) {
posInfo.setAttribute(QGeoPositionInfo::Direction, track);
}
if (climb) {
posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, climb);
}
// Only positions with time (3D) are provided.
if (time) {
posInfo.setTimestamp(QDateTime::fromTime_t(time));
return posInfo;
}
return QGeoPositionInfo();
}
void LiblocationWrapper::satellitesInViewUpdated(const QList<QGeoSatelliteInfo> &satellites)
{
satsInView = satellites;
}
void LiblocationWrapper::satellitesInUseUpdated(const QList<QGeoSatelliteInfo> &satellites)
{
satsInUse = satellites;
}
QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInView()
{
return satsInView;
}
QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInUse()
{
return satsInUse;
}
void LiblocationWrapper::start() {
startcounter++;
if ((locationState & LiblocationWrapper::Inited) &&
!(locationState & LiblocationWrapper::Started)) {
if (!errorHandlerId) {
errorHandlerId =
g_signal_connect(G_OBJECT(locationControl), "error-verbose",
G_CALLBACK(&locationError),
static_cast<void*>(this));
}
if (!posChangedId) {
posChangedId =
g_signal_connect(G_OBJECT(locationDevice), "changed",
G_CALLBACK(&locationChanged),
static_cast<void*>(this));
}
location_gpsd_control_start(locationControl);
locationState |= LiblocationWrapper::Started;
locationState &= ~LiblocationWrapper::Stopped;
}
}
void LiblocationWrapper::stop() {
startcounter--;
if (startcounter > 0)
return;
if ((locationState & (LiblocationWrapper::Started |
LiblocationWrapper::Inited)) &&
!(locationState & LiblocationWrapper::Stopped)) {
if (errorHandlerId)
g_signal_handler_disconnect(G_OBJECT(locationControl),
errorHandlerId);
if (posChangedId)
g_signal_handler_disconnect(G_OBJECT(locationDevice),
posChangedId);
errorHandlerId = 0;
posChangedId = 0;
startcounter = 0;
location_gpsd_control_stop(locationControl);
locationState &= ~LiblocationWrapper::Started;
locationState |= LiblocationWrapper::Stopped;
}
}
bool LiblocationWrapper::isActive() {
if (locationState & LiblocationWrapper::Started)
return true;
else
return false;
}
#include "moc_liblocationwrapper_p.cpp"
QTM_END_NAMESPACE
<commit_msg>Fix for bug in Maemo 5 Location regarding position accuracy.<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 "liblocationwrapper_p.h"
using namespace std;
QTM_BEGIN_NAMESPACE
Q_GLOBAL_STATIC(LiblocationWrapper, LocationEngine)
LiblocationWrapper *LiblocationWrapper::instance()
{
return LocationEngine();
}
LiblocationWrapper::~LiblocationWrapper()
{
if (locationDevice)
g_object_unref(locationDevice);
if (locationControl)
g_object_unref(locationControl);
}
bool LiblocationWrapper::inited()
{
int retval = false;
if (!(locationState & LiblocationWrapper::Inited)) {
g_type_init();
locationControl = location_gpsd_control_get_default();
if (locationControl) {
g_object_set(G_OBJECT(locationControl),
"preferred-method", LOCATION_METHOD_USER_SELECTED,
"preferred-interval", LOCATION_INTERVAL_1S,
NULL);
locationDevice =
(LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE,
NULL);
if (locationDevice) {
errorHandlerId =
g_signal_connect(G_OBJECT(locationControl), "error-verbose",
G_CALLBACK(&locationError),
static_cast<void*>(this));
posChangedId =
g_signal_connect(G_OBJECT(locationDevice), "changed",
G_CALLBACK(&locationChanged),
static_cast<void*>(this));
locationState = LiblocationWrapper::Inited;
retval = true;
startcounter = 0;
}
}
} else {
retval = true;
}
return retval;
}
void LiblocationWrapper::locationError(LocationGPSDevice *device,
gint errorCode, gpointer data)
{
Q_UNUSED(device);
QString locationError;
switch (errorCode) {
case LOCATION_ERROR_USER_REJECTED_DIALOG:
locationError = "User didn't enable requested methods";
break;
case LOCATION_ERROR_USER_REJECTED_SETTINGS:
locationError = "User changed settings, which disabled location.";
break;
case LOCATION_ERROR_BT_GPS_NOT_AVAILABLE:
locationError = "Problems with BT GPS";
break;
case LOCATION_ERROR_METHOD_NOT_ALLOWED_IN_OFFLINE_MODE:
locationError = "Requested method is not allowed in offline mode";
break;
case LOCATION_ERROR_SYSTEM:
locationError = "System error.";
break;
default:
locationError = "Unknown error.";
}
qDebug() << "Location error:" << locationError;
LiblocationWrapper *object;
object = (LiblocationWrapper *)data;
emit object->error();
}
void LiblocationWrapper::locationChanged(LocationGPSDevice *device,
gpointer data)
{
QGeoPositionInfo posInfo;
QGeoCoordinate coordinate;
QGeoSatelliteInfo satInfo;
int satellitesInUseCount = 0;
LiblocationWrapper *object;
if (!data || !device) {
return;
}
object = (LiblocationWrapper *)data;
if (device) {
if (device->fix) {
if (device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) {
posInfo.setTimestamp(QDateTime::fromTime_t(device->fix->time));
}
if (device->fix->fields & LOCATION_GPS_DEVICE_LATLONG_SET) {
coordinate.setLatitude(device->fix->latitude);
coordinate.setLongitude(device->fix->longitude);
posInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy,
device->fix->eph * 100);
posInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy,
device->fix->epv);
}
if (device->fix->fields & LOCATION_GPS_DEVICE_ALTITUDE_SET) {
coordinate.setAltitude(device->fix->altitude);
}
if (device->fix->fields & LOCATION_GPS_DEVICE_SPEED_SET) {
posInfo.setAttribute(QGeoPositionInfo::GroundSpeed,
device->fix->speed);
}
if (device->fix->fields & LOCATION_GPS_DEVICE_CLIMB_SET) {
posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed,
device->fix->climb);
}
if (device->fix->fields & LOCATION_GPS_DEVICE_TRACK_SET) {
posInfo.setAttribute(QGeoPositionInfo::Direction,
device->fix->track);
}
}
if (device->satellites_in_view) {
QList<QGeoSatelliteInfo> satsInView;
QList<QGeoSatelliteInfo> satsInUse;
unsigned int i;
for (i=0;i<device->satellites->len;i++) {
LocationGPSDeviceSatellite *satData =
(LocationGPSDeviceSatellite *)g_ptr_array_index(device->satellites,
i);
satInfo.setSignalStrength(satData->signal_strength);
satInfo.setPrnNumber(satData->prn);
satInfo.setAttribute(QGeoSatelliteInfo::Elevation,
satData->elevation);
satInfo.setAttribute(QGeoSatelliteInfo::Azimuth,
satData->azimuth);
satsInView.append(satInfo);
if (satData->in_use) {
satellitesInUseCount++;
satsInUse.append(satInfo);
}
}
if (!satsInView.isEmpty())
object->satellitesInViewUpdated(satsInView);
if (!satsInUse.isEmpty())
object->satellitesInUseUpdated(satsInUse);
}
}
posInfo.setCoordinate(coordinate);
if ((device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) &&
((device->fix->mode == LOCATION_GPS_DEVICE_MODE_3D) ||
(device->fix->mode == LOCATION_GPS_DEVICE_MODE_2D))) {
object->setLocation(posInfo, true);
} else {
object->setLocation(posInfo, false);
}
}
void LiblocationWrapper::setLocation(const QGeoPositionInfo &update,
bool locationValid)
{
validLastSatUpdate = locationValid;
lastSatUpdate = update;
}
QGeoPositionInfo LiblocationWrapper::position() {
return lastSatUpdate;
}
bool LiblocationWrapper::fixIsValid()
{
return validLastSatUpdate;
}
QGeoPositionInfo LiblocationWrapper::lastKnownPosition(bool fromSatellitePositioningMethodsOnly) const
{
QGeoPositionInfo posInfo;
QGeoCoordinate coordinate;
double time;
double latitude;
double longitude;
double altitude;
double speed;
double track;
double climb;
GConfItem lastKnownPositionTime("/system/nokia/location/lastknown/time");
GConfItem lastKnownPositionLatitude("/system/nokia/location/lastknown/latitude");
GConfItem lastKnownPositionLongitude("/system/nokia/location/lastknown/longitude");
GConfItem lastKnownPositionAltitude("/system/nokia/location/lastknown/altitude");
GConfItem lastKnownPositionSpeed("/system/nokia/location/lastknown/speed");
GConfItem lastKnownPositionTrack("/system/nokia/location/lastknown/track");
GConfItem lastKnownPositionClimb("/system/nokia/location/lastknown/climb");
if (validLastSatUpdate)
return lastSatUpdate;
if (!fromSatellitePositioningMethodsOnly)
if (validLastUpdate)
return lastUpdate;
time = lastKnownPositionTime.value().toDouble();
latitude = lastKnownPositionLatitude.value().toDouble();
longitude = lastKnownPositionLongitude.value().toDouble();
altitude = lastKnownPositionAltitude.value().toDouble();
speed = lastKnownPositionSpeed.value().toDouble();
track = lastKnownPositionTrack.value().toDouble();
climb = lastKnownPositionClimb.value().toDouble();
if (longitude && latitude) {
coordinate.setLongitude(longitude);
coordinate.setLatitude(latitude);
if (altitude) {
coordinate.setAltitude(altitude);
}
posInfo.setCoordinate(coordinate);
}
if (speed) {
posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, speed);
}
if (track) {
posInfo.setAttribute(QGeoPositionInfo::Direction, track);
}
if (climb) {
posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, climb);
}
// Only positions with time (3D) are provided.
if (time) {
posInfo.setTimestamp(QDateTime::fromTime_t(time));
return posInfo;
}
return QGeoPositionInfo();
}
void LiblocationWrapper::satellitesInViewUpdated(const QList<QGeoSatelliteInfo> &satellites)
{
satsInView = satellites;
}
void LiblocationWrapper::satellitesInUseUpdated(const QList<QGeoSatelliteInfo> &satellites)
{
satsInUse = satellites;
}
QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInView()
{
return satsInView;
}
QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInUse()
{
return satsInUse;
}
void LiblocationWrapper::start() {
startcounter++;
if ((locationState & LiblocationWrapper::Inited) &&
!(locationState & LiblocationWrapper::Started)) {
if (!errorHandlerId) {
errorHandlerId =
g_signal_connect(G_OBJECT(locationControl), "error-verbose",
G_CALLBACK(&locationError),
static_cast<void*>(this));
}
if (!posChangedId) {
posChangedId =
g_signal_connect(G_OBJECT(locationDevice), "changed",
G_CALLBACK(&locationChanged),
static_cast<void*>(this));
}
location_gpsd_control_start(locationControl);
locationState |= LiblocationWrapper::Started;
locationState &= ~LiblocationWrapper::Stopped;
}
}
void LiblocationWrapper::stop() {
startcounter--;
if (startcounter > 0)
return;
if ((locationState & (LiblocationWrapper::Started |
LiblocationWrapper::Inited)) &&
!(locationState & LiblocationWrapper::Stopped)) {
if (errorHandlerId)
g_signal_handler_disconnect(G_OBJECT(locationControl),
errorHandlerId);
if (posChangedId)
g_signal_handler_disconnect(G_OBJECT(locationDevice),
posChangedId);
errorHandlerId = 0;
posChangedId = 0;
startcounter = 0;
location_gpsd_control_stop(locationControl);
locationState &= ~LiblocationWrapper::Started;
locationState |= LiblocationWrapper::Stopped;
}
}
bool LiblocationWrapper::isActive() {
if (locationState & LiblocationWrapper::Started)
return true;
else
return false;
}
#include "moc_liblocationwrapper_p.cpp"
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>#include <QApplication>
#include <QSet>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QMetaObject>
#include <QMetaProperty>
#include <QPushButton>
#include <QDebug>
#include <iostream>
#include <QtDeclarative>
#include <QtDeclarative/private/qdeclarativemetatype_p.h>
#include <QtDeclarative/QDeclarativeView>
static QHash<QByteArray, const QDeclarativeType *> qmlTypeByCppName;
static QHash<QByteArray, QByteArray> cppToQml;
QByteArray convertToQmlType(const QByteArray &cppName)
{
QByteArray qmlName = cppToQml.value(cppName, cppName);
qmlName.replace("::", ".");
qmlName.replace("/", ".");
return qmlName;
}
void erasure(QByteArray *typeName, bool *isList, bool *isPointer)
{
static QByteArray declListPrefix = "QDeclarativeListProperty<";
if (typeName->endsWith('*')) {
*isPointer = true;
typeName->truncate(typeName->length() - 1);
erasure(typeName, isList, isPointer);
} else if (typeName->startsWith(declListPrefix)) {
*isList = true;
typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
*typeName = typeName->mid(declListPrefix.size());
erasure(typeName, isList, isPointer);
}
*typeName = convertToQmlType(*typeName);
}
void processMetaObject(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
{
if (! meta || metas->contains(meta))
return;
metas->insert(meta);
processMetaObject(meta->superClass(), metas);
}
void processObject(QObject *object, QSet<const QMetaObject *> *metas)
{
if (! object)
return;
const QMetaObject *meta = object->metaObject();
processMetaObject(meta, metas);
for (int index = 0; index < meta->propertyCount(); ++index) {
QMetaProperty prop = meta->property(index);
if (QDeclarativeMetaType::isQObject(prop.userType())) {
QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
if (oo && !metas->contains(oo->metaObject()))
processObject(oo, metas);
}
}
}
void processDeclarativeType(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
{
processMetaObject(ty->metaObject(), metas);
}
void writeType(QXmlStreamAttributes *attrs, QByteArray typeName)
{
bool isList = false, isPointer = false;
erasure(&typeName, &isList, &isPointer);
attrs->append(QXmlStreamAttribute("type", typeName));
if (isList)
attrs->append(QXmlStreamAttribute("isList", "true"));
}
void dump(const QMetaProperty &prop, QXmlStreamWriter *xml)
{
xml->writeStartElement("property");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(prop.name())));
writeType(&attributes, prop.typeName());
xml->writeAttributes(attributes);
xml->writeEndElement();
}
void dump(const QMetaMethod &meth, QXmlStreamWriter *xml)
{
if (meth.methodType() == QMetaMethod::Signal) {
if (meth.access() != QMetaMethod::Protected)
return; // nothing to do.
} else if (meth.access() != QMetaMethod::Public) {
return; // nothing to do.
}
QByteArray name = meth.signature();
int lparenIndex = name.indexOf('(');
if (lparenIndex == -1) {
return; // invalid signature
}
name = name.left(lparenIndex);
QString elementName = QLatin1String("method");
QXmlStreamAttributes attributes;
if (meth.methodType() == QMetaMethod::Signal)
elementName = QLatin1String("signal");
xml->writeStartElement(elementName);
attributes.append(QXmlStreamAttribute("name", name));
const QString typeName = convertToQmlType(meth.typeName());
if (! typeName.isEmpty())
attributes.append(QXmlStreamAttribute("type", typeName));
xml->writeAttributes(attributes);
for (int i = 0; i < meth.parameterTypes().size(); ++i) {
QByteArray argName = meth.parameterNames().at(i);
xml->writeStartElement("param");
QXmlStreamAttributes attrs;
if (! argName.isEmpty())
attrs.append(QXmlStreamAttribute("name", argName));
writeType(&attrs, meth.parameterTypes().at(i));
xml->writeAttributes(attrs);
xml->writeEndElement();
}
xml->writeEndElement();
}
void dump(const QMetaEnum &e, QXmlStreamWriter *xml)
{
xml->writeStartElement("enum");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.name()))); // ### FIXME
xml->writeAttributes(attributes);
for (int index = 0; index < e.keyCount(); ++index) {
xml->writeStartElement("enumerator");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.key(index))));
attributes.append(QXmlStreamAttribute("value", QString::number(e.value(index))));
xml->writeAttributes(attributes);
xml->writeEndElement();
}
xml->writeEndElement();
}
class FriendlyQObject: public QObject
{
public:
static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
};
void dump(const QMetaObject *meta, QXmlStreamWriter *xml)
{
xml->writeStartElement("type");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", convertToQmlType(meta->className())));
if (const QDeclarativeType *qmlTy = qmlTypeByCppName.value(meta->className())) {
attributes.append(QXmlStreamAttribute("version", QString("%1.%2").arg(qmlTy->majorVersion()).arg(qmlTy->minorVersion())));
}
for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
QMetaClassInfo classInfo = meta->classInfo(index);
if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
attributes.append(QXmlStreamAttribute("defaultProperty", QLatin1String(classInfo.value())));
break;
}
}
QString version;
if (meta->superClass())
attributes.append(QXmlStreamAttribute("extends", convertToQmlType(meta->superClass()->className())));
if (! version.isEmpty())
attributes.append(QXmlStreamAttribute("version", version));
xml->writeAttributes(attributes);
for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
dump(meta->enumerator(index), xml);
for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
dump(meta->property(index), xml);
for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
dump(meta->method(index), xml);
xml->writeEndElement();
}
void writeScriptElement(QXmlStreamWriter *xml)
{
xml->writeStartElement("type");
{
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", "Script"));
xml->writeAttributes(attributes);
}
xml->writeStartElement("property");
{
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", "script"));
attributes.append(QXmlStreamAttribute("type", "string"));
xml->writeAttributes(attributes);
}
xml->writeEndElement();
xml->writeStartElement("property");
{
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", "source"));
attributes.append(QXmlStreamAttribute("type", "QUrl"));
xml->writeAttributes(attributes);
}
xml->writeEndElement();
xml->writeEndElement();
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QDeclarativeView view;
QDeclarativeEngine *engine = view.engine();
{
QByteArray code;
code += "import Qt 4.7;\n";
code += "import Qt.widgets 4.7;\n";
code += "import Qt.multimedia 1.0;\n";
code += "import Qt.labs.particles 4.7;\n";
code += "import org.webkit 1.0;\n";
code += "Item {}";
QDeclarativeComponent c(engine);
c.setData(code, QUrl("xxx"));
c.create();
}
cppToQml.insert("QString", "string");
cppToQml.insert("QEasingCurve", "Qt.Easing");
cppToQml.insert("QDeclarativeEasingValueType::Type", "Type");
QSet<const QMetaObject *> metas;
metas.insert(FriendlyQObject::qtMeta());
// ### TODO: We don't treat extended types correctly. Currently only hits the
// QDeclarativeGraphicsWidget extension to QGraphicsWidget
foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
if (ty->isExtendedType())
continue;
cppToQml.insert(ty->metaObject()->className(), ty->qmlTypeName());
qmlTypeByCppName.insert(ty->metaObject()->className(), ty);
processDeclarativeType(ty, &metas);
}
foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
if (ty->isExtendedType())
continue;
QByteArray tyName = ty->qmlTypeName();
tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
QByteArray code;
code += "import Qt 4.7;\n";
code += "import Qt.widgets 4.7;\n";
code += "import Qt.multimedia 1.0;\n";
code += "import Qt.labs.particles 4.7;\n";
code += "import org.webkit 1.0;\n";
code += tyName;
code += " {}\n";
QDeclarativeComponent c(engine);
c.setData(code, QUrl("xxx"));
processObject(c.create(), &metas);
}
QByteArray bytes;
QXmlStreamWriter xml(&bytes);
xml.setAutoFormatting(true);
xml.writeStartDocument("1.0");
xml.writeStartElement("module");
QMap<QString, const QMetaObject *> nameToMeta;
foreach (const QMetaObject *meta, metas) {
nameToMeta.insert(convertToQmlType(meta->className()), meta);
}
foreach (const QMetaObject *meta, nameToMeta) {
dump(meta, &xml);
}
writeScriptElement(&xml);
xml.writeEndElement();
xml.writeEndDocument();
std::cout << bytes.constData();
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(0);
QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
timer.start();
return app.exec();
}
<commit_msg>QmlJS: Make the qmldump tool treat extended types correctly.<commit_after>#include <QApplication>
#include <QSet>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QMetaObject>
#include <QMetaProperty>
#include <QPushButton>
#include <QDebug>
#include <iostream>
#include <QtDeclarative>
#include <QtDeclarative/private/qdeclarativemetatype_p.h>
#include <QtDeclarative/QDeclarativeView>
static QHash<QByteArray, const QDeclarativeType *> qmlTypeByCppName;
static QHash<QByteArray, QByteArray> cppToQml;
QByteArray convertToQmlType(const QByteArray &cppName)
{
QByteArray qmlName = cppToQml.value(cppName, cppName);
qmlName.replace("::", ".");
qmlName.replace("/", ".");
return qmlName;
}
void erasure(QByteArray *typeName, bool *isList, bool *isPointer)
{
static QByteArray declListPrefix = "QDeclarativeListProperty<";
if (typeName->endsWith('*')) {
*isPointer = true;
typeName->truncate(typeName->length() - 1);
erasure(typeName, isList, isPointer);
} else if (typeName->startsWith(declListPrefix)) {
*isList = true;
typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
*typeName = typeName->mid(declListPrefix.size());
erasure(typeName, isList, isPointer);
}
*typeName = convertToQmlType(*typeName);
}
void processMetaObject(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
{
if (! meta || metas->contains(meta))
return;
metas->insert(meta);
processMetaObject(meta->superClass(), metas);
}
void processObject(QObject *object, QSet<const QMetaObject *> *metas)
{
if (! object)
return;
const QMetaObject *meta = object->metaObject();
processMetaObject(meta, metas);
for (int index = 0; index < meta->propertyCount(); ++index) {
QMetaProperty prop = meta->property(index);
if (QDeclarativeMetaType::isQObject(prop.userType())) {
QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
if (oo && !metas->contains(oo->metaObject()))
processObject(oo, metas);
}
}
}
void processDeclarativeType(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
{
processMetaObject(ty->metaObject(), metas);
}
void writeType(QXmlStreamAttributes *attrs, QByteArray typeName)
{
bool isList = false, isPointer = false;
erasure(&typeName, &isList, &isPointer);
attrs->append(QXmlStreamAttribute("type", typeName));
if (isList)
attrs->append(QXmlStreamAttribute("isList", "true"));
}
void dump(const QMetaProperty &prop, QXmlStreamWriter *xml)
{
xml->writeStartElement("property");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(prop.name())));
writeType(&attributes, prop.typeName());
xml->writeAttributes(attributes);
xml->writeEndElement();
}
void dump(const QMetaMethod &meth, QXmlStreamWriter *xml)
{
if (meth.methodType() == QMetaMethod::Signal) {
if (meth.access() != QMetaMethod::Protected)
return; // nothing to do.
} else if (meth.access() != QMetaMethod::Public) {
return; // nothing to do.
}
QByteArray name = meth.signature();
int lparenIndex = name.indexOf('(');
if (lparenIndex == -1) {
return; // invalid signature
}
name = name.left(lparenIndex);
QString elementName = QLatin1String("method");
QXmlStreamAttributes attributes;
if (meth.methodType() == QMetaMethod::Signal)
elementName = QLatin1String("signal");
xml->writeStartElement(elementName);
attributes.append(QXmlStreamAttribute("name", name));
const QString typeName = convertToQmlType(meth.typeName());
if (! typeName.isEmpty())
attributes.append(QXmlStreamAttribute("type", typeName));
xml->writeAttributes(attributes);
for (int i = 0; i < meth.parameterTypes().size(); ++i) {
QByteArray argName = meth.parameterNames().at(i);
xml->writeStartElement("param");
QXmlStreamAttributes attrs;
if (! argName.isEmpty())
attrs.append(QXmlStreamAttribute("name", argName));
writeType(&attrs, meth.parameterTypes().at(i));
xml->writeAttributes(attrs);
xml->writeEndElement();
}
xml->writeEndElement();
}
void dump(const QMetaEnum &e, QXmlStreamWriter *xml)
{
xml->writeStartElement("enum");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.name()))); // ### FIXME
xml->writeAttributes(attributes);
for (int index = 0; index < e.keyCount(); ++index) {
xml->writeStartElement("enumerator");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.key(index))));
attributes.append(QXmlStreamAttribute("value", QString::number(e.value(index))));
xml->writeAttributes(attributes);
xml->writeEndElement();
}
xml->writeEndElement();
}
class FriendlyQObject: public QObject
{
public:
static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
};
void dump(const QMetaObject *meta, QXmlStreamWriter *xml)
{
xml->writeStartElement("type");
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", convertToQmlType(meta->className())));
if (const QDeclarativeType *qmlTy = qmlTypeByCppName.value(meta->className())) {
attributes.append(QXmlStreamAttribute("version", QString("%1.%2").arg(qmlTy->majorVersion()).arg(qmlTy->minorVersion())));
}
for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
QMetaClassInfo classInfo = meta->classInfo(index);
if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
attributes.append(QXmlStreamAttribute("defaultProperty", QLatin1String(classInfo.value())));
break;
}
}
QString version;
if (meta->superClass())
attributes.append(QXmlStreamAttribute("extends", convertToQmlType(meta->superClass()->className())));
if (! version.isEmpty())
attributes.append(QXmlStreamAttribute("version", version));
xml->writeAttributes(attributes);
for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
dump(meta->enumerator(index), xml);
for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
dump(meta->property(index), xml);
for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
dump(meta->method(index), xml);
xml->writeEndElement();
}
void writeScriptElement(QXmlStreamWriter *xml)
{
xml->writeStartElement("type");
{
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", "Script"));
xml->writeAttributes(attributes);
}
xml->writeStartElement("property");
{
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", "script"));
attributes.append(QXmlStreamAttribute("type", "string"));
xml->writeAttributes(attributes);
}
xml->writeEndElement();
xml->writeStartElement("property");
{
QXmlStreamAttributes attributes;
attributes.append(QXmlStreamAttribute("name", "source"));
attributes.append(QXmlStreamAttribute("type", "QUrl"));
xml->writeAttributes(attributes);
}
xml->writeEndElement();
xml->writeEndElement();
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QDeclarativeView view;
QDeclarativeEngine *engine = view.engine();
{
QByteArray code;
code += "import Qt 4.7;\n";
code += "import Qt.widgets 4.7;\n";
code += "import Qt.multimedia 1.0;\n";
code += "import Qt.labs.particles 4.7;\n";
code += "import org.webkit 1.0;\n";
code += "Item {}";
QDeclarativeComponent c(engine);
c.setData(code, QUrl("xxx"));
c.create();
}
cppToQml.insert("QString", "string");
cppToQml.insert("QEasingCurve", "Qt.Easing");
cppToQml.insert("QDeclarativeEasingValueType::Type", "Type");
QSet<const QMetaObject *> metas;
metas.insert(FriendlyQObject::qtMeta());
QMultiHash<QByteArray, QByteArray> extensions;
foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
qmlTypeByCppName.insert(ty->metaObject()->className(), ty);
if (ty->isExtendedType()) {
extensions.insert(ty->typeName(), ty->metaObject()->className());
} else {
cppToQml.insert(ty->metaObject()->className(), ty->qmlTypeName());
}
processDeclarativeType(ty, &metas);
}
// Adjust qml names of extended objects.
// The chain ends up being:
// __extended__.originalname - the base object
// __extension_0_.originalname - first extension
// ..
// __extension_n-2_.originalname - second to last extension
// originalname - last extension
foreach (const QByteArray &extendedCpp, extensions.keys()) {
const QByteArray extendedQml = cppToQml.value(extendedCpp);
cppToQml.insert(extendedCpp, "__extended__." + extendedQml);
QList<QByteArray> extensionCppNames = extensions.values(extendedCpp);
for (int i = 0; i < extensionCppNames.size() - 1; ++i) {
QByteArray adjustedName = QString("__extension__%1.%2").arg(QString::number(i), QString(extendedQml)).toAscii();
cppToQml.insert(extensionCppNames.value(i), adjustedName);
}
cppToQml.insert(extensionCppNames.last(), extendedQml);
}
foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
if (ty->isExtendedType())
continue;
QByteArray tyName = ty->qmlTypeName();
tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
QByteArray code;
code += "import Qt 4.7;\n";
code += "import Qt.widgets 4.7;\n";
code += "import Qt.multimedia 1.0;\n";
code += "import Qt.labs.particles 4.7;\n";
code += "import org.webkit 1.0;\n";
code += tyName;
code += " {}\n";
QDeclarativeComponent c(engine);
c.setData(code, QUrl("xxx"));
processObject(c.create(), &metas);
}
QByteArray bytes;
QXmlStreamWriter xml(&bytes);
xml.setAutoFormatting(true);
xml.writeStartDocument("1.0");
xml.writeStartElement("module");
QMap<QString, const QMetaObject *> nameToMeta;
foreach (const QMetaObject *meta, metas) {
nameToMeta.insert(convertToQmlType(meta->className()), meta);
}
foreach (const QMetaObject *meta, nameToMeta) {
dump(meta, &xml);
}
writeScriptElement(&xml);
xml.writeEndElement();
xml.writeEndDocument();
std::cout << bytes.constData();
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(0);
QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
timer.start();
return app.exec();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
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 the author 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.
*/
#include <vector>
#include <iostream>
#include <cctype>
#include <iomanip>
#include <sstream>
#include "zlib.h"
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#include "libtorrent/io.hpp"
namespace
{
enum
{
udp_connection_retries = 4,
udp_announce_retries = 15,
udp_connect_timeout = 15,
udp_announce_timeout = 10,
udp_buffer_size = 2048
};
}
using namespace boost::posix_time;
namespace libtorrent
{
udp_tracker_connection::udp_tracker_connection(
tracker_request const& req
, std::string const& hostname
, unsigned short port
, boost::weak_ptr<request_callback> c
, const http_settings& stn)
: tracker_connection(c)
, m_request_time(second_clock::universal_time())
, m_request(req)
, m_transaction_id(0)
, m_connection_id(0)
, m_settings(stn)
, m_attempts(0)
{
// TODO: this is a problem. DNS-lookup is blocking!
// (may block up to 5 seconds)
address a(hostname.c_str(), port);
if (has_requester()) requester().m_tracker_address = a;
m_socket.reset(new socket(socket::udp, false));
m_socket->connect(a);
send_udp_connect();
}
bool udp_tracker_connection::send_finished() const
{
using namespace boost::posix_time;
time_duration d = second_clock::universal_time() - m_request_time;
return (m_transaction_id != 0
&& m_connection_id != 0)
|| d > seconds(m_settings.tracker_timeout);
}
bool udp_tracker_connection::tick()
{
using namespace boost::posix_time;
time_duration d = second_clock::universal_time() - m_request_time;
if (m_connection_id == 0
&& d > seconds(udp_connect_timeout))
{
if (m_attempts >= udp_connection_retries)
{
if (has_requester())
requester().tracker_request_timed_out(m_request);
return true;
}
send_udp_connect();
return false;
}
if (m_connection_id != 0
&& d > seconds(udp_announce_timeout))
{
if (m_attempts >= udp_announce_retries)
{
if (has_requester())
requester().tracker_request_timed_out(m_request);
return true;
}
if (m_request.kind == tracker_request::announce_request)
send_udp_announce();
else if (m_request.kind == tracker_request::scrape_request)
send_udp_scrape();
return false;
}
char buf[udp_buffer_size];
int ret = m_socket->receive(buf, udp_buffer_size);
// if there was nothing to receive, return
if (ret == 0) return false;
if (ret < 0)
{
socket::error_code err = m_socket->last_error();
if (err == socket::would_block) return false;
throw network_error(m_socket->last_error());
}
if (ret == udp_buffer_size)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, "tracker reply too big");
return true;
}
if (m_connection_id == 0)
{
return parse_connect_response(buf, ret);
}
else if (m_request.kind == tracker_request::announce_request)
{
return parse_announce_response(buf, ret);
}
else if (m_request.kind == tracker_request::scrape_request)
{
return parse_scrape_response(buf, ret);
}
assert(false);
return false;
}
void udp_tracker_connection::send_udp_announce()
{
if (m_transaction_id == 0)
m_transaction_id = rand() ^ (rand() << 16);
std::vector<char> buf;
std::back_insert_iterator<std::vector<char> > out(buf);
// connection_id
detail::write_int64(m_connection_id, out);
// action (announce)
detail::write_int32(announce, out);
// transaction_id
detail::write_int32(m_transaction_id, out);
// info_hash
std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out);
// peer_id
std::copy(m_request.id.begin(), m_request.id.end(), out);
// downloaded
detail::write_int64(m_request.downloaded, out);
// left
detail::write_int64(m_request.left, out);
// uploaded
detail::write_int64(m_request.uploaded, out);
// event
detail::write_int32(m_request.event, out);
// ip address
detail::write_int32(0, out);
// key
detail::write_int32(m_request.key, out);
// num_want
detail::write_int32(m_request.num_want, out);
// port
detail::write_uint16(m_request.listen_port, out);
m_socket->send(&buf[0], buf.size());
m_request_time = second_clock::universal_time();
++m_attempts;
}
void udp_tracker_connection::send_udp_scrape()
{
if (m_transaction_id == 0)
m_transaction_id = rand() ^ (rand() << 16);
std::vector<char> buf;
std::back_insert_iterator<std::vector<char> > out(buf);
// connection_id
detail::write_int64(m_connection_id, out);
// action (scrape)
detail::write_int32(scrape, out);
// transaction_id
detail::write_int32(m_transaction_id, out);
// info_hash
std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out);
m_socket->send(&buf[0], buf.size());
m_request_time = second_clock::universal_time();
++m_attempts;
}
void udp_tracker_connection::send_udp_connect()
{
char send_buf[16];
char* ptr = send_buf;
if (m_transaction_id == 0)
m_transaction_id = rand() ^ (rand() << 16);
// connection_id
detail::write_int64(0x41727101980, ptr);
// action (connect)
detail::write_int32(connect, ptr);
// transaction_id
detail::write_int32(m_transaction_id, ptr);
m_socket->send(send_buf, 16);
m_request_time = second_clock::universal_time();
++m_attempts;
}
bool udp_tracker_connection::parse_announce_response(const char* buf, int len)
{
assert(buf != 0);
assert(len > 0);
if (len < 8)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 8, ignoring");
#endif
return false;
}
int action = detail::read_int32(buf);
int transaction = detail::read_int32(buf);
if (transaction != m_transaction_id)
{
return false;
}
if (action == error)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, std::string(buf, buf + len - 8));
return true;
}
if (action != announce) return false;
if (len < 20)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 20, ignoring");
#endif
return false;
}
int interval = detail::read_int32(buf);
int incomplete = detail::read_int32(buf);
int complete = detail::read_int32(buf);
int num_peers = (len - 20) / 6;
if ((len - 20) % 6 != 0)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, "invalid tracker response");
return true;
}
if (!has_requester()) return true;
std::vector<peer_entry> peer_list;
for (int i = 0; i < num_peers; ++i)
{
peer_entry e;
std::stringstream s;
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf);
e.ip = s.str();
e.port = detail::read_uint16(buf);
e.id.clear();
peer_list.push_back(e);
}
requester().tracker_response(m_request, peer_list, interval
, complete, incomplete);
return true;
}
bool udp_tracker_connection::parse_scrape_response(const char* buf, int len)
{
assert(buf != 0);
assert(len > 0);
if (len < 8)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 8, ignoring");
#endif
return false;
}
int action = detail::read_int32(buf);
int transaction = detail::read_int32(buf);
if (transaction != m_transaction_id)
{
return false;
}
if (action == error)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, std::string(buf, buf + len - 8));
return true;
}
if (action != scrape) return false;
if (len < 20)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 20, ignoring");
#endif
return false;
}
int complete = detail::read_int32(buf);
int completed = detail::read_int32(buf);
int incomplete = detail::read_int32(buf);
if (!has_requester()) return true;
std::vector<peer_entry> peer_list;
requester().tracker_response(m_request, peer_list, 0
, complete, incomplete);
return true;
}
bool udp_tracker_connection::parse_connect_response(const char* buf, int len)
{
assert(buf != 0);
assert(len > 0);
if (len < 8)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 8, ignoring");
#endif
return false;
}
const char* ptr = buf;
int action = detail::read_int32(ptr);
int transaction = detail::read_int32(ptr);
if (action == error)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, std::string(ptr, buf + len));
return true;
}
if (action != connect) return false;
if (m_transaction_id != transaction)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with incorrect transaction id, ignoring");
#endif
return false;
}
if (len < 16)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a connection message size < 16, ignoring");
#endif
return false;
}
// reset transaction
m_transaction_id = 0;
m_attempts = 0;
m_connection_id = detail::read_int64(ptr);
if (m_request.kind == tracker_request::announce_request)
send_udp_announce();
else if (m_request.kind == tracker_request::scrape_request)
send_udp_scrape();
return false;
}
}
<commit_msg>*** empty log message ***<commit_after>/*
Copyright (c) 2003, Arvid Norberg
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 the author 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.
*/
#include <vector>
#include <iostream>
#include <cctype>
#include <iomanip>
#include <sstream>
#include "zlib.h"
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#include "libtorrent/io.hpp"
namespace
{
enum
{
udp_connection_retries = 4,
udp_announce_retries = 15,
udp_connect_timeout = 15,
udp_announce_timeout = 10,
udp_buffer_size = 2048
};
}
using namespace boost::posix_time;
namespace libtorrent
{
udp_tracker_connection::udp_tracker_connection(
tracker_request const& req
, std::string const& hostname
, unsigned short port
, boost::weak_ptr<request_callback> c
, const http_settings& stn)
: tracker_connection(c)
, m_request_time(second_clock::universal_time())
, m_request(req)
, m_transaction_id(0)
, m_connection_id(0)
, m_settings(stn)
, m_attempts(0)
{
// TODO: this is a problem. DNS-lookup is blocking!
// (may block up to 5 seconds)
address a(hostname.c_str(), port);
if (has_requester()) requester().m_tracker_address = a;
m_socket.reset(new socket(socket::udp, false));
m_socket->connect(a);
send_udp_connect();
}
bool udp_tracker_connection::send_finished() const
{
using namespace boost::posix_time;
time_duration d = second_clock::universal_time() - m_request_time;
return (m_transaction_id != 0
&& m_connection_id != 0)
|| d > seconds(m_settings.tracker_timeout);
}
bool udp_tracker_connection::tick()
{
using namespace boost::posix_time;
time_duration d = second_clock::universal_time() - m_request_time;
if (m_connection_id == 0
&& d > seconds(udp_connect_timeout))
{
if (m_attempts >= udp_connection_retries)
{
if (has_requester())
requester().tracker_request_timed_out(m_request);
return true;
}
send_udp_connect();
return false;
}
if (m_connection_id != 0
&& d > seconds(udp_announce_timeout))
{
if (m_attempts >= udp_announce_retries)
{
if (has_requester())
requester().tracker_request_timed_out(m_request);
return true;
}
if (m_request.kind == tracker_request::announce_request)
send_udp_announce();
else if (m_request.kind == tracker_request::scrape_request)
send_udp_scrape();
return false;
}
char buf[udp_buffer_size];
int ret = m_socket->receive(buf, udp_buffer_size);
// if there was nothing to receive, return
if (ret == 0) return false;
if (ret < 0)
{
socket::error_code err = m_socket->last_error();
if (err == socket::would_block) return false;
throw network_error(m_socket->last_error());
}
if (ret == udp_buffer_size)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, "tracker reply too big");
return true;
}
if (m_connection_id == 0)
{
return parse_connect_response(buf, ret);
}
else if (m_request.kind == tracker_request::announce_request)
{
return parse_announce_response(buf, ret);
}
else if (m_request.kind == tracker_request::scrape_request)
{
return parse_scrape_response(buf, ret);
}
assert(false);
return false;
}
void udp_tracker_connection::send_udp_announce()
{
if (m_transaction_id == 0)
m_transaction_id = rand() ^ (rand() << 16);
std::vector<char> buf;
std::back_insert_iterator<std::vector<char> > out(buf);
// connection_id
detail::write_int64(m_connection_id, out);
// action (announce)
detail::write_int32(announce, out);
// transaction_id
detail::write_int32(m_transaction_id, out);
// info_hash
std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out);
// peer_id
std::copy(m_request.id.begin(), m_request.id.end(), out);
// downloaded
detail::write_int64(m_request.downloaded, out);
// left
detail::write_int64(m_request.left, out);
// uploaded
detail::write_int64(m_request.uploaded, out);
// event
detail::write_int32(m_request.event, out);
// ip address
detail::write_int32(0, out);
// key
detail::write_int32(m_request.key, out);
// num_want
detail::write_int32(m_request.num_want, out);
// port
detail::write_uint16(m_request.listen_port, out);
// extensions
detail::write_uint16(0, out);
m_socket->send(&buf[0], buf.size());
m_request_time = second_clock::universal_time();
++m_attempts;
}
void udp_tracker_connection::send_udp_scrape()
{
if (m_transaction_id == 0)
m_transaction_id = rand() ^ (rand() << 16);
std::vector<char> buf;
std::back_insert_iterator<std::vector<char> > out(buf);
// connection_id
detail::write_int64(m_connection_id, out);
// action (scrape)
detail::write_int32(scrape, out);
// transaction_id
detail::write_int32(m_transaction_id, out);
// info_hash
std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out);
m_socket->send(&buf[0], buf.size());
m_request_time = second_clock::universal_time();
++m_attempts;
}
void udp_tracker_connection::send_udp_connect()
{
char send_buf[16];
char* ptr = send_buf;
if (m_transaction_id == 0)
m_transaction_id = rand() ^ (rand() << 16);
// connection_id
detail::write_int64(0x41727101980, ptr);
// action (connect)
detail::write_int32(connect, ptr);
// transaction_id
detail::write_int32(m_transaction_id, ptr);
m_socket->send(send_buf, 16);
m_request_time = second_clock::universal_time();
++m_attempts;
}
bool udp_tracker_connection::parse_announce_response(const char* buf, int len)
{
assert(buf != 0);
assert(len > 0);
if (len < 8)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 8, ignoring");
#endif
return false;
}
int action = detail::read_int32(buf);
int transaction = detail::read_int32(buf);
if (transaction != m_transaction_id)
{
return false;
}
if (action == error)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, std::string(buf, buf + len - 8));
return true;
}
if (action != announce) return false;
if (len < 20)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 20, ignoring");
#endif
return false;
}
int interval = detail::read_int32(buf);
int incomplete = detail::read_int32(buf);
int complete = detail::read_int32(buf);
int num_peers = (len - 20) / 6;
if ((len - 20) % 6 != 0)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, "invalid tracker response");
return true;
}
if (!has_requester()) return true;
std::vector<peer_entry> peer_list;
for (int i = 0; i < num_peers; ++i)
{
peer_entry e;
std::stringstream s;
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf);
e.ip = s.str();
e.port = detail::read_uint16(buf);
e.id.clear();
peer_list.push_back(e);
}
requester().tracker_response(m_request, peer_list, interval
, complete, incomplete);
return true;
}
bool udp_tracker_connection::parse_scrape_response(const char* buf, int len)
{
assert(buf != 0);
assert(len > 0);
if (len < 8)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 8, ignoring");
#endif
return false;
}
int action = detail::read_int32(buf);
int transaction = detail::read_int32(buf);
if (transaction != m_transaction_id)
{
return false;
}
if (action == error)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, std::string(buf, buf + len - 8));
return true;
}
if (action != scrape) return false;
if (len < 20)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 20, ignoring");
#endif
return false;
}
int complete = detail::read_int32(buf);
int completed = detail::read_int32(buf);
int incomplete = detail::read_int32(buf);
if (!has_requester()) return true;
std::vector<peer_entry> peer_list;
requester().tracker_response(m_request, peer_list, 0
, complete, incomplete);
return true;
}
bool udp_tracker_connection::parse_connect_response(const char* buf, int len)
{
assert(buf != 0);
assert(len > 0);
if (len < 8)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 8, ignoring");
#endif
return false;
}
const char* ptr = buf;
int action = detail::read_int32(ptr);
int transaction = detail::read_int32(ptr);
if (action == error)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, std::string(ptr, buf + len));
return true;
}
if (action != connect) return false;
if (m_transaction_id != transaction)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with incorrect transaction id, ignoring");
#endif
return false;
}
if (len < 16)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a connection message size < 16, ignoring");
#endif
return false;
}
// reset transaction
m_transaction_id = 0;
m_attempts = 0;
m_connection_id = detail::read_int64(ptr);
if (m_request.kind == tracker_request::announce_request)
send_udp_announce();
else if (m_request.kind == tracker_request::scrape_request)
send_udp_scrape();
return false;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/gpu/GrContext.h"
#include "include/gpu/GrContextThreadSafeProxy.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrContextThreadSafeProxyPriv.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/effects/GrSkSLFP.h"
#include "src/gpu/gl/GrGLGpu.h"
#include "src/gpu/mock/GrMockGpu.h"
#include "src/gpu/text/GrStrikeCache.h"
#ifdef SK_METAL
#include "src/gpu/mtl/GrMtlTrampoline.h"
#endif
#ifdef SK_VULKAN
#include "src/gpu/vk/GrVkGpu.h"
#endif
#ifdef SK_DISABLE_REDUCE_OPLIST_SPLITTING
static const bool kDefaultReduceOpListSplitting = false;
#else
static const bool kDefaultReduceOpListSplitting = true;
#endif
class SK_API GrLegacyDirectContext : public GrContext {
public:
GrLegacyDirectContext(GrBackendApi backend, const GrContextOptions& options)
: INHERITED(backend, options)
, fAtlasManager(nullptr) {
}
~GrLegacyDirectContext() override {
// this if-test protects against the case where the context is being destroyed
// before having been fully created
if (this->priv().getGpu()) {
this->flush();
}
delete fAtlasManager;
}
void abandonContext() override {
INHERITED::abandonContext();
fAtlasManager->freeAll();
}
void releaseResourcesAndAbandonContext() override {
INHERITED::releaseResourcesAndAbandonContext();
fAtlasManager->freeAll();
}
void freeGpuResources() override {
this->flush();
fAtlasManager->freeAll();
INHERITED::freeGpuResources();
}
protected:
bool init(sk_sp<const GrCaps> caps, sk_sp<GrSkSLFPFactoryCache> FPFactoryCache) override {
SkASSERT(caps && !FPFactoryCache);
SkASSERT(!fThreadSafeProxy);
FPFactoryCache.reset(new GrSkSLFPFactoryCache());
fThreadSafeProxy = GrContextThreadSafeProxyPriv::Make(this->backend(),
this->options(),
this->contextID(),
caps, FPFactoryCache);
if (!INHERITED::init(std::move(caps), std::move(FPFactoryCache))) {
return false;
}
bool reduceOpListSplitting = kDefaultReduceOpListSplitting;
if (GrContextOptions::Enable::kNo == this->options().fReduceOpListSplitting) {
reduceOpListSplitting = false;
} else if (GrContextOptions::Enable::kYes == this->options().fReduceOpListSplitting) {
reduceOpListSplitting = true;
}
this->setupDrawingManager(true, reduceOpListSplitting);
SkASSERT(this->caps());
GrDrawOpAtlas::AllowMultitexturing allowMultitexturing;
if (GrContextOptions::Enable::kNo == this->options().fAllowMultipleGlyphCacheTextures ||
// multitexturing supported only if range can represent the index + texcoords fully
!(this->caps()->shaderCaps()->floatIs32Bits() ||
this->caps()->shaderCaps()->integerSupport())) {
allowMultitexturing = GrDrawOpAtlas::AllowMultitexturing::kNo;
} else {
allowMultitexturing = GrDrawOpAtlas::AllowMultitexturing::kYes;
}
GrStrikeCache* glyphCache = this->priv().getGrStrikeCache();
GrProxyProvider* proxyProvider = this->priv().proxyProvider();
fAtlasManager = new GrAtlasManager(proxyProvider, glyphCache,
this->options().fGlyphCacheTextureMaximumBytes,
allowMultitexturing);
this->priv().addOnFlushCallbackObject(fAtlasManager);
return true;
}
GrAtlasManager* onGetAtlasManager() override { return fAtlasManager; }
private:
GrAtlasManager* fAtlasManager;
typedef GrContext INHERITED;
};
sk_sp<GrContext> GrContext::MakeGL(sk_sp<const GrGLInterface> interface) {
GrContextOptions defaultOptions;
return MakeGL(std::move(interface), defaultOptions);
}
sk_sp<GrContext> GrContext::MakeGL(const GrContextOptions& options) {
return MakeGL(nullptr, options);
}
sk_sp<GrContext> GrContext::MakeGL() {
GrContextOptions defaultOptions;
return MakeGL(nullptr, defaultOptions);
}
sk_sp<GrContext> GrContext::MakeGL(sk_sp<const GrGLInterface> interface,
const GrContextOptions& options) {
sk_sp<GrContext> context(new GrLegacyDirectContext(GrBackendApi::kOpenGL, options));
context->fGpu = GrGLGpu::Make(std::move(interface), options, context.get());
if (!context->fGpu) {
return nullptr;
}
if (!context->init(context->fGpu->refCaps(), nullptr)) {
return nullptr;
}
return context;
}
sk_sp<GrContext> GrContext::MakeMock(const GrMockOptions* mockOptions) {
GrContextOptions defaultOptions;
return MakeMock(mockOptions, defaultOptions);
}
sk_sp<GrContext> GrContext::MakeMock(const GrMockOptions* mockOptions,
const GrContextOptions& options) {
sk_sp<GrContext> context(new GrLegacyDirectContext(GrBackendApi::kMock, options));
context->fGpu = GrMockGpu::Make(mockOptions, options, context.get());
if (!context->fGpu) {
return nullptr;
}
if (!context->init(context->fGpu->refCaps(), nullptr)) {
return nullptr;
}
return context;
}
sk_sp<GrContext> GrContext::MakeVulkan(const GrVkBackendContext& backendContext) {
#ifdef SK_VULKAN
GrContextOptions defaultOptions;
return MakeVulkan(backendContext, defaultOptions);
#else
return nullptr;
#endif
}
sk_sp<GrContext> GrContext::MakeVulkan(const GrVkBackendContext& backendContext,
const GrContextOptions& options) {
#ifdef SK_VULKAN
GrContextOptions defaultOptions;
sk_sp<GrContext> context(new GrLegacyDirectContext(GrBackendApi::kVulkan, options));
context->fGpu = GrVkGpu::Make(backendContext, options, context.get());
if (!context->fGpu) {
return nullptr;
}
if (!context->init(context->fGpu->refCaps(), nullptr)) {
return nullptr;
}
return context;
#else
return nullptr;
#endif
}
#ifdef SK_METAL
sk_sp<GrContext> GrContext::MakeMetal(void* device, void* queue) {
GrContextOptions defaultOptions;
return MakeMetal(device, queue, defaultOptions);
}
sk_sp<GrContext> GrContext::MakeMetal(void* device, void* queue, const GrContextOptions& options) {
sk_sp<GrContext> context(new GrLegacyDirectContext(GrBackendApi::kMetal, options));
context->fGpu = GrMtlTrampoline::MakeGpu(context.get(), options, device, queue);
if (!context->fGpu) {
return nullptr;
}
if (!context->init(context->fGpu->refCaps(), nullptr)) {
return nullptr;
}
return context;
}
#endif
<commit_msg>Change opList-splitting reduction default to be off<commit_after>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/gpu/GrContext.h"
#include "include/gpu/GrContextThreadSafeProxy.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrContextThreadSafeProxyPriv.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/effects/GrSkSLFP.h"
#include "src/gpu/gl/GrGLGpu.h"
#include "src/gpu/mock/GrMockGpu.h"
#include "src/gpu/text/GrStrikeCache.h"
#ifdef SK_METAL
#include "src/gpu/mtl/GrMtlTrampoline.h"
#endif
#ifdef SK_VULKAN
#include "src/gpu/vk/GrVkGpu.h"
#endif
#ifdef SK_DISABLE_REDUCE_OPLIST_SPLITTING
static const bool kDefaultReduceOpListSplitting = false;
#else
static const bool kDefaultReduceOpListSplitting = false;
#endif
class SK_API GrLegacyDirectContext : public GrContext {
public:
GrLegacyDirectContext(GrBackendApi backend, const GrContextOptions& options)
: INHERITED(backend, options)
, fAtlasManager(nullptr) {
}
~GrLegacyDirectContext() override {
// this if-test protects against the case where the context is being destroyed
// before having been fully created
if (this->priv().getGpu()) {
this->flush();
}
delete fAtlasManager;
}
void abandonContext() override {
INHERITED::abandonContext();
fAtlasManager->freeAll();
}
void releaseResourcesAndAbandonContext() override {
INHERITED::releaseResourcesAndAbandonContext();
fAtlasManager->freeAll();
}
void freeGpuResources() override {
this->flush();
fAtlasManager->freeAll();
INHERITED::freeGpuResources();
}
protected:
bool init(sk_sp<const GrCaps> caps, sk_sp<GrSkSLFPFactoryCache> FPFactoryCache) override {
SkASSERT(caps && !FPFactoryCache);
SkASSERT(!fThreadSafeProxy);
FPFactoryCache.reset(new GrSkSLFPFactoryCache());
fThreadSafeProxy = GrContextThreadSafeProxyPriv::Make(this->backend(),
this->options(),
this->contextID(),
caps, FPFactoryCache);
if (!INHERITED::init(std::move(caps), std::move(FPFactoryCache))) {
return false;
}
bool reduceOpListSplitting = kDefaultReduceOpListSplitting;
if (GrContextOptions::Enable::kNo == this->options().fReduceOpListSplitting) {
reduceOpListSplitting = false;
} else if (GrContextOptions::Enable::kYes == this->options().fReduceOpListSplitting) {
reduceOpListSplitting = true;
}
this->setupDrawingManager(true, reduceOpListSplitting);
SkASSERT(this->caps());
GrDrawOpAtlas::AllowMultitexturing allowMultitexturing;
if (GrContextOptions::Enable::kNo == this->options().fAllowMultipleGlyphCacheTextures ||
// multitexturing supported only if range can represent the index + texcoords fully
!(this->caps()->shaderCaps()->floatIs32Bits() ||
this->caps()->shaderCaps()->integerSupport())) {
allowMultitexturing = GrDrawOpAtlas::AllowMultitexturing::kNo;
} else {
allowMultitexturing = GrDrawOpAtlas::AllowMultitexturing::kYes;
}
GrStrikeCache* glyphCache = this->priv().getGrStrikeCache();
GrProxyProvider* proxyProvider = this->priv().proxyProvider();
fAtlasManager = new GrAtlasManager(proxyProvider, glyphCache,
this->options().fGlyphCacheTextureMaximumBytes,
allowMultitexturing);
this->priv().addOnFlushCallbackObject(fAtlasManager);
return true;
}
GrAtlasManager* onGetAtlasManager() override { return fAtlasManager; }
private:
GrAtlasManager* fAtlasManager;
typedef GrContext INHERITED;
};
sk_sp<GrContext> GrContext::MakeGL(sk_sp<const GrGLInterface> interface) {
GrContextOptions defaultOptions;
return MakeGL(std::move(interface), defaultOptions);
}
sk_sp<GrContext> GrContext::MakeGL(const GrContextOptions& options) {
return MakeGL(nullptr, options);
}
sk_sp<GrContext> GrContext::MakeGL() {
GrContextOptions defaultOptions;
return MakeGL(nullptr, defaultOptions);
}
sk_sp<GrContext> GrContext::MakeGL(sk_sp<const GrGLInterface> interface,
const GrContextOptions& options) {
sk_sp<GrContext> context(new GrLegacyDirectContext(GrBackendApi::kOpenGL, options));
context->fGpu = GrGLGpu::Make(std::move(interface), options, context.get());
if (!context->fGpu) {
return nullptr;
}
if (!context->init(context->fGpu->refCaps(), nullptr)) {
return nullptr;
}
return context;
}
sk_sp<GrContext> GrContext::MakeMock(const GrMockOptions* mockOptions) {
GrContextOptions defaultOptions;
return MakeMock(mockOptions, defaultOptions);
}
sk_sp<GrContext> GrContext::MakeMock(const GrMockOptions* mockOptions,
const GrContextOptions& options) {
sk_sp<GrContext> context(new GrLegacyDirectContext(GrBackendApi::kMock, options));
context->fGpu = GrMockGpu::Make(mockOptions, options, context.get());
if (!context->fGpu) {
return nullptr;
}
if (!context->init(context->fGpu->refCaps(), nullptr)) {
return nullptr;
}
return context;
}
sk_sp<GrContext> GrContext::MakeVulkan(const GrVkBackendContext& backendContext) {
#ifdef SK_VULKAN
GrContextOptions defaultOptions;
return MakeVulkan(backendContext, defaultOptions);
#else
return nullptr;
#endif
}
sk_sp<GrContext> GrContext::MakeVulkan(const GrVkBackendContext& backendContext,
const GrContextOptions& options) {
#ifdef SK_VULKAN
GrContextOptions defaultOptions;
sk_sp<GrContext> context(new GrLegacyDirectContext(GrBackendApi::kVulkan, options));
context->fGpu = GrVkGpu::Make(backendContext, options, context.get());
if (!context->fGpu) {
return nullptr;
}
if (!context->init(context->fGpu->refCaps(), nullptr)) {
return nullptr;
}
return context;
#else
return nullptr;
#endif
}
#ifdef SK_METAL
sk_sp<GrContext> GrContext::MakeMetal(void* device, void* queue) {
GrContextOptions defaultOptions;
return MakeMetal(device, queue, defaultOptions);
}
sk_sp<GrContext> GrContext::MakeMetal(void* device, void* queue, const GrContextOptions& options) {
sk_sp<GrContext> context(new GrLegacyDirectContext(GrBackendApi::kMetal, options));
context->fGpu = GrMtlTrampoline::MakeGpu(context.get(), options, device, queue);
if (!context->fGpu) {
return nullptr;
}
if (!context->init(context->fGpu->refCaps(), nullptr)) {
return nullptr;
}
return context;
}
#endif
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mimagewidgetview.h"
#include "mimagewidgetview_p.h"
#include <QPixmap>
#include "mimagewidget.h"
#include "mimagewidget_p.h"
#include "mviewcreator.h"
#include "private/mwidgetview_p.h"
MImageWidgetViewPrivate::MImageWidgetViewPrivate()
: controller(NULL),
cachedPixmapSize(0, 0),
borderOpacity(1.0),
brush(Qt::transparent),
leftBorder(0.0),
topBorder(0.0),
rightBorder(0.0),
bottomBorder(0.0)
{
}
MImageWidgetViewPrivate::~MImageWidgetViewPrivate()
{
}
void MImageWidgetViewPrivate::calculateDrawRect(const QSizeF &imageSize)
{
Q_Q(MImageWidgetView);
// no image, return
if (imageSize.isEmpty())
return;
// get target size, bounded by widget size
QSizeF widgetSize = q->size();
QSizeF targetSize = widgetSize;
QSizeF t;
// get the image display size
qreal fx, fy;
controller->zoomFactor(&fx, &fy);
t.setWidth(imageSize.width()*fx);
t.setHeight(imageSize.height()*fy);
// limited by target size
t = targetSize.boundedTo(t);
// calculate the rectangle of draw
qreal dx = (widgetSize.width() - t.width()) / 2.0;
qreal dy = (widgetSize.height() - t.height()) / 2.0;
// calculate draw rect
drawRect.setRect(dx, dy, t.width(), t.height());
}
QSizeF MImageWidgetViewPrivate::calculateSourceSize(const QSizeF &imageSize)
{
QSizeF sourceSize = imageSize;
QSizeF targetSize = controller->size();
// protection codes
if (sourceSize.width() < 1.0)
sourceSize.setWidth(1.0);
if (sourceSize.height() < 1.0)
sourceSize.setHeight(1.0);
QSizeF t;
// get the image display size
qreal fx, fy;
controller->zoomFactor(&fx, &fy);
t.setWidth(imageSize.width()*fx);
t.setHeight(imageSize.height()*fy);
// update sourceSize for crop section by compare with targetSize, simulate zoom effect
qreal value;
if (t.width() > targetSize.width()) {
value = sourceSize.width();
sourceSize.setWidth(qRound(value * targetSize.width() / t.width()));
}
if (t.height() > targetSize.height()) {
value = sourceSize.height();
sourceSize.setHeight(qRound(value * targetSize.height() / t.height()));
}
return sourceSize;
}
void MImageWidgetViewPrivate::calculateSourceRect(const QSizeF &imageSize)
{
QPointF topLeft = controller->crop().topLeft();
QSizeF originalSize = controller->imageSize();
QSizeF sourceSize = calculateSourceSize(imageSize);
if (topLeft == QPointF(-1.0, -1.0)) {
// calculate default crop section
qreal dx = (originalSize.width() - sourceSize.width()) / 2.0;
qreal dy = (originalSize.height() - sourceSize.height()) / 2.0;
sourceRect = QRectF(dx, dy, sourceSize.width(), sourceSize.height());
} else {
// calculate crop section by given topLeft corner
qreal dx = topLeft.x();
qreal dy = topLeft.y();
sourceRect = QRectF(dx, dy, qMin(dx + sourceSize.width(), originalSize.width()),
qMin(dy + sourceSize.height(), originalSize.height()));
}
}
void MImageWidgetViewPrivate::checkPixmapSize()
{
Q_Q(MImageWidgetView);
const QPixmap *pixmap = controller->pixmap();
if (pixmap->size() != cachedPixmapSize) {
cachedPixmapSize = pixmap->size();
q->updateGeometry();
}
}
void MImageWidgetViewPrivate::drawBorders(QPainter *painter, const QRectF &drawRect) const
{
qreal w = leftBorder + rightBorder;
qreal h = topBorder + bottomBorder;
if (w > 0 || h > 0) {
QRectF border;
qreal oldOpacity = painter->opacity();
painter->setOpacity(borderOpacity);
qreal dx = drawRect.x() - leftBorder;
qreal dy = drawRect.y() - topBorder;
if (w > 0 && h == 0) {
// only have horizontal border
border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());
painter->fillRect(border, brush);
border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());
painter->fillRect(border, brush);
} else if (w == 0 && h > 0) {
// only have vertical border
border = QRectF(drawRect.x(), dy, drawRect.width(), topBorder);
painter->fillRect(border, brush);
border = QRectF(drawRect.x(), drawRect.y() + drawRect.height(), drawRect.width(), bottomBorder);
painter->fillRect(border, brush);
} else {
// draw top border
border = QRectF(dx, dy, drawRect.width() + w, topBorder);
painter->fillRect(border, brush);
// draw left border
border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());
painter->fillRect(border, brush);
// draw right border
border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());
painter->fillRect(border, brush);
// draw bottom border
border = QRectF(dx, drawRect.y() + drawRect.height(), drawRect.width() + w, bottomBorder);
painter->fillRect(border, brush);
}
painter->setOpacity(oldOpacity);
}
}
void MImageWidgetViewPrivate::applyStyle()
{
Q_Q(MImageWidgetView);
borderOpacity = q->style()->borderOpacity();
brush.setColor(q->style()->borderColor());
leftBorder = q->style()->borderLeft();
topBorder = q->style()->borderTop();
rightBorder = q->style()->borderRight();
bottomBorder = q->style()->borderBottom();
}
MImageWidgetView::MImageWidgetView(MImageWidget *controller) :
MWidgetView(* new MImageWidgetViewPrivate, controller)
{
Q_D(MImageWidgetView);
d->controller = controller;
}
MImageWidgetView::MImageWidgetView(MImageWidgetViewPrivate &dd, MImageWidget *controller) :
MWidgetView(dd, controller)
{
Q_D(MImageWidgetView);
d->controller = controller;
}
MImageWidgetView::~MImageWidgetView()
{
}
void MImageWidgetView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
Q_UNUSED(option);
Q_D(const MImageWidgetView);
const QPixmap *pixmap = d->controller->pixmap();
d->drawBorders(painter, d->drawRect);
if (pixmap) {
const_cast<MImageWidgetViewPrivate*>(d)->checkPixmapSize();
painter->drawPixmap(d->drawRect, *pixmap, d->sourceRect);
} else {
QImage image = d->controller->d_func()->image;
painter->drawImage(d->drawRect, image, d->sourceRect);
}
}
void MImageWidgetView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
MWidgetView::resizeEvent(event);
update();
}
void MImageWidgetView::setGeometry(const QRectF &rect)
{
Q_D(MImageWidgetView);
MWidgetView::setGeometry(rect);
QSizeF imageSize = d->controller->d_func()->imageDataSize();
d->calculateDrawRect(imageSize);
d->calculateSourceRect(imageSize);
}
void MImageWidgetView::applyStyle()
{
Q_D(MImageWidgetView);
MWidgetView::applyStyle();
d->applyStyle();
}
void MImageWidgetView::updateData(const QList<const char *> &modifications)
{
MWidgetView::updateData(modifications);
const char *member;
for (int i = 0; i < modifications.count(); i++) {
member = modifications[i];
if (member == MImageWidgetModel::ZoomFactorX || member == MImageWidgetModel::ZoomFactorY || member == MImageWidgetModel::Crop) {
updateGeometry();
}
}
}
QSizeF MImageWidgetView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
Q_D(const MImageWidgetView);
QSizeF s = MWidgetView::sizeHint(which, constraint);
if(s.isValid())
return s;
QSizeF s2;
if(which == Qt::MinimumSize)
s2 = QSizeF(0,0);
else if(which == Qt::MaximumSize)
s2 = QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
else
s2 = d->controller->imageSize();
if(s.height() < 0)
s.setHeight(s2.height());
if(s.width() < 0)
s.setWidth(s2.width());
return s;
}
M_REGISTER_VIEW_NEW(MImageWidgetView, MImageWidget)
<commit_msg>Changes: MImageWidgetView checks if widget has pixmap directly from private object.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mimagewidgetview.h"
#include "mimagewidgetview_p.h"
#include <QPixmap>
#include "mimagewidget.h"
#include "mimagewidget_p.h"
#include "mviewcreator.h"
#include "private/mwidgetview_p.h"
MImageWidgetViewPrivate::MImageWidgetViewPrivate()
: controller(NULL),
cachedPixmapSize(0, 0),
borderOpacity(1.0),
brush(Qt::transparent),
leftBorder(0.0),
topBorder(0.0),
rightBorder(0.0),
bottomBorder(0.0)
{
}
MImageWidgetViewPrivate::~MImageWidgetViewPrivate()
{
}
void MImageWidgetViewPrivate::calculateDrawRect(const QSizeF &imageSize)
{
Q_Q(MImageWidgetView);
// no image, return
if (imageSize.isEmpty())
return;
// get target size, bounded by widget size
QSizeF widgetSize = q->size();
QSizeF targetSize = widgetSize;
QSizeF t;
// get the image display size
qreal fx, fy;
controller->zoomFactor(&fx, &fy);
t.setWidth(imageSize.width()*fx);
t.setHeight(imageSize.height()*fy);
// limited by target size
t = targetSize.boundedTo(t);
// calculate the rectangle of draw
qreal dx = (widgetSize.width() - t.width()) / 2.0;
qreal dy = (widgetSize.height() - t.height()) / 2.0;
// calculate draw rect
drawRect.setRect(dx, dy, t.width(), t.height());
}
QSizeF MImageWidgetViewPrivate::calculateSourceSize(const QSizeF &imageSize)
{
QSizeF sourceSize = imageSize;
QSizeF targetSize = controller->size();
// protection codes
if (sourceSize.width() < 1.0)
sourceSize.setWidth(1.0);
if (sourceSize.height() < 1.0)
sourceSize.setHeight(1.0);
QSizeF t;
// get the image display size
qreal fx, fy;
controller->zoomFactor(&fx, &fy);
t.setWidth(imageSize.width()*fx);
t.setHeight(imageSize.height()*fy);
// update sourceSize for crop section by compare with targetSize, simulate zoom effect
qreal value;
if (t.width() > targetSize.width()) {
value = sourceSize.width();
sourceSize.setWidth(qRound(value * targetSize.width() / t.width()));
}
if (t.height() > targetSize.height()) {
value = sourceSize.height();
sourceSize.setHeight(qRound(value * targetSize.height() / t.height()));
}
return sourceSize;
}
void MImageWidgetViewPrivate::calculateSourceRect(const QSizeF &imageSize)
{
QPointF topLeft = controller->crop().topLeft();
QSizeF originalSize = controller->imageSize();
QSizeF sourceSize = calculateSourceSize(imageSize);
if (topLeft == QPointF(-1.0, -1.0)) {
// calculate default crop section
qreal dx = (originalSize.width() - sourceSize.width()) / 2.0;
qreal dy = (originalSize.height() - sourceSize.height()) / 2.0;
sourceRect = QRectF(dx, dy, sourceSize.width(), sourceSize.height());
} else {
// calculate crop section by given topLeft corner
qreal dx = topLeft.x();
qreal dy = topLeft.y();
sourceRect = QRectF(dx, dy, qMin(dx + sourceSize.width(), originalSize.width()),
qMin(dy + sourceSize.height(), originalSize.height()));
}
}
void MImageWidgetViewPrivate::checkPixmapSize()
{
Q_Q(MImageWidgetView);
const QPixmap *pixmap = controller->pixmap();
if (pixmap->size() != cachedPixmapSize) {
cachedPixmapSize = pixmap->size();
q->updateGeometry();
}
}
void MImageWidgetViewPrivate::drawBorders(QPainter *painter, const QRectF &drawRect) const
{
qreal w = leftBorder + rightBorder;
qreal h = topBorder + bottomBorder;
if (w > 0 || h > 0) {
QRectF border;
qreal oldOpacity = painter->opacity();
painter->setOpacity(borderOpacity);
qreal dx = drawRect.x() - leftBorder;
qreal dy = drawRect.y() - topBorder;
if (w > 0 && h == 0) {
// only have horizontal border
border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());
painter->fillRect(border, brush);
border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());
painter->fillRect(border, brush);
} else if (w == 0 && h > 0) {
// only have vertical border
border = QRectF(drawRect.x(), dy, drawRect.width(), topBorder);
painter->fillRect(border, brush);
border = QRectF(drawRect.x(), drawRect.y() + drawRect.height(), drawRect.width(), bottomBorder);
painter->fillRect(border, brush);
} else {
// draw top border
border = QRectF(dx, dy, drawRect.width() + w, topBorder);
painter->fillRect(border, brush);
// draw left border
border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());
painter->fillRect(border, brush);
// draw right border
border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());
painter->fillRect(border, brush);
// draw bottom border
border = QRectF(dx, drawRect.y() + drawRect.height(), drawRect.width() + w, bottomBorder);
painter->fillRect(border, brush);
}
painter->setOpacity(oldOpacity);
}
}
void MImageWidgetViewPrivate::applyStyle()
{
Q_Q(MImageWidgetView);
borderOpacity = q->style()->borderOpacity();
brush.setColor(q->style()->borderColor());
leftBorder = q->style()->borderLeft();
topBorder = q->style()->borderTop();
rightBorder = q->style()->borderRight();
bottomBorder = q->style()->borderBottom();
}
MImageWidgetView::MImageWidgetView(MImageWidget *controller) :
MWidgetView(* new MImageWidgetViewPrivate, controller)
{
Q_D(MImageWidgetView);
d->controller = controller;
}
MImageWidgetView::MImageWidgetView(MImageWidgetViewPrivate &dd, MImageWidget *controller) :
MWidgetView(dd, controller)
{
Q_D(MImageWidgetView);
d->controller = controller;
}
MImageWidgetView::~MImageWidgetView()
{
}
void MImageWidgetView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
Q_UNUSED(option);
Q_D(const MImageWidgetView);
const QPixmap *pixmap = d->controller->d_func()->pixmap;
d->drawBorders(painter, d->drawRect);
if (pixmap) {
const_cast<MImageWidgetViewPrivate*>(d)->checkPixmapSize();
painter->drawPixmap(d->drawRect, *pixmap, d->sourceRect);
} else {
QImage image = d->controller->d_func()->image;
painter->drawImage(d->drawRect, image, d->sourceRect);
}
}
void MImageWidgetView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
MWidgetView::resizeEvent(event);
update();
}
void MImageWidgetView::setGeometry(const QRectF &rect)
{
Q_D(MImageWidgetView);
MWidgetView::setGeometry(rect);
QSizeF imageSize = d->controller->d_func()->imageDataSize();
d->calculateDrawRect(imageSize);
d->calculateSourceRect(imageSize);
}
void MImageWidgetView::applyStyle()
{
Q_D(MImageWidgetView);
MWidgetView::applyStyle();
d->applyStyle();
}
void MImageWidgetView::updateData(const QList<const char *> &modifications)
{
MWidgetView::updateData(modifications);
const char *member;
for (int i = 0; i < modifications.count(); i++) {
member = modifications[i];
if (member == MImageWidgetModel::ZoomFactorX || member == MImageWidgetModel::ZoomFactorY || member == MImageWidgetModel::Crop) {
updateGeometry();
}
}
}
QSizeF MImageWidgetView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
Q_D(const MImageWidgetView);
QSizeF s = MWidgetView::sizeHint(which, constraint);
if(s.isValid())
return s;
QSizeF s2;
if(which == Qt::MinimumSize)
s2 = QSizeF(0,0);
else if(which == Qt::MaximumSize)
s2 = QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
else
s2 = d->controller->imageSize();
if(s.height() < 0)
s.setHeight(s2.height());
if(s.width() < 0)
s.setWidth(s2.width());
return s;
}
M_REGISTER_VIEW_NEW(MImageWidgetView, MImageWidget)
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mimagewidgetview.h"
#include "mimagewidgetview_p.h"
#include <QPixmap>
#include "mimagewidget.h"
#include "mimagewidget_p.h"
#include "mviewcreator.h"
#include "private/mwidgetview_p.h"
MImageWidgetViewPrivate::MImageWidgetViewPrivate()
: controller(NULL),
cachedPixmapSize(0, 0),
borderOpacity(1.0),
brush(Qt::transparent),
leftBorder(0.0),
topBorder(0.0),
rightBorder(0.0),
bottomBorder(0.0)
{
}
MImageWidgetViewPrivate::~MImageWidgetViewPrivate()
{
}
void MImageWidgetViewPrivate::calculateDrawRect(const QSizeF &imageSize)
{
Q_Q(MImageWidgetView);
// no image, return
if (imageSize.isEmpty())
return;
// get target size, bounded by widget size
QSizeF widgetSize = q->size();
QSizeF targetSize = widgetSize;
QSizeF t;
// get the image display size
qreal fx, fy;
controller->zoomFactor(&fx, &fy);
t.setWidth(imageSize.width()*fx);
t.setHeight(imageSize.height()*fy);
// limited by target size
t = targetSize.boundedTo(t);
// calculate the rectangle of draw
qreal dx = (widgetSize.width() - t.width()) / 2.f;
qreal dy = (widgetSize.height() - t.height()) / 2.f;
// calculate draw rect
drawRect.setRect(dx, dy, t.width(), t.height());
}
QSizeF MImageWidgetViewPrivate::calculateSourceSize(const QSizeF &imageSize)
{
QSizeF sourceSize = imageSize;
QSizeF targetSize = controller->size();
// protection codes
if (sourceSize.width() < 1.0)
sourceSize.setWidth(1.f);
if (sourceSize.height() < 1.0)
sourceSize.setHeight(1.f);
QSizeF t;
// get the image display size
qreal fx, fy;
controller->zoomFactor(&fx, &fy);
t.setWidth(imageSize.width()*fx);
t.setHeight(imageSize.height()*fy);
// update sourceSize for crop section by compare with targetSize, simulate zoom effect
qreal value;
if (t.width() > targetSize.width()) {
value = sourceSize.width();
sourceSize.setWidth(qRound(value * targetSize.width() / t.width()));
}
if (t.height() > targetSize.height()) {
value = sourceSize.height();
sourceSize.setHeight(qRound(value * targetSize.height() / t.height()));
}
return sourceSize;
}
void MImageWidgetViewPrivate::calculateSourceRect(const QSizeF &imageSize)
{
QPointF topLeft = controller->crop().topLeft();
QSizeF originalSize = controller->imageSize();
QSizeF sourceSize = calculateSourceSize(imageSize);
if (topLeft == QPointF(-1.0, -1.0)) {
// calculate default crop section
qreal dx = (originalSize.width() - sourceSize.width()) / 2.f;
qreal dy = (originalSize.height() - sourceSize.height()) / 2.f;
sourceRect = QRectF(dx, dy, sourceSize.width(), sourceSize.height());
} else {
// calculate crop section by given topLeft corner
qreal dx = topLeft.x();
qreal dy = topLeft.y();
sourceRect = QRectF(dx, dy, qMin(dx + sourceSize.width(), originalSize.width()),
qMin(dy + sourceSize.height(), originalSize.height()));
}
}
void MImageWidgetViewPrivate::checkPixmapSize()
{
Q_Q(MImageWidgetView);
const QPixmap *pixmap = controller->pixmap();
if (pixmap->size() != cachedPixmapSize) {
cachedPixmapSize = pixmap->size();
q->updateGeometry();
}
}
void MImageWidgetViewPrivate::drawBorders(QPainter *painter, const QRectF &drawRect) const
{
qreal w = leftBorder + rightBorder;
qreal h = topBorder + bottomBorder;
if (w > 0 || h > 0) {
QRectF border;
qreal oldOpacity = painter->opacity();
painter->setOpacity(borderOpacity);
qreal dx = drawRect.x() - leftBorder;
qreal dy = drawRect.y() - topBorder;
if (w > 0 && h == 0) {
// only have horizontal border
border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());
painter->fillRect(border, brush);
border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());
painter->fillRect(border, brush);
} else if (w == 0 && h > 0) {
// only have vertical border
border = QRectF(drawRect.x(), dy, drawRect.width(), topBorder);
painter->fillRect(border, brush);
border = QRectF(drawRect.x(), drawRect.y() + drawRect.height(), drawRect.width(), bottomBorder);
painter->fillRect(border, brush);
} else {
// draw top border
border = QRectF(dx, dy, drawRect.width() + w, topBorder);
painter->fillRect(border, brush);
// draw left border
border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());
painter->fillRect(border, brush);
// draw right border
border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());
painter->fillRect(border, brush);
// draw bottom border
border = QRectF(dx, drawRect.y() + drawRect.height(), drawRect.width() + w, bottomBorder);
painter->fillRect(border, brush);
}
painter->setOpacity(oldOpacity);
}
}
void MImageWidgetViewPrivate::applyStyle()
{
Q_Q(MImageWidgetView);
borderOpacity = q->style()->borderOpacity();
brush.setColor(q->style()->borderColor());
leftBorder = q->style()->borderLeft();
topBorder = q->style()->borderTop();
rightBorder = q->style()->borderRight();
bottomBorder = q->style()->borderBottom();
}
const QPixmap *MImageWidgetViewPrivate::createPixmapFromTheme()
{
QSize imageSize = controller->model()->imageSize();
QString imageId = controller->imageId();
if (!imageSize.isValid() || imageSize.isNull())
imageSize = preferredImageSize();
if (!imageSize.isValid())
return MTheme::pixmap(imageId);
return MTheme::pixmap(imageId, imageSize);
}
QSize MImageWidgetViewPrivate::preferredImageSize()
{
Q_Q(MImageWidgetView);
QSize imageSize = controller->preferredSize().toSize();
imageSize.setWidth(imageSize.width() - (q->marginLeft() + q->marginRight()));
imageSize.setHeight(imageSize.height() - (q->marginTop() + q->marginBottom()));
return imageSize;
}
void MImageWidgetViewPrivate::updateImageGeometry()
{
Q_Q(MImageWidgetView);
QSizeF imageSize = q->imageDataSize();
calculateDrawRect(imageSize);
calculateSourceRect(imageSize);
}
MImageWidgetView::MImageWidgetView(MImageWidget *controller) :
MWidgetView(* new MImageWidgetViewPrivate, controller)
{
Q_D(MImageWidgetView);
d->controller = controller;
}
MImageWidgetView::MImageWidgetView(MImageWidgetViewPrivate &dd, MImageWidget *controller) :
MWidgetView(dd, controller)
{
Q_D(MImageWidgetView);
d->controller = controller;
}
MImageWidgetView::~MImageWidgetView()
{
}
void MImageWidgetView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
Q_UNUSED(option);
Q_D(const MImageWidgetView);
const QPixmap *pixmap = d->controller->d_func()->getPixmap();
d->drawBorders(painter, d->drawRect);
if (pixmap) {
const_cast<MImageWidgetViewPrivate*>(d)->checkPixmapSize();
painter->drawPixmap(d->drawRect, *pixmap, d->sourceRect);
} else
painter->drawImage(d->drawRect, d->controller->d_func()->getImage(), d->sourceRect);
}
void MImageWidgetView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
MWidgetView::resizeEvent(event);
update();
}
void MImageWidgetView::setGeometry(const QRectF &rect)
{
Q_D(MImageWidgetView);
MWidgetView::setGeometry(rect);
d->updateImageGeometry();
}
void MImageWidgetView::updateGeometry()
{
Q_D(MImageWidgetView);
MWidgetView::updateGeometry();
d->updateImageGeometry();
}
void MImageWidgetView::applyStyle()
{
Q_D(MImageWidgetView);
MWidgetView::applyStyle();
d->applyStyle();
if (!model()->imageId().isEmpty())
d->controller->d_func()->setPixmap(d->createPixmapFromTheme(), false);
}
void MImageWidgetView::updateData(const QList<const char *> &modifications)
{
Q_D(MImageWidgetView);
MWidgetView::updateData(modifications);
bool needsGeometryUpdate = false;
bool needsPixmap = false;
const char *member;
for (int i = 0; i < modifications.count(); i++) {
member = modifications[i];
if (member == MImageWidgetModel::ZoomFactorX ||
member == MImageWidgetModel::ZoomFactorY ||
member == MImageWidgetModel::Crop ||
member == MImageWidgetModel::AspectRatioMode) {
needsGeometryUpdate = true;
} else if (member == MImageWidgetModel::ImageId ||
member == MImageWidgetModel::ImageSize) {
needsPixmap = true;
}
}
if (needsPixmap && !model()->imageId().isEmpty())
d->controller->d_func()->setPixmap(d->createPixmapFromTheme(), false);
if (needsGeometryUpdate || needsPixmap)
updateGeometry();
}
QSizeF MImageWidgetView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
Q_D(const MImageWidgetView);
if (which == Qt::MinimumSize || which == Qt::MaximumSize)
return QSizeF(-1,-1);
QSizeF size = d->controller->imageSize();
// an empty QSize() translates to (-1,-1) which would result in an incorrect size hint
if (!size.isValid())
size = QSizeF(0, 0);
if (constraint.width() >= 0 && constraint.width() < size.width())
size.scale(QSizeF(constraint.width(), QWIDGETSIZE_MAX), Qt::KeepAspectRatio);
else if (constraint.height() >= 0 && constraint.height() < size.height())
size.scale(QSizeF(QWIDGETSIZE_MAX, constraint.height()), Qt::KeepAspectRatio);
return size;
}
QSize MImageWidgetView::imageDataSize()
{
Q_D(MImageWidgetView);
return d->controller->d_func()->imageDataSize(model()->crop()).toSize();
}
M_REGISTER_VIEW_NEW(MImageWidgetView, MImageWidget)
<commit_msg>Fixes: NB#299022 - MImageWidget does not render properly the images when a QPixmap is used Changes: enable smooth transformation in MImageWidget for QPixmap RevBy: Heikki Holstila, Vesa Halttunen Details: when the setPixmap method is used in MImageWidget, the QPixmap is provided without mthedaemon interaction, thus, MScalableImage is not called, and it is a requirement to draw the QPixmap with the same transformation as MThemedaemon does, to avoid any blurriness<commit_after>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mimagewidgetview.h"
#include "mimagewidgetview_p.h"
#include <QPixmap>
#include "mimagewidget.h"
#include "mimagewidget_p.h"
#include "mviewcreator.h"
#include "private/mwidgetview_p.h"
MImageWidgetViewPrivate::MImageWidgetViewPrivate()
: controller(NULL),
cachedPixmapSize(0, 0),
borderOpacity(1.0),
brush(Qt::transparent),
leftBorder(0.0),
topBorder(0.0),
rightBorder(0.0),
bottomBorder(0.0)
{
}
MImageWidgetViewPrivate::~MImageWidgetViewPrivate()
{
}
void MImageWidgetViewPrivate::calculateDrawRect(const QSizeF &imageSize)
{
Q_Q(MImageWidgetView);
// no image, return
if (imageSize.isEmpty())
return;
// get target size, bounded by widget size
QSizeF widgetSize = q->size();
QSizeF targetSize = widgetSize;
QSizeF t;
// get the image display size
qreal fx, fy;
controller->zoomFactor(&fx, &fy);
t.setWidth(imageSize.width()*fx);
t.setHeight(imageSize.height()*fy);
// limited by target size
t = targetSize.boundedTo(t);
// calculate the rectangle of draw
qreal dx = (widgetSize.width() - t.width()) / 2.f;
qreal dy = (widgetSize.height() - t.height()) / 2.f;
// calculate draw rect
drawRect.setRect(dx, dy, t.width(), t.height());
}
QSizeF MImageWidgetViewPrivate::calculateSourceSize(const QSizeF &imageSize)
{
QSizeF sourceSize = imageSize;
QSizeF targetSize = controller->size();
// protection codes
if (sourceSize.width() < 1.0)
sourceSize.setWidth(1.f);
if (sourceSize.height() < 1.0)
sourceSize.setHeight(1.f);
QSizeF t;
// get the image display size
qreal fx, fy;
controller->zoomFactor(&fx, &fy);
t.setWidth(imageSize.width()*fx);
t.setHeight(imageSize.height()*fy);
// update sourceSize for crop section by compare with targetSize, simulate zoom effect
qreal value;
if (t.width() > targetSize.width()) {
value = sourceSize.width();
sourceSize.setWidth(qRound(value * targetSize.width() / t.width()));
}
if (t.height() > targetSize.height()) {
value = sourceSize.height();
sourceSize.setHeight(qRound(value * targetSize.height() / t.height()));
}
return sourceSize;
}
void MImageWidgetViewPrivate::calculateSourceRect(const QSizeF &imageSize)
{
QPointF topLeft = controller->crop().topLeft();
QSizeF originalSize = controller->imageSize();
QSizeF sourceSize = calculateSourceSize(imageSize);
if (topLeft == QPointF(-1.0, -1.0)) {
// calculate default crop section
qreal dx = (originalSize.width() - sourceSize.width()) / 2.f;
qreal dy = (originalSize.height() - sourceSize.height()) / 2.f;
sourceRect = QRectF(dx, dy, sourceSize.width(), sourceSize.height());
} else {
// calculate crop section by given topLeft corner
qreal dx = topLeft.x();
qreal dy = topLeft.y();
sourceRect = QRectF(dx, dy, qMin(dx + sourceSize.width(), originalSize.width()),
qMin(dy + sourceSize.height(), originalSize.height()));
}
}
void MImageWidgetViewPrivate::checkPixmapSize()
{
Q_Q(MImageWidgetView);
const QPixmap *pixmap = controller->pixmap();
if (pixmap->size() != cachedPixmapSize) {
cachedPixmapSize = pixmap->size();
q->updateGeometry();
}
}
void MImageWidgetViewPrivate::drawBorders(QPainter *painter, const QRectF &drawRect) const
{
qreal w = leftBorder + rightBorder;
qreal h = topBorder + bottomBorder;
if (w > 0 || h > 0) {
QRectF border;
qreal oldOpacity = painter->opacity();
painter->setOpacity(borderOpacity);
qreal dx = drawRect.x() - leftBorder;
qreal dy = drawRect.y() - topBorder;
if (w > 0 && h == 0) {
// only have horizontal border
border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());
painter->fillRect(border, brush);
border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());
painter->fillRect(border, brush);
} else if (w == 0 && h > 0) {
// only have vertical border
border = QRectF(drawRect.x(), dy, drawRect.width(), topBorder);
painter->fillRect(border, brush);
border = QRectF(drawRect.x(), drawRect.y() + drawRect.height(), drawRect.width(), bottomBorder);
painter->fillRect(border, brush);
} else {
// draw top border
border = QRectF(dx, dy, drawRect.width() + w, topBorder);
painter->fillRect(border, brush);
// draw left border
border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());
painter->fillRect(border, brush);
// draw right border
border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());
painter->fillRect(border, brush);
// draw bottom border
border = QRectF(dx, drawRect.y() + drawRect.height(), drawRect.width() + w, bottomBorder);
painter->fillRect(border, brush);
}
painter->setOpacity(oldOpacity);
}
}
void MImageWidgetViewPrivate::applyStyle()
{
Q_Q(MImageWidgetView);
borderOpacity = q->style()->borderOpacity();
brush.setColor(q->style()->borderColor());
leftBorder = q->style()->borderLeft();
topBorder = q->style()->borderTop();
rightBorder = q->style()->borderRight();
bottomBorder = q->style()->borderBottom();
}
const QPixmap *MImageWidgetViewPrivate::createPixmapFromTheme()
{
QSize imageSize = controller->model()->imageSize();
QString imageId = controller->imageId();
if (!imageSize.isValid() || imageSize.isNull())
imageSize = preferredImageSize();
if (!imageSize.isValid())
return MTheme::pixmap(imageId);
return MTheme::pixmap(imageId, imageSize);
}
QSize MImageWidgetViewPrivate::preferredImageSize()
{
Q_Q(MImageWidgetView);
QSize imageSize = controller->preferredSize().toSize();
imageSize.setWidth(imageSize.width() - (q->marginLeft() + q->marginRight()));
imageSize.setHeight(imageSize.height() - (q->marginTop() + q->marginBottom()));
return imageSize;
}
void MImageWidgetViewPrivate::updateImageGeometry()
{
Q_Q(MImageWidgetView);
QSizeF imageSize = q->imageDataSize();
calculateDrawRect(imageSize);
calculateSourceRect(imageSize);
}
MImageWidgetView::MImageWidgetView(MImageWidget *controller) :
MWidgetView(* new MImageWidgetViewPrivate, controller)
{
Q_D(MImageWidgetView);
d->controller = controller;
}
MImageWidgetView::MImageWidgetView(MImageWidgetViewPrivate &dd, MImageWidget *controller) :
MWidgetView(dd, controller)
{
Q_D(MImageWidgetView);
d->controller = controller;
}
MImageWidgetView::~MImageWidgetView()
{
}
void MImageWidgetView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
Q_UNUSED(option);
Q_D(const MImageWidgetView);
const QPixmap *pixmap = d->controller->d_func()->getPixmap();
d->drawBorders(painter, d->drawRect);
if (pixmap) {
const_cast<MImageWidgetViewPrivate*>(d)->checkPixmapSize();
// Because we are providing the pixmap directly without themedaemon
// mscalableimage it is not called, thus, in order to have a smooth
// scalation of the pixmap we need to draw it with a smooth transformation
static bool enabled = painter->renderHints() & QPainter::SmoothPixmapTransform;
painter->setRenderHint(QPainter::SmoothPixmapTransform);
painter->drawPixmap(d->drawRect, *pixmap, d->sourceRect);
painter->setRenderHint(QPainter::SmoothPixmapTransform, enabled);
} else
painter->drawImage(d->drawRect, d->controller->d_func()->getImage(), d->sourceRect);
}
void MImageWidgetView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
MWidgetView::resizeEvent(event);
update();
}
void MImageWidgetView::setGeometry(const QRectF &rect)
{
Q_D(MImageWidgetView);
MWidgetView::setGeometry(rect);
d->updateImageGeometry();
}
void MImageWidgetView::updateGeometry()
{
Q_D(MImageWidgetView);
MWidgetView::updateGeometry();
d->updateImageGeometry();
}
void MImageWidgetView::applyStyle()
{
Q_D(MImageWidgetView);
MWidgetView::applyStyle();
d->applyStyle();
if (!model()->imageId().isEmpty())
d->controller->d_func()->setPixmap(d->createPixmapFromTheme(), false);
}
void MImageWidgetView::updateData(const QList<const char *> &modifications)
{
Q_D(MImageWidgetView);
MWidgetView::updateData(modifications);
bool needsGeometryUpdate = false;
bool needsPixmap = false;
const char *member;
for (int i = 0; i < modifications.count(); i++) {
member = modifications[i];
if (member == MImageWidgetModel::ZoomFactorX ||
member == MImageWidgetModel::ZoomFactorY ||
member == MImageWidgetModel::Crop ||
member == MImageWidgetModel::AspectRatioMode) {
needsGeometryUpdate = true;
} else if (member == MImageWidgetModel::ImageId ||
member == MImageWidgetModel::ImageSize) {
needsPixmap = true;
}
}
if (needsPixmap && !model()->imageId().isEmpty())
d->controller->d_func()->setPixmap(d->createPixmapFromTheme(), false);
if (needsGeometryUpdate || needsPixmap)
updateGeometry();
}
QSizeF MImageWidgetView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
Q_D(const MImageWidgetView);
if (which == Qt::MinimumSize || which == Qt::MaximumSize)
return QSizeF(-1,-1);
QSizeF size = d->controller->imageSize();
// an empty QSize() translates to (-1,-1) which would result in an incorrect size hint
if (!size.isValid())
size = QSizeF(0, 0);
if (constraint.width() >= 0 && constraint.width() < size.width())
size.scale(QSizeF(constraint.width(), QWIDGETSIZE_MAX), Qt::KeepAspectRatio);
else if (constraint.height() >= 0 && constraint.height() < size.height())
size.scale(QSizeF(QWIDGETSIZE_MAX, constraint.height()), Qt::KeepAspectRatio);
return size;
}
QSize MImageWidgetView::imageDataSize()
{
Q_D(MImageWidgetView);
return d->controller->d_func()->imageDataSize(model()->crop()).toSize();
}
M_REGISTER_VIEW_NEW(MImageWidgetView, MImageWidget)
<|endoftext|> |
<commit_before>//sg: this is going to be the primary vision node for qubo (or future robots, whatever)
#include "vision_node.h"
using namespace std;
using namespace ros;
using namespace AVT::VmbAPI;
//you need to pass in a node handle, and a camera feed, which should be a file path either to a physical device or to a video
VisionNode::VisionNode(NodeHandle n, NodeHandle np, string feed)
: m_buoy_server(n, "buoy_action", boost::bind(&VisionNode::findBuoy, this, _1, &m_buoy_server), false),
m_gate_server(n, "gate_action", boost::bind(&VisionNode::findGate, this, _1, &m_gate_server), false)
{
// isdigit makes sure checks if we're dealing with a number (like if want to open the default camera by passing a 0). If we are we convert our string to an int (VideoCapture won't correctly open the camera with the string in this case);
//this could give us problems if we pass something like "0followed_by_string" but just don't do that.
//sgillen@20170429-07:04 we really don't even need this... we can just pass in /dev/video0 if we want the web camera... I'll leave it for now though
if(feed == "IP") {
// use the mako if feed isn't given
//start the camera
auto vmb_err = [](const int func_call, const string err_msg) {
if (func_call != VmbErrorSuccess){
ROS_ERROR("%s, code: %i", err_msg.c_str(), func_call);
return func_call;
}
return func_call;
};
ROS_ERROR("getting Vimba");
auto& m_vimba_sys = VimbaSystem::GetInstance();
if( vmb_err(m_vimba_sys.Startup(), "Unable to start the Vimba System") ) { exit(1); }
ROS_ERROR("finding cameras");
CameraPtrVector c_vec;
if( vmb_err(m_vimba_sys.GetCameras( c_vec ), "Unable to find cameras") ) {exit(1); }
// Since we only have one camera currently, we can just use the first thing returned when getting all the cameras
m_gige_camera = c_vec[0];
string camera_id;
if (vmb_err(m_gige_camera->GetID(camera_id), "Unable to get a camera ID from Vimba") ){ exit(1); }
while( !vmb_err(m_gige_camera->Open(VmbAccessModeFull), "Error opening a camera with Vimba") ) {}
// We need to height, width and pixel format of the camera to convert the images to something OpenCV likes
FeaturePtr feat;
if(!vmb_err(m_gige_camera->GetFeatureByName( "Width", feat), ("Error getting the camera width" ))){
VmbInt64_t width;
if (!vmb_err(feat->GetValue(width), "Error getting width")) {
ROS_ERROR("Width: %lld", width);
m_width = width;
}
}
if(!vmb_err(m_gige_camera->GetFeatureByName( "Height", feat), ("Error getting the camera height" ))){
VmbInt64_t height;
if (!vmb_err(feat->GetValue(height), "Error getting height")) {
ROS_ERROR("Height: %lld", height);
m_height = height;
}
}
if(!vmb_err(m_gige_camera->GetFeatureByName("PixelFormat", feat), "Error getting pixel format")){
vmb_err(feat->GetValue(m_pixel_format), "Error getting format");
}
} else {
if(isdigit(feed.c_str()[0])){
m_cap = cv::VideoCapture(atoi(feed.c_str()));
}
else{
m_cap = cv::VideoCapture(feed);
}
//make sure we have something valid
if(!m_cap.isOpened()){
ROS_ERROR("couldn't open file/camera %s\n now exiting" ,feed.c_str());
exit(0);
}
m_width = m_cap.get(CV_CAP_PROP_FRAME_WIDTH);
m_height = m_cap.get(CV_CAP_PROP_FRAME_HEIGHT);
}
//TODO give option to user to specify the name of the video
//TODO make sure this doesn't fail when specifying a directory that does not yet exist
string output_dir;
np.param<string>("output_dir", output_dir, ""); //this line will populate the output_dir variable if it's specified in the launch file
//TODO change variable names
if(!output_dir.empty()){
stringstream output_ss;
auto t = time(nullptr);
auto tm = *localtime(&t);
output_ss << output_dir;
output_ss << put_time(&tm, "%Y%m%d_%H-%M-%S");
output_ss << ".avi";
string output_str = output_ss.str();
int ex = static_cast<int>(m_cap.get(CV_CAP_PROP_FOURCC));
cv::Size S = cv::Size((int) m_width, // Acquire input size
(int) m_height);
//sgillen@20172107-06:21 I found more problems trying to keep the extension (by passing ex as the second argument) than I did by forcing the output to be CV_FOURCC('M','J','P','G')
//m_output_video.open(output_str, ex, m_cap.get(CV_CAP_PROP_FPS), S, true);
m_output_video.open(output_str, CV_FOURCC('M','J','P','G'), 20/* m_cap.get(CV_CAP_PROP_FPS) */, S, true);
if(!m_output_video.isOpened()){
ROS_ERROR("problem opening output video! we tried saving it as %s, now exiting" ,output_str.c_str());
exit(0);
}
ROS_INFO("output video being saved as %s" , output_str.c_str());
}
//register all services here
//------------------------------------------------------------------------------
m_test_srv = n.advertiseService("service_test", &VisionNode::serviceTest, this);
//start your action servers here
//------------------------------------------------------------------------------
m_buoy_server.start();
m_gate_server.start();
ROS_INFO("servers started");
}
VisionNode::~VisionNode(){
//sg: may need to close the cameras here not sure..
auto& m_vimba_sys = VimbaSystem::GetInstance();
m_gige_camera->Close();
m_vimba_sys.Shutdown();
}
void VisionNode::update(){
// Use the mako if its present
if (m_gige_camera == nullptr){
ROS_ERROR("Get vimba frame");
getVmbFrame(m_img);
} else {
m_cap >> m_img;
}
//if one of our frames was empty it means we ran out of footage, should only happen with test feeds or if a camera breaks I guess
if(m_img.empty()){
// ROS_ERROR("ran out of video (one of the frames was empty) exiting node now");
// exit(0);
ROS_ERROR("Empty Frame");
}
//if the user didn't specify a directory this will not be open
if(m_output_video.isOpened()){
ROS_ERROR("writing image!");
m_output_video << m_img;
}
spinOnce();
}
void VisionNode::getVmbFrame(cv::Mat& cv_frame){
if(m_gige_camera == nullptr) {
ROS_ERROR("Attempted to get a frame from a null Vimba camera pointer");
return;
}
// This is a wrapper for the Vimba error functions
// call a function in it and give it an error message to print
// if the function fails
// it also returns the error code, so you can still fail if you need to
auto vmb_err = [](const int func_call, const string err_msg) {
if (func_call != VmbErrorSuccess){
ROS_ERROR("%s, code: %i", err_msg.c_str(), func_call);
return func_call;
}
return func_call;
};
FramePtr vmb_frame;
if( vmb_err( m_gige_camera->AcquireSingleImage(vmb_frame, 2), "Error getting single frame" ) ) { return; }
VmbFrameStatusType status;
vmb_frame->GetReceiveStatus(status);
if(status != VmbFrameStatusComplete) {
ROS_ERROR("Malformed frame received");
return;
}
VmbUint32_t size;
vmb_frame->GetImageSize(size);
unsigned char* img_buf;
if( vmb_err( vmb_frame->GetImage(img_buf), "Error getting image buffer")) { return; }
VmbImage img_src, img_dest;
img_src.Size = sizeof( img_src );
img_dest.Size = sizeof( img_dest );
VmbSetImageInfoFromPixelFormat( m_pixel_format, m_width, m_height, &img_src);
VmbSetImageInfoFromPixelFormat(VmbPixelFormatBgr8, m_width, m_height, &img_dest);
img_src.Data = img_buf;
img_src.Data = cv_frame.data;
vmb_err( VmbImageTransform(&img_src, &img_dest, NULL, 0), "Error transforming image" );
}
/*
* Past this point is a collection of services and
* actions that will be able to called from any other node
* =================================================================================================================
*/
bool VisionNode::serviceTest(ram_msgs::bool_bool::Request &req, ram_msgs::bool_bool::Response &res){
ROS_ERROR("service called successfully");
}
//There are the definitions for all of our actionlib actions, may be moved to it's own class not sure yet.
//=================================================================================================================
void VisionNode::testExecute(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer<ram_msgs::VisionNavAction> *as){
// goal->test_feedback = 5;
ROS_ERROR("You called the action well done!");
as->setSucceeded();
}
//if a buoy is found on frame finds where it is and returns the center offset
void VisionNode::findBuoy(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer<ram_msgs::VisionNavAction> *as){
BuoyAction action = BuoyAction(as);
while(true){
action.updateAction(m_img); //this will also publish the feedback
}
as->setSucceeded();
}
void VisionNode::findGate(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer<ram_msgs::VisionNavAction> *as){
GateAction action = GateAction();
while(true){
ROS_ERROR("updating action");
action.updateAction(m_img);
}
as->setSucceeded();
}
<commit_msg>tweaks<commit_after>//sg: this is going to be the primary vision node for qubo (or future robots, whatever)
#include "vision_node.h"
using namespace std;
using namespace ros;
using namespace AVT::VmbAPI;
//you need to pass in a node handle, and a camera feed, which should be a file path either to a physical device or to a video
VisionNode::VisionNode(NodeHandle n, NodeHandle np, string feed)
: m_buoy_server(n, "buoy_action", boost::bind(&VisionNode::findBuoy, this, _1, &m_buoy_server), false),
m_gate_server(n, "gate_action", boost::bind(&VisionNode::findGate, this, _1, &m_gate_server), false)
{
// isdigit makes sure checks if we're dealing with a number (like if want to open the default camera by passing a 0). If we are we convert our string to an int (VideoCapture won't correctly open the camera with the string in this case);
//this could give us problems if we pass something like "0followed_by_string" but just don't do that.
//sgillen@20170429-07:04 we really don't even need this... we can just pass in /dev/video0 if we want the web camera... I'll leave it for now though
if(feed == "IP") {
// use the mako if feed isn't given
//start the camera
auto vmb_err = [](const int func_call, const string err_msg) {
if (func_call != VmbErrorSuccess){
ROS_ERROR("%s, code: %i", err_msg.c_str(), func_call);
return func_call;
}
return func_call;
};
ROS_ERROR("getting Vimba");
auto& m_vimba_sys = VimbaSystem::GetInstance();
if( vmb_err(m_vimba_sys.Startup(), "Unable to start the Vimba System") ) { exit(1); }
ROS_ERROR("finding cameras");
CameraPtrVector c_vec;
if( vmb_err(m_vimba_sys.GetCameras( c_vec ), "Unable to find cameras") ) {exit(1); }
// Since we only have one camera currently, we can just use the first thing returned when getting all the cameras
m_gige_camera = c_vec[0];
string camera_id;
if (vmb_err(m_gige_camera->GetID(camera_id), "Unable to get a camera ID from Vimba") ){ exit(1); }
while( !vmb_err(m_gige_camera->Open(VmbAccessModeFull), "Error opening a camera with Vimba") ) {}
// We need to height, width and pixel format of the camera to convert the images to something OpenCV likes
FeaturePtr feat;
if(!vmb_err(m_gige_camera->GetFeatureByName( "Width", feat), ("Error getting the camera width" ))){
VmbInt64_t width;
if (!vmb_err(feat->GetValue(width), "Error getting width")) {
ROS_ERROR("Width: %lld", width);
m_width = width;
}
}
if(!vmb_err(m_gige_camera->GetFeatureByName( "Height", feat), ("Error getting the camera height" ))){
VmbInt64_t height;
if (!vmb_err(feat->GetValue(height), "Error getting height")) {
ROS_ERROR("Height: %lld", height);
m_height = height;
}
}
if(!vmb_err(m_gige_camera->GetFeatureByName("PixelFormat", feat), "Error getting pixel format")){
vmb_err(feat->GetValue(m_pixel_format), "Error getting format");
}
} else {
if(isdigit(feed.c_str()[0])){
m_cap = cv::VideoCapture(atoi(feed.c_str()));
}
else{
m_cap = cv::VideoCapture(feed);
}
//make sure we have something valid
if(!m_cap.isOpened()){
ROS_ERROR("couldn't open file/camera %s\n now exiting" ,feed.c_str());
exit(0);
}
m_width = m_cap.get(CV_CAP_PROP_FRAME_WIDTH);
m_height = m_cap.get(CV_CAP_PROP_FRAME_HEIGHT);
}
//TODO give option to user to specify the name of the video
//TODO make sure this doesn't fail when specifying a directory that does not yet exist
string output_dir;
np.param<string>("output_dir", output_dir, ""); //this line will populate the output_dir variable if it's specified in the launch file
//TODO change variable names
if(!output_dir.empty()){
stringstream output_ss;
auto t = time(nullptr);
auto tm = *localtime(&t);
output_ss << output_dir;
output_ss << put_time(&tm, "%Y%m%d_%H-%M-%S");
output_ss << ".avi";
string output_str = output_ss.str();
int ex = static_cast<int>(m_cap.get(CV_CAP_PROP_FOURCC));
cv::Size S = cv::Size((int) m_width, // Acquire input size
(int) m_height);
//sgillen@20172107-06:21 I found more problems trying to keep the extension (by passing ex as the second argument) than I did by forcing the output to be CV_FOURCC('M','J','P','G')
//m_output_video.open(output_str, ex, m_cap.get(CV_CAP_PROP_FPS), S, true);
m_output_video.open(output_str, CV_FOURCC('M','J','P','G'), 20/* m_cap.get(CV_CAP_PROP_FPS) */, S, true);
if(!m_output_video.isOpened()){
ROS_ERROR("problem opening output video! we tried saving it as %s, now exiting" ,output_str.c_str());
exit(0);
}
ROS_INFO("output video being saved as %s" , output_str.c_str());
}
//register all services here
//------------------------------------------------------------------------------
m_test_srv = n.advertiseService("service_test", &VisionNode::serviceTest, this);
//start your action servers here
//------------------------------------------------------------------------------
m_buoy_server.start();
m_gate_server.start();
ROS_INFO("servers started");
}
VisionNode::~VisionNode(){
//sg: may need to close the cameras here not sure..
auto& m_vimba_sys = VimbaSystem::GetInstance();
m_gige_camera->Close();
m_vimba_sys.Shutdown();
}
void VisionNode::update(){
// Use the mako if its present
if (m_gige_camera != nullptr){
ROS_ERROR("Get vimba frame");
getVmbFrame(m_img);
ROS_ERROR("%s", m_img.data);
} else {
m_cap >> m_img;
}
//if one of our frames was empty it means we ran out of footage, should only happen with test feeds or if a camera breaks I guess
if(m_img.empty()){
// ROS_ERROR("ran out of video (one of the frames was empty) exiting node now");
// exit(0);
ROS_ERROR("Empty Frame");
}
//if the user didn't specify a directory this will not be open
if(m_output_video.isOpened()){
ROS_ERROR("writing image!");
m_output_video << m_img;
}
spinOnce();
}
void VisionNode::getVmbFrame(cv::Mat& cv_frame){
if(m_gige_camera == nullptr) {
ROS_ERROR("Attempted to get a frame from a null Vimba camera pointer");
return;
}
// This is a wrapper for the Vimba error functions
// call a function in it and give it an error message to print
// if the function fails
// it also returns the error code, so you can still fail if you need to
auto vmb_err = [](const int func_call, const string err_msg) {
if (func_call != VmbErrorSuccess){
ROS_ERROR("%s, code: %i", err_msg.c_str(), func_call);
return func_call;
}
return func_call;
};
FramePtr vmb_frame;
if( vmb_err( m_gige_camera->AcquireSingleImage(vmb_frame, 2), "Error getting single frame" ) ) { return; }
VmbFrameStatusType status;
vmb_frame->GetReceiveStatus(status);
if(status != VmbFrameStatusComplete) {
ROS_ERROR("Malformed frame received");
return;
}
VmbUint32_t size;
vmb_frame->GetImageSize(size);
unsigned char* img_buf;
if( vmb_err( vmb_frame->GetImage(img_buf), "Error getting image buffer")) { return; }
VmbImage img_src, img_dest;
img_src.Size = sizeof( img_src );
img_dest.Size = sizeof( img_dest );
VmbSetImageInfoFromPixelFormat( m_pixel_format, m_width, m_height, &img_src);
VmbSetImageInfoFromPixelFormat(VmbPixelFormatBgr8, m_width, m_height, &img_dest);
img_src.Data = img_buf;
img_src.Data = cv_frame.data;
vmb_err( VmbImageTransform(&img_src, &img_dest, NULL, 0), "Error transforming image" );
}
/*
* Past this point is a collection of services and
* actions that will be able to called from any other node
* =================================================================================================================
*/
bool VisionNode::serviceTest(ram_msgs::bool_bool::Request &req, ram_msgs::bool_bool::Response &res){
ROS_ERROR("service called successfully");
}
//There are the definitions for all of our actionlib actions, may be moved to it's own class not sure yet.
//=================================================================================================================
void VisionNode::testExecute(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer<ram_msgs::VisionNavAction> *as){
// goal->test_feedback = 5;
ROS_ERROR("You called the action well done!");
as->setSucceeded();
}
//if a buoy is found on frame finds where it is and returns the center offset
void VisionNode::findBuoy(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer<ram_msgs::VisionNavAction> *as){
BuoyAction action = BuoyAction(as);
while(true){
action.updateAction(m_img); //this will also publish the feedback
}
as->setSucceeded();
}
void VisionNode::findGate(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer<ram_msgs::VisionNavAction> *as){
GateAction action = GateAction();
while(true){
ROS_ERROR("updating action");
action.updateAction(m_img);
}
as->setSucceeded();
}
<|endoftext|> |
<commit_before>
#include <functional>
#include <random>
#include <ncurses.h>
#include <string.h>
#include <vector>
#include "data.h"
#include "maze.h"
#include "menu.h"
#include "story.h"
#include "windows.h"
using namespace std;
// forward declarations
menu_state game_ui(WINDOW *menu_win, game_data *d, menu_state state);
static void get_new_dims(int& nrows, int& ncols, int level);
/**
* The game maze GUI.
*
* Use arrow keys to navigate the maze or type "q" to quit.
*/
menu_state game_ui(WINDOW *win, game_data *d, menu_state state)
{
maze_data *maze = &d->maze;
player_data *player = &d->player;
int c;
int win_y(15);
int win_x(15);
int last_win_y, last_win_x;
// init window at current resolution
if (maze->level == -1) {
intro_splash(win);
}
init_maze_window(win);
getmaxyx(stdscr, win_y, win_x);
last_win_y = win_y;
last_win_x = win_x;
// generate a new maze, if necessary
if (maze->level == -1) {
// TODO: Move to data.cpp
backtracking_maze_gen(maze);
gen_entrances_opposites(maze);
std::fill_n(player->visited, maze->max_size * maze->max_size / 2, false);
player->visited[maze->finish[0] * maze->max_size + maze->finish[1]] = true;
player->loc[0] = maze->start[0];
player->loc[1] = maze->start[1];
maze->level = 0;
maze->difficulty = state;
}
// select the appropriate print function
function<void(WINDOW*, const maze_data, const int[], const bool[])> maze_print = \
state == game_easy ? maze_print_easy : (state == game_medium ? maze_print_medium : maze_print_hard);
// game loop
while (true) {
player->visited[player->loc[0] * maze->max_size + player->loc[1]] = true;
maze_print(win, *maze, player->loc, player->visited);
// input and update
c = wgetch(win);
switch (c) {
case KEY_UP:
if (maze_valid_move(*maze, player->loc[0] - 1, player->loc[1])) {
player->loc[0] -= 1;
}
break;
case KEY_DOWN:
if (maze_valid_move(*maze, player->loc[0] + 1, player->loc[1])) {
player->loc[0] += 1;
}
break;
case KEY_LEFT:
if (maze_valid_move(*maze, player->loc[0], player->loc[1] - 1)) {
player->loc[1] -= 1;
}
break;
case KEY_RIGHT:
if (maze_valid_move(*maze, player->loc[0], player->loc[1] + 1)) {
player->loc[1] += 1;
}
break;
case 113: // q
return menu_cont;
case KEY_RESIZE:
getmaxyx(stdscr, win_y, win_x);
if (last_win_x != win_x || last_win_y != win_y) {
last_win_y = win_y;
last_win_x = win_x;
wresize(win, win_y, win_x);
wclear(win);
box(win, 0, 0);
refresh();
wrefresh(win);
}
break;
// no default actions to be taken
}
// TODO: How to better check for value equality in arrays?
// If you reach the end, start over in a new maze
if (player->loc[0] == maze->finish[0] && player->loc[1] == maze->finish[1]) {
success_splash(win, maze->level + 2);
wclear(win);
clear();
box(win, 0, 0);
refresh();
wrefresh(win);
get_new_dims(maze->nrows, maze->ncols, maze->level);
// generate a new maze
std::fill_n(player->visited, maze->max_size * maze->max_size / 2, false);
backtracking_maze_gen(maze);
gen_entrances_opposites(maze);
player->loc[0] = maze->start[0];
player->loc[1] = maze->start[1];
maze->level += 1;
}
}
}
/**
* Randomly generate maze dimensions.
*/
static void get_new_dims(int& nrows, int& ncols, int level) {
level %= 20;
const int bottom_y = 15;
nrows = bottom_y + level / 2 + (rand() % (int)(level / 2 + 1));
if (nrows % 2 == 0) { nrows += 1; }
const int bottom_x = 31;
ncols = bottom_x + level + (rand() % (int)((level) + 1));
if (ncols % 2 == 0) { ncols += 1; }
}
<commit_msg>minor cleanup<commit_after>
#include <functional>
#include <random>
#include <ncurses.h>
#include <string.h>
#include <vector>
#include "data.h"
#include "maze.h"
#include "menu.h"
#include "story.h"
#include "windows.h"
using namespace std;
// forward declarations
menu_state game_ui(WINDOW *menu_win, game_data *d, menu_state state);
static void get_new_dims(int& nrows, int& ncols, int level);
/**
* The game maze GUI.
*
* Use arrow keys to navigate the maze or type "q" to quit.
*/
menu_state game_ui(WINDOW *win, game_data *d, menu_state state)
{
maze_data *maze = &d->maze;
player_data *player = &d->player;
int c;
int win_y(15);
int win_x(15);
int last_win_y, last_win_x;
// init window at current resolution
if (maze->level == -1) {
intro_splash(win);
}
init_maze_window(win);
getmaxyx(stdscr, win_y, win_x);
last_win_y = win_y;
last_win_x = win_x;
// generate a new maze, if necessary
if (maze->level == -1) {
// TODO: Move to data.cpp
backtracking_maze_gen(maze);
gen_entrances_opposites(maze);
std::fill_n(player->visited, maze->max_size * maze->max_size / 2, false);
player->visited[maze->finish[0] * maze->max_size + maze->finish[1]] = true;
player->loc[0] = maze->start[0];
player->loc[1] = maze->start[1];
maze->level = 0;
maze->difficulty = state;
}
// select the appropriate print function
function<void(WINDOW*, const maze_data, const int[], const bool[])> maze_print = \
state == game_easy ? maze_print_easy : (state == game_medium ? maze_print_medium : maze_print_hard);
// game loop
while (true) {
player->visited[player->loc[0] * maze->max_size + player->loc[1]] = true;
maze_print(win, *maze, player->loc, player->visited);
// input and update
c = wgetch(win);
switch (c) {
case KEY_UP:
if (maze_valid_move(*maze, player->loc[0] - 1, player->loc[1])) {
player->loc[0] -= 1;
}
break;
case KEY_DOWN:
if (maze_valid_move(*maze, player->loc[0] + 1, player->loc[1])) {
player->loc[0] += 1;
}
break;
case KEY_LEFT:
if (maze_valid_move(*maze, player->loc[0], player->loc[1] - 1)) {
player->loc[1] -= 1;
}
break;
case KEY_RIGHT:
if (maze_valid_move(*maze, player->loc[0], player->loc[1] + 1)) {
player->loc[1] += 1;
}
break;
case 113: // q
return menu_cont;
case KEY_RESIZE:
getmaxyx(stdscr, win_y, win_x);
if (last_win_x != win_x || last_win_y != win_y) {
last_win_y = win_y;
last_win_x = win_x;
wresize(win, win_y, win_x);
wclear(win);
box(win, 0, 0);
refresh();
wrefresh(win);
}
break;
// no default actions to be taken
}
// If you reach the end, start over in a new maze
if (player->loc[0] == maze->finish[0] && player->loc[1] == maze->finish[1]) {
success_splash(win, maze->level + 2);
wclear(win);
clear();
box(win, 0, 0);
refresh();
wrefresh(win);
get_new_dims(maze->nrows, maze->ncols, maze->level);
// generate a new maze
std::fill_n(player->visited, maze->max_size * maze->max_size / 2, false);
backtracking_maze_gen(maze);
gen_entrances_opposites(maze);
player->loc[0] = maze->start[0];
player->loc[1] = maze->start[1];
maze->level += 1;
}
}
}
/**
* Randomly generate maze dimensions.
*/
static void get_new_dims(int& nrows, int& ncols, int level) {
level %= 20;
const int bottom_y = 15;
nrows = bottom_y + level / 2 + (rand() % (int)(level / 2 + 1));
if (nrows % 2 == 0) { nrows += 1; }
const int bottom_x = 31;
ncols = bottom_x + level + (rand() % (int)((level) + 1));
if (ncols % 2 == 0) { ncols += 1; }
}
<|endoftext|> |
<commit_before>/* Copyright 2015 Peter Goodman (peter@trailofbits.com), all rights reserved. */
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <functional>
#include <set>
#include <string>
#include <sstream>
#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/Type.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/Transforms/Utils/ValueMapper.h>
#include "mcsema/Arch/Arch.h"
#include "mcsema/BC/IntrinsicTable.h"
#include "mcsema/BC/Translator.h"
#include "mcsema/CFG/CFG.h"
#include "mcsema/OS/OS.h"
DEFINE_int32(max_dataflow_analysis_iterations, 0,
"Maximum number of iterations of a data flow pass to perform "
"over the control-flow graph being lifted.");
DEFINE_bool(aggressive_dataflow_analysis, false,
"Should data-flow analysis be conservative in their conclusions? "
"If not then the analysis will be really aggressive and make a lot "
"of assumptions about function call behavior.");
namespace llvm {
class ReturnInst;
} // namespace
namespace mcsema {
namespace {
// Name of some meta-data that we use to distinguish between external symbols
// and private symbols.
static std::string NamedSymbolMetaId(std::string func_name) {
return "mcsema_external:" + func_name;
}
// Returns the ID for this binary. We prefix every basic block function added to
// a module with the ID of the binary, where the ID is a number that increments
// linearly.
static int GetBinaryId(llvm::Module *M) {
for (auto i = 1; ; ++i) {
std::string id = "mcsema_binary:" + std::to_string(i);
if (!M->getNamedMetadata(id)) {
M->getOrInsertNamedMetadata(id);
return i;
}
}
__builtin_unreachable();
}
} // namespace
Translator::Translator(const Arch *arch_, llvm::Module *module_)
: arch(arch_),
module(module_),
blocks(),
functions(),
symbols(),
binary_id(GetBinaryId(module)),
basic_block(FindFunction(module, "__mcsema_basic_block")),
intrinsics(new IntrinsicTable(module)) {
EnableDeferredInlining();
IdentifyExistingSymbols();
}
namespace {
static void DisableInlining(llvm::Function *F) {
F->removeFnAttr(llvm::Attribute::AlwaysInline);
F->removeFnAttr(llvm::Attribute::InlineHint);
F->addFnAttr(llvm::Attribute::NoInline);
}
} // namespace
// Enable deferred inlining. The goal is to support better dead-store
// elimination for flags.
void Translator::EnableDeferredInlining(void) {
if (!intrinsics->defer_inlining) return;
DisableInlining(intrinsics->defer_inlining);
for (auto U : intrinsics->defer_inlining->users()) {
if (auto C = llvm::dyn_cast_or_null<llvm::CallInst>(U)) {
auto B = C->getParent();
auto F = B->getParent();
DisableInlining(F);
}
}
}
// Find existing exported functions and variables. This is for the sake of
// linking functions of the same names across CFG files.
void Translator::IdentifyExistingSymbols(void) {
for (auto &F : module->functions()) {
std::string name = F.getName();
if (module->getNamedMetadata(NamedSymbolMetaId(name))) {
functions[name] = &F;
}
}
for (auto &V : module->globals()) {
std::string name = V.getName();
if (module->getNamedMetadata(NamedSymbolMetaId(name))) {
symbols[name] = &V;
}
}
}
namespace {
void InitBlockFuncAttributes(llvm::Function *BF, const llvm::Function *TF) {
BF->setAttributes(TF->getAttributes());
InitFunctionAttributes(BF);
auto args = BF->arg_begin();
(args++)->setName("state");
args->setName("pc");
}
llvm::Function *GetBlockFunction(llvm::Module *M,
const llvm::Function *TF,
std::string name) {
auto func_type = TF->getFunctionType();
auto BF = llvm::dyn_cast<llvm::Function>(
M->getOrInsertFunction(name, func_type));
InitBlockFuncAttributes(BF, TF);
BF->setLinkage(llvm::GlobalValue::PrivateLinkage);
return BF;
}
} // namespace
// Create functions for every block in the CFG.
void Translator::CreateFunctionsForBlocks(const cfg::Module *cfg) {
std::set<uint64_t> indirect_blocks;
for (const auto &block : cfg->indirect_blocks()) {
indirect_blocks.insert(block.address());
}
for (const auto &block : cfg->blocks()) {
auto &BF = blocks[block.address()];
if (!BF) {
std::stringstream ss;
ss << "__lifted_block_" << binary_id << "_0x"
<< std::hex << block.address();
BF = GetBlockFunction(module, basic_block, ss.str());
// This block is externally visible so change its linkage and make a new
// private block to which other blocks will refer.
if (indirect_blocks.count(block.address())) {
std::stringstream ss2;
ss2 << "__extern_block_" << binary_id << "_0x"
<< std::hex << block.address();
auto EF = GetBlockFunction(module, basic_block, ss2.str());
EF->setLinkage(llvm::GlobalValue::ExternalLinkage);
AddTerminatingTailCall(EF, BF, block.address());
}
}
}
}
namespace {
// On Mac this strips off leading the underscore on symbol names.
//
// TODO(pag): This is really ugly and is probably incorrect. The expectation is
// that the leading underscore will be re-added when this code is
// compiled.
std::string CanonicalName(OSName os_name, const std::string &name) {
if (kOSMacOSX == os_name && name.length() && '_' == name[0]) {
return name.substr(1);
} else {
return name;
}
}
} // namespace
// Create functions for every function in the CFG.
void Translator::CreateExternalFunctions(const cfg::Module *cfg) {
for (const auto &func : cfg->functions()) {
if (!func.is_exported() && !func.is_imported()) continue;
auto func_name = CanonicalName(arch->os_name, func.name());
CHECK(!func_name.empty())
<< "Module contains unnamed function at address " << func.address();
CHECK(!(func.is_exported() && func.is_imported()))
<< "Function " << func_name << " can't be imported and exported.";
llvm::Function *&F = functions[func_name];
if (!F) {
F = GetBlockFunction(module, basic_block, func_name);
// To get around some issues that `opt` has.
F->addFnAttr(llvm::Attribute::NoBuiltin);
F->addFnAttr(llvm::Attribute::OptimizeNone);
F->addFnAttr(llvm::Attribute::NoInline);
F->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
}
// Mark this symbol as external. We do this so that we can pick up on it
// if we merge another CFG into this bitcode module.
module->getOrInsertNamedMetadata(NamedSymbolMetaId(func_name));
}
}
// Link together functions and basic blocks.
void Translator::LinkExternalFunctionsToBlocks(const cfg::Module *cfg) {
for (const auto &func : cfg->functions()) {
if (!func.is_exported() && !func.is_imported()) continue;
if (!func.address()) continue;
auto func_name = CanonicalName(arch->os_name, func.name());
auto F = functions[func_name];
auto &BF = blocks[func.address()];
// In the case of an exported function, redirect the function's
// implementation to a locally defined block.
if (func.is_exported()) {
CHECK(nullptr != BF)
<< "Exported function " << func_name << " has no address!";
CHECK(F->isDeclaration())
<< "Function " << func_name << " is already defined!";
AddTerminatingTailCall(F, BF, func.address());
// In the case of ELF binaries, we tend to see a call to something like
// `malloc@plt` that is responsible for finding and invoking the actual
// `malloc` implementation. In this case, we want to treat the `malloc@plt`
// block address as synonymous with the function.
//
// TODO(pag): What about versioned ELF symbols?
} else if (func.is_imported()) {
if (!BF) {
BF = F;
} else {
AddTerminatingTailCall(BF, F);
}
}
}
}
namespace {
// Clone the block method template `TF` into a specific method `BF` that
// will contain lifted code.
static std::vector<llvm::BasicBlock *> InitBlockFunction(
llvm::Function *BF, const llvm::Function *TF, const cfg::Block &block) {
llvm::ValueToValueMapTy var_map;
auto targs = TF->arg_begin();
auto bargs = BF->arg_begin();
for (; targs != TF->arg_end(); ++targs, ++bargs) {
var_map[&*targs] = &*bargs;
}
llvm::SmallVector<llvm::ReturnInst *, 1> returns;
llvm::CloneFunctionInto(BF, TF, var_map, false, returns);
InitBlockFuncAttributes(BF, TF);
auto R = returns[0];
R->removeFromParent();
delete R;
std::vector<llvm::BasicBlock *> instruction_blocks;
instruction_blocks.reserve(block.instructions_size());
instruction_blocks.push_back(&(BF->back()));
for (const auto &instr : block.instructions()) {
// Name the block according to the instruction's address.
std::stringstream ss;
ss << "0x" << std::hex << instr.address();
// Create a block for this instruction.
auto B = llvm::BasicBlock::Create(BF->getContext(), ss.str(), BF);
instruction_blocks.push_back(B);
}
return instruction_blocks;
}
// Fall-through PC for a block.
static uint64_t FallThroughPC(const cfg::Block &block) {
if (0 < block.instructions_size()) {
const auto &instr = block.instructions(block.instructions_size() - 1);
return instr.address() + instr.size();
} else {
LOG(ERROR) << "Using block address as fall-through address.";
return block.address();
}
}
} // namespace
// Add a fall-through terminator to the block method just in case one is
// missing.
void Translator::TerminateBlockMethod(const cfg::Block &block,
llvm::Function *BF) {
auto &B = BF->back();
if (B.getTerminator()) {
return;
}
if (block.instructions_size()) {
auto next_pc = FallThroughPC(block);
AddTerminatingTailCall(BF, GetLiftedBlockForPC(next_pc), next_pc);
} else {
AddTerminatingTailCall(BF, intrinsics->missing_block, block.address());
}
}
// Lift code contained in blocks into the block methods.
void Translator::LiftBlocks(const cfg::Module *cfg) {
llvm::legacy::FunctionPassManager FPM(module);
FPM.add(llvm::createDeadCodeEliminationPass());
FPM.add(llvm::createCFGSimplificationPass());
FPM.add(llvm::createPromoteMemoryToRegisterPass());
FPM.add(llvm::createReassociatePass());
FPM.add(llvm::createInstructionCombiningPass());
FPM.add(llvm::createDeadStoreEliminationPass());
for (const auto &block : cfg->blocks()) {
LOG_IF(WARNING, !block.instructions_size())
<< "Block at " << block.address() << " has no instructions!";
auto BF = GetLiftedBlockForPC(block.address());
if (!BF->isDeclaration()) {
LOG(WARNING) << "Ignoring already lifted block at " << block.address();
continue;
}
const auto instruction_blocks = InitBlockFunction(BF, basic_block, block);
// Lift the instructions into the block in reverse order. This helps for
// using the results of backward data-flow analyses.
for (auto i = block.instructions_size(); i--; ) {
const auto &instr = block.instructions(i);
const auto bb = instruction_blocks[i + 1];
LiftInstructionIntoBlock(block, instr, bb);
}
// Connect the internal blocks together with branches.
if (instruction_blocks.size()) {
for (auto i = 1; i < instruction_blocks.size(); ++i) {
llvm::IRBuilder<> ir(instruction_blocks[i - 1]);
ir.CreateBr(instruction_blocks[i]);
}
}
TerminateBlockMethod(block, BF);
// Perform simple, incremental optimizations on the block functions to
// avoid OOMs.
FPM.run(*BF);
}
}
// Lift an instruction into a basic block. This does some minor sanity checks
// then dispatches to the arch-specific translator.
void Translator::LiftInstructionIntoBlock(
const cfg::Block &block, const cfg::Instr &instr, llvm::BasicBlock *B) {
CHECK(0 < instr.size())
<< "Can't decode zero-sized instruction at " << instr.address();
CHECK(instr.size() == instr.bytes().length())
<< "Instruction size mismatch for instruction at " << instr.address();
arch->LiftInstructionIntoBlock(*this, block, instr, B);
}
void Translator::LiftCFG(const cfg::Module *cfg) {
blocks.clear(); // Just in case we call `LiftCFG` multiple times.
CreateFunctionsForBlocks(cfg);
CreateExternalFunctions(cfg);
LinkExternalFunctionsToBlocks(cfg);
AnalyzeCFG(cfg);
LiftBlocks(cfg);
}
// Run an architecture-specific data-flow analysis on the module.
void Translator::AnalyzeCFG(const cfg::Module *cfg) {
if (!FLAGS_max_dataflow_analysis_iterations) return;
AnalysisWorkList wl;
auto &analysis = arch->CFGAnalyzer();
for (const auto &block : cfg->blocks()) {
analysis.AddBlock(block);
}
for (const auto &func : cfg->functions()) {
analysis.AddFunction(func);
}
analysis.InitWorkList(wl);
for (auto i = 0;
wl.size() && i < FLAGS_max_dataflow_analysis_iterations; ++i) {
AnalysisWorkList next_wl;
for (auto item : wl) {
analysis.AnalyzeBlock(item, next_wl);
}
wl.swap(next_wl);
}
analysis.Finalize();
}
llvm::Function *Translator::GetLiftedBlockForPC(uintptr_t pc) const {
auto F = blocks[pc];
if (!F) {
LOG(ERROR) << "Could not find lifted block for PC " << pc;
F = intrinsics->missing_block;
}
return F;
}
} // namespace mcsema
<commit_msg>Add in address information to lifted basic block functions in the form of metadata.<commit_after>/* Copyright 2015 Peter Goodman (peter@trailofbits.com), all rights reserved. */
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <functional>
#include <set>
#include <string>
#include <sstream>
#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/Type.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/Transforms/Utils/ValueMapper.h>
#include "mcsema/Arch/Arch.h"
#include "mcsema/BC/IntrinsicTable.h"
#include "mcsema/BC/Translator.h"
#include "mcsema/CFG/CFG.h"
#include "mcsema/OS/OS.h"
DEFINE_int32(max_dataflow_analysis_iterations, 0,
"Maximum number of iterations of a data flow pass to perform "
"over the control-flow graph being lifted.");
DEFINE_bool(aggressive_dataflow_analysis, false,
"Should data-flow analysis be conservative in their conclusions? "
"If not then the analysis will be really aggressive and make a lot "
"of assumptions about function call behavior.");
namespace llvm {
class ReturnInst;
} // namespace
namespace mcsema {
namespace {
// Name of some meta-data that we use to distinguish between external symbols
// and private symbols.
static std::string NamedSymbolMetaId(std::string func_name) {
return "mcsema_external:" + func_name;
}
// Returns the ID for this binary. We prefix every basic block function added to
// a module with the ID of the binary, where the ID is a number that increments
// linearly.
static int GetBinaryId(llvm::Module *M) {
for (auto i = 1; ; ++i) {
std::string id = "mcsema_binary:" + std::to_string(i);
if (!M->getNamedMetadata(id)) {
M->getOrInsertNamedMetadata(id);
return i;
}
}
__builtin_unreachable();
}
} // namespace
Translator::Translator(const Arch *arch_, llvm::Module *module_)
: arch(arch_),
module(module_),
blocks(),
functions(),
symbols(),
binary_id(GetBinaryId(module)),
basic_block(FindFunction(module, "__mcsema_basic_block")),
intrinsics(new IntrinsicTable(module)) {
EnableDeferredInlining();
IdentifyExistingSymbols();
}
namespace {
static void DisableInlining(llvm::Function *F) {
F->removeFnAttr(llvm::Attribute::AlwaysInline);
F->removeFnAttr(llvm::Attribute::InlineHint);
F->addFnAttr(llvm::Attribute::NoInline);
}
} // namespace
// Enable deferred inlining. The goal is to support better dead-store
// elimination for flags.
void Translator::EnableDeferredInlining(void) {
if (!intrinsics->defer_inlining) return;
DisableInlining(intrinsics->defer_inlining);
for (auto U : intrinsics->defer_inlining->users()) {
if (auto C = llvm::dyn_cast_or_null<llvm::CallInst>(U)) {
auto B = C->getParent();
auto F = B->getParent();
DisableInlining(F);
}
}
}
// Find existing exported functions and variables. This is for the sake of
// linking functions of the same names across CFG files.
void Translator::IdentifyExistingSymbols(void) {
for (auto &F : module->functions()) {
std::string name = F.getName();
if (module->getNamedMetadata(NamedSymbolMetaId(name))) {
functions[name] = &F;
}
}
for (auto &V : module->globals()) {
std::string name = V.getName();
if (module->getNamedMetadata(NamedSymbolMetaId(name))) {
symbols[name] = &V;
}
}
}
namespace {
void InitBlockFuncAttributes(llvm::Function *BF, const llvm::Function *TF) {
BF->setAttributes(TF->getAttributes());
InitFunctionAttributes(BF);
auto args = BF->arg_begin();
(args++)->setName("state");
args->setName("pc");
}
llvm::Function *GetBlockFunction(llvm::Module *M,
const llvm::Function *TF,
std::string name) {
auto func_type = TF->getFunctionType();
auto BF = llvm::dyn_cast<llvm::Function>(
M->getOrInsertFunction(name, func_type));
InitBlockFuncAttributes(BF, TF);
BF->setLinkage(llvm::GlobalValue::PrivateLinkage);
return BF;
}
// Add the address of the block as a special meta-data flag.
static void SetMetaDataAddress(llvm::Module *M, const std::string &block_name,
uint64_t block_address) {
std::stringstream ss;
ss << "mcsema_address:" << block_name;
auto &C = M->getContext();
auto Int64Ty = llvm::Type::getInt64Ty(C);
auto CI = llvm::ConstantInt::get(Int64Ty, block_address, false);
auto CM = llvm::ConstantAsMetadata::get(CI);
M->addModuleFlag(llvm::Module::Warning, ss.str(), CM);
}
} // namespace
// Create functions for every block in the CFG.
void Translator::CreateFunctionsForBlocks(const cfg::Module *cfg) {
std::set<uint64_t> indirect_blocks;
for (const auto &block : cfg->indirect_blocks()) {
indirect_blocks.insert(block.address());
}
for (const auto &block : cfg->blocks()) {
auto &BF = blocks[block.address()];
if (!BF) {
std::stringstream ss;
ss << "__lifted_block_" << binary_id << "_0x"
<< std::hex << block.address();
BF = GetBlockFunction(module, basic_block, ss.str());
SetMetaDataAddress(module, ss.str(), block.address());
// This block is externally visible so change its linkage and make a new
// private block to which other blocks will refer.
if (indirect_blocks.count(block.address())) {
std::stringstream ss2;
ss2 << "__extern_block_" << binary_id << "_0x"
<< std::hex << block.address();
auto EF = GetBlockFunction(module, basic_block, ss2.str());
EF->setLinkage(llvm::GlobalValue::ExternalLinkage);
AddTerminatingTailCall(EF, BF, block.address());
}
}
}
}
namespace {
// On Mac this strips off leading the underscore on symbol names.
//
// TODO(pag): This is really ugly and is probably incorrect. The expectation is
// that the leading underscore will be re-added when this code is
// compiled.
std::string CanonicalName(OSName os_name, const std::string &name) {
if (kOSMacOSX == os_name && name.length() && '_' == name[0]) {
return name.substr(1);
} else {
return name;
}
}
} // namespace
// Create functions for every function in the CFG.
void Translator::CreateExternalFunctions(const cfg::Module *cfg) {
for (const auto &func : cfg->functions()) {
if (!func.is_exported() && !func.is_imported()) continue;
auto func_name = CanonicalName(arch->os_name, func.name());
CHECK(!func_name.empty())
<< "Module contains unnamed function at address " << func.address();
CHECK(!(func.is_exported() && func.is_imported()))
<< "Function " << func_name << " can't be imported and exported.";
llvm::Function *&F = functions[func_name];
if (!F) {
F = GetBlockFunction(module, basic_block, func_name);
// To get around some issues that `opt` has.
F->addFnAttr(llvm::Attribute::NoBuiltin);
F->addFnAttr(llvm::Attribute::OptimizeNone);
F->addFnAttr(llvm::Attribute::NoInline);
F->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
}
// Mark this symbol as external. We do this so that we can pick up on it
// if we merge another CFG into this bitcode module.
module->getOrInsertNamedMetadata(NamedSymbolMetaId(func_name));
}
}
// Link together functions and basic blocks.
void Translator::LinkExternalFunctionsToBlocks(const cfg::Module *cfg) {
for (const auto &func : cfg->functions()) {
if (!func.is_exported() && !func.is_imported()) continue;
if (!func.address()) continue;
auto func_name = CanonicalName(arch->os_name, func.name());
auto F = functions[func_name];
auto &BF = blocks[func.address()];
// In the case of an exported function, redirect the function's
// implementation to a locally defined block.
if (func.is_exported()) {
CHECK(nullptr != BF)
<< "Exported function " << func_name << " has no address!";
CHECK(F->isDeclaration())
<< "Function " << func_name << " is already defined!";
AddTerminatingTailCall(F, BF, func.address());
// In the case of ELF binaries, we tend to see a call to something like
// `malloc@plt` that is responsible for finding and invoking the actual
// `malloc` implementation. In this case, we want to treat the `malloc@plt`
// block address as synonymous with the function.
//
// TODO(pag): What about versioned ELF symbols?
} else if (func.is_imported()) {
if (!BF) {
BF = F;
} else {
AddTerminatingTailCall(BF, F);
}
}
}
}
namespace {
// Clone the block method template `TF` into a specific method `BF` that
// will contain lifted code.
static std::vector<llvm::BasicBlock *> InitBlockFunction(
llvm::Function *BF, const llvm::Function *TF, const cfg::Block &block) {
llvm::ValueToValueMapTy var_map;
auto targs = TF->arg_begin();
auto bargs = BF->arg_begin();
for (; targs != TF->arg_end(); ++targs, ++bargs) {
var_map[&*targs] = &*bargs;
}
llvm::SmallVector<llvm::ReturnInst *, 1> returns;
llvm::CloneFunctionInto(BF, TF, var_map, false, returns);
InitBlockFuncAttributes(BF, TF);
auto R = returns[0];
R->removeFromParent();
delete R;
std::vector<llvm::BasicBlock *> instruction_blocks;
instruction_blocks.reserve(block.instructions_size());
instruction_blocks.push_back(&(BF->back()));
for (const auto &instr : block.instructions()) {
// Name the block according to the instruction's address.
std::stringstream ss;
ss << "0x" << std::hex << instr.address();
// Create a block for this instruction.
auto B = llvm::BasicBlock::Create(BF->getContext(), ss.str(), BF);
instruction_blocks.push_back(B);
}
return instruction_blocks;
}
// Fall-through PC for a block.
static uint64_t FallThroughPC(const cfg::Block &block) {
if (0 < block.instructions_size()) {
const auto &instr = block.instructions(block.instructions_size() - 1);
return instr.address() + instr.size();
} else {
LOG(ERROR) << "Using block address as fall-through address.";
return block.address();
}
}
} // namespace
// Add a fall-through terminator to the block method just in case one is
// missing.
void Translator::TerminateBlockMethod(const cfg::Block &block,
llvm::Function *BF) {
auto &B = BF->back();
if (B.getTerminator()) {
return;
}
if (block.instructions_size()) {
auto next_pc = FallThroughPC(block);
AddTerminatingTailCall(BF, GetLiftedBlockForPC(next_pc), next_pc);
} else {
AddTerminatingTailCall(BF, intrinsics->missing_block, block.address());
}
}
// Lift code contained in blocks into the block methods.
void Translator::LiftBlocks(const cfg::Module *cfg) {
llvm::legacy::FunctionPassManager FPM(module);
FPM.add(llvm::createDeadCodeEliminationPass());
FPM.add(llvm::createCFGSimplificationPass());
FPM.add(llvm::createPromoteMemoryToRegisterPass());
FPM.add(llvm::createReassociatePass());
FPM.add(llvm::createInstructionCombiningPass());
FPM.add(llvm::createDeadStoreEliminationPass());
for (const auto &block : cfg->blocks()) {
LOG_IF(WARNING, !block.instructions_size())
<< "Block at " << block.address() << " has no instructions!";
auto BF = GetLiftedBlockForPC(block.address());
if (!BF->isDeclaration()) {
LOG(WARNING) << "Ignoring already lifted block at " << block.address();
continue;
}
const auto instruction_blocks = InitBlockFunction(BF, basic_block, block);
// Lift the instructions into the block in reverse order. This helps for
// using the results of backward data-flow analyses.
for (auto i = block.instructions_size(); i--; ) {
const auto &instr = block.instructions(i);
const auto bb = instruction_blocks[i + 1];
LiftInstructionIntoBlock(block, instr, bb);
}
// Connect the internal blocks together with branches.
if (instruction_blocks.size()) {
for (auto i = 1; i < instruction_blocks.size(); ++i) {
llvm::IRBuilder<> ir(instruction_blocks[i - 1]);
ir.CreateBr(instruction_blocks[i]);
}
}
TerminateBlockMethod(block, BF);
// Perform simple, incremental optimizations on the block functions to
// avoid OOMs.
FPM.run(*BF);
}
}
// Lift an instruction into a basic block. This does some minor sanity checks
// then dispatches to the arch-specific translator.
void Translator::LiftInstructionIntoBlock(
const cfg::Block &block, const cfg::Instr &instr, llvm::BasicBlock *B) {
CHECK(0 < instr.size())
<< "Can't decode zero-sized instruction at " << instr.address();
CHECK(instr.size() == instr.bytes().length())
<< "Instruction size mismatch for instruction at " << instr.address();
arch->LiftInstructionIntoBlock(*this, block, instr, B);
}
void Translator::LiftCFG(const cfg::Module *cfg) {
blocks.clear(); // Just in case we call `LiftCFG` multiple times.
CreateFunctionsForBlocks(cfg);
CreateExternalFunctions(cfg);
LinkExternalFunctionsToBlocks(cfg);
AnalyzeCFG(cfg);
LiftBlocks(cfg);
}
// Run an architecture-specific data-flow analysis on the module.
void Translator::AnalyzeCFG(const cfg::Module *cfg) {
if (!FLAGS_max_dataflow_analysis_iterations) return;
AnalysisWorkList wl;
auto &analysis = arch->CFGAnalyzer();
for (const auto &block : cfg->blocks()) {
analysis.AddBlock(block);
}
for (const auto &func : cfg->functions()) {
analysis.AddFunction(func);
}
analysis.InitWorkList(wl);
for (auto i = 0;
wl.size() && i < FLAGS_max_dataflow_analysis_iterations; ++i) {
AnalysisWorkList next_wl;
for (auto item : wl) {
analysis.AnalyzeBlock(item, next_wl);
}
wl.swap(next_wl);
}
analysis.Finalize();
}
llvm::Function *Translator::GetLiftedBlockForPC(uintptr_t pc) const {
auto F = blocks[pc];
if (!F) {
LOG(ERROR) << "Could not find lifted block for PC " << pc;
F = intrinsics->missing_block;
}
return F;
}
} // namespace mcsema
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "FreeRTOS.h"
#include "task.h"
#include <lib/shell/shell.h>
#include <lib/core/CHIPCore.h>
#include <lib/support/Base64.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CodeUtils.h>
#include <lib/support/RandUtils.h>
#include <support/logging/CHIPLogging.h>
#include <ChipShellCollection.h>
#include "qvCHIP.h"
#if CHIP_ENABLE_OPENTHREAD
extern "C" {
#include <openthread/platform/platform-softdevice.h>
}
#endif // CHIP_ENABLE_OPENTHREAD
using namespace chip;
using namespace chip::Shell;
namespace {
const size_t kShellTaskStackSize = 2048;
const int kShellTaskPriority = 1;
TaskHandle_t sShellTaskHandle;
void ShellCLIMain(void * pvParameter)
{
// Initialize the default streamer that was linked.
const int rc = streamer_init(streamer_get());
if (rc != 0)
{
ChipLogError(Shell, "Streamer initialization failed: %d", rc);
return;
}
ChipLogDetail(Shell, "Initializing CHIP shell commands", rc);
cmd_device_init();
cmd_base64_init();
cmd_misc_init();
cmd_btp_init();
cmd_otcli_init();
ChipLogDetail(Shell, "Run CHIP shell Task", rc);
shell_task(nullptr);
}
} // namespace
int StartShellTask(void)
{
int ret = 0;
// Start Shell task.
if (xTaskCreate(ShellCLIMain, "SHELL", kShellTaskStackSize / sizeof(StackType_t), NULL, kShellTaskPriority,
&sShellTaskHandle) != pdPASS)
{
ret = -1;
}
return ret;
}
int main(void)
{
/* Initialize platform */
qvCHIP_init();
/* Launch shell task */
StartShellTask();
/* Start FreeRTOS */
vTaskStartScheduler();
return 0;
}
<commit_msg>CodeQL: Too many arguments to formatting function in examples/shell/qpg6100/main.cpp (#3775)<commit_after>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "FreeRTOS.h"
#include "task.h"
#include <lib/shell/shell.h>
#include <lib/core/CHIPCore.h>
#include <lib/support/Base64.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CodeUtils.h>
#include <lib/support/RandUtils.h>
#include <support/logging/CHIPLogging.h>
#include <ChipShellCollection.h>
#include "qvCHIP.h"
#if CHIP_ENABLE_OPENTHREAD
extern "C" {
#include <openthread/platform/platform-softdevice.h>
}
#endif // CHIP_ENABLE_OPENTHREAD
using namespace chip;
using namespace chip::Shell;
namespace {
const size_t kShellTaskStackSize = 2048;
const int kShellTaskPriority = 1;
TaskHandle_t sShellTaskHandle;
void ShellCLIMain(void * pvParameter)
{
// Initialize the default streamer that was linked.
const int rc = streamer_init(streamer_get());
if (rc != 0)
{
ChipLogError(Shell, "Streamer initialization failed: %d", rc);
return;
}
ChipLogDetail(Shell, "Initializing CHIP shell commands: %d", rc);
cmd_device_init();
cmd_base64_init();
cmd_misc_init();
cmd_btp_init();
cmd_otcli_init();
ChipLogDetail(Shell, "Run CHIP shell Task: %d", rc);
shell_task(nullptr);
}
} // namespace
int StartShellTask(void)
{
int ret = 0;
// Start Shell task.
if (xTaskCreate(ShellCLIMain, "SHELL", kShellTaskStackSize / sizeof(StackType_t), NULL, kShellTaskPriority,
&sShellTaskHandle) != pdPASS)
{
ret = -1;
}
return ret;
}
int main(void)
{
/* Initialize platform */
qvCHIP_init();
/* Launch shell task */
StartShellTask();
/* Start FreeRTOS */
vTaskStartScheduler();
return 0;
}
<|endoftext|> |
<commit_before>/*
* File: Composite.cpp
* Author: Benedikt Vogler
*
* Created on 21. August 2014, 10:51
*/
#include "Composite.hpp"
#include "Intersection.hpp"
#include <algorithm>
void Composite::add_child(std::shared_ptr<RenderObject> const& child) {
children.push_back(child);
}
Intersection Composite::intersect(Ray const& ray) const {
Ray ray_t;
if (isTransformed())
ray_t = Ray(
glm::vec3(getWorldTransfInv() * glm::vec4(ray.origin, 1)),
glm::vec3(getWorldTransfInv() * glm::vec4(ray.direction, 0))
);
else
ray_t = ray;
std::vector<Intersection> intersections;
//collect every intersection
for(auto child = children.begin(); child != children.end(); ++child) {//every children
auto intersection = (*child)->intersect(ray_t);
if (intersection.hit && ray.mint<intersection.distance && ray.maxt>intersection.distance)
intersections.push_back(intersection);
}
if (intersections.size()==0) return Intersection();//no intersection
//return only intersection with nearest point
return *std::min_element(
intersections.begin(),
intersections.end(),
[](Intersection const& a, Intersection const& b)->bool { return a.distance < b.distance;}
);
}<commit_msg>for each loop<commit_after>/*
* File: Composite.cpp
* Author: Benedikt Vogler
*
* Created on 21. August 2014, 10:51
*/
#include "Composite.hpp"
#include "Intersection.hpp"
#include <algorithm>
void Composite::add_child(std::shared_ptr<RenderObject> const& child) {
children.push_back(child);
}
Intersection Composite::intersect(Ray const& ray) const {
Ray ray_t;
if (isTransformed())
ray_t = Ray(
glm::vec3(getWorldTransfInv() * glm::vec4(ray.origin, 1)),
glm::vec3(getWorldTransfInv() * glm::vec4(ray.direction, 0))
);
else
ray_t = ray;
std::vector<Intersection> intersections;
//collect every intersection
for(auto& child : children) {//every children
auto intersection = child->intersect(ray_t);
if (intersection.hit && ray.mint<intersection.distance && ray.maxt>intersection.distance)
intersections.push_back(intersection);
}
if (intersections.size()==0) return Intersection();//no intersection
//return only intersection with nearest point
return *std::min_element(
intersections.begin(),
intersections.end(),
[](Intersection const& a, Intersection const& b)->bool { return a.distance < b.distance;}
);
}<|endoftext|> |
<commit_before>#include "sdfloader.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <memory>
#include <glm/vec3.hpp>
#include "color.hpp"
#include "material.hpp"
#include "box.hpp"
#include "sphere.hpp"
#include "light.hpp"
#include "camera.hpp"
//#include "scene.hpp"
void load_scene() {
std::string line;
std::ifstream myfile ("../../../scene/scene1.txt");
std::map<std::string, std::shared_ptr<Material>> materials;
std::vector<std::shared_ptr<Shape>> shapes;
std::vector<std::shared_ptr<Light>> lights;
int xres,yres;
Color amblight, background;
std::string filename;
Camera cam;
// Scene scene1;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
//std::cout << line << '\n';
std::stringstream ss;
ss << line;
std::string keyword;
ss>>keyword;
if(keyword == "#"){continue;}
if(keyword == "define"){
ss>>keyword;
if(keyword == "material"){
Material mat;
ss>>mat.name;
ss>>mat.ka.r;
ss>>mat.ka.g;
ss>>mat.ka.b;
ss>>mat.ks.r;
ss>>mat.ks.g;
ss>>mat.ks.b;
ss>>mat.kd.r;
ss>>mat.kd.g;
ss>>mat.kd.b;
ss>>mat.m;
std::shared_ptr<Material> temp_ptr = std::make_shared<Material>(mat);
materials.insert({mat.name, temp_ptr});
//materials[mat.name]= mat;
std::cout << mat;
}
if(keyword == "shape"){
ss>>keyword;
if(keyword == "box"){
std::string name;
std::string mat_namebox;
float minx,miny,minz,maxx,maxy,maxz;
ss>>minx;
ss>>miny;
ss>>minz;
ss>>maxx;
ss>>maxy;
ss>>maxz;
glm::vec3 min{minx,miny,minz};
glm::vec3 max{maxx,maxy,maxz};
ss>>name;
ss>>mat_namebox;
//std::string mat_namebox;
std::shared_ptr<Shape> temp_ptr = std::make_shared<Box>
(
Box{min,max,name,*materials[mat_namebox]}
);
std::cout << *temp_ptr;
shapes.push_back(temp_ptr);
}
else if(keyword == "sphere"){
std::string name;
float x,y,z,r;
ss>>name;
ss>>x;
ss>>y;
ss>>z;
glm::vec3 middle{x,y,z};
ss>>r;
std::string mat_name;
ss>>mat_name;
//alternative
/*std::cout <<mat_name;
ss>>sph.name_;
ss>>sph.middle_.x;
ss>>sph.middle_.y;
ss>>sph.middle_.z;
ss>>sph.r_;
ss>>sph.mat_;
std::cout << sph;sph.mat_=*materials(mat_name);*/
std::shared_ptr<Shape> temp_ptr = std::make_shared<Sphere>
(
Sphere{middle,r,name,*materials[mat_name]}
);
std::cout << *temp_ptr;
shapes.push_back(temp_ptr);
// std::cout << sph;
}
}
if(keyword == "light"){
std::string name;
std::string mat_namelight;
float posx, posy, posz, ldr, ldg, ldb;
ss>>name;
ss>>posx;
ss>>posy;
ss>>posz;
glm::vec3 pos{posx,posy,posz};
ss>>ldr;
ss>>ldg;
ss>>ldb;
Color ld{ldr,ldg,ldb};
std::shared_ptr<Light> temp_ptr = std::make_shared<Light>
(
Light{name, pos, ld}
);
std::cout << *temp_ptr;
lights.push_back(temp_ptr);
}
if(keyword == "camera"){
std::string name;
float angle, posx, posy, posz;
ss>>name;
ss>>posx;
ss>>posy;
ss>>posz;
glm::vec3 pos{posx,posy,posz};
ss>>angle;
/*std::shared_ptr<Camera> cam_ptr = std::make_shared<Camera>
(
Camera{name,pos,angle}
);*/
Camera camera;
//cam.name_=name;
//cam.pos_=pos;
//cam.angle_=angle;
//Camera cam{name,pos,angle};
std::cout << cam;
cam=camera;
}
if(keyword == "amblight"){
ss>>ambr;
ss>>ambg;
ss>>ambb;
Color amb{ambr,ambg,ambb};
amblight=amb;
}
if(keyword == "background"){
ss>>backr;
ss>>backg;
ss>>backb;
Color back{backr,backg,backb};
background=back;
}
if(keyword == "renderer"){
ss>>keyword;
ss>>filename;
ss>>xres;
ss>>yres;
std::shared_ptr<Scene> scene_ptr = std::make_shared<Scene>
(
Scene{filename, xres, yres, cam, amblight, background, materials, shapes, lights}
);
}
}
myfile.close();
}
else std::cout << "Unable to open file";
}
<commit_msg>tryin to find out da damn issuse, bad voodo that is ma friend...<commit_after>#include "sdfloader.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <memory>
#include <glm/vec3.hpp>
#include "color.hpp"
#include "material.hpp"
#include "box.hpp"
#include "sphere.hpp"
#include "light.hpp"
#include "camera.hpp"
#include "scene.hpp"
void load_scene() {
std::string line;
std::ifstream myfile ("../../../scene/scene1.txt");
std::map<std::string, std::shared_ptr<Material>> materials;
std::vector<std::shared_ptr<Shape>> shapes;
std::vector<std::shared_ptr<Light>> lights;
int xres,yres;
Color amblight, background;
std::string filename;
Camera cam;
// Scene scene1;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
//std::cout << line << '\n';
std::stringstream ss;
ss << line;
std::string keyword;
ss>>keyword;
if(keyword == "#"){continue;}
if(keyword == "define"){
ss>>keyword;
if(keyword == "material"){
Material mat;
ss>>mat.name;
ss>>mat.ka.r;
ss>>mat.ka.g;
ss>>mat.ka.b;
ss>>mat.ks.r;
ss>>mat.ks.g;
ss>>mat.ks.b;
ss>>mat.kd.r;
ss>>mat.kd.g;
ss>>mat.kd.b;
ss>>mat.m;
std::shared_ptr<Material> temp_ptr = std::make_shared<Material>(mat);
materials.insert({mat.name, temp_ptr});
//materials[mat.name]= mat;
std::cout << mat;
}
if(keyword == "shape"){
ss>>keyword;
if(keyword == "box"){
std::string name;
std::string mat_namebox;
float minx,miny,minz,maxx,maxy,maxz;
ss>>minx;
ss>>miny;
ss>>minz;
ss>>maxx;
ss>>maxy;
ss>>maxz;
glm::vec3 min{minx,miny,minz};
glm::vec3 max{maxx,maxy,maxz};
ss>>name;
ss>>mat_namebox;
//std::string mat_namebox;
std::shared_ptr<Shape> temp_ptr = std::make_shared<Box>
(
Box{min,max,name,*materials[mat_namebox]}
);
std::cout << *temp_ptr;
shapes.push_back(temp_ptr);
}
else if(keyword == "sphere"){
std::string name;
float x,y,z,r;
ss>>name;
ss>>x;
ss>>y;
ss>>z;
glm::vec3 middle{x,y,z};
ss>>r;
std::string mat_name;
ss>>mat_name;
//alternative
/*std::cout <<mat_name;
ss>>sph.name_;
ss>>sph.middle_.x;
ss>>sph.middle_.y;
ss>>sph.middle_.z;
ss>>sph.r_;
ss>>sph.mat_;
std::cout << sph;sph.mat_=*materials(mat_name);*/
std::shared_ptr<Shape> temp_ptr = std::make_shared<Sphere>
(
Sphere{middle,r,name,*materials[mat_name]}
);
std::cout << *temp_ptr;
shapes.push_back(temp_ptr);
// std::cout << sph;
}
}
if(keyword == "light"){
std::string name;
std::string mat_namelight;
float posx, posy, posz, ldr, ldg, ldb;
ss>>name;
ss>>posx;
ss>>posy;
ss>>posz;
glm::vec3 pos{posx,posy,posz};
ss>>ldr;
ss>>ldg;
ss>>ldb;
Color ld{ldr,ldg,ldb};
std::shared_ptr<Light> temp_ptr = std::make_shared<Light>
(
Light{name, pos, ld}
);
std::cout << *temp_ptr;
lights.push_back(temp_ptr);
}
if(keyword == "camera"){
std::string name;
float angle, posx, posy, posz;
ss>>name;
ss>>posx;
ss>>posy;
ss>>posz;
glm::vec3 pos{posx,posy,posz};
ss>>angle;
/*std::shared_ptr<Camera> cam_ptr = std::make_shared<Camera>
(
Camera{name,pos,angle}
);*/
Camera camera;
//cam.name_=name;
//cam.pos_=pos;
//cam.angle_=angle;
//Camera cam{name,pos,angle};
std::cout << cam;
cam=camera;
}
if(keyword == "amblight"){
float ambr,ambg,ambb;
ss>>ambr;
ss>>ambg;
ss>>ambb;
Color amb{ambr,ambg,ambb};
amblight=amb;
}
if(keyword == "background"){
float backr, backg, backb;
ss>>backr;
ss>>backg;
ss>>backb;
Color back{backr,backg,backb};
background=back;
}
if(keyword == "renderer"){
ss>>keyword;
ss>>filename;
ss>>xres;
ss>>yres;
std::shared_ptr<Scene> scene_ptr = std::make_shared<Scene>
(
Scene{filename, xres, yres, cam, amblight, background, materials, shapes, lights}
);
}
}
myfile.close();
}
else std::cout << "Unable to open file";
}
<|endoftext|> |
<commit_before>#include <Bull/Window/X11/WindowImplX11.hpp>
namespace Bull
{
namespace prv
{
/*! \brief Constructor
*
* \param mode The VideoMode to use to create the window
* \param title The title of the window
* \param style The style to use to create the window
*
*/
WindowImplX11::WindowImplX11(const VideoMode& mode, const String& title, Uint32 style) :
m_display(Display::get()),
m_handler(0)
{
XSetWindowAttributes attribs;
attribs.event_mask = KeyPressMask | KeyReleaseMask;
m_handler = XCreateWindow(m_display->getHandler(),
m_display->getRootWindow(),
0, 0,
mode.width, mode.height,
0,
CopyFromParent,
InputOutput,
nullptr,
CWEventMask | CWBackPixel,
&attribs);
setTitle(title);
XMapWindow(m_display->getHandler(), m_handler);
m_display->flush();
}
/*! \brief Destructor
*
*/
WindowImplX11::~WindowImplX11()
{
XDestroyWindow(m_display->getHandler(), m_handler);
}
/*! \brief Start to process events to fill event queue
*
*/
void WindowImplX11::startProcessEvents()
{
XEvent e;
while(XPending(m_display->getHandler()))
{
XNextEvent(m_display->getHandler(), &e);
switch(e.type)
{
case KeyPress:
{
Window::Event event;
event.type = Window::Event::KeyDown;
pushEvent(event);
}
break;
case KeyRelease:
{
Window::Event event;
event.type = Window::Event::KeyUp;
pushEvent(event);
}
break;
}
}
}
/*! \brief Minimize a window
*
*/
void WindowImplX11::minimize()
{
}
/*! \brief Check if the window is minimized
*
* \return Return true if the window is minimized, false otherwise
*
*/
bool WindowImplX11::isMinimized() const
{
}
/*! \brief Maximize a window
*
*/
void WindowImplX11::maximize()
{
}
/*! \brief Check if the window is maximized
*
* \return Return true if the window is maximized, false otherwise
*
*/
bool WindowImplX11::isMaximized() const
{
}
/*! \brief Enable or disable the capture of the cursor inside the window
*
* \param enable The state of the capture
*
*/
void WindowImplX11::enableCaptureCursor(bool capture)
{
}
/*! \brief Hide or show the cursor
*
* \param enable The state of the cursor
*
*/
void WindowImplX11::showCursor(bool enable)
{
}
/*! \brief Set the size of the window
*
* \param size The new size of the window
*
*/
void WindowImplX11::setPosition(const Vector2I& position)
{
}
/*! \brief Set the size of the window
*
* \param x The new width of the window
* \param y The new height of the window
*
*/
Vector2I WindowImplX11::getPosition() const
{
}
/*! \brief Set the size of the window
*
* \param size The new size of the window
*
*/
void WindowImplX11::setSize(const Vector2UI& size)
{
}
/*! \brief Get the size of the window
*
* \return Return the size of the window
*
*/
Vector2UI WindowImplX11::getSize() const
{
}
/*! \brief Set the title of the window
*
* \param title The title to set to the window
*
*/
void WindowImplX11::setTitle(const String& title)
{
XStoreName(m_display->getHandler(), m_handler, title);
}
/*! \brief Get the title of the window
*
* \return Return the title of the window
*
*/
String WindowImplX11::getTitle() const
{
}
/*! \brief Check if the window has the focus
*
* \param Return true if the window has the focus, false otherwise
*
*/
bool WindowImplX11::hasFocus() const
{
}
/*! \brief Enter or leave the fullscreen mode
*
* \param mode The VideoMode to use
* \param fullscreen False to leave the fullscreen mode, true to enter the fullscreen mode
*
* \return Return true if the switch was done successfully, false otherwise
*
*/
bool WindowImplX11::switchFullscreen(const VideoMode& mode, bool fullscreen)
{
}
/*! \brief Show or hide the window
*
* \param visible True to show the window, false to hide the window
*
*/
void WindowImplX11::setVisible(bool visible)
{
}
/*! \brief Get the window system handler
*
* \return Return the native window system handler
*
*/
WindowHandler WindowImplX11::getSystemHandler() const
{
return m_handler;
}
}
}
<commit_msg>[WIndow/Window/X11] Handle mouse events<commit_after>#include <Bull/Window/X11/WindowImplX11.hpp>
#ifndef Button6
#define Button6 6
#endif // Button6
#ifndef Button7
#define Button7 7
#endif // Button6
#ifndef Button8
#define Button8 8
#endif // Button6
#ifndef Button9
#define Button9 9
#endif // Button6
namespace Bull
{
namespace prv
{
namespace
{
const long eventMasks = KeyPressMask | KeyReleaseMask | /// Keyboard events
PointerMotionMask | /// Mouse move event
ButtonPressMask | ButtonReleaseMask;
}
/*! \brief Constructor
*
* \param mode The VideoMode to use to create the window
* \param title The title of the window
* \param style The style to use to create the window
*
*/
WindowImplX11::WindowImplX11(const VideoMode& mode, const String& title, Uint32 style) :
m_display(Display::get()),
m_handler(0)
{
XSetWindowAttributes attribs;
attribs.event_mask = eventMasks;
m_handler = XCreateWindow(m_display->getHandler(),
m_display->getRootWindow(),
0, 0,
mode.width, mode.height,
0,
CopyFromParent,
InputOutput,
nullptr,
CWEventMask | CWBackPixel,
&attribs);
setTitle(title);
XMapWindow(m_display->getHandler(), m_handler);
m_display->flush();
}
/*! \brief Destructor
*
*/
WindowImplX11::~WindowImplX11()
{
XDestroyWindow(m_display->getHandler(), m_handler);
}
/*! \brief Start to process events to fill event queue
*
*/
void WindowImplX11::startProcessEvents()
{
XEvent e;
while(XPending(m_display->getHandler()))
{
XNextEvent(m_display->getHandler(), &e);
switch(e.type)
{
case KeyPress:
{
Window::Event event;
event.type = Window::Event::KeyDown;
pushEvent(event);
}
break;
case KeyRelease:
{
Window::Event event;
event.type = Window::Event::KeyUp;
pushEvent(event);
}
break;
case MotionNotify:
{
Window::Event event;
event.type = Window::Event::MouseMoved;
event.mouseMove.x = e.xmotion.x;
event.mouseMove.y = e.xmotion.y;
pushEvent(event);
}
break;
case ButtonPress:
{
Window::Event event;
if(e.xbutton.button <= Button3 || e.xbutton.button >= Button8)
{
event.type = Window::Event::MouseButtonDown;
event.mouseButton.x = e.xbutton.x;
event.mouseButton.y = e.xbutton.y;
}
else
{
event.type = Window::Event::MouseWheel;
event.mouseWheel.x = e.xbutton.x;
event.mouseWheel.y = e.xbutton.y;
}
switch(e.xbutton.button)
{
case Button1:
event.mouseButton.button = Mouse::Left;
break;
case Button2:
event.mouseButton.button = Mouse::Middle;
break;
case Button3:
event.mouseButton.button = Mouse::Right;
break;
case Button4:
event.mouseWheel.up = true;
event.mouseWheel.wheel = Mouse::Vertical;
break;
case Button5:
event.mouseWheel.up = false;
event.mouseWheel.wheel = Mouse::Vertical;
break;
case Button6:
event.mouseWheel.up = true;
event.mouseWheel.wheel = Mouse::Horizontal;
break;
case Button7:
event.mouseWheel.up = false;
event.mouseWheel.wheel = Mouse::Horizontal;
break;
case Button8:
event.mouseButton.button = Mouse::Extra1;
break;
case Button9:
event.mouseButton.button = Mouse::Extra2;
break;
}
pushEvent(event);
}
break;
case ButtonRelease:
{
if(e.xbutton.button <= Button3 || e.xbutton.button >= Button8)
{
Window::Event event;
event.type = Window::Event::MouseButtonUp;
switch(e.xbutton.button)
{
case Button1:
event.mouseButton.button = Mouse::Left;
break;
case Button2:
event.mouseButton.button = Mouse::Middle;
break;
case Button3:
event.mouseButton.button = Mouse::Right;
break;
case Button8:
event.mouseButton.button = Mouse::Extra1;
break;
case Button9:
event.mouseButton.button = Mouse::Extra2;
break;
}
event.mouseButton.x = e.xbutton.x;
event.mouseButton.y = e.xbutton.y;
pushEvent(event);
}
}
break;
}
}
}
/*! \brief Minimize a window
*
*/
void WindowImplX11::minimize()
{
}
/*! \brief Check if the window is minimized
*
* \return Return true if the window is minimized, false otherwise
*
*/
bool WindowImplX11::isMinimized() const
{
}
/*! \brief Maximize a window
*
*/
void WindowImplX11::maximize()
{
}
/*! \brief Check if the window is maximized
*
* \return Return true if the window is maximized, false otherwise
*
*/
bool WindowImplX11::isMaximized() const
{
}
/*! \brief Enable or disable the capture of the cursor inside the window
*
* \param enable The state of the capture
*
*/
void WindowImplX11::enableCaptureCursor(bool capture)
{
}
/*! \brief Hide or show the cursor
*
* \param enable The state of the cursor
*
*/
void WindowImplX11::showCursor(bool enable)
{
}
/*! \brief Set the size of the window
*
* \param size The new size of the window
*
*/
void WindowImplX11::setPosition(const Vector2I& position)
{
}
/*! \brief Set the size of the window
*
* \param x The new width of the window
* \param y The new height of the window
*
*/
Vector2I WindowImplX11::getPosition() const
{
}
/*! \brief Set the size of the window
*
* \param size The new size of the window
*
*/
void WindowImplX11::setSize(const Vector2UI& size)
{
}
/*! \brief Get the size of the window
*
* \return Return the size of the window
*
*/
Vector2UI WindowImplX11::getSize() const
{
}
/*! \brief Set the title of the window
*
* \param title The title to set to the window
*
*/
void WindowImplX11::setTitle(const String& title)
{
XStoreName(m_display->getHandler(), m_handler, title);
}
/*! \brief Get the title of the window
*
* \return Return the title of the window
*
*/
String WindowImplX11::getTitle() const
{
}
/*! \brief Check if the window has the focus
*
* \param Return true if the window has the focus, false otherwise
*
*/
bool WindowImplX11::hasFocus() const
{
}
/*! \brief Enter or leave the fullscreen mode
*
* \param mode The VideoMode to use
* \param fullscreen False to leave the fullscreen mode, true to enter the fullscreen mode
*
* \return Return true if the switch was done successfully, false otherwise
*
*/
bool WindowImplX11::switchFullscreen(const VideoMode& mode, bool fullscreen)
{
}
/*! \brief Show or hide the window
*
* \param visible True to show the window, false to hide the window
*
*/
void WindowImplX11::setVisible(bool visible)
{
}
/*! \brief Get the window system handler
*
* \return Return the native window system handler
*
*/
WindowHandler WindowImplX11::getSystemHandler() const
{
return m_handler;
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <math.h>
#include <cmath>
#include "CombFilterProject.h"
#include "FilterAudio.h"
//# define TEST_MODE
using namespace std;
//function
int testZeroInput();
float *sinOsc(float, float, float, unsigned);
int testFIRFeedforward();
int testIIRFeedforward();
// main function
int main(int argc, char* argv[])
{
//decalare local variables
CombFilterProject *pCombFilterProject;
string sInputFilePath, sOutputFilePath, sInputFileName, sOutputFileName;
float fFIRCoeff = 0.0;
float fIIRCoeff = 0.0;
float fDelayInMSec = 0.0;
int iBlockSize = 2048; //default blockSize
bool bOutputResultToTextFile = false; //default
int iFileOpenStatus;
// Parse command line arguments
if( argc == 7 || argc == 8) {
//File path and name
sInputFilePath = argv[1];
sInputFileName = argv[2];
//Gain
fFIRCoeff = atof(argv[3]);
fIIRCoeff = atof(argv[4]);
//Check for boundary conditions
if (fFIRCoeff > 1 || fFIRCoeff < -1 || fIIRCoeff > 1 || fFIRCoeff < -1) {
cout<<"\nFIR/IIR Co-efficient should be between -1 and 1.\n";
return 0;
}
//Delay time
fDelayInMSec = atof(argv[5]);
//Check that delay time is positive
if (fDelayInMSec < 0 ) {
cout<<"\nDelay time must be positive.\n";
return 0;
}
//enable write to Text file
if (argv[6] != NULL) {
int temp = atoi(argv[6]);
if (temp == 1) {
bOutputResultToTextFile = true;
}
}
//Optional argument to set blockSize
if (argv[7] != NULL) {
iBlockSize = atoi(argv[7]);
}
}
else if( argc > 8 ) {
printf("Too many arguments supplied.\n");
return 0;
}
else {
printf("Please provide the following\n 1.file path\n 2.audio file name\n 3.FIR gain\n 4.IIR gain\n 5.delay time in milliseconds\n 6.write to text file (yes - 1, no - any value)\n 7.[OPTIONAL] block size\n ");
return 0;
}
//Create Comb Filter
CombFilterProject::create(pCombFilterProject, iBlockSize);
//Print Information
cout<<"CombFilter V"<<pCombFilterProject->getVersion(CombFilterProject::kMajor)
<<"."<<pCombFilterProject->getVersion(CombFilterProject::kMinor)
<<"."<<pCombFilterProject->getVersion(CombFilterProject::kPatch)<<endl;
cout<<"Build date: "<<pCombFilterProject->getBuildDate()<<endl<<endl;
cout<<"Reading audio file: "<<sInputFilePath<<sInputFileName<<"\n";
cout<<"\nFIR Coefficient:"<<fFIRCoeff;
cout<<"\nIIR Coefficient:"<<fIIRCoeff;
cout<<"\nBlock size :"<<iBlockSize;
cout<<"\nDelay in milliseconds :"<<fDelayInMSec;
//Set defaults
sOutputFilePath = sInputFilePath;
sOutputFileName = "output.wav";
//Initialize CombFilter
iFileOpenStatus = pCombFilterProject->init(sInputFilePath, sInputFileName, sOutputFilePath, sOutputFileName, fFIRCoeff, fIIRCoeff, fDelayInMSec, bOutputResultToTextFile);
if (iFileOpenStatus != 0) {
/*File open error*/
return 0;
}
cout<<"\nDelay in samples: "<<pCombFilterProject->getDelayinSamples()<<endl<<endl;
pCombFilterProject->processAudio();
pCombFilterProject->destroy(pCombFilterProject);
cout<<"Success!\n";
testZeroInput();
testFIRFeedforward();
testIIRFeedforward();
return 0;
}
int testZeroInput() {
FilterAudio *pFilter;
float fFIRCoeff = 1.0;
float fIIRCoeff = 0.0;
int iDelayInSamples = 10;
int iNumChannels = 1;
int iBlockSize = 1024;
int iNumBlocks = 50; //Test for 10 blocks
float **ppfAudioData = new float *[iNumChannels];
for (int n=0; n<iNumChannels; n++) {
ppfAudioData[n] = new float[iBlockSize];
for (int m=0; m<iBlockSize; m++) {
ppfAudioData[n][m] = 0;
}
}
pFilter = new FilterAudio(fFIRCoeff, fIIRCoeff, iDelayInSamples, iNumChannels);
while (iNumBlocks > 0) {
pFilter->combFilterBlock(ppfAudioData, iBlockSize, iNumChannels);
for (int n=0; n<iNumChannels; n++) {
for (int m=0; m<iBlockSize; m++) {
if (ppfAudioData[n][m] > 0.001) {
cout<<"\nZero Input Test: failed!\n";
return -1;
}
}
}
iNumBlocks--;
}
cout<<"\nZero Input Test: Success!\n";
return 0;
}
int testFIRFeedforward() {
FilterAudio *pFilter;
float fFIRCoeff = 1.0;
float fIIRCoeff = 0.0;
int iDelayInSamples = 50;
int iNumChannels = 1;
int iBlockSize = 1024;
int iNumBlocks;
float fFreq = 441.0; //Hz
float fTimeInSecs = 2.0;
unsigned uSampleRate = 44100;
float **buffer = new float *[iNumChannels];
for (int i=0;i<iNumChannels ;i++) {
buffer[i] = new float[iBlockSize];
}
pFilter = new FilterAudio(fFIRCoeff, fIIRCoeff, iDelayInSamples, iNumChannels);
float *sinWave = sinOsc(fFreq, 1.0, fTimeInSecs, uSampleRate);
int iLengthInSamples = ceil(fTimeInSecs * uSampleRate);
iNumBlocks = ceil((float)iLengthInSamples/(float)iBlockSize);
for (int c=0; c<iNumChannels; c++) {
int start = 0;
for (int n=0; n<iNumBlocks-1; n++) {
if (n*iBlockSize > iLengthInSamples) {
memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));
}
else {
memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));
}
buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);
start = 0;
if (n == 0){
start = iDelayInSamples+1;
}
for (int m=start; m<iBlockSize; m++) {
if (std::abs(buffer[c][m]) > 0.001) {
cout<<"\nFIR Feedforward Test: failed!\n";
return -1;
}
}
}
cout<<"\nFIR Feedforward Test: Success!\n";
}
return 0;
}
int testIIRFeedforward() {
FilterAudio *pFilter;
float fFIRCoeff = 0.0;
float fIIRCoeff = 0.1;
int iDelayInSamples = 100;
int iNumChannels = 1;
int iBlockSize = 1024;
int iNumBlocks;
float fFreq = 441.0; //Hz
float fTimeInSecs = 2.0;
unsigned uSampleRate = 44100;
float **buffer = new float *[iNumChannels];
for (int i=0;i<iNumChannels ;i++) {
buffer[i] = new float[iBlockSize];
}
float **origBuffer = new float *[iNumChannels];
for (int i=0;i<iNumChannels ;i++) {
origBuffer[i] = new float[iBlockSize];
}
pFilter = new FilterAudio(fFIRCoeff, fIIRCoeff, iDelayInSamples, iNumChannels);
float *sinWave = sinOsc(fFreq, 1.0, fTimeInSecs, uSampleRate);
int iLengthInSamples = ceil(fTimeInSecs * uSampleRate);
iNumBlocks = ceil((float)iLengthInSamples/(float)iBlockSize);
// int iPeriodInSamples = (int)uSampleRate/fFreq;
for (int c=0; c<iNumChannels; c++) {
for (int n=0; n<iNumBlocks-1; n++) {
if (n*iBlockSize > iLengthInSamples) {
memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));
}
else {
memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));
memcpy(origBuffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));
}
buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);
float* temp = buffer[c];
float* origTemp = origBuffer[c];
// float* diff = new float[iBlockSize];
// for (int m=iPeriodInSamples+iPeriodInSamples/4; m<iBlockSize; m=m+iPeriodInSamples) {
//
// if (buffer[c][m] <= origBuffer[c][m]) {
// cout<<"\IIR Feedforward Test: failed!\n";
// return -1;
// }
//
//
// }
}
cout<<"\nIIR Feedforward Test: Success!\n";
}
return 0;
}
float *sinOsc(float fFreq, float fAmp, float fLengthInSec, unsigned uFs){
float pi = 3.1415926535897932346;
int lengthInSamples = ceil(fLengthInSec * uFs);
float* fSineWave = new float[lengthInSamples];
// Fill sine wave
for(int i = 0; i<lengthInSamples; i++){
fSineWave[i] = fAmp* sin((2.f*pi*fFreq)/(uFs) *i);
}
return fSineWave;
}
<commit_msg>All test functions updated<commit_after>#include <iostream>
#include <math.h>
#include <cmath>
#include "CombFilterProject.h"
#include "FilterAudio.h"
# define TEST_MODE
using namespace std;
//function declarations
float *sinOsc(float, float, float, unsigned);
int testZeroInput();
int testFIRFeedforward();
int testIIRDestructiveFeedforward();
int testIIRConstructiveFeedforward();
int testDifferntBlockSizes();
int testZeroDelay(int, float, float);
int testFIRImpulseResponse();
int testIIRImpulseResponse();
// main function
int main(int argc, char* argv[])
{
//decalare local variables
CombFilterProject *pCombFilterProject;
string sInputFilePath, sOutputFilePath, sInputFileName, sOutputFileName;
float fFIRCoeff = 0.0;
float fIIRCoeff = 0.0;
float fDelayInMSec = 0.0;
int iBlockSize = 2048; //default blockSize
bool bOutputResultToTextFile = false; //default
int iFileOpenStatus;
// Parse command line arguments
if( argc == 7 || argc == 8) {
//File path and name
sInputFilePath = argv[1];
sInputFileName = argv[2];
//Gain
fFIRCoeff = atof(argv[3]);
fIIRCoeff = atof(argv[4]);
//Check for boundary conditions
if (fFIRCoeff > 1 || fFIRCoeff < -1 || fIIRCoeff > 1 || fFIRCoeff < -1) {
cout<<"\nFIR/IIR Co-efficient should be between -1 and 1.\n";
return 0;
}
//Delay time
fDelayInMSec = atof(argv[5]);
//Check that delay time is positive
if (fDelayInMSec < 0 ) {
cout<<"\nDelay time must be positive.\n";
return 0;
}
//enable write to Text file
if (argv[6] != NULL) {
int temp = atoi(argv[6]);
if (temp == 1) {
bOutputResultToTextFile = true;
}
}
//Optional argument to set blockSize
if (argv[7] != NULL) {
iBlockSize = atoi(argv[7]);
}
}
else if( argc > 8 ) {
printf("Too many arguments supplied.\n");
return 0;
}
else {
printf("Please provide the following\n 1.file path\n 2.audio file name\n 3.FIR gain\n 4.IIR gain\n 5.delay time in milliseconds\n 6.write to text file (yes - 1, no - any value)\n 7.[OPTIONAL] block size\n ");
return 0;
}
//Create Comb Filter
CombFilterProject::create(pCombFilterProject, iBlockSize);
//Print Information
cout<<"CombFilter V"<<pCombFilterProject->getVersion(CombFilterProject::kMajor)
<<"."<<pCombFilterProject->getVersion(CombFilterProject::kMinor)
<<"."<<pCombFilterProject->getVersion(CombFilterProject::kPatch)<<endl;
cout<<"Build date: "<<pCombFilterProject->getBuildDate()<<endl<<endl;
cout<<"Reading audio file: "<<sInputFilePath<<sInputFileName<<"\n";
cout<<"\nFIR Coefficient:"<<fFIRCoeff;
cout<<"\nIIR Coefficient:"<<fIIRCoeff;
cout<<"\nBlock size :"<<iBlockSize;
cout<<"\nDelay in milliseconds :"<<fDelayInMSec;
//Set defaults
sOutputFilePath = sInputFilePath;
sOutputFileName = "output.wav";
//Initialize CombFilter
iFileOpenStatus = pCombFilterProject->init(sInputFilePath, sInputFileName, sOutputFilePath, sOutputFileName, fFIRCoeff, fIIRCoeff, fDelayInMSec, bOutputResultToTextFile);
if (iFileOpenStatus != 0) {
/*File open error*/
return 0;
}
cout<<"\nDelay in samples: "<<pCombFilterProject->getDelayinSamples()<<endl<<endl;
pCombFilterProject->processAudio();
pCombFilterProject->destroy(pCombFilterProject);
cout<<"Success!\n";
#ifdef TEST_MODE
cout<<"\n====== Test Results ======\n";
testFIRFeedforward();
testIIRDestructiveFeedforward();
testIIRConstructiveFeedforward();
testDifferntBlockSizes();
testZeroInput();
//--- Some extra tests --- //
if (testZeroDelay(1024, 1.0, 0)==0) {
cout<<"\nZero Delay Test: Success!\n";
}
testFIRImpulseResponse();
testIIRImpulseResponse();
#endif
return 0;
}
int testZeroInput() {
FilterAudio *pFilter;
float fFIRCoeff = 1.0;
float fIIRCoeff = 0.0;
int iDelayInSamples = 10;
int iNumChannels = 1;
int iBlockSize = 1024;
int iNumBlocks = 50; //Length of sample is 50 blocks
//Allocate memory
float **ppfAudioData = new float *[iNumChannels];
for (int n=0; n<iNumChannels; n++) {
ppfAudioData[n] = new float[iBlockSize];
for (int m=0; m<iBlockSize; m++) {
ppfAudioData[n][m] = 0; //Initialize all samples to zero
}
}
pFilter = new FilterAudio(fFIRCoeff, fIIRCoeff, iDelayInSamples, iNumChannels);
while (iNumBlocks > 0) {
//Get filtered data
ppfAudioData = pFilter->combFilterBlock(ppfAudioData, iBlockSize, iNumChannels);
for (int n=0; n<iNumChannels; n++) {
for (int m=0; m<iBlockSize; m++) {
//Check if all the values are 0
if (abs(ppfAudioData[n][m]) > 0.001) {
cout<<"\nZero Input Test: failed!\n";
return -1;
}
}
}
iNumBlocks--;
}
cout<<"\nZero Input Test: Success!\n";
//Free memory
delete pFilter;
pFilter = 0;
for (int n=0; n<iNumChannels; n++) {
delete [] ppfAudioData[n];
}
delete ppfAudioData;
return 0;
}
int testFIRFeedforward() {
FilterAudio *pFilter;
float fFIRCoeff = 1.0;
float fIIRCoeff = 0.0;
int iNumChannels = 1;
int iBlockSize = 400;
int iNumBlocks;
float fFreq = 441.0; //in Hz - Test sine wave
float fAmp = 1.0;
float fTimeInSecs = 2.0; // 2 seconds long
unsigned uSampleRate = 44100;
int iPeriodInSamples = uSampleRate/fFreq; // 100 samples in this case
int iDelayInSamples = iPeriodInSamples/2; //Delay = 50 samples to create destructive interference
//Allocate memory
float **buffer = new float *[iNumChannels];
for (int i=0;i<iNumChannels ;i++) {
buffer[i] = new float[iBlockSize];
}
//Create sine wave
float *sinWave = sinOsc(fFreq, fAmp, fTimeInSecs, uSampleRate);
pFilter = new FilterAudio(fFIRCoeff, fIIRCoeff, iDelayInSamples, iNumChannels);
int iLengthInSamples = ceil(fTimeInSecs * uSampleRate);
//To block the sine wave audio
iNumBlocks = ceil((float)iLengthInSamples/(float)iBlockSize);
for (int c=0; c<iNumChannels; c++) {
int start = 0;
for (int n=0; n<iNumBlocks-1; n++) {
if (n*iBlockSize > iLengthInSamples) {
memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));
}
else {
memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));
}
buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);
//Ignore first part of the first block
start = 0;
if (n == 0){
start = iDelayInSamples+1;
}
for (int m=start; m<iBlockSize; m++) {
//Check for Complete destructive interference - so all values are zero
if (std::abs(buffer[c][m]) > 0.001) {
cout<<"\nFIR Feedforward Test: failed!\n";
return -1;
}
}
}
cout<<"\nFIR Feedforward Test: Success!\n";
}
//Free memory
delete pFilter;
pFilter = 0;
for (int i=0;i<iNumChannels ;i++) {
delete [] buffer[i];
}
delete buffer;
delete [] sinWave;
return 0;
}
int testIIRDestructiveFeedforward() {
FilterAudio *pFilter;
float fFIRCoeff = 0.0;
float fIIRCoeff = 0.1;
int iNumChannels = 1;
int iBlockSize = 1024;
int iNumBlocks;
float fFreq = 441.0; //Hz - Test sine wave
float fAmp = 1.0;
float fTimeInSecs = 2.0;
unsigned uSampleRate = 44100;
int iPeriodInSamples = uSampleRate/fFreq; //100 samples
int iDelayInSamples = iPeriodInSamples/2; //50 samples - Causing Destructive interference by 0.1 margin
float **buffer = new float *[iNumChannels];
for (int i=0;i<iNumChannels ;i++) {
buffer[i] = new float[iBlockSize];
}
pFilter = new FilterAudio(fFIRCoeff, fIIRCoeff, iDelayInSamples, iNumChannels);
float *sinWave = sinOsc(fFreq, fAmp, fTimeInSecs, uSampleRate);
int iLengthInSamples = ceil(fTimeInSecs * uSampleRate);
iNumBlocks = ceil((float)iLengthInSamples/(float)iBlockSize);
for (int c=0; c<iNumChannels; c++) {
int start = 0;
float fMaxAmp = 0;
for (int n=0; n<iNumBlocks-1; n++) {
if (n*iBlockSize > iLengthInSamples) {
memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));
}
else {
memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));
}
buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);
if (n == 0){
start = iPeriodInSamples+1;
}
for (int m=0+start; m<iBlockSize; m++) {
if (buffer[c][m] >= fMaxAmp) {
fMaxAmp = buffer[c][m];
}
}
//Max amplitude of output should always be less than input
if (fMaxAmp >= fAmp) {
cout<<"\nIIR Desructive Feedforward Test: failed!\n";
return -1;
}
}
cout<<"\nIIR Destructive Feedforward Test: Success!\n";
}
//Free memory
delete pFilter;
pFilter = 0;
for (int i=0;i<iNumChannels ;i++) {
delete [] buffer[i];
}
delete buffer;
delete [] sinWave;
return 0;
}
int testIIRConstructiveFeedforward() {
FilterAudio *pFilter;
float fFIRCoeff = 0.0;
float fIIRCoeff = 0.1;
int iNumChannels = 1;
int iBlockSize = 1024;
int iNumBlocks;
float fFreq = 441.0; //Hz
float fAmp = 1.0;
float fTimeInSecs = 2.0;
unsigned uSampleRate = 44100;
int iPeriodInSamples = uSampleRate/fFreq; //100 samples
int iDelayInSamples = iPeriodInSamples; //100 samples - Constructive interference
float **buffer = new float *[iNumChannels];
for (int i=0;i<iNumChannels ;i++) {
buffer[i] = new float[iBlockSize];
}
pFilter = new FilterAudio(fFIRCoeff, fIIRCoeff, iDelayInSamples, iNumChannels);
float *sinWave = sinOsc(fFreq, fAmp, fTimeInSecs, uSampleRate);
int iLengthInSamples = ceil(fTimeInSecs * uSampleRate);
iNumBlocks = ceil((float)iLengthInSamples/(float)iBlockSize);
for (int c=0; c<iNumChannels; c++) {
int start = 0;
float fMaxAmp = 0;
for (int n=0; n<iNumBlocks-1; n++) {
if (n*iBlockSize > iLengthInSamples) {
memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));
}
else {
memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));
}
buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);
if (n == 0){
start = iPeriodInSamples+1;
}
for (int m=0+start; m<iBlockSize; m++) {
if (buffer[c][m] >= fMaxAmp) {
fMaxAmp = buffer[c][m];
}
}
//Max amplitude of output should always be greater than input
if (fMaxAmp <= fAmp) {
cout<<"\nIIR Constructive Feedforward Test: failed!\n";
return -1;
}
}
cout<<"\nIIR Constructive Feedforward Test: Success!\n";
}
//Free memory
delete pFilter;
pFilter = 0;
for (int i=0;i<iNumChannels ;i++) {
delete [] buffer[i];
}
delete buffer;
delete [] sinWave;
return 0;
}
int testDifferntBlockSizes() {
if(testZeroDelay(1024, 1.0, 0)!=0) {
cout<<"\nVarying block size test @ 1024 : failed!\n";
return -1;
}
if(testZeroDelay(256, 0.5, 0.5)!=0) {
cout<<"\nVarying block size test @ 1024 : failed!\n";
return -1;
}
if(testZeroDelay(2048, 0.5, 1.0)!=0) {
cout<<"\nVarying block size test @ 1024 : failed!\n";
return -1;
}
if(testZeroDelay(4096, 0, 1.0)!=0) {
cout<<"\nVarying block size test @ 1024 : failed!\n";
return -1;
}
cout<<"\nVarying block size test : Success!\n";
return 0;
}
int testZeroDelay(int iBlockSize, float fFIRCoeff, float fIIRCoeff) {
FilterAudio *pFilter;
int iNumChannels = 1;
int iNumBlocks;
float fFreq = 441.0; //Hz - Test sine wave
float fAmp = 1.0;
float fTimeInSecs = 2.0;
unsigned uSampleRate = 44100;
int iDelayInSamples = 0; //No delay
float **buffer = new float *[iNumChannels];
for (int i=0;i<iNumChannels ;i++) {
buffer[i] = new float[iBlockSize];
}
float **origBuffer = new float *[iNumChannels];
for (int i=0;i<iNumChannels ;i++) {
origBuffer[i] = new float[iBlockSize];
}
pFilter = new FilterAudio(fFIRCoeff, fIIRCoeff, iDelayInSamples, iNumChannels);
float *sinWave = sinOsc(fFreq, fAmp, fTimeInSecs, uSampleRate);
int iLengthInSamples = ceil(fTimeInSecs * uSampleRate);
iNumBlocks = ceil((float)iLengthInSamples/(float)iBlockSize);
for (int c=0; c<iNumChannels; c++) {
for (int n=0; n<iNumBlocks-1; n++) {
if (n*iBlockSize > iLengthInSamples) {
memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));
memcpy(origBuffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));
}
else {
memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));
memcpy(origBuffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));
}
buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);
for (int m=0; m<iBlockSize; m++) {
//Output should be same as input
if (buffer[c][m] != origBuffer[c][m]) {
cout<<"\nZero Delay Test: failure!\n";
return -1;
}
}
}
}
//Free memory
delete pFilter;
pFilter = 0;
for (int i=0;i<iNumChannels ;i++) {
delete [] buffer[i];
}
delete buffer;
for (int i=0;i<iNumChannels ;i++) {
delete [] origBuffer[i];
}
delete origBuffer;
delete [] sinWave;
return 0;
}
int testFIRImpulseResponse() {
FilterAudio *pFilter;
float fFIRCoeff = 1.0;
float fIIRCoeff = 0.0;
int iDelayInSamples = 5;
int iNumChannels = 1;
int iBlockSize = 1024;
int iNumBlocks = 1; //Do this test only for 1 block
float **ppfAudioData = new float *[iNumChannels];
for (int n=0; n<iNumChannels; n++) {
ppfAudioData[n] = new float[iBlockSize];
for (int m=0; m<iBlockSize; m++) {
ppfAudioData[n][m] = 0;
}
ppfAudioData[n][0]=1.0;
}
pFilter = new FilterAudio(fFIRCoeff, fIIRCoeff, iDelayInSamples, iNumChannels);
for (int n=0; n<iNumBlocks; n++) {
ppfAudioData = pFilter->combFilterBlock(ppfAudioData, iBlockSize, iNumChannels);
for (int n=0; n<iNumChannels; n++) {
for (int m=0; m<iBlockSize; m++) {
//Check for peak at the m=delaylength
if (m==0 || m==iDelayInSamples) {
if (ppfAudioData[n][m] != 1.0F) {
cout<<"\nFIR Impulse Response Test: failed!\n";
return -1;
}
}
else {
if (ppfAudioData[n][m] > 0.001) {
cout<<"\nFIR Impulse Response Test: failed!\n";
return -1;
}
}
}
}
}
cout<<"\nFIR Impulse Response Test: Success!\n";
//Free memory
delete pFilter;
pFilter = 0;
for (int i=0;i<iNumChannels ;i++) {
delete [] ppfAudioData[i];
}
delete ppfAudioData;
return 0;
}
int testIIRImpulseResponse() {
FilterAudio *pFilter;
float fFIRCoeff = 0.0;
float fIIRCoeff = 1.0;
int iDelayInSamples = 5;
int iNumChannels = 1;
int iBlockSize = 1024;
int iNumBlocks = 1; //Do this test only for 1 block
float **ppfAudioData = new float *[iNumChannels];
for (int n=0; n<iNumChannels; n++) {
ppfAudioData[n] = new float[iBlockSize];
for (int m=0; m<iBlockSize; m++) {
ppfAudioData[n][m] = 0;
}
ppfAudioData[n][0]=1.0;
}
pFilter = new FilterAudio(fFIRCoeff, fIIRCoeff, iDelayInSamples, iNumChannels);
for (int n=0; n<iNumBlocks; n++) {
ppfAudioData = pFilter->combFilterBlock(ppfAudioData, iBlockSize, iNumChannels);
for (int n=0; n<iNumChannels; n++) {
for (int m=0; m<iBlockSize; m++) {
if (m%5==0) {
//Check for peaks at multiples of delay length
if (ppfAudioData[n][m] != 1.0F) {
cout<<"\nIIR Impulse Response Test: failed!\n";
return -1;
}
}
else {
if (ppfAudioData[n][m] > 0.001) {
cout<<"\nIIR Impulse Response Test: failed!\n";
return -1;
}
}
}
}
}
cout<<"\nIIR Impulse Response Test: Success!\n";
//Free memory
delete pFilter;
pFilter = 0;
for (int i=0;i<iNumChannels ;i++) {
delete [] ppfAudioData[i];
}
delete ppfAudioData;
return 0;
}
float *sinOsc(float fFreq, float fAmp, float fLengthInSec, unsigned uFs){
float pi = 3.1415926535897932346;
int lengthInSamples = ceil(fLengthInSec * uFs);
float* fSineWave = new float[lengthInSamples];
// Fill sine wave
for(int i = 0; i<lengthInSamples; i++){
fSineWave[i] = fAmp* sin((2.f*pi*fFreq)/(uFs) *i);
}
return fSineWave;
}
<|endoftext|> |
<commit_before>#include "PhysicsManager.hpp"
#include <btBulletDynamicsCommon.h>
#include <glm/gtx/quaternion.hpp>
#include "../Component/RigidBody.hpp"
#include "../Component/Shape.hpp"
#include "../Entity/Entity.hpp"
#include "../Physics/GlmConversion.hpp"
#include "../Physics/Shape.hpp"
#include "../Physics/Trigger.hpp"
#include "../Physics/TriggerObserver.hpp"
#include "../Util/Json.hpp"
PhysicsManager::PhysicsManager() {
// The broadphase is used to quickly cull bodies that will not collide with
// each other, normally by leveraging some simpler (and rough) test such as
// bounding boxes.
broadphase = new btDbvtBroadphase;
// With the collision configuration one can configure collision detection
// algorithms.
collisionConfiguration = new btDefaultCollisionConfiguration;
dispatcher = new btCollisionDispatcher(collisionConfiguration);
// The solver makes objects interact by making use of gravity, collisions,
// game logic supplied forces, and constraints.
solver = new btSequentialImpulseConstraintSolver;
// The dynamics world encompasses objects included in the simulation.
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
// Y axis up
dynamicsWorld->setGravity(btVector3(0, -9.82, 0));
// Set the lockbox key we will use for lockboxes created in here.
triggerLockBoxKey.reset(new Utility::LockBox<Physics::Trigger>::Key());
}
PhysicsManager::~PhysicsManager() {
delete dynamicsWorld;
delete solver;
delete dispatcher;
delete collisionConfiguration;
delete broadphase;
for (auto t : triggers) {
delete t;
}
}
void PhysicsManager::Update(float deltaTime) {
for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {
if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) {
continue;
}
rigidBodyComp->Position(rigidBodyComp->entity->position);
dynamicsWorld->removeRigidBody(rigidBodyComp->GetBulletRigidBody());
dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody());
rigidBodyComp->GetBulletRigidBody()->setGravity(btVector3(0, 0, 0));
}
dynamicsWorld->stepSimulation(deltaTime, 10);
for (auto trigger : triggers) {
trigger->Process(*dynamicsWorld);
}
}
void PhysicsManager::UpdateEntityTransforms() {
for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {
if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled)
continue;
Entity* entity = rigidBodyComp->entity;
auto trans = rigidBodyComp->GetBulletRigidBody()->getWorldTransform();
entity->position = Physics::btToGlm(trans.getOrigin());
entity->SetLocalOrientation(Physics::btToGlm(trans.getRotation()));
}
}
void PhysicsManager::OnTriggerEnter(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](Physics::TriggerObserver& observer) {
observer.OnEnter(callback);
});
});
}
void PhysicsManager::OnTriggerRetain(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {
observer.OnRetain(callback);
});
});
}
void PhysicsManager::OnTriggerLeave(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {
observer.OnLeave(callback);
});
});
}
Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner) {
auto comp = rigidBodyComponents.Create();
comp->entity = owner;
comp->NewBulletRigidBody(1.0f);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp) {
comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());
}
return comp;
}
Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner, const Json::Value& node) {
auto comp = rigidBodyComponents.Create();
comp->entity = owner;
auto mass = node.get("mass", 1.0f).asFloat();
comp->NewBulletRigidBody(mass);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp) {
comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());
}
return comp;
}
Component::Shape* PhysicsManager::CreateShape(Entity* owner) {
auto comp = shapeComponents.Create();
comp->entity = owner;
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(1.0f)));
comp->SetShape(shape);
auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>();
if (rigidBodyComp) {
rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());
}
return comp;
}
Component::Shape* PhysicsManager::CreateShape(Entity* owner, const Json::Value& node) {
auto comp = shapeComponents.Create();
comp->entity = owner;
if (node.isMember("sphere")) {
auto sphere = node.get("sphere", {});
auto radius = sphere.get("radius", 1.0f).asFloat();
auto shape = std::shared_ptr<::Physics::Shape>(new ::Physics::Shape(::Physics::Shape::Sphere(radius)));
comp->SetShape(shape);
}
else if (node.isMember("plane")) {
auto plane = node.get("plane", {});
auto normal = Json::LoadVec3(plane.get("normal", {}));
auto planeCoeff = plane.get("planeCoeff", 0.0f).asFloat();
auto shape = std::shared_ptr<::Physics::Shape>(new ::Physics::Shape(::Physics::Shape::Plane(normal, planeCoeff)));
comp->SetShape(shape);
}
auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>();
if (rigidBodyComp) {
rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());
}
return comp;
}
Utility::LockBox<Physics::Trigger> PhysicsManager::CreateTrigger(Component::RigidBody* comp) {
btTransform trans(btQuaternion(0, 0, 0, 1), ::Physics::glmToBt(comp->entity->position));
Physics::Trigger* trigger = new Physics::Trigger(trans);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
trigger->SetCollisionShape(shapeComp ? shapeComp->GetShape() : nullptr);
triggers.push_back(trigger);
return Utility::LockBox<Physics::Trigger>(triggerLockBoxKey, trigger);
}
void PhysicsManager::SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape) {
comp->SetShape(shape);
}
void PhysicsManager::SetMass(Component::RigidBody* comp, float mass) {
// Setting mass is only valid with a shape because it also sets inertia.
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp)
comp->Mass(mass);
}
const std::vector<Component::Shape*>& PhysicsManager::GetShapeComponents() const {
return shapeComponents.GetAll();
}
void PhysicsManager::ClearKilledComponents() {
rigidBodyComponents.ClearKilled(
[this](Component::RigidBody* body) {
dynamicsWorld->removeRigidBody(body->GetBulletRigidBody());
});
shapeComponents.ClearKilled();
}
<commit_msg>Remove braces around single statement for.<commit_after>#include "PhysicsManager.hpp"
#include <btBulletDynamicsCommon.h>
#include <glm/gtx/quaternion.hpp>
#include "../Component/RigidBody.hpp"
#include "../Component/Shape.hpp"
#include "../Entity/Entity.hpp"
#include "../Physics/GlmConversion.hpp"
#include "../Physics/Shape.hpp"
#include "../Physics/Trigger.hpp"
#include "../Physics/TriggerObserver.hpp"
#include "../Util/Json.hpp"
PhysicsManager::PhysicsManager() {
// The broadphase is used to quickly cull bodies that will not collide with
// each other, normally by leveraging some simpler (and rough) test such as
// bounding boxes.
broadphase = new btDbvtBroadphase;
// With the collision configuration one can configure collision detection
// algorithms.
collisionConfiguration = new btDefaultCollisionConfiguration;
dispatcher = new btCollisionDispatcher(collisionConfiguration);
// The solver makes objects interact by making use of gravity, collisions,
// game logic supplied forces, and constraints.
solver = new btSequentialImpulseConstraintSolver;
// The dynamics world encompasses objects included in the simulation.
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
// Y axis up
dynamicsWorld->setGravity(btVector3(0, -9.82, 0));
// Set the lockbox key we will use for lockboxes created in here.
triggerLockBoxKey.reset(new Utility::LockBox<Physics::Trigger>::Key());
}
PhysicsManager::~PhysicsManager() {
delete dynamicsWorld;
delete solver;
delete dispatcher;
delete collisionConfiguration;
delete broadphase;
for (auto t : triggers)
delete t;
}
void PhysicsManager::Update(float deltaTime) {
for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {
if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) {
continue;
}
rigidBodyComp->Position(rigidBodyComp->entity->position);
dynamicsWorld->removeRigidBody(rigidBodyComp->GetBulletRigidBody());
dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody());
rigidBodyComp->GetBulletRigidBody()->setGravity(btVector3(0, 0, 0));
}
dynamicsWorld->stepSimulation(deltaTime, 10);
for (auto trigger : triggers) {
trigger->Process(*dynamicsWorld);
}
}
void PhysicsManager::UpdateEntityTransforms() {
for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {
if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled)
continue;
Entity* entity = rigidBodyComp->entity;
auto trans = rigidBodyComp->GetBulletRigidBody()->getWorldTransform();
entity->position = Physics::btToGlm(trans.getOrigin());
entity->SetLocalOrientation(Physics::btToGlm(trans.getRotation()));
}
}
void PhysicsManager::OnTriggerEnter(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](Physics::TriggerObserver& observer) {
observer.OnEnter(callback);
});
});
}
void PhysicsManager::OnTriggerRetain(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {
observer.OnRetain(callback);
});
});
}
void PhysicsManager::OnTriggerLeave(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {
observer.OnLeave(callback);
});
});
}
Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner) {
auto comp = rigidBodyComponents.Create();
comp->entity = owner;
comp->NewBulletRigidBody(1.0f);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp) {
comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());
}
return comp;
}
Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner, const Json::Value& node) {
auto comp = rigidBodyComponents.Create();
comp->entity = owner;
auto mass = node.get("mass", 1.0f).asFloat();
comp->NewBulletRigidBody(mass);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp) {
comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());
}
return comp;
}
Component::Shape* PhysicsManager::CreateShape(Entity* owner) {
auto comp = shapeComponents.Create();
comp->entity = owner;
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(1.0f)));
comp->SetShape(shape);
auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>();
if (rigidBodyComp) {
rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());
}
return comp;
}
Component::Shape* PhysicsManager::CreateShape(Entity* owner, const Json::Value& node) {
auto comp = shapeComponents.Create();
comp->entity = owner;
if (node.isMember("sphere")) {
auto sphere = node.get("sphere", {});
auto radius = sphere.get("radius", 1.0f).asFloat();
auto shape = std::shared_ptr<::Physics::Shape>(new ::Physics::Shape(::Physics::Shape::Sphere(radius)));
comp->SetShape(shape);
}
else if (node.isMember("plane")) {
auto plane = node.get("plane", {});
auto normal = Json::LoadVec3(plane.get("normal", {}));
auto planeCoeff = plane.get("planeCoeff", 0.0f).asFloat();
auto shape = std::shared_ptr<::Physics::Shape>(new ::Physics::Shape(::Physics::Shape::Plane(normal, planeCoeff)));
comp->SetShape(shape);
}
auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>();
if (rigidBodyComp) {
rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());
}
return comp;
}
Utility::LockBox<Physics::Trigger> PhysicsManager::CreateTrigger(Component::RigidBody* comp) {
btTransform trans(btQuaternion(0, 0, 0, 1), ::Physics::glmToBt(comp->entity->position));
Physics::Trigger* trigger = new Physics::Trigger(trans);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
trigger->SetCollisionShape(shapeComp ? shapeComp->GetShape() : nullptr);
triggers.push_back(trigger);
return Utility::LockBox<Physics::Trigger>(triggerLockBoxKey, trigger);
}
void PhysicsManager::SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape) {
comp->SetShape(shape);
}
void PhysicsManager::SetMass(Component::RigidBody* comp, float mass) {
// Setting mass is only valid with a shape because it also sets inertia.
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp)
comp->Mass(mass);
}
const std::vector<Component::Shape*>& PhysicsManager::GetShapeComponents() const {
return shapeComponents.GetAll();
}
void PhysicsManager::ClearKilledComponents() {
rigidBodyComponents.ClearKilled(
[this](Component::RigidBody* body) {
dynamicsWorld->removeRigidBody(body->GetBulletRigidBody());
});
shapeComponents.ClearKilled();
}
<|endoftext|> |
<commit_before>
using namespace std;
#include "GEOMImpl_ShapeDriver.hxx"
#include "GEOMImpl_IShapes.hxx"
#include "GEOMImpl_IShapesOperations.hxx"
#include "GEOMImpl_Types.hxx"
#include "GEOM_Function.hxx"
#include <BRep_Tool.hxx>
#include <BRep_Builder.hxx>
#include <BRepAlgo_FaceRestrictor.hxx>
#include <BRepAlgo_Sewing.hxx>
#include <BRepBuilderAPI_Copy.hxx>
#include <BRepTools_Quilt.hxx>
#include <BRepCheck.hxx>
#include <BRepCheck_Analyzer.hxx>
#include <BRepCheck_Shell.hxx>
#include <BRepClass3d_SolidClassifier.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <TopAbs.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Compound.hxx>
#include <TopoDS_Iterator.hxx>
#include <TopExp_Explorer.hxx>
#include <TopTools_MapOfShape.hxx>
#include <TopTools_SequenceOfShape.hxx>
#include <TopTools_ListIteratorOfListOfShape.hxx>
#include <Precision.hxx>
#include <Standard_NullObject.hxx>
#include <Standard_TypeMismatch.hxx>
#include <Standard_ConstructionError.hxx>
//=======================================================================
//function : GetID
//purpose :
//=======================================================================
const Standard_GUID& GEOMImpl_ShapeDriver::GetID()
{
static Standard_GUID aShapeDriver("FF1BBB54-5D14-4df2-980B-3A668264EA16");
return aShapeDriver;
}
//=======================================================================
//function : GEOMImpl_ShapeDriver
//purpose :
//=======================================================================
GEOMImpl_ShapeDriver::GEOMImpl_ShapeDriver()
{
}
//=======================================================================
//function : Execute
//purpose :
//=======================================================================
Standard_Integer GEOMImpl_ShapeDriver::Execute(TFunction_Logbook& log) const
{
if (Label().IsNull()) return 0;
Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
GEOMImpl_IShapes aCI (aFunction);
Standard_Integer aType = aFunction->GetType();
TopoDS_Shape aShape;
BRep_Builder B;
if (aType == WIRE_EDGES) {
Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
unsigned int ind, nbshapes = aShapes->Length();
// add edges
BRepBuilderAPI_MakeWire MW;
for (ind = 1; ind <= nbshapes; ind++) {
Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
TopoDS_Shape aShape_i = aRefShape->GetValue();
if (aShape_i.IsNull()) {
Standard_NullObject::Raise("Shape for wire construction is null");
}
if (aShape_i.ShapeType() == TopAbs_EDGE)
MW.Add(TopoDS::Edge(aShape_i));
else if (aShape_i.ShapeType() == TopAbs_WIRE)
MW.Add(TopoDS::Wire(aShape_i));
else
Standard_TypeMismatch::Raise
("Shape for wire construction is neither an edge nor a wire");
}
if (!MW.IsDone()) {
Standard_ConstructionError::Raise("Wire construction failed");
}
aShape = MW;
} else if (aType == FACE_WIRE) {
Handle(GEOM_Function) aRefBase = aCI.GetBase();
TopoDS_Shape aShapeBase = aRefBase->GetValue();
if (aShapeBase.IsNull() || aShapeBase.ShapeType() != TopAbs_WIRE) {
Standard_NullObject::Raise
("Shape for face construction is null or not a wire");
}
TopoDS_Wire W = TopoDS::Wire(aShapeBase);
BRepBuilderAPI_MakeFace MF (W, aCI.GetIsPlanar());
if (!MF.IsDone()) {
Standard_ConstructionError::Raise("Face construction failed");
}
aShape = MF.Shape();
} else if (aType == FACE_WIRES) {
Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
// first wire
Handle(GEOM_Function) aRefWire = Handle(GEOM_Function)::DownCast(aShapes->Value(1));
TopoDS_Shape aWire = aRefWire->GetValue();
if (aWire.IsNull() || aWire.ShapeType() != TopAbs_WIRE) {
Standard_NullObject::Raise("Shape for face construction is null or not a wire");
}
TopoDS_Wire W = TopoDS::Wire(aWire);
// basic face
BRepBuilderAPI_MakeFace MF (W, aCI.GetIsPlanar());
if (!MF.IsDone()) {
Standard_ConstructionError::Raise("Face construction failed");
}
TopoDS_Shape FFace = MF.Shape();
if (!FFace.IsNull()) {
unsigned int ind, nbshapes = aShapes->Length();
if (nbshapes == 1) {
aShape = FFace;
} else if (nbshapes >= 2) {
TopoDS_Compound C;
BRep_Builder aBuilder;
aBuilder.MakeCompound(C);
BRepAlgo_FaceRestrictor FR;
TopAbs_Orientation OriF = FFace.Orientation();
TopoDS_Shape aLocalS = FFace.Oriented(TopAbs_FORWARD);
FR.Init(TopoDS::Face(aLocalS), Standard_False, Standard_True);
for (ind = 1; ind <= nbshapes; ind++) {
Handle(GEOM_Function) aRefWire_i =
Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
TopoDS_Shape aWire_i = aRefWire_i->GetValue();
if (aWire_i.IsNull() || aWire_i.ShapeType() != TopAbs_WIRE) {
Standard_NullObject::Raise("Shape for face construction is null or not a wire");
}
FR.Add(TopoDS::Wire(aWire_i));
}
FR.Perform();
if (FR.IsDone()) {
int k = 0;
TopoDS_Shape aFace;
for (; FR.More(); FR.Next()) {
aFace = FR.Current().Oriented(OriF);
aBuilder.Add(C, aFace);
k++;
}
if (k == 1) {
aShape = aFace;
} else {
aShape = C;
}
}
}
}
} else if (aType == SHELL_FACES) {
Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
unsigned int ind, nbshapes = aShapes->Length();
// add faces
BRepAlgo_Sewing aSewing(Precision::Confusion()*10.0);
for (ind = 1; ind <= nbshapes; ind++) {
Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
TopoDS_Shape aShape_i = aRefShape->GetValue();
if (aShape_i.IsNull()) {
Standard_NullObject::Raise("Face for shell construction is null");
}
aSewing.Add(aShape_i);
}
aSewing.Perform();
TopExp_Explorer exp (aSewing.SewedShape(), TopAbs_SHELL);
Standard_Integer ish = 0;
for (; exp.More(); exp.Next()) {
aShape = exp.Current();
ish++;
}
if (ish != 1)
aShape = aSewing.SewedShape();
} else if (aType == SOLID_SHELL) {
Handle(GEOM_Function) aRefShell = aCI.GetBase();
TopoDS_Shape aShapeShell = aRefShell->GetValue();
if (aShapeShell.IsNull() || aShapeShell.ShapeType() != TopAbs_SHELL) {
Standard_NullObject::Raise("Shape for solid construction is null or not a shell");
}
BRepCheck_Shell chkShell(TopoDS::Shell(aShapeShell));
if(chkShell.Closed() == BRepCheck_NotClosed) return 0;
TopoDS_Solid Sol;
B.MakeSolid(Sol);
B.Add(Sol, aShapeShell);
BRepClass3d_SolidClassifier SC (Sol);
SC.PerformInfinitePoint(Precision::Confusion());
if (SC.State() == TopAbs_IN) {
B.MakeSolid(Sol);
B.Add(Sol, aShapeShell.Reversed());
}
aShape = Sol;
} else if (aType == SOLID_SHELLS) {
Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
unsigned int ind, nbshapes = aShapes->Length();
Standard_Integer ish = 0;
TopoDS_Solid Sol;
TopoDS_Compound Res;
B.MakeCompound(Res);
// add shapes
for (ind = 1; ind <= nbshapes; ind++) {
Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
TopoDS_Shape aShapeShell = aRefShape->GetValue();
if (aShapeShell.IsNull()) {
Standard_NullObject::Raise("Shell for solid construction is null");
}
if (aShapeShell.ShapeType() == TopAbs_SHELL) {
B.MakeSolid(Sol);
B.Add(Sol, aShapeShell);
BRepClass3d_SolidClassifier SC (Sol);
SC.PerformInfinitePoint(Precision::Confusion());
if (SC.State() == TopAbs_IN) {
B.MakeSolid(Sol);
B.Add(Sol, aShapeShell.Reversed());
}
B.Add(Res, Sol);
ish++;
}
}
if (ish == 1) aShape = Sol;
else aShape = Res;
} else if (aType == COMPOUND_SHAPES) {
Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
unsigned int ind, nbshapes = aShapes->Length();
// add shapes
TopoDS_Compound C;
B.MakeCompound(C);
for (ind = 1; ind <= nbshapes; ind++) {
Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
TopoDS_Shape aShape_i = aRefShape->GetValue();
if (aShape_i.IsNull()) {
Standard_NullObject::Raise("Shape for compound construction is null");
}
B.Add(C, aShape_i);
}
aShape = C;
} else if (aType == REVERSE_ORIENTATION) {
Handle(GEOM_Function) aRefShape = aCI.GetBase();
TopoDS_Shape aShape_i = aRefShape->GetValue();
if (aShape_i.IsNull()) {
Standard_NullObject::Raise("Shape for reverse is null");
}
BRepBuilderAPI_Copy Copy(aShape_i);
if( Copy.IsDone() ) {
TopoDS_Shape tds = Copy.Shape();
if( tds.IsNull() ) {
Standard_ConstructionError::Raise("Orientation aborted : Can not reverse the shape");
}
if( tds.Orientation() == TopAbs_FORWARD)
tds.Orientation(TopAbs_REVERSED) ;
else
tds.Orientation(TopAbs_FORWARD) ;
aShape = tds;
}
}
if (aShape.IsNull()) return 0;
// Check shape validity
BRepCheck_Analyzer ana (aShape, false);
if (!ana.IsValid()) {
Standard_ConstructionError::Raise("Algorithm have produced an invalid shape result");
}
aFunction->SetValue(aShape);
log.SetTouched(Label());
return 1;
}
//=======================================================================
//function : GEOMImpl_ShapeDriver_Type_
//purpose :
//=======================================================================
Standard_EXPORT Handle_Standard_Type& GEOMImpl_ShapeDriver_Type_()
{
static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);
if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);
static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);
if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);
static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);
if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);
static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};
static Handle_Standard_Type _aType = new Standard_Type("GEOMImpl_ShapeDriver",
sizeof(GEOMImpl_ShapeDriver),
1,
(Standard_Address)_Ancestors,
(Standard_Address)NULL);
return _aType;
}
//=======================================================================
//function : DownCast
//purpose :
//=======================================================================
const Handle(GEOMImpl_ShapeDriver) Handle(GEOMImpl_ShapeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)
{
Handle(GEOMImpl_ShapeDriver) _anOtherObject;
if (!AnObject.IsNull()) {
if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_ShapeDriver))) {
_anOtherObject = Handle(GEOMImpl_ShapeDriver)((Handle(GEOMImpl_ShapeDriver)&)AnObject);
}
}
return _anOtherObject ;
}
<commit_msg>PAL9074. Now MakeSolidShells() makes one solid of all given shells like OCC MakeSolid() does<commit_after>
using namespace std;
#include "GEOMImpl_ShapeDriver.hxx"
#include "GEOMImpl_IShapes.hxx"
#include "GEOMImpl_IShapesOperations.hxx"
#include "GEOMImpl_Types.hxx"
#include "GEOM_Function.hxx"
#include <BRep_Tool.hxx>
#include <BRep_Builder.hxx>
#include <BRepAlgo_FaceRestrictor.hxx>
#include <BRepAlgo_Sewing.hxx>
#include <BRepBuilderAPI_Copy.hxx>
#include <BRepTools_Quilt.hxx>
#include <BRepCheck.hxx>
#include <BRepCheck_Analyzer.hxx>
#include <BRepCheck_Shell.hxx>
#include <BRepClass3d_SolidClassifier.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <TopAbs.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Compound.hxx>
#include <TopoDS_Iterator.hxx>
#include <TopExp_Explorer.hxx>
#include <TopTools_MapOfShape.hxx>
#include <TopTools_SequenceOfShape.hxx>
#include <TopTools_ListIteratorOfListOfShape.hxx>
#include <Precision.hxx>
#include <Standard_NullObject.hxx>
#include <Standard_TypeMismatch.hxx>
#include <Standard_ConstructionError.hxx>
//=======================================================================
//function : GetID
//purpose :
//=======================================================================
const Standard_GUID& GEOMImpl_ShapeDriver::GetID()
{
static Standard_GUID aShapeDriver("FF1BBB54-5D14-4df2-980B-3A668264EA16");
return aShapeDriver;
}
//=======================================================================
//function : GEOMImpl_ShapeDriver
//purpose :
//=======================================================================
GEOMImpl_ShapeDriver::GEOMImpl_ShapeDriver()
{
}
//=======================================================================
//function : Execute
//purpose :
//=======================================================================
Standard_Integer GEOMImpl_ShapeDriver::Execute(TFunction_Logbook& log) const
{
if (Label().IsNull()) return 0;
Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
GEOMImpl_IShapes aCI (aFunction);
Standard_Integer aType = aFunction->GetType();
TopoDS_Shape aShape;
BRep_Builder B;
if (aType == WIRE_EDGES) {
Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
unsigned int ind, nbshapes = aShapes->Length();
// add edges
BRepBuilderAPI_MakeWire MW;
for (ind = 1; ind <= nbshapes; ind++) {
Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
TopoDS_Shape aShape_i = aRefShape->GetValue();
if (aShape_i.IsNull()) {
Standard_NullObject::Raise("Shape for wire construction is null");
}
if (aShape_i.ShapeType() == TopAbs_EDGE)
MW.Add(TopoDS::Edge(aShape_i));
else if (aShape_i.ShapeType() == TopAbs_WIRE)
MW.Add(TopoDS::Wire(aShape_i));
else
Standard_TypeMismatch::Raise
("Shape for wire construction is neither an edge nor a wire");
}
if (!MW.IsDone()) {
Standard_ConstructionError::Raise("Wire construction failed");
}
aShape = MW;
} else if (aType == FACE_WIRE) {
Handle(GEOM_Function) aRefBase = aCI.GetBase();
TopoDS_Shape aShapeBase = aRefBase->GetValue();
if (aShapeBase.IsNull() || aShapeBase.ShapeType() != TopAbs_WIRE) {
Standard_NullObject::Raise
("Shape for face construction is null or not a wire");
}
TopoDS_Wire W = TopoDS::Wire(aShapeBase);
BRepBuilderAPI_MakeFace MF (W, aCI.GetIsPlanar());
if (!MF.IsDone()) {
Standard_ConstructionError::Raise("Face construction failed");
}
aShape = MF.Shape();
} else if (aType == FACE_WIRES) {
Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
// first wire
Handle(GEOM_Function) aRefWire = Handle(GEOM_Function)::DownCast(aShapes->Value(1));
TopoDS_Shape aWire = aRefWire->GetValue();
if (aWire.IsNull() || aWire.ShapeType() != TopAbs_WIRE) {
Standard_NullObject::Raise("Shape for face construction is null or not a wire");
}
TopoDS_Wire W = TopoDS::Wire(aWire);
// basic face
BRepBuilderAPI_MakeFace MF (W, aCI.GetIsPlanar());
if (!MF.IsDone()) {
Standard_ConstructionError::Raise("Face construction failed");
}
TopoDS_Shape FFace = MF.Shape();
if (!FFace.IsNull()) {
unsigned int ind, nbshapes = aShapes->Length();
if (nbshapes == 1) {
aShape = FFace;
} else if (nbshapes >= 2) {
TopoDS_Compound C;
BRep_Builder aBuilder;
aBuilder.MakeCompound(C);
BRepAlgo_FaceRestrictor FR;
TopAbs_Orientation OriF = FFace.Orientation();
TopoDS_Shape aLocalS = FFace.Oriented(TopAbs_FORWARD);
FR.Init(TopoDS::Face(aLocalS), Standard_False, Standard_True);
for (ind = 1; ind <= nbshapes; ind++) {
Handle(GEOM_Function) aRefWire_i =
Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
TopoDS_Shape aWire_i = aRefWire_i->GetValue();
if (aWire_i.IsNull() || aWire_i.ShapeType() != TopAbs_WIRE) {
Standard_NullObject::Raise("Shape for face construction is null or not a wire");
}
FR.Add(TopoDS::Wire(aWire_i));
}
FR.Perform();
if (FR.IsDone()) {
int k = 0;
TopoDS_Shape aFace;
for (; FR.More(); FR.Next()) {
aFace = FR.Current().Oriented(OriF);
aBuilder.Add(C, aFace);
k++;
}
if (k == 1) {
aShape = aFace;
} else {
aShape = C;
}
}
}
}
} else if (aType == SHELL_FACES) {
Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
unsigned int ind, nbshapes = aShapes->Length();
// add faces
BRepAlgo_Sewing aSewing(Precision::Confusion()*10.0);
for (ind = 1; ind <= nbshapes; ind++) {
Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
TopoDS_Shape aShape_i = aRefShape->GetValue();
if (aShape_i.IsNull()) {
Standard_NullObject::Raise("Face for shell construction is null");
}
aSewing.Add(aShape_i);
}
aSewing.Perform();
TopExp_Explorer exp (aSewing.SewedShape(), TopAbs_SHELL);
Standard_Integer ish = 0;
for (; exp.More(); exp.Next()) {
aShape = exp.Current();
ish++;
}
if (ish != 1)
aShape = aSewing.SewedShape();
} else if (aType == SOLID_SHELL) {
Handle(GEOM_Function) aRefShell = aCI.GetBase();
TopoDS_Shape aShapeShell = aRefShell->GetValue();
if (aShapeShell.IsNull() || aShapeShell.ShapeType() != TopAbs_SHELL) {
Standard_NullObject::Raise("Shape for solid construction is null or not a shell");
}
BRepCheck_Shell chkShell(TopoDS::Shell(aShapeShell));
if(chkShell.Closed() == BRepCheck_NotClosed) return 0;
TopoDS_Solid Sol;
B.MakeSolid(Sol);
B.Add(Sol, aShapeShell);
BRepClass3d_SolidClassifier SC (Sol);
SC.PerformInfinitePoint(Precision::Confusion());
if (SC.State() == TopAbs_IN) {
B.MakeSolid(Sol);
B.Add(Sol, aShapeShell.Reversed());
}
aShape = Sol;
} else if (aType == SOLID_SHELLS) {
Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
unsigned int ind, nbshapes = aShapes->Length();
Standard_Integer ish = 0;
TopoDS_Solid Sol;
B.MakeSolid(Sol);
// add shapes
for (ind = 1; ind <= nbshapes; ind++) {
Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
TopoDS_Shape aShapeShell = aRefShape->GetValue();
if (aShapeShell.IsNull()) {
Standard_NullObject::Raise("Shell for solid construction is null");
}
if (aShapeShell.ShapeType() == TopAbs_SHELL) {
B.Add(Sol, aShapeShell);
ish++;
}
}
if ( ish == 0 ) return 0;
BRepClass3d_SolidClassifier SC (Sol);
SC.PerformInfinitePoint(Precision::Confusion());
switch (SC.State()) {
case TopAbs_IN:
aShape = Sol.Reversed(); break;
case TopAbs_OUT:
aShape = Sol; break;
default: // not closed shell?
return 0;
}
} else if (aType == COMPOUND_SHAPES) {
Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
unsigned int ind, nbshapes = aShapes->Length();
// add shapes
TopoDS_Compound C;
B.MakeCompound(C);
for (ind = 1; ind <= nbshapes; ind++) {
Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
TopoDS_Shape aShape_i = aRefShape->GetValue();
if (aShape_i.IsNull()) {
Standard_NullObject::Raise("Shape for compound construction is null");
}
B.Add(C, aShape_i);
}
aShape = C;
} else if (aType == REVERSE_ORIENTATION) {
Handle(GEOM_Function) aRefShape = aCI.GetBase();
TopoDS_Shape aShape_i = aRefShape->GetValue();
if (aShape_i.IsNull()) {
Standard_NullObject::Raise("Shape for reverse is null");
}
BRepBuilderAPI_Copy Copy(aShape_i);
if( Copy.IsDone() ) {
TopoDS_Shape tds = Copy.Shape();
if( tds.IsNull() ) {
Standard_ConstructionError::Raise("Orientation aborted : Can not reverse the shape");
}
if( tds.Orientation() == TopAbs_FORWARD)
tds.Orientation(TopAbs_REVERSED) ;
else
tds.Orientation(TopAbs_FORWARD) ;
aShape = tds;
}
}
if (aShape.IsNull()) return 0;
// Check shape validity
BRepCheck_Analyzer ana (aShape, false);
if (!ana.IsValid()) {
Standard_ConstructionError::Raise("Algorithm have produced an invalid shape result");
}
aFunction->SetValue(aShape);
log.SetTouched(Label());
return 1;
}
//=======================================================================
//function : GEOMImpl_ShapeDriver_Type_
//purpose :
//=======================================================================
Standard_EXPORT Handle_Standard_Type& GEOMImpl_ShapeDriver_Type_()
{
static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);
if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);
static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);
if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);
static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);
if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);
static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};
static Handle_Standard_Type _aType = new Standard_Type("GEOMImpl_ShapeDriver",
sizeof(GEOMImpl_ShapeDriver),
1,
(Standard_Address)_Ancestors,
(Standard_Address)NULL);
return _aType;
}
//=======================================================================
//function : DownCast
//purpose :
//=======================================================================
const Handle(GEOMImpl_ShapeDriver) Handle(GEOMImpl_ShapeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)
{
Handle(GEOMImpl_ShapeDriver) _anOtherObject;
if (!AnObject.IsNull()) {
if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_ShapeDriver))) {
_anOtherObject = Handle(GEOMImpl_ShapeDriver)((Handle(GEOMImpl_ShapeDriver)&)AnObject);
}
}
return _anOtherObject ;
}
<|endoftext|> |
<commit_before><commit_msg>Sketcher: Ellipse trim, handle multiple intersection<commit_after><|endoftext|> |
<commit_before>/*
* NotebookAlternateEngines.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRmdNotebook.hpp"
#include "SessionExecuteChunkOperation.hpp"
#include "NotebookCache.hpp"
#include "NotebookAlternateEngines.hpp"
#include <boost/algorithm/string.hpp>
#include <core/StringUtils.hpp>
#include <core/Algorithm.hpp>
#include <core/Exec.hpp>
#include <core/json/JsonRpc.hpp>
#include <r/RExec.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
namespace {
class ChunkExecCompletedScope : boost::noncopyable
{
public:
ChunkExecCompletedScope(const std::string& docId,
const std::string& chunkId)
: docId_(docId), chunkId_(chunkId)
{
}
~ChunkExecCompletedScope()
{
events().onChunkExecCompleted(
docId_,
chunkId_,
notebookCtxId());
}
private:
std::string docId_;
std::string chunkId_;
};
Error prepareCacheConsoleOutputFile(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
FilePath* pChunkOutputFile)
{
// forward declare error
Error error;
// prepare chunk directory
FilePath cachePath = notebook::chunkOutputPath(
docId,
chunkId,
notebook::ContextExact);
error = cachePath.resetDirectory();
if (error)
return error;
// prepare cache console output file
*pChunkOutputFile =
notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputText);
return Success();
}
void chunkConsoleOutputHandler(module_context::ConsoleOutputType type,
const std::string& output,
const FilePath& targetPath)
{
using namespace module_context;
Error error = appendConsoleOutput(
type == ConsoleOutputNormal ? kChunkConsoleOutput : kChunkConsoleError,
output,
targetPath);
if (error)
LOG_ERROR(error);
}
void reportChunkExecutionError(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const std::string& message,
const FilePath& targetPath)
{
// emit chunk error
chunkConsoleOutputHandler(
module_context::ConsoleOutputError,
message,
targetPath);
// forward failure to chunk
enqueueChunkOutput(
docId,
chunkId,
nbCtxId,
0, // no ordinal needed
ChunkOutputText,
targetPath);
}
Error executeRcppEngineChunk(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const std::string& code,
const std::map<std::string, std::string>& options)
{
// forward declare error
Error error;
// always ensure we emit a 'execution complete' event on exit
ChunkExecCompletedScope execScope(docId, chunkId);
// prepare cache output file (use tempfile on failure)
FilePath targetPath = module_context::tempFile("rcpp-cache", "");
error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath);
if (error)
LOG_ERROR(error);
// capture console output, error
boost::signals::scoped_connection consoleHandler =
module_context::events().onConsoleOutput.connect(
boost::bind(chunkConsoleOutputHandler,
_1,
_2,
targetPath));
// call Rcpp::sourceCpp on code
std::string escaped = boost::regex_replace(
code,
boost::regex("(\\\\|\")"),
"\\\\$1");
std::string execCode =
"Rcpp::sourceCpp(code = \"" + escaped + "\")";
// write input code to cache
error = appendConsoleOutput(
kChunkConsoleInput,
code,
targetPath);
if (error)
LOG_ERROR(error);
// execute code (output captured on success; on failure we
// explicitly forward the error message returned)
error = r::exec::executeString(execCode);
if (error)
{
chunkConsoleOutputHandler(module_context::ConsoleOutputError,
r::endUserErrorMessage(error),
targetPath);
}
// forward success / failure to chunk
enqueueChunkOutput(
docId,
chunkId,
nbCtxId,
0, // no ordinal needed
ChunkOutputText,
targetPath);
return error;
}
void reportStanExecutionError(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const FilePath& targetPath)
{
std::string message =
"engine.opts$output.var must be a character string providing a "
"name for the returned `stanmodel` object";
reportChunkExecutionError(docId, chunkId, nbCtxId, message, targetPath);
}
Error executeStanEngineChunk(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const std::string& code,
const std::map<std::string, std::string>& options)
{
// forward-declare error
Error error;
// ensure we always emit an execution complete event on exit
ChunkExecCompletedScope execScope(docId, chunkId);
// prepare console output file -- use tempfile on failure
FilePath targetPath = module_context::tempFile("stan-cache-", "");
error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath);
if (error)
LOG_ERROR(error);
// capture console output, error
boost::signals::scoped_connection consoleHandler =
module_context::events().onConsoleOutput.connect(
boost::bind(chunkConsoleOutputHandler,
_1,
_2,
targetPath));
// write code to file
FilePath tempFile = module_context::tempFile("stan-", ".stan");
error = writeStringToFile(tempFile, code);
if (error)
{
reportChunkExecutionError(
docId,
chunkId,
nbCtxId,
r::endUserErrorMessage(error),
targetPath);
LOG_ERROR(error);
return Success();
}
RemoveOnExitScope removeOnExitScope(tempFile, ERROR_LOCATION);
// ensure existence of 'engine.opts' with 'output.var' parameter
// ('x' also allowed for backwards compatibility)
if (!options.count("engine.opts"))
{
reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);
return Success();
}
// evaluate engine options (so we can pass them through to stan call)
r::sexp::Protect protect;
SEXP engineOptsSEXP = R_NilValue;
error = r::exec::evaluateString(
options.at("engine.opts"),
&engineOptsSEXP,
&protect);
if (error)
{
reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);
return Success();
}
// construct call to 'stan_model'
r::exec::RFunction fStanEngine("rstan:::stan_model");
std::vector<std::string> engineOptsNames;
error = r::sexp::getNames(engineOptsSEXP, &engineOptsNames);
if (error)
{
reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);
return Success();
}
// build parameters
std::string modelName;
for (std::size_t i = 0, n = r::sexp::length(engineOptsSEXP); i < n; ++i)
{
// skip 'output.var' engine option (this is the variable we wish to assign to
// after evaluating the stan model)
if (engineOptsNames[i] == "output.var" || engineOptsNames[i] == "x")
{
modelName = r::sexp::asString(VECTOR_ELT(engineOptsSEXP, i));
continue;
}
fStanEngine.addParam(
engineOptsNames[i],
VECTOR_ELT(engineOptsSEXP, i));
}
// if no model name was set, return error message
if (modelName.empty())
{
reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);
return Success();
}
// if the 'file' option was not set, set it explicitly
if (!core::algorithm::contains(engineOptsNames, "file"))
fStanEngine.addParam("file", string_utils::utf8ToSystem(tempFile.absolutePath()));
// evaluate stan_model call
SEXP stanModelSEXP = R_NilValue;
error = fStanEngine.call(&stanModelSEXP, &protect);
if (error)
{
std::string msg = r::endUserErrorMessage(error);
reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath);
return Success();
}
// assign in global env on success
if (stanModelSEXP != R_NilValue)
{
r::exec::RFunction assign("base:::assign");
assign.addParam("x", modelName);
assign.addParam("value", stanModelSEXP);
error = assign.call();
if (error)
{
std::string msg = r::endUserErrorMessage(error);
reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath);
LOG_ERROR(error);
return Success();
}
}
// forward success / failure to chunk
enqueueChunkOutput(
docId,
chunkId,
notebookCtxId(),
0, // no ordinal needed
ChunkOutputText,
targetPath);
return Success();
}
Error executeSqlEngineChunk(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const std::string& code,
const json::Object& options)
{
Error error;
// ensure we always emit an execution complete event on exit
ChunkExecCompletedScope execScope(docId, chunkId);
// prepare console output file -- use tempfile on failure
FilePath consolePath = module_context::tempFile("data-console-", "");
error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &consolePath);
if (error)
LOG_ERROR(error);
// capture console output, error
boost::signals::scoped_connection consoleHandler =
module_context::events().onConsoleOutput.connect(
boost::bind(chunkConsoleOutputHandler,
_1,
_2,
consolePath));
FilePath parentPath = notebook::chunkOutputPath(
docId, chunkId, nbCtxId, ContextSaved);
error = parentPath.ensureDirectory();
if (error)
{
std::string message = "Failed to create SQL chunk directory";
reportChunkExecutionError(docId, chunkId, nbCtxId, message, parentPath);
return Success();
}
FilePath dataPath =
notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputData);
// check package dependencies
if (!module_context::isPackageVersionInstalled("DBI", "0.4"))
{
std::string message = "Executing SQL chunks requires version 0.4 or "
"later of the DBI package";
reportChunkExecutionError(docId, chunkId, nbCtxId, message, consolePath);
return Success();
}
// run sql and save result
error = r::exec::RFunction(
".rs.runSqlForDataCapture",
code,
string_utils::utf8ToSystem(dataPath.absolutePath()),
options).call();
if (error)
{
std::string message = "Failed to execute SQL chunk";
reportChunkExecutionError(docId, chunkId, nbCtxId, message, consolePath);
return Success();
}
if (dataPath.exists()) {
// forward success / failure to chunk
enqueueChunkOutput(
docId,
chunkId,
notebookCtxId(),
0, // no ordinal needed
ChunkOutputData,
dataPath);
}
// forward console output
enqueueChunkOutput(
docId,
chunkId,
notebookCtxId(),
0, // no ordinal needed
ChunkOutputText,
consolePath);
return Success();
}
Error interruptEngineChunk(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
std::string docId, chunkId;
Error error = json::readParams(request.params,
&docId,
&chunkId);
if (error)
{
LOG_ERROR(error);
return error;
}
interruptChunk(docId, chunkId);
return Success();
}
} // anonymous namespace
Error executeAlternateEngineChunk(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const std::string& engine,
const std::string& code,
const json::Object& jsonChunkOptions)
{
// read json chunk options
std::map<std::string, std::string> options;
for (json::Object::const_iterator it = jsonChunkOptions.begin();
it != jsonChunkOptions.end();
++it)
{
if (it->second.type() == json::StringType)
options[it->first] = it->second.get_str();
}
// handle some engines with their own custom routines
if (engine == "Rcpp")
return executeRcppEngineChunk(docId, chunkId, nbCtxId, code, options);
else if (engine == "stan")
return executeStanEngineChunk(docId, chunkId, nbCtxId, code, options);
else if (engine == "sql")
return executeSqlEngineChunk(docId, chunkId, nbCtxId, code, jsonChunkOptions);
runChunk(docId, chunkId, nbCtxId, engine, code, options);
return Success();
}
Error initAlternateEngines()
{
using namespace module_context;
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerRpcMethod, "interrupt_chunk", interruptEngineChunk));
return initBlock.execute();
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>respect use of 'output.var' in chunk header<commit_after>/*
* NotebookAlternateEngines.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRmdNotebook.hpp"
#include "SessionExecuteChunkOperation.hpp"
#include "NotebookCache.hpp"
#include "NotebookAlternateEngines.hpp"
#include <boost/algorithm/string.hpp>
#include <core/StringUtils.hpp>
#include <core/Algorithm.hpp>
#include <core/Exec.hpp>
#include <core/json/JsonRpc.hpp>
#include <r/RExec.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
namespace {
class ChunkExecCompletedScope : boost::noncopyable
{
public:
ChunkExecCompletedScope(const std::string& docId,
const std::string& chunkId)
: docId_(docId), chunkId_(chunkId)
{
}
~ChunkExecCompletedScope()
{
events().onChunkExecCompleted(
docId_,
chunkId_,
notebookCtxId());
}
private:
std::string docId_;
std::string chunkId_;
};
Error prepareCacheConsoleOutputFile(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
FilePath* pChunkOutputFile)
{
// forward declare error
Error error;
// prepare chunk directory
FilePath cachePath = notebook::chunkOutputPath(
docId,
chunkId,
notebook::ContextExact);
error = cachePath.resetDirectory();
if (error)
return error;
// prepare cache console output file
*pChunkOutputFile =
notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputText);
return Success();
}
void chunkConsoleOutputHandler(module_context::ConsoleOutputType type,
const std::string& output,
const FilePath& targetPath)
{
using namespace module_context;
Error error = appendConsoleOutput(
type == ConsoleOutputNormal ? kChunkConsoleOutput : kChunkConsoleError,
output,
targetPath);
if (error)
LOG_ERROR(error);
}
void reportChunkExecutionError(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const std::string& message,
const FilePath& targetPath)
{
// emit chunk error
chunkConsoleOutputHandler(
module_context::ConsoleOutputError,
message,
targetPath);
// forward failure to chunk
enqueueChunkOutput(
docId,
chunkId,
nbCtxId,
0, // no ordinal needed
ChunkOutputText,
targetPath);
}
Error executeRcppEngineChunk(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const std::string& code,
const std::map<std::string, std::string>& options)
{
// forward declare error
Error error;
// always ensure we emit a 'execution complete' event on exit
ChunkExecCompletedScope execScope(docId, chunkId);
// prepare cache output file (use tempfile on failure)
FilePath targetPath = module_context::tempFile("rcpp-cache", "");
error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath);
if (error)
LOG_ERROR(error);
// capture console output, error
boost::signals::scoped_connection consoleHandler =
module_context::events().onConsoleOutput.connect(
boost::bind(chunkConsoleOutputHandler,
_1,
_2,
targetPath));
// call Rcpp::sourceCpp on code
std::string escaped = boost::regex_replace(
code,
boost::regex("(\\\\|\")"),
"\\\\$1");
std::string execCode =
"Rcpp::sourceCpp(code = \"" + escaped + "\")";
// write input code to cache
error = appendConsoleOutput(
kChunkConsoleInput,
code,
targetPath);
if (error)
LOG_ERROR(error);
// execute code (output captured on success; on failure we
// explicitly forward the error message returned)
error = r::exec::executeString(execCode);
if (error)
{
chunkConsoleOutputHandler(module_context::ConsoleOutputError,
r::endUserErrorMessage(error),
targetPath);
}
// forward success / failure to chunk
enqueueChunkOutput(
docId,
chunkId,
nbCtxId,
0, // no ordinal needed
ChunkOutputText,
targetPath);
return error;
}
void reportStanExecutionError(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const FilePath& targetPath)
{
std::string message =
"engine.opts$output.var must be a character string providing a "
"name for the returned `stanmodel` object";
reportChunkExecutionError(docId, chunkId, nbCtxId, message, targetPath);
}
Error executeStanEngineChunk(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const std::string& code,
const std::map<std::string, std::string>& options)
{
// forward-declare error
Error error;
// ensure we always emit an execution complete event on exit
ChunkExecCompletedScope execScope(docId, chunkId);
// prepare console output file -- use tempfile on failure
FilePath targetPath = module_context::tempFile("stan-cache-", "");
error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath);
if (error)
LOG_ERROR(error);
// capture console output, error
boost::signals::scoped_connection consoleHandler =
module_context::events().onConsoleOutput.connect(
boost::bind(chunkConsoleOutputHandler,
_1,
_2,
targetPath));
// write code to file
FilePath tempFile = module_context::tempFile("stan-", ".stan");
error = writeStringToFile(tempFile, code + "\n");
if (error)
{
reportChunkExecutionError(
docId,
chunkId,
nbCtxId,
r::endUserErrorMessage(error),
targetPath);
LOG_ERROR(error);
return Success();
}
RemoveOnExitScope removeOnExitScope(tempFile, ERROR_LOCATION);
// evaluate engine options (so we can pass them through to stan call)
r::sexp::Protect protect;
SEXP engineOptsSEXP = R_NilValue;
if (options.count("engine.opts"))
{
error = r::exec::evaluateString(
options.at("engine.opts"),
&engineOptsSEXP,
&protect);
if (error)
{
reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);
return Success();
}
}
else
{
// if no engine.opts available, just use a plain empty list
engineOptsSEXP = r::sexp::createList(std::vector<std::string>(), &protect);
}
// construct call to 'stan_model'
r::exec::RFunction fStanEngine("rstan:::stan_model");
std::vector<std::string> engineOptsNames;
error = r::sexp::getNames(engineOptsSEXP, &engineOptsNames);
if (error)
{
reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);
return Success();
}
// build parameters
std::string modelName;
for (std::size_t i = 0, n = r::sexp::length(engineOptsSEXP); i < n; ++i)
{
// skip 'output.var' engine option (this is the variable we wish to assign to
// after evaluating the stan model)
if (engineOptsNames[i] == "output.var" || engineOptsNames[i] == "x")
{
modelName = r::sexp::asString(VECTOR_ELT(engineOptsSEXP, i));
continue;
}
fStanEngine.addParam(
engineOptsNames[i],
VECTOR_ELT(engineOptsSEXP, i));
}
// if 'output.var' was provided as part of the chunk parameters
// (not as part of 'engine.opts') then use that here
if (options.count("output.var"))
modelName = options.at("output.var");
// if no model name was set, return error message
if (modelName.empty())
{
reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);
return Success();
}
// if the 'file' option was not set, set it explicitly
if (!core::algorithm::contains(engineOptsNames, "file"))
fStanEngine.addParam("file", string_utils::utf8ToSystem(tempFile.absolutePath()));
// evaluate stan_model call
SEXP stanModelSEXP = R_NilValue;
error = fStanEngine.call(&stanModelSEXP, &protect);
if (error)
{
std::string msg = r::endUserErrorMessage(error);
reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath);
return Success();
}
// assign in global env on success
if (stanModelSEXP != R_NilValue)
{
r::exec::RFunction assign("base:::assign");
assign.addParam("x", modelName);
assign.addParam("value", stanModelSEXP);
error = assign.call();
if (error)
{
std::string msg = r::endUserErrorMessage(error);
reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath);
LOG_ERROR(error);
return Success();
}
}
// forward success / failure to chunk
enqueueChunkOutput(
docId,
chunkId,
notebookCtxId(),
0, // no ordinal needed
ChunkOutputText,
targetPath);
return Success();
}
Error executeSqlEngineChunk(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const std::string& code,
const json::Object& options)
{
Error error;
// ensure we always emit an execution complete event on exit
ChunkExecCompletedScope execScope(docId, chunkId);
// prepare console output file -- use tempfile on failure
FilePath consolePath = module_context::tempFile("data-console-", "");
error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &consolePath);
if (error)
LOG_ERROR(error);
// capture console output, error
boost::signals::scoped_connection consoleHandler =
module_context::events().onConsoleOutput.connect(
boost::bind(chunkConsoleOutputHandler,
_1,
_2,
consolePath));
FilePath parentPath = notebook::chunkOutputPath(
docId, chunkId, nbCtxId, ContextSaved);
error = parentPath.ensureDirectory();
if (error)
{
std::string message = "Failed to create SQL chunk directory";
reportChunkExecutionError(docId, chunkId, nbCtxId, message, parentPath);
return Success();
}
FilePath dataPath =
notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputData);
// check package dependencies
if (!module_context::isPackageVersionInstalled("DBI", "0.4"))
{
std::string message = "Executing SQL chunks requires version 0.4 or "
"later of the DBI package";
reportChunkExecutionError(docId, chunkId, nbCtxId, message, consolePath);
return Success();
}
// run sql and save result
error = r::exec::RFunction(
".rs.runSqlForDataCapture",
code,
string_utils::utf8ToSystem(dataPath.absolutePath()),
options).call();
if (error)
{
std::string message = "Failed to execute SQL chunk";
reportChunkExecutionError(docId, chunkId, nbCtxId, message, consolePath);
return Success();
}
if (dataPath.exists()) {
// forward success / failure to chunk
enqueueChunkOutput(
docId,
chunkId,
notebookCtxId(),
0, // no ordinal needed
ChunkOutputData,
dataPath);
}
// forward console output
enqueueChunkOutput(
docId,
chunkId,
notebookCtxId(),
0, // no ordinal needed
ChunkOutputText,
consolePath);
return Success();
}
Error interruptEngineChunk(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
std::string docId, chunkId;
Error error = json::readParams(request.params,
&docId,
&chunkId);
if (error)
{
LOG_ERROR(error);
return error;
}
interruptChunk(docId, chunkId);
return Success();
}
} // anonymous namespace
Error executeAlternateEngineChunk(const std::string& docId,
const std::string& chunkId,
const std::string& nbCtxId,
const std::string& engine,
const std::string& code,
const json::Object& jsonChunkOptions)
{
// read json chunk options
std::map<std::string, std::string> options;
for (json::Object::const_iterator it = jsonChunkOptions.begin();
it != jsonChunkOptions.end();
++it)
{
if (it->second.type() == json::StringType)
options[it->first] = it->second.get_str();
}
// handle some engines with their own custom routines
if (engine == "Rcpp")
return executeRcppEngineChunk(docId, chunkId, nbCtxId, code, options);
else if (engine == "stan")
return executeStanEngineChunk(docId, chunkId, nbCtxId, code, options);
else if (engine == "sql")
return executeSqlEngineChunk(docId, chunkId, nbCtxId, code, jsonChunkOptions);
runChunk(docId, chunkId, nbCtxId, engine, code, options);
return Success();
}
Error initAlternateEngines()
{
using namespace module_context;
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerRpcMethod, "interrupt_chunk", interruptEngineChunk));
return initBlock.execute();
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <dynamic_reconfigure/server.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
#include <image_transport/image_transport.h>
#include <kinect_tomato_searcher/SearchConfig.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/video.hpp>
class ShowImage {
public:
ShowImage()
: m_gamma(2048),
RGB_WINDOW_NAME {"RGB image"},
DEPTH_WINDOW_NAME {"Depth image"},
BINARY_WINDOW_NAME {"Binary image"}
{
for(int i = 0; i < 2048; i++) {
float v = i / 2048.0;
v = std::pow(v, 3) * 6;
m_gamma[i] = v * 6 * 256;
}
cv::namedWindow(RGB_WINDOW_NAME);
cv::namedWindow(DEPTH_WINDOW_NAME);
cv::namedWindow(BINARY_WINDOW_NAME);
}
~ShowImage() {
cv::destroyWindow(RGB_WINDOW_NAME);
cv::destroyWindow(DEPTH_WINDOW_NAME);
cv::destroyWindow(BINARY_WINDOW_NAME);
}
void showRGB(const cv::Mat& rgb) {
imshow(RGB_WINDOW_NAME, rgb);
}
void showBinary(const cv::Mat& binary) {
imshow(BINARY_WINDOW_NAME, binary);
}
void showDepth(const cv::Mat& depth) {
cv::Mat buf = cv::Mat::zeros(depth.size(), CV_16UC1);
cv::Mat output = cv::Mat::zeros(depth.size(), CV_8UC3);
cv::normalize(depth, buf, 0, 2013, cv::NORM_MINMAX);
for (int i = 0; i < depth.rows * depth.cols; i++) {
int y = (int)(i / depth.cols);
int x = (int)(i % depth.cols);
int pval = m_gamma[buf.at<uint16_t>(i)];
int lb = pval & 0xff;
switch(pval >> 8) {
case 0:
output.at<cv::Vec3b>(y,x)[2] = 255;
output.at<cv::Vec3b>(y,x)[1] = 255-lb;
output.at<cv::Vec3b>(y,x)[0] = 255-lb;
break;
case 1:
output.at<cv::Vec3b>(y,x)[2] = 255;
output.at<cv::Vec3b>(y,x)[1] = lb;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
case 2:
output.at<cv::Vec3b>(y,x)[2] = 255-lb;
output.at<cv::Vec3b>(y,x)[1] = 255;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
case 3:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 255;
output.at<cv::Vec3b>(y,x)[0] = lb;
break;
case 4:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 255-lb;
output.at<cv::Vec3b>(y,x)[0] = 255;
break;
case 5:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 0;
output.at<cv::Vec3b>(y,x)[0] = 255-lb;
break;
default:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 0;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
}
}
imshow(DEPTH_WINDOW_NAME, output);
}
private:
std::vector<uint16_t> m_gamma;
const std::string RGB_WINDOW_NAME;
const std::string DEPTH_WINDOW_NAME;
const std::string BINARY_WINDOW_NAME;
};
class SearchTomato
{
public:
SearchTomato()
: tomato_contours {},
siObj {},
server {},
f(std::bind(&dynamic_reconfigure_callback, std::placeholders::_1, std::placeholders::_2))
{
server.setCallback(f);
}
void update(const cv::Mat& capture_rgb) {
siObj.showRGB(capture_rgb);
cv::Mat binary_mat = cv::Mat::zeros(capture_rgb.size(), CV_8UC1);
imageProsessing(capture_rgb, binary_mat);
siObj.showBinary(binary_mat);
searchTomatoContours(binary_mat, tomato_contours);
}
bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::Point& tomato_point) {
siObj.showDepth(capture_depth);
cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);
cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);
cv::drawContours(mask, tomato_contours, -1, cv::Scalar(255), CV_FILLED, 8);
siObj.showBinary(mask);
capture_depth.copyTo(maskedDepth, mask);
return findClosePoint(maskedDepth, tomato_point);
}
bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::PoseArray& tomato_poses) {
tomato_poses.poses.clear();
siObj.showDepth(capture_depth);
cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);
cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);
for (std::size_t i {0}; i < tomato_contours.size(); ++i) {
cv::drawContours(mask, tomato_contours, i, cv::Scalar(255), CV_FILLED, 8);
siObj.showBinary(mask);
capture_depth.copyTo(maskedDepth, mask);
findClosePoint(maskedDepth, tomato_poses);
}
return tomato_poses.poses.empty() ? false : true;
}
private:
static void dynamic_reconfigure_callback(kinect_tomato_searcher::SearchConfig& config, uint32_t level)
{
h_min_ = config.h_min;
h_max_ = config.h_max;
s_min_ = config.s_min;
s_max_ = config.s_max;
v_min_ = config.v_min;
v_max_ = config.v_max;
}
void imageProsessing(const cv::Mat& rgb, cv::Mat& binary) {
cv::Mat blur, hsv;
cv::GaussianBlur(rgb, blur, cv::Size(5, 5), 4.0, 4.0);
cv::cvtColor(blur, hsv, CV_BGR2HSV);
redFilter(hsv, binary);
cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);
cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 4);
cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 1);
}
void searchTomatoContours(const cv::Mat& binary, std::vector<std::vector<cv::Point> >& tomato_contours) {
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Point> contour;
cv::Rect bounding_box;
float ratio_balance;
cv::findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
tomato_contours.clear();
while (!contours.empty()) {
contour = contours.back();
contours.pop_back();
bounding_box = cv::boundingRect(contour);
ratio_balance = (float)bounding_box.width / (float)bounding_box.height;
if (ratio_balance > 1.0f) ratio_balance = 1.0f / ratio_balance;
// delete mismach. that is smaller or spier or empty
if (bounding_box.area() >= 400 && bounding_box.area() < cv::contourArea(contour)*2 && ratio_balance > 0.4f)
tomato_contours.push_back(contour);
}
}
void redFilter(const cv::Mat& hsv, cv::Mat& binary) {
int a, x, y;
for(y = 0; y < hsv.rows; y++) {
for(x = 0; x < hsv.cols; x++) {
a = hsv.step*y+(x*3);
if((hsv.data[a] <= h_min_ || hsv.data[a] >= h_max_) &&
(hsv.data[a+1] >= s_min_ || hsv.data[a+1] <= s_max_) &&
(hsv.data[a+2] >= v_min_ || hsv.data[a+2] <= v_max_))
binary.at<unsigned char>(y,x) = 255;
else
binary.at<unsigned char>(y,x) = 0;
}
}
}
bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::Point& tomato_point) {
uint16_t depth;
constexpr uint16_t OVER_RANGE = 3000;
uint16_t close_depth = OVER_RANGE;
for (int y = 0; y < maskedDepth.rows; y++) {
const uint16_t* line_point = maskedDepth.ptr<uint16_t>(y);
for (int x = 0; x < maskedDepth.cols; x++) {
depth = line_point[x];
if (512 < depth && depth < close_depth) {
tomato_point.x = depth; // for ros coordinate system
tomato_point.y = x - maskedDepth.cols / 2; // for ros coordinate system
tomato_point.z = -(y - maskedDepth.rows / 2); // for ros coordinate system
close_depth = depth;
}
}
}
return (close_depth != OVER_RANGE ? true : false);
}
bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::PoseArray& tomato_poses) {
geometry_msgs::Point tomato_point {};
if (findClosePoint(maskedDepth, tomato_point)) {
geometry_msgs::Pose tomato_pose {};
tomato_pose.position = tomato_point;
tomato_pose.orientation.w = 1.0;
tomato_poses.poses.push_back(tomato_pose);
return true;
}
return false;
}
static uint16_t h_min_;
static uint16_t h_max_;
static uint16_t s_min_;
static uint16_t s_max_;
static uint16_t v_min_;
static uint16_t v_max_;
std::vector<std::vector<cv::Point> > tomato_contours;
ShowImage siObj;
dynamic_reconfigure::Server<kinect_tomato_searcher::SearchConfig> server;
dynamic_reconfigure::Server<kinect_tomato_searcher::SearchConfig>::CallbackType f;
};
uint16_t SearchTomato::h_min_;
uint16_t SearchTomato::h_max_;
uint16_t SearchTomato::s_min_;
uint16_t SearchTomato::s_max_;
uint16_t SearchTomato::v_min_;
uint16_t SearchTomato::v_max_;
class ImageConverter {
private:
ros::NodeHandle nh;
ros::NodeHandle tomapo_nh;
ros::Publisher poses_pub;
geometry_msgs::PoseArray pub_msg;
image_transport::ImageTransport it;
image_transport::Subscriber rgb_sub;
image_transport::Subscriber depth_sub;
cv_bridge::CvImageConstPtr rgb_ptr;
cv_bridge::CvImageConstPtr depth_ptr;
SearchTomato stObj;
const std::size_t height_;
const double angle_x_per_piccell_;
const double angle_y_per_piccell_;
static constexpr double PI {3.141592653589793};
public:
ImageConverter(const std::size_t width, const std::size_t height, const double angle_of_view_x, const double angle_of_view_y)
: nh {},
tomapo_nh {nh, "tomato_point"},
poses_pub {tomapo_nh.advertise<geometry_msgs::PoseArray>("array", 1)},
it {nh},
rgb_sub {it.subscribe("color", 1, &ImageConverter::rgbCb, this)},
depth_sub {it.subscribe("depth", 1, &ImageConverter::depthCb, this)},
stObj {},
height_ {height},
angle_x_per_piccell_ {(angle_of_view_x * PI / 180.0) / width},
angle_y_per_piccell_ {(angle_of_view_y * PI / 180.0) / height}
{
pub_msg.header.frame_id = "kinect";
}
/**
* search tomato function.
* get rgb image, and search tomato.
* will tomato_point have data.
*
* @author Yusuke Doi
*/
void rgbCb(const sensor_msgs::ImageConstPtr& msg) {
// get rgb image on kinect
try {
rgb_ptr = cv_bridge::toCvShare(msg, "bgr8");
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception by rgb: %s", e.what());
}
stObj.update(rgb_ptr->image);
cv::waitKey(100);
}
void depthCb(const sensor_msgs::ImageConstPtr& msg) {
try {
depth_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_16UC1);
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception by depth: %s", e.what());
}
if (stObj.searchTomato(depth_ptr->image, pub_msg)) {
pub_msg.header.stamp = ros::Time::now();
for (auto& tomato_pose : pub_msg.poses) {
tomato_pose.position.y = tomato_pose.position.x * tan(angle_x_per_piccell_ * tomato_pose.position.y) / 1000.0; // convert to m
tomato_pose.position.z = tomato_pose.position.x * tan(angle_y_per_piccell_ * tomato_pose.position.z) / 1000.0; // convert to m
tomato_pose.position.x = tomato_pose.position.x / 1000.0; // convert to m
}
poses_pub.publish(pub_msg);
}
cv::waitKey(100);
}
};
int main(int argc, char** argv) {
ros::init(argc, argv, "kinect_tomato_searcher_node");
ImageConverter ic {512, 424, 70, 60};
ros::spin();
return 0;
}
<commit_msg>Fix bug of boolean<commit_after>#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <dynamic_reconfigure/server.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
#include <image_transport/image_transport.h>
#include <kinect_tomato_searcher/SearchConfig.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/video.hpp>
class ShowImage {
public:
ShowImage()
: m_gamma(2048),
RGB_WINDOW_NAME {"RGB image"},
DEPTH_WINDOW_NAME {"Depth image"},
BINARY_WINDOW_NAME {"Binary image"}
{
for(int i = 0; i < 2048; i++) {
float v = i / 2048.0;
v = std::pow(v, 3) * 6;
m_gamma[i] = v * 6 * 256;
}
cv::namedWindow(RGB_WINDOW_NAME);
cv::namedWindow(DEPTH_WINDOW_NAME);
cv::namedWindow(BINARY_WINDOW_NAME);
}
~ShowImage() {
cv::destroyWindow(RGB_WINDOW_NAME);
cv::destroyWindow(DEPTH_WINDOW_NAME);
cv::destroyWindow(BINARY_WINDOW_NAME);
}
void showRGB(const cv::Mat& rgb) {
imshow(RGB_WINDOW_NAME, rgb);
}
void showBinary(const cv::Mat& binary) {
imshow(BINARY_WINDOW_NAME, binary);
}
void showDepth(const cv::Mat& depth) {
cv::Mat buf = cv::Mat::zeros(depth.size(), CV_16UC1);
cv::Mat output = cv::Mat::zeros(depth.size(), CV_8UC3);
cv::normalize(depth, buf, 0, 2013, cv::NORM_MINMAX);
for (int i = 0; i < depth.rows * depth.cols; i++) {
int y = (int)(i / depth.cols);
int x = (int)(i % depth.cols);
int pval = m_gamma[buf.at<uint16_t>(i)];
int lb = pval & 0xff;
switch(pval >> 8) {
case 0:
output.at<cv::Vec3b>(y,x)[2] = 255;
output.at<cv::Vec3b>(y,x)[1] = 255-lb;
output.at<cv::Vec3b>(y,x)[0] = 255-lb;
break;
case 1:
output.at<cv::Vec3b>(y,x)[2] = 255;
output.at<cv::Vec3b>(y,x)[1] = lb;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
case 2:
output.at<cv::Vec3b>(y,x)[2] = 255-lb;
output.at<cv::Vec3b>(y,x)[1] = 255;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
case 3:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 255;
output.at<cv::Vec3b>(y,x)[0] = lb;
break;
case 4:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 255-lb;
output.at<cv::Vec3b>(y,x)[0] = 255;
break;
case 5:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 0;
output.at<cv::Vec3b>(y,x)[0] = 255-lb;
break;
default:
output.at<cv::Vec3b>(y,x)[2] = 0;
output.at<cv::Vec3b>(y,x)[1] = 0;
output.at<cv::Vec3b>(y,x)[0] = 0;
break;
}
}
imshow(DEPTH_WINDOW_NAME, output);
}
private:
std::vector<uint16_t> m_gamma;
const std::string RGB_WINDOW_NAME;
const std::string DEPTH_WINDOW_NAME;
const std::string BINARY_WINDOW_NAME;
};
class SearchTomato
{
public:
SearchTomato()
: tomato_contours {},
siObj {},
server {},
f(std::bind(&dynamic_reconfigure_callback, std::placeholders::_1, std::placeholders::_2))
{
server.setCallback(f);
}
void update(const cv::Mat& capture_rgb) {
siObj.showRGB(capture_rgb);
cv::Mat binary_mat = cv::Mat::zeros(capture_rgb.size(), CV_8UC1);
imageProsessing(capture_rgb, binary_mat);
siObj.showBinary(binary_mat);
searchTomatoContours(binary_mat, tomato_contours);
}
bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::Point& tomato_point) {
siObj.showDepth(capture_depth);
cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);
cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);
cv::drawContours(mask, tomato_contours, -1, cv::Scalar(255), CV_FILLED, 8);
siObj.showBinary(mask);
capture_depth.copyTo(maskedDepth, mask);
return findClosePoint(maskedDepth, tomato_point);
}
bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::PoseArray& tomato_poses) {
tomato_poses.poses.clear();
siObj.showDepth(capture_depth);
cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);
cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);
for (std::size_t i {0}; i < tomato_contours.size(); ++i) {
cv::drawContours(mask, tomato_contours, i, cv::Scalar(255), CV_FILLED, 8);
siObj.showBinary(mask);
capture_depth.copyTo(maskedDepth, mask);
findClosePoint(maskedDepth, tomato_poses);
}
return tomato_poses.poses.empty() ? false : true;
}
private:
static void dynamic_reconfigure_callback(kinect_tomato_searcher::SearchConfig& config, uint32_t level)
{
h_min_ = config.h_min;
h_max_ = config.h_max;
s_min_ = config.s_min;
s_max_ = config.s_max;
v_min_ = config.v_min;
v_max_ = config.v_max;
}
void imageProsessing(const cv::Mat& rgb, cv::Mat& binary) {
cv::Mat blur, hsv;
cv::GaussianBlur(rgb, blur, cv::Size(5, 5), 4.0, 4.0);
cv::cvtColor(blur, hsv, CV_BGR2HSV);
redFilter(hsv, binary);
cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);
cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 4);
cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 1);
}
void searchTomatoContours(const cv::Mat& binary, std::vector<std::vector<cv::Point> >& tomato_contours) {
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Point> contour;
cv::Rect bounding_box;
float ratio_balance;
cv::findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
tomato_contours.clear();
while (!contours.empty()) {
contour = contours.back();
contours.pop_back();
bounding_box = cv::boundingRect(contour);
ratio_balance = (float)bounding_box.width / (float)bounding_box.height;
if (ratio_balance > 1.0f) ratio_balance = 1.0f / ratio_balance;
// delete mismach. that is smaller or spier or empty
if (bounding_box.area() >= 400 && bounding_box.area() < cv::contourArea(contour)*2 && ratio_balance > 0.4f)
tomato_contours.push_back(contour);
}
}
void redFilter(const cv::Mat& hsv, cv::Mat& binary) {
int a, x, y;
for(y = 0; y < hsv.rows; y++) {
for(x = 0; x < hsv.cols; x++) {
a = hsv.step*y+(x*3);
if((hsv.data[a] <= h_min_ || hsv.data[a] >= h_max_) &&
(hsv.data[a+1] >= s_min_ && hsv.data[a+1] <= s_max_) &&
(hsv.data[a+2] >= v_min_ && hsv.data[a+2] <= v_max_))
binary.at<unsigned char>(y,x) = 255;
else
binary.at<unsigned char>(y,x) = 0;
}
}
}
bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::Point& tomato_point) {
uint16_t depth;
constexpr uint16_t OVER_RANGE = 3000;
uint16_t close_depth = OVER_RANGE;
for (int y = 0; y < maskedDepth.rows; y++) {
const uint16_t* line_point = maskedDepth.ptr<uint16_t>(y);
for (int x = 0; x < maskedDepth.cols; x++) {
depth = line_point[x];
if (512 < depth && depth < close_depth) {
tomato_point.x = depth; // for ros coordinate system
tomato_point.y = x - maskedDepth.cols / 2; // for ros coordinate system
tomato_point.z = -(y - maskedDepth.rows / 2); // for ros coordinate system
close_depth = depth;
}
}
}
return (close_depth != OVER_RANGE ? true : false);
}
bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::PoseArray& tomato_poses) {
geometry_msgs::Point tomato_point {};
if (findClosePoint(maskedDepth, tomato_point)) {
geometry_msgs::Pose tomato_pose {};
tomato_pose.position = tomato_point;
tomato_pose.orientation.w = 1.0;
tomato_poses.poses.push_back(tomato_pose);
return true;
}
return false;
}
static uint16_t h_min_;
static uint16_t h_max_;
static uint16_t s_min_;
static uint16_t s_max_;
static uint16_t v_min_;
static uint16_t v_max_;
std::vector<std::vector<cv::Point> > tomato_contours;
ShowImage siObj;
dynamic_reconfigure::Server<kinect_tomato_searcher::SearchConfig> server;
dynamic_reconfigure::Server<kinect_tomato_searcher::SearchConfig>::CallbackType f;
};
uint16_t SearchTomato::h_min_;
uint16_t SearchTomato::h_max_;
uint16_t SearchTomato::s_min_;
uint16_t SearchTomato::s_max_;
uint16_t SearchTomato::v_min_;
uint16_t SearchTomato::v_max_;
class ImageConverter {
private:
ros::NodeHandle nh;
ros::NodeHandle tomapo_nh;
ros::Publisher poses_pub;
geometry_msgs::PoseArray pub_msg;
image_transport::ImageTransport it;
image_transport::Subscriber rgb_sub;
image_transport::Subscriber depth_sub;
cv_bridge::CvImageConstPtr rgb_ptr;
cv_bridge::CvImageConstPtr depth_ptr;
SearchTomato stObj;
const std::size_t height_;
const double angle_x_per_piccell_;
const double angle_y_per_piccell_;
static constexpr double PI {3.141592653589793};
public:
ImageConverter(const std::size_t width, const std::size_t height, const double angle_of_view_x, const double angle_of_view_y)
: nh {},
tomapo_nh {nh, "tomato_point"},
poses_pub {tomapo_nh.advertise<geometry_msgs::PoseArray>("array", 1)},
it {nh},
rgb_sub {it.subscribe("color", 1, &ImageConverter::rgbCb, this)},
depth_sub {it.subscribe("depth", 1, &ImageConverter::depthCb, this)},
stObj {},
height_ {height},
angle_x_per_piccell_ {(angle_of_view_x * PI / 180.0) / width},
angle_y_per_piccell_ {(angle_of_view_y * PI / 180.0) / height}
{
pub_msg.header.frame_id = "kinect";
}
/**
* search tomato function.
* get rgb image, and search tomato.
* will tomato_point have data.
*
* @author Yusuke Doi
*/
void rgbCb(const sensor_msgs::ImageConstPtr& msg) {
// get rgb image on kinect
try {
rgb_ptr = cv_bridge::toCvShare(msg, "bgr8");
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception by rgb: %s", e.what());
}
stObj.update(rgb_ptr->image);
cv::waitKey(100);
}
void depthCb(const sensor_msgs::ImageConstPtr& msg) {
try {
depth_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_16UC1);
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception by depth: %s", e.what());
}
if (stObj.searchTomato(depth_ptr->image, pub_msg)) {
pub_msg.header.stamp = ros::Time::now();
for (auto& tomato_pose : pub_msg.poses) {
tomato_pose.position.y = tomato_pose.position.x * tan(angle_x_per_piccell_ * tomato_pose.position.y) / 1000.0; // convert to m
tomato_pose.position.z = tomato_pose.position.x * tan(angle_y_per_piccell_ * tomato_pose.position.z) / 1000.0; // convert to m
tomato_pose.position.x = tomato_pose.position.x / 1000.0; // convert to m
}
poses_pub.publish(pub_msg);
}
cv::waitKey(100);
}
};
int main(int argc, char** argv) {
ros::init(argc, argv, "kinect_tomato_searcher_node");
ImageConverter ic {512, 424, 70, 60};
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>
/* ========================================
* File Name : 15.cpp
* Creation Date : 12-08-2020
* Last Modified : St 12. srpna 2020, 14:28:48
* Created By : Karel Ha <mathemage@gmail.com>
* URL : https://www.facebook.com/codingcompetitions/hacker-cup/2018/round-1/problems/A
* Points Gained (in case of online contest) :
==========================================*/
#include <bits/stdc++.h>
using namespace std;
#define REP(I,N) FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A) (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << (a) << endl;
const int CLEAN = -1;
template <typename T>
string NumberToString ( T Number ) {
ostringstream ss;
ss << Number;
return ss.str();
}
#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
vector<string> v;
stringstream ss(s);
string x;
while (getline(ss, x, c))
v.emplace_back(x);
return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
err(++it, args...);
}
int main() {
return 0;
}
<commit_msg>Read input<commit_after>
/* ========================================
* File Name : 15.cpp
* Creation Date : 12-08-2020
* Last Modified : St 12. srpna 2020, 14:36:32
* Created By : Karel Ha <mathemage@gmail.com>
* URL : https://www.facebook.com/codingcompetitions/hacker-cup/2018/round-1/problems/A
* Points Gained (in case of online contest) :
==========================================*/
#include <bits/stdc++.h>
using namespace std;
#define REP(I,N) FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A) (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << (a) << endl;
const int CLEAN = -1;
template <typename T>
string NumberToString ( T Number ) {
ostringstream ss;
ss << Number;
return ss.str();
}
#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
vector<string> v;
stringstream ss(s);
string x;
while (getline(ss, x, c))
v.emplace_back(x);
return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
err(++it, args...);
}
#define MOD 1000000007
int main() {
int T;
cin >> T;
// MSG(T);
REP(t,T) {
int N;
cin >> N;
// cout << endl; MSG(N);
vector<string> G(3);
REP(l,3) {
cin >> G[l];
// MSG(G[l]);
}
}
return 0;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <iostream>
#include <map>
#include <rtl/string.hxx>
#include "po.hxx"
// Translated style names must be unique
static void checkStyleNames(OString aLanguage)
{
std::map<OString,sal_uInt16> aLocalizedStyleNames;
std::map<OString,sal_uInt16> aLocalizedNumStyleNames;
OString aPoPath = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage + "/sw/source/ui/utlui.po";
PoIfstream aPoInput;
aPoInput.open(aPoPath);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
for(;;)
{
PoEntry aPoEntry;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry.isFuzzy() && aPoEntry.getSourceFile() == "poolfmt.src" &&
aPoEntry.getGroupId().startsWith("STR_POOLCOLL") )
{
OString aMsgStr = aPoEntry.getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedStyleNames.find(aMsgStr) == aLocalizedStyleNames.end() )
aLocalizedStyleNames[aMsgStr] = 1;
else
aLocalizedStyleNames[aMsgStr]++;
}
if( !aPoEntry.isFuzzy() && aPoEntry.getSourceFile() == "poolfmt.src" &&
aPoEntry.getGroupId().startsWith("STR_POOLNUMRULE") )
{
OString aMsgStr = aPoEntry.getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedNumStyleNames.find(aMsgStr) == aLocalizedNumStyleNames.end() )
aLocalizedNumStyleNames[aMsgStr] = 1;
else
aLocalizedNumStyleNames[aMsgStr]++;
}
}
aPoInput.close();
for( std::map<OString,sal_uInt16>::iterator it=aLocalizedStyleNames.begin(); it!=aLocalizedStyleNames.end(); ++it)
{
if( it->second > 1 )
{
std::cout << "ERROR: Style name translations must be unique in:\n" <<
aPoPath << "\nLanguage: " << aLanguage << "\nDuplicated translation is: " << it->first <<
"\nSee STR_POOLCOLL_*\n\n";
}
}
for( std::map<OString,sal_uInt16>::iterator it=aLocalizedNumStyleNames.begin(); it!=aLocalizedNumStyleNames.end(); ++it)
{
if( it->second > 1 )
{
std::cout << "ERROR: Style name translations must be unique in:\n" <<
aPoPath << "\nLanguage: " << aLanguage << "\nDuplicated translation is: " << it->first <<
"\nSee STR_POOLNUMRULE_*\n\n";
}
}
}
// Translated spreadsheet function names must be unique
static void checkFunctionNames(OString aLanguage)
{
std::map<OString,sal_uInt16> aLocalizedFunctionNames;
std::map<OString,sal_uInt16> aLocalizedCoreFunctionNames;
OString aPoPath = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/formula/source/core/resource.po";
PoIfstream aPoInput;
aPoInput.open(aPoPath);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
for(;;)
{
PoEntry aPoEntry;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_STRLIST_FUNCTION_NAMES" )
{
OString aMsgStr = aPoEntry.getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedCoreFunctionNames.find(aMsgStr) == aLocalizedCoreFunctionNames.end() )
aLocalizedCoreFunctionNames[aMsgStr] = 1;
if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() )
aLocalizedFunctionNames[aMsgStr] = 1;
else
aLocalizedFunctionNames[aMsgStr]++;
}
}
aPoInput.close();
aPoPath = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/scaddins/source/analysis.po";
aPoInput.open(aPoPath);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
for(;;)
{
PoEntry aPoEntry;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_ANALYSIS_FUNCTION_NAMES" )
{
OString aMsgStr = aPoEntry.getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )
aMsgStr += "_ADD";
if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() )
aLocalizedFunctionNames[aMsgStr] = 1;
else
aLocalizedFunctionNames[aMsgStr]++;
}
}
aPoInput.close();
aPoPath = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/scaddins/source/datefunc.po";
aPoInput.open(aPoPath);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
for(;;)
{
PoEntry aPoEntry;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_DATE_FUNCTION_NAMES" )
{
OString aMsgStr = aPoEntry.getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )
aMsgStr += "_ADD";
if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() )
aLocalizedFunctionNames[aMsgStr] = 1;
else
aLocalizedFunctionNames[aMsgStr]++;
}
}
aPoInput.close();
aPoPath = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/scaddins/source/pricing.po";
aPoInput.open(aPoPath);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
for(;;)
{
PoEntry aPoEntry;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_PRICING_FUNCTION_NAMES" )
{
OString aMsgStr = aPoEntry.getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )
aMsgStr += "_ADD";
if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() )
aLocalizedFunctionNames[aMsgStr] = 1;
else
aLocalizedFunctionNames[aMsgStr]++;
}
}
aPoInput.close();
for( std::map<OString,sal_uInt16>::iterator it=aLocalizedFunctionNames.begin(); it!=aLocalizedFunctionNames.end(); ++it)
{
if( it->second > 1 )
{
std::cout << "ERROR: Spreadsheet function name translations must be unique.\n" <<
"Language: " << aLanguage <<
"\nDuplicated translation is: " << it->first << "\n\n";
}
}
}
// In instsetoo_native/inc_openoffice/windows/msi_languages.po
// where an en-US string ends with '|', translation must end
// with '|', too.
static void checkVerticalBar(OString aLanguage)
{
OString aPoPath = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/instsetoo_native/inc_openoffice/windows/msi_languages.po";
PoIfstream aPoInput;
aPoInput.open(aPoPath);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
for(;;)
{
PoEntry aPoEntry;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry.isFuzzy() && aPoEntry.getMsgId().endsWith("|") &&
!aPoEntry.getMsgStr().isEmpty() && !aPoEntry.getMsgStr().endsWith("|") )
{
std::cout << "ERROR: Missing '|' character at the end of translated string.\n" <<
"It causes runtime error in installer.\n" <<
"File: " << aPoPath << std::endl <<
"Language: " << aLanguage << std::endl <<
"English: " << aPoEntry.getMsgId() << std::endl <<
"Localized: " << aPoEntry.getMsgStr() << std::endl << std::endl;
}
}
aPoInput.close();
}
// In starmath/source.po Math symbol names (from symbol.src)
// must not contain spaces
static void checkMathSymbolNames(OString aLanguage)
{
OString aPoPath = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/starmath/source.po";
PoIfstream aPoInput;
aPoInput.open(aPoPath);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
for(;;)
{
PoEntry aPoEntry;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_UI_SYMBOL_NAMES" &&
!aPoEntry.getMsgStr().isEmpty() && (aPoEntry.getMsgStr().indexOf(" ") != -1) )
{
std::cout << "ERROR: Math symbol names must not contain spaces.\n" <<
"File: " << aPoPath << std::endl <<
"Language: " << aLanguage << std::endl <<
"English: " << aPoEntry.getMsgId() << std::endl <<
"Localized: " << aPoEntry.getMsgStr() << std::endl << std::endl;
}
}
aPoInput.close();
}
int main()
{
OString aLanguages(getenv("ALL_LANGS"));
if( aLanguages.isEmpty() )
{
std::cerr << "Usage: make cmd cmd=solver/*/bin/pocheck\n";
return 1;
}
for(sal_Int32 i = 1;;++i) // skip en-US
{
OString aLanguage = aLanguages.getToken(i,' ');
if( aLanguage.isEmpty() )
break;
if( aLanguage == "qtz" )
continue;
checkStyleNames(aLanguage);
checkFunctionNames(aLanguage);
checkVerticalBar(aLanguage);
checkMathSymbolNames(aLanguage);
}
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>pocheck now removes entries from .po files which are incorrect<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <iostream>
#include <map>
#include <list>
#include <vector>
#include <rtl/string.hxx>
#include <rtl/ustring.hxx>
#include <osl/file.hxx>
#include "po.hxx"
// Translated style names must be unique
static void checkStyleNames(OString aLanguage)
{
std::map<OString,sal_uInt16> aLocalizedStyleNames;
std::map<OString,sal_uInt16> aLocalizedNumStyleNames;
std::list<PoEntry*> repeatedEntries;
OString aPoPath = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage + "/sw/source/ui/utlui.po";
PoIfstream aPoInput;
aPoInput.open(aPoPath);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
for(;;)
{
PoEntry* aPoEntry = new PoEntry();
aPoInput.readEntry(*aPoEntry);
bool bRepeated = false;
if( aPoInput.eof() )
break;
if( !aPoEntry->isFuzzy() && aPoEntry->getSourceFile() == "poolfmt.src" &&
aPoEntry->getGroupId().startsWith("STR_POOLCOLL") )
{
OString aMsgStr = aPoEntry->getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedStyleNames.find(aMsgStr) == aLocalizedStyleNames.end() )
aLocalizedStyleNames[aMsgStr] = 1;
else {
aLocalizedStyleNames[aMsgStr]++;
bRepeated = true;
}
}
if( !aPoEntry->isFuzzy() && aPoEntry->getSourceFile() == "poolfmt.src" &&
aPoEntry->getGroupId().startsWith("STR_POOLNUMRULE") )
{
OString aMsgStr = aPoEntry->getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedNumStyleNames.find(aMsgStr) == aLocalizedNumStyleNames.end() )
aLocalizedNumStyleNames[aMsgStr] = 1;
else {
aLocalizedNumStyleNames[aMsgStr]++;
bRepeated = true;
}
}
if (bRepeated)
repeatedEntries.push_back(aPoEntry);
else
delete aPoEntry;
}
aPoInput.close();
for( std::map<OString,sal_uInt16>::iterator it=aLocalizedStyleNames.begin(); it!=aLocalizedStyleNames.end(); ++it)
{
if( it->second > 1 )
{
std::cout << "ERROR: Style name translations must be unique in:\n" <<
aPoPath << "\nLanguage: " << aLanguage << "\nDuplicated translation is: " << it->first <<
"\nSee STR_POOLCOLL_*\n\n";
}
}
for( std::map<OString,sal_uInt16>::iterator it=aLocalizedNumStyleNames.begin(); it!=aLocalizedNumStyleNames.end(); ++it)
{
if( it->second > 1 )
{
std::cout << "ERROR: Style name translations must be unique in:\n" <<
aPoPath << "\nLanguage: " << aLanguage << "\nDuplicated translation is: " << it->first <<
"\nSee STR_POOLNUMRULE_*\n\n";
}
}
aPoInput.open(aPoPath);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
PoOfstream aPoOutput;
aPoOutput.open(aPoPath+".new");
PoHeader aTmp("sw/source/ui/utlui");
aPoOutput.writeHeader(aTmp);
bool bAnyError = false;
for(;;)
{
PoEntry aPoEntry;
bool bError = false;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
for ( std::list<PoEntry*>::iterator it=repeatedEntries.begin(); it!=repeatedEntries.end(); ++it) {
if ((*it)->getMsgId() == aPoEntry.getMsgId() && (*it)->getGroupId() == aPoEntry.getGroupId()) {
bError = true;
break;
}
}
if (bError) {
bAnyError = true;
} else {
aPoOutput.writeEntry(aPoEntry);
}
}
aPoInput.close();
aPoOutput.close();
OUString aPoPathURL;
osl::FileBase::getFileURLFromSystemPath(OStringToOUString(aPoPath, RTL_TEXTENCODING_UTF8), aPoPathURL);
if( bAnyError )
osl::File::move(aPoPathURL + ".new", aPoPathURL);
else
osl::File::remove(aPoPathURL + ".new");
}
// Translated spreadsheet function names must be unique
static void checkFunctionNames(OString aLanguage)
{
std::map<OString,sal_uInt16> aLocalizedFunctionNames;
std::map<OString,sal_uInt16> aLocalizedCoreFunctionNames;
//
std::list<PoEntry*> repeatedEntries;
OString aPoPaths[4];
OUString aPoPathURL;
aPoPaths[0] = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/formula/source/core/resource.po";
PoIfstream aPoInput;
aPoInput.open(aPoPaths[0]);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPaths[0] << std::endl;
for(;;)
{
PoEntry* aPoEntry = new PoEntry();
aPoInput.readEntry(*aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry->isFuzzy() && aPoEntry->getGroupId() == "RID_STRLIST_FUNCTION_NAMES" )
{
OString aMsgStr = aPoEntry->getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedCoreFunctionNames.find(aMsgStr) == aLocalizedCoreFunctionNames.end() )
aLocalizedCoreFunctionNames[aMsgStr] = 1;
if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) {
aLocalizedFunctionNames[aMsgStr] = 1;
delete aPoEntry;
} else {
aLocalizedFunctionNames[aMsgStr]++;
repeatedEntries.push_back(aPoEntry);
}
}
}
aPoInput.close();
aPoPaths[1] = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/scaddins/source/analysis.po";
aPoInput.open(aPoPaths[1]);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPaths[1] << std::endl;
for(;;)
{
PoEntry* aPoEntry = new PoEntry();
aPoInput.readEntry(*aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry->isFuzzy() && aPoEntry->getGroupId() == "RID_ANALYSIS_FUNCTION_NAMES" )
{
OString aMsgStr = aPoEntry->getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )
aMsgStr += "_ADD";
if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) {
aLocalizedFunctionNames[aMsgStr] = 1;
delete aPoEntry;
} else {
aLocalizedFunctionNames[aMsgStr]++;
repeatedEntries.push_back(aPoEntry);
}
}
}
aPoInput.close();
aPoPaths[2] = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/scaddins/source/datefunc.po";
aPoInput.open(aPoPaths[2]);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPaths[2] << std::endl;
for(;;)
{
PoEntry* aPoEntry = new PoEntry();
aPoInput.readEntry(*aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry->isFuzzy() && aPoEntry->getGroupId() == "RID_DATE_FUNCTION_NAMES" )
{
OString aMsgStr = aPoEntry->getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )
aMsgStr += "_ADD";
if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) {
aLocalizedFunctionNames[aMsgStr] = 1;
delete aPoEntry;
} else {
aLocalizedFunctionNames[aMsgStr]++;
repeatedEntries.push_back(aPoEntry);
}
}
}
aPoInput.close();
aPoPaths[3] = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/scaddins/source/pricing.po";
aPoInput.open(aPoPaths[3]);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPaths[3] << std::endl;
for(;;)
{
PoEntry* aPoEntry = new PoEntry();
aPoInput.readEntry(*aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry->isFuzzy() && aPoEntry->getGroupId() == "RID_PRICING_FUNCTION_NAMES" )
{
OString aMsgStr = aPoEntry->getMsgStr();
if( aMsgStr.isEmpty() )
continue;
if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )
aMsgStr += "_ADD";
if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) {
aLocalizedFunctionNames[aMsgStr] = 1;
delete aPoEntry;
} else {
aLocalizedFunctionNames[aMsgStr]++;
repeatedEntries.push_back(aPoEntry);
}
}
}
aPoInput.close();
for( std::map<OString,sal_uInt16>::iterator it=aLocalizedFunctionNames.begin(); it!=aLocalizedFunctionNames.end(); ++it)
{
if( it->second > 1 )
{
std::cout << "ERROR: Spreadsheet function name translations must be unique.\n" <<
"Language: " << aLanguage <<
"\nDuplicated translation is: " << it->first << "\n\n";
}
}
//
for (int i=0;i<4;i++) {
aPoInput.open(aPoPaths[i]);
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPaths[i] << std::endl;
PoOfstream aPoOutput;
aPoOutput.open(aPoPaths[i]+".new");
switch (i) {
case 0:
aPoOutput.writeHeader(PoHeader("formula/source/core/resource"));
break;
case 1:
aPoOutput.writeHeader(PoHeader("scaddins/source/analysis"));
break;
case 2:
aPoOutput.writeHeader(PoHeader("scaddins/source/datefunc"));
break;
case 3:
aPoOutput.writeHeader(PoHeader("scaddins/source/pricing"));
}
bool bAnyError = false;
for(;;)
{
PoEntry aPoEntry;
bool bError = false;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
for ( std::list<PoEntry*>::iterator it=repeatedEntries.begin(); it!=repeatedEntries.end(); ++it) {
if ((*it)->getMsgId() == aPoEntry.getMsgId() && (*it)->getGroupId() == aPoEntry.getGroupId()) {
bError = true;
break;
}
}
if (bError) {
bAnyError = true;
} else {
aPoOutput.writeEntry(aPoEntry);
}
}
aPoInput.close();
aPoOutput.close();
osl::FileBase::getFileURLFromSystemPath(OStringToOUString(aPoPaths[i], RTL_TEXTENCODING_UTF8), aPoPathURL);
if( bAnyError )
osl::File::move(aPoPathURL + ".new", aPoPathURL);
else
osl::File::remove(aPoPathURL + ".new");
}
}
// In instsetoo_native/inc_openoffice/windows/msi_languages.po
// where an en-US string ends with '|', translation must end
// with '|', too.
static void checkVerticalBar(OString aLanguage)
{
OString aPoPath = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/instsetoo_native/inc_openoffice/windows/msi_languages.po";
PoIfstream aPoInput;
aPoInput.open(aPoPath);
PoOfstream aPoOutput;
aPoOutput.open(aPoPath+".new");
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
PoHeader aTmp("instsetoo_native/inc_openoffice/windows/msi_languages");
aPoOutput.writeHeader(aTmp);
bool bError = false;
for(;;)
{
PoEntry aPoEntry;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry.isFuzzy() && aPoEntry.getMsgId().endsWith("|") &&
!aPoEntry.getMsgStr().isEmpty() && !aPoEntry.getMsgStr().endsWith("|") )
{
std::cout << "ERROR: Missing '|' character at the end of translated string.\n" <<
"It causes runtime error in installer.\n" <<
"File: " << aPoPath << std::endl <<
"Language: " << aLanguage << std::endl <<
"English: " << aPoEntry.getMsgId() << std::endl <<
"Localized: " << aPoEntry.getMsgStr() << std::endl << std::endl;
bError = true;
}
else
aPoOutput.writeEntry(aPoEntry);
}
aPoInput.close();
aPoOutput.close();
OUString aPoPathURL;
osl::FileBase::getFileURLFromSystemPath(OStringToOUString(aPoPath, RTL_TEXTENCODING_UTF8), aPoPathURL);
if( bError )
osl::File::move(aPoPathURL + ".new", aPoPathURL);
else
osl::File::remove(aPoPathURL + ".new");
}
// In starmath/source.po Math symbol names (from symbol.src)
// must not contain spaces
static void checkMathSymbolNames(OString aLanguage)
{
OString aPoPath = OString(getenv("SRC_ROOT")) +
"/translations/source/" +
aLanguage +
"/starmath/source.po";
PoIfstream aPoInput;
aPoInput.open(aPoPath);
PoOfstream aPoOutput;
aPoOutput.open(aPoPath+".new");
if( !aPoInput.isOpen() )
std::cerr << "Warning: Cannot open " << aPoPath << std::endl;
PoHeader aTmp("starmath/source");
aPoOutput.writeHeader(aTmp);
bool bError = false;
for(;;)
{
PoEntry aPoEntry;
aPoInput.readEntry(aPoEntry);
if( aPoInput.eof() )
break;
if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_UI_SYMBOL_NAMES" &&
!aPoEntry.getMsgStr().isEmpty() && (aPoEntry.getMsgStr().indexOf(" ") != -1) )
{
std::cout << "ERROR: Math symbol names must not contain spaces.\n" <<
"File: " << aPoPath << std::endl <<
"Language: " << aLanguage << std::endl <<
"English: " << aPoEntry.getMsgId() << std::endl <<
"Localized: " << aPoEntry.getMsgStr() << std::endl << std::endl;
bError = true;
}
else
aPoOutput.writeEntry(aPoEntry);
}
aPoInput.close();
aPoOutput.close();
OUString aPoPathURL;
osl::FileBase::getFileURLFromSystemPath(OStringToOUString(aPoPath, RTL_TEXTENCODING_UTF8), aPoPathURL);
if( bError )
osl::File::move(aPoPathURL + ".new", aPoPathURL);
else
osl::File::remove(aPoPathURL + ".new");
}
int main()
{
OString aLanguages(getenv("ALL_LANGS"));
if( aLanguages.isEmpty() )
{
std::cerr << "Usage: make cmd cmd=solver/*/bin/pocheck\n";
return 1;
}
for(sal_Int32 i = 1;;++i) // skip en-US
{
OString aLanguage = aLanguages.getToken(i,' ');
if( aLanguage.isEmpty() )
break;
if( aLanguage == "qtz" )
continue;
checkStyleNames(aLanguage);
checkFunctionNames(aLanguage);
checkVerticalBar(aLanguage);
checkMathSymbolNames(aLanguage);
}
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Author: Junyang
#define DEBUG_TYPE "dyn-aa"
#include <cstdio>
#include <fstream>
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"
#include "rcs/IDAssigner.h"
#include "dyn-aa/LogCounter.h"
#include "dyn-aa/TraceSlicer.h"
using namespace std;
using namespace llvm;
using namespace rcs;
using namespace dyn_aa;
static cl::opt<unsigned> FirstPointerRecordID(
"pt1",
cl::desc("RecordID of the first pointer"));
static cl::opt<unsigned> SecondPointerRecordID(
"pt2",
cl::desc("RecordID of the second pointer"));
static RegisterPass<TraceSlicer> X("slice-trace",
"Slice trace of two input pointers",
false, // Is CFG Only?
true); // Is Analysis?
char TraceSlicer::ID = 0;
bool TraceSlicer::runOnModule(Module &M) {
LogCounter LC;
LC.processLog();
CurrentRecordID = LC.getNumLogRecords();
CurrentState[0].StartRecordID = FirstPointerRecordID;
CurrentState[1].StartRecordID = SecondPointerRecordID;
processLog(true);
return false;
}
void TraceSlicer::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequired<IDAssigner>();
}
void TraceSlicer::printTrace(raw_ostream &O,
pair<unsigned, unsigned> TraceRecord,
int PointerLabel) const {
unsigned RecordID = TraceRecord.first;
unsigned ValueID = TraceRecord.second;
IDAssigner &IDA = getAnalysis<IDAssigner>();
Value *V = IDA.getValue(ValueID);
O << RecordID << "\t";
O << "ptr" << PointerLabel + 1 << "\t";
O << ValueID << "\t";
DynAAUtils::PrintValue(O, V);
// if (Argument *A = dyn_cast<Argument>(V)) {
// O << " (argNo " << A->getArgNo() << ")";
// }
O << "\n";
}
void TraceSlicer::print(raw_ostream &O, const Module *M) const {
O << "RecID\tPtr\tValueID\tFunc: Inst/Arg\n\n";
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
O << "ptr" << PointerLabel + 1 << ": \n";
for (int i = CurrentState[PointerLabel].Trace.size() - 1; i >= 0; --i) {
printTrace(O, CurrentState[PointerLabel].Trace[i], PointerLabel);
}
O << "\n";
}
O << "Merged: \n";
int Index[2];
Index[0] = CurrentState[0].Trace.size() - 1;
Index[1] = CurrentState[1].Trace.size() - 1;
while (true) {
unsigned Min;
int PointerLabel = -1;
for (int i = 0; i < 2; ++i) {
if (Index[i] >= 0 &&
(PointerLabel == -1 || CurrentState[i].Trace[Index[i]].first < Min)) {
Min = CurrentState[i].Trace[Index[i]].first;
PointerLabel = i;
}
}
if (PointerLabel != -1) {
printTrace(O,
CurrentState[PointerLabel].Trace[Index[PointerLabel]],
PointerLabel);
Index[PointerLabel]--;
} else
break;
}
}
bool TraceSlicer::isLive(int PointerLabel) {
if (CurrentState[PointerLabel].StartRecordID < CurrentRecordID ||
CurrentState[PointerLabel].End) {
return false;
}
return true;
}
void TraceSlicer::processAddrTakenDecl(const AddrTakenDeclLogRecord &Record) {
CurrentRecordID--;
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
// Starting record must be a TopLevelPointTo record
assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
}
}
void TraceSlicer::processTopLevelPointTo(
const TopLevelPointToLogRecord &Record) {
CurrentRecordID--;
int NumContainingSlices = 0;
IDAssigner &IDA = getAnalysis<IDAssigner>();
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
if (CurrentState[PointerLabel].StartRecordID == CurrentRecordID) {
Value *V = IDA.getValue(Record.PointerValueID);
assert(V->getType()->isPointerTy());
CurrentState[PointerLabel].ValueID = Record.PointerValueID;
}
if (isLive(PointerLabel)) {
if (CurrentState[PointerLabel].Action != TopLevelPointTo) {
continue;
}
if (!CurrentState[PointerLabel].ValueIDCandidates.empty()) {
// For select and PHI, find current ID according to Address and
// ValueIDCandidates.
// If two variables of select have the same value, we follow the one
// occurs latter, this is just a temporary method.
if (Record.PointeeAddress == CurrentState[PointerLabel].Address &&
CurrentState[PointerLabel].ValueIDCandidates.count(
Record.PointerValueID)) {
CurrentState[PointerLabel].ValueIDCandidates.clear();
CurrentState[PointerLabel].ValueID = Record.PointerValueID;
NumContainingSlices++;
CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
CurrentRecordID, CurrentState[PointerLabel].ValueID));
trackSourcePointer(CurrentState[PointerLabel], Record);
}
} else {
if (Record.PointerValueID == CurrentState[PointerLabel].ValueID) {
NumContainingSlices++;
CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
CurrentRecordID, CurrentState[PointerLabel].ValueID));
trackSourcePointer(CurrentState[PointerLabel], Record);
}
}
}
}
// If two sliced traces meet, we stop tracking
if (NumContainingSlices == 2) {
CurrentState[0].End = true;
CurrentState[1].End = true;
}
}
void TraceSlicer::trackSourcePointer(TraceState &TS,
const TopLevelPointToLogRecord &Record) {
IDAssigner &IDA = getAnalysis<IDAssigner>();
Value *V = IDA.getValue(TS.ValueID);
if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
TS.Address = Record.LoadedFrom;
TS.Action = AddrTakenPointTo;
} else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
TS.ValueID = IDA.getValueID(GEPI->getPointerOperand());
} else if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
TS.ValueID = IDA.getValueID(BCI->getOperand(0));
} else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
TS.ValueIDCandidates.insert(IDA.getValueID(SI->getTrueValue()));
TS.ValueIDCandidates.insert(IDA.getValueID(SI->getFalseValue()));
TS.Address = Record.PointeeAddress;
} else if (PHINode *PN = dyn_cast<PHINode>(V)) {
unsigned NumIncomingValues = PN->getNumIncomingValues();
for (unsigned VI = 0; VI != NumIncomingValues; ++VI) {
TS.ValueIDCandidates.insert(IDA.getValueID(PN->getIncomingValue(VI)));
}
TS.Address = Record.PointeeAddress;
} else if (Argument *A = dyn_cast<Argument>(V)) {
TS.Action = CallInstruction;
TS.ArgNo = A->getArgNo();
// errs() << "(argument of @" << A->getParent()->getName() << ")\n";
} else if (CallInst *CI = dyn_cast<CallInst>(V)) {
TS.Action = ReturnInstruction;
// errs() << "(call @" << CI->getCalledFunction()->getName() << ")\n";
} else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
TS.Action = ReturnInstruction;
// errs() << "(call @" << II->getCalledFunction()->getName() << ")\n";
} else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
TS.End = true;
} else if (isa<GlobalValue>(V)) {
TS.End = true;
} else {
errs() << "Unknown instruction \'" << *V << "\'\n";
TS.End = true;
}
}
void TraceSlicer::processAddrTakenPointTo(
const AddrTakenPointToLogRecord &Record) {
CurrentRecordID--;
int NumContainingSlices = 0;
IDAssigner &IDA = getAnalysis<IDAssigner>();
Instruction *I = IDA.getInstruction(Record.InstructionID);
assert(isa<StoreInst>(I));
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
// Starting record must be a TopLevelPointTo record
assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
if (isLive(PointerLabel)) {
if (CurrentState[PointerLabel].Action != AddrTakenPointTo) {
continue;
}
if (Record.PointerAddress == CurrentState[PointerLabel].Address) {
NumContainingSlices++;
CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
CurrentRecordID, IDA.getValueID(I)));
CurrentState[PointerLabel].Action = TopLevelPointTo;
StoreInst *SI = dyn_cast<StoreInst>(I);
CurrentState[PointerLabel].ValueID =
IDA.getValueID(SI->getValueOperand());
}
}
}
// If two sliced traces meet, we stop tracking
if (NumContainingSlices == 2) {
CurrentState[0].End = true;
CurrentState[1].End = true;
}
}
void TraceSlicer::processCallInstruction(
const CallInstructionLogRecord &Record) {
CurrentRecordID--;
int NumContainingSlices = 0;
IDAssigner &IDA = getAnalysis<IDAssigner>();
Instruction *I = IDA.getInstruction(Record.InstructionID);
CallSite CS(I);
assert(CS);
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
// Starting record must be a TopLevelPointTo record
assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
if (isLive(PointerLabel)) {
if (CurrentState[PointerLabel].Action == ReturnInstruction) {
// this callee is an external function, the trace ends
CurrentState[PointerLabel].End = true;
continue;
}
if (CurrentState[PointerLabel].Action != CallInstruction) {
continue;
}
NumContainingSlices++;
CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
CurrentRecordID, IDA.getValueID(I)));
CurrentState[PointerLabel].Action = TopLevelPointTo;
CurrentState[PointerLabel].ValueID =
IDA.getValueID(CS.getArgument(CurrentState[PointerLabel].ArgNo));
}
}
// If two sliced traces meet, we stop tracking
if (NumContainingSlices == 2) {
CurrentState[0].End = true;
CurrentState[1].End = true;
}
}
void TraceSlicer::processReturnInstruction(
const ReturnInstructionLogRecord &Record) {
CurrentRecordID--;
int NumContainingSlices = 0;
IDAssigner &IDA = getAnalysis<IDAssigner>();
Instruction *I = IDA.getInstruction(Record.InstructionID);
assert(isa<ReturnInst>(I) || isa<ResumeInst>(I));
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
// Starting record must be a TopLevelPointTo record
assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
if (isLive(PointerLabel)) {
if (CurrentState[PointerLabel].Action != ReturnInstruction) {
continue;
}
NumContainingSlices++;
CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
CurrentRecordID, IDA.getValueID(I)));
CurrentState[PointerLabel].Action = TopLevelPointTo;
if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
CurrentState[PointerLabel].ValueID = IDA.getValueID(RI->getReturnValue());
} else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
assert(false);
// CurrentState[PointerLabel].ValueID = IDA.getValueID(RI->getValue());
} else {
assert(false);
}
}
}
// If two sliced traces meet, we stop tracking
if (NumContainingSlices == 2) {
CurrentState[0].End = true;
CurrentState[1].End = true;
}
}
<commit_msg>Warnings fixed.<commit_after>// Author: Junyang
#define DEBUG_TYPE "dyn-aa"
#include <cstdio>
#include <fstream>
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"
#include "rcs/IDAssigner.h"
#include "dyn-aa/LogCounter.h"
#include "dyn-aa/TraceSlicer.h"
using namespace std;
using namespace llvm;
using namespace rcs;
using namespace dyn_aa;
static cl::opt<unsigned> FirstPointerRecordID(
"pt1",
cl::desc("RecordID of the first pointer"));
static cl::opt<unsigned> SecondPointerRecordID(
"pt2",
cl::desc("RecordID of the second pointer"));
static RegisterPass<TraceSlicer> X("slice-trace",
"Slice trace of two input pointers",
false, // Is CFG Only?
true); // Is Analysis?
char TraceSlicer::ID = 0;
bool TraceSlicer::runOnModule(Module &M) {
LogCounter LC;
LC.processLog();
CurrentRecordID = LC.getNumLogRecords();
CurrentState[0].StartRecordID = FirstPointerRecordID;
CurrentState[1].StartRecordID = SecondPointerRecordID;
processLog(true);
return false;
}
void TraceSlicer::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequired<IDAssigner>();
}
void TraceSlicer::printTrace(raw_ostream &O,
pair<unsigned, unsigned> TraceRecord,
int PointerLabel) const {
unsigned RecordID = TraceRecord.first;
unsigned ValueID = TraceRecord.second;
IDAssigner &IDA = getAnalysis<IDAssigner>();
Value *V = IDA.getValue(ValueID);
O << RecordID << "\t";
O << "ptr" << PointerLabel + 1 << "\t";
O << ValueID << "\t";
DynAAUtils::PrintValue(O, V);
// if (Argument *A = dyn_cast<Argument>(V)) {
// O << " (argNo " << A->getArgNo() << ")";
// }
O << "\n";
}
void TraceSlicer::print(raw_ostream &O, const Module *M) const {
O << "RecID\tPtr\tValueID\tFunc: Inst/Arg\n\n";
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
O << "ptr" << PointerLabel + 1 << ": \n";
for (int i = CurrentState[PointerLabel].Trace.size() - 1; i >= 0; --i) {
printTrace(O, CurrentState[PointerLabel].Trace[i], PointerLabel);
}
O << "\n";
}
O << "Merged: \n";
int Index[2];
Index[0] = CurrentState[0].Trace.size() - 1;
Index[1] = CurrentState[1].Trace.size() - 1;
while (true) {
unsigned Min;
int PointerLabel = -1;
for (int i = 0; i < 2; ++i) {
if (Index[i] >= 0 &&
(PointerLabel == -1 || CurrentState[i].Trace[Index[i]].first < Min)) {
Min = CurrentState[i].Trace[Index[i]].first;
PointerLabel = i;
}
}
if (PointerLabel != -1) {
printTrace(O,
CurrentState[PointerLabel].Trace[Index[PointerLabel]],
PointerLabel);
Index[PointerLabel]--;
} else
break;
}
}
bool TraceSlicer::isLive(int PointerLabel) {
if (CurrentState[PointerLabel].StartRecordID < CurrentRecordID ||
CurrentState[PointerLabel].End) {
return false;
}
return true;
}
void TraceSlicer::processAddrTakenDecl(const AddrTakenDeclLogRecord &Record) {
CurrentRecordID--;
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
// Starting record must be a TopLevelPointTo record
assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
}
}
void TraceSlicer::processTopLevelPointTo(
const TopLevelPointToLogRecord &Record) {
CurrentRecordID--;
int NumContainingSlices = 0;
IDAssigner &IDA = getAnalysis<IDAssigner>();
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
if (CurrentState[PointerLabel].StartRecordID == CurrentRecordID) {
Value *V = IDA.getValue(Record.PointerValueID);
assert(V->getType()->isPointerTy());
CurrentState[PointerLabel].ValueID = Record.PointerValueID;
}
if (isLive(PointerLabel)) {
if (CurrentState[PointerLabel].Action != TopLevelPointTo) {
continue;
}
if (!CurrentState[PointerLabel].ValueIDCandidates.empty()) {
// For select and PHI, find current ID according to Address and
// ValueIDCandidates.
// If two variables of select have the same value, we follow the one
// occurs latter, this is just a temporary method.
if (Record.PointeeAddress == CurrentState[PointerLabel].Address &&
CurrentState[PointerLabel].ValueIDCandidates.count(
Record.PointerValueID)) {
CurrentState[PointerLabel].ValueIDCandidates.clear();
CurrentState[PointerLabel].ValueID = Record.PointerValueID;
NumContainingSlices++;
CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
CurrentRecordID, CurrentState[PointerLabel].ValueID));
trackSourcePointer(CurrentState[PointerLabel], Record);
}
} else {
if (Record.PointerValueID == CurrentState[PointerLabel].ValueID) {
NumContainingSlices++;
CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
CurrentRecordID, CurrentState[PointerLabel].ValueID));
trackSourcePointer(CurrentState[PointerLabel], Record);
}
}
}
}
// If two sliced traces meet, we stop tracking
if (NumContainingSlices == 2) {
CurrentState[0].End = true;
CurrentState[1].End = true;
}
}
void TraceSlicer::trackSourcePointer(TraceState &TS,
const TopLevelPointToLogRecord &Record) {
IDAssigner &IDA = getAnalysis<IDAssigner>();
Value *V = IDA.getValue(TS.ValueID);
if (isa<LoadInst>(V)) {
TS.Address = Record.LoadedFrom;
TS.Action = AddrTakenPointTo;
} else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
TS.ValueID = IDA.getValueID(GEPI->getPointerOperand());
} else if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
TS.ValueID = IDA.getValueID(BCI->getOperand(0));
} else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
TS.ValueIDCandidates.insert(IDA.getValueID(SI->getTrueValue()));
TS.ValueIDCandidates.insert(IDA.getValueID(SI->getFalseValue()));
TS.Address = Record.PointeeAddress;
} else if (PHINode *PN = dyn_cast<PHINode>(V)) {
unsigned NumIncomingValues = PN->getNumIncomingValues();
for (unsigned VI = 0; VI != NumIncomingValues; ++VI) {
TS.ValueIDCandidates.insert(IDA.getValueID(PN->getIncomingValue(VI)));
}
TS.Address = Record.PointeeAddress;
} else if (Argument *A = dyn_cast<Argument>(V)) {
TS.Action = CallInstruction;
TS.ArgNo = A->getArgNo();
// errs() << "(argument of @" << A->getParent()->getName() << ")\n";
} else if (isa<CallInst>(V) || isa<InvokeInst>(V)) {
TS.Action = ReturnInstruction;
} else if (isa<AllocaInst>(V)) {
TS.End = true;
} else if (isa<GlobalValue>(V)) {
TS.End = true;
} else {
errs() << "Unknown instruction \'" << *V << "\'\n";
TS.End = true;
}
}
void TraceSlicer::processAddrTakenPointTo(
const AddrTakenPointToLogRecord &Record) {
CurrentRecordID--;
int NumContainingSlices = 0;
IDAssigner &IDA = getAnalysis<IDAssigner>();
Instruction *I = IDA.getInstruction(Record.InstructionID);
assert(isa<StoreInst>(I));
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
// Starting record must be a TopLevelPointTo record
assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
if (isLive(PointerLabel)) {
if (CurrentState[PointerLabel].Action != AddrTakenPointTo) {
continue;
}
if (Record.PointerAddress == CurrentState[PointerLabel].Address) {
NumContainingSlices++;
CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
CurrentRecordID, IDA.getValueID(I)));
CurrentState[PointerLabel].Action = TopLevelPointTo;
StoreInst *SI = dyn_cast<StoreInst>(I);
CurrentState[PointerLabel].ValueID =
IDA.getValueID(SI->getValueOperand());
}
}
}
// If two sliced traces meet, we stop tracking
if (NumContainingSlices == 2) {
CurrentState[0].End = true;
CurrentState[1].End = true;
}
}
void TraceSlicer::processCallInstruction(
const CallInstructionLogRecord &Record) {
CurrentRecordID--;
int NumContainingSlices = 0;
IDAssigner &IDA = getAnalysis<IDAssigner>();
Instruction *I = IDA.getInstruction(Record.InstructionID);
CallSite CS(I);
assert(CS);
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
// Starting record must be a TopLevelPointTo record
assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
if (isLive(PointerLabel)) {
if (CurrentState[PointerLabel].Action == ReturnInstruction) {
// this callee is an external function, the trace ends
CurrentState[PointerLabel].End = true;
continue;
}
if (CurrentState[PointerLabel].Action != CallInstruction) {
continue;
}
NumContainingSlices++;
CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
CurrentRecordID, IDA.getValueID(I)));
CurrentState[PointerLabel].Action = TopLevelPointTo;
CurrentState[PointerLabel].ValueID =
IDA.getValueID(CS.getArgument(CurrentState[PointerLabel].ArgNo));
}
}
// If two sliced traces meet, we stop tracking
if (NumContainingSlices == 2) {
CurrentState[0].End = true;
CurrentState[1].End = true;
}
}
void TraceSlicer::processReturnInstruction(
const ReturnInstructionLogRecord &Record) {
CurrentRecordID--;
int NumContainingSlices = 0;
IDAssigner &IDA = getAnalysis<IDAssigner>();
Instruction *I = IDA.getInstruction(Record.InstructionID);
assert(isa<ReturnInst>(I) || isa<ResumeInst>(I));
for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
// Starting record must be a TopLevelPointTo record
assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
if (isLive(PointerLabel)) {
if (CurrentState[PointerLabel].Action != ReturnInstruction) {
continue;
}
NumContainingSlices++;
CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
CurrentRecordID, IDA.getValueID(I)));
CurrentState[PointerLabel].Action = TopLevelPointTo;
if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
CurrentState[PointerLabel].ValueID =
IDA.getValueID(RI->getReturnValue());
} else if (isa<ResumeInst>(I)) {
assert(false);
} else {
assert(false);
}
}
}
// If two sliced traces meet, we stop tracking
if (NumContainingSlices == 2) {
CurrentState[0].End = true;
CurrentState[1].End = true;
}
}
<|endoftext|> |
<commit_before>//===-- OptimizeExts.cpp - Optimize sign / zero extension instrs -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs optimization of sign / zero extension instructions. It
// may be extended to handle other instructions of similar property.
//
// On some targets, some instructions, e.g. X86 sign / zero extension, may
// leave the source value in the lower part of the result. This pass will
// replace (some) uses of the pre-extension value with uses of the sub-register
// of the results.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "ext-opt"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
static cl::opt<bool> Aggressive("aggressive-ext-opt", cl::Hidden,
cl::desc("Aggressive extension optimization"));
STATISTIC(NumReuse, "Number of extension results reused");
namespace {
class OptimizeExts : public MachineFunctionPass {
const TargetMachine *TM;
const TargetInstrInfo *TII;
MachineRegisterInfo *MRI;
MachineDominatorTree *DT; // Machine dominator tree
public:
static char ID; // Pass identification
OptimizeExts() : MachineFunctionPass(&ID) {}
virtual bool runOnMachineFunction(MachineFunction &MF);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
if (Aggressive) {
AU.addRequired<MachineDominatorTree>();
AU.addPreserved<MachineDominatorTree>();
}
}
private:
bool OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,
SmallPtrSet<MachineInstr*, 8> &LocalMIs);
};
}
char OptimizeExts::ID = 0;
INITIALIZE_PASS(OptimizeExts, "opt-exts",
"Optimize sign / zero extensions", false, false);
FunctionPass *llvm::createOptimizeExtsPass() { return new OptimizeExts(); }
/// OptimizeInstr - If instruction is a copy-like instruction, i.e. it reads
/// a single register and writes a single register and it does not modify
/// the source, and if the source value is preserved as a sub-register of
/// the result, then replace all reachable uses of the source with the subreg
/// of the result.
/// Do not generate an EXTRACT that is used only in a debug use, as this
/// changes the code. Since this code does not currently share EXTRACTs, just
/// ignore all debug uses.
bool OptimizeExts::OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,
SmallPtrSet<MachineInstr*, 8> &LocalMIs) {
bool Changed = false;
LocalMIs.insert(MI);
unsigned SrcReg, DstReg, SubIdx;
if (TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx)) {
if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
TargetRegisterInfo::isPhysicalRegister(SrcReg))
return false;
MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(SrcReg);
if (++UI == MRI->use_nodbg_end())
// No other uses.
return false;
// Ok, the source has other uses. See if we can replace the other uses
// with use of the result of the extension.
SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
UI = MRI->use_nodbg_begin(DstReg);
for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
UI != UE; ++UI)
ReachedBBs.insert(UI->getParent());
bool ExtendLife = true;
// Uses that are in the same BB of uses of the result of the instruction.
SmallVector<MachineOperand*, 8> Uses;
// Uses that the result of the instruction can reach.
SmallVector<MachineOperand*, 8> ExtendedUses;
UI = MRI->use_nodbg_begin(SrcReg);
for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
UI != UE; ++UI) {
MachineOperand &UseMO = UI.getOperand();
MachineInstr *UseMI = &*UI;
if (UseMI == MI)
continue;
if (UseMI->isPHI()) {
ExtendLife = false;
continue;
}
// It's an error to translate this:
//
// %reg1025 = <sext> %reg1024
// ...
// %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
//
// into this:
//
// %reg1025 = <sext> %reg1024
// ...
// %reg1027 = COPY %reg1025:4
// %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
//
// The problem here is that SUBREG_TO_REG is there to assert that an
// implicit zext occurs. It doesn't insert a zext instruction. If we allow
// the COPY here, it will give us the value after the <sext>,
// not the original value of %reg1024 before <sext>.
if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
continue;
MachineBasicBlock *UseMBB = UseMI->getParent();
if (UseMBB == MBB) {
// Local uses that come after the extension.
if (!LocalMIs.count(UseMI))
Uses.push_back(&UseMO);
} else if (ReachedBBs.count(UseMBB))
// Non-local uses where the result of extension is used. Always
// replace these unless it's a PHI.
Uses.push_back(&UseMO);
else if (Aggressive && DT->dominates(MBB, UseMBB))
// We may want to extend live range of the extension result in order
// to replace these uses.
ExtendedUses.push_back(&UseMO);
else {
// Both will be live out of the def MBB anyway. Don't extend live
// range of the extension result.
ExtendLife = false;
break;
}
}
if (ExtendLife && !ExtendedUses.empty())
// Ok, we'll extend the liveness of the extension result.
std::copy(ExtendedUses.begin(), ExtendedUses.end(),
std::back_inserter(Uses));
// Now replace all uses.
if (!Uses.empty()) {
SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
// Look for PHI uses of the extended result, we don't want to extend the
// liveness of a PHI input. It breaks all kinds of assumptions down
// stream. A PHI use is expected to be the kill of its source values.
UI = MRI->use_nodbg_begin(DstReg);
for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
UI != UE; ++UI)
if (UI->isPHI())
PHIBBs.insert(UI->getParent());
const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
MachineOperand *UseMO = Uses[i];
MachineInstr *UseMI = UseMO->getParent();
MachineBasicBlock *UseMBB = UseMI->getParent();
if (PHIBBs.count(UseMBB))
continue;
unsigned NewVR = MRI->createVirtualRegister(RC);
BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
TII->get(TargetOpcode::COPY), NewVR)
.addReg(DstReg, 0, SubIdx);
UseMO->setReg(NewVR);
++NumReuse;
Changed = true;
}
}
}
return Changed;
}
bool OptimizeExts::runOnMachineFunction(MachineFunction &MF) {
TM = &MF.getTarget();
TII = TM->getInstrInfo();
MRI = &MF.getRegInfo();
DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0;
bool Changed = false;
SmallPtrSet<MachineInstr*, 8> LocalMIs;
for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
MachineBasicBlock *MBB = &*I;
LocalMIs.clear();
for (MachineBasicBlock::iterator MII = I->begin(), ME = I->end(); MII != ME;
++MII) {
MachineInstr *MI = &*MII;
Changed |= OptimizeInstr(MI, MBB, LocalMIs);
}
}
return Changed;
}
<commit_msg>Early exit and reduce indentation. No functionality change.<commit_after>//===-- OptimizeExts.cpp - Optimize sign / zero extension instrs -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs optimization of sign / zero extension instructions. It
// may be extended to handle other instructions of similar property.
//
// On some targets, some instructions, e.g. X86 sign / zero extension, may
// leave the source value in the lower part of the result. This pass will
// replace (some) uses of the pre-extension value with uses of the sub-register
// of the results.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "ext-opt"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
static cl::opt<bool> Aggressive("aggressive-ext-opt", cl::Hidden,
cl::desc("Aggressive extension optimization"));
STATISTIC(NumReuse, "Number of extension results reused");
namespace {
class OptimizeExts : public MachineFunctionPass {
const TargetMachine *TM;
const TargetInstrInfo *TII;
MachineRegisterInfo *MRI;
MachineDominatorTree *DT; // Machine dominator tree
public:
static char ID; // Pass identification
OptimizeExts() : MachineFunctionPass(&ID) {}
virtual bool runOnMachineFunction(MachineFunction &MF);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
if (Aggressive) {
AU.addRequired<MachineDominatorTree>();
AU.addPreserved<MachineDominatorTree>();
}
}
private:
bool OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,
SmallPtrSet<MachineInstr*, 8> &LocalMIs);
};
}
char OptimizeExts::ID = 0;
INITIALIZE_PASS(OptimizeExts, "opt-exts",
"Optimize sign / zero extensions", false, false);
FunctionPass *llvm::createOptimizeExtsPass() { return new OptimizeExts(); }
/// OptimizeInstr - If instruction is a copy-like instruction, i.e. it reads
/// a single register and writes a single register and it does not modify
/// the source, and if the source value is preserved as a sub-register of
/// the result, then replace all reachable uses of the source with the subreg
/// of the result.
/// Do not generate an EXTRACT that is used only in a debug use, as this
/// changes the code. Since this code does not currently share EXTRACTs, just
/// ignore all debug uses.
bool OptimizeExts::OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,
SmallPtrSet<MachineInstr*, 8> &LocalMIs) {
LocalMIs.insert(MI);
unsigned SrcReg, DstReg, SubIdx;
if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
return false;
if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
TargetRegisterInfo::isPhysicalRegister(SrcReg))
return false;
MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(SrcReg);
if (++UI == MRI->use_nodbg_end())
// No other uses.
return false;
// Ok, the source has other uses. See if we can replace the other uses
// with use of the result of the extension.
SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
UI = MRI->use_nodbg_begin(DstReg);
for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
UI != UE; ++UI)
ReachedBBs.insert(UI->getParent());
bool ExtendLife = true;
// Uses that are in the same BB of uses of the result of the instruction.
SmallVector<MachineOperand*, 8> Uses;
// Uses that the result of the instruction can reach.
SmallVector<MachineOperand*, 8> ExtendedUses;
UI = MRI->use_nodbg_begin(SrcReg);
for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
UI != UE; ++UI) {
MachineOperand &UseMO = UI.getOperand();
MachineInstr *UseMI = &*UI;
if (UseMI == MI)
continue;
if (UseMI->isPHI()) {
ExtendLife = false;
continue;
}
// It's an error to translate this:
//
// %reg1025 = <sext> %reg1024
// ...
// %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
//
// into this:
//
// %reg1025 = <sext> %reg1024
// ...
// %reg1027 = COPY %reg1025:4
// %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
//
// The problem here is that SUBREG_TO_REG is there to assert that an
// implicit zext occurs. It doesn't insert a zext instruction. If we allow
// the COPY here, it will give us the value after the <sext>, not the
// original value of %reg1024 before <sext>.
if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
continue;
MachineBasicBlock *UseMBB = UseMI->getParent();
if (UseMBB == MBB) {
// Local uses that come after the extension.
if (!LocalMIs.count(UseMI))
Uses.push_back(&UseMO);
} else if (ReachedBBs.count(UseMBB))
// Non-local uses where the result of extension is used. Always replace
// these unless it's a PHI.
Uses.push_back(&UseMO);
else if (Aggressive && DT->dominates(MBB, UseMBB))
// We may want to extend live range of the extension result in order to
// replace these uses.
ExtendedUses.push_back(&UseMO);
else {
// Both will be live out of the def MBB anyway. Don't extend live range of
// the extension result.
ExtendLife = false;
break;
}
}
if (ExtendLife && !ExtendedUses.empty())
// Ok, we'll extend the liveness of the extension result.
std::copy(ExtendedUses.begin(), ExtendedUses.end(),
std::back_inserter(Uses));
// Now replace all uses.
bool Changed = false;
if (!Uses.empty()) {
SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
// Look for PHI uses of the extended result, we don't want to extend the
// liveness of a PHI input. It breaks all kinds of assumptions down
// stream. A PHI use is expected to be the kill of its source values.
UI = MRI->use_nodbg_begin(DstReg);
for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
UI != UE; ++UI)
if (UI->isPHI())
PHIBBs.insert(UI->getParent());
const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
MachineOperand *UseMO = Uses[i];
MachineInstr *UseMI = UseMO->getParent();
MachineBasicBlock *UseMBB = UseMI->getParent();
if (PHIBBs.count(UseMBB))
continue;
unsigned NewVR = MRI->createVirtualRegister(RC);
BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
TII->get(TargetOpcode::COPY), NewVR)
.addReg(DstReg, 0, SubIdx);
UseMO->setReg(NewVR);
++NumReuse;
Changed = true;
}
}
return Changed;
}
bool OptimizeExts::runOnMachineFunction(MachineFunction &MF) {
TM = &MF.getTarget();
TII = TM->getInstrInfo();
MRI = &MF.getRegInfo();
DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0;
bool Changed = false;
SmallPtrSet<MachineInstr*, 8> LocalMIs;
for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
MachineBasicBlock *MBB = &*I;
LocalMIs.clear();
for (MachineBasicBlock::iterator MII = I->begin(), ME = I->end(); MII != ME;
++MII) {
MachineInstr *MI = &*MII;
Changed |= OptimizeInstr(MI, MBB, LocalMIs);
}
}
return Changed;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/GFlags.h>
#include <folly/portability/GTest.h>
#include <thrift/lib/cpp2/async/RocketClientChannel.h>
#include <thrift/lib/cpp2/server/Cpp2Worker.h>
#include <thrift/lib/cpp2/transport/core/testutil/MockCallback.h>
#include <thrift/lib/cpp2/transport/core/testutil/TransportCompatibilityTest.h>
#include <thrift/lib/cpp2/transport/rocket/server/RocketServerConnection.h>
#include <thrift/lib/cpp2/transport/rocket/server/ThriftRocketServerHandler.h>
#include <thrift/lib/cpp2/transport/rsocket/server/RSRoutingHandler.h>
DECLARE_int32(num_client_connections);
DECLARE_string(transport); // ConnectionManager depends on this flag.
namespace apache {
namespace thrift {
using namespace testutil::testservice;
using namespace apache::thrift::transport;
class RSCompatibilityTest
: public testing::Test,
public testing::WithParamInterface<bool /* useRocketClient */> {
public:
RSCompatibilityTest() {
FLAGS_transport = "rocket";
compatibilityTest_ = std::make_unique<TransportCompatibilityTest>();
compatibilityTest_->addRoutingHandler(
std::make_unique<apache::thrift::RSRoutingHandler>());
compatibilityTest_->startServer();
}
protected:
std::unique_ptr<TransportCompatibilityTest> compatibilityTest_;
};
TEST_F(RSCompatibilityTest, RequestResponse_Simple) {
compatibilityTest_->TestRequestResponse_Simple();
}
TEST_F(RSCompatibilityTest, RequestResponse_Sync) {
compatibilityTest_->TestRequestResponse_Sync();
}
TEST_F(RSCompatibilityTest, RequestResponse_Destruction) {
compatibilityTest_->TestRequestResponse_Destruction();
}
TEST_F(RSCompatibilityTest, RequestResponse_MultipleClients) {
compatibilityTest_->TestRequestResponse_MultipleClients();
}
TEST_F(RSCompatibilityTest, RequestResponse_ExpectedException) {
compatibilityTest_->TestRequestResponse_ExpectedException();
}
TEST_F(RSCompatibilityTest, RequestResponse_UnexpectedException) {
compatibilityTest_->TestRequestResponse_UnexpectedException();
}
// Warning: This test may be flaky due to use of timeouts.
TEST_F(RSCompatibilityTest, RequestResponse_Timeout) {
compatibilityTest_->TestRequestResponse_Timeout();
}
TEST_F(RSCompatibilityTest, DefaultTimeoutValueTest) {
compatibilityTest_->connectToServer([](auto client) {
// Opts with no timeout value
RpcOptions opts;
// Ok to sleep for 100msec
auto cb = std::make_unique<MockCallback>(false, false);
client->sleep(opts, std::move(cb), 100);
/* Sleep to give time for all callbacks to be completed */
/* sleep override */
std::this_thread::sleep_for(std::chrono::milliseconds(200));
auto* channel = dynamic_cast<ClientChannel*>(client->getChannel());
EXPECT_TRUE(channel);
channel->getEventBase()->runInEventBaseThreadAndWait([&]() {
channel->setTimeout(1); // 1ms
});
// Now it should timeout
cb = std::make_unique<MockCallback>(false, true);
client->sleep(opts, std::move(cb), 100);
/* Sleep to give time for all callbacks to be completed */
/* sleep override */
std::this_thread::sleep_for(std::chrono::milliseconds(200));
});
}
TEST_F(RSCompatibilityTest, RequestResponse_Header) {
compatibilityTest_->TestRequestResponse_Header();
}
TEST_F(RSCompatibilityTest, RequestResponse_Header_Load) {
compatibilityTest_->TestRequestResponse_Header_Load();
}
TEST_F(RSCompatibilityTest, RequestResponse_Header_ExpectedException) {
compatibilityTest_->TestRequestResponse_Header_ExpectedException();
}
TEST_F(RSCompatibilityTest, RequestResponse_Header_UnexpectedException) {
compatibilityTest_->TestRequestResponse_Header_UnexpectedException();
}
TEST_F(RSCompatibilityTest, RequestResponse_Saturation) {
compatibilityTest_->connectToServer([this](auto client) {
EXPECT_CALL(*compatibilityTest_->handler_.get(), add_(3)).Times(2);
// note that no EXPECT_CALL for add_(5)
auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
ASSERT_NE(nullptr, channel);
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->setMaxPendingRequests(0u); });
EXPECT_THROW(client->future_add(5).get(), TTransportException);
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->setMaxPendingRequests(1u); });
EXPECT_EQ(3, client->future_add(3).get());
EXPECT_EQ(6, client->future_add(3).get());
});
}
TEST_F(RSCompatibilityTest, RequestResponse_Connection_CloseNow) {
compatibilityTest_->TestRequestResponse_Connection_CloseNow();
}
TEST_F(RSCompatibilityTest, RequestResponse_ServerQueueTimeout) {
compatibilityTest_->TestRequestResponse_ServerQueueTimeout();
}
TEST_F(RSCompatibilityTest, RequestResponse_ResponseSizeTooBig) {
compatibilityTest_->TestRequestResponse_ResponseSizeTooBig();
}
TEST_F(RSCompatibilityTest, RequestResponse_Checksumming) {
compatibilityTest_->TestRequestResponse_Checksumming();
}
TEST_F(RSCompatibilityTest, RequestResponse_CompressRequest) {
compatibilityTest_->connectToServer([this](auto client) {
EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));
auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
ASSERT_NE(nullptr, channel);
// set the channel to compress requests
channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
channel->setAutoCompressSizeLimit(0);
std::string name("snoopy");
auto result =
client->future_hello(RpcOptions().setEnableChecksum(true), name).get();
EXPECT_EQ("Hello, snoopy", result);
});
}
TEST_F(RSCompatibilityTest, Oneway_Simple) {
compatibilityTest_->TestOneway_Simple();
}
TEST_F(RSCompatibilityTest, Oneway_WithDelay) {
compatibilityTest_->TestOneway_WithDelay();
}
TEST_F(RSCompatibilityTest, Oneway_Saturation) {
compatibilityTest_->connectToServer([this](auto client) {
EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(100, 5));
EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(50, 5));
if (auto* channel =
dynamic_cast<RocketClientChannel*>(client->getChannel())) {
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->setMaxPendingRequests(0u); });
EXPECT_THROW(
client->future_addAfterDelay(0, 5).get(), TTransportException);
// the first call is not completed as the connection was saturated
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->setMaxPendingRequests(1u); });
} else {
FAIL() << "Test run with unexpected channel type";
}
// Client should be able to issue both of these functions as
// SINGLE_REQUEST_NO_RESPONSE doesn't need to wait for server response
client->future_addAfterDelay(100, 5).get();
client->future_addAfterDelay(50, 5).get(); // TODO: H2 fails in this call.
});
}
TEST_F(RSCompatibilityTest, Oneway_UnexpectedException) {
compatibilityTest_->TestOneway_UnexpectedException();
}
TEST_F(RSCompatibilityTest, Oneway_Connection_CloseNow) {
compatibilityTest_->TestOneway_Connection_CloseNow();
}
TEST_F(RSCompatibilityTest, Oneway_ServerQueueTimeout) {
compatibilityTest_->TestOneway_ServerQueueTimeout();
}
TEST_F(RSCompatibilityTest, Oneway_Checksumming) {
compatibilityTest_->TestOneway_Checksumming();
}
TEST_F(RSCompatibilityTest, RequestContextIsPreserved) {
compatibilityTest_->TestRequestContextIsPreserved();
}
TEST_F(RSCompatibilityTest, BadPayload) {
compatibilityTest_->TestBadPayload();
}
TEST_F(RSCompatibilityTest, EvbSwitch) {
compatibilityTest_->TestEvbSwitch();
}
TEST_F(RSCompatibilityTest, EvbSwitch_Failure) {
compatibilityTest_->TestEvbSwitch_Failure();
}
TEST_F(RSCompatibilityTest, CloseCallback) {
compatibilityTest_->TestCloseCallback();
}
TEST_F(RSCompatibilityTest, ConnectionStats) {
compatibilityTest_->TestConnectionStats();
}
TEST_F(RSCompatibilityTest, ObserverSendReceiveRequests) {
compatibilityTest_->TestObserverSendReceiveRequests();
}
TEST_F(RSCompatibilityTest, ConnectionContext) {
compatibilityTest_->TestConnectionContext();
}
TEST_F(RSCompatibilityTest, ClientIdentityHook) {
compatibilityTest_->TestClientIdentityHook();
}
/**
* This is a test class with customized RoutingHandler. The main purpose is to
* set compression on the server-side and test the behavior.
*/
class RSCompatibilityTest2 : public testing::Test {
class TestRoutingHandler : public RSRoutingHandler {
public:
TestRoutingHandler() = default;
TestRoutingHandler(const TestRoutingHandler&) = delete;
TestRoutingHandler& operator=(const TestRoutingHandler&) = delete;
void handleConnection(
wangle::ConnectionManager* connectionManager,
folly::AsyncTransportWrapper::UniquePtr sock,
folly::SocketAddress const* address,
wangle::TransportInfo const& /*tinfo*/,
std::shared_ptr<Cpp2Worker> worker) override {
auto sockPtr = sock.get();
auto* const server = worker->getServer();
auto* const connection = new rocket::RocketServerConnection(
std::move(sock),
std::make_shared<rocket::ThriftRocketServerHandler>(
worker, *address, sockPtr, setupFrameHandlers),
server->getStreamExpireTime());
connection->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
connection->setMinCompressBytes(server->getMinCompressBytes());
connectionManager->addConnection(connection);
if (auto* observer = server->getObserver()) {
observer->connAccepted();
observer->activeConnections(
connectionManager->getNumConnections() *
server->getNumIOWorkerThreads());
}
}
private:
std::vector<std::unique_ptr<rocket::SetupFrameHandler>> setupFrameHandlers;
};
public:
RSCompatibilityTest2() {
FLAGS_transport = "rocket";
compatibilityTest_ = std::make_unique<TransportCompatibilityTest>();
compatibilityTest_->addRoutingHandler(
std::make_unique<TestRoutingHandler>());
compatibilityTest_->startServer();
}
protected:
std::unique_ptr<TransportCompatibilityTest> compatibilityTest_;
};
TEST_F(RSCompatibilityTest2, RequestResponse_CompressRequestResponse) {
compatibilityTest_->connectToServer([this](auto client) {
EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));
auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
ASSERT_NE(nullptr, channel);
// set the channel to compress requests
channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
channel->setAutoCompressSizeLimit(0);
std::string name("snoopy");
auto result =
client->future_hello(RpcOptions().setEnableChecksum(true), name).get();
EXPECT_EQ("Hello, snoopy", result);
});
}
} // namespace thrift
} // namespace apache
<commit_msg>clean up unused bool for rocket tests<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/GFlags.h>
#include <folly/portability/GTest.h>
#include <thrift/lib/cpp2/async/RocketClientChannel.h>
#include <thrift/lib/cpp2/server/Cpp2Worker.h>
#include <thrift/lib/cpp2/transport/core/testutil/MockCallback.h>
#include <thrift/lib/cpp2/transport/core/testutil/TransportCompatibilityTest.h>
#include <thrift/lib/cpp2/transport/rocket/server/RocketServerConnection.h>
#include <thrift/lib/cpp2/transport/rocket/server/ThriftRocketServerHandler.h>
#include <thrift/lib/cpp2/transport/rsocket/server/RSRoutingHandler.h>
DECLARE_int32(num_client_connections);
DECLARE_string(transport); // ConnectionManager depends on this flag.
namespace apache {
namespace thrift {
using namespace testutil::testservice;
using namespace apache::thrift::transport;
class RSCompatibilityTest : public testing::Test {
public:
RSCompatibilityTest() {
FLAGS_transport = "rocket";
compatibilityTest_ = std::make_unique<TransportCompatibilityTest>();
compatibilityTest_->addRoutingHandler(
std::make_unique<apache::thrift::RSRoutingHandler>());
compatibilityTest_->startServer();
}
protected:
std::unique_ptr<TransportCompatibilityTest> compatibilityTest_;
};
TEST_F(RSCompatibilityTest, RequestResponse_Simple) {
compatibilityTest_->TestRequestResponse_Simple();
}
TEST_F(RSCompatibilityTest, RequestResponse_Sync) {
compatibilityTest_->TestRequestResponse_Sync();
}
TEST_F(RSCompatibilityTest, RequestResponse_Destruction) {
compatibilityTest_->TestRequestResponse_Destruction();
}
TEST_F(RSCompatibilityTest, RequestResponse_MultipleClients) {
compatibilityTest_->TestRequestResponse_MultipleClients();
}
TEST_F(RSCompatibilityTest, RequestResponse_ExpectedException) {
compatibilityTest_->TestRequestResponse_ExpectedException();
}
TEST_F(RSCompatibilityTest, RequestResponse_UnexpectedException) {
compatibilityTest_->TestRequestResponse_UnexpectedException();
}
// Warning: This test may be flaky due to use of timeouts.
TEST_F(RSCompatibilityTest, RequestResponse_Timeout) {
compatibilityTest_->TestRequestResponse_Timeout();
}
TEST_F(RSCompatibilityTest, DefaultTimeoutValueTest) {
compatibilityTest_->connectToServer([](auto client) {
// Opts with no timeout value
RpcOptions opts;
// Ok to sleep for 100msec
auto cb = std::make_unique<MockCallback>(false, false);
client->sleep(opts, std::move(cb), 100);
/* Sleep to give time for all callbacks to be completed */
/* sleep override */
std::this_thread::sleep_for(std::chrono::milliseconds(200));
auto* channel = dynamic_cast<ClientChannel*>(client->getChannel());
EXPECT_TRUE(channel);
channel->getEventBase()->runInEventBaseThreadAndWait([&]() {
channel->setTimeout(1); // 1ms
});
// Now it should timeout
cb = std::make_unique<MockCallback>(false, true);
client->sleep(opts, std::move(cb), 100);
/* Sleep to give time for all callbacks to be completed */
/* sleep override */
std::this_thread::sleep_for(std::chrono::milliseconds(200));
});
}
TEST_F(RSCompatibilityTest, RequestResponse_Header) {
compatibilityTest_->TestRequestResponse_Header();
}
TEST_F(RSCompatibilityTest, RequestResponse_Header_Load) {
compatibilityTest_->TestRequestResponse_Header_Load();
}
TEST_F(RSCompatibilityTest, RequestResponse_Header_ExpectedException) {
compatibilityTest_->TestRequestResponse_Header_ExpectedException();
}
TEST_F(RSCompatibilityTest, RequestResponse_Header_UnexpectedException) {
compatibilityTest_->TestRequestResponse_Header_UnexpectedException();
}
TEST_F(RSCompatibilityTest, RequestResponse_Saturation) {
compatibilityTest_->connectToServer([this](auto client) {
EXPECT_CALL(*compatibilityTest_->handler_.get(), add_(3)).Times(2);
// note that no EXPECT_CALL for add_(5)
auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
ASSERT_NE(nullptr, channel);
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->setMaxPendingRequests(0u); });
EXPECT_THROW(client->future_add(5).get(), TTransportException);
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->setMaxPendingRequests(1u); });
EXPECT_EQ(3, client->future_add(3).get());
EXPECT_EQ(6, client->future_add(3).get());
});
}
TEST_F(RSCompatibilityTest, RequestResponse_Connection_CloseNow) {
compatibilityTest_->TestRequestResponse_Connection_CloseNow();
}
TEST_F(RSCompatibilityTest, RequestResponse_ServerQueueTimeout) {
compatibilityTest_->TestRequestResponse_ServerQueueTimeout();
}
TEST_F(RSCompatibilityTest, RequestResponse_ResponseSizeTooBig) {
compatibilityTest_->TestRequestResponse_ResponseSizeTooBig();
}
TEST_F(RSCompatibilityTest, RequestResponse_Checksumming) {
compatibilityTest_->TestRequestResponse_Checksumming();
}
TEST_F(RSCompatibilityTest, RequestResponse_CompressRequest) {
compatibilityTest_->connectToServer([this](auto client) {
EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));
auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
ASSERT_NE(nullptr, channel);
// set the channel to compress requests
channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
channel->setAutoCompressSizeLimit(0);
std::string name("snoopy");
auto result =
client->future_hello(RpcOptions().setEnableChecksum(true), name).get();
EXPECT_EQ("Hello, snoopy", result);
});
}
TEST_F(RSCompatibilityTest, Oneway_Simple) {
compatibilityTest_->TestOneway_Simple();
}
TEST_F(RSCompatibilityTest, Oneway_WithDelay) {
compatibilityTest_->TestOneway_WithDelay();
}
TEST_F(RSCompatibilityTest, Oneway_Saturation) {
compatibilityTest_->connectToServer([this](auto client) {
EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(100, 5));
EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(50, 5));
if (auto* channel =
dynamic_cast<RocketClientChannel*>(client->getChannel())) {
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->setMaxPendingRequests(0u); });
EXPECT_THROW(
client->future_addAfterDelay(0, 5).get(), TTransportException);
// the first call is not completed as the connection was saturated
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->setMaxPendingRequests(1u); });
} else {
FAIL() << "Test run with unexpected channel type";
}
// Client should be able to issue both of these functions as
// SINGLE_REQUEST_NO_RESPONSE doesn't need to wait for server response
client->future_addAfterDelay(100, 5).get();
client->future_addAfterDelay(50, 5).get(); // TODO: H2 fails in this call.
});
}
TEST_F(RSCompatibilityTest, Oneway_UnexpectedException) {
compatibilityTest_->TestOneway_UnexpectedException();
}
TEST_F(RSCompatibilityTest, Oneway_Connection_CloseNow) {
compatibilityTest_->TestOneway_Connection_CloseNow();
}
TEST_F(RSCompatibilityTest, Oneway_ServerQueueTimeout) {
compatibilityTest_->TestOneway_ServerQueueTimeout();
}
TEST_F(RSCompatibilityTest, Oneway_Checksumming) {
compatibilityTest_->TestOneway_Checksumming();
}
TEST_F(RSCompatibilityTest, RequestContextIsPreserved) {
compatibilityTest_->TestRequestContextIsPreserved();
}
TEST_F(RSCompatibilityTest, BadPayload) {
compatibilityTest_->TestBadPayload();
}
TEST_F(RSCompatibilityTest, EvbSwitch) {
compatibilityTest_->TestEvbSwitch();
}
TEST_F(RSCompatibilityTest, EvbSwitch_Failure) {
compatibilityTest_->TestEvbSwitch_Failure();
}
TEST_F(RSCompatibilityTest, CloseCallback) {
compatibilityTest_->TestCloseCallback();
}
TEST_F(RSCompatibilityTest, ConnectionStats) {
compatibilityTest_->TestConnectionStats();
}
TEST_F(RSCompatibilityTest, ObserverSendReceiveRequests) {
compatibilityTest_->TestObserverSendReceiveRequests();
}
TEST_F(RSCompatibilityTest, ConnectionContext) {
compatibilityTest_->TestConnectionContext();
}
TEST_F(RSCompatibilityTest, ClientIdentityHook) {
compatibilityTest_->TestClientIdentityHook();
}
/**
* This is a test class with customized RoutingHandler. The main purpose is to
* set compression on the server-side and test the behavior.
*/
class RSCompatibilityTest2 : public testing::Test {
class TestRoutingHandler : public RSRoutingHandler {
public:
TestRoutingHandler() = default;
TestRoutingHandler(const TestRoutingHandler&) = delete;
TestRoutingHandler& operator=(const TestRoutingHandler&) = delete;
void handleConnection(
wangle::ConnectionManager* connectionManager,
folly::AsyncTransportWrapper::UniquePtr sock,
folly::SocketAddress const* address,
wangle::TransportInfo const& /*tinfo*/,
std::shared_ptr<Cpp2Worker> worker) override {
auto sockPtr = sock.get();
auto* const server = worker->getServer();
auto* const connection = new rocket::RocketServerConnection(
std::move(sock),
std::make_shared<rocket::ThriftRocketServerHandler>(
worker, *address, sockPtr, setupFrameHandlers),
server->getStreamExpireTime());
connection->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
connection->setMinCompressBytes(server->getMinCompressBytes());
connectionManager->addConnection(connection);
if (auto* observer = server->getObserver()) {
observer->connAccepted();
observer->activeConnections(
connectionManager->getNumConnections() *
server->getNumIOWorkerThreads());
}
}
private:
std::vector<std::unique_ptr<rocket::SetupFrameHandler>> setupFrameHandlers;
};
public:
RSCompatibilityTest2() {
FLAGS_transport = "rocket";
compatibilityTest_ = std::make_unique<TransportCompatibilityTest>();
compatibilityTest_->addRoutingHandler(
std::make_unique<TestRoutingHandler>());
compatibilityTest_->startServer();
}
protected:
std::unique_ptr<TransportCompatibilityTest> compatibilityTest_;
};
TEST_F(RSCompatibilityTest2, RequestResponse_CompressRequestResponse) {
compatibilityTest_->connectToServer([this](auto client) {
EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));
auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
ASSERT_NE(nullptr, channel);
// set the channel to compress requests
channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
channel->setAutoCompressSizeLimit(0);
std::string name("snoopy");
auto result =
client->future_hello(RpcOptions().setEnableChecksum(true), name).get();
EXPECT_EQ("Hello, snoopy", result);
});
}
} // namespace thrift
} // namespace apache
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.