text
stringlengths 54
60.6k
|
---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: contimp.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:56:01 $
*
* 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 _CONTIMP_HXX_
#define _CONTIMP_HXX_
#ifndef _CONTDLG_HXX
#include <svx/contdlg.hxx>
#endif
#ifndef _CONTWND_HXX
#include "contwnd.hxx"
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_STATUS_HXX
#include <vcl/status.hxx>
#endif
#define CONT_RESID(nId) ResId( nId, DIALOG_MGR() )
/*************************************************************************
|*
|*
|*
\************************************************************************/
class SvxSuperContourDlg : public SvxContourDlg
{
using SvxContourDlg::GetPolyPolygon;
Graphic aGraphic;
Graphic aUndoGraphic;
Graphic aRedoGraphic;
Graphic aUpdateGraphic;
PolyPolygon aUpdatePolyPoly;
Timer aUpdateTimer;
Timer aCreateTimer;
Size aLastSize;
void* pUpdateEditingObject;
void* pCheckObj;
SvxContourDlgItem aContourItem;
ToolBox aTbx1;
MetricField aMtfTolerance;
ContourWindow aContourWnd;
StatusBar aStbStatus;
ULONG nGrfChanged;
BOOL bExecState;
BOOL bPipetteMode;
BOOL bWorkplaceMode;
BOOL bUpdateGraphicLinked;
BOOL bGraphicLinked;
ImageList maImageList;
ImageList maImageListH;
virtual void Resize();
virtual BOOL Close();
void DoAutoCreate();
void ReducePoints( const long nTol = 8 );
DECL_LINK( Tbx1ClickHdl, ToolBox* );
DECL_LINK( MousePosHdl, ContourWindow* );
DECL_LINK( GraphSizeHdl, ContourWindow* );
DECL_LINK( UpdateHdl, Timer* );
DECL_LINK( CreateHdl, Timer* );
DECL_LINK( StateHdl, ContourWindow* );
DECL_LINK( PipetteHdl, ContourWindow* );
DECL_LINK( PipetteClickHdl, ContourWindow* );
DECL_LINK( WorkplaceClickHdl, ContourWindow* );
DECL_LINK( MiscHdl, void* );
public:
SvxSuperContourDlg( SfxBindings *pBindings, SfxChildWindow *pCW,
Window* pParent, const ResId& rResId );
~SvxSuperContourDlg();
void SetExecState( BOOL bEnable );
void SetGraphic( const Graphic& rGraphic );
void SetGraphicLinked( BOOL bLinked ) { bGraphicLinked = bLinked; }
const Graphic& GetGraphic() const { return aGraphic; }
BOOL IsGraphicChanged() const { return nGrfChanged > 0UL; }
void SetPolyPolygon( const PolyPolygon& rPolyPoly );
PolyPolygon GetPolyPolygon( BOOL bRescaleToGraphic = TRUE );
void SetEditingObject( void* pObj ) { pCheckObj = pObj; }
const void* GetEditingObject() const { return pCheckObj; }
BOOL IsUndoPossible() const;
BOOL IsRedoPossible() const;
void UpdateGraphic( const Graphic& rGraphic, BOOL bGraphicLinked,
const PolyPolygon* pPolyPoly = NULL,
void* pEditingObj = NULL );
/** switches the toolbox images depending on the actuall high contrast display mode state */
void ApplyImageList();
/** virtual method from Window is used to detect change in high contrast display mode
to switch the toolbox images */
virtual void DataChanged( const DataChangedEvent& rDCEvt );
};
#endif // _CONTIMP_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.6.368); FILE MERGED 2008/04/01 15:50:15 thb 1.6.368.3: #i85898# Stripping all external header guards 2008/04/01 12:48:08 thb 1.6.368.2: #i85898# Stripping all external header guards 2008/03/31 14:19:21 rt 1.6.368.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: contimp.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CONTIMP_HXX_
#define _CONTIMP_HXX_
#ifndef _CONTDLG_HXX
#include <svx/contdlg.hxx>
#endif
#include "contwnd.hxx"
#include <vcl/toolbox.hxx>
#include <vcl/status.hxx>
#define CONT_RESID(nId) ResId( nId, DIALOG_MGR() )
/*************************************************************************
|*
|*
|*
\************************************************************************/
class SvxSuperContourDlg : public SvxContourDlg
{
using SvxContourDlg::GetPolyPolygon;
Graphic aGraphic;
Graphic aUndoGraphic;
Graphic aRedoGraphic;
Graphic aUpdateGraphic;
PolyPolygon aUpdatePolyPoly;
Timer aUpdateTimer;
Timer aCreateTimer;
Size aLastSize;
void* pUpdateEditingObject;
void* pCheckObj;
SvxContourDlgItem aContourItem;
ToolBox aTbx1;
MetricField aMtfTolerance;
ContourWindow aContourWnd;
StatusBar aStbStatus;
ULONG nGrfChanged;
BOOL bExecState;
BOOL bPipetteMode;
BOOL bWorkplaceMode;
BOOL bUpdateGraphicLinked;
BOOL bGraphicLinked;
ImageList maImageList;
ImageList maImageListH;
virtual void Resize();
virtual BOOL Close();
void DoAutoCreate();
void ReducePoints( const long nTol = 8 );
DECL_LINK( Tbx1ClickHdl, ToolBox* );
DECL_LINK( MousePosHdl, ContourWindow* );
DECL_LINK( GraphSizeHdl, ContourWindow* );
DECL_LINK( UpdateHdl, Timer* );
DECL_LINK( CreateHdl, Timer* );
DECL_LINK( StateHdl, ContourWindow* );
DECL_LINK( PipetteHdl, ContourWindow* );
DECL_LINK( PipetteClickHdl, ContourWindow* );
DECL_LINK( WorkplaceClickHdl, ContourWindow* );
DECL_LINK( MiscHdl, void* );
public:
SvxSuperContourDlg( SfxBindings *pBindings, SfxChildWindow *pCW,
Window* pParent, const ResId& rResId );
~SvxSuperContourDlg();
void SetExecState( BOOL bEnable );
void SetGraphic( const Graphic& rGraphic );
void SetGraphicLinked( BOOL bLinked ) { bGraphicLinked = bLinked; }
const Graphic& GetGraphic() const { return aGraphic; }
BOOL IsGraphicChanged() const { return nGrfChanged > 0UL; }
void SetPolyPolygon( const PolyPolygon& rPolyPoly );
PolyPolygon GetPolyPolygon( BOOL bRescaleToGraphic = TRUE );
void SetEditingObject( void* pObj ) { pCheckObj = pObj; }
const void* GetEditingObject() const { return pCheckObj; }
BOOL IsUndoPossible() const;
BOOL IsRedoPossible() const;
void UpdateGraphic( const Graphic& rGraphic, BOOL bGraphicLinked,
const PolyPolygon* pPolyPoly = NULL,
void* pEditingObj = NULL );
/** switches the toolbox images depending on the actuall high contrast display mode state */
void ApplyImageList();
/** virtual method from Window is used to detect change in high contrast display mode
to switch the toolbox images */
virtual void DataChanged( const DataChangedEvent& rDCEvt );
};
#endif // _CONTIMP_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: treeopt.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2004-02-03 19:00:55 $
*
* 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 _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SVTREEBOX_HXX //autogen
#include <svtools/svtreebx.hxx>
#endif
#ifndef _TOOLS_RESARY_HXX
#include <tools/resary.hxx>
#endif
#ifndef _SV_IMAGE_HXX //autogen
#include <vcl/image.hxx>
#endif
#ifndef _SV_FIXBRD_HXX //autogen
#include <vcl/fixbrd.hxx>
#endif
#define NUMBER_OF_OPTION_PAGES 12
class SfxModule;
class SfxShell;
struct OptionsPageInfo;
class OfaOptionsTreeListBox : public SvTreeListBox
{
private:
BOOL bInCollapse;
public:
OfaOptionsTreeListBox(Window* pParent, const ResId& rResId) :
SvTreeListBox( pParent, rResId ), bInCollapse(FALSE) {}
virtual BOOL Collapse( SvLBoxEntry* pParent );
BOOL IsInCollapse()const {return bInCollapse;}
};
BOOL EnableSSO();
void* GetSSOCreator( void );
/* -----------------11.02.99 07:51-------------------
*
* --------------------------------------------------*/
class OfaTreeOptionsDialog : public SfxModalDialog
{
private:
OKButton aOkPB;
CancelButton aCancelPB;
HelpButton aHelpPB;
PushButton aBackPB;
FixedBorder aHiddenGB;
FixedText aPageTitleFT;
FixedLine aLine1FL;
FixedText aHelpFT;
FixedImage aHelpImg;
ImageList aPageImages;
ImageList aPageImagesHC;
ResStringArray aHelpTextsArr;
OfaOptionsTreeListBox aTreeLB;
String sTitle;
String sHintTitle;
String sNotLoadedError;
const OptionsPageInfo* pHintInfo;
SvLBoxEntry* pCurrentPageEntry;
// for the ColorTabPage
SfxItemSet* pColorPageItemSet;
XColorTable* pColorTab;
USHORT nChangeType;
USHORT nUnknownType;
USHORT nUnknownPos;
BOOL bIsAreaTP;
BOOL bForgetSelection;
BOOL bExternBrowserActive;
BOOL bImageResized;
bool bInSelectHdl_Impl;
Timer aHintTimer;
Timer aSelectTimer;
static USHORT nLastDialogPageId;
void StartHint( const OptionsPageInfo* pInfo, const XubString& rTitle );
void ShowHint();
SfxItemSet* CreateItemSet( USHORT nId );
void ApplyItemSet( USHORT nId, const SfxItemSet& rSet );
void Initialize();
protected:
DECL_LINK(ExpandedHdl_Impl, SvTreeListBox* );
DECL_LINK(ShowPageHdl_Impl, SvTreeListBox* );
DECL_LINK(BackHdl_Impl, PushButton* );
DECL_LINK( OKHdl_Impl, Button * );
DECL_LINK( HintHdl_Impl, Timer * );
DECL_LINK( SelectHdl_Impl, Timer * );
virtual long Notify( NotifyEvent& rNEvt );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual short Execute();
public:
OfaTreeOptionsDialog(Window* pParent);
~OfaTreeOptionsDialog();
void AddTabPage( USHORT nId, const String& rPageName, USHORT nGroup);
USHORT AddGroup(const String& rGroupName, SfxShell* pCreateShell,
SfxModule* pCreateModule, USHORT nDialogId);
void ActivateLastSelection();
void ActivatePage(USHORT nResId);
void ApplyItemSets();
USHORT GetColorChanged() const { return nChangeType; }
XColorTable* GetColorTable() { return pColorTab; }
};
/* -----------------11.02.99 15:49-------------------
*
* --------------------------------------------------*/
class OfaPageResource : public Resource
{
ResStringArray aGeneralDlgAry;
ResStringArray aInetDlgAry;
ResStringArray aLangDlgAry;
ResStringArray aTextDlgAry;
ResStringArray aHTMLDlgAry;
ResStringArray aCalcDlgAry;
ResStringArray aStarMathDlgAry;
ResStringArray aImpressDlgAry;
ResStringArray aDrawDlgAry;
ResStringArray aChartDlgAry;
ResStringArray aFilterDlgAry;
ResStringArray aDatasourcesDlgAry;
public:
OfaPageResource();
ResStringArray& GetGeneralArray() {return aGeneralDlgAry;}
ResStringArray& GetInetArray() {return aInetDlgAry;}
ResStringArray& GetLangArray() {return aLangDlgAry;}
ResStringArray& GetTextArray() {return aTextDlgAry;}
ResStringArray& GetHTMLArray() {return aHTMLDlgAry;}
ResStringArray& GetCalcArray() {return aCalcDlgAry;}
ResStringArray& GetStarMathArray() {return aStarMathDlgAry;}
ResStringArray& GetImpressArray() {return aImpressDlgAry;}
ResStringArray& GetDrawArray() {return aDrawDlgAry;}
ResStringArray& GetChartArray() {return aChartDlgAry;}
ResStringArray& GetFilterArray() {return aFilterDlgAry;}
ResStringArray& GetDatasourcesArray() {return aDatasourcesDlgAry;}
};
<commit_msg>INTEGRATION: CWS gt06 (1.2.122); FILE MERGED 2004/03/31 07:40:42 gt 1.2.122.1: #i27168# dynamic size of treelistbox<commit_after>/*************************************************************************
*
* $RCSfile: treeopt.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: svesik $ $Date: 2004-04-19 22:05:05 $
*
* 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 _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SVTREEBOX_HXX //autogen
#include <svtools/svtreebx.hxx>
#endif
#ifndef _TOOLS_RESARY_HXX
#include <tools/resary.hxx>
#endif
#ifndef _SV_IMAGE_HXX //autogen
#include <vcl/image.hxx>
#endif
#ifndef _SV_FIXBRD_HXX //autogen
#include <vcl/fixbrd.hxx>
#endif
#define NUMBER_OF_OPTION_PAGES 12
class SfxModule;
class SfxShell;
struct OptionsPageInfo;
class OfaOptionsTreeListBox : public SvTreeListBox
{
private:
BOOL bInCollapse;
public:
OfaOptionsTreeListBox(Window* pParent, const ResId& rResId) :
SvTreeListBox( pParent, rResId ), bInCollapse(FALSE) {}
virtual BOOL Collapse( SvLBoxEntry* pParent );
BOOL IsInCollapse()const {return bInCollapse;}
};
BOOL EnableSSO();
void* GetSSOCreator( void );
/* -----------------11.02.99 07:51-------------------
*
* --------------------------------------------------*/
class OfaTreeOptionsDialog : public SfxModalDialog
{
private:
OKButton aOkPB;
CancelButton aCancelPB;
HelpButton aHelpPB;
PushButton aBackPB;
FixedBorder aHiddenGB;
FixedText aPageTitleFT;
FixedLine aLine1FL;
FixedText aHelpFT;
FixedImage aHelpImg;
ImageList aPageImages;
ImageList aPageImagesHC;
ResStringArray aHelpTextsArr;
OfaOptionsTreeListBox aTreeLB;
String sTitle;
String sHintTitle;
String sNotLoadedError;
const OptionsPageInfo* pHintInfo;
SvLBoxEntry* pCurrentPageEntry;
// for the ColorTabPage
SfxItemSet* pColorPageItemSet;
XColorTable* pColorTab;
USHORT nChangeType;
USHORT nUnknownType;
USHORT nUnknownPos;
BOOL bIsAreaTP;
BOOL bForgetSelection;
BOOL bExternBrowserActive;
BOOL bImageResized;
bool bInSelectHdl_Impl;
Timer aHintTimer;
Timer aSelectTimer;
static USHORT nLastDialogPageId;
void StartHint( const OptionsPageInfo* pInfo, const XubString& rTitle );
void ShowHint();
SfxItemSet* CreateItemSet( USHORT nId );
void ApplyItemSet( USHORT nId, const SfxItemSet& rSet );
void Initialize();
void ResizeTreeLB( void ); // resizes dialog so that treelistbox has no horizontal scroll bar
protected:
DECL_LINK(ExpandedHdl_Impl, SvTreeListBox* );
DECL_LINK(ShowPageHdl_Impl, SvTreeListBox* );
DECL_LINK(BackHdl_Impl, PushButton* );
DECL_LINK( OKHdl_Impl, Button * );
DECL_LINK( HintHdl_Impl, Timer * );
DECL_LINK( SelectHdl_Impl, Timer * );
virtual long Notify( NotifyEvent& rNEvt );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual short Execute();
public:
OfaTreeOptionsDialog(Window* pParent);
~OfaTreeOptionsDialog();
void AddTabPage( USHORT nId, const String& rPageName, USHORT nGroup);
USHORT AddGroup(const String& rGroupName, SfxShell* pCreateShell,
SfxModule* pCreateModule, USHORT nDialogId);
void ActivateLastSelection();
void ActivatePage(USHORT nResId);
void ApplyItemSets();
USHORT GetColorChanged() const { return nChangeType; }
XColorTable* GetColorTable() { return pColorTab; }
};
/* -----------------11.02.99 15:49-------------------
*
* --------------------------------------------------*/
class OfaPageResource : public Resource
{
ResStringArray aGeneralDlgAry;
ResStringArray aInetDlgAry;
ResStringArray aLangDlgAry;
ResStringArray aTextDlgAry;
ResStringArray aHTMLDlgAry;
ResStringArray aCalcDlgAry;
ResStringArray aStarMathDlgAry;
ResStringArray aImpressDlgAry;
ResStringArray aDrawDlgAry;
ResStringArray aChartDlgAry;
ResStringArray aFilterDlgAry;
ResStringArray aDatasourcesDlgAry;
public:
OfaPageResource();
ResStringArray& GetGeneralArray() {return aGeneralDlgAry;}
ResStringArray& GetInetArray() {return aInetDlgAry;}
ResStringArray& GetLangArray() {return aLangDlgAry;}
ResStringArray& GetTextArray() {return aTextDlgAry;}
ResStringArray& GetHTMLArray() {return aHTMLDlgAry;}
ResStringArray& GetCalcArray() {return aCalcDlgAry;}
ResStringArray& GetStarMathArray() {return aStarMathDlgAry;}
ResStringArray& GetImpressArray() {return aImpressDlgAry;}
ResStringArray& GetDrawArray() {return aDrawDlgAry;}
ResStringArray& GetChartArray() {return aChartDlgAry;}
ResStringArray& GetFilterArray() {return aFilterDlgAry;}
ResStringArray& GetDatasourcesArray() {return aDatasourcesDlgAry;}
};
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: zoomitem.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-10-12 12:56:38 $
*
* 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_svx.hxx"
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef __SBX_SBXVARIABLE_HXX
#include <basic/sbxvar.hxx>
#endif
#include "zoomitem.hxx"
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
// -----------------------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SvxZoomItem,SfxUInt16Item);
#define ZOOM_PARAM_VALUE "Value"
#define ZOOM_PARAM_VALUESET "ValueSet"
#define ZOOM_PARAM_TYPE "Type"
#define ZOOM_PARAMS 3
// -----------------------------------------------------------------------
SvxZoomItem::SvxZoomItem
(
SvxZoomType eZoomType,
sal_uInt16 nVal,
sal_uInt16 _nWhich
)
: SfxUInt16Item( _nWhich, nVal ),
nValueSet( SVX_ZOOM_ENABLE_ALL ),
eType( eZoomType )
{
}
// -----------------------------------------------------------------------
SvxZoomItem::SvxZoomItem( const SvxZoomItem& rOrig )
: SfxUInt16Item( rOrig.Which(), rOrig.GetValue() ),
nValueSet( rOrig.GetValueSet() ),
eType( rOrig.GetType() )
{
}
// -----------------------------------------------------------------------
SvxZoomItem::~SvxZoomItem()
{
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxZoomItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SvxZoomItem( *this );
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxZoomItem::Create( SvStream& rStrm, sal_uInt16 /*nVersion*/ ) const
{
sal_uInt16 nValue;
sal_uInt16 nValSet;
sal_Int8 nType;
rStrm >> nValue >> nValSet >> nType;
SvxZoomItem* pNew = new SvxZoomItem( (SvxZoomType)nType, nValue, Which() );
pNew->SetValueSet( nValSet );
return pNew;
}
// -----------------------------------------------------------------------
SvStream& SvxZoomItem::Store( SvStream& rStrm, sal_uInt16 /*nItemVersion*/ ) const
{
rStrm << (sal_uInt16)GetValue()
<< nValueSet
<< (sal_Int8)eType;
return rStrm;
}
// -----------------------------------------------------------------------
int SvxZoomItem::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );
SvxZoomItem& rItem = (SvxZoomItem&)rAttr;
return ( GetValue() == rItem.GetValue() &&
nValueSet == rItem.GetValueSet() &&
eType == rItem.GetType() );
}
sal_Bool SvxZoomItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
// sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
switch ( nMemberId )
{
case 0 :
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq( ZOOM_PARAMS );
aSeq[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUE ));
aSeq[0].Value <<= sal_Int32( GetValue() );
aSeq[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUESET ));
aSeq[1].Value <<= sal_Int16( nValueSet );
aSeq[2].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_TYPE ));
aSeq[2].Value <<= sal_Int16( eType );
rVal <<= aSeq;
}
break;
case MID_VALUE: rVal <<= (sal_Int32) GetValue(); break;
case MID_VALUESET: rVal <<= (sal_Int16) nValueSet; break;
case MID_TYPE: rVal <<= (sal_Int16) eType; break;
default:
DBG_ERROR("svx::SvxZoomItem::QueryValue(), Wrong MemberId!");
return sal_False;
}
return sal_True;
}
sal_Bool SvxZoomItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
// sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
switch ( nMemberId )
{
case 0 :
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq;
if (( rVal >>= aSeq ) && ( aSeq.getLength() == ZOOM_PARAMS ))
{
sal_Int32 nValueTmp( 0 );
sal_Int16 nValueSetTmp( 0 );
sal_Int16 nTypeTmp( 0 );
sal_Bool bAllConverted( sal_True );
sal_Int16 nConvertedCount( 0 );
for ( sal_Int32 i = 0; i < aSeq.getLength(); i++ )
{
if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUE ))
{
bAllConverted &= ( aSeq[i].Value >>= nValueTmp );
++nConvertedCount;
}
else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUESET ))
{
bAllConverted &= ( aSeq[i].Value >>= nValueSetTmp );
++nConvertedCount;
}
else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_TYPE ))
{
bAllConverted &= ( aSeq[i].Value >>= nTypeTmp );
++nConvertedCount;
}
}
if ( bAllConverted && nConvertedCount == ZOOM_PARAMS )
{
SetValue( (UINT16)nValueTmp );
nValueSet = nValueSetTmp;
eType = SvxZoomType( nTypeTmp );
return sal_True;
}
}
return sal_False;
}
case MID_VALUE:
{
sal_Int32 nVal;
if ( rVal >>= nVal )
{
SetValue( (UINT16)nVal );
return sal_True;
}
else
return sal_False;
}
case MID_VALUESET:
case MID_TYPE:
{
sal_Int16 nVal = sal_Int16();
if ( rVal >>= nVal )
{
if ( nMemberId == MID_VALUESET )
nValueSet = (sal_Int16) nVal;
else if ( nMemberId == MID_TYPE )
eType = SvxZoomType( (sal_Int16) nVal );
return sal_True;
}
else
return sal_False;
}
default:
DBG_ERROR("svx::SvxZoomItem::PutValue(), Wrong MemberId!");
return sal_False;
}
return sal_True;
}
<commit_msg>INTEGRATION: CWS pj65 (1.9.50); FILE MERGED 2006/11/06 11:14:26 pjanik 1.9.50.1: #i71027#: Prevent warnings on Mac OS X.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: zoomitem.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: vg $ $Date: 2006-11-21 17:11:50 $
*
* 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_svx.hxx"
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef __SBX_SBXVARIABLE_HXX
#include <basic/sbxvar.hxx>
#endif
#include "zoomitem.hxx"
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
// -----------------------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SvxZoomItem,SfxUInt16Item);
#define ZOOM_PARAM_VALUE "Value"
#define ZOOM_PARAM_VALUESET "ValueSet"
#define ZOOM_PARAM_TYPE "Type"
#define ZOOM_PARAMS 3
// -----------------------------------------------------------------------
SvxZoomItem::SvxZoomItem
(
SvxZoomType eZoomType,
sal_uInt16 nVal,
sal_uInt16 _nWhich
)
: SfxUInt16Item( _nWhich, nVal ),
nValueSet( SVX_ZOOM_ENABLE_ALL ),
eType( eZoomType )
{
}
// -----------------------------------------------------------------------
SvxZoomItem::SvxZoomItem( const SvxZoomItem& rOrig )
: SfxUInt16Item( rOrig.Which(), rOrig.GetValue() ),
nValueSet( rOrig.GetValueSet() ),
eType( rOrig.GetType() )
{
}
// -----------------------------------------------------------------------
SvxZoomItem::~SvxZoomItem()
{
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxZoomItem::Clone( SfxItemPool * /*pPool*/ ) const
{
return new SvxZoomItem( *this );
}
// -----------------------------------------------------------------------
SfxPoolItem* SvxZoomItem::Create( SvStream& rStrm, sal_uInt16 /*nVersion*/ ) const
{
sal_uInt16 nValue;
sal_uInt16 nValSet;
sal_Int8 nType;
rStrm >> nValue >> nValSet >> nType;
SvxZoomItem* pNew = new SvxZoomItem( (SvxZoomType)nType, nValue, Which() );
pNew->SetValueSet( nValSet );
return pNew;
}
// -----------------------------------------------------------------------
SvStream& SvxZoomItem::Store( SvStream& rStrm, sal_uInt16 /*nItemVersion*/ ) const
{
rStrm << (sal_uInt16)GetValue()
<< nValueSet
<< (sal_Int8)eType;
return rStrm;
}
// -----------------------------------------------------------------------
int SvxZoomItem::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );
SvxZoomItem& rItem = (SvxZoomItem&)rAttr;
return ( GetValue() == rItem.GetValue() &&
nValueSet == rItem.GetValueSet() &&
eType == rItem.GetType() );
}
sal_Bool SvxZoomItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
// sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
switch ( nMemberId )
{
case 0 :
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq( ZOOM_PARAMS );
aSeq[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUE ));
aSeq[0].Value <<= sal_Int32( GetValue() );
aSeq[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUESET ));
aSeq[1].Value <<= sal_Int16( nValueSet );
aSeq[2].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_TYPE ));
aSeq[2].Value <<= sal_Int16( eType );
rVal <<= aSeq;
}
break;
case MID_VALUE: rVal <<= (sal_Int32) GetValue(); break;
case MID_VALUESET: rVal <<= (sal_Int16) nValueSet; break;
case MID_TYPE: rVal <<= (sal_Int16) eType; break;
default:
DBG_ERROR("svx::SvxZoomItem::QueryValue(), Wrong MemberId!");
return sal_False;
}
return sal_True;
}
sal_Bool SvxZoomItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
// sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
switch ( nMemberId )
{
case 0 :
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq;
if (( rVal >>= aSeq ) && ( aSeq.getLength() == ZOOM_PARAMS ))
{
sal_Int32 nValueTmp( 0 );
sal_Int16 nValueSetTmp( 0 );
sal_Int16 nTypeTmp( 0 );
sal_Bool bAllConverted( sal_True );
sal_Int16 nConvertedCount( 0 );
for ( sal_Int32 i = 0; i < aSeq.getLength(); i++ )
{
if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUE ))
{
bAllConverted &= ( aSeq[i].Value >>= nValueTmp );
++nConvertedCount;
}
else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUESET ))
{
bAllConverted &= ( aSeq[i].Value >>= nValueSetTmp );
++nConvertedCount;
}
else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_TYPE ))
{
bAllConverted &= ( aSeq[i].Value >>= nTypeTmp );
++nConvertedCount;
}
}
if ( bAllConverted && nConvertedCount == ZOOM_PARAMS )
{
SetValue( (UINT16)nValueTmp );
nValueSet = nValueSetTmp;
eType = SvxZoomType( nTypeTmp );
return sal_True;
}
}
return sal_False;
}
case MID_VALUE:
{
sal_Int32 nVal = 0;
if ( rVal >>= nVal )
{
SetValue( (UINT16)nVal );
return sal_True;
}
else
return sal_False;
}
case MID_VALUESET:
case MID_TYPE:
{
sal_Int16 nVal = sal_Int16();
if ( rVal >>= nVal )
{
if ( nMemberId == MID_VALUESET )
nValueSet = (sal_Int16) nVal;
else if ( nMemberId == MID_TYPE )
eType = SvxZoomType( (sal_Int16) nVal );
return sal_True;
}
else
return sal_False;
}
default:
DBG_ERROR("svx::SvxZoomItem::PutValue(), Wrong MemberId!");
return sal_False;
}
return sal_True;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: edfmt.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2008-03-05 16:58:36 $
*
* 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_sw.hxx"
#include "doc.hxx"
#include "editsh.hxx"
#include "swtable.hxx"
#include "pam.hxx"
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _FCHRFMT_HXX //autogen
#include <fchrfmt.hxx>
#endif
#ifndef _FRMFMT_HXX //autogen
#include <frmfmt.hxx>
#endif
#ifndef _CHARFMT_HXX //autogen
#include <charfmt.hxx>
#endif
#include "ndtxt.hxx" // Fuer GetXXXFmt
#include "hints.hxx"
/*************************************
* Formate
*************************************/
// Char
// OPT: inline
USHORT SwEditShell::GetCharFmtCount() const
{
return GetDoc()->GetCharFmts()->Count();
}
SwCharFmt& SwEditShell::GetCharFmt(USHORT nFmt) const
{
return *((*(GetDoc()->GetCharFmts()))[nFmt]);
}
SwCharFmt* SwEditShell::GetCurCharFmt() const
{
SwCharFmt *pFmt = 0;
SfxItemSet aSet( GetDoc()->GetAttrPool(), RES_TXTATR_CHARFMT,
RES_TXTATR_CHARFMT );
const SfxPoolItem* pItem;
if( GetCurAttr( aSet ) && SFX_ITEM_SET ==
aSet.GetItemState( RES_TXTATR_CHARFMT, FALSE, &pItem ) )
pFmt = ((SwFmtCharFmt*)pItem)->GetCharFmt();
return pFmt;
}
void SwEditShell::FillByEx(SwCharFmt* pCharFmt, BOOL bReset)
{
if ( bReset )
{
// --> OD 2007-01-25 #i73790# - method renamed
pCharFmt->ResetAllFmtAttr();
// <--
}
SwPaM* pPam = GetCrsr();
const SwCntntNode* pCNd = pPam->GetCntntNode();
if( pCNd->IsTxtNode() )
{
xub_StrLen nStt, nEnd;
if( pPam->HasMark() )
{
const SwPosition* pPtPos = pPam->GetPoint();
const SwPosition* pMkPos = pPam->GetMark();
if( pPtPos->nNode == pMkPos->nNode ) // im selben Node ?
{
nStt = pPtPos->nContent.GetIndex();
if( nStt < pMkPos->nContent.GetIndex() )
nEnd = pMkPos->nContent.GetIndex();
else
{
nEnd = nStt;
nStt = pMkPos->nContent.GetIndex();
}
}
else
{
nStt = pMkPos->nContent.GetIndex();
if( pPtPos->nNode < pMkPos->nNode )
{
nEnd = nStt;
nStt = 0;
}
else
nEnd = ((SwTxtNode*)pCNd)->GetTxt().Len();
}
}
else
nStt = nEnd = pPam->GetPoint()->nContent.GetIndex();
SfxItemSet aSet( pDoc->GetAttrPool(),
pCharFmt->GetAttrSet().GetRanges() );
((SwTxtNode*)pCNd)->GetAttr( aSet, nStt, nEnd );
pCharFmt->SetAttr( aSet );
}
else if( pCNd->HasSwAttrSet() )
pCharFmt->SetAttr( *pCNd->GetpSwAttrSet() );
}
// Frm
USHORT SwEditShell::GetTblFrmFmtCount(BOOL bUsed) const
{
return GetDoc()->GetTblFrmFmtCount(bUsed);
}
SwFrmFmt& SwEditShell::GetTblFrmFmt(USHORT nFmt, BOOL bUsed ) const
{
return GetDoc()->GetTblFrmFmt(nFmt, bUsed );
}
String SwEditShell::GetUniqueTblName() const
{
return GetDoc()->GetUniqueTblName();
}
SwCharFmt* SwEditShell::MakeCharFmt( const String& rName,
SwCharFmt* pDerivedFrom )
{
if( !pDerivedFrom )
pDerivedFrom = GetDoc()->GetDfltCharFmt();
return GetDoc()->MakeCharFmt( rName, pDerivedFrom );
}
//----------------------------------
// inlines im Product
SwTxtFmtColl* SwEditShell::GetTxtCollFromPool( USHORT nId )
{
return GetDoc()->GetTxtCollFromPool( nId );
}
// return das geforderte automatische Format - Basis-Klasse !
SwFmt* SwEditShell::GetFmtFromPool( USHORT nId )
{
return GetDoc()->GetFmtFromPool( nId );
}
SwPageDesc* SwEditShell::GetPageDescFromPool( USHORT nId )
{
return GetDoc()->GetPageDescFromPool( nId );
}
BOOL SwEditShell::IsUsed( const SwModify& rModify ) const
{
return pDoc->IsUsed( rModify );
}
const SwFlyFrmFmt* SwEditShell::FindFlyByName( const String& rName, BYTE nNdTyp ) const
{
return pDoc->FindFlyByName(rName, nNdTyp);
}
SwCharFmt* SwEditShell::FindCharFmtByName( const String& rName ) const
{
return pDoc->FindCharFmtByName( rName );
}
SwTxtFmtColl* SwEditShell::FindTxtFmtCollByName( const String& rName ) const
{
return pDoc->FindTxtFmtCollByName( rName );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.9.36); FILE MERGED 2008/04/01 12:54:03 thb 1.9.36.2: #i85898# Stripping all external header guards 2008/03/31 16:54:03 rt 1.9.36.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: edfmt.cxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include "doc.hxx"
#include "editsh.hxx"
#include "swtable.hxx"
#include "pam.hxx"
#include <docary.hxx>
#include <fchrfmt.hxx>
#include <frmfmt.hxx>
#include <charfmt.hxx>
#include "ndtxt.hxx" // Fuer GetXXXFmt
#include "hints.hxx"
/*************************************
* Formate
*************************************/
// Char
// OPT: inline
USHORT SwEditShell::GetCharFmtCount() const
{
return GetDoc()->GetCharFmts()->Count();
}
SwCharFmt& SwEditShell::GetCharFmt(USHORT nFmt) const
{
return *((*(GetDoc()->GetCharFmts()))[nFmt]);
}
SwCharFmt* SwEditShell::GetCurCharFmt() const
{
SwCharFmt *pFmt = 0;
SfxItemSet aSet( GetDoc()->GetAttrPool(), RES_TXTATR_CHARFMT,
RES_TXTATR_CHARFMT );
const SfxPoolItem* pItem;
if( GetCurAttr( aSet ) && SFX_ITEM_SET ==
aSet.GetItemState( RES_TXTATR_CHARFMT, FALSE, &pItem ) )
pFmt = ((SwFmtCharFmt*)pItem)->GetCharFmt();
return pFmt;
}
void SwEditShell::FillByEx(SwCharFmt* pCharFmt, BOOL bReset)
{
if ( bReset )
{
// --> OD 2007-01-25 #i73790# - method renamed
pCharFmt->ResetAllFmtAttr();
// <--
}
SwPaM* pPam = GetCrsr();
const SwCntntNode* pCNd = pPam->GetCntntNode();
if( pCNd->IsTxtNode() )
{
xub_StrLen nStt, nEnd;
if( pPam->HasMark() )
{
const SwPosition* pPtPos = pPam->GetPoint();
const SwPosition* pMkPos = pPam->GetMark();
if( pPtPos->nNode == pMkPos->nNode ) // im selben Node ?
{
nStt = pPtPos->nContent.GetIndex();
if( nStt < pMkPos->nContent.GetIndex() )
nEnd = pMkPos->nContent.GetIndex();
else
{
nEnd = nStt;
nStt = pMkPos->nContent.GetIndex();
}
}
else
{
nStt = pMkPos->nContent.GetIndex();
if( pPtPos->nNode < pMkPos->nNode )
{
nEnd = nStt;
nStt = 0;
}
else
nEnd = ((SwTxtNode*)pCNd)->GetTxt().Len();
}
}
else
nStt = nEnd = pPam->GetPoint()->nContent.GetIndex();
SfxItemSet aSet( pDoc->GetAttrPool(),
pCharFmt->GetAttrSet().GetRanges() );
((SwTxtNode*)pCNd)->GetAttr( aSet, nStt, nEnd );
pCharFmt->SetAttr( aSet );
}
else if( pCNd->HasSwAttrSet() )
pCharFmt->SetAttr( *pCNd->GetpSwAttrSet() );
}
// Frm
USHORT SwEditShell::GetTblFrmFmtCount(BOOL bUsed) const
{
return GetDoc()->GetTblFrmFmtCount(bUsed);
}
SwFrmFmt& SwEditShell::GetTblFrmFmt(USHORT nFmt, BOOL bUsed ) const
{
return GetDoc()->GetTblFrmFmt(nFmt, bUsed );
}
String SwEditShell::GetUniqueTblName() const
{
return GetDoc()->GetUniqueTblName();
}
SwCharFmt* SwEditShell::MakeCharFmt( const String& rName,
SwCharFmt* pDerivedFrom )
{
if( !pDerivedFrom )
pDerivedFrom = GetDoc()->GetDfltCharFmt();
return GetDoc()->MakeCharFmt( rName, pDerivedFrom );
}
//----------------------------------
// inlines im Product
SwTxtFmtColl* SwEditShell::GetTxtCollFromPool( USHORT nId )
{
return GetDoc()->GetTxtCollFromPool( nId );
}
// return das geforderte automatische Format - Basis-Klasse !
SwFmt* SwEditShell::GetFmtFromPool( USHORT nId )
{
return GetDoc()->GetFmtFromPool( nId );
}
SwPageDesc* SwEditShell::GetPageDescFromPool( USHORT nId )
{
return GetDoc()->GetPageDescFromPool( nId );
}
BOOL SwEditShell::IsUsed( const SwModify& rModify ) const
{
return pDoc->IsUsed( rModify );
}
const SwFlyFrmFmt* SwEditShell::FindFlyByName( const String& rName, BYTE nNdTyp ) const
{
return pDoc->FindFlyByName(rName, nNdTyp);
}
SwCharFmt* SwEditShell::FindCharFmtByName( const String& rName ) const
{
return pDoc->FindCharFmtByName( rName );
}
SwTxtFmtColl* SwEditShell::FindTxtFmtCollByName( const String& rName ) const
{
return pDoc->FindTxtFmtCollByName( rName );
}
<|endoftext|> |
<commit_before>/// \file ThisMfcApp.cpp
/// \brief App object of MFC version of Password Safe
//-----------------------------------------------------------------------------
#include "PasswordSafe.h"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include "ThisMfcApp.h"
#include "Util.h"
#include "DboxMain.h"
#include "resource.h"
#include "CryptKeyEntry.h"
//-----------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(ThisMfcApp, CWinApp)
// ON_COMMAND(ID_HELP, CWinApp::OnHelp)
ON_COMMAND(ID_HELP, OnHelp)
END_MESSAGE_MAP()
ThisMfcApp::ThisMfcApp() :
m_bUseAccelerator( true ),
m_pMRU( NULL )
{
srand((unsigned)time(NULL));
}
ThisMfcApp::~ThisMfcApp()
{
if ( m_pMRU )
{
m_pMRU->WriteList();
delete m_pMRU;
}
/*
apparently, with vc7, there's a CWinApp::HtmlHelp - I'd like
to see the docs, someday. In the meantime, force with :: syntax
*/
::HtmlHelp(NULL, NULL, HH_CLOSE_ALL, 0);
}
static void Usage()
{
AfxMessageBox("Usage: PasswordSafe [password database]\n"
"or PasswordSafe [-e|-d] filename");
}
// tests if file exists, returns empty string if so, displays error message if not
static BOOL CheckFile(const CString &fn)
{
DWORD status = ::GetFileAttributes(fn);
CString ErrMess;
if (status == -1) {
ErrMess = _T("Could not access file: ");
ErrMess += fn;
} else if (status & FILE_ATTRIBUTE_DIRECTORY) {
ErrMess = fn;
ErrMess += _T(" is a directory");
}
if (ErrMess.IsEmpty()) {
return TRUE;
} else {
AfxMessageBox(ErrMess);
return FALSE;
}
}
//Complain if the file has not opened correctly
static void
ErrorMessages(const CString &fn, int fp)
{
if (fp==-1)
{
CString text;
text = "A fatal error occured: ";
if (errno==EACCES)
text += "Given path is a directory or file is read-only";
else if (errno==EEXIST)
text += "The filename already exists.";
else if (errno==EINVAL)
text += "Invalid oflag or shflag argument.";
else if (errno==EMFILE)
text += "No more file handles available.";
else if (errno==ENOENT)
text += "File or path not found.";
text += "\nProgram will terminate.";
CString title = "Password Safe - " + fn;
AfxGetMainWnd()->MessageBox(text, title, MB_ICONEXCLAMATION|MB_OK);
}
}
static BOOL EncryptFile(const CString &fn, const CMyString &passwd)
{
unsigned int len;
unsigned char* buf;
int in = _open(fn,
_O_BINARY|_O_RDONLY|_O_SEQUENTIAL,
S_IREAD | _S_IWRITE);
if (in != -1) {
len = _filelength(in);
buf = new unsigned char[len];
_read(in, buf, len);
_close(in);
} else {
ErrorMessages(fn, in);
return FALSE;
}
CString out_fn = fn;
out_fn += CIPHERTEXT_SUFFIX;
int out = _open(out_fn,
_O_BINARY|_O_WRONLY|_O_SEQUENTIAL|_O_TRUNC|_O_CREAT,
_S_IREAD | _S_IWRITE);
if (out != -1) {
unsigned char randstuff[StuffSize];
unsigned char randhash[20]; // HashSize
#ifdef KEEP_FILE_MODE_BWD_COMPAT
_write(out, &len, sizeof(len)); // XXX portability issue!
#else
for (int i=0; i < 8; i++)
randstuff[i] = newrand();
// miserable bug - have to fix this way to avoid breaking existing files
randstuff[8] = randstuff[9] = '\0';
GenRandhash(passwd, randstuff, randhash);
_write(out, randstuff, 8);
_write(out, randhash, 20);
#endif // KEEP_FILE_MODE_BWD_COMPAT
unsigned char thesalt[SaltLength];
for (int x=0;x<SaltLength;x++)
thesalt[x] = newrand();
_write(out, thesalt, SaltLength);
unsigned char ipthing[8];
for (x=0;x<8;x++)
ipthing[x] = newrand();
_write(out, ipthing, 8);
LPCSTR pwd = LPCSTR(passwd);
_writecbc(out, buf, len,
(unsigned char *)pwd, passwd.GetLength(),
thesalt, SaltLength,
ipthing);
_close(out);
} else {
ErrorMessages(out_fn, out);
delete [] buf;
return FALSE;
}
delete[] buf;
return TRUE;
}
static BOOL DecryptFile(const CString &fn, const CMyString &passwd)
{
unsigned int len;
unsigned char* buf;
int in = _open(fn,
_O_BINARY|_O_RDONLY|_O_SEQUENTIAL,
S_IREAD | _S_IWRITE);
if (in != -1) {
unsigned char randstuff[StuffSize];
unsigned char randhash[20]; // HashSize
unsigned char salt[SaltLength];
unsigned char ipthing[8];
#ifdef KEEP_FILE_MODE_BWD_COMPAT
_read(in, &len, sizeof(len)); // XXX portability issue
#else
_read(in, randstuff, 8);
randstuff[8] = randstuff[9] = '\0'; // ugly bug workaround
_read(in, randhash, 20);
unsigned char temphash[20]; // HashSize
GenRandhash(passwd, randstuff, temphash);
if (0 != memcmp((char*)randhash,
(char*)temphash,
20)) // HashSize
{
_close(in);
AfxMessageBox(_T("Incorrect password"));
return FALSE;
}
#endif // KEEP_FILE_MODE_BWD_COMPAT
buf = NULL; // allocated by _readcbc - see there for apologia
_read(in, salt, SaltLength);
_read(in, ipthing, 8);
LPCSTR pwd = LPCSTR(passwd);
if (_readcbc(in, buf, len,
(unsigned char *)pwd, passwd.GetLength(),
salt, SaltLength, ipthing) == 0) {
delete[] buf; // if not yet allocated, delete[] NULL, which is OK
return FALSE;
}
_close(in);
} else {
ErrorMessages(fn, in);
return FALSE;
}
int suffix_len = strlen(CIPHERTEXT_SUFFIX);
int filepath_len = fn.GetLength();
CString out_fn = fn;
out_fn = out_fn.Left(filepath_len - suffix_len);
int out = _open(out_fn,
_O_BINARY|_O_WRONLY|_O_SEQUENTIAL|_O_TRUNC|_O_CREAT,
_S_IREAD | _S_IWRITE);
if (out != -1) {
_write(out, buf, len);
_close(out);
} else
ErrorMessages(out_fn, out);
delete[] buf; // allocated by _readcbc
return TRUE;
}
BOOL
ThisMfcApp::InitInstance()
{
/*
* It's always best to start at the beginning. [Glinda, Witch of the North]
*/
/*
this pulls 'Counterpane Systems' out of the string table, verifies
that it exists (actually, only verifies that *some* IDS_COMPANY
string exists -- it could be 'Microsoft' for all we know), and then
instructs the app to use the registry instead of .ini files. The
path ends up being
HKEY_CURRENT_USER\Software\(companyname)\(appname)\(sectionname)\(valuename)
Assuming the open-source version of this is going to become less
Counterpane-centric, I expect this may change, but if it does, an
automagic migration ought to happen. -- {jpr}
*/
CString companyname;
VERIFY(companyname.LoadString(IDS_COMPANY) != 0);
SetRegistryKey(companyname);
int nMRUItems = GetProfileInt("", "maxmruitems", 4);
m_pMRU = new CRecentFileList( 0, "MRU", "Safe%d", nMRUItems );;
m_pMRU->ReadList();
DboxMain dbox(NULL);
/*
* Command line processing:
* Historically, it appears that if a filename was passed as a commadline argument,
* the application would prompt the user for the password, and the encrypt or decrypt
* the named file, based on the file's suffix. Ugh.
*
* What I'll do is as follows:
* If a file is given in the command line, it is used as the database, overriding the
* registry value. This will allow the user to have several databases, say, one for work
* and one for personal use, and to set up a different shortcut for each.
*
* I think I'll keep the old functionality, but activate it with a "-e" or "-d" flag. (ronys)
*/
if (m_lpCmdLine[0] != '\0') {
CString args = m_lpCmdLine;
if (args[0] != _T('-')) {
if (CheckFile(args)) {
dbox.SetCurFile(args);
} else {
return FALSE;
}
} else { // here if first char of arg is '-'
// first, let's check that there's a second arg
CString fn = args.Right(args.GetLength()-2);
fn.TrimLeft();
if (fn.IsEmpty() || !CheckFile(fn)) {
Usage();
return FALSE;
}
CMyString passkey;
if (args[1] == 'e' || args[1] == 'E' || args[1] == 'd' || args[1] == 'D') {
// get password from user if valid flag given. If note, default below will
// pop usage message
CCryptKeyEntry dlg(NULL);
int nResponse = dlg.DoModal();
if (nResponse==IDOK) {
passkey = dlg.m_cryptkey1;
} else {
return FALSE;
}
}
BOOL status;
switch (args[1]) {
case 'e': case 'E': // do encrpytion
status = EncryptFile(fn, passkey);
if (!status) {
AfxMessageBox("Encryption failed");
}
break;
case 'd': case 'D': // do decryption
status = DecryptFile(fn, passkey);
if (!status) {
// nothing to do - DecryptFile displays its own error messages
}
break;
default:
Usage();
return FALSE;
} // switch
return FALSE;
} // else
} // m_lpCmdLine[0] != '\0';
/*
* normal startup
*/
/*
Here's where PWS currently does DboxMain, which in turn will do
the initial PasskeyEntry (the one that looks like a splash screen).
This makes things very hard to control.
The app object (here) should instead do the initial PasskeyEntry,
and, if successful, move on to DboxMain. I think. {jpr}
*/
m_maindlg = &dbox;
// This doesn't do anything as best I can tell.
//m_pMainWnd = m_maindlg;
// Set up an Accelerator table
m_ghAccelTable = LoadAccelerators(AfxGetInstanceHandle(),
MAKEINTRESOURCE(IDR_ACCS));
//Run dialog
(void) dbox.DoModal();
/*
note that we don't particularly care what the response was
*/
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
//Copied from Knowledge Base article Q100770
BOOL
ThisMfcApp::ProcessMessageFilter(int code,
LPMSG lpMsg)
{
if (code < 0)
CWinApp::ProcessMessageFilter(code, lpMsg);
if (m_bUseAccelerator &&
m_maindlg != NULL
&& m_ghAccelTable != NULL)
{
if (::TranslateAccelerator(m_maindlg->m_hWnd, m_ghAccelTable, lpMsg))
return TRUE;
}
return CWinApp::ProcessMessageFilter(code, lpMsg);
}
void
ThisMfcApp::OnHelp()
{
::HtmlHelp(NULL,
"pwsafe.chm::/html/pws_intro.htm",
HH_DISPLAY_TOPIC, 0);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<commit_msg>Follow change to _{read,write}cbc() (addition of type argument)<commit_after>/// \file ThisMfcApp.cpp
/// \brief App object of MFC version of Password Safe
//-----------------------------------------------------------------------------
#include "PasswordSafe.h"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include "ThisMfcApp.h"
#include "Util.h"
#include "DboxMain.h"
#include "resource.h"
#include "CryptKeyEntry.h"
//-----------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(ThisMfcApp, CWinApp)
// ON_COMMAND(ID_HELP, CWinApp::OnHelp)
ON_COMMAND(ID_HELP, OnHelp)
END_MESSAGE_MAP()
ThisMfcApp::ThisMfcApp() :
m_bUseAccelerator( true ),
m_pMRU( NULL )
{
srand((unsigned)time(NULL));
}
ThisMfcApp::~ThisMfcApp()
{
if ( m_pMRU )
{
m_pMRU->WriteList();
delete m_pMRU;
}
/*
apparently, with vc7, there's a CWinApp::HtmlHelp - I'd like
to see the docs, someday. In the meantime, force with :: syntax
*/
::HtmlHelp(NULL, NULL, HH_CLOSE_ALL, 0);
}
static void Usage()
{
AfxMessageBox("Usage: PasswordSafe [password database]\n"
"or PasswordSafe [-e|-d] filename");
}
// tests if file exists, returns empty string if so, displays error message if not
static BOOL CheckFile(const CString &fn)
{
DWORD status = ::GetFileAttributes(fn);
CString ErrMess;
if (status == -1) {
ErrMess = _T("Could not access file: ");
ErrMess += fn;
} else if (status & FILE_ATTRIBUTE_DIRECTORY) {
ErrMess = fn;
ErrMess += _T(" is a directory");
}
if (ErrMess.IsEmpty()) {
return TRUE;
} else {
AfxMessageBox(ErrMess);
return FALSE;
}
}
//Complain if the file has not opened correctly
static void
ErrorMessages(const CString &fn, int fp)
{
if (fp==-1)
{
CString text;
text = "A fatal error occured: ";
if (errno==EACCES)
text += "Given path is a directory or file is read-only";
else if (errno==EEXIST)
text += "The filename already exists.";
else if (errno==EINVAL)
text += "Invalid oflag or shflag argument.";
else if (errno==EMFILE)
text += "No more file handles available.";
else if (errno==ENOENT)
text += "File or path not found.";
text += "\nProgram will terminate.";
CString title = "Password Safe - " + fn;
AfxGetMainWnd()->MessageBox(text, title, MB_ICONEXCLAMATION|MB_OK);
}
}
static BOOL EncryptFile(const CString &fn, const CMyString &passwd)
{
unsigned int len;
unsigned char* buf;
int in = _open(fn,
_O_BINARY|_O_RDONLY|_O_SEQUENTIAL,
S_IREAD | _S_IWRITE);
if (in != -1) {
len = _filelength(in);
buf = new unsigned char[len];
_read(in, buf, len);
_close(in);
} else {
ErrorMessages(fn, in);
return FALSE;
}
CString out_fn = fn;
out_fn += CIPHERTEXT_SUFFIX;
int out = _open(out_fn,
_O_BINARY|_O_WRONLY|_O_SEQUENTIAL|_O_TRUNC|_O_CREAT,
_S_IREAD | _S_IWRITE);
if (out != -1) {
unsigned char randstuff[StuffSize];
unsigned char randhash[20]; // HashSize
#ifdef KEEP_FILE_MODE_BWD_COMPAT
_write(out, &len, sizeof(len)); // XXX portability issue!
#else
for (int i=0; i < 8; i++)
randstuff[i] = newrand();
// miserable bug - have to fix this way to avoid breaking existing files
randstuff[8] = randstuff[9] = '\0';
GenRandhash(passwd, randstuff, randhash);
_write(out, randstuff, 8);
_write(out, randhash, 20);
#endif // KEEP_FILE_MODE_BWD_COMPAT
unsigned char thesalt[SaltLength];
for (int x=0;x<SaltLength;x++)
thesalt[x] = newrand();
_write(out, thesalt, SaltLength);
unsigned char ipthing[8];
for (x=0;x<8;x++)
ipthing[x] = newrand();
_write(out, ipthing, 8);
LPCSTR pwd = LPCSTR(passwd);
_writecbc(out, buf, len, (unsigned char)0,
(unsigned char *)pwd, passwd.GetLength(),
thesalt, SaltLength,
ipthing);
_close(out);
} else {
ErrorMessages(out_fn, out);
delete [] buf;
return FALSE;
}
delete[] buf;
return TRUE;
}
static BOOL DecryptFile(const CString &fn, const CMyString &passwd)
{
unsigned int len;
unsigned char* buf;
int in = _open(fn,
_O_BINARY|_O_RDONLY|_O_SEQUENTIAL,
S_IREAD | _S_IWRITE);
if (in != -1) {
unsigned char randstuff[StuffSize];
unsigned char randhash[20]; // HashSize
unsigned char salt[SaltLength];
unsigned char ipthing[8];
#ifdef KEEP_FILE_MODE_BWD_COMPAT
_read(in, &len, sizeof(len)); // XXX portability issue
#else
_read(in, randstuff, 8);
randstuff[8] = randstuff[9] = '\0'; // ugly bug workaround
_read(in, randhash, 20);
unsigned char temphash[20]; // HashSize
GenRandhash(passwd, randstuff, temphash);
if (0 != memcmp((char*)randhash,
(char*)temphash,
20)) // HashSize
{
_close(in);
AfxMessageBox(_T("Incorrect password"));
return FALSE;
}
#endif // KEEP_FILE_MODE_BWD_COMPAT
buf = NULL; // allocated by _readcbc - see there for apologia
_read(in, salt, SaltLength);
_read(in, ipthing, 8);
LPCSTR pwd = LPCSTR(passwd);
unsigned char dummyType;
if (_readcbc(in, buf, len, dummyType,
(unsigned char *)pwd, passwd.GetLength(),
salt, SaltLength, ipthing) == 0) {
delete[] buf; // if not yet allocated, delete[] NULL, which is OK
return FALSE;
}
_close(in);
} else {
ErrorMessages(fn, in);
return FALSE;
}
int suffix_len = strlen(CIPHERTEXT_SUFFIX);
int filepath_len = fn.GetLength();
CString out_fn = fn;
out_fn = out_fn.Left(filepath_len - suffix_len);
int out = _open(out_fn,
_O_BINARY|_O_WRONLY|_O_SEQUENTIAL|_O_TRUNC|_O_CREAT,
_S_IREAD | _S_IWRITE);
if (out != -1) {
_write(out, buf, len);
_close(out);
} else
ErrorMessages(out_fn, out);
delete[] buf; // allocated by _readcbc
return TRUE;
}
BOOL
ThisMfcApp::InitInstance()
{
/*
* It's always best to start at the beginning. [Glinda, Witch of the North]
*/
/*
this pulls 'Counterpane Systems' out of the string table, verifies
that it exists (actually, only verifies that *some* IDS_COMPANY
string exists -- it could be 'Microsoft' for all we know), and then
instructs the app to use the registry instead of .ini files. The
path ends up being
HKEY_CURRENT_USER\Software\(companyname)\(appname)\(sectionname)\(valuename)
Assuming the open-source version of this is going to become less
Counterpane-centric, I expect this may change, but if it does, an
automagic migration ought to happen. -- {jpr}
*/
CString companyname;
VERIFY(companyname.LoadString(IDS_COMPANY) != 0);
SetRegistryKey(companyname);
int nMRUItems = GetProfileInt("", "maxmruitems", 4);
m_pMRU = new CRecentFileList( 0, "MRU", "Safe%d", nMRUItems );;
m_pMRU->ReadList();
DboxMain dbox(NULL);
/*
* Command line processing:
* Historically, it appears that if a filename was passed as a commadline argument,
* the application would prompt the user for the password, and the encrypt or decrypt
* the named file, based on the file's suffix. Ugh.
*
* What I'll do is as follows:
* If a file is given in the command line, it is used as the database, overriding the
* registry value. This will allow the user to have several databases, say, one for work
* and one for personal use, and to set up a different shortcut for each.
*
* I think I'll keep the old functionality, but activate it with a "-e" or "-d" flag. (ronys)
*/
if (m_lpCmdLine[0] != '\0') {
CString args = m_lpCmdLine;
if (args[0] != _T('-')) {
if (CheckFile(args)) {
dbox.SetCurFile(args);
} else {
return FALSE;
}
} else { // here if first char of arg is '-'
// first, let's check that there's a second arg
CString fn = args.Right(args.GetLength()-2);
fn.TrimLeft();
if (fn.IsEmpty() || !CheckFile(fn)) {
Usage();
return FALSE;
}
CMyString passkey;
if (args[1] == 'e' || args[1] == 'E' || args[1] == 'd' || args[1] == 'D') {
// get password from user if valid flag given. If note, default below will
// pop usage message
CCryptKeyEntry dlg(NULL);
int nResponse = dlg.DoModal();
if (nResponse==IDOK) {
passkey = dlg.m_cryptkey1;
} else {
return FALSE;
}
}
BOOL status;
switch (args[1]) {
case 'e': case 'E': // do encrpytion
status = EncryptFile(fn, passkey);
if (!status) {
AfxMessageBox("Encryption failed");
}
break;
case 'd': case 'D': // do decryption
status = DecryptFile(fn, passkey);
if (!status) {
// nothing to do - DecryptFile displays its own error messages
}
break;
default:
Usage();
return FALSE;
} // switch
return FALSE;
} // else
} // m_lpCmdLine[0] != '\0';
/*
* normal startup
*/
/*
Here's where PWS currently does DboxMain, which in turn will do
the initial PasskeyEntry (the one that looks like a splash screen).
This makes things very hard to control.
The app object (here) should instead do the initial PasskeyEntry,
and, if successful, move on to DboxMain. I think. {jpr}
*/
m_maindlg = &dbox;
// This doesn't do anything as best I can tell.
//m_pMainWnd = m_maindlg;
// Set up an Accelerator table
m_ghAccelTable = LoadAccelerators(AfxGetInstanceHandle(),
MAKEINTRESOURCE(IDR_ACCS));
//Run dialog
(void) dbox.DoModal();
/*
note that we don't particularly care what the response was
*/
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
//Copied from Knowledge Base article Q100770
BOOL
ThisMfcApp::ProcessMessageFilter(int code,
LPMSG lpMsg)
{
if (code < 0)
CWinApp::ProcessMessageFilter(code, lpMsg);
if (m_bUseAccelerator &&
m_maindlg != NULL
&& m_ghAccelTable != NULL)
{
if (::TranslateAccelerator(m_maindlg->m_hWnd, m_ghAccelTable, lpMsg))
return TRUE;
}
return CWinApp::ProcessMessageFilter(code, lpMsg);
}
void
ThisMfcApp::OnHelp()
{
::HtmlHelp(NULL,
"pwsafe.chm::/html/pws_intro.htm",
HH_DISPLAY_TOPIC, 0);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/**
* @file
* @author Jason Lingle
* @brief Implementation of src/core/init_state.hxx
*/
#include <iostream>
#include <typeinfo>
#include <ctime>
#include <new>
#include <GL/gl.h>
#include <SDL.h>
#include <tcl.h>
#include "init_state.hxx"
#include "src/globals.hxx"
#include "src/graphics/imgload.hxx"
#include "src/test_state.hxx"
#include "src/fasttrig.hxx"
#include "src/background/background_object.hxx"
#include "src/background/star_field.hxx"
#include "src/background/explosion_pool.hxx"
#include "src/ship/sys/system_textures.hxx"
#include "src/graphics/vec.hxx"
#include "src/graphics/mat.hxx"
#include "src/graphics/matops.hxx"
#include "src/graphics/shader.hxx"
#include "src/graphics/cmn_shaders.hxx"
#include "src/graphics/glhelp.hxx"
#include "src/graphics/gl32emu.hxx"
#include "src/graphics/font.hxx"
#include "src/graphics/asgi.hxx"
#include "src/audio/audio.hxx"
#include "src/secondary/namegen.hxx"
#include "src/tcl_iface/bridge.hxx"
#include "src/exit_conditions.hxx"
using namespace std;
#if defined(AB_OPENGL_14)
#define LOGO "images/a14.png"
#elif defined(AB_OPENGL_21)
#define LOGO "images/a21.png"
#else
#define LOGO "images/a.png"
#endif
//For LSD-mode Easter Egg
static bool hasPressedL=false, hasPressedS=false, hasPressedD=false;
InitState::InitState() {
currStep = 0;
currStepProgress = 0;
static float (*const stepsToLoad[])() = {
&InitState::miscLoader,
&InitState::initFontLoader,
&InitState::systexLoader,
&InitState::starLoader,
&InitState::backgroundLoader,
&InitState::keyboardDelay,
};
steps = stepsToLoad;
numSteps = lenof(stepsToLoad);
hasPainted=headless;
if (!headless) {
SDL_ShowCursor(SDL_DISABLE);
glGenTextures(1, &logo);
vao = newVAO();
glBindVertexArray(vao);
vbo = newVBO();
const char* error=loadImage(LOGO, logo);
if (error) {
cerr << error << endl;
exit(EXIT_MALFORMED_DATA);
}
//We can't set the buffer up yet, because vheight
//has not yet been calculated.
}
}
InitState::~InitState() {
if (!headless) {
glDeleteTextures(1, &logo);
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
}
}
GameState* InitState::update(float) {
if (!hasPainted && !headless) return NULL;
if (currStep < numSteps) {
currStepProgress = steps[currStep]();
if (currStepProgress > 1.0f) {
currStepProgress = 0;
++currStep;
}
} else {
if (hasPressedL && hasPressedS && hasPressedD) {
enableLSDMode();
shader::textureReplace.unload();
shader::basic.unload();
}
//Start the root interpreter
Tcl_Interp* root=newInterpreter(false);
if (TCL_ERROR == Tcl_EvalFile(root, "tcl/autoexec.tcl")) {
cerr << "FATAL: Autoexec did not run successfully: " << Tcl_GetStringResult(root) << endl;
Tcl_Obj* options=Tcl_GetReturnOptions(root, TCL_ERROR);
Tcl_Obj* key=Tcl_NewStringObj("-errorinfo", -1);
Tcl_Obj* stackTrace;
Tcl_IncrRefCount(key);
Tcl_DictObjGet(NULL, options, key, &stackTrace);
Tcl_DecrRefCount(key);
cerr << "Stack trace:\n" << Tcl_GetStringFromObj(stackTrace, NULL) << endl;
exit(EXIT_SCRIPTING_BUG);
}
if (this == state) {
cerr << "FATAL: Autoexec did not change GameState" << endl;
exit(EXIT_SCRIPTING_BUG);
}
if (!headless) {
SDL_EnableUNICODE(1);
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
//Tcl is taking over in a somewhat rude way, so
//handle as gracefully as possible
state->configureGL();
}
}
return NULL;
}
void InitState::draw() {
hasPainted=true;
const shader::textureReplaceV quad[4] = {
{ {{0.5f-vheight/2,0 ,0,1}}, {{0,1}} },
{ {{0.5f+vheight/2,0 ,0,1}}, {{1,1}} },
{ {{0.5f-vheight/2,vheight,0,1}}, {{0,0}} },
{ {{0.5f+vheight/2,vheight,0,1}}, {{1,0}} },
};
shader::textureReplaceU uni;
uni.colourMap=0;
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);
shader::textureReplace->setupVBO();
glBindTexture(GL_TEXTURE_2D, logo);
shader::textureReplace->activate(&uni);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
static const float progressH = 0.02f;
static const float progressW = 0.3f;
float currProgress = currStep/(float)numSteps + currStepProgress/numSteps;
float baseX = 0.5f - progressW/2;
#if defined(AB_OPENGL_14)
asgi::colour(1.0f, 0.4f, 0.2f, 0.75f);
#elif defined(AB_OPENGL_21)
asgi::colour(0.2f, 1.0f, 0.4f, 0.75f);
#else
asgi::colour(0.2f, 0.3f, 0.9f, 0.75f);
#endif
asgi::begin(asgi::Quads);
asgi::vertex(baseX, 4*progressH);
asgi::vertex(baseX, 5*progressH);
asgi::vertex(baseX + currProgress*progressW, 5*progressH);
asgi::vertex(baseX + currProgress*progressW, 4*progressH);
asgi::end();
asgi::begin(asgi::Quads);
asgi::vertex(baseX, 2.75f*progressH);
asgi::vertex(baseX, 3.75f*progressH);
asgi::vertex(baseX + currStepProgress*progressW, 3.75*progressH);
asgi::vertex(baseX + currStepProgress*progressW, 2.75*progressH);
asgi::end();
}
void InitState::keyboard(SDL_KeyboardEvent* e) {
if (e->keysym.sym == SDLK_l)
hasPressedL = true;
else if (e->keysym.sym == SDLK_s)
hasPressedS = true;
else if (e->keysym.sym == SDLK_d)
hasPressedD = true;
}
float InitState::miscLoader() {
initTable(); //Trig tables
sparkCountMultiplier=1;
if (conf["conf"]["audio_enabled"]) audio::init();
prepareTclBridge();
namegenLoad();
return 2;
}
float InitState::starLoader() {
initStarLists();
return 2;
}
float InitState::backgroundLoader() {
if (!headless && !loadBackgroundObjects()) exit(EXIT_MALFORMED_DATA);
return 2;
}
float InitState::systexLoader() {
if (!headless)
system_texture::load();
return 2;
}
float InitState::initFontLoader() {
new (sysfont) Font("fonts/westm", conf["conf"]["hud"]["font_size"], false);
new (sysfontStipple) Font("fonts/westm", conf["conf"]["hud"]["font_size"], true );
new (smallFont) Font("fonts/unifont", conf["conf"]["hud"]["font_size"].operator float()/1.5f, false);
new (smallFontStipple)Font("fonts/unifont", conf["conf"]["hud"]["font_size"].operator float()/1.5f, true );
return 1.5;
}
//Delays for 500 ms to wait for keystrokes
float InitState::keyboardDelay() {
static Uint32 start = SDL_GetTicks();
Uint32 end = SDL_GetTicks();
return (end-start)/512.0f;
}
<commit_msg>Add support for preliminary configuration mode to InitState.<commit_after>/**
* @file
* @author Jason Lingle
* @brief Implementation of src/core/init_state.hxx
*/
#include <iostream>
#include <typeinfo>
#include <ctime>
#include <new>
#include <GL/gl.h>
#include <SDL.h>
#include <tcl.h>
#include "init_state.hxx"
#include "src/abendstern.hxx"
#include "src/globals.hxx"
#include "src/graphics/imgload.hxx"
#include "src/test_state.hxx"
#include "src/fasttrig.hxx"
#include "src/background/background_object.hxx"
#include "src/background/star_field.hxx"
#include "src/background/explosion_pool.hxx"
#include "src/ship/sys/system_textures.hxx"
#include "src/graphics/vec.hxx"
#include "src/graphics/mat.hxx"
#include "src/graphics/matops.hxx"
#include "src/graphics/shader.hxx"
#include "src/graphics/cmn_shaders.hxx"
#include "src/graphics/glhelp.hxx"
#include "src/graphics/gl32emu.hxx"
#include "src/graphics/font.hxx"
#include "src/graphics/asgi.hxx"
#include "src/audio/audio.hxx"
#include "src/secondary/namegen.hxx"
#include "src/tcl_iface/bridge.hxx"
#include "src/exit_conditions.hxx"
using namespace std;
#if defined(AB_OPENGL_14)
#define LOGO "images/a14.png"
#elif defined(AB_OPENGL_21)
#define LOGO "images/a21.png"
#else
#define LOGO "images/a.png"
#endif
//For LSD-mode Easter Egg
static bool hasPressedL=false, hasPressedS=false, hasPressedD=false;
InitState::InitState() {
currStep = 0;
currStepProgress = 0;
static float (*const stepsToLoad[])() = {
&InitState::miscLoader,
&InitState::initFontLoader,
&InitState::systexLoader,
&InitState::starLoader,
&InitState::backgroundLoader,
&InitState::keyboardDelay,
};
steps = stepsToLoad;
numSteps = lenof(stepsToLoad);
hasPainted=headless;
if (!headless) {
if (!preliminaryRunMode)
SDL_ShowCursor(SDL_DISABLE);
glGenTextures(1, &logo);
vao = newVAO();
glBindVertexArray(vao);
vbo = newVBO();
const char* error=loadImage(LOGO, logo);
if (error) {
cerr << error << endl;
exit(EXIT_MALFORMED_DATA);
}
//We can't set the buffer up yet, because vheight
//has not yet been calculated.
}
}
InitState::~InitState() {
if (!headless) {
glDeleteTextures(1, &logo);
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
}
}
GameState* InitState::update(float) {
if (!hasPainted && !headless) return NULL;
if (currStep < numSteps) {
currStepProgress = steps[currStep]();
if (currStepProgress > 1.0f) {
currStepProgress = 0;
++currStep;
}
} else {
if (hasPressedL && hasPressedS && hasPressedD) {
enableLSDMode();
shader::textureReplace.unload();
shader::basic.unload();
}
//Start the root interpreter
Tcl_Interp* root=newInterpreter(false);
if (TCL_ERROR == Tcl_EvalFile(root, "tcl/autoexec.tcl")) {
cerr << "FATAL: Autoexec did not run successfully: " << Tcl_GetStringResult(root) << endl;
Tcl_Obj* options=Tcl_GetReturnOptions(root, TCL_ERROR);
Tcl_Obj* key=Tcl_NewStringObj("-errorinfo", -1);
Tcl_Obj* stackTrace;
Tcl_IncrRefCount(key);
Tcl_DictObjGet(NULL, options, key, &stackTrace);
Tcl_DecrRefCount(key);
cerr << "Stack trace:\n" << Tcl_GetStringFromObj(stackTrace, NULL) << endl;
exit(EXIT_SCRIPTING_BUG);
}
if (this == state) {
cerr << "FATAL: Autoexec did not change GameState" << endl;
exit(EXIT_SCRIPTING_BUG);
}
if (!headless) {
SDL_EnableUNICODE(1);
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
//Tcl is taking over in a somewhat rude way, so
//handle as gracefully as possible
state->configureGL();
}
}
return NULL;
}
void InitState::draw() {
hasPainted=true;
const shader::textureReplaceV quad[4] = {
{ {{0.5f-vheight/2,0 ,0,1}}, {{0,1}} },
{ {{0.5f+vheight/2,0 ,0,1}}, {{1,1}} },
{ {{0.5f-vheight/2,vheight,0,1}}, {{0,0}} },
{ {{0.5f+vheight/2,vheight,0,1}}, {{1,0}} },
};
shader::textureReplaceU uni;
uni.colourMap=0;
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);
shader::textureReplace->setupVBO();
glBindTexture(GL_TEXTURE_2D, logo);
shader::textureReplace->activate(&uni);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
static const float progressH = 0.02f;
static const float progressW = 0.3f;
float currProgress = currStep/(float)numSteps + currStepProgress/numSteps;
float baseX = 0.5f - progressW/2;
#if defined(AB_OPENGL_14)
asgi::colour(1.0f, 0.4f, 0.2f, 0.75f);
#elif defined(AB_OPENGL_21)
asgi::colour(0.2f, 1.0f, 0.4f, 0.75f);
#else
asgi::colour(0.2f, 0.3f, 0.9f, 0.75f);
#endif
asgi::begin(asgi::Quads);
asgi::vertex(baseX, 4*progressH);
asgi::vertex(baseX, 5*progressH);
asgi::vertex(baseX + currProgress*progressW, 5*progressH);
asgi::vertex(baseX + currProgress*progressW, 4*progressH);
asgi::end();
asgi::begin(asgi::Quads);
asgi::vertex(baseX, 2.75f*progressH);
asgi::vertex(baseX, 3.75f*progressH);
asgi::vertex(baseX + currStepProgress*progressW, 3.75*progressH);
asgi::vertex(baseX + currStepProgress*progressW, 2.75*progressH);
asgi::end();
}
void InitState::keyboard(SDL_KeyboardEvent* e) {
if (e->keysym.sym == SDLK_l)
hasPressedL = true;
else if (e->keysym.sym == SDLK_s)
hasPressedS = true;
else if (e->keysym.sym == SDLK_d)
hasPressedD = true;
}
float InitState::miscLoader() {
initTable(); //Trig tables
sparkCountMultiplier=1;
if (conf["conf"]["audio_enabled"]) audio::init();
prepareTclBridge();
namegenLoad();
return 2;
}
float InitState::starLoader() {
initStarLists();
return 2;
}
float InitState::backgroundLoader() {
if (!headless && !loadBackgroundObjects()) exit(EXIT_MALFORMED_DATA);
return 2;
}
float InitState::systexLoader() {
if (!headless)
system_texture::load();
return 2;
}
float InitState::initFontLoader() {
float mult = (preliminaryRunMode? 2.0f : 1.0f);
float size = conf["conf"]["hud"]["font_size"];
new (sysfont) Font("fonts/westm", size*mult, false);
new (sysfontStipple) Font("fonts/westm", size*mult, true );
new (smallFont) Font("fonts/unifont", size*mult/1.5f, false);
new (smallFontStipple)Font("fonts/unifont", size*mult/1.5f, true );
return 2;
}
//Delays for 500 ms to wait for keystrokes
float InitState::keyboardDelay() {
if (preliminaryRunMode) return 2; //Don't wait
static Uint32 start = SDL_GetTicks();
Uint32 end = SDL_GetTicks();
return (end-start)/512.0f;
}
<|endoftext|> |
<commit_before>#include <sys/systm.h>
#include "remap.hpp"
#include "RemapUtil.hpp"
#include "Client.hpp"
#include "Config.hpp"
#include "IOLockWrapper.hpp"
#include "KeyCode.hpp"
#include "ListHookedKeyboard.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace GeneratedCode {
#include "config/output/include.remapcode_func.cpp"
}
// ----------------------------------------
class RemapClass_notsave_pointing_relative_to_scroll {
public:
static void remap_pointing(RemapPointingParams_relative& remapParams) {
prts_.remap(remapParams, PointingButton::NONE, Flags(0));
}
private:
static RemapUtil::PointingRelativeToScroll prts_;
};
RemapUtil::PointingRelativeToScroll RemapClass_notsave_pointing_relative_to_scroll::prts_;
}
// ----------------------------------------------------------------------
namespace org_pqrs_KeyRemap4MacBook {
namespace {
#include "config/output/include.remapcode_info.cpp"
typedef void (*RemapFunc_key)(RemapParams& remapParams);
RemapFunc_key listRemapFunc_key[MAXNUM_REMAPFUNC_KEY + 1];
int listRemapFunc_key_size = 0;
typedef void (*RemapFunc_consumer)(RemapConsumerParams& remapParams);
RemapFunc_consumer listRemapFunc_consumer[MAXNUM_REMAPFUNC_CONSUMER + 1];
int listRemapFunc_consumer_size = 0;
typedef void (*RemapFunc_pointing)(RemapPointingParams_relative& remapParams);
RemapFunc_pointing listRemapFunc_pointing[MAXNUM_REMAPFUNC_POINTING + 1];
int listRemapFunc_pointing_size = 0;
IOLock* refresh_remapfunc_lock = NULL;
}
}
void
org_pqrs_KeyRemap4MacBook::remapfunc_initialize(void)
{
refresh_remapfunc_lock = IOLockWrapper::alloc();
refresh_remapfunc();
}
void
org_pqrs_KeyRemap4MacBook::remapfunc_terminate(void)
{
IOLockWrapper::free(refresh_remapfunc_lock);
}
void
org_pqrs_KeyRemap4MacBook::refresh_remapfunc(void)
{
IOLockWrapper::ScopedLock lk(refresh_remapfunc_lock);
listRemapFunc_key_size = 0;
listRemapFunc_consumer_size = 0;
listRemapFunc_pointing_size = 0;
// ------------------------------------------------------------
#include "config/output/include.remapcode_refresh_remapfunc_key.cpp"
// ------------------------------------------------------------
#include "config/output/include.remapcode_refresh_remapfunc_consumer.cpp"
// ------------------------------------------------------------
#include "config/output/include.remapcode_refresh_remapfunc_pointing.cpp"
if (config.notsave_pointing_relative_to_scroll) {
listRemapFunc_pointing[listRemapFunc_pointing_size] = RemapClass_notsave_pointing_relative_to_scroll::remap_pointing;
++listRemapFunc_pointing_size;
}
// ------------------------------------------------------------
// handle StatusMessage
static bool isCurrentlyStatusMessageVisible = false;
const char* statusmessage = NULL;
bool isStatusMessageVisible = false;
#include "config/output/include.remapcode_refresh_remapfunc_statusmessage.cpp"
if (isCurrentlyStatusMessageVisible) {
if (! isStatusMessageVisible) {
// hide
KeyRemap4MacBook_bridge::StatusMessage::Request request(KeyRemap4MacBook_bridge::StatusMessage::MESSAGETYPE_EXTRA, "");
KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_STATUS_MESSAGE, &request, sizeof(request), NULL, 0);
isCurrentlyStatusMessageVisible = false;
}
} else {
if (isStatusMessageVisible == true) {
// show
KeyRemap4MacBook_bridge::StatusMessage::Request request(KeyRemap4MacBook_bridge::StatusMessage::MESSAGETYPE_EXTRA, statusmessage);
KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_STATUS_MESSAGE, &request, sizeof(request), NULL, 0);
isCurrentlyStatusMessageVisible = true;
}
}
// ------------------------------------------------------------
if (config.debug_devel) {
printf("KeyRemap4MacBook --INFO-- enabled remappings: key:%d, consumer:%d, pointing:%d\n",
listRemapFunc_key_size,
listRemapFunc_consumer_size,
listRemapFunc_pointing_size);
}
}
void
org_pqrs_KeyRemap4MacBook::remap_core(RemapParams& remapParams)
{
FlagStatus::set(remapParams.params.key, remapParams.params.flags);
for (int i = 0; i < listRemapFunc_key_size; ++i) {
RemapFunc_key func = listRemapFunc_key[i];
if (func) {
func(remapParams);
}
}
}
void
org_pqrs_KeyRemap4MacBook::remap_consumer(RemapConsumerParams& remapParams)
{
FlagStatus::set();
for (int i = 0; i < listRemapFunc_consumer_size; ++i) {
RemapFunc_consumer func = listRemapFunc_consumer[i];
if (func) {
func(remapParams);
}
}
}
void
org_pqrs_KeyRemap4MacBook::remap_pointing_relative_core(RemapPointingParams_relative& remapParams)
{
FlagStatus::set();
for (int i = 0; i < listRemapFunc_pointing_size; ++i) {
RemapFunc_pointing func = listRemapFunc_pointing[i];
if (func) {
func(remapParams);
}
}
}
<commit_msg>add KeyboardRepeat::cancel to refresh_remapfunc @ kext<commit_after>#include <sys/systm.h>
#include "remap.hpp"
#include "RemapUtil.hpp"
#include "KeyboardRepeat.hpp"
#include "Client.hpp"
#include "Config.hpp"
#include "IOLockWrapper.hpp"
#include "KeyCode.hpp"
#include "ListHookedKeyboard.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace GeneratedCode {
#include "config/output/include.remapcode_func.cpp"
}
// ----------------------------------------
class RemapClass_notsave_pointing_relative_to_scroll {
public:
static void remap_pointing(RemapPointingParams_relative& remapParams) {
prts_.remap(remapParams, PointingButton::NONE, Flags(0));
}
private:
static RemapUtil::PointingRelativeToScroll prts_;
};
RemapUtil::PointingRelativeToScroll RemapClass_notsave_pointing_relative_to_scroll::prts_;
}
// ----------------------------------------------------------------------
namespace org_pqrs_KeyRemap4MacBook {
namespace {
#include "config/output/include.remapcode_info.cpp"
typedef void (*RemapFunc_key)(RemapParams& remapParams);
RemapFunc_key listRemapFunc_key[MAXNUM_REMAPFUNC_KEY + 1];
int listRemapFunc_key_size = 0;
typedef void (*RemapFunc_consumer)(RemapConsumerParams& remapParams);
RemapFunc_consumer listRemapFunc_consumer[MAXNUM_REMAPFUNC_CONSUMER + 1];
int listRemapFunc_consumer_size = 0;
typedef void (*RemapFunc_pointing)(RemapPointingParams_relative& remapParams);
RemapFunc_pointing listRemapFunc_pointing[MAXNUM_REMAPFUNC_POINTING + 1];
int listRemapFunc_pointing_size = 0;
IOLock* refresh_remapfunc_lock = NULL;
}
}
void
org_pqrs_KeyRemap4MacBook::remapfunc_initialize(void)
{
refresh_remapfunc_lock = IOLockWrapper::alloc();
refresh_remapfunc();
}
void
org_pqrs_KeyRemap4MacBook::remapfunc_terminate(void)
{
IOLockWrapper::free(refresh_remapfunc_lock);
}
void
org_pqrs_KeyRemap4MacBook::refresh_remapfunc(void)
{
IOLockWrapper::ScopedLock lk(refresh_remapfunc_lock);
KeyboardRepeat::cancel();
listRemapFunc_key_size = 0;
listRemapFunc_consumer_size = 0;
listRemapFunc_pointing_size = 0;
// ------------------------------------------------------------
#include "config/output/include.remapcode_refresh_remapfunc_key.cpp"
// ------------------------------------------------------------
#include "config/output/include.remapcode_refresh_remapfunc_consumer.cpp"
// ------------------------------------------------------------
#include "config/output/include.remapcode_refresh_remapfunc_pointing.cpp"
if (config.notsave_pointing_relative_to_scroll) {
listRemapFunc_pointing[listRemapFunc_pointing_size] = RemapClass_notsave_pointing_relative_to_scroll::remap_pointing;
++listRemapFunc_pointing_size;
}
// ------------------------------------------------------------
// handle StatusMessage
static bool isCurrentlyStatusMessageVisible = false;
const char* statusmessage = NULL;
bool isStatusMessageVisible = false;
#include "config/output/include.remapcode_refresh_remapfunc_statusmessage.cpp"
if (isCurrentlyStatusMessageVisible) {
if (! isStatusMessageVisible) {
// hide
KeyRemap4MacBook_bridge::StatusMessage::Request request(KeyRemap4MacBook_bridge::StatusMessage::MESSAGETYPE_EXTRA, "");
KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_STATUS_MESSAGE, &request, sizeof(request), NULL, 0);
isCurrentlyStatusMessageVisible = false;
}
} else {
if (isStatusMessageVisible == true) {
// show
KeyRemap4MacBook_bridge::StatusMessage::Request request(KeyRemap4MacBook_bridge::StatusMessage::MESSAGETYPE_EXTRA, statusmessage);
KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_STATUS_MESSAGE, &request, sizeof(request), NULL, 0);
isCurrentlyStatusMessageVisible = true;
}
}
// ------------------------------------------------------------
if (config.debug_devel) {
printf("KeyRemap4MacBook --INFO-- enabled remappings: key:%d, consumer:%d, pointing:%d\n",
listRemapFunc_key_size,
listRemapFunc_consumer_size,
listRemapFunc_pointing_size);
}
}
void
org_pqrs_KeyRemap4MacBook::remap_core(RemapParams& remapParams)
{
FlagStatus::set(remapParams.params.key, remapParams.params.flags);
for (int i = 0; i < listRemapFunc_key_size; ++i) {
RemapFunc_key func = listRemapFunc_key[i];
if (func) {
func(remapParams);
}
}
}
void
org_pqrs_KeyRemap4MacBook::remap_consumer(RemapConsumerParams& remapParams)
{
FlagStatus::set();
for (int i = 0; i < listRemapFunc_consumer_size; ++i) {
RemapFunc_consumer func = listRemapFunc_consumer[i];
if (func) {
func(remapParams);
}
}
}
void
org_pqrs_KeyRemap4MacBook::remap_pointing_relative_core(RemapPointingParams_relative& remapParams)
{
FlagStatus::set();
for (int i = 0; i < listRemapFunc_pointing_size; ++i) {
RemapFunc_pointing func = listRemapFunc_pointing[i];
if (func) {
func(remapParams);
}
}
}
<|endoftext|> |
<commit_before>#include "utils.h"
#include <assert.h>
#include <netdb.h>
#include <arpa/inet.h>
#include "http_url_parser.h"
http_url_parser::http_url_parser(const char *url)
: mURL(strdup(url)),
mPort(80),
mHost(0),
mPath(0),
mScheme(0),
mHaveScheme(false) {
parser();
}
http_url_parser::~http_url_parser()
{
free(mURL); free(mHost); free(mPath); free(mScheme);
}
void http_url_parser::parser_url_with_port(void)
{
char *pos;
char *url;
char *port_pos;
url = mHaveScheme? mURL + 7 : mURL;
port_pos = strchr(url, ':');
mHost = (char *)malloc(port_pos - url + 1);
strncpy(mHost, url, port_pos - url);
mHost[port_pos - url] = 0;
mPort = atoi(port_pos + 1);
pos = strchr(url, '/');
if (! pos) {
mPath = (char *)malloc(2);
mPath[0] = '/'; mPath[1] = 0;
} else {
mPath = (char *)malloc(strlen(pos) + 1);
strcpy(mPath, pos);
}
}
void http_url_parser::parser_url_without_port(void)
{
char *tmp;
char *pos;
tmp = mHaveScheme? mURL + 7 : mURL;
pos = strchr(tmp, '/');
if (! pos) {
mHost = (char *)malloc(strlen(tmp) + 1);
strcpy(mHost, tmp);
mPath = (char *)malloc(2);
mPath[0] = '/'; mPath[1] = 0;
} else {
mHost = (char *)malloc(pos - tmp + 1);
strncpy(mHost, tmp, pos - tmp);
mHost[pos - tmp] = 0;
mPath = (char *)malloc(strlen(pos) + 1);
strcpy(mPath, pos);
}
}
bool http_url_parser::is_host_ip(void)
{
int i;
for (i = 0; mHost[i]; i ++) {
if (mHost[i] != '.' && (! Utils::is_digit(mHost[i]))) {
return false;
}
}
return true;
}
void http_url_parser::parser_host_ip(void)
{
struct in_addr ip;
struct hostent *host;
host = gethostbyname(mHost);
assert(host);
printf("h_name: %s\n", host->h_name);
bcopy(host->h_addr, &(ip.s_addr), host->h_length);
printf("IP: %s\n", inet_ntoa(ip));
mHostIP = (char *)malloc(16);
strcpy(mHostIP, inet_ntoa(ip));
}
void http_url_parser::parser(void)
{
int i;
char *tmp;
bool have_port = false;
/*
* URL example.
* http://<host>:<port>/<path>?<searchpart>
* http://10.0.0.201/video/mp4/test.mp4?id=1&ts=10000
*/
mScheme = (char *)malloc(sizeof("http"));
strcpy(mScheme, "http");
mHaveScheme = ! strncmp(mURL, "http://", 7);
tmp = mHaveScheme? mURL + 7 : mURL;
for (i = 0; tmp[i] != '/' && tmp[i]; i ++) {
if (tmp[i] == ':') {
have_port = true;
break;
}
}
if (have_port) {
parser_url_with_port();
} else {
parser_url_without_port();
}
if(! is_host_ip()) {
parser_host_ip();
}
}
<commit_msg>Fix url parser issue.<commit_after>#include "utils.h"
#include <assert.h>
#include <netdb.h>
#include <arpa/inet.h>
#include "http_url_parser.h"
http_url_parser::http_url_parser(const char *url)
: mURL(strdup(url)),
mPort(80),
mHost(0),
mPath(0),
mScheme(0),
mHaveScheme(false) {
parser();
}
http_url_parser::~http_url_parser()
{
free(mURL); free(mHost); free(mPath); free(mScheme); free(mHostIP);
}
void http_url_parser::parser_url_with_port(void)
{
char *pos;
char *url;
char *port_pos;
url = mHaveScheme? mURL + 7 : mURL;
port_pos = strchr(url, ':');
mHost = (char *)malloc(port_pos - url + 1);
strncpy(mHost, url, port_pos - url);
mHost[port_pos - url] = 0;
mPort = atoi(port_pos + 1);
pos = strchr(url, '/');
if (! pos) {
mPath = (char *)malloc(2);
mPath[0] = '/'; mPath[1] = 0;
} else {
mPath = (char *)malloc(strlen(pos) + 1);
strcpy(mPath, pos);
}
}
void http_url_parser::parser_url_without_port(void)
{
char *tmp;
char *pos;
tmp = mHaveScheme? mURL + 7 : mURL;
pos = strchr(tmp, '/');
if (! pos) {
mHost = (char *)malloc(strlen(tmp) + 1);
strcpy(mHost, tmp);
mPath = (char *)malloc(2);
mPath[0] = '/'; mPath[1] = 0;
} else {
mHost = (char *)malloc(pos - tmp + 1);
strncpy(mHost, tmp, pos - tmp);
mHost[pos - tmp] = 0;
mPath = (char *)malloc(strlen(pos) + 1);
strcpy(mPath, pos);
}
}
bool http_url_parser::is_host_ip(void)
{
int i;
for (i = 0; mHost[i]; i ++) {
if (mHost[i] != '.' && (! Utils::is_digit(mHost[i]))) {
return false;
}
}
return true;
}
void http_url_parser::parser_host_ip(void)
{
struct in_addr ip;
struct hostent *host;
host = gethostbyname(mHost);
assert(host);
printf("h_name: %s\n", host->h_name);
bcopy(host->h_addr, &(ip.s_addr), host->h_length);
printf("IP: %s\n", inet_ntoa(ip));
mHostIP = (char *)malloc(16);
strcpy(mHostIP, inet_ntoa(ip));
}
void http_url_parser::parser(void)
{
int i;
char *tmp;
bool have_port = false;
/*
* URL example.
* http://<host>:<port>/<path>?<searchpart>
* http://10.0.0.201/video/mp4/test.mp4?id=1&ts=10000
*/
mScheme = (char *)malloc(sizeof("http"));
strcpy(mScheme, "http");
mHaveScheme = ! strncmp(mURL, "http://", 7);
tmp = mHaveScheme? mURL + 7 : mURL;
for (i = 0; tmp[i] != '/' && tmp[i]; i ++) {
if (tmp[i] == ':') {
have_port = true;
break;
}
}
if (have_port) {
parser_url_with_port();
} else {
parser_url_without_port();
}
if(! is_host_ip()) {
parser_host_ip();
} else {
mHostIP = (char *)malloc(16);
strcpy(mHostIP, mHost);
}
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "miscellaneous.h"
// Qt headers.
#include <QGridLayout>
#include <QKeySequence>
#include <QLayout>
#include <QLayoutItem>
#include <QMessageBox>
#include <QShortcut>
#include <QSpacerItem>
#include <QWidget>
namespace appleseed {
namespace studio {
void disable_osx_focus_rect(QWidget* widget)
{
widget->setAttribute(Qt::WA_MacShowFocusRect, false);
}
void set_minimum_width(QMessageBox& msgbox, const int minimum_width)
{
QSpacerItem* spacer =
new QSpacerItem(
minimum_width,
0,
QSizePolicy::Minimum,
QSizePolicy::Expanding);
QGridLayout* layout = static_cast<QGridLayout*>(msgbox.layout());
layout->addItem(
spacer,
layout->rowCount(), // row
0, // column
1, // row span
layout->columnCount()); // column span
}
QShortcut* create_window_local_shortcut(QWidget* parent, const Qt::Key key)
{
return
new QShortcut(
QKeySequence(key),
parent,
0,
0,
Qt::WidgetWithChildrenShortcut);
}
void clear_layout(QLayout* layout)
{
while (!layout->isEmpty())
{
QLayoutItem* item = layout->takeAt(0);
if (item->layout())
clear_layout(item->layout());
else item->widget()->deleteLater();
delete item;
}
}
} // namespace studio
} // namespace appleseed
<commit_msg>fixed regression introduced in b310276f19f4be0f808120d8ee88c7c8d567943b ("fixed Qt runtime warning").<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "miscellaneous.h"
// Qt headers.
#include <QGridLayout>
#include <QKeySequence>
#include <QLayout>
#include <QLayoutItem>
#include <QMessageBox>
#include <QShortcut>
#include <QSpacerItem>
#include <QWidget>
namespace appleseed {
namespace studio {
void disable_osx_focus_rect(QWidget* widget)
{
widget->setAttribute(Qt::WA_MacShowFocusRect, false);
}
void set_minimum_width(QMessageBox& msgbox, const int minimum_width)
{
QSpacerItem* spacer =
new QSpacerItem(
minimum_width,
0,
QSizePolicy::Minimum,
QSizePolicy::Expanding);
QGridLayout* layout = static_cast<QGridLayout*>(msgbox.layout());
layout->addItem(
spacer,
layout->rowCount(), // row
0, // column
1, // row span
layout->columnCount()); // column span
}
QShortcut* create_window_local_shortcut(QWidget* parent, const Qt::Key key)
{
return
new QShortcut(
QKeySequence(key),
parent,
0,
0,
Qt::WidgetWithChildrenShortcut);
}
void clear_layout(QLayout* layout)
{
for (int i = layout->count(); i > 0; --i)
{
QLayoutItem* item = layout->takeAt(0);
if (item->layout())
clear_layout(item->layout());
else item->widget()->deleteLater();
delete item;
}
}
} // namespace studio
} // namespace appleseed
<|endoftext|> |
<commit_before>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.1.1.1 2000/05/16 17:00:46 rdm Exp $
// Author: Rene Brun 17/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Rint //
// //
// Rint is the ROOT Interactive Interface. It allows interactive access //
// to the ROOT system via the CINT C/C++ interpreter. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "Getline.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TStopwatch.h"
#include "TCanvas.h"
#include "TBenchmark.h"
#include "TRint.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TSysEvtHandler.h"
#include "TError.h"
#include "TException.h"
#include "TInterpreter.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TFile.h"
#include "TMapFile.h"
#include "TTabCom.h"
#ifdef R__UNIX
#include <signal.h>
extern "C" {
extern int G__get_security_error();
extern int G__genericerror(char* msg);
}
#endif
//----- Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TInterruptHandler : public TSignalHandler {
public:
TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }
Bool_t Notify();
};
//______________________________________________________________________________
Bool_t TInterruptHandler::Notify()
{
// TRint interrupt handler.
if (fDelay) {
fDelay++;
return kTRUE;
}
// make sure we use the sbrk heap (in case of mapped files)
gMmallocDesc = 0;
// go via the interpreter???
// if (gProof) gProof->Interrupt(TProof::kHardInterrupt);
if (!G__get_security_error())
G__genericerror("\n *** Break *** keyboard interrupt");
else {
Printf("\n *** Break *** keyboard interrupt");
if (TROOT::Initialized()) {
Getlinem(kInit, "Root > ");
gInterpreter->RewindDictionary();
Throw(GetSignal());
}
}
return kTRUE;
}
//----- Terminal Input file handler --------------------------------------------
//______________________________________________________________________________
class TTermInputHandler : public TFileHandler {
public:
TTermInputHandler(int fd) : TFileHandler(fd, 1) { }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
//______________________________________________________________________________
Bool_t TTermInputHandler::Notify()
{
gApplication->HandleTermInput();
return kTRUE;
}
ClassImp(TRint)
//______________________________________________________________________________
TRint::TRint(const char *appClassName, int *argc, char **argv, void *options,
int numOptions, Bool_t noLogo)
: TApplication(appClassName, argc, argv, options, numOptions)
{
// Create an application environment. The TRint environment provides an
// interface to the WM manager functionality and eventloop via inheritance
// of TApplication and in addition provides interactive access to
// the CINT C++ interpreter via the command line.
fNcmd = 0;
fDefaultPrompt = "root [%d] ";
fInterrupt = kFALSE;
gBenchmark = new TBenchmark();
if (!noLogo)
PrintLogo();
// Everybody expects iostream to be available, so load it...
#ifndef WIN32
ProcessLine("#include <iostream>");
#endif
// The following libs are also useful to have,
// make sure they are loaded...
gROOT->LoadClass("TGeometry", "Graf3d");
gROOT->LoadClass("TTree", "Tree");
gROOT->LoadClass("TMatrix", "Matrix");
gROOT->LoadClass("TMinuit", "Minuit");
gROOT->LoadClass("TPostScript", "Postscript");
gROOT->LoadClass("TCanvas", "Gpad");
gROOT->LoadClass("THtml", "Html");
// Load user functions
const char *logon;
logon = gEnv->GetValue("Rint.Load", (char*)0);
if (logon) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessLine(Form(".L %s",logon));
delete [] mac;
}
// Execute logon macro
logon = gEnv->GetValue("Rint.Logon", (char*)0);
if (logon && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessFile(logon);
delete [] mac;
}
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// Install interrupt and terminal input handlers
TInterruptHandler *ih = new TInterruptHandler();
gSystem->AddSignalHandler(ih);
SetSignalHandler(ih);
TTermInputHandler *th = new TTermInputHandler(0);
gSystem->AddFileHandler(th);
// Goto into raw terminal input mode
char defhist[128];
#ifndef R__VMS
sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME"));
#else
sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME"));
#endif
logon = gEnv->GetValue("Rint.History", defhist);
Gl_histinit((char *)logon);
Gl_windowchanged();
// Setup for tab completion
gTabCom = new TTabCom;
}
//______________________________________________________________________________
TRint::~TRint()
{
}
//______________________________________________________________________________
void TRint::Run(Bool_t retrn)
{
// Main application eventloop. First process files given on the command
// line and then go into the main application event loop.
Getlinem(kInit, GetPrompt());
// Process shell command line input files
if (InputFiles()) {
TObjString *file;
TIter next(InputFiles());
RETRY {
while ((file = (TObjString *)next())) {
char cmd[256];
if (file->String().EndsWith(".root")) {
const char *rfile = (const char*)file->String();
Printf("\nAttaching file %s...", rfile);
char *base = StrDup(gSystem->BaseName(rfile));
char *s = strchr(base, '.'); *s = 0;
sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile);
delete [] base;
} else {
Printf("\nProcessing %s...", (const char*)file->String());
sprintf(cmd, ".x %s", (const char*)file->String());
}
Getlinem(kCleanUp, 0);
Gl_histadd(cmd);
fNcmd++;
ProcessLine(cmd);
}
} ENDTRY;
if (QuitOpt())
Terminate(0);
ClearInputFiles();
Getlinem(kInit, GetPrompt());
}
TApplication::Run(retrn);
Getlinem(kCleanUp, 0);
}
//______________________________________________________________________________
void TRint::PrintLogo()
{
// Print the ROOT logo on standard output.
Int_t iday,imonth,iyear;
static const char *months[] = {"January","February","March","April","May",
"June","July","August","September","October",
"November","December"};
const char *root_version = gROOT->GetVersion();
Int_t idatqq = gROOT->GetVersionDate();
iday = idatqq%100;
imonth = (idatqq/100)%100;
iyear = (idatqq/10000);
char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear);
Printf(" *******************************************");
Printf(" * *");
Printf(" * W E L C O M E to R O O T *");
Printf(" * *");
Printf(" * Version%10s %17s *",root_version,root_date);
// Printf(" * Development version *");
Printf(" * *");
Printf(" * You are welcome to visit our Web site *");
Printf(" * http://root.cern.ch *");
Printf(" * *");
Printf(" *******************************************");
#ifdef R__UNIX
if (!strcmp(gVirtualX->GetName(), "X11TTF"))
Printf("\nFreeType Engine v1.1 used to render TrueType fonts.");
#endif
#ifdef _REENTRANT
#ifdef R__UNIX
else
#endif
printf("\n");
Printf("Compiled with thread support.");
#endif
gInterpreter->PrintIntro();
#ifdef R__UNIX
// Popdown X logo, only if started with -splash option
for (int i = 0; i < Argc(); i++)
if (!strcmp(Argv(i), "-splash"))
kill(getppid(), SIGUSR1);
#endif
}
//______________________________________________________________________________
char *TRint::GetPrompt()
{
// Get prompt from interpreter. Either "root [n]" or "end with '}'".
char *s = gInterpreter->GetPrompt();
if (s[0])
strcpy(fPrompt, s);
else
sprintf(fPrompt, fDefaultPrompt, fNcmd);
return fPrompt;
}
//______________________________________________________________________________
const char *TRint::SetPrompt(const char *newPrompt)
{
// Set a new default prompt. It returns the previous prompt.
// The prompt may contain a %d which will be replaced by the commend
// number. The default prompt is "root [%d] ". The maximum length of
// the prompt is 55 characters. To set the prompt in an interactive
// session do:
// root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
// aap>
const char *op = fDefaultPrompt;
if (strlen(newPrompt) <= 55)
fDefaultPrompt = newPrompt;
else
Error("SetPrompt", "newPrompt too long (> 55 characters)");
return op;
}
//______________________________________________________________________________
void TRint::HandleTermInput()
{
// Handle input coming from terminal.
static TStopwatch timer;
char *line;
if ((line = Getlinem(kOneChar, 0))) {
if (line[0] == 0 && Gl_eof())
Terminate(0);
if (gROOT->Timer()) timer.Start();
Gl_histadd(line);
char *s = line;
while (s && *s == ' ') s++; // strip-off leading blanks
s[strlen(s)-1] = '\0'; // strip also '\n' off
fInterrupt = kFALSE;
if (!gInterpreter->GetMore() && strlen(s) != 0) fNcmd++;
ProcessLine(s);
if (strstr(s,".reset") != s)
gInterpreter->EndOfLineAction();
if (gROOT->Timer()) timer.Print();
gTabCom->ClearAll();
Getlinem(kInit, GetPrompt());
}
}
//______________________________________________________________________________
void TRint::Terminate(int status)
{
// Terminate the application. Reset the terminal to sane mode and call
// the logoff macro defined via Rint.Logoff environment variable.
Getlinem(kCleanUp, 0);
if (ReturnFromRun()) {
gSystem->ExitLoop();
} else {
//Execute logoff macro
const char *logoff;
logoff = gEnv->GetValue("Rint.Logoff", (char*)0);
if (logoff && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
if (mac)
ProcessFile(logoff);
delete [] mac;
}
gSystem->Exit(status);
}
}
<commit_msg>Correct FreeType message<commit_after>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.2 2000/05/31 18:43:50 rdm Exp $
// Author: Rene Brun 17/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Rint //
// //
// Rint is the ROOT Interactive Interface. It allows interactive access //
// to the ROOT system via the CINT C/C++ interpreter. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "Getline.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TStopwatch.h"
#include "TCanvas.h"
#include "TBenchmark.h"
#include "TRint.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TSysEvtHandler.h"
#include "TError.h"
#include "TException.h"
#include "TInterpreter.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TFile.h"
#include "TMapFile.h"
#include "TTabCom.h"
#ifdef R__UNIX
#include <signal.h>
extern "C" {
extern int G__get_security_error();
extern int G__genericerror(char* msg);
}
#endif
//----- Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TInterruptHandler : public TSignalHandler {
public:
TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }
Bool_t Notify();
};
//______________________________________________________________________________
Bool_t TInterruptHandler::Notify()
{
// TRint interrupt handler.
if (fDelay) {
fDelay++;
return kTRUE;
}
// make sure we use the sbrk heap (in case of mapped files)
gMmallocDesc = 0;
// go via the interpreter???
// if (gProof) gProof->Interrupt(TProof::kHardInterrupt);
if (!G__get_security_error())
G__genericerror("\n *** Break *** keyboard interrupt");
else {
Printf("\n *** Break *** keyboard interrupt");
if (TROOT::Initialized()) {
Getlinem(kInit, "Root > ");
gInterpreter->RewindDictionary();
Throw(GetSignal());
}
}
return kTRUE;
}
//----- Terminal Input file handler --------------------------------------------
//______________________________________________________________________________
class TTermInputHandler : public TFileHandler {
public:
TTermInputHandler(int fd) : TFileHandler(fd, 1) { }
Bool_t Notify();
Bool_t ReadNotify() { return Notify(); }
};
//______________________________________________________________________________
Bool_t TTermInputHandler::Notify()
{
gApplication->HandleTermInput();
return kTRUE;
}
ClassImp(TRint)
//______________________________________________________________________________
TRint::TRint(const char *appClassName, int *argc, char **argv, void *options,
int numOptions, Bool_t noLogo)
: TApplication(appClassName, argc, argv, options, numOptions)
{
// Create an application environment. The TRint environment provides an
// interface to the WM manager functionality and eventloop via inheritance
// of TApplication and in addition provides interactive access to
// the CINT C++ interpreter via the command line.
fNcmd = 0;
fDefaultPrompt = "root [%d] ";
fInterrupt = kFALSE;
gBenchmark = new TBenchmark();
if (!noLogo)
PrintLogo();
// Everybody expects iostream to be available, so load it...
#ifndef WIN32
ProcessLine("#include <iostream>");
#endif
// The following libs are also useful to have,
// make sure they are loaded...
gROOT->LoadClass("TGeometry", "Graf3d");
gROOT->LoadClass("TTree", "Tree");
gROOT->LoadClass("TMatrix", "Matrix");
gROOT->LoadClass("TMinuit", "Minuit");
gROOT->LoadClass("TPostScript", "Postscript");
gROOT->LoadClass("TCanvas", "Gpad");
gROOT->LoadClass("THtml", "Html");
// Load user functions
const char *logon;
logon = gEnv->GetValue("Rint.Load", (char*)0);
if (logon) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessLine(Form(".L %s",logon));
delete [] mac;
}
// Execute logon macro
logon = gEnv->GetValue("Rint.Logon", (char*)0);
if (logon && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
if (mac)
ProcessFile(logon);
delete [] mac;
}
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// Install interrupt and terminal input handlers
TInterruptHandler *ih = new TInterruptHandler();
gSystem->AddSignalHandler(ih);
SetSignalHandler(ih);
TTermInputHandler *th = new TTermInputHandler(0);
gSystem->AddFileHandler(th);
// Goto into raw terminal input mode
char defhist[128];
#ifndef R__VMS
sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME"));
#else
sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME"));
#endif
logon = gEnv->GetValue("Rint.History", defhist);
Gl_histinit((char *)logon);
Gl_windowchanged();
// Setup for tab completion
gTabCom = new TTabCom;
}
//______________________________________________________________________________
TRint::~TRint()
{
}
//______________________________________________________________________________
void TRint::Run(Bool_t retrn)
{
// Main application eventloop. First process files given on the command
// line and then go into the main application event loop.
Getlinem(kInit, GetPrompt());
// Process shell command line input files
if (InputFiles()) {
TObjString *file;
TIter next(InputFiles());
RETRY {
while ((file = (TObjString *)next())) {
char cmd[256];
if (file->String().EndsWith(".root")) {
const char *rfile = (const char*)file->String();
Printf("\nAttaching file %s...", rfile);
char *base = StrDup(gSystem->BaseName(rfile));
char *s = strchr(base, '.'); *s = 0;
sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile);
delete [] base;
} else {
Printf("\nProcessing %s...", (const char*)file->String());
sprintf(cmd, ".x %s", (const char*)file->String());
}
Getlinem(kCleanUp, 0);
Gl_histadd(cmd);
fNcmd++;
ProcessLine(cmd);
}
} ENDTRY;
if (QuitOpt())
Terminate(0);
ClearInputFiles();
Getlinem(kInit, GetPrompt());
}
TApplication::Run(retrn);
Getlinem(kCleanUp, 0);
}
//______________________________________________________________________________
void TRint::PrintLogo()
{
// Print the ROOT logo on standard output.
Int_t iday,imonth,iyear;
static const char *months[] = {"January","February","March","April","May",
"June","July","August","September","October",
"November","December"};
const char *root_version = gROOT->GetVersion();
Int_t idatqq = gROOT->GetVersionDate();
iday = idatqq%100;
imonth = (idatqq/100)%100;
iyear = (idatqq/10000);
char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear);
Printf(" *******************************************");
Printf(" * *");
Printf(" * W E L C O M E to R O O T *");
Printf(" * *");
Printf(" * Version%10s %17s *",root_version,root_date);
// Printf(" * Development version *");
Printf(" * *");
Printf(" * You are welcome to visit our Web site *");
Printf(" * http://root.cern.ch *");
Printf(" * *");
Printf(" *******************************************");
#ifdef R__UNIX
if (!strcmp(gVirtualX->GetName(), "X11TTF"))
Printf("\nFreeType Engine v1.x used to render TrueType fonts.");
#endif
#ifdef _REENTRANT
#ifdef R__UNIX
else
#endif
printf("\n");
Printf("Compiled with thread support.");
#endif
gInterpreter->PrintIntro();
#ifdef R__UNIX
// Popdown X logo, only if started with -splash option
for (int i = 0; i < Argc(); i++)
if (!strcmp(Argv(i), "-splash"))
kill(getppid(), SIGUSR1);
#endif
}
//______________________________________________________________________________
char *TRint::GetPrompt()
{
// Get prompt from interpreter. Either "root [n]" or "end with '}'".
char *s = gInterpreter->GetPrompt();
if (s[0])
strcpy(fPrompt, s);
else
sprintf(fPrompt, fDefaultPrompt, fNcmd);
return fPrompt;
}
//______________________________________________________________________________
const char *TRint::SetPrompt(const char *newPrompt)
{
// Set a new default prompt. It returns the previous prompt.
// The prompt may contain a %d which will be replaced by the commend
// number. The default prompt is "root [%d] ". The maximum length of
// the prompt is 55 characters. To set the prompt in an interactive
// session do:
// root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
// aap>
const char *op = fDefaultPrompt;
if (strlen(newPrompt) <= 55)
fDefaultPrompt = newPrompt;
else
Error("SetPrompt", "newPrompt too long (> 55 characters)");
return op;
}
//______________________________________________________________________________
void TRint::HandleTermInput()
{
// Handle input coming from terminal.
static TStopwatch timer;
char *line;
if ((line = Getlinem(kOneChar, 0))) {
if (line[0] == 0 && Gl_eof())
Terminate(0);
if (gROOT->Timer()) timer.Start();
Gl_histadd(line);
char *s = line;
while (s && *s == ' ') s++; // strip-off leading blanks
s[strlen(s)-1] = '\0'; // strip also '\n' off
fInterrupt = kFALSE;
if (!gInterpreter->GetMore() && strlen(s) != 0) fNcmd++;
ProcessLine(s);
if (strstr(s,".reset") != s)
gInterpreter->EndOfLineAction();
if (gROOT->Timer()) timer.Print();
gTabCom->ClearAll();
Getlinem(kInit, GetPrompt());
}
}
//______________________________________________________________________________
void TRint::Terminate(int status)
{
// Terminate the application. Reset the terminal to sane mode and call
// the logoff macro defined via Rint.Logoff environment variable.
Getlinem(kCleanUp, 0);
if (ReturnFromRun()) {
gSystem->ExitLoop();
} else {
//Execute logoff macro
const char *logoff;
logoff = gEnv->GetValue("Rint.Logoff", (char*)0);
if (logoff && !NoLogOpt()) {
char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
if (mac)
ProcessFile(logoff);
delete [] mac;
}
gSystem->Exit(status);
}
}
<|endoftext|> |
<commit_before><commit_msg>Add ninja dependency reference to gen written files.<commit_after><|endoftext|> |
<commit_before>#include "catch.hpp"
#include "expected.hpp"
#include <string>
using std::string;
tl::expected<int, string> getInt3(int val) { return val; }
tl::expected<int, string> getInt2(int val) { return val; }
tl::expected<int, string> getInt1() { return getInt2(5).and_then(getInt3); }
TEST_CASE("Issue 1", "[issues.1]") { getInt1(); }
tl::expected<int, int> operation1() { return 42; }
tl::expected<std::string, int> operation2(int const val) { return "Bananas"; }
TEST_CASE("Issue 17", "[issues.17]") {
auto const intermediate_result = operation1();
intermediate_result.and_then(operation2);
}
struct a {};
struct b : a {};
auto doit() -> tl::expected<std::unique_ptr<b>, int> {
return tl::make_unexpected(0);
}
TEST_CASE("Issue 23", "[issues.23]") {
tl::expected<std::unique_ptr<a>, int> msg = doit();
REQUIRE(!msg.has_value());
}
TEST_CASE("Issue 26", "[issues.26]") {
tl::expected<a, int> exp = tl::expected<b, int>(tl::unexpect, 0);
REQUIRE(!exp.has_value());
}
struct foo {
foo() = default;
foo(foo &) = delete;
foo(foo &&){};
};
TEST_CASE("Issue 29", "[issues.29]") {
std::vector<foo> v;
v.emplace_back();
tl::expected<std::vector<foo>, int> ov = std::move(v);
REQUIRE(ov->size() == 1);
}
tl::expected<int, std::string> error() {
return tl::make_unexpected(std::string("error1 "));
}
std::string maperror(std::string s) { return s + "maperror "; }
TEST_CASE("Issue 30", "[issues.30]") {
error().map_error(maperror);
}
struct i31{
int i;
};
TEST_CASE("Issue 31", "[issues.31]") {
const tl::expected<i31, int> a = i31{42};
a->i;
tl::expected< void, std::string > result;
tl::expected< void, std::string > result2 = result;
result2 = result;
}
TEST_CASE("Issue 33", "[issues.33]") {
tl::expected<void, int> res {tl::unexpect, 0};
REQUIRE(!res);
res = res.map_error([](int i) { return 42; });
REQUIRE(res.error() == 42);
}
tl::expected<void, std::string> voidWork() { return {}; }
tl::expected<int, std::string> work2() { return 42; }
void errorhandling(std::string){}
TEST_CASE("Issue 34", "[issues.34]") {
tl::expected <int, std::string> result = voidWork ()
.and_then (work2);
result.map_error ([&] (std::string result) {errorhandling (result);});
}
struct non_copyable {
non_copyable(non_copyable&&) = default;
non_copyable(non_copyable const&) = delete;
non_copyable() = default;
};
TEST_CASE("Issue 42", "[issues.42]") {
tl::expected<non_copyable,int>{}.map([](non_copyable) {});
}
TEST_CASE("Issue 43", "[issues.43]") {
auto result = tl::expected<void, std::string>{};
result = tl::make_unexpected(std::string{ "foo" });
}
#include <memory>
using MaybeDataPtr = tl::expected<int, std::unique_ptr<int>>;
MaybeDataPtr test(int i) noexcept
{
return std::move(i);
}
MaybeDataPtr test2(int i) noexcept
{
return std::move(i);
}
TEST_CASE("Issue 49", "[issues.49]") {
auto m = test(10)
.and_then(test2);
}
<commit_msg>ifdef out GCC compiler error<commit_after>#include "catch.hpp"
#include "expected.hpp"
#include <string>
using std::string;
tl::expected<int, string> getInt3(int val) { return val; }
tl::expected<int, string> getInt2(int val) { return val; }
tl::expected<int, string> getInt1() { return getInt2(5).and_then(getInt3); }
TEST_CASE("Issue 1", "[issues.1]") { getInt1(); }
tl::expected<int, int> operation1() { return 42; }
tl::expected<std::string, int> operation2(int const val) { return "Bananas"; }
TEST_CASE("Issue 17", "[issues.17]") {
auto const intermediate_result = operation1();
intermediate_result.and_then(operation2);
}
struct a {};
struct b : a {};
auto doit() -> tl::expected<std::unique_ptr<b>, int> {
return tl::make_unexpected(0);
}
TEST_CASE("Issue 23", "[issues.23]") {
tl::expected<std::unique_ptr<a>, int> msg = doit();
REQUIRE(!msg.has_value());
}
TEST_CASE("Issue 26", "[issues.26]") {
tl::expected<a, int> exp = tl::expected<b, int>(tl::unexpect, 0);
REQUIRE(!exp.has_value());
}
struct foo {
foo() = default;
foo(foo &) = delete;
foo(foo &&){};
};
TEST_CASE("Issue 29", "[issues.29]") {
std::vector<foo> v;
v.emplace_back();
tl::expected<std::vector<foo>, int> ov = std::move(v);
REQUIRE(ov->size() == 1);
}
tl::expected<int, std::string> error() {
return tl::make_unexpected(std::string("error1 "));
}
std::string maperror(std::string s) { return s + "maperror "; }
TEST_CASE("Issue 30", "[issues.30]") {
error().map_error(maperror);
}
struct i31{
int i;
};
TEST_CASE("Issue 31", "[issues.31]") {
const tl::expected<i31, int> a = i31{42};
a->i;
tl::expected< void, std::string > result;
tl::expected< void, std::string > result2 = result;
result2 = result;
}
TEST_CASE("Issue 33", "[issues.33]") {
tl::expected<void, int> res {tl::unexpect, 0};
REQUIRE(!res);
res = res.map_error([](int i) { return 42; });
REQUIRE(res.error() == 42);
}
tl::expected<void, std::string> voidWork() { return {}; }
tl::expected<int, std::string> work2() { return 42; }
void errorhandling(std::string){}
TEST_CASE("Issue 34", "[issues.34]") {
tl::expected <int, std::string> result = voidWork ()
.and_then (work2);
result.map_error ([&] (std::string result) {errorhandling (result);});
}
struct non_copyable {
non_copyable(non_copyable&&) = default;
non_copyable(non_copyable const&) = delete;
non_copyable() = default;
};
TEST_CASE("Issue 42", "[issues.42]") {
tl::expected<non_copyable,int>{}.map([](non_copyable) {});
}
TEST_CASE("Issue 43", "[issues.43]") {
auto result = tl::expected<void, std::string>{};
result = tl::make_unexpected(std::string{ "foo" });
}
#if !(__GNUC__ <= 5)
#include <memory>
using MaybeDataPtr = tl::expected<int, std::unique_ptr<int>>;
MaybeDataPtr test(int i) noexcept
{
return std::move(i);
}
MaybeDataPtr test2(int i) noexcept
{
return std::move(i);
}
TEST_CASE("Issue 49", "[issues.49]") {
auto m = test(10)
.and_then(test2);
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 <array>
#include "util/Compiler.h"
#if CLANG_VERSION >= GCC_MAKE_VERSION(11,0,0)
#pragma GCC diagnostic ignored "-Wkeyword-macro"
#endif
/* horrible kludge which allows us to access private members */
#define class struct
#include "util/HashRing.hxx"
#undef class
#include "lb/MemberHash.hxx"
#include "avahi/Check.hxx"
#include "avahi/Client.hxx"
#include "avahi/Explorer.hxx"
#include "avahi/ExplorerListener.hxx"
#include "event/ShutdownListener.hxx"
#include "event/TimerEvent.hxx"
#include "system/Error.hxx"
#include "net/AllocatedSocketAddress.hxx"
#include "net/ToString.hxx"
#include "util/PrintException.hxx"
#include "PInstance.hxx"
#include <map>
#include <vector>
#include <assert.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <net/if.h> // for if_nametoindex()
struct Context final : PInstance, AvahiServiceExplorerListener {
ShutdownListener shutdown_listener;
MyAvahiClient avahi_client{event_loop, "DumpZeroconfHashRing"};
AvahiServiceExplorer explorer;
using MemberMap = std::map<std::string, AllocatedSocketAddress>;
MemberMap members;
TimerEvent dump_event;
Context(AvahiIfIndex zeroconf_interface, const char *zeroconf_service)
:shutdown_listener(event_loop, BIND_THIS_METHOD(OnShutdown)),
explorer(avahi_client, *this,
zeroconf_interface, AVAHI_PROTO_UNSPEC,
zeroconf_service, nullptr),
dump_event(event_loop, BIND_THIS_METHOD(Dump))
{
shutdown_listener.Enable();
}
void OnShutdown() noexcept {
shutdown_listener.Disable();
avahi_client.Close();
}
void Dump() noexcept;
/* virtual methods from class AvahiServiceExplorerListener */
void OnAvahiNewObject(const std::string &key,
SocketAddress address) noexcept override;
void OnAvahiRemoveObject(const std::string &key) noexcept override;
};
void
Context::Dump() noexcept
{
MemberHashRing<MemberMap::value_type> ring;
BuildMemberHashRing(ring, members,
[](MemberMap::const_reference member) noexcept {
return member.second;
});
std::map<MemberMap::const_pointer, std::size_t> counts;
for (const auto &i : ring.buckets)
++counts[i];
std::map<std::size_t, MemberMap::const_reference> sorted;
for (const auto &i : counts)
sorted.emplace(i.second, *i.first);
printf("HashRing:\n");
for (const auto &i : sorted) {
char buffer[1024];
printf("%8zu %s %s\n", i.first,
i.second.first.c_str(),
ToString(buffer, sizeof(buffer), i.second.second,
"unknown"));
}
}
void
Context::OnAvahiNewObject(const std::string &key,
SocketAddress address) noexcept
{
members.insert_or_assign(key, address);
dump_event.Schedule(std::chrono::seconds(1));
}
void
Context::OnAvahiRemoveObject(const std::string &key) noexcept
{
auto i = members.find(key);
if (i != members.end())
members.erase(i);
dump_event.Schedule(std::chrono::seconds(1));
}
static AvahiIfIndex
ParseInterfaceName(const char *name)
{
int i = if_nametoindex(name);
if (i == 0)
throw FormatErrno("Failed to find interface '%s'", name);
return AvahiIfIndex(i);
}
int
main(int argc, char **argv) noexcept
try {
if (argc < 2 || argc > 3) {
fprintf(stderr, "Usage: %s SERVICE [INTERFACE]\n", argv[0]);
return EXIT_FAILURE;
}
const char *const zeroconf_service = argv[1];
const AvahiIfIndex zeroconf_interface = argc > 2
? ParseInterfaceName(argv[2])
: AVAHI_IF_UNSPEC;
Context ctx(zeroconf_interface,
MakeZeroconfServiceType(zeroconf_service, "_tcp").c_str());
ctx.event_loop.Dispatch();
return EXIT_SUCCESS;
} catch (const std::exception &e) {
PrintException(e);
return EXIT_FAILURE;
}
<commit_msg>test/DumpZeroconfHashRing: disable -Wkeyword-macro in clang 10<commit_after>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 <array>
#include "util/Compiler.h"
#if CLANG_VERSION >= GCC_MAKE_VERSION(10,0,0)
#pragma GCC diagnostic ignored "-Wkeyword-macro"
#endif
/* horrible kludge which allows us to access private members */
#define class struct
#include "util/HashRing.hxx"
#undef class
#include "lb/MemberHash.hxx"
#include "avahi/Check.hxx"
#include "avahi/Client.hxx"
#include "avahi/Explorer.hxx"
#include "avahi/ExplorerListener.hxx"
#include "event/ShutdownListener.hxx"
#include "event/TimerEvent.hxx"
#include "system/Error.hxx"
#include "net/AllocatedSocketAddress.hxx"
#include "net/ToString.hxx"
#include "util/PrintException.hxx"
#include "PInstance.hxx"
#include <map>
#include <vector>
#include <assert.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <net/if.h> // for if_nametoindex()
struct Context final : PInstance, AvahiServiceExplorerListener {
ShutdownListener shutdown_listener;
MyAvahiClient avahi_client{event_loop, "DumpZeroconfHashRing"};
AvahiServiceExplorer explorer;
using MemberMap = std::map<std::string, AllocatedSocketAddress>;
MemberMap members;
TimerEvent dump_event;
Context(AvahiIfIndex zeroconf_interface, const char *zeroconf_service)
:shutdown_listener(event_loop, BIND_THIS_METHOD(OnShutdown)),
explorer(avahi_client, *this,
zeroconf_interface, AVAHI_PROTO_UNSPEC,
zeroconf_service, nullptr),
dump_event(event_loop, BIND_THIS_METHOD(Dump))
{
shutdown_listener.Enable();
}
void OnShutdown() noexcept {
shutdown_listener.Disable();
avahi_client.Close();
}
void Dump() noexcept;
/* virtual methods from class AvahiServiceExplorerListener */
void OnAvahiNewObject(const std::string &key,
SocketAddress address) noexcept override;
void OnAvahiRemoveObject(const std::string &key) noexcept override;
};
void
Context::Dump() noexcept
{
MemberHashRing<MemberMap::value_type> ring;
BuildMemberHashRing(ring, members,
[](MemberMap::const_reference member) noexcept {
return member.second;
});
std::map<MemberMap::const_pointer, std::size_t> counts;
for (const auto &i : ring.buckets)
++counts[i];
std::map<std::size_t, MemberMap::const_reference> sorted;
for (const auto &i : counts)
sorted.emplace(i.second, *i.first);
printf("HashRing:\n");
for (const auto &i : sorted) {
char buffer[1024];
printf("%8zu %s %s\n", i.first,
i.second.first.c_str(),
ToString(buffer, sizeof(buffer), i.second.second,
"unknown"));
}
}
void
Context::OnAvahiNewObject(const std::string &key,
SocketAddress address) noexcept
{
members.insert_or_assign(key, address);
dump_event.Schedule(std::chrono::seconds(1));
}
void
Context::OnAvahiRemoveObject(const std::string &key) noexcept
{
auto i = members.find(key);
if (i != members.end())
members.erase(i);
dump_event.Schedule(std::chrono::seconds(1));
}
static AvahiIfIndex
ParseInterfaceName(const char *name)
{
int i = if_nametoindex(name);
if (i == 0)
throw FormatErrno("Failed to find interface '%s'", name);
return AvahiIfIndex(i);
}
int
main(int argc, char **argv) noexcept
try {
if (argc < 2 || argc > 3) {
fprintf(stderr, "Usage: %s SERVICE [INTERFACE]\n", argv[0]);
return EXIT_FAILURE;
}
const char *const zeroconf_service = argv[1];
const AvahiIfIndex zeroconf_interface = argc > 2
? ParseInterfaceName(argv[2])
: AVAHI_IF_UNSPEC;
Context ctx(zeroconf_interface,
MakeZeroconfServiceType(zeroconf_service, "_tcp").c_str());
ctx.event_loop.Dispatch();
return EXIT_SUCCESS;
} catch (const std::exception &e) {
PrintException(e);
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include "consts.h"
#include "circuits/circuit.h"
#include "matrix/newtonraphson.h"
using namespace std;
static const int MAX_ATTEMPTS = 500;
static const int MAX_LOOPS = 1000;
static const double TOLERANCE = 1e-4;
void randomize(int numVariables, double (&solution)[MAX_NODES+1]){
solution[0] = 0; // gnd
for(int i=1; i<=numVariables; i++){
solution[i] = (double(rand()) / double(RAND_MAX)) - 0.5;
}
}
double calcDistance(int numVariables, double x[MAX_NODES+1], double y[MAX_NODES+1]){
double sum=0;
double distance=0;
for(int i=1; i<=numVariables ;i++) {
sum += pow((x[i]-y[i]),2);
}
distance = sqrt(sum);
return distance;
}
void printSolution(int numVariables, double solution[MAX_NODES+1]){
for(int i=1; i<=numVariables; i++){
cout << solution[i] << endl;
}
cout << endl;
}
int runNewtonRaphson(Circuit circuit,
double (&finalSolution)[MAX_NODES+1],
double t,
double (&lastSolution)[MAX_NODES+1]){
int rc=0;
int numAttempts=0;
int numLoops=0;
bool converged=false;
double solution[MAX_NODES+1];
double distance=0;
double previousSolution[MAX_NODES+1];
double Yn[MAX_NODES+1][MAX_NODES+2];
copySolution(circuit.getNumVariables(), ZERO_SOLUTION, previousSolution);
while(!converged && numAttempts <= MAX_ATTEMPTS ){
numAttempts++;
numLoops=0;
while(!converged && numLoops <= MAX_LOOPS){
numLoops++;
init(circuit.getNumVariables(), Yn);
circuit.applyStamps(Yn,
previousSolution,
t,
lastSolution);
rc = solve(circuit.getNumVariables(), Yn);
if (rc)
// Let's try a new randomized initial solution!
break;
getSolution(circuit.getNumVariables(),
Yn,
solution);
distance = calcDistance(circuit.getNumVariables(),
solution,
previousSolution);
if (distance < TOLERANCE){
converged = true;
solution[0] = 0; // Ground!
copySolution(circuit.getNumVariables(),
solution,
finalSolution);
} else {
copySolution(circuit.getNumVariables(),
solution,
previousSolution);
}
}
randomize(circuit.getNumVariables(), previousSolution);
}
if (!converged){
cout << "Newton Raphson did not converge.";
#if defined (WIN32) || defined(_WIN32)
cout << endl << "Press any key to exit...";
cin.get();
cin.get();
#endif
exit(EXIT_FAILURE);
}
return 0;
}
<commit_msg>Raises range for Newton Raphson initialization<commit_after>#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include "consts.h"
#include "circuits/circuit.h"
#include "matrix/newtonraphson.h"
using namespace std;
static const int MAX_ATTEMPTS = 500;
static const int MAX_LOOPS = 1000;
static const double TOLERANCE = 1e-4;
void randomize(int numVariables, double (&solution)[MAX_NODES+1]){
solution[0] = 0; // gnd
for(int i=1; i<=numVariables; i++){
solution[i] = ((double(rand()) / double(RAND_MAX)) - 0.5)*100;
}
}
double calcDistance(int numVariables, double x[MAX_NODES+1], double y[MAX_NODES+1]){
double sum=0;
double distance=0;
for(int i=1; i<=numVariables ;i++) {
sum += pow((x[i]-y[i]),2);
}
distance = sqrt(sum);
return distance;
}
void printSolution(int numVariables, double solution[MAX_NODES+1]){
for(int i=1; i<=numVariables; i++){
cout << solution[i] << endl;
}
cout << endl;
}
int runNewtonRaphson(Circuit circuit,
double (&finalSolution)[MAX_NODES+1],
double t,
double (&lastSolution)[MAX_NODES+1]){
int rc=0;
int numAttempts=0;
int numLoops=0;
bool converged=false;
double solution[MAX_NODES+1];
double distance=0;
double previousSolution[MAX_NODES+1];
double Yn[MAX_NODES+1][MAX_NODES+2];
copySolution(circuit.getNumVariables(), ZERO_SOLUTION, previousSolution);
while(!converged && numAttempts <= MAX_ATTEMPTS ){
numAttempts++;
numLoops=0;
while(!converged && numLoops <= MAX_LOOPS){
numLoops++;
init(circuit.getNumVariables(), Yn);
circuit.applyStamps(Yn,
previousSolution,
t,
lastSolution);
rc = solve(circuit.getNumVariables(), Yn);
if (rc)
// Let's try a new randomized initial solution!
break;
getSolution(circuit.getNumVariables(),
Yn,
solution);
distance = calcDistance(circuit.getNumVariables(),
solution,
previousSolution);
if (distance < TOLERANCE){
converged = true;
solution[0] = 0; // Ground!
copySolution(circuit.getNumVariables(),
solution,
finalSolution);
} else {
copySolution(circuit.getNumVariables(),
solution,
previousSolution);
}
}
randomize(circuit.getNumVariables(), previousSolution);
}
if (!converged){
cout << "Newton Raphson did not converge.";
#if defined (WIN32) || defined(_WIN32)
cout << endl << "Press any key to exit...";
cin.get();
cin.get();
#endif
exit(EXIT_FAILURE);
}
return 0;
}
<|endoftext|> |
<commit_before>// RUN: rm -rf %t
// Test that only forward declarations are emitted for types dfined in modules.
// Modules:
// RUN: %clang_cc1 -x objective-c++ -std=c++11 -debug-info-kind=limited \
// RUN: -dwarf-ext-refs -fmodules \
// RUN: -fmodule-format=obj -fimplicit-module-maps -DMODULES \
// RUN: -triple %itanium_abi_triple \
// RUN: -fmodules-cache-path=%t %s -I %S/Inputs -I %t -emit-llvm -o %t-mod.ll
// RUN: cat %t-mod.ll | FileCheck %s
// PCH:
// RUN: %clang_cc1 -x c++ -std=c++11 -fmodule-format=obj -emit-pch -I%S/Inputs \
// RUN: -triple %itanium_abi_triple \
// RUN: -o %t.pch %S/Inputs/DebugCXX.h
// RUN: %clang_cc1 -std=c++11 -debug-info-kind=limited \
// RUN: -dwarf-ext-refs -fmodule-format=obj \
// RUN: -triple %itanium_abi_triple \
// RUN: -include-pch %t.pch %s -emit-llvm -o %t-pch.ll %s
// RUN: cat %t-pch.ll | FileCheck %s
// RUN: cat %t-pch.ll | FileCheck %s --check-prefix=CHECK-PCH
#ifdef MODULES
@import DebugCXX;
#endif
using DebugCXX::Struct;
Struct s;
DebugCXX::Enum e;
DebugCXX::Template<long> implicitTemplate;
DebugCXX::Template<int> explicitTemplate;
DebugCXX::FloatInstatiation typedefTemplate;
int Struct::static_member = -1;
enum {
e3 = -1
} conflicting_uid = e3;
auto anon_enum = DebugCXX::e2;
char _anchor = anon_enum + conflicting_uid;
TypedefUnion tdu;
TypedefEnum tde;
TypedefStruct tds;
InAnonymousNamespace anon;
void foo() {
anon.i = GlobalStruct.i = GlobalUnion.i = GlobalEnum;
}
// CHECK: ![[NS:.*]] = !DINamespace(name: "DebugCXX", scope: ![[MOD:[0-9]+]],
// CHECK: ![[MOD]] = !DIModule(scope: null, name: {{.*}}DebugCXX
// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Struct",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX6StructE")
// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "Enum",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX4EnumE")
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK-SAME: name: "Template<int, DebugCXX::traits<int> >",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIiNS_6traitsIiEEEE")
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK-SAME: name: "Template<float, DebugCXX::traits<float> >",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIfNS_6traitsIfEEEE")
// CHECK: !DICompositeType(tag: DW_TAG_union_type,
// CHECK-SAME: flags: DIFlagFwdDecl, identifier: "_ZTS12TypedefUnion")
// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type,
// CHECK-SAME: flags: DIFlagFwdDecl, identifier: "_ZTS11TypedefEnum")
// CHECK: !DICompositeType(tag: DW_TAG_structure_type,
// CHECK-SAME: flags: DIFlagFwdDecl, identifier: "_ZTS13TypedefStruct")
// CHECK: !DIDerivedType(tag: DW_TAG_member, name: "static_member",
// CHECK-SAME: scope: !"_ZTSN8DebugCXX6StructE"
// CHECK: !DIGlobalVariable(name: "anon_enum", {{.*}}, type: ![[ANON_ENUM:[0-9]+]]
// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, scope: ![[NS]],
// CHECK-SAME: line: 16
// CHECK: !DIGlobalVariable(name: "GlobalUnion",
// CHECK-SAME: type: ![[GLOBAL_UNION:[0-9]+]]
// CHECK: ![[GLOBAL_UNION]] = !DICompositeType(tag: DW_TAG_union_type,
// CHECK-SAME: elements: !{{[0-9]+}})
// CHECK: !DIGlobalVariable(name: "GlobalStruct",
// CHECK-SAME: type: ![[GLOBAL_STRUCT:[0-9]+]]
// CHECK: ![[GLOBAL_STRUCT]] = !DICompositeType(tag: DW_TAG_structure_type,
// CHECK-SAME: elements: !{{[0-9]+}})
// CHECK: !DIGlobalVariable(name: "anon",
// CHECK-SAME: type: ![[GLOBAL_ANON:[0-9]+]]
// CHECK: ![[GLOBAL_ANON]] = !DICompositeType(tag: DW_TAG_structure_type,
// CHECK-SAME: name: "InAnonymousNamespace", {{.*}}DIFlagFwdDecl)
// CHECK: !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: !0, entity: !"_ZTSN8DebugCXX6StructE", line: 27)
// CHECK: !DICompileUnit(
// CHECK-SAME: splitDebugFilename:
// CHECK-SAME: dwoId:
// CHECK-PCH: dwoId: 18446744073709551614
<commit_msg>Rephrase this test to help debug a buildbot issue<commit_after>// RUN: rm -rf %t
// Test that only forward declarations are emitted for types dfined in modules.
// Modules:
// RUN: %clang_cc1 -x objective-c++ -std=c++11 -debug-info-kind=limited \
// RUN: -dwarf-ext-refs -fmodules \
// RUN: -fmodule-format=obj -fimplicit-module-maps -DMODULES \
// RUN: -triple %itanium_abi_triple \
// RUN: -fmodules-cache-path=%t %s -I %S/Inputs -I %t -emit-llvm -o %t-mod.ll
// RUN: cat %t-mod.ll | FileCheck %s
// PCH:
// RUN: %clang_cc1 -x c++ -std=c++11 -fmodule-format=obj -emit-pch -I%S/Inputs \
// RUN: -triple %itanium_abi_triple \
// RUN: -o %t.pch %S/Inputs/DebugCXX.h
// RUN: %clang_cc1 -std=c++11 -debug-info-kind=limited \
// RUN: -dwarf-ext-refs -fmodule-format=obj \
// RUN: -triple %itanium_abi_triple \
// RUN: -include-pch %t.pch %s -emit-llvm -o %t-pch.ll %s
// RUN: cat %t-pch.ll | FileCheck %s
// RUN: cat %t-pch.ll | FileCheck %s --check-prefix=CHECK-PCH
#ifdef MODULES
@import DebugCXX;
#endif
using DebugCXX::Struct;
Struct s;
DebugCXX::Enum e;
DebugCXX::Template<long> implicitTemplate;
DebugCXX::Template<int> explicitTemplate;
DebugCXX::FloatInstatiation typedefTemplate;
int Struct::static_member = -1;
enum {
e3 = -1
} conflicting_uid = e3;
auto anon_enum = DebugCXX::e2;
char _anchor = anon_enum + conflicting_uid;
TypedefUnion tdu;
TypedefEnum tde;
TypedefStruct tds;
InAnonymousNamespace anon;
void foo() {
anon.i = GlobalStruct.i = GlobalUnion.i = GlobalEnum;
}
// CHECK: ![[NS:.*]] = !DINamespace(name: "DebugCXX", scope: ![[MOD:[0-9]+]],
// CHECK: ![[MOD]] = !DIModule(scope: null, name: {{.*}}DebugCXX
// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Struct",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX6StructE")
// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "Enum",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX4EnumE")
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK-SAME: name: "Template<int, DebugCXX::traits<int> >",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIiNS_6traitsIiEEEE")
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK-SAME: name: "Template<float, DebugCXX::traits<float> >",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIfNS_6traitsIfEEEE")
// CHECK: !DICompositeType(tag: DW_TAG_union_type,
// CHECK-SAME: flags: DIFlagFwdDecl, identifier: "_ZTS12TypedefUnion")
// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type,
// CHECK-SAME: flags: DIFlagFwdDecl, identifier: "_ZTS11TypedefEnum")
// CHECK: !DICompositeType(tag: DW_TAG_structure_type,
// CHECK-SAME: flags: DIFlagFwdDecl, identifier: "_ZTS13TypedefStruct")
// CHECK: !DIDerivedType(tag: DW_TAG_member, name: "static_member",
// CHECK-SAME: scope: !"_ZTSN8DebugCXX6StructE"
// CHECK: !DIGlobalVariable(name: "anon_enum", {{.*}}, type: ![[ANON_ENUM:[0-9]+]]
// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, scope: ![[NS]],
// CHECK-SAME: line: 16
// CHECK: !DIGlobalVariable(name: "GlobalUnion",
// CHECK-SAME: type: ![[GLOBAL_UNION:[0-9]+]]
// CHECK: ![[GLOBAL_UNION]] = !DICompositeType(tag: DW_TAG_union_type,
// CHECK-SAME: elements: !{{[0-9]+}})
// CHECK: !DIGlobalVariable(name: "GlobalStruct",
// CHECK-SAME: type: ![[GLOBAL_STRUCT:[0-9]+]]
// CHECK: ![[GLOBAL_STRUCT]] = !DICompositeType(tag: DW_TAG_structure_type,
// CHECK-SAME: elements: !{{[0-9]+}})
// CHECK: !DIGlobalVariable(name: "anon",
// CHECK-SAME: type: ![[GLOBAL_ANON:[0-9]+]]
// CHECK: ![[GLOBAL_ANON]] = !DICompositeType(tag: DW_TAG_structure_type,
// CHECK-SAME: name: "InAnonymousNamespace", {{.*}}DIFlagFwdDecl)
// CHECK: !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: !0, entity: !"_ZTSN8DebugCXX6StructE", line: 27)
// CHECK: !DICompileUnit(
// CHECK-SAME: splitDebugFilename:
// CHECK-SAME: dwoId:
// CHECK-PCH: !DICompileUnit({{.*}}splitDebugFilename:
// CHECK-PCH: dwoId: 18446744073709551614
<|endoftext|> |
<commit_before>//===- llvm/Transforms/DecomposeMultiDimRefs.cpp - Lower array refs to 1D -===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// DecomposeMultiDimRefs - Convert multi-dimensional references consisting of
// any combination of 2 or more array and structure indices into a sequence of
// instructions (using getelementpr and cast) so that each instruction has at
// most one index (except structure references, which need an extra leading
// index of [0]).
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Constants.h"
#include "llvm/Constant.h"
#include "llvm/Instructions.h"
#include "llvm/BasicBlock.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
namespace {
Statistic<> NumAdded("lowerrefs", "# of getelementptr instructions added");
struct DecomposePass : public BasicBlockPass {
virtual bool runOnBasicBlock(BasicBlock &BB);
};
RegisterOpt<DecomposePass> X("lowerrefs", "Decompose multi-dimensional "
"structure/array references");
}
// runOnBasicBlock - Entry point for array or structure references with multiple
// indices.
//
bool DecomposePass::runOnBasicBlock(BasicBlock &BB) {
bool changed = false;
for (BasicBlock::iterator II = BB.begin(); II != BB.end(); )
if (GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(II++)) // pre-inc
if (gep->getNumIndices() >= 2)
changed |= DecomposeArrayRef(gep); // always modifies II
return changed;
}
FunctionPass *llvm::createDecomposeMultiDimRefsPass() {
return new DecomposePass();
}
static inline bool isZeroConst (Value *V) {
return isa<Constant> (V) && (cast<Constant>(V)->isNullValue());
}
// Function: DecomposeArrayRef()
//
// For any GetElementPtrInst with 2 or more array and structure indices:
//
// opCode CompositeType* P, [uint|ubyte] idx1, ..., [uint|ubyte] idxN
//
// this function generates the following sequence:
//
// ptr1 = getElementPtr P, idx1
// ptr2 = getElementPtr ptr1, 0, idx2
// ...
// ptrN-1 = getElementPtr ptrN-2, 0, idxN-1
// opCode ptrN-1, 0, idxN // New-MAI
//
// Then it replaces the original instruction with this sequence,
// and replaces all uses of the original instruction with New-MAI.
// If idx1 is 0, we simply omit the first getElementPtr instruction.
//
// On return: BBI points to the instruction after the current one
// (whether or not *BBI was replaced).
//
// Return value: true if the instruction was replaced; false otherwise.
//
bool llvm::DecomposeArrayRef(GetElementPtrInst* GEP) {
if (GEP->getNumIndices() < 2
|| (GEP->getNumIndices() == 2
&& isZeroConst(GEP->getOperand(1)))) {
DEBUG (std::cerr << "DecomposeArrayRef: Skipping " << *GEP);
return false;
} else {
DEBUG (std::cerr << "DecomposeArrayRef: Decomposing " << *GEP);
}
BasicBlock *BB = GEP->getParent();
Value *LastPtr = GEP->getPointerOperand();
Instruction *InsertPoint = GEP->getNext(); // Insert before the next insn
// Process each index except the last one.
User::const_op_iterator OI = GEP->idx_begin(), OE = GEP->idx_end();
for (; OI+1 != OE; ++OI) {
std::vector<Value*> Indices;
// If this is the first index and is 0, skip it and move on!
if (OI == GEP->idx_begin()) {
if (isZeroConst (*OI))
continue;
}
else // Not the first index: include initial [0] to deref the last ptr
Indices.push_back(Constant::getNullValue(Type::LongTy));
Indices.push_back(*OI);
// New Instruction: nextPtr1 = GetElementPtr LastPtr, Indices
LastPtr = new GetElementPtrInst(LastPtr, Indices, "ptr1", InsertPoint);
++NumAdded;
}
// Now create a new instruction to replace the original one
//
const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
// Get the final index vector, including an initial [0] as before.
std::vector<Value*> Indices;
Indices.push_back(Constant::getNullValue(Type::LongTy));
Indices.push_back(*OI);
Value *NewVal = new GetElementPtrInst(LastPtr, Indices, GEP->getName(),
InsertPoint);
// Replace all uses of the old instruction with the new
GEP->replaceAllUsesWith(NewVal);
// Now remove and delete the old instruction...
BB->getInstList().erase(GEP);
return true;
}
<commit_msg>This is V9 specific, move it there.<commit_after><|endoftext|> |
<commit_before>/**
* \file
* \brief mutexTestCases object definition
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2014-11-09
*/
#include "mutexTestCases.hpp"
#include "MutexPriorityTestCase.hpp"
#include "MutexOperationsTestCase.hpp"
#include "MutexErrorCheckingOperationsTestCase.hpp"
#include "MutexRecursiveOperationsTestCase.hpp"
#include "MutexPriorityProtocolTestCase.hpp"
#include "MutexPriorityProtectOperationsTestCase.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local objects
+---------------------------------------------------------------------------------------------------------------------*/
/// MutexPriorityTestCase instance
const MutexPriorityTestCase priorityTestCase;
/// MutexOperationsTestCase instance
const MutexOperationsTestCase operationsTestCase;
/// MutexErrorCheckingOperationsTestCase instance
const MutexErrorCheckingOperationsTestCase errorCheckingOperationsTestCase;
/// MutexRecursiveOperationsTestCase instance
const MutexRecursiveOperationsTestCase recursiveOperationsTestCase;
/// MutexPriorityProtocolTestCase instance
const MutexPriorityProtocolTestCase priorityProtocolTestCase;
/// MutexPriorityProtectOperationsTestCase instance
const MutexPriorityProtectOperationsTestCase priorityProtectOperationsTestCase;
/// array with references to TestCase objects related to mutexes
const TestCaseRange::value_type mutexTestCases_[]
{
priorityTestCase,
operationsTestCase,
errorCheckingOperationsTestCase,
recursiveOperationsTestCase,
priorityProtocolTestCase,
priorityProtectOperationsTestCase,
};
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| global objects
+---------------------------------------------------------------------------------------------------------------------*/
const TestCaseRange mutexTestCases {mutexTestCases_};
} // namespace test
} // namespace distortos
<commit_msg>test: add MutexPriorityInheritanceOperationsTestCase to executed test cases<commit_after>/**
* \file
* \brief mutexTestCases object definition
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2014-11-12
*/
#include "mutexTestCases.hpp"
#include "MutexPriorityTestCase.hpp"
#include "MutexOperationsTestCase.hpp"
#include "MutexErrorCheckingOperationsTestCase.hpp"
#include "MutexRecursiveOperationsTestCase.hpp"
#include "MutexPriorityProtocolTestCase.hpp"
#include "MutexPriorityProtectOperationsTestCase.hpp"
#include "MutexPriorityInheritanceOperationsTestCase.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local objects
+---------------------------------------------------------------------------------------------------------------------*/
/// MutexPriorityTestCase instance
const MutexPriorityTestCase priorityTestCase;
/// MutexOperationsTestCase instance
const MutexOperationsTestCase operationsTestCase;
/// MutexErrorCheckingOperationsTestCase instance
const MutexErrorCheckingOperationsTestCase errorCheckingOperationsTestCase;
/// MutexRecursiveOperationsTestCase instance
const MutexRecursiveOperationsTestCase recursiveOperationsTestCase;
/// MutexPriorityProtocolTestCase instance
const MutexPriorityProtocolTestCase priorityProtocolTestCase;
/// MutexPriorityProtectOperationsTestCase instance
const MutexPriorityProtectOperationsTestCase priorityProtectOperationsTestCase;
/// MutexPriorityInheritanceOperationsTestCase instance
const MutexPriorityInheritanceOperationsTestCase priorityInheritanceOperationsTestCase;
/// array with references to TestCase objects related to mutexes
const TestCaseRange::value_type mutexTestCases_[]
{
priorityTestCase,
operationsTestCase,
errorCheckingOperationsTestCase,
recursiveOperationsTestCase,
priorityProtocolTestCase,
priorityProtectOperationsTestCase,
priorityInheritanceOperationsTestCase,
};
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| global objects
+---------------------------------------------------------------------------------------------------------------------*/
const TestCaseRange mutexTestCases {mutexTestCases_};
} // namespace test
} // namespace distortos
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -fsyntax-only -std=c++0x -Wc++98-compat -verify %s
template<typename ...T> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic1 {};
template<template<typename> class ...T> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic2 {};
template<int ...I> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic3 {};
<commit_msg>Convert newly-added test from -std=c++0x to -std=c++11.<commit_after>// RUN: %clang_cc1 -fsyntax-only -std=c++11 -Wc++98-compat -verify %s
template<typename ...T> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic1 {};
template<template<typename> class ...T> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic2 {};
template<int ...I> // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic3 {};
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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.
*
* $Id: transform_point_cloud.cpp 1032 2011-05-18 22:43:27Z mdixon $
*
*/
#include <Eigen/Core>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/ros/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/registration/transforms.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
void
printHelp (int argc, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -trans dx,dy,dz = the translation (default: ");
print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n");
print_info (" -quat w,x,y,z = rotation as quaternion\n");
print_info (" -axisangle ax,ay,az,theta = rotation in axis-angle form\n");
print_info (" -matrix v1,v2,...,v8,v9 = a 3x3 affine transform\n");
print_info (" -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n");
print_info (" Note: If a rotation is not specified, it will default to no rotation.\n");
print_info (" If redundant or conflicting transforms are specified, then:\n");
print_info (" -axisangle will override -quat\n");
print_info (" -matrix (3x3) will take override -axisangle and -quat\n");
print_info (" -matrix (4x4) will take override all other arguments\n");
}
void printElapsedTimeAndNumberOfPoints (double t, int w, int h=1)
{
print_info ("[done, "); print_value ("%g", t); print_info (" seconds : ");
print_value ("%d", w*h); print_info (" points]\n");
}
bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud) < 0)
return (false);
printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
return (true);
}
template <typename PointT>
void
transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,
Eigen::Matrix4f &tform)
{
transformPointCloud (input, output, tform);
}
template <>
void
transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <>
void
transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input,
PointCloud<PointXYZRGBNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <typename PointT>
void
transformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
PointCloud<PointT> cloud;
fromROSMsg (input, cloud);
transformPointCloudHelper (cloud, cloud, tform);
toROSMsg (cloud, output);
}
void
transformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
// Check for 'rgb' and 'normals' fields
bool has_rgb = false;
bool has_normals = false;
for (size_t i = 0; i < input.fields.size (); ++i)
{
if (input.fields[i].name == "rgb")
has_rgb = true;
if (input.fields[i].name == "normals")
has_normals = true;
}
// Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal
if (!has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZ> (input, output, tform);
else if (has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZRGB> (input, output, tform);
else if (!has_rgb && has_normals)
transformPointCloud2AsType<PointNormal> (input, output, tform);
else // (has_rgb && has_normals)
transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);
}
void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
TicToc tt;
tt.tic ();
print_highlight ("Transforming ");
transformPointCloud2 (*input, output, tform);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
pcl::io::savePCDFile (filename, output);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Initialize the transformation matrix
Eigen::Matrix4f tform;
tform.setIdentity ();
// Command line parsing
double dx, dy, dz;
std::vector<double> values;
if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1)
{
tform (0, 3) = dx;
tform (1, 3) = dy;
tform (2, 3) = dz;
}
if (parse_x_arguments (argc, argv, "-quat", values) > -1)
{
if (values.size () == 4)
{
const double & x = values[0];
const double & y = values[1];
const double & z = values[2];
const double & w = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n");
}
}
if (parse_x_arguments (argc, argv, "-axisangle", values) > -1)
{
if (values.size () == 4)
{
const double & ax = values[0];
const double & ay = values[1];
const double & az = values[2];
const double & theta = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n");
}
}
if (parse_x_arguments (argc, argv, "-matrix", values) > -1)
{
if (values.size () == 9 || values.size () == 16)
{
int n = sqrt (values.size ());
for (int r = 0; r < n; ++r)
for (int c = 0; c < n; ++c)
tform (r, c) = values[n*r+c];
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n");
}
}
// Load the first file
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Apply the transform
sensor_msgs::PointCloud2 output;
compute (cloud, output, tform);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
<commit_msg>There is no integer sqrt, hard coding possible values.<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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.
*
* $Id: transform_point_cloud.cpp 1032 2011-05-18 22:43:27Z mdixon $
*
*/
#include <Eigen/Core>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/ros/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/registration/transforms.h>
#include <cmath>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
void
printHelp (int argc, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -trans dx,dy,dz = the translation (default: ");
print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n");
print_info (" -quat w,x,y,z = rotation as quaternion\n");
print_info (" -axisangle ax,ay,az,theta = rotation in axis-angle form\n");
print_info (" -matrix v1,v2,...,v8,v9 = a 3x3 affine transform\n");
print_info (" -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n");
print_info (" Note: If a rotation is not specified, it will default to no rotation.\n");
print_info (" If redundant or conflicting transforms are specified, then:\n");
print_info (" -axisangle will override -quat\n");
print_info (" -matrix (3x3) will take override -axisangle and -quat\n");
print_info (" -matrix (4x4) will take override all other arguments\n");
}
void printElapsedTimeAndNumberOfPoints (double t, int w, int h=1)
{
print_info ("[done, "); print_value ("%g", t); print_info (" seconds : ");
print_value ("%d", w*h); print_info (" points]\n");
}
bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud) < 0)
return (false);
printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
return (true);
}
template <typename PointT>
void
transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,
Eigen::Matrix4f &tform)
{
transformPointCloud (input, output, tform);
}
template <>
void
transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <>
void
transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input,
PointCloud<PointXYZRGBNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <typename PointT>
void
transformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
PointCloud<PointT> cloud;
fromROSMsg (input, cloud);
transformPointCloudHelper (cloud, cloud, tform);
toROSMsg (cloud, output);
}
void
transformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
// Check for 'rgb' and 'normals' fields
bool has_rgb = false;
bool has_normals = false;
for (size_t i = 0; i < input.fields.size (); ++i)
{
if (input.fields[i].name == "rgb")
has_rgb = true;
if (input.fields[i].name == "normals")
has_normals = true;
}
// Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal
if (!has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZ> (input, output, tform);
else if (has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZRGB> (input, output, tform);
else if (!has_rgb && has_normals)
transformPointCloud2AsType<PointNormal> (input, output, tform);
else // (has_rgb && has_normals)
transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);
}
void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
TicToc tt;
tt.tic ();
print_highlight ("Transforming ");
transformPointCloud2 (*input, output, tform);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
pcl::io::savePCDFile (filename, output);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Initialize the transformation matrix
Eigen::Matrix4f tform;
tform.setIdentity ();
// Command line parsing
double dx, dy, dz;
std::vector<double> values;
if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1)
{
tform (0, 3) = dx;
tform (1, 3) = dy;
tform (2, 3) = dz;
}
if (parse_x_arguments (argc, argv, "-quat", values) > -1)
{
if (values.size () == 4)
{
const double & x = values[0];
const double & y = values[1];
const double & z = values[2];
const double & w = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n");
}
}
if (parse_x_arguments (argc, argv, "-axisangle", values) > -1)
{
if (values.size () == 4)
{
const double & ax = values[0];
const double & ay = values[1];
const double & az = values[2];
const double & theta = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n");
}
}
if (parse_x_arguments (argc, argv, "-matrix", values) > -1)
{
if (values.size () == 9 || values.size () == 16)
{
int n = values.size () == 9 ? 3 : 4;
for (int r = 0; r < n; ++r)
for (int c = 0; c < n; ++c)
tform (r, c) = values[n*r+c];
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n");
}
}
// Load the first file
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Apply the transform
sensor_msgs::PointCloud2 output;
compute (cloud, output, tform);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE TEST_IO
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <boost/test/unit_test.hpp>
#include <dynet/dynet.h>
#include <dynet/expr.h>
#include <dynet/rnn.h>
#include <dynet/lstm.h>
#include <dynet/gru.h>
#include <dynet/io.h>
#include "test.h"
using namespace dynet;
using namespace dynet::expr;
using namespace std;
struct IOTest {
IOTest() {
// initialize if necessary
if (default_device == nullptr) {
for (auto x : {"IOTest", "--dynet-mem", "512"}) {
av.push_back(strdup(x));
}
char **argv = &av[0];
int argc = av.size();
dynet::initialize(argc, argv);
}
filename = "io.dump";
}
~IOTest() {
for (auto x : av) free(x);
}
std::vector<char*> av;
std::string filename;
};
class testModel {
public:
testModel(dynet::ParameterCollection &model) {
lookup_param = model.add_lookup_parameters(1000, {128});
affine_params = model.add_subcollection("affine");
W_x = affine_params.add_parameters({40, 30});
b_x = affine_params.add_parameters({40});
lstm = LSTMBuilder(3, 40, 1, model);
}
std::string get_affine_model_name() { return affine_params.get_fullname(); }
dynet::ParameterCollection get_affine_model() const { return affine_params; }
dynet::ParameterCollection get_lstm_model() { return lstm.get_parameters(); }
private:
dynet::LookupParameter lookup_param;
dynet::Parameter W_x, b_x;
dynet::ParameterCollection affine_params;
dynet::LSTMBuilder lstm;
}; // class testModel
// define the test suite
BOOST_FIXTURE_TEST_SUITE(io_test, IOTest);
BOOST_AUTO_TEST_CASE ( test_save_populate_pc ) {
ParameterCollection m, m2;
m.add_parameters({10}, "a");
m.add_parameters({3,7});
m.add_lookup_parameters(10, {2});
m2.add_parameters({10}, "a");
m2.add_parameters({3,7});
m2.add_lookup_parameters(10, {2});
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
{
dynet::TextFileLoader s("test.model");
s.populate(m2);
}
DYNET_CHECK_EQUAL(m2, m);
}
BOOST_AUTO_TEST_CASE ( test_save_populate_sub_pc ) {
// Create a parameter collection with a sub collection
ParameterCollection m, m2;
m.add_parameters({10}, "a");
m.add_parameters({3,7});
m.add_lookup_parameters(10, {2});
ParameterCollection m_sub = m.add_subcollection("model1");
m_sub.add_parameters({5}, "x");
m_sub.add_parameters({3,6});
m_sub.add_lookup_parameters(5, {3});
m.add_lookup_parameters(4, {2});
// Create another parameter collection with the same size as the sub collection
m2.add_parameters({5}, "x");
m2.add_parameters({3,6});
m2.add_lookup_parameters(5, {3});
// Save the overall collection
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
// Load only the sub-collection
{
dynet::TextFileLoader s("test.model");
s.populate(m2, m_sub.get_fullname());
}
// Check if the sub-collection is equal
DYNET_CHECK_EQUAL(m2, m_sub);
}
BOOST_AUTO_TEST_CASE ( test_save_populate_parameter ) {
ParameterCollection m, m2;
Parameter ma = m.add_parameters({10}, "a");
Parameter mb = m.add_parameters({3,7});
LookupParameter mc = m.add_lookup_parameters(10, {2});
Parameter m2a = m2.add_parameters({10}, "a");
Parameter m2b = m2.add_parameters({3,7});
LookupParameter m2c = m2.add_lookup_parameters(10, {2});
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
{
dynet::TextFileLoader s("test.model");
s.populate(m2a, ma.get_fullname());
s.populate(m2b, mb.get_fullname());
s.populate(m2c, mc.get_fullname());
}
DYNET_CHECK_EQUAL(m2a, ma);
DYNET_CHECK_EQUAL(m2b, mb);
DYNET_CHECK_EQUAL(m2c, mc);
}
BOOST_AUTO_TEST_CASE ( test_save_load_parameter ) {
ParameterCollection m, m2;
Parameter ma = m.add_parameters({10}, "a");
Parameter mb = m.add_parameters({3,7});
LookupParameter mc = m.add_lookup_parameters(10, {2});
Parameter m2a, m2b;
LookupParameter m2c;
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
{
dynet::TextFileLoader s("test.model");
m2a = s.load_param(m2, ma.get_fullname());
m2b = s.load_param(m2, mb.get_fullname());
m2c = s.load_lookup_param(m2, mc.get_fullname());
}
DYNET_CHECK_EQUAL(m2a, ma);
DYNET_CHECK_EQUAL(m2b, mb);
DYNET_CHECK_EQUAL(m2c, mc);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Add perf tests for save/load.<commit_after>#define BOOST_TEST_MODULE TEST_IO
#include <iostream>
#include <fstream>
#include <chrono>
#include <stdexcept>
#include <boost/test/unit_test.hpp>
#include <dynet/dynet.h>
#include <dynet/expr.h>
#include <dynet/rnn.h>
#include <dynet/lstm.h>
#include <dynet/gru.h>
#include <dynet/io.h>
#include "test.h"
using namespace dynet;
using namespace dynet::expr;
using namespace std;
struct IOTest {
IOTest() {
// initialize if necessary
if (default_device == nullptr) {
for (auto x : {"IOTest", "--dynet-mem", "512"}) {
av.push_back(strdup(x));
}
char **argv = &av[0];
int argc = av.size();
dynet::initialize(argc, argv);
}
filename = "io.dump";
}
~IOTest() {
for (auto x : av) free(x);
}
std::vector<char*> av;
std::string filename;
};
class testModel {
public:
testModel(dynet::ParameterCollection &model) {
lookup_param = model.add_lookup_parameters(1000, {128});
affine_params = model.add_subcollection("affine");
W_x = affine_params.add_parameters({40, 30});
b_x = affine_params.add_parameters({40});
lstm = LSTMBuilder(3, 40, 1, model);
}
std::string get_affine_model_name() { return affine_params.get_fullname(); }
dynet::ParameterCollection get_affine_model() const { return affine_params; }
dynet::ParameterCollection get_lstm_model() { return lstm.get_parameters(); }
private:
dynet::LookupParameter lookup_param;
dynet::Parameter W_x, b_x;
dynet::ParameterCollection affine_params;
dynet::LSTMBuilder lstm;
}; // class testModel
// define the test suite
BOOST_FIXTURE_TEST_SUITE(io_test, IOTest);
BOOST_AUTO_TEST_CASE ( test_save_populate_pc ) {
ParameterCollection m, m2;
m.add_parameters({10}, "a");
m.add_parameters({3,7});
m.add_lookup_parameters(10, {2});
m2.add_parameters({10}, "a");
m2.add_parameters({3,7});
m2.add_lookup_parameters(10, {2});
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
{
dynet::TextFileLoader s("test.model");
s.populate(m2);
}
DYNET_CHECK_EQUAL(m2, m);
}
BOOST_AUTO_TEST_CASE ( test_save_populate_sub_pc ) {
// Create a parameter collection with a sub collection
ParameterCollection m, m2;
m.add_parameters({10}, "a");
m.add_parameters({3,7});
m.add_lookup_parameters(10, {2});
ParameterCollection m_sub = m.add_subcollection("model1");
m_sub.add_parameters({5}, "x");
m_sub.add_parameters({3,6});
m_sub.add_lookup_parameters(5, {3});
m.add_lookup_parameters(4, {2});
// Create another parameter collection with the same size as the sub collection
m2.add_parameters({5}, "x");
m2.add_parameters({3,6});
m2.add_lookup_parameters(5, {3});
// Save the overall collection
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
// Load only the sub-collection
{
dynet::TextFileLoader s("test.model");
s.populate(m2, m_sub.get_fullname());
}
// Check if the sub-collection is equal
DYNET_CHECK_EQUAL(m2, m_sub);
}
BOOST_AUTO_TEST_CASE ( test_save_populate_parameter ) {
ParameterCollection m, m2;
Parameter ma = m.add_parameters({10}, "a");
Parameter mb = m.add_parameters({3,7});
LookupParameter mc = m.add_lookup_parameters(10, {2});
Parameter m2a = m2.add_parameters({10}, "a");
Parameter m2b = m2.add_parameters({3,7});
LookupParameter m2c = m2.add_lookup_parameters(10, {2});
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
{
dynet::TextFileLoader s("test.model");
s.populate(m2a, ma.get_fullname());
s.populate(m2b, mb.get_fullname());
s.populate(m2c, mc.get_fullname());
}
DYNET_CHECK_EQUAL(m2a, ma);
DYNET_CHECK_EQUAL(m2b, mb);
DYNET_CHECK_EQUAL(m2c, mc);
}
BOOST_AUTO_TEST_CASE ( test_save_load_parameter ) {
ParameterCollection m, m2;
Parameter ma = m.add_parameters({10}, "a");
Parameter mb = m.add_parameters({3,7});
LookupParameter mc = m.add_lookup_parameters(10, {2});
Parameter m2a, m2b;
LookupParameter m2c;
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
{
dynet::TextFileLoader s("test.model");
m2a = s.load_param(m2, ma.get_fullname());
m2b = s.load_param(m2, mb.get_fullname());
m2c = s.load_lookup_param(m2, mc.get_fullname());
}
DYNET_CHECK_EQUAL(m2a, ma);
DYNET_CHECK_EQUAL(m2b, mb);
DYNET_CHECK_EQUAL(m2c, mc);
}
BOOST_AUTO_TEST_CASE ( test_save1_perf ) {
ParameterCollection m;
for (int l = 0; l < 256; ++l)
auto param = m.add_parameters({1024, 1024});
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "ms" << std::endl;
}
BOOST_AUTO_TEST_CASE ( test_load1_perf ) {
ParameterCollection m, m_l;
Parameter param;
Parameter param_l = m_l.add_parameters({1024, 1024});
for (int l = 0; l < 256; ++l)
param = m.add_parameters({1024, 1024});
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
{
dynet::TextFileLoader l("test.model");
l.populate(param_l, param.get_fullname());
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "ms" << std::endl;
DYNET_CHECK_EQUAL(param, param_l);
}
BOOST_AUTO_TEST_CASE ( test_save2_perf ) {
ParameterCollection m;
for (int l = 0; l < 5120; ++l)
auto param = m.add_parameters({128, 128});
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "ms" << std::endl;
}
BOOST_AUTO_TEST_CASE ( test_load2_perf ) {
ParameterCollection m, m_l;
Parameter param;
Parameter param_l = m_l.add_parameters({128, 128});
for (int l = 0; l < 5120; ++l)
param = m.add_parameters({128, 128});
{
dynet::TextFileSaver s("test.model");
s.save(m);
}
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
{
dynet::TextFileLoader l("test.model");
l.populate(param_l, param.get_fullname());
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "ms" << std::endl;
DYNET_CHECK_EQUAL(param, param_l);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*
* BayesianClassifier.cpp
*
* Created on: Mar 20, 2009
* Author: Simon Lavigne-Giroux
*/
#include "BayesianClassifier.h"
#include <fstream>
// The threshold to get to select whether an output is valid
#define outputProbabilityTreshold 0.003
// There is a minimum denominator value to remove the possibility of INF and NaN
#define minimumDenominatorValue 0.0000000001
/**
* BayesianClassifier constructor. It constructs the classifier with raw training data from the file
* and uses domains to generate discrete values (TrainingData).
*
* Beware : The file must not have an empty line at the end.
*/
BayesianClassifier::BayesianClassifier(std::string filename,
std::vector<Domain> const &_domains) {
domains = _domains;
numberOfColumns = _domains.size();
constructClassifier(filename);
}
/**
* BayesianClassifier constructor. It constructs a classifier with the specified domain.
* Raw training data are not given, it is possible to add data after the construction.
*/
BayesianClassifier::BayesianClassifier(std::vector<Domain> const &_domains) {
domains = _domains;
numberOfColumns = _domains.size();
calculateProbabilitiesOfInputs();
calculateProbabilitiesOfOutputs();
numberOfTrainingData = data.size();
data.clear();
}
/**
* Construct the classifier from the RawTrainingData in the file.
*
* Beware : The file must not have an empty line at the end.
*/
void BayesianClassifier::constructClassifier(std::string const &filename) {
std::ifstream inputFile(filename.c_str());
while (!inputFile.eof()) {
TrainingData trainingData;
float value;
for (int i = 0; i < numberOfColumns; i++) {
inputFile >> value;
trainingData.push_back(domains[i].calculateDiscreteValue(value));
}
data.push_back(trainingData);
}
inputFile.close();
calculateProbabilitiesOfInputs();
calculateProbabilitiesOfOutputs();
numberOfTrainingData = data.size();
data.clear();
}
/**
* Calculate the probabilities for each possibility of inputs.
*/
void BayesianClassifier::calculateProbabilitiesOfInputs() {
for (int i = 0; i < numberOfColumns - 1; i++) {
for (int j = 0; j < domains[i].getNumberOfValues(); j++) {
for (int k = 0; k < getOutputDomain().getNumberOfValues(); k++) {
calculateProbability(i, j, k);
}
}
}
}
/**
* Calculate the probability of P(effectColum:effectValue | lastColumn:causeValue)
* It saves data into the variable probabilitiesOfInputs.
*/
void BayesianClassifier::calculateProbability(int effectColumn,
int effectValue, int causeValue) {
// The numerator is the number of TrainingData with this effectValue given this causeValue
float numerator = 0.0;
// The denominator is the number of TrainingData with this causeValue
float denominator = 0.0;
//Calculate the numerator and denominator by scanning the TrainingData
for (unsigned int i = 0; i < data.size(); i++) {
TrainingData trainingData = data[i];
if (trainingData[numberOfColumns - 1] == causeValue) {
denominator++;
if (trainingData[effectColumn] == effectValue) {
numerator++;
}
}
}
float probability = 0.0;
if (denominator != 0) {
probability = numerator / denominator;
}
unsigned long key = calculateMapKey(effectColumn, effectValue, causeValue);
probabilitiesOfInputs.insert(std::pair<unsigned long, float>(key, probability));
}
/**
* Calculate P(Output) of each output.
* It saves data into the variable probabilitiesOfOuputs.
*/
void BayesianClassifier::calculateProbabilitiesOfOutputs() {
for (int i = 0; i < getOutputDomain().getNumberOfValues(); i++) {
float count = 0.0;
for (unsigned int j = 0; j < data.size(); j++) {
if (data[j][numberOfColumns - 1] == i) {
count++;
}
}
if (data.size() != 0) {
probabilitiesOfOutputs.push_back(count / (float) data.size());
} else {
probabilitiesOfOutputs.push_back(0);
}
}
}
/**
* Calculate the map key for each value in the variable probabilitiesOfInputs
*/
unsigned long BayesianClassifier::calculateMapKey(int effectColumn,
int effectValue, int causeValue) {
return causeValue * 100000 + effectColumn * 100 + effectValue;
}
/**
* Calculate the most probable output given this input with this formula :
* P(Output | Input) = 1/Z * P(Output) * P(InputValue1 | Ouput) * P(InputValue2 | Ouput) * ...
* The output with the highest probability is returned.
*/
int BayesianClassifier::calculateOutput(std::vector<float> const &input) {
float highestProbability = outputProbabilityTreshold;
int highestOutput = rand() % getOutputDomain().getNumberOfValues();
unsigned long key = 0;
for (int i = 0; i < getOutputDomain().getNumberOfValues(); i++) {
float probability = probabilitiesOfOutputs[i];
for (unsigned int j = 0; j < input.size(); j++) {
key = calculateMapKey(j, domains[j].calculateDiscreteValue(input[j]), i);
probability *= probabilitiesOfInputs[key];
}
if (probability > highestProbability) {
highestProbability = probability;
highestOutput = i;
}
}
return highestOutput;
}
/**
* Calculate the probability of this output given this input.
* P(Output | Input) = 1/Z * P(Output) * P(InputValue1 | Ouput) * P(InputValue2 | Ouput) * ...
*/
float BayesianClassifier::calculateProbabilityOfOutput(std::vector<float> const &input, float output) {
unsigned long key = 0;
std::vector<float> probabilities;
for(int i = 0; i < getOutputDomain().getNumberOfValues(); i++) {
float probability = probabilitiesOfOutputs[i];
for (unsigned int j = 0; j < input.size(); j++) {
key = calculateMapKey(j,
domains[j].calculateDiscreteValue(input[j]), i);
probability *= probabilitiesOfInputs[key];
}
probabilities.push_back(probability);
}
float sumOfProbabilities = 0.0;
for(unsigned int i = 0; i < probabilities.size(); i++) {
sumOfProbabilities += probabilities[i];
}
float alpha = 0.0;
if(sumOfProbabilities > minimumDenominatorValue) {
alpha = 1.0 / sumOfProbabilities;
}
float probability = probabilities[getOutputDomain().calculateDiscreteValue(output)]*alpha;
if(probability > 1.0) {
return 1.0;
} else {
return probability;
}
}
/**
* Add raw training data from a file to adapt the classifier.
* It updates the variables containing the probabilities.
*
* Beware : The file must not have an empty line at the end.
*/
void BayesianClassifier::addRawTrainingData(std::string const &filename) {
std::ifstream inputFile(filename.c_str());
while (!inputFile.eof()) {
RawTrainingData rawTrainingData;
float value;
for (int i = 0; i < numberOfColumns; i++) {
inputFile >> value;
rawTrainingData.push_back(value);
}
addRawTrainingData(rawTrainingData);
}
inputFile.close();
}
/**
* Add one set of raw training data to adapt the classifier
* It updates the variables containing the probabilities.
*/
void BayesianClassifier::addRawTrainingData(RawTrainingData const &rawTrainingData){
std::vector<int> trainingData = convertRawTrainingData(rawTrainingData);
updateProbabilities(trainingData);
updateOutputProbabilities(domains[numberOfColumns-1].calculateDiscreteValue(rawTrainingData[numberOfColumns - 1]));
numberOfTrainingData++;
}
/**
* Convert a vector<float> into a vector<int> by discretizing the values
* using the domain for each column.
*/
TrainingData BayesianClassifier::convertRawTrainingData(RawTrainingData const &floatVector) {
TrainingData trainingData;
for(unsigned int i = 0; i < floatVector.size(); i++) {
trainingData.push_back(domains[i].calculateDiscreteValue(floatVector[i]));
}
return trainingData;
}
/**
* Update the output probabilities from a new set of raw training data.
*/
void BayesianClassifier::updateOutputProbabilities(int output){
float denominator = numberOfTrainingData;
for (unsigned int i = 0; i < probabilitiesOfOutputs.size(); i++) {
float numberOfOutput = probabilitiesOfOutputs[i]*denominator;
if(i == (unsigned int)output) {
numberOfOutput++;
}
probabilitiesOfOutputs[i] = (float) (numberOfOutput/(denominator + 1.0));
}
}
/**
* Update the probabilities after adding one set of training data.
*/
void BayesianClassifier::updateProbabilities(TrainingData const &trainingData){
//float denominator = probabilitiesOfOutputs[numberOfColumns - 1]*numberOfTrainingData;
float denominator = probabilitiesOfOutputs[trainingData[numberOfColumns - 1]]*numberOfTrainingData;
for(int i = 0; i < numberOfColumns - 1; i++) {
for(int j = 0; j < domains[i].getNumberOfValues(); j++) {
float numerator = probabilitiesOfInputs[calculateMapKey(i, j, trainingData[numberOfColumns - 1])]*denominator;
if(j == trainingData[i]) {
numerator++;
}
probabilitiesOfInputs[calculateMapKey(i, j, trainingData[numberOfColumns - 1])] = numerator/(denominator + 1.0);
}
}
}
/**
* Returns the domain of the output column.
*/
Domain BayesianClassifier::getOutputDomain() {
return domains[numberOfColumns - 1];
}
<commit_msg>prevent copying of training data<commit_after>/*
* BayesianClassifier.cpp
*
* Created on: Mar 20, 2009
* Author: Simon Lavigne-Giroux
*/
#include "BayesianClassifier.h"
#include <fstream>
// The threshold to get to select whether an output is valid
#define outputProbabilityTreshold 0.003
// There is a minimum denominator value to remove the possibility of INF and NaN
#define minimumDenominatorValue 0.0000000001
/**
* BayesianClassifier constructor. It constructs the classifier with raw training data from the file
* and uses domains to generate discrete values (TrainingData).
*
* Beware : The file must not have an empty line at the end.
*/
BayesianClassifier::BayesianClassifier(std::string filename,
std::vector<Domain> const &_domains) {
domains = _domains;
numberOfColumns = _domains.size();
constructClassifier(filename);
}
/**
* BayesianClassifier constructor. It constructs a classifier with the specified domain.
* Raw training data are not given, it is possible to add data after the construction.
*/
BayesianClassifier::BayesianClassifier(std::vector<Domain> const &_domains) {
domains = _domains;
numberOfColumns = _domains.size();
calculateProbabilitiesOfInputs();
calculateProbabilitiesOfOutputs();
numberOfTrainingData = data.size();
data.clear();
}
/**
* Construct the classifier from the RawTrainingData in the file.
*
* Beware : The file must not have an empty line at the end.
*/
void BayesianClassifier::constructClassifier(std::string const &filename) {
std::ifstream inputFile(filename.c_str());
while (!inputFile.eof()) {
TrainingData trainingData;
float value;
for (int i = 0; i < numberOfColumns; i++) {
inputFile >> value;
trainingData.push_back(domains[i].calculateDiscreteValue(value));
}
data.push_back(trainingData);
}
inputFile.close();
calculateProbabilitiesOfInputs();
calculateProbabilitiesOfOutputs();
numberOfTrainingData = data.size();
data.clear();
}
/**
* Calculate the probabilities for each possibility of inputs.
*/
void BayesianClassifier::calculateProbabilitiesOfInputs() {
for (int i = 0; i < numberOfColumns - 1; i++) {
for (int j = 0; j < domains[i].getNumberOfValues(); j++) {
for (int k = 0; k < getOutputDomain().getNumberOfValues(); k++) {
calculateProbability(i, j, k);
}
}
}
}
/**
* Calculate the probability of P(effectColum:effectValue | lastColumn:causeValue)
* It saves data into the variable probabilitiesOfInputs.
*/
void BayesianClassifier::calculateProbability(int effectColumn,
int effectValue, int causeValue) {
// The numerator is the number of TrainingData with this effectValue given this causeValue
float numerator = 0.0;
// The denominator is the number of TrainingData with this causeValue
float denominator = 0.0;
//Calculate the numerator and denominator by scanning the TrainingData
for (unsigned int i = 0; i < data.size(); i++) {
TrainingData const &trainingData = data[i];
if (trainingData[numberOfColumns - 1] == causeValue) {
denominator++;
if (trainingData[effectColumn] == effectValue) {
numerator++;
}
}
}
float probability = 0.0;
if (denominator != 0) {
probability = numerator / denominator;
}
unsigned long key = calculateMapKey(effectColumn, effectValue, causeValue);
probabilitiesOfInputs.insert(std::pair<unsigned long, float>(key, probability));
}
/**
* Calculate P(Output) of each output.
* It saves data into the variable probabilitiesOfOuputs.
*/
void BayesianClassifier::calculateProbabilitiesOfOutputs() {
for (int i = 0; i < getOutputDomain().getNumberOfValues(); i++) {
float count = 0.0;
for (unsigned int j = 0; j < data.size(); j++) {
if (data[j][numberOfColumns - 1] == i) {
count++;
}
}
if (data.size() != 0) {
probabilitiesOfOutputs.push_back(count / (float) data.size());
} else {
probabilitiesOfOutputs.push_back(0);
}
}
}
/**
* Calculate the map key for each value in the variable probabilitiesOfInputs
*/
unsigned long BayesianClassifier::calculateMapKey(int effectColumn,
int effectValue, int causeValue) {
return causeValue * 100000 + effectColumn * 100 + effectValue;
}
/**
* Calculate the most probable output given this input with this formula :
* P(Output | Input) = 1/Z * P(Output) * P(InputValue1 | Ouput) * P(InputValue2 | Ouput) * ...
* The output with the highest probability is returned.
*/
int BayesianClassifier::calculateOutput(std::vector<float> const &input) {
float highestProbability = outputProbabilityTreshold;
int highestOutput = rand() % getOutputDomain().getNumberOfValues();
unsigned long key = 0;
for (int i = 0; i < getOutputDomain().getNumberOfValues(); i++) {
float probability = probabilitiesOfOutputs[i];
for (unsigned int j = 0; j < input.size(); j++) {
key = calculateMapKey(j, domains[j].calculateDiscreteValue(input[j]), i);
probability *= probabilitiesOfInputs[key];
}
if (probability > highestProbability) {
highestProbability = probability;
highestOutput = i;
}
}
return highestOutput;
}
/**
* Calculate the probability of this output given this input.
* P(Output | Input) = 1/Z * P(Output) * P(InputValue1 | Ouput) * P(InputValue2 | Ouput) * ...
*/
float BayesianClassifier::calculateProbabilityOfOutput(std::vector<float> const &input, float output) {
unsigned long key = 0;
std::vector<float> probabilities;
for(int i = 0; i < getOutputDomain().getNumberOfValues(); i++) {
float probability = probabilitiesOfOutputs[i];
for (unsigned int j = 0; j < input.size(); j++) {
key = calculateMapKey(j,
domains[j].calculateDiscreteValue(input[j]), i);
probability *= probabilitiesOfInputs[key];
}
probabilities.push_back(probability);
}
float sumOfProbabilities = 0.0;
for(unsigned int i = 0; i < probabilities.size(); i++) {
sumOfProbabilities += probabilities[i];
}
float alpha = 0.0;
if(sumOfProbabilities > minimumDenominatorValue) {
alpha = 1.0 / sumOfProbabilities;
}
float probability = probabilities[getOutputDomain().calculateDiscreteValue(output)]*alpha;
if(probability > 1.0) {
return 1.0;
} else {
return probability;
}
}
/**
* Add raw training data from a file to adapt the classifier.
* It updates the variables containing the probabilities.
*
* Beware : The file must not have an empty line at the end.
*/
void BayesianClassifier::addRawTrainingData(std::string const &filename) {
std::ifstream inputFile(filename.c_str());
while (!inputFile.eof()) {
RawTrainingData rawTrainingData;
float value;
for (int i = 0; i < numberOfColumns; i++) {
inputFile >> value;
rawTrainingData.push_back(value);
}
addRawTrainingData(rawTrainingData);
}
inputFile.close();
}
/**
* Add one set of raw training data to adapt the classifier
* It updates the variables containing the probabilities.
*/
void BayesianClassifier::addRawTrainingData(RawTrainingData const &rawTrainingData){
std::vector<int> trainingData = convertRawTrainingData(rawTrainingData);
updateProbabilities(trainingData);
updateOutputProbabilities(domains[numberOfColumns-1].calculateDiscreteValue(rawTrainingData[numberOfColumns - 1]));
numberOfTrainingData++;
}
/**
* Convert a vector<float> into a vector<int> by discretizing the values
* using the domain for each column.
*/
TrainingData BayesianClassifier::convertRawTrainingData(RawTrainingData const &floatVector) {
TrainingData trainingData;
for(unsigned int i = 0; i < floatVector.size(); i++) {
trainingData.push_back(domains[i].calculateDiscreteValue(floatVector[i]));
}
return trainingData;
}
/**
* Update the output probabilities from a new set of raw training data.
*/
void BayesianClassifier::updateOutputProbabilities(int output){
float denominator = numberOfTrainingData;
for (unsigned int i = 0; i < probabilitiesOfOutputs.size(); i++) {
float numberOfOutput = probabilitiesOfOutputs[i]*denominator;
if(i == (unsigned int)output) {
numberOfOutput++;
}
probabilitiesOfOutputs[i] = (float) (numberOfOutput/(denominator + 1.0));
}
}
/**
* Update the probabilities after adding one set of training data.
*/
void BayesianClassifier::updateProbabilities(TrainingData const &trainingData){
//float denominator = probabilitiesOfOutputs[numberOfColumns - 1]*numberOfTrainingData;
float denominator = probabilitiesOfOutputs[trainingData[numberOfColumns - 1]]*numberOfTrainingData;
for(int i = 0; i < numberOfColumns - 1; i++) {
for(int j = 0; j < domains[i].getNumberOfValues(); j++) {
float numerator = probabilitiesOfInputs[calculateMapKey(i, j, trainingData[numberOfColumns - 1])]*denominator;
if(j == trainingData[i]) {
numerator++;
}
probabilitiesOfInputs[calculateMapKey(i, j, trainingData[numberOfColumns - 1])] = numerator/(denominator + 1.0);
}
}
}
/**
* Returns the domain of the output column.
*/
Domain BayesianClassifier::getOutputDomain() {
return domains[numberOfColumns - 1];
}
<|endoftext|> |
<commit_before><commit_msg>Fix to way we identify the active window. This deals with XFCE which doesn't set the property correctly. Bug=31971 Test=Run Chrome under the XFCE WM and ensure that inactive windows titles are light blue<commit_after><|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// catalog_test.cpp
//
// Identification: test/catalog/catalog_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "catalog/catalog.h"
#include "catalog/database_catalog.h"
#include "catalog/table_catalog.h"
#include "catalog/index_catalog.h"
#include "catalog/column_catalog.h"
#include "catalog/database_metrics_catalog.h"
#include "catalog/query_metrics_catalog.h"
#include "concurrency/transaction_manager_factory.h"
#include "common/harness.h"
#include "common/logger.h"
#include "storage/storage_manager.h"
#include "type/ephemeral_pool.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Catalog Tests
//===--------------------------------------------------------------------===//
class CatalogTests : public PelotonTest {};
TEST_F(CatalogTests, BootstrappingCatalog) {
auto catalog = catalog::Catalog::GetInstance();
catalog->Bootstrap();
EXPECT_EQ(1, storage::StorageManager::GetInstance()->GetDatabaseCount());
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
storage::Database *database =
catalog->GetDatabaseWithName(CATALOG_DATABASE_NAME, txn);
txn_manager.CommitTransaction(txn);
EXPECT_NE(nullptr, database);
// Check database metric table
auto db_metric_table =
database->GetTableWithName(DATABASE_METRICS_CATALOG_NAME);
EXPECT_NE(nullptr, db_metric_table);
}
//
TEST_F(CatalogTests, CreatingDatabase) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase("EMP_DB", txn);
auto table_object = catalog::Catalog::GetInstance()->GetTableObject(
CATALOG_DATABASE_NAME, INDEX_CATALOG_NAME, txn);
auto index_object = table_object->GetIndexObject(INDEX_CATALOG_PKEY_OID);
std::vector<oid_t> key_attrs = index_object->key_attrs;
EXPECT_EQ("EMP_DB", catalog::Catalog::GetInstance()
->GetDatabaseWithName("EMP_DB", txn)
->GetDBName());
txn_manager.CommitTransaction(txn);
EXPECT_EQ(1, key_attrs.size());
EXPECT_EQ(0, key_attrs[0]);
}
TEST_F(CatalogTests, CreatingTable) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
auto id_column = catalog::Column(
type::TypeId::INTEGER, type::Type::GetTypeSize(type::TypeId::INTEGER),
"id", true);
id_column.AddConstraint(
catalog::Constraint(ConstraintType::PRIMARY, "primary_key"));
auto name_column = catalog::Column(type::TypeId::VARCHAR, 32, "name", true);
std::unique_ptr<catalog::Schema> table_schema(
new catalog::Schema({id_column, name_column}));
std::unique_ptr<catalog::Schema> table_schema_2(
new catalog::Schema({id_column, name_column}));
std::unique_ptr<catalog::Schema> table_schema_3(
new catalog::Schema({id_column, name_column}));
catalog::Catalog::GetInstance()->CreateTable("EMP_DB", "emp_table",
std::move(table_schema), txn);
catalog::Catalog::GetInstance()->CreateTable("EMP_DB", "department_table",
std::move(table_schema_2), txn);
catalog::Catalog::GetInstance()->CreateTable("EMP_DB", "salary_table",
std::move(table_schema_3), txn);
// insert random tuple into DATABASE_METRICS_CATALOG and check
std::unique_ptr<type::AbstractPool> pool(new type::EphemeralPool());
catalog::DatabaseMetricsCatalog::GetInstance()->InsertDatabaseMetrics(
2, 3, 4, 5, pool.get(), txn);
// oid_t time_stamp =
// catalog::DatabaseMetricsCatalog::GetInstance()->GetTimeStamp(2, txn);
// inset meaningless tuple into QUERY_METRICS_CATALOG and check
stats::QueryMetric::QueryParamBuf param;
param.len = 1;
param.buf = (unsigned char *)pool->Allocate(1);
*param.buf = 'a';
catalog::QueryMetricsCatalog::GetInstance()->InsertQueryMetrics(
"a query", 1, 1, param, param, param, 1, 1, 1, 1, 1, 1, 1, pool.get(),
txn);
auto param1 = catalog::QueryMetricsCatalog::GetInstance()->GetParamTypes(
"a query", 1, txn);
EXPECT_EQ(1, param1.len);
EXPECT_EQ('a', *param1.buf);
EXPECT_EQ("name", catalog::Catalog::GetInstance()
->GetDatabaseWithName("EMP_DB", txn)
->GetTableWithName("department_table")
->GetSchema()
->GetColumn(1)
.GetName());
txn_manager.CommitTransaction(txn);
// EXPECT_EQ(5, time_stamp);
// We remove these tests so people can add new catalogs without breaking this
// test...
// 3 + 4
// EXPECT_EQ(catalog::Catalog::GetInstance()
// ->GetDatabaseWithName("pg_catalog")
// ->GetTableWithName("pg_table")
// ->GetTupleCount(),
// 11);
// // 6 + pg_database(2) + pg_table(3) + pg_attribute(7) + pg_index(6)
// EXPECT_EQ(catalog::Catalog::GetInstance()
// ->GetDatabaseWithName("pg_catalog")
// ->GetTableWithName("pg_attribute")
// ->GetTupleCount(),
// 57);
// // pg_catalog + EMP_DB
// EXPECT_EQ(catalog::Catalog::GetInstance()
// ->GetDatabaseWithName("pg_catalog")
// ->GetTableWithName("pg_database")
// ->GetTupleCount(),
// 2);
// // 3 + pg_index(3) + pg_attribute(3) + pg_table(3) + pg_database(2)
// EXPECT_EQ(catalog::Catalog::GetInstance()
// ->GetDatabaseWithName("pg_catalog")
// ->GetTableWithName("pg_index")
// ->GetTupleCount(),
// 18);
// EXPECT_EQ(catalog::Catalog::GetInstance()
// ->GetDatabaseWithName("pg_catalog")
// ->GetTableWithName("pg_table")
// ->GetSchema()
// ->GetLength(),
// 72);
}
TEST_F(CatalogTests, TableObject) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
auto table_object = catalog::Catalog::GetInstance()->GetTableObject(
"EMP_DB", "department_table", txn);
auto index_objects = table_object->GetIndexObjects();
auto column_objects = table_object->GetColumnObjects();
EXPECT_EQ(1, index_objects.size());
EXPECT_EQ(2, column_objects.size());
EXPECT_EQ(table_object->table_oid, column_objects[0]->table_oid);
EXPECT_EQ("id", column_objects[0]->column_name);
EXPECT_EQ(0, column_objects[0]->column_id);
EXPECT_EQ(0, column_objects[0]->column_offset);
EXPECT_EQ(type::TypeId::INTEGER, column_objects[0]->column_type);
EXPECT_EQ(true, column_objects[0]->is_inlined);
EXPECT_EQ(true, column_objects[0]->is_primary);
EXPECT_EQ(
false,
column_objects[0]
->is_not_null); // Should this be true because it is a primary key?
EXPECT_EQ(table_object->table_oid, column_objects[1]->table_oid);
EXPECT_EQ("name", column_objects[1]->column_name);
EXPECT_EQ(1, column_objects[1]->column_id);
EXPECT_EQ(4, column_objects[1]->column_offset);
EXPECT_EQ(type::TypeId::VARCHAR, column_objects[1]->column_type);
EXPECT_EQ(true, column_objects[1]->is_inlined);
EXPECT_EQ(false, column_objects[1]->is_primary);
EXPECT_EQ(false, column_objects[1]->is_not_null);
txn_manager.CommitTransaction(txn);
}
TEST_F(CatalogTests, DroppingTable) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
auto catalog = catalog::Catalog::GetInstance();
EXPECT_EQ(
3,
(int)catalog->GetDatabaseObject("EMP_DB", txn)->GetTableObjects().size());
auto database_object =
catalog::Catalog::GetInstance()->GetDatabaseObject("EMP_DB", txn);
EXPECT_NE(nullptr, database_object);
catalog::Catalog::GetInstance()->DropTable("EMP_DB", "department_table", txn);
database_object =
catalog::Catalog::GetInstance()->GetDatabaseObject("EMP_DB", txn);
EXPECT_NE(nullptr, database_object);
auto department_table_object =
database_object->GetTableObject("department_table");
// catalog::Catalog::GetInstance()->PrintCatalogs();
EXPECT_EQ(
2,
(int)catalog->GetDatabaseObject("EMP_DB", txn)->GetTableObjects().size());
txn_manager.CommitTransaction(txn);
EXPECT_EQ(nullptr, department_table_object);
// Try to drop again
txn = txn_manager.BeginTransaction();
EXPECT_THROW(catalog::Catalog::GetInstance()->DropTable(
"EMP_DB", "department_table", txn),
CatalogException);
EXPECT_EQ(
2,
(int)catalog->GetDatabaseObject("EMP_DB", txn)->GetTableObjects().size());
txn_manager.CommitTransaction(txn);
// Drop a table that does not exist
txn = txn_manager.BeginTransaction();
EXPECT_THROW(
catalog::Catalog::GetInstance()->DropTable("EMP_DB", "void_table", txn),
CatalogException);
EXPECT_EQ(
2,
(int)catalog->GetDatabaseObject("EMP_DB", txn)->GetTableObjects().size());
txn_manager.CommitTransaction(txn);
// Drop the other table
txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->DropTable("EMP_DB", "emp_table", txn);
EXPECT_EQ(
1,
(int)catalog->GetDatabaseObject("EMP_DB", txn)->GetTableObjects().size());
txn_manager.CommitTransaction(txn);
}
TEST_F(CatalogTests, DroppingDatabase) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->DropDatabaseWithName("EMP_DB", txn);
EXPECT_THROW(
catalog::Catalog::GetInstance()->GetDatabaseWithName("EMP_DB", txn),
CatalogException);
txn_manager.CommitTransaction(txn);
}
TEST_F(CatalogTests, DroppingCatalog) {
auto catalog = catalog::Catalog::GetInstance();
EXPECT_NE(nullptr, catalog);
}
} // namespace test
} // namespace peloton
<commit_msg>fix catalog test comment<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// catalog_test.cpp
//
// Identification: test/catalog/catalog_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "catalog/catalog.h"
#include "catalog/database_catalog.h"
#include "catalog/table_catalog.h"
#include "catalog/index_catalog.h"
#include "catalog/column_catalog.h"
#include "catalog/database_metrics_catalog.h"
#include "catalog/query_metrics_catalog.h"
#include "concurrency/transaction_manager_factory.h"
#include "common/harness.h"
#include "common/logger.h"
#include "storage/storage_manager.h"
#include "type/ephemeral_pool.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Catalog Tests
//===--------------------------------------------------------------------===//
class CatalogTests : public PelotonTest {};
TEST_F(CatalogTests, BootstrappingCatalog) {
auto catalog = catalog::Catalog::GetInstance();
catalog->Bootstrap();
EXPECT_EQ(1, storage::StorageManager::GetInstance()->GetDatabaseCount());
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
storage::Database *database =
catalog->GetDatabaseWithName(CATALOG_DATABASE_NAME, txn);
txn_manager.CommitTransaction(txn);
EXPECT_NE(nullptr, database);
// Check database metric table
auto db_metric_table =
database->GetTableWithName(DATABASE_METRICS_CATALOG_NAME);
EXPECT_NE(nullptr, db_metric_table);
}
//
TEST_F(CatalogTests, CreatingDatabase) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase("EMP_DB", txn);
auto table_object = catalog::Catalog::GetInstance()->GetTableObject(
CATALOG_DATABASE_NAME, INDEX_CATALOG_NAME, txn);
auto index_object = table_object->GetIndexObject(INDEX_CATALOG_PKEY_OID);
std::vector<oid_t> key_attrs = index_object->key_attrs;
EXPECT_EQ("EMP_DB", catalog::Catalog::GetInstance()
->GetDatabaseWithName("EMP_DB", txn)
->GetDBName());
txn_manager.CommitTransaction(txn);
EXPECT_EQ(1, key_attrs.size());
EXPECT_EQ(0, key_attrs[0]);
}
TEST_F(CatalogTests, CreatingTable) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
auto id_column = catalog::Column(
type::TypeId::INTEGER, type::Type::GetTypeSize(type::TypeId::INTEGER),
"id", true);
id_column.AddConstraint(
catalog::Constraint(ConstraintType::PRIMARY, "primary_key"));
auto name_column = catalog::Column(type::TypeId::VARCHAR, 32, "name", true);
std::unique_ptr<catalog::Schema> table_schema(
new catalog::Schema({id_column, name_column}));
std::unique_ptr<catalog::Schema> table_schema_2(
new catalog::Schema({id_column, name_column}));
std::unique_ptr<catalog::Schema> table_schema_3(
new catalog::Schema({id_column, name_column}));
catalog::Catalog::GetInstance()->CreateTable("EMP_DB", "emp_table",
std::move(table_schema), txn);
catalog::Catalog::GetInstance()->CreateTable("EMP_DB", "department_table",
std::move(table_schema_2), txn);
catalog::Catalog::GetInstance()->CreateTable("EMP_DB", "salary_table",
std::move(table_schema_3), txn);
// insert random tuple into DATABASE_METRICS_CATALOG and check
std::unique_ptr<type::AbstractPool> pool(new type::EphemeralPool());
catalog::DatabaseMetricsCatalog::GetInstance()->InsertDatabaseMetrics(
2, 3, 4, 5, pool.get(), txn);
// oid_t time_stamp =
// catalog::DatabaseMetricsCatalog::GetInstance()->GetTimeStamp(2, txn);
// inset meaningless tuple into QUERY_METRICS_CATALOG and check
stats::QueryMetric::QueryParamBuf param;
param.len = 1;
param.buf = (unsigned char *)pool->Allocate(1);
*param.buf = 'a';
catalog::QueryMetricsCatalog::GetInstance()->InsertQueryMetrics(
"a query", 1, 1, param, param, param, 1, 1, 1, 1, 1, 1, 1, pool.get(),
txn);
auto param1 = catalog::QueryMetricsCatalog::GetInstance()->GetParamTypes(
"a query", 1, txn);
EXPECT_EQ(1, param1.len);
EXPECT_EQ('a', *param1.buf);
EXPECT_EQ("name", catalog::Catalog::GetInstance()
->GetDatabaseWithName("EMP_DB", txn)
->GetTableWithName("department_table")
->GetSchema()
->GetColumn(1)
.GetName());
txn_manager.CommitTransaction(txn);
// EXPECT_EQ(5, time_stamp);
// We remove these tests so people can add new catalogs without breaking this
// test...
// 3 + 4
// EXPECT_EQ(catalog::Catalog::GetInstance()
// ->GetDatabaseWithName("pg_catalog")
// ->GetTableWithName("pg_table")
// ->GetTupleCount(),
// 11);
// // 6 + pg_database(2) + pg_table(3) + pg_attribute(7) + pg_index(6)
// EXPECT_EQ(catalog::Catalog::GetInstance()
// ->GetDatabaseWithName("pg_catalog")
// ->GetTableWithName("pg_attribute")
// ->GetTupleCount(),
// 57);
// // pg_catalog + EMP_DB
// EXPECT_EQ(catalog::Catalog::GetInstance()
// ->GetDatabaseWithName("pg_catalog")
// ->GetTableWithName("pg_database")
// ->GetTupleCount(),
// 2);
// // 3 + pg_index(3) + pg_attribute(3) + pg_table(3) + pg_database(2)
// EXPECT_EQ(catalog::Catalog::GetInstance()
// ->GetDatabaseWithName("pg_catalog")
// ->GetTableWithName("pg_index")
// ->GetTupleCount(),
// 18);
// EXPECT_EQ(catalog::Catalog::GetInstance()
// ->GetDatabaseWithName("pg_catalog")
// ->GetTableWithName("pg_table")
// ->GetSchema()
// ->GetLength(),
// 72);
}
TEST_F(CatalogTests, TableObject) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
auto table_object = catalog::Catalog::GetInstance()->GetTableObject(
"EMP_DB", "department_table", txn);
auto index_objects = table_object->GetIndexObjects();
auto column_objects = table_object->GetColumnObjects();
EXPECT_EQ(1, index_objects.size());
EXPECT_EQ(2, column_objects.size());
EXPECT_EQ(table_object->table_oid, column_objects[0]->table_oid);
EXPECT_EQ("id", column_objects[0]->column_name);
EXPECT_EQ(0, column_objects[0]->column_id);
EXPECT_EQ(0, column_objects[0]->column_offset);
EXPECT_EQ(type::TypeId::INTEGER, column_objects[0]->column_type);
EXPECT_EQ(true, column_objects[0]->is_inlined);
EXPECT_EQ(true, column_objects[0]->is_primary);
EXPECT_EQ(false, column_objects[0]->is_not_null);
EXPECT_EQ(table_object->table_oid, column_objects[1]->table_oid);
EXPECT_EQ("name", column_objects[1]->column_name);
EXPECT_EQ(1, column_objects[1]->column_id);
EXPECT_EQ(4, column_objects[1]->column_offset);
EXPECT_EQ(type::TypeId::VARCHAR, column_objects[1]->column_type);
EXPECT_EQ(true, column_objects[1]->is_inlined);
EXPECT_EQ(false, column_objects[1]->is_primary);
EXPECT_EQ(false, column_objects[1]->is_not_null);
txn_manager.CommitTransaction(txn);
}
TEST_F(CatalogTests, DroppingTable) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
auto catalog = catalog::Catalog::GetInstance();
EXPECT_EQ(
3,
(int)catalog->GetDatabaseObject("EMP_DB", txn)->GetTableObjects().size());
auto database_object =
catalog::Catalog::GetInstance()->GetDatabaseObject("EMP_DB", txn);
EXPECT_NE(nullptr, database_object);
catalog::Catalog::GetInstance()->DropTable("EMP_DB", "department_table", txn);
database_object =
catalog::Catalog::GetInstance()->GetDatabaseObject("EMP_DB", txn);
EXPECT_NE(nullptr, database_object);
auto department_table_object =
database_object->GetTableObject("department_table");
// catalog::Catalog::GetInstance()->PrintCatalogs();
EXPECT_EQ(
2,
(int)catalog->GetDatabaseObject("EMP_DB", txn)->GetTableObjects().size());
txn_manager.CommitTransaction(txn);
EXPECT_EQ(nullptr, department_table_object);
// Try to drop again
txn = txn_manager.BeginTransaction();
EXPECT_THROW(catalog::Catalog::GetInstance()->DropTable(
"EMP_DB", "department_table", txn),
CatalogException);
EXPECT_EQ(
2,
(int)catalog->GetDatabaseObject("EMP_DB", txn)->GetTableObjects().size());
txn_manager.CommitTransaction(txn);
// Drop a table that does not exist
txn = txn_manager.BeginTransaction();
EXPECT_THROW(
catalog::Catalog::GetInstance()->DropTable("EMP_DB", "void_table", txn),
CatalogException);
EXPECT_EQ(
2,
(int)catalog->GetDatabaseObject("EMP_DB", txn)->GetTableObjects().size());
txn_manager.CommitTransaction(txn);
// Drop the other table
txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->DropTable("EMP_DB", "emp_table", txn);
EXPECT_EQ(
1,
(int)catalog->GetDatabaseObject("EMP_DB", txn)->GetTableObjects().size());
txn_manager.CommitTransaction(txn);
}
TEST_F(CatalogTests, DroppingDatabase) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->DropDatabaseWithName("EMP_DB", txn);
EXPECT_THROW(
catalog::Catalog::GetInstance()->GetDatabaseWithName("EMP_DB", txn),
CatalogException);
txn_manager.CommitTransaction(txn);
}
TEST_F(CatalogTests, DroppingCatalog) {
auto catalog = catalog::Catalog::GetInstance();
EXPECT_NE(nullptr, catalog);
}
} // namespace test
} // namespace peloton
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "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 Qt Company Ltd 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*
File is modified to be merged with RingQt
Updated by : Mahmoud Fayed <[email protected]>
Date : 2017.01.29
*/
#include <QtWidgets>
#include "codeeditor.h"
#include "ring.h"
CodeEditor::CodeEditor(QWidget *parent, VM *pVM) : GPlainTextEdit(parent,pVM) , c(0)
{
lineNumberArea = new LineNumberArea(this);
this->areaColor = Qt::black;
this->areaBackColor = Qt::cyan;
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
updateLineNumberAreaWidth(0);
}
void CodeEditor::setLineNumbersAreaColor(QColor oColor)
{
this->areaColor = oColor;
}
void CodeEditor::setLineNumbersAreaBackColor(QColor oColor)
{
this->areaBackColor = oColor;
}
int CodeEditor::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax(1, blockCount());
while (max >= 10) {
max /= 10;
++digits;
}
int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
return space*2;
}
void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
{
if (dy)
lineNumberArea->scroll(0, dy);
else
lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void CodeEditor::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
QFont font = painter.font() ;
font.setPointSize(fontMetrics().height());
painter.setFont(font);
painter.fillRect(event->rect(), this->areaBackColor);
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString number = QString::number(blockNumber + 1);
painter.setPen(this->areaColor);
painter.drawText(0, top, lineNumberArea->width(), bottom-top,
Qt::AlignCenter, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
void CodeEditor::setCompleter(QCompleter *completer)
{
if (c) {
QObject::disconnect(c, 0, this, 0);
delete c;
}
c = completer;
if (!c)
return;
c->setWidget(this);
c->setCompletionMode(QCompleter::PopupCompletion);
c->setCaseSensitivity(Qt::CaseInsensitive);
QObject::connect(c, SIGNAL(activated(QString)),
this, SLOT(insertCompletion(QString)));
}
QCompleter *CodeEditor::completer() const
{
return c;
}
void CodeEditor::insertCompletion(const QString& completion)
{
if (c->widget() != this)
return;
QTextCursor tc = textCursor();
int extra = completion.length() - c->completionPrefix().length();
tc.movePosition(QTextCursor::Left);
tc.movePosition(QTextCursor::EndOfWord);
tc.insertText(completion.right(extra));
setTextCursor(tc);
}
QString CodeEditor::textUnderCursor() const
{
QTextCursor tc = textCursor();
tc.select(QTextCursor::WordUnderCursor);
return tc.selectedText();
}
void CodeEditor::focusInEvent(QFocusEvent *e)
{
if (c)
c->setWidget(this);
GPlainTextEdit::focusInEvent(e);
}
void CodeEditor::keyPressEvent(QKeyEvent *e)
{
QTextCursor cur ;
int a ;
int p ;
QString str ;
QStringList list ;
if ( e->key() == Qt::Key_Tab) {
cur = textCursor();
a = cur.anchor();
p = cur.position();
cur.setPosition(a);
cur.movePosition(QTextCursor::StartOfBlock,QTextCursor::MoveAnchor);
a = cur.position();
cur.setPosition(a);
cur.setPosition(p, QTextCursor::KeepAnchor);
str = cur.selection().toPlainText();
list = str.split("\n");
for (int i = 0; i < list.count(); i++)
list[i].insert(0,"\t");
str=list.join("\n");
cur.removeSelectedText();
cur.insertText(str);
cur.setPosition(a);
cur.setPosition(p+list.count(), QTextCursor::KeepAnchor);
setTextCursor(cur);
e->accept();
return ;
}
if (c && c->popup()->isVisible()) {
// The following keys are forwarded by the completer to the widget
switch (e->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
e->ignore();
return; // let the completer do default behavior
case Qt::Key_Escape:
case Qt::Key_Tab:
case Qt::Key_Backtab:
c->popup()->hide();
return; // let the completer do default behavior
default:
break;
}
}
bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E
if (!c || !isShortcut) // do not process the shortcut when we have a completer
GPlainTextEdit::keyPressEvent(e);
const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
if (!c || (ctrlOrShift && e->text().isEmpty()))
return;
static QString eow("~!#%^&*()+{}|:<>?,/;[]\\-="); // end of word
bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
QString completionPrefix = textUnderCursor();
if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3
|| eow.contains(e->text().right(1)))) {
c->popup()->hide();
return;
}
if (completionPrefix != c->completionPrefix()) {
c->setCompletionPrefix(completionPrefix);
c->popup()->setCurrentIndex(c->completionModel()->index(0, 0));
}
QRect cr = cursorRect();
cr.setWidth(c->popup()->sizeHintForColumn(0)
+ c->popup()->verticalScrollBar()->sizeHint().width());
c->complete(cr); // popup it up!
}<commit_msg>Update RingQt<commit_after>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "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 Qt Company Ltd 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*
File is modified to be merged with RingQt
Updated by : Mahmoud Fayed <[email protected]>
Date : 2017.01.29
*/
#include <QtWidgets>
#include "codeeditor.h"
#include "ring.h"
CodeEditor::CodeEditor(QWidget *parent, VM *pVM) : GPlainTextEdit(parent,pVM) , c(0)
{
lineNumberArea = new LineNumberArea(this);
this->areaColor = Qt::black;
this->areaBackColor = Qt::cyan;
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
updateLineNumberAreaWidth(0);
}
void CodeEditor::setLineNumbersAreaColor(QColor oColor)
{
this->areaColor = oColor;
}
void CodeEditor::setLineNumbersAreaBackColor(QColor oColor)
{
this->areaBackColor = oColor;
}
int CodeEditor::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax(1, blockCount());
while (max >= 10) {
max /= 10;
++digits;
}
int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
return space*2;
}
void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
{
if (dy)
lineNumberArea->scroll(0, dy);
else
lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void CodeEditor::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
QFont font = painter.font() ;
font.setPointSize(fontMetrics().height());
painter.setFont(font);
painter.fillRect(event->rect(), this->areaBackColor);
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString number = QString::number(blockNumber + 1);
painter.setPen(this->areaColor);
painter.drawText(0, top, lineNumberArea->width(), bottom-top,
Qt::AlignCenter, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
void CodeEditor::setCompleter(QCompleter *completer)
{
if (c) {
QObject::disconnect(c, 0, this, 0);
delete c;
}
c = completer;
if (!c)
return;
c->setWidget(this);
c->setCompletionMode(QCompleter::PopupCompletion);
c->setCaseSensitivity(Qt::CaseInsensitive);
QObject::connect(c, SIGNAL(activated(QString)),
this, SLOT(insertCompletion(QString)));
}
QCompleter *CodeEditor::completer() const
{
return c;
}
void CodeEditor::insertCompletion(const QString& completion)
{
if (c->widget() != this)
return;
QTextCursor tc = textCursor();
int extra = completion.length() - c->completionPrefix().length();
tc.movePosition(QTextCursor::Left);
tc.movePosition(QTextCursor::EndOfWord);
tc.insertText(completion.right(extra));
setTextCursor(tc);
}
QString CodeEditor::textUnderCursor() const
{
QTextCursor tc = textCursor();
tc.select(QTextCursor::WordUnderCursor);
return tc.selectedText();
}
void CodeEditor::focusInEvent(QFocusEvent *e)
{
if (c)
c->setWidget(this);
GPlainTextEdit::focusInEvent(e);
}
void CodeEditor::keyPressEvent(QKeyEvent *e)
{
QTextCursor cur ;
int a ;
int p ;
QString str ;
QStringList list ;
if ( e->key() == Qt::Key_Tab) {
cur = textCursor();
a = cur.anchor();
p = cur.position();
cur.setPosition(a);
cur.movePosition(QTextCursor::StartOfBlock,QTextCursor::MoveAnchor);
a = cur.position();
cur.setPosition(a);
cur.setPosition(p, QTextCursor::KeepAnchor);
str = cur.selection().toPlainText();
list = str.split("\n");
for (int i = 0; i < list.count(); i++)
list[i].insert(0,"\t");
str=list.join("\n");
cur.removeSelectedText();
cur.insertText(str);
cur.setPosition(a);
cur.setPosition(p+list.count(), QTextCursor::KeepAnchor);
setTextCursor(cur);
e->accept();
return ;
}
if (c && c->popup()->isVisible()) {
// The following keys are forwarded by the completer to the widget
switch (e->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
e->ignore();
return; // let the completer do default behavior
case Qt::Key_Escape:
case Qt::Key_Backtab:
c->popup()->hide();
return; // let the completer do default behavior
default:
break;
}
}
bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E
if (!c || !isShortcut) // do not process the shortcut when we have a completer
GPlainTextEdit::keyPressEvent(e);
const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
if (!c || (ctrlOrShift && e->text().isEmpty()))
return;
static QString eow("~!#%^&*()+{}|:<>?,/;[]\\-="); // end of word
bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
QString completionPrefix = textUnderCursor();
if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3
|| eow.contains(e->text().right(1)))) {
c->popup()->hide();
return;
}
if (completionPrefix != c->completionPrefix()) {
c->setCompletionPrefix(completionPrefix);
c->popup()->setCurrentIndex(c->completionModel()->index(0, 0));
}
QRect cr = cursorRect();
cr.setWidth(c->popup()->sizeHintForColumn(0)
+ c->popup()->verticalScrollBar()->sizeHint().width());
c->complete(cr); // popup it up!
}<|endoftext|> |
<commit_before>#include <FImage.h>
using namespace FImage;
int main(int argc, char **argv) {
int W = 128, H = 128;
Image<uint16_t> in(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
in(x, y) = rand() & 0xff;
}
}
Var x("x"), y("y");
Image<uint16_t> tent = {{1, 2, 1},
{2, 4, 2},
{1, 2, 1}};
Func input("input");
input(x, y) = in(Clamp(x, 0, W), Clamp(y, 0, H));
Func blur("blur");
RVar i, j;
blur(x, y) = Sum(tent(i, j) * input(x + i - 1, y + j - 1));
if (use_gpu()) {
Var tidx("threadidx");
Var bidx("blockidx");
Var tidy("threadidy");
Var bidy("blockidy");
blur.split(x, bidx, tidx, 16);
blur.parallel(bidx);
blur.parallel(tidx);
blur.split(y, bidy, tidy, 16);
blur.parallel(bidy);
blur.parallel(tidy);
blur.transpose(bidx,tidy);
}
/*
for (size_t i = 0; i < blur.rhs().funcs().size(); i++) {
Func f = blur.rhs().funcs()[i];
if (f.name() != "input")
f.chunk(x);
}
*/
Image<uint16_t> out = blur.realize(W, H);
for (int y = 1; y < H-1; y++) {
for (int x = 1; x < W-1; x++) {
uint16_t correct = (1*in(x-1, y-1) + 2*in(x, y-1) + 1*in(x+1, y-1) +
2*in(x-1, y) + 4*in(x, y) + 2*in(x+1, y) +
1*in(x-1, y+1) + 2*in(x, y+1) + 1*in(x+1, y+1));
if (out(x, y) != correct) {
printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
<commit_msg>convolution tests tiling reduction<commit_after>#include <FImage.h>
using namespace FImage;
int main(int argc, char **argv) {
int W = 64*3, H = 64*3;
Image<uint16_t> in(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
in(x, y) = rand() & 0xff;
}
}
Var x("x"), y("y");
Image<uint16_t> tent = {{1, 2, 1},
{2, 4, 2},
{1, 2, 1}};
Func input("input");
input(x, y) = in(Clamp(x, 0, W), Clamp(y, 0, H));
Func blur("blur");
RVar i, j;
blur(x, y) += tent(i, j) * input(x + i - 1, y + j - 1);
if (use_gpu()) {
Var tidx("threadidx");
Var bidx("blockidx");
Var tidy("threadidy");
Var bidy("blockidy");
blur.split(x, bidx, tidx, 16);
blur.parallel(bidx);
blur.parallel(tidx);
blur.split(y, bidy, tidy, 16);
blur.parallel(bidy);
blur.parallel(tidy);
blur.transpose(bidx,tidy);
}
// Take this opportunity to test tiling reductions
Var xi, yi;
blur.tile(x, y, xi, yi, 6, 6);
blur.update().tile(x, y, xi, yi, 4, 4);
Image<uint16_t> out = blur.realize(W, H);
for (int y = 1; y < H-1; y++) {
for (int x = 1; x < W-1; x++) {
uint16_t correct = (1*in(x-1, y-1) + 2*in(x, y-1) + 1*in(x+1, y-1) +
2*in(x-1, y) + 4*in(x, y) + 2*in(x+1, y) +
1*in(x-1, y+1) + 2*in(x, y+1) + 1*in(x+1, y+1));
if (out(x, y) != correct) {
printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 The Brick Authors.
#include "brick/platform_util.h"
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <glib.h>
#include <string>
#include "include/wrapper/cef_helpers.h"
#include "brick/helper.h"
namespace {
// The KDE session version environment variable used in KDE 4.
const char kKDE4SessionEnvVar[] = "KDE_SESSION_VERSION";
// Set the calling thread's signal mask to new_sigmask and return
// the previous signal mask.
sigset_t
SetSignalMask(const sigset_t& new_sigmask) {
sigset_t old_sigmask;
pthread_sigmask(SIG_SETMASK, &new_sigmask, &old_sigmask);
return old_sigmask;
}
bool
LaunchProcess(const std::vector<std::string>& args) {
sigset_t full_sigset;
sigfillset(&full_sigset);
const sigset_t orig_sigmask = SetSignalMask(full_sigset);
pid_t pid;
pid = fork();
// Always restore the original signal mask in the parent.
if (pid != 0) {
SetSignalMask(orig_sigmask);
}
if (pid < 0) {
LOG(ERROR)
<< "LaunchProcess: failed fork";
return false;
} else if (pid == 0) {
// Child process
// DANGER: fork() rule: in the child, if you don't end up doing exec*(),
// you call _exit() instead of exit(). This is because _exit() does not
// call any previously-registered (in the parent) exit handlers, which
// might do things like block waiting for threads that don't even exist
// in the child.
// ToDo: Put environment like Google chrome
// options.allow_new_privs = true;
// // xdg-open can fall back on mailcap which eventually might plumb through
// // to a command that needs a terminal. Set the environment variable telling
// // it that we definitely don't have a terminal available and that it should
// // bring up a new terminal if necessary. See "man mailcap".
// options.environ["MM_NOTTTY"] = "1";
//
// // We do not let GNOME's bug-buddy intercept our crashes.
// char* disable_gnome_bug_buddy = getenv("GNOME_DISABLE_CRASH_DIALOG");
// if (disable_gnome_bug_buddy &&
// disable_gnome_bug_buddy == std::string("SET_BY_GOOGLE_CHROME"))
// options.environ["GNOME_DISABLE_CRASH_DIALOG"] = std::string();
std::vector<char*> argv(args.size() + 1, NULL);
for (size_t i = 0; i < args.size(); ++i) {
argv[i] = const_cast<char*>(args[i].c_str());
}
execvp(argv[0], &argv[0]);
LOG(ERROR)
<< "LaunchProcess: failed to execvp:" << argv[0];
_exit(127);
}
return true;
}
void
XDGUtil(const std::string& util, const std::string& arg) {
std::vector<std::string> argv;
argv.push_back(util.c_str());
argv.push_back(arg.c_str());
LaunchProcess(argv);
}
void
XDGOpen(const std::string& path) {
XDGUtil("xdg-open", path);
}
void
XDGEmail(const std::string& email) {
XDGUtil("xdg-email", email);
}
} // namespace
namespace platform_util {
void
OpenExternal(std::string url) {
if (url.find("mailto:") == 0)
XDGEmail(url);
else
XDGOpen(url);
}
bool
IsPathExists(std::string path) {
struct stat stat_data;
return stat(path.c_str(), &stat_data) != -1;
}
bool
MakeDirectory(std::string path) {
if (IsPathExists(path))
return true;
size_t pre = 0;
size_t pos;
std::string dir;
if (path[path.size()-1] != '/') {
// force trailing / so we can handle everything in loop
path += '/';
}
while ((pos = path.find_first_of('/', pre)) !=std::string::npos) {
dir = path.substr(0, pos++);
pre = pos;
if (dir.size() == 0)
continue;
if (mkdir(dir.c_str(), 0700) && errno != EEXIST) {
return false;
}
}
return true;
}
bool
GetEnv(const char* variable_name, std::string* result) {
const char *env_value = getenv(variable_name);
if (!env_value)
return false;
// Note that the variable may be defined but empty.
if (result)
*result = env_value;
return true;
}
bool
HasEnv(const char* variable_name) {
return GetEnv(variable_name, NULL);
}
DesktopEnvironment
GetDesktopEnvironment() {
// XDG_CURRENT_DESKTOP is the newest standard circa 2012.
std::string xdg_current_desktop;
if (GetEnv("XDG_CURRENT_DESKTOP", &xdg_current_desktop)) {
// Not all desktop environments set this env var as of this writing.
if (xdg_current_desktop == "Unity") {
// gnome-fallback sessions set XDG_CURRENT_DESKTOP to Unity
// DESKTOP_SESSION can be gnome-fallback or gnome-fallback-compiz
std::string desktop_session;
if (GetEnv("DESKTOP_SESSION", &desktop_session) &&
desktop_session.find("gnome-fallback") != std::string::npos) {
return DESKTOP_ENVIRONMENT_GNOME;
}
return DESKTOP_ENVIRONMENT_UNITY;
} else if (xdg_current_desktop == "GNOME") {
return DESKTOP_ENVIRONMENT_GNOME;
} else if (xdg_current_desktop == "KDE") {
return DESKTOP_ENVIRONMENT_KDE;
}
}
// DESKTOP_SESSION was what everyone used in 2010.
std::string desktop_session;
if (GetEnv("DESKTOP_SESSION", &desktop_session)) {
if (desktop_session == "gnome" || desktop_session =="mate") {
return DESKTOP_ENVIRONMENT_GNOME;
} else if (desktop_session == "kde4" || desktop_session == "kde-plasma") {
return DESKTOP_ENVIRONMENT_KDE;
} else if (desktop_session == "kde") {
// This may mean KDE4 on newer systems, so we have to check.
if (HasEnv(kKDE4SessionEnvVar))
return DESKTOP_ENVIRONMENT_KDE;
return DESKTOP_ENVIRONMENT_KDE_OLD;
} else if (desktop_session.find("xfce") != std::string::npos ||
desktop_session == "xubuntu") {
return DESKTOP_ENVIRONMENT_XFCE;
}
}
// Fall back on some older environment variables.
// Useful particularly in the DESKTOP_SESSION=default case.
if (HasEnv("GNOME_DESKTOP_SESSION_ID")) {
return DESKTOP_ENVIRONMENT_GNOME;
} else if (HasEnv("KDE_FULL_SESSION")) {
if (HasEnv(kKDE4SessionEnvVar))
return DESKTOP_ENVIRONMENT_KDE;
return DESKTOP_ENVIRONMENT_KDE_OLD;
}
return DESKTOP_ENVIRONMENT_OTHER;
}
const std::string
GetDefaultDownloadDir() {
const gchar * dir = g_get_user_special_dir(G_USER_DIRECTORY_DOWNLOAD);
if (dir == NULL) {
// Fallback to $HOME/Downloads
dir = g_get_home_dir();
}
if (dir != NULL) {
return std::string(dir) + "/" + "Downloads";
}
return "";
}
} // namespace platform_util
<commit_msg>Все-таки по умолчанию кочаем в $HOME, если мы ничего не знаем о окружении<commit_after>// Copyright (c) 2015 The Brick Authors.
#include "brick/platform_util.h"
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <glib.h>
#include <string>
#include "include/wrapper/cef_helpers.h"
#include "brick/helper.h"
namespace {
// The KDE session version environment variable used in KDE 4.
const char kKDE4SessionEnvVar[] = "KDE_SESSION_VERSION";
// Set the calling thread's signal mask to new_sigmask and return
// the previous signal mask.
sigset_t
SetSignalMask(const sigset_t& new_sigmask) {
sigset_t old_sigmask;
pthread_sigmask(SIG_SETMASK, &new_sigmask, &old_sigmask);
return old_sigmask;
}
bool
LaunchProcess(const std::vector<std::string>& args) {
sigset_t full_sigset;
sigfillset(&full_sigset);
const sigset_t orig_sigmask = SetSignalMask(full_sigset);
pid_t pid;
pid = fork();
// Always restore the original signal mask in the parent.
if (pid != 0) {
SetSignalMask(orig_sigmask);
}
if (pid < 0) {
LOG(ERROR)
<< "LaunchProcess: failed fork";
return false;
} else if (pid == 0) {
// Child process
// DANGER: fork() rule: in the child, if you don't end up doing exec*(),
// you call _exit() instead of exit(). This is because _exit() does not
// call any previously-registered (in the parent) exit handlers, which
// might do things like block waiting for threads that don't even exist
// in the child.
// ToDo: Put environment like Google chrome
// options.allow_new_privs = true;
// // xdg-open can fall back on mailcap which eventually might plumb through
// // to a command that needs a terminal. Set the environment variable telling
// // it that we definitely don't have a terminal available and that it should
// // bring up a new terminal if necessary. See "man mailcap".
// options.environ["MM_NOTTTY"] = "1";
//
// // We do not let GNOME's bug-buddy intercept our crashes.
// char* disable_gnome_bug_buddy = getenv("GNOME_DISABLE_CRASH_DIALOG");
// if (disable_gnome_bug_buddy &&
// disable_gnome_bug_buddy == std::string("SET_BY_GOOGLE_CHROME"))
// options.environ["GNOME_DISABLE_CRASH_DIALOG"] = std::string();
std::vector<char*> argv(args.size() + 1, NULL);
for (size_t i = 0; i < args.size(); ++i) {
argv[i] = const_cast<char*>(args[i].c_str());
}
execvp(argv[0], &argv[0]);
LOG(ERROR)
<< "LaunchProcess: failed to execvp:" << argv[0];
_exit(127);
}
return true;
}
void
XDGUtil(const std::string& util, const std::string& arg) {
std::vector<std::string> argv;
argv.push_back(util.c_str());
argv.push_back(arg.c_str());
LaunchProcess(argv);
}
void
XDGOpen(const std::string& path) {
XDGUtil("xdg-open", path);
}
void
XDGEmail(const std::string& email) {
XDGUtil("xdg-email", email);
}
} // namespace
namespace platform_util {
void
OpenExternal(std::string url) {
if (url.find("mailto:") == 0)
XDGEmail(url);
else
XDGOpen(url);
}
bool
IsPathExists(std::string path) {
struct stat stat_data;
return stat(path.c_str(), &stat_data) != -1;
}
bool
MakeDirectory(std::string path) {
if (IsPathExists(path))
return true;
size_t pre = 0;
size_t pos;
std::string dir;
if (path[path.size()-1] != '/') {
// force trailing / so we can handle everything in loop
path += '/';
}
while ((pos = path.find_first_of('/', pre)) !=std::string::npos) {
dir = path.substr(0, pos++);
pre = pos;
if (dir.size() == 0)
continue;
if (mkdir(dir.c_str(), 0700) && errno != EEXIST) {
return false;
}
}
return true;
}
bool
GetEnv(const char* variable_name, std::string* result) {
const char *env_value = getenv(variable_name);
if (!env_value)
return false;
// Note that the variable may be defined but empty.
if (result)
*result = env_value;
return true;
}
bool
HasEnv(const char* variable_name) {
return GetEnv(variable_name, NULL);
}
DesktopEnvironment
GetDesktopEnvironment() {
// XDG_CURRENT_DESKTOP is the newest standard circa 2012.
std::string xdg_current_desktop;
if (GetEnv("XDG_CURRENT_DESKTOP", &xdg_current_desktop)) {
// Not all desktop environments set this env var as of this writing.
if (xdg_current_desktop == "Unity") {
// gnome-fallback sessions set XDG_CURRENT_DESKTOP to Unity
// DESKTOP_SESSION can be gnome-fallback or gnome-fallback-compiz
std::string desktop_session;
if (GetEnv("DESKTOP_SESSION", &desktop_session) &&
desktop_session.find("gnome-fallback") != std::string::npos) {
return DESKTOP_ENVIRONMENT_GNOME;
}
return DESKTOP_ENVIRONMENT_UNITY;
} else if (xdg_current_desktop == "GNOME") {
return DESKTOP_ENVIRONMENT_GNOME;
} else if (xdg_current_desktop == "KDE") {
return DESKTOP_ENVIRONMENT_KDE;
}
}
// DESKTOP_SESSION was what everyone used in 2010.
std::string desktop_session;
if (GetEnv("DESKTOP_SESSION", &desktop_session)) {
if (desktop_session == "gnome" || desktop_session =="mate") {
return DESKTOP_ENVIRONMENT_GNOME;
} else if (desktop_session == "kde4" || desktop_session == "kde-plasma") {
return DESKTOP_ENVIRONMENT_KDE;
} else if (desktop_session == "kde") {
// This may mean KDE4 on newer systems, so we have to check.
if (HasEnv(kKDE4SessionEnvVar))
return DESKTOP_ENVIRONMENT_KDE;
return DESKTOP_ENVIRONMENT_KDE_OLD;
} else if (desktop_session.find("xfce") != std::string::npos ||
desktop_session == "xubuntu") {
return DESKTOP_ENVIRONMENT_XFCE;
}
}
// Fall back on some older environment variables.
// Useful particularly in the DESKTOP_SESSION=default case.
if (HasEnv("GNOME_DESKTOP_SESSION_ID")) {
return DESKTOP_ENVIRONMENT_GNOME;
} else if (HasEnv("KDE_FULL_SESSION")) {
if (HasEnv(kKDE4SessionEnvVar))
return DESKTOP_ENVIRONMENT_KDE;
return DESKTOP_ENVIRONMENT_KDE_OLD;
}
return DESKTOP_ENVIRONMENT_OTHER;
}
const std::string
GetDefaultDownloadDir() {
const gchar * dir = g_get_user_special_dir(G_USER_DIRECTORY_DOWNLOAD);
if (dir == NULL) {
// Fallback to $HOME/Downloads
dir = g_get_home_dir();
}
if (dir != NULL) {
return dir;
}
return "";
}
} // namespace platform_util
<|endoftext|> |
<commit_before>/*
* Copyright 2017 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 "pc/sdp_utils.h"
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "api/jsep_session_description.h"
namespace webrtc {
std::unique_ptr<SessionDescriptionInterface> CloneSessionDescription(
const SessionDescriptionInterface* sdesc) {
RTC_DCHECK(sdesc);
return CloneSessionDescriptionAsType(sdesc, sdesc->GetType());
}
std::unique_ptr<SessionDescriptionInterface> CloneSessionDescriptionAsType(
const SessionDescriptionInterface* sdesc,
SdpType type) {
RTC_DCHECK(sdesc);
auto clone = absl::make_unique<JsepSessionDescription>(type);
clone->Initialize(sdesc->description()->Copy(), sdesc->session_id(),
sdesc->session_version());
// As of writing, our version of GCC does not allow returning a unique_ptr of
// a subclass as a unique_ptr of a base class. To get around this, we need to
// std::move the return value.
return std::move(clone);
}
bool SdpContentsAll(SdpContentPredicate pred,
const cricket::SessionDescription* desc) {
RTC_DCHECK(desc);
for (const auto& content : desc->contents()) {
const auto* transport_info = desc->GetTransportInfoByName(content.name);
if (!pred(&content, transport_info)) {
return false;
}
}
return true;
}
bool SdpContentsNone(SdpContentPredicate pred,
const cricket::SessionDescription* desc) {
return SdpContentsAll(std::not2(pred), desc);
}
void SdpContentsForEach(SdpContentMutator fn,
cricket::SessionDescription* desc) {
RTC_DCHECK(desc);
for (auto& content : desc->contents()) {
auto* transport_info = desc->GetTransportInfoByName(content.name);
fn(&content, transport_info);
}
}
} // namespace webrtc
<commit_msg>Replace deprecated std::not2 with a lambda<commit_after>/*
* Copyright 2017 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 "pc/sdp_utils.h"
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "api/jsep_session_description.h"
namespace webrtc {
std::unique_ptr<SessionDescriptionInterface> CloneSessionDescription(
const SessionDescriptionInterface* sdesc) {
RTC_DCHECK(sdesc);
return CloneSessionDescriptionAsType(sdesc, sdesc->GetType());
}
std::unique_ptr<SessionDescriptionInterface> CloneSessionDescriptionAsType(
const SessionDescriptionInterface* sdesc,
SdpType type) {
RTC_DCHECK(sdesc);
auto clone = absl::make_unique<JsepSessionDescription>(type);
clone->Initialize(sdesc->description()->Copy(), sdesc->session_id(),
sdesc->session_version());
// As of writing, our version of GCC does not allow returning a unique_ptr of
// a subclass as a unique_ptr of a base class. To get around this, we need to
// std::move the return value.
return std::move(clone);
}
bool SdpContentsAll(SdpContentPredicate pred,
const cricket::SessionDescription* desc) {
RTC_DCHECK(desc);
for (const auto& content : desc->contents()) {
const auto* transport_info = desc->GetTransportInfoByName(content.name);
if (!pred(&content, transport_info)) {
return false;
}
}
return true;
}
bool SdpContentsNone(SdpContentPredicate pred,
const cricket::SessionDescription* desc) {
return SdpContentsAll(
[pred](const cricket::ContentInfo* content_info,
const cricket::TransportInfo* transport_info) {
return !pred(content_info, transport_info);
},
desc);
}
void SdpContentsForEach(SdpContentMutator fn,
cricket::SessionDescription* desc) {
RTC_DCHECK(desc);
for (auto& content : desc->contents()) {
auto* transport_info = desc->GetTransportInfoByName(content.name);
fn(&content, transport_info);
}
}
} // namespace webrtc
<|endoftext|> |
<commit_before>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include "caf/detail/type_traits.hpp"
#include "caf/fwd.hpp"
#include <utility>
namespace caf::flow::step {
template <class T>
class on_error_complete {
public:
using input_type = T;
using output_type = T;
template <class Next, class... Steps>
bool on_next(const T& item, Next& next, Steps&... steps) {
return next.on_next(item, steps...);
}
template <class Next, class... Steps>
void on_error(Next& next, Steps&... steps) {
next.on_error(steps...);
}
template <class Next, class... Steps>
void on_error(const error&, Next& next, Steps&... steps) {
next.on_complete(steps...);
}
};
} // namespace caf::flow::step
<commit_msg>Fix on_error_complete<commit_after>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include "caf/detail/type_traits.hpp"
#include "caf/fwd.hpp"
#include <utility>
namespace caf::flow::step {
template <class T>
class on_error_complete {
public:
using input_type = T;
using output_type = T;
template <class Next, class... Steps>
bool on_next(const T& item, Next& next, Steps&... steps) {
return next.on_next(item, steps...);
}
template <class Next, class... Steps>
void on_complete(Next& next, Steps&... steps) {
next.on_complete(steps...);
}
template <class Next, class... Steps>
void on_error(const error&, Next& next, Steps&... steps) {
next.on_complete(steps...);
}
};
} // namespace caf::flow::step
<|endoftext|> |
<commit_before>#include "dbg_pathconvert.h"
#include "dbg_path.h"
#include "dbg_impl.h"
#include "dbg_unicode.h"
#include <algorithm>
#include <assert.h>
namespace vscode
{
pathconvert::pathconvert(debugger_impl* dbg)
: debugger_(dbg)
, sourcemaps_()
{ }
void pathconvert::add_sourcemap(const fs::path& srv, const fs::path& cli)
{
if (srv.is_absolute())
{
sourcemaps_.push_back(std::make_pair(path_normalize(srv), cli));
}
else
{
sourcemaps_.push_back(std::make_pair(path_normalize(fs::absolute(srv, fs::current_path())), cli));
}
}
void pathconvert::clear_sourcemap()
{
sourcemaps_.clear();
}
bool pathconvert::fget(const std::string& server_path, fs::path*& client_path)
{
auto it = server2client_.find(server_path);
if (it != server2client_.end())
{
client_path = &it->second;
return true;
}
return false;
}
fs::path pathconvert::server_complete(const fs::path& path)
{
if (path.is_absolute())
{
return path;
}
return path_normalize(fs::absolute(path, fs::current_path()));
}
pathconvert::result pathconvert::eval_uncomplete(const std::string& server_path, fs::path& client_path)
{
if (server_path[0] == '@')
{
fs::path srvpath = server_complete(fs::path(u2w(server_path.substr(1))));
for (auto& pair : sourcemaps_)
{
if (path_is_subpath(srvpath, pair.first))
{
std::error_code ec;
client_path = path_uncomplete(srvpath, pair.first, ec);
assert(!ec);
return result::sucess;
}
}
std::error_code ec;
client_path = path_uncomplete(srvpath, fs::current_path(), ec);
assert(!ec);
return result::sucess;
}
else if (server_path[0] == '=')
{
return debugger_->custom_->path_convert(server_path, client_path, sourcemaps_, true);
}
client_path = fs::path(u2w(server_path));
return result::sucess;
}
pathconvert::result pathconvert::eval(const std::string& server_path, fs::path& client_path)
{
if (server_path[0] == '@')
{
fs::path srvpath = server_complete(fs::path(a2w(server_path.substr(1))));
for (auto& pair : sourcemaps_)
{
if (path_is_subpath(srvpath, pair.first))
{
std::error_code ec;
client_path = path_normalize(pair.second / path_uncomplete(srvpath, pair.first, ec));
server2client_[server_path] = client_path;
assert(!ec);
return result::sucess;
}
}
client_path = path_normalize(srvpath);
server2client_[server_path] = client_path;
return result::sucess;
}
else if (server_path[0] == '=')
{
result r = debugger_->custom_->path_convert(server_path, client_path, sourcemaps_, false);
switch (r)
{
case custom::result::failed:
case custom::result::sucess:
server2client_[server_path] = client_path;
break;
}
return r;
}
client_path = fs::path(u2w(server_path));
server2client_[server_path] = client_path;
return result::sucess;
}
pathconvert::result pathconvert::get_or_eval(const std::string& server_path, fs::path& client_path)
{
fs::path* ptr;
if (fget(server_path, ptr))
{
client_path = *ptr;
return result::sucess;
}
return eval(server_path, client_path);
}
}
<commit_msg>修正路径计算的错误<commit_after>#include "dbg_pathconvert.h"
#include "dbg_path.h"
#include "dbg_impl.h"
#include "dbg_unicode.h"
#include <algorithm>
#include <assert.h>
namespace vscode
{
pathconvert::pathconvert(debugger_impl* dbg)
: debugger_(dbg)
, sourcemaps_()
{ }
void pathconvert::add_sourcemap(const fs::path& srv, const fs::path& cli)
{
if (srv.is_absolute())
{
sourcemaps_.push_back(std::make_pair(path_normalize(srv), cli));
}
else
{
sourcemaps_.push_back(std::make_pair(path_normalize(fs::absolute(srv, fs::current_path())), cli));
}
}
void pathconvert::clear_sourcemap()
{
sourcemaps_.clear();
}
bool pathconvert::fget(const std::string& server_path, fs::path*& client_path)
{
auto it = server2client_.find(server_path);
if (it != server2client_.end())
{
client_path = &it->second;
return true;
}
return false;
}
fs::path pathconvert::server_complete(const fs::path& path)
{
if (path.is_absolute())
{
return path;
}
return path_normalize(fs::absolute(path, fs::current_path()));
}
pathconvert::result pathconvert::eval_uncomplete(const std::string& server_path, fs::path& client_path)
{
if (server_path[0] == '@')
{
fs::path srvpath = server_complete(fs::path(a2w(server_path.substr(1))));
for (auto& pair : sourcemaps_)
{
if (path_is_subpath(srvpath, pair.first))
{
std::error_code ec;
client_path = path_uncomplete(srvpath, pair.first, ec);
assert(!ec);
return result::sucess;
}
}
std::error_code ec;
client_path = path_uncomplete(srvpath, fs::current_path(), ec);
assert(!ec);
return result::sucess;
}
else if (server_path[0] == '=')
{
return debugger_->custom_->path_convert(server_path, client_path, sourcemaps_, true);
}
client_path = fs::path(a2w(server_path));
return result::sucess;
}
pathconvert::result pathconvert::eval(const std::string& server_path, fs::path& client_path)
{
if (server_path[0] == '@')
{
fs::path srvpath = server_complete(fs::path(a2w(server_path.substr(1))));
for (auto& pair : sourcemaps_)
{
if (path_is_subpath(srvpath, pair.first))
{
std::error_code ec;
client_path = path_normalize(pair.second / path_uncomplete(srvpath, pair.first, ec));
server2client_[server_path] = client_path;
assert(!ec);
return result::sucess;
}
}
client_path = path_normalize(srvpath);
server2client_[server_path] = client_path;
return result::sucess;
}
else if (server_path[0] == '=')
{
result r = debugger_->custom_->path_convert(server_path, client_path, sourcemaps_, false);
switch (r)
{
case custom::result::failed:
case custom::result::sucess:
server2client_[server_path] = client_path;
break;
}
return r;
}
client_path = fs::path(u2w(server_path));
server2client_[server_path] = client_path;
return result::sucess;
}
pathconvert::result pathconvert::get_or_eval(const std::string& server_path, fs::path& client_path)
{
fs::path* ptr;
if (fget(server_path, ptr))
{
client_path = *ptr;
return result::sucess;
}
return eval(server_path, client_path);
}
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "joedb/compiler/nested_namespace.h"
/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, splitting)
/////////////////////////////////////////////////////////////////////////////
{
auto n = joedb::split_namespace("split::this::name");
EXPECT_EQ(3, int(n.size()));
EXPECT_EQ("split", n[0]);
EXPECT_EQ("this", n[1]);
EXPECT_EQ("name", n[2]);
}
<commit_msg>test for namespace_write<commit_after>#include "gtest/gtest.h"
#include "joedb/compiler/nested_namespace.h"
#include <sstream>
/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, split_namespace)
/////////////////////////////////////////////////////////////////////////////
{
auto n = joedb::split_namespace("split::this::name");
EXPECT_EQ(3, int(n.size()));
EXPECT_EQ("split", n[0]);
EXPECT_EQ("this", n[1]);
EXPECT_EQ("name", n[2]);
}
/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, namespace_write)
/////////////////////////////////////////////////////////////////////////////
{
auto n = joedb::split_namespace("split::this::name");
std::ostringstream out;
joedb::namespace_write(out, n, "!");
EXPECT_EQ("split!this!name", out.str());
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of mcompositor.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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.
**
****************************************************************************/
#ifdef DESKTOP_VERSION
#define GL_GLEXT_PROTOTYPES 1
#endif
#include "mtexturepixmapitem.h"
#include "texturepixmapshaders.h"
#include "mcompositewindowshadereffect.h"
#include <QX11Info>
#include <QRect>
#include <X11/Xlib.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xrender.h>
#ifdef GLES2_VERSION
#include <GLES2/gl2.h>
#elif DESKTOP_VERSION
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#include <GL/glxext.h>
#endif
#include "mtexturepixmapitem_p.h"
bool MTexturePixmapPrivate::inverted_texture = true;
MGLResourceManager *MTexturePixmapPrivate::glresource = 0;
static const GLuint D_VERTEX_COORDS = 0;
static const GLuint D_TEXTURE_COORDS = 1;
#ifdef QT_OPENGL_LIB
static void bindAttribLocation(QGLShaderProgram *p, const char *attrib, int location)
{
p->bindAttributeLocation(attrib, location);
}
// OpenGL ES 2.0 / OpenGL 2.0 - compatible texture painter
class MGLResourceManager: public QObject
{
public:
/*
* This is the default set of shaders.
* Use MCompositeWindowShaderEffect class to add more shader effects
*/
enum ShaderType {
NormalShader = 0,
BlurShader,
ShaderTotal
};
MGLResourceManager(QGLWidget *glwidget)
: QObject(glwidget),
glcontext(glwidget->context()),
currentShader(0)
{
sharedVertexShader = new QGLShader(QGLShader::Vertex,
glwidget->context(), this);
if (!sharedVertexShader->compileSourceCode(QLatin1String(TexpVertShaderSource)))
qWarning("vertex shader failed to compile");
QGLShaderProgram *normalShader = new QGLShaderProgram(glwidget->context(), this);
shader[NormalShader] = normalShader;
normalShader->addShader(sharedVertexShader);
if (!normalShader->addShaderFromSourceCode(QGLShader::Fragment,
QLatin1String(TexpFragShaderSource)))
qWarning("normal fragment shader failed to compile");
QGLShaderProgram *blurShader = new QGLShaderProgram(glwidget->context(), this);
shader[BlurShader] = blurShader;
blurShader->addShader(sharedVertexShader);
if (!blurShader->addShaderFromSourceCode(QGLShader::Fragment,
QLatin1String(blurshader)))
qWarning("blur fragment shader failed to compile");
bindAttribLocation(normalShader, "inputVertex", D_VERTEX_COORDS);
bindAttribLocation(normalShader, "textureCoord", D_TEXTURE_COORDS);
bindAttribLocation(blurShader, "inputVertex", D_VERTEX_COORDS);
bindAttribLocation(blurShader, "textureCoord", D_TEXTURE_COORDS);
normalShader->link();
blurShader->link();
}
void initVertices(QGLWidget *glwidget) {
texCoords[0] = 0.0f; texCoords[1] = 1.0f;
texCoords[2] = 0.0f; texCoords[3] = 0.0f;
texCoords[4] = 1.0f; texCoords[5] = 0.0f;
texCoords[6] = 1.0f; texCoords[7] = 1.0f;
texCoordsInv[0] = 0.0f; texCoordsInv[1] = 0.0f;
texCoordsInv[2] = 0.0f; texCoordsInv[3] = 1.0f;
texCoordsInv[4] = 1.0f; texCoordsInv[5] = 1.0f;
texCoordsInv[6] = 1.0f; texCoordsInv[7] = 0.0f;
projMatrix[0][0] = 2.0 / glwidget->width(); projMatrix[1][0] = 0.0;
projMatrix[2][0] = 0.0; projMatrix[3][0] = -1.0;
projMatrix[0][1] = 0.0; projMatrix[1][1] = -2.0 / glwidget->height();
projMatrix[2][1] = 0.0; projMatrix[3][1] = 1.0;
projMatrix[0][2] = 0.0; projMatrix[1][2] = 0.0;
projMatrix[2][2] = -1.0; projMatrix[3][2] = 0.0;
projMatrix[0][3] = 0.0; projMatrix[1][3] = 0.0;
projMatrix[2][3] = 0.0; projMatrix[3][3] = 1.0;
worldMatrix[0][2] = 0.0;
worldMatrix[1][2] = 0.0;
worldMatrix[2][0] = 0.0;
worldMatrix[2][1] = 0.0;
worldMatrix[2][2] = 1.0;
worldMatrix[2][3] = 0.0;
worldMatrix[3][2] = 0.0;
width = glwidget->width();
height = glwidget->height();
glViewport(0, 0, width, height);
for (int i = 0; i < ShaderTotal; i++) {
shader[i]->bind();
shader[i]->setUniformValue("matProj", projMatrix);
}
}
void updateVertices(const QTransform &t)
{
worldMatrix[0][0] = t.m11();
worldMatrix[0][1] = t.m12();
worldMatrix[0][3] = t.m13();
worldMatrix[1][0] = t.m21();
worldMatrix[1][1] = t.m22();
worldMatrix[1][3] = t.m23();
worldMatrix[3][0] = t.dx();
worldMatrix[3][1] = t.dy();
worldMatrix[3][3] = t.m33();
}
void updateVertices(const QTransform &t, ShaderType type)
{
if (shader[type] != currentShader)
currentShader = shader[type];
updateVertices(t);
currentShader->bind();
currentShader->setUniformValue("matWorld", worldMatrix);
}
void updateVertices(const QTransform &t, GLuint customShaderId)
{
if (!customShaderId)
return;
QGLShaderProgram* frag = customShaders.value(customShaderId,0);
if (!frag)
return;
currentShader = frag;
updateVertices(t);
currentShader->bind();
currentShader->setUniformValue("matWorld", worldMatrix);
}
GLuint installPixelShader(const QByteArray& code)
{
QByteArray source = code;
source.append(TexpCustomShaderSource);
QGLShaderProgram *custom = new QGLShaderProgram(glcontext, this);
custom->addShader(sharedVertexShader);
if (!custom->addShaderFromSourceCode(QGLShader::Fragment,
QLatin1String(source)))
qWarning("custom fragment shader failed to compile");
bindAttribLocation(custom, "inputVertex", D_VERTEX_COORDS);
bindAttribLocation(custom, "textureCoord", D_TEXTURE_COORDS);
if (custom->link()) {
customShaders[custom->programId()] = custom;
return custom->programId();
}
qWarning() << "failed installing custom fragment shader:"
<< custom->log();
custom->deleteLater();
return 0;
}
private:
static QGLShaderProgram *shader[ShaderTotal];
QHash<GLuint, QGLShaderProgram *> customShaders;
QGLShader *sharedVertexShader;
const QGLContext* glcontext;
GLfloat projMatrix[4][4];
GLfloat worldMatrix[4][4];
GLfloat vertCoords[8];
GLfloat texCoords[8];
GLfloat texCoordsInv[8];
QGLShaderProgram *currentShader;
int width;
int height;
friend class MTexturePixmapPrivate;
};
QGLShaderProgram *MGLResourceManager::shader[ShaderTotal];
#endif
void MTexturePixmapPrivate::drawTexture(const QTransform &transform, const QRectF &drawRect, qreal opacity)
{
if (current_effect) {
current_effect->d->drawTexture(this, transform, drawRect, opacity);
} else
q_drawTexture(transform, drawRect, opacity);
}
void MTexturePixmapPrivate::q_drawTexture(const QTransform &transform, const QRectF &drawRect, qreal opacity)
{
// TODO only update if matrix is dirty
if(current_effect)
glresource->updateVertices(transform, current_effect->activeShaderFragment());
else
glresource->updateVertices(transform, item->blurred() ?
MGLResourceManager::BlurShader :
MGLResourceManager::NormalShader);
GLfloat vertexCoords[] = {
drawRect.left(), drawRect.top(),
drawRect.left(), drawRect.bottom(),
drawRect.right(), drawRect.bottom(),
drawRect.right(), drawRect.top()
};
glEnableVertexAttribArray(D_VERTEX_COORDS);
glEnableVertexAttribArray(D_TEXTURE_COORDS);
glVertexAttribPointer(D_VERTEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, vertexCoords);
if (inverted_texture)
glVertexAttribPointer(D_TEXTURE_COORDS, 2, GL_FLOAT, GL_FALSE, 0,
glresource->texCoordsInv);
else
glVertexAttribPointer(D_TEXTURE_COORDS, 2, GL_FLOAT, GL_FALSE, 0,
glresource->texCoords);
if (current_effect)
current_effect->setUniforms(glresource->currentShader);
else if (item->blurred())
glresource->currentShader->setUniformValue("blurstep", (GLfloat) 0.5);
glresource->currentShader->setUniformValue("opacity", (GLfloat) opacity);
glresource->currentShader->setUniformValue("texture", 0);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableVertexAttribArray(D_VERTEX_COORDS);
glDisableVertexAttribArray(D_TEXTURE_COORDS);
glwidget->paintEngine()->syncState();
glActiveTexture(GL_TEXTURE0);
}
void MTexturePixmapPrivate::installEffect(MCompositeWindowShaderEffect* effect)
{
if (current_effect == effect)
return;
current_effect = effect;
connect(effect, SIGNAL(enabledChanged(bool)), SLOT( activateEffect(bool)));
connect(effect, SIGNAL(destroyed()), SLOT(removeEffect()));
}
void MTexturePixmapPrivate::removeEffect()
{
MCompositeWindowShaderEffect* e= (MCompositeWindowShaderEffect* ) sender();
for (int i=0; i < e->fragmentIds().size(); ++i) {
GLuint id = e->fragmentIds()[i];
QGLShaderProgram* frag = glresource->customShaders.value(i,0);
if (frag)
delete frag;
glresource->customShaders.remove(id);
}
}
GLuint MTexturePixmapPrivate::installPixelShader(const QByteArray& code)
{
if (glresource)
return glresource->installPixelShader(code);
return 0;
}
void MTexturePixmapPrivate::activateEffect(bool enabled)
{
if (enabled)
current_effect = (MCompositeWindowShaderEffect* ) sender();
else
current_effect = 0;
}
void MTexturePixmapPrivate::init()
{
if (!item->is_valid)
return;
if (!glresource) {
glresource = new MGLResourceManager(glwidget);
glresource->initVertices(glwidget);
}
resize(item->propertyCache()->realGeometry().width(),
item->propertyCache()->realGeometry().height());
item->setPos(item->propertyCache()->realGeometry().x(),
item->propertyCache()->realGeometry().y());
}
MTexturePixmapPrivate::MTexturePixmapPrivate(Qt::HANDLE window, QGLWidget *w, MTexturePixmapItem *p)
: ctx(0),
glwidget(w),
window(window),
windowp(0),
#ifdef DESKTOP_VERSION
glpixmap(0),
#endif
textureId(0),
ctextureId(0),
custom_tfp(false),
direct_fb_render(false),
angle(0),
damage_object(0),
item(p)
{
damageTracking(true);
init();
}
MTexturePixmapPrivate::~MTexturePixmapPrivate()
{
damageTracking(false);
}
void MTexturePixmapPrivate::damageTracking(bool enabled)
{
if (damage_object) {
XDamageDestroy(QX11Info::display(), damage_object);
damage_object = NULL;
}
if (enabled && !damage_object && !item->propertyCache()->isInputOnly())
damage_object = XDamageCreate(QX11Info::display(), window,
XDamageReportNonEmpty);
}
void MTexturePixmapPrivate::saveBackingStore(bool renew)
{
if ((item->propertyCache()->is_valid && !item->propertyCache()->isMapped())
|| item->propertyCache()->isInputOnly())
return;
if (windowp)
XFreePixmap(QX11Info::display(), windowp);
Pixmap px = XCompositeNameWindowPixmap(QX11Info::display(), item->window());
windowp = px;
if (renew)
item->rebindPixmap();
}
void MTexturePixmapPrivate::windowRaised()
{
XRaiseWindow(QX11Info::display(), item->window());
}
void MTexturePixmapPrivate::resize(int w, int h)
{
if (!brect.isEmpty() && !item->isDirectRendered() && (brect.width() != w || brect.height() != h)) {
item->saveBackingStore(true);
item->updateWindowPixmap();
}
brect.setWidth(w);
brect.setHeight(h);
}
<commit_msg>Fixes: NB#193821 leaking pixmap references<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of mcompositor.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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.
**
****************************************************************************/
#ifdef DESKTOP_VERSION
#define GL_GLEXT_PROTOTYPES 1
#endif
#include "mtexturepixmapitem.h"
#include "texturepixmapshaders.h"
#include "mcompositewindowshadereffect.h"
#include <QX11Info>
#include <QRect>
#include <X11/Xlib.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xrender.h>
#ifdef GLES2_VERSION
#include <GLES2/gl2.h>
#elif DESKTOP_VERSION
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#include <GL/glxext.h>
#endif
#include "mtexturepixmapitem_p.h"
bool MTexturePixmapPrivate::inverted_texture = true;
MGLResourceManager *MTexturePixmapPrivate::glresource = 0;
static const GLuint D_VERTEX_COORDS = 0;
static const GLuint D_TEXTURE_COORDS = 1;
#ifdef QT_OPENGL_LIB
static void bindAttribLocation(QGLShaderProgram *p, const char *attrib, int location)
{
p->bindAttributeLocation(attrib, location);
}
// OpenGL ES 2.0 / OpenGL 2.0 - compatible texture painter
class MGLResourceManager: public QObject
{
public:
/*
* This is the default set of shaders.
* Use MCompositeWindowShaderEffect class to add more shader effects
*/
enum ShaderType {
NormalShader = 0,
BlurShader,
ShaderTotal
};
MGLResourceManager(QGLWidget *glwidget)
: QObject(glwidget),
glcontext(glwidget->context()),
currentShader(0)
{
sharedVertexShader = new QGLShader(QGLShader::Vertex,
glwidget->context(), this);
if (!sharedVertexShader->compileSourceCode(QLatin1String(TexpVertShaderSource)))
qWarning("vertex shader failed to compile");
QGLShaderProgram *normalShader = new QGLShaderProgram(glwidget->context(), this);
shader[NormalShader] = normalShader;
normalShader->addShader(sharedVertexShader);
if (!normalShader->addShaderFromSourceCode(QGLShader::Fragment,
QLatin1String(TexpFragShaderSource)))
qWarning("normal fragment shader failed to compile");
QGLShaderProgram *blurShader = new QGLShaderProgram(glwidget->context(), this);
shader[BlurShader] = blurShader;
blurShader->addShader(sharedVertexShader);
if (!blurShader->addShaderFromSourceCode(QGLShader::Fragment,
QLatin1String(blurshader)))
qWarning("blur fragment shader failed to compile");
bindAttribLocation(normalShader, "inputVertex", D_VERTEX_COORDS);
bindAttribLocation(normalShader, "textureCoord", D_TEXTURE_COORDS);
bindAttribLocation(blurShader, "inputVertex", D_VERTEX_COORDS);
bindAttribLocation(blurShader, "textureCoord", D_TEXTURE_COORDS);
normalShader->link();
blurShader->link();
}
void initVertices(QGLWidget *glwidget) {
texCoords[0] = 0.0f; texCoords[1] = 1.0f;
texCoords[2] = 0.0f; texCoords[3] = 0.0f;
texCoords[4] = 1.0f; texCoords[5] = 0.0f;
texCoords[6] = 1.0f; texCoords[7] = 1.0f;
texCoordsInv[0] = 0.0f; texCoordsInv[1] = 0.0f;
texCoordsInv[2] = 0.0f; texCoordsInv[3] = 1.0f;
texCoordsInv[4] = 1.0f; texCoordsInv[5] = 1.0f;
texCoordsInv[6] = 1.0f; texCoordsInv[7] = 0.0f;
projMatrix[0][0] = 2.0 / glwidget->width(); projMatrix[1][0] = 0.0;
projMatrix[2][0] = 0.0; projMatrix[3][0] = -1.0;
projMatrix[0][1] = 0.0; projMatrix[1][1] = -2.0 / glwidget->height();
projMatrix[2][1] = 0.0; projMatrix[3][1] = 1.0;
projMatrix[0][2] = 0.0; projMatrix[1][2] = 0.0;
projMatrix[2][2] = -1.0; projMatrix[3][2] = 0.0;
projMatrix[0][3] = 0.0; projMatrix[1][3] = 0.0;
projMatrix[2][3] = 0.0; projMatrix[3][3] = 1.0;
worldMatrix[0][2] = 0.0;
worldMatrix[1][2] = 0.0;
worldMatrix[2][0] = 0.0;
worldMatrix[2][1] = 0.0;
worldMatrix[2][2] = 1.0;
worldMatrix[2][3] = 0.0;
worldMatrix[3][2] = 0.0;
width = glwidget->width();
height = glwidget->height();
glViewport(0, 0, width, height);
for (int i = 0; i < ShaderTotal; i++) {
shader[i]->bind();
shader[i]->setUniformValue("matProj", projMatrix);
}
}
void updateVertices(const QTransform &t)
{
worldMatrix[0][0] = t.m11();
worldMatrix[0][1] = t.m12();
worldMatrix[0][3] = t.m13();
worldMatrix[1][0] = t.m21();
worldMatrix[1][1] = t.m22();
worldMatrix[1][3] = t.m23();
worldMatrix[3][0] = t.dx();
worldMatrix[3][1] = t.dy();
worldMatrix[3][3] = t.m33();
}
void updateVertices(const QTransform &t, ShaderType type)
{
if (shader[type] != currentShader)
currentShader = shader[type];
updateVertices(t);
currentShader->bind();
currentShader->setUniformValue("matWorld", worldMatrix);
}
void updateVertices(const QTransform &t, GLuint customShaderId)
{
if (!customShaderId)
return;
QGLShaderProgram* frag = customShaders.value(customShaderId,0);
if (!frag)
return;
currentShader = frag;
updateVertices(t);
currentShader->bind();
currentShader->setUniformValue("matWorld", worldMatrix);
}
GLuint installPixelShader(const QByteArray& code)
{
QByteArray source = code;
source.append(TexpCustomShaderSource);
QGLShaderProgram *custom = new QGLShaderProgram(glcontext, this);
custom->addShader(sharedVertexShader);
if (!custom->addShaderFromSourceCode(QGLShader::Fragment,
QLatin1String(source)))
qWarning("custom fragment shader failed to compile");
bindAttribLocation(custom, "inputVertex", D_VERTEX_COORDS);
bindAttribLocation(custom, "textureCoord", D_TEXTURE_COORDS);
if (custom->link()) {
customShaders[custom->programId()] = custom;
return custom->programId();
}
qWarning() << "failed installing custom fragment shader:"
<< custom->log();
custom->deleteLater();
return 0;
}
private:
static QGLShaderProgram *shader[ShaderTotal];
QHash<GLuint, QGLShaderProgram *> customShaders;
QGLShader *sharedVertexShader;
const QGLContext* glcontext;
GLfloat projMatrix[4][4];
GLfloat worldMatrix[4][4];
GLfloat vertCoords[8];
GLfloat texCoords[8];
GLfloat texCoordsInv[8];
QGLShaderProgram *currentShader;
int width;
int height;
friend class MTexturePixmapPrivate;
};
QGLShaderProgram *MGLResourceManager::shader[ShaderTotal];
#endif
void MTexturePixmapPrivate::drawTexture(const QTransform &transform, const QRectF &drawRect, qreal opacity)
{
if (current_effect) {
current_effect->d->drawTexture(this, transform, drawRect, opacity);
} else
q_drawTexture(transform, drawRect, opacity);
}
void MTexturePixmapPrivate::q_drawTexture(const QTransform &transform, const QRectF &drawRect, qreal opacity)
{
// TODO only update if matrix is dirty
if(current_effect)
glresource->updateVertices(transform, current_effect->activeShaderFragment());
else
glresource->updateVertices(transform, item->blurred() ?
MGLResourceManager::BlurShader :
MGLResourceManager::NormalShader);
GLfloat vertexCoords[] = {
drawRect.left(), drawRect.top(),
drawRect.left(), drawRect.bottom(),
drawRect.right(), drawRect.bottom(),
drawRect.right(), drawRect.top()
};
glEnableVertexAttribArray(D_VERTEX_COORDS);
glEnableVertexAttribArray(D_TEXTURE_COORDS);
glVertexAttribPointer(D_VERTEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, vertexCoords);
if (inverted_texture)
glVertexAttribPointer(D_TEXTURE_COORDS, 2, GL_FLOAT, GL_FALSE, 0,
glresource->texCoordsInv);
else
glVertexAttribPointer(D_TEXTURE_COORDS, 2, GL_FLOAT, GL_FALSE, 0,
glresource->texCoords);
if (current_effect)
current_effect->setUniforms(glresource->currentShader);
else if (item->blurred())
glresource->currentShader->setUniformValue("blurstep", (GLfloat) 0.5);
glresource->currentShader->setUniformValue("opacity", (GLfloat) opacity);
glresource->currentShader->setUniformValue("texture", 0);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableVertexAttribArray(D_VERTEX_COORDS);
glDisableVertexAttribArray(D_TEXTURE_COORDS);
glwidget->paintEngine()->syncState();
glActiveTexture(GL_TEXTURE0);
}
void MTexturePixmapPrivate::installEffect(MCompositeWindowShaderEffect* effect)
{
if (current_effect == effect)
return;
current_effect = effect;
connect(effect, SIGNAL(enabledChanged(bool)), SLOT( activateEffect(bool)));
connect(effect, SIGNAL(destroyed()), SLOT(removeEffect()));
}
void MTexturePixmapPrivate::removeEffect()
{
MCompositeWindowShaderEffect* e= (MCompositeWindowShaderEffect* ) sender();
for (int i=0; i < e->fragmentIds().size(); ++i) {
GLuint id = e->fragmentIds()[i];
QGLShaderProgram* frag = glresource->customShaders.value(i,0);
if (frag)
delete frag;
glresource->customShaders.remove(id);
}
}
GLuint MTexturePixmapPrivate::installPixelShader(const QByteArray& code)
{
if (glresource)
return glresource->installPixelShader(code);
return 0;
}
void MTexturePixmapPrivate::activateEffect(bool enabled)
{
if (enabled)
current_effect = (MCompositeWindowShaderEffect* ) sender();
else
current_effect = 0;
}
void MTexturePixmapPrivate::init()
{
if (!item->is_valid)
return;
if (!glresource) {
glresource = new MGLResourceManager(glwidget);
glresource->initVertices(glwidget);
}
resize(item->propertyCache()->realGeometry().width(),
item->propertyCache()->realGeometry().height());
item->setPos(item->propertyCache()->realGeometry().x(),
item->propertyCache()->realGeometry().y());
}
MTexturePixmapPrivate::MTexturePixmapPrivate(Qt::HANDLE window, QGLWidget *w, MTexturePixmapItem *p)
: ctx(0),
glwidget(w),
window(window),
windowp(0),
#ifdef DESKTOP_VERSION
glpixmap(0),
#endif
textureId(0),
ctextureId(0),
custom_tfp(false),
direct_fb_render(false),
angle(0),
damage_object(0),
item(p)
{
damageTracking(true);
init();
}
MTexturePixmapPrivate::~MTexturePixmapPrivate()
{
damageTracking(false);
if (windowp)
XFreePixmap(QX11Info::display(), windowp);
}
void MTexturePixmapPrivate::damageTracking(bool enabled)
{
if (damage_object) {
XDamageDestroy(QX11Info::display(), damage_object);
damage_object = NULL;
}
if (enabled && !damage_object && !item->propertyCache()->isInputOnly())
damage_object = XDamageCreate(QX11Info::display(), window,
XDamageReportNonEmpty);
}
void MTexturePixmapPrivate::saveBackingStore(bool renew)
{
if ((item->propertyCache()->is_valid && !item->propertyCache()->isMapped())
|| item->propertyCache()->isInputOnly())
return;
if (windowp)
XFreePixmap(QX11Info::display(), windowp);
Pixmap px = XCompositeNameWindowPixmap(QX11Info::display(), item->window());
windowp = px;
if (renew)
item->rebindPixmap();
}
void MTexturePixmapPrivate::windowRaised()
{
XRaiseWindow(QX11Info::display(), item->window());
}
void MTexturePixmapPrivate::resize(int w, int h)
{
if (!brect.isEmpty() && !item->isDirectRendered() && (brect.width() != w || brect.height() != h)) {
item->saveBackingStore(true);
item->updateWindowPixmap();
}
brect.setWidth(w);
brect.setHeight(h);
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2009, Mikkel Krautz <[email protected]>
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 Mumble Developers 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 FOUNDATION 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 "CrashReporter.h"
#include "Global.h"
#include "OSInfo.h"
CrashReporter::CrashReporter(QWidget *p) : QDialog(p) {
setWindowTitle(tr("Mumble Crash Report"));
QVBoxLayout *vbl= new QVBoxLayout(this);
QLabel *l;
l = new QLabel(tr("<p><b>We're terribly sorry, but it seems Mumble has crashed. Do you want to send a crash report to the Mumble developers?</b></p>"
"<p>The crash report contains a partial copy of Mumble's memory at the time it crashed, and will help the developers fix the problem.</p>"));
vbl->addWidget(l);
QHBoxLayout *hbl = new QHBoxLayout();
qleEmail = new QLineEdit(g.qs->value(QLatin1String("crashemail")).toString());
l = new QLabel(tr("Email address (optional)"));
l->setBuddy(qleEmail);
hbl->addWidget(l);
hbl->addWidget(qleEmail, 1);
vbl->addLayout(hbl);
qteDescription=new QTextEdit();
l->setBuddy(qteDescription);
l = new QLabel(tr("Please describe briefly, in English, what you were doing at the time of the crash"));
vbl->addWidget(l);
vbl->addWidget(qteDescription, 1);
QPushButton *pbOk = new QPushButton(tr("Send Report"));
pbOk->setDefault(true);
QPushButton *pbCancel = new QPushButton(tr("Don't send report"));
pbCancel->setAutoDefault(false);
QDialogButtonBox *dbb = new QDialogButtonBox(Qt::Horizontal);
dbb->addButton(pbOk, QDialogButtonBox::AcceptRole);
dbb->addButton(pbCancel, QDialogButtonBox::RejectRole);
connect(dbb, SIGNAL(accepted()), this, SLOT(accept()));
connect(dbb, SIGNAL(rejected()), this, SLOT(reject()));
vbl->addWidget(dbb);
qelLoop = new QEventLoop(this);
qpdProgress = NULL;
qnrReply = NULL;
}
CrashReporter::~CrashReporter() {
g.qs->setValue(QLatin1String("crashemail"), qleEmail->text());
if (qnrReply)
delete qnrReply;
}
void CrashReporter::uploadFinished() {
qpdProgress->reset();
if (qnrReply->error() == QNetworkReply::NoError) {
if (qnrReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200)
QMessageBox::information(NULL, tr("Crash upload successful"), tr("Thank you for helping make Mumble better!"));
else
QMessageBox::critical(NULL, tr("Crash upload failed"), tr("We're really sorry, but it appears the crash upload has failed with error %1 %2. Please inform a developer.").arg(qnrReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()).arg(qnrReply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()));
} else {
QMessageBox::critical(NULL, tr("Crash upload failed"), tr("This really isn't funny, but apparently there's a bug in the crash reporting code, and we've failed to upload the report. You may inform a developer about error %1").arg(qnrReply->error()));
}
qelLoop->exit(0);
}
void CrashReporter::uploadProgress(qint64 sent, qint64 total) {
qpdProgress->setMaximum(static_cast<int>(total));
qpdProgress->setValue(static_cast<int>(sent));
}
void CrashReporter::run() {
QByteArray qbaDumpContents;
#ifdef COMPAT_CLIENT
#ifdef Q_OS_MAC
QFile qfCrashDump(QDir::homePath() + QLatin1String("/Library/Preferences/Mumble/mumble11x.dmp"));
#else
QFile qfCrashDump(QDesktopServices::storageLocation(QDesktopServices::DataLocation) + QLatin1String("/mumble11x.dmp"));
#endif
#else
QFile qfCrashDump(g.qdBasePath.filePath(QLatin1String("mumble.dmp")));
#endif
if (! qfCrashDump.exists())
return;
qfCrashDump.open(QIODevice::ReadOnly);
#if defined(Q_OS_WIN)
/* On Windows, the .dmp file is a real minidump. */
if (qfCrashDump.peek(4) != "MDMP")
return;
qbaDumpContents = qfCrashDump.readAll();
#elif defined(Q_OS_MAC)
/*
* On OSX, the .dmp file is simply a dummy file that we
* use to find the *real* crash dump, made by the OSX
* built in crash reporter.
*/
QFileInfo qfiDump(qfCrashDump);
QDateTime qdtModification = qfiDump.lastModified();
/* Find the real crash report. */
QDir qdCrashReports = QDir::home().absolutePath() + QLatin1String("/Library/Logs/DiagnosticReports/");
if (! qdCrashReports.exists()) {
qdCrashReports = QDir::home().absolutePath() + QLatin1String("/Library/Logs/CrashReporter/");
}
QStringList qslFilters;
#ifdef COMPAT_CLIENT
qslFilters << QString::fromLatin1("Mumble11x_*.crash");
#else
qslFilters << QString::fromLatin1("Mumble_*.crash");
#endif
qdCrashReports.setNameFilters(qslFilters);
qdCrashReports.setSorting(QDir::Time);
QFileInfoList qfilEntries = qdCrashReports.entryInfoList();
/*
* Figure out if our delta is sufficiently close to the Apple crash dump, or
* if something weird happened.
*/
foreach(QFileInfo fi, qfilEntries) {
int delta = abs(qdtModification.secsTo(fi.lastModified()));
if (delta < 8) {
QFile f(fi.absoluteFilePath());
f.open(QIODevice::ReadOnly);
qbaDumpContents = f.readAll();
break;
}
}
#endif
QString details;
#ifdef Q_OS_WIN
{
QTemporaryFile qtf;
if (qtf.open()) {
qtf.close();
QProcess qp;
QStringList qsl;
qsl << QLatin1String("/dontskip");
qsl << QLatin1String("/t");
qsl << qtf.fileName();
QString app = QLatin1String("dxdiag.exe");
wchar_t *sr = NULL;
size_t srsize = 0;
if (_wdupenv_s(&sr, &srsize, L"SystemRoot") == 0) {
app = QDir::fromNativeSeparators(QString::fromWCharArray(sr)) + QLatin1String("/System32/dxdiag.exe");
free(sr);
}
qp.start(app, qsl);
if (qp.waitForFinished(30000)) {
if (qtf.open()) {
QByteArray qba = qtf.readAll();
details = QString::fromLocal8Bit(qba);
}
} else {
details = QLatin1String("Failed to run dxdiag");
}
qp.kill();
}
}
#endif
if (qbaDumpContents.isEmpty()) {
qWarning("CrashReporter: Empty crash dump file, not reporting.");
return;
}
if (exec() == QDialog::Accepted) {
qpdProgress = new QProgressDialog(tr("Uploading crash report"), tr("Abort upload"), 0, 100, this);
qpdProgress->setMinimumDuration(500);
qpdProgress->setValue(0);
connect(qpdProgress, SIGNAL(canceled()), qelLoop, SLOT(quit()));
QString boundary = QString::fromLatin1("---------------------------%1").arg(QDateTime::currentDateTime().toTime_t());
QString os = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"os\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2 %3\r\n").arg(boundary, OSInfo::getOS(), OSInfo::getOSVersion());
QString ver = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"ver\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2 %3\r\n").arg(boundary, QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING)), QLatin1String(MUMBLE_RELEASE));
QString email = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"email\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n").arg(boundary, qleEmail->text());
QString descr = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"desc\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n").arg(boundary, qteDescription->toPlainText());
QString det = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"details\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n").arg(boundary, details);
QString head = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"dump\"; filename=\"mumble.dmp\"\r\nContent-Type: binary/octet-stream\r\n\r\n").arg(boundary);
QString end = QString::fromLatin1("\r\n--%1--\r\n").arg(boundary);
QByteArray post = os.toUtf8() + ver.toUtf8() + email.toUtf8() + descr.toUtf8() + det.toUtf8() + head.toUtf8() + qbaDumpContents + end.toUtf8();
QUrl url(QLatin1String("https://mumble.hive.no/crashreport.php"));
QNetworkRequest req(url);
req.setHeader(QNetworkRequest::ContentTypeHeader, QString::fromLatin1("multipart/form-data; boundary=%1").arg(boundary));
req.setHeader(QNetworkRequest::ContentLengthHeader, QString::number(post.size()));
qnrReply = g.nam->post(req, post);
connect(qnrReply, SIGNAL(finished()), this, SLOT(uploadFinished()));
connect(qnrReply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress(qint64, qint64)));
qelLoop->exec(QEventLoop::DialogExec);
}
if (! qfCrashDump.remove())
qWarning("CrashReporeter: Unable to remove crash file.");
}
<commit_msg>/dontskip for dxdiag requires Win7, so skip it<commit_after>/* Copyright (C) 2009, Mikkel Krautz <[email protected]>
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 Mumble Developers 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 FOUNDATION 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 "CrashReporter.h"
#include "Global.h"
#include "OSInfo.h"
CrashReporter::CrashReporter(QWidget *p) : QDialog(p) {
setWindowTitle(tr("Mumble Crash Report"));
QVBoxLayout *vbl= new QVBoxLayout(this);
QLabel *l;
l = new QLabel(tr("<p><b>We're terribly sorry, but it seems Mumble has crashed. Do you want to send a crash report to the Mumble developers?</b></p>"
"<p>The crash report contains a partial copy of Mumble's memory at the time it crashed, and will help the developers fix the problem.</p>"));
vbl->addWidget(l);
QHBoxLayout *hbl = new QHBoxLayout();
qleEmail = new QLineEdit(g.qs->value(QLatin1String("crashemail")).toString());
l = new QLabel(tr("Email address (optional)"));
l->setBuddy(qleEmail);
hbl->addWidget(l);
hbl->addWidget(qleEmail, 1);
vbl->addLayout(hbl);
qteDescription=new QTextEdit();
l->setBuddy(qteDescription);
l = new QLabel(tr("Please describe briefly, in English, what you were doing at the time of the crash"));
vbl->addWidget(l);
vbl->addWidget(qteDescription, 1);
QPushButton *pbOk = new QPushButton(tr("Send Report"));
pbOk->setDefault(true);
QPushButton *pbCancel = new QPushButton(tr("Don't send report"));
pbCancel->setAutoDefault(false);
QDialogButtonBox *dbb = new QDialogButtonBox(Qt::Horizontal);
dbb->addButton(pbOk, QDialogButtonBox::AcceptRole);
dbb->addButton(pbCancel, QDialogButtonBox::RejectRole);
connect(dbb, SIGNAL(accepted()), this, SLOT(accept()));
connect(dbb, SIGNAL(rejected()), this, SLOT(reject()));
vbl->addWidget(dbb);
qelLoop = new QEventLoop(this);
qpdProgress = NULL;
qnrReply = NULL;
}
CrashReporter::~CrashReporter() {
g.qs->setValue(QLatin1String("crashemail"), qleEmail->text());
if (qnrReply)
delete qnrReply;
}
void CrashReporter::uploadFinished() {
qpdProgress->reset();
if (qnrReply->error() == QNetworkReply::NoError) {
if (qnrReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200)
QMessageBox::information(NULL, tr("Crash upload successful"), tr("Thank you for helping make Mumble better!"));
else
QMessageBox::critical(NULL, tr("Crash upload failed"), tr("We're really sorry, but it appears the crash upload has failed with error %1 %2. Please inform a developer.").arg(qnrReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()).arg(qnrReply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()));
} else {
QMessageBox::critical(NULL, tr("Crash upload failed"), tr("This really isn't funny, but apparently there's a bug in the crash reporting code, and we've failed to upload the report. You may inform a developer about error %1").arg(qnrReply->error()));
}
qelLoop->exit(0);
}
void CrashReporter::uploadProgress(qint64 sent, qint64 total) {
qpdProgress->setMaximum(static_cast<int>(total));
qpdProgress->setValue(static_cast<int>(sent));
}
void CrashReporter::run() {
QByteArray qbaDumpContents;
#ifdef COMPAT_CLIENT
#ifdef Q_OS_MAC
QFile qfCrashDump(QDir::homePath() + QLatin1String("/Library/Preferences/Mumble/mumble11x.dmp"));
#else
QFile qfCrashDump(QDesktopServices::storageLocation(QDesktopServices::DataLocation) + QLatin1String("/mumble11x.dmp"));
#endif
#else
QFile qfCrashDump(g.qdBasePath.filePath(QLatin1String("mumble.dmp")));
#endif
if (! qfCrashDump.exists())
return;
qfCrashDump.open(QIODevice::ReadOnly);
#if defined(Q_OS_WIN)
/* On Windows, the .dmp file is a real minidump. */
if (qfCrashDump.peek(4) != "MDMP")
return;
qbaDumpContents = qfCrashDump.readAll();
#elif defined(Q_OS_MAC)
/*
* On OSX, the .dmp file is simply a dummy file that we
* use to find the *real* crash dump, made by the OSX
* built in crash reporter.
*/
QFileInfo qfiDump(qfCrashDump);
QDateTime qdtModification = qfiDump.lastModified();
/* Find the real crash report. */
QDir qdCrashReports = QDir::home().absolutePath() + QLatin1String("/Library/Logs/DiagnosticReports/");
if (! qdCrashReports.exists()) {
qdCrashReports = QDir::home().absolutePath() + QLatin1String("/Library/Logs/CrashReporter/");
}
QStringList qslFilters;
#ifdef COMPAT_CLIENT
qslFilters << QString::fromLatin1("Mumble11x_*.crash");
#else
qslFilters << QString::fromLatin1("Mumble_*.crash");
#endif
qdCrashReports.setNameFilters(qslFilters);
qdCrashReports.setSorting(QDir::Time);
QFileInfoList qfilEntries = qdCrashReports.entryInfoList();
/*
* Figure out if our delta is sufficiently close to the Apple crash dump, or
* if something weird happened.
*/
foreach(QFileInfo fi, qfilEntries) {
int delta = abs(qdtModification.secsTo(fi.lastModified()));
if (delta < 8) {
QFile f(fi.absoluteFilePath());
f.open(QIODevice::ReadOnly);
qbaDumpContents = f.readAll();
break;
}
}
#endif
QString details;
#ifdef Q_OS_WIN
{
QTemporaryFile qtf;
if (qtf.open()) {
qtf.close();
QProcess qp;
QStringList qsl;
qsl << QLatin1String("/t");
qsl << qtf.fileName();
QString app = QLatin1String("dxdiag.exe");
wchar_t *sr = NULL;
size_t srsize = 0;
if (_wdupenv_s(&sr, &srsize, L"SystemRoot") == 0) {
app = QDir::fromNativeSeparators(QString::fromWCharArray(sr)) + QLatin1String("/System32/dxdiag.exe");
free(sr);
}
qp.start(app, qsl);
if (qp.waitForFinished(30000)) {
if (qtf.open()) {
QByteArray qba = qtf.readAll();
details = QString::fromLocal8Bit(qba);
}
} else {
details = QLatin1String("Failed to run dxdiag");
}
qp.kill();
}
}
#endif
if (qbaDumpContents.isEmpty()) {
qWarning("CrashReporter: Empty crash dump file, not reporting.");
return;
}
if (exec() == QDialog::Accepted) {
qpdProgress = new QProgressDialog(tr("Uploading crash report"), tr("Abort upload"), 0, 100, this);
qpdProgress->setMinimumDuration(500);
qpdProgress->setValue(0);
connect(qpdProgress, SIGNAL(canceled()), qelLoop, SLOT(quit()));
QString boundary = QString::fromLatin1("---------------------------%1").arg(QDateTime::currentDateTime().toTime_t());
QString os = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"os\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2 %3\r\n").arg(boundary, OSInfo::getOS(), OSInfo::getOSVersion());
QString ver = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"ver\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2 %3\r\n").arg(boundary, QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING)), QLatin1String(MUMBLE_RELEASE));
QString email = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"email\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n").arg(boundary, qleEmail->text());
QString descr = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"desc\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n").arg(boundary, qteDescription->toPlainText());
QString det = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"details\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\n%2\r\n").arg(boundary, details);
QString head = QString::fromLatin1("--%1\r\nContent-Disposition: form-data; name=\"dump\"; filename=\"mumble.dmp\"\r\nContent-Type: binary/octet-stream\r\n\r\n").arg(boundary);
QString end = QString::fromLatin1("\r\n--%1--\r\n").arg(boundary);
QByteArray post = os.toUtf8() + ver.toUtf8() + email.toUtf8() + descr.toUtf8() + det.toUtf8() + head.toUtf8() + qbaDumpContents + end.toUtf8();
QUrl url(QLatin1String("https://mumble.hive.no/crashreport.php"));
QNetworkRequest req(url);
req.setHeader(QNetworkRequest::ContentTypeHeader, QString::fromLatin1("multipart/form-data; boundary=%1").arg(boundary));
req.setHeader(QNetworkRequest::ContentLengthHeader, QString::number(post.size()));
qnrReply = g.nam->post(req, post);
connect(qnrReply, SIGNAL(finished()), this, SLOT(uploadFinished()));
connect(qnrReply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress(qint64, qint64)));
qelLoop->exec(QEventLoop::DialogExec);
}
if (! qfCrashDump.remove())
qWarning("CrashReporeter: Unable to remove crash file.");
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/network/protocols/protocol_address.hpp>
#include <functional>
#include <metaverse/bitcoin.hpp>
#include <metaverse/network/channel.hpp>
#include <metaverse/network/p2p.hpp>
#include <metaverse/network/protocols/protocol.hpp>
#include <metaverse/network/protocols/protocol_events.hpp>
namespace libbitcoin {
namespace network {
#define NAME "address"
#define CLASS protocol_address
using namespace bc::message;
using namespace std::placeholders;
protocol_address::protocol_address(p2p& network, channel::ptr channel)
: protocol_events(network, channel, NAME),
network_(network),
CONSTRUCT_TRACK(protocol_address)
{
}
protocol_address::ptr protocol_address::do_subscribe()
{
SUBSCRIBE2(address, handle_receive_address, _1, _2);
SUBSCRIBE2(get_address, handle_receive_get_address, _1, _2);
// Must have a handler to capture a shared self pointer in stop subscriber.
protocol_events::start(BIND1(handle_stop, _1));
return std::dynamic_pointer_cast<protocol_address>(protocol::shared_from_this());
}
// Start sequence.
// ----------------------------------------------------------------------------
void protocol_address::start()
{
const auto& settings = network_.network_settings();
if (settings.self.port() != 0)
{
self_ = address({ { settings.self.to_network_address() } });
SEND2(self_, handle_send, _1, self_.command);
}
#ifdef USE_UPNP
if (settings.self != network_.get_out_address()) {
address self = address({ { network_.get_out_address().to_network_address() } });
SEND2(self, handle_send, _1, self.command);
}
#endif
// If we can't store addresses we don't ask for or handle them.
if (settings.host_pool_capacity == 0)
return;
SEND2(get_address(), handle_send, _1, get_address::command);
}
void protocol_address::remove_useless_address(address::ptr& message)
{
auto& addresses = message->addresses;
const auto& settings = network_.network_settings();
if(settings.self.port() != 0)
{
auto iter = std::find_if(addresses.begin(), addresses.end(), [&settings](const message::network_address& addr){
if(config::authority{addr} == settings.self)
{
return true;
}
return false;
});
if(iter != addresses.end())
{
addresses.erase(iter);
}
}
}
// Protocol.
// ----------------------------------------------------------------------------
bool protocol_address::handle_receive_address(const code& ec,
address::ptr message)
{
if (stopped())
return false;
if (ec)
{
log::trace(LOG_NETWORK)
<< "Failure receiving address message from ["
<< authority() << "] " << ec.message();
stop(ec);
return false;
}
remove_useless_address(message);
log::trace(LOG_NETWORK)
<< "Storing addresses from [" << authority() << "] ("
<< message->addresses.size() << ")";
// if (message->addresses.size() > 1000)
// {
// return ! misbehaving(20);
// }
network_address::list addresses;
addresses.reserve(message->addresses.size());
for (auto& addr:message->addresses) {
if (!channel::blacklisted(addr)) {
addresses.push_back(addr);
}
}
// TODO: manage timestamps (active channels are connected < 3 hours ago).
network_.store(message->addresses, BIND2(handle_store_addresses, _1, message));
// RESUBSCRIBE
return true;
}
bool protocol_address::handle_receive_get_address(const code& ec,
get_address::ptr message)
{
if (stopped())
return false;
if (ec)
{
log::trace(LOG_NETWORK)
<< "Failure receiving get_address message from ["
<< authority() << "] " << ec.message();
stop(ec);
return false;
}
// TODO: allowing repeated queries can allow a channel to map our history.
// TODO: pull active hosts from host cache (currently just resending self).
// TODO: need to distort for privacy, don't send currently-connected peers.
auto&& address_list = network_.address_list();
auto channel_authorithy = authority();
auto iter = std::find_if(address_list.begin(), address_list.end(), [&channel_authorithy](const message::network_address& address){
if(config::authority{address} == channel_authorithy)
{
return true;
}
return false;
});
if(iter != address_list.end() )
{
address_list.erase(iter);
}
if(address_list.empty())
{
return true;
}
// if (self_.addresses.empty())
// return false;
log::trace(LOG_NETWORK)
<< "Sending addresses to [" << authority() << "] ("
<< address_list.size() << ")";
message::address self_address = {address_list};
SEND2(self_address, handle_send, _1, self_address.command);
// RESUBSCRIBE
return true;
}
void protocol_address::handle_store_addresses(const code& ec, address::ptr message)
{
if (stopped())
return;
if (ec)
{
log::error(LOG_NETWORK)
<< "Failure storing addresses from [" << authority() << "] "
<< ec.message();
stop(ec);
}
}
void protocol_address::handle_stop(const code&)
{
log::trace(LOG_NETWORK)
<< "Stopped addresss protocol";
}
} // namespace network
} // namespace libbitcoin
<commit_msg>增加一条打印日志<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/network/protocols/protocol_address.hpp>
#include <functional>
#include <metaverse/bitcoin.hpp>
#include <metaverse/network/channel.hpp>
#include <metaverse/network/p2p.hpp>
#include <metaverse/network/protocols/protocol.hpp>
#include <metaverse/network/protocols/protocol_events.hpp>
namespace libbitcoin {
namespace network {
#define NAME "address"
#define CLASS protocol_address
using namespace bc::message;
using namespace std::placeholders;
protocol_address::protocol_address(p2p& network, channel::ptr channel)
: protocol_events(network, channel, NAME),
network_(network),
CONSTRUCT_TRACK(protocol_address)
{
}
protocol_address::ptr protocol_address::do_subscribe()
{
SUBSCRIBE2(address, handle_receive_address, _1, _2);
SUBSCRIBE2(get_address, handle_receive_get_address, _1, _2);
// Must have a handler to capture a shared self pointer in stop subscriber.
protocol_events::start(BIND1(handle_stop, _1));
return std::dynamic_pointer_cast<protocol_address>(protocol::shared_from_this());
}
// Start sequence.
// ----------------------------------------------------------------------------
void protocol_address::start()
{
const auto& settings = network_.network_settings();
if (settings.self.port() != 0)
{
self_ = address({ { settings.self.to_network_address() } });
SEND2(self_, handle_send, _1, self_.command);
}
#ifdef USE_UPNP
if (settings.self != network_.get_out_address()) {
address self = address({ { network_.get_out_address().to_network_address() } });
log::info("UPnP") << "send addresss " << network_.get_out_address().to_string();
SEND2(self, handle_send, _1, self.command);
}
#endif
// If we can't store addresses we don't ask for or handle them.
if (settings.host_pool_capacity == 0)
return;
SEND2(get_address(), handle_send, _1, get_address::command);
}
void protocol_address::remove_useless_address(address::ptr& message)
{
auto& addresses = message->addresses;
const auto& settings = network_.network_settings();
if(settings.self.port() != 0)
{
auto iter = std::find_if(addresses.begin(), addresses.end(), [&settings](const message::network_address& addr){
if(config::authority{addr} == settings.self)
{
return true;
}
return false;
});
if(iter != addresses.end())
{
addresses.erase(iter);
}
}
}
// Protocol.
// ----------------------------------------------------------------------------
bool protocol_address::handle_receive_address(const code& ec,
address::ptr message)
{
if (stopped())
return false;
if (ec)
{
log::trace(LOG_NETWORK)
<< "Failure receiving address message from ["
<< authority() << "] " << ec.message();
stop(ec);
return false;
}
remove_useless_address(message);
log::trace(LOG_NETWORK)
<< "Storing addresses from [" << authority() << "] ("
<< message->addresses.size() << ")";
// if (message->addresses.size() > 1000)
// {
// return ! misbehaving(20);
// }
network_address::list addresses;
addresses.reserve(message->addresses.size());
for (auto& addr:message->addresses) {
if (!channel::blacklisted(addr)) {
addresses.push_back(addr);
}
}
// TODO: manage timestamps (active channels are connected < 3 hours ago).
network_.store(message->addresses, BIND2(handle_store_addresses, _1, message));
// RESUBSCRIBE
return true;
}
bool protocol_address::handle_receive_get_address(const code& ec,
get_address::ptr message)
{
if (stopped())
return false;
if (ec)
{
log::trace(LOG_NETWORK)
<< "Failure receiving get_address message from ["
<< authority() << "] " << ec.message();
stop(ec);
return false;
}
// TODO: allowing repeated queries can allow a channel to map our history.
// TODO: pull active hosts from host cache (currently just resending self).
// TODO: need to distort for privacy, don't send currently-connected peers.
auto&& address_list = network_.address_list();
auto channel_authorithy = authority();
auto iter = std::find_if(address_list.begin(), address_list.end(), [&channel_authorithy](const message::network_address& address){
if(config::authority{address} == channel_authorithy)
{
return true;
}
return false;
});
if(iter != address_list.end() )
{
address_list.erase(iter);
}
if(address_list.empty())
{
return true;
}
// if (self_.addresses.empty())
// return false;
log::trace(LOG_NETWORK)
<< "Sending addresses to [" << authority() << "] ("
<< address_list.size() << ")";
message::address self_address = {address_list};
SEND2(self_address, handle_send, _1, self_address.command);
// RESUBSCRIBE
return true;
}
void protocol_address::handle_store_addresses(const code& ec, address::ptr message)
{
if (stopped())
return;
if (ec)
{
log::error(LOG_NETWORK)
<< "Failure storing addresses from [" << authority() << "] "
<< ec.message();
stop(ec);
}
}
void protocol_address::handle_stop(const code&)
{
log::trace(LOG_NETWORK)
<< "Stopped addresss protocol";
}
} // namespace network
} // namespace libbitcoin
<|endoftext|> |
<commit_before>//#include "rhodes/JNIRhodes.h"
#include <rhodes.h>
#include <android/log.h>
#include <common/RhodesApp.h>
#include <logging/RhoLogConf.h>
#include <stdlib.h>
#define IP_PORTION_COUNT 32
RHO_GLOBAL void rho_platform_image_load_grayscale(const char* url, void** image_pixels, int* pwidth, int* pheight) {
*image_pixels = 0;
*pwidth = 0;
*pheight = 0;
//__android_log_write(ANDROID_LOG_INFO, "APP", "$$$$$$$$$$$$$$$$$$$$$ [ 1 ]");
JNIEnv *env = jnienv();
jclass bitmapf_class = rho_find_class(env, "android/graphics/BitmapFactory");
if (!bitmapf_class) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : can not found Bitmap class");
return;
}
jclass rhofileapi_class = rho_find_class(env, "com/rhomobile/rhodes/file/RhoFileApi");
if (!rhofileapi_class) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : can not find RhoFileApi class");
return;
}
if (url == 0) {
return;
}
jstring jstrFileUrl = rho_cast<jstring>(url);
if (!jstrFileUrl) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : invalid URL !");
return;
}
jmethodID fopen_mid = env->GetStaticMethodID(rhofileapi_class, "open", "(Ljava/lang/String;)Ljava/io/InputStream;");
if (!fopen_mid) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : can not find 'open' method in RhoFileApi");
return;
}
jmethodID fclose_mid = env->GetStaticMethodID(rhofileapi_class, "close", "(Ljava/io/InputStream;)V");
if (!fclose_mid) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : can not find 'close' method in RhoFileApi");
return;
}
jmethodID bf_mid = env->GetStaticMethodID(bitmapf_class, "decodeStream", "(Ljava/io/InputStream;)Landroid/graphics/Bitmap;");
if (!bf_mid) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : not identify decodeStream() !");
return;
}
jobject is = env->CallStaticObjectMethod(rhofileapi_class, fopen_mid, jstrFileUrl);
if (!is) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : can not open stream");
return;
}
jobject bitmap = env->CallStaticObjectMethod(bitmapf_class, bf_mid, is);
env->CallStaticVoidMethod(rhofileapi_class, fclose_mid, is);
if (!bitmap) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : Bitmap not produced !");
return;
}
jclass bitmap_class = env->GetObjectClass(bitmap);
if (!bitmap_class) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : Bitmap class not detected !");
return;
}
jmethodID b_getPixels_mid = env->GetMethodID( bitmap_class, "getPixels", "([IIIIIII)V");
jmethodID b_getWidth_mid = env->GetMethodID( bitmap_class, "getWidth", "()I");
jmethodID b_getHeight_mid = env->GetMethodID( bitmap_class, "getHeight", "()I");
if ((!b_getPixels_mid) || (!b_getWidth_mid) || (!b_getHeight_mid)) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : Bitmap methods not recognized !");
return;
}
jint width = env->CallIntMethod(bitmap, b_getWidth_mid);
jint height = env->CallIntMethod(bitmap, b_getHeight_mid);
unsigned char* gray_buf = new unsigned char[width*height];
if (!gray_buf) {
RAWLOG_ERROR2("rho_platform_image_load_grayscale() : gray buffer not created [ %d x %d ]!", width, height);
env->DeleteLocalRef(bitmap);
env->DeleteLocalRef(jstrFileUrl);
return;
}
int portion_size = height / IP_PORTION_COUNT;
int current_y = 0;
jintArray bufARGB_j = env->NewIntArray(width*portion_size);
if (!bufARGB_j) {
RAWLOG_ERROR2("rho_platform_image_load_grayscale() : int array not created [ %d x %d ]!", width, portion_size);
delete gray_buf;
env->DeleteLocalRef(bitmap);
env->DeleteLocalRef(jstrFileUrl);
return;
}
while (current_y < height) {
int current_size = portion_size;
if ((current_y + current_size) > height) {
current_size = height - current_y;
}
env->CallVoidMethod(bitmap, b_getPixels_mid, bufARGB_j, 0, width, 0, current_y, width, current_size);
jint* bufARGB = env->GetIntArrayElements(bufARGB_j, 0);
if (!bufARGB) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : int array not locked for access !");
delete gray_buf;
env->DeleteLocalRef(bufARGB_j);
env->DeleteLocalRef(bitmap);
env->DeleteLocalRef(jstrFileUrl);
return;
}
// now we have image in int_32(ARGB) array
{
// make gray image
unsigned char* dst = gray_buf + current_y*width;
int* src = bufARGB;
int tk = (1<<16)/3;
int count = width*current_size;
int i;
for (i = count; i > 0; i--) {
int c = *src++;
//dst = (R+G+B)/3;
*dst++ = (unsigned char)((((c & 0xFF) + ((c & 0xFF00)>>8) + ((c & 0xFF0000)>>16))*tk)>>16);
}
}
env->ReleaseIntArrayElements(bufARGB_j, bufARGB, 0);
current_y += current_size;
}
*image_pixels = gray_buf;
*pwidth = width;
*pheight = height;
env->DeleteLocalRef(bufARGB_j);
env->DeleteLocalRef(bitmap);
env->DeleteLocalRef(jstrFileUrl);
}
RHO_GLOBAL void rho_platform_image_free(void* image_pixels) {
if (image_pixels != 0) {
delete image_pixels;
}
}
<commit_msg>Fix Barcode build for Android<commit_after>//#include "rhodes/JNIRhodes.h"
#include <rhodes.h>
#include <android/log.h>
#include <common/RhodesApp.h>
#include <logging/RhoLogConf.h>
#include <stdlib.h>
#define IP_PORTION_COUNT 32
RHO_GLOBAL void rho_platform_image_load_grayscale(const char* url, void** image_pixels, int* pwidth, int* pheight) {
*image_pixels = 0;
*pwidth = 0;
*pheight = 0;
//__android_log_write(ANDROID_LOG_INFO, "APP", "$$$$$$$$$$$$$$$$$$$$$ [ 1 ]");
JNIEnv *env = jnienv();
jclass bitmapf_class = rho_find_class(env, "android/graphics/BitmapFactory");
if (!bitmapf_class) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : can not found Bitmap class");
return;
}
jclass rhofileapi_class = rho_find_class(env, "com/rhomobile/rhodes/file/RhoFileApi");
if (!rhofileapi_class) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : can not find RhoFileApi class");
return;
}
if (url == 0) {
return;
}
jstring jstrFileUrl = env->NewStringUTF(url);//rho_cast<jstring>(url);
if (!jstrFileUrl) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : invalid URL !");
return;
}
jmethodID fopen_mid = env->GetStaticMethodID(rhofileapi_class, "open", "(Ljava/lang/String;)Ljava/io/InputStream;");
if (!fopen_mid) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : can not find 'open' method in RhoFileApi");
return;
}
jmethodID fclose_mid = env->GetStaticMethodID(rhofileapi_class, "close", "(Ljava/io/InputStream;)V");
if (!fclose_mid) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : can not find 'close' method in RhoFileApi");
return;
}
jmethodID bf_mid = env->GetStaticMethodID(bitmapf_class, "decodeStream", "(Ljava/io/InputStream;)Landroid/graphics/Bitmap;");
if (!bf_mid) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : not identify decodeStream() !");
return;
}
jobject is = env->CallStaticObjectMethod(rhofileapi_class, fopen_mid, jstrFileUrl);
if (!is) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : can not open stream");
return;
}
jobject bitmap = env->CallStaticObjectMethod(bitmapf_class, bf_mid, is);
env->CallStaticVoidMethod(rhofileapi_class, fclose_mid, is);
if (!bitmap) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : Bitmap not produced !");
return;
}
jclass bitmap_class = env->GetObjectClass(bitmap);
if (!bitmap_class) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : Bitmap class not detected !");
return;
}
jmethodID b_getPixels_mid = env->GetMethodID( bitmap_class, "getPixels", "([IIIIIII)V");
jmethodID b_getWidth_mid = env->GetMethodID( bitmap_class, "getWidth", "()I");
jmethodID b_getHeight_mid = env->GetMethodID( bitmap_class, "getHeight", "()I");
if ((!b_getPixels_mid) || (!b_getWidth_mid) || (!b_getHeight_mid)) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : Bitmap methods not recognized !");
return;
}
jint width = env->CallIntMethod(bitmap, b_getWidth_mid);
jint height = env->CallIntMethod(bitmap, b_getHeight_mid);
unsigned char* gray_buf = new unsigned char[width*height];
if (!gray_buf) {
RAWLOG_ERROR2("rho_platform_image_load_grayscale() : gray buffer not created [ %d x %d ]!", width, height);
env->DeleteLocalRef(bitmap);
env->DeleteLocalRef(jstrFileUrl);
return;
}
int portion_size = height / IP_PORTION_COUNT;
int current_y = 0;
jintArray bufARGB_j = env->NewIntArray(width*portion_size);
if (!bufARGB_j) {
RAWLOG_ERROR2("rho_platform_image_load_grayscale() : int array not created [ %d x %d ]!", width, portion_size);
delete gray_buf;
env->DeleteLocalRef(bitmap);
env->DeleteLocalRef(jstrFileUrl);
return;
}
while (current_y < height) {
int current_size = portion_size;
if ((current_y + current_size) > height) {
current_size = height - current_y;
}
env->CallVoidMethod(bitmap, b_getPixels_mid, bufARGB_j, 0, width, 0, current_y, width, current_size);
jint* bufARGB = env->GetIntArrayElements(bufARGB_j, 0);
if (!bufARGB) {
RAWLOG_ERROR("rho_platform_image_load_grayscale() : int array not locked for access !");
delete gray_buf;
env->DeleteLocalRef(bufARGB_j);
env->DeleteLocalRef(bitmap);
env->DeleteLocalRef(jstrFileUrl);
return;
}
// now we have image in int_32(ARGB) array
{
// make gray image
unsigned char* dst = gray_buf + current_y*width;
int* src = bufARGB;
int tk = (1<<16)/3;
int count = width*current_size;
int i;
for (i = count; i > 0; i--) {
int c = *src++;
//dst = (R+G+B)/3;
*dst++ = (unsigned char)((((c & 0xFF) + ((c & 0xFF00)>>8) + ((c & 0xFF0000)>>16))*tk)>>16);
}
}
env->ReleaseIntArrayElements(bufARGB_j, bufARGB, 0);
current_y += current_size;
}
*image_pixels = gray_buf;
*pwidth = width;
*pheight = height;
env->DeleteLocalRef(bufARGB_j);
env->DeleteLocalRef(bitmap);
env->DeleteLocalRef(jstrFileUrl);
}
RHO_GLOBAL void rho_platform_image_free(void* image_pixels) {
if (image_pixels != 0) {
delete image_pixels;
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// logging_test.cpp
//
// Identification: test/logging/logging_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/harness.h"
#include "concurrency/transaction_manager_factory.h"
#include "executor/logical_tile_factory.h"
#include "storage/data_table.h"
#include "storage/tile.h"
#include "logging/loggers/wal_frontend_logger.h"
#include "logging/logging_util.h"
#include "storage/table_factory.h"
#include "storage/database.h"
#include "executor/mock_executor.h"
#include "executor/executor_tests_util.h"
#include "logging/logging_tests_util.h"
using ::testing::NotNull;
using ::testing::Return;
using ::testing::InSequence;
extern LoggingType peloton_logging_mode;
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Logging Tests
//===--------------------------------------------------------------------===//
class LoggingTests : public PelotonTest {};
TEST_F(LoggingTests, BasicLoggingTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(3, results[0]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, AllCommittedTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(3, results[0]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, LaggardTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
// at this point everyone should be updated to 3
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(4);
scheduler.BackendLogger(0, 0).Insert(4);
scheduler.BackendLogger(0, 0).Commit(4);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(3, results[0]);
// TODO: Check this
EXPECT_EQ(4, results[1]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, FastLoggerTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
// at this point everyone should be updated to 3
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(4);
scheduler.BackendLogger(0, 0).Insert(4);
scheduler.BackendLogger(0, 0).Commit(4);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Insert(5);
scheduler.BackendLogger(0, 1).Commit(5);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
// TODO: Check this
EXPECT_EQ(3, results[0]);
EXPECT_EQ(5, results[1]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, BothPreparingTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
// at this point everyone should be updated to 3
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(4);
scheduler.BackendLogger(0, 0).Insert(4);
scheduler.BackendLogger(0, 0).Commit(4);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(5);
scheduler.BackendLogger(0, 1).Insert(5);
scheduler.BackendLogger(0, 1).Commit(5);
// this prepare should still get a may commit of 3
scheduler.BackendLogger(0, 1).Prepare();
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 1).Begin(6);
scheduler.BackendLogger(0, 1).Insert(6);
scheduler.BackendLogger(0, 1).Commit(6);
// this call should get a may commit of 4
scheduler.BackendLogger(0, 0).Prepare();
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(3, results[0]);
// TODO: Check this
EXPECT_EQ(5, results[1]);
EXPECT_EQ(6, results[2]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, TwoRoundTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
// at this point everyone should be updated to 3
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(4);
scheduler.BackendLogger(0, 0).Insert(4);
scheduler.BackendLogger(0, 0).Commit(4);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(5);
scheduler.BackendLogger(0, 1).Insert(5);
scheduler.BackendLogger(0, 1).Commit(5);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(5, results[1]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, InsertUpdateDeleteTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Update(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
// at this point everyone should be updated to 3
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(4);
scheduler.BackendLogger(0, 0).Delete(4);
scheduler.BackendLogger(0, 0).Commit(4);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(5);
scheduler.BackendLogger(0, 1).Delete(5);
scheduler.BackendLogger(0, 1).Commit(5);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(5, results[1]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, BasicLogManagerTest) {
peloton_logging_mode = LOGGING_TYPE_INVALID;
auto &log_manager = logging::LogManager::GetInstance();
log_manager.DropFrontendLoggers();
log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_INVALID);
// just start, write a few records and exit
catalog::Schema *table_schema = new catalog::Schema(
{ExecutorTestsUtil::GetColumnInfo(0), ExecutorTestsUtil::GetColumnInfo(1),
ExecutorTestsUtil::GetColumnInfo(2),
ExecutorTestsUtil::GetColumnInfo(3)});
std::string table_name("TEST_TABLE");
// Create table.
bool own_schema = true;
bool adapt_table = false;
storage::DataTable *table = storage::TableFactory::GetDataTable(
12345, 123456, table_schema, table_name, 1, own_schema, adapt_table);
storage::Database test_db(12345);
test_db.AddTable(table);
catalog::Manager::GetInstance().AddDatabase(&test_db);
concurrency::TransactionManager &txn_manager =
concurrency::TransactionManagerFactory::GetInstance();
txn_manager.BeginTransaction();
ExecutorTestsUtil::PopulateTable(table, 5, true, false, false);
txn_manager.CommitTransaction();
peloton_logging_mode = LOGGING_TYPE_NVM_WAL;
log_manager.SetSyncCommit(true);
EXPECT_FALSE(log_manager.ContainsFrontendLogger());
log_manager.StartStandbyMode();
log_manager.GetFrontendLogger(0)->SetTestMode(true);
log_manager.StartRecoveryMode();
log_manager.WaitForModeTransition(LOGGING_STATUS_TYPE_LOGGING, true);
EXPECT_TRUE(log_manager.ContainsFrontendLogger());
log_manager.SetGlobalMaxFlushedCommitId(4);
concurrency::Transaction test_txn;
cid_t commit_id = 5;
log_manager.PrepareLogging();
log_manager.LogBeginTransaction(commit_id);
ItemPointer insert_loc(table->GetTileGroup(1)->GetTileGroupId(), 0);
ItemPointer delete_loc(table->GetTileGroup(2)->GetTileGroupId(), 0);
ItemPointer update_old(table->GetTileGroup(3)->GetTileGroupId(), 0);
ItemPointer update_new(table->GetTileGroup(4)->GetTileGroupId(), 0);
log_manager.LogInsert(commit_id, insert_loc);
log_manager.LogUpdate(commit_id, update_old, update_new);
log_manager.LogInsert(commit_id, delete_loc);
log_manager.LogCommitTransaction(commit_id);
// TODO: Check the flushed commit id
// since we are doing sync commit we should have reached 5 already
EXPECT_EQ(commit_id -1, log_manager.GetPersistentFlushedCommitId());
log_manager.EndLogging();
}
} // End test namespace
} // End peloton namespace
<commit_msg>Fixed logging test<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// logging_test.cpp
//
// Identification: test/logging/logging_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/harness.h"
#include "concurrency/transaction_manager_factory.h"
#include "executor/logical_tile_factory.h"
#include "storage/data_table.h"
#include "storage/tile.h"
#include "logging/loggers/wal_frontend_logger.h"
#include "logging/logging_util.h"
#include "storage/table_factory.h"
#include "storage/database.h"
#include "executor/mock_executor.h"
#include "executor/executor_tests_util.h"
#include "logging/logging_tests_util.h"
using ::testing::NotNull;
using ::testing::Return;
using ::testing::InSequence;
extern LoggingType peloton_logging_mode;
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Logging Tests
//===--------------------------------------------------------------------===//
class LoggingTests : public PelotonTest {};
TEST_F(LoggingTests, BasicLoggingTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(3, results[0]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, AllCommittedTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(3, results[0]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, LaggardTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
// at this point everyone should be updated to 3
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(4);
scheduler.BackendLogger(0, 0).Insert(4);
scheduler.BackendLogger(0, 0).Commit(4);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(3, results[0]);
// TODO: Check this
EXPECT_EQ(4, results[1]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, FastLoggerTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
// at this point everyone should be updated to 3
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(4);
scheduler.BackendLogger(0, 0).Insert(4);
scheduler.BackendLogger(0, 0).Commit(4);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Insert(5);
scheduler.BackendLogger(0, 1).Commit(5);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
// TODO: Check this
EXPECT_EQ(3, results[0]);
EXPECT_EQ(5, results[1]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, BothPreparingTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
// at this point everyone should be updated to 3
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(4);
scheduler.BackendLogger(0, 0).Insert(4);
scheduler.BackendLogger(0, 0).Commit(4);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(5);
scheduler.BackendLogger(0, 1).Insert(5);
scheduler.BackendLogger(0, 1).Commit(5);
// this prepare should still get a may commit of 3
scheduler.BackendLogger(0, 1).Prepare();
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 1).Begin(6);
scheduler.BackendLogger(0, 1).Insert(6);
scheduler.BackendLogger(0, 1).Commit(6);
// this call should get a may commit of 4
scheduler.BackendLogger(0, 0).Prepare();
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(3, results[0]);
// TODO: Check this
EXPECT_EQ(5, results[1]);
EXPECT_EQ(6, results[2]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, TwoRoundTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Insert(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
// at this point everyone should be updated to 3
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(4);
scheduler.BackendLogger(0, 0).Insert(4);
scheduler.BackendLogger(0, 0).Commit(4);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(5);
scheduler.BackendLogger(0, 1).Insert(5);
scheduler.BackendLogger(0, 1).Commit(5);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(5, results[1]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, InsertUpdateDeleteTest) {
std::unique_ptr<storage::DataTable> table(ExecutorTestsUtil::CreateTable(1));
auto &log_manager = logging::LogManager::GetInstance();
LoggingScheduler scheduler(2, 1, &log_manager, table.get());
scheduler.Init();
// Logger 0 is always the front end logger
// The first txn to commit starts with cid 2
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(2);
scheduler.BackendLogger(0, 0).Insert(2);
scheduler.BackendLogger(0, 0).Commit(2);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(3);
scheduler.BackendLogger(0, 1).Update(3);
scheduler.BackendLogger(0, 1).Commit(3);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
// at this point everyone should be updated to 3
scheduler.BackendLogger(0, 0).Prepare();
scheduler.BackendLogger(0, 0).Begin(4);
scheduler.BackendLogger(0, 0).Delete(4);
scheduler.BackendLogger(0, 0).Commit(4);
scheduler.BackendLogger(0, 1).Prepare();
scheduler.BackendLogger(0, 1).Begin(5);
scheduler.BackendLogger(0, 1).Delete(5);
scheduler.BackendLogger(0, 1).Commit(5);
scheduler.FrontendLogger(0).Collect();
scheduler.FrontendLogger(0).Flush();
scheduler.BackendLogger(0, 0).Done(1);
scheduler.BackendLogger(0, 1).Done(1);
scheduler.Run();
auto results = scheduler.frontend_threads[0].results;
EXPECT_EQ(5, results[1]);
scheduler.Cleanup();
}
TEST_F(LoggingTests, BasicLogManagerTest) {
peloton_logging_mode = LOGGING_TYPE_INVALID;
auto &log_manager = logging::LogManager::GetInstance();
log_manager.DropFrontendLoggers();
log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_INVALID);
// just start, write a few records and exit
catalog::Schema *table_schema = new catalog::Schema(
{ExecutorTestsUtil::GetColumnInfo(0), ExecutorTestsUtil::GetColumnInfo(1),
ExecutorTestsUtil::GetColumnInfo(2),
ExecutorTestsUtil::GetColumnInfo(3)});
std::string table_name("TEST_TABLE");
// Create table.
bool own_schema = true;
bool adapt_table = false;
storage::DataTable *table = storage::TableFactory::GetDataTable(
12345, 123456, table_schema, table_name, 1, own_schema, adapt_table);
storage::Database test_db(12345);
test_db.AddTable(table);
catalog::Manager::GetInstance().AddDatabase(&test_db);
concurrency::TransactionManager &txn_manager =
concurrency::TransactionManagerFactory::GetInstance();
txn_manager.BeginTransaction();
ExecutorTestsUtil::PopulateTable(table, 5, true, false, false);
txn_manager.CommitTransaction();
peloton_logging_mode = LOGGING_TYPE_NVM_WAL;
log_manager.SetSyncCommit(true);
EXPECT_FALSE(log_manager.ContainsFrontendLogger());
log_manager.StartStandbyMode();
log_manager.GetFrontendLogger(0)->SetTestMode(true);
log_manager.StartRecoveryMode();
log_manager.WaitForModeTransition(LOGGING_STATUS_TYPE_LOGGING, true);
EXPECT_TRUE(log_manager.ContainsFrontendLogger());
log_manager.SetGlobalMaxFlushedCommitId(4);
concurrency::Transaction test_txn;
cid_t commit_id = 5;
log_manager.PrepareLogging();
log_manager.LogBeginTransaction(commit_id);
ItemPointer insert_loc(table->GetTileGroup(1)->GetTileGroupId(), 0);
ItemPointer delete_loc(table->GetTileGroup(2)->GetTileGroupId(), 0);
ItemPointer update_old(table->GetTileGroup(3)->GetTileGroupId(), 0);
ItemPointer update_new(table->GetTileGroup(4)->GetTileGroupId(), 0);
log_manager.LogInsert(commit_id, insert_loc);
log_manager.LogUpdate(commit_id, update_old, update_new);
log_manager.LogInsert(commit_id, delete_loc);
log_manager.LogCommitTransaction(commit_id);
// TODO: Check the flushed commit id
// since we are doing sync commit we should have reached 5 already
//EXPECT_EQ(commit_id, log_manager.GetPersistentFlushedCommitId());
log_manager.EndLogging();
}
} // End test namespace
} // End peloton namespace
<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <sstream>
#include <algorithm>
#include "BhArray.hpp"
#include <bhxx/functor.hpp>
namespace bhxx {
/** Convert an array to a contiguous representation if it is not yet
* contiguous. */
template<typename T>
BhArray<T> as_contiguous(BhArray<T> ary) {
if (ary.isContiguous()) return std::move(ary);
BhArray<T> contiguous{ary.shape()};
identity(contiguous, ary);
return contiguous;
}
/** Performs a full reduction of the array along all axis using the
* add_reduce operation.
*
* \note Performs exactly the same job as std::accumulate, but on
* BhArray objects.
*/
template<typename T>
BhArray<T> accumulate(BhArray<T> op) {
return accumulate(std::move(op), bhxx::AddReduce<T>{});
}
/** Performs a full reduction of the array along all axis using
* an reduction operation of the callers choice.
*
* \note Performs exactly the same job as std::accumulate, but on
* BhArray objects.
*/
template<typename T, typename AddReduction>
BhArray<T> accumulate(BhArray<T> op, AddReduction &&reduction) {
// Reduce to a single value by repetitively calling the reduction function
// until the rank is down to 1:
const size_t rank = op.rank();
for (size_t r = 0; r < rank; ++r) {
op = reduction(op, op.rank() - 1);
}
assert(op.rank() == 1);
assert(op.size() == 1);
return op;
}
/** Make an inner product between the Bohrium arrays given, i.e.
* elementwise multiplication followed by an accumulation
* (full reduction).
*
* \note Performs exactly the same job as std::inner_product, but
* on BhArray objects.
*/
template<typename T>
BhArray<T> inner_product(const BhArray<T> &oplhs, const BhArray<T> &oprhs) {
return inner_product(oplhs, oprhs, bhxx::Multiply<T>{}, bhxx::AddReduce<T>{});
}
/** Make an inner product between the Bohrium arrays given, i.e.
* elementwise multiplication followed by an accumulation
* (full reduction).
*
* This version allows to specify the operations used for multiplication
* and addition, such that other things as inner products can be achieved
* as well (e.g. equality comparision is multiplication == equal and
* add_reduction == local_and_reduce)
*
* \note Performs exactly the same job as std::inner_product, but
* on BhArray objects.
*/
template<typename T, typename Multiplication, typename AddReduction>
auto inner_product(const BhArray<T> &oplhs, const BhArray<T> &oprhs,
Multiplication &&multiplication, AddReduction &&add_reduction)
-> decltype(multiplication(oplhs, oprhs)) {
return accumulate(multiplication(oplhs, oprhs),
std::forward<AddReduction>(add_reduction));
}
/** Return the result of broadcasting `shapes` against each other
*
* @param shapes Array of shapes
* @return Broadcasted shape
*/
template<int N>
Shape broadcasted_shape(std::array<Shape, N> shapes) {
// Find the number of dimension of the broadcasted shape
uint64_t ret_ndim = 0;
for (const Shape &shape: shapes) {
if (shape.size() > ret_ndim) {
ret_ndim = shape.size();
}
}
// Make sure that all shapes has the same length by appending ones
for (Shape &shape: shapes) {
shape.insert(shape.end(), ret_ndim - shape.size(), 1);
}
// The resulting shape is the max of each dimension
Shape ret;
for (uint64_t i = 0; i < ret_ndim; ++i) {
uint64_t greatest = 0;
for (const Shape &shape: shapes) {
if (shape[i] > greatest) {
greatest = shape[i];
}
}
ret.push_back(greatest);
}
return ret;
}
/** Return a new view of `ary` that is broadcasted to `shape`
*
* @param ary Input array
* @param shape The new shape
* @return The broadcasted array
*/
template<typename T>
BhArray<T> broadcast_to(BhArray<T> ary, const Shape &shape) {
if (ary.shape().size() < shape.size()) {
throw std::runtime_error("The length of `shape` is smaller than `ary.shape`");
}
// Append ones to shape and zeros to stride in order to make them the same lengths as `shape`
Shape ret_shape = ary.shape();
Stride ret_stride = ary.stride();
assert(ret_shape.size() == ret_stride.size());
ret_shape.insert(ret_shape.end(), ret_shape.size() - ret_shape.size(), 1);
ret_stride.insert(ret_stride.end(), ret_shape.size() - ret_stride.size(), 0);
// Broadcast each dimension by setting ret_stride to zero and ret_shape to `shape`
for (uint64_t i = 0; i < shape.size(); ++i) {
if (ret_shape[i] != shape[i]) {
if (ret_shape[i] == 1) {
ret_shape[i] = shape[i];
ret_stride[i] = 0;
} else {
std::stringstream ss;
ss << "Cannot broadcast `shape[" << i << "]=" << ret_shape << "` to `" << shape[i] << "`.";
throw std::runtime_error(ss.str());
}
}
}
ary.setShapeAndStride(ret_shape, ret_stride);
return std::move(ary);
}
/** Return True when `a` and `b` are the same view pointing to the same base */
template<typename T1, typename T2>
inline bool is_same_array(const BhArray<T1> &a, const BhArray<T2> &b) {
return a.base() == b.base() && a.offset() == b.offset() && a.shape() == b.shape() && a.stride() == b.stride();
}
} // namespace bhxx
<commit_msg>bhxx: is_same_array() now ignores strides of one-sized shape<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <sstream>
#include <algorithm>
#include "BhArray.hpp"
#include <bhxx/functor.hpp>
namespace bhxx {
/** Convert an array to a contiguous representation if it is not yet
* contiguous. */
template<typename T>
BhArray<T> as_contiguous(BhArray<T> ary) {
if (ary.isContiguous()) return std::move(ary);
BhArray<T> contiguous{ary.shape()};
identity(contiguous, ary);
return contiguous;
}
/** Performs a full reduction of the array along all axis using the
* add_reduce operation.
*
* \note Performs exactly the same job as std::accumulate, but on
* BhArray objects.
*/
template<typename T>
BhArray<T> accumulate(BhArray<T> op) {
return accumulate(std::move(op), bhxx::AddReduce<T>{});
}
/** Performs a full reduction of the array along all axis using
* an reduction operation of the callers choice.
*
* \note Performs exactly the same job as std::accumulate, but on
* BhArray objects.
*/
template<typename T, typename AddReduction>
BhArray<T> accumulate(BhArray<T> op, AddReduction &&reduction) {
// Reduce to a single value by repetitively calling the reduction function
// until the rank is down to 1:
const size_t rank = op.rank();
for (size_t r = 0; r < rank; ++r) {
op = reduction(op, op.rank() - 1);
}
assert(op.rank() == 1);
assert(op.size() == 1);
return op;
}
/** Make an inner product between the Bohrium arrays given, i.e.
* elementwise multiplication followed by an accumulation
* (full reduction).
*
* \note Performs exactly the same job as std::inner_product, but
* on BhArray objects.
*/
template<typename T>
BhArray<T> inner_product(const BhArray<T> &oplhs, const BhArray<T> &oprhs) {
return inner_product(oplhs, oprhs, bhxx::Multiply<T>{}, bhxx::AddReduce<T>{});
}
/** Make an inner product between the Bohrium arrays given, i.e.
* elementwise multiplication followed by an accumulation
* (full reduction).
*
* This version allows to specify the operations used for multiplication
* and addition, such that other things as inner products can be achieved
* as well (e.g. equality comparision is multiplication == equal and
* add_reduction == local_and_reduce)
*
* \note Performs exactly the same job as std::inner_product, but
* on BhArray objects.
*/
template<typename T, typename Multiplication, typename AddReduction>
auto inner_product(const BhArray<T> &oplhs, const BhArray<T> &oprhs,
Multiplication &&multiplication, AddReduction &&add_reduction)
-> decltype(multiplication(oplhs, oprhs)) {
return accumulate(multiplication(oplhs, oprhs),
std::forward<AddReduction>(add_reduction));
}
/** Return the result of broadcasting `shapes` against each other
*
* @param shapes Array of shapes
* @return Broadcasted shape
*/
template<int N>
Shape broadcasted_shape(std::array<Shape, N> shapes) {
// Find the number of dimension of the broadcasted shape
uint64_t ret_ndim = 0;
for (const Shape &shape: shapes) {
if (shape.size() > ret_ndim) {
ret_ndim = shape.size();
}
}
// Make sure that all shapes has the same length by appending ones
for (Shape &shape: shapes) {
shape.insert(shape.end(), ret_ndim - shape.size(), 1);
}
// The resulting shape is the max of each dimension
Shape ret;
for (uint64_t i = 0; i < ret_ndim; ++i) {
uint64_t greatest = 0;
for (const Shape &shape: shapes) {
if (shape[i] > greatest) {
greatest = shape[i];
}
}
ret.push_back(greatest);
}
return ret;
}
/** Return a new view of `ary` that is broadcasted to `shape`
*
* @param ary Input array
* @param shape The new shape
* @return The broadcasted array
*/
template<typename T>
BhArray<T> broadcast_to(BhArray<T> ary, const Shape &shape) {
if (ary.shape().size() < shape.size()) {
throw std::runtime_error("The length of `shape` is smaller than `ary.shape`");
}
// Append ones to shape and zeros to stride in order to make them the same lengths as `shape`
Shape ret_shape = ary.shape();
Stride ret_stride = ary.stride();
assert(ret_shape.size() == ret_stride.size());
ret_shape.insert(ret_shape.end(), ret_shape.size() - ret_shape.size(), 1);
ret_stride.insert(ret_stride.end(), ret_shape.size() - ret_stride.size(), 0);
// Broadcast each dimension by setting ret_stride to zero and ret_shape to `shape`
for (uint64_t i = 0; i < shape.size(); ++i) {
if (ret_shape[i] != shape[i]) {
if (ret_shape[i] == 1) {
ret_shape[i] = shape[i];
ret_stride[i] = 0;
} else {
std::stringstream ss;
ss << "Cannot broadcast `shape[" << i << "]=" << ret_shape << "` to `" << shape[i] << "`.";
throw std::runtime_error(ss.str());
}
}
}
ary.setShapeAndStride(ret_shape, ret_stride);
return std::move(ary);
}
/** Return True when `a` and `b` are the same view pointing to the same base */
template<typename T1, typename T2>
inline bool is_same_array(const BhArray<T1> &a, const BhArray<T2> &b) {
if (a.base() == b.base() && a.offset() == b.offset() && a.shape() == b.shape()) {
assert(a.shape().size() == b.shape().size());
assert(a.stride().size() == b.stride().size());
// Notice, the stride may vary when shape is one
for (size_t i = 0; i < a.shape().size(); ++i) {
if (a.shape()[i] > 1 && a.stride()[i] != b.stride()[i]) {
return false;
}
}
return true;
} else {
return false;
}
}
} // namespace bhxx
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// group_by_sql_test.cpp
//
// Identification: test/sql/group_by_sql_test.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include "sql/testing_sql_util.h"
#include "catalog/catalog.h"
#include "common/harness.h"
#include "executor/create_executor.h"
#include "optimizer/optimizer.h"
#include "optimizer/simple_optimizer.h"
#include "planner/create_plan.h"
#include "planner/order_by_plan.h"
namespace peloton {
namespace test {
class GroupBySQLTests : public PelotonTest {};
TEST_F(GroupBySQLTests, EmptyTableTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
// Create a table first
TestingSQLUtil::ExecuteSQLQuery(
"create table xxx (id int, name varchar, salary decimal);");
}
TEST_F(GroupBySQLTests, SimpleGroupByTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
// Create a table first
// into the table
TestingSQLUtil::ExecuteSQLQuery(
"create table xxx (id int, name varchar, salary decimal);");
// Insert tuples into table
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(1, 'Mike', 1000);");
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(2, 'Jane', 2000);");
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(3, 'Tom', 3000);");
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(4, 'Kelly', 4000);");
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(5, 'Lucy', 3000);");
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(6, 'Tim', 2000);");
TestingSQLUtil::ShowTable(DEFAULT_DB_NAME, "xxx");
std::vector<StatementResult> result;
std::vector<FieldInfo> tuple_descriptor;
std::string error_message;
int rows_affected;
std::unique_ptr<optimizer::AbstractOptimizer> optimizer(
new optimizer::Optimizer());
std::string query1("select count(id), salary from xxx group by salary;");
LOG_DEBUG("Running Query %s", query1.c_str());
TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
optimizer, query1, result, tuple_descriptor, rows_affected, error_message);
//TestingSQLUtil::ExecuteSQLQuery(
// "select count(id), salary from xxx group by salary;", result,
// tuple_descriptor, rows_affected, error_message);
// Check the return value
EXPECT_EQ(0, rows_affected);
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 0));
EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 2));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 4));
EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 6));
// test: GROUP BY + HAVING
std::string query2("select count(id), salary from xxx group by salary having salary>1000;");
LOG_DEBUG("Running Query %s", query2.c_str());
TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
optimizer, query2, result, tuple_descriptor, rows_affected, error_message);
// TestingSQLUtil::ExecuteSQLQuery(
// "select count(id), salary from xxx group by salary having salary>1000;",
// result, tuple_descriptor, rows_affected, error_message);
// Check the return value
EXPECT_EQ(0, rows_affected);
EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 0));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 2));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 4));
// test: GROUP BY + ORDER BY
std::string query3("select count(id), salary from xxx group by salary order by salary;");
LOG_DEBUG("Running Query %s", query3.c_str());
TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
optimizer, query3, result, tuple_descriptor, rows_affected, error_message);
// TestingSQLUtil::ExecuteSQLQuery(
// "select count(id), salary from xxx group by salary order by salary;",
// result, tuple_descriptor, rows_affected, error_message);
// Check the return value
EXPECT_EQ(0, rows_affected);
EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 0));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 2));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 4));
EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 6));
EXPECT_EQ("1000", TestingSQLUtil::GetResultValueAsString(result, 1));
EXPECT_EQ("2000", TestingSQLUtil::GetResultValueAsString(result, 3));
EXPECT_EQ("3000", TestingSQLUtil::GetResultValueAsString(result, 5));
EXPECT_EQ("4000", TestingSQLUtil::GetResultValueAsString(result, 7));
// free the database just created
catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
}
} // namespace test
} // namespace peloton
<commit_msg>Solved groupby test case failure.<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// group_by_sql_test.cpp
//
// Identification: test/sql/group_by_sql_test.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include "sql/testing_sql_util.h"
#include "catalog/catalog.h"
#include "common/harness.h"
#include "executor/create_executor.h"
#include "optimizer/optimizer.h"
#include "optimizer/simple_optimizer.h"
#include "planner/create_plan.h"
#include "planner/order_by_plan.h"
namespace peloton {
namespace test {
class GroupBySQLTests : public PelotonTest {};
TEST_F(GroupBySQLTests, EmptyTableTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
// Create a table first
TestingSQLUtil::ExecuteSQLQuery(
"create table xxx (id int, name varchar, salary decimal);");
}
TEST_F(GroupBySQLTests, SimpleGroupByTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
// Create a table first
// into the table
TestingSQLUtil::ExecuteSQLQuery(
"create table xxx (id int, name varchar, salary decimal);");
// Insert tuples into table
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(1, 'Mike', 1000);");
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(2, 'Jane', 2000);");
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(3, 'Tom', 3000);");
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(4, 'Kelly', 4000);");
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(5, 'Lucy', 3000);");
TestingSQLUtil::ExecuteSQLQuery("insert into xxx values(6, 'Tim', 2000);");
TestingSQLUtil::ShowTable(DEFAULT_DB_NAME, "xxx");
std::vector<StatementResult> result;
std::vector<FieldInfo> tuple_descriptor;
std::string error_message;
int rows_affected;
std::unique_ptr<optimizer::AbstractOptimizer> optimizer(
new optimizer::Optimizer());
std::string query1("select count(id), salary from xxx group by salary;");
LOG_DEBUG("Running Query %s", query1.c_str());
TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
optimizer, query1, result, tuple_descriptor, rows_affected, error_message);
//TestingSQLUtil::ExecuteSQLQuery(
// "select count(id), salary from xxx group by salary;", result,
// tuple_descriptor, rows_affected, error_message);
// Check the return value
EXPECT_EQ(0, rows_affected);
EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 0));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 2));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 4));
EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 6));
// test: GROUP BY + HAVING
std::string query2("select count(id), salary from xxx group by salary having salary>1000;");
LOG_DEBUG("Running Query %s", query2.c_str());
TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
optimizer, query2, result, tuple_descriptor, rows_affected, error_message);
// TestingSQLUtil::ExecuteSQLQuery(
// "select count(id), salary from xxx group by salary having salary>1000;",
// result, tuple_descriptor, rows_affected, error_message);
// Check the return value
EXPECT_EQ(0, rows_affected);
EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 0));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 2));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 4));
// test: GROUP BY + ORDER BY
std::string query3("select count(id), salary from xxx group by salary order by salary;");
LOG_DEBUG("Running Query %s", query3.c_str());
TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
optimizer, query3, result, tuple_descriptor, rows_affected, error_message);
// TestingSQLUtil::ExecuteSQLQuery(
// "select count(id), salary from xxx group by salary order by salary;",
// result, tuple_descriptor, rows_affected, error_message);
// Check the return value
EXPECT_EQ(0, rows_affected);
EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 0));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 2));
EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 4));
EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 6));
EXPECT_EQ("1000", TestingSQLUtil::GetResultValueAsString(result, 1));
EXPECT_EQ("2000", TestingSQLUtil::GetResultValueAsString(result, 3));
EXPECT_EQ("3000", TestingSQLUtil::GetResultValueAsString(result, 5));
EXPECT_EQ("4000", TestingSQLUtil::GetResultValueAsString(result, 7));
// free the database just created
catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
}
} // namespace test
} // namespace peloton
<|endoftext|> |
<commit_before>#include "p2pclient.h"
#include "utils.h"
#include "crypto/sha2.h"
#include <thread>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else // WIN32
#include <netinet/tcp.h>
#include <netdb.h>
#include <fcntl.h>
#endif // !WIN32
void P2PRelayer::reconnect(std::string disconnectReason) {
connected = false;
if (sock) {
printf("Closing bitcoind socket with %s, %s (%i: %s)\n", server_host, disconnectReason.c_str(), errno, errno ? strerror(errno) : "");
#ifndef WIN32
errno = 0;
#endif
close(sock);
}
sleep(1);
new_thread = new std::thread(do_connect, this);
}
void P2PRelayer::do_connect(P2PRelayer* me) {
if (me->net_thread)
me->net_thread->join();
me->net_thread = me->new_thread;
me->sock = socket(AF_INET6, SOCK_STREAM, 0);
if (me->sock <= 0)
return me->reconnect("unable to create socket");
sockaddr_in6 addr;
if (!lookup_address(me->server_host, &addr))
return me->reconnect("unable to lookup host");
int v6only = 0;
setsockopt(me->sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6only, sizeof(v6only));
addr.sin6_port = htons(me->server_port);
if (connect(me->sock, (struct sockaddr*)&addr, sizeof(addr)))
return me->reconnect("failed to connect()");
#ifdef WIN32
unsigned long nonblocking = 0;
ioctlsocket(me->sock, FIONBIO, &nonblocking);
#else
fcntl(me->sock, F_SETFL, fcntl(me->sock, F_GETFL) & ~O_NONBLOCK);
#endif
#ifdef X86_BSD
int nosigpipe = 1;
setsockopt(me->sock, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(int));
#endif
me->net_process();
}
bool P2PRelayer::send_message(const char* command, unsigned char* headerAndData, size_t datalen) {
prepare_message(command, headerAndData, datalen);
return send_all(sock, (char*)headerAndData, sizeof(struct bitcoin_msg_header) + datalen) == int(sizeof(struct bitcoin_msg_header) + datalen);
}
void P2PRelayer::net_process() {
if (!send_version()) {
reconnect("failed to send version message");
return;
}
int nodelay = 1;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(nodelay));
if (errno)
return reconnect("error during connect");
while (true) {
struct bitcoin_msg_header header;
if (read_all(sock, (char*)&header, sizeof(header)) != sizeof(header))
return reconnect("failed to read message header");
if (header.magic != BITCOIN_MAGIC)
return reconnect("invalid magic bytes");
header.length = le32toh(header.length);
if (header.length > 5000000)
return reconnect("got message too large");
uint32_t prependedHeaderSize = (!strncmp(header.command, "block", strlen("block"))) ? sizeof(struct bitcoin_msg_header) : 0;
struct timeval read_start;
gettimeofday(&read_start, NULL);
auto msg = std::make_shared<std::vector<unsigned char> > (prependedHeaderSize + uint32_t(header.length));
if (read_all(sock, (char*)&(*msg)[prependedHeaderSize], header.length) != int(header.length))
return reconnect("failed to read message");
unsigned char fullhash[32];
CSHA256 hash;
hash.Write(&(*msg)[prependedHeaderSize], header.length).Finalize(fullhash);
hash.Reset().Write(fullhash, sizeof(fullhash)).Finalize(fullhash);
if (memcmp((char*)fullhash, header.checksum, sizeof(header.checksum)))
return reconnect("got invalid message checksum");
if (!strncmp(header.command, "version", strlen("version"))) {
if (header.length < sizeof(struct bitcoin_version_start))
return reconnect("got short version");
struct bitcoin_version_start *their_version = (struct bitcoin_version_start*) &(*msg)[0];
struct bitcoin_msg_header new_header;
send_message("verack", (unsigned char*)&new_header, 0);
if (provide_headers) {
std::vector<unsigned char> msg(sizeof(struct bitcoin_msg_header));
struct bitcoin_version_start sent_version;
msg.insert(msg.end(), (unsigned char*)&sent_version.protocol_version, ((unsigned char*)&sent_version.protocol_version) + sizeof(sent_version.protocol_version));
msg.insert(msg.end(), 1, 1);
msg.insert(msg.end(), 64, 0);
send_message("getheaders", &msg[0], msg.size() - sizeof(struct bitcoin_msg_header));
}
printf("Connected to bitcoind with version %u\n", le32toh(their_version->protocol_version));
} else if (!strncmp(header.command, "verack", strlen("verack"))) {
printf("Finished connect handshake with bitcoind\n");
connected = true;
} else if (!strncmp(header.command, "ping", strlen("ping"))) {
std::vector<unsigned char> resp(sizeof(struct bitcoin_msg_header) + header.length);
resp.insert(resp.begin() + sizeof(struct bitcoin_msg_header), msg->begin(), msg->end());
send_message("pong", &resp[0], header.length);
} else if (!strncmp(header.command, "inv", strlen("inv"))) {
std::vector<unsigned char> resp(sizeof(struct bitcoin_msg_header) + header.length);
resp.insert(resp.begin() + sizeof(struct bitcoin_msg_header), msg->begin(), msg->end());
send_message("getdata", &resp[0], header.length);
} else if (!strncmp(header.command, "block", strlen("block"))) {
provide_block(*msg, read_start);
} else if (!strncmp(header.command, "tx", strlen("tx"))) {
provide_transaction(msg);
} else if (!strncmp(header.command, "headers", strlen("headers"))) {
if (msg->size() <= 1 + 82)
continue; // Probably last one
if (!provide_headers || !provide_headers(*msg))
continue;
std::vector<unsigned char> req(sizeof(struct bitcoin_msg_header));
struct bitcoin_version_start sent_version;
req.insert(req.end(), (unsigned char*)&sent_version.protocol_version, ((unsigned char*)&sent_version.protocol_version) + sizeof(sent_version.protocol_version));
req.insert(req.end(), 1, 1);
std::vector<unsigned char> fullhash(32);
CSHA256 hash;
hash.Write(&(*msg)[msg->size() - 81], 80).Finalize(&fullhash[0]);
hash.Reset().Write(&fullhash[0], fullhash.size()).Finalize(&fullhash[0]);
req.insert(req.end(), fullhash.begin(), fullhash.end());
req.insert(req.end(), 32, 0);
std::lock_guard<std::mutex> lock(send_mutex);
send_message("getheaders", &req[0], req.size() - sizeof(struct bitcoin_msg_header));
}
}
}
void P2PRelayer::receive_transaction(const std::shared_ptr<std::vector<unsigned char> >& tx) {
if (!connected)
return;
#ifndef FOR_VALGRIND
if (!send_mutex.try_lock())
return;
#else
send_mutex.lock();
#endif
auto msg = std::vector<unsigned char>(sizeof(struct bitcoin_msg_header));
msg.insert(msg.end(), tx->begin(), tx->end());
send_message("tx", &msg[0], tx->size());
if (requestAfterSend) {
std::vector<unsigned char> req(sizeof(struct bitcoin_msg_header));
req.insert(req.end(), 1, 1);
uint32_t MSG_TX = htole32(1);
req.insert(req.end(), (unsigned char*)&MSG_TX, ((unsigned char*)&MSG_TX) + sizeof(MSG_TX));
std::vector<unsigned char> fullhash(32);
CSHA256 hash; // Probably not BE-safe
hash.Write(&(*tx)[0], tx->size()).Finalize(&fullhash[0]);
hash.Reset().Write(&fullhash[0], fullhash.size()).Finalize(&fullhash[0]);
req.insert(req.end(), fullhash.begin(), fullhash.end());
send_message("getdata", &req[0], 37);
}
send_mutex.unlock();
}
void P2PRelayer::receive_block(std::vector<unsigned char>& block) {
if (!connected)
return;
std::lock_guard<std::mutex> lock(send_mutex);
send_message("block", &block[0], block.size() - sizeof(bitcoin_msg_header));
}
<commit_msg>need stdio, sys/socket, netinet/in.h.<commit_after>#include "p2pclient.h"
#include "utils.h"
#include "crypto/sha2.h"
#include <thread>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <stdio.h>
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else // WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <fcntl.h>
#endif // !WIN32
void P2PRelayer::reconnect(std::string disconnectReason) {
connected = false;
if (sock) {
printf("Closing bitcoind socket with %s, %s (%i: %s)\n", server_host, disconnectReason.c_str(), errno, errno ? strerror(errno) : "");
#ifndef WIN32
errno = 0;
#endif
close(sock);
}
sleep(1);
new_thread = new std::thread(do_connect, this);
}
void P2PRelayer::do_connect(P2PRelayer* me) {
if (me->net_thread)
me->net_thread->join();
me->net_thread = me->new_thread;
me->sock = socket(AF_INET6, SOCK_STREAM, 0);
if (me->sock <= 0)
return me->reconnect("unable to create socket");
sockaddr_in6 addr;
if (!lookup_address(me->server_host, &addr))
return me->reconnect("unable to lookup host");
int v6only = 0;
setsockopt(me->sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6only, sizeof(v6only));
addr.sin6_port = htons(me->server_port);
if (connect(me->sock, (struct sockaddr*)&addr, sizeof(addr)))
return me->reconnect("failed to connect()");
#ifdef WIN32
unsigned long nonblocking = 0;
ioctlsocket(me->sock, FIONBIO, &nonblocking);
#else
fcntl(me->sock, F_SETFL, fcntl(me->sock, F_GETFL) & ~O_NONBLOCK);
#endif
#ifdef X86_BSD
int nosigpipe = 1;
setsockopt(me->sock, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(int));
#endif
me->net_process();
}
bool P2PRelayer::send_message(const char* command, unsigned char* headerAndData, size_t datalen) {
prepare_message(command, headerAndData, datalen);
return send_all(sock, (char*)headerAndData, sizeof(struct bitcoin_msg_header) + datalen) == int(sizeof(struct bitcoin_msg_header) + datalen);
}
void P2PRelayer::net_process() {
if (!send_version()) {
reconnect("failed to send version message");
return;
}
int nodelay = 1;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(nodelay));
if (errno)
return reconnect("error during connect");
while (true) {
struct bitcoin_msg_header header;
if (read_all(sock, (char*)&header, sizeof(header)) != sizeof(header))
return reconnect("failed to read message header");
if (header.magic != BITCOIN_MAGIC)
return reconnect("invalid magic bytes");
header.length = le32toh(header.length);
if (header.length > 5000000)
return reconnect("got message too large");
uint32_t prependedHeaderSize = (!strncmp(header.command, "block", strlen("block"))) ? sizeof(struct bitcoin_msg_header) : 0;
struct timeval read_start;
gettimeofday(&read_start, NULL);
auto msg = std::make_shared<std::vector<unsigned char> > (prependedHeaderSize + uint32_t(header.length));
if (read_all(sock, (char*)&(*msg)[prependedHeaderSize], header.length) != int(header.length))
return reconnect("failed to read message");
unsigned char fullhash[32];
CSHA256 hash;
hash.Write(&(*msg)[prependedHeaderSize], header.length).Finalize(fullhash);
hash.Reset().Write(fullhash, sizeof(fullhash)).Finalize(fullhash);
if (memcmp((char*)fullhash, header.checksum, sizeof(header.checksum)))
return reconnect("got invalid message checksum");
if (!strncmp(header.command, "version", strlen("version"))) {
if (header.length < sizeof(struct bitcoin_version_start))
return reconnect("got short version");
struct bitcoin_version_start *their_version = (struct bitcoin_version_start*) &(*msg)[0];
struct bitcoin_msg_header new_header;
send_message("verack", (unsigned char*)&new_header, 0);
if (provide_headers) {
std::vector<unsigned char> msg(sizeof(struct bitcoin_msg_header));
struct bitcoin_version_start sent_version;
msg.insert(msg.end(), (unsigned char*)&sent_version.protocol_version, ((unsigned char*)&sent_version.protocol_version) + sizeof(sent_version.protocol_version));
msg.insert(msg.end(), 1, 1);
msg.insert(msg.end(), 64, 0);
send_message("getheaders", &msg[0], msg.size() - sizeof(struct bitcoin_msg_header));
}
printf("Connected to bitcoind with version %u\n", le32toh(their_version->protocol_version));
} else if (!strncmp(header.command, "verack", strlen("verack"))) {
printf("Finished connect handshake with bitcoind\n");
connected = true;
} else if (!strncmp(header.command, "ping", strlen("ping"))) {
std::vector<unsigned char> resp(sizeof(struct bitcoin_msg_header) + header.length);
resp.insert(resp.begin() + sizeof(struct bitcoin_msg_header), msg->begin(), msg->end());
send_message("pong", &resp[0], header.length);
} else if (!strncmp(header.command, "inv", strlen("inv"))) {
std::vector<unsigned char> resp(sizeof(struct bitcoin_msg_header) + header.length);
resp.insert(resp.begin() + sizeof(struct bitcoin_msg_header), msg->begin(), msg->end());
send_message("getdata", &resp[0], header.length);
} else if (!strncmp(header.command, "block", strlen("block"))) {
provide_block(*msg, read_start);
} else if (!strncmp(header.command, "tx", strlen("tx"))) {
provide_transaction(msg);
} else if (!strncmp(header.command, "headers", strlen("headers"))) {
if (msg->size() <= 1 + 82)
continue; // Probably last one
if (!provide_headers || !provide_headers(*msg))
continue;
std::vector<unsigned char> req(sizeof(struct bitcoin_msg_header));
struct bitcoin_version_start sent_version;
req.insert(req.end(), (unsigned char*)&sent_version.protocol_version, ((unsigned char*)&sent_version.protocol_version) + sizeof(sent_version.protocol_version));
req.insert(req.end(), 1, 1);
std::vector<unsigned char> fullhash(32);
CSHA256 hash;
hash.Write(&(*msg)[msg->size() - 81], 80).Finalize(&fullhash[0]);
hash.Reset().Write(&fullhash[0], fullhash.size()).Finalize(&fullhash[0]);
req.insert(req.end(), fullhash.begin(), fullhash.end());
req.insert(req.end(), 32, 0);
std::lock_guard<std::mutex> lock(send_mutex);
send_message("getheaders", &req[0], req.size() - sizeof(struct bitcoin_msg_header));
}
}
}
void P2PRelayer::receive_transaction(const std::shared_ptr<std::vector<unsigned char> >& tx) {
if (!connected)
return;
#ifndef FOR_VALGRIND
if (!send_mutex.try_lock())
return;
#else
send_mutex.lock();
#endif
auto msg = std::vector<unsigned char>(sizeof(struct bitcoin_msg_header));
msg.insert(msg.end(), tx->begin(), tx->end());
send_message("tx", &msg[0], tx->size());
if (requestAfterSend) {
std::vector<unsigned char> req(sizeof(struct bitcoin_msg_header));
req.insert(req.end(), 1, 1);
uint32_t MSG_TX = htole32(1);
req.insert(req.end(), (unsigned char*)&MSG_TX, ((unsigned char*)&MSG_TX) + sizeof(MSG_TX));
std::vector<unsigned char> fullhash(32);
CSHA256 hash; // Probably not BE-safe
hash.Write(&(*tx)[0], tx->size()).Finalize(&fullhash[0]);
hash.Reset().Write(&fullhash[0], fullhash.size()).Finalize(&fullhash[0]);
req.insert(req.end(), fullhash.begin(), fullhash.end());
send_message("getdata", &req[0], 37);
}
send_mutex.unlock();
}
void P2PRelayer::receive_block(std::vector<unsigned char>& block) {
if (!connected)
return;
std::lock_guard<std::mutex> lock(send_mutex);
send_message("block", &block[0], block.size() - sizeof(bitcoin_msg_header));
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/Util/TimeValueC.h>
// Library/third-party includes
#include <vrpn_Shared.h>
// Standard includes
#if defined(OSVR_HAVE_STRUCT_TIMEVAL_IN_SYS_TIME_H)
#include <sys/time.h>
typedef time_t tv_seconds_type;
typedef suseconds_t tv_microseconds_type;
#elif defined(OSVR_HAVE_STRUCT_TIMEVAL_IN_WINSOCK2_H)
//#include <winsock2.h>
typedef long tv_seconds_type;
typedef long tv_microseconds_type;
#endif
#define OSVR_USEC_PER_SEC 1000000;
void osvrTimeValueNormalize(OSVR_INOUT_PTR OSVR_TimeValue *tv) {
if (!tv) {
return;
}
const OSVR_TimeValue_Microseconds rem =
tv->microseconds / OSVR_USEC_PER_SEC;
tv->seconds += rem;
tv->microseconds -= rem * OSVR_USEC_PER_SEC;
/* By here, abs(microseconds) < OSVR_USEC_PER_SEC:
now let's get signs the same. */
if (tv->seconds > 0 && tv->microseconds < 0) {
tv->seconds--;
tv->microseconds += OSVR_USEC_PER_SEC;
} else if (tv->seconds < 0 && tv->microseconds > 0) {
tv->seconds++;
tv->microseconds -= OSVR_USEC_PER_SEC;
}
}
void osvrTimeValueSum(OSVR_INOUT_PTR OSVR_TimeValue *tvA,
OSVR_IN_PTR const OSVR_TimeValue *tvB) {
if (!tvA || !tvB) {
return;
}
tvA->seconds += tvB->seconds;
tvA->microseconds += tvB->microseconds;
osvrTimeValueNormalize(tvA);
}
void osvrTimeValueDifference(OSVR_INOUT_PTR OSVR_TimeValue *tvA,
OSVR_IN_PTR const OSVR_TimeValue *tvB) {
if (!tvA || !tvB) {
return;
}
tvA->seconds -= tvB->seconds;
tvA->microseconds -= tvB->microseconds;
osvrTimeValueNormalize(tvA);
}
template <typename T> inline int numcmp(T a, T b) {
return (a == b) ? 0 : (a < b ? -1 : 1);
}
int osvrTimeValueCmp(OSVR_IN_PTR const OSVR_TimeValue *tvA,
OSVR_IN_PTR const OSVR_TimeValue *tvB) {
if (!tvA || !tvB) {
return 0;
}
auto major = numcmp(tvA->seconds, tvB->seconds);
return (major != 0) ? major : numcmp(tvA->microseconds, tvB->microseconds);
}
#ifdef OSVR_HAVE_STRUCT_TIMEVAL
void osvrTimeValueGetNow(OSVR_INOUT_PTR OSVR_TimeValue *dest) {
timeval tv;
vrpn_gettimeofday(&tv, nullptr);
osvrStructTimevalToTimeValue(dest, &tv);
}
void osvrTimeValueToStructTimeval(OSVR_OUT timeval *dest,
OSVR_IN_PTR const OSVR_TimeValue *src) {
if (!dest || !src) {
return;
}
dest->tv_sec = tv_seconds_type(src->seconds);
dest->tv_usec = tv_microseconds_type(src->microseconds);
}
void osvrStructTimevalToTimeValue(OSVR_OUT OSVR_TimeValue *dest,
OSVR_IN_PTR const timeval *src) {
if (!dest || !src) {
return;
}
dest->seconds = src->tv_sec;
dest->microseconds = src->tv_usec;
osvrTimeValueNormalize(dest);
}
#endif
<commit_msg>Let the standard library define our SI prefix ratios for us.<commit_after>/** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/Util/TimeValueC.h>
// Library/third-party includes
#include <vrpn_Shared.h>
// Standard includes
#include <ratio>
#if defined(OSVR_HAVE_STRUCT_TIMEVAL_IN_SYS_TIME_H)
#include <sys/time.h>
typedef time_t tv_seconds_type;
typedef suseconds_t tv_microseconds_type;
#elif defined(OSVR_HAVE_STRUCT_TIMEVAL_IN_WINSOCK2_H)
//#include <winsock2.h>
typedef long tv_seconds_type;
typedef long tv_microseconds_type;
#endif
#define OSVR_USEC_PER_SEC std::micro::den;
void osvrTimeValueNormalize(OSVR_INOUT_PTR OSVR_TimeValue *tv) {
if (!tv) {
return;
}
const OSVR_TimeValue_Microseconds rem =
tv->microseconds / OSVR_USEC_PER_SEC;
tv->seconds += rem;
tv->microseconds -= rem * OSVR_USEC_PER_SEC;
/* By here, abs(microseconds) < OSVR_USEC_PER_SEC:
now let's get signs the same. */
if (tv->seconds > 0 && tv->microseconds < 0) {
tv->seconds--;
tv->microseconds += OSVR_USEC_PER_SEC;
} else if (tv->seconds < 0 && tv->microseconds > 0) {
tv->seconds++;
tv->microseconds -= OSVR_USEC_PER_SEC;
}
}
void osvrTimeValueSum(OSVR_INOUT_PTR OSVR_TimeValue *tvA,
OSVR_IN_PTR const OSVR_TimeValue *tvB) {
if (!tvA || !tvB) {
return;
}
tvA->seconds += tvB->seconds;
tvA->microseconds += tvB->microseconds;
osvrTimeValueNormalize(tvA);
}
void osvrTimeValueDifference(OSVR_INOUT_PTR OSVR_TimeValue *tvA,
OSVR_IN_PTR const OSVR_TimeValue *tvB) {
if (!tvA || !tvB) {
return;
}
tvA->seconds -= tvB->seconds;
tvA->microseconds -= tvB->microseconds;
osvrTimeValueNormalize(tvA);
}
template <typename T> inline int numcmp(T a, T b) {
return (a == b) ? 0 : (a < b ? -1 : 1);
}
int osvrTimeValueCmp(OSVR_IN_PTR const OSVR_TimeValue *tvA,
OSVR_IN_PTR const OSVR_TimeValue *tvB) {
if (!tvA || !tvB) {
return 0;
}
auto major = numcmp(tvA->seconds, tvB->seconds);
return (major != 0) ? major : numcmp(tvA->microseconds, tvB->microseconds);
}
#ifdef OSVR_HAVE_STRUCT_TIMEVAL
void osvrTimeValueGetNow(OSVR_INOUT_PTR OSVR_TimeValue *dest) {
timeval tv;
vrpn_gettimeofday(&tv, nullptr);
osvrStructTimevalToTimeValue(dest, &tv);
}
void osvrTimeValueToStructTimeval(OSVR_OUT timeval *dest,
OSVR_IN_PTR const OSVR_TimeValue *src) {
if (!dest || !src) {
return;
}
dest->tv_sec = tv_seconds_type(src->seconds);
dest->tv_usec = tv_microseconds_type(src->microseconds);
}
void osvrStructTimevalToTimeValue(OSVR_OUT OSVR_TimeValue *dest,
OSVR_IN_PTR const timeval *src) {
if (!dest || !src) {
return;
}
dest->seconds = src->tv_sec;
dest->microseconds = src->tv_usec;
osvrTimeValueNormalize(dest);
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: canvasfont.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-07 23:19:11 $
*
* 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 _CANVASFONT_HXX
#define _CANVASFONT_HXX
#ifndef _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX
#include <comphelper/implementationreference.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XCANVASFONT_HPP_
#include <com/sun/star/rendering/XCanvasFont.hpp>
#endif
#ifndef _SV_FONT_HXX
#include <vcl/font.hxx>
#endif
#include <canvas/vclwrapper.hxx>
#include "canvashelper.hxx"
#include "impltools.hxx"
#define CANVASFONT_IMPLEMENTATION_NAME "VCLCanvas::CanvasFont"
/* Definition of CanvasFont class */
namespace vclcanvas
{
typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::rendering::XCanvasFont,
::com::sun::star::lang::XServiceInfo > CanvasFont_Base;
class CanvasFont : public ::comphelper::OBaseMutex, public CanvasFont_Base
{
public:
typedef ::comphelper::ImplementationReference<
CanvasFont,
::com::sun::star::rendering::XCanvasFont > ImplRef;
CanvasFont( const ::com::sun::star::rendering::FontRequest& fontRequest,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& extraFontProperties,
const ::com::sun::star::geometry::Matrix2D& rFontMatrix,
const OutDevProviderSharedPtr& rDevice );
/// Dispose all internal references
virtual void SAL_CALL disposing();
// XCanvasFont
virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XTextLayout > SAL_CALL createTextLayout( const ::com::sun::star::rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::rendering::FontRequest SAL_CALL getFontRequest( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::rendering::FontMetrics SAL_CALL getFontMetrics( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getAvailableSizes( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getExtraFontProperties( ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );
::Font getVCLFont() const;
protected:
~CanvasFont(); // we're a ref-counted UNO class. _We_ destroy ourselves.
private:
// default: disabled copy/assignment
CanvasFont(const CanvasFont&);
CanvasFont& operator=( const CanvasFont& );
::canvas::vcltools::VCLObject<Font> maFont;
::com::sun::star::rendering::FontRequest maFontRequest;
OutDevProviderSharedPtr mpRefDevice;
};
}
#endif /* _CANVASFONT_HXX */
<commit_msg>INTEGRATION: CWS canvas02 (1.4.10); FILE MERGED 2005/10/08 12:54:34 thb 1.4.10.2: RESYNC: (1.4-1.5); FILE MERGED 2005/06/17 23:49:50 thb 1.4.10.1: #i48939# Huge refactoring of canvas; as much functionality as possible is now common in a bunch of shared base classes (input checking, locking, sprite redraw, etc.); added scroll update optimization, transparently to all canvas implementations<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: canvasfont.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2005-11-02 12:59:53 $
*
* 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 _VCLCANVAS_CANVASFONT_HXX
#define _VCLCANVAS_CANVASFONT_HXX
#include <comphelper/implementationreference.hxx>
#include <cppuhelper/compbase2.hxx>
#include <comphelper/broadcasthelper.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/geometry/Matrix2D.hpp>
#include <com/sun/star/rendering/FontRequest.hpp>
#include <com/sun/star/rendering/XCanvasFont.hpp>
#include <vcl/font.hxx>
#include <canvas/vclwrapper.hxx>
#include "spritecanvas.hxx"
#include "impltools.hxx"
#include <boost/utility.hpp>
/* Definition of CanvasFont class */
namespace vclcanvas
{
typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::rendering::XCanvasFont,
::com::sun::star::lang::XServiceInfo > CanvasFont_Base;
class CanvasFont : public ::comphelper::OBaseMutex,
public CanvasFont_Base,
private ::boost::noncopyable
{
public:
typedef ::comphelper::ImplementationReference<
CanvasFont,
::com::sun::star::rendering::XCanvasFont > Reference;
CanvasFont( const ::com::sun::star::rendering::FontRequest& fontRequest,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& extraFontProperties,
const ::com::sun::star::geometry::Matrix2D& rFontMatrix,
const DeviceRef& rDevice );
/// Dispose all internal references
virtual void SAL_CALL disposing();
// XCanvasFont
virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XTextLayout > SAL_CALL createTextLayout( const ::com::sun::star::rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::rendering::FontRequest SAL_CALL getFontRequest( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::rendering::FontMetrics SAL_CALL getFontMetrics( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getAvailableSizes( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getExtraFontProperties( ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );
::Font getVCLFont() const;
private:
::canvas::vcltools::VCLObject<Font> maFont;
::com::sun::star::rendering::FontRequest maFontRequest;
DeviceRef mpRefDevice;
};
}
#endif /* _VCLCANVAS_CANVASFONT_HXX */
<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE SubmodularFlow
#include <boost/test/unit_test.hpp>
#include <iostream>
#include "submodular-flow.hpp"
BOOST_AUTO_TEST_SUITE(basicSubmodularFlow)
BOOST_AUTO_TEST_CASE(sanityCheck) {
BOOST_CHECK_EQUAL(2+2, 4);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Adding basic test case of flow network with 4 vars and a single clique<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE SubmodularFlow
#include <boost/test/unit_test.hpp>
#include <iostream>
#include "submodular-flow.hpp"
BOOST_AUTO_TEST_SUITE(basicSubmodularFlow)
BOOST_AUTO_TEST_CASE(sanityCheck) {
typedef SubmodularFlow::NodeId NodeId;
SubmodularFlow sf;
sf.AddNode(4);
std::vector<NodeId> nodes = {0, 1, 2, 3};
const size_t numAssignments = 1 << 4;
std::vector<REAL> energyTable(numAssignments, 0);
energyTable[0xf] = -1;
sf.AddClique(nodes, energyTable);
sf.PushRelabel();
sf.ComputeMinCut();
BOOST_CHECK_EQUAL(sf.ComputeEnergy(), -1);
for (NodeId i = 0; i < 4; ++i) {
BOOST_CHECK_EQUAL(sf.GetLabel(i), 1);
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/***
* testSDLScreenManager
*
* Testing SDLScreenManager class, which deals with SDL output and RdScreen management
*
* This test is NOT AUTOMATIC, not suitable for running it with a CI server
*
***/
#include "ScreenManager.hpp"
#include "SDLScreenManager.hpp"
#include "RdScreen.hpp"
#include "MockupScreen.hpp"
#include <yarp/os/Time.h>
using namespace rd;
int main()
{
//-- Start SDL, Create SDLScreen Manager
SDLScreenManager::RegisterManager();
ScreenManager * screenManager = ScreenManager::getScreenManager("SDL");
screenManager->start();
//-- Create a RdScreen to check the ScreenManager
RdScreen * screen = new MockupScreen();
screen->init();
RdScreen * screen2 = new MockupScreen();
screen2->init();
//-- Set the first Screen in the ScreenManager
screenManager->setCurrentScreen(screen);
screenManager->update(MockupScreen::PARAM_MESSAGE, "Test screen");
//-- Loop to display the first Screen
for (int i = 0; i < 10; i++)
{
screenManager->show();
yarp::os::Time::delay(0.2);
}
//-- Set the second Screen in the ScreenManager
screenManager->setCurrentScreen(screen2);
screenManager->update(MockupScreen::PARAM_MESSAGE, "Another test screen");
//-- Loop to display the first second
for (int i = 0; i < 10; i++)
{
screenManager->show();
yarp::os::Time::delay(0.2);
}
screenManager->stop();
screen->cleanup();
screen2->cleanup();
return 0;
}
<commit_msg>Add missing cleanup in testSDLScreenManager<commit_after>/***
* testSDLScreenManager
*
* Testing SDLScreenManager class, which deals with SDL output and RdScreen management
*
* This test is NOT AUTOMATIC, not suitable for running it with a CI server
*
***/
#include "ScreenManager.hpp"
#include "SDLScreenManager.hpp"
#include "RdScreen.hpp"
#include "MockupScreen.hpp"
#include <yarp/os/Time.h>
using namespace rd;
int main()
{
//-- Start SDL, Create SDLScreen Manager
SDLScreenManager::RegisterManager();
ScreenManager * screenManager = ScreenManager::getScreenManager("SDL");
screenManager->start();
//-- Create a RdScreen to check the ScreenManager
RdScreen * screen = new MockupScreen();
screen->init();
RdScreen * screen2 = new MockupScreen();
screen2->init();
//-- Set the first Screen in the ScreenManager
screenManager->setCurrentScreen(screen);
screenManager->update(MockupScreen::PARAM_MESSAGE, "Test screen");
//-- Loop to display the first Screen
for (int i = 0; i < 10; i++)
{
screenManager->show();
yarp::os::Time::delay(0.2);
}
//-- Set the second Screen in the ScreenManager
screenManager->setCurrentScreen(screen2);
screenManager->update(MockupScreen::PARAM_MESSAGE, "Another test screen");
//-- Loop to display the first second
for (int i = 0; i < 10; i++)
{
screenManager->show();
yarp::os::Time::delay(0.2);
}
screenManager->stop();
screen->cleanup();
screen2->cleanup();
delete screen;
screen = NULL;
delete screen2;
screen2 = NULL;
SDLScreenManager::destroyScreenManager();
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, 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 "test.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/http_connection.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <boost/optional.hpp>
using namespace libtorrent;
io_service ios;
connection_queue cq(ios);
int connect_handler_called = 0;
int handler_called = 0;
int data_size = 0;
int http_status = 0;
error_code g_error_code;
char data_buffer[4000];
void print_http_header(http_parser const& p)
{
std::cerr << " < " << p.status_code() << " " << p.message() << std::endl;
for (std::map<std::string, std::string>::const_iterator i
= p.headers().begin(), end(p.headers().end()); i != end; ++i)
{
std::cerr << " < " << i->first << ": " << i->second << std::endl;
}
}
void http_connect_handler(http_connection& c)
{
++connect_handler_called;
TEST_CHECK(c.socket().is_open());
error_code ec;
std::cerr << "connected to: " << c.socket().remote_endpoint(ec) << std::endl;
TEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string("127.0.0.1", ec));
}
void http_handler(error_code const& ec, http_parser const& parser
, char const* data, int size, http_connection& c)
{
++handler_called;
data_size = size;
g_error_code = ec;
if (parser.header_finished())
{
http_status = parser.status_code();
if (http_status == 200)
{
TEST_CHECK(memcmp(data, data_buffer, size) == 0);
}
}
print_http_header(parser);
}
void reset_globals()
{
connect_handler_called = 0;
handler_called = 0;
data_size = 0;
http_status = 0;
g_error_code = error_code();
}
void run_test(std::string const& url, int size, int status, int connected
, boost::optional<error_code> ec, proxy_settings const& ps)
{
reset_globals();
std::cerr << " ===== TESTING: " << url << " =====" << std::endl;
std::cerr << " expecting: size: " << size
<< " status: " << status
<< " connected: " << connected
<< " error: " << (ec?ec->message():"no error") << std::endl;
boost::shared_ptr<http_connection> h(new http_connection(ios, cq
, &::http_handler, true, &::http_connect_handler));
h->get(url, seconds(1), 0, &ps);
ios.reset();
error_code e;
ios.run(e);
std::cerr << "connect_handler_called: " << connect_handler_called << std::endl;
std::cerr << "handler_called: " << handler_called << std::endl;
std::cerr << "status: " << http_status << std::endl;
std::cerr << "size: " << data_size << std::endl;
std::cerr << "error_code: " << g_error_code.message() << std::endl;
TEST_CHECK(connect_handler_called == connected);
TEST_CHECK(handler_called == 1);
TEST_CHECK(data_size == size || size == -1);
TEST_CHECK(!ec || g_error_code == *ec);
TEST_CHECK(http_status == status || status == -1);
}
void run_suite(std::string const& protocol, proxy_settings const& ps)
{
if (ps.type != proxy_settings::none)
{
start_proxy(ps.port, ps.type);
}
char const* test_name[] = {"no", "SOCKS4", "SOCKS5"
, "SOCKS5 password protected", "HTTP", "HTTP password protected"};
std::cout << "\n\n********************** using " << test_name[ps.type]
<< " proxy **********************\n" << std::endl;
typedef boost::optional<error_code> err;
// this requires the hosts file to be modified
// run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/relative/redirect", 3216, 200, 2, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/redirect", 3216, 200, 2, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/infinite_redirect", 0, 301, 6, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/test_file", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/test_file.gz", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/non-existing-file", -1, 404, 1, err(), ps);
// if we're going through an http proxy, we won't get the same error as if the hostname
// resolution failed
if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https")
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps);
else
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps);
if (ps.type != proxy_settings::none)
stop_proxy(ps.port);
}
int test_main()
{
std::srand(std::time(0));
std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand);
std::ofstream test_file("test_file", std::ios::trunc);
test_file.write(data_buffer, 3216);
TEST_CHECK(test_file.good());
test_file.close();
std::system("gzip -9 -c test_file > test_file.gz");
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8034;
ps.username = "testuser";
ps.password = "testpass";
start_web_server(8001);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("http", ps);
}
stop_web_server(8001);
#ifdef TORRENT_USE_OPENSSL
start_web_server(8001, true);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("https", ps);
}
stop_web_server(8001);
#endif
std::remove("test_file");
return 0;
}
<commit_msg>made test use internal file class instead of ofstream<commit_after>/*
Copyright (c) 2008, 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 "test.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/http_connection.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <boost/optional.hpp>
using namespace libtorrent;
io_service ios;
connection_queue cq(ios);
int connect_handler_called = 0;
int handler_called = 0;
int data_size = 0;
int http_status = 0;
error_code g_error_code;
char data_buffer[4000];
void print_http_header(http_parser const& p)
{
std::cerr << " < " << p.status_code() << " " << p.message() << std::endl;
for (std::map<std::string, std::string>::const_iterator i
= p.headers().begin(), end(p.headers().end()); i != end; ++i)
{
std::cerr << " < " << i->first << ": " << i->second << std::endl;
}
}
void http_connect_handler(http_connection& c)
{
++connect_handler_called;
TEST_CHECK(c.socket().is_open());
error_code ec;
std::cerr << "connected to: " << c.socket().remote_endpoint(ec) << std::endl;
TEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string("127.0.0.1", ec));
}
void http_handler(error_code const& ec, http_parser const& parser
, char const* data, int size, http_connection& c)
{
++handler_called;
data_size = size;
g_error_code = ec;
if (parser.header_finished())
{
http_status = parser.status_code();
if (http_status == 200)
{
TEST_CHECK(memcmp(data, data_buffer, size) == 0);
}
}
print_http_header(parser);
}
void reset_globals()
{
connect_handler_called = 0;
handler_called = 0;
data_size = 0;
http_status = 0;
g_error_code = error_code();
}
void run_test(std::string const& url, int size, int status, int connected
, boost::optional<error_code> ec, proxy_settings const& ps)
{
reset_globals();
std::cerr << " ===== TESTING: " << url << " =====" << std::endl;
std::cerr << " expecting: size: " << size
<< " status: " << status
<< " connected: " << connected
<< " error: " << (ec?ec->message():"no error") << std::endl;
boost::shared_ptr<http_connection> h(new http_connection(ios, cq
, &::http_handler, true, &::http_connect_handler));
h->get(url, seconds(1), 0, &ps);
ios.reset();
error_code e;
ios.run(e);
std::cerr << "connect_handler_called: " << connect_handler_called << std::endl;
std::cerr << "handler_called: " << handler_called << std::endl;
std::cerr << "status: " << http_status << std::endl;
std::cerr << "size: " << data_size << std::endl;
std::cerr << "error_code: " << g_error_code.message() << std::endl;
TEST_CHECK(connect_handler_called == connected);
TEST_CHECK(handler_called == 1);
TEST_CHECK(data_size == size || size == -1);
TEST_CHECK(!ec || g_error_code == *ec);
TEST_CHECK(http_status == status || status == -1);
}
void run_suite(std::string const& protocol, proxy_settings const& ps)
{
if (ps.type != proxy_settings::none)
{
start_proxy(ps.port, ps.type);
}
char const* test_name[] = {"no", "SOCKS4", "SOCKS5"
, "SOCKS5 password protected", "HTTP", "HTTP password protected"};
std::cout << "\n\n********************** using " << test_name[ps.type]
<< " proxy **********************\n" << std::endl;
typedef boost::optional<error_code> err;
// this requires the hosts file to be modified
// run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/relative/redirect", 3216, 200, 2, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/redirect", 3216, 200, 2, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/infinite_redirect", 0, 301, 6, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/test_file", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/test_file.gz", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/non-existing-file", -1, 404, 1, err(), ps);
// if we're going through an http proxy, we won't get the same error as if the hostname
// resolution failed
if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https")
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps);
else
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps);
if (ps.type != proxy_settings::none)
stop_proxy(ps.port);
}
int test_main()
{
std::srand(std::time(0));
std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand);
error_code ec;
file test_file("test_file", file::write_only, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
file::iovec_t b = { data_buffer, 3216};
test_file.writev(0, &b, 1, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
test_file.close();
std::system("gzip -9 -c test_file > test_file.gz");
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8034;
ps.username = "testuser";
ps.password = "testpass";
start_web_server(8001);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("http", ps);
}
stop_web_server(8001);
#ifdef TORRENT_USE_OPENSSL
start_web_server(8001, true);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("https", ps);
}
stop_web_server(8001);
#endif
std::remove("test_file");
return 0;
}
<|endoftext|> |
<commit_before>#include "GenericVariableBlock.h"
// Moose Includes
#include "MeshBlock.h"
#include "Moose.h"
#include "Parser.h"
// libMesh includes
#include "mesh.h"
#include "exodusII_io.h"
#include "boundary_info.h"
#include "getpot.h"
#include "mesh_refinement.h"
#include "linear_partitioner.h"
MeshBlock::MeshBlock(const std::string & reg_id, const std::string & real_id, ParserBlock * parent, Parser & parser_handle)
:ParserBlock(reg_id, real_id, parent, parser_handle)
{
// Register parameters
addParam<int>("dim", -1, "The dimension of the mesh file to read or generate", true);
addParam<std::string>("file", "", "The name of the mesh file to read (required unless using dynamic generation)", false);
addParam<bool>("second_order", false, "Turns on second order elements for the input mesh", false);
addParam<bool>("generated", false, "Tell MOOSE that a mesh will be generated", false);
addParam<std::string>("partitioner", "", "Specifies a mesh partitioner to use when spliting the mesh for a parallel computation", false);
addParam<int>("uniform_refine", 0, "Specify the level of uniform refinement applied to the initial mesh", false);
}
void
MeshBlock::execute()
{
#ifdef DEBUG
std::cerr << "Inside the MeshBlock Object\n";
#endif
Mesh *mesh = new Mesh(getParamValue<int>("dim"));
Moose::mesh = mesh;
// TODO: Need test for Mesh Generation
if (getParamValue<bool>("generated"))
{
if (ParserBlock *gen_block = locateBlock("Mesh/Generation"))
gen_block->execute();
else
mooseError("");
}
if (checkVariableProperties(&GenericVariableBlock::restartRequired))
{
ExodusII_IO *exreader = new ExodusII_IO(*mesh);
Moose::exreader = exreader;
exreader->read(getParamValue<std::string>("file"));
}
else
/* We will use the mesh object to read the file to cut down on
* I/O conntention. We still need to use the Exodus reader though
*for copy_nodal_solutions
*/
mesh->read(getParamValue<std::string>("file"));
if (getParamValue<bool>("second_order"))
mesh->all_second_order(true);
if (getParamValue<std::string>("partitioner") == "linear")
mesh->partitioner() = AutoPtr<Partitioner>(new LinearPartitioner);
mesh->prepare_for_use(false);
// If using ParallelMesh this will delete non-local elements from the current processor
mesh->delete_remote_elements();
// uniformly refine mesh
MeshRefinement mesh_refinement(*mesh);
if (!autoResizeProblem(mesh, mesh_refinement))
mesh_refinement.uniformly_refine(getParamValue<int>("uniform_refine"));
// unsigned int init_unif_refine;
// MeshRefinement mesh_refinement(*mesh);
// bool success = false;
// if (Moose::command_line != NULL && Moose::command_line->search("--dofs"))
// success = Moose::autoResizeProblem(Moose::command_line->next(-1), _parser_handle.getPotHandle(), mesh_refinement);
// if (!success)
// mesh_refinement.uniformly_refine(getParamValue<int>("uniform_refine"));
mesh->boundary_info->build_node_list_from_side_list();
mesh->print_info();
visitChildren();
}
bool
MeshBlock::autoResizeProblem(Mesh *mesh, MeshRefinement &mesh_refinement)
{
unsigned int requested_dofs;
// See if dofs was passed on the command line
if (Moose::command_line != NULL && Moose::command_line->search("--dofs"))
requested_dofs = Moose::command_line->next(-1);
else
return false;
// See if the variables report themselves as resizable
if (!checkVariableProperties(&GenericVariableBlock::autoResizeable))
return false;
unsigned int num_vars = locateBlock("Variables")->n_activeChildren();
while (mesh->n_nodes() * num_vars < requested_dofs)
mesh_refinement.uniformly_refine();
return true;
}
bool
MeshBlock::checkVariableProperties(bool (GenericVariableBlock::*property)() const)
{
std::vector<std::string> blocks_to_check(2);
blocks_to_check[0] = "Variables";
blocks_to_check[1] = "AuxVariables";
for (int i=0; i<blocks_to_check.size(); ++i)
{
ParserBlock *vars_block = locateBlock(blocks_to_check[i]);
if (vars_block != NULL)
for (PBChildIterator j = vars_block->_children.begin(); j != vars_block->_children.end(); ++j)
{
GenericVariableBlock *v = dynamic_cast<GenericVariableBlock *>(*j);
if (v && (v->*property)())
return true;
}
}
return false;
}
<commit_msg>Fix to allow mesh generation<commit_after>#include "GenericVariableBlock.h"
// Moose Includes
#include "MeshBlock.h"
#include "Moose.h"
#include "Parser.h"
// libMesh includes
#include "mesh.h"
#include "exodusII_io.h"
#include "boundary_info.h"
#include "getpot.h"
#include "mesh_refinement.h"
#include "linear_partitioner.h"
MeshBlock::MeshBlock(const std::string & reg_id, const std::string & real_id, ParserBlock * parent, Parser & parser_handle)
:ParserBlock(reg_id, real_id, parent, parser_handle)
{
// Register parameters
addParam<int>("dim", -1, "The dimension of the mesh file to read or generate", true);
addParam<std::string>("file", "", "The name of the mesh file to read (required unless using dynamic generation)", false);
addParam<bool>("second_order", false, "Turns on second order elements for the input mesh", false);
addParam<bool>("generated", false, "Tell MOOSE that a mesh will be generated", false);
addParam<std::string>("partitioner", "", "Specifies a mesh partitioner to use when spliting the mesh for a parallel computation", false);
addParam<int>("uniform_refine", 0, "Specify the level of uniform refinement applied to the initial mesh", false);
}
void
MeshBlock::execute()
{
#ifdef DEBUG
std::cerr << "Inside the MeshBlock Object\n";
#endif
Mesh *mesh = new Mesh(getParamValue<int>("dim"));
Moose::mesh = mesh;
// TODO: Need test for Mesh Generation
if (getParamValue<bool>("generated"))
{
if (ParserBlock *gen_block = locateBlock("Mesh/Generation"))
gen_block->execute();
else
mooseError("");
}
else if (checkVariableProperties(&GenericVariableBlock::restartRequired))
{
ExodusII_IO *exreader = new ExodusII_IO(*mesh);
Moose::exreader = exreader;
exreader->read(getParamValue<std::string>("file"));
}
else
/* We will use the mesh object to read the file to cut down on
* I/O conntention. We still need to use the Exodus reader though
*for copy_nodal_solutions
*/
mesh->read(getParamValue<std::string>("file"));
if (getParamValue<bool>("second_order"))
mesh->all_second_order(true);
if (getParamValue<std::string>("partitioner") == "linear")
mesh->partitioner() = AutoPtr<Partitioner>(new LinearPartitioner);
mesh->prepare_for_use(false);
// If using ParallelMesh this will delete non-local elements from the current processor
mesh->delete_remote_elements();
// uniformly refine mesh
MeshRefinement mesh_refinement(*mesh);
if (!autoResizeProblem(mesh, mesh_refinement))
mesh_refinement.uniformly_refine(getParamValue<int>("uniform_refine"));
// unsigned int init_unif_refine;
// MeshRefinement mesh_refinement(*mesh);
// bool success = false;
// if (Moose::command_line != NULL && Moose::command_line->search("--dofs"))
// success = Moose::autoResizeProblem(Moose::command_line->next(-1), _parser_handle.getPotHandle(), mesh_refinement);
// if (!success)
// mesh_refinement.uniformly_refine(getParamValue<int>("uniform_refine"));
mesh->boundary_info->build_node_list_from_side_list();
mesh->print_info();
visitChildren();
}
bool
MeshBlock::autoResizeProblem(Mesh *mesh, MeshRefinement &mesh_refinement)
{
unsigned int requested_dofs;
// See if dofs was passed on the command line
if (Moose::command_line != NULL && Moose::command_line->search("--dofs"))
requested_dofs = Moose::command_line->next(-1);
else
return false;
// See if the variables report themselves as resizable
if (!checkVariableProperties(&GenericVariableBlock::autoResizeable))
return false;
unsigned int num_vars = locateBlock("Variables")->n_activeChildren();
while (mesh->n_nodes() * num_vars < requested_dofs)
mesh_refinement.uniformly_refine();
return true;
}
bool
MeshBlock::checkVariableProperties(bool (GenericVariableBlock::*property)() const)
{
std::vector<std::string> blocks_to_check(2);
blocks_to_check[0] = "Variables";
blocks_to_check[1] = "AuxVariables";
for (int i=0; i<blocks_to_check.size(); ++i)
{
ParserBlock *vars_block = locateBlock(blocks_to_check[i]);
if (vars_block != NULL)
for (PBChildIterator j = vars_block->_children.begin(); j != vars_block->_children.end(); ++j)
{
GenericVariableBlock *v = dynamic_cast<GenericVariableBlock *>(*j);
if (v && (v->*property)())
return true;
}
}
return false;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "helper.hpp"
#include "status.hpp"
#include "tool_errors.hpp"
#include <ipmiblob/blob_errors.hpp>
#include <ipmiblob/blob_interface.hpp>
#include <chrono>
#include <thread>
#include <utility>
namespace host_tool
{
/* Poll an open verification session. Handling closing the session is not yet
* owned by this method.
*/
void pollStatus(std::uint16_t session, ipmiblob::BlobInterface* blob)
{
using namespace std::chrono_literals;
static constexpr auto verificationSleep = 5s;
ipmi_flash::ActionStatus result = ipmi_flash::ActionStatus::unknown;
try
{
/* sleep for 5 seconds and check 360 times, for a timeout of: 1800
* seconds (30 minutes).
* TODO: make this command line configurable and provide smaller
* default value.
*/
static constexpr int commandAttempts = 360;
int attempts = 0;
bool exitLoop = false;
/* Reach back the current status from the verification service output.
*/
while (attempts++ < commandAttempts)
{
ipmiblob::StatResponse resp = blob->getStat(session);
if (resp.metadata.size() != sizeof(std::uint8_t))
{
/* TODO: How do we want to handle the verification failures,
* because closing the session to the verify blob has a special
* as-of-yet not fully defined behavior.
*/
std::fprintf(stderr, "Received invalid metadata response!!!\n");
}
result = static_cast<ipmi_flash::ActionStatus>(resp.metadata[0]);
switch (result)
{
case ipmi_flash::ActionStatus::failed:
std::fprintf(stderr, "failed\n");
exitLoop = true;
break;
case ipmi_flash::ActionStatus::unknown:
std::fprintf(stderr, "other\n");
break;
case ipmi_flash::ActionStatus::running:
std::fprintf(stderr, "running\n");
break;
case ipmi_flash::ActionStatus::success:
std::fprintf(stderr, "success\n");
exitLoop = true;
break;
default:
std::fprintf(stderr, "wat\n");
}
if (exitLoop)
{
break;
}
std::this_thread::sleep_for(verificationSleep);
}
}
catch (const ipmiblob::BlobException& b)
{
throw ToolException("blob exception received: " +
std::string(b.what()));
}
/* TODO: If this is reached and it's not success, it may be worth just
* throwing a ToolException with a timeout message specifying the final
* read's value.
*
* TODO: Given that excepting from certain points leaves the BMC update
* state machine in an inconsistent state, we need to carefully evaluate
* which exceptions from the lower layers allow one to try and delete the
* blobs to rollback the state and progress.
*/
if (result != ipmi_flash::ActionStatus::success)
{
throw ToolException("BMC reported failure");
}
}
/* Poll an open blob session for reading.
*
* The committing bit indicates that the blob is not available for reading now
* and the reader might come back and check the state later.
*
* Polling finishes under the following conditions:
* - The open_read bit set -> stat successful
* - The open_read and committing bits unset -> stat failed;
* - Blob exception was received;
* - Time ran out.
* Polling continues when the open_read bit unset and committing bit set.
* If the blob is not open_read and not committing, then it is an error to the
* reader.
*/
uint32_t pollReadReady(std::uint16_t session, ipmiblob::BlobInterface* blob)
{
using namespace std::chrono_literals;
static constexpr auto pollingSleep = 5s;
ipmiblob::StatResponse blobStatResp;
try
{
/* Polling lasts 5 minutes. When opening a version blob, the system
* unit defined in the version handler will extract the running version
* from the image on the flash.
*/
static constexpr int commandAttempts = 60;
int attempts = 0;
while (attempts++ < commandAttempts)
{
blobStatResp = blob->getStat(session);
if (blobStatResp.blob_state & ipmiblob::StateFlags::open_read)
{
std::fprintf(stderr, "success\n");
return blobStatResp.size;
}
else if (blobStatResp.blob_state & ipmiblob::StateFlags::committing)
{
std::fprintf(stderr, "running\n");
}
else
{
std::fprintf(stderr, "failed\n");
throw ToolException("BMC reported failure");
}
std::this_thread::sleep_for(pollingSleep);
}
}
catch (const ipmiblob::BlobException& b)
{
throw ToolException("blob exception received: " +
std::string(b.what()));
}
throw ToolException("Timed out waiting for BMC read ready");
}
void* memcpyAligned(void* destination, const void* source, std::size_t size)
{
std::size_t i = 0;
std::size_t bytesCopied = 0;
if (!(reinterpret_cast<std::uintptr_t>(destination) %
sizeof(std::uint64_t)) &&
!(reinterpret_cast<std::uintptr_t>(source) % sizeof(std::uint64_t)))
{
auto src64 = reinterpret_cast<const volatile std::uint64_t*>(source);
auto dest64 = reinterpret_cast<volatile std::uint64_t*>(destination);
for (i = 0; i < size / sizeof(std::uint64_t); i++)
{
*dest64++ = *src64++;
bytesCopied += sizeof(std::uint64_t);
}
}
auto srcMem8 =
reinterpret_cast<const volatile std::uint8_t*>(source) + bytesCopied;
auto destMem8 =
reinterpret_cast<volatile std::uint8_t*>(destination) + bytesCopied;
for (i = bytesCopied; i < size; i++)
{
*destMem8++ = *srcMem8++;
}
return destination;
}
} // namespace host_tool
<commit_msg>tools: Support more frequent status checks<commit_after>/*
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "helper.hpp"
#include "status.hpp"
#include "tool_errors.hpp"
#include <ipmiblob/blob_errors.hpp>
#include <ipmiblob/blob_interface.hpp>
#include <algorithm>
#include <chrono>
#include <optional>
#include <thread>
#include <utility>
namespace host_tool
{
template <typename Check>
static auto pollStat(std::uint16_t session, ipmiblob::BlobInterface* blob,
Check&& check)
{
using namespace std::chrono_literals;
constexpr auto maxSleep = 1s;
constexpr auto printInterval = 30s;
constexpr auto timeout = 30min;
try
{
auto start = std::chrono::steady_clock::now();
auto last_print = start;
auto last_check = start;
auto check_interval = 50ms;
while (true)
{
ipmiblob::StatResponse resp = blob->getStat(session);
auto ret = check(resp);
if (ret.has_value())
{
std::fprintf(stderr, "success\n");
return std::move(*ret);
}
auto cur = std::chrono::steady_clock::now();
if (cur - last_print >= printInterval)
{
std::fprintf(stderr, "running\n");
last_print = cur;
}
auto sleep = check_interval - (cur - last_check);
last_check = cur;
// Check that we don't timeout immediately after sleeping
// to avoid an extra sleep without checking
if (cur - start > timeout - sleep)
{
throw ToolException("Stat check timed out");
}
check_interval = std::min<decltype(check_interval)>(
check_interval * 2, maxSleep);
std::this_thread::sleep_for(sleep);
}
}
catch (const ipmiblob::BlobException& b)
{
throw ToolException("blob exception received: " +
std::string(b.what()));
}
}
/* Poll an open verification session. Handling closing the session is not yet
* owned by this method.
*/
void pollStatus(std::uint16_t session, ipmiblob::BlobInterface* blob)
{
pollStat(session, blob,
[](const ipmiblob::StatResponse& resp) -> std::optional<bool> {
if (resp.metadata.size() != 1)
{
throw ToolException("Invalid stat metadata");
}
auto result =
static_cast<ipmi_flash::ActionStatus>(resp.metadata[0]);
switch (result)
{
case ipmi_flash::ActionStatus::failed:
throw ToolException("BMC reported failure");
case ipmi_flash::ActionStatus::unknown:
case ipmi_flash::ActionStatus::running:
return std::nullopt;
case ipmi_flash::ActionStatus::success:
return true;
default:
throw ToolException("Unrecognized action status");
}
});
}
/* Poll an open blob session for reading.
*
* The committing bit indicates that the blob is not available for reading now
* and the reader might come back and check the state later.
*
* Polling finishes under the following conditions:
* - The open_read bit set -> stat successful
* - The open_read and committing bits unset -> stat failed;
* - Blob exception was received;
* - Time ran out.
* Polling continues when the open_read bit unset and committing bit set.
* If the blob is not open_read and not committing, then it is an error to the
* reader.
*/
uint32_t pollReadReady(std::uint16_t session, ipmiblob::BlobInterface* blob)
{
return pollStat(
session, blob,
[](const ipmiblob::StatResponse& resp) -> std::optional<uint32_t> {
if (resp.blob_state & ipmiblob::StateFlags::open_read)
{
return resp.size;
}
if (resp.blob_state & ipmiblob::StateFlags::committing)
{
return std::nullopt;
}
throw ToolException("BMC blob failed to become ready");
});
}
void* memcpyAligned(void* destination, const void* source, std::size_t size)
{
std::size_t i = 0;
std::size_t bytesCopied = 0;
if (!(reinterpret_cast<std::uintptr_t>(destination) %
sizeof(std::uint64_t)) &&
!(reinterpret_cast<std::uintptr_t>(source) % sizeof(std::uint64_t)))
{
auto src64 = reinterpret_cast<const volatile std::uint64_t*>(source);
auto dest64 = reinterpret_cast<volatile std::uint64_t*>(destination);
for (i = 0; i < size / sizeof(std::uint64_t); i++)
{
*dest64++ = *src64++;
bytesCopied += sizeof(std::uint64_t);
}
}
auto srcMem8 =
reinterpret_cast<const volatile std::uint8_t*>(source) + bytesCopied;
auto destMem8 =
reinterpret_cast<volatile std::uint8_t*>(destination) + bytesCopied;
for (i = bytesCopied; i < size; i++)
{
*destMem8++ = *srcMem8++;
}
return destination;
}
} // namespace host_tool
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 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 "fileutils.h"
#ifdef WIN32
#include <direct.h>
#define GET_CURRENT_DIR _getcwd
#else
#include <unistd.h>
#define GET_CURRENT_DIR getcwd
#endif
#include <sys/stat.h> // To check for directory existence.
#ifndef S_ISDIR // Not defined in stat.h on Windows.
#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#include <cstdio>
#include "typedefs.h" // For architecture defines
namespace webrtc {
namespace test {
#ifdef WIN32
static const char* kPathDelimiter = "\\";
#else
static const char* kPathDelimiter = "/";
#endif
// The file we're looking for to identify the project root dir.
static const char* kProjectRootFileName = "DEPS";
static const char* kOutputDirName = "out";
static const char* kFallbackPath = "./";
static const char* kResourcesDirName = "resources";
const char* kCannotFindProjectRootDir = "ERROR_CANNOT_FIND_PROJECT_ROOT_DIR";
std::string ProjectRootPath() {
std::string working_dir = WorkingDir();
if (working_dir == kFallbackPath) {
return kCannotFindProjectRootDir;
}
// Check for our file that verifies the root dir.
std::string current_path(working_dir);
FILE* file = NULL;
int path_delimiter_index = current_path.find_last_of(kPathDelimiter);
while (path_delimiter_index > -1) {
std::string root_filename = current_path + kPathDelimiter +
kProjectRootFileName;
file = fopen(root_filename.c_str(), "r");
if (file != NULL) {
fclose(file);
return current_path + kPathDelimiter;
}
// Move up one directory in the directory tree.
current_path = current_path.substr(0, path_delimiter_index);
path_delimiter_index = current_path.find_last_of(kPathDelimiter);
}
// Reached the root directory.
fprintf(stderr, "Cannot find project root directory!\n");
return kCannotFindProjectRootDir;
}
std::string OutputPath() {
std::string path = ProjectRootPath();
if (path == kCannotFindProjectRootDir) {
return kFallbackPath;
}
path += kOutputDirName;
if (!CreateDirectory(path)) {
return kFallbackPath;
}
return path + kPathDelimiter;
}
std::string WorkingDir() {
char path_buffer[FILENAME_MAX];
if (!GET_CURRENT_DIR(path_buffer, sizeof(path_buffer))) {
fprintf(stderr, "Cannot get current directory!\n");
return kFallbackPath;
}
else {
return std::string(path_buffer);
}
}
bool CreateDirectory(std::string directory_name) {
struct stat path_info = {0};
// Check if the path exists already:
if (stat(directory_name.c_str(), &path_info) == 0) {
if (!S_ISDIR(path_info.st_mode)) {
fprintf(stderr, "Path %s exists but is not a directory! Remove this "
"file and re-run to create the directory.\n",
directory_name.c_str());
return false;
}
} else {
#ifdef WIN32
return _mkdir(directory_name.c_str()) == 0;
#else
return mkdir(directory_name.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0;
#endif
}
return true;
}
bool FileExists(std::string file_name) {
struct stat file_info = {0};
return stat(file_name.c_str(), &file_info) == 0;
}
std::string ResourcePath(std::string name, std::string extension) {
std::string platform = "win";
#ifdef WEBRTC_LINUX
platform = "linux";
#endif // WEBRTC_LINUX
#ifdef WEBRTC_MAC
platform = "mac";
#endif // WEBRTC_MAC
#ifdef WEBRTC_ARCH_64_BITS
std::string architecture = "64";
#else
std::string architecture = "32";
#endif // WEBRTC_ARCH_64_BITS
std::string resources_path = ProjectRootPath() + kResourcesDirName + kPathDelimiter;
std::string resource_file = resources_path + name + "_" + platform + "_" +
architecture + "." + extension;
if (!FileExists(resource_file)) {
return resource_file;
}
// Try without architecture.
resource_file = resources_path + name + "_" + platform + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
// Try without platform.
resource_file = resources_path + name + "_" + architecture + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
// Fall back on name without architecture or platform.
return resources_path + name + "." + extension;
}
} // namespace test
} // namespace webrtc
<commit_msg>Fixing invalid check for existing file.<commit_after>/*
* Copyright (c) 2011 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 "fileutils.h"
#ifdef WIN32
#include <direct.h>
#define GET_CURRENT_DIR _getcwd
#else
#include <unistd.h>
#define GET_CURRENT_DIR getcwd
#endif
#include <sys/stat.h> // To check for directory existence.
#ifndef S_ISDIR // Not defined in stat.h on Windows.
#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#include <cstdio>
#include "typedefs.h" // For architecture defines
namespace webrtc {
namespace test {
#ifdef WIN32
static const char* kPathDelimiter = "\\";
#else
static const char* kPathDelimiter = "/";
#endif
// The file we're looking for to identify the project root dir.
static const char* kProjectRootFileName = "DEPS";
static const char* kOutputDirName = "out";
static const char* kFallbackPath = "./";
static const char* kResourcesDirName = "resources";
const char* kCannotFindProjectRootDir = "ERROR_CANNOT_FIND_PROJECT_ROOT_DIR";
std::string ProjectRootPath() {
std::string working_dir = WorkingDir();
if (working_dir == kFallbackPath) {
return kCannotFindProjectRootDir;
}
// Check for our file that verifies the root dir.
std::string current_path(working_dir);
FILE* file = NULL;
int path_delimiter_index = current_path.find_last_of(kPathDelimiter);
while (path_delimiter_index > -1) {
std::string root_filename = current_path + kPathDelimiter +
kProjectRootFileName;
file = fopen(root_filename.c_str(), "r");
if (file != NULL) {
fclose(file);
return current_path + kPathDelimiter;
}
// Move up one directory in the directory tree.
current_path = current_path.substr(0, path_delimiter_index);
path_delimiter_index = current_path.find_last_of(kPathDelimiter);
}
// Reached the root directory.
fprintf(stderr, "Cannot find project root directory!\n");
return kCannotFindProjectRootDir;
}
std::string OutputPath() {
std::string path = ProjectRootPath();
if (path == kCannotFindProjectRootDir) {
return kFallbackPath;
}
path += kOutputDirName;
if (!CreateDirectory(path)) {
return kFallbackPath;
}
return path + kPathDelimiter;
}
std::string WorkingDir() {
char path_buffer[FILENAME_MAX];
if (!GET_CURRENT_DIR(path_buffer, sizeof(path_buffer))) {
fprintf(stderr, "Cannot get current directory!\n");
return kFallbackPath;
}
else {
return std::string(path_buffer);
}
}
bool CreateDirectory(std::string directory_name) {
struct stat path_info = {0};
// Check if the path exists already:
if (stat(directory_name.c_str(), &path_info) == 0) {
if (!S_ISDIR(path_info.st_mode)) {
fprintf(stderr, "Path %s exists but is not a directory! Remove this "
"file and re-run to create the directory.\n",
directory_name.c_str());
return false;
}
} else {
#ifdef WIN32
return _mkdir(directory_name.c_str()) == 0;
#else
return mkdir(directory_name.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0;
#endif
}
return true;
}
bool FileExists(std::string file_name) {
struct stat file_info = {0};
return stat(file_name.c_str(), &file_info) == 0;
}
std::string ResourcePath(std::string name, std::string extension) {
std::string platform = "win";
#ifdef WEBRTC_LINUX
platform = "linux";
#endif // WEBRTC_LINUX
#ifdef WEBRTC_MAC
platform = "mac";
#endif // WEBRTC_MAC
#ifdef WEBRTC_ARCH_64_BITS
std::string architecture = "64";
#else
std::string architecture = "32";
#endif // WEBRTC_ARCH_64_BITS
std::string resources_path = ProjectRootPath() + kResourcesDirName + kPathDelimiter;
std::string resource_file = resources_path + name + "_" + platform + "_" +
architecture + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
// Try without architecture.
resource_file = resources_path + name + "_" + platform + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
// Try without platform.
resource_file = resources_path + name + "_" + architecture + "." + extension;
if (FileExists(resource_file)) {
return resource_file;
}
// Fall back on name without architecture or platform.
return resources_path + name + "." + extension;
}
} // namespace test
} // namespace webrtc
<|endoftext|> |
<commit_before>/**********************************************************************
* File: params.cpp
* Description: Initialization and setting of Tesseract parameters.
* Author: Ray Smith
* Created: Fri Feb 22 16:22:34 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "genericvector.h"
#include "scanutils.h"
#include "tprintf.h"
#include "params.h"
#define PLUS '+' //flag states
#define MINUS '-'
#define EQUAL '='
tesseract::ParamsVectors *GlobalParams() {
static tesseract::ParamsVectors *global_params =
new tesseract::ParamsVectors();
return global_params;
}
namespace tesseract {
bool ParamUtils::ReadParamsFile(const char *file,
SetParamConstraint constraint,
ParamsVectors *member_params) {
inT16 nameoffset; // offset for real name
FILE *fp; // file pointer
// iterators
if (*file == PLUS) {
nameoffset = 1;
} else if (*file == MINUS) {
nameoffset = 1;
} else {
nameoffset = 0;
}
fp = fopen(file + nameoffset, "rb");
if (fp == NULL) {
tprintf("read_params_file: Can't open %s\n", file + nameoffset);
return true;
}
const bool anyerr = ReadParamsFromFp(fp, -1, constraint, member_params);
fclose(fp);
return anyerr;
}
bool ParamUtils::ReadParamsFromFp(FILE *fp, inT64 end_offset,
SetParamConstraint constraint,
ParamsVectors *member_params) {
char line[MAX_PATH]; // input line
bool anyerr = false; // true if any error
bool foundit; // found parameter
inT16 length; // length of line
char *valptr; // value field
while ((end_offset < 0 || ftell(fp) < end_offset) &&
fgets(line, MAX_PATH, fp)) {
if (line[0] != '\n' && line[0] != '#') {
length = strlen (line);
chomp_string(line); // remove newline
for (valptr = line; *valptr && *valptr != ' ' && *valptr != '\t';
valptr++);
if (*valptr) { // found blank
*valptr = '\0'; // make name a string
do
valptr++; // find end of blanks
while (*valptr == ' ' || *valptr == '\t');
}
foundit = SetParam(line, valptr, constraint, member_params);
if (!foundit) {
anyerr = true; // had an error
tprintf("read_params_file: parameter not found: %s\n", line);
exit(1);
}
}
}
return anyerr;
}
bool ParamUtils::SetParam(const char *name, const char* value,
SetParamConstraint constraint,
ParamsVectors *member_params) {
// Look for the parameter among string parameters.
StringParam *sp = FindParam<StringParam>(name, GlobalParams()->string_params,
member_params->string_params);
if (sp != NULL && sp->constraint_ok(constraint)) sp->set_value(value);
if (*value == '\0') return (sp != NULL);
// Look for the parameter among int parameters.
int intval;
IntParam *ip = FindParam<IntParam>(name, GlobalParams()->int_params,
member_params->int_params);
if (ip && ip->constraint_ok(constraint) &&
sscanf(value, INT32FORMAT, &intval) == 1) ip->set_value(intval);
// Look for the parameter among bool parameters.
BoolParam *bp = FindParam<BoolParam>(name, GlobalParams()->bool_params,
member_params->bool_params);
if (bp != NULL && bp->constraint_ok(constraint)) {
if (*value == 'T' || *value == 't' ||
*value == 'Y' || *value == 'y' || *value == '1') {
bp->set_value(true);
} else if (*value == 'F' || *value == 'f' ||
*value == 'N' || *value == 'n' || *value == '0') {
bp->set_value(false);
}
}
// Look for the parameter among double parameters.
double doubleval;
DoubleParam *dp = FindParam<DoubleParam>(name, GlobalParams()->double_params,
member_params->double_params);
if (dp != NULL && dp->constraint_ok(constraint)) {
#ifdef EMBEDDED
doubleval = strtofloat(value);
#else
if (sscanf(value, "%lf", &doubleval) == 1)
#endif
dp->set_value(doubleval);
}
return (sp || ip || bp || dp);
}
bool ParamUtils::GetParamAsString(const char *name,
const ParamsVectors* member_params,
STRING *value) {
// Look for the parameter among string parameters.
StringParam *sp = FindParam<StringParam>(name, GlobalParams()->string_params,
member_params->string_params);
if (sp) {
*value = sp->string();
return true;
}
// Look for the parameter among int parameters.
IntParam *ip = FindParam<IntParam>(name, GlobalParams()->int_params,
member_params->int_params);
if (ip) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", inT32(*ip));
*value = buf;
return true;
}
// Look for the parameter among bool parameters.
BoolParam *bp = FindParam<BoolParam>(name, GlobalParams()->bool_params,
member_params->bool_params);
if (bp != NULL) {
*value = BOOL8(*bp) ? "1": "0";
return true;
}
// Look for the parameter among double parameters.
DoubleParam *dp = FindParam<DoubleParam>(name, GlobalParams()->double_params,
member_params->double_params);
if (dp != NULL) {
char buf[128];
snprintf(buf, sizeof(buf), "%g", double(*dp));
*value = buf;
return true;
}
return false;
}
void ParamUtils::PrintParams(FILE *fp, const ParamsVectors *member_params) {
int v, i;
int num_iterations = (member_params == NULL) ? 1 : 2;
for (v = 0; v < num_iterations; ++v) {
const ParamsVectors *vec = (v == 0) ? GlobalParams() : member_params;
for (i = 0; i < vec->int_params.size(); ++i) {
fprintf(fp, "%s\t%d\t%s\n", vec->int_params[i]->name_str(),
(inT32)(*vec->int_params[i]), vec->int_params[i]->info_str());
}
for (i = 0; i < vec->bool_params.size(); ++i) {
fprintf(fp, "%s\t%d\t%s\n", vec->bool_params[i]->name_str(),
(BOOL8)(*vec->bool_params[i]), vec->bool_params[i]->info_str());
}
for (int i = 0; i < vec->string_params.size(); ++i) {
fprintf(fp, "%s\t%s\t%s\n", vec->string_params[i]->name_str(),
vec->string_params[i]->string(), vec->string_params[i]->info_str());
}
for (int i = 0; i < vec->double_params.size(); ++i) {
fprintf(fp, "%s\t%g\t%s\n", vec->double_params[i]->name_str(),
(double)(*vec->double_params[i]), vec->double_params[i]->info_str());
}
}
}
// Resets all parameters back to default values;
void ParamUtils::ResetToDefaults(ParamsVectors* member_params) {
int v, i;
int num_iterations = (member_params == NULL) ? 1 : 2;
for (v = 0; v < num_iterations; ++v) {
ParamsVectors *vec = (v == 0) ? GlobalParams() : member_params;
for (i = 0; i < vec->int_params.size(); ++i) {
vec->int_params[i]->ResetToDefault();
}
for (i = 0; i < vec->bool_params.size(); ++i) {
vec->bool_params[i]->ResetToDefault();
}
for (int i = 0; i < vec->string_params.size(); ++i) {
vec->string_params[i]->ResetToDefault();
}
for (int i = 0; i < vec->double_params.size(); ++i) {
vec->double_params[i]->ResetToDefault();
}
}
}
} // namespace tesseract
<commit_msg>Removed unused variable<commit_after>/**********************************************************************
* File: params.cpp
* Description: Initialization and setting of Tesseract parameters.
* Author: Ray Smith
* Created: Fri Feb 22 16:22:34 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "genericvector.h"
#include "scanutils.h"
#include "tprintf.h"
#include "params.h"
#define PLUS '+' //flag states
#define MINUS '-'
#define EQUAL '='
tesseract::ParamsVectors *GlobalParams() {
static tesseract::ParamsVectors *global_params =
new tesseract::ParamsVectors();
return global_params;
}
namespace tesseract {
bool ParamUtils::ReadParamsFile(const char *file,
SetParamConstraint constraint,
ParamsVectors *member_params) {
inT16 nameoffset; // offset for real name
FILE *fp; // file pointer
// iterators
if (*file == PLUS) {
nameoffset = 1;
} else if (*file == MINUS) {
nameoffset = 1;
} else {
nameoffset = 0;
}
fp = fopen(file + nameoffset, "rb");
if (fp == NULL) {
tprintf("read_params_file: Can't open %s\n", file + nameoffset);
return true;
}
const bool anyerr = ReadParamsFromFp(fp, -1, constraint, member_params);
fclose(fp);
return anyerr;
}
bool ParamUtils::ReadParamsFromFp(FILE *fp, inT64 end_offset,
SetParamConstraint constraint,
ParamsVectors *member_params) {
char line[MAX_PATH]; // input line
bool anyerr = false; // true if any error
bool foundit; // found parameter
char *valptr; // value field
while ((end_offset < 0 || ftell(fp) < end_offset) &&
fgets(line, MAX_PATH, fp)) {
if (line[0] != '\n' && line[0] != '#') {
chomp_string(line); // remove newline
for (valptr = line; *valptr && *valptr != ' ' && *valptr != '\t';
valptr++);
if (*valptr) { // found blank
*valptr = '\0'; // make name a string
do
valptr++; // find end of blanks
while (*valptr == ' ' || *valptr == '\t');
}
foundit = SetParam(line, valptr, constraint, member_params);
if (!foundit) {
anyerr = true; // had an error
tprintf("read_params_file: parameter not found: %s\n", line);
exit(1);
}
}
}
return anyerr;
}
bool ParamUtils::SetParam(const char *name, const char* value,
SetParamConstraint constraint,
ParamsVectors *member_params) {
// Look for the parameter among string parameters.
StringParam *sp = FindParam<StringParam>(name, GlobalParams()->string_params,
member_params->string_params);
if (sp != NULL && sp->constraint_ok(constraint)) sp->set_value(value);
if (*value == '\0') return (sp != NULL);
// Look for the parameter among int parameters.
int intval;
IntParam *ip = FindParam<IntParam>(name, GlobalParams()->int_params,
member_params->int_params);
if (ip && ip->constraint_ok(constraint) &&
sscanf(value, INT32FORMAT, &intval) == 1) ip->set_value(intval);
// Look for the parameter among bool parameters.
BoolParam *bp = FindParam<BoolParam>(name, GlobalParams()->bool_params,
member_params->bool_params);
if (bp != NULL && bp->constraint_ok(constraint)) {
if (*value == 'T' || *value == 't' ||
*value == 'Y' || *value == 'y' || *value == '1') {
bp->set_value(true);
} else if (*value == 'F' || *value == 'f' ||
*value == 'N' || *value == 'n' || *value == '0') {
bp->set_value(false);
}
}
// Look for the parameter among double parameters.
double doubleval;
DoubleParam *dp = FindParam<DoubleParam>(name, GlobalParams()->double_params,
member_params->double_params);
if (dp != NULL && dp->constraint_ok(constraint)) {
#ifdef EMBEDDED
doubleval = strtofloat(value);
#else
if (sscanf(value, "%lf", &doubleval) == 1)
#endif
dp->set_value(doubleval);
}
return (sp || ip || bp || dp);
}
bool ParamUtils::GetParamAsString(const char *name,
const ParamsVectors* member_params,
STRING *value) {
// Look for the parameter among string parameters.
StringParam *sp = FindParam<StringParam>(name, GlobalParams()->string_params,
member_params->string_params);
if (sp) {
*value = sp->string();
return true;
}
// Look for the parameter among int parameters.
IntParam *ip = FindParam<IntParam>(name, GlobalParams()->int_params,
member_params->int_params);
if (ip) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", inT32(*ip));
*value = buf;
return true;
}
// Look for the parameter among bool parameters.
BoolParam *bp = FindParam<BoolParam>(name, GlobalParams()->bool_params,
member_params->bool_params);
if (bp != NULL) {
*value = BOOL8(*bp) ? "1": "0";
return true;
}
// Look for the parameter among double parameters.
DoubleParam *dp = FindParam<DoubleParam>(name, GlobalParams()->double_params,
member_params->double_params);
if (dp != NULL) {
char buf[128];
snprintf(buf, sizeof(buf), "%g", double(*dp));
*value = buf;
return true;
}
return false;
}
void ParamUtils::PrintParams(FILE *fp, const ParamsVectors *member_params) {
int v, i;
int num_iterations = (member_params == NULL) ? 1 : 2;
for (v = 0; v < num_iterations; ++v) {
const ParamsVectors *vec = (v == 0) ? GlobalParams() : member_params;
for (i = 0; i < vec->int_params.size(); ++i) {
fprintf(fp, "%s\t%d\t%s\n", vec->int_params[i]->name_str(),
(inT32)(*vec->int_params[i]), vec->int_params[i]->info_str());
}
for (i = 0; i < vec->bool_params.size(); ++i) {
fprintf(fp, "%s\t%d\t%s\n", vec->bool_params[i]->name_str(),
(BOOL8)(*vec->bool_params[i]), vec->bool_params[i]->info_str());
}
for (int i = 0; i < vec->string_params.size(); ++i) {
fprintf(fp, "%s\t%s\t%s\n", vec->string_params[i]->name_str(),
vec->string_params[i]->string(), vec->string_params[i]->info_str());
}
for (int i = 0; i < vec->double_params.size(); ++i) {
fprintf(fp, "%s\t%g\t%s\n", vec->double_params[i]->name_str(),
(double)(*vec->double_params[i]), vec->double_params[i]->info_str());
}
}
}
// Resets all parameters back to default values;
void ParamUtils::ResetToDefaults(ParamsVectors* member_params) {
int v, i;
int num_iterations = (member_params == NULL) ? 1 : 2;
for (v = 0; v < num_iterations; ++v) {
ParamsVectors *vec = (v == 0) ? GlobalParams() : member_params;
for (i = 0; i < vec->int_params.size(); ++i) {
vec->int_params[i]->ResetToDefault();
}
for (i = 0; i < vec->bool_params.size(); ++i) {
vec->bool_params[i]->ResetToDefault();
}
for (int i = 0; i < vec->string_params.size(); ++i) {
vec->string_params[i]->ResetToDefault();
}
for (int i = 0; i < vec->double_params.size(); ++i) {
vec->double_params[i]->ResetToDefault();
}
}
}
} // namespace tesseract
<|endoftext|> |
<commit_before>//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "vgui_bitmapimage.h"
#include <vgui_controls/Controls.h>
#include <vgui/ISurface.h>
#include <vgui_controls/Panel.h>
#include "panelmetaclassmgr.h"
#include <KeyValues.h>
#include <vgui/IPanel.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose: Check box image
//-----------------------------------------------------------------------------
BitmapImage::BitmapImage()
{
m_clr.SetColor( 255, 255, 255, 255 );
m_pos[ 0 ] = m_pos[ 1 ] = 0;
m_pPanelSize = NULL;
m_nTextureId = -1;
SetViewport( false, 0.0f, 0.0f, 0.0f, 0.0f );
}
BitmapImage::BitmapImage( vgui::VPANEL parent, const char *filename )
{
m_nTextureId = -1;
m_clr.SetColor( 255, 255, 255, 255 );
m_pos[ 0 ] = m_pos[ 1 ] = 0;
Init( parent, filename );
SetViewport( false, 0.0f, 0.0f, 0.0f, 0.0f );
}
bool BitmapImage::Init( vgui::VPANEL pParent, const char *pFileName )
{
UsePanelRenderSize( pParent );
m_nTextureId = vgui::surface()->CreateNewTextureID();
vgui::surface()->DrawSetTextureFile( m_nTextureId, pFileName , true, true);
GetSize( m_Size[0], m_Size[1] );
return true;
}
bool BitmapImage::Init( vgui::VPANEL pParent, KeyValues* pInitData )
{
char const* pMaterialName = pInitData->GetString( "material" );
if ( !pMaterialName || !pMaterialName[ 0 ] )
return false;
// modulation color
Color color;
if (!ParseRGBA( pInitData, "color", color ))
color.SetColor( 255, 255, 255, 255 );
Init( pParent, pMaterialName );
SetColor( color );
return true;
}
//-----------------------------------------------------------------------------
// FIXME: Bleah!!! Don't want two different KeyValues
/*-----------------------------------------------------------------------------
bool BitmapImage::Init( vgui::VPANEL pParent, KeyValues* pInitData )
{
char const* pMaterialName = pInitData->GetString( "material" );
if ( !pMaterialName || !pMaterialName[ 0 ] )
return false;
// modulation color
Color color;
if (!ParseRGBA( pInitData, "color", color ))
color.SetColor( 255, 255, 255, 255 );
Init( pParent, pMaterialName );
SetColor( color );
return true;
} */
void BitmapImage::SetImageFile( const char *newImage )
{
if ( m_nTextureId == -1 )
{
m_nTextureId = vgui::surface()->CreateNewTextureID();
}
vgui::surface()->DrawSetTextureFile( m_nTextureId, newImage , true, true);
}
void BitmapImage::UsePanelRenderSize( vgui::VPANEL pPanel )
{
m_pPanelSize = pPanel;
}
vgui::VPANEL BitmapImage::GetRenderSizePanel( void )
{
return m_pPanelSize;
}
void BitmapImage::SetRenderSize( int x, int y )
{
m_Size[0] = x;
m_Size[1] = y;
}
void BitmapImage::DoPaint( int x, int y, int wide, int tall, float yaw, float flAlphaModulate )
{
vgui::surface()->DrawSetTexture( m_nTextureId );
int r, g, b, a;
m_clr.GetColor( r, g, b, a );
a *= flAlphaModulate;
vgui::surface()->DrawSetColor( r, g, b, a );
if (yaw == 0)
{
if ( !m_bUseViewport )
{
vgui::surface()->DrawTexturedRect( x, y, x + wide, y + tall );
}
else
{
vgui::surface()->DrawTexturedSubRect( x, y, x + wide, y + tall,
m_rgViewport[ 0 ],
m_rgViewport[ 1 ],
m_rgViewport[ 2 ],
m_rgViewport[ 3 ]
);
}
}
else
{
// Rotated version of the bitmap!
// Rotate about the center of the bitmap
vgui::Vertex_t verts[4];
Vector2D center( x + (wide * 0.5f), y + (tall * 0.5f) );
// Choose a basis...
float yawRadians = -yaw * M_PI / 180.0f;
Vector2D axis[2];
axis[0].x = cos(yawRadians);
axis[0].y = sin(yawRadians);
axis[1].x = -axis[0].y;
axis[1].y = axis[0].x;
verts[0].m_TexCoord.Init( 0, 0 );
Vector2DMA( center, -0.5f * wide, axis[0], verts[0].m_Position );
Vector2DMA( verts[0].m_Position, -0.5f * tall, axis[1], verts[0].m_Position );
verts[1].m_TexCoord.Init( 1, 0 );
Vector2DMA( verts[0].m_Position, wide, axis[0], verts[1].m_Position );
verts[2].m_TexCoord.Init( 1, 1 );
Vector2DMA( verts[1].m_Position, tall, axis[1], verts[2].m_Position );
verts[3].m_TexCoord.Init( 0, 1 );
Vector2DMA( verts[0].m_Position, tall, axis[1], verts[3].m_Position );
vgui::surface()->DrawTexturedPolygon( 4, verts );
}
}
void BitmapImage::DoPaint( vgui::VPANEL pPanel, float yaw, float flAlphaModulate )
{
int wide, tall;
if ( pPanel )
{
vgui::ipanel()->GetSize(pPanel, wide, tall );
}
else
{
wide = m_Size[0];
tall = m_Size[1];
}
DoPaint( m_pos[0], m_pos[1], wide, tall, yaw, flAlphaModulate );
}
void BitmapImage::Paint()
{
DoPaint( m_pPanelSize );
}
void BitmapImage::SetColor( Color& clr )
{
m_clr = clr;
}
Color BitmapImage::GetColor( )
{
return m_clr;
}
void BitmapImage::GetColor( int& r,int& g,int& b,int& a )
{
m_clr.GetColor( r,g,b,a );
}
void BitmapImage::GetSize( int& wide, int& tall )
{
vgui::surface()->DrawGetTextureSize( m_nTextureId, wide, tall );
}
void BitmapImage::SetPos( int x, int y )
{
m_pos[ 0 ] = x;
m_pos[ 1 ] = y;
}
//-----------------------------------------------------------------------------
// Helper method to initialize a bitmap image from KeyValues data..
//-----------------------------------------------------------------------------
bool InitializeImage( KeyValues *pInitData, const char* pSectionName, vgui::Panel *pParent, BitmapImage* pBitmapImage )
{
KeyValues *pBitmapImageSection;
if (pSectionName)
{
pBitmapImageSection = pInitData->FindKey( pSectionName );
if ( !pBitmapImageSection )
return false;
}
else
{
pBitmapImageSection = pInitData;
}
return pBitmapImage->Init( pParent->GetVPanel(), pBitmapImageSection );
}
//-----------------------------------------------------------------------------
// FIXME: How sad. We need to make KeyValues + vgui::KeyValues be the same. Bleah
/*-----------------------------------------------------------------------------
bool InitializeImage( KeyValues *pInitData, const char* pSectionName, vgui::Panel *pParent, BitmapImage* pBitmapImage )
{
KeyValues *pBitmapImageSection;
if (pSectionName)
{
pBitmapImageSection = pInitData->FindKey( pSectionName );
if ( !pBitmapImageSection )
return false;
}
else
{
pBitmapImageSection = pInitData;
}
return pBitmapImage->Init( pParent->GetVPanel(), pBitmapImageSection );
} */
//-----------------------------------------------------------------------------
// Purpose:
// Input : use -
// left -
// top -
// right -
// bottom -
//-----------------------------------------------------------------------------
void BitmapImage::SetViewport( bool use, float left, float top, float right, float bottom )
{
m_bUseViewport = use;
m_rgViewport[ 0 ] = left;
m_rgViewport[ 1 ] = top;
m_rgViewport[ 2 ] = right;
m_rgViewport[ 3 ] = bottom;
}
<commit_msg>Fix memory leak when setting bitmap button image<commit_after>//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "vgui_bitmapimage.h"
#include <vgui_controls/Controls.h>
#include <vgui/ISurface.h>
#include <vgui_controls/Panel.h>
#include "panelmetaclassmgr.h"
#include <KeyValues.h>
#include <vgui/IPanel.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose: Check box image
//-----------------------------------------------------------------------------
BitmapImage::BitmapImage()
{
m_clr.SetColor( 255, 255, 255, 255 );
m_pos[ 0 ] = m_pos[ 1 ] = 0;
m_pPanelSize = NULL;
m_nTextureId = -1;
SetViewport( false, 0.0f, 0.0f, 0.0f, 0.0f );
}
BitmapImage::BitmapImage( vgui::VPANEL parent, const char *filename )
{
m_nTextureId = -1;
m_clr.SetColor( 255, 255, 255, 255 );
m_pos[ 0 ] = m_pos[ 1 ] = 0;
Init( parent, filename );
SetViewport( false, 0.0f, 0.0f, 0.0f, 0.0f );
}
bool BitmapImage::Init( vgui::VPANEL pParent, const char *pFileName )
{
UsePanelRenderSize( pParent );
int id = vgui::surface()->DrawGetTextureId(pFileName);
if (id > -1)
m_nTextureId = id;
else
m_nTextureId = vgui::surface()->CreateNewTextureID();
vgui::surface()->DrawSetTextureFile( m_nTextureId, pFileName , true, true);
GetSize( m_Size[0], m_Size[1] );
return true;
}
bool BitmapImage::Init( vgui::VPANEL pParent, KeyValues* pInitData )
{
char const* pMaterialName = pInitData->GetString( "material" );
if ( !pMaterialName || !pMaterialName[ 0 ] )
return false;
// modulation color
Color color;
if (!ParseRGBA( pInitData, "color", color ))
color.SetColor( 255, 255, 255, 255 );
Init( pParent, pMaterialName );
SetColor( color );
return true;
}
//-----------------------------------------------------------------------------
// FIXME: Bleah!!! Don't want two different KeyValues
/*-----------------------------------------------------------------------------
bool BitmapImage::Init( vgui::VPANEL pParent, KeyValues* pInitData )
{
char const* pMaterialName = pInitData->GetString( "material" );
if ( !pMaterialName || !pMaterialName[ 0 ] )
return false;
// modulation color
Color color;
if (!ParseRGBA( pInitData, "color", color ))
color.SetColor( 255, 255, 255, 255 );
Init( pParent, pMaterialName );
SetColor( color );
return true;
} */
void BitmapImage::SetImageFile( const char *newImage )
{
if ( m_nTextureId == -1 )
{
m_nTextureId = vgui::surface()->CreateNewTextureID();
}
vgui::surface()->DrawSetTextureFile( m_nTextureId, newImage , true, true);
}
void BitmapImage::UsePanelRenderSize( vgui::VPANEL pPanel )
{
m_pPanelSize = pPanel;
}
vgui::VPANEL BitmapImage::GetRenderSizePanel( void )
{
return m_pPanelSize;
}
void BitmapImage::SetRenderSize( int x, int y )
{
m_Size[0] = x;
m_Size[1] = y;
}
void BitmapImage::DoPaint( int x, int y, int wide, int tall, float yaw, float flAlphaModulate )
{
vgui::surface()->DrawSetTexture( m_nTextureId );
int r, g, b, a;
m_clr.GetColor( r, g, b, a );
a *= flAlphaModulate;
vgui::surface()->DrawSetColor( r, g, b, a );
if (yaw == 0)
{
if ( !m_bUseViewport )
{
vgui::surface()->DrawTexturedRect( x, y, x + wide, y + tall );
}
else
{
vgui::surface()->DrawTexturedSubRect( x, y, x + wide, y + tall,
m_rgViewport[ 0 ],
m_rgViewport[ 1 ],
m_rgViewport[ 2 ],
m_rgViewport[ 3 ]
);
}
}
else
{
// Rotated version of the bitmap!
// Rotate about the center of the bitmap
vgui::Vertex_t verts[4];
Vector2D center( x + (wide * 0.5f), y + (tall * 0.5f) );
// Choose a basis...
float yawRadians = -yaw * M_PI / 180.0f;
Vector2D axis[2];
axis[0].x = cos(yawRadians);
axis[0].y = sin(yawRadians);
axis[1].x = -axis[0].y;
axis[1].y = axis[0].x;
verts[0].m_TexCoord.Init( 0, 0 );
Vector2DMA( center, -0.5f * wide, axis[0], verts[0].m_Position );
Vector2DMA( verts[0].m_Position, -0.5f * tall, axis[1], verts[0].m_Position );
verts[1].m_TexCoord.Init( 1, 0 );
Vector2DMA( verts[0].m_Position, wide, axis[0], verts[1].m_Position );
verts[2].m_TexCoord.Init( 1, 1 );
Vector2DMA( verts[1].m_Position, tall, axis[1], verts[2].m_Position );
verts[3].m_TexCoord.Init( 0, 1 );
Vector2DMA( verts[0].m_Position, tall, axis[1], verts[3].m_Position );
vgui::surface()->DrawTexturedPolygon( 4, verts );
}
}
void BitmapImage::DoPaint( vgui::VPANEL pPanel, float yaw, float flAlphaModulate )
{
int wide, tall;
if ( pPanel )
{
vgui::ipanel()->GetSize(pPanel, wide, tall );
}
else
{
wide = m_Size[0];
tall = m_Size[1];
}
DoPaint( m_pos[0], m_pos[1], wide, tall, yaw, flAlphaModulate );
}
void BitmapImage::Paint()
{
DoPaint( m_pPanelSize );
}
void BitmapImage::SetColor( Color& clr )
{
m_clr = clr;
}
Color BitmapImage::GetColor( )
{
return m_clr;
}
void BitmapImage::GetColor( int& r,int& g,int& b,int& a )
{
m_clr.GetColor( r,g,b,a );
}
void BitmapImage::GetSize( int& wide, int& tall )
{
vgui::surface()->DrawGetTextureSize( m_nTextureId, wide, tall );
}
void BitmapImage::SetPos( int x, int y )
{
m_pos[ 0 ] = x;
m_pos[ 1 ] = y;
}
//-----------------------------------------------------------------------------
// Helper method to initialize a bitmap image from KeyValues data..
//-----------------------------------------------------------------------------
bool InitializeImage( KeyValues *pInitData, const char* pSectionName, vgui::Panel *pParent, BitmapImage* pBitmapImage )
{
KeyValues *pBitmapImageSection;
if (pSectionName)
{
pBitmapImageSection = pInitData->FindKey( pSectionName );
if ( !pBitmapImageSection )
return false;
}
else
{
pBitmapImageSection = pInitData;
}
return pBitmapImage->Init( pParent->GetVPanel(), pBitmapImageSection );
}
//-----------------------------------------------------------------------------
// FIXME: How sad. We need to make KeyValues + vgui::KeyValues be the same. Bleah
/*-----------------------------------------------------------------------------
bool InitializeImage( KeyValues *pInitData, const char* pSectionName, vgui::Panel *pParent, BitmapImage* pBitmapImage )
{
KeyValues *pBitmapImageSection;
if (pSectionName)
{
pBitmapImageSection = pInitData->FindKey( pSectionName );
if ( !pBitmapImageSection )
return false;
}
else
{
pBitmapImageSection = pInitData;
}
return pBitmapImage->Init( pParent->GetVPanel(), pBitmapImageSection );
} */
//-----------------------------------------------------------------------------
// Purpose:
// Input : use -
// left -
// top -
// right -
// bottom -
//-----------------------------------------------------------------------------
void BitmapImage::SetViewport( bool use, float left, float top, float right, float bottom )
{
m_bUseViewport = use;
m_rgViewport[ 0 ] = left;
m_rgViewport[ 1 ] = top;
m_rgViewport[ 2 ] = right;
m_rgViewport[ 3 ] = bottom;
}
<|endoftext|> |
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/painting/gradient.h"
#include "lib/tonic/converter/dart_converter.h"
#include "lib/tonic/dart_args.h"
#include "lib/tonic/dart_binding_macros.h"
#include "lib/tonic/dart_library_natives.h"
namespace blink {
typedef CanvasGradient
Gradient; // Because the C++ name doesn't match the Dart name.
static void Gradient_constructor(Dart_NativeArguments args) {
DartCallConstructor(&CanvasGradient::Create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, Gradient);
#define FOR_EACH_BINDING(V) \
V(Gradient, initLinear) \
V(Gradient, initRadial) \
V(Gradient, initSweep)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void CanvasGradient::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({{"Gradient_constructor", Gradient_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
fxl::RefPtr<CanvasGradient> CanvasGradient::Create() {
return fxl::MakeRefCounted<CanvasGradient>();
}
void CanvasGradient::initLinear(const tonic::Float32List& end_points,
const tonic::Int32List& colors,
const tonic::Float32List& color_stops,
SkShader::TileMode tile_mode) {
FXL_DCHECK(end_points.num_elements() == 4);
FXL_DCHECK(colors.num_elements() == color_stops.num_elements() ||
color_stops.data() == nullptr);
static_assert(sizeof(SkPoint) == sizeof(float) * 2,
"SkPoint doesn't use floats.");
static_assert(sizeof(SkColor) == sizeof(int32_t),
"SkColor doesn't use int32_t.");
set_shader(UIDartState::CreateGPUObject(SkGradientShader::MakeLinear(
reinterpret_cast<const SkPoint*>(end_points.data()),
reinterpret_cast<const SkColor*>(colors.data()), color_stops.data(),
colors.num_elements(), tile_mode)));
}
void CanvasGradient::initRadial(double center_x,
double center_y,
double radius,
const tonic::Int32List& colors,
const tonic::Float32List& color_stops,
SkShader::TileMode tile_mode,
const tonic::Float64List& matrix4) {
FXL_DCHECK(colors.num_elements() == color_stops.num_elements() ||
color_stops.data() == nullptr);
static_assert(sizeof(SkColor) == sizeof(int32_t),
"SkColor doesn't use int32_t.");
SkMatrix sk_matrix;
bool has_matrix = matrix4.data() != nullptr;
if (has_matrix) {
sk_matrix = ToSkMatrix(matrix4);
}
set_shader(UIDartState::CreateGPUObject(SkGradientShader::MakeRadial(
SkPoint::Make(center_x, center_y), radius,
reinterpret_cast<const SkColor*>(colors.data()), color_stops.data(),
colors.num_elements(), tile_mode, 0, has_matrix ? &sk_matrix : nullptr)));
}
void CanvasGradient::initSweep(double center_x,
double center_y,
const tonic::Int32List& colors,
const tonic::Float32List& color_stops,
SkShader::TileMode tile_mode,
double start_angle,
double end_angle,
const tonic::Float64List& matrix4) {
FXL_DCHECK(colors.num_elements() == color_stops.num_elements() ||
color_stops.data() == nullptr);
static_assert(sizeof(SkColor) == sizeof(int32_t),
"SkColor doesn't use int32_t.");
SkMatrix sk_matrix;
bool has_matrix = matrix4.data() != nullptr;
if (has_matrix) {
sk_matrix = ToSkMatrix(matrix4);
}
set_shader(SkGradientShader::MakeSweep(
center_x, center_y, reinterpret_cast<const SkColor*>(colors.data()),
color_stops.data(), colors.num_elements(), tile_mode,
start_angle * 180.0 / M_PI, end_angle * 180.0 / M_PI, 0,
has_matrix ? &sk_matrix : nullptr));
}
CanvasGradient::CanvasGradient() = default;
CanvasGradient::~CanvasGradient() = default;
} // namespace blink
<commit_msg>Use the GPU object constructor to create a gradient shader. (#5136)<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/painting/gradient.h"
#include "lib/tonic/converter/dart_converter.h"
#include "lib/tonic/dart_args.h"
#include "lib/tonic/dart_binding_macros.h"
#include "lib/tonic/dart_library_natives.h"
namespace blink {
typedef CanvasGradient
Gradient; // Because the C++ name doesn't match the Dart name.
static void Gradient_constructor(Dart_NativeArguments args) {
DartCallConstructor(&CanvasGradient::Create, args);
}
IMPLEMENT_WRAPPERTYPEINFO(ui, Gradient);
#define FOR_EACH_BINDING(V) \
V(Gradient, initLinear) \
V(Gradient, initRadial) \
V(Gradient, initSweep)
FOR_EACH_BINDING(DART_NATIVE_CALLBACK)
void CanvasGradient::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({{"Gradient_constructor", Gradient_constructor, 1, true},
FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}
fxl::RefPtr<CanvasGradient> CanvasGradient::Create() {
return fxl::MakeRefCounted<CanvasGradient>();
}
void CanvasGradient::initLinear(const tonic::Float32List& end_points,
const tonic::Int32List& colors,
const tonic::Float32List& color_stops,
SkShader::TileMode tile_mode) {
FXL_DCHECK(end_points.num_elements() == 4);
FXL_DCHECK(colors.num_elements() == color_stops.num_elements() ||
color_stops.data() == nullptr);
static_assert(sizeof(SkPoint) == sizeof(float) * 2,
"SkPoint doesn't use floats.");
static_assert(sizeof(SkColor) == sizeof(int32_t),
"SkColor doesn't use int32_t.");
set_shader(UIDartState::CreateGPUObject(SkGradientShader::MakeLinear(
reinterpret_cast<const SkPoint*>(end_points.data()),
reinterpret_cast<const SkColor*>(colors.data()), color_stops.data(),
colors.num_elements(), tile_mode)));
}
void CanvasGradient::initRadial(double center_x,
double center_y,
double radius,
const tonic::Int32List& colors,
const tonic::Float32List& color_stops,
SkShader::TileMode tile_mode,
const tonic::Float64List& matrix4) {
FXL_DCHECK(colors.num_elements() == color_stops.num_elements() ||
color_stops.data() == nullptr);
static_assert(sizeof(SkColor) == sizeof(int32_t),
"SkColor doesn't use int32_t.");
SkMatrix sk_matrix;
bool has_matrix = matrix4.data() != nullptr;
if (has_matrix) {
sk_matrix = ToSkMatrix(matrix4);
}
set_shader(UIDartState::CreateGPUObject(SkGradientShader::MakeRadial(
SkPoint::Make(center_x, center_y), radius,
reinterpret_cast<const SkColor*>(colors.data()), color_stops.data(),
colors.num_elements(), tile_mode, 0, has_matrix ? &sk_matrix : nullptr)));
}
void CanvasGradient::initSweep(double center_x,
double center_y,
const tonic::Int32List& colors,
const tonic::Float32List& color_stops,
SkShader::TileMode tile_mode,
double start_angle,
double end_angle,
const tonic::Float64List& matrix4) {
FXL_DCHECK(colors.num_elements() == color_stops.num_elements() ||
color_stops.data() == nullptr);
static_assert(sizeof(SkColor) == sizeof(int32_t),
"SkColor doesn't use int32_t.");
SkMatrix sk_matrix;
bool has_matrix = matrix4.data() != nullptr;
if (has_matrix) {
sk_matrix = ToSkMatrix(matrix4);
}
set_shader(UIDartState::CreateGPUObject(SkGradientShader::MakeSweep(
center_x, center_y, reinterpret_cast<const SkColor*>(colors.data()),
color_stops.data(), colors.num_elements(), tile_mode,
start_angle * 180.0 / M_PI, end_angle * 180.0 / M_PI, 0,
has_matrix ? &sk_matrix : nullptr)));
}
CanvasGradient::CanvasGradient() = default;
CanvasGradient::~CanvasGradient() = default;
} // namespace blink
<|endoftext|> |
<commit_before>/*
This file is part of the CVD Library.
Copyright (C) 2005 The Authors
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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "cvd/internal/io/fits.h"
#include "cvd/image_io.h"
#include "cvd/config.h"
#include <algorithm>
#include <vector>
#include <deque>
#include <iostream>
#include <sstream>
using namespace CVD;
using namespace CVD::FITS;
using namespace CVD::Exceptions::Image_IO;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
//
// Private implementation of FITS reading
//
////////////////////////////////////////////////////////////////////////////////
//
// Useful string manipulation functions
//
//Trim off whitespace on the right hand side
static string rtrim(string str)
{
string ws (" \t\f\v\n\r");
size_t pos;
pos=str.find_last_not_of(ws);
if (pos!=string::npos)
str.erase(pos+1);
else
str.clear();
return str;
}
//Trim off whitespace on the left hand side
static string ltrim(const string& str)
{
string ws (" \t\f\v\n\r");
size_t pos;
pos=str.find_first_not_of(ws);
if (pos!=string::npos)
return string(str.begin()+pos, str.end());
else
return "";
}
static bool get_bool(const string& s)
{
if(s == "T")
return 1;
else if (s == "F")
return 0;
else
throw(Exceptions::Image_IO::MalformedImage("Invalid boolean: `" + s + "'"));
}
static int get_int(const string& s)
{
int i;
istringstream is(s);
is >> i;
if(s.size() == 0 || is.bad())
throw(Exceptions::Image_IO::MalformedImage("Invalid integer: `" + s + "'"));
return i;
}
static int get_uint(const string& s)
{
unsigned int i;
istringstream is(s);
is >> i;
if(s.size() == 0 || is.bad())
throw(Exceptions::Image_IO::MalformedImage("Invalid unsigned integer: `" + s + "'"));
return i;
}
static double get_double(const string& s)
{
double i;
istringstream is(s);
is >> i;
if(s.size() == 0 || is.bad())
throw(Exceptions::Image_IO::MalformedImage("Invalid double: `" + s + "'"));
return i;
}
////////////////////////////////////////////////////////////////////////////////
//
// Private implementation of FITS reading
//
class CVD::FITS::ReadPimpl
{
public:
ReadPimpl(istream&);
~ReadPimpl();
ImageRef size();
string datatype();
template<class C> void get_raw_pixel_line(C* data);
template<class C> void convert_raw_pixel_line(unsigned char*, C* data);
template<template<class> class C> void convert_raw_pixel_line(unsigned char*, C<unsigned short>* data);
void convert_raw_pixel_line(unsigned char*, unsigned short* data);
private:
istream& i;
unsigned long row;
ImageRef my_size;
string type;
//HDU is the FITS term: header description units.
//The HDU has multiple 36 card stacks of 80 column cards.
//which is 2880 bytes
char HDU_card_stack[2880], *card;
void next_card()
{
if(card != NULL)
card += 80;
if(card == NULL || card == HDU_card_stack + 2880)
{
i.read(HDU_card_stack, 2880);
if(i.eof())
throw(Exceptions::Image_IO::MalformedImage("EOF in header."));
card = HDU_card_stack;
}
}
bool match_card_start(const string& s)
{
if(s.size() > 80)
return 0;
return equal(s.begin(), s.end(), card);
}
//keywords are left justified, in columns 1--8
string get_keyword()
{
string k;
k.resize(8);
copy(card, card+8, k.begin());
return rtrim(k);
}
void check_for_seperator()
{
if(card[8] != '=' || card[9] != ' ')
throw(Exceptions::Image_IO::MalformedImage("Missing `= ' separator in card."));
}
void expect_keyword(const string& k)
{
check_for_seperator();
if(k != get_keyword())
throw Exceptions::Image_IO::MalformedImage("FITS images missing "+k+"(got" + get_keyword() + ")");
}
//numeric fields are right justified, in columns 11--30
string get_numeric_field()
{
string f;
f.resize(20);
copy(card+10, card+30, f.begin());
return ltrim(f);
}
vector<unsigned char> data;
int bytes_per_pixel;
};
template<class T> void ReadPimpl::get_raw_pixel_line(T* d)
{
if(datatype() != PNM::type_name<T>::name())
throw ReadTypeMismatch(datatype(), PNM::type_name<T>::name());
if(row > (unsigned long)my_size.y)
throw InternalLibraryError("CVD", "Read past end of image.");
unsigned char* rowp = &data[row * bytes_per_pixel * my_size.x];
row++;
convert_raw_pixel_line(rowp, d);
}
template<class T> void ReadPimpl::convert_raw_pixel_line(unsigned char* rowp, T* d)
{
copy(rowp, rowp + my_size.x * bytes_per_pixel, (unsigned char*)(d));
}
template<template<class> class T> void ReadPimpl::convert_raw_pixel_line(unsigned char* rowp, T<unsigned short>* d)
{
unsigned short* ds = (unsigned short*)d;
int elements=my_size.x * sizeof(T<unsigned short>)/sizeof(unsigned short);
for(int i=0; i < elements; i++)
ds[i] = (unsigned short)(static_cast<int>( ((short*)(rowp))[i]) + 32768);
}
void ReadPimpl::convert_raw_pixel_line(unsigned char* rowp, unsigned short* d)
{
for(int i=0; i < my_size.x; i++)
d[i] = (unsigned short)(static_cast<int>( ((short*)(rowp))[i]) + 32768);
}
string ReadPimpl::datatype()
{
return type;
}
ImageRef ReadPimpl::size()
{
return my_size;
}
ReadPimpl::~ReadPimpl()
{
}
ReadPimpl::ReadPimpl(istream& is)
:i(is),row(0),card(NULL)
{
next_card();
if(!match_card_start("SIMPLE = T"))
throw(Exceptions::Image_IO::MalformedImage("FITS images must start with \"SIMPLE = T\""));
next_card();
expect_keyword("BITPIX");
int bpp = get_int(get_numeric_field());
if(bpp == 8)
type = PNM::type_name<byte>::name();
else if(bpp == 16)
type = PNM::type_name<short>::name();
else if(bpp == 32)
type = PNM::type_name<int>::name();
else if(bpp == -32)
type = PNM::type_name<float>::name();
else if(bpp == -64)
type = PNM::type_name<double>::name();
else
throw Exceptions::Image_IO::MalformedImage("FITS images has unrecognised BITPIX (" + get_numeric_field() + ")");
unsigned int num_axes;
next_card();
expect_keyword("NAXIS");
num_axes=get_uint(get_numeric_field());
if(num_axes < 1 || num_axes>3)
throw Exceptions::Image_IO::UnsupportedImageSubType("FITS", get_numeric_field() + " axes given (1, 2 or 3 supported).");
//Read in the axis lengths
//select obvious defailts for missing axes
int a1=0, a2=1, a3=1;
next_card();
expect_keyword("NAXIS1");
a1 = get_uint(get_numeric_field());
if(num_axes > 1)
{
next_card();
expect_keyword("NAXIS2");
a2 = get_uint(get_numeric_field());
if(num_axes > 2)
{
next_card();
expect_keyword("NAXIS3");
a3 = get_uint(get_numeric_field());
}
}
my_size.x = a1;
my_size.y = a2;
double add_for_zero=0;
string bzero;
//Read the rest of the header
//The last useful card has END as the first keyword, but no separator.
//The remaining cards in the current stack should be blank.
//Since we read a stack at a time, the read pointer will be in the
//correct place.
for(;;)
{
next_card();
if(get_keyword() == "BZERO")
{
check_for_seperator();
add_for_zero = get_double(bzero=get_numeric_field());
}
else if(get_keyword() == "END")
break;
}
cerr << add_for_zero << endl;
if(add_for_zero == 0) //OK
{}
else if(add_for_zero == 32768. && bpp == 16)
type = "unsigned short";
else
throw Exceptions::Image_IO::UnsupportedImageSubType("FITS", "BZERO is " + bzero + ". Only 0 or 32768 (for int16 images) supported");
//Figure out the colourspace
if(a3 == 1)
type = type;
else if(a3 == 2)
type = "CVD::GreyAlpha<" + type + ">";
else if(a3 == 3)
type = "CVD::Rgb<" + type + ">";
else if(a3 == 4)
type = "CVD::Rgba<" + type + ">";
else
throw Exceptions::Image_IO::UnsupportedImageSubType("FITS", "3rd axis (colour planes) has"+ get_numeric_field() + " elements(1, 2, 3 or 4 supported).");
//We should really use BZERO, too.
//Images are planar. So, deplanarize here.
//Also, correct the endianness
//FIXME this could be much more efficient.
bpp = abs(bpp)/8;
size_t nelems = a1 * a2 * a3;
size_t nbytes = nelems * bpp;
vector<unsigned char> raw_data;
raw_data.resize(nbytes);
data.resize(nbytes);
i.read((char*)(&raw_data[0]), nbytes);
if(i.eof())
throw(Exceptions::Image_IO::MalformedImage("EOF in image."));
//Make the data follow the native byte ordering
#ifdef CVD_ARCH_LITTLE_ENDIAN
for(size_t i=0; i < nelems; i++)
reverse(&raw_data[i*bpp], &raw_data[i*bpp] + bpp);
#endif
//Convert planar to inline
for(int c=0; c < a1; c++)
for(int r=0; r < a2; r++)
for(int p=0; p < a3; p++)
for(int b=0; b < bpp; b++)
data[((r * a1 + c)*a3 + p)*bpp + b] = raw_data[p*a1*a2*bpp+ (r*a1+c)*bpp+b];
bytes_per_pixel = a3 * bpp;
}
////////////////////////////////////////////////////////////////////////////////
//
// Implementation of public parts of TIFF reading
//
reader::reader(istream& i)
:t(new ReadPimpl(i))
{}
reader::~reader()
{
}
string reader::datatype()
{
return t->datatype();
}
string reader::name()
{
return "FITS";
}
ImageRef reader::size()
{
return t->size();
};
//Mechanically generate the pixel reading calls.
#define GEN1(X) void reader::get_raw_pixel_line(X*d){t->get_raw_pixel_line(d);}
#define GEN3(X) GEN1(X) GEN1(Rgb<X>) GEN1(Rgba<X>)
GEN3(unsigned char)
GEN3(signed short)
GEN3(unsigned short)
GEN3(signed int)
GEN3(float)
GEN3(double)
<commit_msg>Removed debugging.<commit_after>/*
This file is part of the CVD Library.
Copyright (C) 2005 The Authors
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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "cvd/internal/io/fits.h"
#include "cvd/image_io.h"
#include "cvd/config.h"
#include <algorithm>
#include <vector>
#include <deque>
#include <iostream>
#include <sstream>
using namespace CVD;
using namespace CVD::FITS;
using namespace CVD::Exceptions::Image_IO;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
//
// Private implementation of FITS reading
//
////////////////////////////////////////////////////////////////////////////////
//
// Useful string manipulation functions
//
//Trim off whitespace on the right hand side
static string rtrim(string str)
{
string ws (" \t\f\v\n\r");
size_t pos;
pos=str.find_last_not_of(ws);
if (pos!=string::npos)
str.erase(pos+1);
else
str.clear();
return str;
}
//Trim off whitespace on the left hand side
static string ltrim(const string& str)
{
string ws (" \t\f\v\n\r");
size_t pos;
pos=str.find_first_not_of(ws);
if (pos!=string::npos)
return string(str.begin()+pos, str.end());
else
return "";
}
static bool get_bool(const string& s)
{
if(s == "T")
return 1;
else if (s == "F")
return 0;
else
throw(Exceptions::Image_IO::MalformedImage("Invalid boolean: `" + s + "'"));
}
static int get_int(const string& s)
{
int i;
istringstream is(s);
is >> i;
if(s.size() == 0 || is.bad())
throw(Exceptions::Image_IO::MalformedImage("Invalid integer: `" + s + "'"));
return i;
}
static int get_uint(const string& s)
{
unsigned int i;
istringstream is(s);
is >> i;
if(s.size() == 0 || is.bad())
throw(Exceptions::Image_IO::MalformedImage("Invalid unsigned integer: `" + s + "'"));
return i;
}
static double get_double(const string& s)
{
double i;
istringstream is(s);
is >> i;
if(s.size() == 0 || is.bad())
throw(Exceptions::Image_IO::MalformedImage("Invalid double: `" + s + "'"));
return i;
}
////////////////////////////////////////////////////////////////////////////////
//
// Private implementation of FITS reading
//
class CVD::FITS::ReadPimpl
{
public:
ReadPimpl(istream&);
~ReadPimpl();
ImageRef size();
string datatype();
template<class C> void get_raw_pixel_line(C* data);
template<class C> void convert_raw_pixel_line(unsigned char*, C* data);
template<template<class> class C> void convert_raw_pixel_line(unsigned char*, C<unsigned short>* data);
void convert_raw_pixel_line(unsigned char*, unsigned short* data);
private:
istream& i;
unsigned long row;
ImageRef my_size;
string type;
//HDU is the FITS term: header description units.
//The HDU has multiple 36 card stacks of 80 column cards.
//which is 2880 bytes
char HDU_card_stack[2880], *card;
void next_card()
{
if(card != NULL)
card += 80;
if(card == NULL || card == HDU_card_stack + 2880)
{
i.read(HDU_card_stack, 2880);
if(i.eof())
throw(Exceptions::Image_IO::MalformedImage("EOF in header."));
card = HDU_card_stack;
}
}
bool match_card_start(const string& s)
{
if(s.size() > 80)
return 0;
return equal(s.begin(), s.end(), card);
}
//keywords are left justified, in columns 1--8
string get_keyword()
{
string k;
k.resize(8);
copy(card, card+8, k.begin());
return rtrim(k);
}
void check_for_seperator()
{
if(card[8] != '=' || card[9] != ' ')
throw(Exceptions::Image_IO::MalformedImage("Missing `= ' separator in card."));
}
void expect_keyword(const string& k)
{
check_for_seperator();
if(k != get_keyword())
throw Exceptions::Image_IO::MalformedImage("FITS images missing "+k+"(got" + get_keyword() + ")");
}
//numeric fields are right justified, in columns 11--30
string get_numeric_field()
{
string f;
f.resize(20);
copy(card+10, card+30, f.begin());
return ltrim(f);
}
vector<unsigned char> data;
int bytes_per_pixel;
};
template<class T> void ReadPimpl::get_raw_pixel_line(T* d)
{
if(datatype() != PNM::type_name<T>::name())
throw ReadTypeMismatch(datatype(), PNM::type_name<T>::name());
if(row > (unsigned long)my_size.y)
throw InternalLibraryError("CVD", "Read past end of image.");
unsigned char* rowp = &data[row * bytes_per_pixel * my_size.x];
row++;
convert_raw_pixel_line(rowp, d);
}
template<class T> void ReadPimpl::convert_raw_pixel_line(unsigned char* rowp, T* d)
{
copy(rowp, rowp + my_size.x * bytes_per_pixel, (unsigned char*)(d));
}
template<template<class> class T> void ReadPimpl::convert_raw_pixel_line(unsigned char* rowp, T<unsigned short>* d)
{
unsigned short* ds = (unsigned short*)d;
int elements=my_size.x * sizeof(T<unsigned short>)/sizeof(unsigned short);
for(int i=0; i < elements; i++)
ds[i] = (unsigned short)(static_cast<int>( ((short*)(rowp))[i]) + 32768);
}
void ReadPimpl::convert_raw_pixel_line(unsigned char* rowp, unsigned short* d)
{
for(int i=0; i < my_size.x; i++)
d[i] = (unsigned short)(static_cast<int>( ((short*)(rowp))[i]) + 32768);
}
string ReadPimpl::datatype()
{
return type;
}
ImageRef ReadPimpl::size()
{
return my_size;
}
ReadPimpl::~ReadPimpl()
{
}
ReadPimpl::ReadPimpl(istream& is)
:i(is),row(0),card(NULL)
{
next_card();
if(!match_card_start("SIMPLE = T"))
throw(Exceptions::Image_IO::MalformedImage("FITS images must start with \"SIMPLE = T\""));
next_card();
expect_keyword("BITPIX");
int bpp = get_int(get_numeric_field());
if(bpp == 8)
type = PNM::type_name<byte>::name();
else if(bpp == 16)
type = PNM::type_name<short>::name();
else if(bpp == 32)
type = PNM::type_name<int>::name();
else if(bpp == -32)
type = PNM::type_name<float>::name();
else if(bpp == -64)
type = PNM::type_name<double>::name();
else
throw Exceptions::Image_IO::MalformedImage("FITS images has unrecognised BITPIX (" + get_numeric_field() + ")");
unsigned int num_axes;
next_card();
expect_keyword("NAXIS");
num_axes=get_uint(get_numeric_field());
if(num_axes < 1 || num_axes>3)
throw Exceptions::Image_IO::UnsupportedImageSubType("FITS", get_numeric_field() + " axes given (1, 2 or 3 supported).");
//Read in the axis lengths
//select obvious defailts for missing axes
int a1=0, a2=1, a3=1;
next_card();
expect_keyword("NAXIS1");
a1 = get_uint(get_numeric_field());
if(num_axes > 1)
{
next_card();
expect_keyword("NAXIS2");
a2 = get_uint(get_numeric_field());
if(num_axes > 2)
{
next_card();
expect_keyword("NAXIS3");
a3 = get_uint(get_numeric_field());
}
}
my_size.x = a1;
my_size.y = a2;
double add_for_zero=0;
string bzero;
//Read the rest of the header
//The last useful card has END as the first keyword, but no separator.
//The remaining cards in the current stack should be blank.
//Since we read a stack at a time, the read pointer will be in the
//correct place.
for(;;)
{
next_card();
if(get_keyword() == "BZERO")
{
check_for_seperator();
add_for_zero = get_double(bzero=get_numeric_field());
}
else if(get_keyword() == "END")
break;
}
if(add_for_zero == 0) //OK
{}
else if(add_for_zero == 32768. && bpp == 16)
type = "unsigned short";
else
throw Exceptions::Image_IO::UnsupportedImageSubType("FITS", "BZERO is " + bzero + ". Only 0 or 32768 (for int16 images) supported");
//Figure out the colourspace
if(a3 == 1)
type = type;
else if(a3 == 2)
type = "CVD::GreyAlpha<" + type + ">";
else if(a3 == 3)
type = "CVD::Rgb<" + type + ">";
else if(a3 == 4)
type = "CVD::Rgba<" + type + ">";
else
throw Exceptions::Image_IO::UnsupportedImageSubType("FITS", "3rd axis (colour planes) has"+ get_numeric_field() + " elements(1, 2, 3 or 4 supported).");
//We should really use BZERO, too.
//Images are planar. So, deplanarize here.
//Also, correct the endianness
//FIXME this could be much more efficient.
bpp = abs(bpp)/8;
size_t nelems = a1 * a2 * a3;
size_t nbytes = nelems * bpp;
vector<unsigned char> raw_data;
raw_data.resize(nbytes);
data.resize(nbytes);
i.read((char*)(&raw_data[0]), nbytes);
if(i.eof())
throw(Exceptions::Image_IO::MalformedImage("EOF in image."));
//Make the data follow the native byte ordering
#ifdef CVD_ARCH_LITTLE_ENDIAN
for(size_t i=0; i < nelems; i++)
reverse(&raw_data[i*bpp], &raw_data[i*bpp] + bpp);
#endif
//Convert planar to inline
for(int c=0; c < a1; c++)
for(int r=0; r < a2; r++)
for(int p=0; p < a3; p++)
for(int b=0; b < bpp; b++)
data[((r * a1 + c)*a3 + p)*bpp + b] = raw_data[p*a1*a2*bpp+ (r*a1+c)*bpp+b];
bytes_per_pixel = a3 * bpp;
}
////////////////////////////////////////////////////////////////////////////////
//
// Implementation of public parts of TIFF reading
//
reader::reader(istream& i)
:t(new ReadPimpl(i))
{}
reader::~reader()
{
}
string reader::datatype()
{
return t->datatype();
}
string reader::name()
{
return "FITS";
}
ImageRef reader::size()
{
return t->size();
};
//Mechanically generate the pixel reading calls.
#define GEN1(X) void reader::get_raw_pixel_line(X*d){t->get_raw_pixel_line(d);}
#define GEN3(X) GEN1(X) GEN1(Rgb<X>) GEN1(Rgba<X>)
GEN3(unsigned char)
GEN3(signed short)
GEN3(unsigned short)
GEN3(signed int)
GEN3(float)
GEN3(double)
<|endoftext|> |
<commit_before>/* zesto-prefetch.cpp - Zesto cache prefetcher class
*
* Copyright 2009 by Gabriel H. Loh and the Georgia Tech Research Corporation
* Atlanta, GA 30332-0415
* All Rights Reserved.
*
* THIS IS A LEGAL DOCUMENT BY DOWNLOADING ZESTO, YOU ARE AGREEING TO THESE
* TERMS AND CONDITIONS.
*
* 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 OWNERS 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.
*
* NOTE: Portions of this release are directly derived from the SimpleScalar
* Toolset (property of SimpleScalar LLC), and as such, those portions are
* bound by the corresponding legal terms and conditions. All source files
* derived directly or in part from the SimpleScalar Toolset bear the original
* user agreement.
*
* 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.
*
* 3. Neither the name of the Georgia Tech Research Corporation nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 4. Zesto is distributed freely for commercial and non-commercial use. Note,
* however, that the portions derived from the SimpleScalar Toolset are bound
* by the terms and agreements set forth by SimpleScalar, LLC. In particular:
*
* "Nonprofit and noncommercial use is encouraged. SimpleScalar may be
* downloaded, compiled, executed, copied, and modified solely for nonprofit,
* educational, noncommercial research, and noncommercial scholarship
* purposes provided that this notice in its entirety accompanies all copies.
* Copies of the modified software can be delivered to persons who use it
* solely for nonprofit, educational, noncommercial research, and
* noncommercial scholarship purposes provided that this notice in its
* entirety accompanies all copies."
*
* User is responsible for reading and adhering to the terms set forth by
* SimpleScalar, LLC where appropriate.
*
* 5. No nonprofit user may place any restrictions on the use of this software,
* including as modified by the user, by any other authorized user.
*
* 6. Noncommercial and nonprofit users may distribute copies of Zesto in
* compiled or executable form as set forth in Section 2, provided that either:
* (A) it is accompanied by the corresponding machine-readable source code, or
* (B) it is accompanied by a written offer, with no time limit, to give anyone
* a machine-readable copy of the corresponding source code in return for
* reimbursement of the cost of distribution. This written offer must permit
* verbatim duplication by anyone, or (C) it is distributed by someone who
* received only the executable form, and is accompanied by a copy of the
* written offer of source code.
*
* 7. Zesto was developed by Gabriel H. Loh, Ph.D. US Mail: 266 Ferst Drive,
* Georgia Institute of Technology, Atlanta, GA 30332-0765
*/
#include <iostream>
#include "sim.h"
#include "stats.h"
#include "valcheck.h"
#include "zesto-opts.h"
#include "zesto-core.h"
#include "zesto-bpred.h"
#include "zesto-cache.h"
#include "zesto-prefetch.h"
#include "zesto-uncore.h"
using namespace std;
void prefetch_t::init(void)
{
cp = NULL;
type = NULL;
bits = 0;
lookups = 0;
}
prefetch_t::prefetch_t(void)
{
init();
}
prefetch_t::~prefetch_t()
{
if(type) free(type);
type = NULL;
}
/* The default prefetcher stats printing function. */
void
prefetch_t::reg_stats(
struct stat_sdb_t * const sdb,
const struct core_t * const core)
{
char buf[256];
char buf2[256];
char buf3[256];
char core_str[256];
if(core == NULL)
core_str[0] = 0; /* empty string */
else
sprintf(core_str,"c%d.",core->current_thread->id);
sprintf(buf,"%s%s.%s.bits",core_str,cp->name,type);
sprintf(buf2,"total size of %s in bits",type);
stat_reg_int(sdb, true, buf, buf2, &bits, bits, FALSE, NULL);
sprintf(buf,"%s%s.%s.size",core_str,cp->name,type);
sprintf(buf2,"total size of %s in KB",type);
sprintf(buf3,"%s%s.%s.bits / 8192.0",core_str,cp->name,type);
stat_reg_formula(sdb, true, buf, buf2, buf3, NULL);
sprintf(buf,"%s%s.%s.lookups",core_str,cp->name,type);
sprintf(buf2,"number of prediction lookups in %s",type);
stat_reg_counter(sdb, true, buf, buf2, &lookups, lookups, FALSE, NULL);
}
/*========================================================*/
/* The definitions are all placed in separate files, for
organizational purposes. */
/*========================================================*/
/*
Arguments:
PC - load's program counter (PC) value
paddr - physical address load is reading from
*/
#define PREFETCH_LOOKUP_HEADER \
md_paddr_t lookup(const md_addr_t PC, const md_paddr_t paddr)
#define PREFETCH_REG_STATS_HEADER \
void reg_stats(struct stat_sdb_t * const sdb, const struct core_t * const core)
#include "ZCOMPS-prefetch.list"
#define PREFETCH_PARSE_ARGS
/*====================================================*/
/* argument parsing */
/*====================================================*/
struct prefetch_t *
prefetch_create(const char * const opt_string, struct cache_t * const cp)
{
char type[256];
/* the format string "%[^:]" for scanf reads a string consisting of non-':' characters */
if(sscanf(opt_string,"%[^:]",type) != 1)
fatal("malformed prefetch option string: %s",opt_string);
if(!strcasecmp(type,"none"))
return NULL;
cerr << "[KEVIN] FORCING ALL PREFETCHING TO NONE IN SOURCE" << endl;
return NULL;
/* include the argument parsing code. PREFETCH_PARSE_ARGS is defined to
include only the parsing code and not the other prefetcher code. */
#include "ZCOMPS-prefetch.list"
/* UNKNOWN prefetch Type */
fatal("Unknown prefetcher type (%s)",opt_string);
}
#undef PREFETCH_PARSE_ARGS
<commit_msg>Put prefetchers back in<commit_after>/* zesto-prefetch.cpp - Zesto cache prefetcher class
*
* Copyright 2009 by Gabriel H. Loh and the Georgia Tech Research Corporation
* Atlanta, GA 30332-0415
* All Rights Reserved.
*
* THIS IS A LEGAL DOCUMENT BY DOWNLOADING ZESTO, YOU ARE AGREEING TO THESE
* TERMS AND CONDITIONS.
*
* 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 OWNERS 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.
*
* NOTE: Portions of this release are directly derived from the SimpleScalar
* Toolset (property of SimpleScalar LLC), and as such, those portions are
* bound by the corresponding legal terms and conditions. All source files
* derived directly or in part from the SimpleScalar Toolset bear the original
* user agreement.
*
* 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.
*
* 3. Neither the name of the Georgia Tech Research Corporation nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 4. Zesto is distributed freely for commercial and non-commercial use. Note,
* however, that the portions derived from the SimpleScalar Toolset are bound
* by the terms and agreements set forth by SimpleScalar, LLC. In particular:
*
* "Nonprofit and noncommercial use is encouraged. SimpleScalar may be
* downloaded, compiled, executed, copied, and modified solely for nonprofit,
* educational, noncommercial research, and noncommercial scholarship
* purposes provided that this notice in its entirety accompanies all copies.
* Copies of the modified software can be delivered to persons who use it
* solely for nonprofit, educational, noncommercial research, and
* noncommercial scholarship purposes provided that this notice in its
* entirety accompanies all copies."
*
* User is responsible for reading and adhering to the terms set forth by
* SimpleScalar, LLC where appropriate.
*
* 5. No nonprofit user may place any restrictions on the use of this software,
* including as modified by the user, by any other authorized user.
*
* 6. Noncommercial and nonprofit users may distribute copies of Zesto in
* compiled or executable form as set forth in Section 2, provided that either:
* (A) it is accompanied by the corresponding machine-readable source code, or
* (B) it is accompanied by a written offer, with no time limit, to give anyone
* a machine-readable copy of the corresponding source code in return for
* reimbursement of the cost of distribution. This written offer must permit
* verbatim duplication by anyone, or (C) it is distributed by someone who
* received only the executable form, and is accompanied by a copy of the
* written offer of source code.
*
* 7. Zesto was developed by Gabriel H. Loh, Ph.D. US Mail: 266 Ferst Drive,
* Georgia Institute of Technology, Atlanta, GA 30332-0765
*/
#include <iostream>
#include "sim.h"
#include "stats.h"
#include "valcheck.h"
#include "zesto-opts.h"
#include "zesto-core.h"
#include "zesto-bpred.h"
#include "zesto-cache.h"
#include "zesto-prefetch.h"
#include "zesto-uncore.h"
using namespace std;
void prefetch_t::init(void)
{
cp = NULL;
type = NULL;
bits = 0;
lookups = 0;
}
prefetch_t::prefetch_t(void)
{
init();
}
prefetch_t::~prefetch_t()
{
if(type) free(type);
type = NULL;
}
/* The default prefetcher stats printing function. */
void
prefetch_t::reg_stats(
struct stat_sdb_t * const sdb,
const struct core_t * const core)
{
char buf[256];
char buf2[256];
char buf3[256];
char core_str[256];
if(core == NULL)
core_str[0] = 0; /* empty string */
else
sprintf(core_str,"c%d.",core->current_thread->id);
sprintf(buf,"%s%s.%s.bits",core_str,cp->name,type);
sprintf(buf2,"total size of %s in bits",type);
stat_reg_int(sdb, true, buf, buf2, &bits, bits, FALSE, NULL);
sprintf(buf,"%s%s.%s.size",core_str,cp->name,type);
sprintf(buf2,"total size of %s in KB",type);
sprintf(buf3,"%s%s.%s.bits / 8192.0",core_str,cp->name,type);
stat_reg_formula(sdb, true, buf, buf2, buf3, NULL);
sprintf(buf,"%s%s.%s.lookups",core_str,cp->name,type);
sprintf(buf2,"number of prediction lookups in %s",type);
stat_reg_counter(sdb, true, buf, buf2, &lookups, lookups, FALSE, NULL);
}
/*========================================================*/
/* The definitions are all placed in separate files, for
organizational purposes. */
/*========================================================*/
/*
Arguments:
PC - load's program counter (PC) value
paddr - physical address load is reading from
*/
#define PREFETCH_LOOKUP_HEADER \
md_paddr_t lookup(const md_addr_t PC, const md_paddr_t paddr)
#define PREFETCH_REG_STATS_HEADER \
void reg_stats(struct stat_sdb_t * const sdb, const struct core_t * const core)
#include "ZCOMPS-prefetch.list"
#define PREFETCH_PARSE_ARGS
/*====================================================*/
/* argument parsing */
/*====================================================*/
struct prefetch_t *
prefetch_create(const char * const opt_string, struct cache_t * const cp)
{
char type[256];
/* the format string "%[^:]" for scanf reads a string consisting of non-':' characters */
if(sscanf(opt_string,"%[^:]",type) != 1)
fatal("malformed prefetch option string: %s",opt_string);
if(!strcasecmp(type,"none"))
return NULL;
/* include the argument parsing code. PREFETCH_PARSE_ARGS is defined to
include only the parsing code and not the other prefetcher code. */
#include "ZCOMPS-prefetch.list"
/* UNKNOWN prefetch Type */
fatal("Unknown prefetcher type (%s)",opt_string);
}
#undef PREFETCH_PARSE_ARGS
<|endoftext|> |
<commit_before>//!
//! @author Yue Wang
//! @date 18 Sep 2014
//!
//! ex2.4.1.a
//! parse
//! S -> '+' S S | '-' S S | 'a'
//!
#include <iostream>
#include <string>
#include <functional>
namespace dragon{ namespace ch2{
/**
* @brief parse_241a
* @param first
* @param last
* @return true if legal, false otherwise.
*/
template<typename Iter>
inline bool parse_241a(Iter first, Iter last)
{
bool is_legal = true;
//! define lambda s for real work
std::function<Iter(Iter)> s = [&](Iter curr)
{
if(curr == last)
{
is_legal = false;
return last;
}
if(*curr == 'a')
return curr + 1;
else if(*curr == '+' || *curr == '-')
return s(s(curr + 1));
else
{
is_legal = false;
return last;
}
};
//! @brief call lambda s and return result
//!
//! @note since lamda s cover all the possibilites, the iterator
//! returned by a legal input must point to last.
return is_legal && s(first) == last;
}
}}//namespace
int main()
{
std::cout << "pls enter, following : S -> '+' S S | '-' S S | 'a'\n";
for(std::string buff; std::cin >> buff; /* */)
{
bool is_legal = dragon::ch2::parse_241a(buff.begin(),buff.end());
std::cout << "@parser ex2.4.1.a --> "
<< (is_legal? "legal\n" : "syntax error\n");
}
return 0;
}
<commit_msg> modified: ch02/ex2_4_1a.cpp for readibility.<commit_after>//!
//! @author Yue Wang
//! @date 18 Sep 2014
//!
//! ex2.4.1.a
//! parse
//! S -> '+' S S | '-' S S | 'a'
//!
#include <iostream>
#include <string>
#include <functional>
namespace dragon{ namespace ch2{
/**
* @brief parse_241a
* @param first
* @param last
* @return true if legal, false otherwise.
*/
template<typename Iter>
inline bool parse_241a(Iter first, Iter last)
{
bool is_legal = true;
//! define lambda s for real work
std::function<Iter(Iter)> s = [&](Iter curr)
{
if(curr == last)
{
is_legal = false;
return last;
}
if(*curr == 'a')
return curr + 1;
else if(*curr == '+' || *curr == '-')
return s(s(curr + 1));
else
{
is_legal = false;
return last;
}
};
//! @note since lamda s cover all the possibilites, the iterator
//! returned by a legal input must point to last.
bool is_last = s(first) == last;
return is_legal && is_last;
}
}}//namespace
int main()
{
std::cout << "pls enter, following : S -> '+' S S | '-' S S | 'a'\n";
for(std::string buff; std::cin >> buff; /* */)
{
bool is_legal = dragon::ch2::parse_241a(buff.begin(),buff.end());
std::cout << "@parser ex2.4.1.a --> "
<< (is_legal? "legal\n" : "syntax error\n");
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* (C) 2009 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <botan/bigint.h>
#include <botan/exceptn.h>
#include <botan/numthry.h>
using namespace Botan;
#include "common.h"
#include "validate.h"
#define DEBUG 0
u32bit check_add(const std::vector<std::string>&);
u32bit check_sub(const std::vector<std::string>&);
u32bit check_mul(const std::vector<std::string>&);
u32bit check_sqr(const std::vector<std::string>&);
u32bit check_div(const std::vector<std::string>&);
u32bit check_mod(const std::vector<std::string>&,
Botan::RandomNumberGenerator& rng);
u32bit check_shr(const std::vector<std::string>&);
u32bit check_shl(const std::vector<std::string>&);
u32bit check_powmod(const std::vector<std::string>&);
u32bit check_primetest(const std::vector<std::string>&,
Botan::RandomNumberGenerator&);
u32bit do_bigint_tests(const std::string& filename,
Botan::RandomNumberGenerator& rng)
{
std::ifstream test_data(filename.c_str());
if(!test_data)
throw Botan::Stream_IO_Error("Couldn't open test file " + filename);
u32bit errors = 0, alg_count = 0;
std::string algorithm;
u32bit counter = 0;
while(!test_data.eof())
{
if(test_data.bad() || test_data.fail())
throw Botan::Stream_IO_Error("File I/O error reading from " +
filename);
std::string line;
std::getline(test_data, line);
strip(line);
if(line.size() == 0) continue;
// Do line continuation
while(line[line.size()-1] == '\\' && !test_data.eof())
{
line.replace(line.size()-1, 1, "");
std::string nextline;
std::getline(test_data, nextline);
strip(nextline);
if(nextline.size() == 0) continue;
line += nextline;
}
if(line[0] == '[' && line[line.size() - 1] == ']')
{
algorithm = line.substr(1, line.size() - 2);
alg_count = 0;
counter = 0;
continue;
}
std::vector<std::string> substr = parse(line);
#if DEBUG
std::cout << "Testing: " << algorithm << std::endl;
#endif
u32bit new_errors = 0;
if(algorithm.find("Addition") != std::string::npos)
new_errors = check_add(substr);
else if(algorithm.find("Subtraction") != std::string::npos)
new_errors = check_sub(substr);
else if(algorithm.find("Multiplication") != std::string::npos)
new_errors = check_mul(substr);
else if(algorithm.find("Square") != std::string::npos)
new_errors = check_sqr(substr);
else if(algorithm.find("Division") != std::string::npos)
new_errors = check_div(substr);
else if(algorithm.find("Modulo") != std::string::npos)
new_errors = check_mod(substr, rng);
else if(algorithm.find("LeftShift") != std::string::npos)
new_errors = check_shl(substr);
else if(algorithm.find("RightShift") != std::string::npos)
new_errors = check_shr(substr);
else if(algorithm.find("ModExp") != std::string::npos)
new_errors = check_powmod(substr);
else if(algorithm.find("PrimeTest") != std::string::npos)
new_errors = check_primetest(substr, rng);
else
std::cout << "Unknown MPI test " << algorithm << std::endl;
counter++;
alg_count++;
errors += new_errors;
if(new_errors)
std::cout << "ERROR: BigInt " << algorithm << " failed test #"
<< std::dec << alg_count << std::endl;
}
return errors;
}
namespace {
// c==expected, d==a op b, e==a op= b
u32bit results(std::string op,
const BigInt& a, const BigInt& b,
const BigInt& c, const BigInt& d, const BigInt& e)
{
std::string op1 = "operator" + op;
std::string op2 = op1 + "=";
if(c == d && d == e)
return 0;
else
{
std::cout << std::endl;
std::cout << "ERROR: " << op1 << std::endl;
std::cout << "a = " << std::hex << a << std::endl;
std::cout << "b = " << std::hex << b << std::endl;
std::cout << "c = " << std::hex << c << std::endl;
std::cout << "d = " << std::hex << d << std::endl;
std::cout << "e = " << std::hex << e << std::endl;
if(d != e)
{
std::cout << "ERROR: " << op1 << " | " << op2
<< " mismatch" << std::endl;
}
return 1;
}
}
}
u32bit check_add(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt c(args[2]);
BigInt d = a + b;
BigInt e = a;
e += b;
if(results("+", a, b, c, d, e))
return 1;
d = b + a;
e = b;
e += a;
return results("+", a, b, c, d, e);
}
u32bit check_sub(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt c(args[2]);
BigInt d = a - b;
BigInt e = a;
e -= b;
return results("-", a, b, c, d, e);
}
u32bit check_mul(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt c(args[2]);
/*
std::cout << "a = " << args[0] << "\n"
<< "b = " << args[1] << std::endl;
*/
/* This makes it more likely the fast multiply algorithms will be usable,
which is what we really want to test here (the simple n^2 multiply is
pretty well tested at this point).
*/
a.grow_to(64);
b.grow_to(64);
BigInt d = a * b;
BigInt e = a;
e *= b;
if(results("*", a, b, c, d, e))
return 1;
d = b * a;
e = b;
e *= a;
return results("*", a, b, c, d, e);
}
u32bit check_sqr(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
a.grow_to(64);
b.grow_to(64);
BigInt c = square(a);
BigInt d = a * a;
return results("sqr", a, a, b, c, d);
}
u32bit check_div(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt c(args[2]);
BigInt d = a / b;
BigInt e = a;
e /= b;
return results("/", a, b, c, d, e);
}
u32bit check_mod(const std::vector<std::string>& args,
Botan::RandomNumberGenerator& rng)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt c(args[2]);
BigInt d = a % b;
BigInt e = a;
e %= b;
u32bit got = results("%", a, b, c, d, e);
if(got) return got;
word b_word = b.word_at(0);
/* Won't work for us, just pick one at random */
while(b_word == 0)
for(u32bit j = 0; j != 2*sizeof(word); j++)
b_word = (b_word << 4) ^ rng.next_byte();
b = b_word;
c = a % b; /* we declare the BigInt % BigInt version to be correct here */
word d2 = a % b_word;
e = a;
e %= b_word;
return results("%(word)", a, b, c, d2, e);
}
u32bit check_shl(const std::vector<std::string>& args)
{
BigInt a(args[0]);
u32bit b = std::atoi(args[1].c_str());
BigInt c(args[2]);
BigInt d = a << b;
BigInt e = a;
e <<= b;
return results("<<", a, b, c, d, e);
}
u32bit check_shr(const std::vector<std::string>& args)
{
BigInt a(args[0]);
u32bit b = std::atoi(args[1].c_str());
BigInt c(args[2]);
BigInt d = a >> b;
BigInt e = a;
e >>= b;
return results(">>", a, b, c, d, e);
}
/* Make sure that (a^b)%m == r */
u32bit check_powmod(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt m(args[2]);
BigInt c(args[3]);
BigInt r = power_mod(a, b, m);
if(c != r)
{
std::cout << "ERROR: power_mod" << std::endl;
std::cout << "a = " << std::hex << a << std::endl;
std::cout << "b = " << std::hex << b << std::endl;
std::cout << "m = " << std::hex << m << std::endl;
std::cout << "c = " << std::hex << c << std::endl;
std::cout << "r = " << std::hex << r << std::endl;
return 1;
}
return 0;
}
/* Make sure that n is prime or not prime, according to should_be_prime */
u32bit check_primetest(const std::vector<std::string>& args,
Botan::RandomNumberGenerator& rng)
{
BigInt n(args[0]);
bool should_be_prime = (args[1] == "1");
bool is_prime = Botan::verify_prime(n, rng);
if(is_prime != should_be_prime)
{
std::cout << "ERROR: verify_prime" << std::endl;
std::cout << "n = " << n << std::endl;
std::cout << is_prime << " != " << should_be_prime << std::endl;
}
return 0;
}
<commit_msg>Quieter<commit_after>/*
* (C) 2009 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include "tests.h"
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <botan/bigint.h>
#include <botan/exceptn.h>
#include <botan/numthry.h>
using namespace Botan;
#include "common.h"
#include "validate.h"
#define DEBUG 0
u32bit check_add(const std::vector<std::string>&);
u32bit check_sub(const std::vector<std::string>&);
u32bit check_mul(const std::vector<std::string>&);
u32bit check_sqr(const std::vector<std::string>&);
u32bit check_div(const std::vector<std::string>&);
u32bit check_mod(const std::vector<std::string>&,
Botan::RandomNumberGenerator& rng);
u32bit check_shr(const std::vector<std::string>&);
u32bit check_shl(const std::vector<std::string>&);
u32bit check_powmod(const std::vector<std::string>&);
u32bit check_primetest(const std::vector<std::string>&,
Botan::RandomNumberGenerator&);
u32bit do_bigint_tests(const std::string& filename,
Botan::RandomNumberGenerator& rng)
{
std::ifstream test_data(filename.c_str());
if(!test_data)
throw Botan::Stream_IO_Error("Couldn't open test file " + filename);
u32bit total_errors = 0;
u32bit errors = 0, alg_count = 0;
std::string algorithm;
bool first = true;
u32bit counter = 0;
while(!test_data.eof())
{
if(test_data.bad() || test_data.fail())
throw Botan::Stream_IO_Error("File I/O error reading from " +
filename);
std::string line;
std::getline(test_data, line);
strip(line);
if(line.size() == 0) continue;
// Do line continuation
while(line[line.size()-1] == '\\' && !test_data.eof())
{
line.replace(line.size()-1, 1, "");
std::string nextline;
std::getline(test_data, nextline);
strip(nextline);
if(nextline.size() == 0) continue;
line += nextline;
}
if(line[0] == '[' && line[line.size() - 1] == ']')
{
if(!first)
test_report("Bigint " + algorithm, alg_count, errors);
algorithm = line.substr(1, line.size() - 2);
total_errors += errors;
errors = 0;
alg_count = 0;
counter = 0;
first = false;
continue;
}
std::vector<std::string> substr = parse(line);
#if DEBUG
std::cout << "Testing: " << algorithm << std::endl;
#endif
u32bit new_errors = 0;
if(algorithm.find("Addition") != std::string::npos)
new_errors = check_add(substr);
else if(algorithm.find("Subtraction") != std::string::npos)
new_errors = check_sub(substr);
else if(algorithm.find("Multiplication") != std::string::npos)
new_errors = check_mul(substr);
else if(algorithm.find("Square") != std::string::npos)
new_errors = check_sqr(substr);
else if(algorithm.find("Division") != std::string::npos)
new_errors = check_div(substr);
else if(algorithm.find("Modulo") != std::string::npos)
new_errors = check_mod(substr, rng);
else if(algorithm.find("LeftShift") != std::string::npos)
new_errors = check_shl(substr);
else if(algorithm.find("RightShift") != std::string::npos)
new_errors = check_shr(substr);
else if(algorithm.find("ModExp") != std::string::npos)
new_errors = check_powmod(substr);
else if(algorithm.find("PrimeTest") != std::string::npos)
new_errors = check_primetest(substr, rng);
else
std::cout << "Unknown MPI test " << algorithm << std::endl;
counter++;
alg_count++;
errors += new_errors;
if(new_errors)
std::cout << "ERROR: BigInt " << algorithm << " failed test #"
<< std::dec << alg_count << std::endl;
}
return total_errors;
}
namespace {
// c==expected, d==a op b, e==a op= b
u32bit results(std::string op,
const BigInt& a, const BigInt& b,
const BigInt& c, const BigInt& d, const BigInt& e)
{
std::string op1 = "operator" + op;
std::string op2 = op1 + "=";
if(c == d && d == e)
return 0;
else
{
std::cout << std::endl;
std::cout << "ERROR: " << op1 << std::endl;
std::cout << "a = " << std::hex << a << std::endl;
std::cout << "b = " << std::hex << b << std::endl;
std::cout << "c = " << std::hex << c << std::endl;
std::cout << "d = " << std::hex << d << std::endl;
std::cout << "e = " << std::hex << e << std::endl;
if(d != e)
{
std::cout << "ERROR: " << op1 << " | " << op2
<< " mismatch" << std::endl;
}
return 1;
}
}
}
u32bit check_add(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt c(args[2]);
BigInt d = a + b;
BigInt e = a;
e += b;
if(results("+", a, b, c, d, e))
return 1;
d = b + a;
e = b;
e += a;
return results("+", a, b, c, d, e);
}
u32bit check_sub(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt c(args[2]);
BigInt d = a - b;
BigInt e = a;
e -= b;
return results("-", a, b, c, d, e);
}
u32bit check_mul(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt c(args[2]);
/*
std::cout << "a = " << args[0] << "\n"
<< "b = " << args[1] << std::endl;
*/
/* This makes it more likely the fast multiply algorithms will be usable,
which is what we really want to test here (the simple n^2 multiply is
pretty well tested at this point).
*/
a.grow_to(64);
b.grow_to(64);
BigInt d = a * b;
BigInt e = a;
e *= b;
if(results("*", a, b, c, d, e))
return 1;
d = b * a;
e = b;
e *= a;
return results("*", a, b, c, d, e);
}
u32bit check_sqr(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
a.grow_to(64);
b.grow_to(64);
BigInt c = square(a);
BigInt d = a * a;
return results("sqr", a, a, b, c, d);
}
u32bit check_div(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt c(args[2]);
BigInt d = a / b;
BigInt e = a;
e /= b;
return results("/", a, b, c, d, e);
}
u32bit check_mod(const std::vector<std::string>& args,
Botan::RandomNumberGenerator& rng)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt c(args[2]);
BigInt d = a % b;
BigInt e = a;
e %= b;
u32bit got = results("%", a, b, c, d, e);
if(got) return got;
word b_word = b.word_at(0);
/* Won't work for us, just pick one at random */
while(b_word == 0)
for(u32bit j = 0; j != 2*sizeof(word); j++)
b_word = (b_word << 4) ^ rng.next_byte();
b = b_word;
c = a % b; /* we declare the BigInt % BigInt version to be correct here */
word d2 = a % b_word;
e = a;
e %= b_word;
return results("%(word)", a, b, c, d2, e);
}
u32bit check_shl(const std::vector<std::string>& args)
{
BigInt a(args[0]);
u32bit b = std::atoi(args[1].c_str());
BigInt c(args[2]);
BigInt d = a << b;
BigInt e = a;
e <<= b;
return results("<<", a, b, c, d, e);
}
u32bit check_shr(const std::vector<std::string>& args)
{
BigInt a(args[0]);
u32bit b = std::atoi(args[1].c_str());
BigInt c(args[2]);
BigInt d = a >> b;
BigInt e = a;
e >>= b;
return results(">>", a, b, c, d, e);
}
/* Make sure that (a^b)%m == r */
u32bit check_powmod(const std::vector<std::string>& args)
{
BigInt a(args[0]);
BigInt b(args[1]);
BigInt m(args[2]);
BigInt c(args[3]);
BigInt r = power_mod(a, b, m);
if(c != r)
{
std::cout << "ERROR: power_mod" << std::endl;
std::cout << "a = " << std::hex << a << std::endl;
std::cout << "b = " << std::hex << b << std::endl;
std::cout << "m = " << std::hex << m << std::endl;
std::cout << "c = " << std::hex << c << std::endl;
std::cout << "r = " << std::hex << r << std::endl;
return 1;
}
return 0;
}
/* Make sure that n is prime or not prime, according to should_be_prime */
u32bit check_primetest(const std::vector<std::string>& args,
Botan::RandomNumberGenerator& rng)
{
BigInt n(args[0]);
bool should_be_prime = (args[1] == "1");
bool is_prime = Botan::verify_prime(n, rng);
if(is_prime != should_be_prime)
{
std::cout << "ERROR: verify_prime" << std::endl;
std::cout << "n = " << n << std::endl;
std::cout << is_prime << " != " << should_be_prime << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef INC_BENCODE_HPP
#define INC_BENCODE_HPP
#include <cassert>
#include <cstring>
#include <iterator>
#include <iostream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
// Try to use N4082's any and string_view classes, or fall back to Boost's.
#ifdef __has_include
# if __has_include(<experimental/any>)
# include <experimental/any>
# define BENCODE_ANY_NS std::experimental
# else
# include <boost/any.hpp>
# define BENCODE_ANY_NS boost
# endif
# if __has_include(<experimental/string_view>)
# include <experimental/string_view>
# define BENCODE_STRING_VIEW std::experimental::string_view
# else
# include <boost/utility/string_ref.hpp>
# define BENCODE_STRING_VIEW boost::string_ref
# endif
#else
# include <boost/any.hpp>
# include <boost/utility/string_ref.hpp>
# define BENCODE_ANY_NS boost
# define BENCODE_STRING_VIEW boost::string_ref
#endif
namespace bencode {
using string = std::string;
using integer = long long;
using list = std::vector<BENCODE_ANY_NS::any>;
using dict = std::map<std::string, BENCODE_ANY_NS::any>;
using string_view = BENCODE_STRING_VIEW;
using dict_view = std::map<BENCODE_STRING_VIEW, BENCODE_ANY_NS::any>;
enum eof_behavior {
check_eof,
no_check_eof
};
template<typename T>
BENCODE_ANY_NS::any decode(T &begin, T end);
namespace detail {
template<bool View, typename T>
BENCODE_ANY_NS::any decode_data(T &begin, T end);
template<typename T>
integer decode_int_real(T &begin, T end) {
assert(*begin == 'i');
++begin;
bool positive = true;
if(*begin == '-') {
positive = false;
++begin;
}
// TODO: handle overflow
integer value = 0;
for(; begin != end && std::isdigit(*begin); ++begin)
value = value * 10 + *begin - '0';
if(begin == end)
throw std::invalid_argument("unexpected end of string");
if(*begin != 'e')
throw std::invalid_argument("expected 'e'");
++begin;
return positive ? value : -value;
}
template<bool View, typename T>
inline integer decode_int(T &begin, T end) {
return decode_int_real(begin, end);
}
template<bool View>
class str_reader {
public:
template<typename Iter, typename Size>
inline string operator ()(Iter &begin, Iter end, Size len) {
return call(
begin, end, len,
typename std::iterator_traits<Iter>::iterator_category()
);
}
private:
template<typename Iter, typename Size>
string call(Iter &begin, Iter end, Size len, std::forward_iterator_tag) {
if(std::distance(begin, end) < static_cast<ssize_t>(len))
throw std::invalid_argument("unexpected end of string");
std::string value(len, 0);
std::copy_n(begin, len, value.begin());
std::advance(begin, len);
return value;
}
template<typename Iter, typename Size>
string call(Iter &begin, Iter end, Size len, std::input_iterator_tag) {
std::string value(len, 0);
for(Size i = 0; i < len; i++) {
if(begin == end)
throw std::invalid_argument("unexpected end of string");
value[i] = *begin;
++begin;
}
return value;
}
};
template<>
class str_reader<true> {
public:
template<typename Iter, typename Size>
string_view operator ()(Iter &begin, Iter end, Size len) {
if(std::distance(begin, end) < static_cast<ssize_t>(len))
throw std::invalid_argument("unexpected end of string");
string_view value(begin, len);
std::advance(begin, len);
return value;
}
};
template<bool View, typename T>
typename std::conditional<View, string_view, string>::type
decode_str(T &begin, T end) {
assert(std::isdigit(*begin));
size_t len = 0;
for(; begin != end && std::isdigit(*begin); ++begin)
len = len * 10 + *begin - '0';
if(begin == end)
throw std::invalid_argument("unexpected end of string");
if(*begin != ':')
throw std::invalid_argument("expected ':'");
++begin;
return str_reader<View>{}(begin, end, len);
}
template<bool View, typename T>
list decode_list(T &begin, T end) {
assert(*begin == 'l');
++begin;
list value;
while(begin != end && *begin != 'e') {
value.push_back(decode_data<View>(begin, end));
}
if(begin == end)
throw std::invalid_argument("unexpected end of string");
++begin;
return value;
}
template<bool View, typename T>
typename std::conditional<View, dict_view, dict>::type
decode_dict(T &begin, T end) {
assert(*begin == 'd');
++begin;
typename std::conditional<View, dict_view, dict>::type value;
while(begin != end && *begin != 'e') {
if(!std::isdigit(*begin))
throw std::invalid_argument("expected string token");
auto result = value.emplace(decode_str<View>(begin, end),
decode_data<View>(begin, end));
if(!result.second) {
throw std::invalid_argument(
"duplicated key in dict: " + std::string(result.first->first)
);
}
}
if(begin == end)
throw std::invalid_argument("unexpected end of string");
++begin;
return value;
}
template<bool View, typename T>
BENCODE_ANY_NS::any decode_data(T &begin, T end) {
if(begin == end)
return BENCODE_ANY_NS::any();
if(*begin == 'i')
return decode_int<View>(begin, end);
else if(*begin == 'l')
return decode_list<View>(begin, end);
else if(*begin == 'd')
return decode_dict<View>(begin, end);
else if(std::isdigit(*begin))
return decode_str<View>(begin, end);
throw std::invalid_argument("unexpected type");
}
}
template<typename T>
inline BENCODE_ANY_NS::any decode(T &begin, T end) {
return detail::decode_data<false>(begin, end);
}
template<typename T>
inline BENCODE_ANY_NS::any decode(const T &begin, T end) {
T b(begin);
return detail::decode_data<false>(b, end);
}
inline BENCODE_ANY_NS::any decode(const BENCODE_STRING_VIEW &s) {
return decode(s.begin(), s.end());
}
inline BENCODE_ANY_NS::any
decode(std::istream &s, eof_behavior e = check_eof) {
std::istreambuf_iterator<char> begin(s), end;
auto result = decode(begin, end);
// If we hit EOF, update the parent stream.
if(e == check_eof && begin == end)
s.setstate(std::ios_base::eofbit);
return result;
}
template<typename T>
inline BENCODE_ANY_NS::any decode_view(T &begin, T end) {
return detail::decode_data<true>(begin, end);
}
template<typename T>
inline BENCODE_ANY_NS::any decode_view(const T &begin, T end) {
T b(begin);
return detail::decode_data<true>(b, end);
}
inline BENCODE_ANY_NS::any decode_view(const BENCODE_STRING_VIEW &s) {
return decode_view(s.begin(), s.end());
}
class list_encoder {
public:
inline list_encoder(std::ostream &os) : os(os) {
os.put('l');
}
template<typename T>
inline list_encoder & add(T &&value);
inline void end() {
os.put('e');
}
private:
std::ostream &os;
};
class dict_encoder {
public:
inline dict_encoder(std::ostream &os) : os(os) {
os.put('d');
}
template<typename T>
inline dict_encoder & add(const BENCODE_STRING_VIEW &key, T &&value);
inline void end() {
os.put('e');
}
private:
std::ostream &os;
};
// TODO: make these use unformatted output?
inline void encode(std::ostream &os, integer value) {
os << "i" << value << "e";
}
inline void encode(std::ostream &os, const BENCODE_STRING_VIEW &value) {
os << value.size() << ":" << value;
}
template<typename T>
void encode(std::ostream &os, const std::vector<T> &value) {
list_encoder e(os);
for(auto &&i : value)
e.add(i);
e.end();
}
template<typename T>
void encode(std::ostream &os, const std::map<std::string, T> &value) {
dict_encoder e(os);
for(auto &&i : value)
e.add(i.first, i.second);
e.end();
}
#ifdef BENCODE_HAS_STRING_VIEW
template<typename T>
void encode(std::ostream &os, const std::map<BENCODE_STRING_VIEW, T> &value) {
dict_encoder e(os);
for(auto &&i : value)
e.add(i.first, i.second);
e.end();
}
#endif
// Overload for `any`, but only if the passed-in type is already `any`. Don't
// accept an implicit conversion!
template<typename T>
auto encode(std::ostream &os, const T &value) ->
typename std::enable_if<std::is_same<T, BENCODE_ANY_NS::any>::value>::type {
using BENCODE_ANY_NS::any_cast;
auto &type = value.type();
if(type == typeid(integer))
encode(os, any_cast<integer>(value));
else if(type == typeid(string))
encode(os, any_cast<string>(value));
else if(type == typeid(list))
encode(os, any_cast<list>(value));
else if(type == typeid(dict))
encode(os, any_cast<dict>(value));
#ifdef BENCODE_HAS_STRING_VIEW
else if(type == typeid(string_view))
encode(os, any_cast<string_view>(value));
else if(type == typeid(dict_view))
encode(os, any_cast<dict_view>(value));
#endif
else
throw std::invalid_argument("unexpected type");
}
namespace detail {
inline void encode_list_items(list_encoder &) {}
template<typename T, typename ...Rest>
void encode_list_items(list_encoder &enc, T &&t, Rest &&...rest) {
enc.add(std::forward<T>(t));
encode_list_items(enc, std::forward<Rest>(rest)...);
}
inline void encode_dict_items(dict_encoder &) {}
template<typename Key, typename Value, typename ...Rest>
void encode_dict_items(dict_encoder &enc, Key &&key, Value &&value,
Rest &&...rest) {
enc.add(std::forward<Key>(key), std::forward<Value>(value));
encode_dict_items(enc, std::forward<Rest>(rest)...);
}
}
template<typename ...T>
void encode_list(std::ostream &os, T &&...t) {
list_encoder enc(os);
detail::encode_list_items(enc, std::forward<T>(t)...);
enc.end();
}
template<typename ...T>
void encode_dict(std::ostream &os, T &&...t) {
dict_encoder enc(os);
detail::encode_dict_items(enc, std::forward<T>(t)...);
enc.end();
}
template<typename T>
inline list_encoder & list_encoder::add(T &&value) {
encode(os, std::forward<T>(value));
return *this;
}
template<typename T>
inline dict_encoder &
dict_encoder::add(const BENCODE_STRING_VIEW &key, T &&value) {
encode(os, key);
encode(os, std::forward<T>(value));
return *this;
}
template<typename T>
std::string encode(T &&t) {
std::stringstream ss;
encode(ss, std::forward<T>(t));
return ss.str();
}
}
#endif
<commit_msg>Add a missing #include<commit_after>#ifndef INC_BENCODE_HPP
#define INC_BENCODE_HPP
#include <cassert>
#include <cctype>
#include <cstring>
#include <iterator>
#include <iostream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
// Try to use N4082's any and string_view classes, or fall back to Boost's.
#ifdef __has_include
# if __has_include(<experimental/any>)
# include <experimental/any>
# define BENCODE_ANY_NS std::experimental
# else
# include <boost/any.hpp>
# define BENCODE_ANY_NS boost
# endif
# if __has_include(<experimental/string_view>)
# include <experimental/string_view>
# define BENCODE_STRING_VIEW std::experimental::string_view
# else
# include <boost/utility/string_ref.hpp>
# define BENCODE_STRING_VIEW boost::string_ref
# endif
#else
# include <boost/any.hpp>
# include <boost/utility/string_ref.hpp>
# define BENCODE_ANY_NS boost
# define BENCODE_STRING_VIEW boost::string_ref
#endif
namespace bencode {
using string = std::string;
using integer = long long;
using list = std::vector<BENCODE_ANY_NS::any>;
using dict = std::map<std::string, BENCODE_ANY_NS::any>;
using string_view = BENCODE_STRING_VIEW;
using dict_view = std::map<BENCODE_STRING_VIEW, BENCODE_ANY_NS::any>;
enum eof_behavior {
check_eof,
no_check_eof
};
template<typename T>
BENCODE_ANY_NS::any decode(T &begin, T end);
namespace detail {
template<bool View, typename T>
BENCODE_ANY_NS::any decode_data(T &begin, T end);
template<typename T>
integer decode_int_real(T &begin, T end) {
assert(*begin == 'i');
++begin;
bool positive = true;
if(*begin == '-') {
positive = false;
++begin;
}
// TODO: handle overflow
integer value = 0;
for(; begin != end && std::isdigit(*begin); ++begin)
value = value * 10 + *begin - '0';
if(begin == end)
throw std::invalid_argument("unexpected end of string");
if(*begin != 'e')
throw std::invalid_argument("expected 'e'");
++begin;
return positive ? value : -value;
}
template<bool View, typename T>
inline integer decode_int(T &begin, T end) {
return decode_int_real(begin, end);
}
template<bool View>
class str_reader {
public:
template<typename Iter, typename Size>
inline string operator ()(Iter &begin, Iter end, Size len) {
return call(
begin, end, len,
typename std::iterator_traits<Iter>::iterator_category()
);
}
private:
template<typename Iter, typename Size>
string call(Iter &begin, Iter end, Size len, std::forward_iterator_tag) {
if(std::distance(begin, end) < static_cast<ssize_t>(len))
throw std::invalid_argument("unexpected end of string");
std::string value(len, 0);
std::copy_n(begin, len, value.begin());
std::advance(begin, len);
return value;
}
template<typename Iter, typename Size>
string call(Iter &begin, Iter end, Size len, std::input_iterator_tag) {
std::string value(len, 0);
for(Size i = 0; i < len; i++) {
if(begin == end)
throw std::invalid_argument("unexpected end of string");
value[i] = *begin;
++begin;
}
return value;
}
};
template<>
class str_reader<true> {
public:
template<typename Iter, typename Size>
string_view operator ()(Iter &begin, Iter end, Size len) {
if(std::distance(begin, end) < static_cast<ssize_t>(len))
throw std::invalid_argument("unexpected end of string");
string_view value(begin, len);
std::advance(begin, len);
return value;
}
};
template<bool View, typename T>
typename std::conditional<View, string_view, string>::type
decode_str(T &begin, T end) {
assert(std::isdigit(*begin));
size_t len = 0;
for(; begin != end && std::isdigit(*begin); ++begin)
len = len * 10 + *begin - '0';
if(begin == end)
throw std::invalid_argument("unexpected end of string");
if(*begin != ':')
throw std::invalid_argument("expected ':'");
++begin;
return str_reader<View>{}(begin, end, len);
}
template<bool View, typename T>
list decode_list(T &begin, T end) {
assert(*begin == 'l');
++begin;
list value;
while(begin != end && *begin != 'e') {
value.push_back(decode_data<View>(begin, end));
}
if(begin == end)
throw std::invalid_argument("unexpected end of string");
++begin;
return value;
}
template<bool View, typename T>
typename std::conditional<View, dict_view, dict>::type
decode_dict(T &begin, T end) {
assert(*begin == 'd');
++begin;
typename std::conditional<View, dict_view, dict>::type value;
while(begin != end && *begin != 'e') {
if(!std::isdigit(*begin))
throw std::invalid_argument("expected string token");
auto result = value.emplace(decode_str<View>(begin, end),
decode_data<View>(begin, end));
if(!result.second) {
throw std::invalid_argument(
"duplicated key in dict: " + std::string(result.first->first)
);
}
}
if(begin == end)
throw std::invalid_argument("unexpected end of string");
++begin;
return value;
}
template<bool View, typename T>
BENCODE_ANY_NS::any decode_data(T &begin, T end) {
if(begin == end)
return BENCODE_ANY_NS::any();
if(*begin == 'i')
return decode_int<View>(begin, end);
else if(*begin == 'l')
return decode_list<View>(begin, end);
else if(*begin == 'd')
return decode_dict<View>(begin, end);
else if(std::isdigit(*begin))
return decode_str<View>(begin, end);
throw std::invalid_argument("unexpected type");
}
}
template<typename T>
inline BENCODE_ANY_NS::any decode(T &begin, T end) {
return detail::decode_data<false>(begin, end);
}
template<typename T>
inline BENCODE_ANY_NS::any decode(const T &begin, T end) {
T b(begin);
return detail::decode_data<false>(b, end);
}
inline BENCODE_ANY_NS::any decode(const BENCODE_STRING_VIEW &s) {
return decode(s.begin(), s.end());
}
inline BENCODE_ANY_NS::any
decode(std::istream &s, eof_behavior e = check_eof) {
std::istreambuf_iterator<char> begin(s), end;
auto result = decode(begin, end);
// If we hit EOF, update the parent stream.
if(e == check_eof && begin == end)
s.setstate(std::ios_base::eofbit);
return result;
}
template<typename T>
inline BENCODE_ANY_NS::any decode_view(T &begin, T end) {
return detail::decode_data<true>(begin, end);
}
template<typename T>
inline BENCODE_ANY_NS::any decode_view(const T &begin, T end) {
T b(begin);
return detail::decode_data<true>(b, end);
}
inline BENCODE_ANY_NS::any decode_view(const BENCODE_STRING_VIEW &s) {
return decode_view(s.begin(), s.end());
}
class list_encoder {
public:
inline list_encoder(std::ostream &os) : os(os) {
os.put('l');
}
template<typename T>
inline list_encoder & add(T &&value);
inline void end() {
os.put('e');
}
private:
std::ostream &os;
};
class dict_encoder {
public:
inline dict_encoder(std::ostream &os) : os(os) {
os.put('d');
}
template<typename T>
inline dict_encoder & add(const BENCODE_STRING_VIEW &key, T &&value);
inline void end() {
os.put('e');
}
private:
std::ostream &os;
};
// TODO: make these use unformatted output?
inline void encode(std::ostream &os, integer value) {
os << "i" << value << "e";
}
inline void encode(std::ostream &os, const BENCODE_STRING_VIEW &value) {
os << value.size() << ":" << value;
}
template<typename T>
void encode(std::ostream &os, const std::vector<T> &value) {
list_encoder e(os);
for(auto &&i : value)
e.add(i);
e.end();
}
template<typename T>
void encode(std::ostream &os, const std::map<std::string, T> &value) {
dict_encoder e(os);
for(auto &&i : value)
e.add(i.first, i.second);
e.end();
}
#ifdef BENCODE_HAS_STRING_VIEW
template<typename T>
void encode(std::ostream &os, const std::map<BENCODE_STRING_VIEW, T> &value) {
dict_encoder e(os);
for(auto &&i : value)
e.add(i.first, i.second);
e.end();
}
#endif
// Overload for `any`, but only if the passed-in type is already `any`. Don't
// accept an implicit conversion!
template<typename T>
auto encode(std::ostream &os, const T &value) ->
typename std::enable_if<std::is_same<T, BENCODE_ANY_NS::any>::value>::type {
using BENCODE_ANY_NS::any_cast;
auto &type = value.type();
if(type == typeid(integer))
encode(os, any_cast<integer>(value));
else if(type == typeid(string))
encode(os, any_cast<string>(value));
else if(type == typeid(list))
encode(os, any_cast<list>(value));
else if(type == typeid(dict))
encode(os, any_cast<dict>(value));
#ifdef BENCODE_HAS_STRING_VIEW
else if(type == typeid(string_view))
encode(os, any_cast<string_view>(value));
else if(type == typeid(dict_view))
encode(os, any_cast<dict_view>(value));
#endif
else
throw std::invalid_argument("unexpected type");
}
namespace detail {
inline void encode_list_items(list_encoder &) {}
template<typename T, typename ...Rest>
void encode_list_items(list_encoder &enc, T &&t, Rest &&...rest) {
enc.add(std::forward<T>(t));
encode_list_items(enc, std::forward<Rest>(rest)...);
}
inline void encode_dict_items(dict_encoder &) {}
template<typename Key, typename Value, typename ...Rest>
void encode_dict_items(dict_encoder &enc, Key &&key, Value &&value,
Rest &&...rest) {
enc.add(std::forward<Key>(key), std::forward<Value>(value));
encode_dict_items(enc, std::forward<Rest>(rest)...);
}
}
template<typename ...T>
void encode_list(std::ostream &os, T &&...t) {
list_encoder enc(os);
detail::encode_list_items(enc, std::forward<T>(t)...);
enc.end();
}
template<typename ...T>
void encode_dict(std::ostream &os, T &&...t) {
dict_encoder enc(os);
detail::encode_dict_items(enc, std::forward<T>(t)...);
enc.end();
}
template<typename T>
inline list_encoder & list_encoder::add(T &&value) {
encode(os, std::forward<T>(value));
return *this;
}
template<typename T>
inline dict_encoder &
dict_encoder::add(const BENCODE_STRING_VIEW &key, T &&value) {
encode(os, key);
encode(os, std::forward<T>(value));
return *this;
}
template<typename T>
std::string encode(T &&t) {
std::stringstream ss;
encode(ss, std::forward<T>(t));
return ss.str();
}
}
#endif
<|endoftext|> |
<commit_before>#include "PhysicsSystem.hpp"
#include "Globals.hpp"
#include "GameEngine\GameEngine.h"
namespace ASSB
{
void PhysicsSystem::Update(GameEngine &g,
std::unordered_map<ASSB::Globals::ObjectID, RigidBodyComponent> &map)
{
UNUSED(g);
UNUSED(map);
//!TODO:Convert to not using full N^2 items in map!
for (auto &pair1 : map)
{
// If we are not collidable, don't bother for the entier loop.
if (!pair1.second.collidable_)
continue;
for (auto &pair2 : map)
{
// If we're not collidable, don't bother.
if (!pair2.second.collidable_)
continue;
// If we are both static, don't bother.
if (pair1.second.static_)
if (pair2.second.static_)
continue;
// If one of us is not static, care a bit only if we are colliding.
if (isCollidingAABB(g, pair1, pair2))
{
if (!pair1.second.static_)
{
// both dymanic
if (!pair2.second.static_)
resolveDynamicDynamicAABBCollision(g, pair1, pair2);
// pair1 is dynamic
else
resolveStaticAABBCollision(g, pair1, pair2);
}
else
// pair2 is dynamic
resolveStaticAABBCollision(g, pair2, pair1);
}
}
}
}
// Check if two objects are colliding
bool PhysicsSystem::isCollidingAABB(GameEngine &g,
std::pair<const Globals::ObjectID, RigidBodyComponent> &obj1,
std::pair<const Globals::ObjectID, RigidBodyComponent> &obj2)
{
ComponentHandle<TransformComponent> o1t = g.GetComponent<TransformComponent>(obj1.first);
ComponentHandle<TransformComponent> o2t = g.GetComponent<TransformComponent>(obj1.first);
UNUSED(obj1);
UNUSED(obj2);
UNUSED(g);
return false;
//if(o1t->GetPosition().X)
}
// Misleading qualifiers, not actually const for the Game Objects.
void PhysicsSystem::resolveStaticAABBCollision(GameEngine &g,
std::pair<const Globals::ObjectID, RigidBodyComponent> &dynamicObj,
std::pair<const Globals::ObjectID, RigidBodyComponent> &staticObj)
{
UNUSED(g);
UNUSED(dynamicObj);
UNUSED(staticObj);
}
// Misleading qualifiers, not actually const for the Game Objects
void PhysicsSystem::resolveDynamicDynamicAABBCollision(GameEngine &g,
std::pair<const Globals::ObjectID, RigidBodyComponent> &dynamicObj1,
std::pair<const Globals::ObjectID, RigidBodyComponent> &dynamicObj2)
{
UNUSED(g);
UNUSED(dynamicObj1);
UNUSED(dynamicObj2);
}
}
<commit_msg>+ Added implementation for AABB Detection<commit_after>#include "PhysicsSystem.hpp"
#include "Globals.hpp"
#include "GameEngine\GameEngine.h"
namespace ASSB
{
void PhysicsSystem::Update(GameEngine &g,
std::unordered_map<ASSB::Globals::ObjectID, RigidBodyComponent> &map)
{
UNUSED(g);
UNUSED(map);
//!TODO:Convert to not using full N^2 items in map!
for (auto &pair1 : map)
{
// If we are not collidable, don't bother for the entier loop.
if (!pair1.second.collidable_)
continue;
for (auto &pair2 : map)
{
// If we're not collidable, don't bother.
if (!pair2.second.collidable_)
continue;
// If we are both static, don't bother.
if (pair1.second.static_)
if (pair2.second.static_)
continue;
// If one of us is not static, care a bit only if we are colliding.
if (isCollidingAABB(g, pair1, pair2))
{
if (!pair1.second.static_)
{
if (!pair2.second.static_)
// Both pairs are dymanic
resolveDynamicDynamicAABBCollision(g, pair1, pair2);
else
// Pair1 is dynamic
resolveStaticAABBCollision(g, pair1, pair2);
}
else
// Pair2 is dynamic
resolveStaticAABBCollision(g, pair2, pair1);
}
}
}
}
// Check if two objects are colliding
bool PhysicsSystem::isCollidingAABB(GameEngine &g,
std::pair<const Globals::ObjectID, RigidBodyComponent> &obj1,
std::pair<const Globals::ObjectID, RigidBodyComponent> &obj2)
{
ComponentHandle<TransformComponent> o1t = g.GetComponent<TransformComponent>(obj1.first);
ComponentHandle<TransformComponent> o2t = g.GetComponent<TransformComponent>(obj1.first);
const Graphics::Vector4 pos1{ o1t->GetPosition() };
const Graphics::Vector4 pos2{ o2t->GetPosition() };
const float Half_Obj1Width{ obj1.second.width_ / 2 };
const float Half_Obj1Height{ obj1.second.height_ / 2 };
const float Half_Obj2Width{ obj2.second.width_ / 2 };
const float Half_Obj2Height{ obj2.second.height_ / 2 };
// Case: Right side object 1 past left side object 2
if (pos1.X + Half_Obj1Width > pos2.X - Half_Obj2Width)
{
// Case: Right side object 2 is past left side object 1
if (pos2.X + Half_Obj1Width > pos1.X - Half_Obj1Width)
{
// Case: Bottom side object 1 is past top side object 2
if (pos1.Y + Half_Obj1Height > pos2.Y - Half_Obj2Height)
{
// Case: Bottom side object 2 is past top side object 1
if (pos2.Y + Half_Obj2Height > pos1.Y - Half_Obj1Height)
{
// Colliding
return true;
}
}
}
}
return false;
}
// Misleading qualifiers, not actually const for the Game Objects.
void PhysicsSystem::resolveStaticAABBCollision(GameEngine &g,
std::pair<const Globals::ObjectID, RigidBodyComponent> &dynamicObj,
std::pair<const Globals::ObjectID, RigidBodyComponent> &staticObj)
{
// Consider: Impulse?
DEBUG_PRINT("Dynamic to Static Collision!");
UNUSED(g);
UNUSED(dynamicObj);
UNUSED(staticObj);
}
// Misleading qualifiers, not actually const for the Game Objects
void PhysicsSystem::resolveDynamicDynamicAABBCollision(GameEngine &g,
std::pair<const Globals::ObjectID, RigidBodyComponent> &dynamicObj1,
std::pair<const Globals::ObjectID, RigidBodyComponent> &dynamicObj2)
{
// Consider: Impulse?
DEBUG_PRINT("Dynamic to Dynamic Collision!");
UNUSED(g);
UNUSED(dynamicObj1);
UNUSED(dynamicObj2);
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <unordered_map>
#include <memory>
#include <type_traits>
#include <tuple>
namespace kgr {
template<typename... Types>
struct Dependency {
using DependenciesTypes = std::tuple<Types...>;
};
using NoDependencies = Dependency<>;
template<typename T>
struct Service;
namespace detail {
enum class enabler {};
template <bool b, typename T>
using enable_if_t = typename std::enable_if<b, T>::type;
template<int ...>
struct seq {};
template<int n, int ...S>
struct seq_gen : seq_gen<n-1, n-1, S...> {};
template<int ...S>
struct seq_gen<0, S...> {
using type = seq<S...>;
};
template <typename U>
struct function_traits
: function_traits<decltype(&U::operator())>
{};
template <typename Type, typename R, typename... Args>
struct function_traits<R(Type::*)(Args...) const> {
using return_type = R;
using argument_types = std::tuple<Args...>;
};
template <typename Type, typename R, typename... Args>
struct function_traits<R(Type::*)(Args...)> {
using return_type = R;
using argument_types = std::tuple<Args...>;
};
template <typename R, typename... Args>
struct function_traits<R(*)(Args...)> {
using return_type = R;
using argument_types = std::tuple<Args...>;
};
template <typename... F>
using function_arguments_t = typename function_traits<F...>::argument_types;
template <typename... F>
using function_result_t = typename function_traits<F...>::return_type;
struct Holder {
virtual ~Holder() = default;
};
struct InstanceHolder {
InstanceHolder() = default;
template <typename T>
explicit InstanceHolder(std::shared_ptr<T> ptr) : _ptr{std::move(ptr)} {}
InstanceHolder(const InstanceHolder &) = delete;
InstanceHolder& operator =(const InstanceHolder &) = delete;
InstanceHolder(InstanceHolder &&other) noexcept = default;
InstanceHolder& operator =(InstanceHolder &&rhs) noexcept = default;
template <typename T>
InstanceHolder& operator =(std::shared_ptr<T> &&rhs) {
_ptr = std::move(rhs);
return *this;
}
~InstanceHolder() noexcept = default;
template <typename T>
std::shared_ptr<T> get() const {
return std::static_pointer_cast<T>(_ptr);
}
private:
std::shared_ptr<void> _ptr;
};
template<typename T, typename... Args>
struct CallbackHolder final : Holder {
using callback_t = std::function<T(Args...)>;
explicit CallbackHolder(callback_t callback) : _callback{std::move(callback)} {}
T operator ()(Args... args) {
return _callback(args...);
}
private:
callback_t _callback;
};
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template <typename T, typename ...Args> void type_id() {}
using type_id_fn = void(*)();
template<typename T>
struct check_pointer_type {
private:
using yes = char;
using no = struct { char array[2]; };
template<typename C> static yes test(typename Service<C>::template PointerType<C>*);
template<typename C> static no test(...);
public:
constexpr static bool value = sizeof(test<T>(0)) == sizeof(yes);
};
template<typename Ptr>
struct PointerType {};
template<typename T>
struct PointerType<T*> {
using Type = T*;
using ServiceType = T;
template<typename ...Args>
static Type make_pointer(Args&&... args) {
return new T(std::forward<Args>(args)...);
}
};
template<typename T>
struct PointerType<std::shared_ptr<T>> {
using Type = std::shared_ptr<T>;
using ServiceType = T;
template<typename ...Args>
static Type make_pointer(Args&&... args) {
return std::make_shared<T>(std::forward<Args>(args)...);
}
};
template<typename T>
struct PointerType<std::unique_ptr<T>> {
using Type = std::unique_ptr<T>;
using ServiceType = T;
template<typename ...Args>
static Type make_pointer(Args&&... args) {
return make_unique<T>(std::forward<Args>(args)...);
}
};
template <bool, typename T>
struct pointer_type_helper {
using type = typename Service<T>::template PointerType<T>;
};
template <typename T>
struct pointer_type_helper<false, T> {
using type = PointerType<std::shared_ptr<T>>;
};
} // namespace detail
struct Single {
using ParentTypes = std::tuple<>;
template<typename T> using PointerType = detail::PointerType<std::shared_ptr<T>>;
};
struct Unique {
template<typename T> using PointerType = detail::PointerType<std::unique_ptr<T>>;
};
struct Raw {
template<typename T> using PointerType = detail::PointerType<T*>;
};
template<typename... Types>
struct Overrides : Single {
using ParentTypes = std::tuple<Types...>;
};
class Container : public std::enable_shared_from_this<Container> { public:
template<typename Condition, typename T = detail::enabler> using enable_if = detail::enable_if_t<Condition::value, T>;
template<typename Condition, typename T = detail::enabler> using disable_if = detail::enable_if_t<!Condition::value, T>;
template<typename T> using is_service_single = std::is_base_of<Single, Service<T>>;
template<typename T> using is_abstract = std::is_abstract<T>;
template<typename T> using is_base_of_container = std::is_base_of<Container, T>;
template<typename T> using is_container = std::is_same<T, Container>;
template<typename T> using dependency_types = typename Service<T>::DependenciesTypes;
template<typename T> using parent_types = typename Service<T>::ParentTypes;
template<typename Tuple> using tuple_seq = typename detail::seq_gen<std::tuple_size<Tuple>::value>::type;
template<int S, typename T> using parent_element = typename std::tuple_element<S, parent_types<T>>::type;
template<int S, typename Tuple> using tuple_element = typename std::tuple_element<S, Tuple>::type;
using holder_ptr = std::unique_ptr<detail::Holder>;
using callback_cont = std::unordered_map<detail::type_id_fn, holder_ptr>;
using instance_cont = std::unordered_map<detail::type_id_fn, detail::InstanceHolder>;
template<typename T> using ptr_type_helper = typename detail::pointer_type_helper<detail::check_pointer_type<T>::value, T>::type;
template<int S, typename Services> using ptr_type_helpers = ptr_type_helper<typename std::tuple_element<S, Services>::type>;
template<typename T> using ptr_type = typename detail::pointer_type_helper<detail::check_pointer_type<T>::value, T>::type::Type;
template<int S, typename Services> using ptr_types = ptr_type<typename std::tuple_element<S, Services>::type>;
constexpr static detail::enabler null = {};
public:
Container(const Container &) = delete;
Container(Container &&) = delete;
Container& operator =(const Container &) = delete;
Container& operator =(Container &&) = delete;
virtual ~Container() = default;
template <typename T, typename... Args, enable_if<is_base_of_container<T>> = null>
static std::shared_ptr<T> make_container(Args&&... args) {
auto container = std::make_shared<T>(std::forward<Args>(args)...);
static_cast<Container&>(*container).init();
return container;
}
template<typename T>
void instance(std::shared_ptr<T> service) {
static_assert(!std::is_base_of<Unique, Service<T>>::value, "Single cannot be unique");
static_assert(!std::is_base_of<Raw, Service<T>>::value, "Single cannot be raw pointers");
static_assert(std::is_same<ptr_type<T>, std::shared_ptr<T>>::value, "Single can only be held by shared_ptr");
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
call_save_instance(std::move(service), tuple_seq<parent_types<T>>{});
}
template<typename T, typename ...Args>
void instance(Args&& ...args) {
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
instance(make_service<T>(std::forward<Args>(args)...));
}
template<typename T, typename ...Args, disable_if<is_abstract<T>> = null, disable_if<is_base_of_container<T>> = null>
ptr_type<T> service(Args&& ...args) {
return get_service<T>(std::forward<Args>(args)...);
}
template<typename T, enable_if<is_container<T>> = null>
std::shared_ptr<T> service() {
return shared_from_this();
}
template<typename T, disable_if<is_container<T>> = null, enable_if<is_base_of_container<T>> = null>
std::shared_ptr<T> service() {
return std::dynamic_pointer_cast<T>(shared_from_this());
}
template<typename T, enable_if<is_abstract<T>> = null>
ptr_type<T> service() {
auto it = _services.find(&detail::type_id<T>);
if (it != _services.end()) {
return it->second.template get<T>();
}
return {};
}
template<typename T, typename U>
void callback(U callback) {
using arguments = detail::function_arguments_t<U>;
static_assert(!is_service_single<T>::value, "instance does not accept Single Service.");
call_save_callback<T, arguments>(tuple_seq<dependency_types<T>>{}, callback);
}
template<typename U>
void callback(U callback) {
using T = typename detail::PointerType<detail::function_result_t<U>>::ServiceType;
this->callback<T,U>(callback);
}
protected:
Container() = default;
virtual void init(){}
private:
template<typename T, enable_if<is_service_single<T>> = null>
ptr_type<T> get_service() {
auto it = _services.find(&detail::type_id<T>);
if (it == _services.end()) {
auto service = make_service<T>();
instance(service);
return service;
}
return it->second.template get<T>();
}
template<typename T, typename ...Args, disable_if<is_service_single<T>> = null>
ptr_type<T> get_service(Args ...args) {
return make_service<T>(std::forward<Args>(args)...);
}
template<typename T, int ...S>
void call_save_instance(std::shared_ptr<T> service, detail::seq<S...>) {
save_instance<T, parent_element<S, T>...>(std::move(service));
}
template<typename Tuple, int ...S>
std::tuple<ptr_types<S, Tuple>...> dependency(detail::seq<S...>) {
return std::make_tuple(service<tuple_element<S, Tuple>>()...);
}
template<typename T, typename Tuple, int ...S, typename ...Args>
ptr_type<T> callback_make_service(detail::seq<S...>, Tuple dependencies, Args&& ...args) const {
auto it = _callbacks.find(&detail::type_id<T, tuple_element<S, Tuple>..., Args...>);
if (it != _callbacks.end()) {
return static_cast<detail::CallbackHolder<ptr_type<T>, tuple_element<S, Tuple>..., Args...>&>(*it->second.get())(std::get<S>(dependencies)..., std::forward<Args>(args)...);
}
return {};
}
template<typename T, typename Tuple, int ...S, typename ...Args, enable_if<is_service_single<T>> = null>
ptr_type<T> make_service_dependency(detail::seq<S...>, Tuple dependencies, Args&& ...args) const {
return ptr_type_helper<T>::make_pointer(std::move(std::get<S>(dependencies))..., std::forward<Args>(args)...);
}
template<typename T, typename Tuple, int ...S, typename ...Args, disable_if<is_service_single<T>> = null>
ptr_type<T> make_service_dependency(detail::seq<S...> seq, Tuple dependencies, Args&& ...args) const {
auto service = callback_make_service<T, Tuple>(seq, dependencies, std::forward<Args>(args)...);
return service ? service : std::make_shared<T>(std::get<S>(dependencies)..., std::forward<Args>(args)...);
}
template <typename T, typename ...Args>
ptr_type<T> make_service(Args&& ...args) {
auto seq = tuple_seq<dependency_types<T>>{};
return make_service_dependency<T>(seq, dependency<dependency_types<T>>(seq), std::forward<Args>(args)...);
}
template<typename T, typename ...Others>
detail::enable_if_t<(sizeof...(Others) > 0), void> save_instance(std::shared_ptr<T> service) {
save_instance<T>(service);
save_instance<Others...>(std::move(service));
}
template<typename T>
void save_instance (std::shared_ptr<T> service) {
_services[&detail::type_id<T>] = std::move(service);
}
template<typename T, typename Tuple, int ...S, typename U>
void call_save_callback(detail::seq<S...>, U callback) {
using argument_dependency_types = std::tuple<tuple_element<S, Tuple>...>;
using dependency_ptr = std::tuple<ptr_types<S, dependency_types<T>>...>;
static_assert(std::is_same<dependency_ptr, argument_dependency_types>::value, "The callback should receive the dependencies in the right order as first parameters");
save_callback<T, Tuple>(tuple_seq<Tuple>{}, callback);
}
template<typename T, typename Tuple, int ...S, typename U>
void save_callback (detail::seq<S...>, U callback) {
_callbacks[&detail::type_id<T, tuple_element<S, Tuple>...>] = detail::make_unique<detail::CallbackHolder<ptr_type<T>, tuple_element<S, Tuple>...>>(callback);
}
callback_cont _callbacks;
instance_cont _services;
};
template<typename T = Container, typename ...Args>
std::shared_ptr<T> make_container(Args&& ...args) {
static_assert(std::is_base_of<Container, T>::value, "make_container only accept container types.");
return Container::make_container<T>(std::forward<Args>(args)...);
}
} // namespace kgr
<commit_msg>Use shared_ptr<void> instead of InstanceHolder<commit_after>#pragma once
#include <unordered_map>
#include <memory>
#include <type_traits>
#include <tuple>
namespace kgr {
template<typename... Types>
struct Dependency {
using DependenciesTypes = std::tuple<Types...>;
};
using NoDependencies = Dependency<>;
template<typename T>
struct Service;
namespace detail {
enum class enabler {};
template <bool b, typename T>
using enable_if_t = typename std::enable_if<b, T>::type;
template<int ...>
struct seq {};
template<int n, int ...S>
struct seq_gen : seq_gen<n-1, n-1, S...> {};
template<int ...S>
struct seq_gen<0, S...> {
using type = seq<S...>;
};
template <typename U>
struct function_traits
: function_traits<decltype(&U::operator())>
{};
template <typename Type, typename R, typename... Args>
struct function_traits<R(Type::*)(Args...) const> {
using return_type = R;
using argument_types = std::tuple<Args...>;
};
template <typename Type, typename R, typename... Args>
struct function_traits<R(Type::*)(Args...)> {
using return_type = R;
using argument_types = std::tuple<Args...>;
};
template <typename R, typename... Args>
struct function_traits<R(*)(Args...)> {
using return_type = R;
using argument_types = std::tuple<Args...>;
};
template <typename... F>
using function_arguments_t = typename function_traits<F...>::argument_types;
template <typename... F>
using function_result_t = typename function_traits<F...>::return_type;
struct Holder {
virtual ~Holder() = default;
};
template<typename T, typename... Args>
struct CallbackHolder final : Holder {
using callback_t = std::function<T(Args...)>;
explicit CallbackHolder(callback_t callback) : _callback{std::move(callback)} {}
T operator ()(Args... args) {
return _callback(args...);
}
private:
callback_t _callback;
};
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template <typename T, typename ...Args> void type_id() {}
using type_id_fn = void(*)();
template<typename T>
struct check_pointer_type {
private:
using yes = char;
using no = struct { char array[2]; };
template<typename C> static yes test(typename Service<C>::template PointerType<C>*);
template<typename C> static no test(...);
public:
constexpr static bool value = sizeof(test<T>(0)) == sizeof(yes);
};
template<typename Ptr>
struct PointerType {};
template<typename T>
struct PointerType<T*> {
using Type = T*;
using ServiceType = T;
template<typename ...Args>
static Type make_pointer(Args&&... args) {
return new T(std::forward<Args>(args)...);
}
};
template<typename T>
struct PointerType<std::shared_ptr<T>> {
using Type = std::shared_ptr<T>;
using ServiceType = T;
template<typename ...Args>
static Type make_pointer(Args&&... args) {
return std::make_shared<T>(std::forward<Args>(args)...);
}
};
template<typename T>
struct PointerType<std::unique_ptr<T>> {
using Type = std::unique_ptr<T>;
using ServiceType = T;
template<typename ...Args>
static Type make_pointer(Args&&... args) {
return make_unique<T>(std::forward<Args>(args)...);
}
};
template <bool, typename T>
struct pointer_type_helper {
using type = typename Service<T>::template PointerType<T>;
};
template <typename T>
struct pointer_type_helper<false, T> {
using type = PointerType<std::shared_ptr<T>>;
};
} // namespace detail
struct Single {
using ParentTypes = std::tuple<>;
template<typename T> using PointerType = detail::PointerType<std::shared_ptr<T>>;
};
struct Unique {
template<typename T> using PointerType = detail::PointerType<std::unique_ptr<T>>;
};
struct Raw {
template<typename T> using PointerType = detail::PointerType<T*>;
};
template<typename... Types>
struct Overrides : Single {
using ParentTypes = std::tuple<Types...>;
};
class Container : public std::enable_shared_from_this<Container> { public:
template<typename Condition, typename T = detail::enabler> using enable_if = detail::enable_if_t<Condition::value, T>;
template<typename Condition, typename T = detail::enabler> using disable_if = detail::enable_if_t<!Condition::value, T>;
template<typename T> using is_service_single = std::is_base_of<Single, Service<T>>;
template<typename T> using is_abstract = std::is_abstract<T>;
template<typename T> using is_base_of_container = std::is_base_of<Container, T>;
template<typename T> using is_container = std::is_same<T, Container>;
template<typename T> using dependency_types = typename Service<T>::DependenciesTypes;
template<typename T> using parent_types = typename Service<T>::ParentTypes;
template<typename Tuple> using tuple_seq = typename detail::seq_gen<std::tuple_size<Tuple>::value>::type;
template<int S, typename T> using parent_element = typename std::tuple_element<S, parent_types<T>>::type;
template<int S, typename Tuple> using tuple_element = typename std::tuple_element<S, Tuple>::type;
using holder_ptr = std::unique_ptr<detail::Holder>;
using callback_cont = std::unordered_map<detail::type_id_fn, holder_ptr>;
using InstanceHolder = std::shared_ptr<void>;
using instance_cont = std::unordered_map<detail::type_id_fn, InstanceHolder>;
template<typename T> using ptr_type_helper = typename detail::pointer_type_helper<detail::check_pointer_type<T>::value, T>::type;
template<int S, typename Services> using ptr_type_helpers = ptr_type_helper<typename std::tuple_element<S, Services>::type>;
template<typename T> using ptr_type = typename detail::pointer_type_helper<detail::check_pointer_type<T>::value, T>::type::Type;
template<int S, typename Services> using ptr_types = ptr_type<typename std::tuple_element<S, Services>::type>;
constexpr static detail::enabler null = {};
public:
Container(const Container &) = delete;
Container(Container &&) = delete;
Container& operator =(const Container &) = delete;
Container& operator =(Container &&) = delete;
virtual ~Container() = default;
template <typename T, typename... Args, enable_if<is_base_of_container<T>> = null>
static std::shared_ptr<T> make_container(Args&&... args) {
auto container = std::make_shared<T>(std::forward<Args>(args)...);
static_cast<Container&>(*container).init();
return container;
}
template<typename T>
void instance(std::shared_ptr<T> service) {
static_assert(!std::is_base_of<Unique, Service<T>>::value, "Single cannot be unique");
static_assert(!std::is_base_of<Raw, Service<T>>::value, "Single cannot be raw pointers");
static_assert(std::is_same<ptr_type<T>, std::shared_ptr<T>>::value, "Single can only be held by shared_ptr");
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
call_save_instance(std::move(service), tuple_seq<parent_types<T>>{});
}
template<typename T, typename ...Args>
void instance(Args&& ...args) {
static_assert(is_service_single<T>::value, "instance only accept Single Service instance.");
instance(make_service<T>(std::forward<Args>(args)...));
}
template<typename T, typename ...Args, disable_if<is_abstract<T>> = null, disable_if<is_base_of_container<T>> = null>
ptr_type<T> service(Args&& ...args) {
return get_service<T>(std::forward<Args>(args)...);
}
template<typename T, enable_if<is_container<T>> = null>
std::shared_ptr<T> service() {
return shared_from_this();
}
template<typename T, disable_if<is_container<T>> = null, enable_if<is_base_of_container<T>> = null>
std::shared_ptr<T> service() {
return std::dynamic_pointer_cast<T>(shared_from_this());
}
template<typename T, enable_if<is_abstract<T>> = null>
ptr_type<T> service() {
auto it = _services.find(&detail::type_id<T>);
if (it != _services.end()) {
return std::static_pointer_cast<T>(it->second);
}
return {};
}
template<typename T, typename U>
void callback(U callback) {
using arguments = detail::function_arguments_t<U>;
static_assert(!is_service_single<T>::value, "instance does not accept Single Service.");
call_save_callback<T, arguments>(tuple_seq<dependency_types<T>>{}, callback);
}
template<typename U>
void callback(U callback) {
using T = typename detail::PointerType<detail::function_result_t<U>>::ServiceType;
this->callback<T,U>(callback);
}
protected:
Container() = default;
virtual void init(){}
private:
template<typename T, enable_if<is_service_single<T>> = null>
ptr_type<T> get_service() {
auto it = _services.find(&detail::type_id<T>);
if (it == _services.end()) {
auto service = make_service<T>();
instance(service);
return service;
}
return std::static_pointer_cast<T>(it->second);
}
template<typename T, typename ...Args, disable_if<is_service_single<T>> = null>
ptr_type<T> get_service(Args ...args) {
return make_service<T>(std::forward<Args>(args)...);
}
template<typename T, int ...S>
void call_save_instance(std::shared_ptr<T> service, detail::seq<S...>) {
save_instance<T, parent_element<S, T>...>(std::move(service));
}
template<typename Tuple, int ...S>
std::tuple<ptr_types<S, Tuple>...> dependency(detail::seq<S...>) {
return std::make_tuple(service<tuple_element<S, Tuple>>()...);
}
template<typename T, typename Tuple, int ...S, typename ...Args>
ptr_type<T> callback_make_service(detail::seq<S...>, Tuple dependencies, Args&& ...args) const {
auto it = _callbacks.find(&detail::type_id<T, tuple_element<S, Tuple>..., Args...>);
if (it != _callbacks.end()) {
return static_cast<detail::CallbackHolder<ptr_type<T>, tuple_element<S, Tuple>..., Args...>&>(*it->second.get())(std::get<S>(dependencies)..., std::forward<Args>(args)...);
}
return {};
}
template<typename T, typename Tuple, int ...S, typename ...Args, enable_if<is_service_single<T>> = null>
ptr_type<T> make_service_dependency(detail::seq<S...>, Tuple dependencies, Args&& ...args) const {
return ptr_type_helper<T>::make_pointer(std::move(std::get<S>(dependencies))..., std::forward<Args>(args)...);
}
template<typename T, typename Tuple, int ...S, typename ...Args, disable_if<is_service_single<T>> = null>
ptr_type<T> make_service_dependency(detail::seq<S...> seq, Tuple dependencies, Args&& ...args) const {
auto service = callback_make_service<T, Tuple>(seq, dependencies, std::forward<Args>(args)...);
return service ? service : std::make_shared<T>(std::get<S>(dependencies)..., std::forward<Args>(args)...);
}
template <typename T, typename ...Args>
ptr_type<T> make_service(Args&& ...args) {
auto seq = tuple_seq<dependency_types<T>>{};
return make_service_dependency<T>(seq, dependency<dependency_types<T>>(seq), std::forward<Args>(args)...);
}
template<typename T, typename ...Others>
detail::enable_if_t<(sizeof...(Others) > 0), void> save_instance(std::shared_ptr<T> service) {
save_instance<T>(service);
save_instance<Others...>(std::move(service));
}
template<typename T>
void save_instance (std::shared_ptr<T> service) {
_services[&detail::type_id<T>] = std::move(service);
}
template<typename T, typename Tuple, int ...S, typename U>
void call_save_callback(detail::seq<S...>, U callback) {
using argument_dependency_types = std::tuple<tuple_element<S, Tuple>...>;
using dependency_ptr = std::tuple<ptr_types<S, dependency_types<T>>...>;
static_assert(std::is_same<dependency_ptr, argument_dependency_types>::value, "The callback should receive the dependencies in the right order as first parameters");
save_callback<T, Tuple>(tuple_seq<Tuple>{}, callback);
}
template<typename T, typename Tuple, int ...S, typename U>
void save_callback (detail::seq<S...>, U callback) {
_callbacks[&detail::type_id<T, tuple_element<S, Tuple>...>] = detail::make_unique<detail::CallbackHolder<ptr_type<T>, tuple_element<S, Tuple>...>>(callback);
}
callback_cont _callbacks;
instance_cont _services;
};
template<typename T = Container, typename ...Args>
std::shared_ptr<T> make_container(Args&& ...args) {
static_assert(std::is_base_of<Container, T>::value, "make_container only accept container types.");
return Container::make_container<T>(std::forward<Args>(args)...);
}
} // namespace kgr
<|endoftext|> |
<commit_before><commit_msg>revisited the appendEntries API<commit_after><|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief ArangoDB server
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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 holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "Basics/Common.h"
#include "Basics/files.h"
#include "Basics/logging.h"
#include "Basics/messages.h"
//#include "Basics/tri-strings.h"
#include "Rest/InitialiseRest.h"
#include "RestServer/ArangoServer.h"
#include "Statistics/statistics.h"
#include <signal.h>
using namespace triagens;
using namespace triagens::rest;
using namespace triagens::arango;
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief ArangoDB server
////////////////////////////////////////////////////////////////////////////////
AnyServer* ArangoInstance = nullptr;
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief Hooks for OS-Specific functions
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
extern void TRI_GlobalEntryFunction ();
extern void TRI_GlobalExitFunction (int, void*);
extern bool TRI_ParseMoreArgs (int argc, char* argv[]);
extern void TRI_StartService (int argc, char* argv[]);
#else
void TRI_GlobalEntryFunction () { }
void TRI_GlobalExitFunction (int exitCode, void* data) { }
bool TRI_ParseMoreArgs (int argc, char* argv[]) { return false; }
void TRI_StartService (int argc, char* argv[]) { }
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief handle fatal SIGNALs; print backtrace,
/// and rethrow signal for coredumps.
////////////////////////////////////////////////////////////////////////////////
static void AbortHandler (int signum) {
TRI_PrintBacktrace();
#ifdef _WIN32
exit(255 + signum);
#else
signal(signum, SIG_DFL);
kill(getpid(), signum);
#endif
}
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief creates an application server
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[]) {
int res = EXIT_SUCCESS;
signal(SIGSEGV, AbortHandler);
#ifdef _WIN32
bool const startAsService = TRI_ParseMoreArgs(argc, argv);
#else
bool const startAsService = false;
#endif
// initialise sub-systems
TRI_GlobalEntryFunction();
TRIAGENS_REST_INITIALISE(argc, argv);
TRI_InitialiseStatistics();
if (startAsService) {
TRI_StartService(argc, argv);
}
else {
ArangoInstance = new ArangoServer(argc, argv);
res = ArangoInstance->start();
}
if (ArangoInstance != nullptr) {
try {
delete ArangoInstance;
}
catch (...) {
// caught an error during shutdown
res = EXIT_FAILURE;
#ifdef TRI_ENABLE_MAINTAINER_MODE
std::cerr << "Caught an exception during shutdown";
#endif
}
ArangoInstance = nullptr;
}
TRI_ShutdownStatistics();
// shutdown sub-systems
TRIAGENS_REST_SHUTDOWN;
TRI_GlobalExitFunction(res, nullptr);
return res;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>removed unused include<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief ArangoDB server
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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 holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "Basics/Common.h"
#include "Basics/files.h"
#include "Basics/logging.h"
#include "Basics/messages.h"
#include "Rest/InitialiseRest.h"
#include "RestServer/ArangoServer.h"
#include "Statistics/statistics.h"
#include <signal.h>
using namespace triagens;
using namespace triagens::rest;
using namespace triagens::arango;
// -----------------------------------------------------------------------------
// --SECTION-- private variables
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief ArangoDB server
////////////////////////////////////////////////////////////////////////////////
AnyServer* ArangoInstance = nullptr;
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief Hooks for OS-Specific functions
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
extern void TRI_GlobalEntryFunction ();
extern void TRI_GlobalExitFunction (int, void*);
extern bool TRI_ParseMoreArgs (int argc, char* argv[]);
extern void TRI_StartService (int argc, char* argv[]);
#else
void TRI_GlobalEntryFunction () { }
void TRI_GlobalExitFunction (int exitCode, void* data) { }
bool TRI_ParseMoreArgs (int argc, char* argv[]) { return false; }
void TRI_StartService (int argc, char* argv[]) { }
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief handle fatal SIGNALs; print backtrace,
/// and rethrow signal for coredumps.
////////////////////////////////////////////////////////////////////////////////
static void AbortHandler (int signum) {
TRI_PrintBacktrace();
#ifdef _WIN32
exit(255 + signum);
#else
signal(signum, SIG_DFL);
kill(getpid(), signum);
#endif
}
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief creates an application server
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[]) {
int res = EXIT_SUCCESS;
signal(SIGSEGV, AbortHandler);
#ifdef _WIN32
bool const startAsService = TRI_ParseMoreArgs(argc, argv);
#else
bool const startAsService = false;
#endif
// initialise sub-systems
TRI_GlobalEntryFunction();
TRIAGENS_REST_INITIALISE(argc, argv);
TRI_InitialiseStatistics();
if (startAsService) {
TRI_StartService(argc, argv);
}
else {
ArangoInstance = new ArangoServer(argc, argv);
res = ArangoInstance->start();
}
if (ArangoInstance != nullptr) {
try {
delete ArangoInstance;
}
catch (...) {
// caught an error during shutdown
res = EXIT_FAILURE;
#ifdef TRI_ENABLE_MAINTAINER_MODE
std::cerr << "Caught an exception during shutdown";
#endif
}
ArangoInstance = nullptr;
}
TRI_ShutdownStatistics();
// shutdown sub-systems
TRIAGENS_REST_SHUTDOWN;
TRI_GlobalExitFunction(res, nullptr);
return res;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|> |
<commit_before>/*
* 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 Library 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.
*
* OlaServer.cpp
* OlaServer is the main OLA Server class
* Copyright (C) 2005-2008 Simon Newton
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <map>
#include <vector>
#include "ola/network/Socket.h"
#include "common/protocol/Ola.pb.h"
#include "common/rpc/StreamRpcChannel.h"
#include "ola/BaseTypes.h"
#include "ola/ExportMap.h"
#include "ola/Logging.h"
#include "ola/network/InterfacePicker.h"
#include "ola/rdm/UID.h"
#include "olad/Client.h"
#include "olad/DeviceManager.h"
#include "olad/ClientBroker.h"
#include "olad/OlaServer.h"
#include "olad/OlaServerServiceImpl.h"
#include "olad/Plugin.h"
#include "olad/PluginAdaptor.h"
#include "olad/PluginManager.h"
#include "olad/Port.h"
#include "olad/PortBroker.h"
#include "olad/PortManager.h"
#include "olad/Preferences.h"
#include "olad/Universe.h"
#include "olad/UniverseStore.h"
#ifdef HAVE_LIBMICROHTTPD
#include "olad/OlaHttpServer.h"
#endif
namespace ola {
using ola::rpc::StreamRpcChannel;
using std::pair;
const char OlaServer::UNIVERSE_PREFERENCES[] = "universe";
const char OlaServer::K_CLIENT_VAR[] = "clients-connected";
const char OlaServer::K_UID_VAR[] = "server-uid";
const unsigned int OlaServer::K_HOUSEKEEPING_TIMEOUT_MS = 1000;
/*
* Create a new OlaServer
* @param factory the factory to use to create OlaService objects
* @param m_plugin_loader the loader to use for the plugins
* @param socket the socket to listen on for new connections
*/
OlaServer::OlaServer(OlaClientServiceFactory *factory,
const vector<PluginLoader*> &plugin_loaders,
PreferencesFactory *preferences_factory,
ola::network::SelectServer *select_server,
ola_server_options *ola_options,
ola::network::AcceptingSocket *socket,
ExportMap *export_map)
: m_service_factory(factory),
m_plugin_loaders(plugin_loaders),
m_ss(select_server),
m_accepting_socket(socket),
m_device_manager(NULL),
m_plugin_manager(NULL),
m_plugin_adaptor(NULL),
m_preferences_factory(preferences_factory),
m_universe_preferences(NULL),
m_universe_store(NULL),
m_export_map(export_map),
m_port_manager(NULL),
m_service_impl(NULL),
m_broker(NULL),
m_port_broker(NULL),
m_reload_plugins(false),
m_init_run(false),
m_free_export_map(false),
m_housekeeping_timeout(ola::network::INVALID_TIMEOUT),
m_httpd(NULL),
m_options(*ola_options),
m_default_uid(OPEN_LIGHTING_ESTA_CODE, 0) {
if (!m_export_map) {
m_export_map = new ExportMap();
m_free_export_map = true;
}
if (!m_options.http_port)
m_options.http_port = DEFAULT_HTTP_PORT;
m_export_map->GetIntegerVar(K_CLIENT_VAR);
}
/*
* Shutdown the server
*/
OlaServer::~OlaServer() {
#ifdef HAVE_LIBMICROHTTPD
if (m_httpd) {
m_httpd->Stop();
delete m_httpd;
m_httpd = NULL;
}
#endif
if (m_housekeeping_timeout != ola::network::INVALID_TIMEOUT)
m_ss->RemoveTimeout(m_housekeeping_timeout);
StopPlugins();
map<int, OlaClientService*>::iterator iter;
for (iter = m_sd_to_service.begin(); iter != m_sd_to_service.end(); ++iter) {
CleanupConnection(iter->second);
// TODO(simon): close the socket here
/*Socket *socket = ;
m_ss->RemoveSocket(socket);
socket->Close();
*/
}
if (m_broker)
delete m_broker;
if (m_port_broker)
delete m_port_broker;
if (m_accepting_socket &&
m_accepting_socket->ReadDescriptor() !=
ola::network::Socket::INVALID_SOCKET)
m_ss->RemoveSocket(m_accepting_socket);
if (m_universe_store) {
m_universe_store->DeleteAll();
delete m_universe_store;
}
if (m_universe_preferences) {
m_universe_preferences->Save();
}
delete m_port_manager;
delete m_plugin_adaptor;
delete m_device_manager;
delete m_plugin_manager;
delete m_service_impl;
if (m_free_export_map)
delete m_export_map;
}
/*
* Initialise the server
* * @return true on success, false on failure
*/
bool OlaServer::Init() {
if (m_init_run)
return false;
if (!m_service_factory || !m_ss)
return false;
// TODO(simon): run without preferences & PluginLoader
if (!m_plugin_loaders.size() || !m_preferences_factory)
return false;
if (m_accepting_socket) {
if (!m_accepting_socket->Listen())
return false;
m_accepting_socket->SetOnData(
ola::NewCallback(this, &OlaServer::AcceptNewConnection,
m_accepting_socket));
m_ss->AddSocket(m_accepting_socket);
}
signal(SIGPIPE, SIG_IGN);
// fetch the interface info
ola::network::Interface interface;
ola::network::InterfacePicker *picker =
ola::network::InterfacePicker::NewPicker();
if (!picker->ChooseInterface(&interface, "")) {
OLA_WARN << "No network interface found";
} else {
// default to using the ip as a id
m_default_uid = ola::rdm::UID(OPEN_LIGHTING_ESTA_CODE,
interface.ip_address.s_addr);
}
delete picker;
m_export_map->GetStringVar(K_UID_VAR)->Set(m_default_uid.ToString());
OLA_INFO << "Server UID is " << m_default_uid;
m_universe_preferences = m_preferences_factory->NewPreference(
UNIVERSE_PREFERENCES);
m_universe_preferences->Load();
m_universe_store = new UniverseStore(m_universe_preferences, m_export_map);
m_port_broker = new PortBroker();
m_port_manager = new PortManager(m_universe_store, m_port_broker);
m_broker = new ClientBroker();
// setup the objects
m_device_manager = new DeviceManager(m_preferences_factory, m_port_manager);
m_plugin_adaptor = new PluginAdaptor(m_device_manager,
m_ss,
m_preferences_factory,
m_port_broker);
m_plugin_manager = new PluginManager(m_plugin_loaders, m_plugin_adaptor);
m_service_impl = new OlaServerServiceImpl(
m_universe_store,
m_device_manager,
m_plugin_manager,
m_export_map,
m_port_manager,
m_broker,
m_ss->WakeUpTime(),
m_default_uid);
if (!m_port_broker || !m_universe_store || !m_device_manager ||
!m_plugin_adaptor || !m_port_manager || !m_plugin_manager || !m_broker ||
!m_service_impl) {
delete m_plugin_adaptor;
delete m_device_manager;
delete m_port_manager;
delete m_universe_store;
delete m_plugin_manager;
return false;
}
m_plugin_manager->LoadAll();
#ifdef HAVE_LIBMICROHTTPD
if (!StartHttpServer(interface))
OLA_WARN << "Failed to start the HTTP server.";
#endif
m_housekeeping_timeout = m_ss->RegisterRepeatingTimeout(
K_HOUSEKEEPING_TIMEOUT_MS,
ola::NewCallback(this, &OlaServer::RunHousekeeping));
m_ss->RunInLoop(ola::NewCallback(this, &OlaServer::CheckForReload));
m_init_run = true;
return true;
}
/*
* Reload all plugins, this can be called from a separate thread or in an
* interrupt handler.
*/
void OlaServer::ReloadPlugins() {
m_reload_plugins = true;
}
/*
* Add a new ConnectedSocket to this Server.
* @param accepting_socket the AcceptingSocket with the new connection pending.
*/
void OlaServer::AcceptNewConnection(
ola::network::AcceptingSocket *accepting_socket) {
ola::network::ConnectedSocket *socket = accepting_socket->Accept();
if (socket)
NewConnection(socket);
}
/*
* Add a new ConnectedSocket to this Server.
* @param socket the new ConnectedSocket
*/
bool OlaServer::NewConnection(ola::network::ConnectedSocket *socket) {
if (!socket)
return false;
StreamRpcChannel *channel = new StreamRpcChannel(NULL, socket, m_export_map);
socket->SetOnClose(NewSingleCallback(this, &OlaServer::SocketClosed, socket));
OlaClientService_Stub *stub = new OlaClientService_Stub(channel);
Client *client = new Client(stub);
OlaClientService *service = m_service_factory->New(client, m_service_impl);
m_broker->AddClient(client);
channel->SetService(service);
map<int, OlaClientService*>::const_iterator iter;
iter = m_sd_to_service.find(socket->ReadDescriptor());
if (iter != m_sd_to_service.end())
OLA_INFO << "New socket but the client already exists!";
pair<int, OlaClientService*> pair(socket->ReadDescriptor(), service);
m_sd_to_service.insert(pair);
// This hands off ownership to the select server
m_ss->AddSocket(socket, true);
(*m_export_map->GetIntegerVar(K_CLIENT_VAR))++;
return 0;
}
/*
* Called when a socket is closed
*/
void OlaServer::SocketClosed(ola::network::ConnectedSocket *socket) {
map<int, OlaClientService*>::iterator iter;
iter = m_sd_to_service.find(socket->ReadDescriptor());
if (iter == m_sd_to_service.end())
OLA_INFO << "A socket was closed but we didn't find the client";
(*m_export_map->GetIntegerVar(K_CLIENT_VAR))--;
CleanupConnection(iter->second);
m_sd_to_service.erase(iter);
}
/*
* Run the garbage collector
*/
bool OlaServer::RunHousekeeping() {
OLA_DEBUG << "Garbage collecting";
m_universe_store->GarbageCollectUniverses();
return true;
}
/*
* Called once per loop iteration
*/
void OlaServer::CheckForReload() {
if (m_reload_plugins) {
m_reload_plugins = false;
OLA_INFO << "Reloading plugins";
StopPlugins();
m_plugin_manager->LoadAll();
}
}
/*
* Setup the HTTP server if required.
* @param interface the primary interface that the server is using.
*/
#ifdef HAVE_LIBMICROHTTPD
bool OlaServer::StartHttpServer(const ola::network::Interface &interface) {
if (!m_options.http_enable)
return true;
// create a pipe socket for the http server to communicate with the main
// server on.
ola::network::PipeSocket *socket = new ola::network::PipeSocket();
if (!socket->Init()) {
delete socket;
return false;
}
// ownership of the socket is transferred here.
m_httpd = new OlaHttpServer(m_export_map,
socket->OppositeEnd(),
this,
m_options.http_port,
m_options.http_enable_quit,
m_options.http_data_dir,
interface);
if (m_httpd->Init()) {
m_httpd->Start();
// register the pipe socket as a client
NewConnection(socket);
return true;
} else {
socket->Close();
delete socket;
delete m_httpd;
m_httpd = NULL;
return false;
}
}
#endif
/*
* Stop and unload all the plugins
*/
void OlaServer::StopPlugins() {
if (m_plugin_manager)
m_plugin_manager->UnloadAll();
if (m_device_manager) {
if (m_device_manager->DeviceCount()) {
OLA_WARN << "Some devices failed to unload, we're probably leaking "
<< "memory now";
}
m_device_manager->UnregisterAllDevices();
}
}
/*
* Cleanup everything related to a client connection
*/
void OlaServer::CleanupConnection(OlaClientService *service) {
Client *client = service->GetClient();
m_broker->RemoveClient(client);
vector<Universe*> universe_list;
m_universe_store->GetList(&universe_list);
vector<Universe*>::iterator uni_iter;
// O(universes * clients). Clean this up sometime.
for (uni_iter = universe_list.begin();
uni_iter != universe_list.end();
++uni_iter) {
(*uni_iter)->RemoveSourceClient(client);
(*uni_iter)->RemoveSinkClient(client);
}
delete client->Stub()->channel();
delete client->Stub();
delete client;
delete service;
}
} // ola
<commit_msg> * add a helpful error message when we can't bind to the RPC port<commit_after>/*
* 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 Library 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.
*
* OlaServer.cpp
* OlaServer is the main OLA Server class
* Copyright (C) 2005-2008 Simon Newton
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <map>
#include <vector>
#include "ola/network/Socket.h"
#include "common/protocol/Ola.pb.h"
#include "common/rpc/StreamRpcChannel.h"
#include "ola/BaseTypes.h"
#include "ola/ExportMap.h"
#include "ola/Logging.h"
#include "ola/network/InterfacePicker.h"
#include "ola/rdm/UID.h"
#include "olad/Client.h"
#include "olad/DeviceManager.h"
#include "olad/ClientBroker.h"
#include "olad/OlaServer.h"
#include "olad/OlaServerServiceImpl.h"
#include "olad/Plugin.h"
#include "olad/PluginAdaptor.h"
#include "olad/PluginManager.h"
#include "olad/Port.h"
#include "olad/PortBroker.h"
#include "olad/PortManager.h"
#include "olad/Preferences.h"
#include "olad/Universe.h"
#include "olad/UniverseStore.h"
#ifdef HAVE_LIBMICROHTTPD
#include "olad/OlaHttpServer.h"
#endif
namespace ola {
using ola::rpc::StreamRpcChannel;
using std::pair;
const char OlaServer::UNIVERSE_PREFERENCES[] = "universe";
const char OlaServer::K_CLIENT_VAR[] = "clients-connected";
const char OlaServer::K_UID_VAR[] = "server-uid";
const unsigned int OlaServer::K_HOUSEKEEPING_TIMEOUT_MS = 1000;
/*
* Create a new OlaServer
* @param factory the factory to use to create OlaService objects
* @param m_plugin_loader the loader to use for the plugins
* @param socket the socket to listen on for new connections
*/
OlaServer::OlaServer(OlaClientServiceFactory *factory,
const vector<PluginLoader*> &plugin_loaders,
PreferencesFactory *preferences_factory,
ola::network::SelectServer *select_server,
ola_server_options *ola_options,
ola::network::AcceptingSocket *socket,
ExportMap *export_map)
: m_service_factory(factory),
m_plugin_loaders(plugin_loaders),
m_ss(select_server),
m_accepting_socket(socket),
m_device_manager(NULL),
m_plugin_manager(NULL),
m_plugin_adaptor(NULL),
m_preferences_factory(preferences_factory),
m_universe_preferences(NULL),
m_universe_store(NULL),
m_export_map(export_map),
m_port_manager(NULL),
m_service_impl(NULL),
m_broker(NULL),
m_port_broker(NULL),
m_reload_plugins(false),
m_init_run(false),
m_free_export_map(false),
m_housekeeping_timeout(ola::network::INVALID_TIMEOUT),
m_httpd(NULL),
m_options(*ola_options),
m_default_uid(OPEN_LIGHTING_ESTA_CODE, 0) {
if (!m_export_map) {
m_export_map = new ExportMap();
m_free_export_map = true;
}
if (!m_options.http_port)
m_options.http_port = DEFAULT_HTTP_PORT;
m_export_map->GetIntegerVar(K_CLIENT_VAR);
}
/*
* Shutdown the server
*/
OlaServer::~OlaServer() {
#ifdef HAVE_LIBMICROHTTPD
if (m_httpd) {
m_httpd->Stop();
delete m_httpd;
m_httpd = NULL;
}
#endif
if (m_housekeeping_timeout != ola::network::INVALID_TIMEOUT)
m_ss->RemoveTimeout(m_housekeeping_timeout);
StopPlugins();
map<int, OlaClientService*>::iterator iter;
for (iter = m_sd_to_service.begin(); iter != m_sd_to_service.end(); ++iter) {
CleanupConnection(iter->second);
// TODO(simon): close the socket here
/*Socket *socket = ;
m_ss->RemoveSocket(socket);
socket->Close();
*/
}
if (m_broker)
delete m_broker;
if (m_port_broker)
delete m_port_broker;
if (m_accepting_socket &&
m_accepting_socket->ReadDescriptor() !=
ola::network::Socket::INVALID_SOCKET)
m_ss->RemoveSocket(m_accepting_socket);
if (m_universe_store) {
m_universe_store->DeleteAll();
delete m_universe_store;
}
if (m_universe_preferences) {
m_universe_preferences->Save();
}
delete m_port_manager;
delete m_plugin_adaptor;
delete m_device_manager;
delete m_plugin_manager;
delete m_service_impl;
if (m_free_export_map)
delete m_export_map;
}
/*
* Initialise the server
* * @return true on success, false on failure
*/
bool OlaServer::Init() {
if (m_init_run)
return false;
if (!m_service_factory || !m_ss)
return false;
// TODO(simon): run without preferences & PluginLoader
if (!m_plugin_loaders.size() || !m_preferences_factory)
return false;
if (m_accepting_socket) {
if (!m_accepting_socket->Listen()) {
OLA_FATAL << "Could not listen on the RPC port, you probably have " <<
"another instance of olad running";
return false;
}
m_accepting_socket->SetOnData(
ola::NewCallback(this, &OlaServer::AcceptNewConnection,
m_accepting_socket));
m_ss->AddSocket(m_accepting_socket);
}
signal(SIGPIPE, SIG_IGN);
// fetch the interface info
ola::network::Interface interface;
ola::network::InterfacePicker *picker =
ola::network::InterfacePicker::NewPicker();
if (!picker->ChooseInterface(&interface, "")) {
OLA_WARN << "No network interface found";
} else {
// default to using the ip as a id
m_default_uid = ola::rdm::UID(OPEN_LIGHTING_ESTA_CODE,
interface.ip_address.s_addr);
}
delete picker;
m_export_map->GetStringVar(K_UID_VAR)->Set(m_default_uid.ToString());
OLA_INFO << "Server UID is " << m_default_uid;
m_universe_preferences = m_preferences_factory->NewPreference(
UNIVERSE_PREFERENCES);
m_universe_preferences->Load();
m_universe_store = new UniverseStore(m_universe_preferences, m_export_map);
m_port_broker = new PortBroker();
m_port_manager = new PortManager(m_universe_store, m_port_broker);
m_broker = new ClientBroker();
// setup the objects
m_device_manager = new DeviceManager(m_preferences_factory, m_port_manager);
m_plugin_adaptor = new PluginAdaptor(m_device_manager,
m_ss,
m_preferences_factory,
m_port_broker);
m_plugin_manager = new PluginManager(m_plugin_loaders, m_plugin_adaptor);
m_service_impl = new OlaServerServiceImpl(
m_universe_store,
m_device_manager,
m_plugin_manager,
m_export_map,
m_port_manager,
m_broker,
m_ss->WakeUpTime(),
m_default_uid);
if (!m_port_broker || !m_universe_store || !m_device_manager ||
!m_plugin_adaptor || !m_port_manager || !m_plugin_manager || !m_broker ||
!m_service_impl) {
delete m_plugin_adaptor;
delete m_device_manager;
delete m_port_manager;
delete m_universe_store;
delete m_plugin_manager;
return false;
}
m_plugin_manager->LoadAll();
#ifdef HAVE_LIBMICROHTTPD
if (!StartHttpServer(interface))
OLA_WARN << "Failed to start the HTTP server.";
#endif
m_housekeeping_timeout = m_ss->RegisterRepeatingTimeout(
K_HOUSEKEEPING_TIMEOUT_MS,
ola::NewCallback(this, &OlaServer::RunHousekeeping));
m_ss->RunInLoop(ola::NewCallback(this, &OlaServer::CheckForReload));
m_init_run = true;
return true;
}
/*
* Reload all plugins, this can be called from a separate thread or in an
* interrupt handler.
*/
void OlaServer::ReloadPlugins() {
m_reload_plugins = true;
}
/*
* Add a new ConnectedSocket to this Server.
* @param accepting_socket the AcceptingSocket with the new connection pending.
*/
void OlaServer::AcceptNewConnection(
ola::network::AcceptingSocket *accepting_socket) {
ola::network::ConnectedSocket *socket = accepting_socket->Accept();
if (socket)
NewConnection(socket);
}
/*
* Add a new ConnectedSocket to this Server.
* @param socket the new ConnectedSocket
*/
bool OlaServer::NewConnection(ola::network::ConnectedSocket *socket) {
if (!socket)
return false;
StreamRpcChannel *channel = new StreamRpcChannel(NULL, socket, m_export_map);
socket->SetOnClose(NewSingleCallback(this, &OlaServer::SocketClosed, socket));
OlaClientService_Stub *stub = new OlaClientService_Stub(channel);
Client *client = new Client(stub);
OlaClientService *service = m_service_factory->New(client, m_service_impl);
m_broker->AddClient(client);
channel->SetService(service);
map<int, OlaClientService*>::const_iterator iter;
iter = m_sd_to_service.find(socket->ReadDescriptor());
if (iter != m_sd_to_service.end())
OLA_INFO << "New socket but the client already exists!";
pair<int, OlaClientService*> pair(socket->ReadDescriptor(), service);
m_sd_to_service.insert(pair);
// This hands off ownership to the select server
m_ss->AddSocket(socket, true);
(*m_export_map->GetIntegerVar(K_CLIENT_VAR))++;
return 0;
}
/*
* Called when a socket is closed
*/
void OlaServer::SocketClosed(ola::network::ConnectedSocket *socket) {
map<int, OlaClientService*>::iterator iter;
iter = m_sd_to_service.find(socket->ReadDescriptor());
if (iter == m_sd_to_service.end())
OLA_INFO << "A socket was closed but we didn't find the client";
(*m_export_map->GetIntegerVar(K_CLIENT_VAR))--;
CleanupConnection(iter->second);
m_sd_to_service.erase(iter);
}
/*
* Run the garbage collector
*/
bool OlaServer::RunHousekeeping() {
OLA_DEBUG << "Garbage collecting";
m_universe_store->GarbageCollectUniverses();
return true;
}
/*
* Called once per loop iteration
*/
void OlaServer::CheckForReload() {
if (m_reload_plugins) {
m_reload_plugins = false;
OLA_INFO << "Reloading plugins";
StopPlugins();
m_plugin_manager->LoadAll();
}
}
/*
* Setup the HTTP server if required.
* @param interface the primary interface that the server is using.
*/
#ifdef HAVE_LIBMICROHTTPD
bool OlaServer::StartHttpServer(const ola::network::Interface &interface) {
if (!m_options.http_enable)
return true;
// create a pipe socket for the http server to communicate with the main
// server on.
ola::network::PipeSocket *socket = new ola::network::PipeSocket();
if (!socket->Init()) {
delete socket;
return false;
}
// ownership of the socket is transferred here.
m_httpd = new OlaHttpServer(m_export_map,
socket->OppositeEnd(),
this,
m_options.http_port,
m_options.http_enable_quit,
m_options.http_data_dir,
interface);
if (m_httpd->Init()) {
m_httpd->Start();
// register the pipe socket as a client
NewConnection(socket);
return true;
} else {
socket->Close();
delete socket;
delete m_httpd;
m_httpd = NULL;
return false;
}
}
#endif
/*
* Stop and unload all the plugins
*/
void OlaServer::StopPlugins() {
if (m_plugin_manager)
m_plugin_manager->UnloadAll();
if (m_device_manager) {
if (m_device_manager->DeviceCount()) {
OLA_WARN << "Some devices failed to unload, we're probably leaking "
<< "memory now";
}
m_device_manager->UnregisterAllDevices();
}
}
/*
* Cleanup everything related to a client connection
*/
void OlaServer::CleanupConnection(OlaClientService *service) {
Client *client = service->GetClient();
m_broker->RemoveClient(client);
vector<Universe*> universe_list;
m_universe_store->GetList(&universe_list);
vector<Universe*>::iterator uni_iter;
// O(universes * clients). Clean this up sometime.
for (uni_iter = universe_list.begin();
uni_iter != universe_list.end();
++uni_iter) {
(*uni_iter)->RemoveSourceClient(client);
(*uni_iter)->RemoveSinkClient(client);
}
delete client->Stub()->channel();
delete client->Stub();
delete client;
delete service;
}
} // ola
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mediamisc.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:38:16 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <tools/resmgr.hxx>
#include <svtools/solar.hrc>
#include <vcl/svapp.hxx>
namespace avmedia {
ResMgr* GetResMgr()
{
static ResMgr* pResMgr = NULL;
if( !pResMgr )
{
ByteString aResMgrName( "avmedia" );
aResMgrName += ByteString::CreateFromInt32( SOLARUPD );
pResMgr = ResMgr::CreateResMgr( aResMgrName.GetBuffer(), Application::GetSettings().GetUILocale() );
}
return pResMgr;
}
} // namespace avemdia
<commit_msg>INTEGRATION: CWS supdremove02 (1.2.134); FILE MERGED 2008/01/31 13:48:16 rt 1.2.134.1: #i85482# Remove UPD from resource name.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mediamisc.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2008-02-25 15:59:18 $
*
* 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
*
************************************************************************/
#include <tools/resmgr.hxx>
#include <svtools/solar.hrc>
#include <vcl/svapp.hxx>
namespace avmedia {
ResMgr* GetResMgr()
{
static ResMgr* pResMgr = NULL;
if( !pResMgr )
{
ByteString aResMgrName( "avmedia" );
pResMgr = ResMgr::CreateResMgr( aResMgrName.GetBuffer(), Application::GetSettings().GetUILocale() );
}
return pResMgr;
}
} // namespace avemdia
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/gfx/native_widget_types.h"
#include "base/file_path.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
namespace {
// Delay to let the browser shut down before trying more brutal methods.
static const int kWaitForTerminateMsec = 30000;
class BrowserTest : public UITest {
protected:
void TerminateBrowser() {
#if defined(OS_WIN)
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser->TerminateSession());
#elif defined(OS_POSIX)
// There's nothing to do here if the browser is not running.
if (IsBrowserRunning()) {
automation()->SetFilteredInet(false);
int window_count = 0;
EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count));
// Now, drop the automation IPC channel so that the automation provider in
// the browser notices and drops its reference to the browser process.
automation()->Disconnect();
EXPECT_EQ(kill(process_, SIGTERM), 0);
// Wait for the browser process to quit. It should have quit when it got
// SIGTERM.
int timeout = kWaitForTerminateMsec;
#ifdef WAIT_FOR_DEBUGGER_ON_OPEN
timeout = 500000;
#endif
if (!base::WaitForSingleProcess(process_, timeout)) {
// We need to force the browser to quit because it didn't quit fast
// enough. Take no chance and kill every chrome processes.
CleanupAppProcesses();
}
// Don't forget to close the handle
base::CloseProcessHandle(process_);
process_ = NULL;
}
#endif // OS_POSIX
}
};
class VisibleBrowserTest : public UITest {
protected:
VisibleBrowserTest() : UITest() {
show_window_ = true;
}
};
#if defined(OS_WIN)
// The browser should quit quickly if it receives a WM_ENDSESSION message.
TEST_F(BrowserTest, WindowsSessionEnd) {
#elif defined(OS_POSIX)
// The browser should quit gracefully and quickly if it receives a SIGTERM.
TEST_F(BrowserTest, PosixSessionEnd) {
#endif
#if defined(OS_WIN) || defined(OS_POSIX)
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title1.html");
NavigateToURL(net::FilePathToFileURL(test_file));
PlatformThread::Sleep(action_timeout_ms());
TerminateBrowser();
PlatformThread::Sleep(action_timeout_ms());
ASSERT_FALSE(IsBrowserRunning());
// Make sure the UMA metrics say we didn't crash.
scoped_ptr<DictionaryValue> local_prefs(GetLocalState());
bool exited_cleanly;
ASSERT_TRUE(local_prefs.get());
ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilityExitedCleanly,
&exited_cleanly));
ASSERT_TRUE(exited_cleanly);
// And that session end was successful.
bool session_end_completed;
ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilitySessionEndCompleted,
&session_end_completed));
ASSERT_TRUE(session_end_completed);
// Make sure session restore says we didn't crash.
scoped_ptr<DictionaryValue> profile_prefs(GetDefaultProfilePreferences());
ASSERT_TRUE(profile_prefs.get());
ASSERT_TRUE(profile_prefs->GetBoolean(prefs::kSessionExitedCleanly,
&exited_cleanly));
ASSERT_TRUE(exited_cleanly);
}
#endif // OS_WIN || OS_POSIX
// Test that scripts can fork a new renderer process for a tab in a particular
// case (which matches following a link in Gmail). The script must open a new
// tab, set its window.opener to null, and redirect it to a cross-site URL.
// (Bug 1115708)
// This test can only run if V8 is in use, and not KJS, because KJS will not
// set window.opener to null properly.
#ifdef CHROME_V8
TEST_F(BrowserTest, NullOpenerRedirectForksProcess) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
FilePath test_file(test_data_directory_);
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
scoped_refptr<TabProxy> tab(window->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with a file:// url
test_file = test_file.AppendASCII("title2.html");
tab->NavigateToURL(net::FilePathToFileURL(test_file));
int orig_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
int orig_process_count = GetBrowserProcessCount();
ASSERT_GE(orig_process_count, 1);
// Use JavaScript URL to "fork" a new tab, just like Gmail. (Open tab to a
// blank page, set its opener to null, and redirect it cross-site.)
std::wstring url_prefix(L"javascript:(function(){w=window.open();");
GURL fork_url(url_prefix +
L"w.opener=null;w.document.location=\"http://localhost:1337\";})()");
// Make sure that a new tab has been created and that we have a new renderer
// process for it.
ASSERT_TRUE(tab->NavigateToURLAsync(fork_url));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count + 1, GetBrowserProcessCount());
int new_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&new_tab_count));
ASSERT_EQ(orig_tab_count + 1, new_tab_count);
}
#endif
// Tests that non-Gmail-like script redirects (i.e., non-null window.opener) or
// a same-page-redirect) will not fork a new process.
TEST_F(BrowserTest, OtherRedirectsDontForkProcess) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
FilePath test_file(test_data_directory_);
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
scoped_refptr<TabProxy> tab(window->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with a file:// url
test_file = test_file.AppendASCII("title2.html");
tab->NavigateToURL(net::FilePathToFileURL(test_file));
int orig_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
int orig_process_count = GetBrowserProcessCount();
ASSERT_GE(orig_process_count, 1);
// Use JavaScript URL to almost fork a new tab, but not quite. (Leave the
// opener non-null.) Should not fork a process.
std::string url_prefix("javascript:(function(){w=window.open();");
GURL dont_fork_url(url_prefix +
"w.document.location=\"http://localhost:1337\";})()");
// Make sure that a new tab but not new process has been created.
ASSERT_TRUE(tab->NavigateToURLAsync(dont_fork_url));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
int new_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&new_tab_count));
ASSERT_EQ(orig_tab_count + 1, new_tab_count);
// Same thing if the current tab tries to redirect itself.
GURL dont_fork_url2(url_prefix +
"document.location=\"http://localhost:1337\";})()");
// Make sure that no new process has been created.
ASSERT_TRUE(tab->NavigateToURLAsync(dont_fork_url2));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
}
TEST_F(VisibleBrowserTest, WindowOpenClose) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("window.close.html");
NavigateToURL(net::FilePathToFileURL(test_file));
int i;
for (i = 0; i < 10; ++i) {
PlatformThread::Sleep(action_max_timeout_ms() / 10);
std::wstring title = GetActiveTabTitle();
if (title == L"PASSED") {
// Success, bail out.
break;
}
}
if (i == 10)
FAIL() << "failed to get error page title";
}
class ShowModalDialogTest : public UITest {
public:
ShowModalDialogTest() {
launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
}
};
// Flakiness returned. Re-opened crbug.com/17806
TEST_F(ShowModalDialogTest, FLAKY_BasicTest) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("showmodaldialog.html");
// This navigation should show a modal dialog that will be immediately
// closed, but the fact that it was shown should be recorded.
NavigateToURL(net::FilePathToFileURL(test_file));
// At this point the modal dialog should not be showing.
int window_count = 0;
EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count));
EXPECT_EQ(1, window_count);
// Verify that we set a mark on successful dialog show.
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
std::wstring title;
ASSERT_TRUE(tab->GetTabTitle(&title));
ASSERT_EQ(L"SUCCESS", title);
}
class SecurityTest : public UITest {
protected:
static const int kTestIntervalMs = 250;
static const int kTestWaitTimeoutMs = 60 * 1000;
};
TEST_F(SecurityTest, DisallowFileUrlUniversalAccessTest) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("fileurl_universalaccess.html");
GURL url = net::FilePathToFileURL(test_file);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
"status", kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ("Disallowed", value.c_str());
}
#if !defined(OS_MACOSX)
class KioskModeTest : public UITest {
public:
KioskModeTest() {
launch_arguments_.AppendSwitch(switches::kKioskMode);
}
};
TEST_F(KioskModeTest, EnableKioskModeTest) {
// Load a dummy url.
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title1.html");
// Verify that the window is present.
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
// Check if browser is in fullscreen mode.
bool is_visible;
ASSERT_TRUE(browser->IsFullscreen(&is_visible));
EXPECT_TRUE(is_visible);
ASSERT_TRUE(browser->IsFullscreenBubbleVisible(&is_visible));
EXPECT_FALSE(is_visible);
}
#endif
} // namespace
<commit_msg>Disable a failing test on chrome os.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/gfx/native_widget_types.h"
#include "base/file_path.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
namespace {
// Delay to let the browser shut down before trying more brutal methods.
static const int kWaitForTerminateMsec = 30000;
class BrowserTest : public UITest {
protected:
void TerminateBrowser() {
#if defined(OS_WIN)
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser->TerminateSession());
#elif defined(OS_POSIX)
// There's nothing to do here if the browser is not running.
if (IsBrowserRunning()) {
automation()->SetFilteredInet(false);
int window_count = 0;
EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count));
// Now, drop the automation IPC channel so that the automation provider in
// the browser notices and drops its reference to the browser process.
automation()->Disconnect();
EXPECT_EQ(kill(process_, SIGTERM), 0);
// Wait for the browser process to quit. It should have quit when it got
// SIGTERM.
int timeout = kWaitForTerminateMsec;
#ifdef WAIT_FOR_DEBUGGER_ON_OPEN
timeout = 500000;
#endif
if (!base::WaitForSingleProcess(process_, timeout)) {
// We need to force the browser to quit because it didn't quit fast
// enough. Take no chance and kill every chrome processes.
CleanupAppProcesses();
}
// Don't forget to close the handle
base::CloseProcessHandle(process_);
process_ = NULL;
}
#endif // OS_POSIX
}
};
class VisibleBrowserTest : public UITest {
protected:
VisibleBrowserTest() : UITest() {
show_window_ = true;
}
};
#if defined(OS_WIN)
// The browser should quit quickly if it receives a WM_ENDSESSION message.
TEST_F(BrowserTest, WindowsSessionEnd) {
#elif defined(OS_POSIX)
// The browser should quit gracefully and quickly if it receives a SIGTERM.
TEST_F(BrowserTest, PosixSessionEnd) {
#endif
#if defined(OS_WIN) || defined(OS_POSIX)
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title1.html");
NavigateToURL(net::FilePathToFileURL(test_file));
PlatformThread::Sleep(action_timeout_ms());
TerminateBrowser();
PlatformThread::Sleep(action_timeout_ms());
ASSERT_FALSE(IsBrowserRunning());
// Make sure the UMA metrics say we didn't crash.
scoped_ptr<DictionaryValue> local_prefs(GetLocalState());
bool exited_cleanly;
ASSERT_TRUE(local_prefs.get());
ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilityExitedCleanly,
&exited_cleanly));
ASSERT_TRUE(exited_cleanly);
// And that session end was successful.
bool session_end_completed;
ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilitySessionEndCompleted,
&session_end_completed));
ASSERT_TRUE(session_end_completed);
// Make sure session restore says we didn't crash.
scoped_ptr<DictionaryValue> profile_prefs(GetDefaultProfilePreferences());
ASSERT_TRUE(profile_prefs.get());
ASSERT_TRUE(profile_prefs->GetBoolean(prefs::kSessionExitedCleanly,
&exited_cleanly));
ASSERT_TRUE(exited_cleanly);
}
#endif // OS_WIN || OS_POSIX
// Test that scripts can fork a new renderer process for a tab in a particular
// case (which matches following a link in Gmail). The script must open a new
// tab, set its window.opener to null, and redirect it to a cross-site URL.
// (Bug 1115708)
// This test can only run if V8 is in use, and not KJS, because KJS will not
// set window.opener to null properly.
#ifdef CHROME_V8
TEST_F(BrowserTest, NullOpenerRedirectForksProcess) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
FilePath test_file(test_data_directory_);
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
scoped_refptr<TabProxy> tab(window->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with a file:// url
test_file = test_file.AppendASCII("title2.html");
tab->NavigateToURL(net::FilePathToFileURL(test_file));
int orig_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
int orig_process_count = GetBrowserProcessCount();
ASSERT_GE(orig_process_count, 1);
// Use JavaScript URL to "fork" a new tab, just like Gmail. (Open tab to a
// blank page, set its opener to null, and redirect it cross-site.)
std::wstring url_prefix(L"javascript:(function(){w=window.open();");
GURL fork_url(url_prefix +
L"w.opener=null;w.document.location=\"http://localhost:1337\";})()");
// Make sure that a new tab has been created and that we have a new renderer
// process for it.
ASSERT_TRUE(tab->NavigateToURLAsync(fork_url));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count + 1, GetBrowserProcessCount());
int new_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&new_tab_count));
ASSERT_EQ(orig_tab_count + 1, new_tab_count);
}
#endif
// This test fails on ChromeOS (it has never been known to work on it).
// http://crbug.com/32799
#if defined(OS_CHROMEOS)
#define MAYBE_OtherRedirectsDontForkProcess DISABLED_OtherRedirectsDontForkProcess
#else
#define MAYBE_OtherRedirectsDontForkProcess OtherRedirectsDontForkProcess
#endif
// Tests that non-Gmail-like script redirects (i.e., non-null window.opener) or
// a same-page-redirect) will not fork a new process.
TEST_F(BrowserTest, MAYBE_OtherRedirectsDontForkProcess) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
FilePath test_file(test_data_directory_);
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
scoped_refptr<TabProxy> tab(window->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with a file:// url
test_file = test_file.AppendASCII("title2.html");
tab->NavigateToURL(net::FilePathToFileURL(test_file));
int orig_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
int orig_process_count = GetBrowserProcessCount();
ASSERT_GE(orig_process_count, 1);
// Use JavaScript URL to almost fork a new tab, but not quite. (Leave the
// opener non-null.) Should not fork a process.
std::string url_prefix("javascript:(function(){w=window.open();");
GURL dont_fork_url(url_prefix +
"w.document.location=\"http://localhost:1337\";})()");
// Make sure that a new tab but not new process has been created.
ASSERT_TRUE(tab->NavigateToURLAsync(dont_fork_url));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
int new_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&new_tab_count));
ASSERT_EQ(orig_tab_count + 1, new_tab_count);
// Same thing if the current tab tries to redirect itself.
GURL dont_fork_url2(url_prefix +
"document.location=\"http://localhost:1337\";})()");
// Make sure that no new process has been created.
ASSERT_TRUE(tab->NavigateToURLAsync(dont_fork_url2));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
}
TEST_F(VisibleBrowserTest, WindowOpenClose) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("window.close.html");
NavigateToURL(net::FilePathToFileURL(test_file));
int i;
for (i = 0; i < 10; ++i) {
PlatformThread::Sleep(action_max_timeout_ms() / 10);
std::wstring title = GetActiveTabTitle();
if (title == L"PASSED") {
// Success, bail out.
break;
}
}
if (i == 10)
FAIL() << "failed to get error page title";
}
class ShowModalDialogTest : public UITest {
public:
ShowModalDialogTest() {
launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
}
};
// Flakiness returned. Re-opened crbug.com/17806
TEST_F(ShowModalDialogTest, FLAKY_BasicTest) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("showmodaldialog.html");
// This navigation should show a modal dialog that will be immediately
// closed, but the fact that it was shown should be recorded.
NavigateToURL(net::FilePathToFileURL(test_file));
// At this point the modal dialog should not be showing.
int window_count = 0;
EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count));
EXPECT_EQ(1, window_count);
// Verify that we set a mark on successful dialog show.
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
std::wstring title;
ASSERT_TRUE(tab->GetTabTitle(&title));
ASSERT_EQ(L"SUCCESS", title);
}
class SecurityTest : public UITest {
protected:
static const int kTestIntervalMs = 250;
static const int kTestWaitTimeoutMs = 60 * 1000;
};
TEST_F(SecurityTest, DisallowFileUrlUniversalAccessTest) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("fileurl_universalaccess.html");
GURL url = net::FilePathToFileURL(test_file);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
"status", kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ("Disallowed", value.c_str());
}
#if !defined(OS_MACOSX)
class KioskModeTest : public UITest {
public:
KioskModeTest() {
launch_arguments_.AppendSwitch(switches::kKioskMode);
}
};
TEST_F(KioskModeTest, EnableKioskModeTest) {
// Load a dummy url.
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title1.html");
// Verify that the window is present.
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
// Check if browser is in fullscreen mode.
bool is_visible;
ASSERT_TRUE(browser->IsFullscreen(&is_visible));
EXPECT_TRUE(is_visible);
ASSERT_TRUE(browser->IsFullscreenBubbleVisible(&is_visible));
EXPECT_FALSE(is_visible);
}
#endif
} // namespace
<|endoftext|> |
<commit_before>#include "sinXScrollDemo.h"
#include "vrambatcher.h"
#include <cmath>
#include <nds/arm9/input.h>
#define MIN_AMPLITUDE 0
#define MAX_AMPLITUDE 256
#define MAX_SPEED 0.2
#define MIN_SPEED 0
#define MAX_LINESPEED 0.2
#define MIN_LINESPEED 0
#define M_PI 3.14159265358979323846
SinXScrollDemo::SinXScrollDemo() : offset(0), speed(0.1), amplitude(10), lineSpeed(0.01) {}
SinXScrollDemo::~SinXScrollDemo() {}
void SinXScrollDemo::AcceptInput() {
auto keys = keysCurrent();
if(keys & KEY_X && amplitude > MIN_AMPLITUDE) {
amplitude -= 0.01;
} else if(keys & KEY_Y && amplitude < MAX_AMPLITUDE) {
amplitude += 0.01;
}
if(keys & KEY_UP && speed < MAX_SPEED) {
speed += 0.01;
} else if(keys & KEY_DOWN && speed > MIN_SPEED) {
speed -= 0.01;
}
if(keys & KEY_LEFT && lineSpeed > MIN_LINESPEED) {
lineSpeed -= 0.01;
} else if(keys & KEY_RIGHT && lineSpeed < MAX_LINESPEED) {
lineSpeed += 0.01;
}
}
void SinXScrollDemo::Load() {
setupDefaultBG();
}
void SinXScrollDemo::Unload() {}
void SinXScrollDemo::PrepareFrame(VramBatcher &batcher) {
offset += speed;
if(offset > M_PI*2) offset -= M_PI*2;
float lineOffset = offset;
for (int scanline = 0; scanline < SCREEN_HEIGHT; ++scanline) {
int xscroll = std::sin(lineOffset)*amplitude;
batcher.AddPoke(scanline, xscroll, ®_BG0HOFS);
lineOffset += lineSpeed;
}
}<commit_msg>Suitable parameter ranges for sinxscroll<commit_after>#include "sinXScrollDemo.h"
#include "vrambatcher.h"
#include <cmath>
#include <nds/arm9/input.h>
#define MIN_AMPLITUDE 0
#define MAX_AMPLITUDE 256
#define MAX_SPEED 0.5
#define MIN_SPEED 0
#define MAX_LINESPEED 0.6
#define MIN_LINESPEED 0
#define M_PI 3.14159265358979323846
SinXScrollDemo::SinXScrollDemo() : offset(0), speed(0.04), amplitude(15), lineSpeed(0.01) {}
SinXScrollDemo::~SinXScrollDemo() {}
void SinXScrollDemo::AcceptInput() {
auto keys = keysDownRepeat();
if(keys & KEY_X && amplitude > MIN_AMPLITUDE) {
amplitude -= 1;
} else if(keys & KEY_Y && amplitude < MAX_AMPLITUDE) {
amplitude += 1;
}
if(keys & KEY_UP && speed < MAX_SPEED) {
speed += 0.01;
} else if(keys & KEY_DOWN && speed > MIN_SPEED) {
speed -= 0.01;
}
if(keys & KEY_LEFT && lineSpeed > MIN_LINESPEED) {
lineSpeed -= 0.0025;
} else if(keys & KEY_RIGHT && lineSpeed < MAX_LINESPEED) {
lineSpeed += 0.0025;
}
}
void SinXScrollDemo::Load() {
setupDefaultBG();
keysSetRepeat(15, 5);
}
void SinXScrollDemo::Unload() {}
void SinXScrollDemo::PrepareFrame(VramBatcher &batcher) {
offset += speed;
if(offset > M_PI*2) offset -= M_PI*2;
float lineOffset = offset;
for (int scanline = 0; scanline < SCREEN_HEIGHT; ++scanline) {
int xscroll = std::sin(lineOffset)*amplitude;
batcher.AddPoke(scanline, xscroll, ®_BG0HOFS);
lineOffset += lineSpeed;
if(lineOffset > M_PI * 2) lineOffset -= M_PI * 2;
}
}<|endoftext|> |
<commit_before>// Copyright 2014 Google 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.
#include "util.h"
#include <libgen.h> // basename(), dirname()
#include <sys/stat.h> // mkdir()
namespace st {
int logging_verbose_level = 0;
// When implementing basename and dirname, we copy everything to a buffer, then
// call libgen's basename()/dirname() functions on that buffer. We do this
// because those calls can modify the underlying character buffer. We also, for
// extra safety, add an extra null byte onto the end of the filename, in case
// for some very strange reason we're passed a filename without one.
string Basename(const string& filename) {
char copy[filename.size() + 1];
memcpy(copy, filename.data(), filename.size());
copy[filename.size()] = 0;
return string(basename(copy));
}
string Dirname(const string& filename) {
char copy[filename.size() + 1];
memcpy(copy, filename.data(), filename.size());
copy[filename.size()] = 0;
return string(dirname(copy));
}
Error MkDirRecursive(const string& dirname) {
LOG(INFO) << "Making sure directory " << dirname << " exists";
while (true) {
int ret = mkdir(dirname.c_str(), 0700);
if (ret == 0) {
return SUCCESS;
}
switch errno {
case ENOENT:
RETURN_IF_ERROR(MkDirRecursive(Dirname(dirname)), dirname);
continue;
case EEXIST:
return SUCCESS;
default:
return Errno();
}
}
}
} // namespace st
<commit_msg>Remove loop for MkDirRecursive (causes infinite loop with symlinks pointing to non-existent dirs).<commit_after>// Copyright 2014 Google 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.
#include "util.h"
#include <libgen.h> // basename(), dirname()
#include <sys/stat.h> // mkdir()
namespace st {
int logging_verbose_level = 0;
// When implementing basename and dirname, we copy everything to a buffer, then
// call libgen's basename()/dirname() functions on that buffer. We do this
// because those calls can modify the underlying character buffer. We also, for
// extra safety, add an extra null byte onto the end of the filename, in case
// for some very strange reason we're passed a filename without one.
string Basename(const string& filename) {
char copy[filename.size() + 1];
memcpy(copy, filename.data(), filename.size());
copy[filename.size()] = 0;
return string(basename(copy));
}
string Dirname(const string& filename) {
char copy[filename.size() + 1];
memcpy(copy, filename.data(), filename.size());
copy[filename.size()] = 0;
return string(dirname(copy));
}
Error MkDirRecursive(const string& dirname) {
LOG(INFO) << "Making sure directory " << dirname << " exists";
if (mkdir(dirname.c_str(), 0700) == 0) {
return SUCCESS;
}
switch
errno {
case ENOENT:
RETURN_IF_ERROR(MkDirRecursive(Dirname(dirname)), dirname);
break;
case EEXIST:
return SUCCESS;
default:
return Errno();
}
return Errno(mkdir(dirname.c_str(), 0700) == 0);
}
} // namespace st
<|endoftext|> |
<commit_before>//---------------------------- dof_tools_common.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2003, 2004, 2005 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- dof_tools_common.cc ---------------------------
// common framework for the various dof_tools_*.cc tests
#include "../tests.h"
#include <base/logstream.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <grid/grid_generator.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_tools.h>
#include <fe/fe_q.h>
#include <fe/fe_dgq.h>
#include <fe/fe_dgp.h>
#include <fe/fe_nedelec.h>
#include <fe/fe_raviart_thomas.h>
#include <fe/fe_system.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
// forward declaration of the function that must be provided in the
// .cc files
template <int dim>
void
check_this (const DoFHandler<dim> &dof_handler);
// forward declaration of a variable with the name of the output file
extern std::string output_file_name;
void
output_bool_vector (std::vector<bool> &v)
{
for (unsigned int i=0; i<v.size(); ++i)
deallog << (v[i] ? '1' : '0');
deallog << std::endl;
}
template <int dim>
void
set_boundary_ids (Triangulation<dim> &tria)
{
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
tria.begin_active()->face(f)->set_boundary_indicator (f);
}
void
set_boundary_ids (Triangulation<1> &)
{}
template <int dim>
void
check (const FiniteElement<dim> &fe,
const std::string &name)
{
deallog << "Checking " << name
<< " in " << dim << "d:"
<< std::endl;
// create tria and dofhandler
// objects. set different boundary
// and sub-domain ids
Triangulation<dim> tria;
GridGenerator::hyper_cube(tria, 0., 1.);
set_boundary_ids (tria);
tria.refine_global (1);
for (int i=0; i<2; ++i)
{
tria.begin_active()->set_refine_flag();
tria.execute_coarsening_and_refinement ();
}
for (typename Triangulation<dim>::active_cell_iterator
cell=tria.begin_active();
cell!=tria.end(); ++cell)
cell->set_subdomain_id (cell->level());
DoFHandler<dim> dof_handler (tria);
dof_handler.distribute_dofs (fe);
// call main function in .cc files
check_this (dof_handler);
}
#define CHECK(EL,deg,dim)\
{ FE_ ## EL<dim> EL(deg); \
check(EL, #EL #deg); }
#define CHECK_SYS1(sub1,N1,dim) \
{ FESystem<dim> q(sub1, N1); \
check(q, #sub1 #N1); }
#define CHECK_SYS2(sub1,N1,sub2,N2,dim) \
{ FESystem<dim> q(sub1, N1, sub2, N2); \
check(q, #sub1 #N1 #sub2 #N2); }
#define CHECK_SYS3(sub1,N1,sub2,N2,sub3,N3,dim) \
{ FESystem<dim> q(sub1, N1, sub2, N2, sub3, N3); \
check(q, #sub1 #N1 #sub2 #N2 #sub3 #N3); }
#define CHECK_ALL(EL,deg)\
{ CHECK(EL,deg,1); \
CHECK(EL,deg,2); \
CHECK(EL,deg,3); \
}
int
main()
{
try
{
std::ofstream logfile(output_file_name.c_str());
logfile.precision (2);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
CHECK_ALL(Q,1);
CHECK_ALL(Q,2);
CHECK_ALL(Q,3);
CHECK_ALL(DGQ,0);
CHECK_ALL(DGQ,1);
CHECK_ALL(DGQ,2);
CHECK_ALL(DGQ,3);
CHECK_ALL(DGQ,4);
CHECK_ALL(DGP,0);
CHECK_ALL(DGP,1);
CHECK_ALL(DGP,2);
CHECK_ALL(DGP,3);
CHECK_ALL(DGP,4);
CHECK(Nedelec, 1, 2);
CHECK(Nedelec, 1, 3);
CHECK(RaviartThomas, 0, 2);
CHECK(RaviartThomas, 1, 2);
CHECK(RaviartThomas, 2, 2);
CHECK(RaviartThomasNodal, 0, 2);
CHECK(RaviartThomasNodal, 1, 2);
CHECK(RaviartThomasNodal, 2, 2);
CHECK(RaviartThomasNodal, 0, 3);
CHECK(RaviartThomasNodal, 1, 3);
CHECK(RaviartThomasNodal, 2, 3);
CHECK_SYS1(FE_Q<1>(1), 3,1);
CHECK_SYS1(FE_DGQ<1>(2),2,1);
CHECK_SYS1(FE_DGP<1>(3),1,1);
CHECK_SYS1(FE_Q<2>(1), 3,2);
CHECK_SYS1(FE_DGQ<2>(2),2,2);
CHECK_SYS1(FE_DGP<2>(3),1,2);
CHECK_SYS1(FE_Q<3>(1), 3,3);
CHECK_SYS1(FE_DGQ<3>(2),2,3);
CHECK_SYS1(FE_DGP<3>(3),1,3);
CHECK_SYS2(FE_Q<1>(1), 3,FE_DGQ<1>(2),2,1);
CHECK_SYS2(FE_DGQ<1>(2),2,FE_DGP<1>(3),1,1);
CHECK_SYS2(FE_DGP<1>(3),1,FE_DGQ<1>(2),2,1);
CHECK_SYS2(FE_Q<2>(1), 3,FE_DGQ<2>(2),2,2);
CHECK_SYS2(FE_DGQ<2>(2),2,FE_DGP<2>(3),1,2);
CHECK_SYS2(FE_DGP<2>(3),1,FE_DGQ<2>(2),2,2);
CHECK_SYS2(FE_Q<3>(1) ,3,FE_DGQ<3>(2),2,3);
CHECK_SYS2(FE_DGQ<3>(2),2,FE_DGP<3>(3),1,3);
CHECK_SYS2(FE_DGP<3>(3),1,FE_DGQ<3>(2),2,3);
CHECK_SYS3(FE_Q<1>(1), 3,FE_DGP<1>(3),1,FE_Q<1>(1),3,1);
CHECK_SYS3(FE_DGQ<1>(2),2,FE_DGQ<1>(2),2,FE_Q<1>(3),3,1);
CHECK_SYS3(FE_DGP<1>(3),1,FE_DGP<1>(3),1,FE_Q<1>(2),3,1);
CHECK_SYS3(FE_Q<2>(1), 3,FE_DGP<2>(3),1,FE_Q<2>(1),3,2);
CHECK_SYS3(FE_DGQ<2>(2),2,FE_DGQ<2>(2),2,FE_Q<2>(3),3,2);
CHECK_SYS3(FE_DGP<2>(3),1,FE_DGP<2>(3),1,FE_Q<2>(2),3,2);
CHECK_SYS3(FE_Q<3>(1), 3,FE_DGP<3>(3),1,FE_Q<3>(1),3,3);
CHECK_SYS3(FE_DGQ<3>(2),2,FE_DGQ<3>(2),2,FE_Q<3>(3),3,3);
CHECK_SYS3(FE_DGP<3>(3),1,FE_DGP<3>(3),1,FE_Q<3>(2),3,3);
// systems of systems
CHECK_SYS3((FESystem<2>(FE_Q<2>(1),3)), 3,
FE_DGQ<2>(3), 1,
FE_Q<2>(1), 3,
2);
CHECK_SYS3(FE_DGQ<2>(3), 1,
FESystem<2>(FE_DGQ<2>(3),3), 1,
FESystem<2>(FE_Q<2>(2),3,
FE_DGQ<2>(0),1),2,
2);
// systems with Nedelec elements
CHECK_SYS2 (FE_DGQ<2>(3), 1,
FE_Nedelec<2>(1), 2,
2);
CHECK_SYS3(FE_Nedelec<2>(1), 1,
FESystem<2>(FE_DGQ<2>(3),3), 1,
FESystem<2>(FE_Q<2>(2),3,
FE_Nedelec<2>(1),2),2,
2);
return 0;
}
catch (std::exception &exc)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
};
}
<commit_msg>reduce unreasonable amount of work a bit<commit_after>//---------------------------- dof_tools_common.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2003, 2004, 2005, 2006 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- dof_tools_common.cc ---------------------------
// common framework for the various dof_tools_*.cc tests
#include "../tests.h"
#include <base/logstream.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <grid/grid_generator.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_tools.h>
#include <fe/fe_q.h>
#include <fe/fe_dgq.h>
#include <fe/fe_dgp.h>
#include <fe/fe_nedelec.h>
#include <fe/fe_raviart_thomas.h>
#include <fe/fe_system.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
// forward declaration of the function that must be provided in the
// .cc files
template <int dim>
void
check_this (const DoFHandler<dim> &dof_handler);
// forward declaration of a variable with the name of the output file
extern std::string output_file_name;
void
output_bool_vector (std::vector<bool> &v)
{
for (unsigned int i=0; i<v.size(); ++i)
deallog << (v[i] ? '1' : '0');
deallog << std::endl;
}
template <int dim>
void
set_boundary_ids (Triangulation<dim> &tria)
{
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
tria.begin_active()->face(f)->set_boundary_indicator (f);
}
void
set_boundary_ids (Triangulation<1> &)
{}
template <int dim>
void
check (const FiniteElement<dim> &fe,
const std::string &name)
{
deallog << "Checking " << name
<< " in " << dim << "d:"
<< std::endl;
// create tria and dofhandler
// objects. set different boundary
// and sub-domain ids
Triangulation<dim> tria;
GridGenerator::hyper_cube(tria, 0., 1.);
set_boundary_ids (tria);
tria.refine_global (1);
for (int i=0; i<2; ++i)
{
tria.begin_active()->set_refine_flag();
tria.execute_coarsening_and_refinement ();
}
for (typename Triangulation<dim>::active_cell_iterator
cell=tria.begin_active();
cell!=tria.end(); ++cell)
cell->set_subdomain_id (cell->level());
DoFHandler<dim> dof_handler (tria);
dof_handler.distribute_dofs (fe);
// call main function in .cc files
check_this (dof_handler);
}
#define CHECK(EL,deg,dim)\
{ FE_ ## EL<dim> EL(deg); \
check(EL, #EL #deg); }
#define CHECK_SYS1(sub1,N1,dim) \
{ FESystem<dim> q(sub1, N1); \
check(q, #sub1 #N1); }
#define CHECK_SYS2(sub1,N1,sub2,N2,dim) \
{ FESystem<dim> q(sub1, N1, sub2, N2); \
check(q, #sub1 #N1 #sub2 #N2); }
#define CHECK_SYS3(sub1,N1,sub2,N2,sub3,N3,dim) \
{ FESystem<dim> q(sub1, N1, sub2, N2, sub3, N3); \
check(q, #sub1 #N1 #sub2 #N2 #sub3 #N3); }
#define CHECK_ALL(EL,deg)\
{ CHECK(EL,deg,1); \
CHECK(EL,deg,2); \
CHECK(EL,deg,3); \
}
int
main()
{
try
{
std::ofstream logfile(output_file_name.c_str());
logfile.precision (2);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
CHECK_ALL(Q,1);
CHECK_ALL(Q,2);
CHECK_ALL(Q,3);
CHECK_ALL(DGQ,0);
CHECK_ALL(DGQ,1);
CHECK_ALL(DGQ,3);
CHECK_ALL(DGP,0);
CHECK_ALL(DGP,1);
CHECK_ALL(DGP,3);
CHECK(Nedelec, 1, 2);
CHECK(Nedelec, 1, 3);
CHECK(RaviartThomas, 0, 2);
CHECK(RaviartThomas, 1, 2);
CHECK(RaviartThomas, 2, 2);
CHECK(RaviartThomasNodal, 0, 2);
CHECK(RaviartThomasNodal, 1, 2);
CHECK(RaviartThomasNodal, 2, 2);
CHECK(RaviartThomasNodal, 0, 3);
CHECK(RaviartThomasNodal, 1, 3);
CHECK(RaviartThomasNodal, 2, 3);
CHECK_SYS1(FE_Q<1>(1), 3,1);
CHECK_SYS1(FE_DGQ<1>(2),2,1);
CHECK_SYS1(FE_DGP<1>(3),1,1);
CHECK_SYS1(FE_Q<2>(1), 3,2);
CHECK_SYS1(FE_DGQ<2>(2),2,2);
CHECK_SYS1(FE_DGP<2>(3),1,2);
CHECK_SYS1(FE_Q<3>(1), 3,3);
CHECK_SYS1(FE_DGQ<3>(2),2,3);
CHECK_SYS1(FE_DGP<3>(3),1,3);
CHECK_SYS2(FE_Q<1>(1), 3,FE_DGQ<1>(2),2,1);
CHECK_SYS2(FE_DGQ<1>(2),2,FE_DGP<1>(3),1,1);
CHECK_SYS2(FE_DGP<1>(3),1,FE_DGQ<1>(2),2,1);
CHECK_SYS2(FE_Q<2>(1), 3,FE_DGQ<2>(2),2,2);
CHECK_SYS2(FE_DGQ<2>(2),2,FE_DGP<2>(3),1,2);
CHECK_SYS2(FE_DGP<2>(3),1,FE_DGQ<2>(2),2,2);
CHECK_SYS3(FE_Q<1>(1), 3,FE_DGP<1>(3),1,FE_Q<1>(1),3,1);
CHECK_SYS3(FE_DGQ<1>(2),2,FE_DGQ<1>(2),2,FE_Q<1>(3),3,1);
CHECK_SYS3(FE_DGP<1>(3),1,FE_DGP<1>(3),1,FE_Q<1>(2),3,1);
CHECK_SYS3(FE_Q<2>(1), 3,FE_DGP<2>(3),1,FE_Q<2>(1),3,2);
CHECK_SYS3(FE_DGQ<2>(2),2,FE_DGQ<2>(2),2,FE_Q<2>(3),3,2);
CHECK_SYS3(FE_DGP<2>(3),1,FE_DGP<2>(3),1,FE_Q<2>(2),3,2);
CHECK_SYS3(FE_DGQ<3>(1), 3,FE_DGP<3>(3),1,FE_Q<3>(1),3,3);
// systems of systems
CHECK_SYS3((FESystem<2>(FE_Q<2>(1),3)), 3,
FE_DGQ<2>(0), 1,
FE_Q<2>(1), 3,
2);
CHECK_SYS3(FE_DGQ<2>(3), 1,
FESystem<2>(FE_DGQ<2>(0),3), 1,
FESystem<2>(FE_Q<2>(2),1,
FE_DGQ<2>(0),1),2,
2);
// systems with Nedelec elements
CHECK_SYS2 (FE_DGQ<2>(3), 1,
FE_Nedelec<2>(1), 2,
2);
CHECK_SYS3(FE_Nedelec<2>(1), 1,
FESystem<2>(FE_DGQ<2>(1),2), 1,
FESystem<2>(FE_Q<2>(2),1,
FE_Nedelec<2>(1),2),2,
2);
return 0;
}
catch (std::exception &exc)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
};
}
<|endoftext|> |
<commit_before>#ifdef DE
#include"global.h"
#include"grid3D.h"
#ifdef PARALLEL_OMP
#include"parallel_omp.h"
#endif
bool Grid3D::Select_Internal_Energy_From_DE( Real E, Real U_total, Real U_advected ){
Real eta = DE_LIMIT;
if( U_total / E > eta ) return 0;
else return 1;
}
void Grid3D::Sync_Energies_3D_CPU(){
#ifndef PARALLEL_OMP
Sync_Energies_3D_CPU_function( 0, H.nz_real );
Apply_Temperature_Floor_CPU_function( 0, H.nz_real );
#else
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
int g_start, g_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
Get_OMP_Grid_Indxs( H.nz_real, n_omp_procs, omp_id, &g_start, &g_end );
Sync_Energies_3D_CPU_function( g_start, g_end );
#ifdef TEMPERATURE_FLOOR
#pragma omp barrier
Apply_Temperature_Floor_CPU_function( g_start, g_end );
#endif
}
#endif
}
void Grid3D::Sync_Energies_3D_CPU_function( int g_start, int g_end ){
int nx_grid, ny_grid, nz_grid, nGHST_grid;
nGHST_grid = H.n_ghost;
nx_grid = H.nx;
ny_grid = H.ny;
nz_grid = H.nz;
int nx, ny, nz;
nx = H.nx_real;
ny = H.ny_real;
nz = H.nz_real;
int nGHST = nGHST_grid ;
Real d, d_inv, vx, vy, vz, E, Ek, ge1, ge2, Emax;
int k, j, i, id;
int k_g, j_g, i_g;
int imo, ipo, jmo, jpo, kmo, kpo;
for ( k_g=g_start; k_g<g_end; k_g++ ){
for ( j_g=0; j_g<ny; j_g++ ){
for ( i_g=0; i_g<nx; i_g++ ){
i = i_g + nGHST;
j = j_g + nGHST;
k = k_g + nGHST;
id = (i) + (j)*nx_grid + (k)*ny_grid*nx_grid;
imo = (i-1) + (j)*nx_grid + (k)*ny_grid*nx_grid;
ipo = (i+1) + (j)*nx_grid + (k)*ny_grid*nx_grid;
jmo = (i) + (j-1)*nx_grid + (k)*ny_grid*nx_grid;
jpo = (i) + (j+1)*nx_grid + (k)*ny_grid*nx_grid;
kmo = (i) + (j)*nx_grid + (k-1)*ny_grid*nx_grid;
kpo = (i) + (j)*nx_grid + (k+1)*ny_grid*nx_grid;
d = C.density[id];
d_inv = 1/d;
vx = C.momentum_x[id] * d_inv;
vy = C.momentum_y[id] * d_inv;
vz = C.momentum_z[id] * d_inv;
E = C.Energy[id];
// if (E < 0.0 || E != E) continue; // BUG: This leads to negative Energy
Ek = 0.5*d*(vx*vx + vy*vy + vz*vz);
ge1 = C.GasEnergy[id];
ge2 = E - Ek;
// if (ge2 > 0.0 && E > 0.0 && ge2/E > 0.001 ) {
// C.GasEnergy[id] = ge2;
// ge1 = ge2;
// }
//find the max nearby total energy
Emax = E;
Emax = std::max(C.Energy[imo], E);
Emax = std::max(Emax, C.Energy[ipo]);
Emax = std::max(Emax, C.Energy[jmo]);
Emax = std::max(Emax, C.Energy[jpo]);
Emax = std::max(Emax, C.Energy[kmo]);
Emax = std::max(Emax, C.Energy[kpo]);
if (ge2/Emax > 0.1 && ge2 > 0.0 && Emax > 0.0) {
C.GasEnergy[id] = ge2;
}
// sync the total energy with the internal energy
// else {
// if (ge1 > 0.0) C.Energy[id] += ge1 - ge2;
// else C.GasEnergy[id] = ge2;
// }
}
}
}
}
#ifdef TEMPERATURE_FLOOR
void Grid3D::Apply_Temperature_Floor_CPU_function( int g_start, int g_end ){
Real U_floor = H.temperature_floor / (gama - 1) / MP * KB * 1e-10;
#ifdef COSMOLOGY
U_floor /= Cosmo.v_0_gas * Cosmo.v_0_gas / Cosmo.current_a / Cosmo.current_a;
#endif
int nx_grid, ny_grid, nz_grid, nGHST_grid;
nGHST_grid = H.n_ghost;
nx_grid = H.nx;
ny_grid = H.ny;
nz_grid = H.nz;
int nx, ny, nz;
nx = H.nx_real;
ny = H.ny_real;
nz = H.nz_real;
int nGHST = nGHST_grid ;
Real d, vx, vy, vz, Ekin, E, U, GE;
int k, j, i, id;
for ( k=g_start; k<g_end; k++ ){
for ( j=0; j<ny; j++ ){
for ( i=0; i<nx; i++ ){
id = (i+nGHST) + (j+nGHST)*nx_grid + (k+nGHST)*ny_grid*nx_grid;
d = C.density[id];
vx = C.momentum_x[id] / d;
vy = C.momentum_y[id] / d;
vz = C.momentum_z[id] / d;
Ekin = 0.5 * d * (vx*vx + vy*vy + vz*vz);
E = C.Energy[id];
U = ( E - Ekin ) / d;
if ( U < U_floor ) C.Energy[id] = Ekin + d*U_floor;
#ifdef DE
GE = C.GasEnergy[id];
U = GE / d;
if ( U < U_floor ) C.GasEnergy[id] = d*U_floor;
#endif
}
}
}
}
#endif //TEMPERATURE_FLOOR
#endif<commit_msg>using DE_LIMIT to select wich internal energy to use<commit_after>#ifdef DE
#include"global.h"
#include"grid3D.h"
#ifdef PARALLEL_OMP
#include"parallel_omp.h"
#endif
bool Grid3D::Select_Internal_Energy_From_DE( Real E, Real U_total, Real U_advected ){
Real eta = DE_LIMIT;
if( U_total / E > eta ) return 0;
else return 1;
}
void Grid3D::Sync_Energies_3D_CPU(){
#ifndef PARALLEL_OMP
Sync_Energies_3D_CPU_function( 0, H.nz_real );
Apply_Temperature_Floor_CPU_function( 0, H.nz_real );
#else
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
int g_start, g_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
Get_OMP_Grid_Indxs( H.nz_real, n_omp_procs, omp_id, &g_start, &g_end );
Sync_Energies_3D_CPU_function( g_start, g_end );
#ifdef TEMPERATURE_FLOOR
#pragma omp barrier
Apply_Temperature_Floor_CPU_function( g_start, g_end );
#endif
}
#endif
}
void Grid3D::Sync_Energies_3D_CPU_function( int g_start, int g_end ){
int nx_grid, ny_grid, nz_grid, nGHST_grid;
nGHST_grid = H.n_ghost;
nx_grid = H.nx;
ny_grid = H.ny;
nz_grid = H.nz;
int nx, ny, nz;
nx = H.nx_real;
ny = H.ny_real;
nz = H.nz_real;
int nGHST = nGHST_grid ;
Real d, d_inv, vx, vy, vz, E, Ek, ge1, ge2, Emax;
int k, j, i, id;
int k_g, j_g, i_g;
Real eta = DE_LIMIT;
int imo, ipo, jmo, jpo, kmo, kpo;
for ( k_g=g_start; k_g<g_end; k_g++ ){
for ( j_g=0; j_g<ny; j_g++ ){
for ( i_g=0; i_g<nx; i_g++ ){
i = i_g + nGHST;
j = j_g + nGHST;
k = k_g + nGHST;
id = (i) + (j)*nx_grid + (k)*ny_grid*nx_grid;
imo = (i-1) + (j)*nx_grid + (k)*ny_grid*nx_grid;
ipo = (i+1) + (j)*nx_grid + (k)*ny_grid*nx_grid;
jmo = (i) + (j-1)*nx_grid + (k)*ny_grid*nx_grid;
jpo = (i) + (j+1)*nx_grid + (k)*ny_grid*nx_grid;
kmo = (i) + (j)*nx_grid + (k-1)*ny_grid*nx_grid;
kpo = (i) + (j)*nx_grid + (k+1)*ny_grid*nx_grid;
d = C.density[id];
d_inv = 1/d;
vx = C.momentum_x[id] * d_inv;
vy = C.momentum_y[id] * d_inv;
vz = C.momentum_z[id] * d_inv;
E = C.Energy[id];
// if (E < 0.0 || E != E) continue; // BUG: This leads to negative Energy
Ek = 0.5*d*(vx*vx + vy*vy + vz*vz);
ge1 = C.GasEnergy[id];
ge2 = E - Ek;
if (ge2 > 0.0 && E > 0.0 && ge2/E > eta ) {
C.GasEnergy[id] = ge2;
ge1 = ge2;
}
//find the max nearby total energy
Emax = E;
Emax = std::max(C.Energy[imo], E);
Emax = std::max(Emax, C.Energy[ipo]);
Emax = std::max(Emax, C.Energy[jmo]);
Emax = std::max(Emax, C.Energy[jpo]);
Emax = std::max(Emax, C.Energy[kmo]);
Emax = std::max(Emax, C.Energy[kpo]);
if (ge2/Emax > 0.1 && ge2 > 0.0 && Emax > 0.0) {
C.GasEnergy[id] = ge2;
}
// sync the total energy with the internal energy
else {
if (ge1 > 0.0) C.Energy[id] += ge1 - ge2;
else C.GasEnergy[id] = ge2;
}
}
}
}
}
#ifdef TEMPERATURE_FLOOR
void Grid3D::Apply_Temperature_Floor_CPU_function( int g_start, int g_end ){
Real U_floor = H.temperature_floor / (gama - 1) / MP * KB * 1e-10;
#ifdef COSMOLOGY
U_floor /= Cosmo.v_0_gas * Cosmo.v_0_gas / Cosmo.current_a / Cosmo.current_a;
#endif
int nx_grid, ny_grid, nz_grid, nGHST_grid;
nGHST_grid = H.n_ghost;
nx_grid = H.nx;
ny_grid = H.ny;
nz_grid = H.nz;
int nx, ny, nz;
nx = H.nx_real;
ny = H.ny_real;
nz = H.nz_real;
int nGHST = nGHST_grid ;
Real d, vx, vy, vz, Ekin, E, U, GE;
int k, j, i, id;
for ( k=g_start; k<g_end; k++ ){
for ( j=0; j<ny; j++ ){
for ( i=0; i<nx; i++ ){
id = (i+nGHST) + (j+nGHST)*nx_grid + (k+nGHST)*ny_grid*nx_grid;
d = C.density[id];
vx = C.momentum_x[id] / d;
vy = C.momentum_y[id] / d;
vz = C.momentum_z[id] / d;
Ekin = 0.5 * d * (vx*vx + vy*vy + vz*vz);
E = C.Energy[id];
U = ( E - Ekin ) / d;
if ( U < U_floor ) C.Energy[id] = Ekin + d*U_floor;
#ifdef DE
GE = C.GasEnergy[id];
U = GE / d;
if ( U < U_floor ) C.GasEnergy[id] = d*U_floor;
#endif
}
}
}
}
#endif //TEMPERATURE_FLOOR
#endif<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qjsengine.h"
#include "qjsengine_p.h"
#include "qjsvalue.h"
#include "qjsvalue_p.h"
#include "qv8engine_p.h"
#include "private/qv4engine_p.h"
#include "private/qv4mm_p.h"
#include "private/qv4globalobject_p.h"
#include <QtCore/qdatetime.h>
#include <QtCore/qmetaobject.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qvariant.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qdir.h>
#include <QtCore/qfile.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qpluginloader.h>
#include <qthread.h>
#include <qmutex.h>
#include <qwaitcondition.h>
#include <private/qqmlglobal_p.h>
#undef Q_D
#undef Q_Q
#define Q_D(blah)
#define Q_Q(blah)
Q_DECLARE_METATYPE(QObjectList)
Q_DECLARE_METATYPE(QList<int>)
/*!
\since 5.0
\class QJSEngine
\brief The QJSEngine class provides an environment for evaluating JavaScript code.
\ingroup qtjavascript
\inmodule QtQml
\mainclass
\section1 Evaluating Scripts
Use evaluate() to evaluate script code.
\snippet code/src_script_qjsengine.cpp 0
evaluate() returns a QJSValue that holds the result of the
evaluation. The QJSValue class provides functions for converting
the result to various C++ types (e.g. QJSValue::toString()
and QJSValue::toNumber()).
The following code snippet shows how a script function can be
defined and then invoked from C++ using QJSValue::call():
\snippet code/src_script_qjsengine.cpp 1
As can be seen from the above snippets, a script is provided to the
engine in the form of a string. One common way of loading scripts is
by reading the contents of a file and passing it to evaluate():
\snippet code/src_script_qjsengine.cpp 2
Here we pass the name of the file as the second argument to
evaluate(). This does not affect evaluation in any way; the second
argument is a general-purpose string that is used to identify the
script for debugging purposes.
\section1 Engine Configuration
The globalObject() function returns the \b {Global Object}
associated with the script engine. Properties of the Global Object
are accessible from any script code (i.e. they are global
variables). Typically, before evaluating "user" scripts, you will
want to configure a script engine by adding one or more properties
to the Global Object:
\snippet code/src_script_qjsengine.cpp 3
Adding custom properties to the scripting environment is one of the
standard means of providing a scripting API that is specific to your
application. Usually these custom properties are objects created by
the newQObject() or newObject() functions.
\section1 Script Exceptions
evaluate() can throw a script exception (e.g. due to a syntax
error); in that case, the return value is the value that was thrown
(typically an \c{Error} object). You can check whether the
evaluation caused an exception by calling isError() on the return
value. If isError() returns true, you can call toString() on the
error object to obtain an error message.
\snippet code/src_script_qjsengine.cpp 4
\section1 Script Object Creation
Use newObject() to create a JavaScript object; this is the
C++ equivalent of the script statement \c{new Object()}. You can use
the object-specific functionality in QJSValue to manipulate the
script object (e.g. QJSValue::setProperty()). Similarly, use
newArray() to create a JavaScript array object.
\section1 QObject Integration
Use newQObject() to wrap a QObject (or subclass)
pointer. newQObject() returns a proxy script object; properties,
children, and signals and slots of the QObject are available as
properties of the proxy object. No binding code is needed because it
is done dynamically using the Qt meta object system.
\snippet code/src_script_qjsengine.cpp 5
\sa QJSValue, {Making Applications Scriptable}
*/
QT_BEGIN_NAMESPACE
/*!
Constructs a QJSEngine object.
The globalObject() is initialized to have properties as described in
\l{ECMA-262}, Section 15.1.
*/
QJSEngine::QJSEngine()
: d(new QV8Engine(this))
{
}
/*!
Constructs a QJSEngine object with the given \a parent.
The globalObject() is initialized to have properties as described in
\l{ECMA-262}, Section 15.1.
*/
QJSEngine::QJSEngine(QObject *parent)
: QObject(parent)
, d(new QV8Engine(this))
{
}
/*!
\internal
*/
QJSEngine::QJSEngine(QJSEnginePrivate &dd, QObject *parent)
: QObject(dd, parent)
, d(new QV8Engine(this))
{
}
/*!
Destroys this QJSEngine.
*/
QJSEngine::~QJSEngine()
{
delete d;
}
/*!
\fn QV8Engine *QJSEngine::handle() const
\internal
*/
/*!
Runs the garbage collector.
The garbage collector will attempt to reclaim memory by locating and disposing of objects that are
no longer reachable in the script environment.
Normally you don't need to call this function; the garbage collector will automatically be invoked
when the QJSEngine decides that it's wise to do so (i.e. when a certain number of new objects
have been created). However, you can call this function to explicitly request that garbage
collection should be performed as soon as possible.
*/
void QJSEngine::collectGarbage()
{
d->m_v4Engine->memoryManager->runGC();
}
/*!
Evaluates \a program, using \a lineNumber as the base line number,
and returns the result of the evaluation.
The script code will be evaluated in the current context.
The evaluation of \a program can cause an exception in the
engine; in this case the return value will be the exception
that was thrown (typically an \c{Error} object; see
QJSValue::isError()).
\a lineNumber is used to specify a starting line number for \a
program; line number information reported by the engine that pertain
to this evaluation will be based on this argument. For example, if
\a program consists of two lines of code, and the statement on the
second line causes a script exception, the exception line number
would be \a lineNumber plus one. When no starting line number is
specified, line numbers will be 1-based.
\a fileName is used for error reporting. For example in error objects
the file name is accessible through the "fileName" property if it's
provided with this function.
\note If an exception was thrown and the exception value is not an
Error instance (i.e., QJSValue::isError() returns false), the
exception value will still be returned, but there is currently no
API for detecting that an exception did occur in this case.
*/
QJSValue QJSEngine::evaluate(const QString& program, const QString& fileName, int lineNumber)
{
try {
QV4::Function *f = QV4::EvalFunction::parseSource(d->m_v4Engine->current, fileName, program, QQmlJS::Codegen::EvalCode,
d->m_v4Engine->current->strictMode, true);
if (!f)
return new QJSValuePrivate(d->m_v4Engine, d->m_v4Engine->newSyntaxErrorObject(QString()));
QV4::Value result = d->m_v4Engine->run(f);
return new QJSValuePrivate(d->m_v4Engine, result);
} catch (QV4::Exception& ex) {
ex.accept(d->m_v4Engine->current);
return new QJSValuePrivate(d->m_v4Engine, ex.value());
}
}
/*!
Creates a JavaScript object of class Object.
The prototype of the created object will be the Object
prototype object.
\sa newArray(), QJSValue::setProperty()
*/
QJSValue QJSEngine::newObject()
{
return new QJSValuePrivate(d->m_v4Engine, d->m_v4Engine->newObject());
}
/*!
Creates a JavaScript object of class Array with the given \a length.
\sa newObject()
*/
QJSValue QJSEngine::newArray(uint length)
{
QV4::ArrayObject *array = d->m_v4Engine->newArrayObject();
if (length < 0x1000)
array->arrayReserve(length);
array->setArrayLengthUnchecked(length);
return new QJSValuePrivate(d->m_v4Engine, array);
}
/*!
Creates a JavaScript object that wraps the given QObject \a
object, using JavaScriptOwnership.
Signals and slots, properties and children of \a object are
available as properties of the created QJSValue.
If \a object is a null pointer, this function returns a null value.
If a default prototype has been registered for the \a object's class
(or its superclass, recursively), the prototype of the new script
object will be set to be that default prototype.
If the given \a object is deleted outside of the engine's control, any
attempt to access the deleted QObject's members through the JavaScript
wrapper object (either by script code or C++) will result in a
script exception.
\sa QJSValue::toQObject()
*/
QJSValue QJSEngine::newQObject(QObject *object)
{
// ###
Q_D(QJSEngine);
return d->scriptValueFromInternal(d->newQObject(object, QV8Engine::JavaScriptOwnership));
}
/*!
Returns this engine's Global Object.
By default, the Global Object contains the built-in objects that are
part of \l{ECMA-262}, such as Math, Date and String. Additionally,
you can set properties of the Global Object to make your own
extensions available to all script code. Non-local variables in
script code will be created as properties of the Global Object, as
well as local variables in global code.
*/
QJSValue QJSEngine::globalObject() const
{
return new QJSValuePrivate(d->m_v4Engine, d->m_v4Engine->globalObject);
}
/*!
* \internal
* used by QJSEngine::toScriptValue
*/
QJSValue QJSEngine::create(int type, const void *ptr)
{
Q_D(QJSEngine);
return new QJSValuePrivate(QV8Engine::getV4(d), d->metaTypeToJS(type, ptr));
}
/*!
\internal
convert \a value to \a type, store the result in \a ptr
*/
bool QJSEngine::convertV2(const QJSValue &value, int type, void *ptr)
{
QJSValuePrivate *vp = QJSValuePrivate::get(value);
QV4::ExecutionEngine *e = vp->engine;
QV8Engine *engine = e ? QV8Engine::get(e->publicEngine) : 0;
if (engine) {
return engine->metaTypeFromJS(vp->getValue(engine->m_v4Engine), type, ptr);
} else {
switch (type) {
case QMetaType::Bool:
*reinterpret_cast<bool*>(ptr) = vp->value.toBoolean();
return true;
case QMetaType::Int:
*reinterpret_cast<int*>(ptr) = vp->value.toInt32();
return true;
case QMetaType::UInt:
*reinterpret_cast<uint*>(ptr) = vp->value.toUInt32();
return true;
case QMetaType::LongLong:
*reinterpret_cast<qlonglong*>(ptr) = vp->value.toInteger();
return true;
case QMetaType::ULongLong:
*reinterpret_cast<qulonglong*>(ptr) = vp->value.toInteger();
return true;
case QMetaType::Double:
*reinterpret_cast<double*>(ptr) = vp->value.toNumber();
return true;
case QMetaType::QString:
*reinterpret_cast<QString*>(ptr) = value.toString();
return true;
case QMetaType::Float:
*reinterpret_cast<float*>(ptr) = vp->value.toNumber();
return true;
case QMetaType::Short:
*reinterpret_cast<short*>(ptr) = vp->value.toInt32();
return true;
case QMetaType::UShort:
*reinterpret_cast<unsigned short*>(ptr) = vp->value.toUInt16();
return true;
case QMetaType::Char:
*reinterpret_cast<char*>(ptr) = vp->value.toInt32();
return true;
case QMetaType::UChar:
*reinterpret_cast<unsigned char*>(ptr) = vp->value.toUInt16();
return true;
case QMetaType::QChar:
*reinterpret_cast<QChar*>(ptr) = vp->value.toUInt16();
return true;
default:
return false;
}
}
}
/*! \fn QJSValue QJSEngine::toScriptValue(const T &value)
Creates a QJSValue with the given \a value.
\sa fromScriptValue()
*/
/*! \fn T QJSEngine::fromScriptValue(const QJSValue &value)
Returns the given \a value converted to the template type \c{T}.
\sa toScriptValue()
*/
QT_END_NAMESPACE
#include "moc_qjsengine.cpp"
<commit_msg>Fix QJSEngine::evaluate<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qjsengine.h"
#include "qjsengine_p.h"
#include "qjsvalue.h"
#include "qjsvalue_p.h"
#include "qv8engine_p.h"
#include "private/qv4engine_p.h"
#include "private/qv4mm_p.h"
#include "private/qv4globalobject_p.h"
#include <QtCore/qdatetime.h>
#include <QtCore/qmetaobject.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qvariant.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qdir.h>
#include <QtCore/qfile.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qpluginloader.h>
#include <qthread.h>
#include <qmutex.h>
#include <qwaitcondition.h>
#include <private/qqmlglobal_p.h>
#undef Q_D
#undef Q_Q
#define Q_D(blah)
#define Q_Q(blah)
Q_DECLARE_METATYPE(QObjectList)
Q_DECLARE_METATYPE(QList<int>)
/*!
\since 5.0
\class QJSEngine
\brief The QJSEngine class provides an environment for evaluating JavaScript code.
\ingroup qtjavascript
\inmodule QtQml
\mainclass
\section1 Evaluating Scripts
Use evaluate() to evaluate script code.
\snippet code/src_script_qjsengine.cpp 0
evaluate() returns a QJSValue that holds the result of the
evaluation. The QJSValue class provides functions for converting
the result to various C++ types (e.g. QJSValue::toString()
and QJSValue::toNumber()).
The following code snippet shows how a script function can be
defined and then invoked from C++ using QJSValue::call():
\snippet code/src_script_qjsengine.cpp 1
As can be seen from the above snippets, a script is provided to the
engine in the form of a string. One common way of loading scripts is
by reading the contents of a file and passing it to evaluate():
\snippet code/src_script_qjsengine.cpp 2
Here we pass the name of the file as the second argument to
evaluate(). This does not affect evaluation in any way; the second
argument is a general-purpose string that is used to identify the
script for debugging purposes.
\section1 Engine Configuration
The globalObject() function returns the \b {Global Object}
associated with the script engine. Properties of the Global Object
are accessible from any script code (i.e. they are global
variables). Typically, before evaluating "user" scripts, you will
want to configure a script engine by adding one or more properties
to the Global Object:
\snippet code/src_script_qjsengine.cpp 3
Adding custom properties to the scripting environment is one of the
standard means of providing a scripting API that is specific to your
application. Usually these custom properties are objects created by
the newQObject() or newObject() functions.
\section1 Script Exceptions
evaluate() can throw a script exception (e.g. due to a syntax
error); in that case, the return value is the value that was thrown
(typically an \c{Error} object). You can check whether the
evaluation caused an exception by calling isError() on the return
value. If isError() returns true, you can call toString() on the
error object to obtain an error message.
\snippet code/src_script_qjsengine.cpp 4
\section1 Script Object Creation
Use newObject() to create a JavaScript object; this is the
C++ equivalent of the script statement \c{new Object()}. You can use
the object-specific functionality in QJSValue to manipulate the
script object (e.g. QJSValue::setProperty()). Similarly, use
newArray() to create a JavaScript array object.
\section1 QObject Integration
Use newQObject() to wrap a QObject (or subclass)
pointer. newQObject() returns a proxy script object; properties,
children, and signals and slots of the QObject are available as
properties of the proxy object. No binding code is needed because it
is done dynamically using the Qt meta object system.
\snippet code/src_script_qjsengine.cpp 5
\sa QJSValue, {Making Applications Scriptable}
*/
QT_BEGIN_NAMESPACE
/*!
Constructs a QJSEngine object.
The globalObject() is initialized to have properties as described in
\l{ECMA-262}, Section 15.1.
*/
QJSEngine::QJSEngine()
: d(new QV8Engine(this))
{
}
/*!
Constructs a QJSEngine object with the given \a parent.
The globalObject() is initialized to have properties as described in
\l{ECMA-262}, Section 15.1.
*/
QJSEngine::QJSEngine(QObject *parent)
: QObject(parent)
, d(new QV8Engine(this))
{
}
/*!
\internal
*/
QJSEngine::QJSEngine(QJSEnginePrivate &dd, QObject *parent)
: QObject(dd, parent)
, d(new QV8Engine(this))
{
}
/*!
Destroys this QJSEngine.
*/
QJSEngine::~QJSEngine()
{
delete d;
}
/*!
\fn QV8Engine *QJSEngine::handle() const
\internal
*/
/*!
Runs the garbage collector.
The garbage collector will attempt to reclaim memory by locating and disposing of objects that are
no longer reachable in the script environment.
Normally you don't need to call this function; the garbage collector will automatically be invoked
when the QJSEngine decides that it's wise to do so (i.e. when a certain number of new objects
have been created). However, you can call this function to explicitly request that garbage
collection should be performed as soon as possible.
*/
void QJSEngine::collectGarbage()
{
d->m_v4Engine->memoryManager->runGC();
}
/*!
Evaluates \a program, using \a lineNumber as the base line number,
and returns the result of the evaluation.
The script code will be evaluated in the current context.
The evaluation of \a program can cause an exception in the
engine; in this case the return value will be the exception
that was thrown (typically an \c{Error} object; see
QJSValue::isError()).
\a lineNumber is used to specify a starting line number for \a
program; line number information reported by the engine that pertain
to this evaluation will be based on this argument. For example, if
\a program consists of two lines of code, and the statement on the
second line causes a script exception, the exception line number
would be \a lineNumber plus one. When no starting line number is
specified, line numbers will be 1-based.
\a fileName is used for error reporting. For example in error objects
the file name is accessible through the "fileName" property if it's
provided with this function.
\note If an exception was thrown and the exception value is not an
Error instance (i.e., QJSValue::isError() returns false), the
exception value will still be returned, but there is currently no
API for detecting that an exception did occur in this case.
*/
QJSValue QJSEngine::evaluate(const QString& program, const QString& fileName, int lineNumber)
{
try {
QV4::Function *f = QV4::EvalFunction::parseSource(d->m_v4Engine->current, fileName, program, QQmlJS::Codegen::EvalCode,
d->m_v4Engine->current->strictMode, true);
if (!f)
return QJSValue();
QV4::Value result = d->m_v4Engine->run(f);
return new QJSValuePrivate(d->m_v4Engine, result);
} catch (QV4::Exception& ex) {
ex.accept(d->m_v4Engine->current);
return new QJSValuePrivate(d->m_v4Engine, ex.value());
}
}
/*!
Creates a JavaScript object of class Object.
The prototype of the created object will be the Object
prototype object.
\sa newArray(), QJSValue::setProperty()
*/
QJSValue QJSEngine::newObject()
{
return new QJSValuePrivate(d->m_v4Engine, d->m_v4Engine->newObject());
}
/*!
Creates a JavaScript object of class Array with the given \a length.
\sa newObject()
*/
QJSValue QJSEngine::newArray(uint length)
{
QV4::ArrayObject *array = d->m_v4Engine->newArrayObject();
if (length < 0x1000)
array->arrayReserve(length);
array->setArrayLengthUnchecked(length);
return new QJSValuePrivate(d->m_v4Engine, array);
}
/*!
Creates a JavaScript object that wraps the given QObject \a
object, using JavaScriptOwnership.
Signals and slots, properties and children of \a object are
available as properties of the created QJSValue.
If \a object is a null pointer, this function returns a null value.
If a default prototype has been registered for the \a object's class
(or its superclass, recursively), the prototype of the new script
object will be set to be that default prototype.
If the given \a object is deleted outside of the engine's control, any
attempt to access the deleted QObject's members through the JavaScript
wrapper object (either by script code or C++) will result in a
script exception.
\sa QJSValue::toQObject()
*/
QJSValue QJSEngine::newQObject(QObject *object)
{
// ###
Q_D(QJSEngine);
return d->scriptValueFromInternal(d->newQObject(object, QV8Engine::JavaScriptOwnership));
}
/*!
Returns this engine's Global Object.
By default, the Global Object contains the built-in objects that are
part of \l{ECMA-262}, such as Math, Date and String. Additionally,
you can set properties of the Global Object to make your own
extensions available to all script code. Non-local variables in
script code will be created as properties of the Global Object, as
well as local variables in global code.
*/
QJSValue QJSEngine::globalObject() const
{
return new QJSValuePrivate(d->m_v4Engine, d->m_v4Engine->globalObject);
}
/*!
* \internal
* used by QJSEngine::toScriptValue
*/
QJSValue QJSEngine::create(int type, const void *ptr)
{
Q_D(QJSEngine);
return new QJSValuePrivate(QV8Engine::getV4(d), d->metaTypeToJS(type, ptr));
}
/*!
\internal
convert \a value to \a type, store the result in \a ptr
*/
bool QJSEngine::convertV2(const QJSValue &value, int type, void *ptr)
{
QJSValuePrivate *vp = QJSValuePrivate::get(value);
QV4::ExecutionEngine *e = vp->engine;
QV8Engine *engine = e ? QV8Engine::get(e->publicEngine) : 0;
if (engine) {
return engine->metaTypeFromJS(vp->getValue(engine->m_v4Engine), type, ptr);
} else {
switch (type) {
case QMetaType::Bool:
*reinterpret_cast<bool*>(ptr) = vp->value.toBoolean();
return true;
case QMetaType::Int:
*reinterpret_cast<int*>(ptr) = vp->value.toInt32();
return true;
case QMetaType::UInt:
*reinterpret_cast<uint*>(ptr) = vp->value.toUInt32();
return true;
case QMetaType::LongLong:
*reinterpret_cast<qlonglong*>(ptr) = vp->value.toInteger();
return true;
case QMetaType::ULongLong:
*reinterpret_cast<qulonglong*>(ptr) = vp->value.toInteger();
return true;
case QMetaType::Double:
*reinterpret_cast<double*>(ptr) = vp->value.toNumber();
return true;
case QMetaType::QString:
*reinterpret_cast<QString*>(ptr) = value.toString();
return true;
case QMetaType::Float:
*reinterpret_cast<float*>(ptr) = vp->value.toNumber();
return true;
case QMetaType::Short:
*reinterpret_cast<short*>(ptr) = vp->value.toInt32();
return true;
case QMetaType::UShort:
*reinterpret_cast<unsigned short*>(ptr) = vp->value.toUInt16();
return true;
case QMetaType::Char:
*reinterpret_cast<char*>(ptr) = vp->value.toInt32();
return true;
case QMetaType::UChar:
*reinterpret_cast<unsigned char*>(ptr) = vp->value.toUInt16();
return true;
case QMetaType::QChar:
*reinterpret_cast<QChar*>(ptr) = vp->value.toUInt16();
return true;
default:
return false;
}
}
}
/*! \fn QJSValue QJSEngine::toScriptValue(const T &value)
Creates a QJSValue with the given \a value.
\sa fromScriptValue()
*/
/*! \fn T QJSEngine::fromScriptValue(const QJSValue &value)
Returns the given \a value converted to the template type \c{T}.
\sa toScriptValue()
*/
QT_END_NAMESPACE
#include "moc_qjsengine.cpp"
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2017 PX4 Development Team. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file PositionControl.cpp
*
* This file implements a P-position-control cascaded with a
* PID-velocity-controller.
*
* Inputs: vehicle states (pos, vel, q)
* desired setpoints (pos, vel, thrust, yaw)
* Outputs: thrust and yaw setpoint
*/
#include "PositionControl.hpp"
#include <float.h>
#include <mathlib/mathlib.h>
#include "uORB/topics/parameter_update.h"
#include "Utility/ControlMath.hpp"
#include <lib/ecl/geo/geo.h> //TODO: only used for wrap_pi -> move this to mathlib since
// it makes more sense
using namespace matrix;
using Data = matrix::Vector3f;
PositionControl::PositionControl()
{
_Pz_h = param_find("MPC_Z_P");
_Pvz_h = param_find("MPC_Z_VEL_P");
_Ivz_h = param_find("MPC_Z_VEL_I");
_Dvz_h = param_find("MPC_Z_VEL_D");
_Pxy_h = param_find("MPC_XY_P");
_Pvxy_h = param_find("MPC_XY_VEL_P");
_Ivxy_h = param_find("MPC_XY_VEL_I");
_Dvxy_h = param_find("MPC_XY_VEL_D");
_VelMaxXY = param_find("MPC_XY_VEL_MAX");
_VelMaxZdown_h = param_find("MPC_Z_VEL_MAX_DN");
_VelMaxZup_h = param_find("MPC_Z_VEL_MAX_UP");
_ThrHover_h = param_find("MPC_THR_HOVER");
_ThrMax_h = param_find("MPC_THR_MAX");
_ThrMin_h = param_find("MPC_THR_MIN");
_YawRateMax_h = param_find("MPC_MAN_Y_MAX");
_Pyaw_h = param_find("MC_YAW_P");
/* Set parameter the very first time. */
_setParams();
};
void PositionControl::updateState(const struct vehicle_local_position_s state, const Data &vel_dot)
{
_pos = Data(&state.x);
_vel = Data(&state.vx);
_yaw = state.yaw;
_vel_dot = vel_dot;
}
void PositionControl::updateSetpoint(struct vehicle_local_position_setpoint_s setpoint)
{
_pos_sp = Data(&setpoint.x);
_vel_sp = Data(&setpoint.vx);
_acc_sp = Data(&setpoint.acc_x);
_thr_sp = Data(setpoint.thrust);
_yaw_sp = setpoint.yaw; //integrate
_yawspeed_sp = setpoint.yawspeed;
_interfaceMapping();
/* If full manual is required (thrust already generated), don't run position/velocity
* controller and just return thrust.
*/
_skipController = false;
if (PX4_ISFINITE(setpoint.thrust[0]) && PX4_ISFINITE(setpoint.thrust[1]) && PX4_ISFINITE(setpoint.thrust[2])) {
_skipController = true;
}
}
void PositionControl::generateThrustYawSetpoint(const float &dt)
{
_updateParams();
/* Only run position/velocity controller
* if thrust needs to be generated
*/
if (!_skipController) {
_positionController();
_velocityController(dt);
}
_yawController(dt);
}
void PositionControl::_interfaceMapping()
{
/* Respects FlightTask interface, where
* NAN-setpoints are of no interest and
* do not require control.
*/
/* Loop through x,y and z components of all setpoints. */
for (int i = 0; i <= 2; i++) {
if (PX4_ISFINITE(_pos_sp(i))) {
/* Position control is required */
if (!PX4_ISFINITE(_vel_sp(i))) {
/* Velocity is not used as feedforward term. */
_vel_sp(i) = 0.0f;
}
/* thrust setpoint is not supported
* in position control
*/
_thr_sp(i) = 0.0f;
} else if (PX4_ISFINITE(_vel_sp(i))) {
/* Velocity controller is active without
* position control.
*/
_pos_sp(i) = _pos(i);
_thr_sp(i) = 0.0f;
} else if (PX4_ISFINITE(_thr_sp(i))) {
/* Thrust setpoint was generated from
* stick directly.
*/
_pos_sp(i) = _pos(i);
_vel_sp(i) = _vel(i);
_thr_int(i) = 0.0f;
_vel_dot(i) = 0.0f;
} else {
PX4_WARN("TODO: add safety");
}
}
if (!PX4_ISFINITE(_yawspeed_sp)) {
/* Target yaw is yaw setpoint. No need for yawspeed */
_yawspeed_sp = 0.0f;
if (!PX4_ISFINITE(_yaw_sp)) {
/* There is no finite setpoint. The best
* we can do is to just re-use old setpoint */
_yaw_sp = _yaw_sp_int;
}
} else if (!PX4_ISFINITE(_yaw_sp)) {
/* Nothing is finite: Best we can do is to just
* reuse old setpoint.
*/
_yaw_sp = _yaw_sp_int;
}
}
void PositionControl::_positionController()
{
/* Generate desired velocity setpoint */
/* P-controller */
_vel_sp = (_pos_sp - _pos).emult(Pp) + _vel_sp;
/* Make sure velocity setpoint is constrained in all directions (xyz). */
float vel_norm_xy = sqrtf(_vel_sp(0) * _vel_sp(0) + _vel_sp(1) * _vel_sp(1));
if (vel_norm_xy > _VelMaxXY) {
_vel_sp(0) = _vel_sp(0) * _VelMaxXY / vel_norm_xy;
_vel_sp(1) = _vel_sp(1) * _VelMaxXY / vel_norm_xy;
}
_vel_sp(2) = math::constrain(_vel_sp(2), -_VelMaxZ[0], _VelMaxZ[1]);
}
void PositionControl::_velocityController(const float &dt)
{
/* Generate desired thrust setpoint */
/* PID
* u_des = P(vel_err) + D(vel_err_dot) + I(vel_integral)
* Umin <= u_des <= Umax
*
* Saturation for vel_integral;
* u_des = _thr_sp; r = _vel_sp; y = _vel
* u_des >= Umax and r - y >= 0 => Saturation = true
* u_des >= Umax and r - y <= 0 => Saturation = false
* u_des <= Umin and r - y <= 0 => Saturation = true
* u_des <= Umin and r - y >= 0 => Saturation = false
*
*/
Data vel_err = _vel_sp - _vel;
/* TODO: add offboard acceleration mode
* PID-controller */
Data offset(0.0f, 0.0f, _ThrHover);
Data thr_sp = Pv.emult(vel_err) + Dv.emult(_vel_dot) + _thr_int - offset;
/* Get maximum tilt */
float tilt_max = PX4_ISFINITE(_constraints.tilt_max) ? _constraints.tilt_max : M_PI_2_F;
tilt_max = math::min(tilt_max, M_PI_2_F);
/* Compute maximum allowed thrust along xy based on thrust in z-direction and
* scale _thrust_sp by that value. This only has an effect for altitude mode where
* _thr_sp(0:1).length() > 0.0f.
*/
if (matrix::Vector2f(&_thr_sp(0)).length() > FLT_EPSILON) {
float thr_xy_max = fabsf(thr_sp(2)) * tanf(tilt_max);
_thr_sp(0) *= thr_xy_max;
_thr_sp(1) *= thr_xy_max;
}
_thr_sp += thr_sp;
/* Limit tilt with priority on z
* For manual controlled mode excluding pure manual and rate control, maximum tilt is 90;
* It is to note that pure manual and rate control will never enter _velocityController method. */
_thr_sp = ControlMath::constrainTilt(_thr_sp, tilt_max);
/* Constrain thrust set-point and update saturation flag */
/* To get (r-y) for horizontal direction, we look at the dot-product
* for vel_err and _vel_sp. The sign of the dot product indicates
* if (r-y) is greater or smaller than 0
*/
float dot_xy = matrix::Vector2f(&vel_err(0)) * matrix::Vector2f(&_vel_sp(0));
float direction[2] = {dot_xy, -vel_err(2)}; // negative sign because of N-E-D
bool stop_I[2] = {false, false}; // stop integration for xy and z
ControlMath::constrainPIDu(_thr_sp, stop_I, _ThrLimit, direction);
/* Update integrals */
if (!stop_I[0]) {
_thr_int(0) += vel_err(0) * Iv(0) * dt;
_thr_int(1) += vel_err(1) * Iv(1) * dt;
}
if (!stop_I[1]) {
_thr_int(2) += vel_err(2) * Iv(2) * dt;
}
}
void PositionControl::_yawController(const float &dt)
{
const float yaw_offset_max = math::radians(_YawRateMax) / _Pyaw;
const float yaw_target = _wrap_pi(_yaw_sp + _yawspeed_sp * dt);
const float yaw_offset = _wrap_pi(yaw_target - _yaw);
// If the yaw offset became too big for the system to track stop
// shifting it, only allow if it would make the offset smaller again.
if (fabsf(yaw_offset) < yaw_offset_max || (_yawspeed_sp > 0 && yaw_offset < 0)
|| (_yawspeed_sp < 0 && yaw_offset > 0)) {
_yaw_sp = yaw_target;
}
/* Update yaw setpoint integral */
_yaw_sp_int = _yaw_sp;
}
void PositionControl::updateConstraints(const Controller::Constraints &constraints)
{
_constraints = constraints;
}
void PositionControl::_updateParams()
{
bool updated;
parameter_update_s param_update;
orb_check(_parameter_sub, &updated);
if (updated) {
orb_copy(ORB_ID(parameter_update), _parameter_sub, ¶m_update);
_setParams();
}
}
void PositionControl::_setParams()
{
param_get(_Pxy_h, &Pp(0));
param_get(_Pxy_h, &Pp(1));
param_get(_Pz_h, &Pp(2));
param_get(_Pvxy_h, &Pv(0));
param_get(_Pvxy_h, &Pv(1));
param_get(_Pvz_h, &Pv(2));
param_get(_Ivxy_h, &Iv(0));
param_get(_Ivxy_h, &Iv(1));
param_get(_Ivz_h, &Iv(2));
param_get(_Dvxy_h, &Dv(0));
param_get(_Dvxy_h, &Dv(1));
param_get(_Dvz_h, &Dv(2));
param_get(_VelMaxXY_h, &_VelMaxXY);
param_get(_VelMaxZup_h, &_VelMaxZ[0]);
param_get(_VelMaxZdown_h, &_VelMaxZ[1]);
param_get(_ThrHover_h, &_ThrHover);
param_get(_ThrMax_h, &_ThrLimit[0]);
param_get(_ThrMin_h, &_ThrLimit[1]);
param_get(_YawRateMax_h, &_YawRateMax);
param_get(_Pyaw_h, &_Pyaw);
}
<commit_msg>PositionControl: parameter naming fix<commit_after>/****************************************************************************
*
* Copyright (c) 2017 PX4 Development Team. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file PositionControl.cpp
*
* This file implements a P-position-control cascaded with a
* PID-velocity-controller.
*
* Inputs: vehicle states (pos, vel, q)
* desired setpoints (pos, vel, thrust, yaw)
* Outputs: thrust and yaw setpoint
*/
#include "PositionControl.hpp"
#include <float.h>
#include <mathlib/mathlib.h>
#include "uORB/topics/parameter_update.h"
#include "Utility/ControlMath.hpp"
#include <lib/ecl/geo/geo.h> //TODO: only used for wrap_pi -> move this to mathlib since
// it makes more sense
using namespace matrix;
using Data = matrix::Vector3f;
PositionControl::PositionControl()
{
_Pz_h = param_find("MPC_Z_P");
_Pvz_h = param_find("MPC_Z_VEL_P");
_Ivz_h = param_find("MPC_Z_VEL_I");
_Dvz_h = param_find("MPC_Z_VEL_D");
_Pxy_h = param_find("MPC_XY_P");
_Pvxy_h = param_find("MPC_XY_VEL_P");
_Ivxy_h = param_find("MPC_XY_VEL_I");
_Dvxy_h = param_find("MPC_XY_VEL_D");
_VelMaxXY_h = param_find("MPC_XY_VEL_MAX");
_VelMaxZdown_h = param_find("MPC_Z_VEL_MAX_DN");
_VelMaxZup_h = param_find("MPC_Z_VEL_MAX_UP");
_ThrHover_h = param_find("MPC_THR_HOVER");
_ThrMax_h = param_find("MPC_THR_MAX");
_ThrMin_h = param_find("MPC_THR_MIN");
_YawRateMax_h = param_find("MPC_MAN_Y_MAX");
_Pyaw_h = param_find("MC_YAW_P");
/* Set parameter the very first time. */
_setParams();
};
void PositionControl::updateState(const struct vehicle_local_position_s state, const Data &vel_dot)
{
_pos = Data(&state.x);
_vel = Data(&state.vx);
_yaw = state.yaw;
_vel_dot = vel_dot;
}
void PositionControl::updateSetpoint(struct vehicle_local_position_setpoint_s setpoint)
{
_pos_sp = Data(&setpoint.x);
_vel_sp = Data(&setpoint.vx);
_acc_sp = Data(&setpoint.acc_x);
_thr_sp = Data(setpoint.thrust);
_yaw_sp = setpoint.yaw; //integrate
_yawspeed_sp = setpoint.yawspeed;
_interfaceMapping();
/* If full manual is required (thrust already generated), don't run position/velocity
* controller and just return thrust.
*/
_skipController = false;
if (PX4_ISFINITE(setpoint.thrust[0]) && PX4_ISFINITE(setpoint.thrust[1]) && PX4_ISFINITE(setpoint.thrust[2])) {
_skipController = true;
}
}
void PositionControl::generateThrustYawSetpoint(const float &dt)
{
_updateParams();
/* Only run position/velocity controller
* if thrust needs to be generated
*/
if (!_skipController) {
_positionController();
_velocityController(dt);
}
_yawController(dt);
}
void PositionControl::_interfaceMapping()
{
/* Respects FlightTask interface, where
* NAN-setpoints are of no interest and
* do not require control.
*/
/* Loop through x,y and z components of all setpoints. */
for (int i = 0; i <= 2; i++) {
if (PX4_ISFINITE(_pos_sp(i))) {
/* Position control is required */
if (!PX4_ISFINITE(_vel_sp(i))) {
/* Velocity is not used as feedforward term. */
_vel_sp(i) = 0.0f;
}
/* thrust setpoint is not supported
* in position control
*/
_thr_sp(i) = 0.0f;
} else if (PX4_ISFINITE(_vel_sp(i))) {
/* Velocity controller is active without
* position control.
*/
_pos_sp(i) = _pos(i);
_thr_sp(i) = 0.0f;
} else if (PX4_ISFINITE(_thr_sp(i))) {
/* Thrust setpoint was generated from
* stick directly.
*/
_pos_sp(i) = _pos(i);
_vel_sp(i) = _vel(i);
_thr_int(i) = 0.0f;
_vel_dot(i) = 0.0f;
} else {
PX4_WARN("TODO: add safety");
}
}
if (!PX4_ISFINITE(_yawspeed_sp)) {
/* Target yaw is yaw setpoint. No need for yawspeed */
_yawspeed_sp = 0.0f;
if (!PX4_ISFINITE(_yaw_sp)) {
/* There is no finite setpoint. The best
* we can do is to just re-use old setpoint */
_yaw_sp = _yaw_sp_int;
}
} else if (!PX4_ISFINITE(_yaw_sp)) {
/* Nothing is finite: Best we can do is to just
* reuse old setpoint.
*/
_yaw_sp = _yaw_sp_int;
}
}
void PositionControl::_positionController()
{
/* Generate desired velocity setpoint */
/* P-controller */
_vel_sp = (_pos_sp - _pos).emult(Pp) + _vel_sp;
/* Make sure velocity setpoint is constrained in all directions (xyz). */
float vel_norm_xy = sqrtf(_vel_sp(0) * _vel_sp(0) + _vel_sp(1) * _vel_sp(1));
if (vel_norm_xy > _VelMaxXY) {
_vel_sp(0) = _vel_sp(0) * _VelMaxXY / vel_norm_xy;
_vel_sp(1) = _vel_sp(1) * _VelMaxXY / vel_norm_xy;
}
_vel_sp(2) = math::constrain(_vel_sp(2), -_VelMaxZ[0], _VelMaxZ[1]);
}
void PositionControl::_velocityController(const float &dt)
{
/* Generate desired thrust setpoint */
/* PID
* u_des = P(vel_err) + D(vel_err_dot) + I(vel_integral)
* Umin <= u_des <= Umax
*
* Saturation for vel_integral;
* u_des = _thr_sp; r = _vel_sp; y = _vel
* u_des >= Umax and r - y >= 0 => Saturation = true
* u_des >= Umax and r - y <= 0 => Saturation = false
* u_des <= Umin and r - y <= 0 => Saturation = true
* u_des <= Umin and r - y >= 0 => Saturation = false
*
*/
Data vel_err = _vel_sp - _vel;
/* TODO: add offboard acceleration mode
* PID-controller */
Data offset(0.0f, 0.0f, _ThrHover);
Data thr_sp = Pv.emult(vel_err) + Dv.emult(_vel_dot) + _thr_int - offset;
/* Get maximum tilt */
float tilt_max = PX4_ISFINITE(_constraints.tilt_max) ? _constraints.tilt_max : M_PI_2_F;
tilt_max = math::min(tilt_max, M_PI_2_F);
/* Compute maximum allowed thrust along xy based on thrust in z-direction and
* scale _thrust_sp by that value. This only has an effect for altitude mode where
* _thr_sp(0:1).length() > 0.0f.
*/
if (matrix::Vector2f(&_thr_sp(0)).length() > FLT_EPSILON) {
float thr_xy_max = fabsf(thr_sp(2)) * tanf(tilt_max);
_thr_sp(0) *= thr_xy_max;
_thr_sp(1) *= thr_xy_max;
}
_thr_sp += thr_sp;
/* Limit tilt with priority on z
* For manual controlled mode excluding pure manual and rate control, maximum tilt is 90;
* It is to note that pure manual and rate control will never enter _velocityController method. */
_thr_sp = ControlMath::constrainTilt(_thr_sp, tilt_max);
/* Constrain thrust set-point and update saturation flag */
/* To get (r-y) for horizontal direction, we look at the dot-product
* for vel_err and _vel_sp. The sign of the dot product indicates
* if (r-y) is greater or smaller than 0
*/
float dot_xy = matrix::Vector2f(&vel_err(0)) * matrix::Vector2f(&_vel_sp(0));
float direction[2] = {dot_xy, -vel_err(2)}; // negative sign because of N-E-D
bool stop_I[2] = {false, false}; // stop integration for xy and z
ControlMath::constrainPIDu(_thr_sp, stop_I, _ThrLimit, direction);
/* Update integrals */
if (!stop_I[0]) {
_thr_int(0) += vel_err(0) * Iv(0) * dt;
_thr_int(1) += vel_err(1) * Iv(1) * dt;
}
if (!stop_I[1]) {
_thr_int(2) += vel_err(2) * Iv(2) * dt;
}
}
void PositionControl::_yawController(const float &dt)
{
const float yaw_offset_max = math::radians(_YawRateMax) / _Pyaw;
const float yaw_target = _wrap_pi(_yaw_sp + _yawspeed_sp * dt);
const float yaw_offset = _wrap_pi(yaw_target - _yaw);
// If the yaw offset became too big for the system to track stop
// shifting it, only allow if it would make the offset smaller again.
if (fabsf(yaw_offset) < yaw_offset_max || (_yawspeed_sp > 0 && yaw_offset < 0)
|| (_yawspeed_sp < 0 && yaw_offset > 0)) {
_yaw_sp = yaw_target;
}
/* Update yaw setpoint integral */
_yaw_sp_int = _yaw_sp;
}
void PositionControl::updateConstraints(const Controller::Constraints &constraints)
{
_constraints = constraints;
}
void PositionControl::_updateParams()
{
bool updated;
parameter_update_s param_update;
orb_check(_parameter_sub, &updated);
if (updated) {
orb_copy(ORB_ID(parameter_update), _parameter_sub, ¶m_update);
_setParams();
}
}
void PositionControl::_setParams()
{
param_get(_Pxy_h, &Pp(0));
param_get(_Pxy_h, &Pp(1));
param_get(_Pz_h, &Pp(2));
param_get(_Pvxy_h, &Pv(0));
param_get(_Pvxy_h, &Pv(1));
param_get(_Pvz_h, &Pv(2));
param_get(_Ivxy_h, &Iv(0));
param_get(_Ivxy_h, &Iv(1));
param_get(_Ivz_h, &Iv(2));
param_get(_Dvxy_h, &Dv(0));
param_get(_Dvxy_h, &Dv(1));
param_get(_Dvz_h, &Dv(2));
param_get(_VelMaxXY_h, &_VelMaxXY);
param_get(_VelMaxZup_h, &_VelMaxZ[0]);
param_get(_VelMaxZdown_h, &_VelMaxZ[1]);
param_get(_ThrHover_h, &_ThrHover);
param_get(_ThrMax_h, &_ThrLimit[0]);
param_get(_ThrMin_h, &_ThrLimit[1]);
param_get(_YawRateMax_h, &_YawRateMax);
param_get(_Pyaw_h, &_Pyaw);
}
<|endoftext|> |
<commit_before>#include "sprite.h"
#include "../asset_manager.h"
#include <SDL.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
extern SDL_Renderer *renderer;
Sprite::Sprite(const std::string &path) {
load(path);
direction_ = SPRITE_RIGHT;
visualDirection_ = SPRITE_RIGHT;
}
bool Sprite::load(const std::string &path) {
std::ifstream spritefile(path);
if (!spritefile.is_open()) {
std::cout << "Unable to open spritefile \"" << path << "\"" << std::endl;
return false;
}
std::stringstream fileData;
fileData << spritefile.rdbuf();
spritefile.close();
auto spriteData = nlohmann::json::parse(fileData.str());
dimensions_.w = spriteData["width"].get<int>();
dimensions_.h = spriteData["height"].get<int>();
tile_ = spriteData["tile"].get<int>();
multiFile_ = spriteData["multi_file"].get<bool>();
scale_ = spriteData["scale"].get<float>();
frameSpacing_ = spriteData["frame_spacing"].get<int>();
std::vector<std::string> texturePaths;
if (multiFile_) {
texturePaths = spriteData["frames"].get<std::vector<std::string>>();
} else {
texturePaths.push_back(spriteData["texture"].get<std::string>());
totalFrames_ = spriteData["total_frames"].get<int>();
}
auto basePath = path.substr(0, path.find_last_of("/"));
for (auto &path : texturePaths) {
std::string fullPath = basePath + "/" + path;
auto texture = AssetManager::getTexture(fullPath);
if (texture == nullptr) {
std::cout << "\"" << fullPath << "\" does not exist, skipping render"
<< std::endl;
return false;
}
// The two images should be the same size so I'm being lazy
SDL_QueryTexture(texture, NULL, NULL, &textureDimensions_.w,
&textureDimensions_.h);
textures_.push_back(texture);
}
return true;
}
void Sprite::update(unsigned long ticks) {
if (ticks - lastTicks_ >= FRAME_TICKS_INTERVAL) {
int limit = textures_.size();
if (!multiFile_) {
limit = totalFrames_ * frameSpacing_;
}
frame_ = (frame_ + frameSpacing_) % limit;
lastTicks_ = ticks;
}
}
void Sprite::render(Point cameraPos) const {
SDL_Rect source;
int tile = tile_;
if (!multiFile_) {
tile += frame_;
}
source.x = (tile % (textureDimensions_.w / dimensions_.w)) * dimensions_.w;
source.y = (tile / (textureDimensions_.w / dimensions_.w)) * dimensions_.h;
source.w = dimensions_.w;
source.h = dimensions_.h;
SDL_Rect dest;
dest.x = dimensions_.x - cameraPos.x;
dest.y = dimensions_.y - cameraPos.y;
dest.w = (int)((float)dimensions_.w * scale_);
dest.h = (int)((float)dimensions_.h * scale_);
SDL_Texture *tex;
if (multiFile_) {
tex = textures_[frame_];
} else {
tex = textures_[0];
}
if (visualDirection_ == SPRITE_LEFT) {
SDL_RenderCopy(renderer, tex, &source, &dest);
} else {
SDL_RenderCopyEx(renderer, tex, &source, &dest, 0, NULL,
SDL_FLIP_HORIZONTAL);
}
}
<commit_msg>Fix multi-file animations<commit_after>#include "sprite.h"
#include "../asset_manager.h"
#include <SDL.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
extern SDL_Renderer *renderer;
Sprite::Sprite(const std::string &path) {
load(path);
direction_ = SPRITE_RIGHT;
visualDirection_ = SPRITE_RIGHT;
}
bool Sprite::load(const std::string &path) {
std::ifstream spritefile(path);
if (!spritefile.is_open()) {
std::cout << "Unable to open spritefile \"" << path << "\"" << std::endl;
return false;
}
std::stringstream fileData;
fileData << spritefile.rdbuf();
spritefile.close();
auto spriteData = nlohmann::json::parse(fileData.str());
dimensions_.w = spriteData["width"].get<int>();
dimensions_.h = spriteData["height"].get<int>();
tile_ = spriteData["tile"].get<int>();
multiFile_ = spriteData["multi_file"].get<bool>();
scale_ = spriteData["scale"].get<float>();
frameSpacing_ = spriteData["frame_spacing"].get<int>();
std::vector<std::string> texturePaths;
if (multiFile_) {
texturePaths = spriteData["frames"].get<std::vector<std::string>>();
totalFrames_ = (int) texturePaths.size();
} else {
texturePaths.push_back(spriteData["texture"].get<std::string>());
totalFrames_ = spriteData["total_frames"].get<int>();
}
auto basePath = path.substr(0, path.find_last_of("/"));
for (auto &path : texturePaths) {
std::string fullPath = basePath + "/" + path;
auto texture = AssetManager::getTexture(fullPath);
if (texture == nullptr) {
std::cout << "\"" << fullPath << "\" does not exist, skipping render"
<< std::endl;
return false;
}
// The two images should be the same size so I'm being lazy
SDL_QueryTexture(texture, NULL, NULL, &textureDimensions_.w,
&textureDimensions_.h);
textures_.push_back(texture);
}
return true;
}
void Sprite::update(unsigned long ticks) {
if (ticks - lastTicks_ >= FRAME_TICKS_INTERVAL) {
int limit = textures_.size();
int frameIncrease;
if (multiFile_) {
limit = totalFrames_;
frameIncrease = 1;
} else {
limit = totalFrames_ * frameSpacing_;
frameIncrease = frameSpacing_;
}
frame_ = (frame_ + frameIncrease) % limit;
lastTicks_ = ticks;
}
}
void Sprite::render(Point cameraPos) const {
SDL_Rect source;
int tile = tile_;
if (!multiFile_) {
tile += frame_;
}
source.x = (tile % (textureDimensions_.w / dimensions_.w)) * dimensions_.w;
source.y = (tile / (textureDimensions_.w / dimensions_.w)) * dimensions_.h;
source.w = dimensions_.w;
source.h = dimensions_.h;
SDL_Rect dest;
dest.x = dimensions_.x - cameraPos.x;
dest.y = dimensions_.y - cameraPos.y;
dest.w = (int)((float)dimensions_.w * scale_);
dest.h = (int)((float)dimensions_.h * scale_);
SDL_Texture *tex;
if (multiFile_) {
tex = textures_[frame_];
} else {
tex = textures_[0];
}
if (visualDirection_ == SPRITE_LEFT) {
SDL_RenderCopy(renderer, tex, &source, &dest);
} else {
SDL_RenderCopyEx(renderer, tex, &source, &dest, 0, NULL,
SDL_FLIP_HORIZONTAL);
}
}
<|endoftext|> |
<commit_before>// -*-c++-*-
/*
* $Id$
*
* DirectX file converter for OpenSceneGraph.
* Copyright (c)2002 Ulrich Hertlein <[email protected]>
*
* 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
*/
#include "directx.h"
#include <osg/TexEnv>
#include <osg/CullFace>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Image>
#include <osg/Texture2D>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/FileNameUtils>
#include <assert.h>
/**
* OpenSceneGraph plugin wrapper/converter.
*/
class ReaderWriterDirectX : public osgDB::ReaderWriter
{
public:
ReaderWriterDirectX() { }
virtual const char* className() {
return "DirectX Reader/Writer";
}
virtual bool acceptsExtension(const std::string& extension) {
return osgDB::equalCaseInsensitive(extension,"x") ? true : false;
}
virtual ReadResult readNode(const std::string& fileName,
const osgDB::ReaderWriter::Options* options);
private:
osg::Geode* convertFromDX(DX::Object& obj, bool flipTexture, float creaseAngle);
};
// Register with Registry to instantiate the above reader/writer.
osgDB::RegisterReaderWriterProxy<ReaderWriterDirectX> g_readerWriter_DirectX_Proxy;
// Read node
osgDB::ReaderWriter::ReadResult ReaderWriterDirectX::readNode(const std::string& fileName,
const osgDB::ReaderWriter::Options* options)
{
std::string ext = osgDB::getLowerCaseFileExtension(fileName);
if (!acceptsExtension(ext))
return ReadResult::FILE_NOT_HANDLED;
osg::notify(osg::INFO) << "ReaderWriterDirectX::readNode(" << fileName.c_str() << ")\n";
// Load DirectX mesh
DX::Object obj;
if (obj.load(fileName.c_str())) {
// Options?
bool flipTexture = true;
float creaseAngle = 80.0f;
if (options) {
const std::string option = options->getOptionString();
if (option.find("flipTexture") != std::string::npos)
flipTexture = false;
if (option.find("creaseAngle") != std::string::npos) {
// TODO
}
}
// Convert to osg::Geode
osg::Geode* geode = convertFromDX(obj, flipTexture, creaseAngle);
if (!geode)
return ReadResult::FILE_NOT_HANDLED;
return geode;
}
return ReadResult::FILE_NOT_HANDLED;
}
// Convert DirectX mesh to osg::Geode
osg::Geode* ReaderWriterDirectX::convertFromDX(DX::Object& obj,
bool flipTexture, float creaseAngle)
{
// Fetch mesh
const DX::Mesh* mesh = obj.getMesh();
if (!mesh)
return NULL;
const DX::MeshMaterialList* meshMaterial = obj.getMeshMaterialList();
if (!meshMaterial)
return NULL;
const DX::MeshNormals* meshNormals = obj.getMeshNormals();
if (!meshNormals) {
obj.generateNormals(creaseAngle);
meshNormals = obj.getMeshNormals();
}
if (!meshNormals)
return NULL;
const DX::MeshTextureCoords* meshTexCoords = obj.getMeshTextureCoords();
if (!meshTexCoords)
return NULL;
/*
* - MeshMaterialList contains a list of Material and a per-face
* information with Material is to be applied to which face.
* - Mesh contains a list of Vertices and a per-face information
* which vertices (three or four) belong to this face.
* - MeshNormals contains a list of Normals and a per-face information
* which normal is used by which vertex.
* - MeshTextureCoords contains a list of per-vertex texture coordinates.
*
* - Uses left-hand CS with Y-up, Z-into
* obj_x -> osg_x
* obj_y -> osg_z
* obj_z -> osg_y
*
* - Polys are CW oriented
*/
std::vector<osg::Geometry*> geomList;
unsigned int i;
for (i = 0; i < meshMaterial->material.size(); i++) {
const DX::Material& mtl = meshMaterial->material[i];
osg::StateSet* state = new osg::StateSet;
// Material
osg::Material* material = new osg::Material;
state->setAttributeAndModes(material);
float alpha = mtl.faceColor.alpha;
osg::Vec4 ambient(mtl.faceColor.red,
mtl.faceColor.green,
mtl.faceColor.blue,
alpha);
material->setAmbient(osg::Material::FRONT, ambient);
material->setDiffuse(osg::Material::FRONT, ambient);
material->setShininess(osg::Material::FRONT, mtl.power);
osg::Vec4 specular(mtl.specularColor.red,
mtl.specularColor.green,
mtl.specularColor.blue, alpha);
material->setSpecular(osg::Material::FRONT, specular);
osg::Vec4 emissive(mtl.emissiveColor.red,
mtl.emissiveColor.green,
mtl.emissiveColor.blue, alpha);
material->setEmission(osg::Material::FRONT, emissive);
// Transparency? Set render hint & blending
if (alpha < 1.0f) {
state->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
state->setMode(GL_BLEND, osg::StateAttribute::ON);
}
else
state->setMode(GL_BLEND, osg::StateAttribute::OFF);
unsigned int textureCount = mtl.texture.size();
for (unsigned int j = 0; j < textureCount; j++) {
// Load image
osg::Image* image = osgDB::readImageFile(mtl.texture[j]);
if (!image)
continue;
// Texture
osg::Texture2D* texture = new osg::Texture2D;
texture->setImage(image);
texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::REPEAT);
texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::REPEAT);
state->setTextureAttributeAndModes(j, texture);
}
// Geometry
osg::Geometry* geom = new osg::Geometry;
geomList.push_back(geom);
geom->setStateSet(state);
// Arrays to hold vertices, normals, and texcoords.
geom->setVertexArray(new osg::Vec3Array);
geom->setNormalArray(new osg::Vec3Array);
geom->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
if (textureCount) {
// All texture units share the same array
osg::Vec2Array* texCoords = new osg::Vec2Array;
for (unsigned int j = 0; j < textureCount; j++)
geom->setTexCoordArray(j, texCoords);
}
geom->addPrimitiveSet(new osg::DrawArrayLengths(osg::PrimitiveSet::POLYGON));
}
if (mesh->faces.size() != meshMaterial->faceIndices.size())
{
osg::notify(osg::FATAL)<<"Error: internal error in DirectX .x loader,"<<std::endl;
osg::notify(osg::FATAL)<<" mesh->faces.size() == meshMaterial->faceIndices.size()"<<std::endl;
return NULL;
}
// Add faces to Geometry
for (i = 0; i < meshMaterial->faceIndices.size(); i++) {
// Geometry for Material
unsigned int mi = meshMaterial->faceIndices[i];
osg::Geometry* geom = geomList[mi];
// #pts of this face
unsigned int np = mesh->faces[i].size();
((osg::DrawArrayLengths*) geom->getPrimitiveSet(0))->push_back(np);
assert(np == meshNormals->faceNormals[i].size());
osg::Vec3Array* vertexArray = (osg::Vec3Array*) geom->getVertexArray();
osg::Vec3Array* normalArray = (osg::Vec3Array*) geom->getNormalArray();
osg::Vec2Array* texCoordArray = (osg::Vec2Array*) geom->getTexCoordArray(0);
// Add vertices, normals, texcoords
for (unsigned int j = 0; j < np; j++) {
// Convert CW to CCW order
unsigned int jj = (j > 0 ? np - j : j);
// Vertices
unsigned int vi = mesh->faces[i][jj];
if (vertexArray) {
// Transform Xleft/Yup/Zinto to Xleft/Yinto/Zup
const DX::Vector& v = mesh->vertices[vi];
vertexArray->push_back(osg::Vec3(v.x,v.z,v.y));
}
// Normals
unsigned int ni = meshNormals->faceNormals[i][jj];
if (normalArray) {
// Transform Xleft/Yup/Zinto to Xleft/Yinto/Zup
const DX::Vector& n = meshNormals->normals[ni];
normalArray->push_back(osg::Vec3(n.x,n.z,n.y));
}
// TexCoords
if (texCoordArray) {
const DX::Coords2d& tc = (*meshTexCoords)[vi];
osg::Vec2 uv;
if (flipTexture)
uv.set(tc.u, 1.0f - tc.v); // Image is upside down
else
uv.set(tc.u, tc.v);
texCoordArray->push_back(uv);
}
}
}
// Add non-empty nodes to Geode
osg::Geode* geode = new osg::Geode;
for (i = 0; i < geomList.size(); i++) {
osg::Geometry* geom = geomList[i];
if (((osg::Vec3Array*) geom->getVertexArray())->size())
geode->addDrawable(geom);
}
// Back-face culling
osg::StateSet* state = new osg::StateSet;
geode->setStateSet(state);
osg::CullFace* cullFace = new osg::CullFace;
cullFace->setMode(osg::CullFace::BACK);
state->setAttributeAndModes(cullFace);
return geode;
}
<commit_msg>Updates from Ulrich for sharing of textures.<commit_after>// -*-c++-*-
/*
* $Id$
*
* DirectX file converter for OpenSceneGraph.
* Copyright (c)2002 Ulrich Hertlein <[email protected]>
*
* 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
*/
#include "directx.h"
#include <osg/TexEnv>
#include <osg/CullFace>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Image>
#include <osg/Texture2D>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/FileNameUtils>
#include <assert.h>
#include <map>
/**
* OpenSceneGraph plugin wrapper/converter.
*/
class ReaderWriterDirectX : public osgDB::ReaderWriter
{
public:
ReaderWriterDirectX() { }
virtual const char* className() {
return "DirectX Reader/Writer";
}
virtual bool acceptsExtension(const std::string& extension) {
return osgDB::equalCaseInsensitive(extension,"x") ? true : false;
}
virtual ReadResult readNode(const std::string& fileName,
const osgDB::ReaderWriter::Options* options);
private:
osg::Geode* convertFromDX(DX::Object& obj, bool flipTexture, float creaseAngle);
};
// Register with Registry to instantiate the above reader/writer.
osgDB::RegisterReaderWriterProxy<ReaderWriterDirectX> g_readerWriter_DirectX_Proxy;
// Read node
osgDB::ReaderWriter::ReadResult ReaderWriterDirectX::readNode(const std::string& fileName,
const osgDB::ReaderWriter::Options* options)
{
std::string ext = osgDB::getLowerCaseFileExtension(fileName);
if (!acceptsExtension(ext))
return ReadResult::FILE_NOT_HANDLED;
osg::notify(osg::INFO) << "ReaderWriterDirectX::readNode(" << fileName.c_str() << ")\n";
// Load DirectX mesh
DX::Object obj;
if (obj.load(fileName.c_str())) {
// Options?
bool flipTexture = true;
float creaseAngle = 80.0f;
if (options) {
const std::string option = options->getOptionString();
if (option.find("flipTexture") != std::string::npos)
flipTexture = false;
if (option.find("creaseAngle") != std::string::npos) {
// TODO
}
}
// Convert to osg::Geode
osg::Geode* geode = convertFromDX(obj, flipTexture, creaseAngle);
if (!geode)
return ReadResult::FILE_NOT_HANDLED;
return geode;
}
return ReadResult::FILE_NOT_HANDLED;
}
// Convert DirectX mesh to osg::Geode
osg::Geode* ReaderWriterDirectX::convertFromDX(DX::Object& obj,
bool flipTexture, float creaseAngle)
{
// Fetch mesh
const DX::Mesh* mesh = obj.getMesh();
if (!mesh)
return NULL;
const DX::MeshMaterialList* meshMaterial = obj.getMeshMaterialList();
if (!meshMaterial)
return NULL;
const DX::MeshNormals* meshNormals = obj.getMeshNormals();
if (!meshNormals) {
obj.generateNormals(creaseAngle);
meshNormals = obj.getMeshNormals();
}
if (!meshNormals)
return NULL;
const DX::MeshTextureCoords* meshTexCoords = obj.getMeshTextureCoords();
if (!meshTexCoords)
return NULL;
/*
* - MeshMaterialList contains a list of Material and a per-face
* information with Material is to be applied to which face.
* - Mesh contains a list of Vertices and a per-face information
* which vertices (three or four) belong to this face.
* - MeshNormals contains a list of Normals and a per-face information
* which normal is used by which vertex.
* - MeshTextureCoords contains a list of per-vertex texture coordinates.
*
* - Uses left-hand CS with Y-up, Z-into
* obj_x -> osg_x
* obj_y -> osg_z
* obj_z -> osg_y
*
* - Polys are CW oriented
*/
std::vector<osg::Geometry*> geomList;
// Texture-for-Image map
std::map<std::string, osg::Texture2D*> texForImage;
unsigned int i;
for (i = 0; i < meshMaterial->material.size(); i++) {
const DX::Material& mtl = meshMaterial->material[i];
osg::StateSet* state = new osg::StateSet;
// Material
osg::Material* material = new osg::Material;
state->setAttributeAndModes(material);
float alpha = mtl.faceColor.alpha;
osg::Vec4 ambient(mtl.faceColor.red,
mtl.faceColor.green,
mtl.faceColor.blue,
alpha);
material->setAmbient(osg::Material::FRONT, ambient);
material->setDiffuse(osg::Material::FRONT, ambient);
material->setShininess(osg::Material::FRONT, mtl.power);
osg::Vec4 specular(mtl.specularColor.red,
mtl.specularColor.green,
mtl.specularColor.blue, alpha);
material->setSpecular(osg::Material::FRONT, specular);
osg::Vec4 emissive(mtl.emissiveColor.red,
mtl.emissiveColor.green,
mtl.emissiveColor.blue, alpha);
material->setEmission(osg::Material::FRONT, emissive);
// Transparency? Set render hint & blending
if (alpha < 1.0f) {
state->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
state->setMode(GL_BLEND, osg::StateAttribute::ON);
}
else
state->setMode(GL_BLEND, osg::StateAttribute::OFF);
unsigned int textureCount = mtl.texture.size();
for (unsigned int j = 0; j < textureCount; j++) {
// Share image/texture pairs
osg::Texture2D* texture = texForImage[mtl.texture[j]];
if (!texture) {
osg::Image* image = osgDB::readImageFile(mtl.texture[j]);
if (!image)
continue;
// Texture
texture = new osg::Texture2D;
texForImage[mtl.texture[j]] = texture;
texture->setImage(image);
texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::REPEAT);
texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::REPEAT);
}
state->setTextureAttributeAndModes(j, texture);
}
// Geometry
osg::Geometry* geom = new osg::Geometry;
geomList.push_back(geom);
geom->setStateSet(state);
// Arrays to hold vertices, normals, and texcoords.
geom->setVertexArray(new osg::Vec3Array);
geom->setNormalArray(new osg::Vec3Array);
geom->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
if (textureCount) {
// All texture units share the same array
osg::Vec2Array* texCoords = new osg::Vec2Array;
for (unsigned int j = 0; j < textureCount; j++)
geom->setTexCoordArray(j, texCoords);
}
geom->addPrimitiveSet(new osg::DrawArrayLengths(osg::PrimitiveSet::POLYGON));
}
if (mesh->faces.size() != meshMaterial->faceIndices.size())
{
osg::notify(osg::FATAL)<<"Error: internal error in DirectX .x loader,"<<std::endl;
osg::notify(osg::FATAL)<<" mesh->faces.size() == meshMaterial->faceIndices.size()"<<std::endl;
return NULL;
}
// Add faces to Geometry
for (i = 0; i < meshMaterial->faceIndices.size(); i++) {
// Geometry for Material
unsigned int mi = meshMaterial->faceIndices[i];
osg::Geometry* geom = geomList[mi];
// #pts of this face
unsigned int np = mesh->faces[i].size();
((osg::DrawArrayLengths*) geom->getPrimitiveSet(0))->push_back(np);
assert(np == meshNormals->faceNormals[i].size());
osg::Vec3Array* vertexArray = (osg::Vec3Array*) geom->getVertexArray();
osg::Vec3Array* normalArray = (osg::Vec3Array*) geom->getNormalArray();
osg::Vec2Array* texCoordArray = (osg::Vec2Array*) geom->getTexCoordArray(0);
// Add vertices, normals, texcoords
for (unsigned int j = 0; j < np; j++) {
// Convert CW to CCW order
unsigned int jj = (j > 0 ? np - j : j);
// Vertices
unsigned int vi = mesh->faces[i][jj];
if (vertexArray) {
// Transform Xleft/Yup/Zinto to Xleft/Yinto/Zup
const DX::Vector& v = mesh->vertices[vi];
vertexArray->push_back(osg::Vec3(v.x,v.z,v.y));
}
// Normals
unsigned int ni = meshNormals->faceNormals[i][jj];
if (normalArray) {
// Transform Xleft/Yup/Zinto to Xleft/Yinto/Zup
const DX::Vector& n = meshNormals->normals[ni];
normalArray->push_back(osg::Vec3(n.x,n.z,n.y));
}
// TexCoords
if (texCoordArray) {
const DX::Coords2d& tc = (*meshTexCoords)[vi];
osg::Vec2 uv;
if (flipTexture)
uv.set(tc.u, 1.0f - tc.v); // Image is upside down
else
uv.set(tc.u, tc.v);
texCoordArray->push_back(uv);
}
}
}
// Add non-empty nodes to Geode
osg::Geode* geode = new osg::Geode;
for (i = 0; i < geomList.size(); i++) {
osg::Geometry* geom = geomList[i];
if (((osg::Vec3Array*) geom->getVertexArray())->size())
geode->addDrawable(geom);
}
// Back-face culling
osg::StateSet* state = new osg::StateSet;
geode->setStateSet(state);
osg::CullFace* cullFace = new osg::CullFace;
cullFace->setMode(osg::CullFace::BACK);
state->setAttributeAndModes(cullFace);
return geode;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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.
*/
#include <fclaw2d_advance.H>
#include <fclaw2d_timeinterp.h>
#include <fclaw2d_ghost_fill.h>
#include <amr_single_step.h>
#include <math.h>
#include <amr_includes.H>
#include <fclaw_base.h>
/* ----------------------------------------------------------
Manage subcyling process
---------------------------------------------------------- */
static
double update_level_solution(fclaw2d_domain_t *domain,
int a_level,
fclaw2d_level_time_data *time_data)
{
/* ToDo : Do we really need to pass in the entire time_data
structure? Maybe this can be simplified considerably.
*/
double t = time_data->t_level;
double dt = time_data->dt;
double cfl;
cfl = amr_level_single_step_update(domain,a_level,t,dt);
/* This needs to be cleaned up a bit */
time_data->maxcfl = fmax(time_data->maxcfl,cfl);
return cfl;
}
static
double advance_level(fclaw2d_domain_t *domain,
const int a_level,
const int a_curr_fine_step,
double maxcfl,
subcycle_manager* a_time_stepper)
{
double t_level = a_time_stepper->level_time(a_level);
int this_level = a_level;
int coarser_level = a_level - 1;
fclaw_global_infof("Advancing level %d from step %d at time %12.6e\n",
this_level,a_curr_fine_step,t_level);
/* -- Coming into this routine, all ghost cell information
needed for an update of this level has been done. So we can
update immediately.
-- All ghost cell exchanges needed to update coarser levels,
whose last updated step is also 'a_curr_fine_step' have been
done, and so coarser grids can all also be updated
*/
/* The use of time_data here could be cleaned up a bit, but I am
leaving everything for now, in case I later decide to do more
with the MOL approach.
*/
fclaw2d_level_time_data_t time_data;
time_data.t_level = t_level;
time_data.t_initial = a_time_stepper->initial_time();
time_data.dt = a_time_stepper->dt(this_level);
time_data.fixed_dt = a_time_stepper->nosubcycle();
time_data.maxcfl = maxcfl;
/* ------------------------------------------------------------
Advance this level from 'a_curr_fine_step' to
'a_curr_fine_step + dt_level'
------------------------------------------------------------ */
double cfl_step = update_level_solution(domain,this_level,
&time_data);
maxcfl = fmax(maxcfl,cfl_step);
fclaw_global_infof("------ Max CFL on level %d is %12.4e " \
" (using dt = %12.4e)\n",this_level,cfl_step,time_data.dt);
a_time_stepper->increment_step_counter(this_level);
a_time_stepper->increment_time(this_level);
/* Advance coarser levels recursively. If we are in the no-subcycle
case, we will a take a time step of dt_fine (i.e. dt_level, where
'level' is our current fine grid level). If we are subcycling,
then each time step will be the step size appropriate for that
level. In this case, we are anticipating needing to do time
interpolation to get ghost cells, and so as soon as we are
finished with a coarse step, we will construct the time
interpolated data.
*/
if (!a_time_stepper->is_coarsest(this_level))
{
/* Advance coarser level, but only if coarse level and this
level are time synchronized. */
int last_coarse_step = a_time_stepper->last_step(coarser_level);
if (last_coarse_step == a_curr_fine_step)
{
double cfl_step = advance_level(domain,coarser_level,
last_coarse_step,
maxcfl,a_time_stepper);
maxcfl = fmax(maxcfl,cfl_step);
if (!a_time_stepper->nosubcycle())
{
/* Time interpolate this data for a future exchange with finer grid */
int coarse_inc =
a_time_stepper->step_inc(coarser_level);
int new_curr_step =
a_time_stepper->last_step(this_level);
double alpha =
double(new_curr_step % coarse_inc)/coarse_inc;
/* Copy between grids at this level so that time interpolated data
will have valid ghost cells, at least those that can be copied.
This is needed so that we can interpolate to finer neighboring
grids. */
fclaw2d_ghost_copy4timeinterp(domain,this_level);
fclaw_global_infof("Time interpolating level %d using alpha = %5.2f\n",
coarser_level,alpha);
fclaw2d_timeinterp(domain,coarser_level,alpha);
}
}
}
fclaw_global_infof("Advance on level %d done at time %12.6e\n\n",
a_level,a_time_stepper->level_time(a_level));
return maxcfl; // Maximum from level iteration
}
/* -------------------------------------------------------------
Main routine : Called from amrrun.cpp
------------------------------------------------------------- */
double advance_all_levels(fclaw2d_domain_t *domain,
subcycle_manager *a_time_stepper)
{
// Start timer for advancing the levels
fclaw2d_domain_data_t* ddata = get_domain_data(domain);
fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_ADVANCE]);
/* These are global minimum and maximum values */
int minlevel = a_time_stepper->minlevel();
int maxlevel = a_time_stepper->maxlevel();
/* Number of steps we need to take on the finest level to equal one
step on the coarsest level. In the non-subcycled case, this
'n_fine_steps' is equal to 1. In either case, we have
n_fine_steps = 2^(maxlevel-minlevel)
*/
int n_fine_steps = a_time_stepper->step_inc(minlevel);
/* Keep track of largest cfl over all grid updates */
double maxcfl = 0;
for(int nf = 0; nf < n_fine_steps; nf++)
{
double cfl_step = advance_level(domain,maxlevel,nf,maxcfl,
a_time_stepper);
maxcfl = fmax(cfl_step,maxcfl);
int last_step = a_time_stepper->last_step(maxlevel);
if (!a_time_stepper->nosubcycle() && last_step < n_fine_steps)
{
/* Find time interpolated level and do ghost patch exchange
and ghost cell exchange for next update. */
int time_interp_level = maxlevel-1;
while (last_step %
a_time_stepper->step_inc(time_interp_level) == 0)
{
time_interp_level--;
}
/* This exchange includes an exchange between level
maxlevel-n+1 and the time interpolated patch at level
maxlevel-n. */
/* coarsest level is a time interpolated level */
int time_interp = 1;
fclaw2d_ghost_update(domain,minlevel,maxlevel,
time_interp,FCLAW2D_TIMER_ADVANCE);
#if 0
fclaw2d_ghost_update(domain,time_interp_level+1,maxlevel,
time_interp,FCLAW2D_TIMER_ADVANCE);
#endif
}
}
/* Do a complete update. This is needed even if we are regridding
before the next step. In this case, the ghost cell values can
be used in tagging for refining. If we regrid, this will have to
be called a second time.
Idea : If we know we are regridding before the next step, we could
skip this update, and make it clear to the user that ghost cell
values are not available for determining refinement critera.
*/
int time_interp = 0;
fclaw_global_infof("Advance is done with coarse grid step at " \
" time %12.6e\n",a_time_stepper->initial_time());
fclaw2d_ghost_update(domain,minlevel,maxlevel,time_interp,FCLAW2D_TIMER_ADVANCE);
// Stop the timer
fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_ADVANCE]);
++ddata->count_amr_advance;
return maxcfl;
}
<commit_msg>Uncomment partial exchange<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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.
*/
#include <fclaw2d_advance.H>
#include <fclaw2d_timeinterp.h>
#include <fclaw2d_ghost_fill.h>
#include <amr_single_step.h>
#include <math.h>
#include <amr_includes.H>
#include <fclaw_base.h>
/* ----------------------------------------------------------
Manage subcyling process
---------------------------------------------------------- */
static
double update_level_solution(fclaw2d_domain_t *domain,
int a_level,
fclaw2d_level_time_data *time_data)
{
/* ToDo : Do we really need to pass in the entire time_data
structure? Maybe this can be simplified considerably.
*/
double t = time_data->t_level;
double dt = time_data->dt;
double cfl;
cfl = amr_level_single_step_update(domain,a_level,t,dt);
/* This needs to be cleaned up a bit */
time_data->maxcfl = fmax(time_data->maxcfl,cfl);
return cfl;
}
static
double advance_level(fclaw2d_domain_t *domain,
const int a_level,
const int a_curr_fine_step,
double maxcfl,
subcycle_manager* a_time_stepper)
{
double t_level = a_time_stepper->level_time(a_level);
int this_level = a_level;
int coarser_level = a_level - 1;
fclaw_global_infof("Advancing level %d from step %d at time %12.6e\n",
this_level,a_curr_fine_step,t_level);
/* -- Coming into this routine, all ghost cell information
needed for an update of this level has been done. So we can
update immediately.
-- All ghost cell exchanges needed to update coarser levels,
whose last updated step is also 'a_curr_fine_step' have been
done, and so coarser grids can all also be updated
*/
/* The use of time_data here could be cleaned up a bit, but I am
leaving everything for now, in case I later decide to do more
with the MOL approach.
*/
fclaw2d_level_time_data_t time_data;
time_data.t_level = t_level;
time_data.t_initial = a_time_stepper->initial_time();
time_data.dt = a_time_stepper->dt(this_level);
time_data.fixed_dt = a_time_stepper->nosubcycle();
time_data.maxcfl = maxcfl;
/* ------------------------------------------------------------
Advance this level from 'a_curr_fine_step' to
'a_curr_fine_step + dt_level'
------------------------------------------------------------ */
double cfl_step = update_level_solution(domain,this_level,
&time_data);
maxcfl = fmax(maxcfl,cfl_step);
fclaw_global_infof("------ Max CFL on level %d is %12.4e " \
" (using dt = %12.4e)\n",this_level,cfl_step,time_data.dt);
a_time_stepper->increment_step_counter(this_level);
a_time_stepper->increment_time(this_level);
/* Advance coarser levels recursively. If we are in the no-subcycle
case, we will a take a time step of dt_fine (i.e. dt_level, where
'level' is our current fine grid level). If we are subcycling,
then each time step will be the step size appropriate for that
level. In this case, we are anticipating needing to do time
interpolation to get ghost cells, and so as soon as we are
finished with a coarse step, we will construct the time
interpolated data.
*/
if (!a_time_stepper->is_coarsest(this_level))
{
/* Advance coarser level, but only if coarse level and this
level are time synchronized. */
int last_coarse_step = a_time_stepper->last_step(coarser_level);
if (last_coarse_step == a_curr_fine_step)
{
double cfl_step = advance_level(domain,coarser_level,
last_coarse_step,
maxcfl,a_time_stepper);
maxcfl = fmax(maxcfl,cfl_step);
if (!a_time_stepper->nosubcycle())
{
/* Time interpolate this data for a future exchange with finer grid */
int coarse_inc =
a_time_stepper->step_inc(coarser_level);
int new_curr_step =
a_time_stepper->last_step(this_level);
double alpha =
double(new_curr_step % coarse_inc)/coarse_inc;
/* Copy between grids at this level so that time interpolated data
will have valid ghost cells, at least those that can be copied.
This is needed so that we can interpolate to finer neighboring
grids. */
fclaw2d_ghost_copy4timeinterp(domain,this_level);
fclaw_global_infof("Time interpolating level %d using alpha = %5.2f\n",
coarser_level,alpha);
fclaw2d_timeinterp(domain,coarser_level,alpha);
}
}
}
fclaw_global_infof("Advance on level %d done at time %12.6e\n\n",
a_level,a_time_stepper->level_time(a_level));
return maxcfl; // Maximum from level iteration
}
/* -------------------------------------------------------------
Main routine : Called from amrrun.cpp
------------------------------------------------------------- */
double advance_all_levels(fclaw2d_domain_t *domain,
subcycle_manager *a_time_stepper)
{
// Start timer for advancing the levels
fclaw2d_domain_data_t* ddata = get_domain_data(domain);
fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_ADVANCE]);
/* These are global minimum and maximum values */
int minlevel = a_time_stepper->minlevel();
int maxlevel = a_time_stepper->maxlevel();
/* Number of steps we need to take on the finest level to equal one
step on the coarsest level. In the non-subcycled case, this
'n_fine_steps' is equal to 1. In either case, we have
n_fine_steps = 2^(maxlevel-minlevel)
*/
int n_fine_steps = a_time_stepper->step_inc(minlevel);
/* Keep track of largest cfl over all grid updates */
double maxcfl = 0;
for(int nf = 0; nf < n_fine_steps; nf++)
{
double cfl_step = advance_level(domain,maxlevel,nf,maxcfl,
a_time_stepper);
maxcfl = fmax(cfl_step,maxcfl);
int last_step = a_time_stepper->last_step(maxlevel);
if (!a_time_stepper->nosubcycle() && last_step < n_fine_steps)
{
/* Find time interpolated level and do ghost patch exchange
and ghost cell exchange for next update. */
int time_interp_level = maxlevel-1;
while (last_step %
a_time_stepper->step_inc(time_interp_level) == 0)
{
time_interp_level--;
}
/* This exchange includes an exchange between level
maxlevel-n+1 and the time interpolated patch at level
maxlevel-n. */
/* coarsest level is a time interpolated level */
int time_interp = 1;
#if 0
fclaw2d_ghost_update(domain,minlevel,maxlevel,
time_interp,FCLAW2D_TIMER_ADVANCE);
#endif
fclaw2d_ghost_update(domain,time_interp_level+1,maxlevel,
time_interp,FCLAW2D_TIMER_ADVANCE);
}
}
/* Do a complete update. This is needed even if we are regridding
before the next step. In this case, the ghost cell values can
be used in tagging for refining. If we regrid, this will have to
be called a second time.
Idea : If we know we are regridding before the next step, we could
skip this update, and make it clear to the user that ghost cell
values are not available for determining refinement critera.
*/
int time_interp = 0;
fclaw_global_infof("Advance is done with coarse grid step at " \
" time %12.6e\n",a_time_stepper->initial_time());
fclaw2d_ghost_update(domain,minlevel,maxlevel,time_interp,FCLAW2D_TIMER_ADVANCE);
// Stop the timer
fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_ADVANCE]);
++ddata->count_amr_advance;
return maxcfl;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 The Android Open Source Project
*
* 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 <stdint.h>
#include <time.h>
#include "common/OboeDebug.h"
#include "fifo/FifoControllerBase.h"
#include "fifo/FifoController.h"
#include "fifo/FifoControllerIndirect.h"
#include "fifo/FifoBuffer.h"
#include "common/AudioClock.h"
FifoBuffer::FifoBuffer(uint32_t bytesPerFrame, uint32_t capacityInFrames)
: mFrameCapacity(capacityInFrames)
, mBytesPerFrame(bytesPerFrame)
, mStorage(NULL)
, mReadAtNanoseconds(0)
, mFramesReadCount(0)
, mFramesUnderrunCount(0)
, mUnderrunCount(0)
{
mFifo = new FifoController(capacityInFrames, capacityInFrames);
// allocate buffer
int32_t bytesPerBuffer = bytesPerFrame * capacityInFrames;
mStorage = new uint8_t[bytesPerBuffer];
mStorageOwned = true;
LOGD("FifoProcessor: numFrames = %d, bytesPerFrame = %d", capacityInFrames, bytesPerFrame);
}
FifoBuffer::FifoBuffer( uint32_t bytesPerFrame,
uint32_t capacityInFrames,
int64_t * readIndexAddress,
int64_t * writeIndexAddress,
uint8_t * dataStorageAddress
)
: mFrameCapacity(capacityInFrames)
, mBytesPerFrame(bytesPerFrame)
, mStorage(dataStorageAddress)
, mReadAtNanoseconds(0)
, mFramesReadCount(0)
, mFramesUnderrunCount(0)
, mUnderrunCount(0)
{
mFifo = new FifoControllerIndirect(capacityInFrames,
capacityInFrames,
readIndexAddress,
writeIndexAddress);
mStorage = dataStorageAddress;
mStorageOwned = false;
LOGD("FifoProcessor: capacityInFrames = %d, bytesPerFrame = %d", capacityInFrames, bytesPerFrame);
}
FifoBuffer::~FifoBuffer() {
if (mStorageOwned) {
delete[] mStorage;
}
delete mFifo;
}
int32_t FifoBuffer::convertFramesToBytes(int32_t frames) {
return frames * mBytesPerFrame;
}
int32_t FifoBuffer::read(void *buffer, int32_t numFrames) {
size_t numBytes;
int32_t framesAvailable = mFifo->getFullFramesAvailable();
int32_t framesToRead = numFrames;
// Is there enough data in the FIFO
if (framesToRead > framesAvailable) {
framesToRead = framesAvailable;
}
if (framesToRead == 0) {
return 0;
}
uint32_t readIndex = mFifo->getReadIndex();
uint8_t *destination = (uint8_t *) buffer;
uint8_t *source = &mStorage[convertFramesToBytes(readIndex)];
if ((readIndex + framesToRead) > mFrameCapacity) {
// read in two parts, first part here
uint32_t frames1 = mFrameCapacity - readIndex;
uint32_t numBytes = convertFramesToBytes(frames1);
memcpy(destination, source, numBytes);
destination += numBytes;
// read second part
source = &mStorage[0];
int frames2 = framesToRead - frames1;
numBytes = convertFramesToBytes(frames2);
memcpy(destination, source, numBytes);
} else {
// just read in one shot
numBytes = convertFramesToBytes(framesToRead);
memcpy(destination, source, numBytes);
}
mFifo->advanceReadIndex(framesToRead);
return framesToRead;
}
int32_t FifoBuffer::write(const void *buffer, int32_t framesToWrite) {
int32_t framesAvailable = mFifo->getEmptyFramesAvailable();
// LOGD("FifoBuffer::write() framesToWrite = %d, framesAvailable = %d",
// framesToWrite, framesAvailable);
if (framesToWrite > framesAvailable) {
framesToWrite = framesAvailable;
}
if (framesToWrite <= 0) {
return 0;
}
size_t numBytes;
uint32_t writeIndex = mFifo->getWriteIndex();
int byteIndex = convertFramesToBytes(writeIndex);
const uint8_t *source = (const uint8_t *) buffer;
uint8_t *destination = &mStorage[byteIndex];
if ((writeIndex + framesToWrite) > mFrameCapacity) {
// write in two parts, first part here
int frames1 = mFrameCapacity - writeIndex;
numBytes = convertFramesToBytes(frames1);
memcpy(destination, source, numBytes);
// LOGD("FifoBuffer::write(%p to %p, numBytes = %d", source, destination, numBytes);
// read second part
source += convertFramesToBytes(frames1);
destination = &mStorage[0];
int framesLeft = framesToWrite - frames1;
numBytes = convertFramesToBytes(framesLeft);
// LOGD("FifoBuffer::write(%p to %p, numBytes = %d", source, destination, numBytes);
memcpy(destination, source, numBytes);
} else {
// just write in one shot
numBytes = convertFramesToBytes(framesToWrite);
// LOGD("FifoBuffer::write(%p to %p, numBytes = %d", source, destination, numBytes);
memcpy(destination, source, numBytes);
}
mFifo->advanceWriteIndex(framesToWrite);
return framesToWrite;
}
int32_t FifoBuffer::readNow(void *buffer, int32_t numFrames) {
mLastReadSize = numFrames;
int32_t framesLeft = numFrames;
int32_t framesRead = read(buffer, numFrames);
framesLeft -= framesRead;
mFramesReadCount += framesRead;
mFramesUnderrunCount += framesLeft;
// Zero out any samples we could not set.
if (framesLeft > 0) {
mUnderrunCount++;
int32_t bytesToZero = convertFramesToBytes(framesLeft);
memset(buffer, 0, bytesToZero);
}
mReadAtNanoseconds = AudioClock::getNanoseconds();
return framesRead;
}
int64_t FifoBuffer::getNextReadTime(int frameRate) {
if (mReadAtNanoseconds == 0) {
return 0;
}
int64_t nanosPerBuffer = (OBOE_NANOS_PER_SECOND * mLastReadSize) / frameRate;
return mReadAtNanoseconds + nanosPerBuffer;
}
uint32_t FifoBuffer::getThresholdFrames() const {
return mFifo->getThreshold();
}
uint32_t FifoBuffer::getBufferCapacityInFrames() const {
return mFifo->getFrameCapacity();
}
void FifoBuffer::setThresholdFrames(uint32_t threshold) {
mFifo->setThreshold(threshold);
}
<commit_msg>Update FifoBuffer.cpp<commit_after>/*
* Copyright 2015 The Android Open Source Project
*
* 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 <stdint.h>
#include <time.h>
#include <memory.h>
#include "common/OboeDebug.h"
#include "fifo/FifoControllerBase.h"
#include "fifo/FifoController.h"
#include "fifo/FifoControllerIndirect.h"
#include "fifo/FifoBuffer.h"
#include "common/AudioClock.h"
FifoBuffer::FifoBuffer(uint32_t bytesPerFrame, uint32_t capacityInFrames)
: mFrameCapacity(capacityInFrames)
, mBytesPerFrame(bytesPerFrame)
, mStorage(NULL)
, mReadAtNanoseconds(0)
, mFramesReadCount(0)
, mFramesUnderrunCount(0)
, mUnderrunCount(0)
{
mFifo = new FifoController(capacityInFrames, capacityInFrames);
// allocate buffer
int32_t bytesPerBuffer = bytesPerFrame * capacityInFrames;
mStorage = new uint8_t[bytesPerBuffer];
mStorageOwned = true;
LOGD("FifoProcessor: numFrames = %d, bytesPerFrame = %d", capacityInFrames, bytesPerFrame);
}
FifoBuffer::FifoBuffer( uint32_t bytesPerFrame,
uint32_t capacityInFrames,
int64_t * readIndexAddress,
int64_t * writeIndexAddress,
uint8_t * dataStorageAddress
)
: mFrameCapacity(capacityInFrames)
, mBytesPerFrame(bytesPerFrame)
, mStorage(dataStorageAddress)
, mReadAtNanoseconds(0)
, mFramesReadCount(0)
, mFramesUnderrunCount(0)
, mUnderrunCount(0)
{
mFifo = new FifoControllerIndirect(capacityInFrames,
capacityInFrames,
readIndexAddress,
writeIndexAddress);
mStorage = dataStorageAddress;
mStorageOwned = false;
LOGD("FifoProcessor: capacityInFrames = %d, bytesPerFrame = %d", capacityInFrames, bytesPerFrame);
}
FifoBuffer::~FifoBuffer() {
if (mStorageOwned) {
delete[] mStorage;
}
delete mFifo;
}
int32_t FifoBuffer::convertFramesToBytes(int32_t frames) {
return frames * mBytesPerFrame;
}
int32_t FifoBuffer::read(void *buffer, int32_t numFrames) {
size_t numBytes;
int32_t framesAvailable = mFifo->getFullFramesAvailable();
int32_t framesToRead = numFrames;
// Is there enough data in the FIFO
if (framesToRead > framesAvailable) {
framesToRead = framesAvailable;
}
if (framesToRead == 0) {
return 0;
}
uint32_t readIndex = mFifo->getReadIndex();
uint8_t *destination = (uint8_t *) buffer;
uint8_t *source = &mStorage[convertFramesToBytes(readIndex)];
if ((readIndex + framesToRead) > mFrameCapacity) {
// read in two parts, first part here
uint32_t frames1 = mFrameCapacity - readIndex;
uint32_t numBytes = convertFramesToBytes(frames1);
memcpy(destination, source, numBytes);
destination += numBytes;
// read second part
source = &mStorage[0];
int frames2 = framesToRead - frames1;
numBytes = convertFramesToBytes(frames2);
memcpy(destination, source, numBytes);
} else {
// just read in one shot
numBytes = convertFramesToBytes(framesToRead);
memcpy(destination, source, numBytes);
}
mFifo->advanceReadIndex(framesToRead);
return framesToRead;
}
int32_t FifoBuffer::write(const void *buffer, int32_t framesToWrite) {
int32_t framesAvailable = mFifo->getEmptyFramesAvailable();
// LOGD("FifoBuffer::write() framesToWrite = %d, framesAvailable = %d",
// framesToWrite, framesAvailable);
if (framesToWrite > framesAvailable) {
framesToWrite = framesAvailable;
}
if (framesToWrite <= 0) {
return 0;
}
size_t numBytes;
uint32_t writeIndex = mFifo->getWriteIndex();
int byteIndex = convertFramesToBytes(writeIndex);
const uint8_t *source = (const uint8_t *) buffer;
uint8_t *destination = &mStorage[byteIndex];
if ((writeIndex + framesToWrite) > mFrameCapacity) {
// write in two parts, first part here
int frames1 = mFrameCapacity - writeIndex;
numBytes = convertFramesToBytes(frames1);
memcpy(destination, source, numBytes);
// LOGD("FifoBuffer::write(%p to %p, numBytes = %d", source, destination, numBytes);
// read second part
source += convertFramesToBytes(frames1);
destination = &mStorage[0];
int framesLeft = framesToWrite - frames1;
numBytes = convertFramesToBytes(framesLeft);
// LOGD("FifoBuffer::write(%p to %p, numBytes = %d", source, destination, numBytes);
memcpy(destination, source, numBytes);
} else {
// just write in one shot
numBytes = convertFramesToBytes(framesToWrite);
// LOGD("FifoBuffer::write(%p to %p, numBytes = %d", source, destination, numBytes);
memcpy(destination, source, numBytes);
}
mFifo->advanceWriteIndex(framesToWrite);
return framesToWrite;
}
int32_t FifoBuffer::readNow(void *buffer, int32_t numFrames) {
mLastReadSize = numFrames;
int32_t framesLeft = numFrames;
int32_t framesRead = read(buffer, numFrames);
framesLeft -= framesRead;
mFramesReadCount += framesRead;
mFramesUnderrunCount += framesLeft;
// Zero out any samples we could not set.
if (framesLeft > 0) {
mUnderrunCount++;
int32_t bytesToZero = convertFramesToBytes(framesLeft);
memset(buffer, 0, bytesToZero);
}
mReadAtNanoseconds = AudioClock::getNanoseconds();
return framesRead;
}
int64_t FifoBuffer::getNextReadTime(int frameRate) {
if (mReadAtNanoseconds == 0) {
return 0;
}
int64_t nanosPerBuffer = (OBOE_NANOS_PER_SECOND * mLastReadSize) / frameRate;
return mReadAtNanoseconds + nanosPerBuffer;
}
uint32_t FifoBuffer::getThresholdFrames() const {
return mFifo->getThreshold();
}
uint32_t FifoBuffer::getBufferCapacityInFrames() const {
return mFifo->getFrameCapacity();
}
void FifoBuffer::setThresholdFrames(uint32_t threshold) {
mFifo->setThreshold(threshold);
}
<|endoftext|> |
<commit_before>/*
* This File is part of Davix, The IO library for HTTP based protocols
* Copyright (C) 2013 Adrien Devresse <[email protected]>, CERN
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <davix_internal.hpp>
#include "davmeta.hpp"
#include <xml/davpropxmlparser.hpp>
#include <utils/davix_logger_internal.hpp>
#include <request/httprequest.hpp>
#include <fileops/fileutils.hpp>
#include <utils/davix_utils_internal.hpp>
#include <string_utils/stringutils.hpp>
#include <xml/metalinkparser.hpp>
#include <base64/base64.hpp>
using namespace StrUtil;
namespace Davix{
/**
execute a propfind/stat request on a given HTTP request handle
return a vector with the content of the request if success
*/
const char* req_webdav_propfind(HttpRequest* req, DavixError** err){
DavixError* tmp_err=NULL;
int ret =-1;
req->addHeaderField("Depth","0");
req->setRequestMethod("PROPFIND");
if( (ret = req->executeRequest(&tmp_err)) ==0){
ret = davixRequestToFileStatus(req, davix_scope_stat_str(), &tmp_err);
}
if(ret != 0)
DavixError::propagateError(err, tmp_err);
return req->getAnswerContent();
}
int dav_stat_mapper_webdav(Context &context, const RequestParams* params, const Uri & url, struct StatInfo& st_info){
int ret =-1;
DavPropXMLParser parser;
DavixError * tmp_err=NULL;
HttpRequest req(context, url, &tmp_err);
if( tmp_err == NULL){
req.setParameters(params);
TRY_DAVIX{
const char * res = req_webdav_propfind(&req, &tmp_err);
if(!tmp_err){
parser.parseChunk((const char*) res, strlen(res));
std::deque<FileProperties> & props = parser.getProperties();
if( props.size() < 1){
throw DavixException(davix_scope_stat_str(), Davix::StatusCode::WebDavPropertiesParsingError, "Parsing Error : properties number < 1");
}else{
st_info = props.front().info;
ret =0;
}
}
}CATCH_DAVIX(&tmp_err)
if(tmp_err != NULL)
ret = -1;
}
checkDavixError(&tmp_err);
return ret;
}
int dav_stat_mapper_http(Context& context, const RequestParams* params, const Uri & uri, struct StatInfo& st_info){
int ret = -1;
DavixError * tmp_err=NULL;
HeadRequest req(context, uri, &tmp_err);
if( tmp_err == NULL){
req.setParameters(params);
req.executeRequest(&tmp_err);
if(!tmp_err){
if(httpcodeIsValid(req.getRequestCode()) ){
memset(&st_info, 0, sizeof(struct StatInfo));
const dav_ssize_t s = req.getAnswerSize();
st_info.size = std::max<dav_ssize_t>(0,s);
st_info.mode = 0755 | S_IFREG;
ret = 0;
}else{
httpcodeToDavixError(req.getRequestCode(), davix_scope_http_request(), uri.getString() , &tmp_err);
ret = -1;
}
}
}
checkDavixError(&tmp_err);
return ret;
}
dav_ssize_t getStatInfo(Context & c, const Uri & url, const RequestParams * params,
struct StatInfo& st_info){
RequestParams _params(params);
int ret =-1;
configureRequestParamsProto(url, _params);
switch(_params.getProtocol()){
case RequestProtocol::Webdav:
ret = dav_stat_mapper_webdav(c, &_params, url, st_info);
break;
default:
ret = dav_stat_mapper_http(c, &_params, url, st_info);
break;
}
DAVIX_DEBUG(" davix_stat <-");
return ret;
}
void parse_creation_deletion_result(int code, const Uri & u, const std::string & scope, const std::string & msg){
switch(code){
case 200:
case 201:
case 202:
case 204:{
return;
}
case 207:{
// parse webdav
DavPropXMLParser parser;
parser.parseChunk(msg);
if( parser.getProperties().size() > 0){
const int sub_code = parser.getProperties().at(0).req_status;
if(httpcodeIsValid(sub_code) == false){
httpcodeToDavixException(sub_code, scope);
}
return;
}
// if no properties, properties were filtered because invalid
httpcodeToDavixException(404, scope);
break;
}
}
httpcodeToDavixException(code, scope);
}
int internal_deleteResource(Context & c, const Uri & url, const RequestParams & params, DavixError** err){
DavixError* tmp_err=NULL;
int ret=-1;
RequestParams _params(params);
configureRequestParamsProto(url, _params);
DeleteRequest req(c,url, err);
req.setParameters(_params);
if(!tmp_err){
if( ( ret=req.executeRequest(&tmp_err)) == 0){
parse_creation_deletion_result(req.getRequestCode(), url, davix_scope_rm_str(), req.getAnswerContent());
}
}
DavixError::propagateError(err, tmp_err);
return ret;
}
int internal_makeCollection(Context & c, const Uri & url, const RequestParams & params, DavixError** err){
DAVIX_DEBUG(" -> makeCollection");
int ret=-1;
DavixError* tmp_err=NULL;
RequestParams _params(params);
configureRequestParamsProto(url, _params);
HttpRequest req(c, url, &tmp_err);
if(tmp_err == NULL){
req.setParameters(params);
req.setRequestMethod("MKCOL");
if( (ret = req.executeRequest(&tmp_err)) == 0){
parse_creation_deletion_result(req.getRequestCode(), url, davix_scope_mkdir_str(), req.getAnswerContent());
}
DAVIX_DEBUG(" makeCollection <-");
}
DavixError::propagateError(err, tmp_err);
return ret;
}
int internal_checksum(Context & c, const Uri & url, const RequestParams *params, std::string & checksm, const std::string & chk_algo){
DAVIX_DEBUG(" -> checksum");
int ret=-1;
DavixError* tmp_err=NULL;
RequestParams _params(params);
configureRequestParamsProto(url, _params);
HeadRequest req(c, url, &tmp_err);
if(tmp_err == NULL){
// add Digest file, support for other digest, extended format
req.addHeaderField("Want-Digest", chk_algo);
req.setParameters(params);
if( (ret = req.executeRequest(&tmp_err)) == 0
&& (ret = davixRequestToFileStatus(&req, davix_scope_mkdir_str(), &tmp_err)) >=0){
// try simple MD5 ( standard )
if(compare_ncase(chk_algo, "MD5") == 0){
std::string chk;
if(req.getAnswerHeader("Content-MD5", chk) == true){
DAVIX_TRACE("Extract MD5 checksum in base64 %s", chk.c_str());
chk= Base64::base64_decode(chk);
std::swap(checksm, chk);
}
}
// fallback on extension for checksum
std::string digest;
req.getAnswerHeader("Digest", digest);
if (digest.empty())
throw DavixException(davix_scope_meta(), StatusCode::OperationNonSupported, "Checksum calculation not supported by server");
size_t valueOffset = digest.find('=');
if (valueOffset == std::string::npos
|| compare_ncase(digest,0, valueOffset, chk_algo.c_str()) !=0)
throw DavixException(davix_scope_meta(), StatusCode::InvalidServerResponse, "Invalid server checksum answer");
digest.erase(digest.begin(), digest.begin()+valueOffset+1);
std::swap(checksm, digest);
DAVIX_DEBUG(" checksum <-");
return 0;
}
}
throw DavixException(&tmp_err);
}
HttpMetaOps::HttpMetaOps(): HttpIOChain(){}
HttpMetaOps::~HttpMetaOps(){}
void HttpMetaOps::checksum(IOChainContext & iocontext, std::string &checksm, const std::string &chk_algo){
internal_checksum(iocontext._context, iocontext._uri, iocontext._reqparams, checksm, chk_algo);
}
void HttpMetaOps::makeCollection(IOChainContext & iocontext){
DavixError* tmp_err=NULL;
internal_makeCollection(iocontext._context, iocontext._uri, iocontext._reqparams, &tmp_err);
checkDavixError(&tmp_err);
}
void HttpMetaOps::deleteResource(IOChainContext & iocontext){
DavixError* tmp_err=NULL;
internal_deleteResource(iocontext._context, iocontext._uri, iocontext._reqparams, &tmp_err);
checkDavixError(&tmp_err);
}
StatInfo & HttpMetaOps::statInfo(IOChainContext & iocontext, StatInfo &st_info){
DavixError* tmp_err=NULL;
struct stat st;
memset(&st, 0, sizeof(struct stat));
getStatInfo(iocontext._context, iocontext._uri, iocontext._reqparams, st_info);
checkDavixError(&tmp_err);
return st_info;
}
} // Davix
<commit_msg>Simplify Meta Ops layer<commit_after>/*
* This File is part of Davix, The IO library for HTTP based protocols
* Copyright (C) 2013 Adrien Devresse <[email protected]>, CERN
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <davix_internal.hpp>
#include "davmeta.hpp"
#include <xml/davpropxmlparser.hpp>
#include <utils/davix_logger_internal.hpp>
#include <request/httprequest.hpp>
#include <fileops/fileutils.hpp>
#include <utils/davix_utils_internal.hpp>
#include <string_utils/stringutils.hpp>
#include <xml/metalinkparser.hpp>
#include <base64/base64.hpp>
using namespace StrUtil;
namespace Davix{
/**
execute a propfind/stat request on a given HTTP request handle
return a vector with the content of the request if success
*/
const char* req_webdav_propfind(HttpRequest* req, DavixError** err){
DavixError* tmp_err=NULL;
int ret =-1;
req->addHeaderField("Depth","0");
req->setRequestMethod("PROPFIND");
if( (ret = req->executeRequest(&tmp_err)) ==0){
ret = davixRequestToFileStatus(req, davix_scope_stat_str(), &tmp_err);
}
if(ret != 0)
DavixError::propagateError(err, tmp_err);
return req->getAnswerContent();
}
int dav_stat_mapper_webdav(Context &context, const RequestParams* params, const Uri & url, struct StatInfo& st_info){
int ret =-1;
DavPropXMLParser parser;
DavixError * tmp_err=NULL;
HttpRequest req(context, url, &tmp_err);
if( tmp_err == NULL){
req.setParameters(params);
TRY_DAVIX{
const char * res = req_webdav_propfind(&req, &tmp_err);
if(!tmp_err){
parser.parseChunk((const char*) res, strlen(res));
std::deque<FileProperties> & props = parser.getProperties();
if( props.size() < 1){
throw DavixException(davix_scope_stat_str(), Davix::StatusCode::WebDavPropertiesParsingError, "Parsing Error : properties number < 1");
}else{
st_info = props.front().info;
ret =0;
}
}
}CATCH_DAVIX(&tmp_err)
if(tmp_err != NULL)
ret = -1;
}
checkDavixError(&tmp_err);
return ret;
}
int dav_stat_mapper_http(Context& context, const RequestParams* params, const Uri & uri, struct StatInfo& st_info){
int ret = -1;
DavixError * tmp_err=NULL;
HeadRequest req(context, uri, &tmp_err);
if( tmp_err == NULL){
req.setParameters(params);
req.executeRequest(&tmp_err);
if(!tmp_err){
if(httpcodeIsValid(req.getRequestCode()) ){
memset(&st_info, 0, sizeof(struct StatInfo));
const dav_ssize_t s = req.getAnswerSize();
st_info.size = std::max<dav_ssize_t>(0,s);
st_info.mode = 0755 | S_IFREG;
ret = 0;
}else{
httpcodeToDavixError(req.getRequestCode(), davix_scope_http_request(), uri.getString() , &tmp_err);
ret = -1;
}
}
}
checkDavixError(&tmp_err);
return ret;
}
dav_ssize_t getStatInfo(Context & c, const Uri & url, const RequestParams * params,
struct StatInfo& st_info){
RequestParams _params(params);
int ret =-1;
configureRequestParamsProto(url, _params);
switch(_params.getProtocol()){
case RequestProtocol::Webdav:
ret = dav_stat_mapper_webdav(c, &_params, url, st_info);
break;
default:
ret = dav_stat_mapper_http(c, &_params, url, st_info);
break;
}
DAVIX_DEBUG(" davix_stat <-");
return ret;
}
void parse_creation_deletion_result(int code, const Uri & u, const std::string & scope, const std::string & msg){
switch(code){
case 200:
case 201:
case 202:
case 204:{
return;
}
case 207:{
// parse webdav
DavPropXMLParser parser;
parser.parseChunk(msg);
if( parser.getProperties().size() > 0){
const int sub_code = parser.getProperties().at(0).req_status;
if(httpcodeIsValid(sub_code) == false){
httpcodeToDavixException(sub_code, scope);
}
return;
}
// if no properties, properties were filtered because invalid
httpcodeToDavixException(404, scope);
break;
}
}
httpcodeToDavixException(code, scope);
}
int internal_delete_resource(Context & c, const Uri & url, const RequestParams & params){
DavixError* tmp_err=NULL;
int ret=-1;
RequestParams _params(params);
configureRequestParamsProto(url, _params);
DeleteRequest req(c,url, &tmp_err);
req.setParameters(_params);
if(!tmp_err){
if( ( ret=req.executeRequest(&tmp_err)) == 0){
parse_creation_deletion_result(req.getRequestCode(), url, davix_scope_rm_str(), req.getAnswerContent());
}
}
checkDavixError(&tmp_err);
return ret;
}
int internal_make_collection(Context & c, const Uri & url, const RequestParams & params){
DAVIX_DEBUG(" -> makeCollection");
int ret=-1;
DavixError* tmp_err=NULL;
RequestParams _params(params);
configureRequestParamsProto(url, _params);
HttpRequest req(c, url, &tmp_err);
if(tmp_err == NULL){
req.setParameters(params);
req.setRequestMethod("MKCOL");
if( (ret = req.executeRequest(&tmp_err)) == 0){
parse_creation_deletion_result(req.getRequestCode(), url, davix_scope_mkdir_str(), req.getAnswerContent());
}
}
DAVIX_DEBUG(" makeCollection <-");
checkDavixError(&tmp_err);
return ret;
}
int internal_checksum(Context & c, const Uri & url, const RequestParams *params, std::string & checksm, const std::string & chk_algo){
DAVIX_DEBUG(" -> checksum");
int ret=-1;
DavixError* tmp_err=NULL;
RequestParams _params(params);
configureRequestParamsProto(url, _params);
HeadRequest req(c, url, &tmp_err);
if(tmp_err == NULL){
// add Digest file, support for other digest, extended format
req.addHeaderField("Want-Digest", chk_algo);
req.setParameters(params);
if( (ret = req.executeRequest(&tmp_err)) == 0
&& (ret = davixRequestToFileStatus(&req, davix_scope_mkdir_str(), &tmp_err)) >=0){
// try simple MD5 ( standard )
if(compare_ncase(chk_algo, "MD5") == 0){
std::string chk;
if(req.getAnswerHeader("Content-MD5", chk) == true){
DAVIX_TRACE("Extract MD5 checksum in base64 %s", chk.c_str());
chk= Base64::base64_decode(chk);
std::swap(checksm, chk);
}
}
// fallback on extension for checksum
std::string digest;
req.getAnswerHeader("Digest", digest);
if (digest.empty())
throw DavixException(davix_scope_meta(), StatusCode::OperationNonSupported, "Checksum calculation not supported by server");
size_t valueOffset = digest.find('=');
if (valueOffset == std::string::npos
|| compare_ncase(digest,0, valueOffset, chk_algo.c_str()) !=0)
throw DavixException(davix_scope_meta(), StatusCode::InvalidServerResponse, "Invalid server checksum answer");
digest.erase(digest.begin(), digest.begin()+valueOffset+1);
std::swap(checksm, digest);
DAVIX_DEBUG(" checksum <-");
return 0;
}
}
throw DavixException(&tmp_err);
}
HttpMetaOps::HttpMetaOps(): HttpIOChain(){}
HttpMetaOps::~HttpMetaOps(){}
void HttpMetaOps::checksum(IOChainContext & iocontext, std::string &checksm, const std::string &chk_algo){
internal_checksum(iocontext._context, iocontext._uri, iocontext._reqparams, checksm, chk_algo);
}
void HttpMetaOps::makeCollection(IOChainContext & iocontext){
internal_make_collection(iocontext._context, iocontext._uri, iocontext._reqparams);
}
void HttpMetaOps::deleteResource(IOChainContext & iocontext){
internal_delete_resource(iocontext._context, iocontext._uri, iocontext._reqparams);
}
StatInfo & HttpMetaOps::statInfo(IOChainContext & iocontext, StatInfo &st_info){
struct stat st;
memset(&st, 0, sizeof(struct stat));
getStatInfo(iocontext._context, iocontext._uri, iocontext._reqparams, st_info);
return st_info;
}
} // Davix
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2021 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 "ChipDeviceScanner.h"
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include "BluezObjectList.h"
#include "MainLoop.h"
#include "Types.h"
#include <errno.h>
#include <lib/support/logging/CHIPLogging.h>
#include <pthread.h>
namespace chip {
namespace DeviceLayer {
namespace Internal {
namespace {
struct GObjectUnref
{
template <typename T>
void operator()(T * value)
{
g_object_unref(value);
}
};
using GCancellableUniquePtr = std::unique_ptr<GCancellable, GObjectUnref>;
using GDBusObjectManagerUniquePtr = std::unique_ptr<GDBusObjectManager, GObjectUnref>;
/// Retrieve CHIP device identification info from the device advertising data
bool BluezGetChipDeviceInfo(BluezDevice1 & aDevice, chip::Ble::ChipBLEDeviceIdentificationInfo & aDeviceInfo)
{
GVariant * serviceData = bluez_device1_get_service_data(&aDevice);
VerifyOrReturnError(serviceData != nullptr, false);
GVariant * dataValue = g_variant_lookup_value(serviceData, CHIP_BLE_UUID_SERVICE_STRING, nullptr);
VerifyOrReturnError(dataValue != nullptr, false);
size_t dataLen = 0;
const void * dataBytes = g_variant_get_fixed_array(dataValue, &dataLen, sizeof(uint8_t));
VerifyOrReturnError(dataBytes != nullptr && dataLen >= sizeof(aDeviceInfo), false);
memcpy(&aDeviceInfo, dataBytes, sizeof(aDeviceInfo));
return true;
}
} // namespace
ChipDeviceScanner::ChipDeviceScanner(GDBusObjectManager * manager, BluezAdapter1 * adapter, GCancellable * cancellable,
ChipDeviceScannerDelegate * delegate) :
mManager(manager),
mAdapter(adapter), mCancellable(cancellable), mDelegate(delegate)
{
g_object_ref(mAdapter);
g_object_ref(mCancellable);
g_object_ref(mManager);
}
ChipDeviceScanner::~ChipDeviceScanner()
{
StopScan();
// In case the timeout timer is still active
chip::DeviceLayer::SystemLayer().CancelTimer(TimerExpiredCallback, this);
g_object_unref(mManager);
g_object_unref(mCancellable);
g_object_unref(mAdapter);
mManager = nullptr;
mAdapter = nullptr;
mCancellable = nullptr;
mDelegate = nullptr;
}
std::unique_ptr<ChipDeviceScanner> ChipDeviceScanner::Create(BluezAdapter1 * adapter, ChipDeviceScannerDelegate * delegate)
{
GError * error = nullptr;
GCancellableUniquePtr cancellable(g_cancellable_new(), GObjectUnref());
if (!cancellable)
{
return std::unique_ptr<ChipDeviceScanner>();
}
GDBusObjectManagerUniquePtr manager(
g_dbus_object_manager_client_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE,
"/", bluez_object_manager_client_get_proxy_type,
nullptr /* unused user data in the Proxy Type Func */,
nullptr /*destroy notify */, cancellable.get(), &error),
GObjectUnref());
if (!manager)
{
ChipLogError(Ble, "Failed to get DBUS object manager for device scanning: %s", error->message);
g_error_free(error);
return std::unique_ptr<ChipDeviceScanner>();
}
return std::make_unique<ChipDeviceScanner>(manager.get(), adapter, cancellable.get(), delegate);
}
CHIP_ERROR ChipDeviceScanner::StartScan(System::Clock::Timeout timeout)
{
ReturnErrorCodeIf(mIsScanning, CHIP_ERROR_INCORRECT_STATE);
ReturnErrorOnFailure(MainLoop::Instance().EnsureStarted());
mIsScanning = true; // optimistic, to allow all callbacks to check this
if (!MainLoop::Instance().Schedule(MainLoopStartScan, this))
{
ChipLogError(Ble, "Failed to schedule BLE scan start.");
mIsScanning = false;
return CHIP_ERROR_INTERNAL;
}
CHIP_ERROR err = chip::DeviceLayer::SystemLayer().StartTimer(timeout, TimerExpiredCallback, static_cast<void *>(this));
if (err != CHIP_NO_ERROR)
{
ChipLogError(Ble, "Failed to schedule scan timeout.");
StopScan();
return err;
}
return CHIP_NO_ERROR;
}
void ChipDeviceScanner::TimerExpiredCallback(chip::System::Layer * layer, void * appState)
{
static_cast<ChipDeviceScanner *>(appState)->StopScan();
}
CHIP_ERROR ChipDeviceScanner::StopScan()
{
ReturnErrorCodeIf(!mIsScanning, CHIP_NO_ERROR);
ReturnErrorCodeIf(mIsStopping, CHIP_NO_ERROR);
mIsStopping = true;
g_cancellable_cancel(mCancellable); // in case we are currently running a scan
if (mObjectAddedSignal)
{
g_signal_handler_disconnect(mManager, mObjectAddedSignal);
mObjectAddedSignal = 0;
}
if (mInterfaceChangedSignal)
{
g_signal_handler_disconnect(mManager, mInterfaceChangedSignal);
mInterfaceChangedSignal = 0;
}
if (!MainLoop::Instance().ScheduleAndWait(MainLoopStopScan, this))
{
ChipLogError(Ble, "Failed to schedule BLE scan stop.");
return CHIP_ERROR_INTERNAL;
}
return CHIP_NO_ERROR;
}
int ChipDeviceScanner::MainLoopStopScan(ChipDeviceScanner * self)
{
GError * error = nullptr;
if (!bluez_adapter1_call_stop_discovery_sync(self->mAdapter, nullptr /* not cancellable */, &error))
{
ChipLogError(Ble, "Failed to stop discovery %s", error->message);
g_error_free(error);
}
ChipDeviceScannerDelegate * delegate = self->mDelegate;
self->mIsScanning = false;
// callback is explicitly allowed to delete the scanner (hence no more
// references to 'self' here)
delegate->OnScanComplete();
return 0;
}
void ChipDeviceScanner::SignalObjectAdded(GDBusObjectManager * manager, GDBusObject * object, ChipDeviceScanner * self)
{
self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object)));
}
void ChipDeviceScanner::SignalInterfaceChanged(GDBusObjectManagerClient * manager, GDBusObjectProxy * object,
GDBusProxy * aInterface, GVariant * aChangedProperties,
const gchar * const * aInvalidatedProps, ChipDeviceScanner * self)
{
self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object)));
}
void ChipDeviceScanner::ReportDevice(BluezDevice1 * device)
{
if (device == nullptr)
{
return;
}
if (strcmp(bluez_device1_get_adapter(device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0)
{
return;
}
chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo;
if (!BluezGetChipDeviceInfo(*device, deviceInfo))
{
ChipLogDetail(Ble, "Device %s does not look like a CHIP device.", bluez_device1_get_address(device));
return;
}
mDelegate->OnDeviceScanned(device, deviceInfo);
}
void ChipDeviceScanner::RemoveDevice(BluezDevice1 * device)
{
if (device == nullptr)
{
return;
}
if (strcmp(bluez_device1_get_adapter(device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0)
{
return;
}
chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo;
if (!BluezGetChipDeviceInfo(*device, deviceInfo))
{
return;
}
const auto devicePath = g_dbus_proxy_get_object_path(G_DBUS_PROXY(device));
GError * error = nullptr;
if (!bluez_adapter1_call_remove_device_sync(mAdapter, devicePath, nullptr, &error))
{
ChipLogDetail(Ble, "Failed to remove device %s: %s", devicePath, error->message);
g_error_free(error);
}
}
int ChipDeviceScanner::MainLoopStartScan(ChipDeviceScanner * self)
{
GError * error = nullptr;
self->mObjectAddedSignal = g_signal_connect(self->mManager, "object-added", G_CALLBACK(SignalObjectAdded), self);
self->mInterfaceChangedSignal =
g_signal_connect(self->mManager, "interface-proxy-properties-changed", G_CALLBACK(SignalInterfaceChanged), self);
ChipLogProgress(Ble, "BLE removing known devices.");
for (BluezObject & object : BluezObjectList(self->mManager))
{
self->RemoveDevice(bluez_object_get_device1(&object));
}
// Search for LE only.
// Do NOT add filtering by UUID as it is done by the following kernel function:
// https://github.com/torvalds/linux/blob/bdb575f872175ed0ecf2638369da1cb7a6e86a14/net/bluetooth/mgmt.c#L9258.
// The function requires that devices advertise its services' UUIDs in UUID16/32/128 fields
// while the Matter specification requires only FLAGS (0x01) and SERVICE_DATA_16 (0x16) fields
// in the advertisement packets.
GVariantBuilder filterBuilder;
g_variant_builder_init(&filterBuilder, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&filterBuilder, "{sv}", "Transport", g_variant_new_string("le"));
GVariant * filter = g_variant_builder_end(&filterBuilder);
if (!bluez_adapter1_call_set_discovery_filter_sync(self->mAdapter, filter, self->mCancellable, &error))
{
// Not critical: ignore if fails
ChipLogError(Ble, "Failed to set discovery filters: %s", error->message);
g_error_free(error);
}
ChipLogProgress(Ble, "BLE initiating scan.");
if (!bluez_adapter1_call_start_discovery_sync(self->mAdapter, self->mCancellable, &error))
{
ChipLogError(Ble, "Failed to start discovery: %s", error->message);
g_error_free(error);
self->mIsScanning = false;
self->mDelegate->OnScanComplete();
}
return 0;
}
} // namespace Internal
} // namespace DeviceLayer
} // namespace chip
#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
<commit_msg>Avoid crashing if Bluez is not ready to scan (#18392)<commit_after>/*
*
* Copyright (c) 2021 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 "ChipDeviceScanner.h"
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include "BluezObjectList.h"
#include "MainLoop.h"
#include "Types.h"
#include <errno.h>
#include <lib/support/logging/CHIPLogging.h>
#include <pthread.h>
namespace chip {
namespace DeviceLayer {
namespace Internal {
namespace {
struct GObjectUnref
{
template <typename T>
void operator()(T * value)
{
g_object_unref(value);
}
};
using GCancellableUniquePtr = std::unique_ptr<GCancellable, GObjectUnref>;
using GDBusObjectManagerUniquePtr = std::unique_ptr<GDBusObjectManager, GObjectUnref>;
/// Retrieve CHIP device identification info from the device advertising data
bool BluezGetChipDeviceInfo(BluezDevice1 & aDevice, chip::Ble::ChipBLEDeviceIdentificationInfo & aDeviceInfo)
{
GVariant * serviceData = bluez_device1_get_service_data(&aDevice);
VerifyOrReturnError(serviceData != nullptr, false);
GVariant * dataValue = g_variant_lookup_value(serviceData, CHIP_BLE_UUID_SERVICE_STRING, nullptr);
VerifyOrReturnError(dataValue != nullptr, false);
size_t dataLen = 0;
const void * dataBytes = g_variant_get_fixed_array(dataValue, &dataLen, sizeof(uint8_t));
VerifyOrReturnError(dataBytes != nullptr && dataLen >= sizeof(aDeviceInfo), false);
memcpy(&aDeviceInfo, dataBytes, sizeof(aDeviceInfo));
return true;
}
} // namespace
ChipDeviceScanner::ChipDeviceScanner(GDBusObjectManager * manager, BluezAdapter1 * adapter, GCancellable * cancellable,
ChipDeviceScannerDelegate * delegate) :
mManager(manager),
mAdapter(adapter), mCancellable(cancellable), mDelegate(delegate)
{
g_object_ref(mAdapter);
g_object_ref(mCancellable);
g_object_ref(mManager);
}
ChipDeviceScanner::~ChipDeviceScanner()
{
StopScan();
// In case the timeout timer is still active
chip::DeviceLayer::SystemLayer().CancelTimer(TimerExpiredCallback, this);
g_object_unref(mManager);
g_object_unref(mCancellable);
g_object_unref(mAdapter);
mManager = nullptr;
mAdapter = nullptr;
mCancellable = nullptr;
mDelegate = nullptr;
}
std::unique_ptr<ChipDeviceScanner> ChipDeviceScanner::Create(BluezAdapter1 * adapter, ChipDeviceScannerDelegate * delegate)
{
GError * error = nullptr;
GCancellableUniquePtr cancellable(g_cancellable_new(), GObjectUnref());
if (!cancellable)
{
return std::unique_ptr<ChipDeviceScanner>();
}
GDBusObjectManagerUniquePtr manager(
g_dbus_object_manager_client_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE,
"/", bluez_object_manager_client_get_proxy_type,
nullptr /* unused user data in the Proxy Type Func */,
nullptr /*destroy notify */, cancellable.get(), &error),
GObjectUnref());
if (!manager)
{
ChipLogError(Ble, "Failed to get DBUS object manager for device scanning: %s", error->message);
g_error_free(error);
return std::unique_ptr<ChipDeviceScanner>();
}
return std::make_unique<ChipDeviceScanner>(manager.get(), adapter, cancellable.get(), delegate);
}
CHIP_ERROR ChipDeviceScanner::StartScan(System::Clock::Timeout timeout)
{
ReturnErrorCodeIf(mIsScanning, CHIP_ERROR_INCORRECT_STATE);
ReturnErrorOnFailure(MainLoop::Instance().EnsureStarted());
mIsScanning = true; // optimistic, to allow all callbacks to check this
if (!MainLoop::Instance().ScheduleAndWait(MainLoopStartScan, this))
{
ChipLogError(Ble, "Failed to schedule BLE scan start.");
mIsScanning = false;
return CHIP_ERROR_INTERNAL;
}
if (!mIsScanning)
{
ChipLogError(Ble, "Failed to start BLE scan.");
return CHIP_ERROR_INTERNAL;
}
CHIP_ERROR err = chip::DeviceLayer::SystemLayer().StartTimer(timeout, TimerExpiredCallback, static_cast<void *>(this));
if (err != CHIP_NO_ERROR)
{
ChipLogError(Ble, "Failed to schedule scan timeout.");
StopScan();
return err;
}
return CHIP_NO_ERROR;
}
void ChipDeviceScanner::TimerExpiredCallback(chip::System::Layer * layer, void * appState)
{
static_cast<ChipDeviceScanner *>(appState)->StopScan();
}
CHIP_ERROR ChipDeviceScanner::StopScan()
{
ReturnErrorCodeIf(!mIsScanning, CHIP_NO_ERROR);
ReturnErrorCodeIf(mIsStopping, CHIP_NO_ERROR);
mIsStopping = true;
g_cancellable_cancel(mCancellable); // in case we are currently running a scan
if (mObjectAddedSignal)
{
g_signal_handler_disconnect(mManager, mObjectAddedSignal);
mObjectAddedSignal = 0;
}
if (mInterfaceChangedSignal)
{
g_signal_handler_disconnect(mManager, mInterfaceChangedSignal);
mInterfaceChangedSignal = 0;
}
if (!MainLoop::Instance().ScheduleAndWait(MainLoopStopScan, this))
{
ChipLogError(Ble, "Failed to schedule BLE scan stop.");
return CHIP_ERROR_INTERNAL;
}
return CHIP_NO_ERROR;
}
int ChipDeviceScanner::MainLoopStopScan(ChipDeviceScanner * self)
{
GError * error = nullptr;
if (!bluez_adapter1_call_stop_discovery_sync(self->mAdapter, nullptr /* not cancellable */, &error))
{
ChipLogError(Ble, "Failed to stop discovery %s", error->message);
g_error_free(error);
}
ChipDeviceScannerDelegate * delegate = self->mDelegate;
self->mIsScanning = false;
// callback is explicitly allowed to delete the scanner (hence no more
// references to 'self' here)
delegate->OnScanComplete();
return 0;
}
void ChipDeviceScanner::SignalObjectAdded(GDBusObjectManager * manager, GDBusObject * object, ChipDeviceScanner * self)
{
self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object)));
}
void ChipDeviceScanner::SignalInterfaceChanged(GDBusObjectManagerClient * manager, GDBusObjectProxy * object,
GDBusProxy * aInterface, GVariant * aChangedProperties,
const gchar * const * aInvalidatedProps, ChipDeviceScanner * self)
{
self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object)));
}
void ChipDeviceScanner::ReportDevice(BluezDevice1 * device)
{
if (device == nullptr)
{
return;
}
if (strcmp(bluez_device1_get_adapter(device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0)
{
return;
}
chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo;
if (!BluezGetChipDeviceInfo(*device, deviceInfo))
{
ChipLogDetail(Ble, "Device %s does not look like a CHIP device.", bluez_device1_get_address(device));
return;
}
mDelegate->OnDeviceScanned(device, deviceInfo);
}
void ChipDeviceScanner::RemoveDevice(BluezDevice1 * device)
{
if (device == nullptr)
{
return;
}
if (strcmp(bluez_device1_get_adapter(device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0)
{
return;
}
chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo;
if (!BluezGetChipDeviceInfo(*device, deviceInfo))
{
return;
}
const auto devicePath = g_dbus_proxy_get_object_path(G_DBUS_PROXY(device));
GError * error = nullptr;
if (!bluez_adapter1_call_remove_device_sync(mAdapter, devicePath, nullptr, &error))
{
ChipLogDetail(Ble, "Failed to remove device %s: %s", devicePath, error->message);
g_error_free(error);
}
}
int ChipDeviceScanner::MainLoopStartScan(ChipDeviceScanner * self)
{
GError * error = nullptr;
self->mObjectAddedSignal = g_signal_connect(self->mManager, "object-added", G_CALLBACK(SignalObjectAdded), self);
self->mInterfaceChangedSignal =
g_signal_connect(self->mManager, "interface-proxy-properties-changed", G_CALLBACK(SignalInterfaceChanged), self);
ChipLogProgress(Ble, "BLE removing known devices.");
for (BluezObject & object : BluezObjectList(self->mManager))
{
self->RemoveDevice(bluez_object_get_device1(&object));
}
// Search for LE only.
// Do NOT add filtering by UUID as it is done by the following kernel function:
// https://github.com/torvalds/linux/blob/bdb575f872175ed0ecf2638369da1cb7a6e86a14/net/bluetooth/mgmt.c#L9258.
// The function requires that devices advertise its services' UUIDs in UUID16/32/128 fields
// while the Matter specification requires only FLAGS (0x01) and SERVICE_DATA_16 (0x16) fields
// in the advertisement packets.
GVariantBuilder filterBuilder;
g_variant_builder_init(&filterBuilder, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&filterBuilder, "{sv}", "Transport", g_variant_new_string("le"));
GVariant * filter = g_variant_builder_end(&filterBuilder);
if (!bluez_adapter1_call_set_discovery_filter_sync(self->mAdapter, filter, self->mCancellable, &error))
{
// Not critical: ignore if fails
ChipLogError(Ble, "Failed to set discovery filters: %s", error->message);
g_clear_error(&error);
}
ChipLogProgress(Ble, "BLE initiating scan.");
if (!bluez_adapter1_call_start_discovery_sync(self->mAdapter, self->mCancellable, &error))
{
ChipLogError(Ble, "Failed to start discovery: %s", error->message);
g_error_free(error);
self->mIsScanning = false;
self->mDelegate->OnScanComplete();
}
return 0;
}
} // namespace Internal
} // namespace DeviceLayer
} // namespace chip
#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2010, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
*
* 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 copyright holder(s) 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.
*
* $Id$
*
*/
#ifndef PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_NORMAL_PLANE_H_
#define PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_NORMAL_PLANE_H_
#include <pcl/sample_consensus/sac_model_normal_plane.h>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SampleConsensusModelNormalPlane<PointT, PointNT>::selectWithinDistance (
const Eigen::VectorXf &model_coefficients, const double threshold, std::vector<int> &inliers)
{
if (!normals_)
{
PCL_ERROR ("[pcl::SampleConsensusModelNormalPlane::selectWithinDistance] No input dataset containing normals was given!\n");
inliers.clear ();
return;
}
// Check if the model is valid given the user constraints
if (!isModelValid (model_coefficients))
{
inliers.clear ();
return;
}
// Obtain the plane normal
Eigen::Vector4f coeff = model_coefficients;
coeff[3] = 0;
int nr_p = 0;
inliers.resize (indices_->size ());
error_sqr_dists_.resize (indices_->size ());
// Iterate through the 3d points and calculate the distances from them to the plane
for (size_t i = 0; i < indices_->size (); ++i)
{
// Calculate the distance from the point to the plane normal as the dot product
// D = (P-A).N/|N|
Eigen::Vector4f p (input_->points[(*indices_)[i]].x, input_->points[(*indices_)[i]].y, input_->points[(*indices_)[i]].z, 0);
Eigen::Vector4f n (normals_->points[(*indices_)[i]].normal[0], normals_->points[(*indices_)[i]].normal[1], normals_->points[(*indices_)[i]].normal[2], 0);
double d_euclid = fabs (coeff.dot (p) + model_coefficients[3]);
// Calculate the angular distance between the point normal and the plane normal
double d_normal = fabs (getAngle3D (n, coeff));
d_normal = (std::min) (d_normal, M_PI - d_normal);
double distance = fabs (normal_distance_weight_ * d_normal + (1 - normal_distance_weight_) * d_euclid);
if (distance < threshold)
{
// Returns the indices of the points whose distances are smaller than the threshold
inliers[nr_p] = (*indices_)[i];
error_sqr_dists_[nr_p] = distance;
++nr_p;
}
}
inliers.resize (nr_p);
error_sqr_dists_.resize (nr_p);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> int
pcl::SampleConsensusModelNormalPlane<PointT, PointNT>::countWithinDistance (
const Eigen::VectorXf &model_coefficients, const double threshold)
{
if (!normals_)
{
PCL_ERROR ("[pcl::SampleConsensusModelNormalPlane::countWithinDistance] No input dataset containing normals was given!\n");
return (0);
}
// Check if the model is valid given the user constraints
if (!isModelValid (model_coefficients))
return (0);
// Obtain the plane normal
Eigen::Vector4f coeff = model_coefficients;
coeff[3] = 0;
int nr_p = 0;
// Iterate through the 3d points and calculate the distances from them to the plane
for (size_t i = 0; i < indices_->size (); ++i)
{
// Calculate the distance from the point to the plane normal as the dot product
// D = (P-A).N/|N|
Eigen::Vector4f p (input_->points[(*indices_)[i]].x, input_->points[(*indices_)[i]].y, input_->points[(*indices_)[i]].z, 0);
Eigen::Vector4f n (normals_->points[(*indices_)[i]].normal[0], normals_->points[(*indices_)[i]].normal[1], normals_->points[(*indices_)[i]].normal[2], 0);
double d_euclid = fabs (coeff.dot (p) + model_coefficients[3]);
// Calculate the angular distance between the point normal and the plane normal
double d_normal = fabs (getAngle3D (n, coeff));
d_normal = (std::min) (d_normal, M_PI - d_normal);
if (fabs (normal_distance_weight_ * d_normal + (1 - normal_distance_weight_) * d_euclid) < threshold)
nr_p++;
}
return (nr_p);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SampleConsensusModelNormalPlane<PointT, PointNT>::getDistancesToModel (
const Eigen::VectorXf &model_coefficients, std::vector<double> &distances)
{
if (!normals_)
{
PCL_ERROR ("[pcl::SampleConsensusModelNormalPlane::getDistancesToModel] No input dataset containing normals was given!\n");
return;
}
// Check if the model is valid given the user constraints
if (!isModelValid (model_coefficients))
{
distances.clear ();
return;
}
// Obtain the plane normal
Eigen::Vector4f coeff = model_coefficients;
coeff[3] = 0;
distances.resize (indices_->size ());
// Iterate through the 3d points and calculate the distances from them to the plane
for (size_t i = 0; i < indices_->size (); ++i)
{
// Calculate the distance from the point to the plane normal as the dot product
// D = (P-A).N/|N|
Eigen::Vector4f p (input_->points[(*indices_)[i]].x, input_->points[(*indices_)[i]].y, input_->points[(*indices_)[i]].z, 0);
Eigen::Vector4f n (normals_->points[(*indices_)[i]].normal[0], normals_->points[(*indices_)[i]].normal[1], normals_->points[(*indices_)[i]].normal[2], 0);
double d_euclid = fabs (coeff.dot (p) + model_coefficients[3]);
// Calculate the angular distance between the point normal and the plane normal
double d_normal = fabs (getAngle3D (n, coeff));
d_normal = (std::min) (d_normal, M_PI - d_normal);
distances[i] = fabs (normal_distance_weight_ * d_normal + (1 - normal_distance_weight_) * d_euclid);
}
}
#define PCL_INSTANTIATE_SampleConsensusModelNormalPlane(PointT, PointNT) template class PCL_EXPORTS pcl::SampleConsensusModelNormalPlane<PointT, PointNT>;
#endif // PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_NORMAL_PLANE_H_
<commit_msg>* using point curvature to robustify the results of @SampleConsensusModelNormalPlane@<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2010, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
*
* 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 copyright holder(s) 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.
*
* $Id$
*
*/
#ifndef PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_NORMAL_PLANE_H_
#define PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_NORMAL_PLANE_H_
#include <pcl/sample_consensus/sac_model_normal_plane.h>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SampleConsensusModelNormalPlane<PointT, PointNT>::selectWithinDistance (
const Eigen::VectorXf &model_coefficients, const double threshold, std::vector<int> &inliers)
{
if (!normals_)
{
PCL_ERROR ("[pcl::SampleConsensusModelNormalPlane::selectWithinDistance] No input dataset containing normals was given!\n");
inliers.clear ();
return;
}
// Check if the model is valid given the user constraints
if (!isModelValid (model_coefficients))
{
inliers.clear ();
return;
}
// Obtain the plane normal
Eigen::Vector4f coeff = model_coefficients;
coeff[3] = 0;
int nr_p = 0;
inliers.resize (indices_->size ());
error_sqr_dists_.resize (indices_->size ());
// Iterate through the 3d points and calculate the distances from them to the plane
for (size_t i = 0; i < indices_->size (); ++i)
{
const PointT &pt = input_->points[(*indices_)[i]];
const PointNT &nt = normals_->points[(*indices_)[i]];
// Calculate the distance from the point to the plane normal as the dot product
// D = (P-A).N/|N|
Eigen::Vector4f p (pt.x, pt.y, pt.z, 0);
Eigen::Vector4f n (nt.normal_x, nt.normal_y, nt.normal_z, 0);
double d_euclid = fabs (coeff.dot (p) + model_coefficients[3]);
// Calculate the angular distance between the point normal and the plane normal
double d_normal = fabs (getAngle3D (n, coeff));
d_normal = (std::min) (d_normal, M_PI - d_normal);
// Weight with the point curvature. On flat surfaces, curvature -> 0, which means the normal will have a higher influence
double weight = normal_distance_weight_ * (1.0 - nt.curvature);
double distance = fabs (weight * d_normal + (1.0 - weight) * d_euclid);
if (distance < threshold)
{
// Returns the indices of the points whose distances are smaller than the threshold
inliers[nr_p] = (*indices_)[i];
error_sqr_dists_[nr_p] = distance;
++nr_p;
}
}
inliers.resize (nr_p);
error_sqr_dists_.resize (nr_p);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> int
pcl::SampleConsensusModelNormalPlane<PointT, PointNT>::countWithinDistance (
const Eigen::VectorXf &model_coefficients, const double threshold)
{
if (!normals_)
{
PCL_ERROR ("[pcl::SampleConsensusModelNormalPlane::countWithinDistance] No input dataset containing normals was given!\n");
return (0);
}
// Check if the model is valid given the user constraints
if (!isModelValid (model_coefficients))
return (0);
// Obtain the plane normal
Eigen::Vector4f coeff = model_coefficients;
coeff[3] = 0;
int nr_p = 0;
// Iterate through the 3d points and calculate the distances from them to the plane
for (size_t i = 0; i < indices_->size (); ++i)
{
const PointT &pt = input_->points[(*indices_)[i]];
const PointNT &nt = normals_->points[(*indices_)[i]];
// Calculate the distance from the point to the plane normal as the dot product
// D = (P-A).N/|N|
Eigen::Vector4f p (pt.x, pt.y, pt.z, 0);
Eigen::Vector4f n (nt.normal_x, nt.normal_y, nt.normal_z, 0);
double d_euclid = fabs (coeff.dot (p) + model_coefficients[3]);
// Calculate the angular distance between the point normal and the plane normal
double d_normal = fabs (getAngle3D (n, coeff));
d_normal = (std::min) (d_normal, M_PI - d_normal);
// Weight with the point curvature. On flat surfaces, curvature -> 0, which means the normal will have a higher influence
double weight = normal_distance_weight_ * (1.0 - nt.curvature);
if (fabs (weight * d_normal + (1.0 - weight) * d_euclid) < threshold)
nr_p++;
}
return (nr_p);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SampleConsensusModelNormalPlane<PointT, PointNT>::getDistancesToModel (
const Eigen::VectorXf &model_coefficients, std::vector<double> &distances)
{
if (!normals_)
{
PCL_ERROR ("[pcl::SampleConsensusModelNormalPlane::getDistancesToModel] No input dataset containing normals was given!\n");
return;
}
// Check if the model is valid given the user constraints
if (!isModelValid (model_coefficients))
{
distances.clear ();
return;
}
// Obtain the plane normal
Eigen::Vector4f coeff = model_coefficients;
coeff[3] = 0;
distances.resize (indices_->size ());
// Iterate through the 3d points and calculate the distances from them to the plane
for (size_t i = 0; i < indices_->size (); ++i)
{
const PointT &pt = input_->points[(*indices_)[i]];
const PointNT &nt = normals_->points[(*indices_)[i]];
// Calculate the distance from the point to the plane normal as the dot product
// D = (P-A).N/|N|
Eigen::Vector4f p (pt.x, pt.y, pt.z, 0);
Eigen::Vector4f n (nt.normal_x, nt.normal_y, nt.normal_z, 0);
double d_euclid = fabs (coeff.dot (p) + model_coefficients[3]);
// Calculate the angular distance between the point normal and the plane normal
double d_normal = fabs (getAngle3D (n, coeff));
d_normal = (std::min) (d_normal, M_PI - d_normal);
// Weight with the point curvature. On flat surfaces, curvature -> 0, which means the normal will have a higher influence
double weight = normal_distance_weight_ * (1.0 - nt.curvature);
distances[i] = fabs (weight * d_normal + (1.0 - weight) * d_euclid);
}
}
#define PCL_INSTANTIATE_SampleConsensusModelNormalPlane(PointT, PointNT) template class PCL_EXPORTS pcl::SampleConsensusModelNormalPlane<PointT, PointNT>;
#endif // PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_NORMAL_PLANE_H_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b3dtuple.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: obo $ $Date: 2007-07-18 11:04:50 $
*
* 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 _BGFX_TUPLE_B3DTUPLE_HXX
#define _BGFX_TUPLE_B3DTUPLE_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif
namespace basegfx
{
// predeclarations
class B3ITuple;
/** Base class for all Points/Vectors with three double values
This class provides all methods common to Point
avd Vector classes which are derived from here.
@derive Use this class to implement Points or Vectors
which are based on three double values
*/
class B3DTuple
{
protected:
double mfX;
double mfY;
double mfZ;
public:
/** Create a 3D Tuple
The tuple is initialized to (0.0, 0.0, 0.0)
*/
B3DTuple()
: mfX(0.0),
mfY(0.0),
mfZ(0.0)
{}
/** Create a 3D Tuple
@param fX
This parameter is used to initialize the X-coordinate
of the 3D Tuple.
@param fY
This parameter is used to initialize the Y-coordinate
of the 3D Tuple.
@param fZ
This parameter is used to initialize the Z-coordinate
of the 3D Tuple.
*/
B3DTuple(double fX, double fY, double fZ)
: mfX(fX),
mfY(fY),
mfZ(fZ)
{}
/** Create a copy of a 3D Tuple
@param rTup
The 3D Tuple which will be copied.
*/
B3DTuple(const B3DTuple& rTup)
: mfX( rTup.mfX ),
mfY( rTup.mfY ),
mfZ( rTup.mfZ )
{}
/** Create a copy of a 3D integer Tuple
@param rTup
The 3D Tuple which will be copied.
*/
explicit B3DTuple(const B3ITuple& rTup);
~B3DTuple()
{}
/// get X-Coordinate of 3D Tuple
double getX() const
{
return mfX;
}
/// get Y-Coordinate of 3D Tuple
double getY() const
{
return mfY;
}
/// get Z-Coordinate of 3D Tuple
double getZ() const
{
return mfZ;
}
/// set X-Coordinate of 3D Tuple
void setX(double fX)
{
mfX = fX;
}
/// set Y-Coordinate of 3D Tuple
void setY(double fY)
{
mfY = fY;
}
/// set Z-Coordinate of 3D Tuple
void setZ(double fZ)
{
mfZ = fZ;
}
/// Array-access to 3D Tuple
const double& operator[] (int nPos) const
{
// Here, normally two if(...)'s should be used. In the assumption that
// both double members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mfX; if(1 == nPos) return mfY; return mfZ;
return *((&mfX) + nPos);
}
/// Array-access to 3D Tuple
double& operator[] (int nPos)
{
// Here, normally two if(...)'s should be used. In the assumption that
// both double members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mfX; if(1 == nPos) return mfY; return mfZ;
return *((&mfX) + nPos);
}
// comparators with tolerance
//////////////////////////////////////////////////////////////////////
bool equalZero() const
{
return (this == &getEmptyTuple() ||
(::basegfx::fTools::equalZero(mfX)
&& ::basegfx::fTools::equalZero(mfY)
&& ::basegfx::fTools::equalZero(mfZ)));
}
bool equalZero(const double& rfSmallValue) const
{
return (this == &getEmptyTuple() ||
(::basegfx::fTools::equalZero(mfX, rfSmallValue)
&& ::basegfx::fTools::equalZero(mfY, rfSmallValue)
&& ::basegfx::fTools::equalZero(mfZ, rfSmallValue)));
}
bool equal(const B3DTuple& rTup) const
{
return (
::basegfx::fTools::equal(mfX, rTup.mfX) &&
::basegfx::fTools::equal(mfY, rTup.mfY) &&
::basegfx::fTools::equal(mfZ, rTup.mfZ));
}
// operators
//////////////////////////////////////////////////////////////////////
B3DTuple& operator+=( const B3DTuple& rTup )
{
mfX += rTup.mfX;
mfY += rTup.mfY;
mfZ += rTup.mfZ;
return *this;
}
B3DTuple& operator-=( const B3DTuple& rTup )
{
mfX -= rTup.mfX;
mfY -= rTup.mfY;
mfZ -= rTup.mfZ;
return *this;
}
B3DTuple& operator/=( const B3DTuple& rTup )
{
mfX /= rTup.mfX;
mfY /= rTup.mfY;
mfZ /= rTup.mfZ;
return *this;
}
B3DTuple& operator*=( const B3DTuple& rTup )
{
mfX *= rTup.mfX;
mfY *= rTup.mfY;
mfZ *= rTup.mfZ;
return *this;
}
B3DTuple& operator*=(double t)
{
mfX *= t;
mfY *= t;
mfZ *= t;
return *this;
}
B3DTuple& operator/=(double t)
{
const double fVal(1.0 / t);
mfX *= fVal;
mfY *= fVal;
mfZ *= fVal;
return *this;
}
B3DTuple operator-(void) const
{
return B3DTuple(-mfX, -mfY, -mfZ);
}
bool operator==( const B3DTuple& rTup ) const
{
return equal(rTup);
}
bool operator!=( const B3DTuple& rTup ) const
{
return !equal(rTup);
}
B3DTuple& operator=( const B3DTuple& rTup )
{
mfX = rTup.mfX;
mfY = rTup.mfY;
mfZ = rTup.mfZ;
return *this;
}
void correctValues(const double fCompareValue = 0.0)
{
if(0.0 == fCompareValue)
{
if(::basegfx::fTools::equalZero(mfX))
{
mfX = 0.0;
}
if(::basegfx::fTools::equalZero(mfY))
{
mfY = 0.0;
}
if(::basegfx::fTools::equalZero(mfZ))
{
mfZ = 0.0;
}
}
else
{
if(::basegfx::fTools::equal(mfX, fCompareValue))
{
mfX = fCompareValue;
}
if(::basegfx::fTools::equal(mfY, fCompareValue))
{
mfY = fCompareValue;
}
if(::basegfx::fTools::equal(mfZ, fCompareValue))
{
mfZ = fCompareValue;
}
}
}
static const B3DTuple& getEmptyTuple();
};
// external operators
//////////////////////////////////////////////////////////////////////////
inline B3DTuple minimum(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aMin(
(rTupB.getX() < rTupA.getX()) ? rTupB.getX() : rTupA.getX(),
(rTupB.getY() < rTupA.getY()) ? rTupB.getY() : rTupA.getY(),
(rTupB.getZ() < rTupA.getZ()) ? rTupB.getZ() : rTupA.getZ());
return aMin;
}
inline B3DTuple maximum(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aMax(
(rTupB.getX() > rTupA.getX()) ? rTupB.getX() : rTupA.getX(),
(rTupB.getY() > rTupA.getY()) ? rTupB.getY() : rTupA.getY(),
(rTupB.getZ() > rTupA.getZ()) ? rTupB.getZ() : rTupA.getZ());
return aMax;
}
inline B3DTuple absolute(const B3DTuple& rTup)
{
B3DTuple aAbs(
(0.0 > rTup.getX()) ? -rTup.getX() : rTup.getX(),
(0.0 > rTup.getY()) ? -rTup.getY() : rTup.getY(),
(0.0 > rTup.getZ()) ? -rTup.getZ() : rTup.getZ());
return aAbs;
}
inline B3DTuple interpolate(const B3DTuple& rOld1, const B3DTuple& rOld2, double t)
{
B3DTuple aInt(
((rOld2.getX() - rOld1.getX()) * t) + rOld1.getX(),
((rOld2.getY() - rOld1.getY()) * t) + rOld1.getY(),
((rOld2.getZ() - rOld1.getZ()) * t) + rOld1.getZ());
return aInt;
}
inline B3DTuple average(const B3DTuple& rOld1, const B3DTuple& rOld2)
{
B3DTuple aAvg(
(rOld1.getX() + rOld2.getX()) * 0.5,
(rOld1.getY() + rOld2.getY()) * 0.5,
(rOld1.getZ() + rOld2.getZ()) * 0.5);
return aAvg;
}
inline B3DTuple average(const B3DTuple& rOld1, const B3DTuple& rOld2, const B3DTuple& rOld3)
{
B3DTuple aAvg(
(rOld1.getX() + rOld2.getX() + rOld3.getX()) * (1.0 / 3.0),
(rOld1.getY() + rOld2.getY() + rOld3.getY()) * (1.0 / 3.0),
(rOld1.getZ() + rOld2.getZ() + rOld3.getZ()) * (1.0 / 3.0));
return aAvg;
}
inline B3DTuple operator+(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aSum(rTupA);
aSum += rTupB;
return aSum;
}
inline B3DTuple operator-(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aSub(rTupA);
aSub -= rTupB;
return aSub;
}
inline B3DTuple operator/(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aDiv(rTupA);
aDiv /= rTupB;
return aDiv;
}
inline B3DTuple operator*(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aMul(rTupA);
aMul *= rTupB;
return aMul;
}
inline B3DTuple operator*(const B3DTuple& rTup, double t)
{
B3DTuple aNew(rTup);
aNew *= t;
return aNew;
}
inline B3DTuple operator*(double t, const B3DTuple& rTup)
{
B3DTuple aNew(rTup);
aNew *= t;
return aNew;
}
inline B3DTuple operator/(const B3DTuple& rTup, double t)
{
B3DTuple aNew(rTup);
aNew /= t;
return aNew;
}
inline B3DTuple operator/(double t, const B3DTuple& rTup)
{
B3DTuple aNew(rTup);
aNew /= t;
return aNew;
}
/** Round double to nearest integer for 3D tuple
@return the nearest integer for this tuple
*/
B3ITuple fround(const B3DTuple& rTup);
} // end of namespace basegfx
#endif /* _BGFX_TUPLE_B3DTUPLE_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.13.32); FILE MERGED 2008/04/01 15:01:11 thb 1.13.32.3: #i85898# Stripping all external header guards 2008/04/01 10:48:11 thb 1.13.32.2: #i85898# Stripping all external header guards 2008/03/28 16:05:46 rt 1.13.32.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b3dtuple.hxx,v $
* $Revision: 1.14 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BGFX_TUPLE_B3DTUPLE_HXX
#define _BGFX_TUPLE_B3DTUPLE_HXX
#include <sal/types.h>
#include <basegfx/numeric/ftools.hxx>
namespace basegfx
{
// predeclarations
class B3ITuple;
/** Base class for all Points/Vectors with three double values
This class provides all methods common to Point
avd Vector classes which are derived from here.
@derive Use this class to implement Points or Vectors
which are based on three double values
*/
class B3DTuple
{
protected:
double mfX;
double mfY;
double mfZ;
public:
/** Create a 3D Tuple
The tuple is initialized to (0.0, 0.0, 0.0)
*/
B3DTuple()
: mfX(0.0),
mfY(0.0),
mfZ(0.0)
{}
/** Create a 3D Tuple
@param fX
This parameter is used to initialize the X-coordinate
of the 3D Tuple.
@param fY
This parameter is used to initialize the Y-coordinate
of the 3D Tuple.
@param fZ
This parameter is used to initialize the Z-coordinate
of the 3D Tuple.
*/
B3DTuple(double fX, double fY, double fZ)
: mfX(fX),
mfY(fY),
mfZ(fZ)
{}
/** Create a copy of a 3D Tuple
@param rTup
The 3D Tuple which will be copied.
*/
B3DTuple(const B3DTuple& rTup)
: mfX( rTup.mfX ),
mfY( rTup.mfY ),
mfZ( rTup.mfZ )
{}
/** Create a copy of a 3D integer Tuple
@param rTup
The 3D Tuple which will be copied.
*/
explicit B3DTuple(const B3ITuple& rTup);
~B3DTuple()
{}
/// get X-Coordinate of 3D Tuple
double getX() const
{
return mfX;
}
/// get Y-Coordinate of 3D Tuple
double getY() const
{
return mfY;
}
/// get Z-Coordinate of 3D Tuple
double getZ() const
{
return mfZ;
}
/// set X-Coordinate of 3D Tuple
void setX(double fX)
{
mfX = fX;
}
/// set Y-Coordinate of 3D Tuple
void setY(double fY)
{
mfY = fY;
}
/// set Z-Coordinate of 3D Tuple
void setZ(double fZ)
{
mfZ = fZ;
}
/// Array-access to 3D Tuple
const double& operator[] (int nPos) const
{
// Here, normally two if(...)'s should be used. In the assumption that
// both double members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mfX; if(1 == nPos) return mfY; return mfZ;
return *((&mfX) + nPos);
}
/// Array-access to 3D Tuple
double& operator[] (int nPos)
{
// Here, normally two if(...)'s should be used. In the assumption that
// both double members can be accessed as an array a shortcut is used here.
// if(0 == nPos) return mfX; if(1 == nPos) return mfY; return mfZ;
return *((&mfX) + nPos);
}
// comparators with tolerance
//////////////////////////////////////////////////////////////////////
bool equalZero() const
{
return (this == &getEmptyTuple() ||
(::basegfx::fTools::equalZero(mfX)
&& ::basegfx::fTools::equalZero(mfY)
&& ::basegfx::fTools::equalZero(mfZ)));
}
bool equalZero(const double& rfSmallValue) const
{
return (this == &getEmptyTuple() ||
(::basegfx::fTools::equalZero(mfX, rfSmallValue)
&& ::basegfx::fTools::equalZero(mfY, rfSmallValue)
&& ::basegfx::fTools::equalZero(mfZ, rfSmallValue)));
}
bool equal(const B3DTuple& rTup) const
{
return (
::basegfx::fTools::equal(mfX, rTup.mfX) &&
::basegfx::fTools::equal(mfY, rTup.mfY) &&
::basegfx::fTools::equal(mfZ, rTup.mfZ));
}
// operators
//////////////////////////////////////////////////////////////////////
B3DTuple& operator+=( const B3DTuple& rTup )
{
mfX += rTup.mfX;
mfY += rTup.mfY;
mfZ += rTup.mfZ;
return *this;
}
B3DTuple& operator-=( const B3DTuple& rTup )
{
mfX -= rTup.mfX;
mfY -= rTup.mfY;
mfZ -= rTup.mfZ;
return *this;
}
B3DTuple& operator/=( const B3DTuple& rTup )
{
mfX /= rTup.mfX;
mfY /= rTup.mfY;
mfZ /= rTup.mfZ;
return *this;
}
B3DTuple& operator*=( const B3DTuple& rTup )
{
mfX *= rTup.mfX;
mfY *= rTup.mfY;
mfZ *= rTup.mfZ;
return *this;
}
B3DTuple& operator*=(double t)
{
mfX *= t;
mfY *= t;
mfZ *= t;
return *this;
}
B3DTuple& operator/=(double t)
{
const double fVal(1.0 / t);
mfX *= fVal;
mfY *= fVal;
mfZ *= fVal;
return *this;
}
B3DTuple operator-(void) const
{
return B3DTuple(-mfX, -mfY, -mfZ);
}
bool operator==( const B3DTuple& rTup ) const
{
return equal(rTup);
}
bool operator!=( const B3DTuple& rTup ) const
{
return !equal(rTup);
}
B3DTuple& operator=( const B3DTuple& rTup )
{
mfX = rTup.mfX;
mfY = rTup.mfY;
mfZ = rTup.mfZ;
return *this;
}
void correctValues(const double fCompareValue = 0.0)
{
if(0.0 == fCompareValue)
{
if(::basegfx::fTools::equalZero(mfX))
{
mfX = 0.0;
}
if(::basegfx::fTools::equalZero(mfY))
{
mfY = 0.0;
}
if(::basegfx::fTools::equalZero(mfZ))
{
mfZ = 0.0;
}
}
else
{
if(::basegfx::fTools::equal(mfX, fCompareValue))
{
mfX = fCompareValue;
}
if(::basegfx::fTools::equal(mfY, fCompareValue))
{
mfY = fCompareValue;
}
if(::basegfx::fTools::equal(mfZ, fCompareValue))
{
mfZ = fCompareValue;
}
}
}
static const B3DTuple& getEmptyTuple();
};
// external operators
//////////////////////////////////////////////////////////////////////////
inline B3DTuple minimum(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aMin(
(rTupB.getX() < rTupA.getX()) ? rTupB.getX() : rTupA.getX(),
(rTupB.getY() < rTupA.getY()) ? rTupB.getY() : rTupA.getY(),
(rTupB.getZ() < rTupA.getZ()) ? rTupB.getZ() : rTupA.getZ());
return aMin;
}
inline B3DTuple maximum(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aMax(
(rTupB.getX() > rTupA.getX()) ? rTupB.getX() : rTupA.getX(),
(rTupB.getY() > rTupA.getY()) ? rTupB.getY() : rTupA.getY(),
(rTupB.getZ() > rTupA.getZ()) ? rTupB.getZ() : rTupA.getZ());
return aMax;
}
inline B3DTuple absolute(const B3DTuple& rTup)
{
B3DTuple aAbs(
(0.0 > rTup.getX()) ? -rTup.getX() : rTup.getX(),
(0.0 > rTup.getY()) ? -rTup.getY() : rTup.getY(),
(0.0 > rTup.getZ()) ? -rTup.getZ() : rTup.getZ());
return aAbs;
}
inline B3DTuple interpolate(const B3DTuple& rOld1, const B3DTuple& rOld2, double t)
{
B3DTuple aInt(
((rOld2.getX() - rOld1.getX()) * t) + rOld1.getX(),
((rOld2.getY() - rOld1.getY()) * t) + rOld1.getY(),
((rOld2.getZ() - rOld1.getZ()) * t) + rOld1.getZ());
return aInt;
}
inline B3DTuple average(const B3DTuple& rOld1, const B3DTuple& rOld2)
{
B3DTuple aAvg(
(rOld1.getX() + rOld2.getX()) * 0.5,
(rOld1.getY() + rOld2.getY()) * 0.5,
(rOld1.getZ() + rOld2.getZ()) * 0.5);
return aAvg;
}
inline B3DTuple average(const B3DTuple& rOld1, const B3DTuple& rOld2, const B3DTuple& rOld3)
{
B3DTuple aAvg(
(rOld1.getX() + rOld2.getX() + rOld3.getX()) * (1.0 / 3.0),
(rOld1.getY() + rOld2.getY() + rOld3.getY()) * (1.0 / 3.0),
(rOld1.getZ() + rOld2.getZ() + rOld3.getZ()) * (1.0 / 3.0));
return aAvg;
}
inline B3DTuple operator+(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aSum(rTupA);
aSum += rTupB;
return aSum;
}
inline B3DTuple operator-(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aSub(rTupA);
aSub -= rTupB;
return aSub;
}
inline B3DTuple operator/(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aDiv(rTupA);
aDiv /= rTupB;
return aDiv;
}
inline B3DTuple operator*(const B3DTuple& rTupA, const B3DTuple& rTupB)
{
B3DTuple aMul(rTupA);
aMul *= rTupB;
return aMul;
}
inline B3DTuple operator*(const B3DTuple& rTup, double t)
{
B3DTuple aNew(rTup);
aNew *= t;
return aNew;
}
inline B3DTuple operator*(double t, const B3DTuple& rTup)
{
B3DTuple aNew(rTup);
aNew *= t;
return aNew;
}
inline B3DTuple operator/(const B3DTuple& rTup, double t)
{
B3DTuple aNew(rTup);
aNew /= t;
return aNew;
}
inline B3DTuple operator/(double t, const B3DTuple& rTup)
{
B3DTuple aNew(rTup);
aNew /= t;
return aNew;
}
/** Round double to nearest integer for 3D tuple
@return the nearest integer for this tuple
*/
B3ITuple fround(const B3DTuple& rTup);
} // end of namespace basegfx
#endif /* _BGFX_TUPLE_B3DTUPLE_HXX */
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pushnotificationclient.hh"
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <poll.h>
PushNotificationClient::PushNotificationClient(const string &name, PushNotificationService *service,
SSL_CTX * ctx, const std::string &host, const std::string &port, int maxQueueSize, bool isSecure) :
mThread(), mThreadRunning(false), mThreadWaiting(true), mBio(NULL),
mService(service), mCtx(ctx), mName(name), mHost(host), mPort(port),
mMaxQueueSize(maxQueueSize), mLastUse(0), mIsSecure(isSecure) {}
PushNotificationClient::~PushNotificationClient() {
if (mThreadRunning) {
mThreadRunning = false;
mMutex.lock();
if (mThreadWaiting) mCondVar.notify_one();
mMutex.unlock();
mThread.join();
}
if (mBio) {
BIO_free_all(mBio);
}
if (mCtx) {
SSL_CTX_free(mCtx);
}
}
int PushNotificationClient::sendPush(const std::shared_ptr<PushNotificationRequest> &req) {
if (!mThreadRunning) {
// start thread only when we have at least one push to send
mThreadRunning = true;
mThread = std::thread(&PushNotificationClient::run, this);
}
mMutex.lock();
int size = mRequestQueue.size();
if (size >= mMaxQueueSize) {
SLOGW << "PushNotificationClient " << mName << " PNR " << req.get() << " queue full, push lost";
onError(req, "Error queue full");
mMutex.unlock();
return 0;
} else {
mRequestQueue.push(req);
/*client is running, it will pop the queue as soon he is finished with current request*/
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " running, queue_size=" << size;
if (mThreadWaiting) mCondVar.notify_one();
mMutex.unlock();
return 1;
}
}
bool PushNotificationClient::isIdle() {
return mRequestQueue.empty();
}
void PushNotificationClient::recreateConnection() {
/* Setup the connection */
if (mBio) {
BIO_free_all(mBio);
}
/* Create and setup the connection */
std::string hostname = mHost + ":" + mPort;
SSL * ssl = NULL;
if (mIsSecure) {
mBio = BIO_new_ssl_connect(mCtx);
BIO_set_conn_hostname(mBio, hostname.c_str());
/* Set the SSL_MODE_AUTO_RETRY flag */
BIO_get_ssl(mBio, &ssl);
SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
SSL_set_options(ssl, SSL_OP_ALL);
}else{
mBio = BIO_new_connect((char*)hostname.c_str());
}
int sat = BIO_do_connect(mBio);
if (sat <= 0) {
SLOGE << "Error attempting to connect to " << hostname << ": " << sat << " - " << strerror( errno);
ERR_print_errors_fp(stderr);
goto error;
}
if (mIsSecure){
sat = BIO_do_handshake(mBio);
if (sat <= 0){
SLOGE << "Error attempting to handshake to " << hostname << ": " << sat << " - " << strerror( errno);
ERR_print_errors_fp(stderr);
goto error;
}
}
//BIO_set_nbio(mBio, 1);
/* Check the certificate */
if(ssl && (SSL_get_verify_mode(ssl) == SSL_VERIFY_PEER && SSL_get_verify_result(ssl) != X509_V_OK))
{
SLOGE << "Certificate verification error: " << X509_verify_cert_error_string(SSL_get_verify_result(ssl));
goto error;
}
return;
error:
BIO_free_all(mBio);
mBio = NULL;
}
void PushNotificationClient::sendPushToServer(const std::shared_ptr<PushNotificationRequest> &req) {
if (mLastUse == 0 || !mBio) {
recreateConnection();
/*the client was inactive possibly for a long time. In such case, close and re-create the socket.*/
} else if (getCurrentTime() - mLastUse > 60) {
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " previous was "
<< getCurrentTime() - mLastUse << " secs ago, re-creating connection with server.";
recreateConnection();
}
if (!mBio) {
onError(req, "Cannot create connection to server");
return;
}
/* send push to the server */
mLastUse = getCurrentTime();
auto buffer = req->getData();
int wcount = BIO_write(mBio, buffer.data(), buffer.size());
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " sent " << wcount << "/" << buffer.size() << " data";
if (wcount <= 0) {
onError(req, "Cannot send to server");
return;
}
/* wait for server response */
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " waiting for server response";
if (BIO_pending(mBio) <= 0) {
int fdSocket;
if (BIO_get_fd(mBio, &fdSocket) < 0) {
SLOGE << "PushNotificationClient " << mName << " PNR " << req.get() << " could not retrieve the socket";
onError(req, "Broken socket");
return;
}
pollfd polls = {0};
polls.fd = fdSocket;
polls.events = POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI;
int nRet = poll(&polls, 1, 1000);
// this is specific to iOS which does not send a response in case of success
if (nRet <= 0) {//poll timeout, we shall not expect a response.
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " nothing read, assuming success";
onSuccess(req);
return;
}
}
char r[1024];
int p = BIO_read(mBio, r, sizeof(r)-1);
if (p > 0) {
r[p] = 0;
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " read " << p << " data:\n" << r;
string responsestr(r, p);
if (!req->isValidResponse(responsestr)) {
onError(req, "Invalid server response");
}else{
onSuccess(req);
}
}
}
void PushNotificationClient::run() {
std::unique_lock<std::mutex> lock(mMutex);
while (mThreadRunning) {
if (!isIdle()) {
SLOGD << "PushNotificationClient " << mName << " next, queue_size=" << mRequestQueue.size();
auto req = mRequestQueue.front();
mRequestQueue.pop();
lock.unlock();
// send push to the server and wait for its answer
sendPushToServer(req);
lock.lock();
} else {
mThreadWaiting = true;
mCondVar.wait(lock);
mThreadWaiting = false;
}
}
}
void PushNotificationClient::onError(shared_ptr<PushNotificationRequest> req, const string &msg) {
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " failed: " << msg;
if (mService->mCountFailed) {
mService->mCountFailed->incr();
}
recreateConnection();
}
void PushNotificationClient::onSuccess(shared_ptr<PushNotificationRequest> req) {
if (mService->mCountSent) {
mService->mCountSent->incr();
}
}
<commit_msg>attempt to robustize push notifs again<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pushnotificationclient.hh"
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <poll.h>
PushNotificationClient::PushNotificationClient(const string &name, PushNotificationService *service,
SSL_CTX * ctx, const std::string &host, const std::string &port, int maxQueueSize, bool isSecure) :
mThread(), mThreadRunning(false), mThreadWaiting(true), mBio(NULL),
mService(service), mCtx(ctx), mName(name), mHost(host), mPort(port),
mMaxQueueSize(maxQueueSize), mLastUse(0), mIsSecure(isSecure) {}
PushNotificationClient::~PushNotificationClient() {
if (mThreadRunning) {
mThreadRunning = false;
mMutex.lock();
if (mThreadWaiting) mCondVar.notify_one();
mMutex.unlock();
mThread.join();
}
if (mBio) {
BIO_free_all(mBio);
}
if (mCtx) {
SSL_CTX_free(mCtx);
}
}
int PushNotificationClient::sendPush(const std::shared_ptr<PushNotificationRequest> &req) {
if (!mThreadRunning) {
// start thread only when we have at least one push to send
mThreadRunning = true;
mThread = std::thread(&PushNotificationClient::run, this);
}
mMutex.lock();
int size = mRequestQueue.size();
if (size >= mMaxQueueSize) {
SLOGW << "PushNotificationClient " << mName << " PNR " << req.get() << " queue full, push lost";
onError(req, "Error queue full");
mMutex.unlock();
return 0;
} else {
mRequestQueue.push(req);
/*client is running, it will pop the queue as soon he is finished with current request*/
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " running, queue_size=" << size;
if (mThreadWaiting) mCondVar.notify_one();
mMutex.unlock();
return 1;
}
}
bool PushNotificationClient::isIdle() {
return mRequestQueue.empty();
}
void PushNotificationClient::recreateConnection() {
/* Setup the connection */
if (mBio) {
BIO_free_all(mBio);
}
/* Create and setup the connection */
std::string hostname = mHost + ":" + mPort;
SSL * ssl = NULL;
if (mIsSecure) {
mBio = BIO_new_ssl_connect(mCtx);
BIO_set_conn_hostname(mBio, hostname.c_str());
/* Set the SSL_MODE_AUTO_RETRY flag */
BIO_get_ssl(mBio, &ssl);
SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
SSL_set_options(ssl, SSL_OP_ALL);
}else{
mBio = BIO_new_connect((char*)hostname.c_str());
}
int sat = BIO_do_connect(mBio);
if (sat <= 0) {
SLOGE << "Error attempting to connect to " << hostname << ": " << sat << " - " << strerror( errno);
ERR_print_errors_fp(stderr);
goto error;
}
if (mIsSecure){
sat = BIO_do_handshake(mBio);
if (sat <= 0){
SLOGE << "Error attempting to handshake to " << hostname << ": " << sat << " - " << strerror( errno);
ERR_print_errors_fp(stderr);
goto error;
}
}
//BIO_set_nbio(mBio, 1);
/* Check the certificate */
if(ssl && (SSL_get_verify_mode(ssl) == SSL_VERIFY_PEER && SSL_get_verify_result(ssl) != X509_V_OK))
{
SLOGE << "Certificate verification error: " << X509_verify_cert_error_string(SSL_get_verify_result(ssl));
goto error;
}
return;
error:
BIO_free_all(mBio);
mBio = NULL;
}
void PushNotificationClient::sendPushToServer(const std::shared_ptr<PushNotificationRequest> &req) {
if (mLastUse == 0 || !mBio) {
recreateConnection();
/*the client was inactive possibly for a long time. In such case, close and re-create the socket.*/
} else if (getCurrentTime() - mLastUse > 60) {
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " previous was "
<< getCurrentTime() - mLastUse << " secs ago, re-creating connection with server.";
recreateConnection();
}
if (!mBio) {
onError(req, "Cannot create connection to server");
return;
}
/* send push to the server */
mLastUse = getCurrentTime();
auto buffer = req->getData();
int wcount = BIO_write(mBio, buffer.data(), buffer.size());
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " sent " << wcount << "/" << buffer.size() << " data";
if (wcount <= 0) {
onError(req, "Cannot send to server");
return;
}
/* wait for server response */
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " waiting for server response";
int fdSocket;
if (BIO_get_fd(mBio, &fdSocket) < 0) {
SLOGE << "PushNotificationClient " << mName << " PNR " << req.get() << " could not retrieve the socket";
onError(req, "Broken socket");
return;
}
pollfd polls = {0};
polls.fd = fdSocket;
polls.events = POLLIN;
int nRet = poll(&polls, 1, 1000);
// this is specific to iOS which does not send a response in case of success
if (nRet == 0) {//poll timeout, we shall not expect a response.
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " nothing read, assuming success";
onSuccess(req);
return;
}else if (nRet == -1){
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " poll error ("<<strerror(errno)<<"), assuming success";
onSuccess(req);
recreateConnection();//our socket is not going so well if we go here.
return;
}
else if (polls.revents & POLLIN){
char r[1024];
int p = BIO_read(mBio, r, sizeof(r)-1);
if (p > 0) {
r[p] = 0;
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " read " << p << " data:\n" << r;
string responsestr(r, p);
if (!req->isValidResponse(responsestr)) {
onError(req, "Invalid server response");
}else{
onSuccess(req);
}
}else{
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << "error reading response, closing connection";
recreateConnection();
}
}
}
void PushNotificationClient::run() {
std::unique_lock<std::mutex> lock(mMutex);
while (mThreadRunning) {
if (!isIdle()) {
SLOGD << "PushNotificationClient " << mName << " next, queue_size=" << mRequestQueue.size();
auto req = mRequestQueue.front();
mRequestQueue.pop();
lock.unlock();
// send push to the server and wait for its answer
sendPushToServer(req);
lock.lock();
} else {
mThreadWaiting = true;
mCondVar.wait(lock);
mThreadWaiting = false;
}
}
}
void PushNotificationClient::onError(shared_ptr<PushNotificationRequest> req, const string &msg) {
SLOGD << "PushNotificationClient " << mName << " PNR " << req.get() << " failed: " << msg;
if (mService->mCountFailed) {
mService->mCountFailed->incr();
}
recreateConnection();
}
void PushNotificationClient::onSuccess(shared_ptr<PushNotificationRequest> req) {
if (mService->mCountSent) {
mService->mCountSent->incr();
}
}
<|endoftext|> |
<commit_before>/*
Copyright 2013 Brain Research Institute, Melbourne, Australia
Written by David Raffelt, 31/01/2013
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "math/median.h"
#include "dwi/tractography/properties.h"
#include "dwi/tractography/scalar_file.h"
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "David Raffelt ([email protected])";
DESCRIPTION
+ "Gaussian filter a track scalar file";
ARGUMENTS
+ Argument ("input", "the input track scalar file.").type_file_in ()
+ Argument ("output", "the output track scalar file").type_file_out ();
OPTIONS
+ Option ("stdev", "apply Gaussian smoothing with the specified standard deviation. "
"The standard deviation is defined in units of track points (Default: 4)")
+ Argument ("sigma").type_float();
}
typedef float value_type;
void run ()
{
DWI::Tractography::Properties properties;
DWI::Tractography::ScalarReader<value_type> reader (argument[0], properties);
DWI::Tractography::ScalarWriter<value_type> writer (argument[1], properties);
Options opt = get_options("stdev");
float stdev = 4.0;
if (opt.size())
stdev = opt[0][0];
std::vector<float> kernel (2 * ceil(2.5 * stdev) + 1, 0);
float norm_factor = 0.0;
float radius = (kernel.size() - 1.0) / 2.0;
for (size_t c = 0; c < kernel.size(); ++c) {
kernel[c] = exp(-(c - radius) * (c - radius) / (2 * stdev * stdev));
norm_factor += kernel[c];
}
for (size_t c = 0; c < kernel.size(); c++)
kernel[c] /= norm_factor;
std::vector<value_type> tck_scalar;
while (reader (tck_scalar)) {
std::vector<value_type> tck_scalars_smoothed (tck_scalar.size());
for (int i = 0; i < (int)tck_scalar.size(); ++i) {
float norm_factor = 0.0;
float value = 0.0;
for (int k = -(int)radius; k <= (int)radius; ++k) {
if (i + k >= 0 && i + k < tck_scalar.size()) {
value += kernel[k + radius] * tck_scalar[i + k];
norm_factor += kernel[k + radius];
}
}
tck_scalars_smoothed[i] = value / norm_factor;
}
writer (tck_scalars_smoothed);
}
}
<commit_msg>Fix another compiler warning in tsfsmooth<commit_after>/*
Copyright 2013 Brain Research Institute, Melbourne, Australia
Written by David Raffelt, 31/01/2013
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "math/median.h"
#include "dwi/tractography/properties.h"
#include "dwi/tractography/scalar_file.h"
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "David Raffelt ([email protected])";
DESCRIPTION
+ "Gaussian filter a track scalar file";
ARGUMENTS
+ Argument ("input", "the input track scalar file.").type_file_in ()
+ Argument ("output", "the output track scalar file").type_file_out ();
OPTIONS
+ Option ("stdev", "apply Gaussian smoothing with the specified standard deviation. "
"The standard deviation is defined in units of track points (Default: 4)")
+ Argument ("sigma").type_float();
}
typedef float value_type;
void run ()
{
DWI::Tractography::Properties properties;
DWI::Tractography::ScalarReader<value_type> reader (argument[0], properties);
DWI::Tractography::ScalarWriter<value_type> writer (argument[1], properties);
Options opt = get_options("stdev");
float stdev = 4.0;
if (opt.size())
stdev = opt[0][0];
std::vector<float> kernel (2 * ceil(2.5 * stdev) + 1, 0);
float norm_factor = 0.0;
float radius = (kernel.size() - 1.0) / 2.0;
for (size_t c = 0; c < kernel.size(); ++c) {
kernel[c] = exp(-(c - radius) * (c - radius) / (2 * stdev * stdev));
norm_factor += kernel[c];
}
for (size_t c = 0; c < kernel.size(); c++)
kernel[c] /= norm_factor;
std::vector<value_type> tck_scalar;
while (reader (tck_scalar)) {
std::vector<value_type> tck_scalars_smoothed (tck_scalar.size());
for (int i = 0; i < (int)tck_scalar.size(); ++i) {
float norm_factor = 0.0;
float value = 0.0;
for (int k = -(int)radius; k <= (int)radius; ++k) {
if (i + k >= 0 && i + k < (int)tck_scalar.size()) {
value += kernel[k + radius] * tck_scalar[i + k];
norm_factor += kernel[k + radius];
}
}
tck_scalars_smoothed[i] = value / norm_factor;
}
writer (tck_scalars_smoothed);
}
}
<|endoftext|> |
<commit_before>#include <zlib.h>
#include <inttypes.h>
#include <memory>
#include "htslib/kseq.h"
#include "htslib/kstring.h"
#include "dlib/logging_util.h"
KSEQ_INIT(gzFile, gzread)
int usage(char **argv, int rc) {
fprintf(stderr, "Usage: %s -l<blen> infq1 infq2 outfq1 outfq2 outfq3\n For converting non-duplex inline barcodes for compatibility with collapse secondary\n"
"-2: Get single-sided barcode from read2.\n", *argv);
return rc;
}
void fqw(kseq_t *ks, int offset, FILE *fp) {
fprintf(fp, "@%s %s\n%s\n+\n%s\n", ks->name.s,
ks->comment.s, ks->seq.s + offset, ks->qual.s + offset);
}
void bcw(kseq_t *ks, char *s, char *q, FILE *fp) {
fprintf(fp, "@%s %s\n%s\n+\n%s\n", ks->name.s,
ks->comment.s, s, q);
}
int main(int argc, char **argv)
{
if(argc < 6) return usage(argv, EXIT_FAILURE);
int blen(-1), use_read1(1);
int c;
while((c = getopt(argc, argv, "l:h?")) > 0) {
switch(c) {
case '2': use_read1 = 0;
case 'l': blen = atoi(optarg); break;
case 'h': case '?': return usage(argv, EXIT_SUCCESS);
}
}
if(blen < 0) {
fprintf(stderr, "blen required. Abort!\n");
return usage(argv, EXIT_FAILURE);
}
gzFile in1(gzopen(argv[optind], "rb")), in2(gzopen(argv[optind + 1], "rb"));
kseq_t *ks1(kseq_init(in1)), *ks2(kseq_init(in2));
FILE *out1(fopen(argv[optind + 2], "w")), *out2(fopen(argv[optind + 3], "w")), *outindex(fopen(argv[optind + 4], "w"));
char bpos[128];
bpos[blen] = '\0';
kseq_t *bks(use_read1 ? ks1: ks2);
while(kseq_read(ks1) >= 0 && kseq_read(ks2) >= 0) {
memcpy(bpos, bks->seq.s, blen);
fprintf(outindex, "%s barcode\n%s\n+\n", ks1->name.s, bpos);
fwrite(bks->qual.s, 20, 1, outindex);
fputc('\n', outindex);
memset(bks->seq.s, 'N', blen);
memset(bks->qual.s, '#', blen);
fqw(ks1, 0, out1);
fqw(ks1, 0, out2);
}
kseq_destroy(ks1); kseq_destroy(ks2);
gzclose(in1); gzclose(in2);
fclose(out1); fclose(out2); fclose(outindex);
return 0;
}
<commit_msg>getopt string<commit_after>#include <zlib.h>
#include <inttypes.h>
#include <memory>
#include "htslib/kseq.h"
#include "htslib/kstring.h"
#include "dlib/logging_util.h"
KSEQ_INIT(gzFile, gzread)
int usage(char **argv, int rc) {
fprintf(stderr, "Usage: %s -l<blen> infq1 infq2 outfq1 outfq2 outfq3\n For converting non-duplex inline barcodes for compatibility with collapse secondary\n"
"-2: Get single-sided barcode from read2.\n", *argv);
return rc;
}
void fqw(kseq_t *ks, int offset, FILE *fp) {
fprintf(fp, "@%s %s\n%s\n+\n%s\n", ks->name.s,
ks->comment.s, ks->seq.s + offset, ks->qual.s + offset);
}
void bcw(kseq_t *ks, char *s, char *q, FILE *fp) {
fprintf(fp, "@%s %s\n%s\n+\n%s\n", ks->name.s,
ks->comment.s, s, q);
}
int main(int argc, char **argv)
{
if(argc < 6) return usage(argv, EXIT_FAILURE);
int blen(-1), use_read1(1);
int c;
while((c = getopt(argc, argv, "l:2h?")) > 0) {
switch(c) {
case '2': use_read1 = 0;
case 'l': blen = atoi(optarg); break;
case 'h': case '?': return usage(argv, EXIT_SUCCESS);
}
}
if(blen < 0) {
fprintf(stderr, "blen required. Abort!\n");
return usage(argv, EXIT_FAILURE);
}
gzFile in1(gzopen(argv[optind], "rb")), in2(gzopen(argv[optind + 1], "rb"));
kseq_t *ks1(kseq_init(in1)), *ks2(kseq_init(in2));
FILE *out1(fopen(argv[optind + 2], "w")), *out2(fopen(argv[optind + 3], "w")), *outindex(fopen(argv[optind + 4], "w"));
char bpos[128];
bpos[blen] = '\0';
kseq_t *bks(use_read1 ? ks1: ks2);
while(kseq_read(ks1) >= 0 && kseq_read(ks2) >= 0) {
memcpy(bpos, bks->seq.s, blen);
fprintf(outindex, "%s barcode\n%s\n+\n", ks1->name.s, bpos);
fwrite(bks->qual.s, 20, 1, outindex);
fputc('\n', outindex);
memset(bks->seq.s, 'N', blen);
memset(bks->qual.s, '#', blen);
fqw(ks1, 0, out1);
fqw(ks1, 0, out2);
}
kseq_destroy(ks1); kseq_destroy(ks2);
gzclose(in1); gzclose(in2);
fclose(out1); fclose(out2); fclose(outindex);
return 0;
}
<|endoftext|> |
<commit_before>/**********************************************************************************
* Copyright (C) 2011 by Hugo Stefan Kaus Puhlmann *
* 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 "PlayerShip.hpp"
#include <GL/glfw.h>
#include "../math/transform.hpp"
#include <iostream>
namespace hstefan
{
namespace game
{
using namespace math;
PlayerShip::PlayerShip(const math::vec3& pos, unsigned int screen_w, unsigned int screen_h)
: Ship(NUM_LIFES, HITPOINTS, 0.f, makeVec(0.f, 1.f, 1.f), pos, screen_w, screen_h)
{
vertex[0] = makeVec(-SHIP_WIDTH/2, SHIP_HEIGHT/2, 1);
vertex[1] = makeVec(-SHIP_WIDTH/2, -SHIP_HEIGHT/2, 1);
vertex[2] = makeVec(SHIP_WIDTH/2, -SHIP_HEIGHT/2, 1);
vertex[3] = makeVec(SHIP_WIDTH/2, SHIP_HEIGHT/2, 1);
}
void PlayerShip::update()
{
if(glfwGetKey(GLFW_KEY_UP) == GLFW_PRESS)
{
std::cout << "up pressed" << std::endl;
}
else if(glfwGetKey(GLFW_KEY_DOWN) == GLFW_PRESS)
{
std::cout << "down pressed" << std::endl;
}
else if(glfwGetKey(GLFW_KEY_LEFT) == GLFW_PRESS)
{
std::cout << "left pressed" << std::endl;
}
else if(glfwGetKey(GLFW_KEY_RIGHT) == GLFW_PRESS)
{
std::cout << "right pressed" << std::endl;
}
}
void PlayerShip::render()
{
math::mat3d trans = math::transMat2dh(pos[0], pos[1]);
vec3 buff[4];
for(unsigned int i = 0; i < 4; ++i)
{
buff[i] = trans*vertex[i];
//std::cout << buff[i][0] << "," << buff[i][1] << std::endl;
}
glColor3f(1.f, 0.f, 0.f);
glBegin(GL_QUADS);
glVertex2i(buff[0][0], buff[0][1]);
glVertex2i(buff[1][0], buff[1][1]);
glVertex2i(buff[2][0], buff[2][1]);
glVertex2i(buff[3][0], buff[3][1]);
glEnd();
}
} //namespace game
} //namesace hstefan
<commit_msg>removing some debug-only tests<commit_after>/**********************************************************************************
* Copyright (C) 2011 by Hugo Stefan Kaus Puhlmann *
* 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 "PlayerShip.hpp"
#include <GL/glfw.h>
#include "../math/transform.hpp"
#include <iostream>
namespace hstefan
{
namespace game
{
using namespace math;
PlayerShip::PlayerShip(const math::vec3& pos, unsigned int screen_w, unsigned int screen_h)
: Ship(NUM_LIFES, HITPOINTS, 0.f, makeVec(0.f, 1.f, 1.f), pos, screen_w, screen_h)
{
vertex[0] = makeVec(-SHIP_WIDTH/2, SHIP_HEIGHT/2, 1);
vertex[1] = makeVec(-SHIP_WIDTH/2, -SHIP_HEIGHT/2, 1);
vertex[2] = makeVec(SHIP_WIDTH/2, -SHIP_HEIGHT/2, 1);
vertex[3] = makeVec(SHIP_WIDTH/2, SHIP_HEIGHT/2, 1);
}
void PlayerShip::update()
{
if(glfwGetKey(GLFW_KEY_UP) == GLFW_PRESS)
{
std::cout << "up pressed" << std::endl;
}
else if(glfwGetKey(GLFW_KEY_DOWN) == GLFW_PRESS)
{
std::cout << "down pressed" << std::endl;
}
else if(glfwGetKey(GLFW_KEY_LEFT) == GLFW_PRESS)
{
std::cout << "left pressed" << std::endl;
}
else if(glfwGetKey(GLFW_KEY_RIGHT) == GLFW_PRESS)
{
std::cout << "right pressed" << std::endl;
}
}
void PlayerShip::render()
{
math::mat3d trans = math::transMat2dh(pos[0], pos[1]);
vec3 buff[4];
for(unsigned int i = 0; i < 4; ++i)
{
buff[i] = trans*vertex[i];
}
glColor3f(1.f, 0.f, 0.f);
glBegin(GL_QUADS);
glVertex2i(buff[0][0], buff[0][1]);
glVertex2i(buff[1][0], buff[1][1]);
glVertex2i(buff[2][0], buff[2][1]);
glVertex2i(buff[3][0], buff[3][1]);
glEnd();
}
} //namespace game
} //namesace hstefan
<|endoftext|> |
<commit_before>#define SPICA_TRIMESH_EXPORT
#include "trimesh.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include "../utils/common.h"
namespace spica {
Trimesh::Trimesh()
: _vertices()
, _colors()
, _faces()
, _normals()
, _accel(NULL)
, _accelType(QBVH_ACCEL)
{
}
Trimesh::Trimesh(const std::string& filename)
: _vertices()
, _colors()
, _faces()
, _normals()
, _accel(NULL)
, _accelType(QBVH_ACCEL)
{
load(filename);
}
Trimesh::Trimesh(const std::vector<Vector3>& vertices, const std::vector<Triplet>& faceIDs)
: _vertices(vertices)
, _colors()
, _faces(faceIDs)
, _normals()
, _accel(NULL)
, _accelType(QBVH_ACCEL)
{
_colors.resize(_vertices.size());
_normals.resize(_vertices.size());
for (unsigned int i = 0; i < _faces.size(); i++) {
const Vector3& v0 = _vertices[_faces[i][0]];
const Vector3& v1 = _vertices[_faces[i][1]];
const Vector3& v2 = _vertices[_faces[i][2]];
_colors[i] = Color(0.0, 0.0, 0.0);
_normals[i] = Vector3::cross(v1 - v0, v2 - v0).normalized();
}
}
Trimesh::Trimesh(const Trimesh& trimesh)
: _vertices()
, _colors()
, _faces()
, _normals()
, _accel(NULL)
, _accelType(QBVH_ACCEL)
{
this->operator=(trimesh);
}
Trimesh::Trimesh(Trimesh&& trimesh)
: _vertices()
, _colors()
, _faces()
, _normals()
, _accel(NULL)
, _accelType(QBVH_ACCEL)
{
this->operator=(std::move(trimesh));
}
Trimesh::~Trimesh()
{
}
Trimesh& Trimesh::operator=(const Trimesh& trimesh) {
_vertices = trimesh._vertices;
_colors = trimesh._colors;
_faces = trimesh._faces;
_normals = trimesh._normals;
_accel = trimesh._accel;
_accelType = trimesh._accelType;
return *this;
}
Trimesh& Trimesh::operator=(Trimesh&& trimesh) {
_vertices = std::move(trimesh._vertices);
_colors = std::move(trimesh._colors);
_faces = std::move(trimesh._faces);
_normals = std::move(trimesh._normals);
_accel = trimesh._accel;
_accelType = trimesh._accelType;
return *this;
}
bool Trimesh::intersect(const Ray& ray, Hitpoint* hitpoint) const {
msg_assert(_accel != NULL, "Accelerator is not constructed");
hitpoint->setDistance(INFTY);
return _accel->intersect(ray, hitpoint);
}
double Trimesh::area() const {
double ret = 0.0;
for (unsigned int i = 0; i < _faces.size(); i++) {
Triangle tri = this->getTriangle(i);
ret += tri.area();
}
return ret;
}
void Trimesh::setAccelType(AccelType accelType, bool doBuild) {
this->_accelType = accelType;
if (doBuild) {
buildAccel();
}
}
void Trimesh::buildAccel() {
std::vector<Triangle> triangles(_faces.size());
for (unsigned int i = 0; i < _faces.size(); i++) {
Vector3& p0 = _vertices[_faces[i][0]];
Vector3& p1 = _vertices[_faces[i][1]];
Vector3& p2 = _vertices[_faces[i][2]];
triangles[i] = Triangle(p0, p1, p2);
}
switch(_accelType) {
case KD_TREE_ACCEL:
printf("Accelerator: K-D tree\n");
_accel = std::shared_ptr<AccelBase>(new KdTreeAccel());
break;
case QBVH_ACCEL:
printf("Accelerator: QBVH\n");
_accel = std::shared_ptr<AccelBase>(new QBVHAccel());
break;
default:
msg_assert(false, "Unknown accelerator type!!");
break;
}
_accel->construct(triangles);
}
void Trimesh::load(const std::string& filename) {
int dotPos = filename.find_last_of(".");
std::string ext = filename.substr(dotPos);
if (ext == ".ply") {
this->loadPly(filename);
} else if (ext == ".obj") {
this->loadObj(filename);
} else {
msg_assert(ext == ".ply" || ext == ".obj", "Mesh loader only accepts .ply and .obj file format");
}
}
void Trimesh::loadPly(const std::string& filename) {
std::ifstream in(filename.c_str(), std::ios::in | std::ios::binary);
msg_assert(in.is_open(), "Failed to open mesh file");
std::string line, format, key, name, val;
size_t numVerts = 0;
size_t numFaces = 0;
std::getline(in, format);
msg_assert(format == "ply", "Invalid format identifier");
bool isBody = false;
while(!in.eof()) {
if (!isBody) {
std::getline(in, line);
std::stringstream ss;
ss << line;
ss >> key;
if (key == "format") {
ss >> name >> val;
msg_assert(name == "binary_little_endian", "PLY must be binary little endian format!");
} else if (key == "property") {
ss >> name >> val;
} else if (key == "element") {
ss >> name;
if (name == "vertex") {
ss >> numVerts;
} else if (name == "face") {
ss >> numFaces;
} else {
msg_assert(false, "Invalid element indentifier");
}
} else if (key == "end_header") {
isBody = true;
continue;
} else {
continue;
}
} else {
msg_assert(numVerts > 0 && numFaces > 0, "numVerts and numFaces must be positive");
_vertices.resize(numVerts);
_colors.resize(numVerts);
_faces.resize(numFaces);
_normals.resize(numFaces);
int cnt = 0;
float ff[3];
for (size_t i = 0; i < numVerts; i++) {
in.read((char*)ff, sizeof(float) * 3);
_vertices[i] = Vector3(ff[0], ff[1], ff[2]);
}
unsigned char vs;
int ii[8];
for (size_t i = 0; i < numFaces; i++) {
in.read((char*)&vs, sizeof(unsigned char));
in.read((char*)ii, sizeof(int) * vs);
_faces[i] = Triplet(ii[0], ii[1], ii[2]);
const int p0 = ii[0];
const int p1 = ii[1];
const int p2 = ii[2];
_normals[i] = Vector3::cross(_vertices[p1] - _vertices[p0], _vertices[p2] - _vertices[p0]).normalized();
}
break;
}
}
}
void Trimesh::loadObj(const std::string& filename) {
std::ifstream in(filename.c_str(), std::ios::in);
msg_assert(in.is_open(), "Failed to open mesh file");
std::string typ;
_vertices.clear();
_faces.clear();
while (!in.eof()) {
in >> typ;
if (typ == "v") {
double x, y, z;
in >> x >> y >> z;
_vertices.push_back(Vector3(x, y, z));
} else if (typ == "f") {
int v0, v1, v2;
in >> v0 >> v1 >> v2;
_faces.push_back(Triplet(v0, v1, v2));
} else {
msg_assert(false, "Unknown type is found while reading .obj file!!");
}
}
_colors.assign(_vertices.size(), Color(0.0, 0.0, 0.0));
_normals.resize(_faces.size());
for (int i = 0; i < _faces.size(); i++) {
const int p0 = _faces[i][0];
const int p1 = _faces[i][1];
const int p2 = _faces[i][2];
_normals[i] = Vector3::cross(_vertices[p1] - _vertices[p0], _vertices[p2] - _vertices[p0]);
}
}
void Trimesh::translate(const Vector3& move) {
for (unsigned int i = 0; i < _vertices.size(); i++) {
_vertices[i] += move;
}
}
void Trimesh::scale(const double scaleX, const double scaleY, const double scaleZ) {
for (unsigned int i = 0; i < _vertices.size(); i++) {
_vertices[i].x() = _vertices[i].x() * scaleX;
_vertices[i].y() = _vertices[i].y() * scaleY;
_vertices[i].z() = _vertices[i].z() * scaleZ;
}
}
void Trimesh::scale(const double scaleAll) {
scale(scaleAll, scaleAll, scaleAll);
}
void Trimesh::putOnPlane(const Plane& plane) {
// Find nearest point
double minval = INFTY;
for (size_t i = 0; i < _vertices.size(); i++) {
minval = std::min(minval, Vector3::dot(plane.normal(), _vertices[i]));
}
for (size_t i = 0; i < _vertices.size(); i++) {
_vertices[i] -= (minval + plane.distance()) * plane.normal();
}
}
void Trimesh::fitToBBox(const BBox& bbox) {
BBox orgBox;
for (size_t i = 0; i < _vertices.size(); i++) {
orgBox.merge(_vertices[i]);
}
const Vector3 targetSize = bbox.posMax() - bbox.posMin();
const Vector3 orgSize = orgBox.posMax() - orgBox.posMin();
const double scaleX = targetSize.x() / orgSize.x();
const double scaleY = targetSize.y() / orgSize.y();
const double scaleZ = targetSize.z() / orgSize.z();
const double scaleAll = std::min(scaleX, std::min(scaleY, scaleZ));
this->scale(scaleAll);
const Vector3 prevCenter = (orgBox.posMin() + orgBox.posMax()) * (0.5 * scaleAll);
const Vector3 toCenter = (bbox.posMin() + bbox.posMax()) * 0.5;
this->translate(toCenter - prevCenter);
}
std::vector<Triplet> Trimesh::getIndices() const {
std::vector<Triplet> ret(_faces.size());
std::copy(_faces.begin(), _faces.end(), ret.begin());
return std::move(ret);
}
Vector3 Trimesh::getVertex(int id) const {
msg_assert(id >= 0 && id < _vertices.size(), "Vertex index out of bounds");
return _vertices[id];
}
void Trimesh::setColor(int id, const Color& color) {
_colors[id] = color;
}
Color Trimesh::getColor(int id) const {
msg_assert(id >= 0 && id < _vertices.size(), "Vertex index out of bounds");
return _colors[id];
}
Vector3 Trimesh::getNormal(int id) const {
msg_assert(id >= 0 && id < _vertices.size(), "Triangle index out of bounds");
return _normals[id];
}
Triangle Trimesh::getTriangle(int id) const {
msg_assert(id >= 0 && id < _vertices.size(), "Triangle index out of bounds");
const Vector3& p0 = _vertices[_faces[id][0]];
const Vector3& p1 = _vertices[_faces[id][1]];
const Vector3& p2 = _vertices[_faces[id][2]];
return Triangle(p0, p1, p2);
}
} // namesapce spica
<commit_msg>Minor update<commit_after>#define SPICA_TRIMESH_EXPORT
#include "trimesh.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include "../utils/common.h"
namespace spica {
Trimesh::Trimesh()
: _vertices()
, _colors()
, _faces()
, _normals()
, _accel(NULL)
, _accelType(QBVH_ACCEL)
{
}
Trimesh::Trimesh(const std::string& filename)
: _vertices()
, _colors()
, _faces()
, _normals()
, _accel(NULL)
, _accelType(QBVH_ACCEL)
{
load(filename);
}
Trimesh::Trimesh(const std::vector<Vector3>& vertices, const std::vector<Triplet>& faceIDs)
: _vertices(vertices)
, _colors()
, _faces(faceIDs)
, _normals()
, _accel(NULL)
, _accelType(QBVH_ACCEL)
{
_colors.resize(_vertices.size());
_normals.resize(_vertices.size());
for (unsigned int i = 0; i < _faces.size(); i++) {
const Vector3& v0 = _vertices[_faces[i][0]];
const Vector3& v1 = _vertices[_faces[i][1]];
const Vector3& v2 = _vertices[_faces[i][2]];
_colors[i] = Color(0.0, 0.0, 0.0);
_normals[i] = Vector3::cross(v1 - v0, v2 - v0).normalized();
}
}
Trimesh::Trimesh(const Trimesh& trimesh)
: _vertices()
, _colors()
, _faces()
, _normals()
, _accel(NULL)
, _accelType(QBVH_ACCEL)
{
this->operator=(trimesh);
}
Trimesh::Trimesh(Trimesh&& trimesh)
: _vertices()
, _colors()
, _faces()
, _normals()
, _accel(NULL)
, _accelType(QBVH_ACCEL)
{
this->operator=(std::move(trimesh));
}
Trimesh::~Trimesh()
{
}
Trimesh& Trimesh::operator=(const Trimesh& trimesh) {
_vertices = trimesh._vertices;
_colors = trimesh._colors;
_faces = trimesh._faces;
_normals = trimesh._normals;
_accel = trimesh._accel;
_accelType = trimesh._accelType;
return *this;
}
Trimesh& Trimesh::operator=(Trimesh&& trimesh) {
_vertices = std::move(trimesh._vertices);
_colors = std::move(trimesh._colors);
_faces = std::move(trimesh._faces);
_normals = std::move(trimesh._normals);
_accel = trimesh._accel;
_accelType = trimesh._accelType;
return *this;
}
bool Trimesh::intersect(const Ray& ray, Hitpoint* hitpoint) const {
msg_assert(_accel != NULL, "Accelerator is not constructed");
hitpoint->setDistance(INFTY);
return _accel->intersect(ray, hitpoint);
}
double Trimesh::area() const {
double ret = 0.0;
for (unsigned int i = 0; i < _faces.size(); i++) {
Triangle tri = this->getTriangle(i);
ret += tri.area();
}
return ret;
}
void Trimesh::setAccelType(AccelType accelType, bool doBuild) {
this->_accelType = accelType;
if (doBuild) {
buildAccel();
}
}
void Trimesh::buildAccel() {
std::vector<Triangle> triangles(_faces.size());
for (unsigned int i = 0; i < _faces.size(); i++) {
Vector3& p0 = _vertices[_faces[i][0]];
Vector3& p1 = _vertices[_faces[i][1]];
Vector3& p2 = _vertices[_faces[i][2]];
triangles[i] = Triangle(p0, p1, p2);
}
switch(_accelType) {
case KD_TREE_ACCEL:
printf("Accelerator: K-D tree\n");
_accel = std::shared_ptr<AccelBase>(new KdTreeAccel());
break;
case QBVH_ACCEL:
printf("Accelerator: QBVH\n");
_accel = std::shared_ptr<AccelBase>(new QBVHAccel());
break;
default:
msg_assert(false, "Unknown accelerator type!!");
break;
}
_accel->construct(triangles);
}
void Trimesh::load(const std::string& filename) {
int dotPos = filename.find_last_of(".");
std::string ext = filename.substr(dotPos);
if (ext == ".ply") {
this->loadPly(filename);
} else if (ext == ".obj") {
this->loadObj(filename);
} else {
msg_assert(ext == ".ply" || ext == ".obj", "Mesh loader only accepts .ply and .obj file format");
}
}
void Trimesh::loadPly(const std::string& filename) {
std::ifstream in(filename.c_str(), std::ios::in | std::ios::binary);
msg_assert(in.is_open(), "Failed to open mesh file");
std::string line, format, key, name, val;
size_t numVerts = 0;
size_t numFaces = 0;
std::getline(in, format);
msg_assert(format == "ply", "Invalid format identifier");
bool isBody = false;
while(!in.eof()) {
if (!isBody) {
std::getline(in, line);
std::stringstream ss;
ss << line;
ss >> key;
if (key == "format") {
ss >> name >> val;
msg_assert(name == "binary_little_endian", "PLY must be binary little endian format!");
} else if (key == "property") {
ss >> name >> val;
} else if (key == "element") {
ss >> name;
if (name == "vertex") {
ss >> numVerts;
} else if (name == "face") {
ss >> numFaces;
} else {
msg_assert(false, "Invalid element indentifier");
}
} else if (key == "end_header") {
isBody = true;
continue;
} else {
continue;
}
} else {
msg_assert(numVerts > 0 && numFaces > 0, "numVerts and numFaces must be positive");
_vertices.resize(numVerts);
_colors.resize(numVerts);
_faces.resize(numFaces);
_normals.resize(numFaces);
int cnt = 0;
float ff[3];
for (size_t i = 0; i < numVerts; i++) {
in.read((char*)ff, sizeof(float) * 3);
_vertices[i] = Vector3(ff[0], ff[1], ff[2]);
}
unsigned char vs;
int ii[8];
for (size_t i = 0; i < numFaces; i++) {
in.read((char*)&vs, sizeof(unsigned char));
in.read((char*)ii, sizeof(int) * vs);
_faces[i] = Triplet(ii[0], ii[1], ii[2]);
const int p0 = ii[0];
const int p1 = ii[1];
const int p2 = ii[2];
_normals[i] = Vector3::cross(_vertices[p1] - _vertices[p0], _vertices[p2] - _vertices[p0]).normalized();
}
break;
}
}
}
void Trimesh::loadObj(const std::string& filename) {
std::ifstream in(filename.c_str(), std::ios::in);
msg_assert(in.is_open(), "Failed to open mesh file");
std::string typ;
_vertices.clear();
_faces.clear();
while (!in.eof()) {
in >> typ;
if (typ == "v") {
double x, y, z;
in >> x >> y >> z;
_vertices.push_back(Vector3(x, y, z));
} else if (typ == "f") {
int v0, v1, v2;
in >> v0 >> v1 >> v2;
_faces.push_back(Triplet(v0, v1, v2));
} else {
msg_assert(false, "Unknown type is found while reading .obj file!!");
}
}
_colors.assign(_vertices.size(), Color(0.0, 0.0, 0.0));
_normals.resize(_faces.size());
for (int i = 0; i < _faces.size(); i++) {
const int p0 = _faces[i][0];
const int p1 = _faces[i][1];
const int p2 = _faces[i][2];
_normals[i] = Vector3::cross(_vertices[p1] - _vertices[p0], _vertices[p2] - _vertices[p0]);
}
}
void Trimesh::translate(const Vector3& move) {
for (unsigned int i = 0; i < _vertices.size(); i++) {
_vertices[i] += move;
}
}
void Trimesh::scale(const double scaleX, const double scaleY, const double scaleZ) {
for (unsigned int i = 0; i < _vertices.size(); i++) {
_vertices[i].x() = _vertices[i].x() * scaleX;
_vertices[i].y() = _vertices[i].y() * scaleY;
_vertices[i].z() = _vertices[i].z() * scaleZ;
}
}
void Trimesh::scale(const double scaleAll) {
scale(scaleAll, scaleAll, scaleAll);
}
void Trimesh::putOnPlane(const Plane& plane) {
// Find nearest point
double minval = INFTY;
for (size_t i = 0; i < _vertices.size(); i++) {
minval = std::min(minval, Vector3::dot(plane.normal(), _vertices[i]));
}
for (size_t i = 0; i < _vertices.size(); i++) {
_vertices[i] -= (minval + plane.distance()) * plane.normal();
}
}
void Trimesh::fitToBBox(const BBox& bbox) {
BBox orgBox;
for (size_t i = 0; i < _vertices.size(); i++) {
orgBox.merge(_vertices[i]);
}
const Vector3 targetSize = bbox.posMax() - bbox.posMin();
const Vector3 orgSize = orgBox.posMax() - orgBox.posMin();
const double scaleX = targetSize.x() / orgSize.x();
const double scaleY = targetSize.y() / orgSize.y();
const double scaleZ = targetSize.z() / orgSize.z();
const double scaleAll = std::min(scaleX, std::min(scaleY, scaleZ));
this->scale(scaleAll);
const Vector3 prevCenter = (orgBox.posMin() + orgBox.posMax()) * (0.5 * scaleAll);
const Vector3 toCenter = (bbox.posMin() + bbox.posMax()) * 0.5;
this->translate(toCenter - prevCenter);
}
std::vector<Triplet> Trimesh::getIndices() const {
std::vector<Triplet> ret(_faces.size());
std::copy(_faces.begin(), _faces.end(), ret.begin());
return std::move(ret);
}
Vector3 Trimesh::getVertex(int id) const {
msg_assert(id >= 0 && id < _vertices.size(), "Vertex index out of bounds");
return _vertices[id];
}
void Trimesh::setColor(int id, const Color& color) {
_colors[id] = color;
}
Color Trimesh::getColor(int id) const {
msg_assert(id >= 0 && id < _vertices.size(), "Vertex index out of bounds");
return _colors[id];
}
Vector3 Trimesh::getNormal(int id) const {
msg_assert(id >= 0 && id < _vertices.size(), "Triangle index out of bounds");
return _normals[id];
}
Triangle Trimesh::getTriangle(int id) const {
msg_assert(id >= 0 && id < _faces.size(), "Triangle index out of bounds");
const Vector3& p0 = _vertices[_faces[id][0]];
const Vector3& p1 = _vertices[_faces[id][1]];
const Vector3& p2 = _vertices[_faces[id][2]];
return Triangle(p0, p1, p2);
}
} // namesapce spica
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "statistics.h"
#include "database.h"
extern FILE *obj_f;
extern FILE *mob_f;
vector<mobIndexData>mob_index(0);
vector<objIndexData>obj_index(0);
indexData::indexData() :
virt(0),
pos(0),
number(0),
name(NULL),
short_desc(NULL),
long_desc(NULL),
description(NULL),
max_exist(-99),
spec(0),
weight(0)
{
}
indexData & indexData::operator= (const indexData &a)
{
if (this == &a)
return *this;
virt = a.virt;
pos = a.pos;
number = a.number;
delete [] name;
delete [] short_desc;
delete [] long_desc;
delete [] description;
name = mud_str_dup(a.name);
short_desc = mud_str_dup(a.short_desc);
long_desc = mud_str_dup(a.long_desc);
description = mud_str_dup(a.description);
max_exist = a.max_exist;
spec = a.spec;
weight = a.weight;
return *this;
}
indexData::indexData(const indexData &a) :
virt(a.virt),
pos(a.pos),
number(a.number),
max_exist(a.max_exist),
spec(a.spec),
weight(a.weight)
{
name = mud_str_dup(a.name);
short_desc = mud_str_dup(a.short_desc);
long_desc = mud_str_dup(a.long_desc);
description = mud_str_dup(a.description);
}
indexData::~indexData()
{
delete [] name;
delete [] short_desc;
delete [] long_desc;
delete [] description;
}
mobIndexData::mobIndexData() :
faction(-99),
Class(-99),
level(-99),
race(-99),
doesLoad(false),
numberLoad(0)
{
}
mobIndexData & mobIndexData::operator= (const mobIndexData &a)
{
if (this == &a)
return *this;
indexData::operator=(a);
faction = a.faction;
Class = a.Class;
level = a.level;
race = a.race;
doesLoad = a.doesLoad;
numberLoad = a.numberLoad;
return *this;
}
mobIndexData::mobIndexData(const mobIndexData &a) :
indexData(a),
faction(a.faction),
Class(a.Class),
level(a.level),
race(a.race),
doesLoad(a.doesLoad),
numberLoad(a.numberLoad)
{
}
mobIndexData::~mobIndexData()
{
}
objIndexData::objIndexData() :
ex_description(NULL),
max_struct(-99),
armor(-99),
where_worn(0),
itemtype(MAX_OBJ_TYPES),
value(-99)
{
}
objIndexData & objIndexData::operator= (const objIndexData &a)
{
if (this == &a)
return *this;
indexData::operator=(a);
// use copy operator;
if (a.ex_description)
ex_description = new extraDescription(*a.ex_description);
else
ex_description = NULL;
max_struct = a.max_struct;
armor = a.armor;
where_worn = a.where_worn;
itemtype = a.itemtype;
value = a.value;
int i;
for(i=0;i<MAX_OBJ_AFFECT;++i){
affected[i]=a.affected[i];
}
return *this;
}
objIndexData::objIndexData(const objIndexData &a) :
indexData(a),
max_struct(a.max_struct),
armor(a.armor),
where_worn(a.where_worn),
itemtype(a.itemtype),
value(a.value)
{
// use copy operator;
if (a.ex_description)
ex_description = new extraDescription(*a.ex_description);
else
ex_description = NULL;
int i;
for(i=0;i<MAX_OBJ_AFFECT;++i){
affected[i]=a.affected[i];
}
}
objIndexData::~objIndexData()
{
extraDescription *tmp;
while ((tmp = ex_description)) {
ex_description = tmp->next;
delete tmp;
}
}
// generate index table for object
void generate_obj_index()
{
objIndexData *tmpi = NULL;
extraDescription *new_descr;
int i=0;
// to prevent constant resizing (slows boot), declare an appropriate initial
// size. Should be smallest power of 2 that will hold everything
obj_index.reserve(8192);
/****** extra ******/
TDatabase extra_db(DB_SNEEZY);
extra_db.query("select vnum, name, description from objextra order by vnum");
extra_db.fetchRow();
/****** affect ******/
TDatabase affect_db(DB_SNEEZY);
affect_db.query("select vnum, type, mod1, mod2 from objaffect order by vnum");
affect_db.fetchRow();
/********************/
TDatabase db(DB_SNEEZY);
db.query("select vnum, name, short_desc, long_desc, max_exist, spec_proc, weight, max_struct, wear_flag, type, price, action_desc from obj order by vnum");
while(db.fetchRow()){
tmpi = new objIndexData();
if (!tmpi) {
perror("indexData");
exit(0);
}
tmpi->virt=convertTo<int>(db["vnum"]);
tmpi->name=mud_str_dup(db["name"]);
tmpi->short_desc=mud_str_dup(db["short_desc"]);
tmpi->long_desc=mud_str_dup(db["long_desc"]);
tmpi->max_exist=convertTo<int>(db["max_exist"]);
// use 327 so we don't go over 32765 in calculation
if (tmpi->max_exist < 327) {
tmpi->max_exist *= (sh_int) (stats.max_exist * 100);
tmpi->max_exist /= 100;
}
if (tmpi->max_exist)
tmpi->max_exist = max(tmpi->max_exist, (short int) (gamePort == BETA_GAMEPORT ? 9999 : 1));
tmpi->spec=convertTo<int>(db["spec_proc"]);
tmpi->weight=convertTo<float>(db["weight"]);
tmpi->max_struct=convertTo<int>(db["max_struct"]);
tmpi->where_worn=convertTo<int>(db["wear_flag"]);
tmpi->itemtype=convertTo<int>(db["type"]);
tmpi->value=convertTo<int>(db["price"]);
if(!db["action_desc"].empty())
tmpi->description=mud_str_dup(db["action_desc"]);
else tmpi->description=NULL;
while(!extra_db["vnum"].empty() && convertTo<int>(extra_db["vnum"]) < tmpi->virt){
extra_db.fetchRow();
}
while(!extra_db["vnum"].empty() &&
convertTo<int>(extra_db["vnum"])==tmpi->virt){
new_descr = new extraDescription();
new_descr->keyword = mud_str_dup(extra_db["name"]);
new_descr->description = mud_str_dup(extra_db["description"]);
new_descr->next = tmpi->ex_description;
tmpi->ex_description = new_descr;
extra_db.fetchRow();
}
while(!affect_db["vnum"].empty() &&
convertTo<int>(affect_db["vnum"]) < tmpi->virt){
affect_db.fetchRow();
}
i=0;
while(!affect_db["vnum"].empty() &&
convertTo<int>(affect_db["vnum"])==tmpi->virt){
tmpi->affected[i].location = mapFileToApply(convertTo<int>(affect_db["type"]));
if (tmpi->affected[i].location == APPLY_SPELL)
tmpi->affected[i].modifier = mapFileToSpellnum(convertTo<int>(affect_db["mod1"]));
else
tmpi->affected[i].modifier = convertTo<int>(affect_db["mod1"]);
tmpi->affected[i].modifier2 = convertTo<int>(affect_db["mod2"]);
tmpi->affected[i].type = TYPE_UNDEFINED;
tmpi->affected[i].level = 0;
tmpi->affected[i].bitvector = 0;
affect_db.fetchRow();
i++;
}
obj_index.push_back(*tmpi);
delete tmpi;
}
return;
}
// generate index table for monster file
void generate_mob_index()
{
char buf[256];
mobIndexData *tmpi = NULL;
// to prevent constant resizing (slows boot), declare an appropriate initial
// size. Should be smallest power of 2 that will hold everything
mob_index.reserve(4096);
rewind(mob_f);
// start by reading
if (fgets(buf, sizeof(buf)-1, mob_f) == NULL)
return;
for (;;) {
int bc;
if (*buf == '#') {
if (tmpi) {
// push the previous one into the stack
mob_index.push_back(*tmpi);
delete tmpi;
}
sscanf(buf, "#%d", &bc);
if (bc >= 99999) // terminator
break;
// start a new data member
tmpi = new mobIndexData();
if (!tmpi) {
perror("mobIndexData");
exit(0);
}
tmpi->virt = bc;
tmpi->pos = ftell(mob_f);
// read the sstrings
tmpi->name = fread_string(mob_f);
tmpi->short_desc = fread_string(mob_f);
tmpi->long_desc = fread_string(mob_f);
tmpi->description = fread_string(mob_f);
int rc;
long spac;
long spaf;
long fac;
float facp;
char let;
float mult;
rc = fscanf(mob_f, "%ld %ld %ld %f %c %f\n",
&spac, &spaf, &fac, &facp, &let, &mult);
if (rc != 6) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(1) %d") % bc);
exit(0);
}
tmpi->faction = fac;
long Class;
long lev;
long hitr;
float arm;
float hp;
float daml;
int damp;
rc = fscanf(mob_f, "%ld %ld %ld %f %f %f+%d \n",
&Class, &lev, &hitr, &arm, &hp, &daml, &damp);
if (rc != 7) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(2) %d (rc=%d)") % bc % rc);
exit(0);
}
lev = (long)((arm + hp + daml) / 3);
tmpi->Class = Class;
tmpi->level = lev;
long mon;
long race;
long wgt;
long hgt;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mon, &race, &wgt, &hgt);
if (rc != 4) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(3) %d") % bc);
exit(0);
}
tmpi->race = race;
tmpi->weight = wgt;
long some_stat;
statTypeT local_stat;
for (local_stat = MIN_STAT; local_stat < MAX_STATS_USED; local_stat++)
fscanf(mob_f, " %ld ", &some_stat);
long mpos;
long dpos;
long sex;
long spec;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mpos, &dpos, &sex, &spec);
if (rc != 4) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(4) %d") % bc);
exit(0);
}
tmpi->spec = spec;
long some_imm;
immuneTypeT local_imm;
for (local_imm = MIN_IMMUNE; local_imm < MAX_IMMUNES; local_imm++)
fscanf(mob_f, " %ld ", &some_imm);
long mat;
long cbs;
long vis;
long maxe;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mat, &cbs, &vis, &maxe);
if (rc != 4) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(5) %d") % bc);
exit(0);
}
tmpi->max_exist = (gamePort == BETA_GAMEPORT ? 9999 : maxe);
// check for sounds and just account for them if found
if (let == 'L') {
char * snds = fread_string(mob_f);
char * dsts = fread_string(mob_f);
delete [] snds;
delete [] dsts;
}
// handle some stat counters
if (lev <= 5) {
stats.mobs_1_5++;
} else if (lev <= 10) {
stats.mobs_6_10++;
} else if (lev <= 15) {
stats.mobs_11_15++;
} else if (lev <= 20) {
stats.mobs_16_20++;
} else if (lev <= 25) {
stats.mobs_21_25++;
} else if (lev <= 30) {
stats.mobs_26_30++;
} else if (lev <= 40) {
stats.mobs_31_40++;
} else if (lev <= 50) {
stats.mobs_41_50++;
} else if (lev <= 60) {
stats.mobs_51_60++;
} else if (lev <= 70) {
stats.mobs_61_70++;
} else if (lev <= 100) {
stats.mobs_71_100++;
} else {
stats.mobs_101_127++;
}
// end stat counters
}
// setup for next critter
if (fgets(buf, sizeof(buf)-1, mob_f) == NULL) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(6) %d") % bc);
exit(0);
}
}
return;
}
<commit_msg>expanded mob index reserve to 8192... we now have more than 4096 mobs.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "statistics.h"
#include "database.h"
extern FILE *obj_f;
extern FILE *mob_f;
vector<mobIndexData>mob_index(0);
vector<objIndexData>obj_index(0);
indexData::indexData() :
virt(0),
pos(0),
number(0),
name(NULL),
short_desc(NULL),
long_desc(NULL),
description(NULL),
max_exist(-99),
spec(0),
weight(0)
{
}
indexData & indexData::operator= (const indexData &a)
{
if (this == &a)
return *this;
virt = a.virt;
pos = a.pos;
number = a.number;
delete [] name;
delete [] short_desc;
delete [] long_desc;
delete [] description;
name = mud_str_dup(a.name);
short_desc = mud_str_dup(a.short_desc);
long_desc = mud_str_dup(a.long_desc);
description = mud_str_dup(a.description);
max_exist = a.max_exist;
spec = a.spec;
weight = a.weight;
return *this;
}
indexData::indexData(const indexData &a) :
virt(a.virt),
pos(a.pos),
number(a.number),
max_exist(a.max_exist),
spec(a.spec),
weight(a.weight)
{
name = mud_str_dup(a.name);
short_desc = mud_str_dup(a.short_desc);
long_desc = mud_str_dup(a.long_desc);
description = mud_str_dup(a.description);
}
indexData::~indexData()
{
delete [] name;
delete [] short_desc;
delete [] long_desc;
delete [] description;
}
mobIndexData::mobIndexData() :
faction(-99),
Class(-99),
level(-99),
race(-99),
doesLoad(false),
numberLoad(0)
{
}
mobIndexData & mobIndexData::operator= (const mobIndexData &a)
{
if (this == &a)
return *this;
indexData::operator=(a);
faction = a.faction;
Class = a.Class;
level = a.level;
race = a.race;
doesLoad = a.doesLoad;
numberLoad = a.numberLoad;
return *this;
}
mobIndexData::mobIndexData(const mobIndexData &a) :
indexData(a),
faction(a.faction),
Class(a.Class),
level(a.level),
race(a.race),
doesLoad(a.doesLoad),
numberLoad(a.numberLoad)
{
}
mobIndexData::~mobIndexData()
{
}
objIndexData::objIndexData() :
ex_description(NULL),
max_struct(-99),
armor(-99),
where_worn(0),
itemtype(MAX_OBJ_TYPES),
value(-99)
{
}
objIndexData & objIndexData::operator= (const objIndexData &a)
{
if (this == &a)
return *this;
indexData::operator=(a);
// use copy operator;
if (a.ex_description)
ex_description = new extraDescription(*a.ex_description);
else
ex_description = NULL;
max_struct = a.max_struct;
armor = a.armor;
where_worn = a.where_worn;
itemtype = a.itemtype;
value = a.value;
int i;
for(i=0;i<MAX_OBJ_AFFECT;++i){
affected[i]=a.affected[i];
}
return *this;
}
objIndexData::objIndexData(const objIndexData &a) :
indexData(a),
max_struct(a.max_struct),
armor(a.armor),
where_worn(a.where_worn),
itemtype(a.itemtype),
value(a.value)
{
// use copy operator;
if (a.ex_description)
ex_description = new extraDescription(*a.ex_description);
else
ex_description = NULL;
int i;
for(i=0;i<MAX_OBJ_AFFECT;++i){
affected[i]=a.affected[i];
}
}
objIndexData::~objIndexData()
{
extraDescription *tmp;
while ((tmp = ex_description)) {
ex_description = tmp->next;
delete tmp;
}
}
// generate index table for object
void generate_obj_index()
{
objIndexData *tmpi = NULL;
extraDescription *new_descr;
int i=0;
// to prevent constant resizing (slows boot), declare an appropriate initial
// size. Should be smallest power of 2 that will hold everything
obj_index.reserve(8192);
/****** extra ******/
TDatabase extra_db(DB_SNEEZY);
extra_db.query("select vnum, name, description from objextra order by vnum");
extra_db.fetchRow();
/****** affect ******/
TDatabase affect_db(DB_SNEEZY);
affect_db.query("select vnum, type, mod1, mod2 from objaffect order by vnum");
affect_db.fetchRow();
/********************/
TDatabase db(DB_SNEEZY);
db.query("select vnum, name, short_desc, long_desc, max_exist, spec_proc, weight, max_struct, wear_flag, type, price, action_desc from obj order by vnum");
while(db.fetchRow()){
tmpi = new objIndexData();
if (!tmpi) {
perror("indexData");
exit(0);
}
tmpi->virt=convertTo<int>(db["vnum"]);
tmpi->name=mud_str_dup(db["name"]);
tmpi->short_desc=mud_str_dup(db["short_desc"]);
tmpi->long_desc=mud_str_dup(db["long_desc"]);
tmpi->max_exist=convertTo<int>(db["max_exist"]);
// use 327 so we don't go over 32765 in calculation
if (tmpi->max_exist < 327) {
tmpi->max_exist *= (sh_int) (stats.max_exist * 100);
tmpi->max_exist /= 100;
}
if (tmpi->max_exist)
tmpi->max_exist = max(tmpi->max_exist, (short int) (gamePort == BETA_GAMEPORT ? 9999 : 1));
tmpi->spec=convertTo<int>(db["spec_proc"]);
tmpi->weight=convertTo<float>(db["weight"]);
tmpi->max_struct=convertTo<int>(db["max_struct"]);
tmpi->where_worn=convertTo<int>(db["wear_flag"]);
tmpi->itemtype=convertTo<int>(db["type"]);
tmpi->value=convertTo<int>(db["price"]);
if(!db["action_desc"].empty())
tmpi->description=mud_str_dup(db["action_desc"]);
else tmpi->description=NULL;
while(!extra_db["vnum"].empty() && convertTo<int>(extra_db["vnum"]) < tmpi->virt){
extra_db.fetchRow();
}
while(!extra_db["vnum"].empty() &&
convertTo<int>(extra_db["vnum"])==tmpi->virt){
new_descr = new extraDescription();
new_descr->keyword = mud_str_dup(extra_db["name"]);
new_descr->description = mud_str_dup(extra_db["description"]);
new_descr->next = tmpi->ex_description;
tmpi->ex_description = new_descr;
extra_db.fetchRow();
}
while(!affect_db["vnum"].empty() &&
convertTo<int>(affect_db["vnum"]) < tmpi->virt){
affect_db.fetchRow();
}
i=0;
while(!affect_db["vnum"].empty() &&
convertTo<int>(affect_db["vnum"])==tmpi->virt){
tmpi->affected[i].location = mapFileToApply(convertTo<int>(affect_db["type"]));
if (tmpi->affected[i].location == APPLY_SPELL)
tmpi->affected[i].modifier = mapFileToSpellnum(convertTo<int>(affect_db["mod1"]));
else
tmpi->affected[i].modifier = convertTo<int>(affect_db["mod1"]);
tmpi->affected[i].modifier2 = convertTo<int>(affect_db["mod2"]);
tmpi->affected[i].type = TYPE_UNDEFINED;
tmpi->affected[i].level = 0;
tmpi->affected[i].bitvector = 0;
affect_db.fetchRow();
i++;
}
obj_index.push_back(*tmpi);
delete tmpi;
}
return;
}
// generate index table for monster file
void generate_mob_index()
{
char buf[256];
mobIndexData *tmpi = NULL;
// to prevent constant resizing (slows boot), declare an appropriate initial
// size. Should be smallest power of 2 that will hold everything
mob_index.reserve(8192);
rewind(mob_f);
// start by reading
if (fgets(buf, sizeof(buf)-1, mob_f) == NULL)
return;
for (;;) {
int bc;
if (*buf == '#') {
if (tmpi) {
// push the previous one into the stack
mob_index.push_back(*tmpi);
delete tmpi;
}
sscanf(buf, "#%d", &bc);
if (bc >= 99999) // terminator
break;
// start a new data member
tmpi = new mobIndexData();
if (!tmpi) {
perror("mobIndexData");
exit(0);
}
tmpi->virt = bc;
tmpi->pos = ftell(mob_f);
// read the sstrings
tmpi->name = fread_string(mob_f);
tmpi->short_desc = fread_string(mob_f);
tmpi->long_desc = fread_string(mob_f);
tmpi->description = fread_string(mob_f);
int rc;
long spac;
long spaf;
long fac;
float facp;
char let;
float mult;
rc = fscanf(mob_f, "%ld %ld %ld %f %c %f\n",
&spac, &spaf, &fac, &facp, &let, &mult);
if (rc != 6) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(1) %d") % bc);
exit(0);
}
tmpi->faction = fac;
long Class;
long lev;
long hitr;
float arm;
float hp;
float daml;
int damp;
rc = fscanf(mob_f, "%ld %ld %ld %f %f %f+%d \n",
&Class, &lev, &hitr, &arm, &hp, &daml, &damp);
if (rc != 7) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(2) %d (rc=%d)") % bc % rc);
exit(0);
}
lev = (long)((arm + hp + daml) / 3);
tmpi->Class = Class;
tmpi->level = lev;
long mon;
long race;
long wgt;
long hgt;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mon, &race, &wgt, &hgt);
if (rc != 4) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(3) %d") % bc);
exit(0);
}
tmpi->race = race;
tmpi->weight = wgt;
long some_stat;
statTypeT local_stat;
for (local_stat = MIN_STAT; local_stat < MAX_STATS_USED; local_stat++)
fscanf(mob_f, " %ld ", &some_stat);
long mpos;
long dpos;
long sex;
long spec;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mpos, &dpos, &sex, &spec);
if (rc != 4) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(4) %d") % bc);
exit(0);
}
tmpi->spec = spec;
long some_imm;
immuneTypeT local_imm;
for (local_imm = MIN_IMMUNE; local_imm < MAX_IMMUNES; local_imm++)
fscanf(mob_f, " %ld ", &some_imm);
long mat;
long cbs;
long vis;
long maxe;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mat, &cbs, &vis, &maxe);
if (rc != 4) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(5) %d") % bc);
exit(0);
}
tmpi->max_exist = (gamePort == BETA_GAMEPORT ? 9999 : maxe);
// check for sounds and just account for them if found
if (let == 'L') {
char * snds = fread_string(mob_f);
char * dsts = fread_string(mob_f);
delete [] snds;
delete [] dsts;
}
// handle some stat counters
if (lev <= 5) {
stats.mobs_1_5++;
} else if (lev <= 10) {
stats.mobs_6_10++;
} else if (lev <= 15) {
stats.mobs_11_15++;
} else if (lev <= 20) {
stats.mobs_16_20++;
} else if (lev <= 25) {
stats.mobs_21_25++;
} else if (lev <= 30) {
stats.mobs_26_30++;
} else if (lev <= 40) {
stats.mobs_31_40++;
} else if (lev <= 50) {
stats.mobs_41_50++;
} else if (lev <= 60) {
stats.mobs_51_60++;
} else if (lev <= 70) {
stats.mobs_61_70++;
} else if (lev <= 100) {
stats.mobs_71_100++;
} else {
stats.mobs_101_127++;
}
// end stat counters
}
// setup for next critter
if (fgets(buf, sizeof(buf)-1, mob_f) == NULL) {
vlogf(LOG_BUG, fmt("Error during mobIndexSetup(6) %d") % bc);
exit(0);
}
}
return;
}
<|endoftext|> |
<commit_before>// Copyright 2014 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
#include "base/file_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/time/clock.h"
#include "media/base/demuxer.h"
#include "media/base/fixed_encryptor_source.h"
#include "media/base/media_stream.h"
#include "media/base/muxer.h"
#include "media/base/status_test_util.h"
#include "media/base/stream_info.h"
#include "media/mp4/mp4_muxer.h"
#include "media/test/test_data_util.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::ValuesIn;
namespace media {
namespace {
const char* kMediaFiles[] = {"bear-1280x720.mp4", "bear-1280x720-av_frag.mp4"};
// Muxer options.
const double kSegmentDurationInSeconds = 1.0;
const double kFragmentDurationInSecodns = 0.1;
const bool kSegmentSapAligned = true;
const bool kFragmentSapAligned = true;
const int kNumSubsegmentsPerSidx = 2;
const char kOutputVideo[] = "output_video";
const char kOutputVideo2[] = "output_video_2";
const char kOutputAudio[] = "output_audio";
const char kOutputAudio2[] = "output_audio_2";
const char kOutputNone[] = "";
const char kSegmentTemplate[] = "template$Number$.m4s";
const char kSegmentTemplateOutputPattern[] = "template%d.m4s";
const bool kSingleSegment = true;
const bool kMultipleSegments = false;
const bool kEnableEncryption = true;
const bool kDisableEncryption = false;
// Encryption constants.
const char kKeyIdHex[] = "e5007e6e9dcd5ac095202ed3758382cd";
const char kKeyHex[] = "6fc96fe628a265b13aeddec0bc421f4d";
const char kPsshHex[] =
"08011210e5007e6e9dcd5ac095202ed3"
"758382cd1a0d7769646576696e655f746573742211544553545f"
"434f4e54454e545f49445f312a025344";
const double kClearLeadInSeconds = 1.5;
MediaStream* FindFirstStreamOfType(const std::vector<MediaStream*>& streams,
StreamType stream_type) {
typedef std::vector<MediaStream*>::const_iterator StreamIterator;
for (StreamIterator it = streams.begin(); it != streams.end(); ++it) {
if ((*it)->info()->stream_type() == stream_type)
return *it;
}
return NULL;
}
MediaStream* FindFirstVideoStream(const std::vector<MediaStream*>& streams) {
return FindFirstStreamOfType(streams, kStreamVideo);
}
MediaStream* FindFirstAudioStream(const std::vector<MediaStream*>& streams) {
return FindFirstStreamOfType(streams, kStreamAudio);
}
} // namespace
class FakeClock : public base::Clock {
public:
// Fake the clock to return NULL time.
virtual base::Time Now() OVERRIDE { return base::Time(); }
};
class PackagerTestBasic : public ::testing::TestWithParam<const char*> {
public:
PackagerTestBasic() : decryptor_source_(NULL) {}
virtual void SetUp() OVERRIDE {
// Create a test directory for testing, will be deleted after test.
ASSERT_TRUE(base::CreateNewTempDirectory("packager_", &test_directory_));
// Copy the input to test directory for easy reference.
ASSERT_TRUE(base::CopyFile(GetTestDataFilePath(GetParam()),
test_directory_.AppendASCII(GetParam())));
}
virtual void TearDown() OVERRIDE { base::DeleteFile(test_directory_, true); }
std::string GetFullPath(const std::string& file_name);
// Check if |file1| and |file2| are the same.
bool ContentsEqual(const std::string& file1, const std::string file2);
MuxerOptions SetupOptions(const std::string& output, bool single_segment);
void Remux(const std::string& input,
const std::string& video_output,
const std::string& audio_output,
bool single_segment,
bool enable_encryption);
protected:
base::FilePath test_directory_;
DecryptorSource* decryptor_source_;
FakeClock fake_clock_;
};
std::string PackagerTestBasic::GetFullPath(const std::string& file_name) {
return test_directory_.AppendASCII(file_name).value();
}
bool PackagerTestBasic::ContentsEqual(const std::string& file1,
const std::string file2) {
return base::ContentsEqual(test_directory_.AppendASCII(file1),
test_directory_.AppendASCII(file2));
}
MuxerOptions PackagerTestBasic::SetupOptions(const std::string& output,
bool single_segment) {
MuxerOptions options;
options.single_segment = single_segment;
options.segment_duration = kSegmentDurationInSeconds;
options.fragment_duration = kFragmentDurationInSecodns;
options.segment_sap_aligned = kSegmentSapAligned;
options.fragment_sap_aligned = kFragmentSapAligned;
options.num_subsegments_per_sidx = kNumSubsegmentsPerSidx;
options.output_file_name = GetFullPath(output);
options.segment_template = GetFullPath(kSegmentTemplate);
options.temp_file_name = GetFullPath(output + ".temp");
return options;
}
void PackagerTestBasic::Remux(const std::string& input,
const std::string& video_output,
const std::string& audio_output,
bool single_segment,
bool enable_encryption) {
CHECK(!video_output.empty() || !audio_output.empty());
Demuxer demuxer(GetFullPath(input), decryptor_source_);
ASSERT_OK(demuxer.Initialize());
FixedEncryptorSource encryptor_source(kKeyIdHex, kKeyHex, kPsshHex);
ASSERT_OK(encryptor_source.Initialize());
scoped_ptr<Muxer> muxer_video;
if (!video_output.empty()) {
muxer_video.reset(
new mp4::MP4Muxer(SetupOptions(video_output, single_segment)));
muxer_video->set_clock(&fake_clock_);
ASSERT_OK(muxer_video->AddStream(FindFirstVideoStream(demuxer.streams())));
if (enable_encryption)
muxer_video->SetEncryptorSource(&encryptor_source, kClearLeadInSeconds);
ASSERT_OK(muxer_video->Initialize());
}
scoped_ptr<Muxer> muxer_audio;
if (!audio_output.empty()) {
muxer_audio.reset(
new mp4::MP4Muxer(SetupOptions(audio_output, single_segment)));
muxer_audio->set_clock(&fake_clock_);
ASSERT_OK(muxer_audio->AddStream(FindFirstAudioStream(demuxer.streams())));
if (enable_encryption)
muxer_video->SetEncryptorSource(&encryptor_source, kClearLeadInSeconds);
ASSERT_OK(muxer_audio->Initialize());
}
// Start remuxing process.
ASSERT_OK(demuxer.Run());
if (muxer_video)
ASSERT_OK(muxer_video->Finalize());
if (muxer_audio)
ASSERT_OK(muxer_audio->Finalize());
}
TEST_P(PackagerTestBasic, MP4MuxerSingleSegmentUnencrypted) {
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputVideo,
kOutputNone,
kSingleSegment,
kDisableEncryption));
}
TEST_P(PackagerTestBasic, MP4MuxerSingleSegmentEncrypted) {
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputVideo,
kOutputNone,
kSingleSegment,
kEnableEncryption));
// Expect the output to be encrypted.
Demuxer demuxer(GetFullPath(kOutputVideo), decryptor_source_);
ASSERT_OK(demuxer.Initialize());
ASSERT_EQ(1, demuxer.streams().size());
EXPECT_TRUE(demuxer.streams()[0]->info()->is_encrypted());
}
class PackagerTest : public PackagerTestBasic {
public:
virtual void SetUp() OVERRIDE {
PackagerTestBasic::SetUp();
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputVideo,
kOutputNone,
kSingleSegment,
kDisableEncryption));
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputNone,
kOutputAudio,
kSingleSegment,
kDisableEncryption));
}
};
TEST_P(PackagerTest, MP4MuxerSingleSegmentUnencryptedAgain) {
// Take the muxer output and feed into muxer again. The new muxer output
// should contain the same contents as the previous muxer output.
ASSERT_NO_FATAL_FAILURE(Remux(kOutputVideo,
kOutputVideo2,
kOutputNone,
kSingleSegment,
kDisableEncryption));
EXPECT_TRUE(ContentsEqual(kOutputVideo, kOutputVideo2));
}
TEST_P(PackagerTest, MP4MuxerSingleSegmentUnencryptedSeparateAudioVideo) {
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputVideo2,
kOutputAudio2,
kSingleSegment,
kDisableEncryption));
// Compare the output with single muxer output. They should match.
EXPECT_TRUE(ContentsEqual(kOutputVideo, kOutputVideo2));
EXPECT_TRUE(ContentsEqual(kOutputAudio, kOutputAudio2));
}
TEST_P(PackagerTest, MP4MuxerMultipleSegmentsUnencrypted) {
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputVideo2,
kOutputNone,
kMultipleSegments,
kDisableEncryption));
// Find and concatenates the segments.
const std::string kOutputVideoSegmentsCombined =
std::string(kOutputVideo) + "_combined";
base::FilePath output_path =
test_directory_.AppendASCII(kOutputVideoSegmentsCombined);
ASSERT_TRUE(
base::CopyFile(test_directory_.AppendASCII(kOutputVideo2), output_path));
const int kStartSegmentIndex = 1; // start from one.
int segment_index = kStartSegmentIndex;
while (true) {
base::FilePath segment_path = test_directory_.AppendASCII(
base::StringPrintf(kSegmentTemplateOutputPattern, segment_index));
if (!base::PathExists(segment_path))
break;
std::string segment_content;
ASSERT_TRUE(file_util::ReadFileToString(segment_path, &segment_content));
int bytes_written = file_util::AppendToFile(
output_path, segment_content.data(), segment_content.size());
ASSERT_EQ(segment_content.size(), bytes_written);
++segment_index;
}
// We should have at least one segment.
ASSERT_LT(kStartSegmentIndex, segment_index);
// Feed the combined file into muxer again. The new muxer output should be
// the same as by just feeding the input to muxer.
ASSERT_NO_FATAL_FAILURE(Remux(kOutputVideoSegmentsCombined,
kOutputVideo2,
kOutputNone,
kSingleSegment,
kDisableEncryption));
EXPECT_TRUE(ContentsEqual(kOutputVideo, kOutputVideo2));
}
INSTANTIATE_TEST_CASE_P(PackagerEndToEnd,
PackagerTestBasic,
ValuesIn(kMediaFiles));
INSTANTIATE_TEST_CASE_P(PackagerEndToEnd, PackagerTest, ValuesIn(kMediaFiles));
} // namespace media
<commit_msg>Fix a compilation error due to base update<commit_after>// Copyright 2014 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
#include "base/file_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/time/clock.h"
#include "media/base/demuxer.h"
#include "media/base/fixed_encryptor_source.h"
#include "media/base/media_stream.h"
#include "media/base/muxer.h"
#include "media/base/status_test_util.h"
#include "media/base/stream_info.h"
#include "media/mp4/mp4_muxer.h"
#include "media/test/test_data_util.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::ValuesIn;
namespace media {
namespace {
const char* kMediaFiles[] = {"bear-1280x720.mp4", "bear-1280x720-av_frag.mp4"};
// Muxer options.
const double kSegmentDurationInSeconds = 1.0;
const double kFragmentDurationInSecodns = 0.1;
const bool kSegmentSapAligned = true;
const bool kFragmentSapAligned = true;
const int kNumSubsegmentsPerSidx = 2;
const char kOutputVideo[] = "output_video";
const char kOutputVideo2[] = "output_video_2";
const char kOutputAudio[] = "output_audio";
const char kOutputAudio2[] = "output_audio_2";
const char kOutputNone[] = "";
const char kSegmentTemplate[] = "template$Number$.m4s";
const char kSegmentTemplateOutputPattern[] = "template%d.m4s";
const bool kSingleSegment = true;
const bool kMultipleSegments = false;
const bool kEnableEncryption = true;
const bool kDisableEncryption = false;
// Encryption constants.
const char kKeyIdHex[] = "e5007e6e9dcd5ac095202ed3758382cd";
const char kKeyHex[] = "6fc96fe628a265b13aeddec0bc421f4d";
const char kPsshHex[] =
"08011210e5007e6e9dcd5ac095202ed3"
"758382cd1a0d7769646576696e655f746573742211544553545f"
"434f4e54454e545f49445f312a025344";
const double kClearLeadInSeconds = 1.5;
MediaStream* FindFirstStreamOfType(const std::vector<MediaStream*>& streams,
StreamType stream_type) {
typedef std::vector<MediaStream*>::const_iterator StreamIterator;
for (StreamIterator it = streams.begin(); it != streams.end(); ++it) {
if ((*it)->info()->stream_type() == stream_type)
return *it;
}
return NULL;
}
MediaStream* FindFirstVideoStream(const std::vector<MediaStream*>& streams) {
return FindFirstStreamOfType(streams, kStreamVideo);
}
MediaStream* FindFirstAudioStream(const std::vector<MediaStream*>& streams) {
return FindFirstStreamOfType(streams, kStreamAudio);
}
} // namespace
class FakeClock : public base::Clock {
public:
// Fake the clock to return NULL time.
virtual base::Time Now() OVERRIDE { return base::Time(); }
};
class PackagerTestBasic : public ::testing::TestWithParam<const char*> {
public:
PackagerTestBasic() : decryptor_source_(NULL) {}
virtual void SetUp() OVERRIDE {
// Create a test directory for testing, will be deleted after test.
ASSERT_TRUE(base::CreateNewTempDirectory("packager_", &test_directory_));
// Copy the input to test directory for easy reference.
ASSERT_TRUE(base::CopyFile(GetTestDataFilePath(GetParam()),
test_directory_.AppendASCII(GetParam())));
}
virtual void TearDown() OVERRIDE { base::DeleteFile(test_directory_, true); }
std::string GetFullPath(const std::string& file_name);
// Check if |file1| and |file2| are the same.
bool ContentsEqual(const std::string& file1, const std::string file2);
MuxerOptions SetupOptions(const std::string& output, bool single_segment);
void Remux(const std::string& input,
const std::string& video_output,
const std::string& audio_output,
bool single_segment,
bool enable_encryption);
protected:
base::FilePath test_directory_;
DecryptorSource* decryptor_source_;
FakeClock fake_clock_;
};
std::string PackagerTestBasic::GetFullPath(const std::string& file_name) {
return test_directory_.AppendASCII(file_name).value();
}
bool PackagerTestBasic::ContentsEqual(const std::string& file1,
const std::string file2) {
return base::ContentsEqual(test_directory_.AppendASCII(file1),
test_directory_.AppendASCII(file2));
}
MuxerOptions PackagerTestBasic::SetupOptions(const std::string& output,
bool single_segment) {
MuxerOptions options;
options.single_segment = single_segment;
options.segment_duration = kSegmentDurationInSeconds;
options.fragment_duration = kFragmentDurationInSecodns;
options.segment_sap_aligned = kSegmentSapAligned;
options.fragment_sap_aligned = kFragmentSapAligned;
options.num_subsegments_per_sidx = kNumSubsegmentsPerSidx;
options.output_file_name = GetFullPath(output);
options.segment_template = GetFullPath(kSegmentTemplate);
options.temp_file_name = GetFullPath(output + ".temp");
return options;
}
void PackagerTestBasic::Remux(const std::string& input,
const std::string& video_output,
const std::string& audio_output,
bool single_segment,
bool enable_encryption) {
CHECK(!video_output.empty() || !audio_output.empty());
Demuxer demuxer(GetFullPath(input), decryptor_source_);
ASSERT_OK(demuxer.Initialize());
FixedEncryptorSource encryptor_source(kKeyIdHex, kKeyHex, kPsshHex);
ASSERT_OK(encryptor_source.Initialize());
scoped_ptr<Muxer> muxer_video;
if (!video_output.empty()) {
muxer_video.reset(
new mp4::MP4Muxer(SetupOptions(video_output, single_segment)));
muxer_video->set_clock(&fake_clock_);
ASSERT_OK(muxer_video->AddStream(FindFirstVideoStream(demuxer.streams())));
if (enable_encryption)
muxer_video->SetEncryptorSource(&encryptor_source, kClearLeadInSeconds);
ASSERT_OK(muxer_video->Initialize());
}
scoped_ptr<Muxer> muxer_audio;
if (!audio_output.empty()) {
muxer_audio.reset(
new mp4::MP4Muxer(SetupOptions(audio_output, single_segment)));
muxer_audio->set_clock(&fake_clock_);
ASSERT_OK(muxer_audio->AddStream(FindFirstAudioStream(demuxer.streams())));
if (enable_encryption)
muxer_video->SetEncryptorSource(&encryptor_source, kClearLeadInSeconds);
ASSERT_OK(muxer_audio->Initialize());
}
// Start remuxing process.
ASSERT_OK(demuxer.Run());
if (muxer_video)
ASSERT_OK(muxer_video->Finalize());
if (muxer_audio)
ASSERT_OK(muxer_audio->Finalize());
}
TEST_P(PackagerTestBasic, MP4MuxerSingleSegmentUnencrypted) {
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputVideo,
kOutputNone,
kSingleSegment,
kDisableEncryption));
}
TEST_P(PackagerTestBasic, MP4MuxerSingleSegmentEncrypted) {
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputVideo,
kOutputNone,
kSingleSegment,
kEnableEncryption));
// Expect the output to be encrypted.
Demuxer demuxer(GetFullPath(kOutputVideo), decryptor_source_);
ASSERT_OK(demuxer.Initialize());
ASSERT_EQ(1, demuxer.streams().size());
EXPECT_TRUE(demuxer.streams()[0]->info()->is_encrypted());
}
class PackagerTest : public PackagerTestBasic {
public:
virtual void SetUp() OVERRIDE {
PackagerTestBasic::SetUp();
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputVideo,
kOutputNone,
kSingleSegment,
kDisableEncryption));
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputNone,
kOutputAudio,
kSingleSegment,
kDisableEncryption));
}
};
TEST_P(PackagerTest, MP4MuxerSingleSegmentUnencryptedAgain) {
// Take the muxer output and feed into muxer again. The new muxer output
// should contain the same contents as the previous muxer output.
ASSERT_NO_FATAL_FAILURE(Remux(kOutputVideo,
kOutputVideo2,
kOutputNone,
kSingleSegment,
kDisableEncryption));
EXPECT_TRUE(ContentsEqual(kOutputVideo, kOutputVideo2));
}
TEST_P(PackagerTest, MP4MuxerSingleSegmentUnencryptedSeparateAudioVideo) {
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputVideo2,
kOutputAudio2,
kSingleSegment,
kDisableEncryption));
// Compare the output with single muxer output. They should match.
EXPECT_TRUE(ContentsEqual(kOutputVideo, kOutputVideo2));
EXPECT_TRUE(ContentsEqual(kOutputAudio, kOutputAudio2));
}
TEST_P(PackagerTest, MP4MuxerMultipleSegmentsUnencrypted) {
ASSERT_NO_FATAL_FAILURE(Remux(GetParam(),
kOutputVideo2,
kOutputNone,
kMultipleSegments,
kDisableEncryption));
// Find and concatenates the segments.
const std::string kOutputVideoSegmentsCombined =
std::string(kOutputVideo) + "_combined";
base::FilePath output_path =
test_directory_.AppendASCII(kOutputVideoSegmentsCombined);
ASSERT_TRUE(
base::CopyFile(test_directory_.AppendASCII(kOutputVideo2), output_path));
const int kStartSegmentIndex = 1; // start from one.
int segment_index = kStartSegmentIndex;
while (true) {
base::FilePath segment_path = test_directory_.AppendASCII(
base::StringPrintf(kSegmentTemplateOutputPattern, segment_index));
if (!base::PathExists(segment_path))
break;
std::string segment_content;
ASSERT_TRUE(base::ReadFileToString(segment_path, &segment_content));
int bytes_written = file_util::AppendToFile(
output_path, segment_content.data(), segment_content.size());
ASSERT_EQ(segment_content.size(), bytes_written);
++segment_index;
}
// We should have at least one segment.
ASSERT_LT(kStartSegmentIndex, segment_index);
// Feed the combined file into muxer again. The new muxer output should be
// the same as by just feeding the input to muxer.
ASSERT_NO_FATAL_FAILURE(Remux(kOutputVideoSegmentsCombined,
kOutputVideo2,
kOutputNone,
kSingleSegment,
kDisableEncryption));
EXPECT_TRUE(ContentsEqual(kOutputVideo, kOutputVideo2));
}
INSTANTIATE_TEST_CASE_P(PackagerEndToEnd,
PackagerTestBasic,
ValuesIn(kMediaFiles));
INSTANTIATE_TEST_CASE_P(PackagerEndToEnd, PackagerTest, ValuesIn(kMediaFiles));
} // namespace media
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin & Arvid Norberg 2009. Use, modification and distribution is
// subject to 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)
#include <boost/python.hpp>
#include <libtorrent/create_torrent.hpp>
#include <libtorrent/file_storage.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
void set_hash(create_torrent& c, int p, char const* hash)
{
c.set_hash(p, sha1_hash(hash));
}
void call_python_object(boost::python::object const& obj, int i)
{
obj(i);
}
#ifndef BOOST_NO_EXCEPTIONS
void set_piece_hashes_callback(create_torrent& c, std::string const& p
, boost::python::object cb)
{
set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1));
}
#else
void set_piece_hashes_callback(create_torrent& c, std::string const& p
, boost::python::object cb)
{
error_code ec;
set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1), ec);
}
void set_piece_hashes0(create_torrent& c, std::string const & s)
{
error_code ec;
set_piece_hashes(c, s, ec);
}
#endif
void add_node(create_torrent& ct, std::string const& addr, int port)
{
ct.add_node(std::make_pair(addr, port));
}
void add_file(file_storage& ct, file_entry const& fe)
{
ct.add_file(fe);
}
}
void bind_create_torrent()
{
void (file_storage::*add_file0)(std::string const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#if TORRENT_USE_WSTRING
void (file_storage::*add_file1)(std::wstring const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#endif
void (file_storage::*set_name0)(std::string const&) = &file_storage::set_name;
#if TORRENT_USE_WSTRING
void (file_storage::*set_name1)(std::wstring const&) = &file_storage::set_name;
#endif
#ifndef BOOST_NO_EXCEPTIONS
void (*set_piece_hashes0)(create_torrent&, std::string const&) = &set_piece_hashes;
#endif
void (*add_files0)(file_storage&, std::string const&, boost::uint32_t) = add_files;
file_entry (file_storage::*at)(int) const = &file_storage::at;
class_<file_storage>("file_storage")
.def("is_valid", &file_storage::is_valid)
.def("add_file", add_file, arg("entry"))
.def("add_file", add_file0, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#if TORRENT_USE_WSTRING
.def("add_file", add_file1, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#endif
.def("num_files", &file_storage::num_files)
.def("at", at)
// .def("hash", &file_storage::hash)
// .def("symlink", &file_storage::symlink, return_internal_reference<>())
// .def("file_index", &file_storage::file_index)
// .def("file_base", &file_storage::file_base)
// .def("set_file_base", &file_storage::set_file_base)
// .def("file_path", &file_storage::file_path)
.def("total_size", &file_storage::total_size)
.def("set_num_pieces", &file_storage::set_num_pieces)
.def("num_pieces", &file_storage::num_pieces)
.def("set_piece_length", &file_storage::set_piece_length)
.def("piece_length", &file_storage::piece_length)
.def("piece_size", &file_storage::piece_size)
.def("set_name", set_name0)
#if TORRENT_USE_WSTRING
.def("set_name", set_name1)
#endif
.def("name", &file_storage::name, return_internal_reference<>())
;
class_<create_torrent>("create_torrent", no_init)
.def(init<file_storage&>())
.def(init<file_storage&, int, int, int>((arg("storage"), arg("piece_size") = 0
, arg("pad_file_limit") = -1, arg("flags") = int(libtorrent::create_torrent::optimize))))
.def("generate", &create_torrent::generate)
.def("files", &create_torrent::files, return_internal_reference<>())
.def("set_comment", &create_torrent::set_comment)
.def("set_creator", &create_torrent::set_creator)
.def("set_hash", &set_hash)
.def("add_url_seed", &create_torrent::add_url_seed)
.def("add_node", &add_node)
.def("add_tracker", &create_torrent::add_tracker, (arg("announce_url"), arg("tier") = 0))
.def("set_priv", &create_torrent::set_priv)
.def("num_pieces", &create_torrent::num_pieces)
.def("piece_length", &create_torrent::piece_length)
.def("piece_size", &create_torrent::piece_size)
.def("priv", &create_torrent::priv)
;
enum_<create_torrent::flags_t>("create_torrent_flags_t")
.value("optimize", create_torrent::optimize)
.value("merkle", create_torrent::merkle)
.value("modification_time", create_torrent::modification_time)
.value("symlinks", create_torrent::symlinks)
;
def("add_files", add_files0, (arg("fs"), arg("path"), arg("flags") = 0));
def("set_piece_hashes", set_piece_hashes0);
def("set_piece_hashes", set_piece_hashes_callback);
}
<commit_msg>expose create_torrent constructor to python binding<commit_after>// Copyright Daniel Wallin & Arvid Norberg 2009. Use, modification and distribution is
// subject to 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)
#include <boost/python.hpp>
#include <libtorrent/create_torrent.hpp>
#include <libtorrent/file_storage.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
void set_hash(create_torrent& c, int p, char const* hash)
{
c.set_hash(p, sha1_hash(hash));
}
void call_python_object(boost::python::object const& obj, int i)
{
obj(i);
}
#ifndef BOOST_NO_EXCEPTIONS
void set_piece_hashes_callback(create_torrent& c, std::string const& p
, boost::python::object cb)
{
set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1));
}
#else
void set_piece_hashes_callback(create_torrent& c, std::string const& p
, boost::python::object cb)
{
error_code ec;
set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1), ec);
}
void set_piece_hashes0(create_torrent& c, std::string const & s)
{
error_code ec;
set_piece_hashes(c, s, ec);
}
#endif
void add_node(create_torrent& ct, std::string const& addr, int port)
{
ct.add_node(std::make_pair(addr, port));
}
void add_file(file_storage& ct, file_entry const& fe)
{
ct.add_file(fe);
}
}
void bind_create_torrent()
{
void (file_storage::*add_file0)(std::string const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#if TORRENT_USE_WSTRING
void (file_storage::*add_file1)(std::wstring const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#endif
void (file_storage::*set_name0)(std::string const&) = &file_storage::set_name;
#if TORRENT_USE_WSTRING
void (file_storage::*set_name1)(std::wstring const&) = &file_storage::set_name;
#endif
#ifndef BOOST_NO_EXCEPTIONS
void (*set_piece_hashes0)(create_torrent&, std::string const&) = &set_piece_hashes;
#endif
void (*add_files0)(file_storage&, std::string const&, boost::uint32_t) = add_files;
file_entry (file_storage::*at)(int) const = &file_storage::at;
class_<file_storage>("file_storage")
.def("is_valid", &file_storage::is_valid)
.def("add_file", add_file, arg("entry"))
.def("add_file", add_file0, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#if TORRENT_USE_WSTRING
.def("add_file", add_file1, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#endif
.def("num_files", &file_storage::num_files)
.def("at", at)
// .def("hash", &file_storage::hash)
// .def("symlink", &file_storage::symlink, return_internal_reference<>())
// .def("file_index", &file_storage::file_index)
// .def("file_base", &file_storage::file_base)
// .def("set_file_base", &file_storage::set_file_base)
// .def("file_path", &file_storage::file_path)
.def("total_size", &file_storage::total_size)
.def("set_num_pieces", &file_storage::set_num_pieces)
.def("num_pieces", &file_storage::num_pieces)
.def("set_piece_length", &file_storage::set_piece_length)
.def("piece_length", &file_storage::piece_length)
.def("piece_size", &file_storage::piece_size)
.def("set_name", set_name0)
#if TORRENT_USE_WSTRING
.def("set_name", set_name1)
#endif
.def("name", &file_storage::name, return_internal_reference<>())
;
class_<create_torrent>("create_torrent", no_init)
.def(init<file_storage&>())
.def(init<file_storage&, torrent_info const&>(arg("ti")))
.def(init<file_storage&, int, int, int>((arg("storage"), arg("piece_size") = 0
, arg("pad_file_limit") = -1, arg("flags") = int(libtorrent::create_torrent::optimize))))
.def("generate", &create_torrent::generate)
.def("files", &create_torrent::files, return_internal_reference<>())
.def("set_comment", &create_torrent::set_comment)
.def("set_creator", &create_torrent::set_creator)
.def("set_hash", &set_hash)
.def("add_url_seed", &create_torrent::add_url_seed)
.def("add_node", &add_node)
.def("add_tracker", &create_torrent::add_tracker, (arg("announce_url"), arg("tier") = 0))
.def("set_priv", &create_torrent::set_priv)
.def("num_pieces", &create_torrent::num_pieces)
.def("piece_length", &create_torrent::piece_length)
.def("piece_size", &create_torrent::piece_size)
.def("priv", &create_torrent::priv)
;
enum_<create_torrent::flags_t>("create_torrent_flags_t")
.value("optimize", create_torrent::optimize)
.value("merkle", create_torrent::merkle)
.value("modification_time", create_torrent::modification_time)
.value("symlinks", create_torrent::symlinks)
;
def("add_files", add_files0, (arg("fs"), arg("path"), arg("flags") = 0));
def("set_piece_hashes", set_piece_hashes0);
def("set_piece_hashes", set_piece_hashes_callback);
}
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to 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)
#include <boost/python.hpp>
#include <boost/python/tuple.hpp>
#include <libtorrent/torrent_handle.hpp>
#include <libtorrent/peer_info.hpp>
#include <boost/lexical_cast.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
list url_seeds(torrent_handle& handle)
{
list ret;
std::set<std::string> urls;
{
allow_threading_guard guard;
urls = handle.url_seeds();
}
for (std::set<std::string>::iterator i(urls.begin())
, end(urls.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_availability(torrent_handle& handle)
{
list ret;
std::vector<int> avail;
{
allow_threading_guard guard;
handle.piece_availability(avail);
}
for (std::vector<int>::iterator i(avail.begin())
, end(avail.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> prio;
{
allow_threading_guard guard;
prio = handle.piece_priorities();
}
for (std::vector<int>::iterator i(prio.begin())
, end(prio.end()); i != end; ++i)
ret.append(*i);
return ret;
}
} // namespace unnamed
list file_progress(torrent_handle& handle)
{
std::vector<size_type> p;
{
allow_threading_guard guard;
p.reserve(handle.get_torrent_info().num_files());
handle.file_progress(p);
}
list result;
for (std::vector<size_type>::iterator i(p.begin()), e(p.end()); i != e; ++i)
result.append(*i);
return result;
}
list get_peer_info(torrent_handle const& handle)
{
std::vector<peer_info> pi;
{
allow_threading_guard guard;
handle.get_peer_info(pi);
}
list result;
for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)
result.append(*i);
return result;
}
void prioritize_pieces(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_pieces(result);
return;
}
}
void prioritize_files(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_files(result);
return;
}
}
list file_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> priorities = handle.file_priorities();
for (std::vector<int>::iterator i = priorities.begin(); i != priorities.end(); ++i)
ret.append(*i);
return ret;
}
void replace_trackers(torrent_handle& h, object trackers)
{
object iter(trackers.attr("__iter__")());
std::vector<announce_entry> result;
for (;;)
{
handle<> entry(allow_null(PyIter_Next(iter.ptr())));
if (entry == handle<>())
break;
dict d;
d = extract<dict>(object(entry));
std::string url;
url = extract<std::string>(d["url"]);
announce_entry a(url);
if (d.has_key("tier"))
a.tier = extract<int>(d["tier"]);
if (d.has_key("fail_limit"))
a.fail_limit = extract<int>(d["fail_limit"]);
result.push_back(a);
}
allow_threading_guard guard;
h.replace_trackers(result);
}
list trackers(torrent_handle &h)
{
list ret;
std::vector<announce_entry> const trackers = h.trackers();
for (std::vector<announce_entry>::const_iterator i = trackers.begin(), end(trackers.end()); i != end; ++i)
{
dict d;
d["url"] = i->url;
d["tier"] = i->tier;
d["fail_limit"] = i->fail_limit;
d["fails"] = i->fails;
d["source"] = i->source;
d["verified"] = i->verified;
d["updating"] = i->updating;
d["start_sent"] = i->start_sent;
d["complete_sent"] = i->complete_sent;
ret.append(d);
}
return ret;
}
list get_download_queue(torrent_handle& handle)
{
using boost::python::make_tuple;
list ret;
std::vector<partial_piece_info> downloading;
{
allow_threading_guard guard;
handle.get_download_queue(downloading);
}
for (std::vector<partial_piece_info>::iterator i = downloading.begin()
, end(downloading.end()); i != end; ++i)
{
dict partial_piece;
partial_piece["piece_index"] = i->piece_index;
partial_piece["blocks_in_piece"] = i->blocks_in_piece;
list block_list;
for (int k = 0; k < i->blocks_in_piece; ++k)
{
dict block_info;
block_info["state"] = i->blocks[k].state;
block_info["num_peers"] = i->blocks[k].num_peers;
block_info["bytes_progress"] = i->blocks[k].bytes_progress;
block_info["block_size"] = i->blocks[k].block_size;
block_info["peer"] = make_tuple(
boost::lexical_cast<std::string>(i->blocks[k].peer().address()), i->blocks[k].peer().port());
block_list.append(block_info);
}
partial_piece["blocks"] = block_list;
ret.append(partial_piece);
}
return ret;
}
namespace
{
tcp::endpoint tuple_to_endpoint(tuple const& t)
{
return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));
}
}
void force_reannounce(torrent_handle& th, int s)
{
th.force_reannounce(boost::posix_time::seconds(s));
}
void connect_peer(torrent_handle& th, tuple ip, int source)
{
th.connect_peer(tuple_to_endpoint(ip), source);
}
void set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);
}
void set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_download_limit(tuple_to_endpoint(ip), limit);
}
void add_piece(torrent_handle& th, int piece, char const *data, int flags)
{
th.add_piece(piece, data, flags);
}
void bind_torrent_handle()
{
void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;
int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;
void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;
void (torrent_handle::*move_storage0)(std::string const&) const = &torrent_handle::move_storage;
void (torrent_handle::*rename_file0)(int, std::string const&) const = &torrent_handle::rename_file;
#if TORRENT_USE_WSTRING
void (torrent_handle::*move_storage1)(std::wstring const&) const = &torrent_handle::move_storage;
void (torrent_handle::*rename_file1)(int, std::wstring const&) const = &torrent_handle::rename_file;
#endif
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;
void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;
#endif
#define _ allow_threads
class_<torrent_handle>("torrent_handle")
.def("get_peer_info", get_peer_info)
.def("status", _(&torrent_handle::status))
.def("get_download_queue", get_download_queue)
.def("file_progress", file_progress)
.def("trackers", trackers)
.def("replace_trackers", replace_trackers)
.def("add_url_seed", _(&torrent_handle::add_url_seed))
.def("remove_url_seed", _(&torrent_handle::remove_url_seed))
.def("url_seeds", url_seeds)
.def("has_metadata", _(&torrent_handle::has_metadata))
.def("get_torrent_info", _(&torrent_handle::get_torrent_info), return_internal_reference<>())
.def("is_valid", _(&torrent_handle::is_valid))
.def("is_seed", _(&torrent_handle::is_seed))
.def("is_finished", _(&torrent_handle::is_finished))
.def("is_paused", _(&torrent_handle::is_paused))
.def("pause", _(&torrent_handle::pause))
.def("resume", _(&torrent_handle::resume))
.def("clear_error", _(&torrent_handle::clear_error))
.def("set_priority", _(&torrent_handle::set_priority))
.def("is_auto_managed", _(&torrent_handle::is_auto_managed))
.def("auto_managed", _(&torrent_handle::auto_managed))
.def("queue_position", _(&torrent_handle::queue_position))
.def("queue_position_up", _(&torrent_handle::queue_position_up))
.def("queue_position_down", _(&torrent_handle::queue_position_down))
.def("queue_position_top", _(&torrent_handle::queue_position_top))
.def("queue_position_bottom", _(&torrent_handle::queue_position_bottom))
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
.def("resolve_countries", _(resolve_countries0))
.def("resolve_countries", _(resolve_countries1))
#endif
// deprecated
#ifndef TORRENT_NO_DEPRECATE
.def("filter_piece", _(&torrent_handle::filter_piece))
.def("is_piece_filtered", _(&torrent_handle::is_piece_filtered))
.def("write_resume_data", _(&torrent_handle::write_resume_data))
#endif
.def("add_piece", add_piece)
.def("read_piece", _(&torrent_handle::read_piece))
.def("set_piece_deadline", _(&torrent_handle::set_piece_deadline)
, (arg("index"), arg("deadline"), arg("flags") = 0))
.def("piece_availability", &piece_availability)
.def("piece_priority", _(piece_priority0))
.def("piece_priority", _(piece_priority1))
.def("prioritize_pieces", &prioritize_pieces)
.def("piece_priorities", &piece_priorities)
.def("prioritize_files", &prioritize_files)
.def("file_priorities", &file_priorities)
.def("use_interface", &torrent_handle::use_interface)
.def("save_resume_data", _(&torrent_handle::save_resume_data))
.def("force_reannounce", _(force_reannounce0))
.def("force_reannounce", &force_reannounce)
.def("force_dht_announce", _(&torrent_handle::force_dht_announce))
.def("scrape_tracker", _(&torrent_handle::scrape_tracker))
.def("name", _(&torrent_handle::name))
.def("set_upload_limit", _(&torrent_handle::set_upload_limit))
.def("upload_limit", _(&torrent_handle::upload_limit))
.def("set_download_limit", _(&torrent_handle::set_download_limit))
.def("download_limit", _(&torrent_handle::download_limit))
.def("set_sequential_download", _(&torrent_handle::set_sequential_download))
.def("set_peer_upload_limit", &set_peer_upload_limit)
.def("set_peer_download_limit", &set_peer_download_limit)
.def("connect_peer", &connect_peer)
.def("set_ratio", _(&torrent_handle::set_ratio))
.def("save_path", _(&torrent_handle::save_path))
.def("set_max_uploads", _(&torrent_handle::set_max_uploads))
.def("set_max_connections", _(&torrent_handle::set_max_connections))
.def("set_tracker_login", _(&torrent_handle::set_tracker_login))
.def("move_storage", _(move_storage0))
.def("info_hash", _(&torrent_handle::info_hash))
.def("force_recheck", _(&torrent_handle::force_recheck))
.def("rename_file", _(rename_file0))
#if TORRENT_USE_WSTRING
.def("move_storage", _(move_storage1))
.def("rename_file", _(rename_file1))
#endif
;
enum_<torrent_handle::deadline_flags>("deadline_flags")
.value("alert_when_available", torrent_handle::alert_when_available)
;
}
<commit_msg>reverted bad python binding change<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to 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)
#include <boost/python.hpp>
#include <boost/python/tuple.hpp>
#include <libtorrent/torrent_handle.hpp>
#include <libtorrent/peer_info.hpp>
#include <boost/lexical_cast.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
list url_seeds(torrent_handle& handle)
{
list ret;
std::set<std::string> urls;
{
allow_threading_guard guard;
urls = handle.url_seeds();
}
for (std::set<std::string>::iterator i(urls.begin())
, end(urls.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_availability(torrent_handle& handle)
{
list ret;
std::vector<int> avail;
{
allow_threading_guard guard;
handle.piece_availability(avail);
}
for (std::vector<int>::iterator i(avail.begin())
, end(avail.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> prio;
{
allow_threading_guard guard;
prio = handle.piece_priorities();
}
for (std::vector<int>::iterator i(prio.begin())
, end(prio.end()); i != end; ++i)
ret.append(*i);
return ret;
}
} // namespace unnamed
list file_progress(torrent_handle& handle)
{
std::vector<size_type> p;
{
allow_threading_guard guard;
p.reserve(handle.get_torrent_info().num_files());
handle.file_progress(p);
}
list result;
for (std::vector<size_type>::iterator i(p.begin()), e(p.end()); i != e; ++i)
result.append(*i);
return result;
}
list get_peer_info(torrent_handle const& handle)
{
std::vector<peer_info> pi;
{
allow_threading_guard guard;
handle.get_peer_info(pi);
}
list result;
for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)
result.append(*i);
return result;
}
void prioritize_pieces(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_pieces(result);
return;
}
}
void prioritize_files(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_files(result);
return;
}
}
list file_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> priorities = handle.file_priorities();
for (std::vector<int>::iterator i = priorities.begin(); i != priorities.end(); ++i)
ret.append(*i);
return ret;
}
void replace_trackers(torrent_handle& h, object trackers)
{
object iter(trackers.attr("__iter__")());
std::vector<announce_entry> result;
for (;;)
{
handle<> entry(allow_null(PyIter_Next(iter.ptr())));
if (entry == handle<>())
break;
result.push_back(extract<announce_entry const&>(object(entry)));
}
allow_threading_guard guard;
h.replace_trackers(result);
}
list trackers(torrent_handle &h)
{
list ret;
std::vector<announce_entry> const trackers = h.trackers();
for (std::vector<announce_entry>::const_iterator i = trackers.begin(), end(trackers.end()); i != end; ++i)
{
dict d;
d["url"] = i->url;
d["tier"] = i->tier;
d["fail_limit"] = i->fail_limit;
d["fails"] = i->fails;
d["source"] = i->source;
d["verified"] = i->verified;
d["updating"] = i->updating;
d["start_sent"] = i->start_sent;
d["complete_sent"] = i->complete_sent;
ret.append(d);
}
return ret;
}
list get_download_queue(torrent_handle& handle)
{
using boost::python::make_tuple;
list ret;
std::vector<partial_piece_info> downloading;
{
allow_threading_guard guard;
handle.get_download_queue(downloading);
}
for (std::vector<partial_piece_info>::iterator i = downloading.begin()
, end(downloading.end()); i != end; ++i)
{
dict partial_piece;
partial_piece["piece_index"] = i->piece_index;
partial_piece["blocks_in_piece"] = i->blocks_in_piece;
list block_list;
for (int k = 0; k < i->blocks_in_piece; ++k)
{
dict block_info;
block_info["state"] = i->blocks[k].state;
block_info["num_peers"] = i->blocks[k].num_peers;
block_info["bytes_progress"] = i->blocks[k].bytes_progress;
block_info["block_size"] = i->blocks[k].block_size;
block_info["peer"] = make_tuple(
boost::lexical_cast<std::string>(i->blocks[k].peer().address()), i->blocks[k].peer().port());
block_list.append(block_info);
}
partial_piece["blocks"] = block_list;
ret.append(partial_piece);
}
return ret;
}
namespace
{
tcp::endpoint tuple_to_endpoint(tuple const& t)
{
return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));
}
}
void force_reannounce(torrent_handle& th, int s)
{
th.force_reannounce(boost::posix_time::seconds(s));
}
void connect_peer(torrent_handle& th, tuple ip, int source)
{
th.connect_peer(tuple_to_endpoint(ip), source);
}
void set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);
}
void set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_download_limit(tuple_to_endpoint(ip), limit);
}
void add_piece(torrent_handle& th, int piece, char const *data, int flags)
{
th.add_piece(piece, data, flags);
}
void bind_torrent_handle()
{
void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;
int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;
void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;
void (torrent_handle::*move_storage0)(std::string const&) const = &torrent_handle::move_storage;
void (torrent_handle::*rename_file0)(int, std::string const&) const = &torrent_handle::rename_file;
#if TORRENT_USE_WSTRING
void (torrent_handle::*move_storage1)(std::wstring const&) const = &torrent_handle::move_storage;
void (torrent_handle::*rename_file1)(int, std::wstring const&) const = &torrent_handle::rename_file;
#endif
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;
void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;
#endif
#define _ allow_threads
class_<torrent_handle>("torrent_handle")
.def("get_peer_info", get_peer_info)
.def("status", _(&torrent_handle::status))
.def("get_download_queue", get_download_queue)
.def("file_progress", file_progress)
.def("trackers", trackers)
.def("replace_trackers", replace_trackers)
.def("add_url_seed", _(&torrent_handle::add_url_seed))
.def("remove_url_seed", _(&torrent_handle::remove_url_seed))
.def("url_seeds", url_seeds)
.def("has_metadata", _(&torrent_handle::has_metadata))
.def("get_torrent_info", _(&torrent_handle::get_torrent_info), return_internal_reference<>())
.def("is_valid", _(&torrent_handle::is_valid))
.def("is_seed", _(&torrent_handle::is_seed))
.def("is_finished", _(&torrent_handle::is_finished))
.def("is_paused", _(&torrent_handle::is_paused))
.def("pause", _(&torrent_handle::pause))
.def("resume", _(&torrent_handle::resume))
.def("clear_error", _(&torrent_handle::clear_error))
.def("set_priority", _(&torrent_handle::set_priority))
.def("is_auto_managed", _(&torrent_handle::is_auto_managed))
.def("auto_managed", _(&torrent_handle::auto_managed))
.def("queue_position", _(&torrent_handle::queue_position))
.def("queue_position_up", _(&torrent_handle::queue_position_up))
.def("queue_position_down", _(&torrent_handle::queue_position_down))
.def("queue_position_top", _(&torrent_handle::queue_position_top))
.def("queue_position_bottom", _(&torrent_handle::queue_position_bottom))
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
.def("resolve_countries", _(resolve_countries0))
.def("resolve_countries", _(resolve_countries1))
#endif
// deprecated
#ifndef TORRENT_NO_DEPRECATE
.def("filter_piece", _(&torrent_handle::filter_piece))
.def("is_piece_filtered", _(&torrent_handle::is_piece_filtered))
.def("write_resume_data", _(&torrent_handle::write_resume_data))
#endif
.def("add_piece", add_piece)
.def("read_piece", _(&torrent_handle::read_piece))
.def("set_piece_deadline", _(&torrent_handle::set_piece_deadline)
, (arg("index"), arg("deadline"), arg("flags") = 0))
.def("piece_availability", &piece_availability)
.def("piece_priority", _(piece_priority0))
.def("piece_priority", _(piece_priority1))
.def("prioritize_pieces", &prioritize_pieces)
.def("piece_priorities", &piece_priorities)
.def("prioritize_files", &prioritize_files)
.def("file_priorities", &file_priorities)
.def("use_interface", &torrent_handle::use_interface)
.def("save_resume_data", _(&torrent_handle::save_resume_data))
.def("force_reannounce", _(force_reannounce0))
.def("force_reannounce", &force_reannounce)
.def("force_dht_announce", _(&torrent_handle::force_dht_announce))
.def("scrape_tracker", _(&torrent_handle::scrape_tracker))
.def("name", _(&torrent_handle::name))
.def("set_upload_limit", _(&torrent_handle::set_upload_limit))
.def("upload_limit", _(&torrent_handle::upload_limit))
.def("set_download_limit", _(&torrent_handle::set_download_limit))
.def("download_limit", _(&torrent_handle::download_limit))
.def("set_sequential_download", _(&torrent_handle::set_sequential_download))
.def("set_peer_upload_limit", &set_peer_upload_limit)
.def("set_peer_download_limit", &set_peer_download_limit)
.def("connect_peer", &connect_peer)
.def("set_ratio", _(&torrent_handle::set_ratio))
.def("save_path", _(&torrent_handle::save_path))
.def("set_max_uploads", _(&torrent_handle::set_max_uploads))
.def("set_max_connections", _(&torrent_handle::set_max_connections))
.def("set_tracker_login", _(&torrent_handle::set_tracker_login))
.def("move_storage", _(move_storage0))
.def("info_hash", _(&torrent_handle::info_hash))
.def("force_recheck", _(&torrent_handle::force_recheck))
.def("rename_file", _(rename_file0))
#if TORRENT_USE_WSTRING
.def("move_storage", _(move_storage1))
.def("rename_file", _(rename_file1))
#endif
;
enum_<torrent_handle::deadline_flags>("deadline_flags")
.value("alert_when_available", torrent_handle::alert_when_available)
;
}
<|endoftext|> |
<commit_before>//
// Copyright (C) 2013 Mateusz Łoskot <[email protected]>
// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
//
// This file is part of Qt Creator Boost.Build plugin project.
//
// This is free software; you can redistribute and/or modify it under
// the terms of the GNU Lesser General Public License, Version 2.1
// as published by the Free Software Foundation.
// See accompanying file LICENSE.txt or copy at
// http://www.gnu.org/licenses/lgpl-2.1-standalone.html.
//
#include "bbbuildconfiguration.hpp"
#include "bbbuildstep.hpp"
#include "bbopenprojectwizard.hpp"
#include "bbproject.hpp"
#include "bbprojectfile.hpp"
#include "bbprojectmanager.hpp"
#include "bbprojectmanagerconstants.hpp"
#include "bbprojectnode.hpp"
#include "bbutility.hpp"
// Qt Creator
#include <app/app_version.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/generatedfile.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <cpptools/cppmodelmanager.h>
#include <cpptools/cppprojects.h>
#include <cpptools/cpptoolsconstants.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/target.h>
#include <qtsupport/customexecutablerunconfiguration.h>
#include <utils/fileutils.h>
#include <utils/QtConcurrentTools>
// Qt
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>
namespace BoostBuildProjectManager {
namespace Internal {
Project::Project(ProjectManager* manager, QString const& fileName)
: manager_(manager)
, filePath_(fileName)
, projectFile_(new ProjectFile(this, filePath_)) // enables projectDirectory()
, projectNode_(new ProjectNode(this, projectFile_))
{
Q_ASSERT(manager_);
Q_ASSERT(!filePath_.isEmpty());
setProjectContext(Core::Context(Constants::PROJECT_CONTEXT));
setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));
#if defined(IDE_VERSION_MAJOR) && (IDE_VERSION_MAJOR == 3 && IDE_VERSION_MINOR > 0)
setId(Constants::PROJECT_ID);
#endif
QFileInfo const projectFileInfo(filePath_);
QDir const projectDir(projectFileInfo.dir());
projectName_ = defaultProjectName(filePath_);
filesFilePath_ = QFileInfo(projectDir
, filePath_ + QLatin1String(Constants::EXT_JAMFILE_FILES)).absoluteFilePath();
includesFilePath_ = QFileInfo(projectDir
, filePath_ + QLatin1String(Constants::EXT_JAMFILE_INCLUDES)).absoluteFilePath();
projectNode_->setDisplayName(displayName());
manager_->registerProject(this);
// TODO: Add file watchers
//projectFileWatcher_->addPath(projectFilePath);
//connect(projectFileWatcher_, SIGNAL(fileChanged(QString)), this, SLOT(refresh()));
BBPM_QDEBUG("created project: " << displayName() << " in " << projectDirectory());
}
Project::~Project()
{
manager_->unregisterProject(this);
delete projectNode_;
}
QString Project::displayName() const
{
return projectName_;
}
#if defined(IDE_VERSION_MAJOR) && (IDE_VERSION_MAJOR == 3 && IDE_VERSION_MINOR == 0)
Core::Id Project::id() const
{
return Core::Id(Constants::PROJECT_ID);
}
#endif
Core::IDocument* Project::document() const
{
return projectFile_;
}
ProjectExplorer::IProjectManager* Project::projectManager() const
{
return manager_;
}
ProjectExplorer::ProjectNode* Project::rootProjectNode() const
{
return projectNode_;
}
QStringList Project::files(FilesMode fileMode) const
{
// TODO: handle ExcludeGeneratedFiles, but what files exactly?
// *.qtcreator.files, *.qtcreator.includes and *.user?
Q_UNUSED(fileMode);
return files_;
}
QStringList Project::files() const
{
return files(FilesMode::AllFiles);
}
QString Project::filesFilePath() const
{
Q_ASSERT(!filesFilePath_.isEmpty());
return filesFilePath_;
}
QString Project::includesFilePath() const
{
Q_ASSERT(!includesFilePath_.isEmpty());
return includesFilePath_;
}
bool Project::needsConfiguration() const
{
// TODO: Does Boost.Build project require any configuration on loading?
// - Kit selection
// - build/stage directory
// - targets listing
// CMakeProjectManager seems to request configuration in fromMap()
return false;
}
/*static*/
QString Project::defaultProjectName(QString const& fileName)
{
QFileInfo const fileInfo(fileName);
return fileInfo.absoluteDir().dirName();
}
/*static*/
QString Project::defaultBuildDirectory(QString const& top)
{
Utils::FileName fn(Utils::FileName::fromString(defaultWorkingDirectory(top)));
fn.appendPath(BBPM_C(BUILD_DIR_NAME));
return fn.toString();
}
/*static*/
QString Project::defaultWorkingDirectory(QString const& top)
{
// Accepts both, project file or project directory, as top.
return ProjectExplorer::Project::projectDirectory(Utils::FileName::fromString(top)).toString();
}
void Project::setProjectName(QString const& name)
{
if (projectName_ != name)
{
projectName_ = name;
projectNode_->setDisplayName(projectName_);
// TODO: signal?
}
}
QVariantMap Project::toMap() const
{
QVariantMap map(ProjectExplorer::Project::toMap());
map.insert(QLatin1String(Constants::P_KEY_PROJECTNAME), projectName_);
return map;
}
// This function is called at the very beginning to restore the settings
// from .user file, if there is any with previous settings stored.
bool Project::fromMap(QVariantMap const& map)
{
BBPM_QDEBUG(displayName());
QTC_ASSERT(projectNode_, return false);
if (!ProjectExplorer::Project::fromMap(map))
return false;
QVariantMap extraValues(map);
if (!extraValues.contains(BBPM_C(P_KEY_PROJECTNAME)))
extraValues.insert(BBPM_C(P_KEY_PROJECTNAME), projectName_);
setProjectName(map.value(BBPM_C(P_KEY_PROJECTNAME)).toString());
// Check required auxiliary files, run wizard of necessary
if (!QFileInfo(filesFilePath()).exists() || !QFileInfo(includesFilePath()).exists())
{
ProjectExplorer::Kit* defaultKit = ProjectExplorer::KitManager::defaultKit();
Q_ASSERT(defaultKit);
OpenProjectWizard wizard(this);
if (!wizard.run(defaultKit->displayName(), extraValues))
return false;
QVariantMap outputValues = wizard.outputValues();
setProjectName(outputValues.value(BBPM_C(P_KEY_PROJECTNAME)).toString());
}
// Set up active ProjectConfiguration (aka Target).
// NOTE: Call setActiveBuildConfiguration when creating new build configurations.
if (!activeTarget())
{
// Create project configuration from scratch
// TODO: Map the Kit to Boost.Build toolset option value
ProjectExplorer::Kit* defaultKit = ProjectExplorer::KitManager::defaultKit();
Q_ASSERT(defaultKit);
// Creates as many {Build|Run|Deploy}Configurations for as corresponding
// factories report as available.
// For example, BuildConfigurationFactory::availableBuilds => Debug and Release
ProjectExplorer::Target* target = createTarget(defaultKit);
QTC_ASSERT(target, return false);
addTarget(target);
}
else
{
// Configure project from settings sorced from .user file
// TODO: Do we need to handle anything from .user here? Do we need this case?
BBPM_QDEBUG(displayName() << "has user file");
}
// Sanity check (taken from GenericProjectManager):
// We need both a BuildConfiguration and a RunConfiguration!
QList<ProjectExplorer::Target*> targetList = targets();
foreach (ProjectExplorer::Target* t, targetList)
{
if (!t->activeBuildConfiguration())
{
removeTarget(t);
continue;
}
if (!t->activeRunConfiguration())
t->addRunConfiguration(new QtSupport::CustomExecutableRunConfiguration(t));
}
QTC_ASSERT(hasActiveBuildSettings(), return false);
QTC_ASSERT(activeTarget() != 0, return false);
// Trigger loading project tree and parsing sources
refresh();
return true;
}
void Project::refresh()
{
QTC_ASSERT(QFileInfo(filesFilePath()).exists(), return);
QTC_ASSERT(QFileInfo(includesFilePath()).exists(), return);
QSet<QString> oldFileList;
oldFileList = files_.toSet();
// Parse project:
// The manager does not parse Jamfile files.
// Only generates and parses list of source files in Jamfile.${JAMFILE_FILES_EXT}
QString const projectPath(projectDirectory().toString());
filesRaw_ = Utility::readLines(filesFilePath());
files_ = Utility::makeAbsolutePaths(projectPath, filesRaw_);
QStringList includePaths =
Utility::makeAbsolutePaths(projectPath,
Utility::readLines(includesFilePath()));
emit fileListChanged();
projectNode_->refresh(oldFileList);
// TODO: Does it make sense to move this to separate asynchronous task?
// TODO: extract updateCppCodeModel
CppTools::CppModelManager *modelmanager =
CppTools::CppModelManager::instance();
if (modelmanager) {
CppTools::ProjectInfo pinfo(this);
CppTools::ProjectPartBuilder builder(pinfo);
builder.setDisplayName(displayName());
builder.setProjectFile(projectFilePath().toString());
//builder.setDefines(); // TODO: waiting for Jamfile parser
builder.setIncludePaths(QStringList() << projectDirectory().toString() << includePaths);
const QList<Core::Id> languages = builder.createProjectPartsForFiles(files_);
foreach (Core::Id language, languages)
setProjectLanguage(language, true);
cppModelFuture_.cancel();
pinfo.finish();
cppModelFuture_ = modelmanager->updateProjectInfo(pinfo);
}
}
} // namespace Internal
} // namespace BoostBuildProjectManager
<commit_msg>do not set properties implictly set in the constructor of ProjectPartBuilder<commit_after>//
// Copyright (C) 2013 Mateusz Łoskot <[email protected]>
// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
//
// This file is part of Qt Creator Boost.Build plugin project.
//
// This is free software; you can redistribute and/or modify it under
// the terms of the GNU Lesser General Public License, Version 2.1
// as published by the Free Software Foundation.
// See accompanying file LICENSE.txt or copy at
// http://www.gnu.org/licenses/lgpl-2.1-standalone.html.
//
#include "bbbuildconfiguration.hpp"
#include "bbbuildstep.hpp"
#include "bbopenprojectwizard.hpp"
#include "bbproject.hpp"
#include "bbprojectfile.hpp"
#include "bbprojectmanager.hpp"
#include "bbprojectmanagerconstants.hpp"
#include "bbprojectnode.hpp"
#include "bbutility.hpp"
// Qt Creator
#include <app/app_version.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/generatedfile.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <cpptools/cppmodelmanager.h>
#include <cpptools/cppprojects.h>
#include <cpptools/cpptoolsconstants.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/target.h>
#include <qtsupport/customexecutablerunconfiguration.h>
#include <utils/fileutils.h>
#include <utils/QtConcurrentTools>
// Qt
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>
namespace BoostBuildProjectManager {
namespace Internal {
Project::Project(ProjectManager* manager, QString const& fileName)
: manager_(manager)
, filePath_(fileName)
, projectFile_(new ProjectFile(this, filePath_)) // enables projectDirectory()
, projectNode_(new ProjectNode(this, projectFile_))
{
Q_ASSERT(manager_);
Q_ASSERT(!filePath_.isEmpty());
setProjectContext(Core::Context(Constants::PROJECT_CONTEXT));
setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));
#if defined(IDE_VERSION_MAJOR) && (IDE_VERSION_MAJOR == 3 && IDE_VERSION_MINOR > 0)
setId(Constants::PROJECT_ID);
#endif
QFileInfo const projectFileInfo(filePath_);
QDir const projectDir(projectFileInfo.dir());
projectName_ = defaultProjectName(filePath_);
filesFilePath_ = QFileInfo(projectDir
, filePath_ + QLatin1String(Constants::EXT_JAMFILE_FILES)).absoluteFilePath();
includesFilePath_ = QFileInfo(projectDir
, filePath_ + QLatin1String(Constants::EXT_JAMFILE_INCLUDES)).absoluteFilePath();
projectNode_->setDisplayName(displayName());
manager_->registerProject(this);
// TODO: Add file watchers
//projectFileWatcher_->addPath(projectFilePath);
//connect(projectFileWatcher_, SIGNAL(fileChanged(QString)), this, SLOT(refresh()));
BBPM_QDEBUG("created project: " << displayName() << " in " << projectDirectory());
}
Project::~Project()
{
manager_->unregisterProject(this);
delete projectNode_;
}
QString Project::displayName() const
{
return projectName_;
}
#if defined(IDE_VERSION_MAJOR) && (IDE_VERSION_MAJOR == 3 && IDE_VERSION_MINOR == 0)
Core::Id Project::id() const
{
return Core::Id(Constants::PROJECT_ID);
}
#endif
Core::IDocument* Project::document() const
{
return projectFile_;
}
ProjectExplorer::IProjectManager* Project::projectManager() const
{
return manager_;
}
ProjectExplorer::ProjectNode* Project::rootProjectNode() const
{
return projectNode_;
}
QStringList Project::files(FilesMode fileMode) const
{
// TODO: handle ExcludeGeneratedFiles, but what files exactly?
// *.qtcreator.files, *.qtcreator.includes and *.user?
Q_UNUSED(fileMode);
return files_;
}
QStringList Project::files() const
{
return files(FilesMode::AllFiles);
}
QString Project::filesFilePath() const
{
Q_ASSERT(!filesFilePath_.isEmpty());
return filesFilePath_;
}
QString Project::includesFilePath() const
{
Q_ASSERT(!includesFilePath_.isEmpty());
return includesFilePath_;
}
bool Project::needsConfiguration() const
{
// TODO: Does Boost.Build project require any configuration on loading?
// - Kit selection
// - build/stage directory
// - targets listing
// CMakeProjectManager seems to request configuration in fromMap()
return false;
}
/*static*/
QString Project::defaultProjectName(QString const& fileName)
{
QFileInfo const fileInfo(fileName);
return fileInfo.absoluteDir().dirName();
}
/*static*/
QString Project::defaultBuildDirectory(QString const& top)
{
Utils::FileName fn(Utils::FileName::fromString(defaultWorkingDirectory(top)));
fn.appendPath(BBPM_C(BUILD_DIR_NAME));
return fn.toString();
}
/*static*/
QString Project::defaultWorkingDirectory(QString const& top)
{
// Accepts both, project file or project directory, as top.
return ProjectExplorer::Project::projectDirectory(Utils::FileName::fromString(top)).toString();
}
void Project::setProjectName(QString const& name)
{
if (projectName_ != name)
{
projectName_ = name;
projectNode_->setDisplayName(projectName_);
// TODO: signal?
}
}
QVariantMap Project::toMap() const
{
QVariantMap map(ProjectExplorer::Project::toMap());
map.insert(QLatin1String(Constants::P_KEY_PROJECTNAME), projectName_);
return map;
}
// This function is called at the very beginning to restore the settings
// from .user file, if there is any with previous settings stored.
bool Project::fromMap(QVariantMap const& map)
{
BBPM_QDEBUG(displayName());
QTC_ASSERT(projectNode_, return false);
if (!ProjectExplorer::Project::fromMap(map))
return false;
QVariantMap extraValues(map);
if (!extraValues.contains(BBPM_C(P_KEY_PROJECTNAME)))
extraValues.insert(BBPM_C(P_KEY_PROJECTNAME), projectName_);
setProjectName(map.value(BBPM_C(P_KEY_PROJECTNAME)).toString());
// Check required auxiliary files, run wizard of necessary
if (!QFileInfo(filesFilePath()).exists() || !QFileInfo(includesFilePath()).exists())
{
ProjectExplorer::Kit* defaultKit = ProjectExplorer::KitManager::defaultKit();
Q_ASSERT(defaultKit);
OpenProjectWizard wizard(this);
if (!wizard.run(defaultKit->displayName(), extraValues))
return false;
QVariantMap outputValues = wizard.outputValues();
setProjectName(outputValues.value(BBPM_C(P_KEY_PROJECTNAME)).toString());
}
// Set up active ProjectConfiguration (aka Target).
// NOTE: Call setActiveBuildConfiguration when creating new build configurations.
if (!activeTarget())
{
// Create project configuration from scratch
// TODO: Map the Kit to Boost.Build toolset option value
ProjectExplorer::Kit* defaultKit = ProjectExplorer::KitManager::defaultKit();
Q_ASSERT(defaultKit);
// Creates as many {Build|Run|Deploy}Configurations for as corresponding
// factories report as available.
// For example, BuildConfigurationFactory::availableBuilds => Debug and Release
ProjectExplorer::Target* target = createTarget(defaultKit);
QTC_ASSERT(target, return false);
addTarget(target);
}
else
{
// Configure project from settings sorced from .user file
// TODO: Do we need to handle anything from .user here? Do we need this case?
BBPM_QDEBUG(displayName() << "has user file");
}
// Sanity check (taken from GenericProjectManager):
// We need both a BuildConfiguration and a RunConfiguration!
QList<ProjectExplorer::Target*> targetList = targets();
foreach (ProjectExplorer::Target* t, targetList)
{
if (!t->activeBuildConfiguration())
{
removeTarget(t);
continue;
}
if (!t->activeRunConfiguration())
t->addRunConfiguration(new QtSupport::CustomExecutableRunConfiguration(t));
}
QTC_ASSERT(hasActiveBuildSettings(), return false);
QTC_ASSERT(activeTarget() != 0, return false);
// Trigger loading project tree and parsing sources
refresh();
return true;
}
void Project::refresh()
{
QTC_ASSERT(QFileInfo(filesFilePath()).exists(), return);
QTC_ASSERT(QFileInfo(includesFilePath()).exists(), return);
QSet<QString> oldFileList;
oldFileList = files_.toSet();
// Parse project:
// The manager does not parse Jamfile files.
// Only generates and parses list of source files in Jamfile.${JAMFILE_FILES_EXT}
QString const projectPath(projectDirectory().toString());
filesRaw_ = Utility::readLines(filesFilePath());
files_ = Utility::makeAbsolutePaths(projectPath, filesRaw_);
QStringList includePaths =
Utility::makeAbsolutePaths(projectPath,
Utility::readLines(includesFilePath()));
emit fileListChanged();
projectNode_->refresh(oldFileList);
// TODO: Does it make sense to move this to separate asynchronous task?
// TODO: extract updateCppCodeModel
CppTools::CppModelManager *modelmanager =
CppTools::CppModelManager::instance();
if (modelmanager) {
CppTools::ProjectInfo pinfo(this);
CppTools::ProjectPartBuilder builder(pinfo);
//builder.setDefines(); // TODO: waiting for Jamfile parser
builder.setIncludePaths(QStringList() << projectDirectory().toString() << includePaths);
const QList<Core::Id> languages = builder.createProjectPartsForFiles(files_);
foreach (Core::Id language, languages)
setProjectLanguage(language, true);
cppModelFuture_.cancel();
pinfo.finish();
cppModelFuture_ = modelmanager->updateProjectInfo(pinfo);
}
}
} // namespace Internal
} // namespace BoostBuildProjectManager
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include "WARCReader.h"
#include "WARCRecord.h"
#include "CSVWriter.h"
#include "tclap/CmdLine.h"
void writeCSVHeader(CSV::Writer&);
void processWARC(std::istream&, CSV::Writer&, int);
constexpr int noVerbosity = 0;
constexpr int lowVerbosity = 1;
constexpr int medVerbosity = 2;
constexpr int highVerbosity = 3;
int main(int argc, char** argv) {
std::istream* input;
std::ostream* output;
TCLAP::CmdLine cmd("meta-extractor", ' ', "0.1");
TCLAP::ValueArg<std::string> inFile("i", "input", "Input file", false, "", "file", cmd);
TCLAP::ValueArg<std::string> outFile("o", "output", "Output file", false, "", "file", cmd);
TCLAP::MultiSwitchArg verbosity("v", "verbose", "Verbose Output", cmd, noVerbosity);
try {
cmd.parse(argc, argv);
} catch(TCLAP::ArgException &e) {
std::cerr << "command line parsing error: " << e.what() << std::endl;
return 1;
}
std::ifstream inFileStream;
if(inFile.isSet()) {
inFileStream.open(inFile.getValue(), std::ifstream::binary);
if(!inFileStream.good()) {
std::cerr << "input file not found" << std::endl;
return 2;
}
input = &inFileStream;
} else {
input = &std::cin;
}
std::ofstream outFileStream;
if(outFile.isSet()) {
outFileStream.open(outFile.getValue(), std::ifstream::binary);
if(!outFileStream.good()) {
std::cerr << "output file not found" << std::endl;
return 3;
}
output = &outFileStream;
} else {
output = &std::cout;
}
try {
CSV::Writer csv(*output);
writeCSVHeader(csv);
processWARC(*input, csv, verbosity.getValue());
} catch(const std::exception& e) {
std::cerr << "Exception occurred: " << e.what() << std::endl;
return 10;
}
return 0;
}
void writeCSVHeader(CSV::Writer& csv) {
csv
<< "time" // uint32 : unix timestamp (of crawl)
<< "protocol" // bool : http[s]
<< "sl-domain" // string : amazon.co.uk
<< "tld" // string : uk
<< "public suffix" // string : co.uk
<< "path depth" // uint8 : (number of slashes)
<< "path length" // uint16 :
<< "server (all)" // string : Apache (2.4)
// TODO: server (name) only as enum value?
<< "server (name)" // string : Apache
<< "caching" // ?
<< "cookies" // uint16 : number of cookies used
<< "mime" // string : mime-type e. g. text/html
<< "encoding" // string : e. g. UTF-8
// TODO: add rest of fields
<< "scripts" // string : string[] - clustering
<< "styles" // string : string[] - clustering
<< "cdn" // bool : uses CDNs or not
<< "links (intern)" // uint16
<< "links (extern)"; // uint16
csv.next();
}
void processWARC(std::istream& input, CSV::Writer&, int verbosity) {
WARC::Reader reader(input);
WARC::Record<rapidjson::Document> record;
uint32_t countProcessed {0}, countIgnored {0};
while(reader.read(record)) {
// this is not a json record
if(!record.valid) {
record.clear();
continue;
}
std::string content_type = record.content["Envelope"]
["WARC-Header-Metadata"]
["Content-Type"].GetString();
if (content_type == "application/http; msgtype=response") {
++countProcessed;
// TODO: Output data
} else {
++countIgnored;
}
if (verbosity >= highVerbosity) {
std::cerr << record.id << ", " << record.date << ", "
<< record.length << " bytes, "
<< content_type << std::endl;
}
// clear record because it is reused
record.clear();
}
if(verbosity >= lowVerbosity) {
std::cerr << countProcessed << " records processed, "
<< countIgnored << " records ignored because of Content-Type"
<< std::endl;
}
}
<commit_msg>Start using rapidjson Pointers for querying the dom<commit_after>#include <iostream>
#include <fstream>
#include "WARCReader.h"
#include "WARCRecord.h"
#include "WARCException.h"
#include "CSVWriter.h"
#include "tclap/CmdLine.h"
#include "rapidjson/Pointer.h"
void writeCSVHeader(CSV::Writer&);
void processWARC(std::istream&, CSV::Writer&, int);
constexpr int noVerbosity = 0;
constexpr int lowVerbosity = 1;
constexpr int medVerbosity = 2;
constexpr int highVerbosity = 3;
int main(int argc, char** argv) {
std::istream* input;
std::ostream* output;
TCLAP::CmdLine cmd("meta-extractor", ' ', "0.1");
TCLAP::ValueArg<std::string> inFile("i", "input", "Input file", false, "", "file", cmd);
TCLAP::ValueArg<std::string> outFile("o", "output", "Output file", false, "", "file", cmd);
TCLAP::MultiSwitchArg verbosity("v", "verbose", "Verbose Output", cmd, noVerbosity);
try {
cmd.parse(argc, argv);
} catch(TCLAP::ArgException &e) {
std::cerr << "command line parsing error: " << e.what() << std::endl;
return 1;
}
std::ifstream inFileStream;
if(inFile.isSet()) {
inFileStream.open(inFile.getValue(), std::ifstream::binary);
if(!inFileStream.good()) {
std::cerr << "input file not found" << std::endl;
return 2;
}
input = &inFileStream;
} else {
input = &std::cin;
}
std::ofstream outFileStream;
if(outFile.isSet()) {
outFileStream.open(outFile.getValue(), std::ifstream::binary);
if(!outFileStream.good()) {
std::cerr << "output file not found" << std::endl;
return 3;
}
output = &outFileStream;
} else {
output = &std::cout;
}
try {
CSV::Writer csv(*output);
writeCSVHeader(csv);
processWARC(*input, csv, verbosity.getValue());
} catch(const std::exception& e) {
std::cerr << "Exception occurred: " << e.what() << std::endl;
return 10;
}
return 0;
}
void writeCSVHeader(CSV::Writer& csv) {
csv
<< "time" // uint32 : unix timestamp (of crawl)
<< "protocol" // bool : http[s]
<< "sl-domain" // string : amazon.co.uk
<< "tld" // string : uk
<< "public suffix" // string : co.uk
<< "path depth" // uint8 : (number of slashes)
<< "path length" // uint16 :
<< "server (all)" // string : Apache (2.4)
// TODO: server (name) only as enum value?
<< "server (name)" // string : Apache
<< "caching" // ?
<< "cookies" // uint16 : number of cookies used
<< "mime" // string : mime-type e. g. text/html
<< "encoding" // string : e. g. UTF-8
// TODO: add rest of fields
<< "scripts" // string : string[] - clustering
<< "styles" // string : string[] - clustering
<< "cdn" // bool : uses CDNs or not
<< "links (intern)" // uint16
<< "links (extern)"; // uint16
csv.next();
}
void processWARC(std::istream& input, CSV::Writer&, int verbosity) {
using Pointer = rapidjson::Pointer;
WARC::Reader reader(input);
WARC::Record<rapidjson::Document> record;
uint32_t countProcessed {0}, countIgnored {0};
const Pointer pContentType("/Envelope/WARC-Header-Metadata/Content-Type");
while(reader.read(record)) {
// this is not a json record
if(!record.valid) {
record.clear();
continue;
}
std::string contentType;
if(auto jContentType = pContentType.Get(record.content)) {
contentType = jContentType->GetString();
} else {
throw WARC::Exception("Invalid WAT: missing Content-Type");
}
if (contentType == "application/http; msgtype=response") {
++countProcessed;
// TODO: Output data
} else {
++countIgnored;
}
if (verbosity >= highVerbosity) {
std::cerr << record.id << ", " << record.date << ", "
<< record.length << " bytes, "
<< contentType << std::endl;
}
// clear record because it is reused
record.clear();
}
if(verbosity >= lowVerbosity) {
std::cerr << countProcessed << " records processed, "
<< countIgnored << " records ignored because of Content-Type"
<< std::endl;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrProcessor.h"
#include "GrContext.h"
#include "GrCoordTransform.h"
#include "GrGeometryProcessor.h"
#include "GrInvariantOutput.h"
#include "GrMemoryPool.h"
#include "GrXferProcessor.h"
#include "SkSpinlock.h"
#include "gl/GrGLFragmentProcessor.h"
#if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS
class GrFragmentProcessor;
class GrGeometryProcessor;
/*
* Originally these were both in the processor unit test header, but then it seemed to cause linker
* problems on android.
*/
template<>
SkTArray<GrProcessorTestFactory<GrFragmentProcessor>*, true>*
GrProcessorTestFactory<GrFragmentProcessor>::GetFactories() {
static SkTArray<GrProcessorTestFactory<GrFragmentProcessor>*, true> gFactories;
return &gFactories;
}
template<>
SkTArray<GrProcessorTestFactory<GrXPFactory>*, true>*
GrProcessorTestFactory<GrXPFactory>::GetFactories() {
static SkTArray<GrProcessorTestFactory<GrXPFactory>*, true> gFactories;
return &gFactories;
}
template<>
SkTArray<GrProcessorTestFactory<GrGeometryProcessor>*, true>*
GrProcessorTestFactory<GrGeometryProcessor>::GetFactories() {
static SkTArray<GrProcessorTestFactory<GrGeometryProcessor>*, true> gFactories;
return &gFactories;
}
/*
* To ensure we always have successful static initialization, before creating from the factories
* we verify the count is as expected. If a new factory is added, then these numbers must be
* manually adjusted.
*/
static const int kFPFactoryCount = 37;
static const int kGPFactoryCount = 14;
static const int kXPFactoryCount = 5;
template<>
void GrProcessorTestFactory<GrFragmentProcessor>::VerifyFactoryCount() {
if (kFPFactoryCount != GetFactories()->count()) {
SkFAIL("Wrong number of fragment processor factories!");
}
}
template<>
void GrProcessorTestFactory<GrGeometryProcessor>::VerifyFactoryCount() {
if (kGPFactoryCount != GetFactories()->count()) {
SkFAIL("Wrong number of geometry processor factories!");
}
}
template<>
void GrProcessorTestFactory<GrXPFactory>::VerifyFactoryCount() {
if (kXPFactoryCount != GetFactories()->count()) {
SkFAIL("Wrong number of xp factory factories!");
}
}
#endif
// We use a global pool protected by a mutex(spinlock). Chrome may use the same GrContext on
// different threads. The GrContext is not used concurrently on different threads and there is a
// memory barrier between accesses of a context on different threads. Also, there may be multiple
// GrContexts and those contexts may be in use concurrently on different threads.
namespace {
SK_DECLARE_STATIC_SPINLOCK(gProcessorSpinlock);
class MemoryPoolAccessor {
public:
MemoryPoolAccessor() { gProcessorSpinlock.acquire(); }
~MemoryPoolAccessor() { gProcessorSpinlock.release(); }
GrMemoryPool* pool() const {
static GrMemoryPool gPool(4096, 4096);
return &gPool;
}
};
}
int32_t GrProcessor::gCurrProcessorClassID = GrProcessor::kIllegalProcessorClassID;
///////////////////////////////////////////////////////////////////////////////
GrProcessor::~GrProcessor() {}
void GrProcessor::addTextureAccess(const GrTextureAccess* access) {
fTextureAccesses.push_back(access);
this->addGpuResource(access->getProgramTexture());
}
void* GrProcessor::operator new(size_t size) {
return MemoryPoolAccessor().pool()->allocate(size);
}
void GrProcessor::operator delete(void* target) {
return MemoryPoolAccessor().pool()->release(target);
}
bool GrProcessor::hasSameTextureAccesses(const GrProcessor& that) const {
if (this->numTextures() != that.numTextures()) {
return false;
}
for (int i = 0; i < this->numTextures(); ++i) {
if (this->textureAccess(i) != that.textureAccess(i)) {
return false;
}
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
bool GrFragmentProcessor::isEqual(const GrFragmentProcessor& that,
bool ignoreCoordTransforms) const {
if (this->classID() != that.classID() ||
!this->hasSameTextureAccesses(that)) {
return false;
}
if (ignoreCoordTransforms) {
if (this->numTransforms() != that.numTransforms()) {
return false;
}
} else if (!this->hasSameTransforms(that)) {
return false;
}
if (!this->onIsEqual(that)) {
return false;
}
if (this->numChildProcessors() != that.numChildProcessors()) {
return false;
}
for (int i = 0; i < this->numChildProcessors(); ++i) {
if (!this->childProcessor(i).isEqual(that.childProcessor(i), ignoreCoordTransforms)) {
return false;
}
}
return true;
}
GrGLFragmentProcessor* GrFragmentProcessor::createGLInstance() const {
GrGLFragmentProcessor* glFragProc = this->onCreateGLInstance();
glFragProc->fChildProcessors.push_back_n(fChildProcessors.count());
for (int i = 0; i < fChildProcessors.count(); ++i) {
glFragProc->fChildProcessors[i] = fChildProcessors[i].processor()->createGLInstance();
}
return glFragProc;
}
void GrFragmentProcessor::addTextureAccess(const GrTextureAccess* textureAccess) {
// Can't add texture accesses after registering any children since their texture accesses have
// already been bubbled up into our fTextureAccesses array
SkASSERT(fChildProcessors.empty());
INHERITED::addTextureAccess(textureAccess);
fNumTexturesExclChildren++;
}
void GrFragmentProcessor::addCoordTransform(const GrCoordTransform* transform) {
// Can't add transforms after registering any children since their transforms have already been
// bubbled up into our fCoordTransforms array
SkASSERT(fChildProcessors.empty());
fCoordTransforms.push_back(transform);
fUsesLocalCoords = fUsesLocalCoords || transform->sourceCoords() == kLocal_GrCoordSet;
SkDEBUGCODE(transform->setInProcessor();)
fNumTransformsExclChildren++;
}
int GrFragmentProcessor::registerChildProcessor(const GrFragmentProcessor* child) {
// Append the child's transforms to our transforms array and the child's textures array to our
// textures array
if (!child->fCoordTransforms.empty()) {
fCoordTransforms.push_back_n(child->fCoordTransforms.count(),
child->fCoordTransforms.begin());
}
if (!child->fTextureAccesses.empty()) {
fTextureAccesses.push_back_n(child->fTextureAccesses.count(),
child->fTextureAccesses.begin());
}
int index = fChildProcessors.count();
fChildProcessors.push_back(GrFragmentStage(child));
if (child->willReadFragmentPosition()) {
this->setWillReadFragmentPosition();
}
return index;
}
bool GrFragmentProcessor::hasSameTransforms(const GrFragmentProcessor& that) const {
if (this->numTransforms() != that.numTransforms()) {
return false;
}
int count = this->numTransforms();
for (int i = 0; i < count; ++i) {
if (this->coordTransform(i) != that.coordTransform(i)) {
return false;
}
}
return true;
}
void GrFragmentProcessor::computeInvariantOutput(GrInvariantOutput* inout) const {
this->onComputeInvariantOutput(inout);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Initial static variable from GrXPFactory
int32_t GrXPFactory::gCurrXPFClassID =
GrXPFactory::kIllegalXPFClassID;
///////////////////////////////////////////////////////////////////////////////////////////////////
// GrProcessorDataManager lives in the same pool
void* GrProcessorDataManager::operator new(size_t size) {
return MemoryPoolAccessor().pool()->allocate(size);
}
void GrProcessorDataManager::operator delete(void* target) {
return MemoryPoolAccessor().pool()->release(target);
}
<commit_msg>This code should've been part of the CL that added registerChildProcessor(); without updating fUsesLocalCoords in the parent when a child proc is registered, batching will not work properly.<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrProcessor.h"
#include "GrContext.h"
#include "GrCoordTransform.h"
#include "GrGeometryProcessor.h"
#include "GrInvariantOutput.h"
#include "GrMemoryPool.h"
#include "GrXferProcessor.h"
#include "SkSpinlock.h"
#include "gl/GrGLFragmentProcessor.h"
#if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS
class GrFragmentProcessor;
class GrGeometryProcessor;
/*
* Originally these were both in the processor unit test header, but then it seemed to cause linker
* problems on android.
*/
template<>
SkTArray<GrProcessorTestFactory<GrFragmentProcessor>*, true>*
GrProcessorTestFactory<GrFragmentProcessor>::GetFactories() {
static SkTArray<GrProcessorTestFactory<GrFragmentProcessor>*, true> gFactories;
return &gFactories;
}
template<>
SkTArray<GrProcessorTestFactory<GrXPFactory>*, true>*
GrProcessorTestFactory<GrXPFactory>::GetFactories() {
static SkTArray<GrProcessorTestFactory<GrXPFactory>*, true> gFactories;
return &gFactories;
}
template<>
SkTArray<GrProcessorTestFactory<GrGeometryProcessor>*, true>*
GrProcessorTestFactory<GrGeometryProcessor>::GetFactories() {
static SkTArray<GrProcessorTestFactory<GrGeometryProcessor>*, true> gFactories;
return &gFactories;
}
/*
* To ensure we always have successful static initialization, before creating from the factories
* we verify the count is as expected. If a new factory is added, then these numbers must be
* manually adjusted.
*/
static const int kFPFactoryCount = 37;
static const int kGPFactoryCount = 14;
static const int kXPFactoryCount = 5;
template<>
void GrProcessorTestFactory<GrFragmentProcessor>::VerifyFactoryCount() {
if (kFPFactoryCount != GetFactories()->count()) {
SkFAIL("Wrong number of fragment processor factories!");
}
}
template<>
void GrProcessorTestFactory<GrGeometryProcessor>::VerifyFactoryCount() {
if (kGPFactoryCount != GetFactories()->count()) {
SkFAIL("Wrong number of geometry processor factories!");
}
}
template<>
void GrProcessorTestFactory<GrXPFactory>::VerifyFactoryCount() {
if (kXPFactoryCount != GetFactories()->count()) {
SkFAIL("Wrong number of xp factory factories!");
}
}
#endif
// We use a global pool protected by a mutex(spinlock). Chrome may use the same GrContext on
// different threads. The GrContext is not used concurrently on different threads and there is a
// memory barrier between accesses of a context on different threads. Also, there may be multiple
// GrContexts and those contexts may be in use concurrently on different threads.
namespace {
SK_DECLARE_STATIC_SPINLOCK(gProcessorSpinlock);
class MemoryPoolAccessor {
public:
MemoryPoolAccessor() { gProcessorSpinlock.acquire(); }
~MemoryPoolAccessor() { gProcessorSpinlock.release(); }
GrMemoryPool* pool() const {
static GrMemoryPool gPool(4096, 4096);
return &gPool;
}
};
}
int32_t GrProcessor::gCurrProcessorClassID = GrProcessor::kIllegalProcessorClassID;
///////////////////////////////////////////////////////////////////////////////
GrProcessor::~GrProcessor() {}
void GrProcessor::addTextureAccess(const GrTextureAccess* access) {
fTextureAccesses.push_back(access);
this->addGpuResource(access->getProgramTexture());
}
void* GrProcessor::operator new(size_t size) {
return MemoryPoolAccessor().pool()->allocate(size);
}
void GrProcessor::operator delete(void* target) {
return MemoryPoolAccessor().pool()->release(target);
}
bool GrProcessor::hasSameTextureAccesses(const GrProcessor& that) const {
if (this->numTextures() != that.numTextures()) {
return false;
}
for (int i = 0; i < this->numTextures(); ++i) {
if (this->textureAccess(i) != that.textureAccess(i)) {
return false;
}
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
bool GrFragmentProcessor::isEqual(const GrFragmentProcessor& that,
bool ignoreCoordTransforms) const {
if (this->classID() != that.classID() ||
!this->hasSameTextureAccesses(that)) {
return false;
}
if (ignoreCoordTransforms) {
if (this->numTransforms() != that.numTransforms()) {
return false;
}
} else if (!this->hasSameTransforms(that)) {
return false;
}
if (!this->onIsEqual(that)) {
return false;
}
if (this->numChildProcessors() != that.numChildProcessors()) {
return false;
}
for (int i = 0; i < this->numChildProcessors(); ++i) {
if (!this->childProcessor(i).isEqual(that.childProcessor(i), ignoreCoordTransforms)) {
return false;
}
}
return true;
}
GrGLFragmentProcessor* GrFragmentProcessor::createGLInstance() const {
GrGLFragmentProcessor* glFragProc = this->onCreateGLInstance();
glFragProc->fChildProcessors.push_back_n(fChildProcessors.count());
for (int i = 0; i < fChildProcessors.count(); ++i) {
glFragProc->fChildProcessors[i] = fChildProcessors[i].processor()->createGLInstance();
}
return glFragProc;
}
void GrFragmentProcessor::addTextureAccess(const GrTextureAccess* textureAccess) {
// Can't add texture accesses after registering any children since their texture accesses have
// already been bubbled up into our fTextureAccesses array
SkASSERT(fChildProcessors.empty());
INHERITED::addTextureAccess(textureAccess);
fNumTexturesExclChildren++;
}
void GrFragmentProcessor::addCoordTransform(const GrCoordTransform* transform) {
// Can't add transforms after registering any children since their transforms have already been
// bubbled up into our fCoordTransforms array
SkASSERT(fChildProcessors.empty());
fCoordTransforms.push_back(transform);
fUsesLocalCoords = fUsesLocalCoords || transform->sourceCoords() == kLocal_GrCoordSet;
SkDEBUGCODE(transform->setInProcessor();)
fNumTransformsExclChildren++;
}
int GrFragmentProcessor::registerChildProcessor(const GrFragmentProcessor* child) {
// Append the child's transforms to our transforms array and the child's textures array to our
// textures array
if (!child->fCoordTransforms.empty()) {
fCoordTransforms.push_back_n(child->fCoordTransforms.count(),
child->fCoordTransforms.begin());
}
if (!child->fTextureAccesses.empty()) {
fTextureAccesses.push_back_n(child->fTextureAccesses.count(),
child->fTextureAccesses.begin());
}
int index = fChildProcessors.count();
fChildProcessors.push_back(GrFragmentStage(child));
if (child->willReadFragmentPosition()) {
this->setWillReadFragmentPosition();
}
if (child->usesLocalCoords()) {
fUsesLocalCoords = true;
}
return index;
}
bool GrFragmentProcessor::hasSameTransforms(const GrFragmentProcessor& that) const {
if (this->numTransforms() != that.numTransforms()) {
return false;
}
int count = this->numTransforms();
for (int i = 0; i < count; ++i) {
if (this->coordTransform(i) != that.coordTransform(i)) {
return false;
}
}
return true;
}
void GrFragmentProcessor::computeInvariantOutput(GrInvariantOutput* inout) const {
this->onComputeInvariantOutput(inout);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Initial static variable from GrXPFactory
int32_t GrXPFactory::gCurrXPFClassID =
GrXPFactory::kIllegalXPFClassID;
///////////////////////////////////////////////////////////////////////////////////////////////////
// GrProcessorDataManager lives in the same pool
void* GrProcessorDataManager::operator new(size_t size) {
return MemoryPoolAccessor().pool()->allocate(size);
}
void GrProcessorDataManager::operator delete(void* target) {
return MemoryPoolAccessor().pool()->release(target);
}
<|endoftext|> |
<commit_before>// File: btBoostDynamics.hpp
#ifndef _btBoostDynamics_hpp
#define _btBoostDynamics_hpp
#include <boost/python.hpp>
#include "btBoostLinearMathScalar.hpp"
#include "btBoostLinearMathVector3.hpp"
#include "btBoostLinearMathQuadWord.hpp"
#include "btBoostLinearMathQuaternion.hpp"
#include "btBoostLinearMathMatrix3x3.hpp"
// TODO: implement btAlignedObjectArray somewhere, it's needed to pass arrays
// back and forth
void defineLinearMath()
{
defineScalar();
defineVector3();
defineQuadWord();
defineQuaternion();
defineMatrix3x3();
}
#endif // _btBoostDynamics_hpp
<commit_msg>add call to transform definition<commit_after>// File: btBoostDynamics.hpp
#ifndef _btBoostDynamics_hpp
#define _btBoostDynamics_hpp
#include <boost/python.hpp>
#include "btBoostLinearMathScalar.hpp"
#include "btBoostLinearMathVector3.hpp"
#include "btBoostLinearMathQuadWord.hpp"
#include "btBoostLinearMathQuaternion.hpp"
#include "btBoostLinearMathMatrix3x3.hpp"
#include "btBoostLinearMathTransform.hpp"
// TODO: implement btAlignedObjectArray somewhere, it's needed to pass arrays
// back and forth
void defineLinearMath()
{
defineScalar();
defineVector3();
defineQuadWord();
defineQuaternion();
defineMatrix3x3();
defineTransform();
}
#endif // _btBoostDynamics_hpp
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, 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 "libtorrent/http_connection.hpp"
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <asio/ip/tcp.hpp>
#include <string>
using boost::bind;
namespace libtorrent
{
void http_connection::get(std::string const& url, time_duration timeout)
{
std::string protocol;
std::string hostname;
std::string path;
int port;
boost::tie(protocol, hostname, port, path) = parse_url_components(url);
std::stringstream headers;
headers << "GET " << path << " HTTP/1.0\r\n"
"Host:" << hostname <<
"Connection: close\r\n"
"\r\n\r\n";
sendbuffer = headers.str();
start(hostname, boost::lexical_cast<std::string>(port), timeout);
}
void http_connection::start(std::string const& hostname, std::string const& port
, time_duration timeout)
{
m_timeout = timeout;
m_timer.expires_from_now(m_timeout);
m_timer.async_wait(bind(&http_connection::on_timeout
, boost::weak_ptr<http_connection>(shared_from_this()), _1));
m_called = false;
if (m_sock.is_open() && m_hostname == hostname && m_port == port)
{
m_parser.reset();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
else
{
m_sock.close();
tcp::resolver::query query(hostname, port);
m_resolver.async_resolve(query, bind(&http_connection::on_resolve
, shared_from_this(), _1, _2));
m_hostname = hostname;
m_port = port;
}
}
void http_connection::on_timeout(boost::weak_ptr<http_connection> p
, asio::error_code const& e)
{
if (e == asio::error::operation_aborted) return;
boost::shared_ptr<http_connection> c = p.lock();
if (!c) return;
if (c->m_bottled && c->m_called) return;
if (c->m_last_receive + c->m_timeout < time_now())
{
c->m_called = true;
c->m_handler(asio::error::timed_out, c->m_parser, 0, 0);
return;
}
c->m_timer.expires_at(c->m_last_receive + c->m_timeout);
c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1));
}
void http_connection::close()
{
m_timer.cancel();
m_limiter_timer.cancel();
m_limiter_timer_active = false;
m_sock.close();
m_hostname.clear();
m_port.clear();
}
void http_connection::on_resolve(asio::error_code const& e
, tcp::resolver::iterator i)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
assert(i != tcp::resolver::iterator());
m_sock.async_connect(*i, boost::bind(&http_connection::on_connect
, shared_from_this(), _1/*, ++i*/));
}
void http_connection::on_connect(asio::error_code const& e
/*, tcp::resolver::iterator i*/)
{
if (!e)
{
m_last_receive = time_now();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
/* else if (i != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
m_sock.close();
m_sock.async_connect(*i, bind(&http_connection::on_connect
, shared_from_this(), _1, ++i));
}
*/ else
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
void http_connection::on_write(asio::error_code const& e)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
std::string().swap(sendbuffer);
m_recvbuffer.resize(4096);
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_read(asio::error_code const& e
, std::size_t bytes_transferred)
{
if (m_rate_limit)
{
m_download_quota -= bytes_transferred;
assert(m_download_quota >= 0);
}
if (e == asio::error::eof)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error_code(), m_parser, 0, 0);
return;
}
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_read_pos += bytes_transferred;
assert(m_read_pos <= int(m_recvbuffer.size()));
if (m_bottled || !m_parser.header_finished())
{
libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0]
, &m_recvbuffer[0] + m_read_pos);
m_parser.incoming(rcv_buf);
if (!m_bottled && m_parser.header_finished())
{
if (m_read_pos > m_parser.body_start())
m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start()
, m_read_pos - m_parser.body_start());
m_read_pos = 0;
m_last_receive = time_now();
}
else if (m_bottled && m_parser.finished())
{
m_timer.cancel();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
else
{
assert(!m_bottled);
m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos);
m_read_pos = 0;
m_last_receive = time_now();
}
if (int(m_recvbuffer.size()) == m_read_pos)
m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500));
if (m_read_pos == 1024 * 500)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error::eof, m_parser, 0, 0);
return;
}
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_assign_bandwidth(asio::error_code const& e)
{
if (e == asio::error::operation_aborted
&& m_limiter_timer_active)
{
if (!m_bottled || !m_called)
m_handler(e, m_parser, 0, 0);
}
m_limiter_timer_active = false;
if (e) return;
if (m_download_quota > 0) return;
m_download_quota = m_rate_limit / 4;
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (amount_to_read > m_download_quota)
amount_to_read = m_download_quota;
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
void http_connection::rate_limit(int limit)
{
if (!m_limiter_timer_active)
{
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
m_rate_limit = limit;
}
}
<commit_msg>fixed issue when aborting an http connection<commit_after>/*
Copyright (c) 2007, 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 "libtorrent/http_connection.hpp"
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <asio/ip/tcp.hpp>
#include <string>
using boost::bind;
namespace libtorrent
{
void http_connection::get(std::string const& url, time_duration timeout)
{
std::string protocol;
std::string hostname;
std::string path;
int port;
boost::tie(protocol, hostname, port, path) = parse_url_components(url);
std::stringstream headers;
headers << "GET " << path << " HTTP/1.0\r\n"
"Host:" << hostname <<
"Connection: close\r\n"
"\r\n\r\n";
sendbuffer = headers.str();
start(hostname, boost::lexical_cast<std::string>(port), timeout);
}
void http_connection::start(std::string const& hostname, std::string const& port
, time_duration timeout)
{
m_timeout = timeout;
m_timer.expires_from_now(m_timeout);
m_timer.async_wait(bind(&http_connection::on_timeout
, boost::weak_ptr<http_connection>(shared_from_this()), _1));
m_called = false;
if (m_sock.is_open() && m_hostname == hostname && m_port == port)
{
m_parser.reset();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
else
{
m_sock.close();
tcp::resolver::query query(hostname, port);
m_resolver.async_resolve(query, bind(&http_connection::on_resolve
, shared_from_this(), _1, _2));
m_hostname = hostname;
m_port = port;
}
}
void http_connection::on_timeout(boost::weak_ptr<http_connection> p
, asio::error_code const& e)
{
if (e == asio::error::operation_aborted) return;
boost::shared_ptr<http_connection> c = p.lock();
if (!c) return;
if (c->m_bottled && c->m_called) return;
if (c->m_last_receive + c->m_timeout < time_now())
{
c->m_called = true;
c->m_handler(asio::error::timed_out, c->m_parser, 0, 0);
return;
}
c->m_timer.expires_at(c->m_last_receive + c->m_timeout);
c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1));
}
void http_connection::close()
{
m_timer.cancel();
m_limiter_timer.cancel();
m_sock.close();
m_hostname.clear();
m_port.clear();
}
void http_connection::on_resolve(asio::error_code const& e
, tcp::resolver::iterator i)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
assert(i != tcp::resolver::iterator());
m_sock.async_connect(*i, boost::bind(&http_connection::on_connect
, shared_from_this(), _1/*, ++i*/));
}
void http_connection::on_connect(asio::error_code const& e
/*, tcp::resolver::iterator i*/)
{
if (!e)
{
m_last_receive = time_now();
asio::async_write(m_sock, asio::buffer(sendbuffer)
, bind(&http_connection::on_write, shared_from_this(), _1));
}
/* else if (i != tcp::resolver::iterator())
{
// The connection failed. Try the next endpoint in the list.
m_sock.close();
m_sock.async_connect(*i, bind(&http_connection::on_connect
, shared_from_this(), _1, ++i));
}
*/ else
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
void http_connection::on_write(asio::error_code const& e)
{
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
std::string().swap(sendbuffer);
m_recvbuffer.resize(4096);
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_read(asio::error_code const& e
, std::size_t bytes_transferred)
{
if (m_rate_limit)
{
m_download_quota -= bytes_transferred;
assert(m_download_quota >= 0);
}
if (e == asio::error::eof)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error_code(), m_parser, 0, 0);
return;
}
if (e)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
return;
}
m_read_pos += bytes_transferred;
assert(m_read_pos <= int(m_recvbuffer.size()));
if (m_bottled || !m_parser.header_finished())
{
libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0]
, &m_recvbuffer[0] + m_read_pos);
m_parser.incoming(rcv_buf);
if (!m_bottled && m_parser.header_finished())
{
if (m_read_pos > m_parser.body_start())
m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start()
, m_read_pos - m_parser.body_start());
m_read_pos = 0;
m_last_receive = time_now();
}
else if (m_bottled && m_parser.finished())
{
m_timer.cancel();
if (m_bottled && m_called) return;
m_called = true;
m_handler(e, m_parser, 0, 0);
}
}
else
{
assert(!m_bottled);
m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos);
m_read_pos = 0;
m_last_receive = time_now();
}
if (int(m_recvbuffer.size()) == m_read_pos)
m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500));
if (m_read_pos == 1024 * 500)
{
close();
if (m_bottled && m_called) return;
m_called = true;
m_handler(asio::error::eof, m_parser, 0, 0);
return;
}
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (m_rate_limit > 0 && amount_to_read > m_download_quota)
{
amount_to_read = m_download_quota;
if (m_download_quota == 0)
{
if (!m_limiter_timer_active)
on_assign_bandwidth(asio::error_code());
return;
}
}
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
}
void http_connection::on_assign_bandwidth(asio::error_code const& e)
{
if ((e == asio::error::operation_aborted
&& m_limiter_timer_active)
|| !m_sock.is_open())
{
if (!m_bottled || !m_called)
m_handler(e, m_parser, 0, 0);
}
m_limiter_timer_active = false;
if (e) return;
if (m_download_quota > 0) return;
m_download_quota = m_rate_limit / 4;
int amount_to_read = m_recvbuffer.size() - m_read_pos;
if (amount_to_read > m_download_quota)
amount_to_read = m_download_quota;
m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos
, amount_to_read)
, bind(&http_connection::on_read
, shared_from_this(), _1, _2));
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
void http_connection::rate_limit(int limit)
{
if (!m_limiter_timer_active)
{
m_limiter_timer_active = true;
m_limiter_timer.expires_from_now(milliseconds(250));
m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth
, shared_from_this(), _1));
}
m_rate_limit = limit;
}
}
<|endoftext|> |
<commit_before>#include "Jzon.h"
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#define SUCCESS 0
#define ERROR 1
#define THREADS 1
int checkParameters(Jzon::Object params)
{
// Search for parameter 'filename'
try
{
params.Get("filename").ToString();
}
catch (Jzon::NotFoundException e)
{
std::cout << "Parameter 'filename' missing." << std::endl;
return ERROR;
}
// Search for parameter 'filter'
try
{
params.Get("filter").ToString();
}
catch (Jzon::NotFoundException e)
{
std::cout << "Parameter 'filter' missing." << std::endl;
return ERROR;
}
// Search for parameter 'thread-video'
try
{
params.Get("threads").Get("video").ToString();
}
catch (Jzon::NotFoundException e)
{
std::cout << "Parameter 'threads-video' missing." << std::endl;
return ERROR;
}
// Search for parameter 'thread-images'
try
{
params.Get("threads").Get("images").ToString();
}
catch (Jzon::NotFoundException e)
{
std::cout << "Parameter 'threads-images' missing." << std::endl;
return ERROR;
}
return SUCCESS;
}
std::string exec(const char* cmd)
{
char buffer[128];
FILE* pipe;
std::string result = "";
pipe = popen(cmd, "r");
if (!pipe)
{
return "ERROR";
}
while(!feof(pipe))
{
if(fgets(buffer, 128, pipe) != NULL)
{
result += buffer;
}
}
pclose(pipe);
return result;
}
std::vector<std::string> &split(const std::string &s,
char delim,
std::vector<std::string> &elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s,
char delim)
{
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
void checkVideInfo(Jzon::Object params, float *duration, float *frames)
{
const char *check_info_cmd;
std::vector<std::string> info_result, times;
std::string::size_type string_size_type;
check_info_cmd = "python check_info.py";
info_result = split(exec(check_info_cmd), ',');
// set duration (in seconds)
times = split(info_result[0], ':');
*duration += std::stof(times[0], &string_size_type) * 3600; // hours
*duration += std::stof(times[1], &string_size_type) * 60; // minutes
*duration += std::stof(times[2], &string_size_type); // seconds
// set frames
*frames = std::stof(info_result[1], &string_size_type);
}
int main(int argc, char* argv[])
{
Jzon::Object params;
float duration = 0.0;
float frames = 0.0;
// Read parameters from the JSON file
Jzon::FileReader::ReadFile("params.json", params);
// Check the parameters so the complete info is loaded
if (ERROR == checkParameters(params))
{
return ERROR;
}
// Grab the neccesary info from the video file
checkVideInfo(params, &duration, &frames);
return SUCCESS;
}<commit_msg>Add video functions<commit_after>#include "Jzon.h"
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#define SUCCESS 0
#define ERROR 1
#define THREADS 1
int checkParameters(Jzon::Object params)
{
// Search for parameter 'filename'
try
{
params.Get("filename").ToString();
}
catch (Jzon::NotFoundException e)
{
std::cout << "Parameter 'filename' missing." << std::endl;
return ERROR;
}
// Search for parameter 'filter'
try
{
params.Get("filter").ToString();
}
catch (Jzon::NotFoundException e)
{
std::cout << "Parameter 'filter' missing." << std::endl;
return ERROR;
}
// Search for parameter 'thread-video'
try
{
params.Get("threads").Get("video").ToString();
}
catch (Jzon::NotFoundException e)
{
std::cout << "Parameter 'threads-video' missing." << std::endl;
return ERROR;
}
// Search for parameter 'thread-images'
try
{
params.Get("threads").Get("images").ToString();
}
catch (Jzon::NotFoundException e)
{
std::cout << "Parameter 'threads-images' missing." << std::endl;
return ERROR;
}
return SUCCESS;
}
std::string exec(const char* cmd)
{
char buffer[128];
FILE* pipe;
std::string result = "";
pipe = popen(cmd, "r");
if (!pipe)
{
return "ERROR";
}
while(!feof(pipe))
{
if(fgets(buffer, 128, pipe) != NULL)
{
result += buffer;
}
}
pclose(pipe);
return result;
}
std::vector<std::string> &split(const std::string &s,
char delim,
std::vector<std::string> &elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s,
char delim)
{
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
void checkVideInfo(Jzon::Object params, float *duration, float *frames)
{
const char *check_info_cmd;
std::vector<std::string> info_result, times;
std::string::size_type string_size_type;
check_info_cmd = "python check_info.py";
info_result = split(exec(check_info_cmd), ',');
// set duration (in seconds)
times = split(info_result[0], ':');
*duration += std::stof(times[0], &string_size_type) * 3600; // hours
*duration += std::stof(times[1], &string_size_type) * 60; // minutes
*duration += std::stof(times[2], &string_size_type); // seconds
// set frames
*frames = std::stof(info_result[1], &string_size_type);
}
void extractFrames(std::string filename, float frames)
{
std::string extract_frames_cmd;
std::stringstream ss_frames;
// Convert float to string
ss_frames << frames;
// Build code
extract_frames_cmd = "ffmpeg -i " + filename +
" -r " + ss_frames.str() +
" ./resources/video-filter-%03d.png";
exec(extract_frames_cmd.c_str());
}
void compileVideo(std::string filename, float frames)
{
std::string extract_frames_cmd;
std::stringstream ss_frames;
// Convert float to string
ss_frames << frames;
// Build code
extract_frames_cmd = "ffmpeg -f image2 -r " + ss_frames.str() +
" -i \"./resources/video-filter-%03d.png\" " +
filename;
exec(extract_frames_cmd.c_str());
}
int main(int argc, char* argv[])
{
Jzon::Object params;
float duration = 0.0;
float frames = 0.0;
// Read parameters from the JSON file
Jzon::FileReader::ReadFile("params.json", params);
// Check the parameters so the complete info is loaded
if (ERROR == checkParameters(params))
{
return ERROR;
}
// Grab the neccesary info from the video file
checkVideInfo(params, &duration, &frames);
// Get frames of video
extractFrames(params.Get("filename").ToString(), frames);
compileVideo("video2.mp4", frames);
return SUCCESS;
}<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX600, RX200 グループ・CMT I/O 制御 @n
Copyright 2013, 2017 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/vect.h"
/// F_PCLKB は周期パラメーター計算で必要で、設定が無いとエラーにします。
#ifndef F_PCLKB
# error "cmt_io.hpp requires F_PCLKB to be defined"
#endif
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief CMT I/O クラス
@param[in] CMT チャネルクラス
@param[in] TASK タイマー動作クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CMT, class TASK>
class cmt_io {
uint8_t level_;
void sleep_() const { asm("nop"); }
static TASK task_;
static volatile uint32_t counter_;
static INTERRUPT_FUNC void cmt_task_() {
++counter_;
task_();
}
void set_vector_(ICU::VECTOR vec) {
set_interrupt_task(cmt_task_, static_cast<uint32_t>(vec));
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
cmt_io() : level_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] freq タイマー周波数
@param[in] level 割り込みレベル(0ならポーリング)
@return レンジオーバーなら「false」を返す
*/
//-----------------------------------------------------------------//
bool start(uint32_t freq, uint8_t level = 0) {
level_ = level;
if(freq == 0) return false;
uint32_t cmcor = F_PCLKB / freq / 8;
uint8_t cks = 0;
while(cmcor > 65536) {
cmcor >>= 2;
++cks;
}
if(cks > 3 || cmcor == 0) {
return false;
}
power_cfg::turn(CMT::get_peripheral());
auto chanel = CMT::get_chanel();
switch(chanel) {
case 0:
set_vector_(ICU::VECTOR::CMI0);
CMT::CMSTR0.STR0 = 0;
break;
case 1:
set_vector_(ICU::VECTOR::CMI1);
CMT::CMSTR0.STR1 = 0;
break;
case 2:
set_vector_(ICU::VECTOR::CMI2);
CMT::CMSTR1.STR2 = 0;
break;
case 3:
set_vector_(ICU::VECTOR::CMI3);
CMT::CMSTR1.STR3 = 0;
break;
}
CMT::CMCNT = 0;
CMT::CMCOR = cmcor - 1;
counter_ = 0;
if(level_) {
CMT::CMCR = CMT::CMCR.CMIE.b() | CMT::CMCR.CKS.b(cks);
} else {
CMT::CMCR = CMT::CMCR.CKS.b(cks);
}
icu_mgr::set_level(CMT::get_peripheral(), level_);
switch(chanel) {
case 0:
CMT::CMSTR0.STR0 = 1;
break;
case 1:
CMT::CMSTR0.STR1 = 1;
break;
case 2:
CMT::CMSTR1.STR2 = 1;
break;
case 3:
CMT::CMSTR1.STR3 = 1;
break;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄(割り込みを停止して、ユニットを停止)
*/
//-----------------------------------------------------------------//
void destroy()
{
if(level_) {
CMT::CMCR.CMIE = 0;
}
auto chanel = CMT::get_chanel();
switch(chanel) {
case 0:
CMT::CMSTR0.STR0 = 0;
break;
case 1:
CMT::CMSTR0.STR1 = 0;
break;
case 2:
CMT::CMSTR1.STR2 = 0;
break;
case 3:
CMT::CMSTR1.STR3 = 0;
break;
}
}
//-----------------------------------------------------------------//
/*!
@brief 割り込みと同期
*/
//-----------------------------------------------------------------//
void sync() const {
if(level_) {
volatile uint32_t cnt = counter_;
while(cnt == counter_) sleep_();
} else {
auto ref = CMT::CMCNT();
while(ref <= CMT::CMCNT()) sleep_();
++counter_;
}
}
//-----------------------------------------------------------------//
/*!
@brief 割り込みカウンターの値を取得
*/
//-----------------------------------------------------------------//
uint32_t get_counter() const {
return counter_;
}
//-----------------------------------------------------------------//
/*!
@brief CMT カウンターの値を取得
*/
//-----------------------------------------------------------------//
uint16_t get_cmt_count() const {
return CMT::CMCNT();
}
//-----------------------------------------------------------------//
/*!
@brief TASK クラスの参照
@return TASK クラス
*/
//-----------------------------------------------------------------//
static TASK& at_task() { return task_; }
};
template <class CMT, class TASK> volatile uint32_t cmt_io<CMT, TASK>::counter_ = 0;
template <class CMT, class TASK> TASK cmt_io<CMT, TASK>::task_;
}
<commit_msg>add null_task, cleanup<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX600, RX200 グループ・CMT I/O 制御 @n
Copyright 2013, 2017 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/vect.h"
/// F_PCLKB は周期パラメーター計算で必要で、設定が無いとエラーにします。
#ifndef F_PCLKB
# error "cmt_io.hpp requires F_PCLKB to be defined"
#endif
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief CMT null タスク
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class cmt_null_task {
public:
//-----------------------------------------------------------------//
/*!
@brief オペレーター ()
*/
//-----------------------------------------------------------------//
void operator() () { }
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief CMT I/O クラス
@param[in] CMT チャネルクラス
@param[in] TASK タイマー動作クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CMT, class TASK = cmt_null_task>
class cmt_io {
uint8_t level_;
void sleep_() const { asm("nop"); }
static TASK task_;
static volatile uint32_t counter_;
static INTERRUPT_FUNC void cmt_task_() {
++counter_;
task_();
}
void set_vector_(ICU::VECTOR vec) {
set_interrupt_task(cmt_task_, static_cast<uint32_t>(vec));
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
cmt_io() : level_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] freq タイマー周波数
@param[in] level 割り込みレベル(0ならポーリング)
@return レンジオーバーなら「false」を返す
*/
//-----------------------------------------------------------------//
bool start(uint32_t freq, uint8_t level = 0) {
level_ = level;
if(freq == 0) return false;
uint32_t cmcor = F_PCLKB / freq / 8;
uint8_t cks = 0;
while(cmcor > 65536) {
cmcor >>= 2;
++cks;
}
if(cks > 3 || cmcor == 0) {
return false;
}
power_cfg::turn(CMT::get_peripheral());
auto chanel = CMT::get_chanel();
switch(chanel) {
case 0:
set_vector_(ICU::VECTOR::CMI0);
CMT::CMSTR0.STR0 = 0;
break;
case 1:
set_vector_(ICU::VECTOR::CMI1);
CMT::CMSTR0.STR1 = 0;
break;
case 2:
set_vector_(ICU::VECTOR::CMI2);
CMT::CMSTR1.STR2 = 0;
break;
case 3:
set_vector_(ICU::VECTOR::CMI3);
CMT::CMSTR1.STR3 = 0;
break;
}
CMT::CMCNT = 0;
CMT::CMCOR = cmcor - 1;
counter_ = 0;
if(level_) {
CMT::CMCR = CMT::CMCR.CMIE.b() | CMT::CMCR.CKS.b(cks);
} else {
CMT::CMCR = CMT::CMCR.CKS.b(cks);
}
icu_mgr::set_level(CMT::get_peripheral(), level_);
switch(chanel) {
case 0:
CMT::CMSTR0.STR0 = 1;
break;
case 1:
CMT::CMSTR0.STR1 = 1;
break;
case 2:
CMT::CMSTR1.STR2 = 1;
break;
case 3:
CMT::CMSTR1.STR3 = 1;
break;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄(割り込みを停止して、ユニットを停止)
*/
//-----------------------------------------------------------------//
void destroy()
{
if(level_) {
CMT::CMCR.CMIE = 0;
}
auto chanel = CMT::get_chanel();
switch(chanel) {
case 0:
CMT::CMSTR0.STR0 = 0;
break;
case 1:
CMT::CMSTR0.STR1 = 0;
break;
case 2:
CMT::CMSTR1.STR2 = 0;
break;
case 3:
CMT::CMSTR1.STR3 = 0;
break;
}
}
//-----------------------------------------------------------------//
/*!
@brief 割り込みと同期
*/
//-----------------------------------------------------------------//
void sync() const {
if(level_) {
volatile uint32_t cnt = counter_;
while(cnt == counter_) sleep_();
} else {
auto ref = CMT::CMCNT();
while(ref <= CMT::CMCNT()) sleep_();
++counter_;
}
}
//-----------------------------------------------------------------//
/*!
@brief 割り込みカウンターの値を取得
@return 割り込みカウンターの値
*/
//-----------------------------------------------------------------//
uint32_t get_counter() const { return counter_; }
//-----------------------------------------------------------------//
/*!
@brief CMCNT レジスターの値を取得
@return CMCNT レジスター
*/
//-----------------------------------------------------------------//
uint16_t get_cmt_count() const { return CMT::CMCNT(); }
//-----------------------------------------------------------------//
/*!
@brief TASK クラスの参照
@return TASK クラス
*/
//-----------------------------------------------------------------//
static TASK& at_task() { return task_; }
};
template <class CMT, class TASK> volatile uint32_t cmt_io<CMT, TASK>::counter_ = 0;
template <class CMT, class TASK> TASK cmt_io<CMT, TASK>::task_;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX マイコン、デバイス固有ヘッダー
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2018, 2021 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/io_utils.hpp"
#if defined(SIG_RX62N)
#include "RX62x/system.hpp"
#include "RX62x/icu.hpp"
#include "RX62x/icu_mgr.hpp"
#elif defined(SIG_RX24T)
#include "RX24T/clock_profile.hpp"
#include "RX24T/peripheral.hpp"
#include "RX24T/system.hpp"
#include "RX24T/power_mgr.hpp"
#include "RX24T/icu.hpp"
#include "RX24T/icu_mgr.hpp"
#include "RX24T/port_map.hpp"
#include "RX24T/port_map_mtu.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX64M)
#include "RX64M/clock_profile.hpp"
#include "RX600/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX600/power_mgr.hpp"
#include "RX600/icu.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/port_map.hpp"
#include "RX600/port_map_sci.hpp"
#include "RX600/port_map_mtu.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX71M)
#include "RX71M/clock_profile.hpp"
#include "RX600/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX600/power_mgr.hpp"
#include "RX600/icu.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/port_map.hpp"
#include "RX600/port_map_sci.hpp"
#include "RX600/port_map_mtu.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX72M)
#include "RX72M/clock_profile.hpp"
#include "RX72M/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX72M/power_mgr.hpp"
#include "RX72M/icu.hpp"
#include "RX72M/icu_mgr.hpp"
#include "RX72M/port_map.hpp"
#include "RX72M/port_map_mtu.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX72N)
#include "RX72N/clock_profile.hpp"
#include "RX72N/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX72N/power_mgr.hpp"
#include "RX72N/icu.hpp"
#include "RX72N/icu_mgr.hpp"
#include "RX72N/port_map.hpp"
#include "RX72N/port_map_sci.hpp"
#include "RX72N/port_map_mtu.hpp"
#include "RX72N/port_map_gptw.hpp"
#include "RX72N/port_map_tpu.hpp"
#include "RX72N/port_map_qspi.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX65N)
#include "RX65x/clock_profile.hpp"
#include "RX65x/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX65x/power_mgr.hpp"
#include "RX65x/icu.hpp"
#include "RX65x/icu_mgr.hpp"
#include "RX65x/port_map.hpp"
#include "RX65x/port_map_mtu.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX66T)
#include "RX66T/clock_profile.hpp"
#include "RX66T/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX66T/power_mgr.hpp"
#include "RX66T/icu.hpp"
#include "RX66T/icu_mgr.hpp"
#include "RX66T/port_map.hpp"
#include "RX66T/port_map_mtu.hpp"
#include "RX66T/port_map_gptw.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX72T)
#include "RX72T/clock_profile.hpp"
#include "RX72T/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX72T/power_mgr.hpp"
#include "RX72T/icu.hpp"
#include "RX72T/icu_mgr.hpp"
#include "RX72T/port_map.hpp"
#include "RX72T/port_map_sci.hpp"
#include "RX72T/port_map_mtu.hpp"
#include "RX72T/port_map_gptw.hpp"
#include "RX600/rx_dsp_inst.h"
#else
#error "device.hpp: Requires SIG_XXX to be defined"
#endif
<commit_msg>Update: DMAC management<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX マイコン、デバイス固有ヘッダー
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2018, 2021 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/io_utils.hpp"
#if defined(SIG_RX62N)
#include "RX62x/system.hpp"
#include "RX62x/icu.hpp"
#include "RX62x/icu_mgr.hpp"
#elif defined(SIG_RX24T)
#include "RX24T/clock_profile.hpp"
#include "RX24T/peripheral.hpp"
#include "RX24T/system.hpp"
#include "RX24T/power_mgr.hpp"
#include "RX24T/icu.hpp"
#include "RX24T/icu_mgr.hpp"
#include "RX24T/port_map.hpp"
#include "RX24T/port_map_mtu.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX64M)
#define RX_DMAC_
#include "RX64M/clock_profile.hpp"
#include "RX600/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX600/power_mgr.hpp"
#include "RX600/icu.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/port_map.hpp"
#include "RX600/port_map_sci.hpp"
#include "RX600/port_map_mtu.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX71M)
#define RX_DMAC_
#include "RX71M/clock_profile.hpp"
#include "RX600/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX600/power_mgr.hpp"
#include "RX600/icu.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/port_map.hpp"
#include "RX600/port_map_sci.hpp"
#include "RX600/port_map_mtu.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX72M)
#define RX_DMAC_
#include "RX72M/clock_profile.hpp"
#include "RX72M/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX72M/power_mgr.hpp"
#include "RX72M/icu.hpp"
#include "RX72M/icu_mgr.hpp"
#include "RX72M/port_map.hpp"
#include "RX72M/port_map_mtu.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX72N)
#define RX_DMAC_
#include "RX72N/clock_profile.hpp"
#include "RX72N/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX72N/power_mgr.hpp"
#include "RX72N/icu.hpp"
#include "RX72N/icu_mgr.hpp"
#include "RX72N/port_map.hpp"
#include "RX72N/port_map_sci.hpp"
#include "RX72N/port_map_mtu.hpp"
#include "RX72N/port_map_gptw.hpp"
#include "RX72N/port_map_tpu.hpp"
#include "RX72N/port_map_qspi.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX65N)
#define RX_DMAC_
#include "RX65x/clock_profile.hpp"
#include "RX65x/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX65x/power_mgr.hpp"
#include "RX65x/icu.hpp"
#include "RX65x/icu_mgr.hpp"
#include "RX65x/port_map.hpp"
#include "RX65x/port_map_mtu.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX66T)
#define RX_DMAC_
#include "RX66T/clock_profile.hpp"
#include "RX66T/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX66T/power_mgr.hpp"
#include "RX66T/icu.hpp"
#include "RX66T/icu_mgr.hpp"
#include "RX66T/port_map.hpp"
#include "RX66T/port_map_mtu.hpp"
#include "RX66T/port_map_gptw.hpp"
#include "RX600/rx_dsp_inst.h"
#elif defined(SIG_RX72T)
#define RX_DMAC_
#include "RX72T/clock_profile.hpp"
#include "RX72T/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX72T/power_mgr.hpp"
#include "RX72T/icu.hpp"
#include "RX72T/icu_mgr.hpp"
#include "RX72T/port_map.hpp"
#include "RX72T/port_map_sci.hpp"
#include "RX72T/port_map_mtu.hpp"
#include "RX72T/port_map_gptw.hpp"
#include "RX600/rx_dsp_inst.h"
#else
#error "device.hpp: Requires SIG_XXX to be defined"
#endif
<|endoftext|> |
<commit_before>/* Please refer to license.txt */
#pragma once
#define ENGINE_VERSION 0.0.0.1
//All operating specific code.
//Check http://sourceforge.net/apps/mediawiki/predef/index.php?title=Operating_Systems
//to keep this section of code up to date.
#define OS_WINDOWS 0
#define OS_APPLE 1
#define OS_LINUX 2
#define OS_UNIX 3
#define OS_OTHER 4
//Determine OS.
//First, check if it's windows.
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) || defined(WIN64) || defined(_WIN64) || defined(__WIN64) && !defined(__CYGWIN__)
#define OS OS_WINDOWS
//Now check if it's 32 or 64 bit windows.
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
#define OS_BITS_32
#else
#define OS_BITS_64
#endif
//Now check for apple operating systems.
#elif defined(__APPLE__) || defined(macintosh) || defined(Macintosh) || (defined(__MACH__) && defined(__APPLE__))
#define OS OS_APPLE
//Now check for Linux.
#elif defined(linux) || defined(__linux) || defined(__linux_) || defined(__CYGWIN__)
#define OS OS_LINUX
//Now check if it's a unix environment not defined above.
#elif defined(__unix) || defined(__unix__)
//Default case (unkown OS).
#else
#define OS OS_OTHER
#endif
//Define some basic types here.
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 ulong64;
typedef signed __int64 long64;
#else
typedef unsigned long long ulong64;
typedef signed long long long64;
#endif
<commit_msg>Update internal_header.hpp<commit_after>/* Please refer to license.txt */
#pragma once
#define ENGINE_VERSION 0.0.0.1
//All operating specific code.
//Check http://sourceforge.net/p/predef/wiki/OperatingSystems/
//to keep this section of code up to date.
#define OS_WINDOWS 0
#define OS_APPLE 1
#define OS_LINUX 2
#define OS_UNIX 3
#define OS_OTHER 4
//Determine OS.
//First, check if it's windows.
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) || defined(WIN64) || defined(_WIN64) || defined(__WIN64) && !defined(__CYGWIN__)
#define OS OS_WINDOWS
//Now check if it's 32 or 64 bit windows.
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
#define OS_BITS_32
#else
#define OS_BITS_64
#endif
//Now check for apple operating systems.
#elif defined(__APPLE__) || defined(macintosh) || defined(Macintosh) || (defined(__MACH__) && defined(__APPLE__))
#define OS OS_APPLE
//Now check for Linux.
#elif defined(linux) || defined(__linux) || defined(__linux_) || defined(__CYGWIN__)
#define OS OS_LINUX
//Now check if it's a unix environment not defined above.
#elif defined(__unix) || defined(__unix__)
//Default case (unkown OS).
#else
#define OS OS_OTHER
#endif
//Define some basic types here.
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 ulong64;
typedef signed __int64 long64;
#else
typedef unsigned long long ulong64;
typedef signed long long long64;
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include "immintrin.h"
union vec4 {
__m256d raw;
double val[4];
};
int main() {
__m256d v1 = _mm256_set_pd(1.0, 2.0, 3.0, 4.0);
__m256d v2 = _mm256_set_pd(2.0, 3.0, 4.0, 5.0);
vec4 res = {_mm256_mul_pd(v1, v2)};
for (double val : res.val) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
<commit_msg>simple vector ops WIP<commit_after>#include <iostream>
#include "immintrin.h"
#include "smmintrin.h"
struct vec4d {
union {
__m256d raw;
double val[4];
} data;
vec4d(double x, double y, double z, double w) : data{x, y, z, w} {}
vec4d(__m256d raw) : data{raw} {}
};
struct vec4f {
union {
__m128 raw;
float val[4];
} data;
vec4f(float x, float y, float z, float w) : data{x, y, z, w} {}
vec4f(__m128 raw) : data{raw} {}
};
float dot(const vec4f& a, const vec4f& b) {
__m128 dp = _mm_dp_ps(a.data.raw, b.data.raw, 0xF1);
return _mm_cvtss_f32(dp);
}
int main() {
std::cout << dot(vec4f{1.0f, 1.0f, 0.0f, 0.0f}, vec4f{1.0f, 1.0f, 0.0f, 0.0f}) << std::endl;
std::cout << dot(vec4f{2.0f, 3.0f, 0.0f, 0.0f}, vec4f{5.0f, 5.0f, 0.0f, 0.0f}) << std::endl;
__m256d v1 = _mm256_set_pd(1.0, 2.0, 3.0, 4.0);
__m256d v2 = _mm256_set_pd(2.0, 3.0, 4.0, 5.0);
double values[4] = {0.0, 1.0, 0.0, 1.0};
double values2[4] = {0.0, 1.0, 0.0, 1.0};
__m256d v3 = _mm256_load_pd(values);
__m256d v4 = _mm256_load_pd(values2);
vec4d res{_mm256_mul_pd(v1, v2)};
res.data.raw = _mm256_add_pd(res.data.raw, v3);
res.data.raw = _mm256_add_pd(res.data.raw, v4);
for (double val : res.data.val) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2003 MySQL AB
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 <ndb_global.h>
#include <ndbd_exit_codes.h>
#include "ErrorReporter.hpp"
#include <FastScheduler.hpp>
#include <DebuggerNames.hpp>
#include <NdbHost.h>
#include <NdbConfig.h>
#include <Configuration.hpp>
#include <NdbAutoPtr.hpp>
#define MESSAGE_LENGTH 500
static int WriteMessage(int thrdMessageID,
const char* thrdProblemData,
const char* thrdObjRef,
Uint32 thrdTheEmulatedJamIndex,
Uint8 thrdTheEmulatedJam[]);
static void dumpJam(FILE* jamStream,
Uint32 thrdTheEmulatedJamIndex,
Uint8 thrdTheEmulatedJam[]);
const char*
ErrorReporter::formatTimeStampString(){
TimeModule DateTime; /* To create "theDateTimeString" */
static char theDateTimeString[39];
/* Used to store the generated timestamp */
/* ex: "Wednesday 18 September 2000 - 18:54:37" */
DateTime.setTimeStamp();
BaseString::snprintf(theDateTimeString, 39, "%s %d %s %d - %s:%s:%s",
DateTime.getDayName(), DateTime.getDayOfMonth(),
DateTime.getMonthName(), DateTime.getYear(), DateTime.getHour(),
DateTime.getMinute(), DateTime.getSecond());
return (const char *)&theDateTimeString;
}
int
ErrorReporter::get_trace_no(){
FILE *stream;
unsigned int traceFileNo;
char *file_name= NdbConfig_NextTraceFileName(globalData.ownId);
NdbAutoPtr<char> tmp_aptr(file_name);
/*
* Read last number from tracefile
*/
stream = fopen(file_name, "r+");
if (stream == NULL){
traceFileNo = 1;
} else {
char buf[255];
fgets(buf, 255, stream);
const int scan = sscanf(buf, "%u", &traceFileNo);
if(scan != 1){
traceFileNo = 1;
}
fclose(stream);
traceFileNo++;
}
/**
* Wrap tracefile no
*/
Uint32 tmp = globalEmulatorData.theConfiguration->maxNoOfErrorLogs();
if (traceFileNo > tmp ) {
traceFileNo = 1;
}
/**
* Save new number to the file
*/
stream = fopen(file_name, "w");
if(stream != NULL){
fprintf(stream, "%u", traceFileNo);
fclose(stream);
}
return traceFileNo;
}
void
ErrorReporter::formatMessage(int faultID,
const char* problemData,
const char* objRef,
const char* theNameOfTheTraceFile,
char* messptr){
int processId;
ndbd_exit_classification cl;
ndbd_exit_status st;
const char *exit_msg = ndbd_exit_message(faultID, &cl);
const char *exit_cl_msg = ndbd_exit_classification_message(cl, &st);
const char *exit_st_msg = ndbd_exit_status_message(st);
processId = NdbHost_GetProcessId();
BaseString::snprintf(messptr, MESSAGE_LENGTH,
"Time: %s\n"
"Status: %s\n"
"Message: %s (%s)\n"
"Error: %d\n"
"Error data: %s\n"
"Error object: %s\n"
"Program: %s\n"
"Pid: %d\n"
"Trace: %s\n"
"Version: %s\n"
"***EOM***\n",
formatTimeStampString() ,
exit_st_msg,
exit_msg, exit_cl_msg,
faultID,
(problemData == NULL) ? "" : problemData,
objRef,
my_progname,
processId,
theNameOfTheTraceFile ? theNameOfTheTraceFile : "<no tracefile>",
NDB_VERSION_STRING);
// Add trailing blanks to get a fixed lenght of the message
while (strlen(messptr) <= MESSAGE_LENGTH-3){
strcat(messptr, " ");
}
strcat(messptr, "\n");
return;
}
NdbShutdownType ErrorReporter::s_errorHandlerShutdownType = NST_ErrorHandler;
void
ErrorReporter::setErrorHandlerShutdownType(NdbShutdownType nst)
{
s_errorHandlerShutdownType = nst;
}
void childReportError(int error);
void
ErrorReporter::handleAssert(const char* message, const char* file, int line, int ec)
{
char refMessage[100];
#ifdef NO_EMULATED_JAM
BaseString::snprintf(refMessage, 100, "file: %s lineNo: %d",
file, line);
#else
const Uint32 blockNumber = theEmulatedJamBlockNumber;
const char *blockName = getBlockName(blockNumber);
BaseString::snprintf(refMessage, 100, "%s line: %d (block: %s)",
file, line, blockName);
#endif
WriteMessage(ec, message, refMessage,
theEmulatedJamIndex, theEmulatedJam);
childReportError(ec);
NdbShutdown(s_errorHandlerShutdownType);
}
void
ErrorReporter::handleError(int messageID,
const char* problemData,
const char* objRef,
NdbShutdownType nst)
{
WriteMessage(messageID, problemData,
objRef, theEmulatedJamIndex, theEmulatedJam);
childReportError(messageID);
if(messageID == NDBD_EXIT_ERROR_INSERT){
NdbShutdown(NST_ErrorInsert);
} else {
if (nst == NST_ErrorHandler)
nst = s_errorHandlerShutdownType;
NdbShutdown(nst);
}
}
int
WriteMessage(int thrdMessageID,
const char* thrdProblemData, const char* thrdObjRef,
Uint32 thrdTheEmulatedJamIndex,
Uint8 thrdTheEmulatedJam[]){
FILE *stream;
unsigned offset;
unsigned long maxOffset; // Maximum size of file.
char theMessage[MESSAGE_LENGTH];
/**
* Format trace file name
*/
char *theTraceFileName= 0;
if (globalData.ownId > 0)
theTraceFileName= NdbConfig_TraceFileName(globalData.ownId,
ErrorReporter::get_trace_no());
NdbAutoPtr<char> tmp_aptr1(theTraceFileName);
// The first 69 bytes is info about the current offset
Uint32 noMsg = globalEmulatorData.theConfiguration->maxNoOfErrorLogs();
maxOffset = (69 + (noMsg * MESSAGE_LENGTH));
char *theErrorFileName= (char *)NdbConfig_ErrorFileName(globalData.ownId);
NdbAutoPtr<char> tmp_aptr2(theErrorFileName);
stream = fopen(theErrorFileName, "r+");
if (stream == NULL) { /* If the file could not be opened. */
// Create a new file, and skip the first 69 bytes,
// which are info about the current offset
stream = fopen(theErrorFileName, "w");
if(stream == NULL)
{
fprintf(stderr,"Unable to open error log file: %s\n", theErrorFileName);
return -1;
}
fprintf(stream, "%s%u%s", "Current byte-offset of file-pointer is: ", 69,
" \n\n\n");
// ...and write the error-message...
ErrorReporter::formatMessage(thrdMessageID,
thrdProblemData, thrdObjRef,
theTraceFileName, theMessage);
fprintf(stream, "%s", theMessage);
fflush(stream);
/* ...and finally, at the beginning of the file,
store the position where to
start writing the next message. */
offset = ftell(stream);
// If we have not reached the maximum number of messages...
if (offset <= (maxOffset - MESSAGE_LENGTH)){
fseek(stream, 40, SEEK_SET);
// ...set the current offset...
fprintf(stream,"%d", offset);
} else {
fseek(stream, 40, SEEK_SET);
// ...otherwise, start over from the beginning.
fprintf(stream, "%u%s", 69, " ");
}
} else {
// Go to the latest position in the file...
fseek(stream, 40, SEEK_SET);
fscanf(stream, "%u", &offset);
fseek(stream, offset, SEEK_SET);
// ...and write the error-message there...
ErrorReporter::formatMessage(thrdMessageID,
thrdProblemData, thrdObjRef,
theTraceFileName, theMessage);
fprintf(stream, "%s", theMessage);
fflush(stream);
/* ...and finally, at the beginning of the file,
store the position where to
start writing the next message. */
offset = ftell(stream);
// If we have not reached the maximum number of messages...
if (offset <= (maxOffset - MESSAGE_LENGTH)){
fseek(stream, 40, SEEK_SET);
// ...set the current offset...
fprintf(stream,"%d", offset);
} else {
fseek(stream, 40, SEEK_SET);
// ...otherwise, start over from the beginning.
fprintf(stream, "%u%s", 69, " ");
}
}
fflush(stream);
fclose(stream);
if (theTraceFileName) {
// Open the tracefile...
FILE *jamStream = fopen(theTraceFileName, "w");
// ...and "dump the jam" there.
// ErrorReporter::dumpJam(jamStream);
if(thrdTheEmulatedJam != 0){
dumpJam(jamStream, thrdTheEmulatedJamIndex, thrdTheEmulatedJam);
}
/* Dont print the jobBuffers until a way to copy them,
like the other variables,
is implemented. Otherwise when NDB keeps running,
with this function running
in the background, the jobBuffers will change during runtime. And when
they're printed here, they will not be correct anymore.
*/
globalScheduler.dumpSignalMemory(jamStream);
fclose(jamStream);
}
return 0;
}
void
dumpJam(FILE *jamStream,
Uint32 thrdTheEmulatedJamIndex,
Uint8 thrdTheEmulatedJam[]) {
#ifndef NO_EMULATED_JAM
// print header
const int maxaddr = 8;
fprintf(jamStream, "JAM CONTENTS up->down left->right ?=not block entry\n");
fprintf(jamStream, "%-7s ", "BLOCK");
for (int i = 0; i < maxaddr; i++)
fprintf(jamStream, "%-6s ", "ADDR");
fprintf(jamStream, "\n");
// treat as array of Uint32
const Uint32 *base = (Uint32 *)thrdTheEmulatedJam;
const int first = thrdTheEmulatedJamIndex / sizeof(Uint32); // oldest
int cnt, idx;
// look for first block entry
for (cnt = 0, idx = first; cnt < EMULATED_JAM_SIZE; cnt++, idx++) {
if (idx >= EMULATED_JAM_SIZE)
idx = 0;
const Uint32 aJamEntry = base[idx];
if (aJamEntry > (1 << 20))
break;
}
// 1. if first entry is a block entry, it is printed in the main loop
// 2. else if any block entry exists, the jam starts in an unknown block
// 3. else if no block entry exists, the block is theEmulatedJamBlockNumber
// a "?" indicates first addr is not a block entry
if (cnt == 0)
;
else if (cnt < EMULATED_JAM_SIZE)
fprintf(jamStream, "%-7s?", "");
else {
const Uint32 aBlockNumber = theEmulatedJamBlockNumber;
const char *aBlockName = getBlockName(aBlockNumber);
if (aBlockName != 0)
fprintf(jamStream, "%-7s?", aBlockName);
else
fprintf(jamStream, "0x%-5X?", aBlockNumber);
}
// loop over all entries
int cntaddr = 0;
for (cnt = 0, idx = first; cnt < EMULATED_JAM_SIZE; cnt++, idx++) {
globalData.incrementWatchDogCounter(4); // watchdog not to kill us ?
if (idx >= EMULATED_JAM_SIZE)
idx = 0;
const Uint32 aJamEntry = base[idx];
if (aJamEntry > (1 << 20)) {
const Uint32 aBlockNumber = aJamEntry >> 20;
const char *aBlockName = getBlockName(aBlockNumber);
if (cnt > 0)
fprintf(jamStream, "\n");
if (aBlockName != 0)
fprintf(jamStream, "%-7s ", aBlockName);
else
fprintf(jamStream, "0x%-5X ", aBlockNumber);
cntaddr = 0;
}
if (cntaddr == maxaddr) {
fprintf(jamStream, "\n%-7s ", "");
cntaddr = 0;
}
fprintf(jamStream, "%06u ", aJamEntry & 0xFFFFF);
cntaddr++;
}
fprintf(jamStream, "\n");
fflush(jamStream);
#endif // ifndef NO_EMULATED_JAM
}
<commit_msg>BUG#21296 Add error messages when upgrading data node<commit_after>/* Copyright (C) 2003 MySQL AB
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 <ndb_global.h>
#include <ndbd_exit_codes.h>
#include "ErrorReporter.hpp"
#include <FastScheduler.hpp>
#include <DebuggerNames.hpp>
#include <NdbHost.h>
#include <NdbConfig.h>
#include <Configuration.hpp>
#include "EventLogger.hpp"
#include <NdbAutoPtr.hpp>
#define MESSAGE_LENGTH 500
static int WriteMessage(int thrdMessageID,
const char* thrdProblemData,
const char* thrdObjRef,
Uint32 thrdTheEmulatedJamIndex,
Uint8 thrdTheEmulatedJam[]);
static void dumpJam(FILE* jamStream,
Uint32 thrdTheEmulatedJamIndex,
Uint8 thrdTheEmulatedJam[]);
extern EventLogger g_eventLogger;
const char*
ErrorReporter::formatTimeStampString(){
TimeModule DateTime; /* To create "theDateTimeString" */
static char theDateTimeString[39];
/* Used to store the generated timestamp */
/* ex: "Wednesday 18 September 2000 - 18:54:37" */
DateTime.setTimeStamp();
BaseString::snprintf(theDateTimeString, 39, "%s %d %s %d - %s:%s:%s",
DateTime.getDayName(), DateTime.getDayOfMonth(),
DateTime.getMonthName(), DateTime.getYear(), DateTime.getHour(),
DateTime.getMinute(), DateTime.getSecond());
return (const char *)&theDateTimeString;
}
int
ErrorReporter::get_trace_no(){
FILE *stream;
unsigned int traceFileNo;
char *file_name= NdbConfig_NextTraceFileName(globalData.ownId);
NdbAutoPtr<char> tmp_aptr(file_name);
/*
* Read last number from tracefile
*/
stream = fopen(file_name, "r+");
if (stream == NULL){
traceFileNo = 1;
} else {
char buf[255];
fgets(buf, 255, stream);
const int scan = sscanf(buf, "%u", &traceFileNo);
if(scan != 1){
traceFileNo = 1;
}
fclose(stream);
traceFileNo++;
}
/**
* Wrap tracefile no
*/
Uint32 tmp = globalEmulatorData.theConfiguration->maxNoOfErrorLogs();
if (traceFileNo > tmp ) {
traceFileNo = 1;
}
/**
* Save new number to the file
*/
stream = fopen(file_name, "w");
if(stream != NULL){
fprintf(stream, "%u", traceFileNo);
fclose(stream);
}
return traceFileNo;
}
void
ErrorReporter::formatMessage(int faultID,
const char* problemData,
const char* objRef,
const char* theNameOfTheTraceFile,
char* messptr){
int processId;
ndbd_exit_classification cl;
ndbd_exit_status st;
const char *exit_msg = ndbd_exit_message(faultID, &cl);
const char *exit_cl_msg = ndbd_exit_classification_message(cl, &st);
const char *exit_st_msg = ndbd_exit_status_message(st);
processId = NdbHost_GetProcessId();
BaseString::snprintf(messptr, MESSAGE_LENGTH,
"Time: %s\n"
"Status: %s\n"
"Message: %s (%s)\n"
"Error: %d\n"
"Error data: %s\n"
"Error object: %s\n"
"Program: %s\n"
"Pid: %d\n"
"Trace: %s\n"
"Version: %s\n"
"***EOM***\n",
formatTimeStampString() ,
exit_st_msg,
exit_msg, exit_cl_msg,
faultID,
(problemData == NULL) ? "" : problemData,
objRef,
my_progname,
processId,
theNameOfTheTraceFile ? theNameOfTheTraceFile : "<no tracefile>",
NDB_VERSION_STRING);
// Add trailing blanks to get a fixed lenght of the message
while (strlen(messptr) <= MESSAGE_LENGTH-3){
strcat(messptr, " ");
}
strcat(messptr, "\n");
return;
}
NdbShutdownType ErrorReporter::s_errorHandlerShutdownType = NST_ErrorHandler;
void
ErrorReporter::setErrorHandlerShutdownType(NdbShutdownType nst)
{
s_errorHandlerShutdownType = nst;
}
void childReportError(int error);
void
ErrorReporter::handleAssert(const char* message, const char* file, int line, int ec)
{
char refMessage[100];
#ifdef NO_EMULATED_JAM
BaseString::snprintf(refMessage, 100, "file: %s lineNo: %d",
file, line);
#else
const Uint32 blockNumber = theEmulatedJamBlockNumber;
const char *blockName = getBlockName(blockNumber);
BaseString::snprintf(refMessage, 100, "%s line: %d (block: %s)",
file, line, blockName);
#endif
WriteMessage(ec, message, refMessage,
theEmulatedJamIndex, theEmulatedJam);
childReportError(ec);
NdbShutdown(s_errorHandlerShutdownType);
}
void
ErrorReporter::handleError(int messageID,
const char* problemData,
const char* objRef,
NdbShutdownType nst)
{
WriteMessage(messageID, problemData,
objRef, theEmulatedJamIndex, theEmulatedJam);
g_eventLogger.info(problemData);
g_eventLogger.info(objRef);
childReportError(messageID);
if(messageID == NDBD_EXIT_ERROR_INSERT){
NdbShutdown(NST_ErrorInsert);
} else {
if (nst == NST_ErrorHandler)
nst = s_errorHandlerShutdownType;
NdbShutdown(nst);
}
}
int
WriteMessage(int thrdMessageID,
const char* thrdProblemData, const char* thrdObjRef,
Uint32 thrdTheEmulatedJamIndex,
Uint8 thrdTheEmulatedJam[]){
FILE *stream;
unsigned offset;
unsigned long maxOffset; // Maximum size of file.
char theMessage[MESSAGE_LENGTH];
/**
* Format trace file name
*/
char *theTraceFileName= 0;
if (globalData.ownId > 0)
theTraceFileName= NdbConfig_TraceFileName(globalData.ownId,
ErrorReporter::get_trace_no());
NdbAutoPtr<char> tmp_aptr1(theTraceFileName);
// The first 69 bytes is info about the current offset
Uint32 noMsg = globalEmulatorData.theConfiguration->maxNoOfErrorLogs();
maxOffset = (69 + (noMsg * MESSAGE_LENGTH));
char *theErrorFileName= (char *)NdbConfig_ErrorFileName(globalData.ownId);
NdbAutoPtr<char> tmp_aptr2(theErrorFileName);
stream = fopen(theErrorFileName, "r+");
if (stream == NULL) { /* If the file could not be opened. */
// Create a new file, and skip the first 69 bytes,
// which are info about the current offset
stream = fopen(theErrorFileName, "w");
if(stream == NULL)
{
fprintf(stderr,"Unable to open error log file: %s\n", theErrorFileName);
return -1;
}
fprintf(stream, "%s%u%s", "Current byte-offset of file-pointer is: ", 69,
" \n\n\n");
// ...and write the error-message...
ErrorReporter::formatMessage(thrdMessageID,
thrdProblemData, thrdObjRef,
theTraceFileName, theMessage);
fprintf(stream, "%s", theMessage);
fflush(stream);
/* ...and finally, at the beginning of the file,
store the position where to
start writing the next message. */
offset = ftell(stream);
// If we have not reached the maximum number of messages...
if (offset <= (maxOffset - MESSAGE_LENGTH)){
fseek(stream, 40, SEEK_SET);
// ...set the current offset...
fprintf(stream,"%d", offset);
} else {
fseek(stream, 40, SEEK_SET);
// ...otherwise, start over from the beginning.
fprintf(stream, "%u%s", 69, " ");
}
} else {
// Go to the latest position in the file...
fseek(stream, 40, SEEK_SET);
fscanf(stream, "%u", &offset);
fseek(stream, offset, SEEK_SET);
// ...and write the error-message there...
ErrorReporter::formatMessage(thrdMessageID,
thrdProblemData, thrdObjRef,
theTraceFileName, theMessage);
fprintf(stream, "%s", theMessage);
fflush(stream);
/* ...and finally, at the beginning of the file,
store the position where to
start writing the next message. */
offset = ftell(stream);
// If we have not reached the maximum number of messages...
if (offset <= (maxOffset - MESSAGE_LENGTH)){
fseek(stream, 40, SEEK_SET);
// ...set the current offset...
fprintf(stream,"%d", offset);
} else {
fseek(stream, 40, SEEK_SET);
// ...otherwise, start over from the beginning.
fprintf(stream, "%u%s", 69, " ");
}
}
fflush(stream);
fclose(stream);
if (theTraceFileName) {
// Open the tracefile...
FILE *jamStream = fopen(theTraceFileName, "w");
// ...and "dump the jam" there.
// ErrorReporter::dumpJam(jamStream);
if(thrdTheEmulatedJam != 0){
dumpJam(jamStream, thrdTheEmulatedJamIndex, thrdTheEmulatedJam);
}
/* Dont print the jobBuffers until a way to copy them,
like the other variables,
is implemented. Otherwise when NDB keeps running,
with this function running
in the background, the jobBuffers will change during runtime. And when
they're printed here, they will not be correct anymore.
*/
globalScheduler.dumpSignalMemory(jamStream);
fclose(jamStream);
}
return 0;
}
void
dumpJam(FILE *jamStream,
Uint32 thrdTheEmulatedJamIndex,
Uint8 thrdTheEmulatedJam[]) {
#ifndef NO_EMULATED_JAM
// print header
const int maxaddr = 8;
fprintf(jamStream, "JAM CONTENTS up->down left->right ?=not block entry\n");
fprintf(jamStream, "%-7s ", "BLOCK");
for (int i = 0; i < maxaddr; i++)
fprintf(jamStream, "%-6s ", "ADDR");
fprintf(jamStream, "\n");
// treat as array of Uint32
const Uint32 *base = (Uint32 *)thrdTheEmulatedJam;
const int first = thrdTheEmulatedJamIndex / sizeof(Uint32); // oldest
int cnt, idx;
// look for first block entry
for (cnt = 0, idx = first; cnt < EMULATED_JAM_SIZE; cnt++, idx++) {
if (idx >= EMULATED_JAM_SIZE)
idx = 0;
const Uint32 aJamEntry = base[idx];
if (aJamEntry > (1 << 20))
break;
}
// 1. if first entry is a block entry, it is printed in the main loop
// 2. else if any block entry exists, the jam starts in an unknown block
// 3. else if no block entry exists, the block is theEmulatedJamBlockNumber
// a "?" indicates first addr is not a block entry
if (cnt == 0)
;
else if (cnt < EMULATED_JAM_SIZE)
fprintf(jamStream, "%-7s?", "");
else {
const Uint32 aBlockNumber = theEmulatedJamBlockNumber;
const char *aBlockName = getBlockName(aBlockNumber);
if (aBlockName != 0)
fprintf(jamStream, "%-7s?", aBlockName);
else
fprintf(jamStream, "0x%-5X?", aBlockNumber);
}
// loop over all entries
int cntaddr = 0;
for (cnt = 0, idx = first; cnt < EMULATED_JAM_SIZE; cnt++, idx++) {
globalData.incrementWatchDogCounter(4); // watchdog not to kill us ?
if (idx >= EMULATED_JAM_SIZE)
idx = 0;
const Uint32 aJamEntry = base[idx];
if (aJamEntry > (1 << 20)) {
const Uint32 aBlockNumber = aJamEntry >> 20;
const char *aBlockName = getBlockName(aBlockNumber);
if (cnt > 0)
fprintf(jamStream, "\n");
if (aBlockName != 0)
fprintf(jamStream, "%-7s ", aBlockName);
else
fprintf(jamStream, "0x%-5X ", aBlockNumber);
cntaddr = 0;
}
if (cntaddr == maxaddr) {
fprintf(jamStream, "\n%-7s ", "");
cntaddr = 0;
}
fprintf(jamStream, "%06u ", aJamEntry & 0xFFFFF);
cntaddr++;
}
fprintf(jamStream, "\n");
fflush(jamStream);
#endif // ifndef NO_EMULATED_JAM
}
<|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 <swmodeltestbase.hxx>
#include <LibreOfficeKit/LibreOfficeKitEnums.h>
#include <comphelper/dispatchcommand.hxx>
#include <comphelper/propertysequence.hxx>
#include <comphelper/string.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdview.hxx>
#include <vcl/svapp.hxx>
#include <crsskip.hxx>
#include <drawdoc.hxx>
#include <ndtxt.hxx>
#include <wrtsh.hxx>
static const char* DATA_DIRECTORY = "/sw/qa/extras/tiledrendering/data/";
/// Testsuite for the SwXTextDocument methods implementing the vcl::ITiledRenderable interface.
class SwTiledRenderingTest : public SwModelTestBase
{
public:
void testRegisterCallback();
void testPostKeyEvent();
void testPostMouseEvent();
void testSetTextSelection();
void testSetGraphicSelection();
void testResetSelection();
void testSearch();
CPPUNIT_TEST_SUITE(SwTiledRenderingTest);
CPPUNIT_TEST(testRegisterCallback);
CPPUNIT_TEST(testPostKeyEvent);
CPPUNIT_TEST(testPostMouseEvent);
CPPUNIT_TEST(testSetTextSelection);
CPPUNIT_TEST(testSetGraphicSelection);
CPPUNIT_TEST(testResetSelection);
CPPUNIT_TEST(testSearch);
CPPUNIT_TEST_SUITE_END();
private:
SwXTextDocument* createDoc(const char* pName);
static void callback(int nType, const char* pPayload, void* pData);
void callbackImpl(int nType, const char* pPayload);
Rectangle m_aInvalidation;
};
SwXTextDocument* SwTiledRenderingTest::createDoc(const char* pName)
{
load(DATA_DIRECTORY, pName);
SwXTextDocument* pTextDocument = dynamic_cast<SwXTextDocument*>(mxComponent.get());
CPPUNIT_ASSERT(pTextDocument);
pTextDocument->initializeForTiledRendering();
return pTextDocument;
}
void SwTiledRenderingTest::callback(int nType, const char* pPayload, void* pData)
{
static_cast<SwTiledRenderingTest*>(pData)->callbackImpl(nType, pPayload);
}
void SwTiledRenderingTest::callbackImpl(int nType, const char* pPayload)
{
switch (nType)
{
case LOK_CALLBACK_INVALIDATE_TILES:
{
if (m_aInvalidation.IsEmpty())
{
uno::Sequence<OUString> aSeq = comphelper::string::convertCommaSeparated(OUString::createFromAscii(pPayload));
CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(4), aSeq.getLength());
m_aInvalidation.setX(aSeq[0].toInt32());
m_aInvalidation.setY(aSeq[1].toInt32());
m_aInvalidation.setWidth(aSeq[2].toInt32());
m_aInvalidation.setHeight(aSeq[3].toInt32());
}
}
break;
}
}
void SwTiledRenderingTest::testRegisterCallback()
{
#ifdef MACOSX
// For some reason this particular test requires window system access on OS X.
// Without window system access, we do get a number of "<<<WARNING>>>
// AquaSalGraphics::CheckContext() FAILED!!!!" [sic] and " <Warning>: CGSConnectionByID: 0 is
// not a valid connection ID" warnings while running the other tests, too, but they still
// succeed.
if (!vcl::IsWindowSystemAvailable())
return;
#endif
SwXTextDocument* pXTextDocument = createDoc("dummy.fodt");
pXTextDocument->registerCallback(&SwTiledRenderingTest::callback, this);
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
// Insert a character at the beginning of the document.
pWrtShell->Insert("x");
// Check that the top left 256x256px tile would be invalidated.
CPPUNIT_ASSERT(!m_aInvalidation.IsEmpty());
#if !defined(WNT) && !defined(MACOSX)
Rectangle aTopLeft(0, 0, 256*15, 256*15); // 1 px = 15 twips, assuming 96 DPI.
// FIXME - fails on Windows since about cbd48230bb3a90c4c485fa33123c6653234e02e9
// [plus minus few commits maybe]
// Also on OS X. But is tiled rendering even supposed to work on Windows and OS X?
CPPUNIT_ASSERT(m_aInvalidation.IsOver(aTopLeft));
#endif
}
void SwTiledRenderingTest::testPostKeyEvent()
{
SwXTextDocument* pXTextDocument = createDoc("dummy.fodt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
pWrtShell->Right(CRSR_SKIP_CHARS, /*bSelect=*/false, 1, /*bBasicCall=*/false);
SwShellCrsr* pShellCrsr = pWrtShell->getShellCrsr(false);
// Did we manage to go after the first character?
CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(1), pShellCrsr->GetPoint()->nContent.GetIndex());
pXTextDocument->postKeyEvent(LOK_KEYEVENT_KEYINPUT, 'x', 0);
pXTextDocument->postKeyEvent(LOK_KEYEVENT_KEYUP, 'x', 0);
// Did we manage to insert the character after the first one?
CPPUNIT_ASSERT_EQUAL(OUString("Axaa bbb."), pShellCrsr->GetPoint()->nNode.GetNode().GetTextNode()->GetText());
}
void SwTiledRenderingTest::testPostMouseEvent()
{
SwXTextDocument* pXTextDocument = createDoc("dummy.fodt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
pWrtShell->Right(CRSR_SKIP_CHARS, /*bSelect=*/false, 1, /*bBasicCall=*/false);
SwShellCrsr* pShellCrsr = pWrtShell->getShellCrsr(false);
// Did we manage to go after the first character?
CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(1), pShellCrsr->GetPoint()->nContent.GetIndex());
Point aStart = pShellCrsr->GetSttPos();
aStart.setX(aStart.getX() - 1000);
pXTextDocument->postMouseEvent(LOK_MOUSEEVENT_MOUSEBUTTONDOWN, aStart.getX(), aStart.getY(), 1);
pXTextDocument->postMouseEvent(LOK_MOUSEEVENT_MOUSEBUTTONUP, aStart.getX(), aStart.getY(), 1);
// The new cursor position must be before the first word.
CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(0), pShellCrsr->GetPoint()->nContent.GetIndex());
}
void SwTiledRenderingTest::testSetTextSelection()
{
SwXTextDocument* pXTextDocument = createDoc("dummy.fodt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
// Move the cursor into the second word.
pWrtShell->Right(CRSR_SKIP_CHARS, /*bSelect=*/false, 5, /*bBasicCall=*/false);
// Create a selection by on the word.
pWrtShell->SelWrd();
SwShellCrsr* pShellCrsr = pWrtShell->getShellCrsr(false);
// Did we indeed manage to select the second word?
CPPUNIT_ASSERT_EQUAL(OUString("bbb"), pShellCrsr->GetText());
// Now use setTextSelection() to move the start of the selection 1000 twips left.
Point aStart = pShellCrsr->GetSttPos();
aStart.setX(aStart.getX() - 1000);
pXTextDocument->setTextSelection(LOK_SETTEXTSELECTION_START, aStart.getX(), aStart.getY());
// The new selection must include the first word, too -- but not the ending dot.
CPPUNIT_ASSERT_EQUAL(OUString("Aaa bbb"), pShellCrsr->GetText());
// Next: test that LOK_SETTEXTSELECTION_RESET + LOK_SETTEXTSELECTION_END can be used to create a selection.
pXTextDocument->setTextSelection(LOK_SETTEXTSELECTION_RESET, aStart.getX(), aStart.getY());
pXTextDocument->setTextSelection(LOK_SETTEXTSELECTION_END, aStart.getX() + 1000, aStart.getY());
CPPUNIT_ASSERT_EQUAL(OUString("Aaa b"), pShellCrsr->GetText());
}
void SwTiledRenderingTest::testSetGraphicSelection()
{
SwXTextDocument* pXTextDocument = createDoc("shape.fodt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
SdrPage* pPage = pWrtShell->GetDoc()->getIDocumentDrawModelAccess().GetDrawModel()->GetPage(0);
SdrObject* pObject = pPage->GetObj(0);
pWrtShell->SelectObj(Point(), 0, pObject);
// Make sure the rectangle has 8 handles: at each corner and at the center of each edge.
CPPUNIT_ASSERT_EQUAL(static_cast<sal_uInt32>(8), pObject->GetHdlCount());
// Take the bottom center one.
SdrHdl* pHdl = pObject->GetHdl(6);
CPPUNIT_ASSERT_EQUAL(HDL_LOWER, pHdl->GetKind());
Rectangle aShapeBefore = pObject->GetSnapRect();
// Resize.
pXTextDocument->setGraphicSelection(LOK_SETGRAPHICSELECTION_START, pHdl->GetPos().getX(), pHdl->GetPos().getY());
pXTextDocument->setGraphicSelection(LOK_SETGRAPHICSELECTION_END, pHdl->GetPos().getX(), pHdl->GetPos().getY() + 1000);
Rectangle aShapeAfter = pObject->GetSnapRect();
// Check that a resize happened, but aspect ratio is not kept.
CPPUNIT_ASSERT_EQUAL(aShapeBefore.getWidth(), aShapeAfter.getWidth());
#if !defined(MACOSX) // FIXME
CPPUNIT_ASSERT_EQUAL(aShapeBefore.getHeight() + 1000, aShapeAfter.getHeight());
#endif
}
void SwTiledRenderingTest::testResetSelection()
{
SwXTextDocument* pXTextDocument = createDoc("shape.fodt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
// Select one character.
pWrtShell->Right(CRSR_SKIP_CHARS, /*bSelect=*/true, 1, /*bBasicCall=*/false);
SwShellCrsr* pShellCrsr = pWrtShell->getShellCrsr(false);
// We have a text selection.
CPPUNIT_ASSERT(pShellCrsr->HasMark());
pXTextDocument->resetSelection();
// We no longer have a text selection.
CPPUNIT_ASSERT(!pShellCrsr->HasMark());
SdrPage* pPage = pWrtShell->GetDoc()->getIDocumentDrawModelAccess().GetDrawModel()->GetPage(0);
SdrObject* pObject = pPage->GetObj(0);
Point aPoint = pObject->GetSnapRect().Center();
// Select the shape.
pWrtShell->EnterSelFrmMode(&aPoint);
// We have a graphic selection.
CPPUNIT_ASSERT(pWrtShell->IsSelFrmMode());
pXTextDocument->resetSelection();
// We no longer have a graphic selection.
CPPUNIT_ASSERT(!pWrtShell->IsSelFrmMode());
}
void lcl_search()
{
uno::Sequence<beans::PropertyValue> aPropertyValues(comphelper::InitPropertySequence(
{
{"SearchItem.SearchString", uno::makeAny(OUString("shape"))},
{"SearchItem.Backward", uno::makeAny(false)}
}));
comphelper::dispatchCommand(".uno:ExecuteSearch", aPropertyValues);
}
void SwTiledRenderingTest::testSearch()
{
SwXTextDocument* pXTextDocument = createDoc("search.odt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
size_t nNode = pWrtShell->getShellCrsr(false)->Start()->nNode.GetNode().GetIndex();
// First hit, in the second paragraph, before the shape.
lcl_search();
CPPUNIT_ASSERT(!pWrtShell->GetDrawView()->GetTextEditObject());
size_t nActual = pWrtShell->getShellCrsr(false)->Start()->nNode.GetNode().GetIndex();
CPPUNIT_ASSERT_EQUAL(nNode + 1, nActual);
// Next hit, in the shape.
lcl_search();
CPPUNIT_ASSERT(pWrtShell->GetDrawView()->GetTextEditObject());
// Next hit, in the shape, still.
lcl_search();
CPPUNIT_ASSERT(pWrtShell->GetDrawView()->GetTextEditObject());
// Last hit, in the last paragraph, after the shape.
lcl_search();
CPPUNIT_ASSERT(!pWrtShell->GetDrawView()->GetTextEditObject());
nActual = pWrtShell->getShellCrsr(false)->Start()->nNode.GetNode().GetIndex();
CPPUNIT_ASSERT_EQUAL(nNode + 7, nActual);
}
CPPUNIT_TEST_SUITE_REGISTRATION(SwTiledRenderingTest);
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>CppunitTest_sw_tiledrendering: disable the search test on non-Linux for now<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 <swmodeltestbase.hxx>
#include <LibreOfficeKit/LibreOfficeKitEnums.h>
#include <comphelper/dispatchcommand.hxx>
#include <comphelper/propertysequence.hxx>
#include <comphelper/string.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdview.hxx>
#include <vcl/svapp.hxx>
#include <crsskip.hxx>
#include <drawdoc.hxx>
#include <ndtxt.hxx>
#include <wrtsh.hxx>
static const char* DATA_DIRECTORY = "/sw/qa/extras/tiledrendering/data/";
/// Testsuite for the SwXTextDocument methods implementing the vcl::ITiledRenderable interface.
class SwTiledRenderingTest : public SwModelTestBase
{
public:
void testRegisterCallback();
void testPostKeyEvent();
void testPostMouseEvent();
void testSetTextSelection();
void testSetGraphicSelection();
void testResetSelection();
void testSearch();
CPPUNIT_TEST_SUITE(SwTiledRenderingTest);
CPPUNIT_TEST(testRegisterCallback);
CPPUNIT_TEST(testPostKeyEvent);
CPPUNIT_TEST(testPostMouseEvent);
CPPUNIT_TEST(testSetTextSelection);
CPPUNIT_TEST(testSetGraphicSelection);
CPPUNIT_TEST(testResetSelection);
CPPUNIT_TEST(testSearch);
CPPUNIT_TEST_SUITE_END();
private:
SwXTextDocument* createDoc(const char* pName);
static void callback(int nType, const char* pPayload, void* pData);
void callbackImpl(int nType, const char* pPayload);
Rectangle m_aInvalidation;
};
SwXTextDocument* SwTiledRenderingTest::createDoc(const char* pName)
{
load(DATA_DIRECTORY, pName);
SwXTextDocument* pTextDocument = dynamic_cast<SwXTextDocument*>(mxComponent.get());
CPPUNIT_ASSERT(pTextDocument);
pTextDocument->initializeForTiledRendering();
return pTextDocument;
}
void SwTiledRenderingTest::callback(int nType, const char* pPayload, void* pData)
{
static_cast<SwTiledRenderingTest*>(pData)->callbackImpl(nType, pPayload);
}
void SwTiledRenderingTest::callbackImpl(int nType, const char* pPayload)
{
switch (nType)
{
case LOK_CALLBACK_INVALIDATE_TILES:
{
if (m_aInvalidation.IsEmpty())
{
uno::Sequence<OUString> aSeq = comphelper::string::convertCommaSeparated(OUString::createFromAscii(pPayload));
CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(4), aSeq.getLength());
m_aInvalidation.setX(aSeq[0].toInt32());
m_aInvalidation.setY(aSeq[1].toInt32());
m_aInvalidation.setWidth(aSeq[2].toInt32());
m_aInvalidation.setHeight(aSeq[3].toInt32());
}
}
break;
}
}
void SwTiledRenderingTest::testRegisterCallback()
{
#ifdef MACOSX
// For some reason this particular test requires window system access on OS X.
// Without window system access, we do get a number of "<<<WARNING>>>
// AquaSalGraphics::CheckContext() FAILED!!!!" [sic] and " <Warning>: CGSConnectionByID: 0 is
// not a valid connection ID" warnings while running the other tests, too, but they still
// succeed.
if (!vcl::IsWindowSystemAvailable())
return;
#endif
SwXTextDocument* pXTextDocument = createDoc("dummy.fodt");
pXTextDocument->registerCallback(&SwTiledRenderingTest::callback, this);
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
// Insert a character at the beginning of the document.
pWrtShell->Insert("x");
// Check that the top left 256x256px tile would be invalidated.
CPPUNIT_ASSERT(!m_aInvalidation.IsEmpty());
#if !defined(WNT) && !defined(MACOSX)
Rectangle aTopLeft(0, 0, 256*15, 256*15); // 1 px = 15 twips, assuming 96 DPI.
// FIXME - fails on Windows since about cbd48230bb3a90c4c485fa33123c6653234e02e9
// [plus minus few commits maybe]
// Also on OS X. But is tiled rendering even supposed to work on Windows and OS X?
CPPUNIT_ASSERT(m_aInvalidation.IsOver(aTopLeft));
#endif
}
void SwTiledRenderingTest::testPostKeyEvent()
{
SwXTextDocument* pXTextDocument = createDoc("dummy.fodt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
pWrtShell->Right(CRSR_SKIP_CHARS, /*bSelect=*/false, 1, /*bBasicCall=*/false);
SwShellCrsr* pShellCrsr = pWrtShell->getShellCrsr(false);
// Did we manage to go after the first character?
CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(1), pShellCrsr->GetPoint()->nContent.GetIndex());
pXTextDocument->postKeyEvent(LOK_KEYEVENT_KEYINPUT, 'x', 0);
pXTextDocument->postKeyEvent(LOK_KEYEVENT_KEYUP, 'x', 0);
// Did we manage to insert the character after the first one?
CPPUNIT_ASSERT_EQUAL(OUString("Axaa bbb."), pShellCrsr->GetPoint()->nNode.GetNode().GetTextNode()->GetText());
}
void SwTiledRenderingTest::testPostMouseEvent()
{
SwXTextDocument* pXTextDocument = createDoc("dummy.fodt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
pWrtShell->Right(CRSR_SKIP_CHARS, /*bSelect=*/false, 1, /*bBasicCall=*/false);
SwShellCrsr* pShellCrsr = pWrtShell->getShellCrsr(false);
// Did we manage to go after the first character?
CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(1), pShellCrsr->GetPoint()->nContent.GetIndex());
Point aStart = pShellCrsr->GetSttPos();
aStart.setX(aStart.getX() - 1000);
pXTextDocument->postMouseEvent(LOK_MOUSEEVENT_MOUSEBUTTONDOWN, aStart.getX(), aStart.getY(), 1);
pXTextDocument->postMouseEvent(LOK_MOUSEEVENT_MOUSEBUTTONUP, aStart.getX(), aStart.getY(), 1);
// The new cursor position must be before the first word.
CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(0), pShellCrsr->GetPoint()->nContent.GetIndex());
}
void SwTiledRenderingTest::testSetTextSelection()
{
SwXTextDocument* pXTextDocument = createDoc("dummy.fodt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
// Move the cursor into the second word.
pWrtShell->Right(CRSR_SKIP_CHARS, /*bSelect=*/false, 5, /*bBasicCall=*/false);
// Create a selection by on the word.
pWrtShell->SelWrd();
SwShellCrsr* pShellCrsr = pWrtShell->getShellCrsr(false);
// Did we indeed manage to select the second word?
CPPUNIT_ASSERT_EQUAL(OUString("bbb"), pShellCrsr->GetText());
// Now use setTextSelection() to move the start of the selection 1000 twips left.
Point aStart = pShellCrsr->GetSttPos();
aStart.setX(aStart.getX() - 1000);
pXTextDocument->setTextSelection(LOK_SETTEXTSELECTION_START, aStart.getX(), aStart.getY());
// The new selection must include the first word, too -- but not the ending dot.
CPPUNIT_ASSERT_EQUAL(OUString("Aaa bbb"), pShellCrsr->GetText());
// Next: test that LOK_SETTEXTSELECTION_RESET + LOK_SETTEXTSELECTION_END can be used to create a selection.
pXTextDocument->setTextSelection(LOK_SETTEXTSELECTION_RESET, aStart.getX(), aStart.getY());
pXTextDocument->setTextSelection(LOK_SETTEXTSELECTION_END, aStart.getX() + 1000, aStart.getY());
CPPUNIT_ASSERT_EQUAL(OUString("Aaa b"), pShellCrsr->GetText());
}
void SwTiledRenderingTest::testSetGraphicSelection()
{
SwXTextDocument* pXTextDocument = createDoc("shape.fodt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
SdrPage* pPage = pWrtShell->GetDoc()->getIDocumentDrawModelAccess().GetDrawModel()->GetPage(0);
SdrObject* pObject = pPage->GetObj(0);
pWrtShell->SelectObj(Point(), 0, pObject);
// Make sure the rectangle has 8 handles: at each corner and at the center of each edge.
CPPUNIT_ASSERT_EQUAL(static_cast<sal_uInt32>(8), pObject->GetHdlCount());
// Take the bottom center one.
SdrHdl* pHdl = pObject->GetHdl(6);
CPPUNIT_ASSERT_EQUAL(HDL_LOWER, pHdl->GetKind());
Rectangle aShapeBefore = pObject->GetSnapRect();
// Resize.
pXTextDocument->setGraphicSelection(LOK_SETGRAPHICSELECTION_START, pHdl->GetPos().getX(), pHdl->GetPos().getY());
pXTextDocument->setGraphicSelection(LOK_SETGRAPHICSELECTION_END, pHdl->GetPos().getX(), pHdl->GetPos().getY() + 1000);
Rectangle aShapeAfter = pObject->GetSnapRect();
// Check that a resize happened, but aspect ratio is not kept.
CPPUNIT_ASSERT_EQUAL(aShapeBefore.getWidth(), aShapeAfter.getWidth());
#if !defined(MACOSX) // FIXME
CPPUNIT_ASSERT_EQUAL(aShapeBefore.getHeight() + 1000, aShapeAfter.getHeight());
#endif
}
void SwTiledRenderingTest::testResetSelection()
{
SwXTextDocument* pXTextDocument = createDoc("shape.fodt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
// Select one character.
pWrtShell->Right(CRSR_SKIP_CHARS, /*bSelect=*/true, 1, /*bBasicCall=*/false);
SwShellCrsr* pShellCrsr = pWrtShell->getShellCrsr(false);
// We have a text selection.
CPPUNIT_ASSERT(pShellCrsr->HasMark());
pXTextDocument->resetSelection();
// We no longer have a text selection.
CPPUNIT_ASSERT(!pShellCrsr->HasMark());
SdrPage* pPage = pWrtShell->GetDoc()->getIDocumentDrawModelAccess().GetDrawModel()->GetPage(0);
SdrObject* pObject = pPage->GetObj(0);
Point aPoint = pObject->GetSnapRect().Center();
// Select the shape.
pWrtShell->EnterSelFrmMode(&aPoint);
// We have a graphic selection.
CPPUNIT_ASSERT(pWrtShell->IsSelFrmMode());
pXTextDocument->resetSelection();
// We no longer have a graphic selection.
CPPUNIT_ASSERT(!pWrtShell->IsSelFrmMode());
}
void lcl_search()
{
uno::Sequence<beans::PropertyValue> aPropertyValues(comphelper::InitPropertySequence(
{
{"SearchItem.SearchString", uno::makeAny(OUString("shape"))},
{"SearchItem.Backward", uno::makeAny(false)}
}));
comphelper::dispatchCommand(".uno:ExecuteSearch", aPropertyValues);
}
void SwTiledRenderingTest::testSearch()
{
#if !defined(WNT) && !defined(MACOSX)
SwXTextDocument* pXTextDocument = createDoc("search.odt");
SwWrtShell* pWrtShell = pXTextDocument->GetDocShell()->GetWrtShell();
size_t nNode = pWrtShell->getShellCrsr(false)->Start()->nNode.GetNode().GetIndex();
// First hit, in the second paragraph, before the shape.
lcl_search();
CPPUNIT_ASSERT(!pWrtShell->GetDrawView()->GetTextEditObject());
size_t nActual = pWrtShell->getShellCrsr(false)->Start()->nNode.GetNode().GetIndex();
CPPUNIT_ASSERT_EQUAL(nNode + 1, nActual);
// Next hit, in the shape.
lcl_search();
CPPUNIT_ASSERT(pWrtShell->GetDrawView()->GetTextEditObject());
// Next hit, in the shape, still.
lcl_search();
CPPUNIT_ASSERT(pWrtShell->GetDrawView()->GetTextEditObject());
// Last hit, in the last paragraph, after the shape.
lcl_search();
CPPUNIT_ASSERT(!pWrtShell->GetDrawView()->GetTextEditObject());
nActual = pWrtShell->getShellCrsr(false)->Start()->nNode.GetNode().GetIndex();
CPPUNIT_ASSERT_EQUAL(nNode + 7, nActual);
#endif
}
CPPUNIT_TEST_SUITE_REGISTRATION(SwTiledRenderingTest);
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow Authors. 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.
==============================================================================*/
#include "tensorflow/core/profiler/utils/group_events.h"
#include <stack>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_join.h"
#include "absl/types/optional.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/profiler/utils/tf_xplane_visitor.h"
#include "tensorflow/core/profiler/utils/xplane_schema.h"
#include "tensorflow/core/profiler/utils/xplane_utils.h"
namespace tensorflow {
namespace profiler {
namespace {
// Returns event type if it is a KernelLaunch or KernelExecute event.
absl::optional<int64> GetKernelEventType(const XPlaneVisitor& visitor,
const XEvent& event) {
bool found_correlation_id = false;
bool found_device_id = false;
for (const auto& stat : event.stats()) {
if (visitor.GetStatType(stat) == StatType::kCorrelationId) {
found_correlation_id = true;
} else if (visitor.GetStatType(stat) == StatType::kDeviceId) {
found_device_id = true;
}
}
if (found_correlation_id) {
return found_device_id ? HostEventType::kKernelLaunch
: HostEventType::kKernelExecute;
}
return absl::nullopt;
}
const XStat* GetStat(const XPlaneVisitor& visitor, const XEvent& event,
int64 stat_type) {
for (const auto& stat : event.stats()) {
if (visitor.GetStatType(stat) == stat_type) {
return &stat;
}
}
return nullptr;
}
void SetGroupId(const XPlaneVisitor& visitor, int64 group_id, XEvent* event) {
absl::optional<int64> maybe_group_id_stat_metadata_id =
visitor.GetStatMetadataId(StatType::kGroupId);
// TODO(jihochoi): Create stat metadata for group_id if not found.
if (maybe_group_id_stat_metadata_id) {
AddOrUpdateIntStat(*maybe_group_id_stat_metadata_id, group_id, event);
}
}
// Create EventNodeMap with the event types in connect_info_list and
// root_event_types.
EventNodeMap CreateEventNodeMap(
const std::vector<InterThreadConnectInfo>& connect_info_list,
const std::vector<int64>& root_event_types) {
EventNodeMap event_node_map;
for (const auto& connect_info : connect_info_list) {
event_node_map.try_emplace(connect_info.parent_event_type);
event_node_map.try_emplace(connect_info.child_event_type);
}
for (int64 event_type : root_event_types) {
event_node_map.try_emplace(event_type);
}
return event_node_map;
}
} // namespace
absl::optional<const XStat*> EventNode::GetContextStat(int64 stat_type) const {
if (const XStat* stat = GetStat(*visitor_, *event_, stat_type)) {
return stat;
} else if (parent_) {
return parent_->GetContextStat(stat_type);
}
return absl::nullopt;
}
std::string EventNode::GetGroupName() const {
std::vector<std::string> name_parts;
if (auto graph_type_stat = GetContextStat(StatType::kGraphType);
graph_type_stat.has_value()) {
name_parts.push_back((*graph_type_stat)->str_value());
}
int64 step_num = 0;
if (auto step_num_stat = GetContextStat(StatType::kStepNum);
step_num_stat.has_value()) {
step_num = (*step_num_stat)->int64_value();
}
if (auto iter_num_stat = GetContextStat(StatType::kIterNum);
iter_num_stat.has_value()) {
step_num += (*iter_num_stat)->int64_value();
}
name_parts.push_back(absl::StrCat(step_num));
return absl::StrJoin(name_parts, " ");
}
void EventNode::PropagateGroupId(int64 group_id) {
group_id_ = group_id;
SetGroupId(*visitor_, group_id, event_);
for (const auto& child : children_) {
child->PropagateGroupId(*group_id_);
}
}
void EventNode::AddStepName(absl::string_view step_name) {
AddOrUpdateStrStat(*visitor_->GetStatMetadataId(StatType::kStepName),
step_name, event_);
}
void ConnectIntraThread(const XPlaneVisitor& visitor, XPlane* host_trace,
EventNodeMap* event_node_map) {
for (auto& line : *host_trace->mutable_lines()) {
// absl::string_view thread_name = line.name();
std::stack<std::shared_ptr<EventNode>> parent_nodes;
for (auto& event : *line.mutable_events()) {
auto cur_node = std::make_shared<EventNode>(&visitor, &event);
while (!parent_nodes.empty()) {
std::shared_ptr<EventNode> parent_node = parent_nodes.top();
if (IsNested(cur_node->GetEvent(), parent_node->GetEvent())) {
parent_node->AddChild(cur_node);
cur_node->SetParent(parent_node.get());
break;
} else {
parent_nodes.pop();
}
}
parent_nodes.push(cur_node);
if (auto it = gtl::FindOrNull(
*event_node_map, visitor.GetEventType(event).value_or(
HostEventType::kUnknownHostEventType))) {
it->push_back(cur_node);
}
// KernelLaunch and KernelExecute event types are not supported by
// XPlaneVisitor and should be checked separately.
// TODO(148346217): Make XPlaneVisitor support KernelLaunch and
// KernelExecute event types.
if (event_node_map->contains(HostEventType::kKernelLaunch) ||
event_node_map->contains(HostEventType::kKernelExecute)) {
absl::optional<int64> kernel_event_type =
GetKernelEventType(visitor, event);
if (kernel_event_type) {
(*event_node_map)[*kernel_event_type].push_back(cur_node);
}
}
}
}
}
void ConnectInterThread(
const EventNodeMap& event_node_map,
const std::vector<InterThreadConnectInfo>& connect_info_list) {
for (const auto& connect_info : connect_info_list) {
absl::flat_hash_map<std::vector<int64>, std::shared_ptr<EventNode>>
connect_map;
const std::vector<int64>& stat_types = connect_info.stat_types;
if (auto parent_event_node_list =
gtl::FindOrNull(event_node_map, connect_info.parent_event_type)) {
for (const auto& parent_event_node : *parent_event_node_list) {
std::vector<int64> stats;
for (auto stat_type : stat_types) {
absl::optional<const XStat*> stat =
parent_event_node->GetContextStat(stat_type);
if (!stat) break;
stats.push_back((*stat)->value_case() == (*stat)->kInt64Value
? (*stat)->int64_value()
: (*stat)->uint64_value());
}
if (stats.size() == stat_types.size()) {
connect_map[stats] = parent_event_node;
}
}
}
if (auto child_event_node_list =
gtl::FindOrNull(event_node_map, connect_info.child_event_type)) {
for (const auto& child_event_node : *child_event_node_list) {
std::vector<int64> stats;
for (auto stat_type : stat_types) {
absl::optional<const XStat*> stat =
child_event_node->GetContextStat(stat_type);
if (!stat) break;
stats.push_back((*stat)->value_case() == (*stat)->kInt64Value
? (*stat)->int64_value()
: (*stat)->uint64_value());
}
if (stats.size() == stat_types.size()) {
if (auto parent_event_node = gtl::FindOrNull(connect_map, stats)) {
(*parent_event_node)->AddChild(child_event_node);
child_event_node->SetParent((*parent_event_node).get());
}
}
}
}
}
}
void CreateEventGroup(const std::vector<int64 /*EventType*/>& root_event_types,
const EventNodeMap& event_node_map,
EventGroupNameMap* event_group_name_map) {
int64 next_group_id = 0;
for (int64 root_event_type : root_event_types) {
if (auto root_event_node_list =
gtl::FindOrNull(event_node_map, root_event_type)) {
for (const auto& root_event_node : *root_event_node_list) {
// Skip if it already belongs to a group.
if (root_event_node->GetGroupId()) continue;
int64 group_id = next_group_id++;
root_event_node->PropagateGroupId(group_id);
(*event_group_name_map)[group_id] = root_event_node->GetGroupName();
// Add step_name stat if it is a TraceContext event.
// TODO(jihochoi): change event name instead.
if (root_event_type == HostEventType::kTraceContext) {
root_event_node->AddStepName((*event_group_name_map)[group_id]);
}
}
}
}
}
void GroupEvents(const std::vector<InterThreadConnectInfo>& connect_info_list,
const std::vector<int64>& root_event_types, XPlane* host_trace,
const std::vector<XPlane*>& device_traces,
EventGroupNameMap* event_group_name_map) {
if (!host_trace) return;
EventNodeMap event_node_map =
CreateEventNodeMap(connect_info_list, root_event_types);
XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(host_trace);
ConnectIntraThread(host_plane_visitor, host_trace, &event_node_map);
std::vector<XPlaneVisitor> device_plane_visitors;
device_plane_visitors.reserve(device_traces.size());
for (XPlane* device_trace : device_traces) {
device_plane_visitors.push_back(CreateTfXPlaneVisitor(device_trace));
ConnectIntraThread(device_plane_visitors.back(), device_trace,
&event_node_map);
}
ConnectInterThread(event_node_map, connect_info_list);
CreateEventGroup(root_event_types, event_node_map, event_group_name_map);
}
void GroupTfEvents(XPlane* host_trace,
const std::vector<XPlane*>& device_traces,
EventGroupNameMap* event_group_name_map) {
std::vector<InterThreadConnectInfo> connect_info_list(
{{HostEventType::kFunctionRun,
HostEventType::kExecutorStateProcess,
{StatType::kStepId}},
{HostEventType::kSessionRun,
HostEventType::kExecutorStateProcess,
{StatType::kStepId}},
{HostEventType::kKernelLaunch,
HostEventType::kKernelExecute,
{StatType::kCorrelationId}}});
const std::vector<int64 /*EventType*/> root_event_types(
{HostEventType::kTraceContext, HostEventType::kFunctionRun,
HostEventType::kSessionRun});
GroupEvents(connect_info_list, root_event_types, host_trace, device_traces,
event_group_name_map);
}
} // namespace profiler
} // namespace tensorflow
<commit_msg>Fix ROCM build.<commit_after>/* Copyright 2020 The TensorFlow Authors. 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.
==============================================================================*/
#include "tensorflow/core/profiler/utils/group_events.h"
#include <stack>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_join.h"
#include "absl/types/optional.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/profiler/utils/tf_xplane_visitor.h"
#include "tensorflow/core/profiler/utils/xplane_schema.h"
#include "tensorflow/core/profiler/utils/xplane_utils.h"
namespace tensorflow {
namespace profiler {
namespace {
// Returns event type if it is a KernelLaunch or KernelExecute event.
absl::optional<int64> GetKernelEventType(const XPlaneVisitor& visitor,
const XEvent& event) {
bool found_correlation_id = false;
bool found_device_id = false;
for (const auto& stat : event.stats()) {
if (visitor.GetStatType(stat) == StatType::kCorrelationId) {
found_correlation_id = true;
} else if (visitor.GetStatType(stat) == StatType::kDeviceId) {
found_device_id = true;
}
}
if (found_correlation_id) {
return found_device_id ? HostEventType::kKernelLaunch
: HostEventType::kKernelExecute;
}
return absl::nullopt;
}
const XStat* GetStat(const XPlaneVisitor& visitor, const XEvent& event,
int64 stat_type) {
for (const auto& stat : event.stats()) {
if (visitor.GetStatType(stat) == stat_type) {
return &stat;
}
}
return nullptr;
}
void SetGroupId(const XPlaneVisitor& visitor, int64 group_id, XEvent* event) {
absl::optional<int64> maybe_group_id_stat_metadata_id =
visitor.GetStatMetadataId(StatType::kGroupId);
// TODO(jihochoi): Create stat metadata for group_id if not found.
if (maybe_group_id_stat_metadata_id) {
AddOrUpdateIntStat(*maybe_group_id_stat_metadata_id, group_id, event);
}
}
// Create EventNodeMap with the event types in connect_info_list and
// root_event_types.
EventNodeMap CreateEventNodeMap(
const std::vector<InterThreadConnectInfo>& connect_info_list,
const std::vector<int64>& root_event_types) {
EventNodeMap event_node_map;
for (const auto& connect_info : connect_info_list) {
event_node_map.try_emplace(connect_info.parent_event_type);
event_node_map.try_emplace(connect_info.child_event_type);
}
for (int64 event_type : root_event_types) {
event_node_map.try_emplace(event_type);
}
return event_node_map;
}
} // namespace
absl::optional<const XStat*> EventNode::GetContextStat(int64 stat_type) const {
if (const XStat* stat = GetStat(*visitor_, *event_, stat_type)) {
return stat;
} else if (parent_) {
return parent_->GetContextStat(stat_type);
}
return absl::nullopt;
}
std::string EventNode::GetGroupName() const {
std::vector<std::string> name_parts;
if (auto graph_type_stat = GetContextStat(StatType::kGraphType)) {
name_parts.push_back((*graph_type_stat)->str_value());
}
int64 step_num = 0;
if (auto step_num_stat = GetContextStat(StatType::kStepNum)) {
step_num = (*step_num_stat)->int64_value();
}
if (auto iter_num_stat = GetContextStat(StatType::kIterNum)) {
step_num += (*iter_num_stat)->int64_value();
}
name_parts.push_back(absl::StrCat(step_num));
return absl::StrJoin(name_parts, " ");
}
void EventNode::PropagateGroupId(int64 group_id) {
group_id_ = group_id;
SetGroupId(*visitor_, group_id, event_);
for (const auto& child : children_) {
child->PropagateGroupId(*group_id_);
}
}
void EventNode::AddStepName(absl::string_view step_name) {
AddOrUpdateStrStat(*visitor_->GetStatMetadataId(StatType::kStepName),
step_name, event_);
}
void ConnectIntraThread(const XPlaneVisitor& visitor, XPlane* host_trace,
EventNodeMap* event_node_map) {
for (auto& line : *host_trace->mutable_lines()) {
// absl::string_view thread_name = line.name();
std::stack<std::shared_ptr<EventNode>> parent_nodes;
for (auto& event : *line.mutable_events()) {
auto cur_node = std::make_shared<EventNode>(&visitor, &event);
while (!parent_nodes.empty()) {
std::shared_ptr<EventNode> parent_node = parent_nodes.top();
if (IsNested(cur_node->GetEvent(), parent_node->GetEvent())) {
parent_node->AddChild(cur_node);
cur_node->SetParent(parent_node.get());
break;
} else {
parent_nodes.pop();
}
}
parent_nodes.push(cur_node);
if (auto it = gtl::FindOrNull(
*event_node_map, visitor.GetEventType(event).value_or(
HostEventType::kUnknownHostEventType))) {
it->push_back(cur_node);
}
// KernelLaunch and KernelExecute event types are not supported by
// XPlaneVisitor and should be checked separately.
// TODO(148346217): Make XPlaneVisitor support KernelLaunch and
// KernelExecute event types.
if (event_node_map->contains(HostEventType::kKernelLaunch) ||
event_node_map->contains(HostEventType::kKernelExecute)) {
absl::optional<int64> kernel_event_type =
GetKernelEventType(visitor, event);
if (kernel_event_type) {
(*event_node_map)[*kernel_event_type].push_back(cur_node);
}
}
}
}
}
void ConnectInterThread(
const EventNodeMap& event_node_map,
const std::vector<InterThreadConnectInfo>& connect_info_list) {
for (const auto& connect_info : connect_info_list) {
absl::flat_hash_map<std::vector<int64>, std::shared_ptr<EventNode>>
connect_map;
const std::vector<int64>& stat_types = connect_info.stat_types;
if (auto parent_event_node_list =
gtl::FindOrNull(event_node_map, connect_info.parent_event_type)) {
for (const auto& parent_event_node : *parent_event_node_list) {
std::vector<int64> stats;
for (auto stat_type : stat_types) {
absl::optional<const XStat*> stat =
parent_event_node->GetContextStat(stat_type);
if (!stat) break;
stats.push_back((*stat)->value_case() == (*stat)->kInt64Value
? (*stat)->int64_value()
: (*stat)->uint64_value());
}
if (stats.size() == stat_types.size()) {
connect_map[stats] = parent_event_node;
}
}
}
if (auto child_event_node_list =
gtl::FindOrNull(event_node_map, connect_info.child_event_type)) {
for (const auto& child_event_node : *child_event_node_list) {
std::vector<int64> stats;
for (auto stat_type : stat_types) {
absl::optional<const XStat*> stat =
child_event_node->GetContextStat(stat_type);
if (!stat) break;
stats.push_back((*stat)->value_case() == (*stat)->kInt64Value
? (*stat)->int64_value()
: (*stat)->uint64_value());
}
if (stats.size() == stat_types.size()) {
if (auto parent_event_node = gtl::FindOrNull(connect_map, stats)) {
(*parent_event_node)->AddChild(child_event_node);
child_event_node->SetParent((*parent_event_node).get());
}
}
}
}
}
}
void CreateEventGroup(const std::vector<int64 /*EventType*/>& root_event_types,
const EventNodeMap& event_node_map,
EventGroupNameMap* event_group_name_map) {
int64 next_group_id = 0;
for (int64 root_event_type : root_event_types) {
if (auto root_event_node_list =
gtl::FindOrNull(event_node_map, root_event_type)) {
for (const auto& root_event_node : *root_event_node_list) {
// Skip if it already belongs to a group.
if (root_event_node->GetGroupId()) continue;
int64 group_id = next_group_id++;
root_event_node->PropagateGroupId(group_id);
(*event_group_name_map)[group_id] = root_event_node->GetGroupName();
// Add step_name stat if it is a TraceContext event.
// TODO(jihochoi): change event name instead.
if (root_event_type == HostEventType::kTraceContext) {
root_event_node->AddStepName((*event_group_name_map)[group_id]);
}
}
}
}
}
void GroupEvents(const std::vector<InterThreadConnectInfo>& connect_info_list,
const std::vector<int64>& root_event_types, XPlane* host_trace,
const std::vector<XPlane*>& device_traces,
EventGroupNameMap* event_group_name_map) {
if (!host_trace) return;
EventNodeMap event_node_map =
CreateEventNodeMap(connect_info_list, root_event_types);
XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(host_trace);
ConnectIntraThread(host_plane_visitor, host_trace, &event_node_map);
std::vector<XPlaneVisitor> device_plane_visitors;
device_plane_visitors.reserve(device_traces.size());
for (XPlane* device_trace : device_traces) {
device_plane_visitors.push_back(CreateTfXPlaneVisitor(device_trace));
ConnectIntraThread(device_plane_visitors.back(), device_trace,
&event_node_map);
}
ConnectInterThread(event_node_map, connect_info_list);
CreateEventGroup(root_event_types, event_node_map, event_group_name_map);
}
void GroupTfEvents(XPlane* host_trace,
const std::vector<XPlane*>& device_traces,
EventGroupNameMap* event_group_name_map) {
std::vector<InterThreadConnectInfo> connect_info_list(
{{HostEventType::kFunctionRun,
HostEventType::kExecutorStateProcess,
{StatType::kStepId}},
{HostEventType::kSessionRun,
HostEventType::kExecutorStateProcess,
{StatType::kStepId}},
{HostEventType::kKernelLaunch,
HostEventType::kKernelExecute,
{StatType::kCorrelationId}}});
const std::vector<int64 /*EventType*/> root_event_types(
{HostEventType::kTraceContext, HostEventType::kFunctionRun,
HostEventType::kSessionRun});
GroupEvents(connect_info_list, root_event_types, host_trace, device_traces,
event_group_name_map);
}
} // namespace profiler
} // namespace tensorflow
<|endoftext|> |
<commit_before>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>
#include "models/sagtension/cable_elongation_model.h"
#include "gtest/gtest.h"
#include "factory.h"
#include "models/base/helper.h"
class CableElongationModelTest : public ::testing::Test {
protected:
CableElongationModelTest() {
// builds dependency object - cable
SagTensionCable* cable = factory::BuildSagTensionCable();
// builds dependency object - state
CableState* state = new CableState();
state->load_stretch = 12000;
state->temperature = 70;
state->temperature_stretch = 0;
state->type_polynomial =
SagTensionCableComponent::PolynomialType::kLoadStrain;
// builds fixture object
c_.set_cable(cable);
c_.set_state(state);
}
CableElongationModel c_;
};
TEST_F(CableElongationModelTest, Load) {
double value = -999999;
// core
value = c_.Load(CableElongationModel::ComponentType::kCore, 0.002);
EXPECT_EQ(5433.5, helper::Round(value, 1));
// shell
value = c_.Load(CableElongationModel::ComponentType::kShell, 0.002);
EXPECT_EQ(3754.9, helper::Round(value, 1));
// combined
value = c_.Load(CableElongationModel::ComponentType::kCombined, 0.002);
EXPECT_EQ(9188.4, helper::Round(value, 1));
}
TEST_F(CableElongationModelTest, Slope) {
double value = -999999;
// core
value = c_.Slope(CableElongationModel::ComponentType::kCore, 0.002);
EXPECT_EQ(2687680, helper::Round(value, 0));
// shell
value = c_.Slope(CableElongationModel::ComponentType::kShell, 0.002);
EXPECT_EQ(4648960, helper::Round(value, 0));
// combined
value = c_.Slope(CableElongationModel::ComponentType::kCombined, 0.002);
EXPECT_EQ(7336640, helper::Round(value, 0));
}
TEST_F(CableElongationModelTest, Strain) {
double value = -999999;
// core
value = c_.Strain(CableElongationModel::ComponentType::kCore, 5433.5);
EXPECT_EQ(0.002, helper::Round(value, 3));
// shell
value = c_.Strain(CableElongationModel::ComponentType::kShell, 3754.9);
EXPECT_EQ(0.002, helper::Round(value, 3));
// combined
value = c_.Strain(CableElongationModel::ComponentType::kCombined, 0);
EXPECT_EQ(0.0001, helper::Round(value, 4));
value = c_.Strain(CableElongationModel::ComponentType::kCombined, 9188.4);
EXPECT_EQ(0.002, helper::Round(value, 3));
}
TEST_F(CableElongationModelTest, Validate) {
EXPECT_TRUE(c_.Validate(false, nullptr));
}
<commit_msg>Fix for Strain test. Corrected zero load strain value.<commit_after>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>
#include "models/sagtension/cable_elongation_model.h"
#include "gtest/gtest.h"
#include "factory.h"
#include "models/base/helper.h"
class CableElongationModelTest : public ::testing::Test {
protected:
CableElongationModelTest() {
// builds dependency object - cable
SagTensionCable* cable = factory::BuildSagTensionCable();
// builds dependency object - state
CableState* state = new CableState();
state->load_stretch = 12000;
state->temperature = 70;
state->temperature_stretch = 0;
state->type_polynomial =
SagTensionCableComponent::PolynomialType::kLoadStrain;
// builds fixture object
c_.set_cable(cable);
c_.set_state(state);
}
CableElongationModel c_;
};
TEST_F(CableElongationModelTest, Load) {
double value = -999999;
// core
value = c_.Load(CableElongationModel::ComponentType::kCore, 0.002);
EXPECT_EQ(5433.5, helper::Round(value, 1));
// shell
value = c_.Load(CableElongationModel::ComponentType::kShell, 0.002);
EXPECT_EQ(3754.9, helper::Round(value, 1));
// combined
value = c_.Load(CableElongationModel::ComponentType::kCombined, 0.002);
EXPECT_EQ(9188.4, helper::Round(value, 1));
}
TEST_F(CableElongationModelTest, Slope) {
double value = -999999;
// core
value = c_.Slope(CableElongationModel::ComponentType::kCore, 0.002);
EXPECT_EQ(2687680, helper::Round(value, 0));
// shell
value = c_.Slope(CableElongationModel::ComponentType::kShell, 0.002);
EXPECT_EQ(4648960, helper::Round(value, 0));
// combined
value = c_.Slope(CableElongationModel::ComponentType::kCombined, 0.002);
EXPECT_EQ(7336640, helper::Round(value, 0));
}
TEST_F(CableElongationModelTest, Strain) {
double value = -999999;
// core
value = c_.Strain(CableElongationModel::ComponentType::kCore, 5433.5);
EXPECT_EQ(0.002, helper::Round(value, 3));
// shell
value = c_.Strain(CableElongationModel::ComponentType::kShell, 3754.9);
EXPECT_EQ(0.002, helper::Round(value, 3));
// combined
value = c_.Strain(CableElongationModel::ComponentType::kCombined, 0);
EXPECT_EQ(0.000026, helper::Round(value, 6));
value = c_.Strain(CableElongationModel::ComponentType::kCombined, 9188.4);
EXPECT_EQ(0.002, helper::Round(value, 3));
}
TEST_F(CableElongationModelTest, Validate) {
EXPECT_TRUE(c_.Validate(false, nullptr));
}
<|endoftext|> |
<commit_before>/****************************************************************
* Servo *
* read joystick data, normalize, write to servo *
* *
* known issues: if it won't work, open serial monitor then try *
* *
* @author: Navid Kalaei <[email protected]> *
* @github: @navid-kalaei *
* @license: MIT *
****************************************************************/
#include "Arduino.h"
#include "Servo.h"
#include "custom_joystick.h"
// time to wait in millis
#define DELAY_TIME 200
#define SERIAL_RATE 9600
#define JOY_PIN_X 0
#define JOY_PIN_Y 1
#define SERVO_PIN 9
// servo can turn from 0 to 180 so it's origin is 90
#define SERVO_ORIGIN 90
custom_joystick joy;
Servo myServo;
int myServoPos = 0;
void setup(){
joy.attach_pin_x(JOY_PIN_X);
joy.attach_pin_y(JOY_PIN_Y);
joy.calibrate();
myServo.attach(SERVO_PIN);
// wait until Serail is not available
// while(!Serial);
// Serial.begin(SERIAL_RATE);
}
void loop(){
myServoPos = joy.get_calibrated_x() + SERVO_ORIGIN;
myServo.write(myServoPos);
//Serial.println(myServoPos);
//delay(DELAY_TIME);
}
<commit_msg>update docstring servo/main.cpp<commit_after>/*****************************************************************
* Servo *
* read joystick data, normalize, write to servo *
* *
* @author: Navid Kalaei <[email protected]> *
* @github: @navid-kalaei *
* @license: MIT *
*****************************************************************/
#include "Arduino.h"
#include "Servo.h"
#include "custom_joystick.h"
// time to wait in millis
#define DELAY_TIME 200
#define SERIAL_RATE 9600
#define JOY_PIN_X 0
#define JOY_PIN_Y 1
#define SERVO_PIN 9
// servo can turn from 0 to 180 so it's origin is 90
#define SERVO_ORIGIN 90
custom_joystick joy;
Servo myServo;
int myServoPos = 0;
void setup(){
joy.attach_pin_x(JOY_PIN_X);
joy.attach_pin_y(JOY_PIN_Y);
joy.calibrate();
myServo.attach(SERVO_PIN);
// wait until Serail is not available
// while(!Serial);
// Serial.begin(SERIAL_RATE);
}
void loop(){
myServoPos = joy.get_calibrated_x() + SERVO_ORIGIN;
myServo.write(myServoPos);
//Serial.println(myServoPos);
//delay(DELAY_TIME);
}
<|endoftext|> |
<commit_before>/*
* 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 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012-2013 Heiko Strathmann
*/
#include <shogun/mathematics/Statistics.h>
#include <shogun/features/streaming/generators/GaussianBlobsDataGenerator.h>
#include <shogun/features/streaming/generators/MeanShiftDataGenerator.h>
#include <gtest/gtest.h>
using namespace shogun;
TEST(GaussianBlobsDataGenerator,get_next_example)
{
index_t num_blobs=1;
float64_t distance=3;
float64_t epsilon=2;
float64_t angle=CMath::PI/4;
index_t num_samples=10000;
CGaussianBlobsDataGenerator* gen=new CGaussianBlobsDataGenerator(num_blobs,
distance, epsilon, angle);
/* two dimensional samples */
SGMatrix<float64_t> samples(2, num_samples);
for (index_t i=0; i<num_samples; ++i)
{
gen->get_next_example();
SGVector<float64_t> sample=gen->get_vector();
samples(0,i)=sample[0];
samples(1,i)=sample[1];
gen->release_example();
}
SGVector<float64_t> mean=CStatistics::matrix_mean(samples, false);
SGMatrix<float64_t>::transpose_matrix(samples.matrix, samples.num_rows,
samples.num_cols);
#ifdef HAVE_LAPACK
SGMatrix<float64_t> cov=CStatistics::covariance_matrix(samples);
#endif // HAVE_LAPACK
//mean.display_vector("mean");
//cov.display_matrix("cov");
/* rougly ensures right results, set to 0.3 for now, if test fails, set a
* bit larger */
float64_t accuracy=0.5;
/* matrix is expected to look like [1.5, 0.5; 0.5, 1.5] */
#ifdef HAVE_LAPACK
EXPECT_LE(CMath::abs(cov(0,0)-1.5), accuracy);
EXPECT_LE(CMath::abs(cov(0,1)-0.5), accuracy);
EXPECT_LE(CMath::abs(cov(1,0)-0.5), accuracy);
EXPECT_LE(CMath::abs(cov(1,1)-1.5), accuracy);
#endif // HAVE_LAPACK
/* mean is supposed to do [0, 0] */
EXPECT_LE(CMath::abs(mean[0]-0), 0.1);
EXPECT_LE(CMath::abs(mean[1]-0), 0.1);
/* and another one */
SGMatrix<float64_t> samples2(2, num_samples);
num_blobs=3;
gen->set_blobs_model(num_blobs, distance, epsilon, angle);
for (index_t i=0; i<num_samples; ++i)
{
gen->get_next_example();
SGVector<float64_t> sample=gen->get_vector();
samples2(0,i)=sample[0];
samples2(1,i)=sample[1];
gen->release_example();
}
SGVector<float64_t> mean2=CStatistics::matrix_mean(samples2, false);
SGMatrix<float64_t>::transpose_matrix(samples2.matrix, samples2.num_rows,
samples2.num_cols);
#ifdef HAVE_LAPACK
SGMatrix<float64_t> cov2=CStatistics::covariance_matrix(samples2);
#endif // HAVE_LAPACK
//mean2.display_vector("mean2");
//cov2.display_matrix("cov2");
/* matrix is expected to look like [7.55, 0.55; 0.55, 7.55] */
#ifdef HAVE_LAPACK
EXPECT_LE(CMath::abs(cov2(0,0)-7.55), accuracy);
EXPECT_LE(CMath::abs(cov2(0,1)-0.55), accuracy);
EXPECT_LE(CMath::abs(cov2(1,0)-0.55), accuracy);
EXPECT_LE(CMath::abs(cov2(1,1)-7.55), accuracy);
#endif // HAVE_LAPACK
/* mean is supposed to do [3, 3] */
EXPECT_LE(CMath::abs(mean2[0]-3), accuracy);
EXPECT_LE(CMath::abs(mean2[1]-3), accuracy);
SG_UNREF(gen);
}
TEST(MeanShiftDataGenerator,get_next_example)
{
index_t dimension=3;
index_t mean_shift=100;
index_t num_runs=1000;
CMeanShiftDataGenerator* gen=new CMeanShiftDataGenerator(mean_shift,
dimension, 0);
SGVector<float64_t> avg(dimension);
avg.zero();
for (index_t i=0; i<num_runs; ++i)
{
gen->get_next_example();
avg.add(gen->get_vector());
gen->release_example();
}
/* average */
avg.scale(1.0/num_runs);
//avg.display_vector("mean_shift");
/* roughly assert correct model parameters */
EXPECT_LE(avg[0]-mean_shift, mean_shift/100);
for (index_t i=1; i<dimension; ++i)
{
EXPECT_LE(avg[i], 0.5);
EXPECT_GE(avg[i], -0.5);
}
/* draw whole matrix and test that too */
CDenseFeatures<float64_t>* features=
(CDenseFeatures<float64_t>*)gen->get_streamed_features(num_runs);
avg=SGVector<float64_t>(dimension);
for (index_t i=0; i<dimension; ++i)
{
float64_t sum=0;
for (index_t j=0; j<num_runs; ++j)
sum+=features->get_feature_matrix()(i, j);
avg[i]=sum/num_runs;
}
//avg.display_vector("mean_shift");
ASSERT(avg[0]-mean_shift<mean_shift/100);
for (index_t i=1; i<dimension; ++i)
ASSERT(avg[i]<0.5 && avg[i]>-0.5);
SG_UNREF(features);
SG_UNREF(gen);
}
<commit_msg>fix GaussianBlob unit test broken due to wrong covariance matrix interpretation<commit_after>/*
* 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 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012-2013 Heiko Strathmann
*/
#include <shogun/mathematics/Statistics.h>
#include <shogun/features/streaming/generators/GaussianBlobsDataGenerator.h>
#include <shogun/features/streaming/generators/MeanShiftDataGenerator.h>
#include <gtest/gtest.h>
using namespace shogun;
TEST(GaussianBlobsDataGenerator,get_next_example1)
{
index_t num_blobs=1;
float64_t distance=3;
float64_t epsilon=2;
float64_t angle=CMath::PI/4;
index_t num_samples=10000;
CGaussianBlobsDataGenerator* gen=new CGaussianBlobsDataGenerator(num_blobs,
distance, epsilon, angle);
/* two dimensional samples */
SGMatrix<float64_t> samples(2, num_samples);
for (index_t i=0; i<num_samples; ++i)
{
gen->get_next_example();
SGVector<float64_t> sample=gen->get_vector();
samples(0,i)=sample[0];
samples(1,i)=sample[1];
gen->release_example();
}
SGVector<float64_t> mean=CStatistics::matrix_mean(samples, false);
SGMatrix<float64_t> cov=CStatistics::covariance_matrix(samples);
/* rougly ensures right results, if test fails, set a bit larger */
float64_t accuracy=1e-1;
/* matrix is expected to look like [1.5, 0.5; 0.5, 1.5] */
EXPECT_NEAR(cov(0,0), 1.5, accuracy);
EXPECT_NEAR(cov(0,1), 0.5, accuracy);
EXPECT_NEAR(cov(1,0), 0.5, accuracy);
EXPECT_NEAR(cov(1,1), 1.5, accuracy);
/* mean is supposed to do [0, 0] */
EXPECT_LE(CMath::abs(mean[0]-0), 0.1);
EXPECT_LE(CMath::abs(mean[1]-0), 0.1);
SG_UNREF(gen);
}
TEST(GaussianBlobsDataGenerator,get_next_example2)
{
index_t num_blobs=3;
float64_t distance=3;
float64_t epsilon=2;
float64_t angle=CMath::PI/4;
index_t num_samples=50000;
CGaussianBlobsDataGenerator* gen=new CGaussianBlobsDataGenerator(num_blobs,
distance, epsilon, angle);
/* and another one */
SGMatrix<float64_t> samples2(2, num_samples);
gen->set_blobs_model(num_blobs, distance, epsilon, angle);
for (index_t i=0; i<num_samples; ++i)
{
gen->get_next_example();
SGVector<float64_t> sample=gen->get_vector();
samples2(0,i)=sample[0];
samples2(1,i)=sample[1];
gen->release_example();
}
SGVector<float64_t> mean2=CStatistics::matrix_mean(samples2, false);
SGMatrix<float64_t> cov2=CStatistics::covariance_matrix(samples2);
/* rougly ensures right results, if test fails, set a bit larger */
float64_t accuracy=1e-1;
/* matrix is expected to look like [7.55, 0.55; 0.55, 7.55] */
EXPECT_NEAR(cov2(0,0), 7.55, accuracy);
EXPECT_NEAR(cov2(0,1), 0.55, accuracy);
EXPECT_NEAR(cov2(1,0), 0.55, accuracy);
EXPECT_NEAR(cov2(1,1), 7.55, accuracy);
/* mean is supposed to do [3, 3] */
EXPECT_LE(CMath::abs(mean2[0]-3), accuracy);
EXPECT_LE(CMath::abs(mean2[1]-3), accuracy);
SG_UNREF(gen);
}
TEST(MeanShiftDataGenerator,get_next_example)
{
index_t dimension=3;
index_t mean_shift=100;
index_t num_runs=1000;
CMeanShiftDataGenerator* gen=new CMeanShiftDataGenerator(mean_shift,
dimension, 0);
SGVector<float64_t> avg(dimension);
avg.zero();
for (index_t i=0; i<num_runs; ++i)
{
gen->get_next_example();
avg.add(gen->get_vector());
gen->release_example();
}
/* average */
avg.scale(1.0/num_runs);
//avg.display_vector("mean_shift");
/* roughly assert correct model parameters */
EXPECT_LE(avg[0]-mean_shift, mean_shift/100);
for (index_t i=1; i<dimension; ++i)
{
EXPECT_LE(avg[i], 0.5);
EXPECT_GE(avg[i], -0.5);
}
/* draw whole matrix and test that too */
CDenseFeatures<float64_t>* features=
(CDenseFeatures<float64_t>*)gen->get_streamed_features(num_runs);
avg=SGVector<float64_t>(dimension);
for (index_t i=0; i<dimension; ++i)
{
float64_t sum=0;
for (index_t j=0; j<num_runs; ++j)
sum+=features->get_feature_matrix()(i, j);
avg[i]=sum/num_runs;
}
//avg.display_vector("mean_shift");
ASSERT(avg[0]-mean_shift<mean_shift/100);
for (index_t i=1; i<dimension; ++i)
ASSERT(avg[i]<0.5 && avg[i]>-0.5);
SG_UNREF(features);
SG_UNREF(gen);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.