text
stringlengths 54
60.6k
|
---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: objshimp.hxx,v $
*
* $Revision: 1.41 $
*
* last change: $Author: obo $ $Date: 2008-02-26 15:12:13 $
*
* 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 _SFX_OBJSHIMP_HXX
#define _SFX_OBJSHIMP_HXX
//#include <hash_map>
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#include <svtools/securityoptions.hxx>
#include <sfx2/objsh.hxx>
#include "sfx2/docmacromode.hxx"
#include "bitset.hxx"
namespace svtools { class AsynchronLink; }
//====================================================================
DBG_NAMEEX(SfxObjectShell)
class SfxViewFrame;
struct MarkData_Impl
{
String aMark;
String aUserData;
SfxViewFrame* pFrame;
};
class SfxFrame;
class SfxToolBoxConfig;
class SfxAcceleratorManager;
class SfxBasicManagerHolder;
struct SfxObjectShell_Impl : public ::sfx2::IMacroDocumentAccess
{
::comphelper::EmbeddedObjectContainer* mpObjectContainer;
SfxAcceleratorManager* pAccMgr;
SfxConfigManager* pCfgMgr;
SfxBasicManagerHolder*
pBasicManager;
SfxObjectShell& rDocShell;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xBasicLibraries;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xDialogLibraries;
::sfx2::DocumentMacroMode
aMacroMode;
SfxProgress* pProgress;
String aTitle;
String aTempName;
DateTime nTime;
sal_uInt16 nVisualDocumentNumber;
sal_Int16 nDocumentSignatureState;
sal_Int16 nScriptingSignatureState;
sal_Bool bTemplateConfig:1,
bInList:1, // ob per First/Next erreichbar
bClosing:1, // sal_True w"aehrend Close(), um Benachrichtigungs-Rekursionen zu verhindern
bSetInPlaceObj:1, // sal_True, falls bereits versucht wurde pInPlaceObject zu casten
bIsSaving:1,
bPasswd:1,
bIsTmp:1,
bIsNamedVisible:1,
bIsTemplate:1,
bIsAbortingImport:1, // Importvorgang soll abgebrochen werden.
bImportDone : 1, //Import schon fertig? Fuer AutoReload von Docs.
bInPrepareClose : 1,
bPreparedForClose : 1,
bWaitingForPicklist : 1,// Muss noch in die Pickliste
bModuleSearched : 1,
bIsBasicDefault : 1,
bIsHelpObjSh : 1,
bForbidCaching : 1,
bForbidReload : 1,
bSupportsEventMacros: 1,
bLoadingWindows: 1,
bBasicInitialized :1,
//bHidden :1, // indicates a hidden view shell
bIsPrintJobCancelable :1, // Stampit disable/enable cancel button for print jobs ... default = true = enable!
bOwnsStorage:1,
bNoBaseURL:1,
bInitialized:1,
bSignatureErrorIsShown:1,
bModelInitialized:1, // whether the related model is initialized
bPreserveVersions:1,
m_bMacroSignBroken:1, // whether the macro signature was explicitly broken
m_bNoBasicCapabilities:1,
bQueryLoadTemplate:1,
bLoadReadonly:1,
bUseUserData:1,
bSaveVersionOnClose:1;
String aNewName; // Der Name, unter dem das Doc gespeichert
// werden soll
IndexBitSet aBitSet;
sal_uInt32 lErr;
sal_uInt16 nEventId; // falls vor Activate noch ein
// Open/Create gesendet werden mu/s
sal_Bool bDoNotTouchDocInfo;
AutoReloadTimer_Impl *pReloadTimer;
MarkData_Impl* pMarkData;
sal_uInt16 nLoadedFlags;
sal_uInt16 nFlagsInProgress;
String aMark;
Size aViewSize; // wird leider vom Writer beim
sal_Bool bInFrame; // HTML-Import gebraucht
sal_Bool bModalMode;
sal_Bool bRunningMacro;
sal_Bool bReloadAvailable;
sal_uInt16 nAutoLoadLocks;
SfxModule* pModule;
SfxFrame* pFrame;
SfxToolBoxConfig* pTbxConfig;
SfxEventConfigItem_Impl* pEventConfig;
SfxObjectShellFlags eFlags;
svtools::AsynchronLink* pCloser;
String aBaseURL;
sal_Bool bReadOnlyUI;
SvRefBaseRef xHeaderAttributes;
sal_Bool bHiddenLockedByAPI;
sal_Bool bInCloseEvent;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > xModel;
sal_uInt16 nStyleFilter;
sal_Bool bDisposing;
sal_Bool m_bEnableSetModified;
sal_Bool m_bIsModified;
Rectangle m_aVisArea;
MapUnit m_nMapUnit;
sal_Bool m_bCreateTempStor;
::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > m_xDocStorage;
::com::sun::star::uno::Reference<
::com::sun::star::util::XModifyListener > m_xDocInfoListener;
sal_Bool m_bIsInit;
SfxObjectShell_Impl( SfxObjectShell& _rDocShell );
virtual ~SfxObjectShell_Impl();
// IMacroDocumentAccess overridables
virtual sal_Int16 getImposedMacroExecMode() const;
virtual sal_Bool setImposedMacroExecMode( sal_uInt16 nMacroMode );
virtual ::rtl::OUString getDocumentLocation() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > getLastCommitDocumentStorage();
virtual sal_Bool documentStorageHasMacros() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::document::XEmbeddedScripts > getEmbeddedDocumentScripts() const;
virtual sal_Int16 getScriptingSignatureState() const;
virtual void showBrokenSignatureWarning( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction ) const;
};
#endif
<commit_msg>INTEGRATION: CWS odbmacros2 (1.39.2); FILE MERGED 2008/03/04 12:12:04 fs 1.39.2.3: RESYNC: (1.40-1.41); FILE MERGED 2008/02/04 13:15:52 fs 1.39.2.2: RESYNC: (1.39-1.40); FILE MERGED 2007/12/12 14:43:12 fs 1.39.2.1: bIsBasicDefault is not used<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: objshimp.hxx,v $
*
* $Revision: 1.42 $
*
* last change: $Author: kz $ $Date: 2008-03-06 19:57:35 $
*
* 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 _SFX_OBJSHIMP_HXX
#define _SFX_OBJSHIMP_HXX
//#include <hash_map>
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#include <svtools/securityoptions.hxx>
#include <sfx2/objsh.hxx>
#include "sfx2/docmacromode.hxx"
#include "bitset.hxx"
namespace svtools { class AsynchronLink; }
//====================================================================
DBG_NAMEEX(SfxObjectShell)
class SfxViewFrame;
struct MarkData_Impl
{
String aMark;
String aUserData;
SfxViewFrame* pFrame;
};
class SfxFrame;
class SfxToolBoxConfig;
class SfxAcceleratorManager;
class SfxBasicManagerHolder;
struct SfxObjectShell_Impl : public ::sfx2::IMacroDocumentAccess
{
::comphelper::EmbeddedObjectContainer* mpObjectContainer;
SfxAcceleratorManager* pAccMgr;
SfxConfigManager* pCfgMgr;
SfxBasicManagerHolder*
pBasicManager;
SfxObjectShell& rDocShell;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xBasicLibraries;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xDialogLibraries;
::sfx2::DocumentMacroMode
aMacroMode;
SfxProgress* pProgress;
String aTitle;
String aTempName;
DateTime nTime;
sal_uInt16 nVisualDocumentNumber;
sal_Int16 nDocumentSignatureState;
sal_Int16 nScriptingSignatureState;
sal_Bool bTemplateConfig:1,
bInList:1, // ob per First/Next erreichbar
bClosing:1, // sal_True w"aehrend Close(), um Benachrichtigungs-Rekursionen zu verhindern
bSetInPlaceObj:1, // sal_True, falls bereits versucht wurde pInPlaceObject zu casten
bIsSaving:1,
bPasswd:1,
bIsTmp:1,
bIsNamedVisible:1,
bIsTemplate:1,
bIsAbortingImport:1, // Importvorgang soll abgebrochen werden.
bImportDone : 1, //Import schon fertig? Fuer AutoReload von Docs.
bInPrepareClose : 1,
bPreparedForClose : 1,
bWaitingForPicklist : 1,// Muss noch in die Pickliste
bModuleSearched : 1,
bIsHelpObjSh : 1,
bForbidCaching : 1,
bForbidReload : 1,
bSupportsEventMacros: 1,
bLoadingWindows: 1,
bBasicInitialized :1,
//bHidden :1, // indicates a hidden view shell
bIsPrintJobCancelable :1, // Stampit disable/enable cancel button for print jobs ... default = true = enable!
bOwnsStorage:1,
bNoBaseURL:1,
bInitialized:1,
bSignatureErrorIsShown:1,
bModelInitialized:1, // whether the related model is initialized
bPreserveVersions:1,
m_bMacroSignBroken:1, // whether the macro signature was explicitly broken
m_bNoBasicCapabilities:1,
bQueryLoadTemplate:1,
bLoadReadonly:1,
bUseUserData:1,
bSaveVersionOnClose:1;
String aNewName; // Der Name, unter dem das Doc gespeichert
// werden soll
IndexBitSet aBitSet;
sal_uInt32 lErr;
sal_uInt16 nEventId; // falls vor Activate noch ein
// Open/Create gesendet werden mu/s
sal_Bool bDoNotTouchDocInfo;
AutoReloadTimer_Impl *pReloadTimer;
MarkData_Impl* pMarkData;
sal_uInt16 nLoadedFlags;
sal_uInt16 nFlagsInProgress;
String aMark;
Size aViewSize; // wird leider vom Writer beim
sal_Bool bInFrame; // HTML-Import gebraucht
sal_Bool bModalMode;
sal_Bool bRunningMacro;
sal_Bool bReloadAvailable;
sal_uInt16 nAutoLoadLocks;
SfxModule* pModule;
SfxFrame* pFrame;
SfxToolBoxConfig* pTbxConfig;
SfxEventConfigItem_Impl* pEventConfig;
SfxObjectShellFlags eFlags;
svtools::AsynchronLink* pCloser;
String aBaseURL;
sal_Bool bReadOnlyUI;
SvRefBaseRef xHeaderAttributes;
sal_Bool bHiddenLockedByAPI;
sal_Bool bInCloseEvent;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > xModel;
sal_uInt16 nStyleFilter;
sal_Bool bDisposing;
sal_Bool m_bEnableSetModified;
sal_Bool m_bIsModified;
Rectangle m_aVisArea;
MapUnit m_nMapUnit;
sal_Bool m_bCreateTempStor;
::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > m_xDocStorage;
::com::sun::star::uno::Reference<
::com::sun::star::util::XModifyListener > m_xDocInfoListener;
sal_Bool m_bIsInit;
SfxObjectShell_Impl( SfxObjectShell& _rDocShell );
virtual ~SfxObjectShell_Impl();
// IMacroDocumentAccess overridables
virtual sal_Int16 getImposedMacroExecMode() const;
virtual sal_Bool setImposedMacroExecMode( sal_uInt16 nMacroMode );
virtual ::rtl::OUString getDocumentLocation() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > getLastCommitDocumentStorage();
virtual sal_Bool documentStorageHasMacros() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::document::XEmbeddedScripts > getEmbeddedDocumentScripts() const;
virtual sal_Int16 getScriptingSignatureState() const;
virtual void showBrokenSignatureWarning( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction ) const;
};
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 _SFX_TEMPDLGI_HXX
#define _SFX_TEMPDLGI_HXX
class SfxTemplateControllerItem;
#include <vcl/button.hxx>
#include <vcl/toolbox.hxx>
#include <vcl/lstbox.hxx>
#include <svl/lstner.hxx>
#include <svtools/svtreebx.hxx>
#include <svl/eitem.hxx>
#define _SVSTDARR_USHORTS
#include <svl/svstdarr.hxx> // SvUShorts
#include <rsc/rscsfx.hxx>
#include <tools/rtti.hxx>
#include <sfx2/childwin.hxx>
#include <sfx2/templdlg.hxx>
class SfxStyleFamilies;
class SfxStyleFamilyItem;
class SfxTemplateItem;
class SfxBindings;
class SfxStyleSheetBasePool;
class SvTreeListBox ;
class StyleTreeListBox_Impl;
class SfxTemplateDialog_Impl;
class SfxCommonTemplateDialog_Impl;
class SfxTemplateDialogWrapper;
class SfxDockingWindow;
namespace com { namespace sun { namespace star { namespace frame { class XModuleManager; } } } }
// class DropListBox_Impl ------------------------------------------------
class DropListBox_Impl : public SvTreeListBox
{
private:
DECL_LINK( OnAsyncExecuteDrop, SvLBoxEntry* );
DECL_LINK( OnAsyncExecuteError, void* );
protected:
SfxCommonTemplateDialog_Impl* pDialog;
USHORT nModifier;
public:
DropListBox_Impl( Window* pParent, const ResId& rId, SfxCommonTemplateDialog_Impl* pD ) :
SvTreeListBox( pParent, rId ), pDialog( pD ) {}
DropListBox_Impl( Window* pParent, WinBits nWinBits, SfxCommonTemplateDialog_Impl* pD ) :
SvTreeListBox( pParent, nWinBits ), pDialog( pD ) {}
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
using SvLBox::ExecuteDrop;
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
USHORT GetModifier() const { return nModifier; }
virtual long Notify( NotifyEvent& rNEvt );
};
// class SfxActionListBox ------------------------------------------------
class SfxActionListBox : public DropListBox_Impl
{
protected:
public:
SfxActionListBox( SfxCommonTemplateDialog_Impl* pParent, WinBits nWinBits );
SfxActionListBox( SfxCommonTemplateDialog_Impl* pParent, const ResId &rResId );
virtual PopupMenu* CreateContextMenu( void );
};
// class SfxCommonTemplateDialog_Impl ------------------------------------
struct Deleted
{
bool bDead;
Deleted() : bDead(false) {}
inline bool operator()() { return bDead; }
};
class SfxCommonTemplateDialog_Impl : public SfxListener
{
private:
class ISfxTemplateCommon_Impl : public ISfxTemplateCommon
{
private:
SfxCommonTemplateDialog_Impl* pDialog;
public:
ISfxTemplateCommon_Impl( SfxCommonTemplateDialog_Impl* pDialogP ) : pDialog( pDialogP ) {}
virtual SfxStyleFamily GetActualFamily() const { return pDialog->GetActualFamily(); }
virtual String GetSelectedEntry() const { return pDialog->GetSelectedEntry(); }
};
ISfxTemplateCommon_Impl aISfxTemplateCommon;
void ReadResource();
void ClearResource();
protected:
#define MAX_FAMILIES 5
#define COUNT_BOUND_FUNC 13
#define UPDATE_FAMILY_LIST 0x0001
#define UPDATE_FAMILY 0x0002
friend class DropListBox_Impl;
friend class SfxTemplateControllerItem;
friend class SfxTemplateDialogWrapper;
SfxBindings* pBindings;
SfxTemplateControllerItem* pBoundItems[COUNT_BOUND_FUNC];
Window* pWindow;
SfxModule* pModule;
Timer* pTimer;
ResId* m_pStyleFamiliesId;
SfxStyleFamilies* pStyleFamilies;
SfxTemplateItem* pFamilyState[MAX_FAMILIES];
SfxStyleSheetBasePool* pStyleSheetPool;
SvTreeListBox* pTreeBox;
SfxObjectShell* pCurObjShell;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModuleManager >
xModuleManager;
Deleted* pbDeleted;
SfxActionListBox aFmtLb;
ListBox aFilterLb;
Size aSize;
USHORT nActFamily; // Id in the ToolBox = Position - 1
USHORT nActFilter; // FilterIdx
USHORT nAppFilter; // Filter, which has set the application (for automatic)
BOOL bDontUpdate :1,
bIsWater :1,
bEnabled :1,
bUpdate :1,
bUpdateFamily :1,
bCanEdit :1,
bCanDel :1,
bCanNew :1,
bWaterDisabled :1,
bNewByExampleDisab§led :1,
bUpdateByExampleDisabled:1,
bTreeDrag :1,
bHierarchical :1,
bBindingUpdate :1;
DECL_LINK( FilterSelectHdl, ListBox * );
DECL_LINK( FmtSelectHdl, SvTreeListBox * );
DECL_LINK( ApplyHdl, Control * );
DECL_LINK( DropHdl, StyleTreeListBox_Impl * );
DECL_LINK( TimeOut, Timer * );
virtual void EnableItem( USHORT /*nMesId*/, BOOL /*bCheck*/ = TRUE ) {}
virtual void CheckItem( USHORT /*nMesId*/, BOOL /*bCheck*/ = TRUE ) {}
virtual BOOL IsCheckedItem( USHORT /*nMesId*/ ) { return TRUE; }
virtual void LoadedFamilies() {}
virtual void Update() { UpdateStyles_Impl(UPDATE_FAMILY_LIST); }
virtual void InvalidateBindings();
virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten ) = 0;
virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE ) = 0;
virtual void ClearFamilyList() = 0;
virtual void ReplaceUpdateButtonByMenu();
void NewHdl( void* );
void EditHdl( void* );
void DeleteHdl( void* );
BOOL Execute_Impl( USHORT nId, const String& rStr, const String& rRefStr,
USHORT nFamily, USHORT nMask = 0,
USHORT* pIdx = NULL, const USHORT* pModifier = NULL );
void UpdateStyles_Impl(USHORT nFlags);
const SfxStyleFamilyItem* GetFamilyItem_Impl() const;
BOOL IsInitialized() { return nActFamily != 0xffff; }
void ResetFocus();
void EnableDelete();
void Initialize();
void FilterSelect( USHORT nFilterIdx, BOOL bForce = FALSE );
void SetFamilyState( USHORT nSlotId, const SfxTemplateItem* );
void SetWaterCanState( const SfxBoolItem* pItem );
void SelectStyle( const String& rStyle );
BOOL HasSelectedStyle() const;
void FillTreeBox();
void Update_Impl();
void UpdateFamily_Impl();
// In which FamilyState do I have to look , in order to get the
// information of the ith Family in the pStyleFamilies.
USHORT StyleNrToInfoOffset( USHORT i );
USHORT InfoOffsetToStyleNr( USHORT i );
void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
void FamilySelect( USHORT nId );
void SetFamily( USHORT nId );
void ActionSelect( USHORT nId );
sal_Int32 LoadFactoryStyleFilter( SfxObjectShell* i_pObjSh );
void SaveFactoryStyleFilter( SfxObjectShell* i_pObjSh, sal_Int32 i_nFilter );
public:
TYPEINFO();
SfxCommonTemplateDialog_Impl( SfxBindings* pB, SfxDockingWindow* );
SfxCommonTemplateDialog_Impl( SfxBindings* pB, ModalDialog* );
~SfxCommonTemplateDialog_Impl();
DECL_LINK( MenuSelectHdl, Menu * );
virtual void EnableEdit( BOOL b = TRUE ) { bCanEdit = b; }
virtual void EnableDel( BOOL b = TRUE ) { bCanDel = b; }
virtual void EnableNew( BOOL b = TRUE ) { bCanNew = b; }
ISfxTemplateCommon* GetISfxTemplateCommon() { return &aISfxTemplateCommon; }
Window* GetWindow() { return pWindow; }
void EnableTreeDrag( BOOL b = TRUE );
void ExecuteContextMenu_Impl( const Point& rPos, Window* pWin );
void EnableExample_Impl( USHORT nId, BOOL bEnable );
SfxStyleFamily GetActualFamily() const;
String GetSelectedEntry() const;
SfxObjectShell* GetObjectShell() const { return pCurObjShell; }
virtual void PrepareDeleteAction(); // disable buttons, change button text, etc. when del is going to happen
inline BOOL CanEdit( void ) const { return bCanEdit; }
inline BOOL CanDel( void ) const { return bCanDel; }
inline BOOL CanNew( void ) const { return bCanNew; }
// normaly for derivates from SvTreeListBoxes, but in this case the dialog handles context menus
virtual PopupMenu* CreateContextMenu( void );
// converts from SFX_STYLE_FAMILY Ids to 1-5
static USHORT SfxFamilyIdToNId( SfxStyleFamily nFamily );
void SetAutomaticFilter();
};
class DropToolBox_Impl : public ToolBox, public DropTargetHelper
{
SfxTemplateDialog_Impl& rParent;
protected:
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
public:
DropToolBox_Impl(Window* pParent, SfxTemplateDialog_Impl* pTemplateDialog);
~DropToolBox_Impl();
};
// class SfxTemplateDialog_Impl ------------------------------------------
class SfxTemplateDialog_Impl : public SfxCommonTemplateDialog_Impl
{
private:
friend class SfxTemplateControllerItem;
friend class SfxTemplateDialogWrapper;
friend class DropToolBox_Impl;
SfxTemplateDialog* m_pFloat;
BOOL m_bZoomIn;
DropToolBox_Impl m_aActionTbL;
ToolBox m_aActionTbR;
DECL_LINK( ToolBoxLSelect, ToolBox * );
DECL_LINK( ToolBoxRSelect, ToolBox * );
DECL_LINK( ToolBoxRClick, ToolBox * );
DECL_LINK( MenuSelectHdl, Menu* );
protected:
virtual void Command( const CommandEvent& rMEvt );
virtual void EnableEdit( BOOL = TRUE );
virtual void EnableItem( USHORT nMesId, BOOL bCheck = TRUE );
virtual void CheckItem( USHORT nMesId, BOOL bCheck = TRUE );
virtual BOOL IsCheckedItem( USHORT nMesId );
virtual void LoadedFamilies();
virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten );
virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE );
virtual void ClearFamilyList();
virtual void ReplaceUpdateButtonByMenu();
void Resize();
Size GetMinOutputSizePixel();
void updateFamilyImages();
void updateNonFamilyImages();
public:
friend class SfxTemplateDialog;
TYPEINFO();
SfxTemplateDialog_Impl( Window* pParent, SfxBindings*, SfxTemplateDialog* pWindow );
~SfxTemplateDialog_Impl();
};
// class SfxTemplateCatalog_Impl -----------------------------------------
class SfxTemplateCatalog_Impl : public SfxCommonTemplateDialog_Impl
{
private:
friend class SfxTemplateControllerItem;
friend class SfxCommonTemplateDialog_Impl;
ListBox aFamList;
OKButton aOkBtn;
CancelButton aCancelBtn;
PushButton aNewBtn;
PushButton aChangeBtn;
PushButton aDelBtn;
PushButton aOrgBtn;
HelpButton aHelpBtn;
SfxTemplateCatalog* pReal;
SvUShorts aFamIds;
SfxModalDefParentHelper aHelper;
protected:
virtual void EnableItem( USHORT nMesId, BOOL bCheck = TRUE );
virtual void CheckItem( USHORT nMesId, BOOL bCheck = TRUE );
virtual BOOL IsCheckedItem( USHORT nMesId );
virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten );
virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE );
virtual void ClearFamilyList();
virtual void EnableEdit( BOOL = TRUE );
virtual void EnableDel( BOOL = TRUE );
virtual void EnableNew( BOOL = TRUE );
using SfxCommonTemplateDialog_Impl::NewHdl;
DECL_LINK( FamListSelect, ListBox * );
DECL_LINK( OkHdl, Button * );
DECL_LINK( CancelHdl, Button * );
DECL_LINK( NewHdl, Button * );
DECL_LINK( ChangeHdl, Button * );
DECL_LINK( DelHdl, Button * );
DECL_LINK( OrgHdl, Button * );
public:
TYPEINFO();
SfxTemplateCatalog_Impl( Window* pParent, SfxBindings*, SfxTemplateCatalog* pWindow );
~SfxTemplateCatalog_Impl();
friend class SfxTemplateCatalog;
virtual void PrepareDeleteAction();
};
#endif // #ifndef _SFX_TEMPDLGI_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>random character added by translation<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 _SFX_TEMPDLGI_HXX
#define _SFX_TEMPDLGI_HXX
class SfxTemplateControllerItem;
#include <vcl/button.hxx>
#include <vcl/toolbox.hxx>
#include <vcl/lstbox.hxx>
#include <svl/lstner.hxx>
#include <svtools/svtreebx.hxx>
#include <svl/eitem.hxx>
#define _SVSTDARR_USHORTS
#include <svl/svstdarr.hxx> // SvUShorts
#include <rsc/rscsfx.hxx>
#include <tools/rtti.hxx>
#include <sfx2/childwin.hxx>
#include <sfx2/templdlg.hxx>
class SfxStyleFamilies;
class SfxStyleFamilyItem;
class SfxTemplateItem;
class SfxBindings;
class SfxStyleSheetBasePool;
class SvTreeListBox ;
class StyleTreeListBox_Impl;
class SfxTemplateDialog_Impl;
class SfxCommonTemplateDialog_Impl;
class SfxTemplateDialogWrapper;
class SfxDockingWindow;
namespace com { namespace sun { namespace star { namespace frame { class XModuleManager; } } } }
// class DropListBox_Impl ------------------------------------------------
class DropListBox_Impl : public SvTreeListBox
{
private:
DECL_LINK( OnAsyncExecuteDrop, SvLBoxEntry* );
DECL_LINK( OnAsyncExecuteError, void* );
protected:
SfxCommonTemplateDialog_Impl* pDialog;
USHORT nModifier;
public:
DropListBox_Impl( Window* pParent, const ResId& rId, SfxCommonTemplateDialog_Impl* pD ) :
SvTreeListBox( pParent, rId ), pDialog( pD ) {}
DropListBox_Impl( Window* pParent, WinBits nWinBits, SfxCommonTemplateDialog_Impl* pD ) :
SvTreeListBox( pParent, nWinBits ), pDialog( pD ) {}
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
using SvLBox::ExecuteDrop;
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
USHORT GetModifier() const { return nModifier; }
virtual long Notify( NotifyEvent& rNEvt );
};
// class SfxActionListBox ------------------------------------------------
class SfxActionListBox : public DropListBox_Impl
{
protected:
public:
SfxActionListBox( SfxCommonTemplateDialog_Impl* pParent, WinBits nWinBits );
SfxActionListBox( SfxCommonTemplateDialog_Impl* pParent, const ResId &rResId );
virtual PopupMenu* CreateContextMenu( void );
};
// class SfxCommonTemplateDialog_Impl ------------------------------------
struct Deleted
{
bool bDead;
Deleted() : bDead(false) {}
inline bool operator()() { return bDead; }
};
class SfxCommonTemplateDialog_Impl : public SfxListener
{
private:
class ISfxTemplateCommon_Impl : public ISfxTemplateCommon
{
private:
SfxCommonTemplateDialog_Impl* pDialog;
public:
ISfxTemplateCommon_Impl( SfxCommonTemplateDialog_Impl* pDialogP ) : pDialog( pDialogP ) {}
virtual SfxStyleFamily GetActualFamily() const { return pDialog->GetActualFamily(); }
virtual String GetSelectedEntry() const { return pDialog->GetSelectedEntry(); }
};
ISfxTemplateCommon_Impl aISfxTemplateCommon;
void ReadResource();
void ClearResource();
protected:
#define MAX_FAMILIES 5
#define COUNT_BOUND_FUNC 13
#define UPDATE_FAMILY_LIST 0x0001
#define UPDATE_FAMILY 0x0002
friend class DropListBox_Impl;
friend class SfxTemplateControllerItem;
friend class SfxTemplateDialogWrapper;
SfxBindings* pBindings;
SfxTemplateControllerItem* pBoundItems[COUNT_BOUND_FUNC];
Window* pWindow;
SfxModule* pModule;
Timer* pTimer;
ResId* m_pStyleFamiliesId;
SfxStyleFamilies* pStyleFamilies;
SfxTemplateItem* pFamilyState[MAX_FAMILIES];
SfxStyleSheetBasePool* pStyleSheetPool;
SvTreeListBox* pTreeBox;
SfxObjectShell* pCurObjShell;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModuleManager >
xModuleManager;
Deleted* pbDeleted;
SfxActionListBox aFmtLb;
ListBox aFilterLb;
Size aSize;
USHORT nActFamily; // Id in the ToolBox = Position - 1
USHORT nActFilter; // FilterIdx
USHORT nAppFilter; // Filter, which has set the application (for automatic)
BOOL bDontUpdate :1,
bIsWater :1,
bEnabled :1,
bUpdate :1,
bUpdateFamily :1,
bCanEdit :1,
bCanDel :1,
bCanNew :1,
bWaterDisabled :1,
bNewByExampleDisabled :1,
bUpdateByExampleDisabled:1,
bTreeDrag :1,
bHierarchical :1,
bBindingUpdate :1;
DECL_LINK( FilterSelectHdl, ListBox * );
DECL_LINK( FmtSelectHdl, SvTreeListBox * );
DECL_LINK( ApplyHdl, Control * );
DECL_LINK( DropHdl, StyleTreeListBox_Impl * );
DECL_LINK( TimeOut, Timer * );
virtual void EnableItem( USHORT /*nMesId*/, BOOL /*bCheck*/ = TRUE ) {}
virtual void CheckItem( USHORT /*nMesId*/, BOOL /*bCheck*/ = TRUE ) {}
virtual BOOL IsCheckedItem( USHORT /*nMesId*/ ) { return TRUE; }
virtual void LoadedFamilies() {}
virtual void Update() { UpdateStyles_Impl(UPDATE_FAMILY_LIST); }
virtual void InvalidateBindings();
virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten ) = 0;
virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE ) = 0;
virtual void ClearFamilyList() = 0;
virtual void ReplaceUpdateButtonByMenu();
void NewHdl( void* );
void EditHdl( void* );
void DeleteHdl( void* );
BOOL Execute_Impl( USHORT nId, const String& rStr, const String& rRefStr,
USHORT nFamily, USHORT nMask = 0,
USHORT* pIdx = NULL, const USHORT* pModifier = NULL );
void UpdateStyles_Impl(USHORT nFlags);
const SfxStyleFamilyItem* GetFamilyItem_Impl() const;
BOOL IsInitialized() { return nActFamily != 0xffff; }
void ResetFocus();
void EnableDelete();
void Initialize();
void FilterSelect( USHORT nFilterIdx, BOOL bForce = FALSE );
void SetFamilyState( USHORT nSlotId, const SfxTemplateItem* );
void SetWaterCanState( const SfxBoolItem* pItem );
void SelectStyle( const String& rStyle );
BOOL HasSelectedStyle() const;
void FillTreeBox();
void Update_Impl();
void UpdateFamily_Impl();
// In which FamilyState do I have to look , in order to get the
// information of the ith Family in the pStyleFamilies.
USHORT StyleNrToInfoOffset( USHORT i );
USHORT InfoOffsetToStyleNr( USHORT i );
void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
void FamilySelect( USHORT nId );
void SetFamily( USHORT nId );
void ActionSelect( USHORT nId );
sal_Int32 LoadFactoryStyleFilter( SfxObjectShell* i_pObjSh );
void SaveFactoryStyleFilter( SfxObjectShell* i_pObjSh, sal_Int32 i_nFilter );
public:
TYPEINFO();
SfxCommonTemplateDialog_Impl( SfxBindings* pB, SfxDockingWindow* );
SfxCommonTemplateDialog_Impl( SfxBindings* pB, ModalDialog* );
~SfxCommonTemplateDialog_Impl();
DECL_LINK( MenuSelectHdl, Menu * );
virtual void EnableEdit( BOOL b = TRUE ) { bCanEdit = b; }
virtual void EnableDel( BOOL b = TRUE ) { bCanDel = b; }
virtual void EnableNew( BOOL b = TRUE ) { bCanNew = b; }
ISfxTemplateCommon* GetISfxTemplateCommon() { return &aISfxTemplateCommon; }
Window* GetWindow() { return pWindow; }
void EnableTreeDrag( BOOL b = TRUE );
void ExecuteContextMenu_Impl( const Point& rPos, Window* pWin );
void EnableExample_Impl( USHORT nId, BOOL bEnable );
SfxStyleFamily GetActualFamily() const;
String GetSelectedEntry() const;
SfxObjectShell* GetObjectShell() const { return pCurObjShell; }
virtual void PrepareDeleteAction(); // disable buttons, change button text, etc. when del is going to happen
inline BOOL CanEdit( void ) const { return bCanEdit; }
inline BOOL CanDel( void ) const { return bCanDel; }
inline BOOL CanNew( void ) const { return bCanNew; }
// normaly for derivates from SvTreeListBoxes, but in this case the dialog handles context menus
virtual PopupMenu* CreateContextMenu( void );
// converts from SFX_STYLE_FAMILY Ids to 1-5
static USHORT SfxFamilyIdToNId( SfxStyleFamily nFamily );
void SetAutomaticFilter();
};
class DropToolBox_Impl : public ToolBox, public DropTargetHelper
{
SfxTemplateDialog_Impl& rParent;
protected:
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
public:
DropToolBox_Impl(Window* pParent, SfxTemplateDialog_Impl* pTemplateDialog);
~DropToolBox_Impl();
};
// class SfxTemplateDialog_Impl ------------------------------------------
class SfxTemplateDialog_Impl : public SfxCommonTemplateDialog_Impl
{
private:
friend class SfxTemplateControllerItem;
friend class SfxTemplateDialogWrapper;
friend class DropToolBox_Impl;
SfxTemplateDialog* m_pFloat;
BOOL m_bZoomIn;
DropToolBox_Impl m_aActionTbL;
ToolBox m_aActionTbR;
DECL_LINK( ToolBoxLSelect, ToolBox * );
DECL_LINK( ToolBoxRSelect, ToolBox * );
DECL_LINK( ToolBoxRClick, ToolBox * );
DECL_LINK( MenuSelectHdl, Menu* );
protected:
virtual void Command( const CommandEvent& rMEvt );
virtual void EnableEdit( BOOL = TRUE );
virtual void EnableItem( USHORT nMesId, BOOL bCheck = TRUE );
virtual void CheckItem( USHORT nMesId, BOOL bCheck = TRUE );
virtual BOOL IsCheckedItem( USHORT nMesId );
virtual void LoadedFamilies();
virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten );
virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE );
virtual void ClearFamilyList();
virtual void ReplaceUpdateButtonByMenu();
void Resize();
Size GetMinOutputSizePixel();
void updateFamilyImages();
void updateNonFamilyImages();
public:
friend class SfxTemplateDialog;
TYPEINFO();
SfxTemplateDialog_Impl( Window* pParent, SfxBindings*, SfxTemplateDialog* pWindow );
~SfxTemplateDialog_Impl();
};
// class SfxTemplateCatalog_Impl -----------------------------------------
class SfxTemplateCatalog_Impl : public SfxCommonTemplateDialog_Impl
{
private:
friend class SfxTemplateControllerItem;
friend class SfxCommonTemplateDialog_Impl;
ListBox aFamList;
OKButton aOkBtn;
CancelButton aCancelBtn;
PushButton aNewBtn;
PushButton aChangeBtn;
PushButton aDelBtn;
PushButton aOrgBtn;
HelpButton aHelpBtn;
SfxTemplateCatalog* pReal;
SvUShorts aFamIds;
SfxModalDefParentHelper aHelper;
protected:
virtual void EnableItem( USHORT nMesId, BOOL bCheck = TRUE );
virtual void CheckItem( USHORT nMesId, BOOL bCheck = TRUE );
virtual BOOL IsCheckedItem( USHORT nMesId );
virtual void InsertFamilyItem( USHORT nId, const SfxStyleFamilyItem* pIten );
virtual void EnableFamilyItem( USHORT nId, BOOL bEnabled = TRUE );
virtual void ClearFamilyList();
virtual void EnableEdit( BOOL = TRUE );
virtual void EnableDel( BOOL = TRUE );
virtual void EnableNew( BOOL = TRUE );
using SfxCommonTemplateDialog_Impl::NewHdl;
DECL_LINK( FamListSelect, ListBox * );
DECL_LINK( OkHdl, Button * );
DECL_LINK( CancelHdl, Button * );
DECL_LINK( NewHdl, Button * );
DECL_LINK( ChangeHdl, Button * );
DECL_LINK( DelHdl, Button * );
DECL_LINK( OrgHdl, Button * );
public:
TYPEINFO();
SfxTemplateCatalog_Impl( Window* pParent, SfxBindings*, SfxTemplateCatalog* pWindow );
~SfxTemplateCatalog_Impl();
friend class SfxTemplateCatalog;
virtual void PrepareDeleteAction();
};
#endif // #ifndef _SFX_TEMPDLGI_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "tizen_utils.hpp"
#include "../../std/vector.hpp"
#include "../../tizen/inc/FBase.hpp"
#include "../base/logging.hpp"
#include <FSystem.h>
string FromTizenString(Tizen::Base::String const & str_tizen)
{
string utf8Str;
if (str_tizen.GetLength() == 0)
return utf8Str;
Tizen::Base::ByteBuffer * pBuffer = Tizen::Base::Utility::StringUtil::StringToUtf8N(str_tizen);
if (pBuffer)
{
int byteCount = pBuffer->GetLimit();
byteCount--; // Don't copy Zero at the end
if (byteCount > 0)
{
vector<char> chBuf(byteCount);
pBuffer->GetArray((byte *)&chBuf[0], 0, byteCount);
utf8Str.assign(chBuf.begin(), chBuf.end());
}
delete pBuffer;
}
return utf8Str;
}
string GetTizenLocale()
{
Tizen::Base::String languageCode;
Tizen::System::SettingInfo::GetValue(L"http://tizen.org/setting/locale.language", languageCode);
Tizen::Base::String languageCode_truncated;
languageCode.SubString(0, 3, languageCode_truncated);
return CodeFromISO369_2to_1(FromTizenString(languageCode_truncated));
}
string CodeFromISO369_2to_1(string const & code_ISO_639_2)
{
static const string ar [] =
{
"aar", "aa",
"abk", "ab",
"afr", "af",
"aka", "ak",
"sqi", "sq",
"amh", "am",
"ara", "ar",
"arg", "an",
"hye", "hy",
"asm", "as",
"ava", "av",
"ave", "ae",
"aym", "ay",
"aze", "az",
"bak", "ba",
"bam", "bm",
"eus", "eu",
"bel", "be",
"ben", "bn",
"bih", "bh",
"bis", "bi",
"bod", "bo",
"bos", "bs",
"bre", "br",
"bul", "bg",
"mya", "my",
"cat", "ca",
"ces", "cs",
"cha", "ch",
"che", "ce",
"zho", "zh",
"chu", "cu",
"chv", "cv",
"cor", "kw",
"cos", "co",
"cre", "cr",
"cym", "cy",
"ces", "cs",
"dan", "da",
"deu", "de",
"div", "dv",
"nld", "nl",
"dzo", "dz",
"ell", "el",
"eng", "en",
"epo", "eo",
"est", "et",
"eus", "eu",
"ewe", "ee",
"fao", "fo",
"fas", "fa",
"fij", "fj",
"fin", "fi",
"fra", "fr",
"fra", "fr",
"fry", "fy",
"ful", "ff",
"kat", "ka",
"deu", "de",
"gla", "gd",
"gle", "ga",
"glg", "gl",
"glv", "gv",
"ell", "el",
"grn", "gn",
"guj", "gu",
"hat", "ht",
"hau", "ha",
"heb", "he",
"her", "hz",
"hin", "hi",
"hmo", "ho",
"hrv", "hr",
"hun", "hu",
"hye", "hy",
"ibo", "ig",
"ice", "is",
"ido", "io",
"iii", "ii",
"iku", "iu",
"ile", "ie",
"ina", "ia",
"ind", "id",
"ipk", "ik",
"isl", "is",
"ita", "it",
"jav", "jv",
"jpn", "ja",
"kal", "kl",
"kan", "kn",
"kas", "ks",
"kat", "ka",
"kau", "kr",
"kaz", "kk",
"khm", "km",
"kik", "ki",
"kin", "rw",
"kir", "ky",
"kom", "kv",
"kon", "kg",
"kor", "ko",
"kua", "kj",
"kur", "ku",
"lao", "lo",
"lat", "la",
"lav", "lv",
"lim", "li",
"lin", "ln",
"lit", "lt",
"ltz", "lb",
"lub", "lu",
"lug", "lg",
"mkd", "mk",
"mah", "mh",
"mal", "ml",
"mri", "mi",
"mar", "mr",
"msa", "ms",
"mkd", "mk",
"mlg", "mg",
"mlt", "mt",
"mon", "mn",
"mri", "mi",
"msa", "ms",
"mya", "my",
"nau", "na",
"nav", "nv",
"nbl", "nr",
"nde", "nd",
"ndo", "ng",
"nep", "ne",
"nld", "nl",
"nno", "nn",
"nob", "nb",
"nor", "no",
"nya", "ny",
"oci", "oc",
"oji", "oj",
"ori", "or",
"orm", "om",
"oss", "os",
"pan", "pa",
"fas", "fa",
"pli", "pi",
"pol", "pl",
"por", "pt",
"pus", "ps",
"que", "qu",
"roh", "rm",
"ron", "ro",
"ron", "ro",
"run", "rn",
"rus", "ru",
"sag", "sg",
"san", "sa",
"sin", "si",
"slk", "sk",
"slk", "sk",
"slv", "sl",
"sme", "se",
"smo", "sm",
"sna", "sn",
"snd", "sd",
"som", "so",
"sot", "st",
"spa", "es",
"sqi", "sq",
"srd", "sc",
"srp", "sr",
"ssw", "ss",
"sun", "su",
"swa", "sw",
"swe", "sv",
"tah", "ty",
"tam", "ta",
"tat", "tt",
"tel", "te",
"tgk", "tg",
"tgl", "tl",
"tha", "th",
"bod", "bo",
"tir", "ti",
"ton", "to",
"tsn", "tn",
"tso", "ts",
"tuk", "tk",
"tur", "tr",
"twi", "tw",
"uig", "ug",
"ukr", "uk",
"urd", "ur",
"uzb", "uz",
"ven", "ve",
"vie", "vi",
"vol", "vo",
"cym", "cy",
"wln", "wa",
"wol", "wo",
"xho", "xh",
"yid", "yi",
"yor", "yo",
"zha", "za",
"zho", "zh",
"zul", "zu"
};
for (size_t i = 0; i < sizeof(ar)/sizeof(ar[0]); i += 2)
if (code_ISO_639_2 == ar[i])
{
return ar[i + 1];
}
LOG(LDEBUG, ("Language not found", code_ISO_639_2));
return "en";
}
<commit_msg>[Tizen] review fix<commit_after>#include "tizen_utils.hpp"
#include "../../std/vector.hpp"
#include "../../tizen/inc/FBase.hpp"
#include "../base/logging.hpp"
#include <FSystem.h>
string FromTizenString(Tizen::Base::String const & str_tizen)
{
string utf8Str;
if (str_tizen.GetLength() == 0)
return utf8Str;
Tizen::Base::ByteBuffer * pBuffer = Tizen::Base::Utility::StringUtil::StringToUtf8N(str_tizen);
if (pBuffer)
{
int byteCount = pBuffer->GetLimit();
byteCount--; // Don't copy Zero at the end
if (byteCount > 0)
{
vector<char> chBuf(byteCount);
pBuffer->GetArray((byte *)&chBuf[0], 0, byteCount);
utf8Str.assign(chBuf.begin(), chBuf.end());
}
delete pBuffer;
}
return utf8Str;
}
string GetTizenLocale()
{
Tizen::Base::String languageCode;
Tizen::System::SettingInfo::GetValue(L"http://tizen.org/setting/locale.language", languageCode);
Tizen::Base::String languageCode_truncated;
languageCode.SubString(0, 3, languageCode_truncated);
return CodeFromISO369_2to_1(FromTizenString(languageCode_truncated));
}
string CodeFromISO369_2to_1(string const & code_ISO_639_2)
{
static const string ar [] =
{
"aar", "aa",
"abk", "ab",
"afr", "af",
"aka", "ak",
"sqi", "sq",
"amh", "am",
"ara", "ar",
"arg", "an",
"hye", "hy",
"asm", "as",
"ava", "av",
"ave", "ae",
"aym", "ay",
"aze", "az",
"bak", "ba",
"bam", "bm",
"eus", "eu",
"bel", "be",
"ben", "bn",
"bih", "bh",
"bis", "bi",
"bod", "bo",
"bos", "bs",
"bre", "br",
"bul", "bg",
"mya", "my",
"cat", "ca",
"ces", "cs",
"cha", "ch",
"che", "ce",
"zho", "zh",
"chu", "cu",
"chv", "cv",
"cor", "kw",
"cos", "co",
"cre", "cr",
"cym", "cy",
"ces", "cs",
"dan", "da",
"deu", "de",
"div", "dv",
"nld", "nl",
"dzo", "dz",
"ell", "el",
"eng", "en",
"epo", "eo",
"est", "et",
"eus", "eu",
"ewe", "ee",
"fao", "fo",
"fas", "fa",
"fij", "fj",
"fin", "fi",
"fra", "fr",
"fra", "fr",
"fry", "fy",
"ful", "ff",
"kat", "ka",
"deu", "de",
"gla", "gd",
"gle", "ga",
"glg", "gl",
"glv", "gv",
"ell", "el",
"grn", "gn",
"guj", "gu",
"hat", "ht",
"hau", "ha",
"heb", "he",
"her", "hz",
"hin", "hi",
"hmo", "ho",
"hrv", "hr",
"hun", "hu",
"hye", "hy",
"ibo", "ig",
"ice", "is",
"ido", "io",
"iii", "ii",
"iku", "iu",
"ile", "ie",
"ina", "ia",
"ind", "id",
"ipk", "ik",
"isl", "is",
"ita", "it",
"jav", "jv",
"jpn", "ja",
"kal", "kl",
"kan", "kn",
"kas", "ks",
"kat", "ka",
"kau", "kr",
"kaz", "kk",
"khm", "km",
"kik", "ki",
"kin", "rw",
"kir", "ky",
"kom", "kv",
"kon", "kg",
"kor", "ko",
"kua", "kj",
"kur", "ku",
"lao", "lo",
"lat", "la",
"lav", "lv",
"lim", "li",
"lin", "ln",
"lit", "lt",
"ltz", "lb",
"lub", "lu",
"lug", "lg",
"mkd", "mk",
"mah", "mh",
"mal", "ml",
"mri", "mi",
"mar", "mr",
"msa", "ms",
"mkd", "mk",
"mlg", "mg",
"mlt", "mt",
"mon", "mn",
"mri", "mi",
"msa", "ms",
"mya", "my",
"nau", "na",
"nav", "nv",
"nbl", "nr",
"nde", "nd",
"ndo", "ng",
"nep", "ne",
"nld", "nl",
"nno", "nn",
"nob", "nb",
"nor", "no",
"nya", "ny",
"oci", "oc",
"oji", "oj",
"ori", "or",
"orm", "om",
"oss", "os",
"pan", "pa",
"fas", "fa",
"pli", "pi",
"pol", "pl",
"por", "pt",
"pus", "ps",
"que", "qu",
"roh", "rm",
"ron", "ro",
"ron", "ro",
"run", "rn",
"rus", "ru",
"sag", "sg",
"san", "sa",
"sin", "si",
"slk", "sk",
"slk", "sk",
"slv", "sl",
"sme", "se",
"smo", "sm",
"sna", "sn",
"snd", "sd",
"som", "so",
"sot", "st",
"spa", "es",
"sqi", "sq",
"srd", "sc",
"srp", "sr",
"ssw", "ss",
"sun", "su",
"swa", "sw",
"swe", "sv",
"tah", "ty",
"tam", "ta",
"tat", "tt",
"tel", "te",
"tgk", "tg",
"tgl", "tl",
"tha", "th",
"bod", "bo",
"tir", "ti",
"ton", "to",
"tsn", "tn",
"tso", "ts",
"tuk", "tk",
"tur", "tr",
"twi", "tw",
"uig", "ug",
"ukr", "uk",
"urd", "ur",
"uzb", "uz",
"ven", "ve",
"vie", "vi",
"vol", "vo",
"cym", "cy",
"wln", "wa",
"wol", "wo",
"xho", "xh",
"yid", "yi",
"yor", "yo",
"zha", "za",
"zho", "zh",
"zul", "zu"
};
for (size_t i = 0; i < sizeof(ar)/sizeof(ar[0]); i += 2)
{
if (code_ISO_639_2 == ar[i])
{
return ar[i + 1];
}
}
LOG(LDEBUG, ("Language not found", code_ISO_639_2));
return "en";
}
<|endoftext|> |
<commit_before>#include <QFile>
#include "quagzipfile.h"
class QuaGzipFilePrivate {
friend class QuaGzipFile;
QString fileName;
gzFile gzd;
inline QuaGzipFilePrivate(): gzd(NULL) {}
inline QuaGzipFilePrivate(const QString &fileName):
fileName(fileName), gzd(NULL) {}
template<typename FileId> bool open(FileId id,
QIODevice::OpenMode mode, QString &error);
template<typename FileId> gzFile open(FileId id,
const char *modeString);
};
template<> // const QString& doesn't work in MSVS 2008 for some reason
gzFile QuaGzipFilePrivate::open(QString id, const char *modeString)
{
return gzopen(QFile::encodeName(id).constData(), modeString);
}
template<>
gzFile QuaGzipFilePrivate::open(int id, const char *modeString)
{
return gzdopen(id, modeString);
}
template<typename FileId>
bool QuaGzipFilePrivate::open(FileId id, QIODevice::OpenMode mode,
QString &error)
{
char modeString[2];
modeString[0] = modeString[1] = '\0';
if ((mode & QIODevice::ReadOnly) != 0
&& (mode & QIODevice::WriteOnly) != 0) {
error = QuaGzipFile::trUtf8("Opening gzip for both reading"
" and writing is not supported");
return false;
} else if ((mode & QIODevice::ReadOnly) != 0) {
modeString[0] = 'r';
} else if ((mode & QIODevice::WriteOnly) != 0) {
modeString[0] = 'w';
} else {
error = QuaGzipFile::trUtf8("You can open a gzip either for reading"
" or for writing. Which is it?");
return false;
}
gzd = open(id, modeString);
if (gzd == NULL) {
error = QuaGzipFile::trUtf8("Could not gzopen() file");
return false;
}
return true;
}
QuaGzipFile::QuaGzipFile():
d(new QuaGzipFilePrivate())
{
}
QuaGzipFile::QuaGzipFile(QObject *parent):
QIODevice(parent),
d(new QuaGzipFilePrivate())
{
}
QuaGzipFile::QuaGzipFile(const QString &fileName, QObject *parent):
QIODevice(parent),
d(new QuaGzipFilePrivate(fileName))
{
}
QuaGzipFile::~QuaGzipFile()
{
if (isOpen()) {
close();
}
delete d;
}
void QuaGzipFile::setFileName(const QString& fileName)
{
d->fileName = fileName;
}
QString QuaGzipFile::getFileName() const
{
return d->fileName;
}
bool QuaGzipFile::isSequential() const
{
return true;
}
bool QuaGzipFile::open(QIODevice::OpenMode mode)
{
QString error;
if (!d->open(d->fileName, mode, error)) {
setErrorString(error);
return false;
}
return QIODevice::open(mode);
}
bool QuaGzipFile::open(int fd, QIODevice::OpenMode mode)
{
QString error;
if (!d->open(fd, mode, error)) {
setErrorString(error);
return false;
}
return QIODevice::open(mode);
}
bool QuaGzipFile::flush()
{
return gzflush(d->gzd, Z_SYNC_FLUSH) == Z_OK;
}
void QuaGzipFile::close()
{
QIODevice::close();
gzclose(d->gzd);
}
qint64 QuaGzipFile::readData(char *data, qint64 maxSize)
{
return gzread(d->gzd, (voidp)data, (unsigned)maxSize);
}
qint64 QuaGzipFile::writeData(const char *data, qint64 maxSize)
{
if (maxSize == 0)
return 0;
int written = gzwrite(d->gzd, (voidp)data, (unsigned)maxSize);
if (written == 0)
return -1;
else
return written;
}
<commit_msg>Removed unnecessary templates<commit_after>#include <QFile>
#include "quagzipfile.h"
class QuaGzipFilePrivate {
friend class QuaGzipFile;
QString fileName;
gzFile gzd;
inline QuaGzipFilePrivate(): gzd(NULL) {}
inline QuaGzipFilePrivate(const QString &fileName):
fileName(fileName), gzd(NULL) {}
template<typename FileId> bool open(FileId id,
QIODevice::OpenMode mode, QString &error);
gzFile open(int fd, const char *modeString);
gzFile open(const QString &name, const char *modeString);
};
gzFile QuaGzipFilePrivate::open(const QString &name, const char *modeString)
{
return gzopen(QFile::encodeName(name).constData(), modeString);
}
gzFile QuaGzipFilePrivate::open(int fd, const char *modeString)
{
return gzdopen(fd, modeString);
}
template<typename FileId>
bool QuaGzipFilePrivate::open(FileId id, QIODevice::OpenMode mode,
QString &error)
{
char modeString[2];
modeString[0] = modeString[1] = '\0';
if ((mode & QIODevice::ReadOnly) != 0
&& (mode & QIODevice::WriteOnly) != 0) {
error = QuaGzipFile::trUtf8("Opening gzip for both reading"
" and writing is not supported");
return false;
} else if ((mode & QIODevice::ReadOnly) != 0) {
modeString[0] = 'r';
} else if ((mode & QIODevice::WriteOnly) != 0) {
modeString[0] = 'w';
} else {
error = QuaGzipFile::trUtf8("You can open a gzip either for reading"
" or for writing. Which is it?");
return false;
}
gzd = open(id, modeString);
if (gzd == NULL) {
error = QuaGzipFile::trUtf8("Could not gzopen() file");
return false;
}
return true;
}
QuaGzipFile::QuaGzipFile():
d(new QuaGzipFilePrivate())
{
}
QuaGzipFile::QuaGzipFile(QObject *parent):
QIODevice(parent),
d(new QuaGzipFilePrivate())
{
}
QuaGzipFile::QuaGzipFile(const QString &fileName, QObject *parent):
QIODevice(parent),
d(new QuaGzipFilePrivate(fileName))
{
}
QuaGzipFile::~QuaGzipFile()
{
if (isOpen()) {
close();
}
delete d;
}
void QuaGzipFile::setFileName(const QString& fileName)
{
d->fileName = fileName;
}
QString QuaGzipFile::getFileName() const
{
return d->fileName;
}
bool QuaGzipFile::isSequential() const
{
return true;
}
bool QuaGzipFile::open(QIODevice::OpenMode mode)
{
QString error;
if (!d->open(d->fileName, mode, error)) {
setErrorString(error);
return false;
}
return QIODevice::open(mode);
}
bool QuaGzipFile::open(int fd, QIODevice::OpenMode mode)
{
QString error;
if (!d->open(fd, mode, error)) {
setErrorString(error);
return false;
}
return QIODevice::open(mode);
}
bool QuaGzipFile::flush()
{
return gzflush(d->gzd, Z_SYNC_FLUSH) == Z_OK;
}
void QuaGzipFile::close()
{
QIODevice::close();
gzclose(d->gzd);
}
qint64 QuaGzipFile::readData(char *data, qint64 maxSize)
{
return gzread(d->gzd, (voidp)data, (unsigned)maxSize);
}
qint64 QuaGzipFile::writeData(const char *data, qint64 maxSize)
{
if (maxSize == 0)
return 0;
int written = gzwrite(d->gzd, (voidp)data, (unsigned)maxSize);
if (written == 0)
return -1;
else
return written;
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include <fstream>
#include <sstream>
#include <queue>
#include "omp.h"
// Contains the various options the user can pass ptgz.
struct Settings {
Settings(): extract(),
compress(),
verbose(),
output() {}
bool extract;
bool compress;
bool verbose;
bool output;
std::string name;
};
// Checks if the user asks for help.
// Provides usage information to the user.
// Parameters: argc (int) number of cli arguments.
// argv (char *[]) user provided arguments.
void helpCheck(int argc, char *argv[]) {
if (argc == 1) {
std::cout << "ERROR: ptgz was passed no parameters. \"ptgz -h\" for help." << std::endl;
exit(0);
}
if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
std::cout << "\nptgz - Parallel Tar GZ by Ryan Chui (2017)\n" << std::endl;
exit(0);
}
}
// Gets the parameters passed by the user and stores them.
// Parameters: argc (int) number of cli arguments.
// argv (char *[]) user provided arguments.
// instance (Settings *) user argument storage.
void getSettings(int argc, char *argv[], Settings *instance) {
// Get all passed arguments
std::queue<std::string> settings;
for (int i = 1; i < argc; ++i) {
settings.push(argv[i]);
}
// Continue to check until there are no more passed arguments.
while (!settings.empty()) {
std::string arg = settings.front();
if (arg == "-x") {
if ((*instance).compress) {
std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).extract = true;
} else if (arg == "-c") {
if ((*instance).extract) {
std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).compress = true;
} else if (arg == "-v"){
(*instance).verbose = true;
} else if (arg == "-o") {
(*instance).output = true;
} else {
if (settings.size() > 1) {
std::cout << "ERROR: ptgz was called incorrectly. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).output = true;
(*instance).name = arg;
}
settings.pop();
}
if (!(*instance).output) {
std::cout << "ERROR: No output file name given. \"ptgz -h\" for help." << std::endl;
exit(0);
}
}
// Finds the number of files in the space to store.
// Parameters: numFiles (int *) number of files.
// cwd (const char *) current working directory.
void findAll(int *numFiles, const char *cwd) {
DIR *dir;
struct dirent *ent;
// Check if cwd is a directory
if ((dir = opendir(cwd)) != NULL) {
// Get all file paths within directory.
while ((ent = readdir (dir)) != NULL) {
std::string fileBuff = std::string(ent -> d_name);
if (fileBuff != "." && fileBuff != "..") {
DIR *dir2;
std::string filePath = std::string(cwd) + "/" + fileBuff;
// Check if file path is a directory.
if ((dir2 = opendir(filePath.c_str())) != NULL) {
closedir(dir2);
findAll(numFiles, filePath.c_str());
} else {
*numFiles += 1;
}
}
}
closedir(dir);
}
}
// Gets the paths for all files in the space to store.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// cwd (const char *) current working directory.
// rootPath (std::string) path from the root of the directory to be stored.
void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
DIR *dir;
struct dirent *ent;
// Check if cwd is a directory
if ((dir = opendir(cwd)) != NULL) {
// Get all file paths within directory.
while ((ent = readdir (dir)) != NULL) {
std::string fileBuff = std::string(ent -> d_name);
if (fileBuff != "." && fileBuff != "..") {
DIR *dir2;
std::string filePath = std::string(cwd) + "/" + fileBuff;
// Check if file path is a directory.
if ((dir2 = opendir(filePath.c_str())) != NULL) {
closedir(dir2);
getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
} else {
filePaths->push_back(rootPath + fileBuff);
}
}
}
closedir(dir);
}
}
// Divides files into blocks.
// Compresses each block into a single file.
// Combines all compressed blocks into a single file.
// Removes temporary blocks and header files.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// name (std::string) user given name for storage file.
// verbose (bool) user option for verbose output.
void compression(std::vector<std::string> *filePaths, std::string name, bool verbose) {
std::random_shuffle(filePaths->begin(), filePaths->end());
unsigned long long int filePathSize = filePaths->size();
unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1;
std::vector<std::string> *tarNames = new std::vector<std::string>(filePathSize / blockSize + 1);
// Gzips the blocks of files into a single compressed file
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < omp_get_max_threads() * 10; ++i) {
unsigned long long int start = blockSize * i;
if (start < filePathSize) {
// Store the name of each file for a block owned by each thread.
// Each thread will use the file to tar and gzip compress their block.
std::ofstream tmp;
tmp.open(std::to_string(i) + "." + name + ".ptgz.tmp", std::ios_base::app);
std::string gzCommand = "GZIP=-1 tar -cz -T " + std::to_string(i) + "." + name + ".ptgz.tmp -f " + std::to_string(i) + "." + name + ".tar.gz";
for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) {
tmp << filePaths->at(j) + "\n";
}
if (verbose) {
std::cout << gzCommand + "\n";
}
tmp.close();
system(gzCommand.c_str());
tarNames->at(i) = std::to_string(i) + "." + name + ".tar.gz";
}
}
// Combines gzipped blocks together into a single tarball.
// Write tarball names into an idx file for extraction.
std::ofstream idx, tmp;
idx.open(name + ".ptgz.idx", std::ios_base::app);
std::string tarCommand = "tar -c -T " + name + ".ptgz.idx -f " + name + ".ptgz.tar";
for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
idx << tarNames->at(i) + "\n";
}
idx << name + ".ptgz.idx" + "\n";
idx.close();
if (verbose) {
std::cout << tarCommand + "\n";
}
system(tarCommand.c_str());
// Removes all temporary blocks and idx file.
#pragma omp parallel for schedule(static)
for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
std::string rmCommand = tarNames->at(i);
if (verbose) {
std::cout << "remove(" + rmCommand + ")\n";
}
if (remove(rmCommand.c_str())) {
std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
}
rmCommand = std::to_string(i) + "." + name + ".ptgz.tmp";
if (verbose) {
std::cout << "remove(" + rmCommand + ")\n";
}
if (remove(rmCommand.c_str())) {
std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
}
}
std::string rmCommand;
if (verbose) {
std::cout << "remove(" + name + ".ptgz.idx)\n";
}
rmCommand = name + ".ptgz.idx";
if (remove(rmCommand.c_str())) {
std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
}
tarNames->clear();
delete(tarNames);
}
void extraction(std::vector<std::string> *filePaths, std::string name, bool verbose) {
// Unpack the 1st layer tarball
std::string exCommand = "tar xf " + name;
if (verbose) {
std::cout << exCommand + "\n";
}
// system(exCommand.c_str());
// Get the name from the name of the 1st layer tarball
for (int i = 0; i < 9; ++i) {
name.pop_back();
}
std::ifstream idx;
std::string line;
idx.open(name + ".ptgz.idx", std::ios_base::in);
while (std::getline(idx, line)) {
filePaths->push_back(line);
}
idx.close();
filePaths->pop_back();
for (int i = 0; i < filePaths->size(); ++i) {
std::cout << filePaths->at(i) << std::endl;
}
}
char cwd [PATH_MAX];
// Checks to see if the user asks for help.
// Gathers the user provided settings for ptgz.
// Finds the number of files that need to be stored.
// Gathers the file paths of all files to be stored.
// Either compresses the files or extracts the ptgz.tar archive.
int main(int argc, char *argv[]) {
Settings *instance = new Settings;
int *numFiles = new int(0);
std::vector<std::string> *filePaths = new std::vector<std::string>();
helpCheck(argc, argv);
getSettings(argc, argv, instance);
getcwd(cwd, PATH_MAX);
if ((*instance).compress) {
findAll(numFiles, cwd);
getPaths(filePaths, cwd, "");
compression(filePaths, (*instance).name, (*instance).verbose);
} else {
extraction(filePaths, (*instance).name, (*instance).verbose);
}
delete(instance);
delete(numFiles);
filePaths->clear();
delete(filePaths);
return 0;
}
<commit_msg>Added keep option to keep ptgz.tar archive. Added keep error if used without extract. Added tar.gz deletion after extraction. Added tar.gz unpacking.<commit_after>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include <fstream>
#include <sstream>
#include <queue>
#include "omp.h"
// Contains the various options the user can pass ptgz.
struct Settings {
Settings(): extract(),
compress(),
verbose(),
keep(),
output() {}
bool extract;
bool compress;
bool verbose;
bool keep;
bool output;
std::string name;
};
// Checks if the user asks for help.
// Provides usage information to the user.
// Parameters: argc (int) number of cli arguments.
// argv (char *[]) user provided arguments.
void helpCheck(int argc, char *argv[]) {
if (argc == 1) {
std::cout << "ERROR: ptgz was passed no parameters. \"ptgz -h\" for help." << std::endl;
exit(0);
}
if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
std::cout << "\nptgz - Parallel Tar GZ by Ryan Chui (2017)\n" << std::endl;
exit(0);
}
}
// Gets the parameters passed by the user and stores them.
// Parameters: argc (int) number of cli arguments.
// argv (char *[]) user provided arguments.
// instance (Settings *) user argument storage.
void getSettings(int argc, char *argv[], Settings *instance) {
// Get all passed arguments
std::queue<std::string> settings;
for (int i = 1; i < argc; ++i) {
settings.push(argv[i]);
}
// Continue to check until there are no more passed arguments.
while (!settings.empty()) {
std::string arg = settings.front();
if (arg == "-x") {
if ((*instance).compress) {
std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).extract = true;
} else if (arg == "-c") {
if ((*instance).extract) {
std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).compress = true;
} else if (arg == "-v"){
(*instance).verbose = true;
} else if (arg == "-o") {
(*instance).output = true;
} else if (arg == "-k") {
(*instance).keep = true;
} else {
if (settings.size() > 1) {
std::cout << "ERROR: ptgz was called incorrectly. \"ptgz -h\" for help." << std::endl;
exit(0);
}
(*instance).output = true;
(*instance).name = arg;
}
settings.pop();
}
if (!(*instance).output) {
std::cout << "ERROR: No output file name given. \"ptgz -h\" for help." << std::endl;
exit(0);
} else if (((*instance).keep && !(*instance).extract) {
std::cout << "ERROR: Can't use keep option without extract. \"ptgz -h\" for help." << std::endl;
}
}
// Finds the number of files in the space to store.
// Parameters: numFiles (int *) number of files.
// cwd (const char *) current working directory.
void findAll(int *numFiles, const char *cwd) {
DIR *dir;
struct dirent *ent;
// Check if cwd is a directory
if ((dir = opendir(cwd)) != NULL) {
// Get all file paths within directory.
while ((ent = readdir (dir)) != NULL) {
std::string fileBuff = std::string(ent -> d_name);
if (fileBuff != "." && fileBuff != "..") {
DIR *dir2;
std::string filePath = std::string(cwd) + "/" + fileBuff;
// Check if file path is a directory.
if ((dir2 = opendir(filePath.c_str())) != NULL) {
closedir(dir2);
findAll(numFiles, filePath.c_str());
} else {
*numFiles += 1;
}
}
}
closedir(dir);
}
}
// Gets the paths for all files in the space to store.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// cwd (const char *) current working directory.
// rootPath (std::string) path from the root of the directory to be stored.
void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
DIR *dir;
struct dirent *ent;
// Check if cwd is a directory
if ((dir = opendir(cwd)) != NULL) {
// Get all file paths within directory.
while ((ent = readdir (dir)) != NULL) {
std::string fileBuff = std::string(ent -> d_name);
if (fileBuff != "." && fileBuff != "..") {
DIR *dir2;
std::string filePath = std::string(cwd) + "/" + fileBuff;
// Check if file path is a directory.
if ((dir2 = opendir(filePath.c_str())) != NULL) {
closedir(dir2);
getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
} else {
filePaths->push_back(rootPath + fileBuff);
}
}
}
closedir(dir);
}
}
// Divides files into blocks.
// Compresses each block into a single file.
// Combines all compressed blocks into a single file.
// Removes temporary blocks and header files.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// name (std::string) user given name for storage file.
// verbose (bool) user option for verbose output.
void compression(std::vector<std::string> *filePaths, std::string name, bool verbose) {
std::random_shuffle(filePaths->begin(), filePaths->end());
unsigned long long int filePathSize = filePaths->size();
unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1;
std::vector<std::string> *tarNames = new std::vector<std::string>(filePathSize / blockSize + 1);
// Gzips the blocks of files into a single compressed file
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < omp_get_max_threads() * 10; ++i) {
unsigned long long int start = blockSize * i;
if (start < filePathSize) {
// Store the name of each file for a block owned by each thread.
// Each thread will use the file to tar and gzip compress their block.
std::ofstream tmp;
tmp.open(std::to_string(i) + "." + name + ".ptgz.tmp", std::ios_base::app);
std::string gzCommand = "GZIP=-1 tar -cz -T " + std::to_string(i) + "." + name + ".ptgz.tmp -f " + std::to_string(i) + "." + name + ".tar.gz";
for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) {
tmp << filePaths->at(j) + "\n";
}
if (verbose) {
std::cout << gzCommand + "\n";
}
tmp.close();
system(gzCommand.c_str());
tarNames->at(i) = std::to_string(i) + "." + name + ".tar.gz";
}
}
// Combines gzipped blocks together into a single tarball.
// Write tarball names into an idx file for extraction.
std::ofstream idx, tmp;
idx.open(name + ".ptgz.idx", std::ios_base::app);
std::string tarCommand = "tar -c -T " + name + ".ptgz.idx -f " + name + ".ptgz.tar";
for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
idx << tarNames->at(i) + "\n";
}
idx << name + ".ptgz.idx" + "\n";
idx.close();
if (verbose) {
std::cout << tarCommand + "\n";
}
system(tarCommand.c_str());
// Removes all temporary blocks and idx file.
#pragma omp parallel for schedule(static)
for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
std::string rmCommand = tarNames->at(i);
if (verbose) {
std::cout << "remove(" + rmCommand + ")\n";
}
if (remove(rmCommand.c_str())) {
std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
}
rmCommand = std::to_string(i) + "." + name + ".ptgz.tmp";
if (verbose) {
std::cout << "remove(" + rmCommand + ")\n";
}
if (remove(rmCommand.c_str())) {
std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
}
}
std::string rmCommand;
if (verbose) {
std::cout << "remove(" + name + ".ptgz.idx)\n";
}
rmCommand = name + ".ptgz.idx";
if (remove(rmCommand.c_str())) {
std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
}
tarNames->clear();
delete(tarNames);
}
void extraction(std::vector<std::string> *filePaths, std::string name, bool verbose, bool keep) {
// Unpack the 1st layer tarball
std::string exCommand = "tar xf " + name;
if (verbose) {
std::cout << exCommand + "\n";
}
// system(exCommand.c_str());
// Get the name from the name of the 1st layer tarball
for (int i = 0; i < 9; ++i) {
name.pop_back();
}
// Read in all tar.gz files form the ptgz.idx file
// Delete the ptgz.idx file
std::ifstream idx;
std::string line;
idx.open(name + ".ptgz.idx", std::ios_base::in);
while (std::getline(idx, line)) {
filePaths->push_back(line);
}
idx.close();
std::string idxRmCommand = filePaths->back();
remove(idxRmCommand.c_str());
filePaths->pop_back();
// Unpack each tar.gz file
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < filePaths->size(); ++i) {
std::string gzCommand = "tar xzf " + filePaths->at(i);
if (verbose) {
std::cout << gzCommand + "\n";
}
system(gzCommand.c_str());
}
// Delete each tar.gz file
#pragma omp parallel for schedule(static)
for (int i = 0; i < filePaths->size(); ++i) {
std::string gzRmCommand = filePaths->at(i);
remove(gzRmCommand.c_str());
}
// Decided whether or not to keep the ptgz.tar archive
if (!keep) {
std::string tarRmCommand = name + ".ptgz.tar";
remove(tarRmCommand);
}
}
char cwd [PATH_MAX];
// Checks to see if the user asks for help.
// Gathers the user provided settings for ptgz.
// Finds the number of files that need to be stored.
// Gathers the file paths of all files to be stored.
// Either compresses the files or extracts the ptgz.tar archive.
int main(int argc, char *argv[]) {
Settings *instance = new Settings;
int *numFiles = new int(0);
std::vector<std::string> *filePaths = new std::vector<std::string>();
helpCheck(argc, argv);
getSettings(argc, argv, instance);
getcwd(cwd, PATH_MAX);
if ((*instance).compress) {
findAll(numFiles, cwd);
getPaths(filePaths, cwd, "");
compression(filePaths, (*instance).name, (*instance).verbose);
} else {
extraction(filePaths, (*instance).name, (*instance).verbose, (*instance).keep);
}
delete(instance);
delete(numFiles);
filePaths->clear();
delete(filePaths);
return 0;
}
<|endoftext|> |
<commit_before>//Copyright (c) 2022 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <polyclipping/clipper.hpp>
#include "Application.h" //To get settings.
#include "ExtruderTrain.h"
#include "raft.h"
#include "Slice.h"
#include "sliceDataStorage.h"
#include "support.h"
#include "settings/EnumSettings.h" //For EPlatformAdhesion.
#include "utils/math.h"
namespace cura
{
void Raft::generate(SliceDataStorage& storage)
{
assert(storage.raftOutline.size() == 0 && "Raft polygon isn't generated yet, so should be empty!");
const Settings& settings = Application::getInstance().current_slice->scene.current_mesh_group->settings.get<ExtruderTrain&>("adhesion_extruder_nr").settings;
const coord_t distance = settings.get<coord_t>("raft_margin");
constexpr bool include_support = true;
constexpr bool include_prime_tower = true;
Polygons global_raft_outlines{ storage.getLayerOutlines(0, include_support, include_prime_tower).offset(distance, ClipperLib::jtRound) };
const coord_t shield_line_width_layer0 = settings.get<coord_t>("skirt_brim_line_width");
if (storage.draft_protection_shield.size() > 0)
{
Polygons draft_shield_raft = storage.draft_protection_shield.offset(shield_line_width_layer0) // start half a line width outside shield
.difference(storage.draft_protection_shield.offset(-distance - shield_line_width_layer0 / 2, ClipperLib::jtRound)); // end distance inside shield
global_raft_outlines = global_raft_outlines.unionPolygons(draft_shield_raft);
}
if (storage.oozeShield.size() > 0 && storage.oozeShield[0].size() > 0)
{
const Polygons& ooze_shield = storage.oozeShield[0];
Polygons ooze_shield_raft = ooze_shield.offset(shield_line_width_layer0) // start half a line width outside shield
.difference(ooze_shield.offset(-distance - shield_line_width_layer0 / 2, ClipperLib::jtRound)); // end distance inside shield
global_raft_outlines = global_raft_outlines.unionPolygons(ooze_shield_raft);
}
if(settings.get<bool>("raft_remove_inside_corners"))
{
global_raft_outlines.makeConvex();
}
else
{
const coord_t smoothing = settings.get<coord_t>("raft_smoothing");
global_raft_outlines = global_raft_outlines.offset(smoothing, ClipperLib::jtRound).offset(-smoothing, ClipperLib::jtRound); // remove small holes and smooth inward corners
}
constexpr bool dont_include_prime_tower = false;
const Polygons raw_raft_without_prime{ storage.getLayerOutlines(0, include_support, dont_include_prime_tower).offset(distance, ClipperLib::jtRound) };
storage.primeRaftOutline = global_raft_outlines.difference(raw_raft_without_prime);
storage.raftOutline = global_raft_outlines.difference(storage.primeRaftOutline);
}
coord_t Raft::getTotalThickness()
{
const ExtruderTrain& train = Application::getInstance().current_slice->scene.current_mesh_group->settings.get<ExtruderTrain&>("adhesion_extruder_nr");
return train.settings.get<coord_t>("raft_base_thickness")
+ train.settings.get<size_t>("raft_interface_layers") * train.settings.get<coord_t>("raft_interface_thickness")
+ train.settings.get<size_t>("raft_surface_layers") * train.settings.get<coord_t>("raft_surface_thickness");
}
coord_t Raft::getZdiffBetweenRaftAndLayer1()
{
const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings;
const ExtruderTrain& train = mesh_group_settings.get<ExtruderTrain&>("adhesion_extruder_nr");
if (mesh_group_settings.get<EPlatformAdhesion>("adhesion_type") != EPlatformAdhesion::RAFT)
{
return 0;
}
const coord_t airgap = std::max(coord_t(0), train.settings.get<coord_t>("raft_airgap"));
const coord_t layer_0_overlap = mesh_group_settings.get<coord_t>("layer_0_z_overlap");
const coord_t layer_height_0 = mesh_group_settings.get<coord_t>("layer_height_0");
const coord_t z_diff_raft_to_bottom_of_layer_1 = std::max(coord_t(0), airgap + layer_height_0 - layer_0_overlap);
return z_diff_raft_to_bottom_of_layer_1;
}
size_t Raft::getFillerLayerCount()
{
const coord_t normal_layer_height = Application::getInstance().current_slice->scene.current_mesh_group->settings.get<coord_t>("layer_height");
return round_divide(getZdiffBetweenRaftAndLayer1(), normal_layer_height);
}
coord_t Raft::getFillerLayerHeight()
{
const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings;
if (mesh_group_settings.get<EPlatformAdhesion>("adhesion_type") != EPlatformAdhesion::RAFT)
{
const coord_t normal_layer_height = mesh_group_settings.get<coord_t>("layer_height");
return normal_layer_height;
}
return round_divide(getZdiffBetweenRaftAndLayer1(), getFillerLayerCount());
}
size_t Raft::getTotalExtraLayers()
{
const ExtruderTrain& train = Application::getInstance().current_slice->scene.current_mesh_group->settings.get<ExtruderTrain&>("adhesion_extruder_nr");
if (train.settings.get<EPlatformAdhesion>("adhesion_type") != EPlatformAdhesion::RAFT)
{
return 0;
}
return 1 + train.settings.get<size_t>("raft_interface_layers") + train.settings.get<size_t>("raft_surface_layers") + getFillerLayerCount();
}
}//namespace cura
<commit_msg>Don't print 'all same extruder' prime raft without prime tower.<commit_after>//Copyright (c) 2022 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <polyclipping/clipper.hpp>
#include "Application.h" //To get settings.
#include "ExtruderTrain.h"
#include "raft.h"
#include "Slice.h"
#include "sliceDataStorage.h"
#include "support.h"
#include "settings/EnumSettings.h" //For EPlatformAdhesion.
#include "utils/math.h"
namespace cura
{
void Raft::generate(SliceDataStorage& storage)
{
assert(storage.raftOutline.size() == 0 && "Raft polygon isn't generated yet, so should be empty!");
const Settings& settings = Application::getInstance().current_slice->scene.current_mesh_group->settings.get<ExtruderTrain&>("adhesion_extruder_nr").settings;
const coord_t distance = settings.get<coord_t>("raft_margin");
constexpr bool include_support = true;
constexpr bool include_prime_tower = true;
Polygons global_raft_outlines{ storage.getLayerOutlines(0, include_support, include_prime_tower).offset(distance, ClipperLib::jtRound) };
const coord_t shield_line_width_layer0 = settings.get<coord_t>("skirt_brim_line_width");
if (storage.draft_protection_shield.size() > 0)
{
Polygons draft_shield_raft = storage.draft_protection_shield.offset(shield_line_width_layer0) // start half a line width outside shield
.difference(storage.draft_protection_shield.offset(-distance - shield_line_width_layer0 / 2, ClipperLib::jtRound)); // end distance inside shield
global_raft_outlines = global_raft_outlines.unionPolygons(draft_shield_raft);
}
if (storage.oozeShield.size() > 0 && storage.oozeShield[0].size() > 0)
{
const Polygons& ooze_shield = storage.oozeShield[0];
Polygons ooze_shield_raft = ooze_shield.offset(shield_line_width_layer0) // start half a line width outside shield
.difference(ooze_shield.offset(-distance - shield_line_width_layer0 / 2, ClipperLib::jtRound)); // end distance inside shield
global_raft_outlines = global_raft_outlines.unionPolygons(ooze_shield_raft);
}
if(settings.get<bool>("raft_remove_inside_corners"))
{
global_raft_outlines.makeConvex();
}
else
{
const coord_t smoothing = settings.get<coord_t>("raft_smoothing");
global_raft_outlines = global_raft_outlines.offset(smoothing, ClipperLib::jtRound).offset(-smoothing, ClipperLib::jtRound); // remove small holes and smooth inward corners
}
constexpr bool dont_include_prime_tower = false;
const Polygons raw_raft_without_prime{ storage.getLayerOutlines(0, include_support, dont_include_prime_tower).offset(distance, ClipperLib::jtRound) };
storage.primeRaftOutline = global_raft_outlines.difference(raw_raft_without_prime);
storage.raftOutline = global_raft_outlines.difference(storage.primeRaftOutline);
if (storage.primeTower.enabled && ! storage.primeTower.would_have_actual_tower)
{
// Find out if the prime-tower part of the raft still needs to be printed, even if there is no actual tower.
// This will only happen if the different raft layers are printed by different extruders.
const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings;
const size_t base_extruder_nr = mesh_group_settings.get<ExtruderTrain&>("raft_base_extruder_nr").extruder_nr;
const size_t interface_extruder_nr = mesh_group_settings.get<ExtruderTrain&>("raft_interface_extruder_nr").extruder_nr;
const size_t surface_extruder_nr = mesh_group_settings.get<ExtruderTrain&>("raft_surface_extruder_nr").extruder_nr;
if (base_extruder_nr == interface_extruder_nr && base_extruder_nr == surface_extruder_nr)
{
storage.primeRaftOutline.clear();
}
}
}
coord_t Raft::getTotalThickness()
{
const ExtruderTrain& train = Application::getInstance().current_slice->scene.current_mesh_group->settings.get<ExtruderTrain&>("adhesion_extruder_nr");
return train.settings.get<coord_t>("raft_base_thickness")
+ train.settings.get<size_t>("raft_interface_layers") * train.settings.get<coord_t>("raft_interface_thickness")
+ train.settings.get<size_t>("raft_surface_layers") * train.settings.get<coord_t>("raft_surface_thickness");
}
coord_t Raft::getZdiffBetweenRaftAndLayer1()
{
const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings;
const ExtruderTrain& train = mesh_group_settings.get<ExtruderTrain&>("adhesion_extruder_nr");
if (mesh_group_settings.get<EPlatformAdhesion>("adhesion_type") != EPlatformAdhesion::RAFT)
{
return 0;
}
const coord_t airgap = std::max(coord_t(0), train.settings.get<coord_t>("raft_airgap"));
const coord_t layer_0_overlap = mesh_group_settings.get<coord_t>("layer_0_z_overlap");
const coord_t layer_height_0 = mesh_group_settings.get<coord_t>("layer_height_0");
const coord_t z_diff_raft_to_bottom_of_layer_1 = std::max(coord_t(0), airgap + layer_height_0 - layer_0_overlap);
return z_diff_raft_to_bottom_of_layer_1;
}
size_t Raft::getFillerLayerCount()
{
const coord_t normal_layer_height = Application::getInstance().current_slice->scene.current_mesh_group->settings.get<coord_t>("layer_height");
return round_divide(getZdiffBetweenRaftAndLayer1(), normal_layer_height);
}
coord_t Raft::getFillerLayerHeight()
{
const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings;
if (mesh_group_settings.get<EPlatformAdhesion>("adhesion_type") != EPlatformAdhesion::RAFT)
{
const coord_t normal_layer_height = mesh_group_settings.get<coord_t>("layer_height");
return normal_layer_height;
}
return round_divide(getZdiffBetweenRaftAndLayer1(), getFillerLayerCount());
}
size_t Raft::getTotalExtraLayers()
{
const ExtruderTrain& train = Application::getInstance().current_slice->scene.current_mesh_group->settings.get<ExtruderTrain&>("adhesion_extruder_nr");
if (train.settings.get<EPlatformAdhesion>("adhesion_type") != EPlatformAdhesion::RAFT)
{
return 0;
}
return 1 + train.settings.get<size_t>("raft_interface_layers") + train.settings.get<size_t>("raft_surface_layers") + getFillerLayerCount();
}
}//namespace cura
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 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 "src/profiling/memory/unwinding.h"
#include <sys/types.h>
#include <unistd.h>
#include <unwindstack/MachineArm.h>
#include <unwindstack/MachineArm64.h>
#include <unwindstack/MachineMips.h>
#include <unwindstack/MachineMips64.h>
#include <unwindstack/MachineX86.h>
#include <unwindstack/MachineX86_64.h>
#include <unwindstack/Maps.h>
#include <unwindstack/Memory.h>
#include <unwindstack/Regs.h>
#include <unwindstack/RegsArm.h>
#include <unwindstack/RegsArm64.h>
#include <unwindstack/RegsMips.h>
#include <unwindstack/RegsMips64.h>
#include <unwindstack/RegsX86.h>
#include <unwindstack/RegsX86_64.h>
#include <unwindstack/Unwinder.h>
#include <unwindstack/UserArm.h>
#include <unwindstack/UserArm64.h>
#include <unwindstack/UserMips.h>
#include <unwindstack/UserMips64.h>
#include <unwindstack/UserX86.h>
#include <unwindstack/UserX86_64.h>
#include <procinfo/process_map.h>
#include "perfetto/base/file_utils.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/scoped_file.h"
#include "perfetto/base/string_utils.h"
#include "src/profiling/memory/wire_protocol.h"
namespace perfetto {
namespace profiling {
namespace {
size_t kMaxFrames = 1000;
#pragma GCC diagnostic push
// We do not care about deterministic destructor order.
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
static std::vector<std::string> kSkipMaps{"heapprofd_client.so"};
#pragma GCC diagnostic pop
std::unique_ptr<unwindstack::Regs> CreateFromRawData(unwindstack::ArchEnum arch,
void* raw_data) {
std::unique_ptr<unwindstack::Regs> ret;
// unwindstack::RegsX::Read returns a raw ptr which we are expected to free.
switch (arch) {
case unwindstack::ARCH_X86:
ret.reset(unwindstack::RegsX86::Read(raw_data));
break;
case unwindstack::ARCH_X86_64:
ret.reset(unwindstack::RegsX86_64::Read(raw_data));
break;
case unwindstack::ARCH_ARM:
ret.reset(unwindstack::RegsArm::Read(raw_data));
break;
case unwindstack::ARCH_ARM64:
ret.reset(unwindstack::RegsArm64::Read(raw_data));
break;
case unwindstack::ARCH_MIPS:
ret.reset(unwindstack::RegsMips::Read(raw_data));
break;
case unwindstack::ARCH_MIPS64:
ret.reset(unwindstack::RegsMips64::Read(raw_data));
break;
case unwindstack::ARCH_UNKNOWN:
ret.reset(nullptr);
break;
}
return ret;
}
// Behaves as a pread64, emulating it if not already exposed by the standard
// library. Safe to use on 32bit platforms for addresses with the top bit set.
// Clobbers the |fd| seek position if emulating.
ssize_t ReadAtOffsetClobberSeekPos(int fd,
void* buf,
size_t count,
uint64_t addr) {
#ifdef __BIONIC__
return pread64(fd, buf, count, static_cast<off64_t>(addr));
#else
if (lseek64(fd, static_cast<off64_t>(addr), SEEK_SET) == -1)
return -1;
return read(fd, buf, count);
#endif
}
} // namespace
StackOverlayMemory::StackOverlayMemory(std::shared_ptr<unwindstack::Memory> mem,
uint64_t sp,
uint8_t* stack,
size_t size)
: mem_(std::move(mem)), sp_(sp), stack_end_(sp + size), stack_(stack) {}
size_t StackOverlayMemory::Read(uint64_t addr, void* dst, size_t size) {
if (addr >= sp_ && addr + size <= stack_end_ && addr + size > sp_) {
size_t offset = static_cast<size_t>(addr - sp_);
memcpy(dst, stack_ + offset, size);
return size;
}
return mem_->Read(addr, dst, size);
}
FDMemory::FDMemory(base::ScopedFile mem_fd) : mem_fd_(std::move(mem_fd)) {}
size_t FDMemory::Read(uint64_t addr, void* dst, size_t size) {
ssize_t rd = ReadAtOffsetClobberSeekPos(*mem_fd_, dst, size, addr);
if (rd == -1) {
PERFETTO_DPLOG("read at offset");
return 0;
}
return static_cast<size_t>(rd);
}
FileDescriptorMaps::FileDescriptorMaps(base::ScopedFile fd)
: fd_(std::move(fd)) {}
bool FileDescriptorMaps::Parse() {
// If the process has already exited, lseek or ReadFileDescriptor will
// return false.
if (lseek(*fd_, 0, SEEK_SET) == -1)
return false;
std::string content;
if (!base::ReadFileDescriptor(*fd_, &content))
return false;
return android::procinfo::ReadMapFileContent(
&content[0], [&](uint64_t start, uint64_t end, uint16_t flags,
uint64_t pgoff, ino_t, const char* name) {
// Mark a device map in /dev/ and not in /dev/ashmem/ specially.
if (strncmp(name, "/dev/", 5) == 0 &&
strncmp(name + 5, "ashmem/", 7) != 0) {
flags |= unwindstack::MAPS_FLAGS_DEVICE_MAP;
}
maps_.push_back(
new unwindstack::MapInfo(nullptr, start, end, pgoff, flags, name));
});
}
void FileDescriptorMaps::Reset() {
for (unwindstack::MapInfo* info : maps_)
delete info;
maps_.clear();
}
bool DoUnwind(WireMessage* msg, UnwindingMetadata* metadata, AllocRecord* out) {
AllocMetadata* alloc_metadata = msg->alloc_header;
std::unique_ptr<unwindstack::Regs> regs(
CreateFromRawData(alloc_metadata->arch, alloc_metadata->register_data));
if (regs == nullptr) {
unwindstack::FrameData frame_data{};
frame_data.function_name = "ERROR READING REGISTERS";
frame_data.map_name = "ERROR";
out->frames.emplace_back(frame_data, "");
PERFETTO_DLOG("regs");
return false;
}
uint8_t* stack = reinterpret_cast<uint8_t*>(msg->payload);
std::shared_ptr<unwindstack::Memory> mems =
std::make_shared<StackOverlayMemory>(metadata->fd_mem,
alloc_metadata->stack_pointer, stack,
msg->payload_size);
unwindstack::Unwinder unwinder(kMaxFrames, &metadata->maps, regs.get(), mems);
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());
unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());
#endif
// Surpress incorrect "variable may be uninitialized" error for if condition
// after this loop. error_code = LastErrorCode gets run at least once.
uint8_t error_code = 0;
for (int attempt = 0; attempt < 2; ++attempt) {
if (attempt > 0) {
metadata->ReparseMaps();
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());
unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());
#endif
}
unwinder.Unwind(&kSkipMaps, nullptr);
error_code = unwinder.LastErrorCode();
if (error_code != unwindstack::ERROR_INVALID_MAP)
break;
}
std::vector<unwindstack::FrameData> frames = unwinder.ConsumeFrames();
for (unwindstack::FrameData& fd : frames) {
std::string build_id;
if (fd.map_name != "") {
unwindstack::MapInfo* map_info = metadata->maps.Find(fd.pc);
if (map_info)
build_id = map_info->GetBuildID();
}
out->frames.emplace_back(std::move(fd), std::move(build_id));
}
if (error_code != 0) {
unwindstack::FrameData frame_data{};
frame_data.function_name = "ERROR " + std::to_string(error_code);
frame_data.map_name = "ERROR";
out->frames.emplace_back(frame_data, "");
PERFETTO_DLOG("unwinding failed %" PRIu8, error_code);
}
return true;
}
bool HandleUnwindingRecord(UnwindingRecord* rec, BookkeepingRecord* out) {
WireMessage msg;
if (!ReceiveWireMessage(reinterpret_cast<char*>(rec->data.get()), rec->size,
&msg))
return false;
if (msg.record_type == RecordType::Malloc) {
std::shared_ptr<UnwindingMetadata> metadata = rec->metadata.lock();
if (!metadata) {
// Process has already gone away.
return false;
}
out->alloc_record.alloc_metadata = *msg.alloc_header;
out->pid = rec->pid;
out->client_generation = msg.alloc_header->client_generation;
out->record_type = BookkeepingRecord::Type::Malloc;
DoUnwind(&msg, metadata.get(), &out->alloc_record);
return true;
} else if (msg.record_type == RecordType::Free) {
out->record_type = BookkeepingRecord::Type::Free;
out->pid = rec->pid;
out->client_generation = msg.free_header->client_generation;
// We need to keep this alive, because msg.free_header is a pointer into
// this.
out->free_record.free_data = std::move(rec->data);
out->free_record.metadata = msg.free_header;
return true;
} else {
PERFETTO_DFATAL("Invalid record type.");
return false;
}
}
void UnwindingMainLoop(BoundedQueue<UnwindingRecord>* input_queue,
BoundedQueue<BookkeepingRecord>* output_queue) {
for (;;) {
UnwindingRecord rec;
if (!input_queue->Get(&rec))
return;
BookkeepingRecord out;
if (HandleUnwindingRecord(&rec, &out))
output_queue->Add(std::move(out));
}
}
} // namespace profiling
} // namespace perfetto
<commit_msg>Use emplace_back over push_back to support unique_ptr. am: 5abc126b07 am: ec0446a677<commit_after>/*
* Copyright (C) 2018 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 "src/profiling/memory/unwinding.h"
#include <sys/types.h>
#include <unistd.h>
#include <unwindstack/MachineArm.h>
#include <unwindstack/MachineArm64.h>
#include <unwindstack/MachineMips.h>
#include <unwindstack/MachineMips64.h>
#include <unwindstack/MachineX86.h>
#include <unwindstack/MachineX86_64.h>
#include <unwindstack/Maps.h>
#include <unwindstack/Memory.h>
#include <unwindstack/Regs.h>
#include <unwindstack/RegsArm.h>
#include <unwindstack/RegsArm64.h>
#include <unwindstack/RegsMips.h>
#include <unwindstack/RegsMips64.h>
#include <unwindstack/RegsX86.h>
#include <unwindstack/RegsX86_64.h>
#include <unwindstack/Unwinder.h>
#include <unwindstack/UserArm.h>
#include <unwindstack/UserArm64.h>
#include <unwindstack/UserMips.h>
#include <unwindstack/UserMips64.h>
#include <unwindstack/UserX86.h>
#include <unwindstack/UserX86_64.h>
#include <procinfo/process_map.h>
#include "perfetto/base/file_utils.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/scoped_file.h"
#include "perfetto/base/string_utils.h"
#include "src/profiling/memory/wire_protocol.h"
namespace perfetto {
namespace profiling {
namespace {
size_t kMaxFrames = 1000;
#pragma GCC diagnostic push
// We do not care about deterministic destructor order.
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
static std::vector<std::string> kSkipMaps{"heapprofd_client.so"};
#pragma GCC diagnostic pop
std::unique_ptr<unwindstack::Regs> CreateFromRawData(unwindstack::ArchEnum arch,
void* raw_data) {
std::unique_ptr<unwindstack::Regs> ret;
// unwindstack::RegsX::Read returns a raw ptr which we are expected to free.
switch (arch) {
case unwindstack::ARCH_X86:
ret.reset(unwindstack::RegsX86::Read(raw_data));
break;
case unwindstack::ARCH_X86_64:
ret.reset(unwindstack::RegsX86_64::Read(raw_data));
break;
case unwindstack::ARCH_ARM:
ret.reset(unwindstack::RegsArm::Read(raw_data));
break;
case unwindstack::ARCH_ARM64:
ret.reset(unwindstack::RegsArm64::Read(raw_data));
break;
case unwindstack::ARCH_MIPS:
ret.reset(unwindstack::RegsMips::Read(raw_data));
break;
case unwindstack::ARCH_MIPS64:
ret.reset(unwindstack::RegsMips64::Read(raw_data));
break;
case unwindstack::ARCH_UNKNOWN:
ret.reset(nullptr);
break;
}
return ret;
}
// Behaves as a pread64, emulating it if not already exposed by the standard
// library. Safe to use on 32bit platforms for addresses with the top bit set.
// Clobbers the |fd| seek position if emulating.
ssize_t ReadAtOffsetClobberSeekPos(int fd,
void* buf,
size_t count,
uint64_t addr) {
#ifdef __BIONIC__
return pread64(fd, buf, count, static_cast<off64_t>(addr));
#else
if (lseek64(fd, static_cast<off64_t>(addr), SEEK_SET) == -1)
return -1;
return read(fd, buf, count);
#endif
}
} // namespace
StackOverlayMemory::StackOverlayMemory(std::shared_ptr<unwindstack::Memory> mem,
uint64_t sp,
uint8_t* stack,
size_t size)
: mem_(std::move(mem)), sp_(sp), stack_end_(sp + size), stack_(stack) {}
size_t StackOverlayMemory::Read(uint64_t addr, void* dst, size_t size) {
if (addr >= sp_ && addr + size <= stack_end_ && addr + size > sp_) {
size_t offset = static_cast<size_t>(addr - sp_);
memcpy(dst, stack_ + offset, size);
return size;
}
return mem_->Read(addr, dst, size);
}
FDMemory::FDMemory(base::ScopedFile mem_fd) : mem_fd_(std::move(mem_fd)) {}
size_t FDMemory::Read(uint64_t addr, void* dst, size_t size) {
ssize_t rd = ReadAtOffsetClobberSeekPos(*mem_fd_, dst, size, addr);
if (rd == -1) {
PERFETTO_DPLOG("read at offset");
return 0;
}
return static_cast<size_t>(rd);
}
FileDescriptorMaps::FileDescriptorMaps(base::ScopedFile fd)
: fd_(std::move(fd)) {}
bool FileDescriptorMaps::Parse() {
// If the process has already exited, lseek or ReadFileDescriptor will
// return false.
if (lseek(*fd_, 0, SEEK_SET) == -1)
return false;
std::string content;
if (!base::ReadFileDescriptor(*fd_, &content))
return false;
return android::procinfo::ReadMapFileContent(
&content[0], [&](uint64_t start, uint64_t end, uint16_t flags,
uint64_t pgoff, ino_t, const char* name) {
// Mark a device map in /dev/ and not in /dev/ashmem/ specially.
if (strncmp(name, "/dev/", 5) == 0 &&
strncmp(name + 5, "ashmem/", 7) != 0) {
flags |= unwindstack::MAPS_FLAGS_DEVICE_MAP;
}
maps_.emplace_back(
new unwindstack::MapInfo(nullptr, start, end, pgoff, flags, name));
});
}
void FileDescriptorMaps::Reset() {
maps_.clear();
}
bool DoUnwind(WireMessage* msg, UnwindingMetadata* metadata, AllocRecord* out) {
AllocMetadata* alloc_metadata = msg->alloc_header;
std::unique_ptr<unwindstack::Regs> regs(
CreateFromRawData(alloc_metadata->arch, alloc_metadata->register_data));
if (regs == nullptr) {
unwindstack::FrameData frame_data{};
frame_data.function_name = "ERROR READING REGISTERS";
frame_data.map_name = "ERROR";
out->frames.emplace_back(frame_data, "");
PERFETTO_DLOG("regs");
return false;
}
uint8_t* stack = reinterpret_cast<uint8_t*>(msg->payload);
std::shared_ptr<unwindstack::Memory> mems =
std::make_shared<StackOverlayMemory>(metadata->fd_mem,
alloc_metadata->stack_pointer, stack,
msg->payload_size);
unwindstack::Unwinder unwinder(kMaxFrames, &metadata->maps, regs.get(), mems);
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());
unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());
#endif
// Surpress incorrect "variable may be uninitialized" error for if condition
// after this loop. error_code = LastErrorCode gets run at least once.
uint8_t error_code = 0;
for (int attempt = 0; attempt < 2; ++attempt) {
if (attempt > 0) {
metadata->ReparseMaps();
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());
unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());
#endif
}
unwinder.Unwind(&kSkipMaps, nullptr);
error_code = unwinder.LastErrorCode();
if (error_code != unwindstack::ERROR_INVALID_MAP)
break;
}
std::vector<unwindstack::FrameData> frames = unwinder.ConsumeFrames();
for (unwindstack::FrameData& fd : frames) {
std::string build_id;
if (fd.map_name != "") {
unwindstack::MapInfo* map_info = metadata->maps.Find(fd.pc);
if (map_info)
build_id = map_info->GetBuildID();
}
out->frames.emplace_back(std::move(fd), std::move(build_id));
}
if (error_code != 0) {
unwindstack::FrameData frame_data{};
frame_data.function_name = "ERROR " + std::to_string(error_code);
frame_data.map_name = "ERROR";
out->frames.emplace_back(frame_data, "");
PERFETTO_DLOG("unwinding failed %" PRIu8, error_code);
}
return true;
}
bool HandleUnwindingRecord(UnwindingRecord* rec, BookkeepingRecord* out) {
WireMessage msg;
if (!ReceiveWireMessage(reinterpret_cast<char*>(rec->data.get()), rec->size,
&msg))
return false;
if (msg.record_type == RecordType::Malloc) {
std::shared_ptr<UnwindingMetadata> metadata = rec->metadata.lock();
if (!metadata) {
// Process has already gone away.
return false;
}
out->alloc_record.alloc_metadata = *msg.alloc_header;
out->pid = rec->pid;
out->client_generation = msg.alloc_header->client_generation;
out->record_type = BookkeepingRecord::Type::Malloc;
DoUnwind(&msg, metadata.get(), &out->alloc_record);
return true;
} else if (msg.record_type == RecordType::Free) {
out->record_type = BookkeepingRecord::Type::Free;
out->pid = rec->pid;
out->client_generation = msg.free_header->client_generation;
// We need to keep this alive, because msg.free_header is a pointer into
// this.
out->free_record.free_data = std::move(rec->data);
out->free_record.metadata = msg.free_header;
return true;
} else {
PERFETTO_DFATAL("Invalid record type.");
return false;
}
}
void UnwindingMainLoop(BoundedQueue<UnwindingRecord>* input_queue,
BoundedQueue<BookkeepingRecord>* output_queue) {
for (;;) {
UnwindingRecord rec;
if (!input_queue->Get(&rec))
return;
BookkeepingRecord out;
if (HandleUnwindingRecord(&rec, &out))
output_queue->Add(std::move(out));
}
}
} // namespace profiling
} // namespace perfetto
<|endoftext|> |
<commit_before>/*
* Open Chinese Convert
*
* Copyright 2010-2013 BYVoid <[email protected]>
*
* 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.
*/
#pragma once
#include "Common.hpp"
#include "DictEntry.hpp"
namespace opencc {
class OPENCC_EXPORT Dict {
public:
virtual size_t KeyMaxLength() const = 0;
virtual Optional<DictEntry> Match(const char* word) = 0;
virtual Optional<DictEntry> MatchPrefix(const char* word);
virtual vector<DictEntry> MatchAllPrefixes(const char* word);
virtual vector<DictEntry> GetLexicon() = 0;
virtual void LoadFromDict(Dict* dictionary) = 0;
};
}
<commit_msg>Add std::string interface for Dict<commit_after>/*
* Open Chinese Convert
*
* Copyright 2010-2013 BYVoid <[email protected]>
*
* 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.
*/
#pragma once
#include "Common.hpp"
#include "DictEntry.hpp"
namespace opencc {
class OPENCC_EXPORT Dict {
public:
virtual size_t KeyMaxLength() const = 0;
virtual Optional<DictEntry> Match(const char* word) = 0;
virtual Optional<DictEntry> MatchPrefix(const char* word);
virtual vector<DictEntry> MatchAllPrefixes(const char* word);
Optional<DictEntry> Match(const string& word) {
return Match(word.c_str());
}
Optional<DictEntry> MatchPrefix(const string& word) {
return MatchPrefix(word.c_str());
}
vector<DictEntry> MatchAllPrefixes(const string& word) {
return MatchAllPrefixes(word.c_str());
}
virtual vector<DictEntry> GetLexicon() = 0;
virtual void LoadFromDict(Dict* dictionary) = 0;
};
}
<|endoftext|> |
<commit_before>#include "protocol.h"
void Protocol::connectServer() {
}
bool Protocol::connected() {
}
bool Protocol::shouldUnload() {
}
void Protocol::disconnect() {
}
void Protocol::onRehash() {
}
void Protocol::sendMsg(const std::string& client, const std::string& target, const std::string& message, const std::map<std::string, std::string>& tags) {
}
void Protocol::sendNotice(const std::string& client, const std::string& target, const std::string& message, const std::map<std::string, std::string>& tags) {
}
void Protocol::setMode(const std::string& client, const std::string& target, const std::list<std::tuple<bool, std::string, std::string>>& modes, const std::map<std::string, std::string>& tags) {
}
void Protocol::joinChan(const std::string& client, const std::string& channel, const std::map<std::string, std::string>& tags) {
}
void Protocol::joinChan(const std::string& client, const std::string& channel, const std::map<std::string, std::string>& tags) {
}
void Protocol::partChan(const std::string& client, const std::string& channel, const std::string& reason, const std::map<std::string, std::string>& tags) {
}
void Protocol::kickUser(const std::string& client, const std::string& channel, const std::string& user, const std::string& reason, const std::map<std::string, std::string>& tags) {
}
void Protocol::setTopic(const std::string& client, const std::string& channel, const std::string& topic, const std::map<std::string, std::string>& tags) {
}
void Protocol::inviteUser(const std::string& client, const std::string& channel, const std::string& user, const std::map<std::string, std::string>& tags) {
}
void Protocol::knock(const std::string& client, const std::string& channel, const std::string& reason, const std::map<std::string, std::string>& tags) {
}
void Protocol::changeNick(const std::string& client, const std::string& newNick, const std::map<std::string, std::string>& tags) {
}
void Protocol::sendPing(const std::string& client, const std::string& data, const std::map<std::string, std::string>& tags) {
}
void Protocol::setAway(const std::string& client, const std::string& reason, const std::map<std::string, std::string>& tags) {
}
void Protocol::setUnaway(const std::string& client, const std::map<std::string, std::string>& tags) {
}
void Protocol::oper(const std::string& client, const std::string& username, const std::string& password, const std::map<std::string, std::string>& tags) {
}
void Protocol::sendWallops(const std::string& client, const std::string& message, const std::map<std::string, std::string>& tags) {
}
void Protocol::sendOtherData(const std::string& client, const IRCMessage* line) {
}
std::string Protocol::addClient(const std::string& nick, const std::string& ident, const std::string& gecos) {
}
void Protocol::removeClient(const std::string& client) {
}
std::set<std::string> Protocol::serverCapabilities() {
}
std::set<char> Protocol::chanTypes() {
}
std::list<std::pair<ModeType, std::string>> Protocol::allChanModes() {
}
ModeType Protocol::chanModeType(const std::string& mode) {
}
char Protocol::prefixSymbol(const std::string& mode) {
}
std::pair<std::string, char> Protocol::compareStatus(const std::string& status0, const std::string& status1) {
}
std::pair<std::string, char> Protocol::compareStatus(const std::string& status0, char status1) {
}
std::pair<std::string, char> Protocol::compareStatus(char status0, char status1) {
}
std::string Protocol::chanTopic(const std::string& channel) {
}
std::string Protocol::chanTopicSetter(const std::string& channel) {
}
time_t Protocol::chanTopicTimestamp(const std::string& channel) {
}
time_t Protocol::chanTimestamp(const std::string& channel) {
}
std::list<std::string> Protocol::chanUsers(const std::string& channel) {
}
bool Protocol::userInChan(const std::string& channel, const std::string& user) {
}
std::pair<std::string, char> Protocol::userStatus(const std::string& channel, const std::string& user) {
}
bool Protocol::userHasStatus(const std::string& channel, const std::string& user, const std::string& status) {
}
bool Protocol::userHasStatus(const std::string& channel, const std::string& user, char status) {
}
bool Protocol::userHasStatusOrGreater(const std::string& channel, const std::string& user, const std::string& status) {
}
bool Protocol::userHasStatusOrGreater(const std::string& channel, const std::string& user, char status) {
}
std::map<std::string, std::string> Protocol::chanModes(const std::string& channel) {
}
bool Protocol::chanHasMode(const std::string& channel, const std::string& mode) {
}
std::string Protocol::chanModeParam(const std::string& channel, const std::string& mode) {
}
std::list<std::string> Protocol::chanListModeList(const std::string& channel, const std::string& mode) {
}
std::list<std::string> Protocol::clientList() {
}
std::string Protocol::userNick(const std::string& user) {
}
std::string Protocol::userIdent(const std::string& user) {
}
std::string Protocol::userHost(const std::string& user) {
}
std::string Protocol::userGecos(const std::string& user) {
}
std::string Protocol::idFromNick(const std::string& nick) {
}
std::list<std::pair<ModeType, std::string>> Protocol::allUserModes() {
}
ModeType Protocol::userModeType(const std::string& mode) {
}
std::map<std::string, std::string> Protocol::userModes(const std::string& user) {
}
bool Protocol::userHasMode(const std::string& user, const std::string& mode) {
}
std::string Protocol::userModeParam(const std::string& user, const std::string& mode) {
}
std::list<std::string> Protocol::userListModeList(const std::string& user, const std::string& listMode) {
}
std::set<std::string> Protocol::userChans(const std::string& user) {
}<commit_msg>Fix Protocol definition signatures<commit_after>#include "protocol.h"
void Protocol::connectServer() {
}
bool Protocol::connected() {
}
bool Protocol::shouldUnload() {
}
void Protocol::disconnect() {
}
void Protocol::onRehash() {
}
void Protocol::sendMsg(const std::string& client, const std::string& target, const std::string& message, const std::map<std::string, std::string>& tags) {
}
void Protocol::sendNotice(const std::string& client, const std::string& target, const std::string& message, const std::map<std::string, std::string>& tags) {
}
void Protocol::setMode(const std::string& client, const std::string& target, const std::list<std::tuple<bool, std::string, std::string>>& modes, const std::map<std::string, std::string>& tags) {
}
void Protocol::joinChan(const std::string& client, const std::string& channel, const std::map<std::string, std::string>& tags) {
}
void Protocol::joinChan(const std::string& client, const std::string& channel, const std::string& key, const std::map<std::string, std::string>& tags) {
}
void Protocol::partChan(const std::string& client, const std::string& channel, const std::string& reason, const std::map<std::string, std::string>& tags) {
}
void Protocol::kickUser(const std::string& client, const std::string& channel, const std::string& user, const std::string& reason, const std::map<std::string, std::string>& tags) {
}
void Protocol::setTopic(const std::string& client, const std::string& channel, const std::string& topic, const std::map<std::string, std::string>& tags) {
}
void Protocol::inviteUser(const std::string& client, const std::string& channel, const std::string& user, const std::map<std::string, std::string>& tags) {
}
void Protocol::knock(const std::string& client, const std::string& channel, const std::string& reason, const std::map<std::string, std::string>& tags) {
}
void Protocol::changeNick(const std::string& client, const std::string& newNick, const std::map<std::string, std::string>& tags) {
}
void Protocol::sendPing(const std::string& client, const std::string& data, const std::map<std::string, std::string>& tags) {
}
void Protocol::setAway(const std::string& client, const std::string& reason, const std::map<std::string, std::string>& tags) {
}
void Protocol::setUnaway(const std::string& client, const std::map<std::string, std::string>& tags) {
}
void Protocol::oper(const std::string& client, const std::string& username, const std::string& password, const std::map<std::string, std::string>& tags) {
}
void Protocol::sendWallops(const std::string& client, const std::string& message, const std::map<std::string, std::string>& tags) {
}
void Protocol::sendOtherData(const std::string& client, const IRCMessage* line) {
}
std::string Protocol::addClient(const std::string& nick, const std::string& ident, const std::string& gecos) {
}
void Protocol::removeClient(const std::string& client) {
}
std::set<std::string> Protocol::serverCapabilities() {
}
std::set<char> Protocol::chanTypes() {
}
std::list<std::pair<ModeType, std::string>> Protocol::allChanModes() {
}
ModeType Protocol::chanModeType(const std::string& mode) {
}
char Protocol::prefixSymbol(const std::string& mode) {
}
std::pair<std::string, char> Protocol::compareStatus(const std::string& status0, const std::string& status1) {
}
std::pair<std::string, char> Protocol::compareStatus(const std::string& status0, char status1) {
}
std::pair<std::string, char> Protocol::compareStatus(char status0, char status1) {
}
std::string Protocol::chanTopic(const std::string& channel) {
}
std::string Protocol::chanTopicSetter(const std::string& channel) {
}
time_t Protocol::chanTopicTimestamp(const std::string& channel) {
}
time_t Protocol::chanTimestamp(const std::string& channel) {
}
std::list<std::string> Protocol::chanUsers(const std::string& channel) {
}
bool Protocol::userInChan(const std::string& channel, const std::string& user) {
}
std::pair<std::string, char> Protocol::userStatus(const std::string& channel, const std::string& user) {
}
bool Protocol::userHasStatus(const std::string& channel, const std::string& user, const std::string& status) {
}
bool Protocol::userHasStatus(const std::string& channel, const std::string& user, char status) {
}
bool Protocol::userHasStatusOrGreater(const std::string& channel, const std::string& user, const std::string& status) {
}
bool Protocol::userHasStatusOrGreater(const std::string& channel, const std::string& user, char status) {
}
std::map<std::string, std::string> Protocol::chanModes(const std::string& channel) {
}
bool Protocol::chanHasMode(const std::string& channel, const std::string& mode) {
}
std::string Protocol::chanModeParam(const std::string& channel, const std::string& mode) {
}
std::list<std::string> Protocol::chanListModeList(const std::string& channel, const std::string& mode) {
}
std::list<std::string> Protocol::clientList() {
}
std::string Protocol::userNick(const std::string& user) {
}
std::string Protocol::userIdent(const std::string& user) {
}
std::string Protocol::userHost(const std::string& user) {
}
std::string Protocol::userGecos(const std::string& user) {
}
std::string Protocol::idFromNick(const std::string& nick) {
}
std::list<std::pair<ModeType, std::string>> Protocol::allUserModes() {
}
ModeType Protocol::userModeType(const std::string& mode) {
}
std::map<std::string, std::string> Protocol::userModes(const std::string& user) {
}
bool Protocol::userHasMode(const std::string& user, const std::string& mode) {
}
std::string Protocol::userModeParam(const std::string& user, const std::string& mode) {
}
std::list<std::string> Protocol::userListModeList(const std::string& user, const std::string& listMode) {
}
std::set<std::string> Protocol::userChans(const std::string& user) {
}<|endoftext|> |
<commit_before>///
/// @file Erat.cpp
/// @brief The Erat class manages prime sieving using the
/// EratSmall, EratMedium, EratBig classes.
///
/// Copyright (C) 2020 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/CpuInfo.hpp>
#include <primesieve/Erat.hpp>
#include <primesieve/EratSmall.hpp>
#include <primesieve/EratMedium.hpp>
#include <primesieve/EratBig.hpp>
#include <primesieve/PreSieve.hpp>
#include <primesieve/pmath.hpp>
#include <stdint.h>
#include <array>
#include <algorithm>
#include <cassert>
#include <memory>
using namespace std;
using namespace primesieve;
namespace {
/// unset bits < start
const array<uint8_t, 37> unsetSmaller =
{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xfe, 0xfe, 0xfe, 0xfe, 0xfc, 0xfc, 0xf8, 0xf8,
0xf8, 0xf8, 0xf0, 0xf0, 0xe0, 0xe0, 0xe0, 0xe0,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x80, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00
};
/// unset bits > stop
const array<uint8_t, 37> unsetLarger =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x01, 0x01, 0x01, 0x03, 0x03, 0x07, 0x07, 0x07,
0x07, 0x0f, 0x0f, 0x1f, 0x1f, 0x1f, 0x1f, 0x3f,
0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x7f, 0x7f, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff
};
} // namespace
namespace primesieve {
Erat::Erat() = default;
Erat::Erat(uint64_t start, uint64_t stop) :
start_(start),
stop_(stop)
{ }
/// @start: Sieve primes >= start
/// @stop: Sieve primes <= stop
/// @sieveSize: Sieve size in KiB
/// @preSieve: Pre-sieve small primes
///
void Erat::init(uint64_t start,
uint64_t stop,
uint64_t sieveSize,
PreSieve& preSieve)
{
if (start > stop)
return;
assert(start >= 7);
start_ = start;
stop_ = stop;
preSieve_ = &preSieve;
preSieve_->init(start, stop);
maxPreSieve_ = preSieve_->getMaxPrime();
initSieve(sieveSize);
// The 8 bits of each byte of the sieve array correspond to
// the offsets { 7, 11, 13, 17, 19, 23, 29, 31 }. If we
// would set dist = sieveSize * 30 we would not include the
// last bit of the last byte which corresponds to the offset
// 31. For this reason we set dist = sieveSize * 30 + 6.
uint64_t rem = byteRemainder(start);
uint64_t dist = sieveSize_ * 30 + 6;
segmentLow_ = start_ - rem;
segmentHigh_ = checkedAdd(segmentLow_, dist);
segmentHigh_ = min(segmentHigh_, stop);
initErat();
}
void Erat::initSieve(uint64_t sieveSize)
{
sieveSize_ = floorPow2(sieveSize);
sieveSize_ = inBetween(8, sieveSize_, 4096);
sieveSize_ *= 1024;
sieve_ = new uint8_t[sieveSize_];
deleter_.reset(sieve_);
}
void Erat::initErat()
{
uint64_t sqrtStop = isqrt(stop_);
uint64_t l1CacheSize = getL1CacheSize();
maxEratSmall_ = (uint64_t) (l1CacheSize * config::FACTOR_ERATSMALL);
maxEratMedium_ = (uint64_t) (sieveSize_ * config::FACTOR_ERATMEDIUM);
if (sqrtStop > maxPreSieve_)
eratSmall_.init(stop_, l1CacheSize, maxEratSmall_);
if (sqrtStop > maxEratSmall_)
eratMedium_.init(stop_, sieveSize_, maxEratMedium_);
if (sqrtStop > maxEratMedium_)
eratBig_.init(stop_, sieveSize_, sqrtStop);
}
/// EratMedium and EratBig usually run fastest using a sieve
/// size that matches the CPUs L2 cache size. EratSmall
/// however runs fastest using a sieve size that matches the
/// CPUs L1 cache size. Hence we use a smaller sieve size
/// (L1 cache size) in EratSmall and a larger sieve size (L2
/// cache size) in both EratMedium and EratBig.
///
uint64_t Erat::getL1CacheSize() const
{
if (!cpuInfo.hasL1Cache())
return sieveSize_;
uint64_t size = cpuInfo.l1CacheSize();
uint64_t minSize = 8 << 10;
uint64_t maxSize = 4096 << 10;
size = std::min(size, sieveSize_);
size = inBetween(minSize, size, maxSize);
return size;
}
bool Erat::hasNextSegment() const
{
return segmentLow_ < stop_;
}
uint64_t Erat::byteRemainder(uint64_t n)
{
n %= 30;
if (n <= 6) n += 30;
return n;
}
/// Pre-sieve multiples of small primes e.g. <= 19
/// to speed up the sieve of Eratosthenes
///
void Erat::preSieve()
{
preSieve_->copy(sieve_, sieveSize_, segmentLow_);
// unset bits < start
if (segmentLow_ <= start_)
{
if (start_ <= maxPreSieve_)
sieve_[0] = 0xff;
uint64_t rem = byteRemainder(start_);
sieve_[0] &= unsetSmaller[rem];
}
}
void Erat::crossOff()
{
if (eratSmall_.enabled())
eratSmall_.crossOff(sieve_, sieveSize_);
if (eratMedium_.enabled())
eratMedium_.crossOff(sieve_, sieveSize_);
if (eratBig_.enabled())
eratBig_.crossOff(sieve_);
}
void Erat::sieveSegment()
{
if (segmentHigh_ == stop_)
sieveLastSegment();
else
{
preSieve();
crossOff();
uint64_t dist = sieveSize_ * 30;
segmentLow_ = checkedAdd(segmentLow_, dist);
segmentHigh_ = checkedAdd(segmentHigh_, dist);
segmentHigh_ = min(segmentHigh_, stop_);
}
}
void Erat::sieveLastSegment()
{
uint64_t rem = byteRemainder(stop_);
uint64_t dist = (stop_ - rem) - segmentLow_;
sieveSize_ = dist / 30 + 1;
preSieve();
crossOff();
// unset bits > stop
sieve_[sieveSize_ - 1] &= unsetLarger[rem];
// unset bytes > stop
uint64_t bytes = sieveSize_ % 8;
bytes = (8 - bytes) % 8;
fill_n(&sieve_[sieveSize_], bytes, (uint8_t) 0);
segmentLow_ = stop_;
}
} // namespace
<commit_msg>Remove using namespace<commit_after>///
/// @file Erat.cpp
/// @brief The Erat class manages prime sieving using the
/// EratSmall, EratMedium, EratBig classes.
///
/// Copyright (C) 2020 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/CpuInfo.hpp>
#include <primesieve/Erat.hpp>
#include <primesieve/EratSmall.hpp>
#include <primesieve/EratMedium.hpp>
#include <primesieve/EratBig.hpp>
#include <primesieve/PreSieve.hpp>
#include <primesieve/pmath.hpp>
#include <stdint.h>
#include <array>
#include <algorithm>
#include <cassert>
#include <memory>
using namespace std;
namespace {
/// unset bits < start
const array<uint8_t, 37> unsetSmaller =
{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xfe, 0xfe, 0xfe, 0xfe, 0xfc, 0xfc, 0xf8, 0xf8,
0xf8, 0xf8, 0xf0, 0xf0, 0xe0, 0xe0, 0xe0, 0xe0,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x80, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00
};
/// unset bits > stop
const array<uint8_t, 37> unsetLarger =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x01, 0x01, 0x01, 0x03, 0x03, 0x07, 0x07, 0x07,
0x07, 0x0f, 0x0f, 0x1f, 0x1f, 0x1f, 0x1f, 0x3f,
0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x7f, 0x7f, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff
};
} // namespace
namespace primesieve {
Erat::Erat() = default;
Erat::Erat(uint64_t start, uint64_t stop) :
start_(start),
stop_(stop)
{ }
/// @start: Sieve primes >= start
/// @stop: Sieve primes <= stop
/// @sieveSize: Sieve size in KiB
/// @preSieve: Pre-sieve small primes
///
void Erat::init(uint64_t start,
uint64_t stop,
uint64_t sieveSize,
PreSieve& preSieve)
{
if (start > stop)
return;
assert(start >= 7);
start_ = start;
stop_ = stop;
preSieve_ = &preSieve;
preSieve_->init(start, stop);
maxPreSieve_ = preSieve_->getMaxPrime();
initSieve(sieveSize);
// The 8 bits of each byte of the sieve array correspond to
// the offsets { 7, 11, 13, 17, 19, 23, 29, 31 }. If we
// would set dist = sieveSize * 30 we would not include the
// last bit of the last byte which corresponds to the offset
// 31. For this reason we set dist = sieveSize * 30 + 6.
uint64_t rem = byteRemainder(start);
uint64_t dist = sieveSize_ * 30 + 6;
segmentLow_ = start_ - rem;
segmentHigh_ = checkedAdd(segmentLow_, dist);
segmentHigh_ = min(segmentHigh_, stop);
initErat();
}
void Erat::initSieve(uint64_t sieveSize)
{
sieveSize_ = floorPow2(sieveSize);
sieveSize_ = inBetween(8, sieveSize_, 4096);
sieveSize_ *= 1024;
sieve_ = new uint8_t[sieveSize_];
deleter_.reset(sieve_);
}
void Erat::initErat()
{
uint64_t sqrtStop = isqrt(stop_);
uint64_t l1CacheSize = getL1CacheSize();
maxEratSmall_ = (uint64_t) (l1CacheSize * config::FACTOR_ERATSMALL);
maxEratMedium_ = (uint64_t) (sieveSize_ * config::FACTOR_ERATMEDIUM);
if (sqrtStop > maxPreSieve_)
eratSmall_.init(stop_, l1CacheSize, maxEratSmall_);
if (sqrtStop > maxEratSmall_)
eratMedium_.init(stop_, sieveSize_, maxEratMedium_);
if (sqrtStop > maxEratMedium_)
eratBig_.init(stop_, sieveSize_, sqrtStop);
}
/// EratMedium and EratBig usually run fastest using a sieve
/// size that matches the CPUs L2 cache size. EratSmall
/// however runs fastest using a sieve size that matches the
/// CPUs L1 cache size. Hence we use a smaller sieve size
/// (L1 cache size) in EratSmall and a larger sieve size (L2
/// cache size) in both EratMedium and EratBig.
///
uint64_t Erat::getL1CacheSize() const
{
if (!cpuInfo.hasL1Cache())
return sieveSize_;
uint64_t size = cpuInfo.l1CacheSize();
uint64_t minSize = 8 << 10;
uint64_t maxSize = 4096 << 10;
size = std::min(size, sieveSize_);
size = inBetween(minSize, size, maxSize);
return size;
}
bool Erat::hasNextSegment() const
{
return segmentLow_ < stop_;
}
uint64_t Erat::byteRemainder(uint64_t n)
{
n %= 30;
if (n <= 6) n += 30;
return n;
}
/// Pre-sieve multiples of small primes e.g. <= 19
/// to speed up the sieve of Eratosthenes
///
void Erat::preSieve()
{
preSieve_->copy(sieve_, sieveSize_, segmentLow_);
// unset bits < start
if (segmentLow_ <= start_)
{
if (start_ <= maxPreSieve_)
sieve_[0] = 0xff;
uint64_t rem = byteRemainder(start_);
sieve_[0] &= unsetSmaller[rem];
}
}
void Erat::crossOff()
{
if (eratSmall_.enabled())
eratSmall_.crossOff(sieve_, sieveSize_);
if (eratMedium_.enabled())
eratMedium_.crossOff(sieve_, sieveSize_);
if (eratBig_.enabled())
eratBig_.crossOff(sieve_);
}
void Erat::sieveSegment()
{
if (segmentHigh_ == stop_)
sieveLastSegment();
else
{
preSieve();
crossOff();
uint64_t dist = sieveSize_ * 30;
segmentLow_ = checkedAdd(segmentLow_, dist);
segmentHigh_ = checkedAdd(segmentHigh_, dist);
segmentHigh_ = min(segmentHigh_, stop_);
}
}
void Erat::sieveLastSegment()
{
uint64_t rem = byteRemainder(stop_);
uint64_t dist = (stop_ - rem) - segmentLow_;
sieveSize_ = dist / 30 + 1;
preSieve();
crossOff();
// unset bits > stop
sieve_[sieveSize_ - 1] &= unsetLarger[rem];
// unset bytes > stop
uint64_t bytes = sieveSize_ % 8;
bytes = (8 - bytes) % 8;
fill_n(&sieve_[sieveSize_], bytes, (uint8_t) 0);
segmentLow_ = stop_;
}
} // namespace
<|endoftext|> |
<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "skin.h"
#include "utils/polygonUtils.h"
#define MIN_AREA_SIZE (0.4 * 0.4)
namespace cura
{
void generateSkins(int layerNr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount, int wall_line_count, int innermost_wall_extrusion_width, int insetCount, bool no_small_gaps_heuristic, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
generateSkinAreas(layerNr, storage, innermost_wall_extrusion_width, downSkinCount, upSkinCount, wall_line_count, no_small_gaps_heuristic);
SliceLayer* layer = &storage.layers[layerNr];
for(unsigned int partNr=0; partNr<layer->parts.size(); partNr++)
{
SliceLayerPart* part = &layer->parts[partNr];
generateSkinInsets(part, extrusionWidth, insetCount, avoidOverlappingPerimeters_0, avoidOverlappingPerimeters);
}
}
void generateSkinAreas(int layer_nr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int downSkinCount, int upSkinCount, int wall_line_count, bool no_small_gaps_heuristic)
{
SliceLayer& layer = storage.layers[layer_nr];
if (downSkinCount == 0 && upSkinCount == 0)
{
return;
}
for(unsigned int partNr = 0; partNr < layer.parts.size(); partNr++)
{
SliceLayerPart& part = layer.parts[partNr];
if (int(part.insets.size()) < wall_line_count)
{
continue; // the last wall is not present, the part should only get inter preimeter gaps, but no skin.
}
Polygons upskin = part.insets.back().offset(-innermost_wall_extrusion_width/2);
Polygons downskin = (downSkinCount == 0)? Polygons() : upskin;
if (upSkinCount == 0) upskin = Polygons();
auto getInsidePolygons = [&part, wall_line_count](SliceLayer& layer2)
{
Polygons result;
for(SliceLayerPart& part2 : layer2.parts)
{
if (part.boundaryBox.hit(part2.boundaryBox))
{
unsigned int wall_idx = std::min(wall_line_count, (int) part2.insets.size()) - 1;
result.add(part2.insets[wall_idx]);
}
}
return result;
};
if (no_small_gaps_heuristic)
{
if (static_cast<int>(layer_nr - downSkinCount) >= 0)
{
downskin = downskin.difference(getInsidePolygons(storage.layers[layer_nr - downSkinCount])); // skin overlaps with the walls
}
if (static_cast<int>(layer_nr + upSkinCount) < static_cast<int>(storage.layers.size()))
{
upskin = upskin.difference(getInsidePolygons(storage.layers[layer_nr + upSkinCount])); // skin overlaps with the walls
}
}
else
{
if (layer_nr >= downSkinCount && downSkinCount > 0)
{
Polygons not_air = getInsidePolygons(storage.layers[layer_nr - 1]);
for (int downskin_layer_nr = layer_nr - downSkinCount; downskin_layer_nr < layer_nr - 1; downskin_layer_nr++)
{
not_air = not_air.intersection(getInsidePolygons(storage.layers[downskin_layer_nr]));
}
downskin = downskin.difference(not_air); // skin overlaps with the walls
}
if (layer_nr < static_cast<int>(storage.layers.size()) - downSkinCount && upSkinCount > 0)
{
Polygons not_air = getInsidePolygons(storage.layers[layer_nr + 1]);
for (int upskin_layer_nr = layer_nr + 2; upskin_layer_nr < layer_nr + upSkinCount + 1; upskin_layer_nr++)
{
not_air = not_air.intersection(getInsidePolygons(storage.layers[upskin_layer_nr]));
}
upskin = upskin.difference(not_air); // skin overlaps with the walls
}
}
Polygons skin = upskin.unionPolygons(downskin);
skin.removeSmallAreas(MIN_AREA_SIZE);
for (PolygonsPart& skin_area_part : skin.splitIntoParts())
{
part.skin_parts.emplace_back();
part.skin_parts.back().outline = skin_area_part;
}
}
}
void generateSkinInsets(SliceLayerPart* part, int extrusionWidth, int insetCount, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
if (insetCount == 0)
{
return;
}
for (SkinPart& skin_part : part->skin_parts)
{
for(int i=0; i<insetCount; i++)
{
skin_part.insets.push_back(Polygons());
if (i == 0)
{
PolygonUtils::offsetSafe(skin_part.outline, - extrusionWidth/2, extrusionWidth, skin_part.insets[0], avoidOverlappingPerimeters_0);
Polygons in_between = skin_part.outline.difference(skin_part.insets[0].offset(extrusionWidth/2));
skin_part.perimeterGaps.add(in_between);
} else
{
PolygonUtils::offsetExtrusionWidth(skin_part.insets[i-1], true, extrusionWidth, skin_part.insets[i], &skin_part.perimeterGaps, avoidOverlappingPerimeters);
}
// optimize polygons: remove unnnecesary verts
skin_part.insets[i].simplify();
if (skin_part.insets[i].size() < 1)
{
skin_part.insets.pop_back();
break;
}
}
}
}
void generateInfill(int layerNr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int infill_skin_overlap, int wall_line_count)
{
SliceLayer& layer = storage.layers[layerNr];
for(SliceLayerPart& part : layer.parts)
{
if (int(part.insets.size()) < wall_line_count)
{
part.infill_area.emplace_back(); // put empty polygon as (uncombined) infill
continue; // the last wall is not present, the part should only get inter preimeter gaps, but no infill.
}
Polygons infill = part.insets.back().offset(-innermost_wall_extrusion_width / 2 - infill_skin_overlap);
for(SliceLayerPart& part2 : layer.parts)
{
if (part.boundaryBox.hit(part2.boundaryBox))
{
for(SkinPart& skin_part : part2.skin_parts)
{
infill = infill.difference(skin_part.outline);
}
}
}
infill.removeSmallAreas(MIN_AREA_SIZE);
part.infill_area.push_back(infill.offset(infill_skin_overlap));
}
}
void combineInfillLayers(SliceMeshStorage& storage,unsigned int amount)
{
if(amount <= 1) //If we must combine 1 layer, nothing needs to be combined. Combining 0 layers is invalid.
{
return;
}
if(storage.layers.empty() || storage.layers.size() - 1 < static_cast<size_t>(storage.getSettingAsCount("top_layers")) || storage.getSettingAsCount("infill_line_distance") <= 0) //No infill is even generated.
{
return;
}
/* We need to round down the layer index we start at to the nearest
divisible index. Otherwise we get some parts that have infill at divisible
layers and some at non-divisible layers. Those layers would then miss each
other. */
size_t min_layer = storage.getSettingAsCount("bottom_layers") + amount - 1;
min_layer -= min_layer % amount; //Round upwards to the nearest layer divisible by infill_sparse_combine.
size_t max_layer = storage.layers.size() - 1 - storage.getSettingAsCount("top_layers");
max_layer -= max_layer % amount; //Round downwards to the nearest layer divisible by infill_sparse_combine.
for(size_t layer_idx = min_layer;layer_idx <= max_layer;layer_idx += amount) //Skip every few layers, but extrude more.
{
SliceLayer* layer = &storage.layers[layer_idx];
for(unsigned int n = 1;n < amount;n++)
{
if(layer_idx < n)
{
break;
}
SliceLayer* layer2 = &storage.layers[layer_idx - n];
for(SliceLayerPart& part : layer->parts)
{
Polygons result;
for(SliceLayerPart& part2 : layer2->parts)
{
if(part.boundaryBox.hit(part2.boundaryBox))
{
Polygons intersection = part.infill_area[n - 1].intersection(part2.infill_area[0]).offset(-200).offset(200);
result.add(intersection);
part.infill_area[n - 1] = part.infill_area[n - 1].difference(intersection);
part2.infill_area[0] = part2.infill_area[0].difference(intersection);
}
}
part.infill_area.push_back(result);
}
}
}
}
void generatePerimeterGaps(int layer_nr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount)
{
SliceLayer& layer = storage.layers[layer_nr];
for (SliceLayerPart& part : layer.parts)
{ // handle gaps between perimeters etc.
if (downSkinCount > 0 && upSkinCount > 0 && // note: if both are zero or less, then all gaps will be used
layer_nr >= downSkinCount && layer_nr < static_cast<int>(storage.layers.size() - upSkinCount)) // remove gaps which appear within print, i.e. not on the bottom most or top most skin
{
Polygons outlines_above;
for (SliceLayerPart& part_above : storage.layers[layer_nr + upSkinCount].parts)
{
if (part.boundaryBox.hit(part_above.boundaryBox))
{
outlines_above.add(part_above.outline);
}
}
Polygons outlines_below;
for (SliceLayerPart& part_below : storage.layers[layer_nr - downSkinCount].parts)
{
if (part.boundaryBox.hit(part_below.boundaryBox))
{
outlines_below.add(part_below.outline);
}
}
part.perimeterGaps = part.perimeterGaps.intersection(outlines_above.xorPolygons(outlines_below));
}
part.perimeterGaps.removeSmallAreas(MIN_AREA_SIZE);
}
}
}//namespace cura
<commit_msg>Fix typo. downSkinCount -> upSkinCount (CURA-1299)<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "skin.h"
#include "utils/polygonUtils.h"
#define MIN_AREA_SIZE (0.4 * 0.4)
namespace cura
{
void generateSkins(int layerNr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount, int wall_line_count, int innermost_wall_extrusion_width, int insetCount, bool no_small_gaps_heuristic, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
generateSkinAreas(layerNr, storage, innermost_wall_extrusion_width, downSkinCount, upSkinCount, wall_line_count, no_small_gaps_heuristic);
SliceLayer* layer = &storage.layers[layerNr];
for(unsigned int partNr=0; partNr<layer->parts.size(); partNr++)
{
SliceLayerPart* part = &layer->parts[partNr];
generateSkinInsets(part, extrusionWidth, insetCount, avoidOverlappingPerimeters_0, avoidOverlappingPerimeters);
}
}
void generateSkinAreas(int layer_nr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int downSkinCount, int upSkinCount, int wall_line_count, bool no_small_gaps_heuristic)
{
SliceLayer& layer = storage.layers[layer_nr];
if (downSkinCount == 0 && upSkinCount == 0)
{
return;
}
for(unsigned int partNr = 0; partNr < layer.parts.size(); partNr++)
{
SliceLayerPart& part = layer.parts[partNr];
if (int(part.insets.size()) < wall_line_count)
{
continue; // the last wall is not present, the part should only get inter preimeter gaps, but no skin.
}
Polygons upskin = part.insets.back().offset(-innermost_wall_extrusion_width/2);
Polygons downskin = (downSkinCount == 0)? Polygons() : upskin;
if (upSkinCount == 0) upskin = Polygons();
auto getInsidePolygons = [&part, wall_line_count](SliceLayer& layer2)
{
Polygons result;
for(SliceLayerPart& part2 : layer2.parts)
{
if (part.boundaryBox.hit(part2.boundaryBox))
{
unsigned int wall_idx = std::min(wall_line_count, (int) part2.insets.size()) - 1;
result.add(part2.insets[wall_idx]);
}
}
return result;
};
if (no_small_gaps_heuristic)
{
if (static_cast<int>(layer_nr - downSkinCount) >= 0)
{
downskin = downskin.difference(getInsidePolygons(storage.layers[layer_nr - downSkinCount])); // skin overlaps with the walls
}
if (static_cast<int>(layer_nr + upSkinCount) < static_cast<int>(storage.layers.size()))
{
upskin = upskin.difference(getInsidePolygons(storage.layers[layer_nr + upSkinCount])); // skin overlaps with the walls
}
}
else
{
if (layer_nr >= downSkinCount && downSkinCount > 0)
{
Polygons not_air = getInsidePolygons(storage.layers[layer_nr - 1]);
for (int downskin_layer_nr = layer_nr - downSkinCount; downskin_layer_nr < layer_nr - 1; downskin_layer_nr++)
{
not_air = not_air.intersection(getInsidePolygons(storage.layers[downskin_layer_nr]));
}
downskin = downskin.difference(not_air); // skin overlaps with the walls
}
if (layer_nr < static_cast<int>(storage.layers.size()) - upSkinCount && upSkinCount > 0)
{
Polygons not_air = getInsidePolygons(storage.layers[layer_nr + 1]);
for (int upskin_layer_nr = layer_nr + 2; upskin_layer_nr < layer_nr + upSkinCount + 1; upskin_layer_nr++)
{
not_air = not_air.intersection(getInsidePolygons(storage.layers[upskin_layer_nr]));
}
upskin = upskin.difference(not_air); // skin overlaps with the walls
}
}
Polygons skin = upskin.unionPolygons(downskin);
skin.removeSmallAreas(MIN_AREA_SIZE);
for (PolygonsPart& skin_area_part : skin.splitIntoParts())
{
part.skin_parts.emplace_back();
part.skin_parts.back().outline = skin_area_part;
}
}
}
void generateSkinInsets(SliceLayerPart* part, int extrusionWidth, int insetCount, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
if (insetCount == 0)
{
return;
}
for (SkinPart& skin_part : part->skin_parts)
{
for(int i=0; i<insetCount; i++)
{
skin_part.insets.push_back(Polygons());
if (i == 0)
{
PolygonUtils::offsetSafe(skin_part.outline, - extrusionWidth/2, extrusionWidth, skin_part.insets[0], avoidOverlappingPerimeters_0);
Polygons in_between = skin_part.outline.difference(skin_part.insets[0].offset(extrusionWidth/2));
skin_part.perimeterGaps.add(in_between);
} else
{
PolygonUtils::offsetExtrusionWidth(skin_part.insets[i-1], true, extrusionWidth, skin_part.insets[i], &skin_part.perimeterGaps, avoidOverlappingPerimeters);
}
// optimize polygons: remove unnnecesary verts
skin_part.insets[i].simplify();
if (skin_part.insets[i].size() < 1)
{
skin_part.insets.pop_back();
break;
}
}
}
}
void generateInfill(int layerNr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int infill_skin_overlap, int wall_line_count)
{
SliceLayer& layer = storage.layers[layerNr];
for(SliceLayerPart& part : layer.parts)
{
if (int(part.insets.size()) < wall_line_count)
{
part.infill_area.emplace_back(); // put empty polygon as (uncombined) infill
continue; // the last wall is not present, the part should only get inter preimeter gaps, but no infill.
}
Polygons infill = part.insets.back().offset(-innermost_wall_extrusion_width / 2 - infill_skin_overlap);
for(SliceLayerPart& part2 : layer.parts)
{
if (part.boundaryBox.hit(part2.boundaryBox))
{
for(SkinPart& skin_part : part2.skin_parts)
{
infill = infill.difference(skin_part.outline);
}
}
}
infill.removeSmallAreas(MIN_AREA_SIZE);
part.infill_area.push_back(infill.offset(infill_skin_overlap));
}
}
void combineInfillLayers(SliceMeshStorage& storage,unsigned int amount)
{
if(amount <= 1) //If we must combine 1 layer, nothing needs to be combined. Combining 0 layers is invalid.
{
return;
}
if(storage.layers.empty() || storage.layers.size() - 1 < static_cast<size_t>(storage.getSettingAsCount("top_layers")) || storage.getSettingAsCount("infill_line_distance") <= 0) //No infill is even generated.
{
return;
}
/* We need to round down the layer index we start at to the nearest
divisible index. Otherwise we get some parts that have infill at divisible
layers and some at non-divisible layers. Those layers would then miss each
other. */
size_t min_layer = storage.getSettingAsCount("bottom_layers") + amount - 1;
min_layer -= min_layer % amount; //Round upwards to the nearest layer divisible by infill_sparse_combine.
size_t max_layer = storage.layers.size() - 1 - storage.getSettingAsCount("top_layers");
max_layer -= max_layer % amount; //Round downwards to the nearest layer divisible by infill_sparse_combine.
for(size_t layer_idx = min_layer;layer_idx <= max_layer;layer_idx += amount) //Skip every few layers, but extrude more.
{
SliceLayer* layer = &storage.layers[layer_idx];
for(unsigned int n = 1;n < amount;n++)
{
if(layer_idx < n)
{
break;
}
SliceLayer* layer2 = &storage.layers[layer_idx - n];
for(SliceLayerPart& part : layer->parts)
{
Polygons result;
for(SliceLayerPart& part2 : layer2->parts)
{
if(part.boundaryBox.hit(part2.boundaryBox))
{
Polygons intersection = part.infill_area[n - 1].intersection(part2.infill_area[0]).offset(-200).offset(200);
result.add(intersection);
part.infill_area[n - 1] = part.infill_area[n - 1].difference(intersection);
part2.infill_area[0] = part2.infill_area[0].difference(intersection);
}
}
part.infill_area.push_back(result);
}
}
}
}
void generatePerimeterGaps(int layer_nr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount)
{
SliceLayer& layer = storage.layers[layer_nr];
for (SliceLayerPart& part : layer.parts)
{ // handle gaps between perimeters etc.
if (downSkinCount > 0 && upSkinCount > 0 && // note: if both are zero or less, then all gaps will be used
layer_nr >= downSkinCount && layer_nr < static_cast<int>(storage.layers.size() - upSkinCount)) // remove gaps which appear within print, i.e. not on the bottom most or top most skin
{
Polygons outlines_above;
for (SliceLayerPart& part_above : storage.layers[layer_nr + upSkinCount].parts)
{
if (part.boundaryBox.hit(part_above.boundaryBox))
{
outlines_above.add(part_above.outline);
}
}
Polygons outlines_below;
for (SliceLayerPart& part_below : storage.layers[layer_nr - downSkinCount].parts)
{
if (part.boundaryBox.hit(part_below.boundaryBox))
{
outlines_below.add(part_below.outline);
}
}
part.perimeterGaps = part.perimeterGaps.intersection(outlines_above.xorPolygons(outlines_below));
}
part.perimeterGaps.removeSmallAreas(MIN_AREA_SIZE);
}
}
}//namespace cura
<|endoftext|> |
<commit_before>/*
This file is part of INDDGO.
Copyright (C) 2012, Oak Ridge National Laboratory
This product includes software produced by UT-Battelle, LLC under Contract No.
DE-AC05-00OR22725 with the Department of Energy.
This program is free software; you can redistribute it and/or modify
it under the terms of the New BSD 3-clause software license (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
LICENSE for more details.
For more information please contact the INDDGO developers at:
[email protected]
*/
#include "GraphDecomposition.h"
#include "TreeDecomposition.h"
#include <fstream>
#include <unistd.h>
#include <sstream>
/*
* This file generates one or more tree decompositions and
* calculates a variety of statistics (width, bag size distribution,
* average bag score), as well as optional treewidth lower bounds.
* It generates a single output file containing all requested
* information in a csv format.
* As usual, this operates on the largest connected component.
*/
int main(int argc, char **argv)
{
/*current required arguments (in this order, no flags):
* graph_file (dimacs)
* kcore_file (scorefile format)
* output_file_basename
* tree_outfile_basename
*/
vector<double> *kcore_score = new vector<double>();
vector<double> *degree_score = new vector<double>();
int tdt[] = {TD_SUPERETREE, TD_GAVRIL, TD_BK, TD_NICE};
int et[] = {GD_AMD, GD_METIS_NODE_ND, GD_METIS_MMD};
const char* tdtype[] = {"Super-E-Tree", "Gavril"}; /*,"Bodlaender-Koster", "Nice"};*/ //Edited to speed up computations
const char* elimtype[] = {"AMD", "MetisNodeND", "MetisMultMinD"};
vector<int> td_types(tdt, tdt+sizeof(tdt)/sizeof(tdt[0]));
vector<int> elim_types(et, et+sizeof(et)/sizeof(et[0]));
vector<double>* st[] = {degree_score, kcore_score};
vector<vector<double> *> scores(st, st+sizeof(st)/sizeof(st[0]));
/*File names; this needs some checking to catch NULLS/miscalls*/
char *graph_file = argv[1];
char *kcore_file = argv[2];
/*we'll print to stdout otherwise*/
char *out_file_base = NULL;
if(argc > 3)
out_file_base = argv[3];
char *tree_file_base = NULL;
if(argc > 4)
tree_file_base = argv[4];
int t, e, i, s;
Graph::WeightedMutableGraph *G;
TDTree *T;
int treewidth, treelength, minecc;
double kcore_max, kcore_min;
int degree_max, degree_min;
std::ofstream out;
std::ostream outStream(cout.rdbuf());
std::stringstream sstm;
int td_id;
/*initialize log files if needed*/
int pid;
#if WIN32 || _WIN32
pid=_getpid();
#else
pid=(int)getpid();
#endif
char lfname[100];
char efname[100];
sprintf(lfname, "stats-%d.log",pid);
sprintf(efname, "stats-%d.log",pid);
//0: debug, 5: critical
LOG_INIT(lfname, efname, 0);
try
{
if(kcore_file == NULL || graph_file == NULL || out_file_base == NULL || tree_file_base == NULL )
throw(Graph::GraphException("Call with four arguments: graph_file kcore_file outfile_base treefile_base\n"));
/*populate the graph*/
Graph::create_largestcomponent_graph(graph_file, G);
/*populate appropriate score vectors*/
bool range = read_color_file(kcore_file,kcore_max,kcore_min,*kcore_score);
Graph::GraphUtil gutil;
gutil.recompute_degrees(G);
vector<int> idegree_score = G->get_degree();
(*degree_score).resize(idegree_score.size());
for(int i = 0; i < idegree_score.size(); i++)
(*degree_score)[i] = idegree_score[i];
/*loop over tree decomposition algorithms*/
for(t = 0; t < td_types.size(); t++)
{
/*loop over elimination order heuristics*/
for(e = 0; e < elim_types.size(); e++)
{
td_id = 10*(t+1) + e; //gives a unique number for the decomposition
/*form the tree decomposition*/
create_tree_decomposition(G, &T, false, NULL, false,
false, NULL, elim_types[e],
GD_UNDEFINED, td_types[t],
false, true);
/*create a place to store all the statistics for this particular decomposition*/
vector<vector<double> > stats(T->num_tree_nodes);
vector<double> mystats;
vector<double>::iterator it;
//fill the bag vectors
T->fill_bag_vecs();
cout << "T has " << T->num_tree_nodes << " tree nodes\n";
//Non-score-specific statistics - width, length, eccentricity
/* Width - uses degree scores for non-negativity check*/
/* We define width = |B| - 1 to coincide with treewidth*/
bag_statistics(T, *(scores[0]), &mystats, GD_STAT_COUNT);
treewidth = 0;
for(int i = 0; i < mystats.size(); i++)
{
if(mystats[i]-1 > treewidth)
treewidth = (int)(mystats[i])-1;
stats[i].push_back(mystats[i]-1);
}
/*Length*/
vector<int> lengths;
treelength = 0;
bag_lengths(T, &lengths);
for(int i = 0; i < lengths.size(); i++)
{
if(lengths[i] > treelength)
treelength = lengths[i];
stats[i].push_back((double)lengths[i]);
}
/*Eccentricity*/
Graph::MutableGraph *GT = T->export_tree();
vector<int> ecc;
minecc = INT_MAX;
gutil.find_ecc(GT, &ecc);
for(int i = 0; i < ecc.size(); i++)
{
if(ecc[i] < minecc)
minecc = ecc[i];
stats[i].push_back(ecc[i]);
}
/*loop over scores and calculate mean med stddev*/
for(s = 0; s < scores.size(); s++)
{
/*Mean*/
bag_statistics(T, *(scores[s]), &mystats, GD_STAT_MEAN);
for(int i = 0; i < mystats.size(); i++)
stats[i].push_back(mystats[i]);
/*Median*/
bag_statistics(T, *(scores[s]), &mystats, GD_STAT_MED);
for(int i = 0; i < mystats.size(); i++)
stats[i].push_back(mystats[i]);
/*Standard Deviation*/
bag_statistics(T, *(scores[s]), &mystats, GD_STAT_STD);
for(int i = 0; i < mystats.size(); i++)
stats[i].push_back(mystats[i]);
}
/*
* Open output file for writing results
*/
if(out_file_base == NULL)
outStream.rdbuf(std::cout.rdbuf());
else
{
sstm << out_file_base << td_id;
out.open((sstm.str()).c_str(), fstream::out);
if(out.fail())
fatal_error("%s: Error opening file %s for writing graphviz output\n", __FUNCTION__, (sstm.str()).c_str());
outStream.rdbuf(out.rdbuf());
sstm.str("");//clears the stream
}
/*
* Print the file header
*/
outStream << "# " << graph_file << endl;
outStream << "# " << tdtype[t] << endl;
outStream << "# " << elimtype[e] << endl;
outStream << "# " << "Width " << (treewidth-1) << endl;
outStream << "# " << "Length " << treelength << endl;
outStream << "# " << "MinEcc " << minecc << endl;
outStream << "# Bag\t Cardinality\t Length\t Eccentricity\t MeanDegree\t MedianDegree\t StdDevDegree\t MeanScore\t MedianScore\t StdDevScore" << endl;
/*
* Print the statistics for each bag
*/
for(int i = 0; i < mystats.size(); i++)
{
outStream << i << "\t";
for(it = stats[i].begin(); it != stats[i].end(); ++it)
outStream << *it << "\t";
outStream << endl;
}
/*
* Close the output file.
*/
out.close();
/*
* Write the tree decomposition to file, if required.
*/
if(tree_file_base != NULL)
{
sstm << tree_file_base << td_id;
T->write_DIMACS_file((sstm.str()).c_str());
sstm.str("");//clears the stream
}
/*delete the tree decomposition*/
delete T;
}
}
delete G;
LOG_CLOSE();
return 1;
}
catch(Graph::GraphException& e)
{
cerr << "exception caught: " << e.what() << endl;
LOG_CLOSE();
return -1;
}
}
<commit_msg>Correcting td_stats to run only two construction algorithms.<commit_after>/*
This file is part of INDDGO.
Copyright (C) 2012, Oak Ridge National Laboratory
This product includes software produced by UT-Battelle, LLC under Contract No.
DE-AC05-00OR22725 with the Department of Energy.
This program is free software; you can redistribute it and/or modify
it under the terms of the New BSD 3-clause software license (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
LICENSE for more details.
For more information please contact the INDDGO developers at:
[email protected]
*/
#include "GraphDecomposition.h"
#include "TreeDecomposition.h"
#include <fstream>
#include <unistd.h>
#include <sstream>
/*
* This file generates one or more tree decompositions and
* calculates a variety of statistics (width, bag size distribution,
* average bag score), as well as optional treewidth lower bounds.
* It generates a single output file containing all requested
* information in a csv format.
* As usual, this operates on the largest connected component.
*/
int main(int argc, char **argv)
{
/*current required arguments (in this order, no flags):
* graph_file (dimacs)
* kcore_file (scorefile format)
* output_file_basename
* tree_outfile_basename
*/
vector<double> *kcore_score = new vector<double>();
vector<double> *degree_score = new vector<double>();
int tdt[] = {TD_SUPERETREE, TD_GAVRIL}; //, TD_BK, TD_NICE};
int et[] = {GD_AMD, GD_METIS_NODE_ND, GD_METIS_MMD};
const char* tdtype[] = {"Super-E-Tree", "Gavril"}; /*,"Bodlaender-Koster", "Nice"};*/ //Edited to speed up computations
const char* elimtype[] = {"AMD", "MetisNodeND", "MetisMultMinD"};
vector<int> td_types(tdt, tdt+sizeof(tdt)/sizeof(tdt[0]));
vector<int> elim_types(et, et+sizeof(et)/sizeof(et[0]));
vector<double>* st[] = {degree_score, kcore_score};
vector<vector<double> *> scores(st, st+sizeof(st)/sizeof(st[0]));
/*File names; this needs some checking to catch NULLS/miscalls*/
char *graph_file = argv[1];
char *kcore_file = argv[2];
/*we'll print to stdout otherwise*/
char *out_file_base = NULL;
if(argc > 3)
out_file_base = argv[3];
char *tree_file_base = NULL;
if(argc > 4)
tree_file_base = argv[4];
int t, e, i, s;
Graph::WeightedMutableGraph *G;
TDTree *T;
int treewidth, treelength, minecc;
double kcore_max, kcore_min;
int degree_max, degree_min;
std::ofstream out;
std::ostream outStream(cout.rdbuf());
std::stringstream sstm;
int td_id;
/*initialize log files if needed*/
int pid;
#if WIN32 || _WIN32
pid=_getpid();
#else
pid=(int)getpid();
#endif
char lfname[100];
char efname[100];
sprintf(lfname, "stats-%d.log",pid);
sprintf(efname, "stats-%d.log",pid);
//0: debug, 5: critical
LOG_INIT(lfname, efname, 0);
try
{
if(kcore_file == NULL || graph_file == NULL || out_file_base == NULL || tree_file_base == NULL )
throw(Graph::GraphException("Call with four arguments: graph_file kcore_file outfile_base treefile_base\n"));
/*populate the graph*/
Graph::create_largestcomponent_graph(graph_file, G);
/*populate appropriate score vectors*/
bool range = read_color_file(kcore_file,kcore_max,kcore_min,*kcore_score);
Graph::GraphUtil gutil;
gutil.recompute_degrees(G);
vector<int> idegree_score = G->get_degree();
(*degree_score).resize(idegree_score.size());
for(int i = 0; i < idegree_score.size(); i++)
(*degree_score)[i] = idegree_score[i];
/*loop over tree decomposition algorithms*/
for(t = 0; t < td_types.size(); t++)
{
/*loop over elimination order heuristics*/
for(e = 0; e < elim_types.size(); e++)
{
td_id = 10*(t+1) + e; //gives a unique number for the decomposition
/*form the tree decomposition*/
create_tree_decomposition(G, &T, false, NULL, false,
false, NULL, elim_types[e],
GD_UNDEFINED, td_types[t],
false, true);
/*create a place to store all the statistics for this particular decomposition*/
vector<vector<double> > stats(T->num_tree_nodes);
vector<double> mystats;
vector<double>::iterator it;
//fill the bag vectors
T->fill_bag_vecs();
cout << "T has " << T->num_tree_nodes << " tree nodes\n";
//Non-score-specific statistics - width, length, eccentricity
/* Width - uses degree scores for non-negativity check*/
/* We define width = |B| - 1 to coincide with treewidth*/
bag_statistics(T, *(scores[0]), &mystats, GD_STAT_COUNT);
treewidth = 0;
for(int i = 0; i < mystats.size(); i++)
{
if(mystats[i]-1 > treewidth)
treewidth = (int)(mystats[i])-1;
stats[i].push_back(mystats[i]-1);
}
/*Length*/
vector<int> lengths;
treelength = 0;
bag_lengths(T, &lengths);
for(int i = 0; i < lengths.size(); i++)
{
if(lengths[i] > treelength)
treelength = lengths[i];
stats[i].push_back((double)lengths[i]);
}
/*Eccentricity*/
Graph::MutableGraph *GT = T->export_tree();
vector<int> ecc;
minecc = INT_MAX;
gutil.find_ecc(GT, &ecc);
for(int i = 0; i < ecc.size(); i++)
{
if(ecc[i] < minecc)
minecc = ecc[i];
stats[i].push_back(ecc[i]);
}
/*loop over scores and calculate mean med stddev*/
for(s = 0; s < scores.size(); s++)
{
/*Mean*/
bag_statistics(T, *(scores[s]), &mystats, GD_STAT_MEAN);
for(int i = 0; i < mystats.size(); i++)
stats[i].push_back(mystats[i]);
/*Median*/
bag_statistics(T, *(scores[s]), &mystats, GD_STAT_MED);
for(int i = 0; i < mystats.size(); i++)
stats[i].push_back(mystats[i]);
/*Standard Deviation*/
bag_statistics(T, *(scores[s]), &mystats, GD_STAT_STD);
for(int i = 0; i < mystats.size(); i++)
stats[i].push_back(mystats[i]);
}
/*
* Open output file for writing results
*/
if(out_file_base == NULL)
outStream.rdbuf(std::cout.rdbuf());
else
{
sstm << out_file_base << td_id;
out.open((sstm.str()).c_str(), fstream::out);
if(out.fail())
fatal_error("%s: Error opening file %s for writing graphviz output\n", __FUNCTION__, (sstm.str()).c_str());
outStream.rdbuf(out.rdbuf());
sstm.str("");//clears the stream
}
/*
* Print the file header
*/
outStream << "# " << graph_file << endl;
outStream << "# " << tdtype[t] << endl;
outStream << "# " << elimtype[e] << endl;
outStream << "# " << "Width " << (treewidth-1) << endl;
outStream << "# " << "Length " << treelength << endl;
outStream << "# " << "MinEcc " << minecc << endl;
outStream << "# Bag\t Cardinality\t Length\t Eccentricity\t MeanDegree\t MedianDegree\t StdDevDegree\t MeanScore\t MedianScore\t StdDevScore" << endl;
/*
* Print the statistics for each bag
*/
for(int i = 0; i < mystats.size(); i++)
{
outStream << i << "\t";
for(it = stats[i].begin(); it != stats[i].end(); ++it)
outStream << *it << "\t";
outStream << endl;
}
/*
* Close the output file.
*/
out.close();
/*
* Write the tree decomposition to file, if required.
*/
if(tree_file_base != NULL)
{
sstm << tree_file_base << td_id;
T->write_DIMACS_file((sstm.str()).c_str());
sstm.str("");//clears the stream
}
/*delete the tree decomposition*/
delete T;
}
}
delete G;
LOG_CLOSE();
return 1;
}
catch(Graph::GraphException& e)
{
cerr << "exception caught: " << e.what() << endl;
LOG_CLOSE();
return -1;
}
}
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install, copy or use the software.
//
// Copyright (C) 2009, Farhad Dadgostar
// Intel Corporation and third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <opencv2/contrib/contrib.hpp>
#include <opencv2/highgui/highgui.hpp>
class ASDFrameHolder
{
private:
IplImage *image;
double timeStamp;
public:
ASDFrameHolder();
virtual ~ASDFrameHolder();
virtual void assignFrame(IplImage *sourceImage, double frameTime);
inline IplImage *getImage();
inline double getTimeStamp();
virtual void setImage(IplImage *sourceImage);
};
class ASDFrameSequencer
{
public:
virtual ~ASDFrameSequencer();
virtual IplImage *getNextImage();
virtual void close();
virtual bool isOpen();
virtual void getFrameCaption(char *caption);
};
class ASDCVFrameSequencer : public ASDFrameSequencer
{
protected:
CvCapture *capture;
public:
virtual IplImage *getNextImage();
virtual void close();
virtual bool isOpen();
};
class ASDFrameSequencerWebCam : public ASDCVFrameSequencer
{
public:
virtual bool open(int cameraIndex);
};
class ASDFrameSequencerVideoFile : public ASDCVFrameSequencer
{
public:
virtual bool open(const char *fileName);
};
class ASDFrameSequencerImageFile : public ASDFrameSequencer {
private:
char sFileNameMask[2048];
int nCurrentIndex, nStartIndex, nEndIndex;
public:
virtual void open(const char *fileNameMask, int startIndex, int endIndex);
virtual void getFrameCaption(char *caption);
virtual IplImage *getNextImage();
virtual void close();
virtual bool isOpen();
};
//-------------------- ASDFrameHolder -----------------------//
ASDFrameHolder::ASDFrameHolder( )
{
image = NULL;
timeStamp = 0;
};
ASDFrameHolder::~ASDFrameHolder( )
{
cvReleaseImage(&image);
};
void ASDFrameHolder::assignFrame(IplImage *sourceImage, double frameTime)
{
if (image != NULL)
{
cvReleaseImage(&image);
image = NULL;
}
image = cvCloneImage(sourceImage);
timeStamp = frameTime;
};
IplImage *ASDFrameHolder::getImage()
{
return image;
};
double ASDFrameHolder::getTimeStamp()
{
return timeStamp;
};
void ASDFrameHolder::setImage(IplImage *sourceImage)
{
image = sourceImage;
};
//-------------------- ASDFrameSequencer -----------------------//
ASDFrameSequencer::~ASDFrameSequencer()
{
close();
};
IplImage *ASDFrameSequencer::getNextImage()
{
return NULL;
};
void ASDFrameSequencer::close()
{
};
bool ASDFrameSequencer::isOpen()
{
return false;
};
void ASDFrameSequencer::getFrameCaption(char *caption) {
return;
};
IplImage* ASDCVFrameSequencer::getNextImage()
{
IplImage *image;
image = cvQueryFrame(capture);
if (image != NULL)
{
return cvCloneImage(image);
}
else
{
return NULL;
}
};
void ASDCVFrameSequencer::close()
{
if (capture != NULL)
{
cvReleaseCapture(&capture);
}
};
bool ASDCVFrameSequencer::isOpen()
{
return (capture != NULL);
};
//-------------------- ASDFrameSequencerWebCam -----------------------//
bool ASDFrameSequencerWebCam::open(int cameraIndex)
{
close();
capture = cvCaptureFromCAM(cameraIndex);
if (!capture)
{
return false;
}
else
{
return true;
}
};
//-------------------- ASDFrameSequencerVideoFile -----------------------//
bool ASDFrameSequencerVideoFile::open(const char *fileName)
{
close();
capture = cvCaptureFromFile(fileName);
if (!capture)
{
return false;
}
else
{
return true;
}
};
//-------------------- ASDFrameSequencerImageFile -----------------------//
void ASDFrameSequencerImageFile::open(const char *fileNameMask, int startIndex, int endIndex)
{
nCurrentIndex = startIndex-1;
nStartIndex = startIndex;
nEndIndex = endIndex;
std::sprintf(sFileNameMask, "%s", fileNameMask);
};
void ASDFrameSequencerImageFile::getFrameCaption(char *caption) {
std::sprintf(caption, sFileNameMask, nCurrentIndex);
};
IplImage* ASDFrameSequencerImageFile::getNextImage()
{
char fileName[2048];
nCurrentIndex++;
if (nCurrentIndex > nEndIndex)
return NULL;
std::sprintf(fileName, sFileNameMask, nCurrentIndex);
IplImage* img = cvLoadImage(fileName);
return img;
};
void ASDFrameSequencerImageFile::close()
{
nCurrentIndex = nEndIndex+1;
};
bool ASDFrameSequencerImageFile::isOpen()
{
return (nCurrentIndex <= nEndIndex);
};
void putTextWithShadow(IplImage *img, const char *str, CvPoint point, CvFont *font, CvScalar color = CV_RGB(255, 255, 128))
{
cvPutText(img, str, cvPoint(point.x-1,point.y-1), font, CV_RGB(0, 0, 0));
cvPutText(img, str, point, font, color);
};
#define ASD_RGB_SET_PIXEL(pointer, r, g, b) { (*pointer) = (unsigned char)b; (*(pointer+1)) = (unsigned char)g; (*(pointer+2)) = (unsigned char)r; }
#define ASD_RGB_GET_PIXEL(pointer, r, g, b) {b = (unsigned char)(*(pointer)); g = (unsigned char)(*(pointer+1)); r = (unsigned char)(*(pointer+2));}
void displayBuffer(IplImage *rgbDestImage, IplImage *buffer, int rValue, int gValue, int bValue)
{
int x, y, nWidth, nHeight;
double destX, destY, dx, dy;
uchar c;
unsigned char *pSrc;
nWidth = buffer->width;
nHeight = buffer->height;
dx = double(rgbDestImage->width)/double(nWidth);
dy = double(rgbDestImage->height)/double(nHeight);
destX = 0;
for (x = 0; x < nWidth; x++)
{
destY = 0;
for (y = 0; y < nHeight; y++)
{
c = ((uchar*)(buffer->imageData + buffer->widthStep*y))[x];
if (c)
{
pSrc = (unsigned char *)rgbDestImage->imageData + rgbDestImage->widthStep*int(destY) + (int(destX)*rgbDestImage->nChannels);
ASD_RGB_SET_PIXEL(pSrc, rValue, gValue, bValue);
}
destY += dy;
}
destY = 0;
destX += dx;
}
};
int main(int argc, char** argv )
{
IplImage *img, *filterMask = NULL;
CvAdaptiveSkinDetector filter(1, CvAdaptiveSkinDetector::MORPHING_METHOD_ERODE_DILATE);
ASDFrameSequencer *sequencer;
CvFont base_font;
char caption[2048], s[256], windowName[256];
long int clockTotal = 0, numFrames = 0;
std::clock_t clock;
if (argc < 4)
{
std::cout << "Usage: " << std::endl <<
argv[0] << " fileMask firstFrame lastFrame" << std::endl << std::endl <<
"Example: " << std::endl <<
argv[0] << " C:\\VideoSequences\\sample1\\right_view\\temp_%05d.jpg 0 1000" << std::endl <<
" iterates through temp_00000.jpg to temp_01000.jpg" << std::endl << std::endl <<
"If no parameter specified, this application will try to capture from the default Webcam." << std::endl <<
"Please note: Background should not contain large surfaces with skin tone." <<
std::endl;
sequencer = new ASDFrameSequencerWebCam();
(dynamic_cast<ASDFrameSequencerWebCam*>(sequencer))->open(-1);
if (! sequencer->isOpen())
{
std::cout << std::endl << "Error: Cannot initialize the default Webcam" << std::endl << std::endl;
}
}
else
{
sequencer = new ASDFrameSequencerImageFile();
(dynamic_cast<ASDFrameSequencerImageFile*>(sequencer))->open(argv[1], std::atoi(argv[2]), std::atoi(argv[3]) ); // A sequence of images captured from video source, is stored here
}
std::sprintf(windowName, "%s", "Adaptive Skin Detection Algorithm for Video Sequences");
cvNamedWindow(windowName, CV_WINDOW_AUTOSIZE);
cvInitFont( &base_font, CV_FONT_VECTOR0, 0.5, 0.5);
// Usage:
// c:\>CvASDSample "C:\VideoSequences\sample1\right_view\temp_%05d.jpg" 0 1000
std::cout << "Press ESC to stop." << std::endl << std::endl;
while ((img = sequencer->getNextImage()) != 0)
{
numFrames++;
if (filterMask == NULL)
{
filterMask = cvCreateImage( cvSize(img->width, img->height), IPL_DEPTH_8U, 1);
}
clock = std::clock();
filter.process(img, filterMask); // process the frame
clockTotal += (std::clock() - clock);
displayBuffer(img, filterMask, 0, 255, 0);
sequencer->getFrameCaption(caption);
std::sprintf(s, "%s - %d x %d", caption, img->width, img->height);
putTextWithShadow(img, s, cvPoint(10, img->height-35), &base_font);
std::sprintf(s, "Average processing time per frame: %5.2fms", (double(clockTotal*1000/CLOCKS_PER_SEC))/numFrames);
putTextWithShadow(img, s, cvPoint(10, img->height-15), &base_font);
cvShowImage (windowName, img);
cvReleaseImage(&img);
if (cvWaitKey(1) == 27)
break;
}
sequencer->close();
delete sequencer;
cvReleaseImage(&filterMask);
cvDestroyWindow(windowName);
std::cout << "Finished, " << numFrames << " frames processed." << std::endl;
return 0;
}
<commit_msg>added to and moved comments to top<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install, copy or use the software.
//
// Copyright (C) 2009, Farhad Dadgostar
// Intel Corporation and third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <opencv2/contrib/contrib.hpp>
#include <opencv2/highgui/highgui.hpp>
void help(char **argv)
{
std::cout << "\nThis program demonstrates the contributed flesh detector CvAdaptiveSkinDetector which can be found in contrib.cpp\n"
<< "Usage: " << std::endl <<
argv[0] << " fileMask firstFrame lastFrame" << std::endl << std::endl <<
"Example: " << std::endl <<
argv[0] << " C:\\VideoSequences\\sample1\\right_view\\temp_%05d.jpg 0 1000" << std::endl <<
" iterates through temp_00000.jpg to temp_01000.jpg" << std::endl << std::endl <<
"If no parameter specified, this application will try to capture from the default Webcam." << std::endl <<
"Please note: Background should not contain large surfaces with skin tone." <<
"\n\n ESC will stop\n" <<
std::endl;
}
class ASDFrameHolder
{
private:
IplImage *image;
double timeStamp;
public:
ASDFrameHolder();
virtual ~ASDFrameHolder();
virtual void assignFrame(IplImage *sourceImage, double frameTime);
inline IplImage *getImage();
inline double getTimeStamp();
virtual void setImage(IplImage *sourceImage);
};
class ASDFrameSequencer
{
public:
virtual ~ASDFrameSequencer();
virtual IplImage *getNextImage();
virtual void close();
virtual bool isOpen();
virtual void getFrameCaption(char *caption);
};
class ASDCVFrameSequencer : public ASDFrameSequencer
{
protected:
CvCapture *capture;
public:
virtual IplImage *getNextImage();
virtual void close();
virtual bool isOpen();
};
class ASDFrameSequencerWebCam : public ASDCVFrameSequencer
{
public:
virtual bool open(int cameraIndex);
};
class ASDFrameSequencerVideoFile : public ASDCVFrameSequencer
{
public:
virtual bool open(const char *fileName);
};
class ASDFrameSequencerImageFile : public ASDFrameSequencer {
private:
char sFileNameMask[2048];
int nCurrentIndex, nStartIndex, nEndIndex;
public:
virtual void open(const char *fileNameMask, int startIndex, int endIndex);
virtual void getFrameCaption(char *caption);
virtual IplImage *getNextImage();
virtual void close();
virtual bool isOpen();
};
//-------------------- ASDFrameHolder -----------------------//
ASDFrameHolder::ASDFrameHolder( )
{
image = NULL;
timeStamp = 0;
};
ASDFrameHolder::~ASDFrameHolder( )
{
cvReleaseImage(&image);
};
void ASDFrameHolder::assignFrame(IplImage *sourceImage, double frameTime)
{
if (image != NULL)
{
cvReleaseImage(&image);
image = NULL;
}
image = cvCloneImage(sourceImage);
timeStamp = frameTime;
};
IplImage *ASDFrameHolder::getImage()
{
return image;
};
double ASDFrameHolder::getTimeStamp()
{
return timeStamp;
};
void ASDFrameHolder::setImage(IplImage *sourceImage)
{
image = sourceImage;
};
//-------------------- ASDFrameSequencer -----------------------//
ASDFrameSequencer::~ASDFrameSequencer()
{
close();
};
IplImage *ASDFrameSequencer::getNextImage()
{
return NULL;
};
void ASDFrameSequencer::close()
{
};
bool ASDFrameSequencer::isOpen()
{
return false;
};
void ASDFrameSequencer::getFrameCaption(char *caption) {
return;
};
IplImage* ASDCVFrameSequencer::getNextImage()
{
IplImage *image;
image = cvQueryFrame(capture);
if (image != NULL)
{
return cvCloneImage(image);
}
else
{
return NULL;
}
};
void ASDCVFrameSequencer::close()
{
if (capture != NULL)
{
cvReleaseCapture(&capture);
}
};
bool ASDCVFrameSequencer::isOpen()
{
return (capture != NULL);
};
//-------------------- ASDFrameSequencerWebCam -----------------------//
bool ASDFrameSequencerWebCam::open(int cameraIndex)
{
close();
capture = cvCaptureFromCAM(cameraIndex);
if (!capture)
{
return false;
}
else
{
return true;
}
};
//-------------------- ASDFrameSequencerVideoFile -----------------------//
bool ASDFrameSequencerVideoFile::open(const char *fileName)
{
close();
capture = cvCaptureFromFile(fileName);
if (!capture)
{
return false;
}
else
{
return true;
}
};
//-------------------- ASDFrameSequencerImageFile -----------------------//
void ASDFrameSequencerImageFile::open(const char *fileNameMask, int startIndex, int endIndex)
{
nCurrentIndex = startIndex-1;
nStartIndex = startIndex;
nEndIndex = endIndex;
std::sprintf(sFileNameMask, "%s", fileNameMask);
};
void ASDFrameSequencerImageFile::getFrameCaption(char *caption) {
std::sprintf(caption, sFileNameMask, nCurrentIndex);
};
IplImage* ASDFrameSequencerImageFile::getNextImage()
{
char fileName[2048];
nCurrentIndex++;
if (nCurrentIndex > nEndIndex)
return NULL;
std::sprintf(fileName, sFileNameMask, nCurrentIndex);
IplImage* img = cvLoadImage(fileName);
return img;
};
void ASDFrameSequencerImageFile::close()
{
nCurrentIndex = nEndIndex+1;
};
bool ASDFrameSequencerImageFile::isOpen()
{
return (nCurrentIndex <= nEndIndex);
};
void putTextWithShadow(IplImage *img, const char *str, CvPoint point, CvFont *font, CvScalar color = CV_RGB(255, 255, 128))
{
cvPutText(img, str, cvPoint(point.x-1,point.y-1), font, CV_RGB(0, 0, 0));
cvPutText(img, str, point, font, color);
};
#define ASD_RGB_SET_PIXEL(pointer, r, g, b) { (*pointer) = (unsigned char)b; (*(pointer+1)) = (unsigned char)g; (*(pointer+2)) = (unsigned char)r; }
#define ASD_RGB_GET_PIXEL(pointer, r, g, b) {b = (unsigned char)(*(pointer)); g = (unsigned char)(*(pointer+1)); r = (unsigned char)(*(pointer+2));}
void displayBuffer(IplImage *rgbDestImage, IplImage *buffer, int rValue, int gValue, int bValue)
{
int x, y, nWidth, nHeight;
double destX, destY, dx, dy;
uchar c;
unsigned char *pSrc;
nWidth = buffer->width;
nHeight = buffer->height;
dx = double(rgbDestImage->width)/double(nWidth);
dy = double(rgbDestImage->height)/double(nHeight);
destX = 0;
for (x = 0; x < nWidth; x++)
{
destY = 0;
for (y = 0; y < nHeight; y++)
{
c = ((uchar*)(buffer->imageData + buffer->widthStep*y))[x];
if (c)
{
pSrc = (unsigned char *)rgbDestImage->imageData + rgbDestImage->widthStep*int(destY) + (int(destX)*rgbDestImage->nChannels);
ASD_RGB_SET_PIXEL(pSrc, rValue, gValue, bValue);
}
destY += dy;
}
destY = 0;
destX += dx;
}
};
int main(int argc, char** argv )
{
IplImage *img, *filterMask = NULL;
CvAdaptiveSkinDetector filter(1, CvAdaptiveSkinDetector::MORPHING_METHOD_ERODE_DILATE);
ASDFrameSequencer *sequencer;
CvFont base_font;
char caption[2048], s[256], windowName[256];
long int clockTotal = 0, numFrames = 0;
std::clock_t clock;
if (argc < 4)
{
help(argv);
sequencer = new ASDFrameSequencerWebCam();
(dynamic_cast<ASDFrameSequencerWebCam*>(sequencer))->open(-1);
if (! sequencer->isOpen())
{
std::cout << std::endl << "Error: Cannot initialize the default Webcam" << std::endl << std::endl;
}
}
else
{
sequencer = new ASDFrameSequencerImageFile();
(dynamic_cast<ASDFrameSequencerImageFile*>(sequencer))->open(argv[1], std::atoi(argv[2]), std::atoi(argv[3]) ); // A sequence of images captured from video source, is stored here
}
std::sprintf(windowName, "%s", "Adaptive Skin Detection Algorithm for Video Sequences");
cvNamedWindow(windowName, CV_WINDOW_AUTOSIZE);
cvInitFont( &base_font, CV_FONT_VECTOR0, 0.5, 0.5);
// Usage:
// c:\>CvASDSample "C:\VideoSequences\sample1\right_view\temp_%05d.jpg" 0 1000
std::cout << "Press ESC to stop." << std::endl << std::endl;
while ((img = sequencer->getNextImage()) != 0)
{
numFrames++;
if (filterMask == NULL)
{
filterMask = cvCreateImage( cvSize(img->width, img->height), IPL_DEPTH_8U, 1);
}
clock = std::clock();
filter.process(img, filterMask); // DETECT SKIN
clockTotal += (std::clock() - clock);
displayBuffer(img, filterMask, 0, 255, 0);
sequencer->getFrameCaption(caption);
std::sprintf(s, "%s - %d x %d", caption, img->width, img->height);
putTextWithShadow(img, s, cvPoint(10, img->height-35), &base_font);
std::sprintf(s, "Average processing time per frame: %5.2fms", (double(clockTotal*1000/CLOCKS_PER_SEC))/numFrames);
putTextWithShadow(img, s, cvPoint(10, img->height-15), &base_font);
cvShowImage (windowName, img);
cvReleaseImage(&img);
if (cvWaitKey(1) == 27)
break;
}
sequencer->close();
delete sequencer;
cvReleaseImage(&filterMask);
cvDestroyWindow(windowName);
std::cout << "Finished, " << numFrames << " frames processed." << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <imgui/imgui.h>
#include "game_view.h"
#include "editor/asset_browser.h"
#include "editor/asset_compiler.h"
#include "editor/settings.h"
#include "editor/studio_app.h"
#include "editor/utils.h"
#include "editor/world_editor.h"
#include "engine/crc32.h"
#include "engine/engine.h"
#include "engine/geometry.h"
#include "engine/input_system.h"
#include "engine/lua_wrapper.h"
#include "engine/profiler.h"
#include "engine/resource_manager.h"
#include "engine/universe.h"
#include "gui/gui_system.h"
#include "renderer/gpu/gpu.h"
#include "renderer/pipeline.h"
#include "renderer/render_scene.h"
#include "renderer/renderer.h"
#include "renderer/texture.h"
namespace Lumix
{
struct GUIInterface : GUISystem::Interface
{
explicit GUIInterface(GameView& game_view)
: m_game_view(game_view)
{
}
Pipeline* getPipeline() override { return m_game_view.m_pipeline.get(); }
Vec2 getPos() const override { return m_game_view.m_pos; }
Vec2 getSize() const override { return m_game_view.m_size; }
void setCursor(os::CursorType type) override { m_game_view.setCursor(type); }
void enableCursor(bool enable) override { m_game_view.enableIngameCursor(enable); }
GameView& m_game_view;
};
GameView::GameView(StudioApp& app)
: m_app(app)
, m_is_open(false)
, m_is_fullscreen(false)
, m_is_mouse_captured(false)
, m_is_ingame_cursor(false)
, m_time_multiplier(1.0f)
, m_paused(false)
, m_show_stats(false)
, m_editor(app.getWorldEditor())
{
Engine& engine = app.getEngine();
auto f = &LuaWrapper::wrapMethodClosure<&GameView::forceViewport>;
LuaWrapper::createSystemClosure(engine.getState(), "GameView", this, "forceViewport", f);
}
void GameView::init() {
IAllocator& allocator = m_app.getAllocator();
m_toggle_ui.init("Game View", "Toggle game view", "game_view", "", true);
m_toggle_ui.func.bind<&GameView::onAction>(this);
m_toggle_ui.is_selected.bind<&GameView::isOpen>(this);
m_app.addWindowAction(&m_toggle_ui);
m_fullscreen_action.init("Game View fullscreen", "Game View fullscreen", "game_view_fullscreen", "", true);
m_fullscreen_action.func.bind<&GameView::toggleFullscreen>(this);
m_app.addAction(&m_fullscreen_action);
Engine& engine = m_app.getEngine();
auto* renderer = (Renderer*)engine.getPluginManager().getPlugin("renderer");
PipelineResource* pres = engine.getResourceManager().load<PipelineResource>(Path("pipelines/main.pln"));
m_pipeline = Pipeline::create(*renderer, pres, "GAME_VIEW", engine.getAllocator());
auto* gui = static_cast<GUISystem*>(engine.getPluginManager().getPlugin("gui"));
if (gui)
{
m_gui_interface = UniquePtr<GUIInterface>::create(engine.getAllocator(), *this);
gui->setInterface(m_gui_interface.get());
}
}
GameView::~GameView()
{
m_app.removeAction(&m_toggle_ui);
m_app.removeAction(&m_fullscreen_action);
Engine& engine = m_app.getEngine();
auto* gui = static_cast<GUISystem*>(engine.getPluginManager().getPlugin("gui"));
if (gui) {
gui->setInterface(nullptr);
}
}
void GameView::setCursor(os::CursorType type)
{
m_cursor_type = type;
}
void GameView::enableIngameCursor(bool enable)
{
m_is_ingame_cursor = enable;
if (!m_is_mouse_captured) return;
os::showCursor(m_is_ingame_cursor);
}
void GameView::captureMouse(bool capture)
{
if (m_is_mouse_captured == capture) return;
m_app.setCursorCaptured(capture);
m_is_mouse_captured = capture;
os::showCursor(!capture || m_is_ingame_cursor);
if (capture) {
const os::Point cp = os::getMouseScreenPos();
m_captured_mouse_x = cp.x;
m_captured_mouse_y = cp.y;
}
else {
os::unclipCursor();
os::setMouseScreenPos(m_captured_mouse_x, m_captured_mouse_y);
}
}
void GameView::onSettingsLoaded() {
m_is_open = m_app.getSettings().getValue("is_game_view_open", false);
}
void GameView::onBeforeSettingsSaved() {
m_app.getSettings().setValue("is_game_view_open", m_is_open);
}
void GameView::onFullscreenGUI()
{
processInputEvents();
ImGuiIO& io = ImGui::GetIO();
bool open = true;
ImVec2 size = io.DisplaySize;
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->Pos);
ImGui::SetNextWindowSize(size);
if (!ImGui::Begin("game view fullscreen",
&open,
ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings))
{
ImGui::End();
return;
}
EntityPtr camera = m_pipeline->getScene()->getActiveCamera();
if (camera.isValid()) {
Viewport vp = m_pipeline->getScene()->getCameraViewport((EntityRef)camera);
vp.w = (int)size.x;
vp.h = (int)size.y;
m_pipeline->getScene()->setCameraScreenSize((EntityRef)camera, vp.w, vp.h);
m_pipeline->setViewport(vp);
m_pipeline->render(false);
const gpu::TextureHandle texture_handle = m_pipeline->getOutput();
if (gpu::isOriginBottomLeft())
{
ImGui::Image(texture_handle, size, ImVec2(0, 1), ImVec2(1, 0));
}
else
{
ImGui::Image(texture_handle, size);
}
}
else {
ImGuiEx::Rect(size.x, size.y, 0xff0000FF);
}
m_pos = ImGui::GetItemRectMin();
m_size = ImGui::GetItemRectSize();
ImGui::End();
if (m_is_fullscreen && (io.KeysDown[ImGui::GetKeyIndex(ImGuiKey_Escape)] || !m_editor.isGameMode()))
{
setFullscreen(false);
}
}
void GameView::toggleFullscreen()
{
if (!m_editor.isGameMode()) return;
setFullscreen(!m_is_fullscreen);
}
void GameView::setFullscreen(bool fullscreen)
{
captureMouse(fullscreen);
m_app.setFullscreen(fullscreen);
m_is_fullscreen = fullscreen;
}
void GameView::onStatsGUI(const ImVec2& view_pos)
{
if (!m_show_stats || !m_is_open) return;
float toolbar_height = 24 + ImGui::GetStyle().FramePadding.y * 2;
ImVec2 v = view_pos;
v.x += ImGui::GetStyle().FramePadding.x;
v.y += ImGui::GetStyle().FramePadding.y + toolbar_height;
ImGui::SetNextWindowPos(v);
auto col = ImGui::GetStyle().Colors[ImGuiCol_WindowBg];
col.w = 0.3f;
ImGui::PushStyleColor(ImGuiCol_WindowBg, col);
ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings;
if (ImGui::Begin("###stats_overlay", nullptr, flags)) {
const auto& stats = m_pipeline->getStats();
ImGui::LabelText("Draw calls", "%d", stats.draw_call_count);
ImGui::LabelText("Instances", "%d", stats.instance_count);
char buf[30];
toCStringPretty(stats.triangle_count, Span(buf));
ImGui::LabelText("Triangles", "%s", buf);
ImGui::LabelText("Resolution", "%dx%d", (int)m_size.x, (int)m_size.y);
}
ImGui::End();
ImGui::PopStyleColor();
}
void GameView::forceViewport(bool enable, int w, int h)
{
m_forced_viewport.enabled = enable;
m_forced_viewport.width = w;
m_forced_viewport.height = h;
}
void GameView::processInputEvents()
{
if (!m_is_mouse_captured) return;
Engine& engine = m_app.getEngine();
InputSystem& input = engine.getInputSystem();
const os::Event* events = m_app.getEvents();
for (int i = 0, c = m_app.getEventsCount(); i < c; ++i) {
input.injectEvent(events[i], int(m_pos.x), int(m_pos.y));
}
}
void GameView::controlsGUI() {
Engine& engine = m_app.getEngine();
if (ImGui::Checkbox("Pause", &m_paused)) engine.pause(m_paused);
if (m_paused) {
ImGui::SameLine();
if (ImGui::Button("Next frame")) engine.nextFrame();
}
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragFloat("Time multiplier", &m_time_multiplier, 0.01f, 0.01f, 30.0f)) {
engine.setTimeMultiplier(m_time_multiplier);
}
ImGui::PopItemWidth();
if(m_editor.isGameMode()) {
ImGui::SameLine();
if (ImGui::Button("Fullscreen")) setFullscreen(true);
}
ImGui::SameLine();
ImGui::Checkbox("Stats", &m_show_stats);
ImGui::SameLine();
m_pipeline->callLuaFunction("onGUI");
}
void GameView::onWindowGUI()
{
PROFILE_FUNCTION();
if (!m_pipeline->isReady()) {
captureMouse(false);
return;
}
m_pipeline->setUniverse(m_editor.getUniverse());
ImGuiIO& io = ImGui::GetIO();
if (m_is_mouse_captured && (io.KeysDown[ImGui::GetKeyIndex(ImGuiKey_Escape)] || !m_editor.isGameMode())) {
captureMouse(false);
}
const char* window_name = ICON_FA_CAMERA "Game View###game_view";
if (m_is_mouse_captured) {
window_name = ICON_FA_CAMERA "Game View (mouse captured)###game_view";
os::setCursor(m_cursor_type);
}
if (m_is_fullscreen) {
onFullscreenGUI();
return;
}
if (!m_is_open) {
captureMouse(false);
return;
}
ImVec2 view_pos;
bool is_game_view_visible = false;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
if (ImGui::Begin(window_name, &m_is_open, ImGuiWindowFlags_NoNavInputs)) {
is_game_view_visible = true;
view_pos = ImGui::GetCursorScreenPos();
const ImVec2 content_min = view_pos;
ImVec2 size = ImGui::GetContentRegionAvail();
size.y -= ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().ItemSpacing.y * 3;
ImVec2 content_max(content_min.x + size.x, content_min.y + size.y);
if (m_forced_viewport.enabled) size = { (float)m_forced_viewport.width, (float)m_forced_viewport.height };
if (size.x > 0 && size.y > 0) {
RenderScene* scene = m_pipeline->getScene();
const EntityPtr camera = scene->getActiveCamera();
Viewport vp;
if (camera.isValid()) {
vp = scene->getCameraViewport((EntityRef)camera);
vp.w = (int)size.x;
vp.h = (int)size.y;
scene->setCameraScreenSize((EntityRef)camera, vp.w, vp.h);
}
else {
vp.w = (int)size.x;
vp.h = (int)size.y;
vp.fov = degreesToRadians(90.f);
vp.is_ortho = false;
vp.far = 10'000.f;
vp.near = 1.f;
vp.pos = DVec3(0);
vp.rot = Quat(0, 0, 0, 1);
}
m_pipeline->setViewport(vp);
m_pipeline->render(false);
const gpu::TextureHandle texture_handle = m_pipeline->getOutput();
if (texture_handle) {
if (gpu::isOriginBottomLeft()) {
ImGui::Image(texture_handle, size, ImVec2(0, 1), ImVec2(1, 0));
}
else {
ImGui::Image(texture_handle, size);
}
}
else {
ImGuiEx::Rect(size.x, size.y, 0xffFF00FF);
}
const bool is_hovered = ImGui::IsItemHovered();
if (is_hovered && ImGui::IsMouseClicked(0) && m_editor.isGameMode()) captureMouse(true);
m_pos = ImGui::GetItemRectMin();
m_size = ImGui::GetItemRectSize();
if (m_is_mouse_captured) {
os::clipCursor((int)m_pos.x, (int)m_pos.y, (int)m_size.x, (int)m_size.y);
}
processInputEvents();
controlsGUI();
}
}
if (m_is_mouse_captured && os::getFocused() != ImGui::GetWindowViewport()->PlatformHandle) captureMouse(false);
ImGui::End();
ImGui::PopStyleVar();
if (is_game_view_visible) onStatsGUI(view_pos);
}
} // namespace Lumix
<commit_msg>game view does not automatically get focus after pipeline is reloaded<commit_after>#include <imgui/imgui.h>
#include "game_view.h"
#include "editor/asset_browser.h"
#include "editor/asset_compiler.h"
#include "editor/settings.h"
#include "editor/studio_app.h"
#include "editor/utils.h"
#include "editor/world_editor.h"
#include "engine/crc32.h"
#include "engine/engine.h"
#include "engine/geometry.h"
#include "engine/input_system.h"
#include "engine/lua_wrapper.h"
#include "engine/profiler.h"
#include "engine/resource_manager.h"
#include "engine/universe.h"
#include "gui/gui_system.h"
#include "renderer/gpu/gpu.h"
#include "renderer/pipeline.h"
#include "renderer/render_scene.h"
#include "renderer/renderer.h"
#include "renderer/texture.h"
namespace Lumix
{
struct GUIInterface : GUISystem::Interface
{
explicit GUIInterface(GameView& game_view)
: m_game_view(game_view)
{
}
Pipeline* getPipeline() override { return m_game_view.m_pipeline.get(); }
Vec2 getPos() const override { return m_game_view.m_pos; }
Vec2 getSize() const override { return m_game_view.m_size; }
void setCursor(os::CursorType type) override { m_game_view.setCursor(type); }
void enableCursor(bool enable) override { m_game_view.enableIngameCursor(enable); }
GameView& m_game_view;
};
GameView::GameView(StudioApp& app)
: m_app(app)
, m_is_open(false)
, m_is_fullscreen(false)
, m_is_mouse_captured(false)
, m_is_ingame_cursor(false)
, m_time_multiplier(1.0f)
, m_paused(false)
, m_show_stats(false)
, m_editor(app.getWorldEditor())
{
Engine& engine = app.getEngine();
auto f = &LuaWrapper::wrapMethodClosure<&GameView::forceViewport>;
LuaWrapper::createSystemClosure(engine.getState(), "GameView", this, "forceViewport", f);
}
void GameView::init() {
IAllocator& allocator = m_app.getAllocator();
m_toggle_ui.init("Game View", "Toggle game view", "game_view", "", true);
m_toggle_ui.func.bind<&GameView::onAction>(this);
m_toggle_ui.is_selected.bind<&GameView::isOpen>(this);
m_app.addWindowAction(&m_toggle_ui);
m_fullscreen_action.init("Game View fullscreen", "Game View fullscreen", "game_view_fullscreen", "", true);
m_fullscreen_action.func.bind<&GameView::toggleFullscreen>(this);
m_app.addAction(&m_fullscreen_action);
Engine& engine = m_app.getEngine();
auto* renderer = (Renderer*)engine.getPluginManager().getPlugin("renderer");
PipelineResource* pres = engine.getResourceManager().load<PipelineResource>(Path("pipelines/main.pln"));
m_pipeline = Pipeline::create(*renderer, pres, "GAME_VIEW", engine.getAllocator());
auto* gui = static_cast<GUISystem*>(engine.getPluginManager().getPlugin("gui"));
if (gui)
{
m_gui_interface = UniquePtr<GUIInterface>::create(engine.getAllocator(), *this);
gui->setInterface(m_gui_interface.get());
}
}
GameView::~GameView()
{
m_app.removeAction(&m_toggle_ui);
m_app.removeAction(&m_fullscreen_action);
Engine& engine = m_app.getEngine();
auto* gui = static_cast<GUISystem*>(engine.getPluginManager().getPlugin("gui"));
if (gui) {
gui->setInterface(nullptr);
}
}
void GameView::setCursor(os::CursorType type)
{
m_cursor_type = type;
}
void GameView::enableIngameCursor(bool enable)
{
m_is_ingame_cursor = enable;
if (!m_is_mouse_captured) return;
os::showCursor(m_is_ingame_cursor);
}
void GameView::captureMouse(bool capture)
{
if (m_is_mouse_captured == capture) return;
m_app.setCursorCaptured(capture);
m_is_mouse_captured = capture;
os::showCursor(!capture || m_is_ingame_cursor);
if (capture) {
const os::Point cp = os::getMouseScreenPos();
m_captured_mouse_x = cp.x;
m_captured_mouse_y = cp.y;
}
else {
os::unclipCursor();
os::setMouseScreenPos(m_captured_mouse_x, m_captured_mouse_y);
}
}
void GameView::onSettingsLoaded() {
m_is_open = m_app.getSettings().getValue("is_game_view_open", false);
}
void GameView::onBeforeSettingsSaved() {
m_app.getSettings().setValue("is_game_view_open", m_is_open);
}
void GameView::onFullscreenGUI()
{
processInputEvents();
ImGuiIO& io = ImGui::GetIO();
bool open = true;
ImVec2 size = io.DisplaySize;
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->Pos);
ImGui::SetNextWindowSize(size);
if (!ImGui::Begin("game view fullscreen",
&open,
ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings))
{
ImGui::End();
return;
}
EntityPtr camera = m_pipeline->getScene()->getActiveCamera();
if (camera.isValid()) {
Viewport vp = m_pipeline->getScene()->getCameraViewport((EntityRef)camera);
vp.w = (int)size.x;
vp.h = (int)size.y;
m_pipeline->getScene()->setCameraScreenSize((EntityRef)camera, vp.w, vp.h);
m_pipeline->setViewport(vp);
m_pipeline->render(false);
const gpu::TextureHandle texture_handle = m_pipeline->getOutput();
if (gpu::isOriginBottomLeft())
{
ImGui::Image(texture_handle, size, ImVec2(0, 1), ImVec2(1, 0));
}
else
{
ImGui::Image(texture_handle, size);
}
}
else {
ImGuiEx::Rect(size.x, size.y, 0xff0000FF);
}
m_pos = ImGui::GetItemRectMin();
m_size = ImGui::GetItemRectSize();
ImGui::End();
if (m_is_fullscreen && (io.KeysDown[ImGui::GetKeyIndex(ImGuiKey_Escape)] || !m_editor.isGameMode()))
{
setFullscreen(false);
}
}
void GameView::toggleFullscreen()
{
if (!m_editor.isGameMode()) return;
setFullscreen(!m_is_fullscreen);
}
void GameView::setFullscreen(bool fullscreen)
{
captureMouse(fullscreen);
m_app.setFullscreen(fullscreen);
m_is_fullscreen = fullscreen;
}
void GameView::onStatsGUI(const ImVec2& view_pos)
{
if (!m_show_stats || !m_is_open) return;
float toolbar_height = 24 + ImGui::GetStyle().FramePadding.y * 2;
ImVec2 v = view_pos;
v.x += ImGui::GetStyle().FramePadding.x;
v.y += ImGui::GetStyle().FramePadding.y + toolbar_height;
ImGui::SetNextWindowPos(v);
auto col = ImGui::GetStyle().Colors[ImGuiCol_WindowBg];
col.w = 0.3f;
ImGui::PushStyleColor(ImGuiCol_WindowBg, col);
ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings;
if (ImGui::Begin("###stats_overlay", nullptr, flags)) {
const auto& stats = m_pipeline->getStats();
ImGui::LabelText("Draw calls", "%d", stats.draw_call_count);
ImGui::LabelText("Instances", "%d", stats.instance_count);
char buf[30];
toCStringPretty(stats.triangle_count, Span(buf));
ImGui::LabelText("Triangles", "%s", buf);
ImGui::LabelText("Resolution", "%dx%d", (int)m_size.x, (int)m_size.y);
}
ImGui::End();
ImGui::PopStyleColor();
}
void GameView::forceViewport(bool enable, int w, int h)
{
m_forced_viewport.enabled = enable;
m_forced_viewport.width = w;
m_forced_viewport.height = h;
}
void GameView::processInputEvents()
{
if (!m_is_mouse_captured) return;
Engine& engine = m_app.getEngine();
InputSystem& input = engine.getInputSystem();
const os::Event* events = m_app.getEvents();
for (int i = 0, c = m_app.getEventsCount(); i < c; ++i) {
input.injectEvent(events[i], int(m_pos.x), int(m_pos.y));
}
}
void GameView::controlsGUI() {
Engine& engine = m_app.getEngine();
if (ImGui::Checkbox("Pause", &m_paused)) engine.pause(m_paused);
if (m_paused) {
ImGui::SameLine();
if (ImGui::Button("Next frame")) engine.nextFrame();
}
ImGui::SameLine();
ImGui::PushItemWidth(50);
if (ImGui::DragFloat("Time multiplier", &m_time_multiplier, 0.01f, 0.01f, 30.0f)) {
engine.setTimeMultiplier(m_time_multiplier);
}
ImGui::PopItemWidth();
if(m_editor.isGameMode()) {
ImGui::SameLine();
if (ImGui::Button("Fullscreen")) setFullscreen(true);
}
ImGui::SameLine();
ImGui::Checkbox("Stats", &m_show_stats);
ImGui::SameLine();
m_pipeline->callLuaFunction("onGUI");
}
void GameView::onWindowGUI()
{
PROFILE_FUNCTION();
m_pipeline->setUniverse(m_editor.getUniverse());
ImGuiIO& io = ImGui::GetIO();
if (m_is_mouse_captured && (io.KeysDown[ImGui::GetKeyIndex(ImGuiKey_Escape)] || !m_editor.isGameMode())) {
captureMouse(false);
}
const char* window_name = ICON_FA_CAMERA "Game View###game_view";
if (m_is_mouse_captured) {
window_name = ICON_FA_CAMERA "Game View (mouse captured)###game_view";
os::setCursor(m_cursor_type);
}
if (m_is_fullscreen && m_pipeline->isReady()) {
onFullscreenGUI();
return;
}
if (!m_is_open) {
captureMouse(false);
return;
}
if (!m_pipeline->isReady()) captureMouse(false);
ImVec2 view_pos;
bool is_game_view_visible = false;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
if (ImGui::Begin(window_name, &m_is_open, ImGuiWindowFlags_NoNavInputs)) {
is_game_view_visible = true;
view_pos = ImGui::GetCursorScreenPos();
const ImVec2 content_min = view_pos;
ImVec2 size = ImGui::GetContentRegionAvail();
size.y -= ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().ItemSpacing.y * 3;
ImVec2 content_max(content_min.x + size.x, content_min.y + size.y);
if (m_forced_viewport.enabled) size = { (float)m_forced_viewport.width, (float)m_forced_viewport.height };
if (size.x > 0 && size.y > 0) {
RenderScene* scene = m_pipeline->getScene();
const EntityPtr camera = scene->getActiveCamera();
Viewport vp;
if (camera.isValid()) {
vp = scene->getCameraViewport((EntityRef)camera);
vp.w = (int)size.x;
vp.h = (int)size.y;
scene->setCameraScreenSize((EntityRef)camera, vp.w, vp.h);
}
else {
vp.w = (int)size.x;
vp.h = (int)size.y;
vp.fov = degreesToRadians(90.f);
vp.is_ortho = false;
vp.far = 10'000.f;
vp.near = 1.f;
vp.pos = DVec3(0);
vp.rot = Quat(0, 0, 0, 1);
}
m_pipeline->setViewport(vp);
m_pipeline->render(false);
const gpu::TextureHandle texture_handle = m_pipeline->getOutput();
if (texture_handle) {
if (gpu::isOriginBottomLeft()) {
ImGui::Image(texture_handle, size, ImVec2(0, 1), ImVec2(1, 0));
}
else {
ImGui::Image(texture_handle, size);
}
}
else {
ImGuiEx::Rect(size.x, size.y, 0xffFF00FF);
}
const bool is_hovered = ImGui::IsItemHovered();
if (is_hovered && ImGui::IsMouseClicked(0) && m_editor.isGameMode()) captureMouse(true);
m_pos = ImGui::GetItemRectMin();
m_size = ImGui::GetItemRectSize();
if (m_is_mouse_captured) {
os::clipCursor((int)m_pos.x, (int)m_pos.y, (int)m_size.x, (int)m_size.y);
}
processInputEvents();
controlsGUI();
}
}
if (m_is_mouse_captured && os::getFocused() != ImGui::GetWindowViewport()->PlatformHandle) captureMouse(false);
ImGui::End();
ImGui::PopStyleVar();
if (is_game_view_visible) onStatsGUI(view_pos);
}
} // namespace Lumix
<|endoftext|> |
<commit_before>#include "scene/scenegroup.hpp"
#include <algorithm>
#include <tuple>
#include <functional>
#include <cassert>
#include "config/globals.hpp"
#include "sceneitem.hpp"
using namespace scene;
typedef collisiondetection::AxisAlignedBoundingBox AABB;
typedef std::tuple<glm::vec3, glm::vec3> Diagonal;
SceneGroup* SceneGroup::rootNode;
std::recursive_mutex SceneGroup::sceneMutex;
SceneGroup::SceneGroup() : childGroups{nullptr} {
rootNode = this;
}
SceneGroup::SceneGroup(unsigned int octreeLevels, collisiondetection::AxisAlignedBoundingBox myConstraints)
: constraints(new AABB(myConstraints)) {
addOctreeLayers(octreeLevels);
rootNode = this;
}
void SceneGroup::addOctreeLayers(unsigned int levels) {
if(levels != 0) {
childGroups = new std::array<SceneGroup,8>;
//Calculate and set constraints for all childGroups
float width = (constraints->maxX - constraints->minX) / 2.0f;
float height = (constraints->maxY - constraints->minY) / 2.0f;
float depth = (constraints->maxZ - constraints->minZ) / 2.0f;
glm::vec3 childMinimum(constraints->minX, constraints->minY, constraints->maxZ);
glm::vec3 childMaximum(constraints->minX + width, constraints->minY + height, constraints->maxZ - depth);
(*childGroups)[0].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.x += width;
childMaximum.x += width;
(*childGroups)[1].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.z -= depth;
childMaximum.z -= depth;
(*childGroups)[2].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.x -= width;
childMaximum.x -= width;
(*childGroups)[3].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.y += height;
childMaximum.y += height;
(*childGroups)[4].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.z += depth;
childMaximum.z += depth;
(*childGroups)[5].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.x += width;
childMaximum.x += width;
(*childGroups)[6].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.z -= depth;
childMaximum.z -= depth;
(*childGroups)[7].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
//Recursive call
std::for_each(childGroups->begin(), childGroups->end(),
[=](SceneGroup& child) {
child.addOctreeLayers(levels-1);
});
}
}
void SceneGroup::visitScene(std::function<void(std::unique_ptr<SceneItem>&)> visitation) {
std::lock_guard<std::recursive_mutex> guard(sceneMutex);
std::for_each(childItems.begin(), childItems.end(), visitation);
if(childGroups != nullptr) {
std::for_each(childGroups->begin(), childGroups->end(),
[&](SceneGroup& child) {
child.visitScene(visitation);
});
}
}
void SceneGroup::visitGroups(std::function<void(SceneGroup&)> visitation) {
visitation(*this);
if(childGroups != nullptr) {
std::for_each(childGroups->begin(), childGroups->end(),
[&](SceneGroup& child) {
child.visitGroups(visitation);
});
}
}
void SceneGroup::bubbleItem(std::unique_ptr<SceneItem> item) {
std::lock_guard<std::recursive_mutex> guard(sceneMutex);
if(childGroups != nullptr) {
std::function<bool(SceneGroup&)> itemInGroup = [&item](SceneGroup& child) {
return child.constraints->intersects(item->getBounds());
};
auto viableGroup = std::find_if(childGroups->begin(), childGroups->end(), itemInGroup);
assert(viableGroup != childGroups->end());
if(viableGroup+1 != childGroups->end()) {
auto otherGroup = std::find_if(viableGroup+1, childGroups->end(), itemInGroup);
if(otherGroup != childGroups->end()) {
addItem(std::move(item));
return;
}
}
viableGroup->bubbleItem(std::move(item));
}
addItem(std::move(item));
}
void SceneGroup::addItem(std::unique_ptr<SceneItem> item) {
if (childGroups == nullptr && childItems.size() == config::globals::maxSceneGroupSize) {
addOctreeLayers(1);
auto it = childItems.begin();
while(it != childItems.end()) {
std::lock_guard<std::recursive_mutex> guard(rootNode->sceneMutex);
bubbleItem(std::move(*it));
it = childItems.erase(it);
}
//Finally push in item
std::lock_guard<std::recursive_mutex> lock(rootNode->sceneMutex);
bubbleItem(std::move(item));
} else {
childItems.push_back(std::move(item));
}
}
SceneGroup::~SceneGroup() {
if(childGroups != nullptr) {
delete childGroups;
}
}<commit_msg>SceneGroup: Add needed comment<commit_after>#include "scene/scenegroup.hpp"
#include <algorithm>
#include <tuple>
#include <functional>
#include <cassert>
#include "config/globals.hpp"
#include "sceneitem.hpp"
using namespace scene;
typedef collisiondetection::AxisAlignedBoundingBox AABB;
typedef std::tuple<glm::vec3, glm::vec3> Diagonal;
SceneGroup* SceneGroup::rootNode;
std::recursive_mutex SceneGroup::sceneMutex;
SceneGroup::SceneGroup() : childGroups{nullptr} {
rootNode = this;
}
SceneGroup::SceneGroup(unsigned int octreeLevels, collisiondetection::AxisAlignedBoundingBox myConstraints)
: constraints(new AABB(myConstraints)) {
addOctreeLayers(octreeLevels);
rootNode = this;
}
void SceneGroup::addOctreeLayers(unsigned int levels) {
if(levels != 0) {
childGroups = new std::array<SceneGroup,8>;
//Calculate and set constraints for all childGroups
float width = (constraints->maxX - constraints->minX) / 2.0f;
float height = (constraints->maxY - constraints->minY) / 2.0f;
float depth = (constraints->maxZ - constraints->minZ) / 2.0f;
glm::vec3 childMinimum(constraints->minX, constraints->minY, constraints->maxZ);
glm::vec3 childMaximum(constraints->minX + width, constraints->minY + height, constraints->maxZ - depth);
(*childGroups)[0].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.x += width;
childMaximum.x += width;
(*childGroups)[1].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.z -= depth;
childMaximum.z -= depth;
(*childGroups)[2].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.x -= width;
childMaximum.x -= width;
(*childGroups)[3].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.y += height;
childMaximum.y += height;
(*childGroups)[4].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.z += depth;
childMaximum.z += depth;
(*childGroups)[5].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.x += width;
childMaximum.x += width;
(*childGroups)[6].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
childMinimum.z -= depth;
childMaximum.z -= depth;
(*childGroups)[7].constraints.reset(new AABB(Diagonal(childMinimum, childMaximum)));
//Recursive call
std::for_each(childGroups->begin(), childGroups->end(),
[=](SceneGroup& child) {
child.addOctreeLayers(levels-1);
});
}
}
void SceneGroup::visitScene(std::function<void(std::unique_ptr<SceneItem>&)> visitation) {
std::lock_guard<std::recursive_mutex> guard(sceneMutex);
std::for_each(childItems.begin(), childItems.end(), visitation);
if(childGroups != nullptr) {
std::for_each(childGroups->begin(), childGroups->end(),
[&](SceneGroup& child) {
child.visitScene(visitation);
});
}
}
void SceneGroup::visitGroups(std::function<void(SceneGroup&)> visitation) {
visitation(*this);
if(childGroups != nullptr) {
std::for_each(childGroups->begin(), childGroups->end(),
[&](SceneGroup& child) {
child.visitGroups(visitation);
});
}
}
void SceneGroup::bubbleItem(std::unique_ptr<SceneItem> item) {
std::lock_guard<std::recursive_mutex> guard(sceneMutex);
if(childGroups != nullptr) {
std::function<bool(SceneGroup&)> itemInGroup = [&item](SceneGroup& child) {
return child.constraints->intersects(item->getBounds());
};
auto viableGroup = std::find_if(childGroups->begin(), childGroups->end(), itemInGroup);
assert(viableGroup != childGroups->end());
if(viableGroup+1 != childGroups->end()) {
auto otherGroup = std::find_if(viableGroup+1, childGroups->end(), itemInGroup);
if(otherGroup != childGroups->end()) {
//The item is on the edge of two groups, add to current group
addItem(std::move(item));
return;
}
}
viableGroup->bubbleItem(std::move(item));
}
addItem(std::move(item));
}
void SceneGroup::addItem(std::unique_ptr<SceneItem> item) {
if (childGroups == nullptr && childItems.size() == config::globals::maxSceneGroupSize) {
addOctreeLayers(1);
auto it = childItems.begin();
while(it != childItems.end()) {
std::lock_guard<std::recursive_mutex> guard(rootNode->sceneMutex);
bubbleItem(std::move(*it));
it = childItems.erase(it);
}
//Finally push in item
std::lock_guard<std::recursive_mutex> lock(rootNode->sceneMutex);
bubbleItem(std::move(item));
} else {
childItems.push_back(std::move(item));
}
}
SceneGroup::~SceneGroup() {
if(childGroups != nullptr) {
delete childGroups;
}
}<|endoftext|> |
<commit_before>//(c) 2016 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)
#include "read_aligner.h"
#include "../common/parallel.h"
#include <cmath>
#include <iomanip>
namespace
{
struct Chain
{
Chain(): score(0) {}
std::vector<const EdgeAlignment*> aln;
int32_t score;
};
}
//Give alignments to separate edges for a single read, merges them
//into non-overlapping chains (could be more than one chain per read
//in case of chimera) with maximum score
std::vector<GraphAlignment>
ReadAligner::chainReadAlignments(const SequenceContainer& edgeSeqs,
const std::vector<EdgeAlignment>& ovlps) const
{
static const int32_t MAX_JUMP = Config::get("maximum_jump");
static const int32_t MAX_READ_OVLP = 50;
std::list<Chain> activeChains;
for (auto& edgeAlignment : ovlps)
{
std::list<Chain> newChains;
int32_t maxScore = 0;
Chain* maxChain = nullptr;
for (auto& chain : activeChains)
{
const OverlapRange& nextOvlp = edgeAlignment.overlap;
const OverlapRange& prevOvlp = chain.aln.back()->overlap;
int32_t readDiff = nextOvlp.curBegin - prevOvlp.curEnd;
int32_t graphDiff = nextOvlp.extBegin +
prevOvlp.extLen - prevOvlp.extEnd;
if (chain.aln.back()->edge->nodeRight == edgeAlignment.edge->nodeLeft &&
MAX_JUMP > readDiff && readDiff > -MAX_READ_OVLP &&
MAX_JUMP > graphDiff && graphDiff > 0)
{
int32_t jumpDiv = abs(readDiff - graphDiff);
int32_t gapCost = jumpDiv ? std::log2(jumpDiv) : 0;
int32_t score = chain.score + nextOvlp.score - gapCost;
if (score > maxScore)
{
maxScore = score;
maxChain = &chain;
}
}
}
if (maxChain)
{
newChains.push_back(*maxChain);
maxChain->aln.push_back(&edgeAlignment);
maxChain->score = maxScore;
}
activeChains.splice(activeChains.end(), newChains);
activeChains.push_back(Chain());
activeChains.back().aln.push_back(&edgeAlignment);
activeChains.back().score = edgeAlignment.overlap.score;
}
//greedily choose non-intersecting set of alignments
std::vector<GraphAlignment> acceptedAlignments;
std::vector<Chain> sortedChains(activeChains.begin(), activeChains.end());
std::sort(sortedChains.begin(), sortedChains.end(),
[](const Chain& c1, const Chain& c2)
{return c1.score > c2.score;});
for (auto& chain : sortedChains)
{
int32_t alnLen = chain.aln.back()->overlap.curEnd -
chain.aln.front()->overlap.curBegin;
if (alnLen < Parameters::get().minimumOverlap) continue;
//check if it overlaps with other accepted chains
bool overlaps = false;
for (auto& existAln : acceptedAlignments)
{
int32_t existStart = existAln.front().overlap.curBegin;
int32_t existEnd = existAln.back().overlap.curEnd;
int32_t curStart = chain.aln.front()->overlap.curBegin;
int32_t curEnd = chain.aln.back()->overlap.curEnd;
int32_t overlapRate = std::min(curEnd, existEnd) -
std::max(curStart, existStart);
if (overlapRate > (int)Config::get("max_separation")) overlaps = true;
}
if (!overlaps)
{
acceptedAlignments.emplace_back();
for (auto& aln : chain.aln) acceptedAlignments.back().push_back(*aln);
}
}
return acceptedAlignments;
}
void ReadAligner::alignReads()
{
static const int MIN_EDGE_OVLP = (int)Config::get("max_separation");
static const int EDGE_FLANK = 100;
//create database
std::unordered_map<FastaRecord::Id,
std::pair<GraphEdge*, SequenceSegment>> idToSegment;
SequenceContainer pathsContainer;
for (auto& edge : _graph.iterEdges())
{
if (!edge->edgeId.strand()) continue;
//add each edge sequence variant to the database
for (auto& segment : edge->seqSegments)
{
size_t len = segment.end - segment.start;
auto sequence = _asmSeqs.getSeq(segment.seqId)
.substr(segment.start, len);
auto& newRec = pathsContainer.addSequence(sequence, "");
idToSegment[newRec.id] = {edge, segment};
idToSegment[newRec.id.rc()] = {_graph.complementEdge(edge),
segment.complement()};
}
}
pathsContainer.buildPositionIndex();
//index it and align reads
VertexIndex pathsIndex(pathsContainer,
(int)Config::get("read_align_kmer_sample"));
pathsIndex.countKmers(/*min freq*/ 1, /* genome size*/ 0);
pathsIndex.setRepeatCutoff(/*min freq*/ 1);
pathsIndex.buildIndex(/*min freq*/ 1);
OverlapDetector readsOverlapper(pathsContainer, pathsIndex,
(int)Config::get("maximum_jump"),
MIN_EDGE_OVLP - EDGE_FLANK,
/*no overhang*/ 0, /*no max ovlp count*/ 0,
/*keep alignment*/ false, /*only max*/ false,
(float)Config::get("read_align_ovlp_ident"),
/* bad end adjust*/ 0.0f);
OverlapContainer readsOverlaps(readsOverlapper, _readSeqs);
std::vector<FastaRecord::Id> allQueries;
int64_t totalLength = 0;
for (auto& read : _readSeqs.iterSeqs())
{
if (!read.id.strand()) continue;
if (read.sequence.length() > (size_t)Parameters::get().minimumOverlap)
{
totalLength += read.sequence.length();
allQueries.push_back(read.id);
}
}
std::mutex indexMutex;
int numAligned = 0;
int alignedInFull = 0;
int64_t alignedLength = 0;
std::function<void(const FastaRecord::Id&)> alignRead =
[this, &indexMutex, &numAligned, &readsOverlaps,
&idToSegment, &pathsContainer, &alignedLength, &alignedInFull]
(const FastaRecord::Id& seqId)
{
auto overlaps = readsOverlaps.quickSeqOverlaps(seqId);
std::vector<EdgeAlignment> alignments;
for (auto& ovlp : overlaps)
{
//because edges might be as short as max_separation,
//we set minimum alignment threshold to a bit shorter value.
//However, apply the actual threshold for longer edges now.
if (ovlp.extLen < MIN_EDGE_OVLP + EDGE_FLANK ||
std::min(ovlp.curRange(), ovlp.extRange()) > MIN_EDGE_OVLP)
{
alignments.push_back({ovlp, idToSegment[ovlp.extId].first,
idToSegment[ovlp.extId].second});
}
}
std::sort(alignments.begin(), alignments.end(),
[](const EdgeAlignment& e1, const EdgeAlignment& e2)
{return e1.overlap.curBegin < e2.overlap.curBegin;});
auto readChains = this->chainReadAlignments(pathsContainer, alignments);
std::vector<GraphAlignment> complChains(readChains);
for (auto& chain : complChains)
{
for (auto& aln : chain)
{
aln.edge = _graph.complementEdge(aln.edge);
aln.segment = aln.segment.complement();
aln.overlap = aln.overlap.complement();
}
std::reverse(chain.begin(), chain.end());
}
if (readChains.empty()) return;
/////synchronized part
indexMutex.lock();
++numAligned;
if (readChains.size() == 1) ++alignedInFull;
for (auto& chain : readChains)
{
_readAlignments.push_back(chain);
alignedLength += chain.back().overlap.curEnd -
chain.front().overlap.curBegin;
}
for (auto& chain : complChains)
{
_readAlignments.push_back(chain);
}
indexMutex.unlock();
/////
};
processInParallel(allQueries, alignRead,
Parameters::get().numThreads, true);
/*for (auto& aln : _readAlignments)
{
if (aln.size() > 1)
{
std::string alnStr;
int switches = 0;
for (size_t i = 0; i < aln.size() - 1; ++i)
{
if (aln[i].segment.end != aln[i + 1].segment.start) ++switches;
}
for (auto& edge : aln)
{
alnStr += std::to_string(edge.edge->edgeId.signedId()) + " ("
+ std::to_string(edge.overlap.curRange()) + " "
+ std::to_string(edge.overlap.score) + " "
+ std::to_string((float)edge.overlap.score /
edge.overlap.curRange()) + ") -> ";
}
alnStr.erase(alnStr.size() - 4);
alnStr += " s: " + std::to_string(switches);
FastaRecord::Id readId = aln.front().overlap.curId;
Logger::get().debug() << "Aln " << _readSeqs.seqName(readId);
Logger::get().debug() << "\t" << alnStr;
}
}*/
Logger::get().debug() << "Total reads : " << allQueries.size();
Logger::get().debug() << "Read with aligned parts : " << numAligned;
Logger::get().debug() << "Aligned in one piece : " << alignedInFull;
Logger::get().info() << "Aligned read sequence: " << alignedLength << " / "
<< totalLength << " (" << (float)alignedLength / totalLength << ")";
readsOverlaps.overlapDivergenceStats();
}
//updates alignments with respect to the new graph
void ReadAligner::updateAlignments()
{
std::vector<GraphAlignment> newAlignments;
for (auto& aln : _readAlignments)
{
GraphAlignment curAlignment;
for (size_t i = 0; i < aln.size() - 1; ++i)
{
if (!_graph.hasEdge(aln[i].edge)) continue;
curAlignment.push_back(aln[i]);
if (!_graph.hasEdge(aln[i + 1].edge) ||
aln[i].edge->nodeRight != aln[i + 1].edge->nodeLeft)
{
newAlignments.push_back(curAlignment);
curAlignment.clear();
}
}
if (_graph.hasEdge(aln.back().edge)) curAlignment.push_back(aln.back());
if (!curAlignment.empty()) newAlignments.push_back(curAlignment);
}
_readAlignments = newAlignments;
}
<commit_msg>more accurate read alignment chaining<commit_after>//(c) 2016 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)
#include "read_aligner.h"
#include "../common/parallel.h"
#include <cmath>
#include <iomanip>
namespace
{
struct Chain
{
Chain(): score(0) {}
std::vector<const EdgeAlignment*> aln;
int32_t score;
};
}
//Give alignments to separate edges for a single read, merges them
//into non-overlapping chains (could be more than one chain per read
//in case of chimera) with maximum score
std::vector<GraphAlignment>
ReadAligner::chainReadAlignments(const SequenceContainer& edgeSeqs,
const std::vector<EdgeAlignment>& ovlps) const
{
static const int32_t MAX_JUMP = Config::get("maximum_jump");
static const int32_t MAX_SEP = Config::get("max_separation");
static const int32_t MAX_READ_OVLP = 50;
std::list<Chain> activeChains;
for (auto& edgeAlignment : ovlps)
{
std::list<Chain> newChains;
int32_t maxScore = 0;
Chain* maxChain = nullptr;
for (auto& chain : activeChains)
{
const OverlapRange& nextOvlp = edgeAlignment.overlap;
const OverlapRange& prevOvlp = chain.aln.back()->overlap;
int32_t readDiff = nextOvlp.curBegin - prevOvlp.curEnd;
int32_t graphLeftDiff = nextOvlp.extBegin;
int32_t graphRightDiff = prevOvlp.extLen - prevOvlp.extEnd;
if (chain.aln.back()->edge->nodeRight == edgeAlignment.edge->nodeLeft &&
MAX_JUMP > readDiff && readDiff > -MAX_READ_OVLP &&
graphLeftDiff < MAX_SEP && graphRightDiff < MAX_SEP)
{
//int32_t jumpDiv = abs(readDiff - graphDiff);
//int32_t gapCost = jumpDiv ? std::log2(jumpDiv) : 0;
int32_t gapCost = (graphLeftDiff + graphRightDiff) / 10;
int32_t score = chain.score + nextOvlp.score - gapCost;
if (score > maxScore)
{
maxScore = score;
maxChain = &chain;
}
}
}
if (maxChain)
{
newChains.push_back(*maxChain);
maxChain->aln.push_back(&edgeAlignment);
maxChain->score = maxScore;
}
activeChains.splice(activeChains.end(), newChains);
activeChains.push_back(Chain());
activeChains.back().aln.push_back(&edgeAlignment);
activeChains.back().score = edgeAlignment.overlap.score;
}
//greedily choose non-intersecting set of alignments
std::vector<GraphAlignment> acceptedAlignments;
std::vector<Chain> sortedChains(activeChains.begin(), activeChains.end());
std::sort(sortedChains.begin(), sortedChains.end(),
[](const Chain& c1, const Chain& c2)
{return c1.score > c2.score;});
for (auto& chain : sortedChains)
{
int32_t alnLen = chain.aln.back()->overlap.curEnd -
chain.aln.front()->overlap.curBegin;
if (alnLen < Parameters::get().minimumOverlap) continue;
//check if it overlaps with other accepted chains
bool overlaps = false;
for (auto& existAln : acceptedAlignments)
{
int32_t existStart = existAln.front().overlap.curBegin;
int32_t existEnd = existAln.back().overlap.curEnd;
int32_t curStart = chain.aln.front()->overlap.curBegin;
int32_t curEnd = chain.aln.back()->overlap.curEnd;
int32_t overlapRate = std::min(curEnd, existEnd) -
std::max(curStart, existStart);
if (overlapRate > (int)Config::get("max_separation")) overlaps = true;
}
if (!overlaps)
{
acceptedAlignments.emplace_back();
for (auto& aln : chain.aln) acceptedAlignments.back().push_back(*aln);
}
}
return acceptedAlignments;
}
void ReadAligner::alignReads()
{
static const int MIN_EDGE_OVLP = (int)Config::get("max_separation");
static const int EDGE_FLANK = 100;
//create database
std::unordered_map<FastaRecord::Id,
std::pair<GraphEdge*, SequenceSegment>> idToSegment;
SequenceContainer pathsContainer;
for (auto& edge : _graph.iterEdges())
{
if (!edge->edgeId.strand()) continue;
//add each edge sequence variant to the database
for (auto& segment : edge->seqSegments)
{
size_t len = segment.end - segment.start;
auto sequence = _asmSeqs.getSeq(segment.seqId)
.substr(segment.start, len);
auto& newRec = pathsContainer.addSequence(sequence, "");
idToSegment[newRec.id] = {edge, segment};
idToSegment[newRec.id.rc()] = {_graph.complementEdge(edge),
segment.complement()};
}
}
pathsContainer.buildPositionIndex();
//index it and align reads
VertexIndex pathsIndex(pathsContainer,
(int)Config::get("read_align_kmer_sample"));
pathsIndex.countKmers(/*min freq*/ 1, /* genome size*/ 0);
pathsIndex.setRepeatCutoff(/*min freq*/ 1);
pathsIndex.buildIndex(/*min freq*/ 1);
OverlapDetector readsOverlapper(pathsContainer, pathsIndex,
(int)Config::get("maximum_jump"),
MIN_EDGE_OVLP - EDGE_FLANK,
/*no overhang*/ 0, /*no max ovlp count*/ 0,
/*keep alignment*/ false, /*only max*/ false,
(float)Config::get("read_align_ovlp_ident"),
/* bad end adjust*/ 0.0f);
OverlapContainer readsOverlaps(readsOverlapper, _readSeqs);
std::vector<FastaRecord::Id> allQueries;
int64_t totalLength = 0;
for (auto& read : _readSeqs.iterSeqs())
{
if (!read.id.strand()) continue;
if (read.sequence.length() > (size_t)Parameters::get().minimumOverlap)
{
totalLength += read.sequence.length();
allQueries.push_back(read.id);
}
}
std::mutex indexMutex;
int numAligned = 0;
int alignedInFull = 0;
int64_t alignedLength = 0;
std::function<void(const FastaRecord::Id&)> alignRead =
[this, &indexMutex, &numAligned, &readsOverlaps,
&idToSegment, &pathsContainer, &alignedLength, &alignedInFull]
(const FastaRecord::Id& seqId)
{
auto overlaps = readsOverlaps.quickSeqOverlaps(seqId);
std::vector<EdgeAlignment> alignments;
for (auto& ovlp : overlaps)
{
//because edges might be as short as max_separation,
//we set minimum alignment threshold to a bit shorter value.
//However, apply the actual threshold for longer edges now.
if (ovlp.extLen < MIN_EDGE_OVLP + EDGE_FLANK ||
std::min(ovlp.curRange(), ovlp.extRange()) > MIN_EDGE_OVLP)
{
alignments.push_back({ovlp, idToSegment[ovlp.extId].first,
idToSegment[ovlp.extId].second});
}
}
std::sort(alignments.begin(), alignments.end(),
[](const EdgeAlignment& e1, const EdgeAlignment& e2)
{return e1.overlap.curBegin < e2.overlap.curBegin;});
auto readChains = this->chainReadAlignments(pathsContainer, alignments);
std::vector<GraphAlignment> complChains(readChains);
for (auto& chain : complChains)
{
for (auto& aln : chain)
{
aln.edge = _graph.complementEdge(aln.edge);
aln.segment = aln.segment.complement();
aln.overlap = aln.overlap.complement();
}
std::reverse(chain.begin(), chain.end());
}
if (readChains.empty()) return;
/////synchronized part
indexMutex.lock();
++numAligned;
if (readChains.size() == 1) ++alignedInFull;
for (auto& chain : readChains)
{
_readAlignments.push_back(chain);
alignedLength += chain.back().overlap.curEnd -
chain.front().overlap.curBegin;
}
for (auto& chain : complChains)
{
_readAlignments.push_back(chain);
}
indexMutex.unlock();
/////
};
processInParallel(allQueries, alignRead,
Parameters::get().numThreads, true);
/*for (auto& aln : _readAlignments)
{
if (aln.size() > 1)
{
std::string alnStr;
int switches = 0;
for (size_t i = 0; i < aln.size() - 1; ++i)
{
if (aln[i].segment.end != aln[i + 1].segment.start) ++switches;
}
for (auto& edge : aln)
{
alnStr += std::to_string(edge.edge->edgeId.signedId()) + " ("
+ std::to_string(edge.overlap.curRange()) + " "
+ std::to_string(edge.overlap.score) + " "
+ std::to_string((float)edge.overlap.score /
edge.overlap.curRange()) + ") -> ";
}
alnStr.erase(alnStr.size() - 4);
alnStr += " s: " + std::to_string(switches);
FastaRecord::Id readId = aln.front().overlap.curId;
Logger::get().debug() << "Aln " << _readSeqs.seqName(readId);
Logger::get().debug() << "\t" << alnStr;
}
}*/
Logger::get().debug() << "Total reads : " << allQueries.size();
Logger::get().debug() << "Read with aligned parts : " << numAligned;
Logger::get().debug() << "Aligned in one piece : " << alignedInFull;
Logger::get().info() << "Aligned read sequence: " << alignedLength << " / "
<< totalLength << " (" << (float)alignedLength / totalLength << ")";
readsOverlaps.overlapDivergenceStats();
}
//updates alignments with respect to the new graph
void ReadAligner::updateAlignments()
{
std::vector<GraphAlignment> newAlignments;
for (auto& aln : _readAlignments)
{
GraphAlignment curAlignment;
for (size_t i = 0; i < aln.size() - 1; ++i)
{
if (!_graph.hasEdge(aln[i].edge)) continue;
curAlignment.push_back(aln[i]);
if (!_graph.hasEdge(aln[i + 1].edge) ||
aln[i].edge->nodeRight != aln[i + 1].edge->nodeLeft)
{
newAlignments.push_back(curAlignment);
curAlignment.clear();
}
}
if (_graph.hasEdge(aln.back().edge)) curAlignment.push_back(aln.back());
if (!curAlignment.empty()) newAlignments.push_back(curAlignment);
}
_readAlignments = newAlignments;
}
<|endoftext|> |
<commit_before>#include "obj_loader.hpp"
#include <fstream>
#include <sstream>
namespace sample_util
{
static bool begins_with(const std::string& input, const std::string& search_string)
{
if (input.size() < search_string.size())
{
return false;
}
for (size_t i = 0; i < search_string.size(); ++i)
{
if (input[i] != search_string[i])
{
return false;
}
}
return true;
}
template <typename vertex_type, typename output_iterator>
static void copy_face_elements(const std::vector<vertex_type>& source, const std::vector<size_t>& indices, output_iterator output)
{
for (size_t i = 0; i < indices.size(); ++i)
{
if (indices[i] < 1 || indices[i] > source.size())
{
std::ostringstream err;
err << "index " << i << "(" << indices[i] << ") is out of range, must be in [0, " << source.size() << "].";
throw std::runtime_error(err.str());
}
*output = source[indices[i] - 1];
++output;
}
}
template <typename vertex_type, size_t element_count>
static void compute_bounds(const std::vector< std::array<vertex_type, element_count> >& elements,
std::array<vertex_type, element_count>& min_bound, std::array<vertex_type, element_count>& max_bound)
{
min_bound.assign(std::numeric_limits<vertex_type>::max());
max_bound.assign(std::numeric_limits<vertex_type>::min());
for (size_t i = 0; i < elements.size(); ++i)
{
for (size_t j = 0; j < element_count; ++j)
{
min_bound[j] = std::min(min_bound[j], elements[i][j]);
max_bound[j] = std::max(max_bound[j], elements[i][j]);
}
}
}
template <typename element_type>
void read_attribute(std::istringstream& stream, element_type& element)
{
stream >> element;
}
template <typename element_type, size_t count>
void read_attribute(std::istringstream& stream, std::array<element_type, count>& arr, size_t seperator_size = 0)
{
for (size_t i = 0; i < count; ++i)
{
stream >> arr[i];
if (seperator_size > 0 && i + 1 < count)
{
char sep;
for (size_t j = 0; j < seperator_size; ++j)
{
stream >> sep;
}
}
}
}
model load_model_from_file(const std::string& path)
{
static const std::string vertex_identifier = "v";
static const std::string texcoord_identifier = "vt";
static const std::string normal_identifier = "vn";
static const std::string face_identifier = "f";
std::vector<float4> vertices;
std::vector<size_t> vertex_indicies;
std::vector<float3> texcoords;
std::vector<size_t> texcoord_indices;
std::vector<float3> normals;
std::vector<size_t> normal_indices;
std::ifstream input_stream(path);
if (!input_stream)
{
std::ostringstream err;
err << "error opening model file " << path << " for reading.";
throw std::runtime_error(err.str());
}
size_t line_count = 0;
std::string line, identifier;
while (std::getline(input_stream, line))
{
std::istringstream line_stream(line);
line_stream >> identifier;
if (identifier == vertex_identifier)
{
float4 vertex = { 0.0f, 0.0f, 0.0f, 1.0f };
read_attribute(line_stream, vertex);
vertices.push_back(vertex);
}
else if (identifier == texcoord_identifier)
{
float3 texcoord = { 0.0f, 0.0f, 0.0f };
read_attribute(line_stream, texcoord);
texcoords.push_back(texcoord);
}
else if (identifier == normal_identifier)
{
float3 normal = { 0.0f, 0.0f, 0.0f };
read_attribute(line_stream, normal);
normals.push_back(normal);
}
else if (identifier == face_identifier)
{
for (size_t i = 0; i < 3; ++i)
{
std::array<size_t, 3> face = { 0, 0, 0 };
read_attribute(line_stream, face, 1);
vertex_indicies.push_back(face[0]);
texcoord_indices.push_back(face[1]);
normal_indices.push_back(face[2]);
}
}
else
{
// unsupported identifier
}
line_count++;
}
model result;
copy_face_elements(vertices, vertex_indicies, std::back_inserter(result.vertices));
copy_face_elements(texcoords, texcoord_indices, std::back_inserter(result.texcoords));
copy_face_elements(normals, normal_indices, std::back_inserter(result.normals));
return result;
}
static const std::string ambient_identifier = "Ka";
static const std::string diffuse_identifier = "Kd";
static const std::string specular_color_identifier = "Ks";
static const std::string specular_coefficient_identifier = "Ns";
static const std::string disolved_identifier = "d";
static const std::string transparency_identifier = "Tr";
static const std::string ambient_map_identifier = "map_Ka";
static const std::string diffuse_map_identifier = "map_Kd";
static const std::string specular_color_map_identifier = "map_Ks";
static const std::string alpha_map_identifier = "map_d";
static const std::string bump_identifier = "bump";
static const std::string bump_map_identifier = "map_bump";
static const std::string displacement_map_identifier = "disp";
material load_material_from_file(const std::string& path)
{
material result;
std::ifstream input_stream(path);
if (!input_stream)
{
std::ostringstream err;
err << "error opening model file " << path << " for reading.";
throw std::runtime_error(err.str());
}
size_t line_count = 0;
std::string line, identifier;
while (std::getline(input_stream, line))
{
std::istringstream line_stream(line);
line_stream >> identifier;
if (identifier == ambient_identifier)
{
read_attribute(line_stream, result.ambient_color);
}
else if (identifier == diffuse_identifier)
{
read_attribute(line_stream, result.diffuse_color);
}
else if (identifier == specular_color_identifier)
{
read_attribute(line_stream, result.specular_color);
}
else if (identifier == specular_coefficient_identifier)
{
read_attribute(line_stream, result.specular_coefficient);
}
else if (identifier == disolved_identifier || identifier == transparency_identifier)
{
read_attribute(line_stream, result.transparency);
}
else if (identifier == ambient_map_identifier)
{
read_attribute(line_stream, result.ambient_map_path);
}
else if (identifier == diffuse_map_identifier)
{
read_attribute(line_stream, result.diffuse_map_path);
}
else if (identifier == alpha_map_identifier)
{
read_attribute(line_stream, result.alpha_map_path);
}
else if (identifier == bump_identifier || identifier == bump_map_identifier)
{
read_attribute(line_stream, result.bump_map_path);
}
else if (identifier == displacement_map_identifier)
{
read_attribute(line_stream, result.displacement_map_path);
}
else
{
// unsupported identifier
}
}
return result;
}
}
<commit_msg>Removed unreferenced function and moved constants out of the global scope.<commit_after>#include "obj_loader.hpp"
#include <fstream>
#include <sstream>
namespace sample_util
{
template <typename vertex_type, typename output_iterator>
static void copy_face_elements(const std::vector<vertex_type>& source, const std::vector<size_t>& indices, output_iterator output)
{
for (size_t i = 0; i < indices.size(); ++i)
{
if (indices[i] < 1 || indices[i] > source.size())
{
std::ostringstream err;
err << "index " << i << "(" << indices[i] << ") is out of range, must be in [0, " << source.size() << "].";
throw std::runtime_error(err.str());
}
*output = source[indices[i] - 1];
++output;
}
}
template <typename vertex_type, size_t element_count>
static void compute_bounds(const std::vector< std::array<vertex_type, element_count> >& elements,
std::array<vertex_type, element_count>& min_bound, std::array<vertex_type, element_count>& max_bound)
{
min_bound.assign(std::numeric_limits<vertex_type>::max());
max_bound.assign(std::numeric_limits<vertex_type>::min());
for (size_t i = 0; i < elements.size(); ++i)
{
for (size_t j = 0; j < element_count; ++j)
{
min_bound[j] = std::min(min_bound[j], elements[i][j]);
max_bound[j] = std::max(max_bound[j], elements[i][j]);
}
}
}
template <typename element_type>
void read_attribute(std::istringstream& stream, element_type& element)
{
stream >> element;
}
template <typename element_type, size_t count>
void read_attribute(std::istringstream& stream, std::array<element_type, count>& arr, size_t seperator_size = 0)
{
for (size_t i = 0; i < count; ++i)
{
stream >> arr[i];
if (seperator_size > 0 && i + 1 < count)
{
char sep;
for (size_t j = 0; j < seperator_size; ++j)
{
stream >> sep;
}
}
}
}
model load_model_from_file(const std::string& path)
{
static const std::string vertex_identifier = "v";
static const std::string texcoord_identifier = "vt";
static const std::string normal_identifier = "vn";
static const std::string face_identifier = "f";
std::vector<float4> vertices;
std::vector<size_t> vertex_indicies;
std::vector<float3> texcoords;
std::vector<size_t> texcoord_indices;
std::vector<float3> normals;
std::vector<size_t> normal_indices;
std::ifstream input_stream(path);
if (!input_stream)
{
std::ostringstream err;
err << "error opening model file " << path << " for reading.";
throw std::runtime_error(err.str());
}
size_t line_count = 0;
std::string line, identifier;
while (std::getline(input_stream, line))
{
std::istringstream line_stream(line);
line_stream >> identifier;
if (identifier == vertex_identifier)
{
float4 vertex = { 0.0f, 0.0f, 0.0f, 1.0f };
read_attribute(line_stream, vertex);
vertices.push_back(vertex);
}
else if (identifier == texcoord_identifier)
{
float3 texcoord = { 0.0f, 0.0f, 0.0f };
read_attribute(line_stream, texcoord);
texcoords.push_back(texcoord);
}
else if (identifier == normal_identifier)
{
float3 normal = { 0.0f, 0.0f, 0.0f };
read_attribute(line_stream, normal);
normals.push_back(normal);
}
else if (identifier == face_identifier)
{
for (size_t i = 0; i < 3; ++i)
{
std::array<size_t, 3> face = { 0, 0, 0 };
read_attribute(line_stream, face, 1);
vertex_indicies.push_back(face[0]);
texcoord_indices.push_back(face[1]);
normal_indices.push_back(face[2]);
}
}
else
{
// unsupported identifier
}
line_count++;
}
model result;
copy_face_elements(vertices, vertex_indicies, std::back_inserter(result.vertices));
copy_face_elements(texcoords, texcoord_indices, std::back_inserter(result.texcoords));
copy_face_elements(normals, normal_indices, std::back_inserter(result.normals));
return result;
}
material load_material_from_file(const std::string& path)
{
static const std::string ambient_identifier = "Ka";
static const std::string diffuse_identifier = "Kd";
static const std::string specular_color_identifier = "Ks";
static const std::string specular_coefficient_identifier = "Ns";
static const std::string disolved_identifier = "d";
static const std::string transparency_identifier = "Tr";
static const std::string ambient_map_identifier = "map_Ka";
static const std::string diffuse_map_identifier = "map_Kd";
static const std::string specular_color_map_identifier = "map_Ks";
static const std::string alpha_map_identifier = "map_d";
static const std::string bump_identifier = "bump";
static const std::string bump_map_identifier = "map_bump";
static const std::string displacement_map_identifier = "disp";
material result;
std::ifstream input_stream(path);
if (!input_stream)
{
std::ostringstream err;
err << "error opening model file " << path << " for reading.";
throw std::runtime_error(err.str());
}
size_t line_count = 0;
std::string line, identifier;
while (std::getline(input_stream, line))
{
std::istringstream line_stream(line);
line_stream >> identifier;
if (identifier == ambient_identifier)
{
read_attribute(line_stream, result.ambient_color);
}
else if (identifier == diffuse_identifier)
{
read_attribute(line_stream, result.diffuse_color);
}
else if (identifier == specular_color_identifier)
{
read_attribute(line_stream, result.specular_color);
}
else if (identifier == specular_coefficient_identifier)
{
read_attribute(line_stream, result.specular_coefficient);
}
else if (identifier == disolved_identifier || identifier == transparency_identifier)
{
read_attribute(line_stream, result.transparency);
}
else if (identifier == ambient_map_identifier)
{
read_attribute(line_stream, result.ambient_map_path);
}
else if (identifier == diffuse_map_identifier)
{
read_attribute(line_stream, result.diffuse_map_path);
}
else if (identifier == alpha_map_identifier)
{
read_attribute(line_stream, result.alpha_map_path);
}
else if (identifier == bump_identifier || identifier == bump_map_identifier)
{
read_attribute(line_stream, result.bump_map_path);
}
else if (identifier == displacement_map_identifier)
{
read_attribute(line_stream, result.displacement_map_path);
}
else
{
// unsupported identifier
}
}
return result;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 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 "ppapi/cpp/input_event.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"
#include "ppapi/cpp/point.h"
#include "ppapi/cpp/var.h"
namespace pp {
namespace {
template <> const char* interface_name<PPB_InputEvent>() {
return PPB_INPUT_EVENT_INTERFACE;
}
template <> const char* interface_name<PPB_KeyboardInputEvent>() {
return PPB_KEYBOARD_INPUT_EVENT_INTERFACE;
}
template <> const char* interface_name<PPB_MouseInputEvent>() {
return PPB_MOUSE_INPUT_EVENT_INTERFACE;
}
template <> const char* interface_name<PPB_WheelInputEvent>() {
return PPB_WHEEL_INPUT_EVENT_INTERFACE;
}
} // namespace
// InputEvent ------------------------------------------------------------------
InputEvent::InputEvent() : Resource() {
}
InputEvent::InputEvent(PP_Resource input_event_resource) : Resource() {
// Type check the input event before setting it.
if (!has_interface<PPB_InputEvent>())
return;
if (get_interface<PPB_InputEvent>()->IsInputEvent(input_event_resource)) {
Module::Get()->core()->AddRefResource(input_event_resource);
PassRefFromConstructor(input_event_resource);
}
}
InputEvent::~InputEvent() {
}
PP_InputEvent_Type InputEvent::GetType() const {
if (!has_interface<PPB_InputEvent>())
return PP_INPUTEVENT_TYPE_UNDEFINED;
return get_interface<PPB_InputEvent>()->GetType(pp_resource());
}
PP_TimeTicks InputEvent::GetTimeStamp() const {
if (!has_interface<PPB_InputEvent>())
return 0.0f;
return get_interface<PPB_InputEvent>()->GetTimeStamp(pp_resource());
}
uint32_t InputEvent::GetModifiers() const {
if (!has_interface<PPB_InputEvent>())
return 0;
return get_interface<PPB_InputEvent>()->GetModifiers(pp_resource());
}
// MouseInputEvent -------------------------------------------------------------
MouseInputEvent::MouseInputEvent() : InputEvent() {
}
MouseInputEvent::MouseInputEvent(const InputEvent& event) : InputEvent() {
// Type check the input event before setting it.
if (!has_interface<PPB_MouseInputEvent>())
return;
if (get_interface<PPB_MouseInputEvent>()->IsMouseInputEvent(
event.pp_resource())) {
Module::Get()->core()->AddRefResource(event.pp_resource());
PassRefFromConstructor(event.pp_resource());
}
}
PP_InputEvent_MouseButton MouseInputEvent::GetMouseButton() const {
if (!has_interface<PPB_MouseInputEvent>())
return PP_INPUTEVENT_MOUSEBUTTON_NONE;
return get_interface<PPB_MouseInputEvent>()->GetMouseButton(pp_resource());
}
Point MouseInputEvent::GetMousePosition() const {
if (!has_interface<PPB_MouseInputEvent>())
return Point();
return get_interface<PPB_MouseInputEvent>()->GetMousePosition(pp_resource());
}
int32_t MouseInputEvent::GetMouseClickCount() const {
if (!has_interface<PPB_MouseInputEvent>())
return 0;
return get_interface<PPB_MouseInputEvent>()->GetMouseClickCount(
pp_resource());
}
// WheelInputEvent -------------------------------------------------------------
WheelInputEvent::WheelInputEvent() : InputEvent() {
}
WheelInputEvent::WheelInputEvent(const InputEvent& event) : InputEvent() {
// Type check the input event before setting it.
if (!has_interface<PPB_WheelInputEvent>())
return;
if (get_interface<PPB_WheelInputEvent>()->IsWheelInputEvent(
event.pp_resource())) {
Module::Get()->core()->AddRefResource(event.pp_resource());
PassRefFromConstructor(event.pp_resource());
}
}
FloatPoint WheelInputEvent::GetWheelDelta() const {
if (!has_interface<PPB_WheelInputEvent>())
return FloatPoint();
return get_interface<PPB_WheelInputEvent>()->GetWheelDelta(pp_resource());
}
FloatPoint WheelInputEvent::GetWheelTicks() const {
if (!has_interface<PPB_WheelInputEvent>())
return FloatPoint();
return get_interface<PPB_WheelInputEvent>()->GetWheelTicks(pp_resource());
}
bool WheelInputEvent::GetScrollByPage() const {
if (!has_interface<PPB_WheelInputEvent>())
return false;
return PP_ToBool(
get_interface<PPB_WheelInputEvent>()->GetScrollByPage(pp_resource()));
}
// KeyboardInputEvent ----------------------------------------------------------
KeyboardInputEvent::KeyboardInputEvent() : InputEvent() {
}
KeyboardInputEvent::KeyboardInputEvent(const InputEvent& event) : InputEvent() {
// Type check the input event before setting it.
if (!has_interface<PPB_KeyboardInputEvent>())
return;
if (get_interface<PPB_KeyboardInputEvent>()->IsKeyboardInputEvent(
event.pp_resource())) {
Module::Get()->core()->AddRefResource(event.pp_resource());
PassRefFromConstructor(event.pp_resource());
}
}
uint32_t KeyboardInputEvent::GetKeyCode() const {
if (!has_interface<PPB_KeyboardInputEvent>())
return 0;
return get_interface<PPB_KeyboardInputEvent>()->GetKeyCode(pp_resource());
}
Var KeyboardInputEvent::GetCharacterText() const {
if (!has_interface<PPB_KeyboardInputEvent>())
return PP_INPUTEVENT_TYPE_UNDEFINED;
return Var(Var::PassRef(),
get_interface<PPB_KeyboardInputEvent>()->GetCharacterText(
pp_resource()));
}
} // namespace pp
<commit_msg>Fix return statement in ppapi/cpp/input_event.cc<commit_after>// Copyright (c) 2011 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 "ppapi/cpp/input_event.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"
#include "ppapi/cpp/point.h"
#include "ppapi/cpp/var.h"
namespace pp {
namespace {
template <> const char* interface_name<PPB_InputEvent>() {
return PPB_INPUT_EVENT_INTERFACE;
}
template <> const char* interface_name<PPB_KeyboardInputEvent>() {
return PPB_KEYBOARD_INPUT_EVENT_INTERFACE;
}
template <> const char* interface_name<PPB_MouseInputEvent>() {
return PPB_MOUSE_INPUT_EVENT_INTERFACE;
}
template <> const char* interface_name<PPB_WheelInputEvent>() {
return PPB_WHEEL_INPUT_EVENT_INTERFACE;
}
} // namespace
// InputEvent ------------------------------------------------------------------
InputEvent::InputEvent() : Resource() {
}
InputEvent::InputEvent(PP_Resource input_event_resource) : Resource() {
// Type check the input event before setting it.
if (!has_interface<PPB_InputEvent>())
return;
if (get_interface<PPB_InputEvent>()->IsInputEvent(input_event_resource)) {
Module::Get()->core()->AddRefResource(input_event_resource);
PassRefFromConstructor(input_event_resource);
}
}
InputEvent::~InputEvent() {
}
PP_InputEvent_Type InputEvent::GetType() const {
if (!has_interface<PPB_InputEvent>())
return PP_INPUTEVENT_TYPE_UNDEFINED;
return get_interface<PPB_InputEvent>()->GetType(pp_resource());
}
PP_TimeTicks InputEvent::GetTimeStamp() const {
if (!has_interface<PPB_InputEvent>())
return 0.0f;
return get_interface<PPB_InputEvent>()->GetTimeStamp(pp_resource());
}
uint32_t InputEvent::GetModifiers() const {
if (!has_interface<PPB_InputEvent>())
return 0;
return get_interface<PPB_InputEvent>()->GetModifiers(pp_resource());
}
// MouseInputEvent -------------------------------------------------------------
MouseInputEvent::MouseInputEvent() : InputEvent() {
}
MouseInputEvent::MouseInputEvent(const InputEvent& event) : InputEvent() {
// Type check the input event before setting it.
if (!has_interface<PPB_MouseInputEvent>())
return;
if (get_interface<PPB_MouseInputEvent>()->IsMouseInputEvent(
event.pp_resource())) {
Module::Get()->core()->AddRefResource(event.pp_resource());
PassRefFromConstructor(event.pp_resource());
}
}
PP_InputEvent_MouseButton MouseInputEvent::GetMouseButton() const {
if (!has_interface<PPB_MouseInputEvent>())
return PP_INPUTEVENT_MOUSEBUTTON_NONE;
return get_interface<PPB_MouseInputEvent>()->GetMouseButton(pp_resource());
}
Point MouseInputEvent::GetMousePosition() const {
if (!has_interface<PPB_MouseInputEvent>())
return Point();
return get_interface<PPB_MouseInputEvent>()->GetMousePosition(pp_resource());
}
int32_t MouseInputEvent::GetMouseClickCount() const {
if (!has_interface<PPB_MouseInputEvent>())
return 0;
return get_interface<PPB_MouseInputEvent>()->GetMouseClickCount(
pp_resource());
}
// WheelInputEvent -------------------------------------------------------------
WheelInputEvent::WheelInputEvent() : InputEvent() {
}
WheelInputEvent::WheelInputEvent(const InputEvent& event) : InputEvent() {
// Type check the input event before setting it.
if (!has_interface<PPB_WheelInputEvent>())
return;
if (get_interface<PPB_WheelInputEvent>()->IsWheelInputEvent(
event.pp_resource())) {
Module::Get()->core()->AddRefResource(event.pp_resource());
PassRefFromConstructor(event.pp_resource());
}
}
FloatPoint WheelInputEvent::GetWheelDelta() const {
if (!has_interface<PPB_WheelInputEvent>())
return FloatPoint();
return get_interface<PPB_WheelInputEvent>()->GetWheelDelta(pp_resource());
}
FloatPoint WheelInputEvent::GetWheelTicks() const {
if (!has_interface<PPB_WheelInputEvent>())
return FloatPoint();
return get_interface<PPB_WheelInputEvent>()->GetWheelTicks(pp_resource());
}
bool WheelInputEvent::GetScrollByPage() const {
if (!has_interface<PPB_WheelInputEvent>())
return false;
return PP_ToBool(
get_interface<PPB_WheelInputEvent>()->GetScrollByPage(pp_resource()));
}
// KeyboardInputEvent ----------------------------------------------------------
KeyboardInputEvent::KeyboardInputEvent() : InputEvent() {
}
KeyboardInputEvent::KeyboardInputEvent(const InputEvent& event) : InputEvent() {
// Type check the input event before setting it.
if (!has_interface<PPB_KeyboardInputEvent>())
return;
if (get_interface<PPB_KeyboardInputEvent>()->IsKeyboardInputEvent(
event.pp_resource())) {
Module::Get()->core()->AddRefResource(event.pp_resource());
PassRefFromConstructor(event.pp_resource());
}
}
uint32_t KeyboardInputEvent::GetKeyCode() const {
if (!has_interface<PPB_KeyboardInputEvent>())
return 0;
return get_interface<PPB_KeyboardInputEvent>()->GetKeyCode(pp_resource());
}
Var KeyboardInputEvent::GetCharacterText() const {
if (!has_interface<PPB_KeyboardInputEvent>())
return Var();
return Var(Var::PassRef(),
get_interface<PPB_KeyboardInputEvent>()->GetCharacterText(
pp_resource()));
}
} // namespace pp
<|endoftext|> |
<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.40
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "Simulation.h"
#include "GOMC_Config.h" //For version number
#if GOMC_LIB_MPI
#include <mpi.h>
#include "ParallelTemperingPreprocessor.h"
#endif
#ifdef GOMC_CUDA
#include "cuda.h"
#include <cuda_runtime_api.h>
#endif
#include <iostream>
#include <ctime>
//find and include appropriate files for getHostname
#ifdef _WIN32
#include <Winsock2.h>
#define HOSTNAME
#elif defined(__linux__) || defined(__apple__) || defined(__FreeBSD__)
#include <unistd.h>
#include <sys/sysinfo.h>
#include <sys/utsname.h>
#define HOSTNAME
#endif
namespace
{
std::ostream& PrintTime(std::ostream& stream);
std::ostream& PrintHostname(std::ostream& stream);
std::ostream& PrintVersion(std::ostream& stream);
void PrintSimulationHeader();
void PrintSimulationFooter();
void PrintDebugMode();
bool CheckAndPrintEnsemble();
uint ReadNum(char *argv);
}
void PrintHardwareInfo();
#ifdef GOMC_CUDA
void PrintGPUHardwareInfo();
#endif
int main(int argc, char *argv[])
{
#if GOMC_LIB_MPI
string inputFileStringMPI;
fstream inputFileReaderMPI;
MultiSim * multisim;
int worldSize;
int worldRank;
ParallelTemperingPreprocessor pt;
//std::streambuf * savedCOUT;
//CHECK IF ARGS/FILE PROVIDED IN CMD LINE
if (argc < 2) {
std::cout << "Error: Input parameter file (*.dat or *.conf) not specified on command line!\n";
exit(EXIT_FAILURE);
} else {
if(argc == 2) {
//FIRST PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[1];
} else {
//SECOND PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[2];
if(argv[1][0] == '+' && argv[1][1] == 'p') {
// placeholder
} else {
std::cout << "Error: Undefined command to set number of threads!\n";
std::cout << "Use +p# command to set number of threads.\n";
exit(EXIT_FAILURE);
}
}
//OPEN FILE
inputFileReaderMPI.open(inputFileStringMPI.c_str(), ios::in | ios::out);
//CHECK IF FILE IS OPENED...IF NOT OPENED EXCEPTION REASON FIRED
if (!inputFileReaderMPI.is_open()) {
std::cout << "Error: Cannot open/find " << inputFileStringMPI <<
" in the directory provided!\n";
exit(EXIT_FAILURE);
}
//CLOSE FILE TO NOW PASS TO SIMULATION
inputFileReaderMPI.close();
// Initialize the MPI environment
MPI_Init(NULL, NULL);
// Get the number of processes
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
// Get the rank of the process
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
std::string pathToReplicaDirectory;
if(pt.checkIfParallelTempering(inputFileStringMPI)){
pt.checkIfValid(inputFileStringMPI);
if(worldSize > pt.getNumberOfReplicas(inputFileStringMPI)){
std::cout << "You may not request more processes (" << worldSize
<< ") than there are replicas(" << pt.getNumberOfReplicas(inputFileStringMPI) << ")! Exiting!\n";
} else {
#if ENSEMBLE == GCMC
pathToReplicaDirectory = pt.setupReplicaDirectoriesAndRedirectSTDOUTToFile ( pt.getMultiSimFolderName(inputFileStringMPI).c_str(),
pt.getTemperature(inputFileStringMPI.c_str(), worldRank).c_str(),
pt.getChemicalPotential(inputFileStringMPI.c_str(), worldRank).c_str()
);
#else
pathToReplicaDirectory = pt.setupReplicaDirectoriesAndRedirectSTDOUTToFile ( pt.getMultiSimFolderName(inputFileStringMPI).c_str(),
pt.getTemperature(inputFileStringMPI.c_str(), worldRank).c_str()
);
#endif
multisim = new MultiSim(worldSize, worldRank, pathToReplicaDirectory);
}
}
}
#endif
#ifndef NDEBUG
PrintDebugMode();
#endif
PrintSimulationHeader();
PrintHardwareInfo();
#ifdef GOMC_CUDA
PrintGPUHardwareInfo();
#endif
//Only run if valid ensemble was detected.
if (CheckAndPrintEnsemble()) {
//FOLLOWING LINES ADDED TO OBTAIN INPUT PARAMETER FILE
string inputFileString;
fstream inputFileReader;
uint numThreads;
//CHECK IF ARGS/FILE PROVIDED IN CMD LINE
if (argc < 2) {
std::cout << "Error: Input parameter file (*.dat or *.conf) not specified on command line!\n";
exit(EXIT_FAILURE);
} else {
if(argc == 2) {
//FIRST PARAMETER WILL BE FILE NAME
inputFileString = argv[1];
numThreads = 1;
} else {
//SECOND PARAMETER WILL BE FILE NAME
inputFileString = argv[2];
if(argv[1][0] == '+' && argv[1][1] == 'p') {
numThreads = ReadNum(argv[1]);
} else {
std::cout << "Error: Undefined command to set number of threads!\n";
std::cout << "Use +p# command to set number of threads.\n";
exit(EXIT_FAILURE);
}
}
}
//SET NUMBER OF THREADS
#ifdef _OPENMP
omp_set_num_threads(numThreads);
printf("%-40s %-d \n", "Info: Number of threads", numThreads);
#else
printf("%-40s %-d \n", "Info: Number of threads", 1);
#endif
//OPEN FILE
inputFileReader.open(inputFileString.c_str(), ios::in | ios::out);
//CHECK IF FILE IS OPENED...IF NOT OPENED EXCEPTION REASON FIRED
if (!inputFileReader.is_open()) {
std::cout << "Error: Cannot open/find " << inputFileString <<
" in the directory provided!\n";
exit(EXIT_FAILURE);
}
//CLOSE FILE TO NOW PASS TO SIMULATION
inputFileReader.close();
//ONCE FILE FOUND PASS STRING TO SIMULATION CLASS TO READ AND
//HANDLE PDB|PSF FILE
#if GOMC_LIB_MPI
if(worldSize <= pt.getNumberOfReplicas(inputFileStringMPI)){
Simulation sim(inputFileString.c_str(), multisim);
sim.RunSimulation();
PrintSimulationFooter();
}
#else
Simulation sim(inputFileString.c_str());
sim.RunSimulation();
PrintSimulationFooter();
#endif
}
#if GOMC_LIB_MPI
delete multisim;
MPI_Finalize();
//std::cout.rdbuf(savedCOUT); //reset to standard output again
#endif
return 0;
}
namespace
{
void PrintSimulationHeader()
{
std::cout << PrintVersion << '\n'
<< "Info: Start Time: " << PrintTime
#ifdef HOSTNAME
<< "Info: Host Name: " << PrintHostname
#endif
<< "\n";
}
bool CheckAndPrintEnsemble()
{
bool healthy = true;
std::cout << "Info: GOMC COMPILED TO RUN ";
#if ENSEMBLE == NVT
std::cout << "CANONICAL (NVT)";
#elif ENSEMBLE == GEMC
std::cout << "GIBBS";
#elif ENSEMBLE == GCMC
std::cout << "GRAND CANONICAL";
#elif ENSEMBLE == NPT
std::cout << "ISOBARIC-ISOTHERMAL";
#else
std::cerr << "CRITICAL ERROR! Preprocessor value ENSEMBLE is "
<< "invalid or undefined." << std::endl
<< "Code will exit.";
healthy = false;
#endif
std::cout << " ENSEMBLE." << std::endl;
return healthy;
}
void PrintDebugMode()
{
std::cout << "################################################################################\n";
std::cout << "########################## RUNNING GOMC IN DEBUG MODE ##########################\n";
std::cout << "################################################################################\n";
}
void PrintSimulationFooter()
{
std::cout << PrintVersion << '\n'
<< "Info: Completed at: " << PrintTime
<< "Info: On hostname: " << PrintHostname
<< '\n';
}
std::ostream& PrintVersion(std::ostream& stream)
{
stream << "Info: GOMC Version " << GOMC_VERSION_MAJOR
<< '.' << GOMC_VERSION_MINOR;
return stream;
}
std::ostream& PrintTime(std::ostream& stream)
{
time_t timer;
time(&timer);
stream << asctime(localtime(&timer));
return stream;
}
std::ostream& PrintHostname(std::ostream& stream)
{
#ifdef HOSTNAME
#ifdef _WIN32
//setup WINSOCK
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 0), &wsaData);
#endif
const int maxNameLength = 80;
char hostname[maxNameLength];
gethostname(hostname, maxNameLength);
//gethostname does not guarantee null termination
hostname[maxNameLength - 1] = '\0';
stream << hostname;
#ifdef _WIN32
//teardown WINSOCK
WSACleanup();
#endif
#else
stream << "Info: Hostname Unavailable";
#endif
return stream;
}
uint ReadNum(char *argv)
{
uint thread = 0;
for(uint i = 2; argv[i] != 0; i++) {
thread = thread * 10 + (argv[i] - '0');
}
return thread;
}
}
void PrintHardwareInfo()
{
#ifdef __linux__
struct sysinfo mem;
const double megabyte = 1024 * 1024;
struct utsname name;
uname(&name);
printf("CPU information:\n");
std::cout << std::setprecision(1) << std::fixed;
std::cout << "Info: Total number of CPUs: " << get_nprocs() << std::endl;
std::cout << "Info: Total number of CPUs available: " << sysconf(_SC_NPROCESSORS_ONLN) << std::endl;
std::cout << "Info: Model name:" << std::flush;
if(system("awk -F: '/model name/ {print $2;exit}' /proc/cpuinfo") == -1)
std::cout << "Error: Couldn't retrieve CPU information" << std::endl;
std::cout << "Info: System name: " << name.sysname << std::endl;
std::cout << "Info: Release: " << name.release << std::endl;
std::cout << "Info: Version: " << name.version << std::endl;
std::cout << "Info: Kernel Architecture: " << name.machine << std::endl;
if(sysinfo(&mem) == 0) {
std::cout << "Info: Total Ram: " << mem.totalram / megabyte << "MB" << std::endl;
std::cout << "Info: Used Ram: " << mem.totalram / megabyte - mem.freeram / megabyte << "MB" << std::endl;
}
std::cout << "Info: Working in the current directory: " << get_current_dir_name();
std::cout << std::endl;
#endif
}
#ifdef GOMC_CUDA
void PrintGPUHardwareInfo()
{
int nDevices;
int fast = 0;
int fastIndex = 0;
cudaGetDeviceCount(&nDevices);
if(nDevices == 0) {
printf("There are no available device(s) that support CUDA\n");
exit(EXIT_FAILURE);
}
if(nDevices <= 4) {
printf("GPU information:\n");
for (int i = 0; i < nDevices; i++) {
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, i);
printf("Info: Device Number: %d\n", i);
printf("Info: Device name: %s\n", prop.name);
printf("Info: Memory Clock Rate (KHz): %d\n", prop.memoryClockRate);
printf("Info: Memory Bus Width (bits): %d\n", prop.memoryBusWidth);
printf("Info: Peak Memory Bandwidth (GB/s): %f\n",
2.0 * prop.memoryClockRate * (prop.memoryBusWidth / 8) / 1.0e6);
if( prop.memoryClockRate > fast) {
fast = prop.memoryClockRate;
fastIndex = i;
}
}
}
cudaSetDevice(fastIndex);
printf("Info: Using Device Number: %d\n", fastIndex);
}
#endif
<commit_msg>Delete multisim only if created<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.40
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "Simulation.h"
#include "GOMC_Config.h" //For version number
#if GOMC_LIB_MPI
#include <mpi.h>
#include "ParallelTemperingPreprocessor.h"
#endif
#ifdef GOMC_CUDA
#include "cuda.h"
#include <cuda_runtime_api.h>
#endif
#include <iostream>
#include <ctime>
//find and include appropriate files for getHostname
#ifdef _WIN32
#include <Winsock2.h>
#define HOSTNAME
#elif defined(__linux__) || defined(__apple__) || defined(__FreeBSD__)
#include <unistd.h>
#include <sys/sysinfo.h>
#include <sys/utsname.h>
#define HOSTNAME
#endif
namespace
{
std::ostream& PrintTime(std::ostream& stream);
std::ostream& PrintHostname(std::ostream& stream);
std::ostream& PrintVersion(std::ostream& stream);
void PrintSimulationHeader();
void PrintSimulationFooter();
void PrintDebugMode();
bool CheckAndPrintEnsemble();
uint ReadNum(char *argv);
}
void PrintHardwareInfo();
#ifdef GOMC_CUDA
void PrintGPUHardwareInfo();
#endif
int main(int argc, char *argv[])
{
#if GOMC_LIB_MPI
string inputFileStringMPI;
fstream inputFileReaderMPI;
MultiSim * multisim;
int worldSize;
int worldRank;
ParallelTemperingPreprocessor pt;
//std::streambuf * savedCOUT;
//CHECK IF ARGS/FILE PROVIDED IN CMD LINE
if (argc < 2) {
std::cout << "Error: Input parameter file (*.dat or *.conf) not specified on command line!\n";
exit(EXIT_FAILURE);
} else {
if(argc == 2) {
//FIRST PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[1];
} else {
//SECOND PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[2];
if(argv[1][0] == '+' && argv[1][1] == 'p') {
// placeholder
} else {
std::cout << "Error: Undefined command to set number of threads!\n";
std::cout << "Use +p# command to set number of threads.\n";
exit(EXIT_FAILURE);
}
}
//OPEN FILE
inputFileReaderMPI.open(inputFileStringMPI.c_str(), ios::in | ios::out);
//CHECK IF FILE IS OPENED...IF NOT OPENED EXCEPTION REASON FIRED
if (!inputFileReaderMPI.is_open()) {
std::cout << "Error: Cannot open/find " << inputFileStringMPI <<
" in the directory provided!\n";
exit(EXIT_FAILURE);
}
//CLOSE FILE TO NOW PASS TO SIMULATION
inputFileReaderMPI.close();
// Initialize the MPI environment
MPI_Init(NULL, NULL);
// Get the number of processes
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
// Get the rank of the process
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
std::string pathToReplicaDirectory;
if(pt.checkIfParallelTempering(inputFileStringMPI)){
pt.checkIfValid(inputFileStringMPI);
if(worldSize > pt.getNumberOfReplicas(inputFileStringMPI)){
std::cout << "You may not request more processes (" << worldSize
<< ") than there are replicas(" << pt.getNumberOfReplicas(inputFileStringMPI) << ")! Exiting!\n";
} else {
#if ENSEMBLE == GCMC
pathToReplicaDirectory = pt.setupReplicaDirectoriesAndRedirectSTDOUTToFile ( pt.getMultiSimFolderName(inputFileStringMPI).c_str(),
pt.getTemperature(inputFileStringMPI.c_str(), worldRank).c_str(),
pt.getChemicalPotential(inputFileStringMPI.c_str(), worldRank).c_str()
);
#else
pathToReplicaDirectory = pt.setupReplicaDirectoriesAndRedirectSTDOUTToFile ( pt.getMultiSimFolderName(inputFileStringMPI).c_str(),
pt.getTemperature(inputFileStringMPI.c_str(), worldRank).c_str()
);
#endif
multisim = new MultiSim(worldSize, worldRank, pathToReplicaDirectory);
}
}
}
#endif
#ifndef NDEBUG
PrintDebugMode();
#endif
PrintSimulationHeader();
PrintHardwareInfo();
#ifdef GOMC_CUDA
PrintGPUHardwareInfo();
#endif
//Only run if valid ensemble was detected.
if (CheckAndPrintEnsemble()) {
//FOLLOWING LINES ADDED TO OBTAIN INPUT PARAMETER FILE
string inputFileString;
fstream inputFileReader;
uint numThreads;
//CHECK IF ARGS/FILE PROVIDED IN CMD LINE
if (argc < 2) {
std::cout << "Error: Input parameter file (*.dat or *.conf) not specified on command line!\n";
exit(EXIT_FAILURE);
} else {
if(argc == 2) {
//FIRST PARAMETER WILL BE FILE NAME
inputFileString = argv[1];
numThreads = 1;
} else {
//SECOND PARAMETER WILL BE FILE NAME
inputFileString = argv[2];
if(argv[1][0] == '+' && argv[1][1] == 'p') {
numThreads = ReadNum(argv[1]);
} else {
std::cout << "Error: Undefined command to set number of threads!\n";
std::cout << "Use +p# command to set number of threads.\n";
exit(EXIT_FAILURE);
}
}
}
//SET NUMBER OF THREADS
#ifdef _OPENMP
omp_set_num_threads(numThreads);
printf("%-40s %-d \n", "Info: Number of threads", numThreads);
#else
printf("%-40s %-d \n", "Info: Number of threads", 1);
#endif
//OPEN FILE
inputFileReader.open(inputFileString.c_str(), ios::in | ios::out);
//CHECK IF FILE IS OPENED...IF NOT OPENED EXCEPTION REASON FIRED
if (!inputFileReader.is_open()) {
std::cout << "Error: Cannot open/find " << inputFileString <<
" in the directory provided!\n";
exit(EXIT_FAILURE);
}
//CLOSE FILE TO NOW PASS TO SIMULATION
inputFileReader.close();
//ONCE FILE FOUND PASS STRING TO SIMULATION CLASS TO READ AND
//HANDLE PDB|PSF FILE
#if GOMC_LIB_MPI
if(worldSize <= pt.getNumberOfReplicas(inputFileStringMPI)){
Simulation sim(inputFileString.c_str(), multisim);
sim.RunSimulation();
PrintSimulationFooter();
delete multisim;
}
#else
Simulation sim(inputFileString.c_str());
sim.RunSimulation();
PrintSimulationFooter();
#endif
}
#if GOMC_LIB_MPI
MPI_Finalize();
//std::cout.rdbuf(savedCOUT); //reset to standard output again
#endif
return 0;
}
namespace
{
void PrintSimulationHeader()
{
std::cout << PrintVersion << '\n'
<< "Info: Start Time: " << PrintTime
#ifdef HOSTNAME
<< "Info: Host Name: " << PrintHostname
#endif
<< "\n";
}
bool CheckAndPrintEnsemble()
{
bool healthy = true;
std::cout << "Info: GOMC COMPILED TO RUN ";
#if ENSEMBLE == NVT
std::cout << "CANONICAL (NVT)";
#elif ENSEMBLE == GEMC
std::cout << "GIBBS";
#elif ENSEMBLE == GCMC
std::cout << "GRAND CANONICAL";
#elif ENSEMBLE == NPT
std::cout << "ISOBARIC-ISOTHERMAL";
#else
std::cerr << "CRITICAL ERROR! Preprocessor value ENSEMBLE is "
<< "invalid or undefined." << std::endl
<< "Code will exit.";
healthy = false;
#endif
std::cout << " ENSEMBLE." << std::endl;
return healthy;
}
void PrintDebugMode()
{
std::cout << "################################################################################\n";
std::cout << "########################## RUNNING GOMC IN DEBUG MODE ##########################\n";
std::cout << "################################################################################\n";
}
void PrintSimulationFooter()
{
std::cout << PrintVersion << '\n'
<< "Info: Completed at: " << PrintTime
<< "Info: On hostname: " << PrintHostname
<< '\n';
}
std::ostream& PrintVersion(std::ostream& stream)
{
stream << "Info: GOMC Version " << GOMC_VERSION_MAJOR
<< '.' << GOMC_VERSION_MINOR;
return stream;
}
std::ostream& PrintTime(std::ostream& stream)
{
time_t timer;
time(&timer);
stream << asctime(localtime(&timer));
return stream;
}
std::ostream& PrintHostname(std::ostream& stream)
{
#ifdef HOSTNAME
#ifdef _WIN32
//setup WINSOCK
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 0), &wsaData);
#endif
const int maxNameLength = 80;
char hostname[maxNameLength];
gethostname(hostname, maxNameLength);
//gethostname does not guarantee null termination
hostname[maxNameLength - 1] = '\0';
stream << hostname;
#ifdef _WIN32
//teardown WINSOCK
WSACleanup();
#endif
#else
stream << "Info: Hostname Unavailable";
#endif
return stream;
}
uint ReadNum(char *argv)
{
uint thread = 0;
for(uint i = 2; argv[i] != 0; i++) {
thread = thread * 10 + (argv[i] - '0');
}
return thread;
}
}
void PrintHardwareInfo()
{
#ifdef __linux__
struct sysinfo mem;
const double megabyte = 1024 * 1024;
struct utsname name;
uname(&name);
printf("CPU information:\n");
std::cout << std::setprecision(1) << std::fixed;
std::cout << "Info: Total number of CPUs: " << get_nprocs() << std::endl;
std::cout << "Info: Total number of CPUs available: " << sysconf(_SC_NPROCESSORS_ONLN) << std::endl;
std::cout << "Info: Model name:" << std::flush;
if(system("awk -F: '/model name/ {print $2;exit}' /proc/cpuinfo") == -1)
std::cout << "Error: Couldn't retrieve CPU information" << std::endl;
std::cout << "Info: System name: " << name.sysname << std::endl;
std::cout << "Info: Release: " << name.release << std::endl;
std::cout << "Info: Version: " << name.version << std::endl;
std::cout << "Info: Kernel Architecture: " << name.machine << std::endl;
if(sysinfo(&mem) == 0) {
std::cout << "Info: Total Ram: " << mem.totalram / megabyte << "MB" << std::endl;
std::cout << "Info: Used Ram: " << mem.totalram / megabyte - mem.freeram / megabyte << "MB" << std::endl;
}
std::cout << "Info: Working in the current directory: " << get_current_dir_name();
std::cout << std::endl;
#endif
}
#ifdef GOMC_CUDA
void PrintGPUHardwareInfo()
{
int nDevices;
int fast = 0;
int fastIndex = 0;
cudaGetDeviceCount(&nDevices);
if(nDevices == 0) {
printf("There are no available device(s) that support CUDA\n");
exit(EXIT_FAILURE);
}
if(nDevices <= 4) {
printf("GPU information:\n");
for (int i = 0; i < nDevices; i++) {
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, i);
printf("Info: Device Number: %d\n", i);
printf("Info: Device name: %s\n", prop.name);
printf("Info: Memory Clock Rate (KHz): %d\n", prop.memoryClockRate);
printf("Info: Memory Bus Width (bits): %d\n", prop.memoryBusWidth);
printf("Info: Peak Memory Bandwidth (GB/s): %f\n",
2.0 * prop.memoryClockRate * (prop.memoryBusWidth / 8) / 1.0e6);
if( prop.memoryClockRate > fast) {
fast = prop.memoryClockRate;
fastIndex = i;
}
}
}
cudaSetDevice(fastIndex);
printf("Info: Using Device Number: %d\n", fastIndex);
}
#endif
<|endoftext|> |
<commit_before>#include "Version.h"
#include "System/Config.h"
#include "System/Events/EventLoop.h"
#include "System/IO/IOProcessor.h"
#include "Framework/Storage/StorageEnvironment.h"
#ifdef DEBUG
#define VERSION_FMT_STRING "ScalienDB v" VERSION_STRING " (DEBUG build date " __DATE__ " " __TIME__ ")"
#else
#define VERSION_FMT_STRING "ScalienDB v" VERSION_STRING
#endif
void InitLog();
int main()
{
StartClock();
IOProcessor::Init(configFile.GetIntValue("io.maxfd", 1024), true);
Log_SetTarget(LOG_TARGET_STDOUT);
Log_SetTrace(false);
Log_SetTimestamping(true);
EventLoop::Init();
StorageEnvironment env;
Buffer envPath;
envPath.Write("db/");
env.Open(envPath);
env.CreateShard(1, 1, 1, ReadBuffer(""), ReadBuffer(""), true);
env.CreateShard(1, 2, 1, ReadBuffer(""), ReadBuffer(""), true);
Buffer key, value;
ReadBuffer rk, rv;
uint64_t i,j, rnd, num;
key.Writef("999999");
value.Writef("world");
env.Get(1, 2, ReadBuffer(key), rv);
env.Set(1, 2, ReadBuffer(key), ReadBuffer(value));
num = 10*1000*1000;
for (i = 0; i < num; i++)
{
// rnd = RandomInt(0, num - 1);
key.Writef("%U", i);
value.Writef("%0100U", i);
env.Set(1, 1, ReadBuffer(key), ReadBuffer(value));
if (i % (100*1000) == 0)
{
env.Commit();
Log_Message("%U", i);
}
if (i > 0 && i % (10*1000) == 0)
{
EventLoop::RunOnce();
// for (j = 0; j < 1000; j++)
// {
// rnd = RandomInt(0, i - 1);
// key.Writef("%U", rnd);
// if (!env.Get(1, 1, ReadBuffer(key), rv))
// Log_Message("%B => not found", &key);
// }
}
}
env.Commit();
StorageBulkCursor* bc = env.GetBulkCursor(1, 1);
StorageKeyValue* it;
i = 0;
Log_Message("Bulk iterating...");
FOREACH(it, *bc)
{
rk = it->GetKey();
rv = it->GetValue();
// Log_Message("%R => %R", &rk, &rv);
i++;
if (i > 0 && i % (100*1000) == 0)
{
Log_Message("%U", i);
Log_Message("%R => %R", &rk, &rv);
}
}
Log_Message("%d", i);
// ReadBuffer rv;
// uint64_t rnd;
// Log_Message("GET begin");
// for (i = 0; i < 100*1000; i++)
// {
// rnd = RandomInt(0, 1000*1000 - 1);
// key.Writef("%U", rnd);
// if (!env.Get(1, 1, ReadBuffer(key), rv))
// Log_Message("%B => not found", &key);
// }
//
// Log_Message("GET end");
// env.Close();
EventLoop::Shutdown();
IOProcessor::Shutdown();
StopClock();
Log_Shutdown();
}
void InitLog()
{
int logTargets;
logTargets = 0;
if (configFile.GetListNum("log.targets") == 0)
logTargets = LOG_TARGET_STDOUT;
for (int i = 0; i < configFile.GetListNum("log.targets"); i++)
{
if (strcmp(configFile.GetListValue("log.targets", i, ""), "file") == 0)
{
logTargets |= LOG_TARGET_FILE;
Log_SetOutputFile(configFile.GetValue("log.file", NULL),
configFile.GetBoolValue("log.truncate", false));
}
if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stdout") == 0)
logTargets |= LOG_TARGET_STDOUT;
if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stderr") == 0)
logTargets |= LOG_TARGET_STDERR;
}
Log_SetTarget(logTargets);
Log_SetTrace(configFile.GetBoolValue("log.trace", false));
Log_SetTimestamping(configFile.GetBoolValue("log.timestamping", false));
}
//#include "Version.h"
//#include "System/Config.h"
//#include "System/Events/EventLoop.h"
//#include "System/IO/IOProcessor.h"
//#include "Application/Common/ContextTransport.h"
//#include "Application/ConfigServer/ConfigServerApp.h"
//#include "Application/ShardServer/ShardServerApp.h"
//
//#ifdef DEBUG
//#define VERSION_FMT_STRING "ScalienDB v" VERSION_STRING " (DEBUG build date " __DATE__ " " __TIME__ ")"
//#else
//#define VERSION_FMT_STRING "ScalienDB v" VERSION_STRING
//#endif
//
//void InitLog();
//bool IsController();
//void InitContextTransport();
//
//int main(int argc, char** argv)
//{
// Application* app;
// bool isController;
//
// if (argc < 2)
// STOP_FAIL(1, "Config file argument not given, exiting");
//
// if (!configFile.Init(argv[1]))
// STOP_FAIL(1, "Invalid config file (%s)", argv[1]);
//
// InitLog();
// StartClock();
// IOProcessor::Init(configFile.GetIntValue("io.maxfd", 1024), true);
// InitContextTransport();
//
// isController = IsController();
// Log_Message(VERSION_FMT_STRING " started as %s", isController ? "CONTROLLER" : "SHARD SERVER");
// if (isController)
// app = new ConfigServerApp;
// else
// app = new ShardServerApp;
//
// app->Init();
//
// EventLoop::Init();
// EventLoop::Run();
// EventLoop::Shutdown();
//
// app->Shutdown();
// delete app;
//
// IOProcessor::Shutdown();
// DEFAULT_BUFFERPOOL->Shutdown();
// StopClock();
// configFile.Shutdown();
// Log_Shutdown();
//}
//
//void InitLog()
//{
// int logTargets;
//
// logTargets = 0;
// if (configFile.GetListNum("log.targets") == 0)
// logTargets = LOG_TARGET_STDOUT;
//
// for (int i = 0; i < configFile.GetListNum("log.targets"); i++)
// {
// if (strcmp(configFile.GetListValue("log.targets", i, ""), "file") == 0)
// {
// logTargets |= LOG_TARGET_FILE;
// Log_SetOutputFile(configFile.GetValue("log.file", NULL),
// configFile.GetBoolValue("log.truncate", false));
// }
// if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stdout") == 0)
// logTargets |= LOG_TARGET_STDOUT;
// if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stderr") == 0)
// logTargets |= LOG_TARGET_STDERR;
// }
// Log_SetTarget(logTargets);
//
// Log_SetTrace(configFile.GetBoolValue("log.trace", false));
// Log_SetTimestamping(configFile.GetBoolValue("log.timestamping", false));
//}
//
//bool IsController()
//{
// const char* role;
//
// role = configFile.GetValue("role", "");
// if (strcmp(role, "controller") == 0)
// return true;
// else
// return false;
//}
//
//void InitContextTransport()
//{
// const char* str;
// Endpoint endpoint;
//
// // set my endpoint
// str = configFile.GetValue("endpoint", "");
// if (str == 0)
// ASSERT_FAIL();
// endpoint.Set(str);
// CONTEXT_TRANSPORT->Init(endpoint);
//}
<commit_msg>Fixed Main.cpp<commit_after>#include "Version.h"
#include "System/Config.h"
#include "System/Events/EventLoop.h"
#include "System/IO/IOProcessor.h"
#include "Application/Common/ContextTransport.h"
#include "Application/ConfigServer/ConfigServerApp.h"
#include "Application/ShardServer/ShardServerApp.h"
#ifdef DEBUG
#define VERSION_FMT_STRING "ScalienDB v" VERSION_STRING " (DEBUG build date " __DATE__ " " __TIME__ ")"
#else
#define VERSION_FMT_STRING "ScalienDB v" VERSION_STRING
#endif
void InitLog();
bool IsController();
void InitContextTransport();
int main(int argc, char** argv)
{
Application* app;
bool isController;
if (argc < 2)
STOP_FAIL(1, "Config file argument not given, exiting");
if (!configFile.Init(argv[1]))
STOP_FAIL(1, "Invalid config file (%s)", argv[1]);
InitLog();
StartClock();
IOProcessor::Init(configFile.GetIntValue("io.maxfd", 1024), true);
InitContextTransport();
isController = IsController();
Log_Message(VERSION_FMT_STRING " started as %s", isController ? "CONTROLLER" : "SHARD SERVER");
if (isController)
app = new ConfigServerApp;
else
app = new ShardServerApp;
app->Init();
EventLoop::Init();
EventLoop::Run();
EventLoop::Shutdown();
app->Shutdown();
delete app;
IOProcessor::Shutdown();
DEFAULT_BUFFERPOOL->Shutdown();
StopClock();
configFile.Shutdown();
Log_Shutdown();
}
void InitLog()
{
int logTargets;
logTargets = 0;
if (configFile.GetListNum("log.targets") == 0)
logTargets = LOG_TARGET_STDOUT;
for (int i = 0; i < configFile.GetListNum("log.targets"); i++)
{
if (strcmp(configFile.GetListValue("log.targets", i, ""), "file") == 0)
{
logTargets |= LOG_TARGET_FILE;
Log_SetOutputFile(configFile.GetValue("log.file", NULL),
configFile.GetBoolValue("log.truncate", false));
}
if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stdout") == 0)
logTargets |= LOG_TARGET_STDOUT;
if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stderr") == 0)
logTargets |= LOG_TARGET_STDERR;
}
Log_SetTarget(logTargets);
Log_SetTrace(configFile.GetBoolValue("log.trace", false));
Log_SetTimestamping(configFile.GetBoolValue("log.timestamping", false));
}
bool IsController()
{
const char* role;
role = configFile.GetValue("role", "");
if (strcmp(role, "controller") == 0)
return true;
else
return false;
}
void InitContextTransport()
{
const char* str;
Endpoint endpoint;
// set my endpoint
str = configFile.GetValue("endpoint", "");
if (str == 0)
ASSERT_FAIL();
endpoint.Set(str);
CONTEXT_TRANSPORT->Init(endpoint);
}<|endoftext|> |
<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.40
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "Simulation.h"
#include "GOMC_Config.h" //For version number
#if GOMC_LIB_MPI
#include <mpi.h>
#include "ParallelTemperingPreprocessor.h"
#endif
#ifdef GOMC_CUDA
#include "cuda.h"
#include <cuda_runtime_api.h>
#endif
#include <iostream>
#include <ctime>
//find and include appropriate files for getHostname
#ifdef _WIN32
#include <Winsock2.h>
#define HOSTNAME
#elif defined(__linux__) || defined(__apple__) || defined(__FreeBSD__)
#include <unistd.h>
#include <sys/sysinfo.h>
#include <sys/utsname.h>
#define HOSTNAME
#endif
namespace
{
std::ostream& PrintTime(std::ostream& stream);
std::ostream& PrintHostname(std::ostream& stream);
std::ostream& PrintVersion(std::ostream& stream);
void PrintSimulationHeader();
void PrintSimulationFooter();
void PrintDebugMode();
bool CheckAndPrintEnsemble();
uint ReadNum(char *argv);
}
void PrintHardwareInfo();
#ifdef GOMC_CUDA
void PrintGPUHardwareInfo();
#endif
int main(int argc, char *argv[])
{
#if GOMC_LIB_MPI
string inputFileStringMPI;
fstream inputFileReaderMPI;
MultiSim * multisim;
int worldSize;
int worldRank;
ParallelTemperingPreprocessor pt;
//std::streambuf * savedCOUT;
//CHECK IF ARGS/FILE PROVIDED IN CMD LINE
if (argc < 2) {
std::cout << "Error: Input parameter file (*.dat or *.conf) not specified on command line!\n";
exit(EXIT_FAILURE);
} else {
if(argc == 2) {
//FIRST PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[1];
} else {
//SECOND PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[2];
if(argv[1][0] == '+' && argv[1][1] == 'p') {
// placeholder
} else {
std::cout << "Error: Undefined command to set number of threads!\n";
std::cout << "Use +p# command to set number of threads.\n";
exit(EXIT_FAILURE);
}
}
//OPEN FILE
inputFileReaderMPI.open(inputFileStringMPI.c_str(), ios::in | ios::out);
//CHECK IF FILE IS OPENED...IF NOT OPENED EXCEPTION REASON FIRED
if (!inputFileReaderMPI.is_open()) {
std::cout << "Error: Cannot open/find " << inputFileStringMPI <<
" in the directory provided!\n";
exit(EXIT_FAILURE);
}
//CLOSE FILE TO NOW PASS TO SIMULATION
inputFileReaderMPI.close();
// Initialize the MPI environment
MPI_Init(NULL, NULL);
// Get the number of processes
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
// Get the rank of the process
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
std::string pathToReplicaDirectory;
if(pt.checkIfParallelTempering(inputFileStringMPI)){
pt.checkIfValid(inputFileStringMPI);
if(worldSize > pt.getNumberOfReplicas(inputFileStringMPI)){
std::cout << "You may not request more processes (" << worldSize
<< ") than there are replicas(" << pt.getNumberOfReplicas(inputFileStringMPI) << ")! Exiting!\n";
} else {
#if ENSEMBLE == GCMC
pathToReplicaDirectory = pt.setupReplicaDirectoriesAndRedirectSTDOUTToFile ( pt.getMultiSimFolderName(inputFileStringMPI).c_str(),
pt.getTemperature(inputFileStringMPI.c_str(), worldRank).c_str(),
pt.getChemicalPotential(inputFileStringMPI.c_str(), worldRank).c_str()
);
#else
pathToReplicaDirectory = pt.setupReplicaDirectoriesAndRedirectSTDOUTToFile ( pt.getMultiSimFolderName(inputFileStringMPI).c_str(),
pt.getTemperature(inputFileStringMPI.c_str(), worldRank).c_str()
);
#endif
multisim = new MultiSim(worldSize, worldRank, pathToReplicaDirectory);
}
}
}
#endif
#ifndef NDEBUG
PrintDebugMode();
#endif
PrintSimulationHeader();
PrintHardwareInfo();
#ifdef GOMC_CUDA
PrintGPUHardwareInfo();
#endif
//Only run if valid ensemble was detected.
if (CheckAndPrintEnsemble()) {
//FOLLOWING LINES ADDED TO OBTAIN INPUT PARAMETER FILE
string inputFileString;
fstream inputFileReader;
uint numThreads;
//CHECK IF ARGS/FILE PROVIDED IN CMD LINE
if (argc < 2) {
std::cout << "Error: Input parameter file (*.dat or *.conf) not specified on command line!\n";
exit(EXIT_FAILURE);
} else {
if(argc == 2) {
//FIRST PARAMETER WILL BE FILE NAME
inputFileString = argv[1];
numThreads = 1;
} else {
//SECOND PARAMETER WILL BE FILE NAME
inputFileString = argv[2];
if(argv[1][0] == '+' && argv[1][1] == 'p') {
numThreads = ReadNum(argv[1]);
} else {
std::cout << "Error: Undefined command to set number of threads!\n";
std::cout << "Use +p# command to set number of threads.\n";
exit(EXIT_FAILURE);
}
}
}
//SET NUMBER OF THREADS
#ifdef _OPENMP
omp_set_num_threads(numThreads);
printf("%-40s %-d \n", "Info: Number of threads", numThreads);
#else
printf("%-40s %-d \n", "Info: Number of threads", 1);
#endif
//OPEN FILE
inputFileReader.open(inputFileString.c_str(), ios::in | ios::out);
//CHECK IF FILE IS OPENED...IF NOT OPENED EXCEPTION REASON FIRED
if (!inputFileReader.is_open()) {
std::cout << "Error: Cannot open/find " << inputFileString <<
" in the directory provided!\n";
exit(EXIT_FAILURE);
}
//CLOSE FILE TO NOW PASS TO SIMULATION
inputFileReader.close();
//ONCE FILE FOUND PASS STRING TO SIMULATION CLASS TO READ AND
//HANDLE PDB|PSF FILE
#if GOMC_LIB_MPI
if(worldSize <= pt.getNumberOfReplicas(inputFileStringMPI)){
Simulation sim(inputFileString.c_str(), multisim);
sim.RunSimulation();
PrintSimulationFooter();
delete multisim;
}
#else
Simulation sim(inputFileString.c_str());
sim.RunSimulation();
PrintSimulationFooter();
#endif
}
#if GOMC_LIB_MPI
MPI_Finalize();
//std::cout.rdbuf(savedCOUT); //reset to standard output again
#endif
return 0;
}
namespace
{
void PrintSimulationHeader()
{
std::cout << PrintVersion << '\n'
<< "Info: Start Time: " << PrintTime
#ifdef HOSTNAME
<< "Info: Host Name: " << PrintHostname
#endif
<< "\n";
}
bool CheckAndPrintEnsemble()
{
bool healthy = true;
std::cout << "Info: GOMC COMPILED TO RUN ";
#if ENSEMBLE == NVT
std::cout << "CANONICAL (NVT)";
#elif ENSEMBLE == GEMC
std::cout << "GIBBS";
#elif ENSEMBLE == GCMC
std::cout << "GRAND CANONICAL";
#elif ENSEMBLE == NPT
std::cout << "ISOBARIC-ISOTHERMAL";
#else
std::cerr << "CRITICAL ERROR! Preprocessor value ENSEMBLE is "
<< "invalid or undefined." << std::endl
<< "Code will exit.";
healthy = false;
#endif
std::cout << " ENSEMBLE." << std::endl;
return healthy;
}
void PrintDebugMode()
{
std::cout << "################################################################################\n";
std::cout << "########################## RUNNING GOMC IN DEBUG MODE ##########################\n";
std::cout << "################################################################################\n";
}
void PrintSimulationFooter()
{
std::cout << PrintVersion << '\n'
<< "Info: Completed at: " << PrintTime
<< "Info: On hostname: " << PrintHostname
<< '\n';
}
std::ostream& PrintVersion(std::ostream& stream)
{
stream << "Info: GOMC Version " << GOMC_VERSION_MAJOR
<< '.' << GOMC_VERSION_MINOR;
return stream;
}
std::ostream& PrintTime(std::ostream& stream)
{
time_t timer;
time(&timer);
stream << asctime(localtime(&timer));
return stream;
}
std::ostream& PrintHostname(std::ostream& stream)
{
#ifdef HOSTNAME
#ifdef _WIN32
//setup WINSOCK
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 0), &wsaData);
#endif
const int maxNameLength = 80;
char hostname[maxNameLength];
gethostname(hostname, maxNameLength);
//gethostname does not guarantee null termination
hostname[maxNameLength - 1] = '\0';
stream << hostname;
#ifdef _WIN32
//teardown WINSOCK
WSACleanup();
#endif
#else
stream << "Info: Hostname Unavailable";
#endif
return stream;
}
uint ReadNum(char *argv)
{
uint thread = 0;
for(uint i = 2; argv[i] != 0; i++) {
thread = thread * 10 + (argv[i] - '0');
}
return thread;
}
}
void PrintHardwareInfo()
{
#ifdef __linux__
struct sysinfo mem;
const double megabyte = 1024 * 1024;
struct utsname name;
uname(&name);
printf("CPU information:\n");
std::cout << std::setprecision(1) << std::fixed;
std::cout << "Info: Total number of CPUs: " << get_nprocs() << std::endl;
std::cout << "Info: Total number of CPUs available: " << sysconf(_SC_NPROCESSORS_ONLN) << std::endl;
std::cout << "Info: Model name:" << std::flush;
if(system("awk -F: '/model name/ {print $2;exit}' /proc/cpuinfo") == -1)
std::cout << "Error: Couldn't retrieve CPU information" << std::endl;
std::cout << "Info: System name: " << name.sysname << std::endl;
std::cout << "Info: Release: " << name.release << std::endl;
std::cout << "Info: Version: " << name.version << std::endl;
std::cout << "Info: Kernel Architecture: " << name.machine << std::endl;
if(sysinfo(&mem) == 0) {
std::cout << "Info: Total Ram: " << mem.totalram / megabyte << "MB" << std::endl;
std::cout << "Info: Used Ram: " << mem.totalram / megabyte - mem.freeram / megabyte << "MB" << std::endl;
}
std::cout << "Info: Working in the current directory: " << get_current_dir_name();
std::cout << std::endl;
#endif
}
#ifdef GOMC_CUDA
void PrintGPUHardwareInfo()
{
int nDevices;
int fast = 0;
int fastIndex = 0;
cudaGetDeviceCount(&nDevices);
if(nDevices == 0) {
printf("There are no available device(s) that support CUDA\n");
exit(EXIT_FAILURE);
}
if(nDevices <= 4) {
printf("GPU information:\n");
for (int i = 0; i < nDevices; i++) {
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, i);
printf("Info: Device Number: %d\n", i);
printf("Info: Device name: %s\n", prop.name);
printf("Info: Memory Clock Rate (KHz): %d\n", prop.memoryClockRate);
printf("Info: Memory Bus Width (bits): %d\n", prop.memoryBusWidth);
printf("Info: Peak Memory Bandwidth (GB/s): %f\n",
2.0 * prop.memoryClockRate * (prop.memoryBusWidth / 8) / 1.0e6);
if( prop.memoryClockRate > fast) {
fast = prop.memoryClockRate;
fastIndex = i;
}
}
}
cudaSetDevice(fastIndex);
printf("Info: Using Device Number: %d\n", fastIndex);
}
#endif
<commit_msg>Consolidated MPI macro at end of Main<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.40
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "Simulation.h"
#include "GOMC_Config.h" //For version number
#if GOMC_LIB_MPI
#include <mpi.h>
#include "ParallelTemperingPreprocessor.h"
#endif
#ifdef GOMC_CUDA
#include "cuda.h"
#include <cuda_runtime_api.h>
#endif
#include <iostream>
#include <ctime>
//find and include appropriate files for getHostname
#ifdef _WIN32
#include <Winsock2.h>
#define HOSTNAME
#elif defined(__linux__) || defined(__apple__) || defined(__FreeBSD__)
#include <unistd.h>
#include <sys/sysinfo.h>
#include <sys/utsname.h>
#define HOSTNAME
#endif
namespace
{
std::ostream& PrintTime(std::ostream& stream);
std::ostream& PrintHostname(std::ostream& stream);
std::ostream& PrintVersion(std::ostream& stream);
void PrintSimulationHeader();
void PrintSimulationFooter();
void PrintDebugMode();
bool CheckAndPrintEnsemble();
uint ReadNum(char *argv);
}
void PrintHardwareInfo();
#ifdef GOMC_CUDA
void PrintGPUHardwareInfo();
#endif
int main(int argc, char *argv[])
{
#if GOMC_LIB_MPI
string inputFileStringMPI;
fstream inputFileReaderMPI;
MultiSim * multisim;
int worldSize;
int worldRank;
ParallelTemperingPreprocessor pt;
//std::streambuf * savedCOUT;
//CHECK IF ARGS/FILE PROVIDED IN CMD LINE
if (argc < 2) {
std::cout << "Error: Input parameter file (*.dat or *.conf) not specified on command line!\n";
exit(EXIT_FAILURE);
} else {
if(argc == 2) {
//FIRST PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[1];
} else {
//SECOND PARAMETER WILL BE FILE NAME
inputFileStringMPI = argv[2];
if(argv[1][0] == '+' && argv[1][1] == 'p') {
// placeholder
} else {
std::cout << "Error: Undefined command to set number of threads!\n";
std::cout << "Use +p# command to set number of threads.\n";
exit(EXIT_FAILURE);
}
}
//OPEN FILE
inputFileReaderMPI.open(inputFileStringMPI.c_str(), ios::in | ios::out);
//CHECK IF FILE IS OPENED...IF NOT OPENED EXCEPTION REASON FIRED
if (!inputFileReaderMPI.is_open()) {
std::cout << "Error: Cannot open/find " << inputFileStringMPI <<
" in the directory provided!\n";
exit(EXIT_FAILURE);
}
//CLOSE FILE TO NOW PASS TO SIMULATION
inputFileReaderMPI.close();
// Initialize the MPI environment
MPI_Init(NULL, NULL);
// Get the number of processes
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
// Get the rank of the process
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
std::string pathToReplicaDirectory;
if(pt.checkIfParallelTempering(inputFileStringMPI)){
pt.checkIfValid(inputFileStringMPI);
if(worldSize > pt.getNumberOfReplicas(inputFileStringMPI)){
std::cout << "You may not request more processes (" << worldSize
<< ") than there are replicas(" << pt.getNumberOfReplicas(inputFileStringMPI) << ")! Exiting!\n";
} else {
#if ENSEMBLE == GCMC
pathToReplicaDirectory = pt.setupReplicaDirectoriesAndRedirectSTDOUTToFile ( pt.getMultiSimFolderName(inputFileStringMPI).c_str(),
pt.getTemperature(inputFileStringMPI.c_str(), worldRank).c_str(),
pt.getChemicalPotential(inputFileStringMPI.c_str(), worldRank).c_str()
);
#else
pathToReplicaDirectory = pt.setupReplicaDirectoriesAndRedirectSTDOUTToFile ( pt.getMultiSimFolderName(inputFileStringMPI).c_str(),
pt.getTemperature(inputFileStringMPI.c_str(), worldRank).c_str()
);
#endif
multisim = new MultiSim(worldSize, worldRank, pathToReplicaDirectory);
}
}
}
#endif
#ifndef NDEBUG
PrintDebugMode();
#endif
PrintSimulationHeader();
PrintHardwareInfo();
#ifdef GOMC_CUDA
PrintGPUHardwareInfo();
#endif
//Only run if valid ensemble was detected.
if (CheckAndPrintEnsemble()) {
//FOLLOWING LINES ADDED TO OBTAIN INPUT PARAMETER FILE
string inputFileString;
fstream inputFileReader;
uint numThreads;
//CHECK IF ARGS/FILE PROVIDED IN CMD LINE
if (argc < 2) {
std::cout << "Error: Input parameter file (*.dat or *.conf) not specified on command line!\n";
exit(EXIT_FAILURE);
} else {
if(argc == 2) {
//FIRST PARAMETER WILL BE FILE NAME
inputFileString = argv[1];
numThreads = 1;
} else {
//SECOND PARAMETER WILL BE FILE NAME
inputFileString = argv[2];
if(argv[1][0] == '+' && argv[1][1] == 'p') {
numThreads = ReadNum(argv[1]);
} else {
std::cout << "Error: Undefined command to set number of threads!\n";
std::cout << "Use +p# command to set number of threads.\n";
exit(EXIT_FAILURE);
}
}
}
//SET NUMBER OF THREADS
#ifdef _OPENMP
omp_set_num_threads(numThreads);
printf("%-40s %-d \n", "Info: Number of threads", numThreads);
#else
printf("%-40s %-d \n", "Info: Number of threads", 1);
#endif
//OPEN FILE
inputFileReader.open(inputFileString.c_str(), ios::in | ios::out);
//CHECK IF FILE IS OPENED...IF NOT OPENED EXCEPTION REASON FIRED
if (!inputFileReader.is_open()) {
std::cout << "Error: Cannot open/find " << inputFileString <<
" in the directory provided!\n";
exit(EXIT_FAILURE);
}
//CLOSE FILE TO NOW PASS TO SIMULATION
inputFileReader.close();
//ONCE FILE FOUND PASS STRING TO SIMULATION CLASS TO READ AND
//HANDLE PDB|PSF FILE
#if GOMC_LIB_MPI
if(worldSize <= pt.getNumberOfReplicas(inputFileStringMPI)){
Simulation sim(inputFileString.c_str(), multisim);
sim.RunSimulation();
PrintSimulationFooter();
delete multisim;
MPI_Finalize();
} else {
MPI_Finalize();
}
#else
Simulation sim(inputFileString.c_str());
sim.RunSimulation();
PrintSimulationFooter();
#endif
}
return 0;
}
namespace
{
void PrintSimulationHeader()
{
std::cout << PrintVersion << '\n'
<< "Info: Start Time: " << PrintTime
#ifdef HOSTNAME
<< "Info: Host Name: " << PrintHostname
#endif
<< "\n";
}
bool CheckAndPrintEnsemble()
{
bool healthy = true;
std::cout << "Info: GOMC COMPILED TO RUN ";
#if ENSEMBLE == NVT
std::cout << "CANONICAL (NVT)";
#elif ENSEMBLE == GEMC
std::cout << "GIBBS";
#elif ENSEMBLE == GCMC
std::cout << "GRAND CANONICAL";
#elif ENSEMBLE == NPT
std::cout << "ISOBARIC-ISOTHERMAL";
#else
std::cerr << "CRITICAL ERROR! Preprocessor value ENSEMBLE is "
<< "invalid or undefined." << std::endl
<< "Code will exit.";
healthy = false;
#endif
std::cout << " ENSEMBLE." << std::endl;
return healthy;
}
void PrintDebugMode()
{
std::cout << "################################################################################\n";
std::cout << "########################## RUNNING GOMC IN DEBUG MODE ##########################\n";
std::cout << "################################################################################\n";
}
void PrintSimulationFooter()
{
std::cout << PrintVersion << '\n'
<< "Info: Completed at: " << PrintTime
<< "Info: On hostname: " << PrintHostname
<< '\n';
}
std::ostream& PrintVersion(std::ostream& stream)
{
stream << "Info: GOMC Version " << GOMC_VERSION_MAJOR
<< '.' << GOMC_VERSION_MINOR;
return stream;
}
std::ostream& PrintTime(std::ostream& stream)
{
time_t timer;
time(&timer);
stream << asctime(localtime(&timer));
return stream;
}
std::ostream& PrintHostname(std::ostream& stream)
{
#ifdef HOSTNAME
#ifdef _WIN32
//setup WINSOCK
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 0), &wsaData);
#endif
const int maxNameLength = 80;
char hostname[maxNameLength];
gethostname(hostname, maxNameLength);
//gethostname does not guarantee null termination
hostname[maxNameLength - 1] = '\0';
stream << hostname;
#ifdef _WIN32
//teardown WINSOCK
WSACleanup();
#endif
#else
stream << "Info: Hostname Unavailable";
#endif
return stream;
}
uint ReadNum(char *argv)
{
uint thread = 0;
for(uint i = 2; argv[i] != 0; i++) {
thread = thread * 10 + (argv[i] - '0');
}
return thread;
}
}
void PrintHardwareInfo()
{
#ifdef __linux__
struct sysinfo mem;
const double megabyte = 1024 * 1024;
struct utsname name;
uname(&name);
printf("CPU information:\n");
std::cout << std::setprecision(1) << std::fixed;
std::cout << "Info: Total number of CPUs: " << get_nprocs() << std::endl;
std::cout << "Info: Total number of CPUs available: " << sysconf(_SC_NPROCESSORS_ONLN) << std::endl;
std::cout << "Info: Model name:" << std::flush;
if(system("awk -F: '/model name/ {print $2;exit}' /proc/cpuinfo") == -1)
std::cout << "Error: Couldn't retrieve CPU information" << std::endl;
std::cout << "Info: System name: " << name.sysname << std::endl;
std::cout << "Info: Release: " << name.release << std::endl;
std::cout << "Info: Version: " << name.version << std::endl;
std::cout << "Info: Kernel Architecture: " << name.machine << std::endl;
if(sysinfo(&mem) == 0) {
std::cout << "Info: Total Ram: " << mem.totalram / megabyte << "MB" << std::endl;
std::cout << "Info: Used Ram: " << mem.totalram / megabyte - mem.freeram / megabyte << "MB" << std::endl;
}
std::cout << "Info: Working in the current directory: " << get_current_dir_name();
std::cout << std::endl;
#endif
}
#ifdef GOMC_CUDA
void PrintGPUHardwareInfo()
{
int nDevices;
int fast = 0;
int fastIndex = 0;
cudaGetDeviceCount(&nDevices);
if(nDevices == 0) {
printf("There are no available device(s) that support CUDA\n");
exit(EXIT_FAILURE);
}
if(nDevices <= 4) {
printf("GPU information:\n");
for (int i = 0; i < nDevices; i++) {
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, i);
printf("Info: Device Number: %d\n", i);
printf("Info: Device name: %s\n", prop.name);
printf("Info: Memory Clock Rate (KHz): %d\n", prop.memoryClockRate);
printf("Info: Memory Bus Width (bits): %d\n", prop.memoryBusWidth);
printf("Info: Peak Memory Bandwidth (GB/s): %f\n",
2.0 * prop.memoryClockRate * (prop.memoryBusWidth / 8) / 1.0e6);
if( prop.memoryClockRate > fast) {
fast = prop.memoryClockRate;
fastIndex = i;
}
}
}
cudaSetDevice(fastIndex);
printf("Info: Using Device Number: %d\n", fastIndex);
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dtint.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: hr $ $Date: 2007-06-27 20:38:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SV_DTINT_HXX
#define _SV_DTINT_HXX
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#include <vcl/font.hxx>
class SalBitmap;
class SalDisplay;
class AllSettings;
#ifndef _XLIB_H_
// forwards from X
struct Display;
struct XEvent;
#define Atom UINT32
#define XLIB_Window UINT32
#endif
enum DtType {
DtGeneric,
DtCDE,
DtMACOSX
};
class DtIntegrator
{
protected:
DtType meType;
Display* mpDisplay;
SalDisplay* mpSalDisplay;
int mnSystemLookCommandProcess;
DtIntegrator();
static String aHomeDir;
public:
static DtIntegrator* CreateDtIntegrator();
virtual ~DtIntegrator();
// SystemLook
virtual void GetSystemLook( AllSettings& rSettings );
DtType GetDtType() { return meType; }
SalDisplay* GetSalDisplay() { return mpSalDisplay; }
Display* GetDisplay() { return mpDisplay; }
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.16.248); FILE MERGED 2008/04/01 16:05:46 thb 1.16.248.2: #i85898# Stripping all external header guards 2008/03/28 15:45:14 rt 1.16.248.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: dtint.hxx,v $
* $Revision: 1.17 $
*
* 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 _SV_DTINT_HXX
#define _SV_DTINT_HXX
#include <tools/link.hxx>
#include <tools/string.hxx>
#include <tools/color.hxx>
#include <vcl/font.hxx>
class SalBitmap;
class SalDisplay;
class AllSettings;
#ifndef _XLIB_H_
// forwards from X
struct Display;
struct XEvent;
#define Atom UINT32
#define XLIB_Window UINT32
#endif
enum DtType {
DtGeneric,
DtCDE,
DtMACOSX
};
class DtIntegrator
{
protected:
DtType meType;
Display* mpDisplay;
SalDisplay* mpSalDisplay;
int mnSystemLookCommandProcess;
DtIntegrator();
static String aHomeDir;
public:
static DtIntegrator* CreateDtIntegrator();
virtual ~DtIntegrator();
// SystemLook
virtual void GetSystemLook( AllSettings& rSettings );
DtType GetDtType() { return meType; }
SalDisplay* GetSalDisplay() { return mpSalDisplay; }
Display* GetDisplay() { return mpDisplay; }
};
#endif
<|endoftext|> |
<commit_before>/*
* O ,-
* o . - ' ,-
* . ` . ,
* ( )) . (
* `-;_ . - `.`.
* `._'
*
* Copyright (c) 2007-2011 Markus Fisch <[email protected]>
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
#include "Menu.h"
#include "WindowManager.h"
#include <X11/Xutil.h>
#include <unistd.h>
#include <stdlib.h>
#include <sstream>
using namespace PieDock;
/**
* Initialize menu
*
* @param a - application
*/
Menu::Menu( Application *a ) :
app( a ),
selected( 0 ),
menuItems( 0 )
{
}
/**
* Update menu
*
* @param menuName - menu name
*/
bool Menu::update( std::string menuName )
{
if( !(menuItems = app->getSettings()->getMenu( menuName )) )
return false;
// multiple windows per icon
typedef std::map<Icon *, MenuItem *> IconToItem;
IconToItem iconToItem;
// one icon per window
typedef std::map<Window, MenuItem *> WindowToItem;
WindowToItem windowToItem;
IconMap *iconMap = &app->getSettings()->getIconMap();
// clear windows and make sure all items have valid icons
{
MenuItems::iterator si = menuItems->end();
for( MenuItems::iterator i = menuItems->begin();
i != menuItems->end();
i++ )
{
Icon *icon;
if( !(icon = (*i)->getIcon()) )
{
if( !(icon = iconMap->getIconByName( (*i)->getTitle() )) )
icon = iconMap->getMissingIcon( (*i)->getTitle() );
(*i)->setIcon( icon );
}
if( menuItems->oneIconPerWindow() )
{
windowToItem[(*i)->getNextWindow()] = (*i);
if( *i == selected )
si = i;
}
iconToItem[icon] = (*i);
(*i)->clearWindows();
}
// move menu item to the top when one icon per window is used
if( si != menuItems->end() )
{
menuItems->erase( si );
menuItems->push_front( selected );
}
}
// get filter
std::string classFilter;
if( menuItems->onlyFromActive() )
{
Window w = WindowManager::getActive( app->getDisplay() );
XClassHint xch;
if( w &&
XGetClassHint( app->getDisplay(), w, &xch ) )
classFilter = xch.res_class;
}
// assign windows to menu items; this is done by evaluating name, class
// or title of the windows since you just can't trust window IDs over time
{
WindowManager::WindowList wl( app->getDisplay() );
for( WindowManager::WindowList::iterator i = wl.begin();
i != wl.end();
i++ )
{
if( !WindowManager::isNormalWindow( app->getDisplay(), (*i) ) )
continue;
if( menuItems->oneIconPerWindow() )
{
WindowToItem::iterator w;
if( (w = windowToItem.find( (*i) )) != windowToItem.end() )
{
if( menuItems->onlyFromActive() )
{
XClassHint xch;
if( XGetClassHint( app->getDisplay(), (*i), &xch ) &&
classFilter.compare( xch.res_class ) )
continue;
}
(*w).second->addWindow( app->getDisplay(), (*i) );
continue;
}
}
XClassHint xch;
if( !XGetClassHint( app->getDisplay(), (*i), &xch ) ||
app->getSettings()->ignoreWindow( xch.res_name ) )
continue;
if( menuItems->onlyFromActive() &&
classFilter.compare( xch.res_class ) )
continue;
Icon *icon;
if( !(icon = iconMap->getIconByTitle(
WindowManager::getTitle( app->getDisplay(), (*i) ) )) &&
!(icon = iconMap->getIconByClass( xch.res_class )) &&
!(icon = iconMap->getIconByName( xch.res_name )) )
icon = iconMap->getMissingIcon( xch.res_name );
if( menuItems->oneIconPerWindow() )
{
MenuItem *item = new MenuItem( icon );
item->addWindow( app->getDisplay(), (*i) );
menuItems->push_back( item );
continue;
}
// find existing icon or create a new one
{
IconToItem::iterator m;
if( (m = iconToItem.find( icon )) != iconToItem.end() )
(*m).second->addWindow( app->getDisplay(), (*i) );
else if( menuItems->includeWindows() )
{
MenuItem *item = new MenuItem( icon );
item->addWindow( app->getDisplay(), (*i) );
iconToItem[icon] = item;
menuItems->push_back( item );
}
}
}
}
// remove all menu items that have no windows and
// are not sticky
{
MenuItems::iterator i = menuItems->begin();
while( i != menuItems->end() )
if( !(*i)->isSticky() &&
!(*i)->hasWindows() )
{
delete (*i);
i = menuItems->erase( i );
}
else
++i;
}
// fill menu with dummy icons if there is a minimum number
{
int m = app->getSettings()->getMinimumNumber();
if( m > 0 &&
menuItems->size() < m )
{
for( m -= menuItems->size(); m--; )
menuItems->push_back( new MenuItem(
iconMap->getFillerIcon() ) );
}
}
return true;
}
/**
* Check if item points to another menu and if so, change to it
*
* @param a - action to execute (optional)
*/
bool Menu::change( Settings::Action a )
{
if( !selected ||
(
a != Settings::Launch &&
a != Settings::ShowNext &&
a != Settings::ShowPrevious
) )
return false;
std::string cmd = selected->getCommand();
// check if this menu should launch another menu
if( !cmd.compare( 0, 1, ":" ) )
{
update( cmd.substr( 1 ) );
return true;
}
return false;
}
/**
* Execute some action for the seleced icon
*
* @param a - action to execute (optional)
*/
void Menu::execute( Settings::Action a )
{
if( !selected )
return;
// if there are no windows only Launch is allowed
if( !selected->hasWindows() )
{
if( a != Settings::Launch &&
a != Settings::ShowNext &&
a != Settings::ShowPrevious )
return;
a = Settings::Launch;
}
switch( a )
{
case Settings::Launch:
{
std::string cmd = selected->getCommand();
// substitute $WID with window ID
{
std::string::size_type p;
if( (p = cmd.find( "$WID" )) != std::string::npos )
{
std::ostringstream oss;
oss << cmd.substr( 0, p ) <<
"0x" <<
std::hex << getWindowBelowCursor() <<
cmd.substr( p+4 );
cmd = oss.str();
}
}
run( cmd );
}
break;
case Settings::ShowNext:
WindowManager::activate(
app->getDisplay(),
selected->getNextWindow() );
break;
case Settings::ShowPrevious:
WindowManager::activate(
app->getDisplay(),
selected->getPreviousWindow() );
break;
case Settings::Hide:
WindowManager::iconify(
app->getDisplay(),
selected->getNextWindow() );
break;
case Settings::Close:
WindowManager::close(
app->getDisplay(),
selected->getNextWindow() );
break;
}
}
/**
* Return item title
*/
std::string Menu::getItemTitle() const
{
if( selected )
{
if( !selected->isSticky() &&
selected->hasWindows() )
{
std::string t = WindowManager::getTitle(
app->getDisplay(),
selected->getNextWindow() );
selected->setTitle( t );
return t;
}
return selected->getTitle();
}
return "";
};
/**
* Run some command
*
* @param command - command to execute
*/
int Menu::run( std::string command ) const
{
int pid = fork();
if( pid < 0 )
throw "fork failed";
else if( pid )
return pid;
char *shell = getenv( "SHELL" );
if( !shell )
shell = const_cast<char *>( "/bin/sh" );
setsid();
execl( shell, shell, "-c", command.c_str(), NULL );
throw "exec failed";
// make compiler happy
return 0;
}
<commit_msg>improved icon determination in one-icon-per-window menus<commit_after>/*
* O ,-
* o . - ' ,-
* . ` . ,
* ( )) . (
* `-;_ . - `.`.
* `._'
*
* Copyright (c) 2007-2011 Markus Fisch <[email protected]>
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
#include "Menu.h"
#include "WindowManager.h"
#include <X11/Xutil.h>
#include <unistd.h>
#include <stdlib.h>
#include <sstream>
using namespace PieDock;
/**
* Initialize menu
*
* @param a - application
*/
Menu::Menu( Application *a ) :
app( a ),
selected( 0 ),
menuItems( 0 )
{
}
/**
* Update menu
*
* @param menuName - menu name
*/
bool Menu::update( std::string menuName )
{
if( !(menuItems = app->getSettings()->getMenu( menuName )) )
return false;
// multiple windows per icon
typedef std::map<Icon *, MenuItem *> IconToItem;
IconToItem iconToItem;
// one icon per window
typedef std::map<Window, MenuItem *> WindowToItem;
WindowToItem windowToItem;
IconMap *iconMap = &app->getSettings()->getIconMap();
// clear windows and make sure all items have valid icons
{
MenuItems::iterator si = menuItems->end();
for( MenuItems::iterator i = menuItems->begin();
i != menuItems->end();
i++ )
{
Icon *icon;
if( !(icon = (*i)->getIcon()) )
{
if( !(icon = iconMap->getIconByName( (*i)->getTitle() )) )
icon = iconMap->getMissingIcon( (*i)->getTitle() );
(*i)->setIcon( icon );
}
if( menuItems->oneIconPerWindow() )
{
windowToItem[(*i)->getNextWindow()] = (*i);
if( *i == selected )
si = i;
}
iconToItem[icon] = (*i);
(*i)->clearWindows();
}
// move menu item to the top when one icon per window is used
if( si != menuItems->end() )
{
menuItems->erase( si );
menuItems->push_front( selected );
}
}
// get filter
std::string classFilter;
if( menuItems->onlyFromActive() )
{
Window w = WindowManager::getActive( app->getDisplay() );
XClassHint xch;
if( w &&
XGetClassHint( app->getDisplay(), w, &xch ) )
classFilter = xch.res_class;
}
// assign windows to menu items; this is done by evaluating name, class
// and title of the windows since you just can't trust window IDs over time
{
WindowManager::WindowList wl( app->getDisplay() );
for( WindowManager::WindowList::iterator i = wl.begin();
i != wl.end();
i++ )
{
if( !WindowManager::isNormalWindow( app->getDisplay(), (*i) ) )
continue;
if( menuItems->oneIconPerWindow() )
{
WindowToItem::iterator w;
if( (w = windowToItem.find( (*i) )) != windowToItem.end() )
{
XClassHint xch;
Icon *icon;
if( !XGetClassHint( app->getDisplay(), (*i), &xch ) )
continue;
if( menuItems->onlyFromActive() &&
classFilter.compare( xch.res_class ) )
continue;
// always get icon anew when reusing a window ID
if( (icon = iconMap->getIcon(
WindowManager::getTitle( app->getDisplay(), (*i) ),
xch.res_class,
xch.res_name ) ))
(*w).second->setIcon( icon );
(*w).second->addWindow( app->getDisplay(), (*i) );
continue;
}
}
XClassHint xch;
if( !XGetClassHint( app->getDisplay(), (*i), &xch ) ||
app->getSettings()->ignoreWindow( xch.res_name ) )
continue;
if( menuItems->onlyFromActive() &&
classFilter.compare( xch.res_class ) )
continue;
Icon *icon = iconMap->getIcon(
WindowManager::getTitle( app->getDisplay(), (*i) ),
xch.res_class,
xch.res_name );
if( menuItems->oneIconPerWindow() )
{
MenuItem *item = new MenuItem( icon );
item->addWindow( app->getDisplay(), (*i) );
menuItems->push_back( item );
continue;
}
// find existing icon or create a new one
{
IconToItem::iterator m;
if( (m = iconToItem.find( icon )) != iconToItem.end() )
(*m).second->addWindow( app->getDisplay(), (*i) );
else if( menuItems->includeWindows() )
{
MenuItem *item = new MenuItem( icon );
item->addWindow( app->getDisplay(), (*i) );
iconToItem[icon] = item;
menuItems->push_back( item );
}
}
}
}
// remove all menu items that have no windows and
// are not sticky
{
MenuItems::iterator i = menuItems->begin();
while( i != menuItems->end() )
if( !(*i)->isSticky() &&
!(*i)->hasWindows() )
{
delete (*i);
i = menuItems->erase( i );
}
else
++i;
}
// fill menu with dummy icons if there is a minimum number
{
int m = app->getSettings()->getMinimumNumber();
if( m > 0 &&
menuItems->size() < m )
{
for( m -= menuItems->size(); m--; )
menuItems->push_back( new MenuItem(
iconMap->getFillerIcon() ) );
}
}
return true;
}
/**
* Check if item points to another menu and if so, change to it
*
* @param a - action to execute (optional)
*/
bool Menu::change( Settings::Action a )
{
if( !selected ||
(
a != Settings::Launch &&
a != Settings::ShowNext &&
a != Settings::ShowPrevious
) )
return false;
std::string cmd = selected->getCommand();
// check if this menu should launch another menu
if( !cmd.compare( 0, 1, ":" ) )
{
update( cmd.substr( 1 ) );
return true;
}
return false;
}
/**
* Execute some action for the seleced icon
*
* @param a - action to execute (optional)
*/
void Menu::execute( Settings::Action a )
{
if( !selected )
return;
// if there are no windows only Launch is allowed
if( !selected->hasWindows() )
{
if( a != Settings::Launch &&
a != Settings::ShowNext &&
a != Settings::ShowPrevious )
return;
a = Settings::Launch;
}
switch( a )
{
case Settings::Launch:
{
std::string cmd = selected->getCommand();
// substitute $WID with window ID
{
std::string::size_type p;
if( (p = cmd.find( "$WID" )) != std::string::npos )
{
std::ostringstream oss;
oss << cmd.substr( 0, p ) <<
"0x" <<
std::hex << getWindowBelowCursor() <<
cmd.substr( p+4 );
cmd = oss.str();
}
}
run( cmd );
}
break;
case Settings::ShowNext:
WindowManager::activate(
app->getDisplay(),
selected->getNextWindow() );
break;
case Settings::ShowPrevious:
WindowManager::activate(
app->getDisplay(),
selected->getPreviousWindow() );
break;
case Settings::Hide:
WindowManager::iconify(
app->getDisplay(),
selected->getNextWindow() );
break;
case Settings::Close:
WindowManager::close(
app->getDisplay(),
selected->getNextWindow() );
break;
}
}
/**
* Return item title
*/
std::string Menu::getItemTitle() const
{
if( selected )
{
if( !selected->isSticky() &&
selected->hasWindows() )
{
std::string t = WindowManager::getTitle(
app->getDisplay(),
selected->getNextWindow() );
selected->setTitle( t );
return t;
}
return selected->getTitle();
}
return "";
};
/**
* Run some command
*
* @param command - command to execute
*/
int Menu::run( std::string command ) const
{
int pid = fork();
if( pid < 0 )
throw "fork failed";
else if( pid )
return pid;
char *shell = getenv( "SHELL" );
if( !shell )
shell = const_cast<char *>( "/bin/sh" );
setsid();
execl( shell, shell, "-c", command.c_str(), NULL );
throw "exec failed";
// make compiler happy
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (C) Microsoft Corporation. All rights reserved.
#include "TestAppPch.h"
#include <thread>
#include <chrono>
#include <playfab/PlayFabClientApi.h>
#include <playfab/PlayFabEventsApi.h>
#include <playfab/PlayFabSettings.h>
#include <playfab/QoS/PlayFabQoSApi.h>
#include "PlayFabEventTest.h"
#include "TestContext.h"
#include "TestDataTypes.h"
using namespace PlayFab;
using namespace ClientModels;
using namespace EventsModels;
namespace PlayFabUnit
{
/// QoS API
void PlayFabEventTest::QosResultApi(TestContext& testContext)
{
QoS::PlayFabQoSApi api;
auto result = api.GetQoSResult(5, 200);
if (result.lastErrorCode == 0)
testContext.Pass();
else
{
std::string errorMessage = "Error Code:"; // Work around XBO C++/CX Platform::String^ error, which happens
errorMessage += result.lastErrorCode; // when trying to create a std::string from a string literal + int
testContext.Fail(errorMessage);
}
}
/// EVENTS API
/// Test that sends heavyweight events as a whole batch.
static EventContents CreateEventContents(const std::string& eventName, int i)
{
PlayFab::EventsModels::EventContents event;
std::stringstream name;
name << eventName << i;
event.Name = name.str();
event.EventNamespace = "com.playfab.events.default";
event.Payload["PropA"] = "prop-value-a";
event.Payload["PropB"] = "prop-value-b";
return event;
}
void PlayFabEventTest::EventsApi(TestContext& testContext)
{
if (!PlayFabClientAPI::IsClientLoggedIn())
{
testContext.Skip("Earlier tests failed to log in");
return;
}
EventsModels::WriteEventsRequest request;
// send several events
for (int i = 0; i < 2; i++)
{
request.Events.push_back(CreateEventContents("event_A_", i));
request.Events.push_back(CreateEventContents("event_B_", i));
}
PlayFabEventsAPI::WriteEvents(request,
Callback(&PlayFabEventTest::OnEventsApiSucceeded),
Callback(&PlayFabEventTest::OnEventsApiFailed),
&testContext);
}
void PlayFabEventTest::OnEventsApiSucceeded(const PlayFab::EventsModels::WriteEventsResponse&, void* customData)
{
TestContext* testContext = reinterpret_cast<TestContext*>(customData);
testContext->Pass();
}
void PlayFabEventTest::OnEventsApiFailed(const PlayFab::PlayFabError& error, void* customData)
{
TestContext* testContext = reinterpret_cast<TestContext*>(customData);
testContext->Fail(error.GenerateErrorReport());
}
/// EVENTS API
/// Shared functions & data
std::shared_ptr<TestContext*> PlayFabEventTest::eventTestContext;
size_t PlayFabEventTest::eventBatchMax;
int PlayFabEventTest::eventPassCount;
int PlayFabEventTest::eventFailCount;
std::string PlayFabEventTest::eventFailLog;
void PlayFabEventTest::EmitEventCallback(std::shared_ptr<const PlayFab::IPlayFabEvent> event, std::shared_ptr<const PlayFab::IPlayFabEmitEventResponse> response)
{
auto pfEvent = std::dynamic_pointer_cast<const PlayFab::PlayFabEvent>(event);
auto pfResponse = std::dynamic_pointer_cast<const PlayFab::PlayFabEmitEventResponse>(response);
// Handle successful event delivery.
if (PlayFab::PlayFabErrorCode::PlayFabErrorSuccess == pfResponse->playFabError->ErrorCode)
{
++eventPassCount;
eventFailLog += pfEvent->GetName() + " was sent successfully " +
"in the batch #" + std::to_string(pfResponse->batchNumber) + " "
"of " + std::to_string(pfResponse->batch->size()) + " events. "
"HTTP code: " + std::to_string(pfResponse->playFabError->HttpCode) +
", app error code: " + std::to_string(pfResponse->playFabError->ErrorCode) + "\n";
// Keep track of the highest batch number.
eventBatchMax = (pfResponse->batchNumber > eventBatchMax) ? pfResponse->batchNumber : eventBatchMax;
}
// Handle failed event delivery.
else
{
++eventFailCount;
eventFailLog += pfEvent->GetName() + " received an error back " +
"in the batch #" + std::to_string(pfResponse->batchNumber) + " "
"of " + std::to_string(pfResponse->batch->size()) + " events. "
"HTTP code: " + std::to_string(pfResponse->playFabError->HttpCode) +
", app error code: " + std::to_string(pfResponse->playFabError->ErrorCode) +
", HTTP status: " + pfResponse->playFabError->HttpStatus +
", Message: " + pfResponse->playFabError->ErrorMessage +
"\n";
}
// Complete the test once all events have been processed.
const int eventCount = eventPassCount + eventFailCount;
if (eventCount >= eventEmitCount)
{
if (eventBatchMax >= eventEmitCount)
(*eventTestContext)->Fail("Events did not batch:\n" + eventFailLog);
else if (eventFailCount > 0)
(*eventTestContext)->Fail("Events failed delivery:\n" + eventFailLog);
else
(*eventTestContext)->Pass();
}
}
void PlayFabEventTest::EmitEvents(PlayFab::PlayFabEventType eventType)
{
// Emit several events quickly.
// They will be batched up according to pipeline's settings
for (int i = 0; i < eventEmitCount; i++)
{
auto event = std::unique_ptr<PlayFab::PlayFabEvent>(new PlayFab::PlayFabEvent());
// user can specify whether it's
// - lightweight (goes to 1DS),
// - heavyweight (goes to PlayFab's WriteEvents),
// - or anything else
event->eventType = eventType;
std::stringstream name;
name << "event_" << i;
event->SetName(name.str());
event->SetProperty("prop_A", 123);
event->SetProperty("prop_B", "hello, world!");
event->SetProperty("prop_C", true);
(*eventApi)->EmitEvent(std::move(event), EmitEventCallback);
}
}
/// EVENTS API
/// PlayFab heavyweight events (emitted individually
/// and processed in a background thread using event pipeline (router, batching, etc))
void PlayFabEventTest::HeavyweightEvents(TestContext& testContext)
{
eventTestContext = std::make_shared<TestContext*>(&testContext);
// test custom event API (it uses event pipeline (router, batching, etc))
eventApi = std::make_shared<PlayFabEventAPI*>(new PlayFabEventAPI()); // create Event API instance
// adjust some pipeline settings
auto pipeline = std::dynamic_pointer_cast<PlayFab::PlayFabEventPipeline>((*eventApi)->GetEventRouter()->GetPipelines().at(PlayFab::EventPipelineKey::PlayFab)); // get PF pipeline
auto settings = pipeline->GetSettings(); // get pipeline's settings
settings->maximalBatchWaitTime = 4; // incomplete batch expiration in seconds
settings->maximalNumberOfItemsInBatch = 4; // number of events in a batch
settings->maximalNumberOfBatchesInFlight = 3; // maximal number of batches processed simultaneously by a transport plugin before taking next events from the buffer
EmitEvents(PlayFab::PlayFabEventType::Heavyweight);
}
/// EVENTS API
/// OneDS lightweight events (emitted individually
/// and processed in a background thread using event pipeline (router, batching, etc))
void PlayFabEventTest::LightweightEvents(TestContext& testContext)
{
eventTestContext = std::make_shared<TestContext*>(&testContext);
// test custom event API (it uses event pipeline (router, batching, etc))
eventApi = std::make_shared<PlayFabEventAPI*>(new PlayFabEventAPI()); // create Event API instance
// adjust some pipeline settings
auto pipeline = std::dynamic_pointer_cast<PlayFab::PlayFabEventPipeline>((*eventApi)->GetEventRouter()->GetPipelines().at(PlayFab::EventPipelineKey::OneDS)); // get OneDS pipeline
auto settings = pipeline->GetSettings(); // get pipeline's settings
settings->maximalBatchWaitTime = 2; // incomplete batch expiration in seconds
settings->maximalNumberOfItemsInBatch = 3; // number of events in a batch
settings->maximalNumberOfBatchesInFlight = 10; // maximal number of batches processed simultaneously by a transport plugin before taking next events from the buffer
EmitEvents(PlayFab::PlayFabEventType::Lightweight);
}
/// EVENTS API
/// OneDS Events API (lightweight events sent as a whole batch)
void PlayFabEventTest::OneDSEventsApi(TestContext& testContext)
{
TelemetryIngestionConfigRequest configRequest;
PlayFab::OneDSEventsAPI::GetTelemetryIngestionConfig(configRequest,
Callback(&PlayFabEventTest::OnGetTelemetryIngestionConfig),
Callback(&PlayFabEventTest::OnGetTelemetryIngestionConfigFail),
&testContext);
}
void PlayFabEventTest::OnGetTelemetryIngestionConfig(const TelemetryIngestionConfigResponse& result, void* customData)
{
// create OneDS Events API instance
PlayFab::OneDSEventsAPI api;
api.SetCredentials("o:" + result.TenantId,
result.IngestionKey,
result.TelemetryJwtToken,
result.TelemetryJwtHeaderKey,
result.TelemetryJwtHeaderPrefix);
// Prepare a batch of events
PlayFab::EventsModels::WriteEventsRequest req;
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 2; i++)
{
req.Events.push_back(CreateEventContents("event_AA_", i));
req.Events.push_back(CreateEventContents("event_BB_", i));
}
}
// Send the batch
api.WriteTelemetryEvents(req,
Callback(&PlayFabEventTest::OnOneDSWriteTelemetryEvents),
Callback(&PlayFabEventTest::OnOneDSWriteTelemetryEventsFail),
customData);
}
void PlayFabEventTest::OnGetTelemetryIngestionConfigFail(const PlayFabError& error, void* customData)
{
TestContext* testContext = reinterpret_cast<TestContext*>(customData);
testContext->Fail("GetTelemetryIngestionConfig Failed : " + error.GenerateErrorReport());
}
void PlayFabEventTest::OnOneDSWriteTelemetryEvents(const WriteEventsResponse&, void* customData)
{
TestContext* testContext = reinterpret_cast<TestContext*>(customData);
testContext->Pass();
}
void PlayFabEventTest::OnOneDSWriteTelemetryEventsFail(const PlayFabError& error, void* customData)
{
TestContext* testContext = reinterpret_cast<TestContext*>(customData);
testContext->Fail("OneDS WriteTelemetryEvents Failed : " + error.GenerateErrorReport());
}
void PlayFabEventTest::AddTests()
{
AddTest("QosResultApi", &PlayFabEventTest::QosResultApi);
AddTest("EventsApi", &PlayFabEventTest::EventsApi);
AddTest("HeavyweightEvents", &PlayFabEventTest::HeavyweightEvents);
AddTest("LightweightEvents", &PlayFabEventTest::LightweightEvents);
AddTest("OneDSEventsApi", &PlayFabEventTest::OneDSEventsApi);
}
void PlayFabEventTest::ClassSetUp()
{
// Make sure PlayFab state is clean.
PlayFabSettings::ForgetAllCredentials();
// Log in to use event functions.
LoginWithCustomIDRequest request;
request.CustomId = PlayFabSettings::buildIdentifier;
request.CreateAccount = true;
loggedIn = false;
bool loginComplete = false;
PlayFabClientAPI::LoginWithCustomID(request,
[&loginComplete](const LoginResult& /*result*/, void* customData)
{
*reinterpret_cast<bool*>(customData) = true;
loginComplete = true;
},
[&loginComplete](const PlayFabError /*error*/, void* customData)
{
*reinterpret_cast<bool*>(customData) = false;
loginComplete = true;
},
&loggedIn);
// Sleep while waiting for log in to complete.
while (!loginComplete)
{
std::this_thread::sleep_for(TimeValueMs(100));
}
}
void PlayFabEventTest::SetUp(TestContext& testContext)
{
if (!loggedIn)
testContext.Skip("Not logged in to PlayFab"); // Cannot run event tests if not logged in
// Reset event test values.
eventBatchMax = 0;
eventPassCount = 0;
eventFailCount = 0;
eventFailLog = "";
}
void PlayFabEventTest::Tick(TestContext& /*testContext*/)
{
// No work needed, async tests will end themselves
}
void PlayFabEventTest::TearDown(TestContext& /*testContext*/)
{
eventTestContext = nullptr;
eventApi = nullptr;
}
void PlayFabEventTest::ClassTearDown()
{
// Clean up any PlayFab state for next TestCase.
PlayFabSettings::ForgetAllCredentials();
}
}<commit_msg>Fix Win32 TestApp compile error (#437)<commit_after>// Copyright (C) Microsoft Corporation. All rights reserved.
#include "TestAppPch.h"
#include <thread>
#include <chrono>
#include <playfab/PlayFabClientApi.h>
#include <playfab/PlayFabEventsApi.h>
#include <playfab/PlayFabSettings.h>
#include <playfab/QoS/PlayFabQoSApi.h>
#include "PlayFabEventTest.h"
#include "TestContext.h"
#include "TestDataTypes.h"
using namespace PlayFab;
using namespace ClientModels;
using namespace EventsModels;
namespace PlayFabUnit
{
/// QoS API
void PlayFabEventTest::QosResultApi(TestContext& testContext)
{
QoS::PlayFabQoSApi api;
auto result = api.GetQoSResult(5, 200);
if (result.lastErrorCode == 0)
testContext.Pass();
else
testContext.Fail("Error Code:" + std::to_string(result.lastErrorCode));
}
/// EVENTS API
/// Test that sends heavyweight events as a whole batch.
static EventContents CreateEventContents(const std::string& eventName, int i)
{
PlayFab::EventsModels::EventContents event;
std::stringstream name;
name << eventName << i;
event.Name = name.str();
event.EventNamespace = "com.playfab.events.default";
event.Payload["PropA"] = "prop-value-a";
event.Payload["PropB"] = "prop-value-b";
return event;
}
void PlayFabEventTest::EventsApi(TestContext& testContext)
{
if (!PlayFabClientAPI::IsClientLoggedIn())
{
testContext.Skip("Earlier tests failed to log in");
return;
}
EventsModels::WriteEventsRequest request;
// send several events
for (int i = 0; i < 2; i++)
{
request.Events.push_back(CreateEventContents("event_A_", i));
request.Events.push_back(CreateEventContents("event_B_", i));
}
PlayFabEventsAPI::WriteEvents(request,
Callback(&PlayFabEventTest::OnEventsApiSucceeded),
Callback(&PlayFabEventTest::OnEventsApiFailed),
&testContext);
}
void PlayFabEventTest::OnEventsApiSucceeded(const PlayFab::EventsModels::WriteEventsResponse&, void* customData)
{
TestContext* testContext = reinterpret_cast<TestContext*>(customData);
testContext->Pass();
}
void PlayFabEventTest::OnEventsApiFailed(const PlayFab::PlayFabError& error, void* customData)
{
TestContext* testContext = reinterpret_cast<TestContext*>(customData);
testContext->Fail(error.GenerateErrorReport());
}
/// EVENTS API
/// Shared functions & data
std::shared_ptr<TestContext*> PlayFabEventTest::eventTestContext;
size_t PlayFabEventTest::eventBatchMax;
int PlayFabEventTest::eventPassCount;
int PlayFabEventTest::eventFailCount;
std::string PlayFabEventTest::eventFailLog;
void PlayFabEventTest::EmitEventCallback(std::shared_ptr<const PlayFab::IPlayFabEvent> event, std::shared_ptr<const PlayFab::IPlayFabEmitEventResponse> response)
{
auto pfEvent = std::dynamic_pointer_cast<const PlayFab::PlayFabEvent>(event);
auto pfResponse = std::dynamic_pointer_cast<const PlayFab::PlayFabEmitEventResponse>(response);
// Handle successful event delivery.
if (PlayFab::PlayFabErrorCode::PlayFabErrorSuccess == pfResponse->playFabError->ErrorCode)
{
++eventPassCount;
eventFailLog += pfEvent->GetName() + " was sent successfully " +
"in the batch #" + std::to_string(pfResponse->batchNumber) + " "
"of " + std::to_string(pfResponse->batch->size()) + " events. "
"HTTP code: " + std::to_string(pfResponse->playFabError->HttpCode) +
", app error code: " + std::to_string(pfResponse->playFabError->ErrorCode) + "\n";
// Keep track of the highest batch number.
eventBatchMax = (pfResponse->batchNumber > eventBatchMax) ? pfResponse->batchNumber : eventBatchMax;
}
// Handle failed event delivery.
else
{
++eventFailCount;
eventFailLog += pfEvent->GetName() + " received an error back " +
"in the batch #" + std::to_string(pfResponse->batchNumber) + " "
"of " + std::to_string(pfResponse->batch->size()) + " events. "
"HTTP code: " + std::to_string(pfResponse->playFabError->HttpCode) +
", app error code: " + std::to_string(pfResponse->playFabError->ErrorCode) +
", HTTP status: " + pfResponse->playFabError->HttpStatus +
", Message: " + pfResponse->playFabError->ErrorMessage +
"\n";
}
// Complete the test once all events have been processed.
const int eventCount = eventPassCount + eventFailCount;
if (eventCount >= eventEmitCount)
{
if (eventBatchMax >= eventEmitCount)
(*eventTestContext)->Fail("Events did not batch:\n" + eventFailLog);
else if (eventFailCount > 0)
(*eventTestContext)->Fail("Events failed delivery:\n" + eventFailLog);
else
(*eventTestContext)->Pass();
}
}
void PlayFabEventTest::EmitEvents(PlayFab::PlayFabEventType eventType)
{
// Emit several events quickly.
// They will be batched up according to pipeline's settings
for (int i = 0; i < eventEmitCount; i++)
{
auto event = std::unique_ptr<PlayFab::PlayFabEvent>(new PlayFab::PlayFabEvent());
// user can specify whether it's
// - lightweight (goes to 1DS),
// - heavyweight (goes to PlayFab's WriteEvents),
// - or anything else
event->eventType = eventType;
std::stringstream name;
name << "event_" << i;
event->SetName(name.str());
event->SetProperty("prop_A", 123);
event->SetProperty("prop_B", "hello, world!");
event->SetProperty("prop_C", true);
(*eventApi)->EmitEvent(std::move(event), EmitEventCallback);
}
}
/// EVENTS API
/// PlayFab heavyweight events (emitted individually
/// and processed in a background thread using event pipeline (router, batching, etc))
void PlayFabEventTest::HeavyweightEvents(TestContext& testContext)
{
eventTestContext = std::make_shared<TestContext*>(&testContext);
// test custom event API (it uses event pipeline (router, batching, etc))
eventApi = std::make_shared<PlayFabEventAPI*>(new PlayFabEventAPI()); // create Event API instance
// adjust some pipeline settings
auto pipeline = std::dynamic_pointer_cast<PlayFab::PlayFabEventPipeline>((*eventApi)->GetEventRouter()->GetPipelines().at(PlayFab::EventPipelineKey::PlayFab)); // get PF pipeline
auto settings = pipeline->GetSettings(); // get pipeline's settings
settings->maximalBatchWaitTime = 4; // incomplete batch expiration in seconds
settings->maximalNumberOfItemsInBatch = 4; // number of events in a batch
settings->maximalNumberOfBatchesInFlight = 3; // maximal number of batches processed simultaneously by a transport plugin before taking next events from the buffer
EmitEvents(PlayFab::PlayFabEventType::Heavyweight);
}
/// EVENTS API
/// OneDS lightweight events (emitted individually
/// and processed in a background thread using event pipeline (router, batching, etc))
void PlayFabEventTest::LightweightEvents(TestContext& testContext)
{
eventTestContext = std::make_shared<TestContext*>(&testContext);
// test custom event API (it uses event pipeline (router, batching, etc))
eventApi = std::make_shared<PlayFabEventAPI*>(new PlayFabEventAPI()); // create Event API instance
// adjust some pipeline settings
auto pipeline = std::dynamic_pointer_cast<PlayFab::PlayFabEventPipeline>((*eventApi)->GetEventRouter()->GetPipelines().at(PlayFab::EventPipelineKey::OneDS)); // get OneDS pipeline
auto settings = pipeline->GetSettings(); // get pipeline's settings
settings->maximalBatchWaitTime = 2; // incomplete batch expiration in seconds
settings->maximalNumberOfItemsInBatch = 3; // number of events in a batch
settings->maximalNumberOfBatchesInFlight = 10; // maximal number of batches processed simultaneously by a transport plugin before taking next events from the buffer
EmitEvents(PlayFab::PlayFabEventType::Lightweight);
}
/// EVENTS API
/// OneDS Events API (lightweight events sent as a whole batch)
void PlayFabEventTest::OneDSEventsApi(TestContext& testContext)
{
TelemetryIngestionConfigRequest configRequest;
PlayFab::OneDSEventsAPI::GetTelemetryIngestionConfig(configRequest,
Callback(&PlayFabEventTest::OnGetTelemetryIngestionConfig),
Callback(&PlayFabEventTest::OnGetTelemetryIngestionConfigFail),
&testContext);
}
void PlayFabEventTest::OnGetTelemetryIngestionConfig(const TelemetryIngestionConfigResponse& result, void* customData)
{
// create OneDS Events API instance
PlayFab::OneDSEventsAPI api;
api.SetCredentials("o:" + result.TenantId,
result.IngestionKey,
result.TelemetryJwtToken,
result.TelemetryJwtHeaderKey,
result.TelemetryJwtHeaderPrefix);
// Prepare a batch of events
PlayFab::EventsModels::WriteEventsRequest req;
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 2; i++)
{
req.Events.push_back(CreateEventContents("event_AA_", i));
req.Events.push_back(CreateEventContents("event_BB_", i));
}
}
// Send the batch
api.WriteTelemetryEvents(req,
Callback(&PlayFabEventTest::OnOneDSWriteTelemetryEvents),
Callback(&PlayFabEventTest::OnOneDSWriteTelemetryEventsFail),
customData);
}
void PlayFabEventTest::OnGetTelemetryIngestionConfigFail(const PlayFabError& error, void* customData)
{
TestContext* testContext = reinterpret_cast<TestContext*>(customData);
testContext->Fail("GetTelemetryIngestionConfig Failed : " + error.GenerateErrorReport());
}
void PlayFabEventTest::OnOneDSWriteTelemetryEvents(const WriteEventsResponse&, void* customData)
{
TestContext* testContext = reinterpret_cast<TestContext*>(customData);
testContext->Pass();
}
void PlayFabEventTest::OnOneDSWriteTelemetryEventsFail(const PlayFabError& error, void* customData)
{
TestContext* testContext = reinterpret_cast<TestContext*>(customData);
testContext->Fail("OneDS WriteTelemetryEvents Failed : " + error.GenerateErrorReport());
}
void PlayFabEventTest::AddTests()
{
AddTest("QosResultApi", &PlayFabEventTest::QosResultApi);
AddTest("EventsApi", &PlayFabEventTest::EventsApi);
AddTest("HeavyweightEvents", &PlayFabEventTest::HeavyweightEvents);
AddTest("LightweightEvents", &PlayFabEventTest::LightweightEvents);
AddTest("OneDSEventsApi", &PlayFabEventTest::OneDSEventsApi);
}
void PlayFabEventTest::ClassSetUp()
{
// Make sure PlayFab state is clean.
PlayFabSettings::ForgetAllCredentials();
// Log in to use event functions.
LoginWithCustomIDRequest request;
request.CustomId = PlayFabSettings::buildIdentifier;
request.CreateAccount = true;
loggedIn = false;
bool loginComplete = false;
PlayFabClientAPI::LoginWithCustomID(request,
[&loginComplete](const LoginResult& /*result*/, void* customData)
{
*reinterpret_cast<bool*>(customData) = true;
loginComplete = true;
},
[&loginComplete](const PlayFabError /*error*/, void* customData)
{
*reinterpret_cast<bool*>(customData) = false;
loginComplete = true;
},
&loggedIn);
// Sleep while waiting for log in to complete.
while (!loginComplete)
{
std::this_thread::sleep_for(TimeValueMs(100));
}
}
void PlayFabEventTest::SetUp(TestContext& testContext)
{
if (!loggedIn)
testContext.Skip("Not logged in to PlayFab"); // Cannot run event tests if not logged in
// Reset event test values.
eventBatchMax = 0;
eventPassCount = 0;
eventFailCount = 0;
eventFailLog = "";
}
void PlayFabEventTest::Tick(TestContext& /*testContext*/)
{
// No work needed, async tests will end themselves
}
void PlayFabEventTest::TearDown(TestContext& /*testContext*/)
{
eventTestContext = nullptr;
eventApi = nullptr;
}
void PlayFabEventTest::ClassTearDown()
{
// Clean up any PlayFab state for next TestCase.
PlayFabSettings::ForgetAllCredentials();
}
}<|endoftext|> |
<commit_before>// This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.
/** http_streambuf.cc
Jeremy Barnes, 26 November 2014
Copyright (c) 2014 Datacratic Inc. All rights reserved.
*/
#include <atomic>
#include <boost/iostreams/stream_buffer.hpp>
#include "mldb/http/http_rest_proxy.h"
#include "mldb/jml/utils/ring_buffer.h"
#include "mldb/vfs/filter_streams_registry.h"
#include "mldb/vfs/fs_utils.h"
#include "mldb/http/http_exception.h"
#include "mldb/types/basic_value_descriptions.h"
#include <chrono>
#include <future>
using namespace std;
namespace MLDB {
static FsObjectInfo
convertHeaderToInfo(const HttpHeader & header)
{
FsObjectInfo result;
if (header.responseCode() == 200) {
result.exists = true;
result.etag = header.tryGetHeader("etag");
result.size = header.contentLength;
string lastModified = header.tryGetHeader("last-modified");
if (!lastModified.empty()) {
static const char format[] = "%a, %d %b %Y %H:%M:%S %Z"; // rfc 1123
struct tm tm;
bzero(&tm, sizeof(tm));
if (strptime(lastModified.c_str(), format, &tm)) {
result.lastModified = Date(1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
}
}
return result;
}
if (header.responseCode() >= 400 && header.responseCode() < 500) {
result.exists = false;
return result;
}
throw HttpReturnException(header.responseCode(),
"Unable to convert unknown header code "
+ to_string(header.responseCode()) +
" to object info",
"code", header.responseCode());
}
struct HttpStreamingDownloadSource {
/** Create a streaming download source.
For options, the following is accepted:
http-set-cookie: sets the given header in the request to the given value.
*/
HttpStreamingDownloadSource(const std::string & urlStr,
const std::map<std::string, std::string> & options)
{
impl.reset(new Impl(urlStr, options));
impl->start();
}
~HttpStreamingDownloadSource()
{
}
/** Wait for the HTTP header to be available from the connection, and
return it.
*/
HttpHeader getHeader() const
{
auto future = impl->headerPromise.get_future();
return future.get();
}
typedef char char_type;
struct category
: //input_seekable,
boost::iostreams::input,
boost::iostreams::device_tag,
boost::iostreams::closable_tag
{ };
struct Impl {
Impl(const std::string & urlStr,
const std::map<std::string, std::string> & options)
: proxy(urlStr), urlStr(urlStr), shutdown(false), dataQueue(100),
eof(false), currentDone(0), headerSet(false)
{
for (auto & o: options) {
if (o.first == "http-set-cookie")
proxy.setCookie(o.second);
else if (o.first.find("http-") == 0)
throw MLDB::Exception("Unknown HTTP stream parameter " + o.first + " = " + o.second);
}
reset();
}
~Impl()
{
stop();
}
HttpRestProxy proxy;
std::string urlStr;
atomic<bool> shutdown;
exception_ptr lastExc;
/* Data queue */
ML::RingBufferSRMW<string> dataQueue;
atomic<bool> eof;
std::string current;
size_t currentDone;
vector<std::thread> threads; /* thread pool */
std::atomic<bool> headerSet;
std::promise<HttpHeader> headerPromise;
/* cleanup all the variables that are used during reading, the
"static" ones are left untouched */
void reset()
{
shutdown = false;
current = "";
currentDone = 0;
threads.clear();
}
void start()
{
threads.emplace_back(&Impl::runThread, this);
}
void stop()
{
shutdown = true;
while (!dataQueue.tryPush("")) {
string item;
dataQueue.tryPop(item, 0.001);
}
for (thread & th: threads) {
th.join();
}
threads.clear();
if (!headerSet) {
if (lastExc)
headerPromise.set_exception(lastExc);
else headerPromise.set_value(HttpHeader());
}
}
/* reader thread */
std::streamsize read(char_type* s, std::streamsize n)
{
if (lastExc) {
rethrow_exception(lastExc);
}
if (eof)
return -1;
if (currentDone == current.size()) {
// Get some more data
current = dataQueue.pop();
currentDone = 0;
if (current.empty()) {
if (lastExc) rethrow_exception(lastExc);
eof = true;
return -1; // shutdown or empty
}
}
if (lastExc) {
rethrow_exception(lastExc);
}
size_t toDo = min<size_t>(current.size() - currentDone, n);
const char_type * start = current.c_str() + currentDone;
std::copy(start, start + toDo, s);
currentDone += toDo;
return toDo;
}
void runThread()
{
try {
int errorCode =-1;
std::string errorBody;
bool error = false;
auto onData = [&] (const std::string & data)
{
if (error) {
errorBody = data;
return false;
}
if (shutdown)
return false;
while (!shutdown && !dataQueue.tryPush(data)) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return !shutdown;
};
auto isRedirect = [](const HttpHeader & header)
{
return header.responseCode() >= 300
&& header.responseCode() < 400;
};
auto onHeader = [&] (const HttpHeader & header)
{
// Don't set the promise on a 3xx... it's a redirect
// and we will get the correct header later on
if (!isRedirect(header)) {
if (headerSet)
throw std::logic_error("set header twice");
if (!headerSet.exchange(true)) {
this->headerPromise.set_value(header);
}
}
if (shutdown)
return false;
//cerr << "got header " << header << endl;
errorCode = header.responseCode();
if (header.responseCode() != 200 && !isRedirect(header))
error = true;
return !shutdown;
};
auto resp = proxy.get("", {}, {}, -1 /* timeout */,
false /* exceptions */,
onData, onHeader,
true /* follow redirect */);
if (shutdown)
return;
if (resp.code() != 200) {
cerr << "resp.errorCode_ = " << resp.errorCode() << endl;
cerr << "resp.errorMessage = " << resp.errorMessage() << endl;
throw MLDB::Exception("HTTP code %d reading %s\n\n%s",
}
dataQueue.push("");
} catch (const std::exception & exc) {
lastExc = std::current_exception();
dataQueue.tryPush("");
if (!headerSet.exchange(true)) {
headerPromise.set_exception(lastExc);
}
}
}
};
std::shared_ptr<Impl> impl;
std::streamsize read(char_type* s, std::streamsize n)
{
return impl->read(s, n);
}
bool is_open() const
{
return !!impl;
}
void close()
{
impl.reset();
}
};
std::pair<std::unique_ptr<std::streambuf>, FsObjectInfo>
makeHttpStreamingDownload(const std::string & uri,
const std::map<std::string, std::string> & options)
{
std::unique_ptr<std::streambuf> result;
HttpStreamingDownloadSource source(uri, options);
const HttpHeader & header = source.getHeader();
result.reset(new boost::iostreams::stream_buffer<HttpStreamingDownloadSource>
(source, 131072));
return { std::move(result), convertHeaderToInfo(header) };
}
struct HttpUrlFsHandler: UrlFsHandler {
HttpRestProxy proxy;
virtual FsObjectInfo getInfo(const Url & url) const
{
auto info = tryGetInfo(url);
if (!info)
throw MLDB::Exception("Couldn't get URI info for " + url.toString());
return info;
}
virtual FsObjectInfo tryGetInfo(const Url & url) const
{
HttpHeader header;
FsObjectInfo result;
HttpRestProxy::Response resp;
bool didGetHeader = false;
for (unsigned attempt = 0; attempt < 5; ++attempt) {
if (attempt != 0)
std::this_thread::sleep_for(std::chrono::milliseconds(100 * attempt + random() % 100));
didGetHeader = false;
auto onHeader = [&] (const HttpHeader & gotHeader)
{
header = gotHeader;
didGetHeader = true;
// Return false to make CURL stop after the header
//return false;
return true;
};
resp = proxy.perform("HEAD", url.toDecodedString(),
HttpRestProxy::Content(),
{}, {}, 1.0, false, nullptr, onHeader,
true /* follow redirects */);
if (!didGetHeader && resp.errorCode() != 0) {
cerr << "error retrieving HEAD (retry) " << url.toString() << ": "
<< resp.errorMessage() << endl;
continue; // didn't get header; retry
}
#if 0
cerr << "header = " << header << endl;
cerr << "resp = " << resp << endl;
cerr << "resp.responseCode = " << resp.code_ << endl;
cerr << "resp.errorCode = " << resp.errorCode() << endl;
cerr << "resp.errorMessage = " << resp.errorMessage() << endl;
cerr << "header.responseCode() = " << header.responseCode() << endl;
#endif
if (header.responseCode() >= 200 && header.responseCode() < 500) {
return convertHeaderToInfo(header);
}
if (header.responseCode() >= 500 && header.responseCode() < 600) {
continue;
}
cerr << "don't know what to do with response code "
<< header.responseCode()
<< " from HEAD" << endl;
}
throw MLDB::Exception("Couldn't reach server to determine HEAD of '"
+ url.toString() + "': HTTP code "
+ (didGetHeader ? to_string(header.responseCode()) : string("(unknown)"))
+ " " + resp.errorMessage());
//if (resp.hasHeader("content-type"))
// result.contentType = resp.getHeader("content-type");
//cerr << "result = " << result.lastModified << endl;
return result;
}
virtual size_t getSize(const Url & url) const
{
return getInfo(url).size;
}
virtual std::string getEtag(const Url & url) const
{
return getInfo(url).etag;
}
virtual void makeDirectory(const Url & url) const
{
// no-op
}
virtual bool erase(const Url & url, bool throwException) const
{
throw MLDB::Exception("Http URIs don't support DELETE");
}
/** For each object under the given prefix (object or subdirectory),
call the given callback.
*/
virtual bool forEach(const Url & prefix,
const OnUriObject & onObject,
const OnUriSubdir & onSubdir,
const std::string & delimiter,
const std::string & startAt) const
{
throw MLDB::Exception("Http URIs don't support listing");
}
};
/** Register Http with the filter streams API so that a filter_stream can be
used to treat an Http object as a simple stream.
*/
struct RegisterHttpHandler {
static UriHandler
getHttpHandler(const std::string & scheme,
const std::string & resource,
std::ios_base::open_mode mode,
const std::map<std::string, std::string> & options,
const OnUriHandlerException & onException)
{
string::size_type pos = resource.find('/');
if (pos == string::npos)
throw MLDB::Exception("unable to find http bucket name in resource "
+ resource);
string bucket(resource, 0, pos);
if (mode == ios::in) {
std::pair<std::unique_ptr<std::streambuf>, FsObjectInfo> sb_info
= makeHttpStreamingDownload(scheme+"://"+resource, options);
std::shared_ptr<std::streambuf> buf(sb_info.first.release());
return UriHandler(buf.get(), buf, sb_info.second);
}
else if (mode == ios::out) {
throw MLDB::Exception("Can't currently upload files via HTTP/HTTPs");
}
else throw MLDB::Exception("no way to create http handler for non in/out");
}
RegisterHttpHandler()
{
registerUriHandler("http", getHttpHandler);
registerUriHandler("https", getHttpHandler);
registerUrlFsHandler("http", new HttpUrlFsHandler());
registerUrlFsHandler("https", new HttpUrlFsHandler());
}
} registerHttpHandler;
} // namespace MLDB
<commit_msg>Fixup for http_streambuf fixes<commit_after>// This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.
/** http_streambuf.cc
Jeremy Barnes, 26 November 2014
Copyright (c) 2014 Datacratic Inc. All rights reserved.
*/
#include <atomic>
#include <boost/iostreams/stream_buffer.hpp>
#include "mldb/http/http_rest_proxy.h"
#include "mldb/jml/utils/ring_buffer.h"
#include "mldb/vfs/filter_streams_registry.h"
#include "mldb/vfs/fs_utils.h"
#include "mldb/http/http_exception.h"
#include "mldb/types/basic_value_descriptions.h"
#include <chrono>
#include <future>
using namespace std;
namespace MLDB {
static FsObjectInfo
convertHeaderToInfo(const HttpHeader & header)
{
FsObjectInfo result;
if (header.responseCode() == 200) {
result.exists = true;
result.etag = header.tryGetHeader("etag");
result.size = header.contentLength;
string lastModified = header.tryGetHeader("last-modified");
if (!lastModified.empty()) {
static const char format[] = "%a, %d %b %Y %H:%M:%S %Z"; // rfc 1123
struct tm tm;
bzero(&tm, sizeof(tm));
if (strptime(lastModified.c_str(), format, &tm)) {
result.lastModified = Date(1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
}
}
return result;
}
if (header.responseCode() >= 400 && header.responseCode() < 500) {
result.exists = false;
return result;
}
throw HttpReturnException(header.responseCode(),
"Unable to convert unknown header code "
+ to_string(header.responseCode()) +
" to object info",
"code", header.responseCode());
}
struct HttpStreamingDownloadSource {
/** Create a streaming download source.
For options, the following is accepted:
http-set-cookie: sets the given header in the request to the given value.
*/
HttpStreamingDownloadSource(const std::string & urlStr,
const std::map<std::string, std::string> & options)
{
impl.reset(new Impl(urlStr, options));
impl->start();
}
~HttpStreamingDownloadSource()
{
}
/** Wait for the HTTP header to be available from the connection, and
return it.
*/
HttpHeader getHeader() const
{
auto future = impl->headerPromise.get_future();
return future.get();
}
typedef char char_type;
struct category
: //input_seekable,
boost::iostreams::input,
boost::iostreams::device_tag,
boost::iostreams::closable_tag
{ };
struct Impl {
Impl(const std::string & urlStr,
const std::map<std::string, std::string> & options)
: proxy(urlStr), urlStr(urlStr), shutdown(false), dataQueue(100),
eof(false), currentDone(0), headerSet(false)
{
for (auto & o: options) {
if (o.first == "http-set-cookie")
proxy.setCookie(o.second);
else if (o.first.find("http-") == 0)
throw MLDB::Exception("Unknown HTTP stream parameter " + o.first + " = " + o.second);
}
reset();
}
~Impl()
{
stop();
}
HttpRestProxy proxy;
std::string urlStr;
atomic<bool> shutdown;
exception_ptr lastExc;
/* Data queue */
ML::RingBufferSRMW<string> dataQueue;
atomic<bool> eof;
std::string current;
size_t currentDone;
vector<std::thread> threads; /* thread pool */
std::atomic<bool> headerSet;
std::promise<HttpHeader> headerPromise;
/* cleanup all the variables that are used during reading, the
"static" ones are left untouched */
void reset()
{
shutdown = false;
current = "";
currentDone = 0;
threads.clear();
}
void start()
{
threads.emplace_back(&Impl::runThread, this);
}
void stop()
{
shutdown = true;
while (!dataQueue.tryPush("")) {
string item;
dataQueue.tryPop(item, 0.001);
}
for (thread & th: threads) {
th.join();
}
threads.clear();
if (!headerSet) {
if (lastExc)
headerPromise.set_exception(lastExc);
else headerPromise.set_value(HttpHeader());
}
}
/* reader thread */
std::streamsize read(char_type* s, std::streamsize n)
{
if (lastExc) {
rethrow_exception(lastExc);
}
if (eof)
return -1;
if (currentDone == current.size()) {
// Get some more data
current = dataQueue.pop();
currentDone = 0;
if (current.empty()) {
if (lastExc) rethrow_exception(lastExc);
eof = true;
return -1; // shutdown or empty
}
}
if (lastExc) {
rethrow_exception(lastExc);
}
size_t toDo = min<size_t>(current.size() - currentDone, n);
const char_type * start = current.c_str() + currentDone;
std::copy(start, start + toDo, s);
currentDone += toDo;
return toDo;
}
void runThread()
{
try {
int errorCode =-1;
std::string errorBody;
bool error = false;
auto onData = [&] (const std::string & data)
{
if (error) {
errorBody = data;
return false;
}
if (shutdown)
return false;
while (!shutdown && !dataQueue.tryPush(data)) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return !shutdown;
};
auto isRedirect = [](const HttpHeader & header)
{
return header.responseCode() >= 300
&& header.responseCode() < 400;
};
auto onHeader = [&] (const HttpHeader & header)
{
// Don't set the promise on a 3xx... it's a redirect
// and we will get the correct header later on
if (!isRedirect(header)) {
if (headerSet)
throw std::logic_error("set header twice");
if (!headerSet.exchange(true)) {
this->headerPromise.set_value(header);
}
}
if (shutdown)
return false;
//cerr << "got header " << header << endl;
errorCode = header.responseCode();
if (header.responseCode() != 200 && !isRedirect(header))
error = true;
return !shutdown;
};
auto resp = proxy.get("", {}, {}, -1 /* timeout */,
false /* exceptions */,
onData, onHeader,
true /* follow redirect */);
if (shutdown)
return;
if (resp.code() != 200) {
cerr << "resp.errorCode_ = " << resp.errorCode() << endl;
cerr << "resp.errorMessage = " << resp.errorMessage() << endl;
throw MLDB::Exception("HTTP code %d reading %s\n\n%s",
resp.code(),
urlStr.c_str(),
resp.errorMessage().c_str());
}
dataQueue.push("");
} catch (const std::exception & exc) {
lastExc = std::current_exception();
dataQueue.tryPush("");
if (!headerSet.exchange(true)) {
headerPromise.set_exception(lastExc);
}
}
}
};
std::shared_ptr<Impl> impl;
std::streamsize read(char_type* s, std::streamsize n)
{
return impl->read(s, n);
}
bool is_open() const
{
return !!impl;
}
void close()
{
impl.reset();
}
};
std::pair<std::unique_ptr<std::streambuf>, FsObjectInfo>
makeHttpStreamingDownload(const std::string & uri,
const std::map<std::string, std::string> & options)
{
std::unique_ptr<std::streambuf> result;
HttpStreamingDownloadSource source(uri, options);
const HttpHeader & header = source.getHeader();
result.reset(new boost::iostreams::stream_buffer<HttpStreamingDownloadSource>
(source, 131072));
return { std::move(result), convertHeaderToInfo(header) };
}
struct HttpUrlFsHandler: UrlFsHandler {
HttpRestProxy proxy;
virtual FsObjectInfo getInfo(const Url & url) const
{
auto info = tryGetInfo(url);
if (!info)
throw MLDB::Exception("Couldn't get URI info for " + url.toString());
return info;
}
virtual FsObjectInfo tryGetInfo(const Url & url) const
{
HttpHeader header;
FsObjectInfo result;
HttpRestProxy::Response resp;
bool didGetHeader = false;
for (unsigned attempt = 0; attempt < 5; ++attempt) {
if (attempt != 0)
std::this_thread::sleep_for(std::chrono::milliseconds(100 * attempt + random() % 100));
didGetHeader = false;
auto onHeader = [&] (const HttpHeader & gotHeader)
{
header = gotHeader;
didGetHeader = true;
// Return false to make CURL stop after the header
//return false;
return true;
};
resp = proxy.perform("HEAD", url.toDecodedString(),
HttpRestProxy::Content(),
{}, {}, 1.0, false, nullptr, onHeader,
true /* follow redirects */);
if (!didGetHeader && resp.errorCode() != 0) {
cerr << "error retrieving HEAD (retry) " << url.toString() << ": "
<< resp.errorMessage() << endl;
continue; // didn't get header; retry
}
#if 0
cerr << "header = " << header << endl;
cerr << "resp = " << resp << endl;
cerr << "resp.responseCode = " << resp.code_ << endl;
cerr << "resp.errorCode = " << resp.errorCode() << endl;
cerr << "resp.errorMessage = " << resp.errorMessage() << endl;
cerr << "header.responseCode() = " << header.responseCode() << endl;
#endif
if (header.responseCode() >= 200 && header.responseCode() < 500) {
return convertHeaderToInfo(header);
}
if (header.responseCode() >= 500 && header.responseCode() < 600) {
continue;
}
cerr << "don't know what to do with response code "
<< header.responseCode()
<< " from HEAD" << endl;
}
throw MLDB::Exception("Couldn't reach server to determine HEAD of '"
+ url.toString() + "': HTTP code "
+ (didGetHeader ? to_string(header.responseCode()) : string("(unknown)"))
+ " " + resp.errorMessage());
//if (resp.hasHeader("content-type"))
// result.contentType = resp.getHeader("content-type");
//cerr << "result = " << result.lastModified << endl;
return result;
}
virtual size_t getSize(const Url & url) const
{
return getInfo(url).size;
}
virtual std::string getEtag(const Url & url) const
{
return getInfo(url).etag;
}
virtual void makeDirectory(const Url & url) const
{
// no-op
}
virtual bool erase(const Url & url, bool throwException) const
{
throw MLDB::Exception("Http URIs don't support DELETE");
}
/** For each object under the given prefix (object or subdirectory),
call the given callback.
*/
virtual bool forEach(const Url & prefix,
const OnUriObject & onObject,
const OnUriSubdir & onSubdir,
const std::string & delimiter,
const std::string & startAt) const
{
throw MLDB::Exception("Http URIs don't support listing");
}
};
/** Register Http with the filter streams API so that a filter_stream can be
used to treat an Http object as a simple stream.
*/
struct RegisterHttpHandler {
static UriHandler
getHttpHandler(const std::string & scheme,
const std::string & resource,
std::ios_base::open_mode mode,
const std::map<std::string, std::string> & options,
const OnUriHandlerException & onException)
{
string::size_type pos = resource.find('/');
if (pos == string::npos)
throw MLDB::Exception("unable to find http bucket name in resource "
+ resource);
string bucket(resource, 0, pos);
if (mode == ios::in) {
std::pair<std::unique_ptr<std::streambuf>, FsObjectInfo> sb_info
= makeHttpStreamingDownload(scheme+"://"+resource, options);
std::shared_ptr<std::streambuf> buf(sb_info.first.release());
return UriHandler(buf.get(), buf, sb_info.second);
}
else if (mode == ios::out) {
throw MLDB::Exception("Can't currently upload files via HTTP/HTTPs");
}
else throw MLDB::Exception("no way to create http handler for non in/out");
}
RegisterHttpHandler()
{
registerUriHandler("http", getHttpHandler);
registerUriHandler("https", getHttpHandler);
registerUrlFsHandler("http", new HttpUrlFsHandler());
registerUrlFsHandler("https", new HttpUrlFsHandler());
}
} registerHttpHandler;
} // namespace MLDB
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sync.h"
#include "util.h"
#include <stdio.h>
#include <set>
#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
{
LogPrintf("LOCKCONTENTION: %s\n", pszName);
LogPrintf("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */
#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
// Problem being solved:
// Thread 1 locks A, then B, then C
// Thread 2 locks D, then C, then A
// --> may result in deadlock between the two threads, depending on when they run.
// Solution implemented here:
// Keep track of pairs of locks: (A before B), (A before C), etc.
// Complain if any thread tries to lock in a different order.
//
struct CLockLocation {
CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn)
{
mutexName = pszName;
sourceFile = pszFile;
sourceLine = nLine;
fTry = fTryIn;
}
std::string ToString() const
{
return mutexName + " " + sourceFile + ":" + ::ToString(sourceLine) + (fTry ? " (TRY)" : "");
}
private:
bool fTry;
std::string mutexName;
std::string sourceFile;
int sourceLine;
};
typedef std::vector<std::pair<void*, CLockLocation> > LockStack;
typedef std::map<std::pair<void*, void*>, LockStack> LockOrders;
typedef std::set<std::pair<void*, void*> > InvLockOrders;
struct LockData {
// Very ugly hack: as the global constructs and destructors run single
// threaded, we use this boolean to know whether LockData still exists,
// as DeleteLock can get called by global CCriticalSection destructors
// after LockData disappears.
bool available;
LockData() : available(true) {}
~LockData() { available = false; }
LockOrders lockorders;
InvLockOrders invlockorders;
std::mutex dd_mutex;
} static lockdata;
static thread_local std::unique_ptr<LockStack> lockstack;
static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
{
LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
LogPrintf("Previous lock order was:\n");
for (const std::pair<void*, CLockLocation> & i : s2) {
if (i.first == mismatch.first) {
LogPrintf(" (1)");
}
if (i.first == mismatch.second) {
LogPrintf(" (2)");
}
LogPrintf(" %s\n", i.second.ToString());
}
LogPrintf("Current lock order is:\n");
for (const std::pair<void*, CLockLocation> & i : s1) {
if (i.first == mismatch.first) {
LogPrintf(" (1)");
}
if (i.first == mismatch.second) {
LogPrintf(" (2)");
}
LogPrintf(" %s\n", i.second.ToString());
}
assert(false);
}
static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{
if (!lockstack)
lockstack.reset(new LockStack);
std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
lockstack->push_back(std::make_pair(c, locklocation));
for (const std::pair<void*, CLockLocation> & i : (*lockstack)) {
if (i.first == c)
break;
std::pair<void*, void*> p1 = std::make_pair(i.first, c);
if (lockdata.lockorders.count(p1))
continue;
lockdata.lockorders[p1] = (*lockstack);
std::pair<void*, void*> p2 = std::make_pair(c, i.first);
lockdata.invlockorders.insert(p2);
if (lockdata.lockorders.count(p2))
potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]);
}
}
static void pop_lock()
{
(*lockstack).pop_back();
}
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
{
push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry), fTry);
}
void LeaveCritical()
{
pop_lock();
}
std::string LocksHeld()
{
std::string result;
for (const std::pair<void*, CLockLocation> & i : *lockstack)
result += i.second.ToString() + std::string("\n");
return result;
}
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
{
for (const std::pair<void*, CLockLocation> & i : *lockstack)
if (i.first == cs)
return;
fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld());
abort();
}
void DeleteLock(void* cs)
{
if (!lockdata.available) {
// We're already shutting down.
return;
}
std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
std::pair<void*, void*> item = std::make_pair(cs, (void*)0);
LockOrders::iterator it = lockdata.lockorders.lower_bound(item);
while (it != lockdata.lockorders.end() && it->first.first == cs) {
std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);
lockdata.invlockorders.erase(invitem);
lockdata.lockorders.erase(it++);
}
InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item);
while (invit != lockdata.invlockorders.end() && invit->first == cs) {
std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first);
lockdata.lockorders.erase(invinvitem);
lockdata.invlockorders.erase(invit++);
}
}
#endif /* DEBUG_LOCKORDER */
<commit_msg>add missing memory header that can break potential builds on some systems<commit_after>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sync.h"
#include "util.h"
#include <stdio.h>
#include <set>
#include <memory>
#ifdef DEBUG_LOCKCONTENTION
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
{
LogPrintf("LOCKCONTENTION: %s\n", pszName);
LogPrintf("Locker: %s:%d\n", pszFile, nLine);
}
#endif /* DEBUG_LOCKCONTENTION */
#ifdef DEBUG_LOCKORDER
//
// Early deadlock detection.
// Problem being solved:
// Thread 1 locks A, then B, then C
// Thread 2 locks D, then C, then A
// --> may result in deadlock between the two threads, depending on when they run.
// Solution implemented here:
// Keep track of pairs of locks: (A before B), (A before C), etc.
// Complain if any thread tries to lock in a different order.
//
struct CLockLocation {
CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn)
{
mutexName = pszName;
sourceFile = pszFile;
sourceLine = nLine;
fTry = fTryIn;
}
std::string ToString() const
{
return mutexName + " " + sourceFile + ":" + ::ToString(sourceLine) + (fTry ? " (TRY)" : "");
}
private:
bool fTry;
std::string mutexName;
std::string sourceFile;
int sourceLine;
};
typedef std::vector<std::pair<void*, CLockLocation> > LockStack;
typedef std::map<std::pair<void*, void*>, LockStack> LockOrders;
typedef std::set<std::pair<void*, void*> > InvLockOrders;
struct LockData {
// Very ugly hack: as the global constructs and destructors run single
// threaded, we use this boolean to know whether LockData still exists,
// as DeleteLock can get called by global CCriticalSection destructors
// after LockData disappears.
bool available;
LockData() : available(true) {}
~LockData() { available = false; }
LockOrders lockorders;
InvLockOrders invlockorders;
std::mutex dd_mutex;
} static lockdata;
static thread_local std::unique_ptr<LockStack> lockstack;
static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
{
LogPrintf("POTENTIAL DEADLOCK DETECTED\n");
LogPrintf("Previous lock order was:\n");
for (const std::pair<void*, CLockLocation> & i : s2) {
if (i.first == mismatch.first) {
LogPrintf(" (1)");
}
if (i.first == mismatch.second) {
LogPrintf(" (2)");
}
LogPrintf(" %s\n", i.second.ToString());
}
LogPrintf("Current lock order is:\n");
for (const std::pair<void*, CLockLocation> & i : s1) {
if (i.first == mismatch.first) {
LogPrintf(" (1)");
}
if (i.first == mismatch.second) {
LogPrintf(" (2)");
}
LogPrintf(" %s\n", i.second.ToString());
}
assert(false);
}
static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
{
if (!lockstack)
lockstack.reset(new LockStack);
std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
lockstack->push_back(std::make_pair(c, locklocation));
for (const std::pair<void*, CLockLocation> & i : (*lockstack)) {
if (i.first == c)
break;
std::pair<void*, void*> p1 = std::make_pair(i.first, c);
if (lockdata.lockorders.count(p1))
continue;
lockdata.lockorders[p1] = (*lockstack);
std::pair<void*, void*> p2 = std::make_pair(c, i.first);
lockdata.invlockorders.insert(p2);
if (lockdata.lockorders.count(p2))
potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]);
}
}
static void pop_lock()
{
(*lockstack).pop_back();
}
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
{
push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry), fTry);
}
void LeaveCritical()
{
pop_lock();
}
std::string LocksHeld()
{
std::string result;
for (const std::pair<void*, CLockLocation> & i : *lockstack)
result += i.second.ToString() + std::string("\n");
return result;
}
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs)
{
for (const std::pair<void*, CLockLocation> & i : *lockstack)
if (i.first == cs)
return;
fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld());
abort();
}
void DeleteLock(void* cs)
{
if (!lockdata.available) {
// We're already shutting down.
return;
}
std::lock_guard<std::mutex> lock(lockdata.dd_mutex);
std::pair<void*, void*> item = std::make_pair(cs, (void*)0);
LockOrders::iterator it = lockdata.lockorders.lower_bound(item);
while (it != lockdata.lockorders.end() && it->first.first == cs) {
std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first);
lockdata.invlockorders.erase(invitem);
lockdata.lockorders.erase(it++);
}
InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item);
while (invit != lockdata.invlockorders.end() && invit->first == cs) {
std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first);
lockdata.lockorders.erase(invinvitem);
lockdata.invlockorders.erase(invit++);
}
}
#endif /* DEBUG_LOCKORDER */
<|endoftext|> |
<commit_before>// primes.cpp : Defines the entry point for the console application.
//
#include <stdio.h>
bool is_prime(int);
char key[1024];
int main(int argc, char* argv[])
{
int print_threshold = 10000, threshold_interval = 10000;
for (int i = 0; i < 300000; i++) {
if (is_prime(i)) {
if (i > print_threshold) {
printf("%d\n", i);
print_threshold += threshold_interval;
}
}
}
// printf("Press Enter to continue\n");
// getchar();
return 0;
}
bool is_prime(int n)
{
for (int i = 2; i < n; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}<commit_msg>changed tabs to spaces<commit_after>// primes.cpp : Defines the entry point for the console application.
//
#include <stdio.h>
bool is_prime(int);
char key[1024];
int main(int argc, char* argv[])
{
int print_threshold = 10000, threshold_interval = 10000;
for (int i = 0; i < 300000; i++) {
if (is_prime(i)) {
if (i > print_threshold) {
printf("%d\n", i);
print_threshold += threshold_interval;
}
}
}
// printf("Press Enter to continue\n");
// getchar();
return 0;
}
bool is_prime(int n)
{
for (int i = 2; i < n; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}<|endoftext|> |
<commit_before>#include <ygo/deck/User.h>
#include <ygo/deck/DB.h>
#include <ygo/deck/DeckSet.h>
#include <mindbw/SQLite3.h>
#include <ygo/data/Serialize.h>
#include <cassert>
#include <stdexcept>
namespace ygo
{
namespace deck
{
User::User(std::string name, bool create) :
mName(std::move(name))
{
// check if the user already exists
auto exists = false;
std::string userid;
mindbw::SQLite3 db(DB::get().path());
db.select(mindbw::KeyList({"name","user_id"}),"users",
mindbw::Equal("name",mName),
[&](mindbw::DataMap data) {
exists = true;
userid = data["user_id"];
});
if (exists) {
mID = userid;
} else if (create) {
mID = db.insert("users",mindbw::ValueList({mName}));
} else {
throw std::runtime_error("User " + mName + " does not exist");
}
}
std::vector<DeckSet> User::deckSets() const
{
// return all deck sets for a given user
std::vector<std::string> deckids;
assert(!DB::get().path().empty());
mindbw::SQLite3 db(DB::get().path());
db.select("deck_set_id","user_to_decks",
mindbw::Equal("user_id",id()),
[&](mindbw::DataMap data) {
deckids.push_back(data["deck_set_id"]);
});
// look up the deck set ids and convert them into objects
std::vector<DeckSet> ret;
for (auto&& i : deckids) {
db.select(mindbw::All(),"deck_set",
mindbw::Equal("deck_set_id",i),
[&](mindbw::DataMap data) {
// extract the format
Format f(data::toFormat(data["format"]),
data["format_date"]);
// add a new DBDeckSet
ret.emplace_back(DeckSet{data["name"],*this,f});
});
}
return ret;
}
void User::remove()
{
// delete all the deck sets associated with this user
auto sets = deckSets();
for (auto&& s : sets) {
s.remove();
}
// delete the user
mindbw::SQLite3 db(DB::get().path());
db.del("users",mindbw::Equal("user_id",mID));
}
}
}
<commit_msg>Android returns multiple deck_set_ids<commit_after>#include <ygo/deck/User.h>
#include <ygo/deck/DB.h>
#include <ygo/deck/DeckSet.h>
#include <mindbw/SQLite3.h>
#include <ygo/data/Serialize.h>
#include <cassert>
#include <stdexcept>
namespace ygo
{
namespace deck
{
User::User(std::string name, bool create) :
mName(std::move(name))
{
// check if the user already exists
auto exists = false;
std::string userid;
mindbw::SQLite3 db(DB::get().path());
db.select(mindbw::KeyList({"name","user_id"}),"users",
mindbw::Equal("name",mName),
[&](mindbw::DataMap data) {
exists = true;
userid = data["user_id"];
});
if (exists) {
mID = userid;
} else if (create) {
mID = db.insert("users",mindbw::ValueList({mName}));
} else {
throw std::runtime_error("User " + mName + " does not exist");
}
}
std::vector<DeckSet> User::deckSets() const
{
// return all deck sets for a given user
std::vector<std::string> deckids;
assert(!DB::get().path().empty());
mindbw::SQLite3 db(DB::get().path());
db.select(mindbw::Unique("deck_set_id"),"user_to_decks",
mindbw::Equal("user_id",id()),
[&](mindbw::DataMap data) {
deckids.push_back(data["deck_set_id"]);
});
// look up the deck set ids and convert them into objects
std::vector<DeckSet> ret;
for (auto&& i : deckids) {
db.select(mindbw::All(),"deck_set",
mindbw::Equal("deck_set_id",i),
[&](mindbw::DataMap data) {
// extract the format
Format f(data::toFormat(data["format"]),
data["format_date"]);
// add a new DBDeckSet
ret.emplace_back(DeckSet{data["name"],*this,f});
});
}
return ret;
}
void User::remove()
{
// delete all the deck sets associated with this user
auto sets = deckSets();
for (auto&& s : sets) {
s.remove();
}
// delete the user
mindbw::SQLite3 db(DB::get().path());
db.del("users",mindbw::Equal("user_id",mID));
}
}
}
<|endoftext|> |
<commit_before>#include <Poco/Exception.h>
#include <Poco/Logger.h>
#include <Poco/Nullable.h>
#include <Poco/Timestamp.h>
#include "di/Injectable.h"
#include "model/Device.h"
#include "model/Gateway.h"
#include "service/DeviceServiceImpl.h"
#include "work/DeviceUnpairWork.h"
#include "work/WorkFacade.h"
BEEEON_OBJECT_BEGIN(BeeeOn, DeviceServiceImpl)
BEEEON_OBJECT_CASTABLE(DeviceService)
BEEEON_OBJECT_REF("deviceDao", &DeviceServiceImpl::setDeviceDao)
BEEEON_OBJECT_REF("controlDao", &DeviceServiceImpl::setControlDao)
BEEEON_OBJECT_REF("sensorHistoryDao", &DeviceServiceImpl::setSensorHistoryDao)
BEEEON_OBJECT_REF("devicePropertyDao", &DeviceServiceImpl::setDevicePropertyDao)
BEEEON_OBJECT_REF("gatewayRPC", &DeviceServiceImpl::setGatewayRPC)
BEEEON_OBJECT_REF("accessPolicy", &DeviceServiceImpl::setAccessPolicy)
BEEEON_OBJECT_REF("workFacade", &DeviceServiceImpl::setWorkFacade)
BEEEON_OBJECT_REF("transactionManager", &DeviceServiceImpl::setTransactionManager)
BEEEON_OBJECT_END(BeeeOn, DeviceServiceImpl)
using namespace std;
using namespace Poco;
using namespace BeeeOn;
DeviceServiceImpl::DeviceServiceImpl()
{
}
void DeviceServiceImpl::setDeviceDao(DeviceDao::Ptr dao)
{
m_dao = dao;
}
void DeviceServiceImpl::setControlDao(ControlDao::Ptr dao)
{
m_controlDao = dao;
}
void DeviceServiceImpl::setSensorHistoryDao(SensorHistoryDao::Ptr dao)
{
m_historyDao = dao;
}
void DeviceServiceImpl::setDevicePropertyDao(DevicePropertyDao::Ptr dao)
{
m_propertyDao = dao;
}
void DeviceServiceImpl::setGatewayRPC(GatewayRPC::Ptr rpc)
{
m_gatewayRPC = rpc;
}
void DeviceServiceImpl::setWorkFacade(WorkFacade::Ptr facade)
{
m_workFacade = facade;
}
void DeviceServiceImpl::setAccessPolicy(DeviceAccessPolicy::Ptr policy)
{
m_policy = policy;
}
bool DeviceServiceImpl::doFetch(Relation<Device, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.target(), input.base());
return m_dao->fetch(input.target(), input.base());
}
void DeviceServiceImpl::valuesFor(DeviceWithData &device)
{
// fetch last value of all device modules
vector<ModuleInfo> sensors;
list<Control> controls;
size_t count = 0;
for (const auto &info : *device.type()) {
if (info.isControllable())
controls.emplace_back(Control{info.id()});
else
sensors.emplace_back(info);
count += 1;
}
// values of all modules
vector<ValueAt> values(count);
// a null result means that there is no data for that sensor yet
vector<Nullable<ValueAt>> nullableValues;
m_historyDao->fetchMany(device, sensors, nullableValues);
size_t i = 0;
for (const auto &sensor : sensors) {
const auto ¤t = nullableValues.at(i++);
const unsigned int index = sensor.id();
if (!current.isNull())
values[index] = current;
// else leave the value as invalid
}
m_controlDao->fetchBy(controls, device);
for (const auto &control : controls) {
const unsigned int index = control.id();
const auto &confirmed = control.lastConfirmed();
if (!confirmed.isNull()) {
const Control::State &state = confirmed;
values[index] = {state.at().value(), state.value()};
}
// else leave the value as invalid
}
device.setValues(values);
}
void DeviceServiceImpl::doFetchMany(Single<list<Device>> &input)
{
m_policy->assureMany(DeviceAccessPolicy::ACTION_USER_GET,
input, input.target());
list<Device> &devices = input.target();
m_dao->fetchMany(devices);
}
void DeviceServiceImpl::doFetchMany(Single<list<DeviceWithData>> &input)
{
list<Device> devices;
for (const auto &dev : input.target())
devices.emplace_back(dev);
m_dao->fetchMany(devices);
// convert to list of DeviceWithData
list<DeviceWithData> result;
for (const auto &dev : devices) {
DeviceWithData device = dev;
try {
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, device, device.gateway());
} catch (const InvalidAccessException &e) {
continue;
}
valuesFor(device);
result.emplace_back(device);
}
input.target() = result;
}
void DeviceServiceImpl::doFetchMany(Relation<list<Device>, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET, input, input.base());
list<Device> &devices = input.target();
m_dao->fetchMany(devices);
list<Device>::iterator it = devices.begin();
while (it != devices.end()) {
Device &device = *it;
try {
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, device, input.base());
} catch (const InvalidAccessException &e) {
// drop inaccessible devices
it = devices.erase(it);
continue;
}
++it; // no erase occured, continue
}
}
/**
* The method performs 1 + 2 * N Dao requests where N is the number of devices.
* The first query obtains list of Device instances. Because we need a list
* of DeviceWithData instances, the loop would convert it. The conversion
* fetches module data for every single device.
*
* The method should be optimized (moved to Dao layer) if needed.
*/
void DeviceServiceImpl::doFetchMany(Relation<list<DeviceWithData>, Gateway> &input)
{
// fetch list of Devices
list<Device> devices;
for (const auto &dev : input.target())
devices.emplace_back(dev);
m_policy->assureMany(DeviceAccessPolicy::ACTION_USER_GET, input, devices);
m_dao->fetchMany(devices);
// convert to list of DeviceWithData
list<DeviceWithData> result;
for (const auto &dev : devices) {
DeviceWithData device = dev;
try {
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, device, input.base());
} catch (const InvalidAccessException &e) {
continue;
}
valuesFor(device);
result.emplace_back(device);
}
input.target() = result;
}
void DeviceServiceImpl::doFetchActiveBy(Relation<vector<Device>, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base());
m_dao->fetchActiveBy(input.target(), input.base());
}
void DeviceServiceImpl::doFetchActiveBy(Relation<vector<DeviceWithData>, Gateway> &input)
{
// fetch list of Devices
vector<Device> devices;
for (const auto &dev : input.target())
devices.emplace_back(dev);
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base());
m_dao->fetchActiveBy(devices, input.base());
// convert to list of DeviceWithData
vector<DeviceWithData> result;
for (const auto &dev : devices) {
DeviceWithData device = dev;
try {
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, device, input.base());
} catch (const InvalidAccessException &e) {
continue;
}
valuesFor(device);
result.emplace_back(device);
}
input.target() = result;
}
void DeviceServiceImpl::doFetchInactiveBy(Relation<vector<Device>, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base());
m_dao->fetchInactiveBy(input.target(), input.base());
}
void DeviceServiceImpl::doFetchInactiveBy(Relation<vector<DeviceWithData>, Gateway> &input)
{
// fetch list of Devices
vector<Device> devices;
for (const auto &dev : input.target())
devices.emplace_back(dev);
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base());
m_dao->fetchInactiveBy(devices, input.base());
// convert to list of DeviceWithData
vector<DeviceWithData> result;
for (const auto &dev : devices) {
DeviceWithData device = dev;
try {
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, device, input.base());
} catch (const InvalidAccessException &e) {
continue;
}
valuesFor(device);
result.emplace_back(device);
}
input.target() = result;
}
Work DeviceServiceImpl::doUnregister(Relation<Device, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UNREGISTER,
input, input.target(), input.base());
Device &device = input.target();
if (!m_dao->fetch(device, input.base()))
throw NotFoundException("no such device " + device);
Work work(WorkID::random());
DeviceUnpairWork content;
content.setGatewayID(device.gateway().id());
content.setDeviceID(device.id());
work.setContent(content);
m_workFacade->schedule(work, input);
return work;
}
bool DeviceServiceImpl::doActivate(Relation<Device, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_ACTIVATE,
input, input.target(), input.base());
Device &device = input.target();
if (!m_dao->fetch(device, input.base()))
return false;
return tryActivateAndUpdate(device, input.base());
}
bool DeviceServiceImpl::tryActivateAndUpdate(Device &device,
const Gateway &gateway, bool forceUpdate)
{
const DeviceStatus &status = device.status();
if (!status.active()) {
Device copy(device);
m_gatewayRPC->pairDevice([copy, this](GatewayRPCResult::Ptr r) {
switch (r->status()) {
case GatewayRPCResult::Status::PENDING:
Loggable::forClass(typeid(DeviceServiceImpl)).information(
"device " + device + " pairing is pending...",
__FILE__, __LINE__);
break;
case GatewayRPCResult::Status::ACCEPTED:
Loggable::forClass(typeid(DeviceServiceImpl)).debug(
"device " + device + " would be paired",
__FILE__, __LINE__);
break;
case GatewayRPCResult::Status::SUCCESS:
Loggable::forClass(typeid(DeviceServiceImpl)).information(
"device " + device + " successfully paired",
__FILE__, __LINE__);
break;
case GatewayRPCResult::Status::FAILED:
case GatewayRPCResult::Status::TIMEOUT:
case GatewayRPCResult::Status::NOT_CONNECTED:
Loggable::forClass(typeid(DeviceServiceImpl)).warning(
"device " + device + " failed to pair",
__FILE__, __LINE__);
break;
}
}, gateway, device);
device.status().setState(DeviceStatus::STATE_ACTIVE);
device.status().setLastChanged(Timestamp());
return m_dao->update(device, gateway);
}
return forceUpdate? m_dao->update(device, gateway) : false;
}
bool DeviceServiceImpl::prepareUpdate(RelationWithData<Device, Gateway> &input)
{
if (!m_dao->fetch(input.target(), input.base()))
return false;
input.data().partial(input.target());
return true;
}
bool DeviceServiceImpl::doUpdate(RelationWithData<Device, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,
input, input.target(), input.base());
if (!prepareUpdate(input))
return false;
return m_dao->update(input.target(), input.base());
}
bool DeviceServiceImpl::doUpdateAndActivate(
RelationWithData<Device, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE_AND_ACTIVATE,
input, input.target(), input.base());
if (!prepareUpdate(input))
return false;
return tryActivateAndUpdate(input.target(), input.base(), true);
}
bool DeviceServiceImpl::doCreateProperty(RelationWithData<DeviceProperty, Device> &input)
{
const Gateway &gateway = input.base().gateway();
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,
input, input.base(), gateway);
input.data().full(input.target());
return m_propertyDao->insert(input.target(), input.base());
}
bool DeviceServiceImpl::doUpdateProperty(RelationWithData<DeviceProperty, Device> &input)
{
const Gateway &gateway = input.base().gateway();
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,
input, input.base(), gateway);
if (!m_propertyDao->fetch(input.target(), input.base()))
return false;
input.data().partial(input.target());
return m_propertyDao->update(input.target(), input.base());
}
bool DeviceServiceImpl::doRemoveProperty(Relation<const DeviceProperty, Device> &input)
{
const Gateway &gateway = input.base().gateway();
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,
input, input.base(), gateway);
return m_propertyDao->remove(input.target(), input.base());
}
bool DeviceServiceImpl::doFindProperty(Relation<DeviceProperty, Device> &input)
{
const Gateway &gateway = input.base().gateway();
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base(), gateway);
return m_propertyDao->fetch(input.target(), input.base());
}
void DeviceServiceImpl::doListProperties(Relation<list<DeviceProperty>, Device> &input)
{
const Gateway &gateway = input.base().gateway();
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base(), gateway);
return m_propertyDao->fetchByDevice(input.target(), input.base());
}
<commit_msg>DeviceServiceImpl: differentiate failure and timeout during pair<commit_after>#include <Poco/Exception.h>
#include <Poco/Logger.h>
#include <Poco/Nullable.h>
#include <Poco/Timestamp.h>
#include "di/Injectable.h"
#include "model/Device.h"
#include "model/Gateway.h"
#include "service/DeviceServiceImpl.h"
#include "work/DeviceUnpairWork.h"
#include "work/WorkFacade.h"
BEEEON_OBJECT_BEGIN(BeeeOn, DeviceServiceImpl)
BEEEON_OBJECT_CASTABLE(DeviceService)
BEEEON_OBJECT_REF("deviceDao", &DeviceServiceImpl::setDeviceDao)
BEEEON_OBJECT_REF("controlDao", &DeviceServiceImpl::setControlDao)
BEEEON_OBJECT_REF("sensorHistoryDao", &DeviceServiceImpl::setSensorHistoryDao)
BEEEON_OBJECT_REF("devicePropertyDao", &DeviceServiceImpl::setDevicePropertyDao)
BEEEON_OBJECT_REF("gatewayRPC", &DeviceServiceImpl::setGatewayRPC)
BEEEON_OBJECT_REF("accessPolicy", &DeviceServiceImpl::setAccessPolicy)
BEEEON_OBJECT_REF("workFacade", &DeviceServiceImpl::setWorkFacade)
BEEEON_OBJECT_REF("transactionManager", &DeviceServiceImpl::setTransactionManager)
BEEEON_OBJECT_END(BeeeOn, DeviceServiceImpl)
using namespace std;
using namespace Poco;
using namespace BeeeOn;
DeviceServiceImpl::DeviceServiceImpl()
{
}
void DeviceServiceImpl::setDeviceDao(DeviceDao::Ptr dao)
{
m_dao = dao;
}
void DeviceServiceImpl::setControlDao(ControlDao::Ptr dao)
{
m_controlDao = dao;
}
void DeviceServiceImpl::setSensorHistoryDao(SensorHistoryDao::Ptr dao)
{
m_historyDao = dao;
}
void DeviceServiceImpl::setDevicePropertyDao(DevicePropertyDao::Ptr dao)
{
m_propertyDao = dao;
}
void DeviceServiceImpl::setGatewayRPC(GatewayRPC::Ptr rpc)
{
m_gatewayRPC = rpc;
}
void DeviceServiceImpl::setWorkFacade(WorkFacade::Ptr facade)
{
m_workFacade = facade;
}
void DeviceServiceImpl::setAccessPolicy(DeviceAccessPolicy::Ptr policy)
{
m_policy = policy;
}
bool DeviceServiceImpl::doFetch(Relation<Device, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.target(), input.base());
return m_dao->fetch(input.target(), input.base());
}
void DeviceServiceImpl::valuesFor(DeviceWithData &device)
{
// fetch last value of all device modules
vector<ModuleInfo> sensors;
list<Control> controls;
size_t count = 0;
for (const auto &info : *device.type()) {
if (info.isControllable())
controls.emplace_back(Control{info.id()});
else
sensors.emplace_back(info);
count += 1;
}
// values of all modules
vector<ValueAt> values(count);
// a null result means that there is no data for that sensor yet
vector<Nullable<ValueAt>> nullableValues;
m_historyDao->fetchMany(device, sensors, nullableValues);
size_t i = 0;
for (const auto &sensor : sensors) {
const auto ¤t = nullableValues.at(i++);
const unsigned int index = sensor.id();
if (!current.isNull())
values[index] = current;
// else leave the value as invalid
}
m_controlDao->fetchBy(controls, device);
for (const auto &control : controls) {
const unsigned int index = control.id();
const auto &confirmed = control.lastConfirmed();
if (!confirmed.isNull()) {
const Control::State &state = confirmed;
values[index] = {state.at().value(), state.value()};
}
// else leave the value as invalid
}
device.setValues(values);
}
void DeviceServiceImpl::doFetchMany(Single<list<Device>> &input)
{
m_policy->assureMany(DeviceAccessPolicy::ACTION_USER_GET,
input, input.target());
list<Device> &devices = input.target();
m_dao->fetchMany(devices);
}
void DeviceServiceImpl::doFetchMany(Single<list<DeviceWithData>> &input)
{
list<Device> devices;
for (const auto &dev : input.target())
devices.emplace_back(dev);
m_dao->fetchMany(devices);
// convert to list of DeviceWithData
list<DeviceWithData> result;
for (const auto &dev : devices) {
DeviceWithData device = dev;
try {
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, device, device.gateway());
} catch (const InvalidAccessException &e) {
continue;
}
valuesFor(device);
result.emplace_back(device);
}
input.target() = result;
}
void DeviceServiceImpl::doFetchMany(Relation<list<Device>, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET, input, input.base());
list<Device> &devices = input.target();
m_dao->fetchMany(devices);
list<Device>::iterator it = devices.begin();
while (it != devices.end()) {
Device &device = *it;
try {
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, device, input.base());
} catch (const InvalidAccessException &e) {
// drop inaccessible devices
it = devices.erase(it);
continue;
}
++it; // no erase occured, continue
}
}
/**
* The method performs 1 + 2 * N Dao requests where N is the number of devices.
* The first query obtains list of Device instances. Because we need a list
* of DeviceWithData instances, the loop would convert it. The conversion
* fetches module data for every single device.
*
* The method should be optimized (moved to Dao layer) if needed.
*/
void DeviceServiceImpl::doFetchMany(Relation<list<DeviceWithData>, Gateway> &input)
{
// fetch list of Devices
list<Device> devices;
for (const auto &dev : input.target())
devices.emplace_back(dev);
m_policy->assureMany(DeviceAccessPolicy::ACTION_USER_GET, input, devices);
m_dao->fetchMany(devices);
// convert to list of DeviceWithData
list<DeviceWithData> result;
for (const auto &dev : devices) {
DeviceWithData device = dev;
try {
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, device, input.base());
} catch (const InvalidAccessException &e) {
continue;
}
valuesFor(device);
result.emplace_back(device);
}
input.target() = result;
}
void DeviceServiceImpl::doFetchActiveBy(Relation<vector<Device>, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base());
m_dao->fetchActiveBy(input.target(), input.base());
}
void DeviceServiceImpl::doFetchActiveBy(Relation<vector<DeviceWithData>, Gateway> &input)
{
// fetch list of Devices
vector<Device> devices;
for (const auto &dev : input.target())
devices.emplace_back(dev);
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base());
m_dao->fetchActiveBy(devices, input.base());
// convert to list of DeviceWithData
vector<DeviceWithData> result;
for (const auto &dev : devices) {
DeviceWithData device = dev;
try {
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, device, input.base());
} catch (const InvalidAccessException &e) {
continue;
}
valuesFor(device);
result.emplace_back(device);
}
input.target() = result;
}
void DeviceServiceImpl::doFetchInactiveBy(Relation<vector<Device>, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base());
m_dao->fetchInactiveBy(input.target(), input.base());
}
void DeviceServiceImpl::doFetchInactiveBy(Relation<vector<DeviceWithData>, Gateway> &input)
{
// fetch list of Devices
vector<Device> devices;
for (const auto &dev : input.target())
devices.emplace_back(dev);
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base());
m_dao->fetchInactiveBy(devices, input.base());
// convert to list of DeviceWithData
vector<DeviceWithData> result;
for (const auto &dev : devices) {
DeviceWithData device = dev;
try {
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, device, input.base());
} catch (const InvalidAccessException &e) {
continue;
}
valuesFor(device);
result.emplace_back(device);
}
input.target() = result;
}
Work DeviceServiceImpl::doUnregister(Relation<Device, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UNREGISTER,
input, input.target(), input.base());
Device &device = input.target();
if (!m_dao->fetch(device, input.base()))
throw NotFoundException("no such device " + device);
Work work(WorkID::random());
DeviceUnpairWork content;
content.setGatewayID(device.gateway().id());
content.setDeviceID(device.id());
work.setContent(content);
m_workFacade->schedule(work, input);
return work;
}
bool DeviceServiceImpl::doActivate(Relation<Device, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_ACTIVATE,
input, input.target(), input.base());
Device &device = input.target();
if (!m_dao->fetch(device, input.base()))
return false;
return tryActivateAndUpdate(device, input.base());
}
bool DeviceServiceImpl::tryActivateAndUpdate(Device &device,
const Gateway &gateway, bool forceUpdate)
{
const DeviceStatus &status = device.status();
if (!status.active()) {
Device copy(device);
m_gatewayRPC->pairDevice([copy, this](GatewayRPCResult::Ptr r) {
switch (r->status()) {
case GatewayRPCResult::Status::PENDING:
Loggable::forClass(typeid(DeviceServiceImpl)).information(
"device " + device + " pairing is pending...",
__FILE__, __LINE__);
break;
case GatewayRPCResult::Status::ACCEPTED:
Loggable::forClass(typeid(DeviceServiceImpl)).debug(
"device " + device + " would be paired",
__FILE__, __LINE__);
break;
case GatewayRPCResult::Status::SUCCESS:
Loggable::forClass(typeid(DeviceServiceImpl)).information(
"device " + device + " successfully paired",
__FILE__, __LINE__);
break;
case GatewayRPCResult::Status::FAILED:
Loggable::forClass(typeid(DeviceServiceImpl)).warning(
"device " + device + " failed to pair",
__FILE__, __LINE__);
break;
case GatewayRPCResult::Status::TIMEOUT:
case GatewayRPCResult::Status::NOT_CONNECTED:
Loggable::forClass(typeid(DeviceServiceImpl)).warning(
"device " + device + " failed to pair on time",
__FILE__, __LINE__);
break;
}
}, gateway, device);
device.status().setState(DeviceStatus::STATE_ACTIVE);
device.status().setLastChanged(Timestamp());
return m_dao->update(device, gateway);
}
return forceUpdate? m_dao->update(device, gateway) : false;
}
bool DeviceServiceImpl::prepareUpdate(RelationWithData<Device, Gateway> &input)
{
if (!m_dao->fetch(input.target(), input.base()))
return false;
input.data().partial(input.target());
return true;
}
bool DeviceServiceImpl::doUpdate(RelationWithData<Device, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,
input, input.target(), input.base());
if (!prepareUpdate(input))
return false;
return m_dao->update(input.target(), input.base());
}
bool DeviceServiceImpl::doUpdateAndActivate(
RelationWithData<Device, Gateway> &input)
{
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE_AND_ACTIVATE,
input, input.target(), input.base());
if (!prepareUpdate(input))
return false;
return tryActivateAndUpdate(input.target(), input.base(), true);
}
bool DeviceServiceImpl::doCreateProperty(RelationWithData<DeviceProperty, Device> &input)
{
const Gateway &gateway = input.base().gateway();
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,
input, input.base(), gateway);
input.data().full(input.target());
return m_propertyDao->insert(input.target(), input.base());
}
bool DeviceServiceImpl::doUpdateProperty(RelationWithData<DeviceProperty, Device> &input)
{
const Gateway &gateway = input.base().gateway();
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,
input, input.base(), gateway);
if (!m_propertyDao->fetch(input.target(), input.base()))
return false;
input.data().partial(input.target());
return m_propertyDao->update(input.target(), input.base());
}
bool DeviceServiceImpl::doRemoveProperty(Relation<const DeviceProperty, Device> &input)
{
const Gateway &gateway = input.base().gateway();
m_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,
input, input.base(), gateway);
return m_propertyDao->remove(input.target(), input.base());
}
bool DeviceServiceImpl::doFindProperty(Relation<DeviceProperty, Device> &input)
{
const Gateway &gateway = input.base().gateway();
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base(), gateway);
return m_propertyDao->fetch(input.target(), input.base());
}
void DeviceServiceImpl::doListProperties(Relation<list<DeviceProperty>, Device> &input)
{
const Gateway &gateway = input.base().gateway();
m_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,
input, input.base(), gateway);
return m_propertyDao->fetchByDevice(input.target(), input.base());
}
<|endoftext|> |
<commit_before>#include <Sound.h>
#include <Display.h>
#include <SDL.h>
#include <SDL_mixer.h>
#include <hx/Thread.h>
namespace nme
{
bool gSDLIsInit = false;
class SDLSoundChannel;
bool sChannelsInit = false;
enum { sMaxChannels = 8 };
bool sUsedChannel[sMaxChannels];
bool sDoneChannel[sMaxChannels];
void *sUsedMusic = 0;
bool sDoneMusic = false;
enum { STEREO_SAMPLES = 2 };
unsigned int sSoundPos = 0;
void onChannelDone(int inChannel)
{
if (sUsedChannel[inChannel])
sDoneChannel[inChannel] = true;
}
void onMusicDone()
{
if (sUsedMusic)
sDoneMusic = true;
}
void onPostMix(void *udata, Uint8 *stream, int len)
{
sSoundPos += len / sizeof(short) / STEREO_SAMPLES ;
}
static bool Init()
{
if (!gSDLIsInit)
{
ELOG("Please init Stage before creating sound.");
return false;
}
if (!sChannelsInit)
{
sChannelsInit = true;
for(int i=0;i<sMaxChannels;i++)
{
sUsedChannel[i] = false;
sDoneChannel[i] = false;
}
Mix_ChannelFinished(onChannelDone);
Mix_HookMusicFinished(onMusicDone);
Mix_SetPostMix(onPostMix,0);
}
return sChannelsInit;
}
// --- Using "Mix_Chunk" API ----------------------------------------------------
class SDLSoundChannel : public SoundChannel
{
enum { BUF_SIZE = (1<<17) };
public:
SDLSoundChannel(Object *inSound, Mix_Chunk *inChunk, double inStartTime, int inLoops,
const SoundTransform &inTransform)
{
mChunk = inChunk;
mDynamicBuffer = 0;
mSound = inSound;
mSound->IncRef();
mChannel = -1;
// Allocate myself a channel
if (mChunk)
{
for(int i=0;i<sMaxChannels;i++)
if (!sUsedChannel[i])
{
IncRef();
sDoneChannel[i] = false;
sUsedChannel[i] = true;
mChannel = i;
break;
}
}
if (mChannel>=0)
{
Mix_PlayChannel( mChannel , mChunk, inLoops<0 ? -1 : inLoops==0 ? 0 : inLoops-1 );
Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME );
// Mix_SetPanning
}
}
SDLSoundChannel(const ByteArray &inBytes, const SoundTransform &inTransform)
{
Mix_QuerySpec(&mFrequency, &mFormat, &mChannels);
if (mFrequency!=44100)
ELOG("Warning - Frequency mismatch %d",mFrequency);
if (mFormat!=32784)
ELOG("Warning - Format mismatch %d",mFormat);
if (mChannels!=2)
ELOG("Warning - channe mismatch %d",mChannels);
mChunk = 0;
mDynamicBuffer = new short[BUF_SIZE * STEREO_SAMPLES];
memset(mDynamicBuffer,0,BUF_SIZE*sizeof(short));
mSound = 0;
mChannel = -1;
mDynamicChunk.allocated = 0;
mDynamicChunk.abuf = (Uint8 *)mDynamicBuffer;
mDynamicChunk.alen = BUF_SIZE * sizeof(short) * STEREO_SAMPLES; // bytes
mDynamicChunk.volume = MIX_MAX_VOLUME;
mDynamicFillPos = 0;
mDynamicStartPos = 0;
mDynamicDataDue = 0;
// Allocate myself a channel
for(int i=0;i<sMaxChannels;i++)
if (!sUsedChannel[i])
{
IncRef();
sDoneChannel[i] = false;
sUsedChannel[i] = true;
mChannel = i;
break;
}
if (mChannel>=0)
{
FillBuffer(inBytes);
// Just once ...
if (mDynamicFillPos<1024)
{
mDynamicDone = true;
mDynamicChunk.alen = mDynamicFillPos * sizeof(short) * STEREO_SAMPLES;
Mix_PlayChannel( mChannel , &mDynamicChunk, 0 );
}
else
{
mDynamicDone = false;
// TODO: Lock?
Mix_PlayChannel( mChannel , &mDynamicChunk, -1 );
mDynamicStartPos = sSoundPos;
}
Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME );
}
}
void FillBuffer(const ByteArray &inBytes)
{
int time_samples = inBytes.Size()/sizeof(float)/STEREO_SAMPLES;
const float *buffer = (const float *)inBytes.Bytes();
enum { MASK = BUF_SIZE - 1 };
for(int i=0;i<time_samples;i++)
{
int mono_pos = (i+mDynamicFillPos) & MASK;
mDynamicBuffer[ mono_pos<<1 ] = *buffer++ * ((1<<15)-1);
mDynamicBuffer[ (mono_pos<<1) + 1 ] = *buffer++ * ((1<<15)-1);
}
if (mDynamicFillPos<(sSoundPos-mDynamicStartPos))
ELOG("Too slow - FillBuffer %d / %d)", mDynamicFillPos, (sSoundPos-mDynamicStartPos) );
mDynamicFillPos += time_samples;
if (time_samples<1024 && !mDynamicDone)
{
mDynamicDone = true;
for(int i=0;i<2048;i++)
{
int mono_pos = (i+mDynamicFillPos) & MASK;
mDynamicBuffer[ mono_pos<<1 ] = 0;
mDynamicBuffer[ (mono_pos<<1) + 1 ] = 0;
}
int samples_left = (int)mDynamicFillPos - (int)(sSoundPos-mDynamicStartPos);
int ticks_left = samples_left*1000/44100;
//printf("Expire in %d (%d)\n", samples_left, ticks_left );
Mix_ExpireChannel(mChannel, ticks_left>0 ? ticks_left : 1 );
}
}
~SDLSoundChannel()
{
delete [] mDynamicBuffer;
if (mSound)
mSound->DecRef();
}
void CheckDone()
{
if (mChannel>=0 && sDoneChannel[mChannel])
{
sDoneChannel[mChannel] = false;
int c = mChannel;
mChannel = -1;
DecRef();
sUsedChannel[c] = 0;
}
}
bool isComplete()
{
CheckDone();
return mChannel < 0;
}
double getLeft() { return 1; }
double getRight() { return 1; }
double getPosition() { return 1; }
void stop()
{
if (mChannel>=0)
Mix_HaltChannel(mChannel);
}
void setTransform(const SoundTransform &inTransform)
{
if (mChannel>=0)
Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME );
}
double getDataPosition()
{
return (sSoundPos-mDynamicStartPos)*1000.0/mFrequency;
}
bool needsData()
{
if (!mDynamicBuffer || mDynamicDone)
return false;
if (mDynamicDataDue<=sSoundPos)
{
mDynamicDone = true;
return true;
}
return false;
}
void addData(const ByteArray &inBytes)
{
mDynamicDone = false;
mDynamicDataDue = mDynamicFillPos + mDynamicStartPos;
FillBuffer(inBytes);
}
Object *mSound;
Mix_Chunk *mChunk;
int mChannel;
Mix_Chunk mDynamicChunk;
short *mDynamicBuffer;
unsigned int mDynamicFillPos;
unsigned int mDynamicStartPos;
unsigned int mDynamicDataDue;
bool mDynamicDone;
int mFrequency;
Uint16 mFormat;
int mChannels;
};
SoundChannel *SoundChannel::Create(const ByteArray &inBytes,const SoundTransform &inTransform)
{
if (!Init())
return 0;
return new SDLSoundChannel(inBytes,inTransform);
}
class SDLSound : public Sound
{
public:
SDLSound(const std::string &inFilename)
{
IncRef();
#ifdef HX_MACOS
char name[1024];
GetBundleFilename(inFilename.c_str(),name,1024);
#else
const char *name = inFilename.c_str();
#endif
mChunk = Mix_LoadWAV(name);
if ( mChunk == NULL )
{
mError = SDL_GetError();
// ELOG("Error %s (%s)", mError.c_str(), name );
}
}
SDLSound(unsigned char *inData, int len)
{
IncRef();
mChunk = Mix_LoadWAV_RW(SDL_RWFromMem(inData, len), 1);
if ( mChunk == NULL )
{
mError = SDL_GetError();
// ELOG("Error %s (%s)", mError.c_str(), name );
}
}
~SDLSound()
{
if (mChunk)
Mix_FreeChunk( mChunk );
}
double getLength()
{
if (mChunk==0) return 0;
#if defined(DYNAMIC_SDL) || defined(WEBOS)
// ?
return 0.0;
#else
return 0.0;
#endif
}
// Will return with one ref...
SoundChannel *openChannel(double startTime, int loops, const SoundTransform &inTransform)
{
if (!mChunk)
return 0;
return new SDLSoundChannel(this,mChunk,startTime, loops,inTransform);
}
int getBytesLoaded() { return mChunk ? mChunk->alen : 0; }
int getBytesTotal() { return mChunk ? mChunk->alen : 0; }
bool ok() { return mChunk; }
std::string getError() { return mError; }
std::string mError;
Mix_Chunk *mChunk;
};
// --- Using "Mix_Music" API ----------------------------------------------------
class SDLMusicChannel : public SoundChannel
{
public:
SDLMusicChannel(Object *inSound, Mix_Music *inMusic, double inStartTime, int inLoops,
const SoundTransform &inTransform)
{
mMusic = inMusic;
mSound = inSound;
mSound->IncRef();
mPlaying = false;
if (mMusic)
{
mPlaying = true;
sUsedMusic = this;
sDoneMusic = false;
IncRef();
Mix_PlayMusic( mMusic, inLoops<0 ? -1 : inLoops==0 ? 0 : inLoops-1 );
Mix_VolumeMusic( inTransform.volume*MIX_MAX_VOLUME );
// Mix_SetPanning
}
}
~SDLMusicChannel()
{
mSound->DecRef();
}
void CheckDone()
{
if (mPlaying && (sDoneMusic || (sUsedMusic!=this)) )
{
mPlaying = false;
if (sUsedMusic == this)
{
sUsedMusic = 0;
sDoneMusic = false;
}
DecRef();
}
}
bool isComplete()
{
CheckDone();
return !mPlaying;
}
double getLeft() { return 1; }
double getRight() { return 1; }
double getPosition() { return 1; }
void stop()
{
if (mMusic)
Mix_HaltMusic();
}
void setTransform(const SoundTransform &inTransform)
{
if (mMusic>=0)
Mix_VolumeMusic( inTransform.volume*MIX_MAX_VOLUME );
}
bool mPlaying;
Object *mSound;
Mix_Music *mMusic;
};
class SDLMusic : public Sound
{
public:
SDLMusic(const std::string &inFilename)
{
IncRef();
#ifdef HX_MACOS
char name[1024];
GetBundleFilename(inFilename.c_str(),name,1024);
#else
const char *name = inFilename.c_str();
#endif
mMusic = Mix_LoadMUS(name);
if ( mMusic == NULL )
{
mError = SDL_GetError();
ELOG("Error in music %s (%s)", mError.c_str(), name );
}
}
SDLMusic(unsigned char *inData, int len)
{
IncRef();
mMusic = Mix_LoadMUS_RW(SDL_RWFromMem(inData, len));
if ( mMusic == NULL )
{
mError = SDL_GetError();
ELOG("Error in music with len (%d)", len );
}
}
~SDLMusic()
{
if (mMusic)
Mix_FreeMusic( mMusic );
}
double getLength()
{
if (mMusic==0) return 0;
// TODO:
return 60000;
}
// Will return with one ref...
SoundChannel *openChannel(double startTime, int loops, const SoundTransform &inTransform)
{
if (!mMusic)
return 0;
return new SDLMusicChannel(this,mMusic,startTime, loops,inTransform);
}
int getBytesLoaded() { return mMusic ? 100 : 0; }
int getBytesTotal() { return mMusic ? 100 : 0; }
bool ok() { return mMusic; }
std::string getError() { return mError; }
std::string mError;
Mix_Music *mMusic;
};
// --- External Interface -----------------------------------------------------------
Sound *Sound::Create(const std::string &inFilename,bool inForceMusic)
{
if (!Init())
return 0;
Sound *sound = inForceMusic ? 0 : new SDLSound(inFilename);
if (!sound || !sound->ok())
{
if (sound) sound->DecRef();
sound = new SDLMusic(inFilename);
}
return sound;
}
Sound *Sound::Create(unsigned char *inData, int len, bool inForceMusic) {
if (!Init())
return 0;
Sound *sound = inForceMusic ? 0 : new SDLSound(inData, len);
if (!sound || !sound->ok())
{
if (sound) sound->DecRef();
sound = new SDLMusic(inData, len);
}
return sound;
}
}
<commit_msg>Added proper position to SDL music channels, but cannot set the position because it causes crash errors in SDL, currently<commit_after>#include <Sound.h>
#include <Display.h>
#include <SDL.h>
#include <SDL_mixer.h>
#include <hx/Thread.h>
namespace nme
{
bool gSDLIsInit = false;
class SDLSoundChannel;
bool sChannelsInit = false;
enum { sMaxChannels = 8 };
bool sUsedChannel[sMaxChannels];
bool sDoneChannel[sMaxChannels];
void *sUsedMusic = 0;
bool sDoneMusic = false;
enum { STEREO_SAMPLES = 2 };
unsigned int sSoundPos = 0;
void onChannelDone(int inChannel)
{
if (sUsedChannel[inChannel])
sDoneChannel[inChannel] = true;
}
void onMusicDone()
{
if (sUsedMusic)
sDoneMusic = true;
}
void onPostMix(void *udata, Uint8 *stream, int len)
{
sSoundPos += len / sizeof(short) / STEREO_SAMPLES ;
}
static bool Init()
{
if (!gSDLIsInit)
{
ELOG("Please init Stage before creating sound.");
return false;
}
if (!sChannelsInit)
{
sChannelsInit = true;
for(int i=0;i<sMaxChannels;i++)
{
sUsedChannel[i] = false;
sDoneChannel[i] = false;
}
Mix_ChannelFinished(onChannelDone);
Mix_HookMusicFinished(onMusicDone);
Mix_SetPostMix(onPostMix,0);
}
return sChannelsInit;
}
// --- Using "Mix_Chunk" API ----------------------------------------------------
class SDLSoundChannel : public SoundChannel
{
enum { BUF_SIZE = (1<<17) };
public:
SDLSoundChannel(Object *inSound, Mix_Chunk *inChunk, double inStartTime, int inLoops,
const SoundTransform &inTransform)
{
mChunk = inChunk;
mDynamicBuffer = 0;
mSound = inSound;
mSound->IncRef();
mChannel = -1;
// Allocate myself a channel
if (mChunk)
{
for(int i=0;i<sMaxChannels;i++)
if (!sUsedChannel[i])
{
IncRef();
sDoneChannel[i] = false;
sUsedChannel[i] = true;
mChannel = i;
break;
}
}
if (mChannel>=0)
{
Mix_PlayChannel( mChannel , mChunk, inLoops<0 ? -1 : inLoops==0 ? 0 : inLoops-1 );
Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME );
// Mix_SetPanning
}
}
SDLSoundChannel(const ByteArray &inBytes, const SoundTransform &inTransform)
{
Mix_QuerySpec(&mFrequency, &mFormat, &mChannels);
if (mFrequency!=44100)
ELOG("Warning - Frequency mismatch %d",mFrequency);
if (mFormat!=32784)
ELOG("Warning - Format mismatch %d",mFormat);
if (mChannels!=2)
ELOG("Warning - channe mismatch %d",mChannels);
mChunk = 0;
mDynamicBuffer = new short[BUF_SIZE * STEREO_SAMPLES];
memset(mDynamicBuffer,0,BUF_SIZE*sizeof(short));
mSound = 0;
mChannel = -1;
mDynamicChunk.allocated = 0;
mDynamicChunk.abuf = (Uint8 *)mDynamicBuffer;
mDynamicChunk.alen = BUF_SIZE * sizeof(short) * STEREO_SAMPLES; // bytes
mDynamicChunk.volume = MIX_MAX_VOLUME;
mDynamicFillPos = 0;
mDynamicStartPos = 0;
mDynamicDataDue = 0;
// Allocate myself a channel
for(int i=0;i<sMaxChannels;i++)
if (!sUsedChannel[i])
{
IncRef();
sDoneChannel[i] = false;
sUsedChannel[i] = true;
mChannel = i;
break;
}
if (mChannel>=0)
{
FillBuffer(inBytes);
// Just once ...
if (mDynamicFillPos<1024)
{
mDynamicDone = true;
mDynamicChunk.alen = mDynamicFillPos * sizeof(short) * STEREO_SAMPLES;
Mix_PlayChannel( mChannel , &mDynamicChunk, 0 );
}
else
{
mDynamicDone = false;
// TODO: Lock?
Mix_PlayChannel( mChannel , &mDynamicChunk, -1 );
mDynamicStartPos = sSoundPos;
}
Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME );
}
}
void FillBuffer(const ByteArray &inBytes)
{
int time_samples = inBytes.Size()/sizeof(float)/STEREO_SAMPLES;
const float *buffer = (const float *)inBytes.Bytes();
enum { MASK = BUF_SIZE - 1 };
for(int i=0;i<time_samples;i++)
{
int mono_pos = (i+mDynamicFillPos) & MASK;
mDynamicBuffer[ mono_pos<<1 ] = *buffer++ * ((1<<15)-1);
mDynamicBuffer[ (mono_pos<<1) + 1 ] = *buffer++ * ((1<<15)-1);
}
if (mDynamicFillPos<(sSoundPos-mDynamicStartPos))
ELOG("Too slow - FillBuffer %d / %d)", mDynamicFillPos, (sSoundPos-mDynamicStartPos) );
mDynamicFillPos += time_samples;
if (time_samples<1024 && !mDynamicDone)
{
mDynamicDone = true;
for(int i=0;i<2048;i++)
{
int mono_pos = (i+mDynamicFillPos) & MASK;
mDynamicBuffer[ mono_pos<<1 ] = 0;
mDynamicBuffer[ (mono_pos<<1) + 1 ] = 0;
}
int samples_left = (int)mDynamicFillPos - (int)(sSoundPos-mDynamicStartPos);
int ticks_left = samples_left*1000/44100;
//printf("Expire in %d (%d)\n", samples_left, ticks_left );
Mix_ExpireChannel(mChannel, ticks_left>0 ? ticks_left : 1 );
}
}
~SDLSoundChannel()
{
delete [] mDynamicBuffer;
if (mSound)
mSound->DecRef();
}
void CheckDone()
{
if (mChannel>=0 && sDoneChannel[mChannel])
{
sDoneChannel[mChannel] = false;
int c = mChannel;
mChannel = -1;
DecRef();
sUsedChannel[c] = 0;
}
}
bool isComplete()
{
CheckDone();
return mChannel < 0;
}
double getLeft() { return 1; }
double getRight() { return 1; }
double getPosition() { return 1; }
void stop()
{
if (mChannel>=0)
Mix_HaltChannel(mChannel);
}
void setTransform(const SoundTransform &inTransform)
{
if (mChannel>=0)
Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME );
}
double getDataPosition()
{
return (sSoundPos-mDynamicStartPos)*1000.0/mFrequency;
}
bool needsData()
{
if (!mDynamicBuffer || mDynamicDone)
return false;
if (mDynamicDataDue<=sSoundPos)
{
mDynamicDone = true;
return true;
}
return false;
}
void addData(const ByteArray &inBytes)
{
mDynamicDone = false;
mDynamicDataDue = mDynamicFillPos + mDynamicStartPos;
FillBuffer(inBytes);
}
Object *mSound;
Mix_Chunk *mChunk;
int mChannel;
Mix_Chunk mDynamicChunk;
short *mDynamicBuffer;
unsigned int mDynamicFillPos;
unsigned int mDynamicStartPos;
unsigned int mDynamicDataDue;
bool mDynamicDone;
int mFrequency;
Uint16 mFormat;
int mChannels;
};
SoundChannel *SoundChannel::Create(const ByteArray &inBytes,const SoundTransform &inTransform)
{
if (!Init())
return 0;
return new SDLSoundChannel(inBytes,inTransform);
}
class SDLSound : public Sound
{
public:
SDLSound(const std::string &inFilename)
{
IncRef();
#ifdef HX_MACOS
char name[1024];
GetBundleFilename(inFilename.c_str(),name,1024);
#else
const char *name = inFilename.c_str();
#endif
mChunk = Mix_LoadWAV(name);
if ( mChunk == NULL )
{
mError = SDL_GetError();
// ELOG("Error %s (%s)", mError.c_str(), name );
}
}
SDLSound(unsigned char *inData, int len)
{
IncRef();
mChunk = Mix_LoadWAV_RW(SDL_RWFromMem(inData, len), 1);
if ( mChunk == NULL )
{
mError = SDL_GetError();
// ELOG("Error %s (%s)", mError.c_str(), name );
}
}
~SDLSound()
{
if (mChunk)
Mix_FreeChunk( mChunk );
}
double getLength()
{
if (mChunk==0) return 0;
#if defined(DYNAMIC_SDL) || defined(WEBOS)
// ?
return 0.0;
#else
return 0.0;
#endif
}
// Will return with one ref...
SoundChannel *openChannel(double startTime, int loops, const SoundTransform &inTransform)
{
if (!mChunk)
return 0;
return new SDLSoundChannel(this,mChunk,startTime, loops,inTransform);
}
int getBytesLoaded() { return mChunk ? mChunk->alen : 0; }
int getBytesTotal() { return mChunk ? mChunk->alen : 0; }
bool ok() { return mChunk; }
std::string getError() { return mError; }
std::string mError;
Mix_Chunk *mChunk;
};
// --- Using "Mix_Music" API ----------------------------------------------------
class SDLMusicChannel : public SoundChannel
{
public:
SDLMusicChannel(Object *inSound, Mix_Music *inMusic, double inStartTime, int inLoops,
const SoundTransform &inTransform)
{
mMusic = inMusic;
mSound = inSound;
mSound->IncRef();
mPlaying = false;
if (mMusic)
{
mPlaying = true;
sUsedMusic = this;
sDoneMusic = false;
mStartTime = SDL_GetTicks ();
mLength = 0;
IncRef();
Mix_PlayMusic( mMusic, inLoops<0 ? -1 : inLoops==0 ? 0 : inLoops-1 );
Mix_VolumeMusic( inTransform.volume*MIX_MAX_VOLUME );
if (inStartTime > 0)
{
// this is causing crash errors
//Mix_RewindMusic();
//int seconds = inStartTime / 1000;
//Mix_SetMusicPosition(seconds);
//mStartTime = SDL_GetTicks () - inStartTime;
}
// Mix_SetPanning not available for music
}
}
~SDLMusicChannel()
{
mSound->DecRef();
}
void CheckDone()
{
if (mPlaying && (sDoneMusic || (sUsedMusic!=this)) )
{
mLength = SDL_GetTicks () - mStartTime;
mPlaying = false;
if (sUsedMusic == this)
{
sUsedMusic = 0;
sDoneMusic = false;
}
DecRef();
}
}
bool isComplete()
{
CheckDone();
return !mPlaying;
}
double getLeft() { return 1; }
double getRight() { return 1; }
double getPosition() { return mPlaying ? SDL_GetTicks() - mStartTime : mLength; }
void stop()
{
if (mMusic)
Mix_HaltMusic();
}
void setTransform(const SoundTransform &inTransform)
{
if (mMusic>=0)
Mix_VolumeMusic( inTransform.volume*MIX_MAX_VOLUME );
}
bool mPlaying;
Object *mSound;
int mStartTime;
int mLength;
Mix_Music *mMusic;
};
class SDLMusic : public Sound
{
public:
SDLMusic(const std::string &inFilename)
{
IncRef();
#ifdef HX_MACOS
char name[1024];
GetBundleFilename(inFilename.c_str(),name,1024);
#else
const char *name = inFilename.c_str();
#endif
mMusic = Mix_LoadMUS(name);
if ( mMusic == NULL )
{
mError = SDL_GetError();
ELOG("Error in music %s (%s)", mError.c_str(), name );
}
}
SDLMusic(unsigned char *inData, int len)
{
IncRef();
mMusic = Mix_LoadMUS_RW(SDL_RWFromMem(inData, len));
if ( mMusic == NULL )
{
mError = SDL_GetError();
ELOG("Error in music with len (%d)", len );
}
}
~SDLMusic()
{
if (mMusic)
Mix_FreeMusic( mMusic );
}
double getLength()
{
if (mMusic==0) return 0;
// TODO:
return 60000;
}
// Will return with one ref...
SoundChannel *openChannel(double startTime, int loops, const SoundTransform &inTransform)
{
if (!mMusic)
return 0;
return new SDLMusicChannel(this,mMusic,startTime, loops,inTransform);
}
int getBytesLoaded() { return mMusic ? 100 : 0; }
int getBytesTotal() { return mMusic ? 100 : 0; }
bool ok() { return mMusic; }
std::string getError() { return mError; }
std::string mError;
Mix_Music *mMusic;
};
// --- External Interface -----------------------------------------------------------
Sound *Sound::Create(const std::string &inFilename,bool inForceMusic)
{
if (!Init())
return 0;
Sound *sound = inForceMusic ? 0 : new SDLSound(inFilename);
if (!sound || !sound->ok())
{
if (sound) sound->DecRef();
sound = new SDLMusic(inFilename);
}
return sound;
}
Sound *Sound::Create(unsigned char *inData, int len, bool inForceMusic) {
if (!Init())
return 0;
Sound *sound = inForceMusic ? 0 : new SDLSound(inData, len);
if (!sound || !sound->ok())
{
if (sound) sound->DecRef();
sound = new SDLMusic(inData, len);
}
return sound;
}
}
<|endoftext|> |
<commit_before>/*
ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio
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 "ch.h"
#include "hal.h"
#include "analog.h"
#include "encoder.h"
#include "encoderfoaw.h"
#include "packet/frame.h"
#include "packet/serialize.h"
#include "simulation.pb.h"
#include "messageutil.h"
#include "filter/movingaverage.h"
#include "angle.h"
#include "blink.h"
#include "usbconfig.h"
#include "saconfig.h"
#include "parameters.h"
#include <algorithm>
#include <array>
#include <type_traits>
#include "bicycle/kinematic.h" /* simplified bicycle model */
#include "bicycle/whipple.h" /* whipple bicycle model */
#include "oracle.h" /* oracle observer */
#include "kalman.h" /* kalman filter observer */
#include "haptic.h" /* handlebar feedback */
#include "simbicycle.h"
namespace {
#if defined(USE_BICYCLE_KINEMATIC_MODEL)
using model_t = model::BicycleKinematic;
using observer_t = observer::Oracle<model_t>;
using haptic_t = haptic::HandlebarStatic;
#else // defined(USE_BICYCLE_KINEMATIC_MODEL)
using model_t = model::BicycleWhipple;
using observer_t = observer::Kalman<model_t>;
using haptic_t = haptic::HandlebarDynamic;
#endif // defined(USE_BICYCLE_KINEMATIC_MODEL)
using bicycle_t = sim::Bicycle<model_t, observer_t, haptic_t>;
/* sensors */
Analog analog;
Encoder encoder_steer(sa::RLS_ROLIN_ENC, sa::RLS_ROLIN_ENC_INDEX_CFG);
EncoderFoaw<float, 32> encoder_rear_wheel(sa::RLS_GTS35_ENC,
sa::RLS_GTS35_ENC_CFG,
MS2ST(1), 3.0f);
filter::MovingAverage<float, 5> velocity_filter;
constexpr float fixed_velocity = 7.0f;
/* transmission */
std::array<uint8_t, SimulationMessage_size + packet::frame::PACKET_OVERHEAD> encode_buffer;
std::array<uint8_t, SimulationMessage_size + packet::frame::PACKET_OVERHEAD> packet_buffer;
SimulationMessage msg;
constexpr SimulationMessage msg_init = SimulationMessage_init_zero;
/* kinematics loop */
constexpr systime_t kinematics_loop_time = US2ST(8333); /* update kinematics at 120 Hz */
/* dynamics loop */
constexpr model::real_t dynamics_period = 0.005; /* 5 ms -> 200 Hz */
time_measurement_t computation_time_measurement;
time_measurement_t transmission_time_measurement;
dacsample_t set_handlebar_torque(float handlebar_torque) {
int32_t saturated_value = (handlebar_torque/sa::MAX_KOLLMORGEN_TORQUE * 2048) +
sa::KOLLMORGEN_DAC_ZERO_OFFSET;
saturated_value = std::min<int32_t>(std::max<int32_t>(saturated_value, 0), 4096);
dacsample_t aout = static_cast<dacsample_t>(saturated_value);
dacPutChannelX(sa::KOLLM_DAC, 0, aout);
return aout;
}
void update_and_transmit_kinematics(bicycle_t& bicycle) {
bicycle.update_kinematics();
/*
* TODO: Pose message should be transmitted asynchronously.
* After starting transmission, the simulation should start to calculate pose for the next timestep.
* This is currently not necessary given the observed timings.
*/
//size_t bytes_encoded = packet::serialize::encode_delimited(bicycle.pose(),
// encode_buffer.data(), encode_buffer.size());
//TODO: clear message
//message::set_simulation_loop_values(&msg, bicycle);
//size_t bytes_encoded = packet::serialize::encode_delimited(
// msg, encode_buffer.data(), encode_buffer.size());
//size_t bytes_written = packet::frame::stuff(
// encode_buffer.data(), packet_buffer.data(), bytes_encoded);
//if ((SDU1.config->usbp->state == USB_ACTIVE) && (SDU1.state == SDU_READY)) {
// usbTransmit(SDU1.config->usbp, SDU1.config->bulk_in, packet_buffer.data(), bytes_written);
//}
}
template <typename T>
struct observer_initializer{
template <typename S = T>
typename std::enable_if<std::is_same<typename S::observer_t, observer::Kalman<model_t>>::value, void>::type
initialize(S& bicycle) {
typename S::observer_t& observer = bicycle.observer();
observer.set_Q(parameters::defaultvalue::kalman::Q(observer.dt()));
/* Reduce steer measurement noise covariance */
observer.set_R(parameters::defaultvalue::kalman::R/1000);
/* prime the Kalman gain matrix */
bicycle.prime_observer();
/* We start with steer angle equal to the measurement and all other state elements at zero. */
model_t::state_t x0 = model_t::state_t::Zero();
model_t::set_state_element(x0, model_t::state_index_t::steer_angle,
angle::encoder_count<float>(encoder_steer));
observer.set_x(x0);
}
template <typename S = T>
typename std::enable_if<!std::is_same<typename S::observer_t, observer::Kalman<model_t>>::value, void>::type
initialize(S& bicycle) {
// no-op
(void)bicycle;
}
};
THD_WORKING_AREA(wa_kinematics_thread, 2048);
THD_FUNCTION(kinematics_thread, arg) {
bicycle_t& bicycle = *static_cast<bicycle_t*>(arg);
chRegSetThreadName("kinematics");
while (true) {
systime_t starttime = chVTGetSystemTime();
update_and_transmit_kinematics(bicycle);
systime_t sleeptime = kinematics_loop_time + starttime - chVTGetSystemTime();
if (sleeptime >= kinematics_loop_time) {
continue;
} else {
chThdSleep(sleeptime);
}
}
}
size_t write_message_to_encode_buffer(const SimulationMessage& m) {
const size_t bytes_encoded = packet::serialize::encode_delimited(
m, encode_buffer.data(), encode_buffer.size());
return packet::frame::stuff(
encode_buffer.data(), packet_buffer.data(), bytes_encoded);
}
} // namespace
/*
* Application entry point.
*/
int main(void) {
/*
* System initializations.
* - HAL initialization, this also initializes the configured device drivers
* and performs the board-specific initializations.
* - Kernel initialization, the main() function becomes a thread and the
* RTOS is active.
*/
halInit();
chSysInit();
/*
* Initialize a serial-over-USB CDC driver.
*/
sduObjectInit(&SDU1);
sduStart(&SDU1, &serusbcfg);
/*
* Activate the USB driver and then the USB bus pull-up on D+.
* Note, a delay is inserted in order to not have to disconnect the cable
* after a reset.
*/
board_usb_lld_disconnect_bus(); //usbDisconnectBus(serusbcfg.usbp);
chThdSleepMilliseconds(1500);
usbStart(serusbcfg.usbp, &usbcfg);
board_usb_lld_connect_bus(); //usbConnectBus(serusbcfg.usbp);
/* create the blink thread and print state monitor */
chBlinkThreadCreateStatic();
/*
* Start sensors.
* Encoder:
* Initialize encoder driver 5 on pins PA0, PA1 (EXT2-4, EXT2-8).
* Pins for encoder driver 3 are already set in board.h.
*/
palSetLineMode(LINE_TIM5_CH1, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);
palSetLineMode(LINE_TIM5_CH2, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);
encoder_steer.start();
encoder_rear_wheel.start();
analog.start(1000); /* trigger ADC conversion at 1 kHz */
/*
* Set torque measurement enable line low.
* The output of the Kistler torque sensor is not valid until after a falling edge
* on the measurement line and it is held low. The 'LINE_TORQUE_MEAS_EN' line is
* reversed due to NPN switch Q1.
*/
palClearLine(LINE_TORQUE_MEAS_EN);
chThdSleepMilliseconds(1);
palSetLine(LINE_TORQUE_MEAS_EN);
/*
* Start DAC1 driver and set output pin as analog as suggested in Reference Manual.
* The default line configuration is OUTPUT_OPENDRAIN_PULLUP for SPI1_ENC1_NSS
* and must be changed to use as analog output.
*/
palSetLineMode(LINE_KOLLM_ACTL_TORQUE, PAL_MODE_INPUT_ANALOG);
dacStart(sa::KOLLM_DAC, sa::KOLLM_DAC_CFG);
set_handlebar_torque(0.0f);
/*
* Initialize bicycle. The initial velocity is important as we use it to prime
* the Kalman gain matrix.
*/
bicycle_t bicycle(fixed_velocity, dynamics_period);
/*
* Initialize HandlebarDynamic object to estimate torque due to handlebar inertia.
* TODO: naming here is poor
*/
haptic::HandlebarDynamic handlebar_model(bicycle.model(), sa::HANDLEBAR_INERTIA);
observer_initializer<observer_t> oi;
oi.initialize(bicycle);
chTMObjectInit(&computation_time_measurement);
chTMObjectInit(&transmission_time_measurement);
/*
* Transmit initial message containing gitsha1, model, and observer data.
* This initial transmission is blocking.
*/
msg = msg_init;
msg.timestamp = chVTGetSystemTime();
message::set_simulation_full_model_observer(&msg, bicycle);
size_t bytes_written = write_message_to_encode_buffer(msg);
/* block until ready */
while ((SDU1.config->usbp->state != USB_ACTIVE) || (SDU1.state != SDU_READY)) {
chThdSleepMilliseconds(10);
}
/* transmit data */
if ((SDU1.config->usbp->state == USB_ACTIVE) && (SDU1.state == SDU_READY)) {
chTMStartMeasurementX(&transmission_time_measurement);
usbTransmit(SDU1.config->usbp, SDU1.config->bulk_in, packet_buffer.data(), bytes_written);
chTMStopMeasurementX(&transmission_time_measurement);
}
/*
* Normal main() thread activity, in this demo it simulates the bicycle
* dynamics in real-time (roughly).
*/
chThdCreateStatic(wa_kinematics_thread, sizeof(wa_kinematics_thread),
NORMALPRIO - 1, kinematics_thread, static_cast<void*>(&bicycle));
while (true) {
systime_t starttime = chVTGetSystemTime();
chTMStartMeasurementX(&computation_time_measurement);
constexpr float roll_torque = 0.0f;
/* get sensor measurements */
const float kistler_torque = static_cast<float>(
analog.get_adc12()*2.0f*sa::MAX_KISTLER_TORQUE/4096 -
sa::MAX_KISTLER_TORQUE);
const float motor_torque = static_cast<float>(
analog.get_adc13()*2.0f*sa::MAX_KOLLMORGEN_TORQUE/4096 -
sa::MAX_KOLLMORGEN_TORQUE);
const float steer_angle = angle::encoder_count<float>(encoder_steer);
const float rear_wheel_angle = -angle::encoder_count<float>(encoder_rear_wheel);
const float v = velocity_filter.output(
-sa::REAR_WHEEL_RADIUS*(angle::encoder_rate(encoder_rear_wheel)));
/* yaw angle, just use previous state value */
const float yaw_angle = angle::wrap(bicycle.pose().yaw);
/* calculate rider applied torque */
const float inertia_torque = -handlebar_model.feedback_torque(bicycle.observer().state());
const float steer_torque = kistler_torque - inertia_torque;
/* simulate bicycle */
bicycle.set_v(fixed_velocity);
bicycle.update_dynamics(roll_torque, steer_torque, yaw_angle, steer_angle, rear_wheel_angle);
/* generate handlebar torque output */
const dacsample_t handlebar_torque_dac = set_handlebar_torque(bicycle.handlebar_feedback_torque());
chTMStopMeasurementX(&computation_time_measurement);
/* prepare message for transmission */
msg = msg_init;
msg.timestamp = starttime;
message::set_bicycle_input(&msg.input,
(model_t::input_t() << roll_torque, steer_torque).finished());
msg.has_input = true;
message::set_simulation_state(&msg, bicycle);
message::set_simulation_auxiliary_state(&msg, bicycle);
if (std::is_same<observer_t, typename observer::Kalman<model_t>>::value) {
message::set_kalman_gain(&msg.kalman, bicycle.observer());
msg.has_kalman = true;
}
message::set_simulation_actuators(&msg, handlebar_torque_dac);
message::set_simulation_sensors(&msg,
analog.get_adc12(), analog.get_adc13(),
encoder_steer.count(), encoder_rear_wheel.count());
message::set_simulation_timing(&msg,
computation_time_measurement.last, transmission_time_measurement.last);
msg.feedback_torque = bicycle.handlebar_feedback_torque();
msg.has_feedback_torque = true;
size_t bytes_written = write_message_to_encode_buffer(msg);
/* transmit message */
if ((SDU1.config->usbp->state == USB_ACTIVE) && (SDU1.state == SDU_READY)) {
chTMStartMeasurementX(&transmission_time_measurement);
usbTransmit(SDU1.config->usbp, SDU1.config->bulk_in, packet_buffer.data(), bytes_written);
chTMStopMeasurementX(&transmission_time_measurement);
}
const systime_t looptime = MS2ST(static_cast<systime_t>(1000*bicycle.dt()));
const systime_t sleeptime = looptime + starttime - chVTGetSystemTime();
if (sleeptime >= looptime) {
//chDbgAssert(false, "deadline missed");
continue;
} else {
chThdSleep(sleeptime);
}
}
}
<commit_msg>Refactor comment type in Flimnap<commit_after>/*
ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio
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 "ch.h"
#include "hal.h"
#include "analog.h"
#include "encoder.h"
#include "encoderfoaw.h"
#include "packet/frame.h"
#include "packet/serialize.h"
#include "simulation.pb.h"
#include "messageutil.h"
#include "filter/movingaverage.h"
#include "angle.h"
#include "blink.h"
#include "usbconfig.h"
#include "saconfig.h"
#include "parameters.h"
#include <algorithm>
#include <array>
#include <type_traits>
#include "bicycle/kinematic.h" // simplified bicycle model
#include "bicycle/whipple.h" // whipple bicycle model
#include "oracle.h" // oracle observer
#include "kalman.h" // kalman filter observer
#include "haptic.h" // handlebar feedback
#include "simbicycle.h"
namespace {
#if defined(USE_BICYCLE_KINEMATIC_MODEL)
using model_t = model::BicycleKinematic;
using observer_t = observer::Oracle<model_t>;
using haptic_t = haptic::HandlebarStatic;
#else // defined(USE_BICYCLE_KINEMATIC_MODEL)
using model_t = model::BicycleWhipple;
using observer_t = observer::Kalman<model_t>;
using haptic_t = haptic::HandlebarDynamic;
#endif // defined(USE_BICYCLE_KINEMATIC_MODEL)
using bicycle_t = sim::Bicycle<model_t, observer_t, haptic_t>;
// sensors
Analog analog;
Encoder encoder_steer(sa::RLS_ROLIN_ENC, sa::RLS_ROLIN_ENC_INDEX_CFG);
EncoderFoaw<float, 32> encoder_rear_wheel(sa::RLS_GTS35_ENC,
sa::RLS_GTS35_ENC_CFG,
MS2ST(1), 3.0f);
filter::MovingAverage<float, 5> velocity_filter;
constexpr float fixed_velocity = 7.0f;
// transmission
std::array<uint8_t, SimulationMessage_size + packet::frame::PACKET_OVERHEAD> encode_buffer;
std::array<uint8_t, SimulationMessage_size + packet::frame::PACKET_OVERHEAD> packet_buffer;
SimulationMessage msg;
constexpr SimulationMessage msg_init = SimulationMessage_init_zero;
// kinematics loop
constexpr systime_t kinematics_loop_time = US2ST(8333); // update kinematics at 120 Hz
// dynamics loop
constexpr model::real_t dynamics_period = 0.005; //5 ms -> 200 Hz
time_measurement_t computation_time_measurement;
time_measurement_t transmission_time_measurement;
dacsample_t set_handlebar_torque(float handlebar_torque) {
int32_t saturated_value = (handlebar_torque/sa::MAX_KOLLMORGEN_TORQUE * 2048) +
sa::KOLLMORGEN_DAC_ZERO_OFFSET;
saturated_value = std::min<int32_t>(std::max<int32_t>(saturated_value, 0), 4096);
dacsample_t aout = static_cast<dacsample_t>(saturated_value);
dacPutChannelX(sa::KOLLM_DAC, 0, aout);
return aout;
}
void update_and_transmit_kinematics(bicycle_t& bicycle) {
bicycle.update_kinematics();
//
//TODO: Pose message should be transmitted asynchronously.
//After starting transmission, the simulation should start to calculate pose for the next timestep.
//This is currently not necessary given the observed timings.
//
//size_t bytes_encoded = packet::serialize::encode_delimited(bicycle.pose(),
// encode_buffer.data(), encode_buffer.size());
//TODO: clear message
//message::set_simulation_loop_values(&msg, bicycle);
//size_t bytes_encoded = packet::serialize::encode_delimited(
// msg, encode_buffer.data(), encode_buffer.size());
//size_t bytes_written = packet::frame::stuff(
// encode_buffer.data(), packet_buffer.data(), bytes_encoded);
//if ((SDU1.config->usbp->state == USB_ACTIVE) && (SDU1.state == SDU_READY)) {
// usbTransmit(SDU1.config->usbp, SDU1.config->bulk_in, packet_buffer.data(), bytes_written);
//}
}
template <typename T>
struct observer_initializer{
template <typename S = T>
typename std::enable_if<std::is_same<typename S::observer_t, observer::Kalman<model_t>>::value, void>::type
initialize(S& bicycle) {
typename S::observer_t& observer = bicycle.observer();
observer.set_Q(parameters::defaultvalue::kalman::Q(observer.dt()));
// Reduce steer measurement noise covariance
observer.set_R(parameters::defaultvalue::kalman::R/1000);
// prime the Kalman gain matrix
bicycle.prime_observer();
// We start with steer angle equal to the measurement and all other state elements at zero.
model_t::state_t x0 = model_t::state_t::Zero();
model_t::set_state_element(x0, model_t::state_index_t::steer_angle,
angle::encoder_count<float>(encoder_steer));
observer.set_x(x0);
}
template <typename S = T>
typename std::enable_if<!std::is_same<typename S::observer_t, observer::Kalman<model_t>>::value, void>::type
initialize(S& bicycle) {
// no-op
(void)bicycle;
}
};
THD_WORKING_AREA(wa_kinematics_thread, 2048);
THD_FUNCTION(kinematics_thread, arg) {
bicycle_t& bicycle = *static_cast<bicycle_t*>(arg);
chRegSetThreadName("kinematics");
while (true) {
systime_t starttime = chVTGetSystemTime();
update_and_transmit_kinematics(bicycle);
systime_t sleeptime = kinematics_loop_time + starttime - chVTGetSystemTime();
if (sleeptime >= kinematics_loop_time) {
continue;
} else {
chThdSleep(sleeptime);
}
}
}
size_t write_message_to_encode_buffer(const SimulationMessage& m) {
const size_t bytes_encoded = packet::serialize::encode_delimited(
m, encode_buffer.data(), encode_buffer.size());
return packet::frame::stuff(
encode_buffer.data(), packet_buffer.data(), bytes_encoded);
}
} // namespace
/*
* Application entry point.
*/
int main(void) {
//System initializations.
//- HAL initialization, this also initializes the configured device drivers
// and performs the board-specific initializations.
//- Kernel initialization, the main() function becomes a thread and the
// RTOS is active.
halInit();
chSysInit();
// Initialize a serial-over-USB CDC driver.
sduObjectInit(&SDU1);
sduStart(&SDU1, &serusbcfg);
//Activate the USB driver and then the USB bus pull-up on D+.
//Note, a delay is inserted in order to not have to disconnect the cable
//after a reset.
board_usb_lld_disconnect_bus(); //usbDisconnectBus(serusbcfg.usbp);
chThdSleepMilliseconds(1500);
usbStart(serusbcfg.usbp, &usbcfg);
board_usb_lld_connect_bus(); //usbConnectBus(serusbcfg.usbp);
// create the blink thread and print state monitor
chBlinkThreadCreateStatic();
// Start sensors.
// Encoder:
// Initialize encoder driver 5 on pins PA0, PA1 (EXT2-4, EXT2-8).
// Pins for encoder driver 3 are already set in board.h.
palSetLineMode(LINE_TIM5_CH1, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);
palSetLineMode(LINE_TIM5_CH2, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);
encoder_steer.start();
encoder_rear_wheel.start();
analog.start(1000); // trigger ADC conversion at 1 kHz
//Set torque measurement enable line low.
//The output of the Kistler torque sensor is not valid until after a falling edge
//on the measurement line and it is held low. The 'LINE_TORQUE_MEAS_EN' line is
//reversed due to NPN switch Q1.
palClearLine(LINE_TORQUE_MEAS_EN);
chThdSleepMilliseconds(1);
palSetLine(LINE_TORQUE_MEAS_EN);
// Start DAC1 driver and set output pin as analog as suggested in Reference Manual.
// The default line configuration is OUTPUT_OPENDRAIN_PULLUP for SPI1_ENC1_NSS
// and must be changed to use as analog output.
palSetLineMode(LINE_KOLLM_ACTL_TORQUE, PAL_MODE_INPUT_ANALOG);
dacStart(sa::KOLLM_DAC, sa::KOLLM_DAC_CFG);
set_handlebar_torque(0.0f);
// Initialize bicycle. The initial velocity is important as we use it to prime
// the Kalman gain matrix.
bicycle_t bicycle(fixed_velocity, dynamics_period);
// Initialize HandlebarDynamic object to estimate torque due to handlebar inertia.
// TODO: naming here is poor
haptic::HandlebarDynamic handlebar_model(bicycle.model(), sa::HANDLEBAR_INERTIA);
observer_initializer<observer_t> oi;
oi.initialize(bicycle);
chTMObjectInit(&computation_time_measurement);
chTMObjectInit(&transmission_time_measurement);
// Transmit initial message containing gitsha1, model, and observer data.
// This initial transmission is blocking.
msg = msg_init;
msg.timestamp = chVTGetSystemTime();
message::set_simulation_full_model_observer(&msg, bicycle);
size_t bytes_written = write_message_to_encode_buffer(msg);
// block until ready
while ((SDU1.config->usbp->state != USB_ACTIVE) || (SDU1.state != SDU_READY)) {
chThdSleepMilliseconds(10);
}
// transmit data
if ((SDU1.config->usbp->state == USB_ACTIVE) && (SDU1.state == SDU_READY)) {
chTMStartMeasurementX(&transmission_time_measurement);
usbTransmit(SDU1.config->usbp, SDU1.config->bulk_in, packet_buffer.data(), bytes_written);
chTMStopMeasurementX(&transmission_time_measurement);
}
// Normal main() thread activity, in this project it simulates the bicycle
// dynamics in real-time (roughly).
chThdCreateStatic(wa_kinematics_thread, sizeof(wa_kinematics_thread),
NORMALPRIO - 1, kinematics_thread, static_cast<void*>(&bicycle));
while (true) {
systime_t starttime = chVTGetSystemTime();
chTMStartMeasurementX(&computation_time_measurement);
constexpr float roll_torque = 0.0f;
// get sensor measurements
const float kistler_torque = static_cast<float>(
analog.get_adc12()*2.0f*sa::MAX_KISTLER_TORQUE/4096 -
sa::MAX_KISTLER_TORQUE);
const float motor_torque = static_cast<float>(
analog.get_adc13()*2.0f*sa::MAX_KOLLMORGEN_TORQUE/4096 -
sa::MAX_KOLLMORGEN_TORQUE);
const float steer_angle = angle::encoder_count<float>(encoder_steer);
const float rear_wheel_angle = -angle::encoder_count<float>(encoder_rear_wheel);
const float v = velocity_filter.output(
-sa::REAR_WHEEL_RADIUS*(angle::encoder_rate(encoder_rear_wheel)));
// yaw angle, just use previous state value
const float yaw_angle = angle::wrap(bicycle.pose().yaw);
// calculate rider applied torque
const float inertia_torque = -handlebar_model.feedback_torque(bicycle.observer().state());
const float steer_torque = kistler_torque - inertia_torque;
// simulate bicycle
bicycle.set_v(fixed_velocity);
bicycle.update_dynamics(roll_torque, steer_torque, yaw_angle, steer_angle, rear_wheel_angle);
// generate handlebar torque output
const dacsample_t handlebar_torque_dac = set_handlebar_torque(bicycle.handlebar_feedback_torque());
chTMStopMeasurementX(&computation_time_measurement);
// prepare message for transmission
msg = msg_init;
msg.timestamp = starttime;
message::set_bicycle_input(&msg.input,
(model_t::input_t() << roll_torque, steer_torque).finished());
msg.has_input = true;
message::set_simulation_state(&msg, bicycle);
message::set_simulation_auxiliary_state(&msg, bicycle);
if (std::is_same<observer_t, typename observer::Kalman<model_t>>::value) {
message::set_kalman_gain(&msg.kalman, bicycle.observer());
msg.has_kalman = true;
}
message::set_simulation_actuators(&msg, handlebar_torque_dac);
message::set_simulation_sensors(&msg,
analog.get_adc12(), analog.get_adc13(),
encoder_steer.count(), encoder_rear_wheel.count());
message::set_simulation_timing(&msg,
computation_time_measurement.last, transmission_time_measurement.last);
msg.feedback_torque = bicycle.handlebar_feedback_torque();
msg.has_feedback_torque = true;
size_t bytes_written = write_message_to_encode_buffer(msg);
// transmit message
if ((SDU1.config->usbp->state == USB_ACTIVE) && (SDU1.state == SDU_READY)) {
chTMStartMeasurementX(&transmission_time_measurement);
usbTransmit(SDU1.config->usbp, SDU1.config->bulk_in, packet_buffer.data(), bytes_written);
chTMStopMeasurementX(&transmission_time_measurement);
}
const systime_t looptime = MS2ST(static_cast<systime_t>(1000*bicycle.dt()));
const systime_t sleeptime = looptime + starttime - chVTGetSystemTime();
if (sleeptime >= looptime) {
//chDbgAssert(false, "deadline missed");
continue;
} else {
chThdSleep(sleeptime);
}
}
}
<|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 meegotouch-controlpanelsoundsettingsapplet.
**
** 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.
**
****************************************************************************/
#include "drilldownitem.h"
#include <MWidget>
#include <MLabel>
#include <MImageWidget>
#include <QGraphicsGridLayout>
#define DEBUG
#define WARNING
#include "../debug.h"
DrillDownItem::DrillDownItem (
MBasicListItem::ItemStyle style,
QGraphicsItem *parent) :
MBasicListItem (style, parent)
{
}
QGraphicsLayout *
DrillDownItem::createLayout()
{
QGraphicsGridLayout *layout;
MLabel *titleLabel;
MLabel *subTitleLabel;
MImageWidget *iconWidget;
MImageWidget *drillIconWidget;
layout = new QGraphicsGridLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
titleLabel = titleLabelWidget ();
subTitleLabel = subtitleLabelWidget ();
iconWidget = imageWidget();
drillIconWidget = new MImageWidget ();
drillIconWidget->setImage ("icon-m-common-drilldown-arrow");
// FIXME: According to the layout guide we should use CommonDrilldownIcon,
// but that does not look good. It makes the icon pixelated.
drillIconWidget->setStyleName ("CommonMainIcon");
titleLabel->setStyleName ("CommonTitleInverted");
subTitleLabel->setStyleName ("CommonSubTitleInverted");
switch (itemStyle()) {
case TitleWithSubtitle:
/*
* The title label.
*/
layout->addItem (titleLabel, 0, 0);
layout->setAlignment(titleLabel, Qt::AlignLeft | Qt::AlignVCenter);
/*
* The sub-title label.
*/
layout->addItem (subTitleLabel, 1, 0);
layout->setAlignment (subTitleLabel, Qt::AlignLeft | Qt::AlignVCenter);
/*
* The drill down icon.
*/
layout->addItem(drillIconWidget, 0, 1, 2, 1);
layout->setAlignment (drillIconWidget, Qt::AlignVCenter | Qt::AlignRight);
break;
case IconWithTitleAndSubtitle:
/*
* The left side icon.
*/
layout->addItem (iconWidget, 0, 0, 2, 1);
layout->setAlignment (iconWidget, Qt::AlignVCenter | Qt::AlignRight);
/*
* The title label.
*/
layout->addItem (titleLabel, 0, 1);
layout->setAlignment (titleLabel, Qt::AlignLeft | Qt::AlignVCenter);
/*
* The sub-title label.
*/
layout->addItem (subTitleLabel, 1, 1, Qt::AlignLeft | Qt::AlignVCenter);
/*
* The drill down icon.
*/
layout->addItem(drillIconWidget, 0, 2, 2, 1);
layout->setAlignment (drillIconWidget, Qt::AlignVCenter | Qt::AlignRight);
break;
case IconWithTitle:
/*
* The left side icon.
*/
layout->addItem (iconWidget, 0, 0);
layout->setAlignment (iconWidget, Qt::AlignVCenter | Qt::AlignRight);
/*
* The title label.
*/
layout->addItem (titleLabel, 0, 1);
layout->setAlignment (titleLabel, Qt::AlignLeft | Qt::AlignVCenter);
/*
* The drill down icon.
*/
layout->addItem(drillIconWidget, 0, 2);
layout->setAlignment (drillIconWidget, Qt::AlignVCenter | Qt::AlignRight);
break;
default:
SYS_WARNING ("itemStyle not supported.");
}
setStyleName ("CommonPanelInverted");
return layout;
}
<commit_msg>Fixes: Use the proper style name for drilldown icon in theme-aplet<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 meegotouch-controlpanelsoundsettingsapplet.
**
** 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.
**
****************************************************************************/
#include "drilldownitem.h"
#include <MWidget>
#include <MLabel>
#include <MImageWidget>
#include <QGraphicsGridLayout>
#define DEBUG
#define WARNING
#include "../debug.h"
DrillDownItem::DrillDownItem (
MBasicListItem::ItemStyle style,
QGraphicsItem *parent) :
MBasicListItem (style, parent)
{
}
QGraphicsLayout *
DrillDownItem::createLayout()
{
QGraphicsGridLayout *layout;
MLabel *titleLabel;
MLabel *subTitleLabel;
MImageWidget *iconWidget;
MImageWidget *drillIconWidget;
layout = new QGraphicsGridLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
titleLabel = titleLabelWidget ();
subTitleLabel = subtitleLabelWidget ();
iconWidget = imageWidget();
drillIconWidget = new MImageWidget ();
drillIconWidget->setImage ("icon-m-common-drilldown-arrow");
drillIconWidget->setStyleName ("CommonDrillDownIcon");
titleLabel->setStyleName ("CommonTitleInverted");
subTitleLabel->setStyleName ("CommonSubTitleInverted");
switch (itemStyle()) {
case TitleWithSubtitle:
/*
* The title label.
*/
layout->addItem (titleLabel, 0, 0);
layout->setAlignment(titleLabel, Qt::AlignLeft | Qt::AlignVCenter);
/*
* The sub-title label.
*/
layout->addItem (subTitleLabel, 1, 0);
layout->setAlignment (subTitleLabel, Qt::AlignLeft | Qt::AlignVCenter);
/*
* The drill down icon.
*/
layout->addItem(drillIconWidget, 0, 1, 2, 1);
layout->setAlignment (drillIconWidget, Qt::AlignVCenter | Qt::AlignRight);
break;
case IconWithTitleAndSubtitle:
/*
* The left side icon.
*/
layout->addItem (iconWidget, 0, 0, 2, 1);
layout->setAlignment (iconWidget, Qt::AlignVCenter | Qt::AlignRight);
/*
* The title label.
*/
layout->addItem (titleLabel, 0, 1);
layout->setAlignment (titleLabel, Qt::AlignLeft | Qt::AlignVCenter);
/*
* The sub-title label.
*/
layout->addItem (subTitleLabel, 1, 1, Qt::AlignLeft | Qt::AlignVCenter);
/*
* The drill down icon.
*/
layout->addItem(drillIconWidget, 0, 2, 2, 1);
layout->setAlignment (drillIconWidget, Qt::AlignVCenter | Qt::AlignRight);
break;
case IconWithTitle:
/*
* The left side icon.
*/
layout->addItem (iconWidget, 0, 0);
layout->setAlignment (iconWidget, Qt::AlignVCenter | Qt::AlignRight);
/*
* The title label.
*/
layout->addItem (titleLabel, 0, 1);
layout->setAlignment (titleLabel, Qt::AlignLeft | Qt::AlignVCenter);
/*
* The drill down icon.
*/
layout->addItem(drillIconWidget, 0, 2);
layout->setAlignment (drillIconWidget, Qt::AlignVCenter | Qt::AlignRight);
break;
default:
SYS_WARNING ("itemStyle not supported.");
}
setStyleName ("CommonPanelInverted");
return layout;
}
<|endoftext|> |
<commit_before>#line 2 "togo/gfx/renderer/private.ipp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#pragma once
#include <togo/config.hpp>
#include <togo/gfx/types.hpp>
#include <togo/gfx/renderer/types.hpp>
#include <togo/gfx/renderer/private.hpp>
namespace togo {
namespace gfx {
#define TOGO_GFX_RENDERER_TEARDOWN_RA_(ra, func_destroy) \
if (renderer->ra._num > 0) { \
for (auto const& slot : renderer->ra._slots) { \
if (slot.id._value != ID_VALUE_NULL) { \
renderer::func_destroy(renderer, slot.id); \
} \
} \
}
void renderer::teardown_base(gfx::Renderer* const renderer) {
TOGO_GFX_RENDERER_TEARDOWN_RA_(_buffers, destroy_buffer);
TOGO_GFX_RENDERER_TEARDOWN_RA_(_buffer_bindings, destroy_buffer_binding);
//TOGO_GFX_RENDERER_TEARDOWN_RA_(_textures, destroy_texture);
//TOGO_GFX_RENDERER_TEARDOWN_RA_(_uniforms, destroy_uniform);
TOGO_GFX_RENDERER_TEARDOWN_RA_(_shaders, destroy_shader);
for (auto& pb_name_hash : renderer->_fixed_param_blocks) {
pb_name_hash = gfx::PB_NAME_NULL;
}
renderer->_num_active_draw_param_blocks = 0;
}
} // namespace gfx
} // namespace togo
<commit_msg>gfx/renderer/private: destroy generator defs on teardown.<commit_after>#line 2 "togo/gfx/renderer/private.ipp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#pragma once
#include <togo/config.hpp>
#include <togo/gfx/types.hpp>
#include <togo/gfx/renderer/types.hpp>
#include <togo/gfx/renderer/private.hpp>
namespace togo {
namespace gfx {
#define TOGO_GFX_RENDERER_TEARDOWN_RA_(ra, func_destroy) \
if (renderer->ra._num > 0) { \
for (auto const& slot : renderer->ra._slots) { \
if (slot.id._value != ID_VALUE_NULL) { \
renderer::func_destroy(renderer, slot.id); \
} \
} \
}
void renderer::teardown_base(gfx::Renderer* const renderer) {
TOGO_GFX_RENDERER_TEARDOWN_RA_(_buffers, destroy_buffer);
TOGO_GFX_RENDERER_TEARDOWN_RA_(_buffer_bindings, destroy_buffer_binding);
//TOGO_GFX_RENDERER_TEARDOWN_RA_(_textures, destroy_texture);
//TOGO_GFX_RENDERER_TEARDOWN_RA_(_uniforms, destroy_uniform);
TOGO_GFX_RENDERER_TEARDOWN_RA_(_shaders, destroy_shader);
for (auto& pb_name_hash : renderer->_fixed_param_blocks) {
pb_name_hash = gfx::PB_NAME_NULL;
}
renderer->_num_active_draw_param_blocks = 0;
for (auto& entry : renderer->_generators) {
entry.value.func_destroy(entry.value, renderer);
}
hash_map::clear(renderer->_generators);
}
} // namespace gfx
} // namespace togo
<|endoftext|> |
<commit_before>
/*
* client.cpp
*
* Handles the client env.
*
* Created by Ryan Faulkner on 2014-06-08
* Copyright (c) 2014. All rights reserved.
*/
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>
#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"
#include "bayes.h"
#define REDISHOST "127.0.0.1"
#define REDISPORT 6379
using namespace std;
/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
RedisHandler r;
r.connect();
r.write("foo", "bar");
}
/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
RedisHandler r;
r.connect();
cout << endl << "VALUE FOR KEY foo" << endl;
cout << r.read("foo") << endl << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
RedisHandler r;
std::vector<std::string> vec;
r.connect();
vec = r.keys("*");
cout << "KEY LIST FOR *" << endl;
for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
cout << *it << endl;
}
cout << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
RedisHandler r;
std::vector<string>* vec;
std::string outTrue, outFalse = "";
r.connect();
r.write("test_key", "test value");
outTrue = r.read("test_key");
assert(std::strcmp(outTrue.c_str(), "test value") == 0);
r.deleteKey("test_key");
assert(!r.exists("test_key"));
}
/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}
/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
IntegerColumn ic;
FloatColumn fc;
assert(ic.validate("1981"));
assert(fc.validate("5.2"));
cout << "Passed regex tests." << endl;
}
/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
IndexHandler ih;
assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
cout << "Passed orderPairAlphaNumeric tests." << endl;
}
/**
* Test to ensure that relation entities are encoded properly
*/
void testJSONEntityEncoding() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
ih.fetchEntity("test", json); // Fetch the entity representation
cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;
// Assert that entity as read matches definition
assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
json["fields"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test"); // Remove the entity
}
/**
* Test to ensure that relation fields are encoded properly
*/
void testJSONRelationEncoding() {
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent_1;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent_2;
std::vector<std::pair<std::string, std::string>> fields_rel_1;
std::vector<std::pair<std::string, std::string>> fields_rel_2;
// Popualate fields
fields_ent_1.push_back(std::make_pair(getColumnType("integer"), "a"));
fields_ent_2.push_back(std::make_pair(getColumnType("string"), "b"));
fields_rel_1.push_back(std::make_pair("a", "1"));
fields_rel_2.push_back(std::make_pair("b", "hello"));
// Create entities
Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2);
ih.writeEntity(e1);
ih.writeEntity(e2);
// Create relation in redis
Relation r("test_1", "test_2", fields_rel_1, fields_rel_2);
ih.writeRelation(r);
// Fetch the entity representation
ret = ih.fetchRelationPrefix("test_1", "test_2");
cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;
// Assert that entity as read matches definition
assert(
std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
ret[0]["fields_left"]["_itemcount"].asInt() == 1 &&
ret[0]["fields_right"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test_1"); // Remove the entity
ih.removeEntity("test_2"); // Remove the entity
ih.removeRelation(r); // Remove the relation
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to integer fields
*/
void testFieldAssignTypeMismatchInteger() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
!ih.validateEntityFieldType("test", "a", "1.0") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to float fields
*/
void testFieldAssignTypeMismatchFloat() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("float"), "a")); // Create fields
Entity e("test", fields_ent); // Create the entity
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1.2") &&
ih.validateEntityFieldType("test", "a", "12.5") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to string fields
*/
void testFieldAssignTypeMismatchString() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("string"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that existsEntityField correctly flags when entity does not contain a field
*/
void testEntityDoesNotContainField() {
// TODO - implement
}
/**
* Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct
*/
void testComputeMarginal() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
long num_relations = ih.getRelationCountTotal();
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel);
Relation r2("_x", "_y", fields_rel, fields_rel);
Relation r3("_x", "_z", fields_rel, fields_rel);
Relation r4("_x", "_z", fields_rel, fields_rel);
Relation r5("_w", "_y", fields_rel, fields_rel);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
// Ensure marginal likelihood reflects the number of relations that contain each entity
valpair attrs;
// TODO - fix computeMarginal seg fault
cout << bayes.computeMarginal(e1.name, attrs) << endl;
assert(bayes.computeMarginal(e1.name, attrs) == 4.0 / 5.0);
assert(bayes.computeMarginal(e2.name, attrs) == 3.0 / 5.0);
assert(bayes.computeMarginal(e3.name, attrs) == 2.0 / 5.0);
assert(bayes.computeMarginal(e4.name, attrs) == 1.0 / 5.0);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
// Reset the relations count
ih.setRelationCountTotal(num_relations);
}
/**
* Tests that removal of entities functions properly
*/
void testEntityRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations functions properly
*/
void testRelationRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations cascading on entities functions properly
*/
void testEntityCascadeRemoval() {
// TODO - implement
}
int main() {
cout << "-- TESTS BEGIN --" << endl << endl;
// testRedisSet();
// testRedisGet();
// testRedisKeys();
// md5Hashing();
// testRedisIO();
// testRegexForTypes();
// testOrderPairAlphaNumeric();
// testJSONEntityEncoding();
// testJSONRelationEncoding();
// testFieldAssignTypeMismatchInteger();
// testFieldAssignTypeMismatchFloat();
// testFieldAssignTypeMismatchString();
testComputeMarginal();
cout << endl << "-- TESTS END --" << endl;
return 0;
}
<commit_msg>add test stub for relation filtering<commit_after>
/*
* client.cpp
*
* Handles the client env.
*
* Created by Ryan Faulkner on 2014-06-08
* Copyright (c) 2014. All rights reserved.
*/
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>
#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"
#include "bayes.h"
#define REDISHOST "127.0.0.1"
#define REDISPORT 6379
using namespace std;
/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
RedisHandler r;
r.connect();
r.write("foo", "bar");
}
/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
RedisHandler r;
r.connect();
cout << endl << "VALUE FOR KEY foo" << endl;
cout << r.read("foo") << endl << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
RedisHandler r;
std::vector<std::string> vec;
r.connect();
vec = r.keys("*");
cout << "KEY LIST FOR *" << endl;
for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
cout << *it << endl;
}
cout << endl;
}
/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
RedisHandler r;
std::vector<string>* vec;
std::string outTrue, outFalse = "";
r.connect();
r.write("test_key", "test value");
outTrue = r.read("test_key");
assert(std::strcmp(outTrue.c_str(), "test value") == 0);
r.deleteKey("test_key");
assert(!r.exists("test_key"));
}
/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}
/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
IntegerColumn ic;
FloatColumn fc;
assert(ic.validate("1981"));
assert(fc.validate("5.2"));
cout << "Passed regex tests." << endl;
}
/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
IndexHandler ih;
assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
cout << "Passed orderPairAlphaNumeric tests." << endl;
}
/**
* Test to ensure that relation entities are encoded properly
*/
void testJSONEntityEncoding() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
ih.fetchEntity("test", json); // Fetch the entity representation
cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;
// Assert that entity as read matches definition
assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
json["fields"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test"); // Remove the entity
}
/**
* Test to ensure that relation fields are encoded properly
*/
void testJSONRelationEncoding() {
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent_1;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent_2;
std::vector<std::pair<std::string, std::string>> fields_rel_1;
std::vector<std::pair<std::string, std::string>> fields_rel_2;
// Popualate fields
fields_ent_1.push_back(std::make_pair(getColumnType("integer"), "a"));
fields_ent_2.push_back(std::make_pair(getColumnType("string"), "b"));
fields_rel_1.push_back(std::make_pair("a", "1"));
fields_rel_2.push_back(std::make_pair("b", "hello"));
// Create entities
Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2);
ih.writeEntity(e1);
ih.writeEntity(e2);
// Create relation in redis
Relation r("test_1", "test_2", fields_rel_1, fields_rel_2);
ih.writeRelation(r);
// Fetch the entity representation
ret = ih.fetchRelationPrefix("test_1", "test_2");
cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;
// Assert that entity as read matches definition
assert(
std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
ret[0]["fields_left"]["_itemcount"].asInt() == 1 &&
ret[0]["fields_right"]["_itemcount"].asInt() == 1
);
ih.removeEntity("test_1"); // Remove the entity
ih.removeEntity("test_2"); // Remove the entity
ih.removeRelation(r); // Remove the relation
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to integer fields
*/
void testFieldAssignTypeMismatchInteger() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
!ih.validateEntityFieldType("test", "a", "1.0") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to float fields
*/
void testFieldAssignTypeMismatchFloat() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("float"), "a")); // Create fields
Entity e("test", fields_ent); // Create the entity
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1.2") &&
ih.validateEntityFieldType("test", "a", "12.5") &&
!ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that parseEntityAssignField correctly flags invalid assignments to string fields
*/
void testFieldAssignTypeMismatchString() {
IndexHandler ih;
Json::Value json;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
fields_ent.push_back(std::make_pair(getColumnType("string"), "a")); // Create fields
Entity e("test", fields_ent);
ih.writeEntity(e); // Create the entity
assert(
ih.validateEntityFieldType("test", "a", "1") &&
ih.validateEntityFieldType("test", "a", "12345") &&
ih.validateEntityFieldType("test", "a", "string")
);
ih.removeEntity("test");
}
/**
* Tests that existsEntityField correctly flags when entity does not contain a field
*/
void testEntityDoesNotContainField() {
// TODO - implement
}
/**
* Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct
*/
void testComputeMarginal() {
Bayes bayes;
IndexHandler ih;
std::vector<Json::Value> ret;
std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
std::vector<std::pair<std::string, std::string>> fields_rel;
long num_relations = ih.getRelationCountTotal();
// declare three entities
Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);
ih.writeEntity(e1);
ih.writeEntity(e2);
ih.writeEntity(e3);
ih.writeEntity(e4);
// construct a number of relations
Relation r1("_x", "_y", fields_rel, fields_rel);
Relation r2("_x", "_y", fields_rel, fields_rel);
Relation r3("_x", "_z", fields_rel, fields_rel);
Relation r4("_x", "_z", fields_rel, fields_rel);
Relation r5("_w", "_y", fields_rel, fields_rel);
ih.writeRelation(r1);
ih.writeRelation(r2);
ih.writeRelation(r3);
ih.writeRelation(r4);
ih.writeRelation(r5);
// Ensure marginal likelihood reflects the number of relations that contain each entity
valpair attrs;
// TODO - fix computeMarginal seg fault
cout << bayes.computeMarginal(e1.name, attrs) << endl;
assert(bayes.computeMarginal(e1.name, attrs) == 4.0 / 5.0);
assert(bayes.computeMarginal(e2.name, attrs) == 3.0 / 5.0);
assert(bayes.computeMarginal(e3.name, attrs) == 2.0 / 5.0);
assert(bayes.computeMarginal(e4.name, attrs) == 1.0 / 5.0);
ih.removeEntity("_w");
ih.removeEntity("_x");
ih.removeEntity("_y");
ih.removeEntity("_z");
ih.removeRelation(r1);
ih.removeRelation(r2);
ih.removeRelation(r3);
ih.removeRelation(r4);
ih.removeRelation(r5);
// Reset the relations count
ih.setRelationCountTotal(num_relations);
}
/**
* Tests that removal of entities functions properly
*/
void testEntityRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations functions properly
*/
void testRelationRemoval() {
// TODO - implement
}
/**
* Tests that removal of relations cascading on entities functions properly
*/
void testEntityCascadeRemoval() {
// TODO - implement
}
/**
* Tests that the correct relations are filtered from a set
*/
void testRelationFiltering() {
// TODO - implement
}
int main() {
cout << "-- TESTS BEGIN --" << endl << endl;
// testRedisSet();
// testRedisGet();
// testRedisKeys();
// md5Hashing();
// testRedisIO();
// testRegexForTypes();
// testOrderPairAlphaNumeric();
// testJSONEntityEncoding();
// testJSONRelationEncoding();
// testFieldAssignTypeMismatchInteger();
// testFieldAssignTypeMismatchFloat();
// testFieldAssignTypeMismatchString();
testComputeMarginal();
cout << endl << "-- TESTS END --" << endl;
return 0;
}
<|endoftext|> |
<commit_before>/// \file multipath_mapper.cpp
///
/// unit tests for the multipath mapper
#include <iostream>
#include "json2pb.h"
#include "vg.pb.h"
#include "../multipath_mapper.hpp"
#include "catch.hpp"
namespace vg {
namespace unittest {
TEST_CASE( "MultipathMapper::read_coverage works", "[multipath][mapping][multipathmapper]" ) {
// Make up some MEMs
// GCSA range_type is just a pair of [start, end], so we can fake them.
// This will actually own the MEMs
vector<MaximalExactMatch> mems;
// This will hold our MEMs and their start positions in the imaginary graph.
vector<pair<const MaximalExactMatch*, pos_t>> mem_hits;
// We need a fake read
string read("GATTACA");
SECTION("No hits cover no bases") {
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == 0);
}
SECTION("A hit of zero length covers 0 bases") {
// Make a MEM hit
mems.emplace_back(read.begin(), read.begin(), make_pair(5, 5), 1);
// Drop it on some arbitrary node
mem_hits.emplace_back(&mems.back(), make_pos_t(999, false, 3));
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == 0);
}
SECTION("A hit that one-past-the-ends just after its start position covers 1 base") {
// Make a MEM hit
mems.emplace_back(read.begin(), read.begin() + 1, make_pair(5, 5), 1);
// Drop it on some arbitrary node
mem_hits.emplace_back(&mems.back(), make_pos_t(999, false, 3));
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == 1);
}
SECTION("A hit that ends at the end of the string covers the string") {
// Make a MEM hit
mems.emplace_back(read.begin(), read.end(), make_pair(5, 5), 1);
// Drop it on some arbitrary node
mem_hits.emplace_back(&mems.back(), make_pos_t(999, false, 3));
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == read.size());
}
SECTION("Two overlapping hits still only cover the string once") {
// Make a MEM hit
mems.emplace_back(read.begin(), read.begin() + 5, make_pair(5, 5), 1);
// Drop it on some arbitrary node
mem_hits.emplace_back(&mems.back(), make_pos_t(999, false, 3));
// Do it again
mems.emplace_back(read.begin() + 2, read.end(), make_pair(6, 6), 1);
mem_hits.emplace_back(&mems.back(), make_pos_t(888, false, 3));
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == read.size());
}
SECTION("Two abutting hits cover the string") {
// Make a MEM hit
mems.emplace_back(read.begin(), read.begin() + 3, make_pair(5, 5), 1);
// Drop it on some arbitrary node
mem_hits.emplace_back(&mems.back(), make_pos_t(999, false, 3));
// Do it again
mems.emplace_back(read.begin() + 3, read.end(), make_pair(6, 6), 1);
mem_hits.emplace_back(&mems.back(), make_pos_t(888, false, 3));
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == read.size());
}
}
TEST_CASE( "MultipathMapper can map to a one-node graph", "[multipath][mapping][multipathmapper]" ) {
string graph_json = R"({
"node": [{"id": 1, "sequence": "GATTACA"}],
"path": [
{"name": "ref", "mapping": [
{"position": {"node_id": 1}, "edit": [{"from_length": 7, "to_length": 7}]}
]}
]
})";
// Load the JSON
Graph proto_graph;
json2pb(proto_graph, graph_json.c_str(), graph_json.size());
// Make it into a VG
VG graph;
graph.extend(proto_graph);
// Configure GCSA temp directory to the system temp directory
gcsa::TempFile::setDirectory(find_temp_dir());
// And make it quiet
gcsa::Verbosity::set(gcsa::Verbosity::SILENT);
// Make pointers to fill in
gcsa::GCSA* gcsaidx = nullptr;
gcsa::LCPArray* lcpidx = nullptr;
// Build the GCSA index
graph.build_gcsa_lcp(gcsaidx, lcpidx, 16, false, false, 3);
// Build the xg index
xg::XG xg_index(proto_graph);
// Make a multipath mapper to map against the graph.
MultipathMapper mapper(&xg_index, gcsaidx, lcpidx);
// Lower the max mapping quality so that it thinks it can find unambiguous mappings of
// short sequences
mapper.max_mapping_quality = 10;
SECTION( "MultipathMapper can map a short fake read" ) {
// Make the alignment
string read = "GAT";
Alignment aln;
aln.set_sequence(read);
// Have a list to fill with results
vector<MultipathAlignment> results;
// Align for just one alignment
mapper.multipath_map(aln, results, 1);
SECTION("there should be one alignment") {
REQUIRE(results.size() == 1);
auto& aligned = results.front();
SECTION("which should have one subpath") {
REQUIRE(aligned.subpath_size() == 1);
auto& subpath = aligned.subpath(0);
SECTION("which should have one mapping") {
REQUIRE(subpath.path().mapping_size() == 1);
auto& mapping = subpath.path().mapping(0);
SECTION("which should be at the start of node 1") {
REQUIRE(mapping.position().node_id() == 1);
REQUIRE(mapping.position().offset() == 0);
REQUIRE(mapping.position().is_reverse() == false);
}
SECTION("which should have one edit") {
REQUIRE(mapping.edit_size() == 1);
auto& edit = mapping.edit(0);
SECTION("which should be a length 3 perfect match") {
REQUIRE(edit.from_length() == 3);
REQUIRE(edit.to_length() == 3);
REQUIRE(edit.sequence() == "");
}
}
}
}
}
}
SECTION( "MultipathMapper can map two tiny paired reads" ) {
// Here are two reads in opposing, inward-facing directions
Alignment read1, read2;
read1.set_sequence("GAT");
read2.set_sequence("ACA");
// Have a list to fill with results
vector<pair<MultipathAlignment, MultipathAlignment>> results;
vector<pair<Alignment, Alignment>> buffer;
// Align for just one pair of alignments
mapper.multipath_map_paired(read1, read2, results, buffer, 1);
SECTION("there should be one pair of alignments") {
REQUIRE(results.size() == 1);
auto& aligned1 = results.front().first;
auto& aligned2 = results.front().second;
SECTION("each read should have one subpath") {
REQUIRE(aligned1.subpath_size() == 1);
REQUIRE(aligned2.subpath_size() == 1);
auto& subpath1 = aligned1.subpath(0);
auto& subpath2 = aligned2.subpath(0);
SECTION("each should have one mapping") {
REQUIRE(subpath1.path().mapping_size() == 1);
REQUIRE(subpath2.path().mapping_size() == 1);
auto& mapping1 = subpath1.path().mapping(0);
auto& mapping2 = subpath2.path().mapping(0);
SECTION("the first should be at the start of node 1") {
REQUIRE(mapping1.position().node_id() == 1);
REQUIRE(mapping1.position().offset() == 0);
REQUIRE(mapping1.position().is_reverse() == false);
}
SECTION("the second should be further along the same node") {
REQUIRE(mapping2.position().node_id() == 1);
REQUIRE(mapping2.position().offset() == 4);
REQUIRE(mapping2.position().is_reverse() == false);
}
SECTION("each should have one edit") {
REQUIRE(mapping1.edit_size() == 1);
REQUIRE(mapping2.edit_size() == 1);
auto& edit1 = mapping1.edit(0);
auto& edit2 = mapping2.edit(0);
SECTION("which should be a length 3 perfect match") {
REQUIRE(edit1.from_length() == 3);
REQUIRE(edit1.to_length() == 3);
REQUIRE(edit1.sequence() == "");
REQUIRE(edit2.from_length() == 3);
REQUIRE(edit2.to_length() == 3);
REQUIRE(edit2.sequence() == "");
}
}
}
}
}
}
// Clean up the GCSA/LCP index
delete gcsaidx;
delete lcpidx;
}
}
}
<commit_msg>Fix test not to alter pointed-to vector<commit_after>/// \file multipath_mapper.cpp
///
/// unit tests for the multipath mapper
#include <iostream>
#include "json2pb.h"
#include "vg.pb.h"
#include "../multipath_mapper.hpp"
#include "catch.hpp"
namespace vg {
namespace unittest {
TEST_CASE( "MultipathMapper::read_coverage works", "[multipath][mapping][multipathmapper]" ) {
// Make up some MEMs
// GCSA range_type is just a pair of [start, end], so we can fake them.
// This will actually own the MEMs
vector<MaximalExactMatch> mems;
// This will hold our MEMs and their start positions in the imaginary graph.
vector<pair<const MaximalExactMatch*, pos_t>> mem_hits;
// We need a fake read
string read("GATTACA");
SECTION("No hits cover no bases") {
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == 0);
}
SECTION("A hit of zero length covers 0 bases") {
// Make a MEM hit
mems.emplace_back(read.begin(), read.begin(), make_pair(5, 5), 1);
// Drop it on some arbitrary node
mem_hits.emplace_back(&mems.back(), make_pos_t(999, false, 3));
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == 0);
}
SECTION("A hit that one-past-the-ends just after its start position covers 1 base") {
// Make a MEM hit
mems.emplace_back(read.begin(), read.begin() + 1, make_pair(5, 5), 1);
// Drop it on some arbitrary node
mem_hits.emplace_back(&mems.back(), make_pos_t(999, false, 3));
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == 1);
}
SECTION("A hit that ends at the end of the string covers the string") {
// Make a MEM hit
mems.emplace_back(read.begin(), read.end(), make_pair(5, 5), 1);
// Drop it on some arbitrary node
mem_hits.emplace_back(&mems.back(), make_pos_t(999, false, 3));
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == read.size());
}
SECTION("Two overlapping hits still only cover the string once") {
// Make a MEM hit
mems.emplace_back(read.begin(), read.begin() + 5, make_pair(5, 5), 1);
// Drop it on some arbitrary node
// Do it again
mems.emplace_back(read.begin() + 2, read.end(), make_pair(6, 6), 1);
// Point into vector *after* it's done.
mem_hits.emplace_back(&mems[0], make_pos_t(999, false, 3));
mem_hits.emplace_back(&mems[1], make_pos_t(888, false, 3));
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == read.size());
}
SECTION("Two abutting hits cover the string") {
// Make a MEM hit
mems.emplace_back(read.begin(), read.begin() + 3, make_pair(5, 5), 1);
// Do it again
mems.emplace_back(read.begin() + 3, read.end(), make_pair(6, 6), 1);
// Point into vector *after* it's done.
mem_hits.emplace_back(&mems[0], make_pos_t(999, false, 3));
mem_hits.emplace_back(&mems[1], make_pos_t(888, false, 3));
auto covered = MultipathMapper::read_coverage(mem_hits);
REQUIRE(covered == read.size());
}
}
TEST_CASE( "MultipathMapper can map to a one-node graph", "[multipath][mapping][multipathmapper]" ) {
string graph_json = R"({
"node": [{"id": 1, "sequence": "GATTACA"}],
"path": [
{"name": "ref", "mapping": [
{"position": {"node_id": 1}, "edit": [{"from_length": 7, "to_length": 7}]}
]}
]
})";
// Load the JSON
Graph proto_graph;
json2pb(proto_graph, graph_json.c_str(), graph_json.size());
// Make it into a VG
VG graph;
graph.extend(proto_graph);
// Configure GCSA temp directory to the system temp directory
gcsa::TempFile::setDirectory(find_temp_dir());
// And make it quiet
gcsa::Verbosity::set(gcsa::Verbosity::SILENT);
// Make pointers to fill in
gcsa::GCSA* gcsaidx = nullptr;
gcsa::LCPArray* lcpidx = nullptr;
// Build the GCSA index
graph.build_gcsa_lcp(gcsaidx, lcpidx, 16, false, false, 3);
// Build the xg index
xg::XG xg_index(proto_graph);
// Make a multipath mapper to map against the graph.
MultipathMapper mapper(&xg_index, gcsaidx, lcpidx);
// Lower the max mapping quality so that it thinks it can find unambiguous mappings of
// short sequences
mapper.max_mapping_quality = 10;
SECTION( "MultipathMapper can map a short fake read" ) {
// Make the alignment
string read = "GAT";
Alignment aln;
aln.set_sequence(read);
// Have a list to fill with results
vector<MultipathAlignment> results;
// Align for just one alignment
mapper.multipath_map(aln, results, 1);
SECTION("there should be one alignment") {
REQUIRE(results.size() == 1);
auto& aligned = results.front();
SECTION("which should have one subpath") {
REQUIRE(aligned.subpath_size() == 1);
auto& subpath = aligned.subpath(0);
SECTION("which should have one mapping") {
REQUIRE(subpath.path().mapping_size() == 1);
auto& mapping = subpath.path().mapping(0);
SECTION("which should be at the start of node 1") {
REQUIRE(mapping.position().node_id() == 1);
REQUIRE(mapping.position().offset() == 0);
REQUIRE(mapping.position().is_reverse() == false);
}
SECTION("which should have one edit") {
REQUIRE(mapping.edit_size() == 1);
auto& edit = mapping.edit(0);
SECTION("which should be a length 3 perfect match") {
REQUIRE(edit.from_length() == 3);
REQUIRE(edit.to_length() == 3);
REQUIRE(edit.sequence() == "");
}
}
}
}
}
}
SECTION( "MultipathMapper can map two tiny paired reads" ) {
// Here are two reads in opposing, inward-facing directions
Alignment read1, read2;
read1.set_sequence("GAT");
read2.set_sequence("ACA");
// Have a list to fill with results
vector<pair<MultipathAlignment, MultipathAlignment>> results;
vector<pair<Alignment, Alignment>> buffer;
// Align for just one pair of alignments
mapper.multipath_map_paired(read1, read2, results, buffer, 1);
SECTION("there should be one pair of alignments") {
REQUIRE(results.size() == 1);
auto& aligned1 = results.front().first;
auto& aligned2 = results.front().second;
SECTION("each read should have one subpath") {
REQUIRE(aligned1.subpath_size() == 1);
REQUIRE(aligned2.subpath_size() == 1);
auto& subpath1 = aligned1.subpath(0);
auto& subpath2 = aligned2.subpath(0);
SECTION("each should have one mapping") {
REQUIRE(subpath1.path().mapping_size() == 1);
REQUIRE(subpath2.path().mapping_size() == 1);
auto& mapping1 = subpath1.path().mapping(0);
auto& mapping2 = subpath2.path().mapping(0);
SECTION("the first should be at the start of node 1") {
REQUIRE(mapping1.position().node_id() == 1);
REQUIRE(mapping1.position().offset() == 0);
REQUIRE(mapping1.position().is_reverse() == false);
}
SECTION("the second should be further along the same node") {
REQUIRE(mapping2.position().node_id() == 1);
REQUIRE(mapping2.position().offset() == 4);
REQUIRE(mapping2.position().is_reverse() == false);
}
SECTION("each should have one edit") {
REQUIRE(mapping1.edit_size() == 1);
REQUIRE(mapping2.edit_size() == 1);
auto& edit1 = mapping1.edit(0);
auto& edit2 = mapping2.edit(0);
SECTION("which should be a length 3 perfect match") {
REQUIRE(edit1.from_length() == 3);
REQUIRE(edit1.to_length() == 3);
REQUIRE(edit1.sequence() == "");
REQUIRE(edit2.from_length() == 3);
REQUIRE(edit2.to_length() == 3);
REQUIRE(edit2.sequence() == "");
}
}
}
}
}
}
// Clean up the GCSA/LCP index
delete gcsaidx;
delete lcpidx;
}
}
}
<|endoftext|> |
<commit_before>// Lesson 13.cpp : Defines the entry point for the console application.
#include <render_framework\render_framework.h>
#pragma comment (lib , "Render Framework" )
using namespace std;
using namespace glm;
using namespace render_framework;
int main()
{
// Initialize the renderer
if (!renderer::get_instance().initialise()) return -1;
// Set the clear colour to cyan
glClearColor(0.0f, 1.0f, 1.0f, 1.0f);
/* Set the projection matrix */
// First get the aspect ratio (width/height)
float aspect = (float)renderer::get_instance().get_screen_width() /
(float)renderer::get_instance().get_screen_width();
// Use this to create projection matrix
auto projection = perspective(
degrees(quarter_pi<float>()), // FOV
aspect, // Aspect ratio
2.414f, // Near plane
10000.0f); // Far plane
// Set the projection matrix
renderer::get_instance().set_projection(projection);
// Set the view matrix
auto view = lookAt(
vec3(20.0f, 20.0f, 20.0f), // Camera position
vec3(0.0f, 0.0f, 0.0f), // Target
vec3(0.0f, 1.0f, 0.0f)); // Up vector
renderer::get_instance().set_view(view);
// Create Cube
auto object = geometry_builder::create_tetrahedron();
// Main render loop
while (renderer::get_instance().is_running())
{
// Check if running
if (renderer::get_instance().begin_render())
{
// Render Cube
renderer::get_instance().render(object);
// End the render
renderer::get_instance().end_render();
}
}
}
<commit_msg>Create pyramid<commit_after>// Lesson 13.cpp : Defines the entry point for the console application.
#include <render_framework\render_framework.h>
#pragma comment (lib , "Render Framework" )
using namespace std;
using namespace glm;
using namespace render_framework;
int main()
{
// Initialize the renderer
if (!renderer::get_instance().initialise()) return -1;
// Set the clear colour to cyan
glClearColor(0.0f, 1.0f, 1.0f, 1.0f);
/* Set the projection matrix */
// First get the aspect ratio (width/height)
float aspect = (float)renderer::get_instance().get_screen_width() /
(float)renderer::get_instance().get_screen_width();
// Use this to create projection matrix
auto projection = perspective(
degrees(quarter_pi<float>()), // FOV
aspect, // Aspect ratio
2.414f, // Near plane
10000.0f); // Far plane
// Set the projection matrix
renderer::get_instance().set_projection(projection);
// Set the view matrix
auto view = lookAt(
vec3(20.0f, 20.0f, 20.0f), // Camera position
vec3(0.0f, 0.0f, 0.0f), // Target
vec3(0.0f, 1.0f, 0.0f)); // Up vector
renderer::get_instance().set_view(view);
// Create Object
auto object = geometry_builder::create_pyramid();
// Main render loop
while (renderer::get_instance().is_running())
{
// Check if running
if (renderer::get_instance().begin_render())
{
// Render Cube
renderer::get_instance().render(object);
// End the render
renderer::get_instance().end_render();
}
}
}
<|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 libdui.
**
** 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.
**
****************************************************************************/
#include <DuiWidget>
#include "duiwidgetrecycler.h"
#include "duiwidgetrecycler_p.h"
DuiWidgetRecyclerPrivate::DuiWidgetRecyclerPrivate()
: widgetCount(0), maxWidgetCount(10)
{
}
DuiWidgetRecyclerPrivate::~DuiWidgetRecyclerPrivate()
{
qDeleteAll(widgets);
}
void DuiWidgetRecyclerPrivate::resetWidgetState(DuiWidget *widget)
{
widget->setVisible(false);
//widget->setParentItem(NULL);
//widget->setParentLayoutItem(NULL);
}
bool DuiWidgetRecyclerPrivate::hasEnoughSpaceFor(DuiWidget *widget)
{
return widgets.count(widget->metaObject()->className()) < maxWidgetCount;
}
void DuiWidgetRecyclerPrivate::put(DuiWidget *widget)
{
widgets.insert(widget->metaObject()->className(), widget);
}
DuiWidget *DuiWidgetRecyclerPrivate::take(const QString &className)
{
return widgets.take(className);
}
DuiWidgetRecycler::DuiWidgetRecycler()
: d_ptr(new DuiWidgetRecyclerPrivate())
{
}
DuiWidgetRecycler::~DuiWidgetRecycler()
{
delete d_ptr;
}
DuiWidgetRecycler *DuiWidgetRecycler::instance()
{
static DuiWidgetRecycler recycler;
return &recycler;
}
void DuiWidgetRecycler::setMaxItemsPerClass(int count)
{
d_ptr->maxWidgetCount = count;
}
int DuiWidgetRecycler::maxItemsPerClass() const
{
return d_ptr->maxWidgetCount;
}
void DuiWidgetRecycler::recycle(DuiWidget *widget)
{
if (widget) {
if (d_ptr->hasEnoughSpaceFor(widget)) {
d_ptr->resetWidgetState(widget);
d_ptr->put(widget);
} else {
delete widget;
}
}
}
DuiWidget *DuiWidgetRecycler::take(const QString &className)
{
DuiWidget *widget = d_ptr->take(className);
return widget;
}
<commit_msg>Changes: DuiWidgetRecycler doesn't hide recycled item anymore, it just moves it outside of the screen. setVisible() is quite expensive operation in QT.<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 libdui.
**
** 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.
**
****************************************************************************/
#include <DuiWidget>
#include "duiwidgetrecycler.h"
#include "duiwidgetrecycler_p.h"
DuiWidgetRecyclerPrivate::DuiWidgetRecyclerPrivate()
: widgetCount(0), maxWidgetCount(10)
{
}
DuiWidgetRecyclerPrivate::~DuiWidgetRecyclerPrivate()
{
qDeleteAll(widgets);
}
void DuiWidgetRecyclerPrivate::resetWidgetState(DuiWidget *widget)
{
// lets just move it far far away, so that noone can see it
widget->setPos(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX);
//widget->setVisible(false);
//widget->setParentItem(NULL);
//widget->setParentLayoutItem(NULL);
}
bool DuiWidgetRecyclerPrivate::hasEnoughSpaceFor(DuiWidget *widget)
{
return widgets.count(widget->metaObject()->className()) < maxWidgetCount;
}
void DuiWidgetRecyclerPrivate::put(DuiWidget *widget)
{
widgets.insert(widget->metaObject()->className(), widget);
}
DuiWidget *DuiWidgetRecyclerPrivate::take(const QString &className)
{
return widgets.take(className);
}
DuiWidgetRecycler::DuiWidgetRecycler()
: d_ptr(new DuiWidgetRecyclerPrivate())
{
}
DuiWidgetRecycler::~DuiWidgetRecycler()
{
delete d_ptr;
}
DuiWidgetRecycler *DuiWidgetRecycler::instance()
{
static DuiWidgetRecycler recycler;
return &recycler;
}
void DuiWidgetRecycler::setMaxItemsPerClass(int count)
{
d_ptr->maxWidgetCount = count;
}
int DuiWidgetRecycler::maxItemsPerClass() const
{
return d_ptr->maxWidgetCount;
}
void DuiWidgetRecycler::recycle(DuiWidget *widget)
{
if (widget) {
if (d_ptr->hasEnoughSpaceFor(widget)) {
d_ptr->resetWidgetState(widget);
d_ptr->put(widget);
} else {
delete widget;
}
}
}
DuiWidget *DuiWidgetRecycler::take(const QString &className)
{
DuiWidget *widget = d_ptr->take(className);
return widget;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/sha.h>
#include <iomanip>
#include <sstream>
#define MAX_SIZE 256
using namespace std;
// https://memset.wordpress.com/2010/10/06/using-sha1-function/
// http://stackoverflow.com/questions/11765522/how-do-i-write-this-in-cout-c
string print_hex(unsigned char *bs, unsigned int n) {
string ret_val = "";
for (int i = 0; i < n; i++) {
stringstream ss;
ss << hex << static_cast<int>(bs[i]);
ret_val += ss.str();
}
return ret_val;
}
int main(int argc, char ** argv) {
if ( argc != 2 ) {
cerr << "Usage: " << argv[0] << " <string>" << endl;
exit(EXIT_FAILURE);
}
char * tmp = new char[MAX_SIZE];
unsigned char temp[SHA512_DIGEST_LENGTH];
strncpy(tmp, argv[1], MAX_SIZE);
memset(temp, 0x0, SHA512_DIGEST_LENGTH);
SHA512((unsigned char *)argv[1], strlen(argv[1]), temp);
cout << "SHA512 of " << tmp << " is " << print_hex(temp, sizeof(temp)) << endl;
return 0;
}
<commit_msg>Fixed Buffer Overflow Bug<commit_after>#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/sha.h>
#include <iomanip>
#include <sstream>
#define MAX_SIZE 256
using namespace std;
// https://memset.wordpress.com/2010/10/06/using-sha1-function/
// http://stackoverflow.com/questions/11765522/how-do-i-write-this-in-cout-c
string print_hex(unsigned char *bs, unsigned int n) {
string ret_val = "";
for (int i = 0; i < n; i++) {
stringstream ss;
ss << hex << static_cast<int>(bs[i]);
ret_val += ss.str();
}
return ret_val;
}
int main(int argc, char ** argv) {
if ( argc != 2 ) {
cerr << "Usage: " << argv[0] << " <string>" << endl;
exit(EXIT_FAILURE);
}
char * tmp = new char[MAX_SIZE];
unsigned char temp[SHA512_DIGEST_LENGTH];
strncpy(tmp, argv[1], MAX_SIZE);
memset(temp, 0x0, SHA512_DIGEST_LENGTH);
SHA512((unsigned char *)tmp, strlen(tmp), temp);
cout << "SHA512 of " << tmp << " is " << print_hex(temp, sizeof(temp)) << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "widgets/helper/splitinput.hpp"
#include "singletons/commandmanager.hpp"
#include "singletons/completionmanager.hpp"
#include "singletons/ircmanager.hpp"
#include "singletons/settingsmanager.hpp"
#include "singletons/thememanager.hpp"
#include "util/layoutcreator.hpp"
#include "widgets/notebook.hpp"
#include "widgets/split.hpp"
#include "widgets/splitcontainer.hpp"
#include <QCompleter>
#include <QPainter>
namespace chatterino {
namespace widgets {
SplitInput::SplitInput(Split *_chatWidget)
: BaseWidget(_chatWidget)
, chatWidget(_chatWidget)
{
this->initLayout();
// auto completion
auto completer = new QCompleter(
singletons::CompletionManager::getInstance().createModel(this->chatWidget->channelName));
this->ui.textEdit->setCompleter(completer);
// misc
this->installKeyPressedEvent();
this->themeRefreshEvent();
this->scaleChangedEvent(this->getScale());
}
void SplitInput::initLayout()
{
auto &fontManager = singletons::FontManager::getInstance();
util::LayoutCreator<SplitInput> layoutCreator(this);
auto layout = layoutCreator.setLayoutType<QHBoxLayout>().withoutMargin().assign(&this->ui.hbox);
// input
auto textEdit = layout.emplace<ResizingTextEdit>().assign(&this->ui.textEdit);
connect(textEdit.getElement(), &ResizingTextEdit::textChanged, this,
&SplitInput::editTextChanged);
// right box
auto box = layout.emplace<QVBoxLayout>().withoutMargin();
box->setSpacing(0);
{
auto textEditLength = box.emplace<QLabel>().assign(&this->ui.textEditLength);
textEditLength->setAlignment(Qt::AlignRight);
box->addStretch(1);
box.emplace<RippleEffectLabel>().assign(&this->ui.emoteButton);
}
this->ui.emoteButton->getLabel().setTextFormat(Qt::RichText);
// ---- misc
// set edit font
this->ui.textEdit->setFont(
fontManager.getFont(singletons::FontManager::Type::Medium, this->getScale()));
this->managedConnections.emplace_back(fontManager.fontChanged.connect([this, &fontManager]() {
this->ui.textEdit->setFont(
fontManager.getFont(singletons::FontManager::Type::Medium, this->getScale()));
}));
// open emote popup
QObject::connect(this->ui.emoteButton, &RippleEffectLabel::clicked, [this] {
if (!this->emotePopup) {
this->emotePopup = std::make_unique<EmotePopup>(this->themeManager);
this->emotePopup->linkClicked.connect([this](const messages::Link &link) {
if (link.getType() == messages::Link::InsertText) {
this->insertText(link.getValue());
}
});
}
this->emotePopup->resize((int)(300 * this->emotePopup->getScale()),
(int)(500 * this->emotePopup->getScale()));
this->emotePopup->loadChannel(this->chatWidget->getChannel());
this->emotePopup->show();
});
// clear channelview selection when selecting in the input
QObject::connect(this->ui.textEdit, &QTextEdit::copyAvailable, [this](bool available) {
if (available) {
this->chatWidget->view.clearSelection();
}
});
// textEditLength visibility
singletons::SettingManager::getInstance().showMessageLength.connect(
[this](const bool &value, auto) { this->ui.textEditLength->setHidden(!value); },
this->managedConnections);
}
void SplitInput::scaleChangedEvent(float scale)
{
// update the icon size of the emote button
QString text = "<img src=':/images/emote.svg' width='xD' height='xD' />";
text.replace("xD", QString::number((int)12 * scale));
this->ui.emoteButton->getLabel().setText(text);
this->ui.emoteButton->setFixedHeight((int)18 * scale);
// set maximum height
this->setMaximumHeight((int)(150 * this->getScale()));
this->themeRefreshEvent();
}
void SplitInput::themeRefreshEvent()
{
QPalette palette;
palette.setColor(QPalette::Foreground, this->themeManager.splits.input.text);
this->ui.textEditLength->setPalette(palette);
this->ui.textEdit->setStyleSheet(this->themeManager.splits.input.styleSheet);
this->ui.hbox->setMargin((this->themeManager.isLightTheme() ? 4 : 2) * this->getScale());
}
void SplitInput::installKeyPressedEvent()
{
this->ui.textEdit->keyPressed.connect([this](QKeyEvent *event) {
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
auto c = this->chatWidget->getChannel();
if (c == nullptr) {
return;
}
QString message = ui.textEdit->toPlainText();
QString sendMessage =
singletons::CommandManager::getInstance().execCommand(message, c, false);
sendMessage = sendMessage.replace('\n', ' ');
c->sendMessage(sendMessage);
this->prevMsg.append(message);
event->accept();
if (!(event->modifiers() == Qt::ControlModifier)) {
this->ui.textEdit->setText(QString());
this->prevIndex = 0;
} else if (this->ui.textEdit->toPlainText() ==
this->prevMsg.at(this->prevMsg.size() - 1)) {
this->prevMsg.removeLast();
}
this->prevIndex = this->prevMsg.size();
} else if (event->key() == Qt::Key_Up) {
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
int reqX = page->currentX;
int reqY = page->lastRequestedY[reqX] - 1;
qDebug() << "Alt+Down to" << reqX << "/" << reqY;
page->requestFocus(reqX, reqY);
} else {
if (this->prevMsg.size() && this->prevIndex) {
this->prevIndex--;
this->ui.textEdit->setText(this->prevMsg.at(this->prevIndex));
}
}
} else if (event->key() == Qt::Key_Down) {
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
int reqX = page->currentX;
int reqY = page->lastRequestedY[reqX] + 1;
qDebug() << "Alt+Down to" << reqX << "/" << reqY;
page->requestFocus(reqX, reqY);
} else {
if (this->prevIndex != (this->prevMsg.size() - 1) &&
this->prevIndex != this->prevMsg.size()) {
this->prevIndex++;
this->ui.textEdit->setText(this->prevMsg.at(this->prevIndex));
} else {
this->prevIndex = this->prevMsg.size();
this->ui.textEdit->setText(QString());
}
}
} else if (event->key() == Qt::Key_Left) {
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
int reqX = page->currentX - 1;
int reqY = page->lastRequestedY[reqX];
qDebug() << "Alt+Left to" << reqX << "/" << reqY;
page->requestFocus(reqX, reqY);
}
} else if (event->key() == Qt::Key_Right) {
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
int reqX = page->currentX + 1;
int reqY = page->lastRequestedY[reqX];
qDebug() << "Alt+Right to" << reqX << "/" << reqY;
page->requestFocus(reqX, reqY);
}
} else if (event->key() == Qt::Key_Tab) {
if (event->modifiers() == Qt::ControlModifier) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
Notebook *notebook = static_cast<Notebook *>(page->parentWidget());
notebook->nextTab();
}
} else if (event->key() == Qt::Key_Backtab) {
if (event->modifiers() == (Qt::ControlModifier | Qt::ShiftModifier)) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
Notebook *notebook = static_cast<Notebook *>(page->parentWidget());
notebook->previousTab();
}
} else if (event->key() == Qt::Key_C && event->modifiers() == Qt::ControlModifier) {
if (this->chatWidget->view.hasSelection()) {
this->chatWidget->doCopy();
event->accept();
}
}
});
}
void SplitInput::clearSelection()
{
QTextCursor c = this->ui.textEdit->textCursor();
c.setPosition(c.position());
c.setPosition(c.position(), QTextCursor::KeepAnchor);
this->ui.textEdit->setTextCursor(c);
}
QString SplitInput::getInputText() const
{
return this->ui.textEdit->toPlainText();
}
void SplitInput::insertText(const QString &text)
{
this->ui.textEdit->insertPlainText(text);
}
void SplitInput::editTextChanged()
{
// set textLengthLabel value
QString text = this->ui.textEdit->toPlainText();
this->textChanged.invoke(text);
text = text.trimmed();
static QRegularExpression spaceRegex("\\s\\s+");
text = text.replace(spaceRegex, " ");
text = singletons::CommandManager::getInstance().execCommand(
text, this->chatWidget->getChannel(), true);
QString labelText;
if (text.length() == 0) {
labelText = "";
} else {
labelText = QString::number(text.length());
}
this->ui.textEditLength->setText(labelText);
}
void SplitInput::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.fillRect(this->rect(), this->themeManager.splits.input.background);
QPen pen(this->themeManager.splits.input.border);
if (this->themeManager.isLightTheme()) {
pen.setWidth((int)(6 * this->getScale()));
}
painter.setPen(pen);
painter.drawRect(0, 0, this->width() - 1, this->height() - 1);
}
void SplitInput::resizeEvent(QResizeEvent *)
{
if (this->height() == this->maximumHeight()) {
this->ui.textEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
} else {
this->ui.textEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
}
void SplitInput::mousePressEvent(QMouseEvent *)
{
this->chatWidget->giveFocus(Qt::MouseFocusReason);
}
} // namespace widgets
} // namespace chatterino
<commit_msg>fixed #252 clicking emotes in the emote popup<commit_after>#include "widgets/helper/splitinput.hpp"
#include "singletons/commandmanager.hpp"
#include "singletons/completionmanager.hpp"
#include "singletons/ircmanager.hpp"
#include "singletons/settingsmanager.hpp"
#include "singletons/thememanager.hpp"
#include "util/layoutcreator.hpp"
#include "widgets/notebook.hpp"
#include "widgets/split.hpp"
#include "widgets/splitcontainer.hpp"
#include <QCompleter>
#include <QPainter>
namespace chatterino {
namespace widgets {
SplitInput::SplitInput(Split *_chatWidget)
: BaseWidget(_chatWidget)
, chatWidget(_chatWidget)
{
this->initLayout();
// auto completion
auto completer = new QCompleter(
singletons::CompletionManager::getInstance().createModel(this->chatWidget->channelName));
this->ui.textEdit->setCompleter(completer);
// misc
this->installKeyPressedEvent();
this->themeRefreshEvent();
this->scaleChangedEvent(this->getScale());
}
void SplitInput::initLayout()
{
auto &fontManager = singletons::FontManager::getInstance();
util::LayoutCreator<SplitInput> layoutCreator(this);
auto layout = layoutCreator.setLayoutType<QHBoxLayout>().withoutMargin().assign(&this->ui.hbox);
// input
auto textEdit = layout.emplace<ResizingTextEdit>().assign(&this->ui.textEdit);
connect(textEdit.getElement(), &ResizingTextEdit::textChanged, this,
&SplitInput::editTextChanged);
// right box
auto box = layout.emplace<QVBoxLayout>().withoutMargin();
box->setSpacing(0);
{
auto textEditLength = box.emplace<QLabel>().assign(&this->ui.textEditLength);
textEditLength->setAlignment(Qt::AlignRight);
box->addStretch(1);
box.emplace<RippleEffectLabel>().assign(&this->ui.emoteButton);
}
this->ui.emoteButton->getLabel().setTextFormat(Qt::RichText);
// ---- misc
// set edit font
this->ui.textEdit->setFont(
fontManager.getFont(singletons::FontManager::Type::Medium, this->getScale()));
this->managedConnections.emplace_back(fontManager.fontChanged.connect([this, &fontManager]() {
this->ui.textEdit->setFont(
fontManager.getFont(singletons::FontManager::Type::Medium, this->getScale()));
}));
// open emote popup
QObject::connect(this->ui.emoteButton, &RippleEffectLabel::clicked, [this] {
if (!this->emotePopup) {
this->emotePopup = std::make_unique<EmotePopup>(this->themeManager);
this->emotePopup->linkClicked.connect([this](const messages::Link &link) {
if (link.getType() == messages::Link::InsertText) {
this->insertText(link.getValue() + " ");
}
});
}
this->emotePopup->resize((int)(300 * this->emotePopup->getScale()),
(int)(500 * this->emotePopup->getScale()));
this->emotePopup->loadChannel(this->chatWidget->getChannel());
this->emotePopup->show();
});
// clear channelview selection when selecting in the input
QObject::connect(this->ui.textEdit, &QTextEdit::copyAvailable, [this](bool available) {
if (available) {
this->chatWidget->view.clearSelection();
}
});
// textEditLength visibility
singletons::SettingManager::getInstance().showMessageLength.connect(
[this](const bool &value, auto) { this->ui.textEditLength->setHidden(!value); },
this->managedConnections);
}
void SplitInput::scaleChangedEvent(float scale)
{
// update the icon size of the emote button
QString text = "<img src=':/images/emote.svg' width='xD' height='xD' />";
text.replace("xD", QString::number((int)12 * scale));
this->ui.emoteButton->getLabel().setText(text);
this->ui.emoteButton->setFixedHeight((int)18 * scale);
// set maximum height
this->setMaximumHeight((int)(150 * this->getScale()));
this->themeRefreshEvent();
}
void SplitInput::themeRefreshEvent()
{
QPalette palette;
palette.setColor(QPalette::Foreground, this->themeManager.splits.input.text);
this->ui.textEditLength->setPalette(palette);
this->ui.textEdit->setStyleSheet(this->themeManager.splits.input.styleSheet);
this->ui.hbox->setMargin((this->themeManager.isLightTheme() ? 4 : 2) * this->getScale());
}
void SplitInput::installKeyPressedEvent()
{
this->ui.textEdit->keyPressed.connect([this](QKeyEvent *event) {
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
auto c = this->chatWidget->getChannel();
if (c == nullptr) {
return;
}
QString message = ui.textEdit->toPlainText();
QString sendMessage =
singletons::CommandManager::getInstance().execCommand(message, c, false);
sendMessage = sendMessage.replace('\n', ' ');
c->sendMessage(sendMessage);
this->prevMsg.append(message);
event->accept();
if (!(event->modifiers() == Qt::ControlModifier)) {
this->ui.textEdit->setText(QString());
this->prevIndex = 0;
} else if (this->ui.textEdit->toPlainText() ==
this->prevMsg.at(this->prevMsg.size() - 1)) {
this->prevMsg.removeLast();
}
this->prevIndex = this->prevMsg.size();
} else if (event->key() == Qt::Key_Up) {
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
int reqX = page->currentX;
int reqY = page->lastRequestedY[reqX] - 1;
qDebug() << "Alt+Down to" << reqX << "/" << reqY;
page->requestFocus(reqX, reqY);
} else {
if (this->prevMsg.size() && this->prevIndex) {
this->prevIndex--;
this->ui.textEdit->setText(this->prevMsg.at(this->prevIndex));
}
}
} else if (event->key() == Qt::Key_Down) {
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
int reqX = page->currentX;
int reqY = page->lastRequestedY[reqX] + 1;
qDebug() << "Alt+Down to" << reqX << "/" << reqY;
page->requestFocus(reqX, reqY);
} else {
if (this->prevIndex != (this->prevMsg.size() - 1) &&
this->prevIndex != this->prevMsg.size()) {
this->prevIndex++;
this->ui.textEdit->setText(this->prevMsg.at(this->prevIndex));
} else {
this->prevIndex = this->prevMsg.size();
this->ui.textEdit->setText(QString());
}
}
} else if (event->key() == Qt::Key_Left) {
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
int reqX = page->currentX - 1;
int reqY = page->lastRequestedY[reqX];
qDebug() << "Alt+Left to" << reqX << "/" << reqY;
page->requestFocus(reqX, reqY);
}
} else if (event->key() == Qt::Key_Right) {
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
int reqX = page->currentX + 1;
int reqY = page->lastRequestedY[reqX];
qDebug() << "Alt+Right to" << reqX << "/" << reqY;
page->requestFocus(reqX, reqY);
}
} else if (event->key() == Qt::Key_Tab) {
if (event->modifiers() == Qt::ControlModifier) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
Notebook *notebook = static_cast<Notebook *>(page->parentWidget());
notebook->nextTab();
}
} else if (event->key() == Qt::Key_Backtab) {
if (event->modifiers() == (Qt::ControlModifier | Qt::ShiftModifier)) {
SplitContainer *page =
static_cast<SplitContainer *>(this->chatWidget->parentWidget());
Notebook *notebook = static_cast<Notebook *>(page->parentWidget());
notebook->previousTab();
}
} else if (event->key() == Qt::Key_C && event->modifiers() == Qt::ControlModifier) {
if (this->chatWidget->view.hasSelection()) {
this->chatWidget->doCopy();
event->accept();
}
}
});
}
void SplitInput::clearSelection()
{
QTextCursor c = this->ui.textEdit->textCursor();
c.setPosition(c.position());
c.setPosition(c.position(), QTextCursor::KeepAnchor);
this->ui.textEdit->setTextCursor(c);
}
QString SplitInput::getInputText() const
{
return this->ui.textEdit->toPlainText();
}
void SplitInput::insertText(const QString &text)
{
this->ui.textEdit->insertPlainText(text);
}
void SplitInput::editTextChanged()
{
// set textLengthLabel value
QString text = this->ui.textEdit->toPlainText();
this->textChanged.invoke(text);
text = text.trimmed();
static QRegularExpression spaceRegex("\\s\\s+");
text = text.replace(spaceRegex, " ");
text = singletons::CommandManager::getInstance().execCommand(
text, this->chatWidget->getChannel(), true);
QString labelText;
if (text.length() == 0) {
labelText = "";
} else {
labelText = QString::number(text.length());
}
this->ui.textEditLength->setText(labelText);
}
void SplitInput::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.fillRect(this->rect(), this->themeManager.splits.input.background);
QPen pen(this->themeManager.splits.input.border);
if (this->themeManager.isLightTheme()) {
pen.setWidth((int)(6 * this->getScale()));
}
painter.setPen(pen);
painter.drawRect(0, 0, this->width() - 1, this->height() - 1);
}
void SplitInput::resizeEvent(QResizeEvent *)
{
if (this->height() == this->maximumHeight()) {
this->ui.textEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
} else {
this->ui.textEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
}
void SplitInput::mousePressEvent(QMouseEvent *)
{
this->chatWidget->giveFocus(Qt::MouseFocusReason);
}
} // namespace widgets
} // namespace chatterino
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Matthew Hoyt ([email protected])
*/
#if !defined(XALANDEQUE_HEADER_GUARD_1357924680)
#define XALANDEQUE_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMemoryManagement.hpp>
XALAN_CPP_NAMESPACE_BEGIN
template <class Value>
struct XalanDequeIteratorTraits
{
typedef Value value_type;
typedef Value& reference;
typedef Value* pointer;
typedef const Value& const_reference;
};
template <class Value>
struct XalanDequeConstIteratorTraits
{
typedef Value value_type;
typedef const Value& reference;
typedef const Value* pointer;
typedef const Value& const_reference;
};
template <class XalanDequeTraits, class XalanDeque>
struct XalanDequeIterator
{
typedef size_t size_type;
typedef typename XalanDequeTraits::value_type value_type;
typedef typename XalanDequeTraits::reference reference;
typedef typename XalanDequeTraits::pointer pointer;
typedef typename XalanDequeTraits::const_reference const_reference;
typedef ptrdiff_t difference_type;
typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> Iterator;
typedef XALAN_STD_QUALIFIER random_access_iterator_tag iterator_category;
XalanDequeIterator(XalanDeque* deque,
size_type pos) :
m_deque(deque),
m_pos(pos)
{
}
XalanDequeIterator(const Iterator & iterator) :
m_deque(iterator.m_deque),
m_pos(iterator.m_pos)
{
}
XalanDequeIterator& operator=(const Iterator & iterator)
{
m_deque = iterator.m_deque;
m_pos = iterator.m_pos;
return *this;
}
XalanDequeIterator& operator++()
{
++m_pos;
return *this;
}
XalanDequeIterator operator++(int)
{
XalanDequeIterator temp = *this;
++m_pos;
return temp;
}
XalanDequeIterator& operator--()
{
--m_pos;
return *this;
}
pointer operator->()
{
return &(*m_deque[m_pos]);
}
reference operator*()
{
return (*m_deque)[m_pos];
}
const_reference operator*() const
{
return (*m_deque)[m_pos];
}
XalanDequeIterator operator+(difference_type difference) const
{
return XalanDequeIterator(m_deque, m_pos + difference);
}
XalanDequeIterator operator-(difference_type difference) const
{
return XalanDequeIterator(m_deque, m_pos - difference);
}
difference_type operator-(const XalanDequeIterator &theRhs) const
{
return m_pos - theRhs.m_pos;
}
bool operator==(const XalanDequeIterator & theRhs) const
{
return (theRhs.m_deque == m_deque)
&& theRhs.m_pos == m_pos;
}
bool operator!=(const XalanDequeIterator & theRhs) const
{
return !(theRhs == *this);
}
bool operator<(const XalanDequeIterator & theRhs) const
{
return m_pos < theRhs.m_pos;
}
XalanDeque* m_deque;
size_type m_pos;
};
/**
* Xalan implementation of deque
*/
template <class Type, class ConstructionTraits = MemoryManagedConstructionTraits<Type> >
class XalanDeque
{
public:
typedef size_t size_type;
typedef Type value_type;
typedef Type& reference;
typedef const Type& const_reference;
typedef XalanVector<Type, ConstructionTraits> BlockType;
typedef XalanVector<BlockType*> BlockIndexType;
typedef XalanDeque<Type, ConstructionTraits> ThisType;
typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, ThisType> iterator;
typedef XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, ThisType> const_iterator;
#if defined(XALAN_HAS_STD_ITERATORS)
typedef XALAN_STD_QUALIFIER reverse_iterator<iterator> reverse_iterator_;
typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator> const_reverse_iterator_;
#elif defined(XALAN_RW_NO_CLASS_PARTIAL_SPEC)
typedef XALAN_STD_QUALIFIER reverse_iterator<
iterator,
XALAN_STD_QUALIFIER random_access_iterator_tag,
value_type> reverse_iterator_;
typedef XALAN_STD_QUALIFIER reverse_iterator<
const_iterator,
XALAN_STD_QUALIFIER random_access_iterator_tag,
const value_type> const_reverse_iterator_;
#else
typedef XALAN_STD_QUALIFIER reverse_iterator<iterator, value_type> reverse_iterator_;
typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator, value_type, const_reference> const_reverse_iterator_;
#endif
typedef reverse_iterator_ reverse_iterator;
typedef const_reverse_iterator_ const_reverse_iterator;
typedef typename ConstructionTraits::Constructor Constructor;
typedef typename Constructor::ConstructableType ConstructibleType;
XalanDeque(
MemoryManagerType& memoryManager,
size_type initialSize = 0,
size_type blockSize = 10) :
m_memoryManager(&memoryManager),
m_blockSize(blockSize),
m_blockIndex(memoryManager,
initialSize / blockSize + (initialSize % blockSize == 0 ? 0 : 1)),
m_freeBlockVector(memoryManager)
{
typename Constructor::ConstructableType defaultValue(*m_memoryManager);
XALAN_STD_QUALIFIER fill_n(XALAN_STD_QUALIFIER back_inserter(*this), initialSize, defaultValue.value);
}
XalanDeque(const XalanDeque& theRhs, MemoryManagerType& memoryManager) :
m_memoryManager(&memoryManager),
m_blockSize(theRhs.m_blockSize),
m_blockIndex(*theRhs.m_memoryManager,
theRhs.size() / theRhs.m_blockSize + (theRhs.size() % theRhs.m_blockSize == 0 ? 0 : 1)),
m_freeBlockVector(memoryManager)
{
XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this));
}
static XalanDeque*
create(
MemoryManagerType& theManager,
size_type initialSize = 0,
size_type blockSize = 10)
{
typedef XalanDeque ThisType;
XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType)));
ThisType* theResult = theGuard.get();
new (theResult) ThisType(theManager, initialSize, blockSize);
theGuard.release();
return theResult;
}
~XalanDeque()
{
destroyBlockList(m_freeBlockVector);
destroyBlockList(m_blockIndex);
}
iterator begin()
{
return iterator(this, 0);
}
const_iterator begin() const
{
return const_iterator(const_cast<XalanDeque*>(this), 0);
}
iterator end()
{
return iterator(this, size());
}
const_iterator end() const
{
return const_iterator(const_cast<XalanDeque*>(this), size());
}
const_reverse_iterator rbegin() const
{
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const
{
return const_reverse_iterator(begin());
}
bool empty() const
{
return m_blockIndex.empty();
}
size_type size() const
{
if (m_blockIndex.empty())
{
return 0;
}
else
{
return (m_blockIndex.size() - 1) * m_blockSize
+ m_blockIndex.back()->size();
}
}
value_type& back()
{
return m_blockIndex.back()->back();
}
value_type& operator[](size_type index)
{
BlockType & block = *(m_blockIndex[index / m_blockSize]);
return block[index % m_blockSize];
}
const value_type& operator[](size_type index) const
{
BlockType & block = *(m_blockIndex[index / m_blockSize]);
return block[index % m_blockSize];
}
void clear()
{
typename BlockIndexType::iterator iter = m_blockIndex.begin();
m_freeBlockVector.reserve(m_freeBlockVector.size() + m_blockIndex.size());
while (iter != m_blockIndex.end())
{
(*iter)->clear();
m_freeBlockVector.push_back(*iter);
++iter;
}
m_blockIndex.clear();
}
void push_back(const value_type & value)
{
if (m_blockIndex.empty() ||
m_blockIndex.back()->size() >= m_blockSize)
{
m_blockIndex.push_back(getNewBlock());
}
m_blockIndex.back()->push_back(value);
}
void pop_back()
{
BlockType & lastBlock = *(m_blockIndex.back());
lastBlock.pop_back();
if (lastBlock.empty())
{
m_freeBlockVector.push_back(&lastBlock);
m_blockIndex.pop_back();
}
}
void resize(size_type newSize)
{
typename Constructor::ConstructableType defaultValue(*m_memoryManager);
if (newSize > size())
{
for (size_type i = 0; i < newSize - size(); ++i)
{
push_back(defaultValue.value);
}
}
else
{
for (size_type i = 0; i < size() - newSize; ++i)
{
pop_back();
}
}
}
void swap(XalanDeque& theRhs)
{
MemoryManagerType* tempMemoryManager = m_memoryManager;
m_memoryManager = theRhs.m_memoryManager;
theRhs.m_memoryManager = tempMemoryManager;
theRhs.m_blockIndex.swap(m_blockIndex);
theRhs.m_freeBlockVector.swap(m_freeBlockVector);
}
XalanDeque & operator=(const XalanDeque & theRhs)
{
clear();
XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this));
return *this;
}
MemoryManagerType&
getMemoryManager()
{
assert (m_memoryManager != 0);
return *m_memoryManager;
}
protected:
BlockType* getNewBlock()
{
BlockType * newBlock;
if (m_freeBlockVector.empty())
{
newBlock = allocate(1);
new (&*newBlock) BlockType(*m_memoryManager, m_blockSize);
}
else
{
newBlock = m_freeBlockVector.back();
m_freeBlockVector.pop_back();
}
assert (newBlock != 0);
return newBlock;
}
BlockType*
allocate(size_type size)
{
const size_type theBytesNeeded = size * sizeof(BlockType);
BlockType* pointer = (BlockType*)m_memoryManager->allocate(theBytesNeeded);
assert(pointer != 0);
return pointer;
}
void
destroyBlockList(BlockIndexType& theBlockIndex)
{
typename BlockIndexType::iterator iter =
theBlockIndex.begin();
while (iter != theBlockIndex.end())
{
XalanDestroy(*m_memoryManager, *(*iter));
++iter;
}
}
void
deallocate(BlockType* pointer)
{
m_memoryManager->deallocate(pointer);
}
MemoryManagerType* m_memoryManager;
const size_type m_blockSize;
BlockIndexType m_blockIndex;
BlockIndexType m_freeBlockVector;
private:
// These are not implemented
XalanDeque();
XalanDeque(const XalanDeque&);
};
XALAN_CPP_NAMESPACE_END
#endif // XALANDEQUE_HEADER_GUARD_1357924680
<commit_msg>Major error reporting cleanup.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Matthew Hoyt ([email protected])
*/
#if !defined(XALANDEQUE_HEADER_GUARD_1357924680)
#define XALANDEQUE_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMemoryManagement.hpp>
XALAN_CPP_NAMESPACE_BEGIN
template <class Value>
struct XalanDequeIteratorTraits
{
typedef Value value_type;
typedef Value& reference;
typedef Value* pointer;
typedef const Value& const_reference;
};
template <class Value>
struct XalanDequeConstIteratorTraits
{
typedef Value value_type;
typedef const Value& reference;
typedef const Value* pointer;
typedef const Value& const_reference;
};
template <class XalanDequeTraits, class XalanDeque>
struct XalanDequeIterator
{
typedef size_t size_type;
typedef typename XalanDequeTraits::value_type value_type;
typedef typename XalanDequeTraits::reference reference;
typedef typename XalanDequeTraits::pointer pointer;
typedef typename XalanDequeTraits::const_reference const_reference;
typedef ptrdiff_t difference_type;
typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> Iterator;
typedef XALAN_STD_QUALIFIER random_access_iterator_tag iterator_category;
XalanDequeIterator(XalanDeque* deque,
size_type pos) :
m_deque(deque),
m_pos(pos)
{
}
XalanDequeIterator(const Iterator & iterator) :
m_deque(iterator.m_deque),
m_pos(iterator.m_pos)
{
}
XalanDequeIterator& operator=(const Iterator & iterator)
{
m_deque = iterator.m_deque;
m_pos = iterator.m_pos;
return *this;
}
XalanDequeIterator& operator++()
{
++m_pos;
return *this;
}
XalanDequeIterator operator++(int)
{
XalanDequeIterator temp = *this;
++m_pos;
return temp;
}
XalanDequeIterator& operator--()
{
--m_pos;
return *this;
}
pointer operator->()
{
return &(*m_deque[m_pos]);
}
reference operator*()
{
return (*m_deque)[m_pos];
}
const_reference operator*() const
{
return (*m_deque)[m_pos];
}
XalanDequeIterator operator+(difference_type difference) const
{
return XalanDequeIterator(m_deque, m_pos + difference);
}
XalanDequeIterator operator-(difference_type difference) const
{
return XalanDequeIterator(m_deque, m_pos - difference);
}
difference_type operator-(const XalanDequeIterator &theRhs) const
{
return m_pos - theRhs.m_pos;
}
bool operator==(const XalanDequeIterator & theRhs) const
{
return (theRhs.m_deque == m_deque)
&& theRhs.m_pos == m_pos;
}
bool operator!=(const XalanDequeIterator & theRhs) const
{
return !(theRhs == *this);
}
bool operator<(const XalanDequeIterator & theRhs) const
{
return m_pos < theRhs.m_pos;
}
XalanDeque* m_deque;
size_type m_pos;
};
/**
* Xalan implementation of deque
*/
template <class Type, class ConstructionTraits = MemoryManagedConstructionTraits<Type> >
class XalanDeque
{
public:
typedef size_t size_type;
typedef Type value_type;
typedef Type& reference;
typedef const Type& const_reference;
typedef XalanVector<Type, ConstructionTraits> BlockType;
typedef XalanVector<BlockType*> BlockIndexType;
typedef XalanDeque<Type, ConstructionTraits> ThisType;
typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, ThisType> iterator;
typedef XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, ThisType> const_iterator;
#if defined(XALAN_HAS_STD_ITERATORS)
typedef XALAN_STD_QUALIFIER reverse_iterator<iterator> reverse_iterator_;
typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator> const_reverse_iterator_;
#elif defined(XALAN_RW_NO_CLASS_PARTIAL_SPEC)
typedef XALAN_STD_QUALIFIER reverse_iterator<
iterator,
XALAN_STD_QUALIFIER random_access_iterator_tag,
value_type> reverse_iterator_;
typedef XALAN_STD_QUALIFIER reverse_iterator<
const_iterator,
XALAN_STD_QUALIFIER random_access_iterator_tag,
const value_type> const_reverse_iterator_;
#else
typedef XALAN_STD_QUALIFIER reverse_iterator<iterator, value_type> reverse_iterator_;
typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator, value_type, const_reference> const_reverse_iterator_;
#endif
typedef reverse_iterator_ reverse_iterator;
typedef const_reverse_iterator_ const_reverse_iterator;
typedef typename ConstructionTraits::Constructor Constructor;
typedef typename Constructor::ConstructableType ConstructibleType;
XalanDeque(
MemoryManagerType& memoryManager,
size_type initialSize = 0,
size_type blockSize = 10) :
m_memoryManager(&memoryManager),
m_blockSize(blockSize),
m_blockIndex(memoryManager,
initialSize / blockSize + (initialSize % blockSize == 0 ? 0 : 1)),
m_freeBlockVector(memoryManager)
{
typename Constructor::ConstructableType defaultValue(*m_memoryManager);
XALAN_STD_QUALIFIER fill_n(XALAN_STD_QUALIFIER back_inserter(*this), initialSize, defaultValue.value);
}
XalanDeque(const XalanDeque& theRhs, MemoryManagerType& memoryManager) :
m_memoryManager(&memoryManager),
m_blockSize(theRhs.m_blockSize),
m_blockIndex(*theRhs.m_memoryManager,
theRhs.size() / theRhs.m_blockSize + (theRhs.size() % theRhs.m_blockSize == 0 ? 0 : 1)),
m_freeBlockVector(memoryManager)
{
XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this));
}
static XalanDeque*
create(
MemoryManager& theManager,
size_type initialSize = 0,
size_type blockSize = 10)
{
typedef XalanDeque ThisType;
XalanAllocationGuard theGuard(theManager, theManager.allocate(sizeof(ThisType)));
ThisType* const theResult =
new (theGuard.get()) ThisType(theManager, initialSize, blockSize);
theGuard.release();
return theResult;
}
~XalanDeque()
{
destroyBlockList(m_freeBlockVector);
destroyBlockList(m_blockIndex);
}
iterator begin()
{
return iterator(this, 0);
}
const_iterator begin() const
{
return const_iterator(const_cast<XalanDeque*>(this), 0);
}
iterator end()
{
return iterator(this, size());
}
const_iterator end() const
{
return const_iterator(const_cast<XalanDeque*>(this), size());
}
const_reverse_iterator rbegin() const
{
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const
{
return const_reverse_iterator(begin());
}
bool empty() const
{
return m_blockIndex.empty();
}
size_type size() const
{
if (m_blockIndex.empty())
{
return 0;
}
else
{
return (m_blockIndex.size() - 1) * m_blockSize
+ m_blockIndex.back()->size();
}
}
value_type& back()
{
return m_blockIndex.back()->back();
}
value_type& operator[](size_type index)
{
BlockType & block = *(m_blockIndex[index / m_blockSize]);
return block[index % m_blockSize];
}
const value_type& operator[](size_type index) const
{
BlockType & block = *(m_blockIndex[index / m_blockSize]);
return block[index % m_blockSize];
}
void clear()
{
typename BlockIndexType::iterator iter = m_blockIndex.begin();
m_freeBlockVector.reserve(m_freeBlockVector.size() + m_blockIndex.size());
while (iter != m_blockIndex.end())
{
(*iter)->clear();
m_freeBlockVector.push_back(*iter);
++iter;
}
m_blockIndex.clear();
}
void push_back(const value_type & value)
{
if (m_blockIndex.empty() ||
m_blockIndex.back()->size() >= m_blockSize)
{
m_blockIndex.push_back(getNewBlock());
}
m_blockIndex.back()->push_back(value);
}
void pop_back()
{
BlockType & lastBlock = *(m_blockIndex.back());
lastBlock.pop_back();
if (lastBlock.empty())
{
m_freeBlockVector.push_back(&lastBlock);
m_blockIndex.pop_back();
}
}
void resize(size_type newSize)
{
typename Constructor::ConstructableType defaultValue(*m_memoryManager);
if (newSize > size())
{
for (size_type i = 0; i < newSize - size(); ++i)
{
push_back(defaultValue.value);
}
}
else
{
for (size_type i = 0; i < size() - newSize; ++i)
{
pop_back();
}
}
}
void swap(XalanDeque& theRhs)
{
MemoryManagerType* tempMemoryManager = m_memoryManager;
m_memoryManager = theRhs.m_memoryManager;
theRhs.m_memoryManager = tempMemoryManager;
theRhs.m_blockIndex.swap(m_blockIndex);
theRhs.m_freeBlockVector.swap(m_freeBlockVector);
}
XalanDeque & operator=(const XalanDeque & theRhs)
{
clear();
XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this));
return *this;
}
MemoryManagerType&
getMemoryManager()
{
assert (m_memoryManager != 0);
return *m_memoryManager;
}
protected:
BlockType* getNewBlock()
{
BlockType * newBlock;
if (m_freeBlockVector.empty())
{
newBlock = allocate(1);
new (&*newBlock) BlockType(*m_memoryManager, m_blockSize);
}
else
{
newBlock = m_freeBlockVector.back();
m_freeBlockVector.pop_back();
}
assert (newBlock != 0);
return newBlock;
}
BlockType*
allocate(size_type size)
{
const size_type theBytesNeeded = size * sizeof(BlockType);
BlockType* pointer = (BlockType*)m_memoryManager->allocate(theBytesNeeded);
assert(pointer != 0);
return pointer;
}
void
destroyBlockList(BlockIndexType& theBlockIndex)
{
typename BlockIndexType::iterator iter =
theBlockIndex.begin();
while (iter != theBlockIndex.end())
{
XalanDestroy(*m_memoryManager, *(*iter));
++iter;
}
}
void
deallocate(BlockType* pointer)
{
m_memoryManager->deallocate(pointer);
}
MemoryManagerType* m_memoryManager;
const size_type m_blockSize;
BlockIndexType m_blockIndex;
BlockIndexType m_freeBlockVector;
private:
// These are not implemented
XalanDeque();
XalanDeque(const XalanDeque&);
};
XALAN_CPP_NAMESPACE_END
#endif // XALANDEQUE_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "pow.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/thread.hpp>
using namespace std;
static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f';
static const char DB_TXINDEX = 't';
static const char DB_BLOCK_INDEX = 'b';
static const char DB_BEST_BLOCK = 'B';
static const char DB_FLAG = 'F';
static const char DB_REINDEX_FLAG = 'R';
static const char DB_LAST_BLOCK = 'l';
void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
if (coins.IsPruned())
batch.Erase(make_pair(DB_COINS, hash));
else
batch.Write(make_pair(DB_COINS, hash), coins);
}
void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
batch.Write(DB_BEST_BLOCK, hash);
}
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
}
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
return db.Read(make_pair(DB_COINS, txid), coins);
}
bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
return db.Exists(make_pair(DB_COINS, txid));
}
uint256 CCoinsViewDB::GetBestBlock() const {
uint256 hashBestChain;
if (!db.Read(DB_BEST_BLOCK, hashBestChain))
return uint256(0);
return hashBestChain;
}
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
CLevelDBBatch batch;
size_t count = 0;
size_t changed = 0;
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
BatchWriteCoins(batch, it->first, it->second.coins);
changed++;
}
count++;
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
if (hashBlock != uint256(0))
BatchWriteHashBestChain(batch, hashBlock);
LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
return db.WriteBatch(batch);
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
if (!Read('S', salt)) {
salt = GetRandHash();
Write('S', salt);
}
}
bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
}
bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
return Write(make_pair('f', nFile), info);
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair(DB_BLOCK_FILES, nFile), info);
}
bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
return Write('l', nFile);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write(DB_REINDEX_FLAG, '1');
else
return Erase(DB_REINDEX_FLAG);
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists(DB_REINDEX_FLAG);
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read(DB_LAST_BLOCK, nFile);
}
bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
/* It seems that there are no "const iterators" for LevelDB. Since we
only need read operations on it, use a const-cast to get around
that restriction. */
boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator());
pcursor->SeekToFirst();
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = GetBestBlock();
ss << stats.hashBlock;
CAmount nTotalAmount = 0;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == DB_COINS) {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CCoins coins;
ssValue >> coins;
uint256 txhash;
ssKey >> txhash;
ss << txhash;
ss << VARINT(coins.nVersion);
ss << (coins.fCoinBase ? 'c' : 'n');
ss << VARINT(coins.nHeight);
stats.nTransactions++;
for (unsigned int i=0; i<coins.vout.size(); i++) {
const CTxOut &out = coins.vout[i];
if (!out.IsNull()) {
stats.nTransactionOutputs++;
ss << VARINT(i+1);
ss << out;
nTotalAmount += out.nValue;
}
}
stats.nSerializedSize += 32 + slValue.size();
ss << VARINT(0);
}
pcursor->Next();
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight;
stats.hashSerialized = ss.GetHash();
stats.nTotalAmount = nTotalAmount;
return true;
}
bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
CLevelDBBatch batch;
for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
}
batch.Write(DB_LAST_BLOCK, nLastFile);
for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
}
return WriteBatch(batch, true);
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair(DB_TXINDEX, txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CLevelDBBatch batch;
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::ReadAddrIndex(uint160 addrid, std::vector<CExtDiskTxPos> &list) {
boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
uint64_t lookupid;
{
CHashWriter ss(SER_GETHASH, 0);
ss << salt;
ss << addrid;
lookupid = ss.GetHash().GetLow64();
}
CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
ssKeySet << make_pair('a', lookupid);
pcursor->Seek(ssKeySet.str());
while (pcursor->Valid()) {
std::pair<std::pair<char, uint64_t>, CExtDiskTxPos> key;
leveldb::Slice slKey = pcursor->key();
try {
CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION);
ssKey >> key;
} catch(std::exception &e) {
break;
}
if (key.first.first == 'a' && key.first.second == lookupid) {
list.push_back(key.second);
} else {
break;
}
pcursor->Next();
}
return true;
}
bool CBlockTreeDB::AddAddrIndex(const std::vector<std::pair<uint160, CExtDiskTxPos> > &list) {
unsigned char foo[0];
CLevelDBBatch batch;
for (std::vector<std::pair<uint160, CExtDiskTxPos> >::const_iterator it=list.begin(); it!=list.end(); it++) {
CHashWriter ss(SER_GETHASH, 0);
ss << salt;
ss << it->first;
batch.Write(make_pair(make_pair('a', ss.GetHash().GetLow64()), it->second), FLATDATA(foo));
}
return WriteBatch(batch, true);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair(DB_FLAG, name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts()
{
boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
ssKeySet << make_pair(DB_BLOCK_INDEX, uint256());
pcursor->Seek(ssKeySet.str());
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == DB_BLOCK_INDEX) {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CDiskBlockIndex diskindex;
ssValue >> diskindex;
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits))
return error("LoadBlockIndex() : CheckProofOfWork failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
break; // if shutdown requested or finished loading block index
}
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
return true;
}
<commit_msg>remove code added from cherry-pikcing from bitcoin master<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "pow.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/thread.hpp>
using namespace std;
static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f';
static const char DB_TXINDEX = 't';
static const char DB_BLOCK_INDEX = 'b';
static const char DB_BEST_BLOCK = 'B';
static const char DB_FLAG = 'F';
static const char DB_REINDEX_FLAG = 'R';
static const char DB_LAST_BLOCK = 'l';
void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
if (coins.IsPruned())
batch.Erase(make_pair(DB_COINS, hash));
else
batch.Write(make_pair(DB_COINS, hash), coins);
}
void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
batch.Write(DB_BEST_BLOCK, hash);
}
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
}
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
return db.Read(make_pair(DB_COINS, txid), coins);
}
bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
return db.Exists(make_pair(DB_COINS, txid));
}
uint256 CCoinsViewDB::GetBestBlock() const {
uint256 hashBestChain;
if (!db.Read(DB_BEST_BLOCK, hashBestChain))
return uint256(0);
return hashBestChain;
}
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
CLevelDBBatch batch;
size_t count = 0;
size_t changed = 0;
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
BatchWriteCoins(batch, it->first, it->second.coins);
changed++;
}
count++;
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
if (hashBlock != uint256(0))
BatchWriteHashBestChain(batch, hashBlock);
LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
return db.WriteBatch(batch);
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
if (!Read('S', salt)) {
salt = GetRandHash();
Write('S', salt);
}
}
bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
}
bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
return Write(make_pair('f', nFile), info);
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair(DB_BLOCK_FILES, nFile), info);
}
bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
return Write('l', nFile);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write(DB_REINDEX_FLAG, '1');
else
return Erase(DB_REINDEX_FLAG);
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists(DB_REINDEX_FLAG);
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read(DB_LAST_BLOCK, nFile);
}
bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
/* It seems that there are no "const iterators" for LevelDB. Since we
only need read operations on it, use a const-cast to get around
that restriction. */
boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator());
pcursor->SeekToFirst();
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = GetBestBlock();
ss << stats.hashBlock;
CAmount nTotalAmount = 0;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == DB_COINS) {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CCoins coins;
ssValue >> coins;
uint256 txhash;
ssKey >> txhash;
ss << txhash;
ss << VARINT(coins.nVersion);
ss << (coins.fCoinBase ? 'c' : 'n');
ss << VARINT(coins.nHeight);
stats.nTransactions++;
for (unsigned int i=0; i<coins.vout.size(); i++) {
const CTxOut &out = coins.vout[i];
if (!out.IsNull()) {
stats.nTransactionOutputs++;
ss << VARINT(i+1);
ss << out;
nTotalAmount += out.nValue;
}
}
stats.nSerializedSize += 32 + slValue.size();
ss << VARINT(0);
}
pcursor->Next();
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight;
stats.hashSerialized = ss.GetHash();
stats.nTotalAmount = nTotalAmount;
return true;
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair(DB_TXINDEX, txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CLevelDBBatch batch;
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::ReadAddrIndex(uint160 addrid, std::vector<CExtDiskTxPos> &list) {
boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
uint64_t lookupid;
{
CHashWriter ss(SER_GETHASH, 0);
ss << salt;
ss << addrid;
lookupid = ss.GetHash().GetLow64();
}
CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
ssKeySet << make_pair('a', lookupid);
pcursor->Seek(ssKeySet.str());
while (pcursor->Valid()) {
std::pair<std::pair<char, uint64_t>, CExtDiskTxPos> key;
leveldb::Slice slKey = pcursor->key();
try {
CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION);
ssKey >> key;
} catch(std::exception &e) {
break;
}
if (key.first.first == 'a' && key.first.second == lookupid) {
list.push_back(key.second);
} else {
break;
}
pcursor->Next();
}
return true;
}
bool CBlockTreeDB::AddAddrIndex(const std::vector<std::pair<uint160, CExtDiskTxPos> > &list) {
unsigned char foo[0];
CLevelDBBatch batch;
for (std::vector<std::pair<uint160, CExtDiskTxPos> >::const_iterator it=list.begin(); it!=list.end(); it++) {
CHashWriter ss(SER_GETHASH, 0);
ss << salt;
ss << it->first;
batch.Write(make_pair(make_pair('a', ss.GetHash().GetLow64()), it->second), FLATDATA(foo));
}
return WriteBatch(batch, true);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair(DB_FLAG, name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts()
{
boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
ssKeySet << make_pair(DB_BLOCK_INDEX, uint256());
pcursor->Seek(ssKeySet.str());
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == DB_BLOCK_INDEX) {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CDiskBlockIndex diskindex;
ssValue >> diskindex;
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits))
return error("LoadBlockIndex() : CheckProofOfWork failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
break; // if shutdown requested or finished loading block index
}
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
return true;
}
<|endoftext|> |
<commit_before>/* Copyright 2009 Juan González de Benito.
* This source comes from the XtreemFS project. It is licensed under the GPLv2
* (see COPYING for terms and conditions).
*/
#include "xtreemfs/main.h"
using namespace xtreemfs;
#include "vivaldi_node.h"
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <limits>
#include <cstring>
#include <typeinfo>
#ifdef _WIN32
YIELD::platform::CountingSemaphore YIELD::Main::pause_semaphore;
#endif
/*
* Minimum recalculation period.
*
* The recalculation period is randomly determined and is always included
* between the minimum and the maximum period.
*/
#define MIN_RECALCULATION_IN_MS 1000 * 270
/*
* Maximum recalculation period.
*
* The recalculation period is randomly determined and is always included
* between the minimum and the maximum period.
*/
#define MAX_RECALCULATION_IN_MS 1000 * 330
/*
* Number of times the node recalculates its position before updating
* its list of existent OSDs.
*/
#define ITERATIONS_BEFORE_UPDATING 24
/*
* Number of retries sent before accepting a high RTT.
*/
#define MAX_RETRIES_FOR_A_REQUEST 2
//#define MAX_REQUEST_TIMEOUT_IN_NS 1000000000ul * 120ul
#ifndef _WIN32
#define SPRINTF_VIV(buff,size,format,...) \
snprintf(buff,size,format,__VA_ARGS__)
#else
#define SPRINTF_VIV(buff,size,format,...) \
sprintf_s(buff,size,format,__VA_ARGS__)
#endif
namespace xtfs_vivaldi
{
class Main : public xtreemfs::Main, public YIELD::platform::Thread
{
public:
Main()
: xtreemfs::Main( "xtfs_vivaldi", "start the XtreemFS Vivaldi service ",
"<dir host>[:port] <path to Vivaldi coordinates output file>" )
{
std::srand( static_cast<unsigned int>( std::time( NULL ) ) );
}
private:
auto_DIRProxy dir_proxy;
YIELD::platform::Path vivaldi_coordinates_file_path;
// YIELD::Main
int _main( int, char** )
{
YIELD::platform::Thread::start();
YIELD::Main::pause();
return 0;
}
void parseFiles( int file_count, char** files )
{
if ( file_count >= 2 )
{
YIELD::ipc::auto_URI dir_uri = parseURI( files[0] );
dir_proxy = createDIRProxy( *dir_uri );
vivaldi_coordinates_file_path = files[1];
}
else
throw YIELD::platform::Exception("must specify dir_host and a "\
"Vivaldi coordinates output file path");
}
// YIELD::Thread
void run()
{
//Initialized to (0,0) by default
org::xtreemfs::interfaces::VivaldiCoordinates \
my_vivaldi_coordinates( 0, 0, 0 );
//Try to read coordinates from local file
YIELD::platform::auto_File vivaldi_coordinates_file =
YIELD::platform::Volume().open( vivaldi_coordinates_file_path, O_RDONLY );
if ( vivaldi_coordinates_file != NULL )
{
for ( ;; )
{
//x,y,local_error => 3 doubles
yidl::runtime::StackBuffer<3*sizeof(double)> xdr_buffer;
if ( vivaldi_coordinates_file->read( xdr_buffer.incRef() ) ==
3*sizeof(double) )
{
YIELD::platform::XDRUnmarshaller xdr_unmarshaller( xdr_buffer.incRef() );
my_vivaldi_coordinates.unmarshal( xdr_unmarshaller );
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:coordinates readed from file:(" <<
my_vivaldi_coordinates.get_x_coordinate() <<
"," << my_vivaldi_coordinates.get_y_coordinate() << ")";
}else
{
break;
}
}
vivaldi_coordinates_file->close();
}else{
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:impossible to read coordinates from file."\
"Initializing them by default...";
}
VivaldiNode own_node(my_vivaldi_coordinates);
long vivaldiIterations = 0;
org::xtreemfs::interfaces::ServiceSet osd_services;
std::vector<uint64_t> currentRetries;
int retriesInARow = 0;
org::xtreemfs::interfaces::Service *random_osd_service;
for ( ;; )
{
try
{
//Get a list of OSDs from the DS
if( (vivaldiIterations%ITERATIONS_BEFORE_UPDATING) == 1)
{
updateKnownOSDs(osd_services);
currentRetries.clear(); /*The pending retries are discarded, because
the old OSDs might not be in the new list*/
retriesInARow = 0;
}
if ( !osd_services.empty() )
{
if(retriesInARow==0){
//Choose one OSD randomly, only if there's no pending retry
random_osd_service = &osd_services[std::rand() % osd_services.size()];
}
yidl::runtime::auto_Object<org::xtreemfs::interfaces::AddressMappingSet> \
random_osd_address_mappings =
dir_proxy->getAddressMappingsFromUUID(random_osd_service->get_uuid());
//Several mappings for the same UUID
for ( org::xtreemfs::interfaces::AddressMappingSet::iterator \
random_osd_address_mapping_i = random_osd_address_mappings->begin();
random_osd_address_mapping_i != random_osd_address_mappings->end();
random_osd_address_mapping_i++ )
{
if ( (*random_osd_address_mapping_i).get_protocol() ==
org::xtreemfs::interfaces::ONCRPCU_SCHEME )
{
auto_OSDProxy osd_proxy =
OSDProxy::create( ( *random_osd_address_mapping_i ).get_uri(),
OSDProxy::CONCURRENCY_LEVEL_DEFAULT,
get_proxy_flags(),
get_log(),
get_operation_timeout() );
org::xtreemfs::interfaces::VivaldiCoordinates random_osd_vivaldi_coordinates;
//Send the request and measure the RTT
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:recalculating against " <<
random_osd_service->get_uuid();
YIELD::platform::Time start_time;
osd_proxy->xtreemfs_ping( org::xtreemfs::interfaces::VivaldiCoordinates(),
random_osd_vivaldi_coordinates );
YIELD::platform::Time rtt( YIELD::platform::Time() - start_time );
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:ping response received";
//Next code is not executed if the ping request times out
uint64_t measuredRTT = rtt.as_unix_time_ms();
bool retried = false;
// Recalculate coordinates here
if( retriesInARow < MAX_RETRIES_FOR_A_REQUEST ){
if( !own_node.recalculatePosition(random_osd_vivaldi_coordinates,
measuredRTT,
false) ){
/*The movement has been postponed because the measured RTT
seems to be a peak*/
currentRetries.push_back(measuredRTT);
retriesInARow++;
retried = true;
}else{
//The movement has been accepted
currentRetries.clear();
retriesInARow = 0;
}
}else{
//Choose the lowest RTT
uint64_t lowestOne = measuredRTT;
for( std::vector<uint64_t>::iterator it = currentRetries.begin();
it<currentRetries.end();
it++){
if( (*it) < lowestOne ){
lowestOne = (*it);
}
}
//Forcing recalculation because we've retried too many times
own_node.recalculatePosition( random_osd_vivaldi_coordinates,
lowestOne,
true);
currentRetries.clear();
retriesInARow = 0;
//This is just to include in the trace the definitive RTT
measuredRTT = lowestOne;
}
//Print trace
char auxStr[256];
SPRINTF_VIV( auxStr,
256,
"%s:%lld(Viv:%.3f) Own:(%.3f,%.3f) lE=%.3f "\
"Rem:(%.3f,%.3f) rE=%.3f %s",
retried?"RETRY":"RTT",
static_cast<long long int>(measuredRTT),
own_node.calculateDistance((*own_node.getCoordinates()),
random_osd_vivaldi_coordinates),
own_node.getCoordinates()->get_x_coordinate(),
own_node.getCoordinates()->get_y_coordinate(),
own_node.getCoordinates()->get_local_error(),
random_osd_vivaldi_coordinates.get_x_coordinate(),
random_osd_vivaldi_coordinates.get_y_coordinate(),
random_osd_vivaldi_coordinates.get_local_error(),
random_osd_service->get_uuid().data());
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:" << auxStr;
}
}
}else{
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:no OSD available";
}
}catch ( std::exception& exc ){
get_log()->getStream( YIELD::platform::Log::LOG_ERR ) <<
"xtfs_vivaldi: error pinging OSDs: " << exc.what() << ".";
//TOFIX:This must be done only for timeout exceptions
//We must avoid to keep retrying indefinitely against an OSD which is not responding
if(retriesInARow && (++retriesInARow >= MAX_RETRIES_FOR_A_REQUEST) ){
//If the last retry times out all the previous retries are discarded
currentRetries.clear();
retriesInARow = 0;
}
}
//Store the new coordinates in a local file
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:storing coordinates in file:(" <<
own_node.getCoordinates()->get_x_coordinate() <<
"," << own_node.getCoordinates()->get_y_coordinate() << ")";
vivaldi_coordinates_file = \
YIELD::platform::Volume().open( vivaldi_coordinates_file_path,
O_CREAT|O_TRUNC|O_WRONLY );
if ( vivaldi_coordinates_file != NULL )
{
YIELD::platform::XDRMarshaller xdr_marshaller;
own_node.getCoordinates()->marshal( xdr_marshaller );
vivaldi_coordinates_file->write( xdr_marshaller.get_buffer().release() );
vivaldi_coordinates_file->close();
}
//Sleep until the next iteration
uint64_t sleep_in_ms =
MIN_RECALCULATION_IN_MS +
( (static_cast<double>(std::rand())/(RAND_MAX-1)) *
(MAX_RECALCULATION_IN_MS - MIN_RECALCULATION_IN_MS) );
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:sleeping during " << sleep_in_ms << " ms.";
YIELD::platform::Thread::sleep( sleep_in_ms * NS_IN_MS );
vivaldiIterations = (vivaldiIterations+1)%LONG_MAX;
}
}
/* Retrieves a list of available OSDs from the DS
*/
void updateKnownOSDs(org::xtreemfs::interfaces::ServiceSet &osds){
try{
dir_proxy->xtreemfs_service_get_by_type( \
org::xtreemfs::interfaces::SERVICE_TYPE_OSD,
osds );
org::xtreemfs::interfaces::ServiceSet::iterator ss_iterator = osds.begin();
while( ss_iterator != osds.end() ){
if( (*ss_iterator).get_last_updated_s() == 0)
{
osds.erase(ss_iterator);
}else
{
ss_iterator++;
}
}
}catch( std::exception ex ){
get_log()->getStream( YIELD::platform::Log::LOG_ERR ) <<
"xtfs_vivaldi:Impossible to update known OSDs";
}
}
};
};
int main( int argc, char** argv )
{
return xtfs_vivaldi::Main().main( argc, argv );
}
<commit_msg>xtfs_vivaldi: Fixed some remaining formatting errors<commit_after>/* Copyright 2009 Juan González de Benito.
* This source comes from the XtreemFS project. It is licensed under the GPLv2
* (see COPYING for terms and conditions).
*/
#include "xtreemfs/main.h"
using namespace xtreemfs;
#include "vivaldi_node.h"
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <limits>
#include <cstring>
#include <typeinfo>
#ifdef _WIN32
YIELD::platform::CountingSemaphore YIELD::Main::pause_semaphore;
#endif
/*
* Minimum recalculation period.
*
* The recalculation period is randomly determined and is always included
* between the minimum and the maximum period.
*/
#define MIN_RECALCULATION_IN_MS 1000 * 270
/*
* Maximum recalculation period.
*
* The recalculation period is randomly determined and is always included
* between the minimum and the maximum period.
*/
#define MAX_RECALCULATION_IN_MS 1000 * 330
/*
* Number of times the node recalculates its position before updating
* its list of existent OSDs.
*/
#define ITERATIONS_BEFORE_UPDATING 24
/*
* Number of retries sent before accepting a high RTT.
*/
#define MAX_RETRIES_FOR_A_REQUEST 2
//#define MAX_REQUEST_TIMEOUT_IN_NS 1000000000ul * 120ul
#ifndef _WIN32
#define SPRINTF_VIV(buff,size,format,...) \
snprintf(buff,size,format,__VA_ARGS__)
#else
#define SPRINTF_VIV(buff,size,format,...) \
sprintf_s(buff,size,format,__VA_ARGS__)
#endif
namespace xtfs_vivaldi
{
class Main : public xtreemfs::Main, public YIELD::platform::Thread
{
public:
Main()
: xtreemfs::Main( "xtfs_vivaldi", "start the XtreemFS Vivaldi service ",
"<dir host>[:port] <path to Vivaldi coordinates output file>" )
{
std::srand( static_cast<unsigned int>( std::time( NULL ) ) );
}
private:
auto_DIRProxy dir_proxy;
YIELD::platform::Path vivaldi_coordinates_file_path;
// YIELD::Main
int _main( int, char** )
{
YIELD::platform::Thread::start();
YIELD::Main::pause();
return 0;
}
void parseFiles( int file_count, char** files )
{
if ( file_count >= 2 )
{
YIELD::ipc::auto_URI dir_uri = parseURI( files[0] );
dir_proxy = createDIRProxy( *dir_uri );
vivaldi_coordinates_file_path = files[1];
}
else
throw YIELD::platform::Exception("must specify dir_host and a "\
"Vivaldi coordinates output file path");
}
// YIELD::Thread
void run()
{
//Initialized to (0,0) by default
org::xtreemfs::interfaces::VivaldiCoordinates \
my_vivaldi_coordinates( 0, 0, 0 );
//Try to read coordinates from local file
YIELD::platform::auto_File vivaldi_coordinates_file =
YIELD::platform::Volume().open( vivaldi_coordinates_file_path, O_RDONLY );
if ( vivaldi_coordinates_file != NULL )
{
for ( ;; )
{
//x,y,local_error => 3 doubles
yidl::runtime::StackBuffer<3*sizeof(double)> xdr_buffer;
if ( vivaldi_coordinates_file->read( xdr_buffer.incRef() ) ==
3*sizeof(double) )
{
YIELD::platform::XDRUnmarshaller xdr_unmarshaller( xdr_buffer.incRef() );
my_vivaldi_coordinates.unmarshal( xdr_unmarshaller );
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:coordinates readed from file:(" <<
my_vivaldi_coordinates.get_x_coordinate() <<
"," << my_vivaldi_coordinates.get_y_coordinate() << ")";
}else
{
break;
}
}
vivaldi_coordinates_file->close();
}else{
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:impossible to read coordinates from file."\
"Initializing them by default...";
}
VivaldiNode own_node(my_vivaldi_coordinates);
long vivaldiIterations = 0;
org::xtreemfs::interfaces::ServiceSet osd_services;
std::vector<uint64_t> currentRetries;
int retriesInARow = 0;
org::xtreemfs::interfaces::Service *random_osd_service;
for ( ;; )
{
try
{
//Get a list of OSDs from the DS
if( (vivaldiIterations%ITERATIONS_BEFORE_UPDATING) == 1)
{
updateKnownOSDs(osd_services);
currentRetries.clear(); /*The pending retries are discarded, because
the old OSDs might not be in the new list*/
retriesInARow = 0;
}
if ( !osd_services.empty() )
{
if(retriesInARow==0){
//Choose one OSD randomly, only if there's no pending retry
random_osd_service = &osd_services[std::rand() % osd_services.size()];
}
yidl::runtime::auto_Object<org::xtreemfs::interfaces::AddressMappingSet> \
random_osd_address_mappings =
dir_proxy->getAddressMappingsFromUUID(random_osd_service->get_uuid());
//Several mappings for the same UUID
for ( org::xtreemfs::interfaces::AddressMappingSet::iterator \
random_osd_address_mapping_i = random_osd_address_mappings->begin();
random_osd_address_mapping_i != random_osd_address_mappings->end();
random_osd_address_mapping_i++ )
{
if ( (*random_osd_address_mapping_i).get_protocol() ==
org::xtreemfs::interfaces::ONCRPCU_SCHEME )
{
auto_OSDProxy osd_proxy =
OSDProxy::create( ( *random_osd_address_mapping_i ).get_uri(),
OSDProxy::CONCURRENCY_LEVEL_DEFAULT,
get_proxy_flags(),
get_log(),
get_operation_timeout() );
org::xtreemfs::interfaces::VivaldiCoordinates random_osd_vivaldi_coordinates;
//Send the request and measure the RTT
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:recalculating against " <<
random_osd_service->get_uuid();
YIELD::platform::Time start_time;
osd_proxy->xtreemfs_ping( org::xtreemfs::interfaces::VivaldiCoordinates(),
random_osd_vivaldi_coordinates );
YIELD::platform::Time rtt( YIELD::platform::Time() - start_time );
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:ping response received";
//Next code is not executed if the ping request times out
uint64_t measuredRTT = rtt.as_unix_time_ms();
bool retried = false;
// Recalculate coordinates here
if( retriesInARow < MAX_RETRIES_FOR_A_REQUEST ){
if( !own_node.recalculatePosition(random_osd_vivaldi_coordinates,
measuredRTT,
false) ){
/*The movement has been postponed because the measured RTT
seems to be a peak*/
currentRetries.push_back(measuredRTT);
retriesInARow++;
retried = true;
}else{
//The movement has been accepted
currentRetries.clear();
retriesInARow = 0;
}
}else{
//Choose the lowest RTT
uint64_t lowestOne = measuredRTT;
for( std::vector<uint64_t>::iterator it = currentRetries.begin();
it<currentRetries.end();
it++){
if( (*it) < lowestOne ){
lowestOne = (*it);
}
}
//Forcing recalculation because we've retried too many times
own_node.recalculatePosition( random_osd_vivaldi_coordinates,
lowestOne,
true);
currentRetries.clear();
retriesInARow = 0;
//This is just to include in the trace the definitive RTT
measuredRTT = lowestOne;
}
//Print trace
char auxStr[256];
SPRINTF_VIV( auxStr,
256,
"%s:%lld(Viv:%.3f) Own:(%.3f,%.3f) lE=%.3f "\
"Rem:(%.3f,%.3f) rE=%.3f %s",
retried?"RETRY":"RTT",
static_cast<long long int>(measuredRTT),
own_node.calculateDistance((*own_node.getCoordinates()),
random_osd_vivaldi_coordinates),
own_node.getCoordinates()->get_x_coordinate(),
own_node.getCoordinates()->get_y_coordinate(),
own_node.getCoordinates()->get_local_error(),
random_osd_vivaldi_coordinates.get_x_coordinate(),
random_osd_vivaldi_coordinates.get_y_coordinate(),
random_osd_vivaldi_coordinates.get_local_error(),
random_osd_service->get_uuid().data());
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:" << auxStr;
}
}
}else{
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:no OSD available";
}
}catch ( std::exception& exc ){
get_log()->getStream( YIELD::platform::Log::LOG_ERR ) <<
"xtfs_vivaldi: error pinging OSDs: " << exc.what() << ".";
//TOFIX:This must be done only for timeout exceptions
//We must avoid to keep retrying indefinitely against an OSD which is not responding
if(retriesInARow && (++retriesInARow >= MAX_RETRIES_FOR_A_REQUEST) ){
//If the last retry times out all the previous retries are discarded
currentRetries.clear();
retriesInARow = 0;
}
}
//Store the new coordinates in a local file
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:storing coordinates in file:(" <<
own_node.getCoordinates()->get_x_coordinate() <<
"," << own_node.getCoordinates()->get_y_coordinate() << ")";
vivaldi_coordinates_file = \
YIELD::platform::Volume().open( vivaldi_coordinates_file_path,
O_CREAT|O_TRUNC|O_WRONLY );
if ( vivaldi_coordinates_file != NULL )
{
YIELD::platform::XDRMarshaller xdr_marshaller;
own_node.getCoordinates()->marshal( xdr_marshaller );
vivaldi_coordinates_file->write( xdr_marshaller.get_buffer().release() );
vivaldi_coordinates_file->close();
}
//Sleep until the next iteration
uint64_t sleep_in_ms =
MIN_RECALCULATION_IN_MS +
( (static_cast<double>(std::rand())/(RAND_MAX-1)) *
(MAX_RECALCULATION_IN_MS - MIN_RECALCULATION_IN_MS) );
get_log()->getStream( YIELD::platform::Log::LOG_DEBUG ) <<
"xtfs_vivaldi:sleeping during " << sleep_in_ms << " ms.";
YIELD::platform::Thread::sleep( sleep_in_ms * NS_IN_MS );
vivaldiIterations = (vivaldiIterations+1)%LONG_MAX;
}
}
/* Retrieves a list of available OSDs from the DS
*/
void updateKnownOSDs(org::xtreemfs::interfaces::ServiceSet &osds){
try{
dir_proxy->xtreemfs_service_get_by_type( \
org::xtreemfs::interfaces::SERVICE_TYPE_OSD,
osds );
org::xtreemfs::interfaces::ServiceSet::iterator ss_iterator = osds.begin();
while( ss_iterator != osds.end() ){
if( (*ss_iterator).get_last_updated_s() == 0)
{
osds.erase(ss_iterator);
}else
{
ss_iterator++;
}
}
}catch( std::exception ex ){
get_log()->getStream( YIELD::platform::Log::LOG_ERR ) <<
"xtfs_vivaldi:Impossible to update known OSDs";
}
}
};
};
int main( int argc, char** argv )
{
return xtfs_vivaldi::Main().main( argc, argv );
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "pow.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/thread.hpp>
using namespace std;
void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
if (coins.IsPruned())
batch.Erase(make_pair('c', hash));
else
batch.Write(make_pair('c', hash), coins);
}
void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
batch.Write('B', hash);
}
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
}
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
return db.Read(make_pair('c', txid), coins);
}
bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
return db.Exists(make_pair('c', txid));
}
uint256 CCoinsViewDB::GetBestBlock() const {
uint256 hashBestChain;
if (!db.Read('B', hashBestChain))
return uint256(0);
return hashBestChain;
}
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
CLevelDBBatch batch;
size_t count = 0;
size_t changed = 0;
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
BatchWriteCoins(batch, it->first, it->second.coins);
changed++;
}
count++;
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
if (hashBlock != uint256(0))
BatchWriteHashBestChain(batch, hashBlock);
LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
return db.WriteBatch(batch);
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}
bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
}
bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
return Write(make_pair('f', nFile), info);
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair('f', nFile), info);
}
bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
return Write('l', nFile);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write('R', '1');
else
return Erase('R');
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists('R');
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read('l', nFile);
}
bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
/* It seems that there are no "const iterators" for LevelDB. Since we
only need read operations on it, use a const-cast to get around
that restriction. */
boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator());
pcursor->SeekToFirst();
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = GetBestBlock();
ss << stats.hashBlock;
CAmount nTotalAmount = 0;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == 'c') {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CCoins coins;
ssValue >> coins;
uint256 txhash;
ssKey >> txhash;
ss << txhash;
ss << VARINT(coins.nVersion);
ss << (coins.fCoinBase ? 'c' : 'n');
ss << VARINT(coins.nHeight);
stats.nTransactions++;
for (unsigned int i=0; i<coins.vout.size(); i++) {
const CTxOut &out = coins.vout[i];
if (!out.IsNull()) {
stats.nTransactionOutputs++;
ss << VARINT(i+1);
ss << out;
nTotalAmount += out.nValue;
}
}
stats.nSerializedSize += 32 + slValue.size();
ss << VARINT(0);
}
pcursor->Next();
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight;
stats.hashSerialized = ss.GetHash();
stats.nTotalAmount = nTotalAmount;
return true;
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair('t', txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CLevelDBBatch batch;
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair('t', it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair('F', name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair('F', name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts()
{
boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
ssKeySet << make_pair('b', uint256(0));
pcursor->Seek(ssKeySet.str());
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == 'b') {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CDiskBlockIndex diskindex;
ssValue >> diskindex;
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits))
return error("LoadBlockIndex() : CheckProofOfWork failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
break; // if shutdown requested or finished loading block index
}
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
return true;
}
<commit_msg>change PoW checking for block index to properly use PoW hash rather than sha256 hash<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "pow.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/thread.hpp>
using namespace std;
void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
if (coins.IsPruned())
batch.Erase(make_pair('c', hash));
else
batch.Write(make_pair('c', hash), coins);
}
void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
batch.Write('B', hash);
}
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
}
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
return db.Read(make_pair('c', txid), coins);
}
bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
return db.Exists(make_pair('c', txid));
}
uint256 CCoinsViewDB::GetBestBlock() const {
uint256 hashBestChain;
if (!db.Read('B', hashBestChain))
return uint256(0);
return hashBestChain;
}
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
CLevelDBBatch batch;
size_t count = 0;
size_t changed = 0;
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
BatchWriteCoins(batch, it->first, it->second.coins);
changed++;
}
count++;
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
if (hashBlock != uint256(0))
BatchWriteHashBestChain(batch, hashBlock);
LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
return db.WriteBatch(batch);
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}
bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
}
bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
return Write(make_pair('f', nFile), info);
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair('f', nFile), info);
}
bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
return Write('l', nFile);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write('R', '1');
else
return Erase('R');
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists('R');
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read('l', nFile);
}
bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
/* It seems that there are no "const iterators" for LevelDB. Since we
only need read operations on it, use a const-cast to get around
that restriction. */
boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator());
pcursor->SeekToFirst();
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = GetBestBlock();
ss << stats.hashBlock;
CAmount nTotalAmount = 0;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == 'c') {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CCoins coins;
ssValue >> coins;
uint256 txhash;
ssKey >> txhash;
ss << txhash;
ss << VARINT(coins.nVersion);
ss << (coins.fCoinBase ? 'c' : 'n');
ss << VARINT(coins.nHeight);
stats.nTransactions++;
for (unsigned int i=0; i<coins.vout.size(); i++) {
const CTxOut &out = coins.vout[i];
if (!out.IsNull()) {
stats.nTransactionOutputs++;
ss << VARINT(i+1);
ss << out;
nTotalAmount += out.nValue;
}
}
stats.nSerializedSize += 32 + slValue.size();
ss << VARINT(0);
}
pcursor->Next();
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight;
stats.hashSerialized = ss.GetHash();
stats.nTotalAmount = nTotalAmount;
return true;
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair('t', txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CLevelDBBatch batch;
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair('t', it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair('F', name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair('F', name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts()
{
boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator());
CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
ssKeySet << make_pair('b', uint256(0));
pcursor->Seek(ssKeySet.str());
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
try {
leveldb::Slice slKey = pcursor->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
char chType;
ssKey >> chType;
if (chType == 'b') {
leveldb::Slice slValue = pcursor->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CDiskBlockIndex diskindex;
ssValue >> diskindex;
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
if (!CheckProofOfWork(pindexNew->GetBlockHeader().GetPoWHash(), pindexNew->nBits))
return error("LoadBlockIndex() : CheckProofOfWork failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
break; // if shutdown requested or finished loading block index
}
} catch (std::exception &e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "chainparams.h"
#include "hash.h"
#include "pow.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/thread.hpp>
using namespace std;
static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f';
static const char DB_TXINDEX = 't';
static const char DB_BLOCK_INDEX = 'b';
static const char DB_BEST_BLOCK = 'B';
static const char DB_FLAG = 'F';
static const char DB_REINDEX_FLAG = 'R';
static const char DB_LAST_BLOCK = 'l';
void static BatchWriteCoins(CDBBatch &batch, const uint256 &hash, const CCoins &coins) {
if (coins.IsPruned())
batch.Erase(make_pair(DB_COINS, hash));
else
batch.Write(make_pair(DB_COINS, hash), coins);
}
void static BatchWriteHashBestChain(CDBBatch &batch, const uint256 &hash) {
batch.Write(DB_BEST_BLOCK, hash);
}
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool &isObfuscated, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, isObfuscated, fMemory, fWipe) {
}
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
return db.Read(make_pair(DB_COINS, txid), coins);
}
bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
return db.Exists(make_pair(DB_COINS, txid));
}
uint256 CCoinsViewDB::GetBestBlock() const {
uint256 hashBestChain;
if (!db.Read(DB_BEST_BLOCK, hashBestChain))
return uint256();
return hashBestChain;
}
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
CDBBatch batch;
size_t count = 0;
size_t changed = 0;
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
BatchWriteCoins(batch, it->first, it->second.coins);
changed++;
}
count++;
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
if (!hashBlock.IsNull())
BatchWriteHashBestChain(batch, hashBlock);
LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
return db.WriteBatch(batch);
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool &isObfuscated, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, isObfuscated, fMemory, fWipe) {
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair(DB_BLOCK_FILES, nFile), info);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write(DB_REINDEX_FLAG, '1');
else
return Erase(DB_REINDEX_FLAG);
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists(DB_REINDEX_FLAG);
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read(DB_LAST_BLOCK, nFile);
}
CCoinsViewCursor *CCoinsViewDB::Cursor() const
{
CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper*>(&db)->NewIterator(), GetBestBlock());
/* It seems that there are no "const iterators" for LevelDB. Since we
only need read operations on it, use a const-cast to get around
that restriction. */
i->pcursor->Seek(DB_COINS);
// Cache key of first record
i->pcursor->GetKey(i->keyTmp);
return i;
}
bool CCoinsViewDBCursor::GetKey(uint256 &key) const
{
// Return cached key
if (keyTmp.first == DB_COINS) {
key = keyTmp.second;
return true;
}
return false;
}
bool CCoinsViewDBCursor::GetValue(CCoins &coins) const
{
return pcursor->GetValue(coins);
}
unsigned int CCoinsViewDBCursor::GetValueSize() const
{
return pcursor->GetValueSize();
}
bool CCoinsViewDBCursor::Valid() const
{
return keyTmp.first == DB_COINS;
}
void CCoinsViewDBCursor::Next()
{
pcursor->Next();
if (pcursor->Valid()) {
bool ok = pcursor->GetKey(keyTmp);
assert(ok); // If GetKey fails here something must be wrong with underlying database, we cannot handle that here
} else {
keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false
}
}
bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
CDBBatch batch;
for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
}
batch.Write(DB_LAST_BLOCK, nLastFile);
for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
}
return WriteBatch(batch, true);
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair(DB_TXINDEX, txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CDBBatch batch;
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair(DB_FLAG, name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts(boost::function<CBlockIndex*(const uint256&)> insertBlockIndex)
{
std::unique_ptr<CDBIterator> pcursor(NewIterator());
pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256()));
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
std::pair<char, uint256> key;
if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
CDiskBlockIndex diskindex;
if (pcursor->GetValue(diskindex)) {
// Construct block index object
CBlockIndex* pindexNew = insertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = insertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
pindexNew->nSerialVersion = diskindex.nSerialVersion;
pindexNew->nMaxBlockSize = diskindex.nMaxBlockSize;
pindexNew->nMaxBlockSizeVote = diskindex.nMaxBlockSizeVote;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
return error("LoadBlockIndex() : failed to read value");
}
} else {
break;
}
}
return true;
}
<commit_msg>txdb: Fix assert crash in new UTXO set cursor<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "chainparams.h"
#include "hash.h"
#include "pow.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/thread.hpp>
using namespace std;
static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f';
static const char DB_TXINDEX = 't';
static const char DB_BLOCK_INDEX = 'b';
static const char DB_BEST_BLOCK = 'B';
static const char DB_FLAG = 'F';
static const char DB_REINDEX_FLAG = 'R';
static const char DB_LAST_BLOCK = 'l';
void static BatchWriteCoins(CDBBatch &batch, const uint256 &hash, const CCoins &coins) {
if (coins.IsPruned())
batch.Erase(make_pair(DB_COINS, hash));
else
batch.Write(make_pair(DB_COINS, hash), coins);
}
void static BatchWriteHashBestChain(CDBBatch &batch, const uint256 &hash) {
batch.Write(DB_BEST_BLOCK, hash);
}
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool &isObfuscated, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, isObfuscated, fMemory, fWipe) {
}
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
return db.Read(make_pair(DB_COINS, txid), coins);
}
bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
return db.Exists(make_pair(DB_COINS, txid));
}
uint256 CCoinsViewDB::GetBestBlock() const {
uint256 hashBestChain;
if (!db.Read(DB_BEST_BLOCK, hashBestChain))
return uint256();
return hashBestChain;
}
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
CDBBatch batch;
size_t count = 0;
size_t changed = 0;
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
BatchWriteCoins(batch, it->first, it->second.coins);
changed++;
}
count++;
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
if (!hashBlock.IsNull())
BatchWriteHashBestChain(batch, hashBlock);
LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
return db.WriteBatch(batch);
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool &isObfuscated, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, isObfuscated, fMemory, fWipe) {
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(make_pair(DB_BLOCK_FILES, nFile), info);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write(DB_REINDEX_FLAG, '1');
else
return Erase(DB_REINDEX_FLAG);
}
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists(DB_REINDEX_FLAG);
return true;
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read(DB_LAST_BLOCK, nFile);
}
CCoinsViewCursor *CCoinsViewDB::Cursor() const
{
CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper*>(&db)->NewIterator(), GetBestBlock());
/* It seems that there are no "const iterators" for LevelDB. Since we
only need read operations on it, use a const-cast to get around
that restriction. */
i->pcursor->Seek(DB_COINS);
// Cache key of first record
i->pcursor->GetKey(i->keyTmp);
return i;
}
bool CCoinsViewDBCursor::GetKey(uint256 &key) const
{
// Return cached key
if (keyTmp.first == DB_COINS) {
key = keyTmp.second;
return true;
}
return false;
}
bool CCoinsViewDBCursor::GetValue(CCoins &coins) const
{
return pcursor->GetValue(coins);
}
unsigned int CCoinsViewDBCursor::GetValueSize() const
{
return pcursor->GetValueSize();
}
bool CCoinsViewDBCursor::Valid() const
{
return keyTmp.first == DB_COINS;
}
void CCoinsViewDBCursor::Next()
{
pcursor->Next();
if (!pcursor->Valid() || !pcursor->GetKey(keyTmp))
keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false
}
bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
CDBBatch batch;
for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
}
batch.Write(DB_LAST_BLOCK, nLastFile);
for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
}
return WriteBatch(batch, true);
}
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
return Read(make_pair(DB_TXINDEX, txid), pos);
}
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
CDBBatch batch;
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
return WriteBatch(batch);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair(DB_FLAG, name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts(boost::function<CBlockIndex*(const uint256&)> insertBlockIndex)
{
std::unique_ptr<CDBIterator> pcursor(NewIterator());
pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256()));
// Load mapBlockIndex
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
std::pair<char, uint256> key;
if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
CDiskBlockIndex diskindex;
if (pcursor->GetValue(diskindex)) {
// Construct block index object
CBlockIndex* pindexNew = insertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = insertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
pindexNew->nSerialVersion = diskindex.nSerialVersion;
pindexNew->nMaxBlockSize = diskindex.nMaxBlockSize;
pindexNew->nMaxBlockSizeVote = diskindex.nMaxBlockSizeVote;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
return error("LoadBlockIndex() : failed to read value");
}
} else {
break;
}
}
return true;
}
<|endoftext|> |
<commit_before>#pragma once
#include <memory>
#include <cstdint>
#include <string>
#include <vector>
#include <iostream>
#include <variant>
namespace dlvm {
using namespace dlvm;
using namespace std;
typedef uint64_t vaddr_t;
typedef uint32_t addr_t;
typedef uint32_t array_t;
typedef variant<int64_t, uint64_t, double, bool, char, addr_t> VType;
typedef variant<array_t, VType> RType;
struct ValueType;
struct ReferenceType;
template<typename Type>
struct Result;
typedef enum type_e {
NIL,
INTEGER,
UINTEGER,
FLOAT,
BOOL,
STRING,
ARRAY,
REFERENCE,
STRUCT
} type_t;
struct ValueType {
type_t type;
VType Value;
ValueType()
{ type = NIL; }
ValueType(type_t type, VType value)
: type{type}
, Value{value}
{ }
ReferenceType Box();
};
struct ReferenceType {
type_t type;
bool Marked = false;
RType Value;
ReferenceType()
{ type = NIL; }
ReferenceType(ValueType value)
: type{value.type}
, Value{value.Value}
{ }
ReferenceType(type_t type, RType value)
: type{type}
, Value{value}
{ }
Result<ValueType> Unbox();
};
typedef enum ErrorCode {
OK,
OUT_OF_MEMORY,
OUT_OF_BOUNDS,
STACK_OVERFLOW,
TYPE_ERROR,
NULL_REFERENCE,
INVALID_ARGUMENT,
UNKNOWN
} ErrorCode;
template<typename Type>
struct Result {
ErrorCode ErrCode;
Type Value;
string Message;
Result(Type value, string msg, ErrorCode error_code)
: Value{value}
, Message{msg}
, ErrCode{error_code}
{ }
Result(Type value)
: Value{value}
, ErrCode{OK}
{ }
Result(string msg, ErrorCode error_code)
: Message{msg}
, ErrCode{error_code}
{ }
};
template<typename Type>
Result<Type> OkResult(Type value);
template<typename Type>
Result<Type> TypeError(Type value);
template<typename Type>
Result<Type> ThrowError(string msg, Type value, ErrorCode error_code);
template<typename Type>
Result<Type> ThrowError(string msg, ErrorCode error_code);
/*
Result operator+ (Result lhs, Result rhs);
Result operator- (Type lhs, Type rhs);
Result operator* (Type lhs, Type rhs);
Result operator/ (Type lhs, Type rhs);
Result operator&& (Type lhs, Type rhs);
Result operator|| (Type lhs, Type rhs);
Result operator! (Type rhs);
ostream& operator<< (ostream &o, Type t);
*/
}<commit_msg>switched to 'using' instead of typedef<commit_after>#pragma once
#include <memory>
#include <cstdint>
#include <string>
#include <vector>
#include <iostream>
#include <variant>
namespace dlvm {
using namespace dlvm;
using namespace std;
using vaddr_t = uint64_t;
using addr_t = uint32_t;
using array_t = uint32_t;
using VType = variant<int64_t, uint64_t, double, bool, char, addr_t>;
using RType = variant<array_t, VType>;
struct ValueType;
struct ReferenceType;
template<typename Type>
struct Result;
typedef enum type_e {
NIL,
INTEGER,
UINTEGER,
FLOAT,
BOOL,
STRING,
ARRAY,
REFERENCE,
STRUCT
} type_t;
struct ValueType {
type_t type;
VType Value;
ValueType()
{ type = NIL; }
ValueType(type_t type, VType value)
: type{type}
, Value{value}
{ }
ReferenceType Box();
};
struct ReferenceType {
type_t type;
bool Marked = false;
RType Value;
ReferenceType()
{ type = NIL; }
ReferenceType(ValueType value)
: type{value.type}
, Value{value.Value}
{ }
ReferenceType(type_t type, RType value)
: type{type}
, Value{value}
{ }
Result<ValueType> Unbox();
};
typedef enum ErrorCode {
OK,
OUT_OF_MEMORY,
OUT_OF_BOUNDS,
STACK_OVERFLOW,
TYPE_ERROR,
NULL_REFERENCE,
INVALID_ARGUMENT,
UNKNOWN
} ErrorCode;
template<typename Type>
struct Result {
ErrorCode ErrCode;
Type Value;
string Message;
Result(Type value, string msg, ErrorCode error_code)
: Value{value}
, Message{msg}
, ErrCode{error_code}
{ }
Result(Type value)
: Value{value}
, ErrCode{OK}
{ }
Result(string msg, ErrorCode error_code)
: Message{msg}
, ErrCode{error_code}
{ }
};
template<typename Type>
Result<Type> OkResult(Type value);
template<typename Type>
Result<Type> TypeError(Type value);
template<typename Type>
Result<Type> ThrowError(string msg, Type value, ErrorCode error_code);
template<typename Type>
Result<Type> ThrowError(string msg, ErrorCode error_code);
/*
Result operator+ (Result lhs, Result rhs);
Result operator- (Type lhs, Type rhs);
Result operator* (Type lhs, Type rhs);
Result operator/ (Type lhs, Type rhs);
Result operator&& (Type lhs, Type rhs);
Result operator|| (Type lhs, Type rhs);
Result operator! (Type rhs);
ostream& operator<< (ostream &o, Type t);
*/
}<|endoftext|> |
<commit_before>#include "degenerate.hpp"
//retourne les nucléotides concaténés dans l'ordre (assuré par une itération sur le vecteur nucleotides)
const string find_neighbor_motifs( sparse_hash_map<string, pair<int, Node *>> &motifs,
sparse_hash_map<char, pair<string, Node *>> &neighbor_motifs,
const string &motif,
unsigned int pos) {
string neighbor_motif(motif);
string neighbors_nuc;
neighbors_nuc.reserve(4);
//pour tous les nucléotides
for (auto const &nuc : nucleotides) {
//on remplace la (pos)ième position du motif de base par ce nucléotide
neighbor_motif.replace(pos, 1, 1, nuc);
//on passe au suivant si le voisin n'est pas dans la table
auto const motif_it = motifs.find(neighbor_motif);
if(motif_it == motifs.end())
continue;
motif_it->second.first = pos;
//sinon, on insère dans la table des résultats le motif et son compte
neighbor_motifs[nuc] = make_pair(neighbor_motif, motifs[neighbor_motif].second);
neighbors_nuc.push_back(nuc);
}
return neighbors_nuc;
}
void degenerate(sparse_hash_map<string, pair<int, Node *>> &motifs,
sparse_hash_map<string, pair<int, Node *>> °enerated_motifs,
const unsigned int kmer_size,
bool rc) {
//pour chaque position
for (unsigned int pos = 0; pos < kmer_size; pos++) {
//pour chaque motif dans la table
for (auto const &motif_it : motifs) {
//s'il n'a pas été marqué pour cette position ou si la position a déjà été dégénérée
if(motif_it.second.first == pos || motif_it.second.first == kmer_size || !string("ACGT").find(motif_it.first[pos])) {
continue;
}
sparse_hash_map<char, pair<string, Node *>> neighbor_motifs;
neighbor_motifs.reserve(4);
//on trouve les voisins du kmer par rapport à la position courante
const string neighbors_nuc = find_neighbor_motifs(motifs, neighbor_motifs, motif_it.first, pos);
if (neighbors_nuc.size() <= 1) {
continue;
}
//this is where things can explode if the string is not sorted alphabetically
auto iupacs = nucs_to_iupacs.find(neighbors_nuc);
assert(iupacs != nucs_to_iupacs.end());
//string that will be transformed into the degenerated motif later
string degenerated_motif(motif_it.first);
//TODO not required since lookup in a hashtable is O(1)
sparse_hash_map<char, Node *> iupac_to_node;
iupac_to_node.reserve(11);
// pour tous les iupacs dérivant des nucléotides
for (int degeneration_degree = 0; degeneration_degree < iupacs->second.size(); degeneration_degree++) {
for (auto const iupac : iupacs->second[degeneration_degree]) {
degenerated_motif.replace(pos, 1, 1, iupac);
Node *current_node_ptr;
//checks if the node has already been created
auto entry_ptr = degenerated_motifs.find(degenerated_motif);
if(entry_ptr != degenerated_motifs.end()) {
current_node_ptr = entry_ptr->second.second;
}
else {
//node creation
current_node_ptr = new Node(0, 0);
unsigned int degenerated_motif_positive_count = 0;
unsigned int degenerated_motif_negative_count = 0;
for (auto const &nuc : iupac_to_nucs[iupac]) {
//add child count
if (degenerated_motif_positive_count > ~0 - neighbor_motifs[nuc].second->get_positive_count()) {
std::cerr << "Error : an overflow occurred while setting the positive count of a degenerated motif. You should consider switching to a bigger unsigned type." << endl;
exit(EXIT_FAILURE);
}
degenerated_motif_positive_count += neighbor_motifs[nuc].second->get_positive_count();
if (degenerated_motif_negative_count > ~0 - neighbor_motifs[nuc].second->get_negative_count()) {
std::cerr << "Error : an overflow occurred while setting the negative count of a degenerated motif. You should consider switching to a bigger unsigned type." << endl;
exit(EXIT_FAILURE);
}
degenerated_motif_negative_count += neighbor_motifs[nuc].second->get_negative_count();
}
current_node_ptr->set_positive_count(degenerated_motif_positive_count);
current_node_ptr->set_negative_count(degenerated_motif_negative_count);
// current_node_ptr->set_motif(degenerated_motif);
degenerated_motifs.emplace(make_pair(degenerated_motif, make_pair(-1, current_node_ptr)));
if (rc) {
degenerated_motifs.emplace(make_pair(reverse_complement(degenerated_motif), make_pair(kmer_size, current_node_ptr)));
}
}
//remembering the node that we created to be able to find them easily
//TODO this is not required since lookup in a hash table is O(1)
iupac_to_node[iupac] = current_node_ptr;
//adding links between nodes
//here we create the nodes that depends on the nucleotides first,
//then we create the nodes that depends on the previous one, etc.
if (degeneration_degree == 0) {
for (char nuc : iupacs_dependencies[iupac]) {
// std::cout << degenerated_motif << "->" << neighbor_motifs[nuc].second->get_motif()<< ";" << endl;
current_node_ptr->add_successor(neighbor_motifs[nuc].second);
neighbor_motifs[nuc].second->add_predecessor(current_node_ptr);
}
} else {
for (char iupac_dependency : iupacs_dependencies[iupac]) {
// std::cout << degenerated_motif << "->" << iupac_to_node[iupac_dependency]->get_motif() << ";" << endl;
current_node_ptr->add_successor(iupac_to_node[iupac_dependency]);
iupac_to_node[iupac_dependency]->add_predecessor(current_node_ptr);
}
}
}
}
}
}
}
<commit_msg>[METHOD] Changed the way motif are degenerated : now degenerated motif are only created if each of their successors is present in either file (before we could find one successor in a file, and another successor in another file, that is now forbidden)<commit_after>#include "degenerate.hpp"
//retourne les nucléotides concaténés dans l'ordre (assuré par une itération sur le vecteur nucleotides)
const string find_neighbor_motifs( sparse_hash_map<string, pair<int, Node *>> &motifs,
sparse_hash_map<char, pair<string, Node *>> &neighbor_motifs,
const string &motif,
unsigned int pos) {
string neighbor_motif(motif);
string neighbors_nuc;
neighbors_nuc.reserve(4);
//pour tous les nucléotides
for (auto const &nuc : nucleotides) {
//on remplace la (pos)ième position du motif de base par ce nucléotide
neighbor_motif.replace(pos, 1, 1, nuc);
//on passe au suivant si le voisin n'est pas dans la table
auto const motif_it = motifs.find(neighbor_motif);
if(motif_it == motifs.end())
continue;
motif_it->second.first = pos;
//sinon, on insère dans la table des résultats le motif et son compte
neighbor_motifs[nuc] = make_pair(neighbor_motif, motifs[neighbor_motif].second);
neighbors_nuc.push_back(nuc);
}
return neighbors_nuc;
}
void degenerate(sparse_hash_map<string, pair<int, Node *>> &motifs,
sparse_hash_map<string, pair<int, Node *>> °enerated_motifs,
const unsigned int kmer_size,
bool rc) {
//pour chaque position
for (unsigned int pos = 0; pos < kmer_size; pos++) {
//pour chaque motif dans la table
for (auto const &motif_it : motifs) {
//s'il n'a pas été marqué pour cette position ou si la position a déjà été dégénérée
if((motif_it.second.first == pos) || (motif_it.second.first == kmer_size) || (!string("ACGT").find(motif_it.first[pos]))) {
continue;
}
sparse_hash_map<char, pair<string, Node *>> neighbor_motifs;
neighbor_motifs.reserve(4);
//on trouve les voisins du kmer par rapport à la position courante
const string neighbors_nuc = find_neighbor_motifs(motifs, neighbor_motifs, motif_it.first, pos);
if (neighbors_nuc.size() <= 1) {
continue;
}
//this is where things can explode if the string is not sorted alphabetically
auto iupacs = nucs_to_iupacs.find(neighbors_nuc);
assert(iupacs != nucs_to_iupacs.end());
//string that will be transformed into the degenerated motif later
string degenerated_motif(motif_it.first);
//TODO not required since lookup in a hashtable is O(1)
sparse_hash_map<char, Node *> iupac_to_node;
iupac_to_node.reserve(11);
// pour tous les iupacs dérivant des nucléotides
for (unsigned int degeneration_degree = 0; degeneration_degree < iupacs->second.size(); degeneration_degree++) {
for (auto const iupac : iupacs->second[degeneration_degree]) {
degenerated_motif.replace(pos, 1, 1, iupac);
Node *current_node_ptr;
//checks if the node has already been created
auto entry_ptr = degenerated_motifs.find(degenerated_motif);
if(entry_ptr != degenerated_motifs.end()) {
current_node_ptr = entry_ptr->second.second;
}
else {
//node creation
bool missing_successor_positive = false;
bool missing_successor_negative = false;
unsigned int degenerated_motif_positive_count = 0;
unsigned int degenerated_motif_negative_count = 0;
for (auto const &nuc : iupac_to_nucs[iupac]) {
unsigned int successor_positive_count = neighbor_motifs[nuc].second->get_positive_count();
unsigned int successor_negative_count = neighbor_motifs[nuc].second->get_negative_count();
//add positive successor count or raise flag
if (degenerated_motif_positive_count > ~0 - successor_positive_count) {
std::cerr << "Error : an overflow occurred while setting the positive count of a degenerated motif. You should consider switching to a bigger unsigned type." << endl;
exit(EXIT_FAILURE);
}
if (successor_positive_count == 0)
missing_successor_positive = true;
else
degenerated_motif_positive_count += successor_positive_count;
//add negative successor count or raise flag
if (degenerated_motif_negative_count > ~0 - successor_negative_count) {
std::cerr << "Error : an overflow occurred while setting the negative count of a degenerated motif. You should consider switching to a bigger unsigned type." << endl;
exit(EXIT_FAILURE);
}
if (successor_negative_count == 0)
missing_successor_negative = true;
else
degenerated_motif_negative_count += successor_negative_count;
}
//if a successor is missing in each datasets, then the motif should not be created
if (missing_successor_positive && missing_successor_negative)
continue;
current_node_ptr = new Node(degenerated_motif_positive_count, degenerated_motif_negative_count);
// current_node_ptr->set_motif(degenerated_motif);
degenerated_motifs.emplace(make_pair(degenerated_motif, make_pair(-1, current_node_ptr)));
if (rc) {
degenerated_motifs.emplace(make_pair(reverse_complement(degenerated_motif), make_pair(kmer_size, current_node_ptr)));
}
}
//remembering the node that we created to be able to find them easily
//TODO this is not required since lookup in a hash table is O(1)
iupac_to_node[iupac] = current_node_ptr;
//adding links between nodes
//here we create the nodes that depends on the nucleotides first,
//then we create the nodes that depends on the previous one, etc.
if (degeneration_degree == 0) {
for (char nuc : iupacs_dependencies[iupac]) {
current_node_ptr->add_successor(neighbor_motifs[nuc].second);
neighbor_motifs[nuc].second->add_predecessor(current_node_ptr);
}
} else {
for (char iupac_dependency : iupacs_dependencies[iupac]) {
if (iupac_to_node.find(iupac_dependency) == iupac_to_node.end()) {
std::cerr << "Tried to link a node to an non-existing one" << std::endl;
exit(EXIT_FAILURE);
}
current_node_ptr->add_successor(iupac_to_node[iupac_dependency]);
iupac_to_node[iupac_dependency]->add_predecessor(current_node_ptr);
}
}
}
}
}
}
}
<|endoftext|> |
<commit_before>#include "SUPPORT/generate2.h"
#include "SUPPORT/window.h"
#include "SUPPORT/geometricObject2.h"
#include "SUPPORT/delone10.h"
#include "SUPPORT/betaSet.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <list>
#include <mpi.h>
#include <string>
#include <chrono>
#define MASTER 0 /* task ID of master task */
typedef betaSet numberType;
typedef circle windowType;
int main (int argc, char* argv[])
{
// time measuring
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
int taskid;
int numtasks;
int nodeid;
int nodes;
int rc;
std::string buffer;
std::string send_buffer;
int length;
std::list<std::string> res;
std::list<std::string> data;
std::list<std::string>::iterator iterator;
MPI_Status status;
// initialize
numberType winSize(-10, 3, 2);
Cpoint<numberType> origin( numberType::get(0,0), numberType::get(0,0) );
windowType win( winSize );
win.center( origin );
// hyperquasicrystal
rhombus *circ = dynamic_cast<rhombus*> ( win.circumscribed() );
//rhombus *circ = new rhombus(winSize*betaSet::get(4,0,3));
// hypoquasicrystal
rhombus *insc = dynamic_cast<rhombus*> ( win.inscribed() );
//rhombus *insc = new rhombus(winSize*betaSet::get(2,0,3));
betaSet S = circ->Xwindow().Small();
betaSet L = insc->Xwindow().Large();
betaSet coveringR = numberType::get(161, -43)*L;
// size of rhumbus circumscribed to covering radius disc
betaSet lengthToCover = numberType::get(8, 0)*coveringR;
CvoronoiCell<numberType>::large = numberType::get(2, 0)*coveringR;
// find out the word length by testing
int wordLength = 1;
do
{
++wordLength;
} while ( minWord(language(circ->Xwindow(), wordLength), circ->Xwindow()) < lengthToCover );
//wordLength = 10;
/* Obtain number of tasks and task ID */
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&numtasks);
MPI_Comm_rank(MPI_COMM_WORLD,&taskid);
std::cout << std::string(4, ' ') << "MPI task " << taskid << " has started..." << std::endl;
nodes = numtasks-1;
nodeid = taskid-1;
if (taskid != MASTER) // NODE ----------------------------------------
{
do
{
MPI_Probe(MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_CHAR, &length);
char *cache = new char[length];
MPI_Recv(cache, length, MPI_CHAR, MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
buffer = std::string(cache, length);
delete [] cache;
//std::cout << std::string(4, ' ') << taskid << ": received " << buffer << " status: " << status.MPI_TAG << std::endl;
//std::cout << " node " << taskid << " data received" << std::endl;
if (status.MPI_TAG == 0)
{
// process data ------------------------------------------------
std::string word1 = buffer.substr(0, buffer.length()/2);
std::string word2 = buffer.substr(buffer.length()/2);
CdeloneSet10<numberType> delone = quasicrystal2D10(circ->Xwindow(), word1, word2);
delone.setPackingR();
delone.setCoveringR(numberType::get(2, 0)*coveringR);
delone.setDescription(word1+word2);
delone.sortPotentialByDistance();
delone.sortByDistance();
std::list<CdeloneSet10<numberType> > delones;
std::list<CvoronoiCell<numberType> > cells;
delones.push_back(delone);
for (std::list<CdeloneSet10<numberType> >::iterator it = delones.begin(); it != delones.end(); it = delones.begin())
{
std::cout << "SIZE POTENTIAL: " << it->sizePotential() << std::endl;
//it->filterPotentialByWindow(win);
CvoronoiCell<numberType> voronoi;
*(voronoi.CarrierSet) = *it;
voronoi.CarrierSet->sortByDistance();
voronoi.CarrierSet->setPackingR();
voronoi.CarrierSet->setCoveringR(CvoronoiCell<numberType>::large);
voronoi.setCenter(origin);
voronoi.construct();
voronoi.filterSet();
std::list<Cpoint<numberType> > potential;
potential = it->getPotential();
voronoi.filterSetPotential( &potential );
it->clearPotential();
it->addPotential(potential);
std::cout << "SIZE POTENTIAL: " << it->sizePotential() << '\t' << "SIZE DELONES: " << delones.size() << std::endl;
// deal with potential
while (it->isPotential())
{
Cpoint<numberType> cache = it->popPotential();
delone = *it;
delone << cache;
delones.push_back(delone);
}
cells.push_back( voronoi );
delones.erase(it);
delones.sort();
delones.unique();
//std::cout << " node " << taskid << " delones: " << delones.size() << std::endl;
}
cells.sort();
cells.unique();
std::list<std::string> list;
for (std::list<CvoronoiCell<numberType> >::iterator it = cells.begin(); it != cells.end(); ++it)
{
list.push_back(it->save());
}
list.sort();
list.unique();
// end ---------------------------------------------------------
std::cout << " node " << taskid << " sending back: " << list.size() << std::endl;
for (std::list<std::string>::iterator it = list.begin(); it != --list.end(); ++it)
{
send_buffer = *it;
// return result
MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, MASTER, 0, MPI_COMM_WORLD);
}
send_buffer = *list.rbegin();
// return result
MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, MASTER, 1, MPI_COMM_WORLD);
}
} while (status.MPI_TAG == 0);
}
else // MASTER -------------------------------------------------------
{
// create data -----------------------------------------------------
std::cout << "Load data" << std::endl;
std::list<std::string> lang = language( insc->Xwindow(), circ->Xwindow(), wordLength );
for ( std::list<std::string>::iterator it = lang.begin(); it != lang.end(); ++it )
{
for ( std::list<std::string>::iterator ot = lang.begin(); ot != lang.end(); ++ot )
{
data.push_back(*it+*ot);
}
}
std::string fillColor = "#689F38";
std::string strokeColor = "#263238";
std::ostringstream convert;
convert << (0.3)*winSize;
std::string strokeWidth = convert.str();
// OUTPUT
int count = 1;
for ( std::list<std::string>::iterator it = data.begin(); it != data.end(); ++it )
{
std::string word1 = it->substr(0, it->length()/2);
std::string word2 = it->substr(it->length()/2);
CdeloneSet10<numberType> delone = quasicrystal2D10(circ->Xwindow(), word1, word2);
delone.setPackingR();
delone.setCoveringR(numberType::get(2, 0)*coveringR);
delone.setDescription(word1+word2);
delone.sortPotentialByDistance();
delone.setColor(fillColor, strokeColor, strokeWidth);
CvoronoiCell<numberType> voronoi;
*(voronoi.CarrierSet) = delone;
voronoi.CarrierSet->sortByDistance();
voronoi.CarrierSet->setPackingR();
voronoi.CarrierSet->setCoveringR(CvoronoiCell<numberType>::large);
voronoi.setCenter(origin);
voronoi.construct();
voronoi.filterSet();
voronoi.setColor("#4FC3F7", "#FFFFFF", strokeWidth);
voronoi.CarrierSet->setColor("#4FC3F7", "#00695C", strokeWidth);
std::ostringstream oss;
oss << "outputTile" << '/' << "tile" << std::setfill('0') << std::setw(3) << count << ".svg";// << " " << it->size();
std::ofstream myfile ( oss.str().c_str() );
myfile << "<?xml version=\"1.0\" standalone=\"no\"?>\n" << std::endl;
myfile << "<svg width=\"1000\" height=\"1000\" viewBox=\"" << -30*8.4 << " " << -30*8.4 << " " << 60*8.4 << " " << 60*8.4 << "\">\n" << std::endl;
myfile << "<g transform=\"scale(10,-10)\">" << std::endl;
voronoi.svg(myfile);
//delone.svg(myfile);
std::list<Cpoint<numberType> > potential;
potential = delone.getPotential();
std::cout << potential.size() << " " << delone.sizePotential();
voronoi.filterSetPotential( &potential );
std::cout << " " << potential.size() << std::endl;
delone.clearPotential();
delone.addPotential(potential);
delone.setColor(fillColor, "#FF4081", strokeWidth);
delone.svg(myfile);
voronoi.CarrierSet->svg(myfile);
myfile << "</g>" << std::endl;
myfile << "</svg>";
myfile.close();
++count;
}
std::cout << "tasks: " << data.size() << std::endl;
std::cout << "word length: " << wordLength << std::endl;
iterator = data.begin();
// send initial load of data
std::cout << "Send initial load of data" << std::endl;
for (int it = 0; it < nodes; ++it)
{
send_buffer = *(iterator++);
//std::cout << std::string(4, ' ') << "MASTER sending: " << iterator << "/168" << std::endl;
MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, it+1, 0, MPI_COMM_WORLD);
}
// gather data while processing
std::cout << "distribute the rest on demand" << std::endl;
while (iterator != data.end())
{
std::cout << "waiting" << std::endl;
MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_CHAR, &length);
char *cache = new char[length];
MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
buffer = std::string(cache, length);
delete [] cache;
// save result
res.push_back(buffer);
std::cout << "finished: " << res.size() << std::endl;
while (status.MPI_TAG == 0)
{
MPI_Probe(status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_CHAR, &length);
char *cache = new char[length];
MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
buffer = std::string(cache, length);
delete [] cache;
// save result
res.push_back(buffer);
std::cout << "finished: " << res.size() << std::endl;
}
//std::cout << std::string(4, ' ') << "MASTER received from: " << status.MPI_SOURCE << " sending: " << iterator << std::endl;
send_buffer = *(iterator++);
MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, status.MPI_SOURCE, 0, MPI_COMM_WORLD);
}
// terminate processes
std::cout << "termination" << std::endl;
for (int it = 0; it < nodes; ++it)
{
MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_CHAR, &length);
char *cache = new char[length];
MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
buffer = std::string(cache, length);
delete [] cache;
// save result
res.push_back(buffer);
std::cout << "finished: " << res.size() << std::endl;
//std::cout << std::string(4, ' ') << "MASTER received from: " << status.MPI_SOURCE << " - " << buffer << std::endl;
send_buffer = std::to_string(0);
rc = MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, it+1, 1, MPI_COMM_WORLD);
}
// write to file
std::ofstream output(argv[1]);
res.sort();
res.unique();
for (std::list<std::string>::iterator it = res.begin(); it != res.end(); ++it)
{
output << *it << std::endl;
}
output.close();
}
std::cout << std::string(4, ' ') << "... MPI task " << taskid << " is closing" << std::endl;
MPI_Finalize();
// time measuring
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << "microseconds: " << duration << " (" << std::round(duration/100000.0)/10.0 << "s)" << std::endl;
return 0;
}
<commit_msg>removed picture output from MPI implementation<commit_after>#include "SUPPORT/generate2.h"
#include "SUPPORT/window.h"
#include "SUPPORT/geometricObject2.h"
#include "SUPPORT/delone10.h"
#include "SUPPORT/betaSet.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <list>
#include <mpi.h>
#include <string>
#include <chrono>
#define MASTER 0 /* task ID of master task */
typedef betaSet numberType;
typedef circle windowType;
int main (int argc, char* argv[])
{
// time measuring
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
int taskid;
int numtasks;
int nodeid;
int nodes;
int rc;
std::string buffer;
std::string send_buffer;
int length;
std::list<std::string> res;
std::list<std::string> data;
std::list<std::string>::iterator iterator;
MPI_Status status;
// initialize
numberType winSize(-10, 3, 2);
Cpoint<numberType> origin( numberType::get(0,0), numberType::get(0,0) );
windowType win( winSize );
win.center( origin );
// hyperquasicrystal
rhombus *circ = dynamic_cast<rhombus*> ( win.circumscribed() );
//rhombus *circ = new rhombus(winSize*betaSet::get(4,0,3));
// hypoquasicrystal
rhombus *insc = dynamic_cast<rhombus*> ( win.inscribed() );
//rhombus *insc = new rhombus(winSize*betaSet::get(2,0,3));
betaSet S = circ->Xwindow().Small();
betaSet L = insc->Xwindow().Large();
betaSet coveringR = numberType::get(161, -43)*L;
// size of rhumbus circumscribed to covering radius disc
betaSet lengthToCover = numberType::get(8, 0)*coveringR;
CvoronoiCell<numberType>::large = numberType::get(2, 0)*coveringR;
// find out the word length by testing
int wordLength = 1;
do
{
++wordLength;
} while ( minWord(language(circ->Xwindow(), wordLength), circ->Xwindow()) < lengthToCover );
//wordLength = 10;
/* Obtain number of tasks and task ID */
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&numtasks);
MPI_Comm_rank(MPI_COMM_WORLD,&taskid);
std::cout << std::string(4, ' ') << "MPI task " << taskid << " has started..." << std::endl;
nodes = numtasks-1;
nodeid = taskid-1;
if (taskid != MASTER) // NODE ----------------------------------------
{
do
{
MPI_Probe(MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_CHAR, &length);
char *cache = new char[length];
MPI_Recv(cache, length, MPI_CHAR, MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
buffer = std::string(cache, length);
delete [] cache;
//std::cout << std::string(4, ' ') << taskid << ": received " << buffer << " status: " << status.MPI_TAG << std::endl;
//std::cout << " node " << taskid << " data received" << std::endl;
if (status.MPI_TAG == 0)
{
// process data ------------------------------------------------
std::string word1 = buffer.substr(0, buffer.length()/2);
std::string word2 = buffer.substr(buffer.length()/2);
CdeloneSet10<numberType> delone = quasicrystal2D10(circ->Xwindow(), word1, word2);
delone.setPackingR();
delone.setCoveringR(numberType::get(2, 0)*coveringR);
delone.setDescription(word1+word2);
delone.sortPotentialByDistance();
delone.sortByDistance();
std::list<CdeloneSet10<numberType> > delones;
std::list<CvoronoiCell<numberType> > cells;
delones.push_back(delone);
for (std::list<CdeloneSet10<numberType> >::iterator it = delones.begin(); it != delones.end(); it = delones.begin())
{
std::cout << "SIZE POTENTIAL: " << it->sizePotential() << std::endl;
//it->filterPotentialByWindow(win);
CvoronoiCell<numberType> voronoi;
*(voronoi.CarrierSet) = *it;
voronoi.CarrierSet->sortByDistance();
voronoi.CarrierSet->setPackingR();
voronoi.CarrierSet->setCoveringR(CvoronoiCell<numberType>::large);
voronoi.setCenter(origin);
voronoi.construct();
voronoi.filterSet();
std::list<Cpoint<numberType> > potential;
potential = it->getPotential();
voronoi.filterSetPotential( &potential );
it->clearPotential();
it->addPotential(potential);
std::cout << "SIZE POTENTIAL: " << it->sizePotential() << '\t' << "SIZE DELONES: " << delones.size() << std::endl;
// deal with potential
while (it->isPotential())
{
Cpoint<numberType> cache = it->popPotential();
delone = *it;
delone << cache;
delones.push_back(delone);
}
cells.push_back( voronoi );
delones.erase(it);
delones.sort();
delones.unique();
//std::cout << " node " << taskid << " delones: " << delones.size() << std::endl;
}
cells.sort();
cells.unique();
std::list<std::string> list;
for (std::list<CvoronoiCell<numberType> >::iterator it = cells.begin(); it != cells.end(); ++it)
{
list.push_back(it->save());
}
list.sort();
list.unique();
// end ---------------------------------------------------------
std::cout << " node " << taskid << " sending back: " << list.size() << std::endl;
for (std::list<std::string>::iterator it = list.begin(); it != --list.end(); ++it)
{
send_buffer = *it;
// return result
MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, MASTER, 0, MPI_COMM_WORLD);
}
send_buffer = *list.rbegin();
// return result
MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, MASTER, 1, MPI_COMM_WORLD);
}
} while (status.MPI_TAG == 0);
}
else // MASTER -------------------------------------------------------
{
// create data -----------------------------------------------------
std::cout << "Load data" << std::endl;
std::list<std::string> lang = language( insc->Xwindow(), circ->Xwindow(), wordLength );
for ( std::list<std::string>::iterator it = lang.begin(); it != lang.end(); ++it )
{
for ( std::list<std::string>::iterator ot = lang.begin(); ot != lang.end(); ++ot )
{
data.push_back(*it+*ot);
}
}
std::cout << "tasks: " << data.size() << std::endl;
std::cout << "word length: " << wordLength << std::endl;
iterator = data.begin();
// send initial load of data
std::cout << "Send initial load of data" << std::endl;
for (int it = 0; it < nodes; ++it)
{
send_buffer = *(iterator++);
//std::cout << std::string(4, ' ') << "MASTER sending: " << iterator << "/168" << std::endl;
MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, it+1, 0, MPI_COMM_WORLD);
}
// gather data while processing
std::cout << "distribute the rest on demand" << std::endl;
while (iterator != data.end())
{
std::cout << "waiting" << std::endl;
MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_CHAR, &length);
char *cache = new char[length];
MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
buffer = std::string(cache, length);
delete [] cache;
// save result
res.push_back(buffer);
std::cout << "finished: " << res.size() << std::endl;
while (status.MPI_TAG == 0)
{
MPI_Probe(status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_CHAR, &length);
char *cache = new char[length];
MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
buffer = std::string(cache, length);
delete [] cache;
// save result
res.push_back(buffer);
std::cout << "finished: " << res.size() << std::endl;
}
//std::cout << std::string(4, ' ') << "MASTER received from: " << status.MPI_SOURCE << " sending: " << iterator << std::endl;
send_buffer = *(iterator++);
MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, status.MPI_SOURCE, 0, MPI_COMM_WORLD);
}
// terminate processes
std::cout << "termination" << std::endl;
for (int it = 0; it < nodes; ++it)
{
MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_CHAR, &length);
char *cache = new char[length];
MPI_Recv(cache, length, MPI_CHAR, status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
buffer = std::string(cache, length);
delete [] cache;
// save result
res.push_back(buffer);
std::cout << "finished: " << res.size() << std::endl;
//std::cout << std::string(4, ' ') << "MASTER received from: " << status.MPI_SOURCE << " - " << buffer << std::endl;
send_buffer = std::to_string(0);
rc = MPI_Send(send_buffer.c_str(), send_buffer.length(), MPI_CHAR, it+1, 1, MPI_COMM_WORLD);
}
// write to file
std::ofstream output(argv[1]);
res.sort();
res.unique();
for (std::list<std::string>::iterator it = res.begin(); it != res.end(); ++it)
{
output << *it << std::endl;
}
output.close();
}
std::cout << std::string(4, ' ') << "... MPI task " << taskid << " is closing" << std::endl;
MPI_Finalize();
// time measuring
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << "microseconds: " << duration << " (" << std::round(duration/100000.0)/10.0 << "s)" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>//===-- AppleObjCRuntime.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AppleObjCRuntime.h"
#include "AppleObjCTrampolineHandler.h"
#include "llvm/Support/MachO.h"
#include "clang/AST/Type.h"
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/ConstString.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Scalar.h"
#include "lldb/Core/Section.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Expression/ClangFunction.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include <vector>
using namespace lldb;
using namespace lldb_private;
bool
AppleObjCRuntime::GetObjectDescription (Stream &str, ValueObject &valobj)
{
bool is_signed;
// ObjC objects can only be pointers, but we extend this to integer types because an expression might just
// result in an address, and we should try that to see if the address is an ObjC object.
if (!(valobj.IsPointerType() || valobj.IsIntegerType(is_signed)))
return NULL;
// Make the argument list: we pass one arg, the address of our pointer, to the print function.
Value val;
if (!valobj.ResolveValue(val.GetScalar()))
return NULL;
ExecutionContext exe_ctx (valobj.GetExecutionContextRef());
return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope());
}
bool
AppleObjCRuntime::GetObjectDescription (Stream &strm, Value &value, ExecutionContextScope *exe_scope)
{
if (!m_read_objc_library)
return false;
ExecutionContext exe_ctx;
exe_scope->CalculateExecutionContext(exe_ctx);
Process *process = exe_ctx.GetProcessPtr();
if (!process)
return false;
// We need other parts of the exe_ctx, but the processes have to match.
assert (m_process == process);
// Get the function address for the print function.
const Address *function_address = GetPrintForDebuggerAddr();
if (!function_address)
return false;
Target *target = exe_ctx.GetTargetPtr();
if (value.GetClangType())
{
clang::QualType value_type = clang::QualType::getFromOpaquePtr (value.GetClangType());
if (!value_type->isObjCObjectPointerType())
{
strm.Printf ("Value doesn't point to an ObjC object.\n");
return false;
}
}
else
{
// If it is not a pointer, see if we can make it into a pointer.
ClangASTContext *ast_context = target->GetScratchClangASTContext();
void *opaque_type_ptr = ast_context->GetBuiltInType_objc_id();
if (opaque_type_ptr == NULL)
opaque_type_ptr = ast_context->GetVoidPtrType(false);
value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);
}
ValueList arg_value_list;
arg_value_list.PushValue(value);
// This is the return value:
ClangASTContext *ast_context = target->GetScratchClangASTContext();
void *return_qualtype = ast_context->GetCStringType(true);
Value ret;
ret.SetContext(Value::eContextTypeClangType, return_qualtype);
if (exe_ctx.GetFramePtr() == NULL)
{
Thread *thread = exe_ctx.GetThreadPtr();
if (thread == NULL)
{
exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread());
thread = exe_ctx.GetThreadPtr();
}
if (thread)
{
exe_ctx.SetFrameSP(thread->GetSelectedFrame());
}
}
// Now we're ready to call the function:
ClangFunction func (*exe_ctx.GetBestExecutionContextScope(),
ast_context,
return_qualtype,
*function_address,
arg_value_list);
StreamString error_stream;
lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
func.InsertFunction(exe_ctx, wrapper_struct_addr, error_stream);
bool unwind_on_error = true;
bool try_all_threads = true;
bool stop_others = true;
ExecutionResults results = func.ExecuteFunction (exe_ctx,
&wrapper_struct_addr,
error_stream,
stop_others,
1000000,
try_all_threads,
unwind_on_error,
ret);
if (results != eExecutionCompleted)
{
strm.Printf("Error evaluating Print Object function: %d.\n", results);
return false;
}
addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
char buf[512];
size_t cstr_len = 0;
size_t full_buffer_len = sizeof (buf) - 1;
size_t curr_len = full_buffer_len;
while (curr_len == full_buffer_len)
{
Error error;
curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf, sizeof(buf), error);
strm.Write (buf, curr_len);
cstr_len += curr_len;
}
return cstr_len > 0;
}
Address *
AppleObjCRuntime::GetPrintForDebuggerAddr()
{
if (!m_PrintForDebugger_addr.get())
{
ModuleList &modules = m_process->GetTarget().GetImages();
SymbolContextList contexts;
SymbolContext context;
if ((!modules.FindSymbolsWithNameAndType(ConstString ("_NSPrintForDebugger"), eSymbolTypeCode, contexts)) &&
(!modules.FindSymbolsWithNameAndType(ConstString ("_CFPrintForDebugger"), eSymbolTypeCode, contexts)))
return NULL;
contexts.GetContextAtIndex(0, context);
m_PrintForDebugger_addr.reset(new Address(context.symbol->GetAddress()));
}
return m_PrintForDebugger_addr.get();
}
bool
AppleObjCRuntime::CouldHaveDynamicValue (ValueObject &in_value)
{
lldb::LanguageType known_type = in_value.GetObjectRuntimeLanguage();
if (known_type == lldb::eLanguageTypeObjC)
return in_value.IsPossibleDynamicType ();
else
return in_value.IsPointerType();
}
bool
AppleObjCRuntime::GetDynamicTypeAndAddress (ValueObject &in_value,
lldb::DynamicValueType use_dynamic,
TypeAndOrName &class_type_or_name,
Address &address)
{
return false;
}
bool
AppleObjCRuntime::AppleIsModuleObjCLibrary (const ModuleSP &module_sp)
{
const FileSpec &module_file_spec = module_sp->GetFileSpec();
static ConstString ObjCName ("libobjc.A.dylib");
if (module_file_spec)
{
if (module_file_spec.GetFilename() == ObjCName)
return true;
}
return false;
}
bool
AppleObjCRuntime::IsModuleObjCLibrary (const ModuleSP &module_sp)
{
return AppleIsModuleObjCLibrary(module_sp);
}
bool
AppleObjCRuntime::ReadObjCLibrary (const ModuleSP &module_sp)
{
// Maybe check here and if we have a handler already, and the UUID of this module is the same as the one in the
// current module, then we don't have to reread it?
m_objc_trampoline_handler_ap.reset(new AppleObjCTrampolineHandler (m_process->shared_from_this(), module_sp));
if (m_objc_trampoline_handler_ap.get() != NULL)
{
m_read_objc_library = true;
return true;
}
else
return false;
}
ThreadPlanSP
AppleObjCRuntime::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
{
ThreadPlanSP thread_plan_sp;
if (m_objc_trampoline_handler_ap.get())
thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan (thread, stop_others);
return thread_plan_sp;
}
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
enum ObjCRuntimeVersions
AppleObjCRuntime::GetObjCVersion (Process *process, ModuleSP &objc_module_sp)
{
ModuleList &images = process->GetTarget().GetImages();
size_t num_images = images.GetSize();
for (size_t i = 0; i < num_images; i++)
{
ModuleSP module_sp = images.GetModuleAtIndex(i);
if (AppleIsModuleObjCLibrary (module_sp))
{
objc_module_sp = module_sp;
ObjectFile *ofile = module_sp->GetObjectFile();
if (!ofile)
return eObjC_VersionUnknown;
SectionList *sections = ofile->GetSectionList();
if (!sections)
return eObjC_VersionUnknown;
SectionSP v1_telltale_section_sp = sections->FindSectionByName(ConstString ("__OBJC"));
if (v1_telltale_section_sp)
{
return eAppleObjC_V1;
}
return eAppleObjC_V2;
}
}
return eObjC_VersionUnknown;
}
void
AppleObjCRuntime::SetExceptionBreakpoints ()
{
const bool catch_bp = false;
const bool throw_bp = true;
const bool is_internal = true;
if (!m_objc_exception_bp_sp)
m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint (m_process->GetTarget(),
GetLanguageType(),
catch_bp,
throw_bp,
is_internal);
else
m_objc_exception_bp_sp->SetEnabled(true);
}
void
AppleObjCRuntime::ClearExceptionBreakpoints ()
{
if (!m_process)
return;
if (m_objc_exception_bp_sp.get())
{
m_objc_exception_bp_sp->SetEnabled (false);
}
}
bool
AppleObjCRuntime::ExceptionBreakpointsExplainStop (lldb::StopInfoSP stop_reason)
{
if (!m_process)
return false;
if (!stop_reason ||
stop_reason->GetStopReason() != eStopReasonBreakpoint)
return false;
uint64_t break_site_id = stop_reason->GetValue();
return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint (break_site_id,
m_objc_exception_bp_sp->GetID());
}
bool
AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing()
{
if (!m_process)
return false;
Target &target(m_process->GetTarget());
static ConstString s_method_signature("-[NSDictionary objectForKeyedSubscript:]");
SymbolContextList sc_list;
if (target.GetImages().FindSymbolsWithNameAndType(s_method_signature, eSymbolTypeCode, sc_list))
return true;
else
return false;
}
<commit_msg>Handle the case where we get called to determine the ObjC runtime version BEFORE the loader code has winnowed all the unloaded libraries from the process module list. <rdar://problem/11015223><commit_after>//===-- AppleObjCRuntime.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AppleObjCRuntime.h"
#include "AppleObjCTrampolineHandler.h"
#include "llvm/Support/MachO.h"
#include "clang/AST/Type.h"
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Core/ConstString.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Scalar.h"
#include "lldb/Core/Section.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Expression/ClangFunction.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include <vector>
using namespace lldb;
using namespace lldb_private;
bool
AppleObjCRuntime::GetObjectDescription (Stream &str, ValueObject &valobj)
{
bool is_signed;
// ObjC objects can only be pointers, but we extend this to integer types because an expression might just
// result in an address, and we should try that to see if the address is an ObjC object.
if (!(valobj.IsPointerType() || valobj.IsIntegerType(is_signed)))
return NULL;
// Make the argument list: we pass one arg, the address of our pointer, to the print function.
Value val;
if (!valobj.ResolveValue(val.GetScalar()))
return NULL;
ExecutionContext exe_ctx (valobj.GetExecutionContextRef());
return GetObjectDescription(str, val, exe_ctx.GetBestExecutionContextScope());
}
bool
AppleObjCRuntime::GetObjectDescription (Stream &strm, Value &value, ExecutionContextScope *exe_scope)
{
if (!m_read_objc_library)
return false;
ExecutionContext exe_ctx;
exe_scope->CalculateExecutionContext(exe_ctx);
Process *process = exe_ctx.GetProcessPtr();
if (!process)
return false;
// We need other parts of the exe_ctx, but the processes have to match.
assert (m_process == process);
// Get the function address for the print function.
const Address *function_address = GetPrintForDebuggerAddr();
if (!function_address)
return false;
Target *target = exe_ctx.GetTargetPtr();
if (value.GetClangType())
{
clang::QualType value_type = clang::QualType::getFromOpaquePtr (value.GetClangType());
if (!value_type->isObjCObjectPointerType())
{
strm.Printf ("Value doesn't point to an ObjC object.\n");
return false;
}
}
else
{
// If it is not a pointer, see if we can make it into a pointer.
ClangASTContext *ast_context = target->GetScratchClangASTContext();
void *opaque_type_ptr = ast_context->GetBuiltInType_objc_id();
if (opaque_type_ptr == NULL)
opaque_type_ptr = ast_context->GetVoidPtrType(false);
value.SetContext(Value::eContextTypeClangType, opaque_type_ptr);
}
ValueList arg_value_list;
arg_value_list.PushValue(value);
// This is the return value:
ClangASTContext *ast_context = target->GetScratchClangASTContext();
void *return_qualtype = ast_context->GetCStringType(true);
Value ret;
ret.SetContext(Value::eContextTypeClangType, return_qualtype);
if (exe_ctx.GetFramePtr() == NULL)
{
Thread *thread = exe_ctx.GetThreadPtr();
if (thread == NULL)
{
exe_ctx.SetThreadSP(process->GetThreadList().GetSelectedThread());
thread = exe_ctx.GetThreadPtr();
}
if (thread)
{
exe_ctx.SetFrameSP(thread->GetSelectedFrame());
}
}
// Now we're ready to call the function:
ClangFunction func (*exe_ctx.GetBestExecutionContextScope(),
ast_context,
return_qualtype,
*function_address,
arg_value_list);
StreamString error_stream;
lldb::addr_t wrapper_struct_addr = LLDB_INVALID_ADDRESS;
func.InsertFunction(exe_ctx, wrapper_struct_addr, error_stream);
bool unwind_on_error = true;
bool try_all_threads = true;
bool stop_others = true;
ExecutionResults results = func.ExecuteFunction (exe_ctx,
&wrapper_struct_addr,
error_stream,
stop_others,
1000000,
try_all_threads,
unwind_on_error,
ret);
if (results != eExecutionCompleted)
{
strm.Printf("Error evaluating Print Object function: %d.\n", results);
return false;
}
addr_t result_ptr = ret.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
char buf[512];
size_t cstr_len = 0;
size_t full_buffer_len = sizeof (buf) - 1;
size_t curr_len = full_buffer_len;
while (curr_len == full_buffer_len)
{
Error error;
curr_len = process->ReadCStringFromMemory(result_ptr + cstr_len, buf, sizeof(buf), error);
strm.Write (buf, curr_len);
cstr_len += curr_len;
}
return cstr_len > 0;
}
Address *
AppleObjCRuntime::GetPrintForDebuggerAddr()
{
if (!m_PrintForDebugger_addr.get())
{
ModuleList &modules = m_process->GetTarget().GetImages();
SymbolContextList contexts;
SymbolContext context;
if ((!modules.FindSymbolsWithNameAndType(ConstString ("_NSPrintForDebugger"), eSymbolTypeCode, contexts)) &&
(!modules.FindSymbolsWithNameAndType(ConstString ("_CFPrintForDebugger"), eSymbolTypeCode, contexts)))
return NULL;
contexts.GetContextAtIndex(0, context);
m_PrintForDebugger_addr.reset(new Address(context.symbol->GetAddress()));
}
return m_PrintForDebugger_addr.get();
}
bool
AppleObjCRuntime::CouldHaveDynamicValue (ValueObject &in_value)
{
lldb::LanguageType known_type = in_value.GetObjectRuntimeLanguage();
if (known_type == lldb::eLanguageTypeObjC)
return in_value.IsPossibleDynamicType ();
else
return in_value.IsPointerType();
}
bool
AppleObjCRuntime::GetDynamicTypeAndAddress (ValueObject &in_value,
lldb::DynamicValueType use_dynamic,
TypeAndOrName &class_type_or_name,
Address &address)
{
return false;
}
bool
AppleObjCRuntime::AppleIsModuleObjCLibrary (const ModuleSP &module_sp)
{
const FileSpec &module_file_spec = module_sp->GetFileSpec();
static ConstString ObjCName ("libobjc.A.dylib");
if (module_file_spec)
{
if (module_file_spec.GetFilename() == ObjCName)
return true;
}
return false;
}
bool
AppleObjCRuntime::IsModuleObjCLibrary (const ModuleSP &module_sp)
{
return AppleIsModuleObjCLibrary(module_sp);
}
bool
AppleObjCRuntime::ReadObjCLibrary (const ModuleSP &module_sp)
{
// Maybe check here and if we have a handler already, and the UUID of this module is the same as the one in the
// current module, then we don't have to reread it?
m_objc_trampoline_handler_ap.reset(new AppleObjCTrampolineHandler (m_process->shared_from_this(), module_sp));
if (m_objc_trampoline_handler_ap.get() != NULL)
{
m_read_objc_library = true;
return true;
}
else
return false;
}
ThreadPlanSP
AppleObjCRuntime::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
{
ThreadPlanSP thread_plan_sp;
if (m_objc_trampoline_handler_ap.get())
thread_plan_sp = m_objc_trampoline_handler_ap->GetStepThroughDispatchPlan (thread, stop_others);
return thread_plan_sp;
}
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
enum ObjCRuntimeVersions
AppleObjCRuntime::GetObjCVersion (Process *process, ModuleSP &objc_module_sp)
{
if (!process)
return eObjC_VersionUnknown;
Target &target = process->GetTarget();
ModuleList &images = target.GetImages();
size_t num_images = images.GetSize();
for (size_t i = 0; i < num_images; i++)
{
ModuleSP module_sp = images.GetModuleAtIndex(i);
// One tricky bit here is that we might get called as part of the initial module loading, but
// before all the pre-run libraries get winnowed from the module list. So there might actually
// be an old and incorrect ObjC library sitting around in the list, and we don't want to look at that.
// That's why we call IsLoadedInTarget.
if (AppleIsModuleObjCLibrary (module_sp) && module_sp->IsLoadedInTarget(&target))
{
objc_module_sp = module_sp;
ObjectFile *ofile = module_sp->GetObjectFile();
if (!ofile)
return eObjC_VersionUnknown;
SectionList *sections = ofile->GetSectionList();
if (!sections)
return eObjC_VersionUnknown;
SectionSP v1_telltale_section_sp = sections->FindSectionByName(ConstString ("__OBJC"));
if (v1_telltale_section_sp)
{
return eAppleObjC_V1;
}
return eAppleObjC_V2;
}
}
return eObjC_VersionUnknown;
}
void
AppleObjCRuntime::SetExceptionBreakpoints ()
{
const bool catch_bp = false;
const bool throw_bp = true;
const bool is_internal = true;
if (!m_objc_exception_bp_sp)
m_objc_exception_bp_sp = LanguageRuntime::CreateExceptionBreakpoint (m_process->GetTarget(),
GetLanguageType(),
catch_bp,
throw_bp,
is_internal);
else
m_objc_exception_bp_sp->SetEnabled(true);
}
void
AppleObjCRuntime::ClearExceptionBreakpoints ()
{
if (!m_process)
return;
if (m_objc_exception_bp_sp.get())
{
m_objc_exception_bp_sp->SetEnabled (false);
}
}
bool
AppleObjCRuntime::ExceptionBreakpointsExplainStop (lldb::StopInfoSP stop_reason)
{
if (!m_process)
return false;
if (!stop_reason ||
stop_reason->GetStopReason() != eStopReasonBreakpoint)
return false;
uint64_t break_site_id = stop_reason->GetValue();
return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint (break_site_id,
m_objc_exception_bp_sp->GetID());
}
bool
AppleObjCRuntime::CalculateHasNewLiteralsAndIndexing()
{
if (!m_process)
return false;
Target &target(m_process->GetTarget());
static ConstString s_method_signature("-[NSDictionary objectForKeyedSubscript:]");
SymbolContextList sc_list;
if (target.GetImages().FindSymbolsWithNameAndType(s_method_signature, eSymbolTypeCode, sc_list))
return true;
else
return false;
}
<|endoftext|> |
<commit_before>#include "Globals.h"
#include "Application.h"
#include "ModuleFileSystem.h"
#include "PhysFS/include/physfs.h"
#include "SDL/include/SDL.h"
#include "JSON/parson.h"
#pragma comment( lib, "PhysFS/libx86/physfs.lib" )
ModuleFileSystem::ModuleFileSystem(Application* app, bool start_enabled) : Module(app, start_enabled)
{
// need to be created before Awake so other modules can use it
char* base_path = SDL_GetBasePath();
PHYSFS_init(base_path);
SDL_free(base_path);
}
// Destructor
ModuleFileSystem::~ModuleFileSystem()
{
PHYSFS_deinit();
}
// Called before render is available
bool ModuleFileSystem::Init()
{
MYLOG("Loading File System");
bool ret = true;
PHYSFS_setWriteDir(".");
return ret;
}
void ModuleFileSystem::AddImGui()
{
}
// Called before quitting
bool ModuleFileSystem::CleanUp()
{
//LOG("Freeing File System subsystem");
return true;
}
// Add a new zip file or folder
bool ModuleFileSystem::AddPath(const char* path_or_zip, const char* mount_point)
{
bool ret = false;
if (PHYSFS_mount(path_or_zip, mount_point, 1) == 0)
{
MYLOG("File System error while adding a path or zip(%s): %s\n", path_or_zip, PHYSFS_getLastError());
}
else
ret = true;
return ret;
}
// Check if a file exists
bool ModuleFileSystem::Exists(const char* file) const
{
return PHYSFS_exists(file) != 0;
}
// Check if a file is a directory
bool ModuleFileSystem::IsDirectory(const char* file) const
{
return PHYSFS_isDirectory(file) != 0;
}
std::vector<std::string> ModuleFileSystem::GetFolderContent(char * path)
{
std::vector<std::string> ret;
// Convert char** to vector<string>
PHYSFS_enumerateFiles(path);
return ret;
}
// Read a whole file and put it in a new buffer
unsigned int ModuleFileSystem::Load(const char* file, char** buffer) const
{
unsigned int ret = 0;
PHYSFS_file* fs_file = PHYSFS_openRead(file);
if (fs_file != NULL)
{
PHYSFS_sint64 size = PHYSFS_fileLength(fs_file);
if (size > 0)
{
*buffer = new char[(uint)size];
PHYSFS_sint64 readed = PHYSFS_read(fs_file, *buffer, 1, (PHYSFS_sint32)size);
if (readed != size)
{
MYLOG("File System error while reading from file %s: %s\n", file, PHYSFS_getLastError());
delete (buffer);
}
else
ret = (uint)readed;
}
if (PHYSFS_close(fs_file) == 0)
MYLOG("File System error while closing file %s: %s\n", file, PHYSFS_getLastError());
}
else
MYLOG("File System error while opening file %s: %s\n", file, PHYSFS_getLastError());
return ret;
}
// Read a whole file and put it in a new buffer
SDL_RWops* ModuleFileSystem::Load(const char* file) const
{
char* buffer;
int size = Load(file, &buffer);
if (size > 0)
{
SDL_RWops* r = SDL_RWFromConstMem(buffer, size);
if (r != NULL)
r->close = close_sdl_rwops;
return r;
}
else
return NULL;
}
int close_sdl_rwops(SDL_RWops *rw)
{
delete (rw->hidden.mem.base);
SDL_FreeRW(rw);
return 0;
}
// Save a whole buffer to disk
unsigned int ModuleFileSystem::Save(const char* file, const char* buffer, unsigned int size) const
{
unsigned int ret = 0;
PHYSFS_file* fs_file = PHYSFS_openWrite(file);
if (fs_file != NULL)
{
PHYSFS_sint64 written = PHYSFS_write(fs_file, (const void*)buffer, 1, size);
if (written != size)
{
MYLOG("File System error while writing to file %s: %s\n", file, PHYSFS_getLastError());
}
else
ret = (uint)written;
if (PHYSFS_close(fs_file) == 0)
MYLOG("File System error while closing file %s: %s\n", file, PHYSFS_getLastError());
}
else
MYLOG("File System error while opening file %s: %s\n", file, PHYSFS_getLastError());
return ret;
}<commit_msg>EnumerateFiles not working YET<commit_after>#include "Globals.h"
#include "Application.h"
#include "ModuleFileSystem.h"
#include "PhysFS/include/physfs.h"
#include "SDL/include/SDL.h"
#include "JSON/parson.h"
#pragma comment( lib, "PhysFS/libx86/physfs.lib" )
ModuleFileSystem::ModuleFileSystem(Application* app, bool start_enabled) : Module(app, start_enabled)
{
// need to be created before Awake so other modules can use it
char* base_path = SDL_GetBasePath();
PHYSFS_init(base_path);
SDL_free(base_path);
}
// Destructor
ModuleFileSystem::~ModuleFileSystem()
{
PHYSFS_deinit();
}
// Called before render is available
bool ModuleFileSystem::Init()
{
MYLOG("Loading File System");
bool ret = true;
PHYSFS_setWriteDir(".");
return ret;
}
void ModuleFileSystem::AddImGui()
{
}
// Called before quitting
bool ModuleFileSystem::CleanUp()
{
//LOG("Freeing File System subsystem");
return true;
}
// Add a new zip file or folder
bool ModuleFileSystem::AddPath(const char* path_or_zip, const char* mount_point)
{
bool ret = false;
if (PHYSFS_mount(path_or_zip, mount_point, 1) == 0)
{
MYLOG("File System error while adding a path or zip(%s): %s\n", path_or_zip, PHYSFS_getLastError());
}
else
ret = true;
return ret;
}
// Check if a file exists
bool ModuleFileSystem::Exists(const char* file) const
{
return PHYSFS_exists(file) != 0;
}
// Check if a file is a directory
bool ModuleFileSystem::IsDirectory(const char* file) const
{
return PHYSFS_isDirectory(file) != 0;
}
std::vector<std::string> ModuleFileSystem::GetFolderContent(char * path)
{
std::vector<std::string> ret;
// Convert char** to vector<string>
char **files = PHYSFS_enumerateFiles(path);
if (*files == NULL)
printf("Failure. Reason: %s.\n", PHYSFS_getLastError());
for (char* i = *files; i != NULL; i=*++files)
{
for (std::vector<std::string>::iterator it = ret.begin();; it++)
{
*it = i;
}
}
PHYSFS_freeList(files);
return ret;
}
// Read a whole file and put it in a new buffer
unsigned int ModuleFileSystem::Load(const char* file, char** buffer) const
{
unsigned int ret = 0;
PHYSFS_file* fs_file = PHYSFS_openRead(file);
if (fs_file != NULL)
{
PHYSFS_sint64 size = PHYSFS_fileLength(fs_file);
if (size > 0)
{
*buffer = new char[(uint)size];
PHYSFS_sint64 readed = PHYSFS_read(fs_file, *buffer, 1, (PHYSFS_sint32)size);
if (readed != size)
{
MYLOG("File System error while reading from file %s: %s\n", file, PHYSFS_getLastError());
delete (buffer);
}
else
ret = (uint)readed;
}
if (PHYSFS_close(fs_file) == 0)
MYLOG("File System error while closing file %s: %s\n", file, PHYSFS_getLastError());
}
else
MYLOG("File System error while opening file %s: %s\n", file, PHYSFS_getLastError());
return ret;
}
// Read a whole file and put it in a new buffer
SDL_RWops* ModuleFileSystem::Load(const char* file) const
{
char* buffer;
int size = Load(file, &buffer);
if (size > 0)
{
SDL_RWops* r = SDL_RWFromConstMem(buffer, size);
if (r != NULL)
r->close = close_sdl_rwops;
return r;
}
else
return NULL;
}
int close_sdl_rwops(SDL_RWops *rw)
{
delete (rw->hidden.mem.base);
SDL_FreeRW(rw);
return 0;
}
// Save a whole buffer to disk
unsigned int ModuleFileSystem::Save(const char* file, const char* buffer, unsigned int size) const
{
unsigned int ret = 0;
PHYSFS_file* fs_file = PHYSFS_openWrite(file);
if (fs_file != NULL)
{
PHYSFS_sint64 written = PHYSFS_write(fs_file, (const void*)buffer, 1, size);
if (written != size)
{
MYLOG("File System error while writing to file %s: %s\n", file, PHYSFS_getLastError());
}
else
ret = (uint)written;
if (PHYSFS_close(fs_file) == 0)
MYLOG("File System error while closing file %s: %s\n", file, PHYSFS_getLastError());
}
else
MYLOG("File System error while opening file %s: %s\n", file, PHYSFS_getLastError());
return ret;
}<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
// If <iostream> is included, put it after <stdio.h>, because it includes
// <stdio.h>, and therefore would ignore the _WITH_GETLINE.
#ifdef FREEBSD
#define _WITH_GETLINE
#endif
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdint.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <errno.h>
#include <signal.h>
#include <sys/select.h>
#include <Date.h>
#include <text.h>
#include <main.h>
#include <i18n.h>
#include <util.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// Uses std::getline, because std::cin eats leading whitespace, and that means
// that if a newline is entered, std::cin eats it and never returns from the
// "std::cin >> answer;" line, but it does display the newline. This way, with
// std::getline, the newline can be detected, and the prompt re-written.
bool confirm (const std::string& question)
{
std::vector <std::string> options {STRING_UTIL_CONFIRM_YES,
STRING_UTIL_CONFIRM_NO};
std::vector <std::string> matches;
do
{
std::cout << question
<< STRING_UTIL_CONFIRM_YN;
std::string answer {""};
std::getline (std::cin, answer);
answer = std::cin.eof() ? STRING_UTIL_CONFIRM_NO : lowerCase (trim (answer));
autoComplete (answer, options, matches, 1); // Hard-coded 1.
}
while (matches.size () != 1);
return matches[0] == STRING_UTIL_CONFIRM_YES ? true : false;
}
////////////////////////////////////////////////////////////////////////////////
// 0 = no
// 1 = yes
// 2 = all
// 3 = quit
int confirm4 (const std::string& question)
{
std::vector <std::string> options {STRING_UTIL_CONFIRM_YES_U,
STRING_UTIL_CONFIRM_YES,
STRING_UTIL_CONFIRM_NO,
STRING_UTIL_CONFIRM_ALL_U,
STRING_UTIL_CONFIRM_ALL,
STRING_UTIL_CONFIRM_QUIT};
std::vector <std::string> matches;
do
{
std::cout << question
<< " ("
<< options[1] << "/"
<< options[2] << "/"
<< options[4] << "/"
<< options[5]
<< ") ";
std::string answer {""};
std::getline (std::cin, answer);
answer = trim (answer);
autoComplete (answer, options, matches, 1); // Hard-coded 1.
}
while (matches.size () != 1);
if (matches[0] == STRING_UTIL_CONFIRM_YES_U) return 1;
else if (matches[0] == STRING_UTIL_CONFIRM_YES) return 1;
else if (matches[0] == STRING_UTIL_CONFIRM_ALL_U) return 2;
else if (matches[0] == STRING_UTIL_CONFIRM_ALL) return 2;
else if (matches[0] == STRING_UTIL_CONFIRM_QUIT) return 3;
else return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Convert a quantity in seconds to a more readable format.
std::string formatBytes (size_t bytes)
{
char formatted[24];
if (bytes >= 995000000) sprintf (formatted, "%.1f %s", (bytes / 1000000000.0), STRING_UTIL_GIBIBYTES);
else if (bytes >= 995000) sprintf (formatted, "%.1f %s", (bytes / 1000000.0), STRING_UTIL_MEBIBYTES);
else if (bytes >= 995) sprintf (formatted, "%.1f %s", (bytes / 1000.0), STRING_UTIL_KIBIBYTES);
else sprintf (formatted, "%d %s", (int)bytes, STRING_UTIL_BYTES);
return commify (formatted);
}
////////////////////////////////////////////////////////////////////////////////
int autoComplete (
const std::string& partial,
const std::vector<std::string>& list,
std::vector<std::string>& matches,
int minimum/* = 1*/)
{
matches.clear ();
// Handle trivial case.
unsigned int length = partial.length ();
if (length)
{
for (auto& item : list)
{
// An exact match is a special case. Assume there is only one exact match
// and return immediately.
if (partial == item)
{
matches.clear ();
matches.push_back (item);
return 1;
}
// Maintain a list of partial matches.
else if (length >= (unsigned) minimum &&
length <= item.length () &&
partial == item.substr (0, length))
matches.push_back (item);
}
}
return matches.size ();
}
// Handle the generation of UUIDs on FreeBSD in a separate implementation
// of the uuid () function, since the API is quite different from Linux's.
// Also, uuid_unparse_lower is not needed on FreeBSD, because the string
// representation is always lowercase anyway.
// For the implementation details, refer to
// http://svnweb.freebsd.org/base/head/sys/kern/kern_uuid.c
#ifdef FREEBSD
const std::string uuid ()
{
uuid_t id;
uint32_t status;
char *buffer (0);
uuid_create (&id, &status);
uuid_to_string (&id, &buffer, &status);
std::string res (buffer);
free (buffer);
return res;
}
#else
////////////////////////////////////////////////////////////////////////////////
#ifndef HAVE_UUID_UNPARSE_LOWER
// Older versions of libuuid don't have uuid_unparse_lower(), only uuid_unparse()
void uuid_unparse_lower (uuid_t uu, char *out)
{
uuid_unparse (uu, out);
// Characters in out are either 0-9, a-z, '-', or A-Z. A-Z is mapped to
// a-z by bitwise or with 0x20, and the others already have this bit set
for (size_t i = 0; i < 36; ++i) out[i] |= 0x20;
}
#endif
const std::string uuid ()
{
uuid_t id;
uuid_generate (id);
char buffer[100] = {0};
uuid_unparse_lower (id, buffer);
// Bug found by Steven de Brouwer.
buffer[36] = '\0';
return std::string (buffer);
}
#endif
////////////////////////////////////////////////////////////////////////////////
// Run a binary with args, capturing output.
int execute (
const std::string& executable,
const std::vector <std::string>& args,
const std::string& input,
std::string& output)
{
pid_t pid;
int pin[2], pout[2];
fd_set rfds, wfds;
struct timeval tv;
int select_retval, read_retval, write_retval;
char buf[16384];
unsigned int written;
const char* input_cstr = input.c_str ();
if (signal (SIGPIPE, SIG_IGN) == SIG_ERR) // Handled locally with EPIPE.
throw std::string (std::strerror (errno));
if (pipe (pin) == -1)
throw std::string (std::strerror (errno));
if (pipe (pout) == -1)
throw std::string (std::strerror (errno));
if ((pid = fork ()) == -1)
throw std::string (std::strerror (errno));
if (pid == 0)
{
// This is only reached in the child
close (pin[1]); // Close the write end of the input pipe.
close (pout[0]); // Close the read end of the output pipe.
// Parent writes to pin[1]. Set read end pin[0] as STDIN for child.
if (dup2 (pin[0], STDIN_FILENO) == -1)
throw std::string (std::strerror (errno));
close (pin[0]);
// Parent reads from pout[0]. Set write end pout[1] as STDOUT for child.
if (dup2 (pout[1], STDOUT_FILENO) == -1)
throw std::string (std::strerror (errno));
close (pout[1]);
// Add executable as argv[0] and NULL-terminate the array for execvp().
char** argv = new char* [args.size () + 2];
argv[0] = (char*) executable.c_str ();
for (unsigned int i = 0; i < args.size (); ++i)
argv[i+1] = (char*) args[i].c_str ();
argv[args.size () + 1] = NULL;
_exit (execvp (executable.c_str (), argv));
}
// This is only reached in the parent
close (pin[0]); // Close the read end of the input pipe.
close (pout[1]); // Close the write end of the output pipe.
if (input.size () == 0)
{
// Nothing to send to the child, close the pipe early.
close (pin[1]);
}
output = "";
read_retval = -1;
written = 0;
while (read_retval != 0 || input.size () != written)
{
FD_ZERO (&rfds);
if (read_retval != 0)
FD_SET (pout[0], &rfds);
FD_ZERO (&wfds);
if (input.size () != written)
FD_SET (pin[1], &wfds);
// On Linux, tv may be overwritten by select(). Reset it each time.
// NOTE: Timeout chosen arbitrarily - we don't time out execute() calls.
// select() is run over and over again unless the child exits or closes
// its pipes.
tv.tv_sec = 5;
tv.tv_usec = 0;
select_retval = select (std::max (pout[0], pin[1]) + 1, &rfds, &wfds, NULL, &tv);
if (select_retval == -1)
throw std::string (std::strerror (errno));
// Write data to child's STDIN
if (FD_ISSET (pin[1], &wfds))
{
write_retval = write (pin[1], input_cstr + written, input.size () - written);
if (write_retval == -1)
{
if (errno == EPIPE)
{
// Child died (or closed the pipe) before reading all input.
// We don't really care; pretend we wrote it all.
write_retval = input.size () - written;
}
else
{
throw std::string (std::strerror (errno));
}
}
written += write_retval;
if (written == input.size ())
{
// Let the child know that no more input is coming by closing the pipe.
close (pin[1]);
}
}
// Read data from child's STDOUT
if (FD_ISSET (pout[0], &rfds))
{
read_retval = read (pout[0], &buf, sizeof (buf) - 1);
if (read_retval == -1)
throw std::string (std::strerror (errno));
buf[read_retval] = '\0';
output += buf;
}
}
close (pout[0]); // Close the read end of the output pipe.
int status = -1;
if (wait (&status) == -1)
throw std::string (std::strerror (errno));
if (WIFEXITED (status))
{
status = WEXITSTATUS (status);
}
else
{
throw std::string ("Error: Could not get Hook exit status!");
}
if (signal (SIGPIPE, SIG_DFL) == SIG_ERR) // We're done, return to default.
throw std::string (std::strerror (errno));
return status;
}
// Collides with std::numeric_limits methods
#undef max
////////////////////////////////////////////////////////////////////////////////
// Accept a list of projects, and return an indented list
// that reflects the hierarchy.
//
// Input - "one"
// "one.two"
// "one.two.three"
// "one.four"
// "two"
// Output - "one"
// " one.two"
// " one.two.three"
// " one.four"
// "two"
//
// There are two optional arguments, 'whitespace', and 'delimiter',
//
// - whitespace is the string used to build the prefixes of indented items.
// - defaults to two spaces, " "
// - delimiter is the character used to split up projects into subprojects.
// - defaults to the period, '.'
//
const std::string indentProject (
const std::string& project,
const std::string& whitespace /* = " " */,
char delimiter /* = '.' */)
{
// Count the delimiters in *i.
std::string prefix = "";
std::string::size_type pos = 0;
std::string::size_type lastpos = 0;
while ((pos = project.find (delimiter, pos + 1)) != std::string::npos)
{
if (pos != project.size () - 1)
{
prefix += whitespace;
lastpos = pos;
}
}
std::string child = "";
if (lastpos == 0)
child = project;
else
child = project.substr (lastpos + 1);
return prefix + child;
}
////////////////////////////////////////////////////////////////////////////////
const std::vector <std::string> extractParents (
const std::string& project,
const char& delimiter /* = '.' */)
{
std::vector <std::string> vec;
std::string::size_type pos = 0;
std::string::size_type copyUntil = 0;
while ((copyUntil = project.find (delimiter, pos + 1)) != std::string::npos)
{
if (copyUntil != project.size () - 1)
vec.push_back (project.substr (0, copyUntil));
pos = copyUntil;
}
return vec;
}
////////////////////////////////////////////////////////////////////////////////
#ifndef HAVE_TIMEGM
time_t timegm (struct tm *tm)
{
time_t ret;
char *tz;
tz = getenv ("TZ");
setenv ("TZ", "UTC", 1);
tzset ();
ret = mktime (tm);
if (tz)
setenv ("TZ", tz, 1);
else
unsetenv ("TZ");
tzset ();
return ret;
}
#endif
////////////////////////////////////////////////////////////////////////////////
<commit_msg>util: Sends all read input to debug output<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
// If <iostream> is included, put it after <stdio.h>, because it includes
// <stdio.h>, and therefore would ignore the _WITH_GETLINE.
#ifdef FREEBSD
#define _WITH_GETLINE
#endif
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdint.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <errno.h>
#include <signal.h>
#include <sys/select.h>
#include <Date.h>
#include <text.h>
#include <main.h>
#include <i18n.h>
#include <util.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// Uses std::getline, because std::cin eats leading whitespace, and that means
// that if a newline is entered, std::cin eats it and never returns from the
// "std::cin >> answer;" line, but it does display the newline. This way, with
// std::getline, the newline can be detected, and the prompt re-written.
bool confirm (const std::string& question)
{
std::vector <std::string> options {STRING_UTIL_CONFIRM_YES,
STRING_UTIL_CONFIRM_NO};
std::vector <std::string> matches;
do
{
std::cout << question
<< STRING_UTIL_CONFIRM_YN;
std::string answer {""};
std::getline (std::cin, answer);
context.debug ("STDIN '" + answer + "'");
answer = std::cin.eof() ? STRING_UTIL_CONFIRM_NO : lowerCase (trim (answer));
autoComplete (answer, options, matches, 1); // Hard-coded 1.
}
while (matches.size () != 1);
return matches[0] == STRING_UTIL_CONFIRM_YES ? true : false;
}
////////////////////////////////////////////////////////////////////////////////
// 0 = no
// 1 = yes
// 2 = all
// 3 = quit
int confirm4 (const std::string& question)
{
std::vector <std::string> options {STRING_UTIL_CONFIRM_YES_U,
STRING_UTIL_CONFIRM_YES,
STRING_UTIL_CONFIRM_NO,
STRING_UTIL_CONFIRM_ALL_U,
STRING_UTIL_CONFIRM_ALL,
STRING_UTIL_CONFIRM_QUIT};
std::vector <std::string> matches;
do
{
std::cout << question
<< " ("
<< options[1] << "/"
<< options[2] << "/"
<< options[4] << "/"
<< options[5]
<< ") ";
std::string answer {""};
std::getline (std::cin, answer);
context.debug ("STDIN '" + answer + "'");
answer = trim (answer);
autoComplete (answer, options, matches, 1); // Hard-coded 1.
}
while (matches.size () != 1);
if (matches[0] == STRING_UTIL_CONFIRM_YES_U) return 1;
else if (matches[0] == STRING_UTIL_CONFIRM_YES) return 1;
else if (matches[0] == STRING_UTIL_CONFIRM_ALL_U) return 2;
else if (matches[0] == STRING_UTIL_CONFIRM_ALL) return 2;
else if (matches[0] == STRING_UTIL_CONFIRM_QUIT) return 3;
else return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Convert a quantity in seconds to a more readable format.
std::string formatBytes (size_t bytes)
{
char formatted[24];
if (bytes >= 995000000) sprintf (formatted, "%.1f %s", (bytes / 1000000000.0), STRING_UTIL_GIBIBYTES);
else if (bytes >= 995000) sprintf (formatted, "%.1f %s", (bytes / 1000000.0), STRING_UTIL_MEBIBYTES);
else if (bytes >= 995) sprintf (formatted, "%.1f %s", (bytes / 1000.0), STRING_UTIL_KIBIBYTES);
else sprintf (formatted, "%d %s", (int)bytes, STRING_UTIL_BYTES);
return commify (formatted);
}
////////////////////////////////////////////////////////////////////////////////
int autoComplete (
const std::string& partial,
const std::vector<std::string>& list,
std::vector<std::string>& matches,
int minimum/* = 1*/)
{
matches.clear ();
// Handle trivial case.
unsigned int length = partial.length ();
if (length)
{
for (auto& item : list)
{
// An exact match is a special case. Assume there is only one exact match
// and return immediately.
if (partial == item)
{
matches.clear ();
matches.push_back (item);
return 1;
}
// Maintain a list of partial matches.
else if (length >= (unsigned) minimum &&
length <= item.length () &&
partial == item.substr (0, length))
matches.push_back (item);
}
}
return matches.size ();
}
// Handle the generation of UUIDs on FreeBSD in a separate implementation
// of the uuid () function, since the API is quite different from Linux's.
// Also, uuid_unparse_lower is not needed on FreeBSD, because the string
// representation is always lowercase anyway.
// For the implementation details, refer to
// http://svnweb.freebsd.org/base/head/sys/kern/kern_uuid.c
#ifdef FREEBSD
const std::string uuid ()
{
uuid_t id;
uint32_t status;
char *buffer (0);
uuid_create (&id, &status);
uuid_to_string (&id, &buffer, &status);
std::string res (buffer);
free (buffer);
return res;
}
#else
////////////////////////////////////////////////////////////////////////////////
#ifndef HAVE_UUID_UNPARSE_LOWER
// Older versions of libuuid don't have uuid_unparse_lower(), only uuid_unparse()
void uuid_unparse_lower (uuid_t uu, char *out)
{
uuid_unparse (uu, out);
// Characters in out are either 0-9, a-z, '-', or A-Z. A-Z is mapped to
// a-z by bitwise or with 0x20, and the others already have this bit set
for (size_t i = 0; i < 36; ++i) out[i] |= 0x20;
}
#endif
const std::string uuid ()
{
uuid_t id;
uuid_generate (id);
char buffer[100] = {0};
uuid_unparse_lower (id, buffer);
// Bug found by Steven de Brouwer.
buffer[36] = '\0';
return std::string (buffer);
}
#endif
////////////////////////////////////////////////////////////////////////////////
// Run a binary with args, capturing output.
int execute (
const std::string& executable,
const std::vector <std::string>& args,
const std::string& input,
std::string& output)
{
pid_t pid;
int pin[2], pout[2];
fd_set rfds, wfds;
struct timeval tv;
int select_retval, read_retval, write_retval;
char buf[16384];
unsigned int written;
const char* input_cstr = input.c_str ();
if (signal (SIGPIPE, SIG_IGN) == SIG_ERR) // Handled locally with EPIPE.
throw std::string (std::strerror (errno));
if (pipe (pin) == -1)
throw std::string (std::strerror (errno));
if (pipe (pout) == -1)
throw std::string (std::strerror (errno));
if ((pid = fork ()) == -1)
throw std::string (std::strerror (errno));
if (pid == 0)
{
// This is only reached in the child
close (pin[1]); // Close the write end of the input pipe.
close (pout[0]); // Close the read end of the output pipe.
// Parent writes to pin[1]. Set read end pin[0] as STDIN for child.
if (dup2 (pin[0], STDIN_FILENO) == -1)
throw std::string (std::strerror (errno));
close (pin[0]);
// Parent reads from pout[0]. Set write end pout[1] as STDOUT for child.
if (dup2 (pout[1], STDOUT_FILENO) == -1)
throw std::string (std::strerror (errno));
close (pout[1]);
// Add executable as argv[0] and NULL-terminate the array for execvp().
char** argv = new char* [args.size () + 2];
argv[0] = (char*) executable.c_str ();
for (unsigned int i = 0; i < args.size (); ++i)
argv[i+1] = (char*) args[i].c_str ();
argv[args.size () + 1] = NULL;
_exit (execvp (executable.c_str (), argv));
}
// This is only reached in the parent
close (pin[0]); // Close the read end of the input pipe.
close (pout[1]); // Close the write end of the output pipe.
if (input.size () == 0)
{
// Nothing to send to the child, close the pipe early.
close (pin[1]);
}
output = "";
read_retval = -1;
written = 0;
while (read_retval != 0 || input.size () != written)
{
FD_ZERO (&rfds);
if (read_retval != 0)
FD_SET (pout[0], &rfds);
FD_ZERO (&wfds);
if (input.size () != written)
FD_SET (pin[1], &wfds);
// On Linux, tv may be overwritten by select(). Reset it each time.
// NOTE: Timeout chosen arbitrarily - we don't time out execute() calls.
// select() is run over and over again unless the child exits or closes
// its pipes.
tv.tv_sec = 5;
tv.tv_usec = 0;
select_retval = select (std::max (pout[0], pin[1]) + 1, &rfds, &wfds, NULL, &tv);
if (select_retval == -1)
throw std::string (std::strerror (errno));
// Write data to child's STDIN
if (FD_ISSET (pin[1], &wfds))
{
write_retval = write (pin[1], input_cstr + written, input.size () - written);
if (write_retval == -1)
{
if (errno == EPIPE)
{
// Child died (or closed the pipe) before reading all input.
// We don't really care; pretend we wrote it all.
write_retval = input.size () - written;
}
else
{
throw std::string (std::strerror (errno));
}
}
written += write_retval;
if (written == input.size ())
{
// Let the child know that no more input is coming by closing the pipe.
close (pin[1]);
}
}
// Read data from child's STDOUT
if (FD_ISSET (pout[0], &rfds))
{
read_retval = read (pout[0], &buf, sizeof (buf) - 1);
if (read_retval == -1)
throw std::string (std::strerror (errno));
buf[read_retval] = '\0';
output += buf;
}
}
close (pout[0]); // Close the read end of the output pipe.
int status = -1;
if (wait (&status) == -1)
throw std::string (std::strerror (errno));
if (WIFEXITED (status))
{
status = WEXITSTATUS (status);
}
else
{
throw std::string ("Error: Could not get Hook exit status!");
}
if (signal (SIGPIPE, SIG_DFL) == SIG_ERR) // We're done, return to default.
throw std::string (std::strerror (errno));
return status;
}
// Collides with std::numeric_limits methods
#undef max
////////////////////////////////////////////////////////////////////////////////
// Accept a list of projects, and return an indented list
// that reflects the hierarchy.
//
// Input - "one"
// "one.two"
// "one.two.three"
// "one.four"
// "two"
// Output - "one"
// " one.two"
// " one.two.three"
// " one.four"
// "two"
//
// There are two optional arguments, 'whitespace', and 'delimiter',
//
// - whitespace is the string used to build the prefixes of indented items.
// - defaults to two spaces, " "
// - delimiter is the character used to split up projects into subprojects.
// - defaults to the period, '.'
//
const std::string indentProject (
const std::string& project,
const std::string& whitespace /* = " " */,
char delimiter /* = '.' */)
{
// Count the delimiters in *i.
std::string prefix = "";
std::string::size_type pos = 0;
std::string::size_type lastpos = 0;
while ((pos = project.find (delimiter, pos + 1)) != std::string::npos)
{
if (pos != project.size () - 1)
{
prefix += whitespace;
lastpos = pos;
}
}
std::string child = "";
if (lastpos == 0)
child = project;
else
child = project.substr (lastpos + 1);
return prefix + child;
}
////////////////////////////////////////////////////////////////////////////////
const std::vector <std::string> extractParents (
const std::string& project,
const char& delimiter /* = '.' */)
{
std::vector <std::string> vec;
std::string::size_type pos = 0;
std::string::size_type copyUntil = 0;
while ((copyUntil = project.find (delimiter, pos + 1)) != std::string::npos)
{
if (copyUntil != project.size () - 1)
vec.push_back (project.substr (0, copyUntil));
pos = copyUntil;
}
return vec;
}
////////////////////////////////////////////////////////////////////////////////
#ifndef HAVE_TIMEGM
time_t timegm (struct tm *tm)
{
time_t ret;
char *tz;
tz = getenv ("TZ");
setenv ("TZ", "UTC", 1);
tzset ();
ret = mktime (tm);
if (tz)
setenv ("TZ", tz, 1);
else
unsetenv ("TZ");
tzset ();
return ret;
}
#endif
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docshel3.cxx,v $
*
* $Revision: 1.23 $
*
* last change: $Author: kz $ $Date: 2008-04-03 13:27:19 $
*
* 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_sd.hxx"
#include "DrawDocShell.hxx"
#include "app.hrc"
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif
#include <svx/ofaitem.hxx>
#ifndef _SVXERR_HXX
#include <svx/svxerr.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include <svx/dialmgr.hxx>
#endif
#ifndef _SFX_SRCHITEM_HXX
#include <sfx2/srchitem.hxx>
#endif
#ifndef _SVX_SRCHDLG_HXX
#include <svx/srchdlg.hxx>
#endif
#ifdef _OUTLINER_HXX
#include <svx/outliner.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#ifndef _SVX_DRAWITEM_HXX //autogen
#include <svx/drawitem.hxx>
#endif
#ifndef _UNO_LINGU_HXX
#include <svx/unolingu.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_TEXTCONVERSIONOPTION_HPP_
#include <com/sun/star/i18n/TextConversionOption.hpp>
#endif
#include "strings.hrc"
#include "glob.hrc"
#include "res_bmp.hrc"
#include "app.hxx"
#include "drawdoc.hxx"
#include "sdpage.hxx"
#include "sdattr.hxx"
#ifndef SD_FU_SEARCH_HXX
#include "fusearch.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef _SD_SLIDESHOW_HXX
#include "slideshow.hxx"
#endif
#include "fuhhconv.hxx"
#include "slideshow.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
namespace sd {
#define POOL_BUFFER_SIZE (USHORT)32768
#define BASIC_BUFFER_SIZE (USHORT)8192
#define DOCUMENT_BUFFER_SIZE (USHORT)32768
/*************************************************************************
|*
|* SFX-Requests bearbeiten
|*
\************************************************************************/
void DrawDocShell::Execute( SfxRequest& rReq )
{
if(mpViewShell && SlideShow::IsRunning( mpViewShell->GetViewShellBase() ))
{
// during a running presentation no slot will be executed
return;
}
switch ( rReq.GetSlot() )
{
case SID_SEARCH_ITEM:
{
const SfxItemSet* pReqArgs = rReq.GetArgs();
if (pReqArgs)
{
const SvxSearchItem* pSearchItem =
(const SvxSearchItem*) &pReqArgs->Get(SID_SEARCH_ITEM);
// ein Zuweisungsoperator am SearchItem waer nicht schlecht...
SvxSearchItem* pAppSearchItem = SD_MOD()->GetSearchItem();
delete pAppSearchItem;
pAppSearchItem = (SvxSearchItem*) pSearchItem->Clone();
SD_MOD()->SetSearchItem(pAppSearchItem);
}
rReq.Done();
}
break;
case FID_SEARCH_ON:
{
// Keine Aktion noetig
rReq.Done();
}
break;
case FID_SEARCH_OFF:
{
if( dynamic_cast< FuSearch* >(mxDocShellFunction.get()) )
{
// Suchen&Ersetzen in allen DocShells beenden
SfxObjectShell* pFirstShell = SfxObjectShell::GetFirst();
SfxObjectShell* pShell = pFirstShell;
while (pShell)
{
if (pShell->ISA(DrawDocShell))
{
( (DrawDocShell*) pShell)->CancelSearching();
}
pShell = SfxObjectShell::GetNext(*pShell);
if (pShell == pFirstShell)
{
pShell = NULL;
}
}
SetDocShellFunction(0);
Invalidate();
rReq.Done();
}
}
break;
case FID_SEARCH_NOW:
{
const SfxItemSet* pReqArgs = rReq.GetArgs();
if ( pReqArgs )
{
rtl::Reference< FuSearch > xFuSearch( dynamic_cast< FuSearch* >( GetDocShellFunction().get() ) );
if( !xFuSearch.is() && mpViewShell )
{
::sd::View* pView = mpViewShell->GetView();
SetDocShellFunction( FuSearch::Create( mpViewShell, mpViewShell->GetActiveWindow(), pView, mpDoc, rReq ) );
xFuSearch.set( dynamic_cast< FuSearch* >( GetDocShellFunction().get() ) );
}
if( xFuSearch.is() )
{
const SvxSearchItem* pSearchItem =
(const SvxSearchItem*) &pReqArgs->Get(SID_SEARCH_ITEM);
// ein Zuweisungsoperator am SearchItem waer nicht schlecht...
SvxSearchItem* pAppSearchItem = SD_MOD()->GetSearchItem();
delete pAppSearchItem;
pAppSearchItem = (SvxSearchItem*)pSearchItem->Clone();
SD_MOD()->SetSearchItem(pAppSearchItem);
xFuSearch->SearchAndReplace(pSearchItem);
}
}
rReq.Done();
}
break;
case SID_CLOSEDOC:
{
// SfxObjectShell::DoClose();
ExecuteSlot(rReq, SfxObjectShell::GetStaticInterface());
}
break;
case SID_GET_COLORTABLE:
{
// passende ColorTable ist per PutItem gesetzt worden
SvxColorTableItem* pColItem = (SvxColorTableItem*) GetItem( SID_COLOR_TABLE );
XColorTable* pTable = pColItem->GetColorTable();
rReq.SetReturnValue( OfaPtrItem( SID_GET_COLORTABLE, pTable ) );
}
break;
case SID_VERSION:
{
const ULONG nOldSwapMode = mpDoc->GetSwapGraphicsMode();
mpDoc->SetSwapGraphicsMode( SDR_SWAPGRAPHICSMODE_TEMP );
ExecuteSlot( rReq, SfxObjectShell::GetStaticInterface() );
mpDoc->SetSwapGraphicsMode( nOldSwapMode );
}
break;
case SID_HANGUL_HANJA_CONVERSION:
{
if( mpViewShell )
{
FunctionReference aFunc( FuHangulHanjaConversion::Create( mpViewShell, mpViewShell->GetActiveWindow(), mpViewShell->GetView(), mpDoc, rReq ) );
static_cast< FuHangulHanjaConversion* >( aFunc.get() )->StartConversion( LANGUAGE_KOREAN, LANGUAGE_KOREAN, NULL, i18n::TextConversionOption::CHARACTER_BY_CHARACTER, sal_True );
}
}
break;
case SID_CHINESE_CONVERSION:
{
if( mpViewShell )
{
FunctionReference aFunc( FuHangulHanjaConversion::Create( mpViewShell, mpViewShell->GetActiveWindow(), mpViewShell->GetView(), mpDoc, rReq ) );
static_cast< FuHangulHanjaConversion* >( aFunc.get() )->StartChineseConversion();
}
}
break;
default:
break;
}
}
/*************************************************************************
|*
|* Suchmaske fuer Organizer
|*
\************************************************************************/
void DrawDocShell::SetOrganizerSearchMask(SfxStyleSheetBasePool* pBasePool) const
{
pBasePool->SetSearchMask(SD_STYLE_FAMILY_GRAPHICS, SFXSTYLEBIT_USERDEF | SFXSTYLEBIT_USED);
}
void DrawDocShell::SetDocShellFunction( const ::sd::FunctionReference& xFunction )
{
if( mxDocShellFunction.is() )
mxDocShellFunction->Dispose();
mxDocShellFunction = xFunction;
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS changefileheader (1.22.14); FILE MERGED 2008/04/01 15:34:24 thb 1.22.14.3: #i85898# Stripping all external header guards 2008/04/01 12:38:43 thb 1.22.14.2: #i85898# Stripping all external header guards 2008/03/31 13:57:59 rt 1.22.14.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: docshel3.cxx,v $
* $Revision: 1.24 $
*
* 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_sd.hxx"
#include "DrawDocShell.hxx"
#include "app.hrc"
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif
#include <svx/ofaitem.hxx>
#include <svx/svxerr.hxx>
#include <svx/dialmgr.hxx>
#include <sfx2/srchitem.hxx>
#include <svx/srchdlg.hxx>
#ifdef _OUTLINER_HXX
#include <svx/outliner.hxx>
#endif
#include <sfx2/request.hxx>
#include <svtools/style.hxx>
#include <svx/drawitem.hxx>
#include <svx/unolingu.hxx>
#include <com/sun/star/i18n/TextConversionOption.hpp>
#include "strings.hrc"
#include "glob.hrc"
#include "res_bmp.hrc"
#include "app.hxx"
#include "drawdoc.hxx"
#include "sdpage.hxx"
#include "sdattr.hxx"
#include "fusearch.hxx"
#include "ViewShell.hxx"
#include "View.hxx"
#include "slideshow.hxx"
#include "fuhhconv.hxx"
#include "slideshow.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
namespace sd {
#define POOL_BUFFER_SIZE (USHORT)32768
#define BASIC_BUFFER_SIZE (USHORT)8192
#define DOCUMENT_BUFFER_SIZE (USHORT)32768
/*************************************************************************
|*
|* SFX-Requests bearbeiten
|*
\************************************************************************/
void DrawDocShell::Execute( SfxRequest& rReq )
{
if(mpViewShell && SlideShow::IsRunning( mpViewShell->GetViewShellBase() ))
{
// during a running presentation no slot will be executed
return;
}
switch ( rReq.GetSlot() )
{
case SID_SEARCH_ITEM:
{
const SfxItemSet* pReqArgs = rReq.GetArgs();
if (pReqArgs)
{
const SvxSearchItem* pSearchItem =
(const SvxSearchItem*) &pReqArgs->Get(SID_SEARCH_ITEM);
// ein Zuweisungsoperator am SearchItem waer nicht schlecht...
SvxSearchItem* pAppSearchItem = SD_MOD()->GetSearchItem();
delete pAppSearchItem;
pAppSearchItem = (SvxSearchItem*) pSearchItem->Clone();
SD_MOD()->SetSearchItem(pAppSearchItem);
}
rReq.Done();
}
break;
case FID_SEARCH_ON:
{
// Keine Aktion noetig
rReq.Done();
}
break;
case FID_SEARCH_OFF:
{
if( dynamic_cast< FuSearch* >(mxDocShellFunction.get()) )
{
// Suchen&Ersetzen in allen DocShells beenden
SfxObjectShell* pFirstShell = SfxObjectShell::GetFirst();
SfxObjectShell* pShell = pFirstShell;
while (pShell)
{
if (pShell->ISA(DrawDocShell))
{
( (DrawDocShell*) pShell)->CancelSearching();
}
pShell = SfxObjectShell::GetNext(*pShell);
if (pShell == pFirstShell)
{
pShell = NULL;
}
}
SetDocShellFunction(0);
Invalidate();
rReq.Done();
}
}
break;
case FID_SEARCH_NOW:
{
const SfxItemSet* pReqArgs = rReq.GetArgs();
if ( pReqArgs )
{
rtl::Reference< FuSearch > xFuSearch( dynamic_cast< FuSearch* >( GetDocShellFunction().get() ) );
if( !xFuSearch.is() && mpViewShell )
{
::sd::View* pView = mpViewShell->GetView();
SetDocShellFunction( FuSearch::Create( mpViewShell, mpViewShell->GetActiveWindow(), pView, mpDoc, rReq ) );
xFuSearch.set( dynamic_cast< FuSearch* >( GetDocShellFunction().get() ) );
}
if( xFuSearch.is() )
{
const SvxSearchItem* pSearchItem =
(const SvxSearchItem*) &pReqArgs->Get(SID_SEARCH_ITEM);
// ein Zuweisungsoperator am SearchItem waer nicht schlecht...
SvxSearchItem* pAppSearchItem = SD_MOD()->GetSearchItem();
delete pAppSearchItem;
pAppSearchItem = (SvxSearchItem*)pSearchItem->Clone();
SD_MOD()->SetSearchItem(pAppSearchItem);
xFuSearch->SearchAndReplace(pSearchItem);
}
}
rReq.Done();
}
break;
case SID_CLOSEDOC:
{
// SfxObjectShell::DoClose();
ExecuteSlot(rReq, SfxObjectShell::GetStaticInterface());
}
break;
case SID_GET_COLORTABLE:
{
// passende ColorTable ist per PutItem gesetzt worden
SvxColorTableItem* pColItem = (SvxColorTableItem*) GetItem( SID_COLOR_TABLE );
XColorTable* pTable = pColItem->GetColorTable();
rReq.SetReturnValue( OfaPtrItem( SID_GET_COLORTABLE, pTable ) );
}
break;
case SID_VERSION:
{
const ULONG nOldSwapMode = mpDoc->GetSwapGraphicsMode();
mpDoc->SetSwapGraphicsMode( SDR_SWAPGRAPHICSMODE_TEMP );
ExecuteSlot( rReq, SfxObjectShell::GetStaticInterface() );
mpDoc->SetSwapGraphicsMode( nOldSwapMode );
}
break;
case SID_HANGUL_HANJA_CONVERSION:
{
if( mpViewShell )
{
FunctionReference aFunc( FuHangulHanjaConversion::Create( mpViewShell, mpViewShell->GetActiveWindow(), mpViewShell->GetView(), mpDoc, rReq ) );
static_cast< FuHangulHanjaConversion* >( aFunc.get() )->StartConversion( LANGUAGE_KOREAN, LANGUAGE_KOREAN, NULL, i18n::TextConversionOption::CHARACTER_BY_CHARACTER, sal_True );
}
}
break;
case SID_CHINESE_CONVERSION:
{
if( mpViewShell )
{
FunctionReference aFunc( FuHangulHanjaConversion::Create( mpViewShell, mpViewShell->GetActiveWindow(), mpViewShell->GetView(), mpDoc, rReq ) );
static_cast< FuHangulHanjaConversion* >( aFunc.get() )->StartChineseConversion();
}
}
break;
default:
break;
}
}
/*************************************************************************
|*
|* Suchmaske fuer Organizer
|*
\************************************************************************/
void DrawDocShell::SetOrganizerSearchMask(SfxStyleSheetBasePool* pBasePool) const
{
pBasePool->SetSearchMask(SD_STYLE_FAMILY_GRAPHICS, SFXSTYLEBIT_USERDEF | SFXSTYLEBIT_USED);
}
void DrawDocShell::SetDocShellFunction( const ::sd::FunctionReference& xFunction )
{
if( mxDocShellFunction.is() )
mxDocShellFunction->Dispose();
mxDocShellFunction = xFunction;
}
} // end of namespace sd
<|endoftext|> |
<commit_before>/*
* Copyright 2014 BrewPi/Elco Jacobs.
*
* This file is part of BrewPi.
*
* BrewPi 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.
*
* BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
#include "BrewPiTouch.h"
#include "application.h"
#include <limits.h>
// includes for getting a median:
#undef min
#undef max
#undef swap
#include <vector>
#include <algorithm>
BrewPiTouch::BrewPiTouch(SPIArbiter & spia, uint8_t cs, uint8_t irq) : _spi(spia), pinCS(cs), pinIRQ(irq) {
}
BrewPiTouch::~BrewPiTouch() {
}
void BrewPiTouch::init(uint8_t configuration) {
// default is:
// 12bit (mode=0)
// power down between conversions, penIRQ enabled (PD1,PD0 = 00)
// Differential reference (SER/DFR = 0)
config = configuration;
width = 1600;
height = 1600;
tftWidth = 320;
tftHeight = 240;
xOffset = 0;
yOffset = 0;
setStabilityThreshold(); // default threshold
pinMode(pinCS, OUTPUT);
pinMode(pinIRQ, INPUT);
_spi.setClockDivider(SPI_CLOCK_DIV64);
_spi.setClockDivider(SPI_MODE0);
_spi.begin(pinCS);
_spi.transfer(config);
_spi.end();
filterX.init(width/2);
filterX.setCoefficients(SETTLING_TIME_25_SAMPLES);
filterY.init(height/2);
filterY.setCoefficients(SETTLING_TIME_25_SAMPLES);
update();
}
void BrewPiTouch::set8bit() {
config = config | MODE;
}
void BrewPiTouch::set12bit() {
config = config & ~MODE;
}
bool BrewPiTouch::is8bit() {
return (config & MODE) ? 1 : 0;
}
bool BrewPiTouch::is12bit() {
return (config & MODE) ? 0 : 1;
}
uint16_t BrewPiTouch::readChannel() {
uint16_t data;
data = _spi.transfer(0);
if (is12bit()) {
data = data << 8;
data += _spi.transfer(0);
data = data >> 4;
}
return data;
}
bool BrewPiTouch::isTouched() {
return (digitalRead(pinIRQ) == HIGH ? 0 : 1);
}
int16_t BrewPiTouch::getXRaw() {
return filterX.readInput();
}
int16_t BrewPiTouch::getYRaw() {
return filterY.readInput();
}
int16_t BrewPiTouch::getX() {
int32_t val = getXRaw(); // create room for multiplication
val -= xOffset; // remove offset
val = val * tftWidth / width; //scale
return val;
}
int16_t BrewPiTouch::getY() {
int32_t val = getYRaw(); // create room for multiplication
val -= yOffset; // remove offset
val = val * tftHeight / height; //scale
return val;
}
/*
* update() updates the x and y coordinates of the touch screen
* It reads numSamples values and takes the median
* The result is fed to the low pass filters
*/
bool BrewPiTouch::update(uint16_t numSamples) {
std::vector<int16_t> samplesX;
std::vector<int16_t> samplesY;
_spi.begin();
bool valid = true;
for (uint16_t i = 0; i < numSamples; i++) {
if (!isTouched()) {
valid = false;
break;
}
pinMode(pinIRQ, OUTPUT); // reverse bias diode during conversion
digitalWrite(pinIRQ, LOW); // as recommended in SBAA028
_spi.transfer((config & CHMASK) | CHX); // select channel x
samplesX.push_back(readChannel());
_spi.transfer((config & CHMASK) | CHY); // select channel y
samplesY.push_back(readChannel());
pinMode(pinIRQ, INPUT); // Set back to input
}
if (valid) {
// get median
size_t middle = samplesX.size() / 2;
std::nth_element(samplesX.begin(), samplesX.begin() + middle, samplesX.end());
std::nth_element(samplesY.begin(), samplesY.begin() + middle, samplesY.end());
// feed to filter to check stability
filterX.add(samplesX[middle]);
filterY.add(samplesY[middle]);
}
_spi.end();
return valid && isStable();
}
void BrewPiTouch::setStabilityThreshold(int16_t threshold){
stabilityThreshold = threshold;
}
/* isStable() returns true if the difference between the last sample and
* a low pass filtered value of past samples is under a certain threshold
*/
bool BrewPiTouch::isStable() {
if (abs(filterX.readInput() - filterX.readOutput()) > stabilityThreshold) {
return false;
}
if (abs(filterY.readInput() - filterY.readOutput()) > stabilityThreshold) {
return false;
}
return true;
}
/*
void BrewPiTouch::calibrate(Adafruit_ILI9341 * tft) {
int32_t xTouch[3];
int32_t yTouch[3];
tftWidth = tft->width();
tftHeight = tft->height();
int32_t xDisplay[3] = {CALIBRATE_FROM_EDGE, CALIBRATE_FROM_EDGE, tftWidth - CALIBRATE_FROM_EDGE};
int32_t yDisplay[3] = {CALIBRATE_FROM_EDGE, tftHeight - CALIBRATE_FROM_EDGE, tftHeight / 2};
volatile int16_t samples;
const int16_t requiredSamples = 1024;
tft->fillScreen(ILI9341_BLACK);
for (uint8_t i = 0; i < 3; i++) {
tft->drawCrossHair(xDisplay[i], yDisplay[i], 10, ILI9341_GREEN);
while (!isTouched()); // wait for touch
do {
samples = 0;
xTouch[i] = 0;
yTouch[i] = 0;
tft->drawFastHLine(0, 0, tftWidth, ILI9341_RED);
while (isTouched()) {
update();
if (!isStable()) {
// update is not valid, reset
break;
}
int32_t xSample = getXRaw();
int32_t ySample = getYRaw();
xTouch[i] += xSample;
yTouch[i] += ySample;
samples++;
int32_t xAverage = xTouch[i] / samples;
int32_t yAverage = yTouch[i] / samples;
int16_t xCalibrated = getX();
int16_t yCalibrated = getY();
tft->fillCircle(xCalibrated, yCalibrated, 2, ILI9341_WHITE);
// print progress line
uint16_t progress = samples * tftWidth / requiredSamples;
tft->drawFastHLine(0, 0, progress, ILI9341_BLUE);
// stop when required number of samples is reached
if (samples >= requiredSamples) {
tft->drawFastHLine(0, 0, tftWidth, ILI9341_GREEN);
tft->fillCircle(xDisplay[i], yDisplay[i], 8, ILI9341_BLUE);
while (isTouched()); // wait until released
break;
}
if (abs(xSample - xAverage) > 50 || abs(ySample - yAverage) > 50) {
// if new sample deviates too much from average, reset
break;
}
}
} while (samples < requiredSamples || isTouched());
xTouch[i] = xTouch[i] / samples;
yTouch[i] = yTouch[i] / samples;
}
width = tftWidth * (xTouch[2] - xTouch[0]) / (xDisplay[2] - xDisplay[0]);
height = tftHeight * (yTouch[1] - yTouch[0]) / (yDisplay[1] - yDisplay[0]);
xOffset = xTouch[0] - xDisplay[0] * width / tftWidth;
yOffset = yTouch[0] - yDisplay[0] * height / tftHeight;
}
*/
<commit_msg>fixed calling setClockDivider twice instead of setDataMode<commit_after>/*
* Copyright 2014 BrewPi/Elco Jacobs.
*
* This file is part of BrewPi.
*
* BrewPi 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.
*
* BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>.
*/
#include "BrewPiTouch.h"
#include "application.h"
#include <limits.h>
// includes for getting a median:
#undef min
#undef max
#undef swap
#include <vector>
#include <algorithm>
BrewPiTouch::BrewPiTouch(SPIArbiter & spia, uint8_t cs, uint8_t irq) : _spi(spia), pinCS(cs), pinIRQ(irq) {
}
BrewPiTouch::~BrewPiTouch() {
}
void BrewPiTouch::init(uint8_t configuration) {
// default is:
// 12bit (mode=0)
// power down between conversions, penIRQ enabled (PD1,PD0 = 00)
// Differential reference (SER/DFR = 0)
config = configuration;
width = 1600;
height = 1600;
tftWidth = 320;
tftHeight = 240;
xOffset = 0;
yOffset = 0;
setStabilityThreshold(); // default threshold
pinMode(pinCS, OUTPUT);
pinMode(pinIRQ, INPUT);
_spi.setClockDivider(SPI_CLOCK_DIV64);
_spi.setDataMode(SPI_MODE0);
_spi.begin(pinCS);
_spi.transfer(config);
_spi.end();
filterX.init(width/2);
filterX.setCoefficients(SETTLING_TIME_25_SAMPLES);
filterY.init(height/2);
filterY.setCoefficients(SETTLING_TIME_25_SAMPLES);
update();
}
void BrewPiTouch::set8bit() {
config = config | MODE;
}
void BrewPiTouch::set12bit() {
config = config & ~MODE;
}
bool BrewPiTouch::is8bit() {
return (config & MODE) ? 1 : 0;
}
bool BrewPiTouch::is12bit() {
return (config & MODE) ? 0 : 1;
}
uint16_t BrewPiTouch::readChannel() {
uint16_t data;
data = _spi.transfer(0);
if (is12bit()) {
data = data << 8;
data += _spi.transfer(0);
data = data >> 4;
}
return data;
}
bool BrewPiTouch::isTouched() {
return (digitalRead(pinIRQ) == HIGH ? 0 : 1);
}
int16_t BrewPiTouch::getXRaw() {
return filterX.readInput();
}
int16_t BrewPiTouch::getYRaw() {
return filterY.readInput();
}
int16_t BrewPiTouch::getX() {
int32_t val = getXRaw(); // create room for multiplication
val -= xOffset; // remove offset
val = val * tftWidth / width; //scale
return val;
}
int16_t BrewPiTouch::getY() {
int32_t val = getYRaw(); // create room for multiplication
val -= yOffset; // remove offset
val = val * tftHeight / height; //scale
return val;
}
/*
* update() updates the x and y coordinates of the touch screen
* It reads numSamples values and takes the median
* The result is fed to the low pass filters
*/
bool BrewPiTouch::update(uint16_t numSamples) {
std::vector<int16_t> samplesX;
std::vector<int16_t> samplesY;
_spi.begin();
bool valid = true;
for (uint16_t i = 0; i < numSamples; i++) {
if (!isTouched()) {
valid = false;
break;
}
pinMode(pinIRQ, OUTPUT); // reverse bias diode during conversion
digitalWrite(pinIRQ, LOW); // as recommended in SBAA028
_spi.transfer((config & CHMASK) | CHX); // select channel x
samplesX.push_back(readChannel());
_spi.transfer((config & CHMASK) | CHY); // select channel y
samplesY.push_back(readChannel());
pinMode(pinIRQ, INPUT); // Set back to input
}
if (valid) {
// get median
size_t middle = samplesX.size() / 2;
std::nth_element(samplesX.begin(), samplesX.begin() + middle, samplesX.end());
std::nth_element(samplesY.begin(), samplesY.begin() + middle, samplesY.end());
// feed to filter to check stability
filterX.add(samplesX[middle]);
filterY.add(samplesY[middle]);
}
_spi.end();
return valid && isStable();
}
void BrewPiTouch::setStabilityThreshold(int16_t threshold){
stabilityThreshold = threshold;
}
/* isStable() returns true if the difference between the last sample and
* a low pass filtered value of past samples is under a certain threshold
*/
bool BrewPiTouch::isStable() {
if (abs(filterX.readInput() - filterX.readOutput()) > stabilityThreshold) {
return false;
}
if (abs(filterY.readInput() - filterY.readOutput()) > stabilityThreshold) {
return false;
}
return true;
}
/*
void BrewPiTouch::calibrate(Adafruit_ILI9341 * tft) {
int32_t xTouch[3];
int32_t yTouch[3];
tftWidth = tft->width();
tftHeight = tft->height();
int32_t xDisplay[3] = {CALIBRATE_FROM_EDGE, CALIBRATE_FROM_EDGE, tftWidth - CALIBRATE_FROM_EDGE};
int32_t yDisplay[3] = {CALIBRATE_FROM_EDGE, tftHeight - CALIBRATE_FROM_EDGE, tftHeight / 2};
volatile int16_t samples;
const int16_t requiredSamples = 1024;
tft->fillScreen(ILI9341_BLACK);
for (uint8_t i = 0; i < 3; i++) {
tft->drawCrossHair(xDisplay[i], yDisplay[i], 10, ILI9341_GREEN);
while (!isTouched()); // wait for touch
do {
samples = 0;
xTouch[i] = 0;
yTouch[i] = 0;
tft->drawFastHLine(0, 0, tftWidth, ILI9341_RED);
while (isTouched()) {
update();
if (!isStable()) {
// update is not valid, reset
break;
}
int32_t xSample = getXRaw();
int32_t ySample = getYRaw();
xTouch[i] += xSample;
yTouch[i] += ySample;
samples++;
int32_t xAverage = xTouch[i] / samples;
int32_t yAverage = yTouch[i] / samples;
int16_t xCalibrated = getX();
int16_t yCalibrated = getY();
tft->fillCircle(xCalibrated, yCalibrated, 2, ILI9341_WHITE);
// print progress line
uint16_t progress = samples * tftWidth / requiredSamples;
tft->drawFastHLine(0, 0, progress, ILI9341_BLUE);
// stop when required number of samples is reached
if (samples >= requiredSamples) {
tft->drawFastHLine(0, 0, tftWidth, ILI9341_GREEN);
tft->fillCircle(xDisplay[i], yDisplay[i], 8, ILI9341_BLUE);
while (isTouched()); // wait until released
break;
}
if (abs(xSample - xAverage) > 50 || abs(ySample - yAverage) > 50) {
// if new sample deviates too much from average, reset
break;
}
}
} while (samples < requiredSamples || isTouched());
xTouch[i] = xTouch[i] / samples;
yTouch[i] = yTouch[i] / samples;
}
width = tftWidth * (xTouch[2] - xTouch[0]) / (xDisplay[2] - xDisplay[0]);
height = tftHeight * (yTouch[1] - yTouch[0]) / (yDisplay[1] - yDisplay[0]);
xOffset = xTouch[0] - xDisplay[0] * width / tftWidth;
yOffset = yTouch[0] - yDisplay[0] * height / tftHeight;
}
*/
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// UI.cc
//------------------------------------------------------------------------------
#include "UI.h"
#include "yakc_app/Util.h"
#include "MemoryWindow.h"
#include "MemoryMapWindow.h"
#include "DebugWindow.h"
#include "DisasmWindow.h"
#include "PIOWindow.h"
#include "CTCWindow.h"
#include "ModuleWindow.h"
#include "KeyboardWindow.h"
#include "LoadWindow.h"
#include "Time/Clock.h"
#include "Input/Input.h"
#include "Core/String/StringBuilder.h"
#include "yakc_roms/roms.h"
using namespace Oryol;
using namespace yakc;
const ImVec4 UI::ColorText = ImColor(255, 255, 255).Value;
const ImVec4 UI::ColorDetail = ImColor(164, 17, 6).Value;
const ImVec4 UI::ColorDetailBright = ImColor(230, 17, 6).Value;
const ImVec4 UI::ColorDetailDark = ImColor(94, 17, 6).Value;
const ImVec4 UI::ColorBackground = ImColor(32, 32, 32).Value;
const ImVec4 UI::ColorBackgroundLight = ImColor(96, 96, 96).Value;
//------------------------------------------------------------------------------
void
UI::Setup(kc85& kc) {
IMUI::Setup();
ImGuiStyle& style = ImGui::GetStyle();
style.WindowRounding = 0.0f;
style.Alpha = 1.0f;
style.WindowFillAlphaDefault = 1.0f;
style.WindowTitleAlign = ImGuiAlign_Center;
style.TouchExtraPadding = ImVec2(5.0f, 5.0f);
style.AntiAliasedLines = false;
style.AntiAliasedShapes = false;
/*
style.Colors[ImGuiCol_Text] = ColorText;
style.Colors[ImGuiCol_Border] = ColorDetail;
style.Colors[ImGuiCol_TitleBg] = ColorDetail;
style.Colors[ImGuiCol_FrameBg] = ColorBackgroundLight;
style.Colors[ImGuiCol_FrameBgHovered] = ColorDetail;
style.Colors[ImGuiCol_FrameBgActive] = ColorDetail;
style.Colors[ImGuiCol_WindowBg] = ColorBackground;
style.Colors[ImGuiCol_ChildWindowBg] = ColorBackground;
style.Colors[ImGuiCol_TitleBgActive] = ColorDetail;
style.Colors[ImGuiCol_MenuBarBg] = ColorDetail;
style.Colors[ImGuiCol_CheckMark] = ColorDetailBright;
style.Colors[ImGuiCol_SliderGrab] = ColorDetail;
style.Colors[ImGuiCol_SliderGrabActive] = ColorDetail;
style.Colors[ImGuiCol_Button] = ColorDetail;
style.Colors[ImGuiCol_ButtonHovered] = ColorDetailBright;
style.Colors[ImGuiCol_ButtonActive] = ColorDetailDark;
style.Colors[ImGuiCol_ScrollbarBg] = ColorBackgroundLight;
style.Colors[ImGuiCol_ScrollbarGrab] = ColorDetail;
style.Colors[ImGuiCol_ScrollbarGrabHovered] = ColorDetailBright;
style.Colors[ImGuiCol_ScrollbarGrabActive] = ColorDetailBright;
*/
this->fileLoader.Setup(kc);
this->curTime = Clock::Now();
}
//------------------------------------------------------------------------------
void
UI::Discard() {
this->fileLoader.Discard();
this->windows.Clear();
IMUI::Discard();
}
//------------------------------------------------------------------------------
void
UI::Toggle() {
this->uiEnabled = !this->uiEnabled;
}
//------------------------------------------------------------------------------
void
UI::OpenWindow(kc85& kc, const Ptr<WindowBase>& win) {
win->Setup(kc);
this->windows.Add(win);
}
//------------------------------------------------------------------------------
void
UI::OnFrame(kc85& kc) {
IMUI::NewFrame(Clock::LapTime(this->curTime));
if (this->uiEnabled) {
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu(kc.model() == kc85_model::kc85_3 ? "KC85/3":"KC85/4")) {
if (ImGui::MenuItem("Load File...")) {
auto loadWindow = LoadWindow::Create();
loadWindow->SetFileLoader(&this->fileLoader);
this->OpenWindow(kc, loadWindow);
}
if (ImGui::MenuItem("Power Cycle")) {
kc.switchoff();
kc.switchon(kc.model(), kc.caos_rom(), kc.caos_rom_size());
}
if (ImGui::MenuItem("Reset")) {
kc.reset();
}
if (ImGui::BeginMenu("KC 85/3")) {
if (ImGui::MenuItem("CAOS 3.1")) {
kc.switchoff();
kc.switchon(kc85_model::kc85_3, dump_caos31, sizeof(dump_caos31));
}
ImGui::EndMenu();
}
if (ImGui::MenuItem("KC85/4 (TODO)")) {
// FIXME
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Hardware")) {
if (ImGui::MenuItem("Keyboard")) {
this->OpenWindow(kc, KeyboardWindow::Create());
}
if (ImGui::MenuItem("Expansion Slots")) {
this->OpenWindow(kc, ModuleWindow::Create());
}
if (ImGui::MenuItem("Memory Map")) {
this->OpenWindow(kc, MemoryMapWindow::Create());
}
if (ImGui::MenuItem("Z80 PIO")) {
this->OpenWindow(kc, PIOWindow::Create());
}
if (ImGui::MenuItem("Z80 CTC")) {
this->OpenWindow(kc, CTCWindow::Create());
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Debugging")) {
if (ImGui::MenuItem("Debugger")) {
this->OpenWindow(kc, DebugWindow::Create());
}
if (ImGui::MenuItem("Disassembler")) {
this->OpenWindow(kc, DisasmWindow::Create());
}
if (ImGui::MenuItem("Memory Editor")) {
this->OpenWindow(kc, MemoryWindow::Create());
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Settings")) {
if (ImGui::MenuItem("CRT Effect", nullptr, this->Settings.crtEffect)) {
this->Settings.crtEffect = !this->Settings.crtEffect;
}
if (ImGui::MenuItem("Color TV", nullptr, this->Settings.colorTV)) {
this->Settings.colorTV = !this->Settings.colorTV;
}
ImGui::SliderFloat("CRT Warp", &this->Settings.crtWarp, 0.0f, 1.0f/16.0f);
ImGui::SliderInt("CPU Speed", &this->Settings.cpuSpeed, 1, 8, "%.0fx");
if (ImGui::MenuItem("Reset To Defaults")) {
this->Settings = settings();
}
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
// draw open windows
for (auto& win : this->windows) {
win->Draw(kc);
}
}
else {
// if UI is disabled, draw a simple overlay with help on how to toggle UI
if (helpOpen) {
ImGui::SetNextWindowPosCenter();
if (ImGui::Begin("Help", &this->helpOpen, ImVec2(0,0), 0.75f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize))
{
ImGui::Text("Press TAB or double-tap to toggle UI!");
ImGui::Dummy(ImVec2(96,0)); ImGui::SameLine();
if (ImGui::Button("Got it!")) {
this->helpOpen = false;
}
}
ImGui::End();
}
}
ImGui::Render();
// delete closed windows
for (int i = this->windows.Size() - 1; i >= 0; i--) {
if (!this->windows[i]->Visible) {
this->windows.Erase(i);
}
}
}
<commit_msg>Added a quickstart menu for games<commit_after>//------------------------------------------------------------------------------
// UI.cc
//------------------------------------------------------------------------------
#include "UI.h"
#include "yakc_app/Util.h"
#include "MemoryWindow.h"
#include "MemoryMapWindow.h"
#include "DebugWindow.h"
#include "DisasmWindow.h"
#include "PIOWindow.h"
#include "CTCWindow.h"
#include "ModuleWindow.h"
#include "KeyboardWindow.h"
#include "LoadWindow.h"
#include "Time/Clock.h"
#include "Input/Input.h"
#include "Core/String/StringBuilder.h"
#include "yakc_roms/roms.h"
using namespace Oryol;
using namespace yakc;
const ImVec4 UI::ColorText = ImColor(255, 255, 255).Value;
const ImVec4 UI::ColorDetail = ImColor(164, 17, 6).Value;
const ImVec4 UI::ColorDetailBright = ImColor(230, 17, 6).Value;
const ImVec4 UI::ColorDetailDark = ImColor(94, 17, 6).Value;
const ImVec4 UI::ColorBackground = ImColor(32, 32, 32).Value;
const ImVec4 UI::ColorBackgroundLight = ImColor(96, 96, 96).Value;
//------------------------------------------------------------------------------
void
UI::Setup(kc85& kc) {
IMUI::Setup();
ImGuiStyle& style = ImGui::GetStyle();
style.WindowRounding = 0.0f;
style.Alpha = 1.0f;
style.WindowFillAlphaDefault = 1.0f;
style.WindowTitleAlign = ImGuiAlign_Center;
style.TouchExtraPadding = ImVec2(5.0f, 5.0f);
style.AntiAliasedLines = false;
style.AntiAliasedShapes = false;
/*
style.Colors[ImGuiCol_Text] = ColorText;
style.Colors[ImGuiCol_Border] = ColorDetail;
style.Colors[ImGuiCol_TitleBg] = ColorDetail;
style.Colors[ImGuiCol_FrameBg] = ColorBackgroundLight;
style.Colors[ImGuiCol_FrameBgHovered] = ColorDetail;
style.Colors[ImGuiCol_FrameBgActive] = ColorDetail;
style.Colors[ImGuiCol_WindowBg] = ColorBackground;
style.Colors[ImGuiCol_ChildWindowBg] = ColorBackground;
style.Colors[ImGuiCol_TitleBgActive] = ColorDetail;
style.Colors[ImGuiCol_MenuBarBg] = ColorDetail;
style.Colors[ImGuiCol_CheckMark] = ColorDetailBright;
style.Colors[ImGuiCol_SliderGrab] = ColorDetail;
style.Colors[ImGuiCol_SliderGrabActive] = ColorDetail;
style.Colors[ImGuiCol_Button] = ColorDetail;
style.Colors[ImGuiCol_ButtonHovered] = ColorDetailBright;
style.Colors[ImGuiCol_ButtonActive] = ColorDetailDark;
style.Colors[ImGuiCol_ScrollbarBg] = ColorBackgroundLight;
style.Colors[ImGuiCol_ScrollbarGrab] = ColorDetail;
style.Colors[ImGuiCol_ScrollbarGrabHovered] = ColorDetailBright;
style.Colors[ImGuiCol_ScrollbarGrabActive] = ColorDetailBright;
*/
this->fileLoader.Setup(kc);
this->curTime = Clock::Now();
}
//------------------------------------------------------------------------------
void
UI::Discard() {
this->fileLoader.Discard();
this->windows.Clear();
IMUI::Discard();
}
//------------------------------------------------------------------------------
void
UI::Toggle() {
this->uiEnabled = !this->uiEnabled;
}
//------------------------------------------------------------------------------
void
UI::OpenWindow(kc85& kc, const Ptr<WindowBase>& win) {
win->Setup(kc);
this->windows.Add(win);
}
//------------------------------------------------------------------------------
void
UI::OnFrame(kc85& kc) {
IMUI::NewFrame(Clock::LapTime(this->curTime));
if (this->uiEnabled) {
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu(kc.model() == kc85_model::kc85_3 ? "KC85/3":"KC85/4")) {
if (ImGui::MenuItem("Load File...")) {
auto loadWindow = LoadWindow::Create();
loadWindow->SetFileLoader(&this->fileLoader);
this->OpenWindow(kc, loadWindow);
}
if (ImGui::MenuItem("Power Cycle")) {
kc.switchoff();
kc.switchon(kc.model(), kc.caos_rom(), kc.caos_rom_size());
}
if (ImGui::MenuItem("Reset")) {
kc.reset();
}
if (ImGui::BeginMenu("KC 85/3")) {
if (ImGui::MenuItem("CAOS 3.1")) {
kc.switchoff();
kc.switchon(kc85_model::kc85_3, dump_caos31, sizeof(dump_caos31));
}
ImGui::EndMenu();
}
if (ImGui::MenuItem("KC85/4 (TODO)")) {
// FIXME
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Games")) {
for (const auto& item : this->fileLoader.Items) {
if (ImGui::MenuItem(item.Name.AsCStr())) {
this->fileLoader.LoadAndStart(kc, item);
}
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Hardware")) {
if (ImGui::MenuItem("Keyboard")) {
this->OpenWindow(kc, KeyboardWindow::Create());
}
if (ImGui::MenuItem("Expansion Slots")) {
this->OpenWindow(kc, ModuleWindow::Create());
}
if (ImGui::MenuItem("Memory Map")) {
this->OpenWindow(kc, MemoryMapWindow::Create());
}
if (ImGui::MenuItem("Z80 PIO")) {
this->OpenWindow(kc, PIOWindow::Create());
}
if (ImGui::MenuItem("Z80 CTC")) {
this->OpenWindow(kc, CTCWindow::Create());
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Debugging")) {
if (ImGui::MenuItem("Debugger")) {
this->OpenWindow(kc, DebugWindow::Create());
}
if (ImGui::MenuItem("Disassembler")) {
this->OpenWindow(kc, DisasmWindow::Create());
}
if (ImGui::MenuItem("Memory Editor")) {
this->OpenWindow(kc, MemoryWindow::Create());
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Settings")) {
if (ImGui::MenuItem("CRT Effect", nullptr, this->Settings.crtEffect)) {
this->Settings.crtEffect = !this->Settings.crtEffect;
}
if (ImGui::MenuItem("Color TV", nullptr, this->Settings.colorTV)) {
this->Settings.colorTV = !this->Settings.colorTV;
}
ImGui::SliderFloat("CRT Warp", &this->Settings.crtWarp, 0.0f, 1.0f/16.0f);
ImGui::SliderInt("CPU Speed", &this->Settings.cpuSpeed, 1, 8, "%.0fx");
if (ImGui::MenuItem("Reset To Defaults")) {
this->Settings = settings();
}
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
// draw open windows
for (auto& win : this->windows) {
win->Draw(kc);
}
}
else {
// if UI is disabled, draw a simple overlay with help on how to toggle UI
if (helpOpen) {
ImGui::SetNextWindowPosCenter();
if (ImGui::Begin("Help", &this->helpOpen, ImVec2(0,0), 0.75f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize))
{
ImGui::Text("Press TAB or double-tap to toggle UI!");
ImGui::Dummy(ImVec2(96,0)); ImGui::SameLine();
if (ImGui::Button("Got it!")) {
this->helpOpen = false;
}
}
ImGui::End();
}
}
ImGui::Render();
// delete closed windows
for (int i = this->windows.Size() - 1; i >= 0; i--) {
if (!this->windows[i]->Visible) {
this->windows.Erase(i);
}
}
}
<|endoftext|> |
<commit_before>/*
* This file is part of telepathy-accounts-kcm
*
* Copyright (C) 2009 Collabora Ltd. <[email protected]>
* Copyright (C) 2011 Thomas Richard <[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "profile-list-model.h"
#include "profile-item.h"
#include <TelepathyQt/Feature>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/ProfileManager>
#include <TelepathyQt/PendingStringList>
#include <KDebug>
#include <KIcon>
ProfileListModel::ProfileListModel(QObject *parent)
: QAbstractListModel(parent)
{
m_profileItems.clear();
m_profileManager = Tp::ProfileManager::create(QDBusConnection::sessionBus());
// FIXME: Until all distros ship correct profile files, we should fake them
connect(m_profileManager->becomeReady(Tp::Features() << Tp::ProfileManager::FeatureFakeProfiles),
SIGNAL(finished(Tp::PendingOperation*)),
this,
SLOT(onProfileManagerReady(Tp::PendingOperation*)));
}
ProfileListModel::~ProfileListModel()
{
}
void ProfileListModel::onProfileManagerReady(Tp::PendingOperation *op)
{
// Check the pending operation completed successfully.
if (op->isError()) {
kDebug() << "becomeReady() failed:" << op->errorName() << op->errorMessage();
return;
}
Tp::PendingStringList* pendingNames = Tp::ConnectionManager::listNames();
connect(pendingNames, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onConnectionManagerNamesFetched(Tp::PendingOperation*)));
}
int ProfileListModel::rowCount(const QModelIndex &index) const
{
// If the index is the root item, then return the row count.
if (index == QModelIndex()) {
return m_profileItems.size();
}
// Otherwise, return 0 (as this is a list model, so all items
// are children of the root item).
return 0;
}
QVariant ProfileListModel::data(const QModelIndex &index, int role) const
{
// FIXME: This is a basic implementation just so I can see what's going
// on while developing this code further. Needs expanding.
QVariant data;
switch (role) {
case Qt::DisplayRole:
data = QVariant(m_profileItems.at(index.row())->localizedName());
break;
case Qt::DecorationRole:
data = QVariant(m_profileItems.at(index.row())->icon());
break;
case ProfileListModel::ProfileProtocolNameRole:
data = QVariant(m_profileItems.at(index.row())->protocolName());
break;
case ProfileListModel::ProfileCmNameRole:
data = QVariant(m_profileItems.at(index.row())->cmName());
break;
default:
break;
}
return data;
}
ProfileItem *ProfileListModel::itemForIndex(const QModelIndex &index) const
{
return m_profileItems.at(index.row());
}
ProfileItem *ProfileListModel::itemForService(const QString &serviceName) const
{
Q_FOREACH (ProfileItem *profileItem, m_profileItems) {
if (profileItem->serviceName() == serviceName) {
return profileItem;
}
}
return 0;
}
bool ProfileListModel::hasNonFakeProfile(const Tp::ProfilePtr& profile, const QList<Tp::ProfilePtr> &profiles) const
{
//loop through all profiles, and look for a non autogenerated profile which matches this name.
Q_FOREACH (const Tp::ProfilePtr &otherProfile, profiles) {
if (profile->protocolName() == otherProfile->protocolName() && !otherProfile->isFake()) {
// check if this profile is for a special service or for this protocol in general
if (otherProfile->serviceName() == otherProfile->cmName().append(QLatin1Char('-')).append(otherProfile->protocolName())
|| otherProfile->serviceName() == otherProfile->protocolName()) {
//check we have a valid CM for the non-fake profile
if (m_connectionManagerNames.contains(otherProfile->cmName())) {
return true;
}
}
}
}
return false;
}
void ProfileListModel::populateList()
{
Q_FOREACH (ProfileItem *item, m_profileItems) {
delete item;
item = 0;
}
m_profileItems.clear();
QList<Tp::ProfilePtr> profiles = m_profileManager->profiles();
QList<ProfileItem*> insertItems;
Q_FOREACH (const Tp::ProfilePtr &profile, profiles) {
if (profile->isFake()) {
if (hasNonFakeProfile(profile, profiles)) {
continue;
}
}
//don't include profiles which we don't have a CM for
if (! m_connectionManagerNames.contains(profile->cmName())) {
continue;
}
insertItems.append(new ProfileItem(profile, this));
}
if (insertItems.size() > 0) {
beginInsertRows(QModelIndex(), 0, insertItems.size()-1);
m_profileItems.append(insertItems);
endInsertRows();
} else {
return;
}
}
void ProfileListModel::onConnectionManagerNamesFetched(Tp::PendingOperation *operation)
{
Tp::PendingStringList* connectionManagerNamesOperation = qobject_cast<Tp::PendingStringList*>(operation);
Q_ASSERT(connectionManagerNamesOperation);
m_connectionManagerNames = connectionManagerNamesOperation->result();
populateList();
}
#include "profile-list-model.moc"
<commit_msg>Disable creation of IRC accounts in the GUI<commit_after>/*
* This file is part of telepathy-accounts-kcm
*
* Copyright (C) 2009 Collabora Ltd. <[email protected]>
* Copyright (C) 2011 Thomas Richard <[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "profile-list-model.h"
#include "profile-item.h"
#include <TelepathyQt/Feature>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/ProfileManager>
#include <TelepathyQt/PendingStringList>
#include <KDebug>
#include <KIcon>
ProfileListModel::ProfileListModel(QObject *parent)
: QAbstractListModel(parent)
{
m_profileItems.clear();
m_profileManager = Tp::ProfileManager::create(QDBusConnection::sessionBus());
// FIXME: Until all distros ship correct profile files, we should fake them
connect(m_profileManager->becomeReady(Tp::Features() << Tp::ProfileManager::FeatureFakeProfiles),
SIGNAL(finished(Tp::PendingOperation*)),
this,
SLOT(onProfileManagerReady(Tp::PendingOperation*)));
}
ProfileListModel::~ProfileListModel()
{
}
void ProfileListModel::onProfileManagerReady(Tp::PendingOperation *op)
{
// Check the pending operation completed successfully.
if (op->isError()) {
kDebug() << "becomeReady() failed:" << op->errorName() << op->errorMessage();
return;
}
Tp::PendingStringList* pendingNames = Tp::ConnectionManager::listNames();
connect(pendingNames, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onConnectionManagerNamesFetched(Tp::PendingOperation*)));
}
int ProfileListModel::rowCount(const QModelIndex &index) const
{
// If the index is the root item, then return the row count.
if (index == QModelIndex()) {
return m_profileItems.size();
}
// Otherwise, return 0 (as this is a list model, so all items
// are children of the root item).
return 0;
}
QVariant ProfileListModel::data(const QModelIndex &index, int role) const
{
// FIXME: This is a basic implementation just so I can see what's going
// on while developing this code further. Needs expanding.
QVariant data;
switch (role) {
case Qt::DisplayRole:
data = QVariant(m_profileItems.at(index.row())->localizedName());
break;
case Qt::DecorationRole:
data = QVariant(m_profileItems.at(index.row())->icon());
break;
case ProfileListModel::ProfileProtocolNameRole:
data = QVariant(m_profileItems.at(index.row())->protocolName());
break;
case ProfileListModel::ProfileCmNameRole:
data = QVariant(m_profileItems.at(index.row())->cmName());
break;
default:
break;
}
return data;
}
ProfileItem *ProfileListModel::itemForIndex(const QModelIndex &index) const
{
return m_profileItems.at(index.row());
}
ProfileItem *ProfileListModel::itemForService(const QString &serviceName) const
{
Q_FOREACH (ProfileItem *profileItem, m_profileItems) {
if (profileItem->serviceName() == serviceName) {
return profileItem;
}
}
return 0;
}
bool ProfileListModel::hasNonFakeProfile(const Tp::ProfilePtr& profile, const QList<Tp::ProfilePtr> &profiles) const
{
//loop through all profiles, and look for a non autogenerated profile which matches this name.
Q_FOREACH (const Tp::ProfilePtr &otherProfile, profiles) {
if (profile->protocolName() == otherProfile->protocolName() && !otherProfile->isFake()) {
// check if this profile is for a special service or for this protocol in general
if (otherProfile->serviceName() == otherProfile->cmName().append(QLatin1Char('-')).append(otherProfile->protocolName())
|| otherProfile->serviceName() == otherProfile->protocolName()) {
//check we have a valid CM for the non-fake profile
if (m_connectionManagerNames.contains(otherProfile->cmName())) {
return true;
}
}
}
}
return false;
}
void ProfileListModel::populateList()
{
Q_FOREACH (ProfileItem *item, m_profileItems) {
delete item;
item = 0;
}
m_profileItems.clear();
QList<Tp::ProfilePtr> profiles = m_profileManager->profiles();
QList<ProfileItem*> insertItems;
Q_FOREACH (const Tp::ProfilePtr &profile, profiles) {
if (profile->isFake()) {
if (hasNonFakeProfile(profile, profiles)) {
continue;
}
}
//don't include profiles which we don't have a CM for
if (! m_connectionManagerNames.contains(profile->cmName())) {
continue;
}
//Hide all IRC accounts
//this is a deliberate decision from Akademy meeting 2012
//"no, we don't support IRC", it's a different usage and in order to have a semi-decent IRC experience
//we need to add a lot more that we simply don't have resources to do.
//It's a better user experience to learn how to use a different app than to try using this.
//Remove this "continue" to re-enable IRC support, for personal reasons or hacking
//this topic can be discussed again as of July 2013
if(profile->serviceName() == QLatin1String("irc")) {
continue;
}
insertItems.append(new ProfileItem(profile, this));
}
if (insertItems.size() > 0) {
beginInsertRows(QModelIndex(), 0, insertItems.size()-1);
m_profileItems.append(insertItems);
endInsertRows();
} else {
return;
}
}
void ProfileListModel::onConnectionManagerNamesFetched(Tp::PendingOperation *operation)
{
Tp::PendingStringList* connectionManagerNamesOperation = qobject_cast<Tp::PendingStringList*>(operation);
Q_ASSERT(connectionManagerNamesOperation);
m_connectionManagerNames = connectionManagerNamesOperation->result();
populateList();
}
#include "profile-list-model.moc"
<|endoftext|> |
<commit_before><commit_msg>no mkdtemp on AIX either<commit_after><|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCDataList.h
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCDataList
//
// -------------------------------------------------------------------------
#include <cstdarg>
#include "NFCDataList.h"
#include "NFIDataList.h"
NFCDataList::NFCDataList()
: NFIDataList()
{
}
NFCDataList::NFCDataList(const char* str, const char* strSplit)
{
Clear();
Split(str, strSplit);
}
NFCDataList::NFCDataList(const NFCDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
}
NFCDataList::NFCDataList(const NFIDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
}
NFCDataList::~NFCDataList()
{
Clear();
};
/*
NFCDataList& NFCDataList::operator=(const NFCDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
return *this;
}
NFCDataList& NFCDataList::operator=(const NFIDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
return *this;
}
*/
//
bool NFCDataList::Append(const NFIDataList& src, const int start, const int count)
{
if (start >= src.GetCount())
{
return false;
}
int end = start + count;
if (end > src.GetCount())
{
return false;
}
InnerAppendEx(src, start, end);
return true;
}
bool NFCDataList::Append(const NFIDataList::TData& TData)
{
if (TData.nType <= TDATA_UNKNOWN
|| TData.nType >= TDATA_MAX)
{
return false;
}
switch (TData.nType)
{
case TDATA_INT:
case TDATA_FLOAT:
case TDATA_DOUBLE:
case TDATA_OBJECT:
{
AddValue(TData.nType, TData.variantData);
}
break;
case TDATA_STRING:
{
const std::string& strData = boost::get<std::string>(TData.variantData);
AddString(strData);
}
break;
default:
break;
}
return false;
}
bool NFCDataList::Append( const NFIDataList& src )
{
return Append(src, 0, src.GetCount());
}
bool NFCDataList::Add(const NFINT64 value)
{
return NFIDataList::AddValue<NFINT64>(TDATA_INT, value);
}
bool NFCDataList::Add(const float value)
{
return AddValue<float>(TDATA_FLOAT, value);
}
bool NFCDataList::Add(const double value)
{
return AddValue<double>(TDATA_DOUBLE, value);
}
bool NFCDataList::Add(const char* value)
{
return AddValue<std::string>(TDATA_STRING, std::string(value));
}
bool NFCDataList::Add(const std::string& value)
{
return AddValue<std::string>(TDATA_STRING, value);
}
bool NFCDataList::Add(const NFIDENTID& value)
{
return AddValue<NFIDENTID>(TDATA_OBJECT, value);
}
bool NFCDataList::Add(const void* value)
{
//return AddNumber<const void*>(TDATA_POINTER, value);
return true;
}
bool NFCDataList::Set(const int index, const NFINT64 value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const float value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const double value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const char* value)
{
if (index < GetCount() && index > 0)
{
return SetString(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const NFIDENTID& value)
{
if (index < GetCount() && index >= 0)
{
return SetValue<NFIDENTID>(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const void* value)
{
if (index < GetCount() && index >= 0)
{
//return SetNumber(index, value);
}
return false;
}
NFINT64 NFCDataList::Int(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<NFINT64>(index);
}
return 0;
}
float NFCDataList::Float(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<float>(index);
}
return 0.0f;
}
double NFCDataList::Double(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<double>(index);
}
return 0.0f;
}
const std::string& NFCDataList::String(const int index) const
{
if (index < GetCount() && index >= 0)
{
const NF_SHARE_PTR<TData> var = mvList[index];
if (var && TDATA_STRING == var->nType)
{
return boost::get<const std::string&>(var->variantData);
}
}
return NULL_STR;
}
NFIDENTID NFCDataList::Object(const int index) const
{
// if (index < GetCount() && index >= 0)
// {
// return NumberVal<NFIDENTID>(index);
// }
if (index < GetCount() && index >= 0)
{
NFIDENTID result;
if (index < GetCount() && index >= 0)
{
TDATA_TYPE type = Type(index);
if (type == TDATA_OBJECT)
{
NF_SHARE_PTR<TData> var = GetStack(index);
result = boost::get<NFIDENTID>(var->variantData);
}
}
return result;
}
return NFIDENTID();
}
void* NFCDataList::Pointer(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<void*>(index);
}
return NULL;
}
bool NFCDataList::Split(const char* str, const char* strSplit)
{
Clear();
std::string strData(str);
if (strData.empty())
{
return true;
}
std::string temstrSplit(strSplit);
std::string::size_type pos;
strData += temstrSplit;
std::string::size_type size = strData.length();
for (std::string::size_type i = 0; i < size; i++)
{
pos = int(strData.find(temstrSplit, i));
if (pos < size)
{
std::string strSub = strData.substr(i, pos - i);
Add(strSub.c_str());
i = pos + temstrSplit.size() - 1;
}
}
return true;
}
TDATA_TYPE NFCDataList::Type(const int index) const
{
if (index >= GetCount() || index < 0)
{
return TDATA_UNKNOWN;
}
if (index < STACK_SIZE)
{
return mvList[index]->nType;
}
else
{
const NF_SHARE_PTR<TData> pData = GetStack(index);
if (pData)
{
return pData->nType;
}
}
return TDATA_UNKNOWN;
}
bool NFCDataList::TypeEx(const int nType, ...) const
{
bool bRet = true;
if (TDATA_UNKNOWN == nType)
{
bRet = false;
return bRet;
}
TDATA_TYPE pareType = (TDATA_TYPE)nType;
va_list arg_ptr;
va_start(arg_ptr, nType);
int index = 0;
while (pareType != TDATA_UNKNOWN)
{
//Ƚ
TDATA_TYPE varType = Type(index);
if (varType != pareType)
{
bRet = false;
break;
}
++index;
pareType = (TDATA_TYPE)va_arg(arg_ptr, int); //ȡһ
}
va_end(arg_ptr); //
return bRet;
}
bool NFCDataList::Concat(const NFIDataList& src)
{
InnerAppendEx(src, 0, src.GetCount());
return true;
}
void NFCDataList::Clear()
{
mnUseSize = 0;
//mnCapacity = STACK_SIZE;
//8Ժ
if (mvList.size() > STACK_SIZE)
{
for (int i = 0; i < STACK_SIZE; ++i)
{
mvList[i]->nType = TDATA_UNKNOWN;
}
mvList.erase(mvList.begin() + 8, mvList.end());
}
}
bool NFCDataList::IsEmpty() const
{
return (0 == mnUseSize);
}
int NFCDataList::GetCount() const
{
return mnUseSize;
}
void NFCDataList::InnerAppendEx(const NFIDataList& src, const int start, const int end)
{
for (int i = start; i < end; ++i)
{
TDATA_TYPE vType = src.Type(i);
switch (vType)
{
case TDATA_INT:
AddValue<NFINT64>(vType, src.Int(i));
break;
case TDATA_FLOAT:
AddValue<float>(vType, src.Float(i));
break;
case TDATA_DOUBLE:
AddValue<double>(vType, src.Double(i));
break;
case TDATA_STRING:
AddString(src.String(i).c_str());
break;
case TDATA_OBJECT:
AddValue<NFIDENTID>(vType, src.Object(i));
break;
//case TDATA_POINTER:
// AddNumber<void*>(vType, src.NumberVal<void*>(i));
// break;
default:
//Assert(0);
break;
}
}
}
std::string NFCDataList::StringValEx(const int index, const bool bForce) const
{
if (index < GetCount() && index >= 0)
{
TDATA_TYPE type = Type(index);
if (type == TDATA_STRING)
{
return String(index);
}
// const NF_SHARE_PTR<NFIDataList::TData> var = GetStack(index);
// if (var)
// {
// //return boost::lexical_cast<std::string>(var->variantData);
// }
}
return NULL_STR;
}
bool NFCDataList::ToString(std::string& str, const char* strSplit) const
{
for (int i = 0; i < GetCount(); ++i)
{
std::string strVal = StringValEx(i, true);
str += strVal;
str += strSplit;
}
std::string strTempSplit(strSplit);
std::string::size_type nPos = str.rfind(strSplit);
if (nPos == str.length() - strTempSplit.length())
{
str = str.substr(0, nPos);
}
return true;
}
<commit_msg>fixed bug for set data<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCDataList.h
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCDataList
//
// -------------------------------------------------------------------------
#include <cstdarg>
#include "NFCDataList.h"
#include "NFIDataList.h"
NFCDataList::NFCDataList()
: NFIDataList()
{
}
NFCDataList::NFCDataList(const char* str, const char* strSplit)
{
Clear();
Split(str, strSplit);
}
NFCDataList::NFCDataList(const NFCDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
}
NFCDataList::NFCDataList(const NFIDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
}
NFCDataList::~NFCDataList()
{
Clear();
};
/*
NFCDataList& NFCDataList::operator=(const NFCDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
return *this;
}
NFCDataList& NFCDataList::operator=(const NFIDataList& src)
{
Clear();
InnerAppendEx(src, 0, src.GetCount());
return *this;
}
*/
//
bool NFCDataList::Append(const NFIDataList& src, const int start, const int count)
{
if (start >= src.GetCount())
{
return false;
}
int end = start + count;
if (end > src.GetCount())
{
return false;
}
InnerAppendEx(src, start, end);
return true;
}
bool NFCDataList::Append(const NFIDataList::TData& TData)
{
if (TData.nType <= TDATA_UNKNOWN
|| TData.nType >= TDATA_MAX)
{
return false;
}
switch (TData.nType)
{
case TDATA_INT:
case TDATA_FLOAT:
case TDATA_DOUBLE:
case TDATA_OBJECT:
{
AddValue(TData.nType, TData.variantData);
}
break;
case TDATA_STRING:
{
const std::string& strData = boost::get<std::string>(TData.variantData);
AddString(strData);
}
break;
default:
break;
}
return false;
}
bool NFCDataList::Append( const NFIDataList& src )
{
return Append(src, 0, src.GetCount());
}
bool NFCDataList::Add(const NFINT64 value)
{
return NFIDataList::AddValue<NFINT64>(TDATA_INT, value);
}
bool NFCDataList::Add(const float value)
{
return AddValue<float>(TDATA_FLOAT, value);
}
bool NFCDataList::Add(const double value)
{
return AddValue<double>(TDATA_DOUBLE, value);
}
bool NFCDataList::Add(const char* value)
{
return AddValue<std::string>(TDATA_STRING, std::string(value));
}
bool NFCDataList::Add(const std::string& value)
{
return AddValue<std::string>(TDATA_STRING, value);
}
bool NFCDataList::Add(const NFIDENTID& value)
{
return AddValue<NFIDENTID>(TDATA_OBJECT, value);
}
bool NFCDataList::Add(const void* value)
{
//return AddNumber<const void*>(TDATA_POINTER, value);
return true;
}
bool NFCDataList::Set(const int index, const NFINT64 value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const float value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const double value)
{
if (index < GetCount() && index >= 0)
{
return SetValue(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const char* value)
{
if (index < GetCount() && index >= 0)
{
return SetString(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const NFIDENTID& value)
{
if (index < GetCount() && index >= 0)
{
return SetValue<NFIDENTID>(index, value);
}
return false;
}
bool NFCDataList::Set(const int index, const void* value)
{
if (index < GetCount() && index >= 0)
{
//return SetNumber(index, value);
}
return false;
}
NFINT64 NFCDataList::Int(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<NFINT64>(index);
}
return 0;
}
float NFCDataList::Float(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<float>(index);
}
return 0.0f;
}
double NFCDataList::Double(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<double>(index);
}
return 0.0f;
}
const std::string& NFCDataList::String(const int index) const
{
if (index < GetCount() && index >= 0)
{
const NF_SHARE_PTR<TData> var = mvList[index];
if (var && TDATA_STRING == var->nType)
{
return boost::get<const std::string&>(var->variantData);
}
}
return NULL_STR;
}
NFIDENTID NFCDataList::Object(const int index) const
{
// if (index < GetCount() && index >= 0)
// {
// return NumberVal<NFIDENTID>(index);
// }
if (index < GetCount() && index >= 0)
{
NFIDENTID result;
if (index < GetCount() && index >= 0)
{
TDATA_TYPE type = Type(index);
if (type == TDATA_OBJECT)
{
NF_SHARE_PTR<TData> var = GetStack(index);
result = boost::get<NFIDENTID>(var->variantData);
}
}
return result;
}
return NFIDENTID();
}
void* NFCDataList::Pointer(const int index) const
{
if (index < GetCount() && index >= 0)
{
return NumberVal<void*>(index);
}
return NULL;
}
bool NFCDataList::Split(const char* str, const char* strSplit)
{
Clear();
std::string strData(str);
if (strData.empty())
{
return true;
}
std::string temstrSplit(strSplit);
std::string::size_type pos;
strData += temstrSplit;
std::string::size_type size = strData.length();
for (std::string::size_type i = 0; i < size; i++)
{
pos = int(strData.find(temstrSplit, i));
if (pos < size)
{
std::string strSub = strData.substr(i, pos - i);
Add(strSub.c_str());
i = pos + temstrSplit.size() - 1;
}
}
return true;
}
TDATA_TYPE NFCDataList::Type(const int index) const
{
if (index >= GetCount() || index < 0)
{
return TDATA_UNKNOWN;
}
if (index < STACK_SIZE)
{
return mvList[index]->nType;
}
else
{
const NF_SHARE_PTR<TData> pData = GetStack(index);
if (pData)
{
return pData->nType;
}
}
return TDATA_UNKNOWN;
}
bool NFCDataList::TypeEx(const int nType, ...) const
{
bool bRet = true;
if (TDATA_UNKNOWN == nType)
{
bRet = false;
return bRet;
}
TDATA_TYPE pareType = (TDATA_TYPE)nType;
va_list arg_ptr;
va_start(arg_ptr, nType);
int index = 0;
while (pareType != TDATA_UNKNOWN)
{
//Ƚ
TDATA_TYPE varType = Type(index);
if (varType != pareType)
{
bRet = false;
break;
}
++index;
pareType = (TDATA_TYPE)va_arg(arg_ptr, int); //ȡһ
}
va_end(arg_ptr); //
return bRet;
}
bool NFCDataList::Concat(const NFIDataList& src)
{
InnerAppendEx(src, 0, src.GetCount());
return true;
}
void NFCDataList::Clear()
{
mnUseSize = 0;
//mnCapacity = STACK_SIZE;
//8Ժ
if (mvList.size() > STACK_SIZE)
{
for (int i = 0; i < STACK_SIZE; ++i)
{
mvList[i]->nType = TDATA_UNKNOWN;
}
mvList.erase(mvList.begin() + 8, mvList.end());
}
}
bool NFCDataList::IsEmpty() const
{
return (0 == mnUseSize);
}
int NFCDataList::GetCount() const
{
return mnUseSize;
}
void NFCDataList::InnerAppendEx(const NFIDataList& src, const int start, const int end)
{
for (int i = start; i < end; ++i)
{
TDATA_TYPE vType = src.Type(i);
switch (vType)
{
case TDATA_INT:
AddValue<NFINT64>(vType, src.Int(i));
break;
case TDATA_FLOAT:
AddValue<float>(vType, src.Float(i));
break;
case TDATA_DOUBLE:
AddValue<double>(vType, src.Double(i));
break;
case TDATA_STRING:
AddString(src.String(i).c_str());
break;
case TDATA_OBJECT:
AddValue<NFIDENTID>(vType, src.Object(i));
break;
//case TDATA_POINTER:
// AddNumber<void*>(vType, src.NumberVal<void*>(i));
// break;
default:
//Assert(0);
break;
}
}
}
std::string NFCDataList::StringValEx(const int index, const bool bForce) const
{
if (index < GetCount() && index >= 0)
{
TDATA_TYPE type = Type(index);
if (type == TDATA_STRING)
{
return String(index);
}
// const NF_SHARE_PTR<NFIDataList::TData> var = GetStack(index);
// if (var)
// {
// //return boost::lexical_cast<std::string>(var->variantData);
// }
}
return NULL_STR;
}
bool NFCDataList::ToString(std::string& str, const char* strSplit) const
{
for (int i = 0; i < GetCount(); ++i)
{
std::string strVal = StringValEx(i, true);
str += strVal;
str += strSplit;
}
std::string strTempSplit(strSplit);
std::string::size_type nPos = str.rfind(strSplit);
if (nPos == str.length() - strTempSplit.length())
{
str = str.substr(0, nPos);
}
return true;
}
<|endoftext|> |
<commit_before>#include "util.h"
#include <string>
#include <sstream>
#include <algorithm>
#include <glog/logging.h>
#include <openssl/sha.h>
#include <curl/curl.h>
namespace {
const uint32_t buff_size = 1024;
const uint32_t json_buff_size = 1024 * 4;
const char *json_base =
"{\"host\": \"%s\", \"service\": \"%s\", \"description\": \"%s\""
",\"state\": \"%s\", \"metric\": %f, \"time\": %i, \"tags\": [%s] %s}";
}
std::string metric_to_string(const Event& e) {
std::ostringstream ss;
if (e.has_metric_f()) {
ss << e.metric_f();
} else if (e.has_metric_d()) {
ss << e.metric_d();
} else if (e.has_metric_sint64()) {
ss << e.metric_sint64();
} else {
ss << "";
}
return ss.str();
}
std::string ttl_to_string(const Event& e) {
std::ostringstream ss;
ss << e.ttl();
return ss.str();
}
double metric_to_double(const Event &e) {
if (e.has_metric_f()) {
return e.metric_f();
} else if (e.has_metric_sint64()) {
return e.metric_sint64();
} else if (e.has_metric_d()) {
return e.metric_d();
} else {
return 0;
}
}
void clear_metrics(Event & e) {
e.clear_metric_d();
e.clear_metric_f();
e.clear_metric_sint64();
}
bool metric_set(const Event & e) {
return (e.has_metric_f() || e.has_metric_d() || e.has_metric_sint64());
}
std::string string_to_value(const Event& e, const std::string& key) {
if (key == "host") {
return e.host();
} else if (key == "service") {
return e.service();
} else if (key == "description") {
return e.description();
} else if (key == "state") {
return e.state();
} else if (key == "metric") {
return metric_to_string(e);
} else if (key == "ttl") {
return ttl_to_string(e);
} else {
return "__nil__";
}
}
std::string event_to_json(const Event &e) {
char tags[buff_size] = "";
char attrs[buff_size] = "";
for (int i = 0; i < e.tags_size(); i++) {
if (i != 0) {
strncat(tags, ", ", buff_size- strlen(tags));
}
strncat(tags, "\"", buff_size - strlen(tags));
strncat(tags, e.tags(i).c_str(), buff_size - strlen(tags));
strncat(tags, "\"", buff_size - strlen(tags));
}
for (int i = 0; i < e.attributes_size(); i++) {
strncat(attrs, ", ", buff_size - strlen(attrs));
strncat(attrs, "\"", buff_size - strlen(attrs));
strncat(attrs, e.attributes(i).key().c_str(), buff_size - strlen(attrs));
strncat(attrs, "\": ", buff_size - strlen(attrs));
strncat(attrs, "\"", buff_size - strlen(attrs));
strncat(attrs, e.attributes(i).value().c_str(), buff_size - strlen(attrs));
strncat(attrs, "\"", buff_size - strlen(attrs));
}
double metric;
if (e.has_metric_f()) {
metric = (double)e.metric_f();
} else if (e.has_metric_d()) {
metric = e.metric_d();
} else if (e.has_metric_sint64()) {
metric = (double) e.metric_sint64();
} else {
metric = 0;
}
char json_buffer[json_buff_size];
size_t r = snprintf(json_buffer, json_buff_size, json_base,
e.host().c_str(), e.service().c_str(), e.description().c_str(),
e.state().c_str(), metric, e.time(), tags, attrs);
if (r >= json_buff_size) {
VLOG(1) << "json string is too big";
return "";
} else {
return json_buffer;
}
}
void set_event_value(
Event& e,
const std::string& key,
const std::string& value,
const bool& replace)
{
if (key == "host") {
if (replace || (!e.has_host())) {
e.set_host(value);
}
} else if (key == "service") {
if (replace || (!e.has_service())) {
e.set_service(value);
}
} else if (key == "description") {
if (replace || (!e.has_description())) {
e.set_description(value);
}
} else if (key == "state") {
if (replace || (!e.has_state())) {
e.set_state(value);
}
} else {
auto att = e.add_attributes();
att->set_key(key);
att->set_value(value);
}
}
bool no_metric_set(const Event & e) {
return (!e.has_metric_sint64() && !e.has_metric_d() && ! e.has_metric_f());
}
void set_event_value(
Event& e,
const std::string & key,
const int & value,
const bool & replace)
{
if (key == "metric") {
if (replace) {
e.clear_metric_d();
e.clear_metric_f();
e.set_metric_sint64(value);
} else if (no_metric_set(e)) {
e.set_metric_sint64(value);
}
} else if (key == "ttl") {
if (replace || (!e.has_ttl())) {
e.set_ttl(value);
}
} else {
LOG(ERROR) << "set_event_value() wrong key: " << key;
}
}
void set_event_value(
Event& e,
const std::string & key,
const double & value,
const bool & replace)
{
if (key == "metric") {
if (replace) {
e.clear_metric_sint64();
e.clear_metric_f();
e.set_metric_d(value);
} else if (no_metric_set(e)) {
e.set_metric_d(value);
}
} else {
LOG(ERROR) << "set_event_value() wrong key: " << key;
}
}
void set_event_value(
Event & e,
const std::string & key,
const boost::variant<std::string, int, double> & val,
const bool & replace)
{
switch (val.which()) {
case 0:
set_event_value(e, key, boost::get<std::string>(val), replace);
break;
case 1:
set_event_value(e, key, boost::get<int>(val), replace);
break;
case 2:
set_event_value(e, key, boost::get<double>(val), replace);
break;
}
}
bool tag_exists(const Event& e, const std::string& tag) {
for (int i = 0; i < e.tags_size(); i++) {
if (e.tags(i) == tag) {
return true;
}
}
return false;
}
bool attribute_exists(const Event& e, const std::string& attribute) {
for (int i = 0; i < e.attributes_size(); i++) {
if (e.attributes(i).key() == attribute) {
return true;
}
}
return false;
}
#include <iostream>
std::string attribute_value(const Event& e, const std::string& attribute) {
if (attribute_exists(e, attribute)) {
for (int i = 0; i < e.attributes_size(); i++) {
if (e.attributes(i).key() == attribute) {
return e.attributes(i).value();
}
}
}
return "";
}
std::string sha1(const std::string& str) {
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1((const unsigned char*)str.c_str(), (unsigned long)str.size(), hash);
return std::string((char*)hash, SHA_DIGEST_LENGTH);
}
/* Taken and slightly modified from
http://en.wikibooks.org/wiki/Algorithm_Implementation/Miscellaneous/Base64 */
const static char encodeLookup[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const static char padCharacter = '=';
std::basic_string<char> base64Encode(std::vector<unsigned char> inputBuffer)
{
std::basic_string<char> encodedString;
encodedString.reserve(((inputBuffer.size()/3) + (inputBuffer.size() % 3 > 0)) * 4);
long temp;
std::vector<unsigned char>::iterator cursor = inputBuffer.begin();
for(size_t idx = 0; idx < inputBuffer.size()/3; idx++)
{
temp = (*cursor++) << 16; //Convert to big endian
temp += (*cursor++) << 8;
temp += (*cursor++);
encodedString.append(1,encodeLookup[(temp & 0x00FC0000) >> 18]);
encodedString.append(1,encodeLookup[(temp & 0x0003F000) >> 12]);
encodedString.append(1,encodeLookup[(temp & 0x00000FC0) >> 6 ]);
encodedString.append(1,encodeLookup[(temp & 0x0000003F) ]);
}
switch(inputBuffer.size() % 3)
{
case 1:
temp = (*cursor++) << 16; //Convert to big endian
encodedString.append(1,encodeLookup[(temp & 0x00FC0000) >> 18]);
encodedString.append(1,encodeLookup[(temp & 0x0003F000) >> 12]);
encodedString.append(2,padCharacter);
break;
case 2:
temp = (*cursor++) << 16; //Convert to big endian
temp += (*cursor++) << 8;
encodedString.append(1,encodeLookup[(temp & 0x00FC0000) >> 18]);
encodedString.append(1,encodeLookup[(temp & 0x0003F000) >> 12]);
encodedString.append(1,encodeLookup[(temp & 0x00000FC0) >> 6 ]);
encodedString.append(1,padCharacter);
break;
}
return encodedString;
}
std::string uri_unescape(const std::string& uri) {
VLOG(3) << "uri_unescape() uri: " << uri;
CURL *curl = curl_easy_init();
if (curl == NULL) {
LOG(ERROR) << "uri_unescape(): curl_easy_init() failed";
return uri;
}
char *ret = curl_easy_unescape(curl, uri.c_str(), uri.size(), 0);
VLOG(3) << "*ret " << ret;
const std::string unescaped(ret);
curl_free(ret);
curl_easy_cleanup(curl);
return unescaped;
}
bool parse_uri(
const std::string& escaped_uri,
std::string& index,
std::map<std::string, std::string>& params )
{
VLOG(3) << "parse_uri() escaped_uri: " << escaped_uri;
std::string uri = uri_unescape(escaped_uri);
VLOG(3) << "parse_uri() uri: " << uri;
auto it = uri.begin();
if (*it != '/') {
LOG(ERROR) << "uri doesn't start with /";
return false;
}
while (it != uri.end() && *it != '?') {
index += *it;
it++;
}
if (it == uri.end()) {
LOG(ERROR) << "uri doesn't contain '?'";
return false;
}
it++;
VLOG(3) << "index name: " << index;
while(true) {
std::string key;
while (it != uri.end() && *it != '=') {
key += *it;
it++;
}
if (it == uri.end()) {
LOG(ERROR) << "uri doesn't contain '='";
return false;
}
it++;
VLOG(3) << "key: " << key;
std::string value;
while (it != uri.end() && *it != '&') {
value += *it;
it++;
}
VLOG(3) << "value: " << value;
params.insert({key, value});
if (it == uri.end()) {
break;
} else if (*it == '&') {
it++;
}
}
return true;
}
<commit_msg>Fix time_t format<commit_after>#include "util.h"
#include <string>
#include <sstream>
#include <algorithm>
#include <glog/logging.h>
#include <openssl/sha.h>
#include <curl/curl.h>
namespace {
const uint32_t buff_size = 1024;
const uint32_t json_buff_size = 1024 * 4;
const char *json_base =
"{\"host\": \"%s\", \"service\": \"%s\", \"description\": \"%s\""
",\"state\": \"%s\", \"metric\": %f, \"time\": %lld, \"tags\": [%s] %s}";
}
std::string metric_to_string(const Event& e) {
std::ostringstream ss;
if (e.has_metric_f()) {
ss << e.metric_f();
} else if (e.has_metric_d()) {
ss << e.metric_d();
} else if (e.has_metric_sint64()) {
ss << e.metric_sint64();
} else {
ss << "";
}
return ss.str();
}
std::string ttl_to_string(const Event& e) {
std::ostringstream ss;
ss << e.ttl();
return ss.str();
}
double metric_to_double(const Event &e) {
if (e.has_metric_f()) {
return e.metric_f();
} else if (e.has_metric_sint64()) {
return e.metric_sint64();
} else if (e.has_metric_d()) {
return e.metric_d();
} else {
return 0;
}
}
void clear_metrics(Event & e) {
e.clear_metric_d();
e.clear_metric_f();
e.clear_metric_sint64();
}
bool metric_set(const Event & e) {
return (e.has_metric_f() || e.has_metric_d() || e.has_metric_sint64());
}
std::string string_to_value(const Event& e, const std::string& key) {
if (key == "host") {
return e.host();
} else if (key == "service") {
return e.service();
} else if (key == "description") {
return e.description();
} else if (key == "state") {
return e.state();
} else if (key == "metric") {
return metric_to_string(e);
} else if (key == "ttl") {
return ttl_to_string(e);
} else {
return "__nil__";
}
}
std::string event_to_json(const Event &e) {
char tags[buff_size] = "";
char attrs[buff_size] = "";
for (int i = 0; i < e.tags_size(); i++) {
if (i != 0) {
strncat(tags, ", ", buff_size- strlen(tags));
}
strncat(tags, "\"", buff_size - strlen(tags));
strncat(tags, e.tags(i).c_str(), buff_size - strlen(tags));
strncat(tags, "\"", buff_size - strlen(tags));
}
for (int i = 0; i < e.attributes_size(); i++) {
strncat(attrs, ", ", buff_size - strlen(attrs));
strncat(attrs, "\"", buff_size - strlen(attrs));
strncat(attrs, e.attributes(i).key().c_str(), buff_size - strlen(attrs));
strncat(attrs, "\": ", buff_size - strlen(attrs));
strncat(attrs, "\"", buff_size - strlen(attrs));
strncat(attrs, e.attributes(i).value().c_str(), buff_size - strlen(attrs));
strncat(attrs, "\"", buff_size - strlen(attrs));
}
double metric;
if (e.has_metric_f()) {
metric = (double)e.metric_f();
} else if (e.has_metric_d()) {
metric = e.metric_d();
} else if (e.has_metric_sint64()) {
metric = (double) e.metric_sint64();
} else {
metric = 0;
}
char json_buffer[json_buff_size];
size_t r = snprintf(json_buffer, json_buff_size, json_base,
e.host().c_str(), e.service().c_str(), e.description().c_str(),
e.state().c_str(), metric, e.time(), tags, attrs);
if (r >= json_buff_size) {
VLOG(1) << "json string is too big";
return "";
} else {
return json_buffer;
}
}
void set_event_value(
Event& e,
const std::string& key,
const std::string& value,
const bool& replace)
{
if (key == "host") {
if (replace || (!e.has_host())) {
e.set_host(value);
}
} else if (key == "service") {
if (replace || (!e.has_service())) {
e.set_service(value);
}
} else if (key == "description") {
if (replace || (!e.has_description())) {
e.set_description(value);
}
} else if (key == "state") {
if (replace || (!e.has_state())) {
e.set_state(value);
}
} else {
auto att = e.add_attributes();
att->set_key(key);
att->set_value(value);
}
}
bool no_metric_set(const Event & e) {
return (!e.has_metric_sint64() && !e.has_metric_d() && ! e.has_metric_f());
}
void set_event_value(
Event& e,
const std::string & key,
const int & value,
const bool & replace)
{
if (key == "metric") {
if (replace) {
e.clear_metric_d();
e.clear_metric_f();
e.set_metric_sint64(value);
} else if (no_metric_set(e)) {
e.set_metric_sint64(value);
}
} else if (key == "ttl") {
if (replace || (!e.has_ttl())) {
e.set_ttl(value);
}
} else {
LOG(ERROR) << "set_event_value() wrong key: " << key;
}
}
void set_event_value(
Event& e,
const std::string & key,
const double & value,
const bool & replace)
{
if (key == "metric") {
if (replace) {
e.clear_metric_sint64();
e.clear_metric_f();
e.set_metric_d(value);
} else if (no_metric_set(e)) {
e.set_metric_d(value);
}
} else {
LOG(ERROR) << "set_event_value() wrong key: " << key;
}
}
void set_event_value(
Event & e,
const std::string & key,
const boost::variant<std::string, int, double> & val,
const bool & replace)
{
switch (val.which()) {
case 0:
set_event_value(e, key, boost::get<std::string>(val), replace);
break;
case 1:
set_event_value(e, key, boost::get<int>(val), replace);
break;
case 2:
set_event_value(e, key, boost::get<double>(val), replace);
break;
}
}
bool tag_exists(const Event& e, const std::string& tag) {
for (int i = 0; i < e.tags_size(); i++) {
if (e.tags(i) == tag) {
return true;
}
}
return false;
}
bool attribute_exists(const Event& e, const std::string& attribute) {
for (int i = 0; i < e.attributes_size(); i++) {
if (e.attributes(i).key() == attribute) {
return true;
}
}
return false;
}
#include <iostream>
std::string attribute_value(const Event& e, const std::string& attribute) {
if (attribute_exists(e, attribute)) {
for (int i = 0; i < e.attributes_size(); i++) {
if (e.attributes(i).key() == attribute) {
return e.attributes(i).value();
}
}
}
return "";
}
std::string sha1(const std::string& str) {
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1((const unsigned char*)str.c_str(), (unsigned long)str.size(), hash);
return std::string((char*)hash, SHA_DIGEST_LENGTH);
}
/* Taken and slightly modified from
http://en.wikibooks.org/wiki/Algorithm_Implementation/Miscellaneous/Base64 */
const static char encodeLookup[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const static char padCharacter = '=';
std::basic_string<char> base64Encode(std::vector<unsigned char> inputBuffer)
{
std::basic_string<char> encodedString;
encodedString.reserve(((inputBuffer.size()/3) + (inputBuffer.size() % 3 > 0)) * 4);
long temp;
std::vector<unsigned char>::iterator cursor = inputBuffer.begin();
for(size_t idx = 0; idx < inputBuffer.size()/3; idx++)
{
temp = (*cursor++) << 16; //Convert to big endian
temp += (*cursor++) << 8;
temp += (*cursor++);
encodedString.append(1,encodeLookup[(temp & 0x00FC0000) >> 18]);
encodedString.append(1,encodeLookup[(temp & 0x0003F000) >> 12]);
encodedString.append(1,encodeLookup[(temp & 0x00000FC0) >> 6 ]);
encodedString.append(1,encodeLookup[(temp & 0x0000003F) ]);
}
switch(inputBuffer.size() % 3)
{
case 1:
temp = (*cursor++) << 16; //Convert to big endian
encodedString.append(1,encodeLookup[(temp & 0x00FC0000) >> 18]);
encodedString.append(1,encodeLookup[(temp & 0x0003F000) >> 12]);
encodedString.append(2,padCharacter);
break;
case 2:
temp = (*cursor++) << 16; //Convert to big endian
temp += (*cursor++) << 8;
encodedString.append(1,encodeLookup[(temp & 0x00FC0000) >> 18]);
encodedString.append(1,encodeLookup[(temp & 0x0003F000) >> 12]);
encodedString.append(1,encodeLookup[(temp & 0x00000FC0) >> 6 ]);
encodedString.append(1,padCharacter);
break;
}
return encodedString;
}
std::string uri_unescape(const std::string& uri) {
VLOG(3) << "uri_unescape() uri: " << uri;
CURL *curl = curl_easy_init();
if (curl == NULL) {
LOG(ERROR) << "uri_unescape(): curl_easy_init() failed";
return uri;
}
char *ret = curl_easy_unescape(curl, uri.c_str(), uri.size(), 0);
VLOG(3) << "*ret " << ret;
const std::string unescaped(ret);
curl_free(ret);
curl_easy_cleanup(curl);
return unescaped;
}
bool parse_uri(
const std::string& escaped_uri,
std::string& index,
std::map<std::string, std::string>& params )
{
VLOG(3) << "parse_uri() escaped_uri: " << escaped_uri;
std::string uri = uri_unescape(escaped_uri);
VLOG(3) << "parse_uri() uri: " << uri;
auto it = uri.begin();
if (*it != '/') {
LOG(ERROR) << "uri doesn't start with /";
return false;
}
while (it != uri.end() && *it != '?') {
index += *it;
it++;
}
if (it == uri.end()) {
LOG(ERROR) << "uri doesn't contain '?'";
return false;
}
it++;
VLOG(3) << "index name: " << index;
while(true) {
std::string key;
while (it != uri.end() && *it != '=') {
key += *it;
it++;
}
if (it == uri.end()) {
LOG(ERROR) << "uri doesn't contain '='";
return false;
}
it++;
VLOG(3) << "key: " << key;
std::string value;
while (it != uri.end() && *it != '&') {
value += *it;
it++;
}
VLOG(3) << "value: " << value;
params.insert({key, value});
if (it == uri.end()) {
break;
} else if (*it == '&') {
it++;
}
}
return true;
}
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCProperty.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCProperty
//
// -------------------------------------------------------------------------
#include "NFCProperty.h"
#include <complex>
NFCProperty::NFCProperty()
{
mbPublic = false;
mbPrivate = false;
mbSave = false;
mSelf = NFGUID();
eType = TDATA_UNKNOWN;
msPropertyName = "";
}
NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, bool bView, int nIndex, const std::string& strScriptFunction)
{
mbPublic = bPublic;
mbPrivate = bPrivate;
mbSave = bSave;
mbView = bView;
mnIndex = nIndex;
mSelf = self;
msPropertyName = strPropertyName;
eType = varType;
}
NFCProperty::~NFCProperty()
{
for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)
{
iter->reset();
}
mtPropertyCallback.clear();
mxData.reset();
}
void NFCProperty::SetValue(const NFIDataList::TData& TData)
{
if (eType != TData.GetType())
{
return;
}
if (!mxData.get())
{
if (!TData.IsNullValue())
{
return;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->variantData = TData.variantData;
NFCDataList::TData newValue;
newValue = *mxData;
OnEventHandler(oldValue , newValue);
}
void NFCProperty::SetValue(const NFIProperty* pProperty)
{
SetValue(pProperty->GetValue());
}
const NFIDataList::TData& NFCProperty::GetValue() const
{
if (mxData.get())
{
return *mxData;
}
return NULL_TDATA;
}
const std::string& NFCProperty::GetKey() const
{
return msPropertyName;
}
const bool NFCProperty::GetSave() const
{
return mbSave;
}
const bool NFCProperty::GetView() const
{
return mbView;
}
const bool NFCProperty::GetPublic() const
{
return mbPublic;
}
const bool NFCProperty::GetPrivate() const
{
return mbPrivate;
}
const int NFCProperty::GetIndex() const
{
return mnIndex;
};
const std::string& NFCProperty::GetRelationValue() const
{
return NULL_STR;//msScriptFunction;
}
void NFCProperty::SetSave(bool bSave)
{
mbSave = bSave;
}
void NFCProperty::SetView(bool bView)
{
mbView = bView;
}
void NFCProperty::SetPublic(bool bPublic)
{
mbPublic = bPublic;
}
void NFCProperty::SetPrivate(bool bPrivate)
{
mbPrivate = bPrivate;
}
void NFCProperty::SetScriptFunction(const std::string& strScriptFunction)
{
//msScriptFunction = strScriptFunction;
}
NFINT64 NFCProperty::GetInt() const
{
if (!mxData.get())
{
return 0;
}
return mxData->GetInt();
}
double NFCProperty::GetFloat() const
{
if (!mxData.get())
{
return 0.0;
}
return mxData->GetFloat();
}
const std::string& NFCProperty::GetString() const
{
if (!mxData.get())
{
return NULL_STR;
}
return mxData->GetString();
}
const NFGUID& NFCProperty::GetObject() const
{
if (!mxData.get())
{
return NULL_OBJECT;
}
return mxData->GetObject();
}
void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
mtPropertyCallback.push_back(cb);
}
int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
if (mtPropertyCallback.size() <= 0)
{
return 0;
}
TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();
TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();
for (it; it != end; ++it)
{
//NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)
PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;
PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();
int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);
}
return 0;
}
bool NFCProperty::SetInt(const NFINT64 value)
{
if (eType != TDATA_INT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (0 == value)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));
mxData->SetInt(0);
}
if (value == mxData->GetInt())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetInt(value);
OnEventHandler(oldValue , value);
return true;
}
bool NFCProperty::SetFloat(const double value)
{
if (eType != TDATA_FLOAT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (std::abs(value) < 0.001)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));
mxData->SetFloat(0.0);
}
if (value - mxData->GetFloat() < 0.001)
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetFloat(value);
OnEventHandler(oldValue , newValue);
return true;
}
bool NFCProperty::SetString(const std::string& value)
{
if (eType != TDATA_STRING)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.empty())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));
mxData->SetString(NULL_STR);
}
if (value == mxData->GetString())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetString(value);
OnEventHandler(oldValue , newValue);
return true;
}
bool NFCProperty::SetObject(const NFGUID& value)
{
if (eType != TDATA_OBJECT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.IsNull())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));
mxData->SetObject(NFGUID());
}
if (value == mxData->GetObject())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetObject(value);
OnEventHandler(oldValue , *mxData);
return true;
}
bool NFCProperty::Changed() const
{
return GetValue().IsNullValue();
}
const TDATA_TYPE NFCProperty::GetType() const
{
return eType;
}
const bool NFCProperty::GeUsed() const
{
if (mxData.get())
{
return true;
}
return false;
}
std::string NFCProperty::ToString()
{
std::string strData;
const TDATA_TYPE eType = GetType();
switch (eType)
{
case TDATA_INT:
strData = lexical_cast<std::string> (GetInt());
break;
case TDATA_FLOAT:
strData = lexical_cast<std::string> (GetFloat());
break;
case TDATA_STRING:
strData = lexical_cast<std::string> (GetString());
break;
case TDATA_OBJECT:
strData = GetObject().ToString();
break;
default:
strData = NULL_STR;
break;
}
return strData;
}
bool NFCProperty::FromString( const std::string& strData )
{
const TDATA_TYPE eType = GetType();
bool bRet = false;
switch (eType)
{
case TDATA_INT:
{
NFINT64 nValue = 0;
bRet = NF_StrTo(strData, nValue);
SetInt(nValue);
}
break;
case TDATA_FLOAT:
{
double dValue = 0;
bRet = NF_StrTo(strData, dValue);
SetFloat(dValue);
}
break;
case TDATA_STRING:
{
SetString(strData);
bRet = true;
}
break;
case TDATA_OBJECT:
{
NFGUID xID;
bRet = xID.FromString(strData);
SetObject(xID);
}
break;
default:
break;
}
return bRet;
}
<commit_msg>fixed for error commit<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCProperty.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCProperty
//
// -------------------------------------------------------------------------
#include "NFCProperty.h"
#include <complex>
NFCProperty::NFCProperty()
{
mbPublic = false;
mbPrivate = false;
mbSave = false;
mSelf = NFGUID();
eType = TDATA_UNKNOWN;
msPropertyName = "";
}
NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, bool bView, int nIndex, const std::string& strScriptFunction)
{
mbPublic = bPublic;
mbPrivate = bPrivate;
mbSave = bSave;
mbView = bView;
mnIndex = nIndex;
mSelf = self;
msPropertyName = strPropertyName;
eType = varType;
}
NFCProperty::~NFCProperty()
{
for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)
{
iter->reset();
}
mtPropertyCallback.clear();
mxData.reset();
}
void NFCProperty::SetValue(const NFIDataList::TData& TData)
{
if (eType != TData.GetType())
{
return;
}
if (!mxData.get())
{
if (!TData.IsNullValue())
{
return;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->variantData = TData.variantData;
NFCDataList::TData newValue;
newValue = *mxData;
OnEventHandler(oldValue , newValue);
}
void NFCProperty::SetValue(const NFIProperty* pProperty)
{
SetValue(pProperty->GetValue());
}
const NFIDataList::TData& NFCProperty::GetValue() const
{
if (mxData.get())
{
return *mxData;
}
return NULL_TDATA;
}
const std::string& NFCProperty::GetKey() const
{
return msPropertyName;
}
const bool NFCProperty::GetSave() const
{
return mbSave;
}
const bool NFCProperty::GetView() const
{
return mbView;
}
const bool NFCProperty::GetPublic() const
{
return mbPublic;
}
const bool NFCProperty::GetPrivate() const
{
return mbPrivate;
}
const int NFCProperty::GetIndex() const
{
return mnIndex;
};
const std::string& NFCProperty::GetRelationValue() const
{
return NULL_STR;//msScriptFunction;
}
void NFCProperty::SetSave(bool bSave)
{
mbSave = bSave;
}
void NFCProperty::SetView(bool bView)
{
mbView = bView;
}
void NFCProperty::SetPublic(bool bPublic)
{
mbPublic = bPublic;
}
void NFCProperty::SetPrivate(bool bPrivate)
{
mbPrivate = bPrivate;
}
void NFCProperty::SetScriptFunction(const std::string& strScriptFunction)
{
//msScriptFunction = strScriptFunction;
}
NFINT64 NFCProperty::GetInt() const
{
if (!mxData.get())
{
return 0;
}
return mxData->GetInt();
}
double NFCProperty::GetFloat() const
{
if (!mxData.get())
{
return 0.0;
}
return mxData->GetFloat();
}
const std::string& NFCProperty::GetString() const
{
if (!mxData.get())
{
return NULL_STR;
}
return mxData->GetString();
}
const NFGUID& NFCProperty::GetObject() const
{
if (!mxData.get())
{
return NULL_OBJECT;
}
return mxData->GetObject();
}
void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
mtPropertyCallback.push_back(cb);
}
int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
if (mtPropertyCallback.size() <= 0)
{
return 0;
}
TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();
TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();
for (it; it != end; ++it)
{
//NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)
PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;
PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();
int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);
}
return 0;
}
bool NFCProperty::SetInt(const NFINT64 value)
{
if (eType != TDATA_INT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (0 == value)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));
mxData->SetInt(0);
}
if (value == mxData->GetInt())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetInt(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetFloat(const double value)
{
if (eType != TDATA_FLOAT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (std::abs(value) < 0.001)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));
mxData->SetFloat(0.0);
}
if (value - mxData->GetFloat() < 0.001)
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetFloat(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetString(const std::string& value)
{
if (eType != TDATA_STRING)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.empty())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));
mxData->SetString(NULL_STR);
}
if (value == mxData->GetString())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetString(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetObject(const NFGUID& value)
{
if (eType != TDATA_OBJECT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.IsNull())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));
mxData->SetObject(NFGUID());
}
if (value == mxData->GetObject())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetObject(value);
OnEventHandler(oldValue , *mxData);
return true;
}
bool NFCProperty::Changed() const
{
return GetValue().IsNullValue();
}
const TDATA_TYPE NFCProperty::GetType() const
{
return eType;
}
const bool NFCProperty::GeUsed() const
{
if (mxData.get())
{
return true;
}
return false;
}
std::string NFCProperty::ToString()
{
std::string strData;
const TDATA_TYPE eType = GetType();
switch (eType)
{
case TDATA_INT:
strData = lexical_cast<std::string> (GetInt());
break;
case TDATA_FLOAT:
strData = lexical_cast<std::string> (GetFloat());
break;
case TDATA_STRING:
strData = lexical_cast<std::string> (GetString());
break;
case TDATA_OBJECT:
strData = GetObject().ToString();
break;
default:
strData = NULL_STR;
break;
}
return strData;
}
bool NFCProperty::FromString( const std::string& strData )
{
const TDATA_TYPE eType = GetType();
bool bRet = false;
switch (eType)
{
case TDATA_INT:
{
NFINT64 nValue = 0;
bRet = NF_StrTo(strData, nValue);
SetInt(nValue);
}
break;
case TDATA_FLOAT:
{
double dValue = 0;
bRet = NF_StrTo(strData, dValue);
SetFloat(dValue);
}
break;
case TDATA_STRING:
{
SetString(strData);
bRet = true;
}
break;
case TDATA_OBJECT:
{
NFGUID xID;
bRet = xID.FromString(strData);
SetObject(xID);
}
break;
default:
break;
}
return bRet;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: sdclient.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:48:34 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _IPOBJ_HXX //autogen
#include <so3/ipobj.hxx>
#endif
#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _CLIENT_HXX //autogen
#include <so3/client.hxx>
#endif
#ifndef _IPENV_HXX //autogen
#include <so3/ipenv.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif
#pragma hdrstop
#include "misc.hxx"
#ifdef STARIMAGE_AVAILABLE
#ifndef _SIMDLL_HXX
#include <sim2/simdll.hxx>
#endif
#endif
#include "strings.hrc"
#include "sdclient.hxx"
#include "viewshel.hxx"
#include "drviewsh.hxx"
#include "sdview.hxx"
#include "sdwindow.hxx"
#include "sdresid.hxx"
/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) :
SfxInPlaceClient(pSdViewShell, pWindow),
pViewShell(pSdViewShell),
pSdrOle2Obj(pObj),
pSdrGrafObj(NULL),
pOutlinerParaObj (NULL)
{
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
__EXPORT SdClient::~SdClient()
{
}
/*************************************************************************
|*
|* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des
|* sichtbaren Ausschnitts des Objektes
|*
\************************************************************************/
void __EXPORT SdClient::RequestObjAreaPixel(const Rectangle& rRect)
{
Window* pWin = pViewShell->GetWindow();
Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ),
pWin->PixelToLogic( rRect.GetSize() ) );
SdView* pView = pViewShell->GetView();
Rectangle aWorkArea( pView->GetWorkArea() );
if (!aWorkArea.IsInside(aObjRect))
{
// Position korrigieren
Point aPos = aObjRect.TopLeft();
Size aSize = aObjRect.GetSize();
Point aWorkAreaTL = aWorkArea.TopLeft();
Point aWorkAreaBR = aWorkArea.BottomRight();
aPos.X() = Max(aPos.X(), aWorkAreaTL.X());
aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width());
aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y());
aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height());
aObjRect.SetPos(aPos);
SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()->
LogicToPixel(aObjRect) );
}
else
{
SfxInPlaceClient::RequestObjAreaPixel(rRect);
}
const SdrMarkList& rMarkList = pView->GetMarkList();
if (rMarkList.GetMarkCount() == 1)
{
SdrMark* pMark = rMarkList.GetMark(0);
SdrObject* pObj = pMark->GetObj();
Rectangle aOldRect( pObj->GetLogicRect() );
if ( aObjRect != aOldRect )
{
// Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied
// (getrennt fuer Position und Groesse)
Size aOnePixel = pWin->PixelToLogic( Size(1, 1) );
Size aLogicSize = aObjRect.GetSize();
Rectangle aNewRect = aOldRect;
Size aNewSize = aNewRect.GetSize();
if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() )
aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) );
if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() )
aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) );
if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() )
aNewSize.Width() = aLogicSize.Width();
if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() )
aNewSize.Height() = aLogicSize.Height();
aNewRect.SetSize( aNewSize );
if ( aNewRect != aOldRect ) // veraendert nur, wenn mindestens 1 Pixel
pObj->SetLogicRect( aNewRect );
}
}
}
/*************************************************************************
|*
|*
|*
\************************************************************************/
void __EXPORT SdClient::ViewChanged(USHORT nAspect)
{
// Eventuell neues MetaFile holen
SfxInPlaceClient::ViewChanged(nAspect);
if (pViewShell->GetActiveWindow())
{
SdView* pView = pViewShell->GetView();
if (pView)
{
// Der sichtbare Ausschnitt hat sich eventuell geaendert
SvEmbeddedObject* pObj = GetEmbedObj();
Rectangle aObjVisArea = OutputDevice::LogicToLogic(
pObj->GetVisArea(), pObj->GetMapUnit(),
MAP_100TH_MM );
Size aVisSize = aObjVisArea.GetSize();
SvClientData* pClientData = GetEnv();
if (pClientData)
{
Fraction aFractX = pClientData->GetScaleWidth();
Fraction aFractY = pClientData->GetScaleHeight();
aFractX *= aVisSize.Width();
aFractY *= aVisSize.Height();
aVisSize = Size( (long) aFractX, (long) aFractY );
Rectangle aLogicRect = pSdrOle2Obj->GetLogicRect();
Rectangle aObjArea = aLogicRect;
// Dokument-Groesse vom Server
aObjArea.SetSize(aObjVisArea.GetSize());
pClientData->SetObjArea(aObjArea);
if (aLogicRect.GetSize() != aVisSize)
{
aLogicRect.SetSize(aVisSize);
pSdrOle2Obj->SetLogicRect(aLogicRect);
pSdrOle2Obj->SendRepaintBroadcast();
}
}
}
}
}
/*************************************************************************
|*
|* InPlace-Objekt aktivieren / deaktivieren
|*
\************************************************************************/
void __EXPORT SdClient::UIActivate(BOOL bActivate)
{
SfxInPlaceClient::UIActivate(bActivate);
if (!bActivate)
{
#ifdef STARIMAGE_AVAILABLE
if (pSdrGrafObj && pViewShell->GetActiveWindow())
{
// Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht
pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect());
SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef();
pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) );
SdView* pView = pViewShell->GetView();
SdrPageView* pPV = pView->GetPageViewPvNum(0);
SdrPage* pPg = pPV->GetPage();
delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() );
pSdrGrafObj = NULL;
}
#endif
}
}
/*************************************************************************
|*
|* Daten fuer eine ggf. spaeter zu erzeugende View
|*
\************************************************************************/
void __EXPORT SdClient::MakeViewData()
{
SfxInPlaceClient::MakeViewData();
SvClientData* pCD = GetClientData();
if (pCD)
{
SvEmbeddedObject* pObj = GetEmbedObj();
Rectangle aObjVisArea = OutputDevice::LogicToLogic(
pObj->GetVisArea(), pObj->GetMapUnit(),
MAP_100TH_MM );
Size aVisSize = aObjVisArea.GetSize();
Fraction aFractX = pCD->GetScaleWidth();
Fraction aFractY = pCD->GetScaleHeight();
aFractX *= aVisSize.Width();
aFractY *= aVisSize.Height();
pCD->SetSizeScale(aFractX, aFractY);
Rectangle aObjArea = pSdrOle2Obj->GetLogicRect();
pCD->SetObjArea(aObjArea);
}
}
/*************************************************************************
|*
|* Objekt in den sichtbaren Breich scrollen
|*
\************************************************************************/
void __EXPORT SdClient::MakeVisible()
{
SfxInPlaceClient::MakeVisible();
if (pViewShell->ISA(SdDrawViewShell))
{
((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(),
*pViewShell->GetActiveWindow());
}
}
<commit_msg>#91555#: rounding errors<commit_after>/*************************************************************************
*
* $RCSfile: sdclient.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ka $ $Date: 2001-08-29 13:55:44 $
*
* 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 _IPOBJ_HXX //autogen
#include <so3/ipobj.hxx>
#endif
#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _CLIENT_HXX //autogen
#include <so3/client.hxx>
#endif
#ifndef _IPENV_HXX //autogen
#include <so3/ipenv.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif
#pragma hdrstop
#include "misc.hxx"
#ifdef STARIMAGE_AVAILABLE
#ifndef _SIMDLL_HXX
#include <sim2/simdll.hxx>
#endif
#endif
#include "strings.hrc"
#include "sdclient.hxx"
#include "viewshel.hxx"
#include "drviewsh.hxx"
#include "sdview.hxx"
#include "sdwindow.hxx"
#include "sdresid.hxx"
/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) :
SfxInPlaceClient(pSdViewShell, pWindow),
pViewShell(pSdViewShell),
pSdrOle2Obj(pObj),
pSdrGrafObj(NULL),
pOutlinerParaObj (NULL)
{
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
__EXPORT SdClient::~SdClient()
{
}
/*************************************************************************
|*
|* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des
|* sichtbaren Ausschnitts des Objektes
|*
\************************************************************************/
void __EXPORT SdClient::RequestObjAreaPixel(const Rectangle& rRect)
{
Window* pWin = pViewShell->GetWindow();
Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ),
pWin->PixelToLogic( rRect.GetSize() ) );
SdView* pView = pViewShell->GetView();
Rectangle aWorkArea( pView->GetWorkArea() );
if (!aWorkArea.IsInside(aObjRect))
{
// Position korrigieren
Point aPos = aObjRect.TopLeft();
Size aSize = aObjRect.GetSize();
Point aWorkAreaTL = aWorkArea.TopLeft();
Point aWorkAreaBR = aWorkArea.BottomRight();
aPos.X() = Max(aPos.X(), aWorkAreaTL.X());
aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width());
aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y());
aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height());
aObjRect.SetPos(aPos);
SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()->
LogicToPixel(aObjRect) );
}
else
{
SfxInPlaceClient::RequestObjAreaPixel(rRect);
}
const SdrMarkList& rMarkList = pView->GetMarkList();
if (rMarkList.GetMarkCount() == 1)
{
SdrMark* pMark = rMarkList.GetMark(0);
SdrObject* pObj = pMark->GetObj();
Rectangle aOldRect( pObj->GetLogicRect() );
if ( aObjRect != aOldRect )
{
// Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied
// (getrennt fuer Position und Groesse)
Size aOnePixel = pWin->PixelToLogic( Size(1, 1) );
Size aLogicSize = aObjRect.GetSize();
Rectangle aNewRect = aOldRect;
Size aNewSize = aNewRect.GetSize();
if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() )
aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) );
if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() )
aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) );
if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() )
aNewSize.Width() = aLogicSize.Width();
if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() )
aNewSize.Height() = aLogicSize.Height();
aNewRect.SetSize( aNewSize );
if ( aNewRect != aOldRect ) // veraendert nur, wenn mindestens 1 Pixel
pObj->SetLogicRect( aNewRect );
}
}
}
/*************************************************************************
|*
|*
|*
\************************************************************************/
void __EXPORT SdClient::ViewChanged(USHORT nAspect)
{
// Eventuell neues MetaFile holen
SfxInPlaceClient::ViewChanged(nAspect);
if (pViewShell->GetActiveWindow())
{
SdView* pView = pViewShell->GetView();
if (pView)
{
// Der sichtbare Ausschnitt hat sich eventuell geaendert
SvEmbeddedObject* pObj = GetEmbedObj();
const MapMode aMap100( MAP_100TH_MM );
Rectangle aObjVisArea( OutputDevice::LogicToLogic( pObj->GetVisArea(),
pObj->GetMapUnit(),
aMap100 ) );
Size aVisSize( aObjVisArea.GetSize() );
SvClientData* pClientData = GetEnv();
if( pClientData )
{
Fraction aFractX( pClientData->GetScaleWidth() );
Fraction aFractY( pClientData->GetScaleHeight() );
aVisSize = Size( (long) ( aFractX *= aVisSize.Width() ), (long) ( aFractY *= aVisSize.Height() ) );
Rectangle aLogicRect( pSdrOle2Obj->GetLogicRect() );
Rectangle aObjArea( aLogicRect );
aObjArea.SetSize( aObjVisArea.GetSize() );
pClientData->SetObjArea( aObjArea );
const Size aVisSizePix( Application::GetDefaultDevice()->LogicToPixel( aVisSize, aMap100 ) );
const Size aObjSizePix( Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) );
if( aVisSizePix != aObjSizePix )
{
aLogicRect.SetSize(aVisSize);
pSdrOle2Obj->SetLogicRect(aLogicRect);
pSdrOle2Obj->SendRepaintBroadcast();
}
}
}
}
}
/*************************************************************************
|*
|* InPlace-Objekt aktivieren / deaktivieren
|*
\************************************************************************/
void __EXPORT SdClient::UIActivate(BOOL bActivate)
{
SfxInPlaceClient::UIActivate(bActivate);
if (!bActivate)
{
#ifdef STARIMAGE_AVAILABLE
if (pSdrGrafObj && pViewShell->GetActiveWindow())
{
// Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht
pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect());
SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef();
pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) );
SdView* pView = pViewShell->GetView();
SdrPageView* pPV = pView->GetPageViewPvNum(0);
SdrPage* pPg = pPV->GetPage();
delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() );
pSdrGrafObj = NULL;
}
#endif
}
}
/*************************************************************************
|*
|* Daten fuer eine ggf. spaeter zu erzeugende View
|*
\************************************************************************/
void __EXPORT SdClient::MakeViewData()
{
SfxInPlaceClient::MakeViewData();
SvClientData* pCD = GetClientData();
if (pCD)
{
SvEmbeddedObject* pObj = GetEmbedObj();
Rectangle aObjVisArea = OutputDevice::LogicToLogic(
pObj->GetVisArea(), pObj->GetMapUnit(),
MAP_100TH_MM );
Size aVisSize = aObjVisArea.GetSize();
Fraction aFractX = pCD->GetScaleWidth();
Fraction aFractY = pCD->GetScaleHeight();
aFractX *= aVisSize.Width();
aFractY *= aVisSize.Height();
pCD->SetSizeScale(aFractX, aFractY);
Rectangle aObjArea = pSdrOle2Obj->GetLogicRect();
pCD->SetObjArea(aObjArea);
}
}
/*************************************************************************
|*
|* Objekt in den sichtbaren Breich scrollen
|*
\************************************************************************/
void __EXPORT SdClient::MakeVisible()
{
SfxInPlaceClient::MakeVisible();
if (pViewShell->ISA(SdDrawViewShell))
{
((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(),
*pViewShell->GetActiveWindow());
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2014-2017 Alexandr Akulich <[email protected]>
This file is a part of TelegramQt library.
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.
*/
#include "AesCtr.hpp"
#include "CTcpTransport.hpp"
#include "CRawStream.hpp"
#include <QHostAddress>
#include <QTimer>
#include <QLoggingCategory>
using namespace Telegram;
#ifndef Q_FALLTHROUGH
#define Q_FALLTHROUGH() (void)0
#endif
Q_LOGGING_CATEGORY(c_loggingTcpTransport, "telegram.transport.tcp", QtWarningMsg)
static const quint32 tcpTimeout = 15 * 1000;
CTcpTransport::CTcpTransport(QObject *parent) :
CTelegramTransport(parent),
m_socket(nullptr),
m_timeoutTimer(new QTimer(this))
{
m_timeoutTimer->setInterval(tcpTimeout);
connect(m_timeoutTimer, &QTimer::timeout, this, &CTcpTransport::onTimeout);
}
CTcpTransport::~CTcpTransport()
{
if (m_socket && m_socket->isWritable()) {
m_socket->waitForBytesWritten(100);
m_socket->disconnectFromHost();
}
}
QString CTcpTransport::remoteAddress() const
{
return m_socket ? m_socket->peerAddress().toString() : QString();
}
void CTcpTransport::connectToHost(const QString &ipAddress, quint32 port)
{
qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << ipAddress << port;
m_socket->connectToHost(ipAddress, port);
}
void CTcpTransport::disconnectFromHost()
{
qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO;
if (m_socket) {
m_socket->disconnectFromHost();
}
}
CTcpTransport::SessionType CTcpTransport::sessionType() const
{
return m_sessionType;
}
void CTcpTransport::sendPackageImplementation(const QByteArray &payload)
{
// quint32 length (included length itself + packet number + crc32 + payload (MUST be divisible by 4)
// quint32 packet number
// quint32 CRC32 (length, quint32 packet number, payload)
// Payload
// Abridged version:
// quint8: 0xef
// DataLength / 4 < 0x7f ?
// (quint8: Packet length / 4) :
// (quint8: 0x7f, quint24: Packet length / 4)
// Payload
if (payload.length() % 4) {
qCCritical(c_loggingTcpTransport) << Q_FUNC_INFO
<< "Invalid outgoing package! "
"The payload size is not divisible by four!";
}
QByteArray package;
package.reserve(payload.size() + 4);
const quint32 length = payload.length() / 4;
if (length < 0x7f) {
package.append(char(length));
} else {
package.append(char(0x7f));
package.append(reinterpret_cast<const char *>(&length), 3);
}
package.append(payload);
if (m_writeAesContext && m_writeAesContext->hasKey()) {
package = m_writeAesContext->crypt(package);
}
m_socket->write(package);
}
void CTcpTransport::setSessionType(CTcpTransport::SessionType sessionType)
{
m_sessionType = sessionType;
}
void CTcpTransport::setCryptoKeysSourceData(const QByteArray &source, SourceRevertion revertion)
{
if (source.size() != (Crypto::AesCtrContext::KeySize + Crypto::AesCtrContext::IvecSize)) {
qCWarning(c_loggingTcpTransport) << Q_FUNC_INFO << "Invalid input data (size mismatch)";
return;
}
QByteArray reversed = source;
std::reverse(reversed.begin(), reversed.end());
const auto setSourceData = [](const QByteArray &source, Crypto::AesCtrContext *&context) {
if (!context) {
context = new Crypto::AesCtrContext();
}
context->setKey(source.left(Crypto::AesCtrContext::KeySize));
context->setIVec(source.mid(Crypto::AesCtrContext::KeySize));
};
if (revertion == DirectIsReadReversedIsWrite) {
setSourceData(source, m_readAesContext);
setSourceData(reversed, m_writeAesContext);
} else { // Server, DirectIsWriteReversedIsRead
setSourceData(source, m_writeAesContext);
setSourceData(reversed, m_readAesContext);
}
const char *className = metaObject()->className();
if (strstr(className, "Server")) {
m_readAesContext->setDescription(QByteArrayLiteral("server read"));
m_writeAesContext->setDescription(QByteArrayLiteral("server write"));
} else if (strstr(className, "Client")) {
m_readAesContext->setDescription(QByteArrayLiteral("client read"));
m_writeAesContext->setDescription(QByteArrayLiteral("client write"));
}
}
void CTcpTransport::setState(QAbstractSocket::SocketState newState)
{
qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << newState;
switch (newState) {
case QAbstractSocket::HostLookupState:
case QAbstractSocket::ConnectingState:
m_timeoutTimer->start();
break;
case QAbstractSocket::ConnectedState:
m_expectedLength = 0;
setSessionType(Unknown);
Q_FALLTHROUGH();
default:
m_timeoutTimer->stop();
break;
}
CTelegramTransport::setState(newState);
}
void CTcpTransport::onReadyRead()
{
qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << m_socket->bytesAvailable();
readEvent();
if (m_sessionType == Unknown) {
qCCritical(c_loggingTcpTransport) << "Unknown session type!";
return;
}
while ((m_socket->bytesAvailable() > 0) || !m_readBuffer.isEmpty()) {
if (m_socket->bytesAvailable() > 0) {
QByteArray allData = m_socket->readAll();
if (m_readAesContext) {
allData = m_readAesContext->crypt(allData);
}
m_readBuffer.append(allData);
}
CRawStreamEx bufferStream(m_readBuffer);
if (m_expectedLength == 0) {
quint8 length_t1;
bufferStream >> length_t1;
if (length_t1 < char(0x7f)) {
m_expectedLength = length_t1;
} else if (length_t1 == char(0x7f)) {
QByteArray nextThree = bufferStream.readBytes(3);
char *lengthCharPointer = reinterpret_cast<char *>(&m_expectedLength);
lengthCharPointer[0] = nextThree.at(0);
lengthCharPointer[1] = nextThree.at(1);
lengthCharPointer[2] = nextThree.at(2);
} else {
qCWarning(c_loggingTcpTransport) << "Invalid package size byte" << hex << showbase << length_t1;
qCWarning(c_loggingTcpTransport) << "Buffer:" << m_readBuffer.toHex();
}
m_expectedLength *= 4;
}
if (bufferStream.bytesAvailable() < static_cast<qint64>(m_expectedLength)) {
qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO << "Ready read, but only "
<< bufferStream.bytesAvailable() << "bytes available ("
<< m_expectedLength << "bytes expected)";
return;
}
const QByteArray readPackage = bufferStream.readBytes(m_expectedLength);
m_readBuffer = bufferStream.readAll();
m_expectedLength = 0;
qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO
<< "Received a package (" << readPackage.size() << " bytes)";
emit packageReceived(readPackage);
}
}
void CTcpTransport::onTimeout()
{
qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO << m_socket->peerName() << m_socket->peerPort();
emit timeout();
m_socket->disconnectFromHost();
}
void CTcpTransport::onSocketErrorOccurred(QAbstractSocket::SocketError error)
{
setError(error, m_socket->errorString());
}
void CTcpTransport::setSocket(QAbstractSocket *socket)
{
if (m_socket) {
qCCritical(c_loggingTcpTransport()) << Q_FUNC_INFO << "An attempt to set a socket twice";
}
m_socket = socket;
connect(m_socket, &QAbstractSocket::stateChanged, this, &CTcpTransport::setState);
connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(onSocketErrorOccurred(QAbstractSocket::SocketError)));
connect(m_socket, &QIODevice::readyRead, this, &CTcpTransport::onReadyRead);
}
<commit_msg>CTcpTransport: Hide warning on destruct<commit_after>/*
Copyright (C) 2014-2017 Alexandr Akulich <[email protected]>
This file is a part of TelegramQt library.
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.
*/
#include "AesCtr.hpp"
#include "CTcpTransport.hpp"
#include "CRawStream.hpp"
#include <QHostAddress>
#include <QTimer>
#include <QLoggingCategory>
using namespace Telegram;
#ifndef Q_FALLTHROUGH
#define Q_FALLTHROUGH() (void)0
#endif
Q_LOGGING_CATEGORY(c_loggingTcpTransport, "telegram.transport.tcp", QtWarningMsg)
static const quint32 tcpTimeout = 15 * 1000;
CTcpTransport::CTcpTransport(QObject *parent) :
CTelegramTransport(parent),
m_socket(nullptr),
m_timeoutTimer(new QTimer(this))
{
m_timeoutTimer->setInterval(tcpTimeout);
connect(m_timeoutTimer, &QTimer::timeout, this, &CTcpTransport::onTimeout);
}
CTcpTransport::~CTcpTransport()
{
if (m_socket && m_socket->isWritable() && m_socket->isOpen()
&& m_socket->state() != QAbstractSocket::UnconnectedState) {
m_socket->waitForBytesWritten(100);
m_socket->disconnectFromHost();
}
}
QString CTcpTransport::remoteAddress() const
{
return m_socket ? m_socket->peerAddress().toString() : QString();
}
void CTcpTransport::connectToHost(const QString &ipAddress, quint32 port)
{
qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << ipAddress << port;
m_socket->connectToHost(ipAddress, port);
}
void CTcpTransport::disconnectFromHost()
{
qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO;
if (m_socket) {
m_socket->disconnectFromHost();
}
}
CTcpTransport::SessionType CTcpTransport::sessionType() const
{
return m_sessionType;
}
void CTcpTransport::sendPackageImplementation(const QByteArray &payload)
{
// quint32 length (included length itself + packet number + crc32 + payload (MUST be divisible by 4)
// quint32 packet number
// quint32 CRC32 (length, quint32 packet number, payload)
// Payload
// Abridged version:
// quint8: 0xef
// DataLength / 4 < 0x7f ?
// (quint8: Packet length / 4) :
// (quint8: 0x7f, quint24: Packet length / 4)
// Payload
if (payload.length() % 4) {
qCCritical(c_loggingTcpTransport) << Q_FUNC_INFO
<< "Invalid outgoing package! "
"The payload size is not divisible by four!";
}
QByteArray package;
package.reserve(payload.size() + 4);
const quint32 length = payload.length() / 4;
if (length < 0x7f) {
package.append(char(length));
} else {
package.append(char(0x7f));
package.append(reinterpret_cast<const char *>(&length), 3);
}
package.append(payload);
if (m_writeAesContext && m_writeAesContext->hasKey()) {
package = m_writeAesContext->crypt(package);
}
m_socket->write(package);
}
void CTcpTransport::setSessionType(CTcpTransport::SessionType sessionType)
{
m_sessionType = sessionType;
}
void CTcpTransport::setCryptoKeysSourceData(const QByteArray &source, SourceRevertion revertion)
{
if (source.size() != (Crypto::AesCtrContext::KeySize + Crypto::AesCtrContext::IvecSize)) {
qCWarning(c_loggingTcpTransport) << Q_FUNC_INFO << "Invalid input data (size mismatch)";
return;
}
QByteArray reversed = source;
std::reverse(reversed.begin(), reversed.end());
const auto setSourceData = [](const QByteArray &source, Crypto::AesCtrContext *&context) {
if (!context) {
context = new Crypto::AesCtrContext();
}
context->setKey(source.left(Crypto::AesCtrContext::KeySize));
context->setIVec(source.mid(Crypto::AesCtrContext::KeySize));
};
if (revertion == DirectIsReadReversedIsWrite) {
setSourceData(source, m_readAesContext);
setSourceData(reversed, m_writeAesContext);
} else { // Server, DirectIsWriteReversedIsRead
setSourceData(source, m_writeAesContext);
setSourceData(reversed, m_readAesContext);
}
const char *className = metaObject()->className();
if (strstr(className, "Server")) {
m_readAesContext->setDescription(QByteArrayLiteral("server read"));
m_writeAesContext->setDescription(QByteArrayLiteral("server write"));
} else if (strstr(className, "Client")) {
m_readAesContext->setDescription(QByteArrayLiteral("client read"));
m_writeAesContext->setDescription(QByteArrayLiteral("client write"));
}
}
void CTcpTransport::setState(QAbstractSocket::SocketState newState)
{
qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << newState;
switch (newState) {
case QAbstractSocket::HostLookupState:
case QAbstractSocket::ConnectingState:
m_timeoutTimer->start();
break;
case QAbstractSocket::ConnectedState:
m_expectedLength = 0;
setSessionType(Unknown);
Q_FALLTHROUGH();
default:
m_timeoutTimer->stop();
break;
}
CTelegramTransport::setState(newState);
}
void CTcpTransport::onReadyRead()
{
qCDebug(c_loggingTcpTransport) << Q_FUNC_INFO << m_socket->bytesAvailable();
readEvent();
if (m_sessionType == Unknown) {
qCCritical(c_loggingTcpTransport) << "Unknown session type!";
return;
}
while ((m_socket->bytesAvailable() > 0) || !m_readBuffer.isEmpty()) {
if (m_socket->bytesAvailable() > 0) {
QByteArray allData = m_socket->readAll();
if (m_readAesContext) {
allData = m_readAesContext->crypt(allData);
}
m_readBuffer.append(allData);
}
CRawStreamEx bufferStream(m_readBuffer);
if (m_expectedLength == 0) {
quint8 length_t1;
bufferStream >> length_t1;
if (length_t1 < char(0x7f)) {
m_expectedLength = length_t1;
} else if (length_t1 == char(0x7f)) {
QByteArray nextThree = bufferStream.readBytes(3);
char *lengthCharPointer = reinterpret_cast<char *>(&m_expectedLength);
lengthCharPointer[0] = nextThree.at(0);
lengthCharPointer[1] = nextThree.at(1);
lengthCharPointer[2] = nextThree.at(2);
} else {
qCWarning(c_loggingTcpTransport) << "Invalid package size byte" << hex << showbase << length_t1;
qCWarning(c_loggingTcpTransport) << "Buffer:" << m_readBuffer.toHex();
}
m_expectedLength *= 4;
}
if (bufferStream.bytesAvailable() < static_cast<qint64>(m_expectedLength)) {
qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO << "Ready read, but only "
<< bufferStream.bytesAvailable() << "bytes available ("
<< m_expectedLength << "bytes expected)";
return;
}
const QByteArray readPackage = bufferStream.readBytes(m_expectedLength);
m_readBuffer = bufferStream.readAll();
m_expectedLength = 0;
qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO
<< "Received a package (" << readPackage.size() << " bytes)";
emit packageReceived(readPackage);
}
}
void CTcpTransport::onTimeout()
{
qCDebug(c_loggingTcpTransport()) << Q_FUNC_INFO << m_socket->peerName() << m_socket->peerPort();
emit timeout();
m_socket->disconnectFromHost();
}
void CTcpTransport::onSocketErrorOccurred(QAbstractSocket::SocketError error)
{
setError(error, m_socket->errorString());
}
void CTcpTransport::setSocket(QAbstractSocket *socket)
{
if (m_socket) {
qCCritical(c_loggingTcpTransport()) << Q_FUNC_INFO << "An attempt to set a socket twice";
}
m_socket = socket;
connect(m_socket, &QAbstractSocket::stateChanged, this, &CTcpTransport::setState);
connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(onSocketErrorOccurred(QAbstractSocket::SocketError)));
connect(m_socket, &QIODevice::readyRead, this, &CTcpTransport::onReadyRead);
}
<|endoftext|> |
<commit_before>#include "VBOMesh.h"
#include "AttributeSet.h"
#include "GLBlaat/GLBuffer.h"
#include "GLBlaat/GLProgram.h"
#include <vector>
#include <map>
#include <string>
#include <cassert>
#include <iostream>
// These might be missing with older GLEW headers
#ifndef GL_FLOAT_MAT2x3
#define GL_FLOAT_MAT2x3 0x8B65
#define GL_FLOAT_MAT2x4 0x8B66
#define GL_FLOAT_MAT3x2 0x8B67
#define GL_FLOAT_MAT3x4 0x8B68
#define GL_FLOAT_MAT4x2 0x8B69
#define GL_FLOAT_MAT4x3 0x8B6A
#endif
namespace NQVTK
{
// ------------------------------------------------------------------------
VBOMesh::VBOMesh()
{
}
// ------------------------------------------------------------------------
VBOMesh::~VBOMesh()
{
// Delete the attribute sets
for (AttributeMap::iterator it = attributeSets.begin();
it != attributeSets.end(); ++it)
{
delete it->second;
}
}
// ------------------------------------------------------------------------
void VBOMesh::BindAttributes() const
{
for (AttributeMap::const_iterator it = attributeSets.begin();
it != attributeSets.end(); ++it)
{
it->second->Bind();
}
}
// ------------------------------------------------------------------------
void VBOMesh::UnbindAttributes() const
{
for (AttributeMap::const_iterator it = attributeSets.begin();
it != attributeSets.end(); ++it)
{
it->second->Unbind();
}
}
// ------------------------------------------------------------------------
void VBOMesh::SetupAttributes(
const std::vector<GLAttributeInfo> requiredAttribs)
{
// Clear all attributes
for (AttributeMap::iterator it = this->customAttribs.begin();
it != this->customAttribs.end(); ++it)
{
it->second->DontUse();
}
// Set attributes used by the program
for (std::vector<GLAttributeInfo>::const_iterator it =
requiredAttribs.begin(); it != requiredAttribs.end(); ++it)
{
if (it->index >= 0)
{
AttributeMap::iterator ait = customAttribs.find(it->name);
if (ait != customAttribs.end())
{
ait->second->UseAsVertexAttrib(it->index);
}
else
{
// Set a default value for the attribute
// It seems we can ignore the size, as array elements are listed
// separately in requiredAttribs.
// Matrices seem to be listed once; rows need to be set separately
// TODO: type for mat4 is returned as vec4, how to distinguish?
std::vector<float> zeroes;
zeroes.resize(4 * 4);
switch (it->type)
{
case GL_FLOAT:
glVertexAttrib1fv(it->index, &zeroes[0]);
break;
case GL_FLOAT_MAT4x2:
glVertexAttrib2fv(it->index + 3, &zeroes[0]);
case GL_FLOAT_MAT3x2:
glVertexAttrib2fv(it->index + 2, &zeroes[0]);
case GL_FLOAT_MAT2:
glVertexAttrib2fv(it->index + 1, &zeroes[0]);
case GL_FLOAT_VEC2:
glVertexAttrib2fv(it->index, &zeroes[0]);
break;
case GL_FLOAT_MAT4x3:
glVertexAttrib3fv(it->index + 3, &zeroes[0]);
case GL_FLOAT_MAT3:
glVertexAttrib3fv(it->index + 2, &zeroes[0]);
case GL_FLOAT_MAT2x3:
glVertexAttrib3fv(it->index + 1, &zeroes[0]);
case GL_FLOAT_VEC3:
glVertexAttrib3fv(it->index, &zeroes[0]);
break;
case GL_FLOAT_MAT4:
glVertexAttrib4fv(it->index + 3, &zeroes[0]);
case GL_FLOAT_MAT3x4:
glVertexAttrib4fv(it->index + 2, &zeroes[0]);
case GL_FLOAT_MAT2x4:
glVertexAttrib4fv(it->index + 1, &zeroes[0]);
case GL_FLOAT_VEC4:
glVertexAttrib4fv(it->index, &zeroes[0]);
break;
default:
std::cerr << "Error! Attribute " << it->name <<
" has unsupported type " << it->type << std::endl;
}
}
}
}
}
// ------------------------------------------------------------------------
void VBOMesh::AddAttributeSet(const std::string &name,
AttributeSet *attribSet, bool isCustom)
{
AttributeSet *oldSet = attributeSets[name];
assert(!oldSet);
if (oldSet) delete oldSet;
attributeSets[name] = attribSet;
if (isCustom)
{
customAttribs[name] = attribSet;
}
}
// ------------------------------------------------------------------------
AttributeSet *VBOMesh::GetAttributeSet(const std::string &name)
{
AttributeMap::iterator it = attributeSets.find(name);
if (it != attributeSets.end())
{
return it->second;
}
return 0;
}
// ------------------------------------------------------------------------
AttributeSet *VBOMesh::ReplaceAttributeSet(const std::string &name,
AttributeSet *attribSet)
{
AttributeMap::iterator it = attributeSets.find(name);
assert(it != attributeSets.end());
AttributeSet *oldSet = it->second;
it->second = attribSet;
// Check the custom sets
it = customAttribs.find(name);
if (it != customAttribs.end())
{
it->second = attribSet;
}
return oldSet;
}
}
<commit_msg>Removed unhelpful assert.<commit_after>#include "VBOMesh.h"
#include "AttributeSet.h"
#include "GLBlaat/GLBuffer.h"
#include "GLBlaat/GLProgram.h"
#include <vector>
#include <map>
#include <string>
#include <cassert>
#include <iostream>
// These might be missing with older GLEW headers
#ifndef GL_FLOAT_MAT2x3
#define GL_FLOAT_MAT2x3 0x8B65
#define GL_FLOAT_MAT2x4 0x8B66
#define GL_FLOAT_MAT3x2 0x8B67
#define GL_FLOAT_MAT3x4 0x8B68
#define GL_FLOAT_MAT4x2 0x8B69
#define GL_FLOAT_MAT4x3 0x8B6A
#endif
namespace NQVTK
{
// ------------------------------------------------------------------------
VBOMesh::VBOMesh()
{
}
// ------------------------------------------------------------------------
VBOMesh::~VBOMesh()
{
// Delete the attribute sets
for (AttributeMap::iterator it = attributeSets.begin();
it != attributeSets.end(); ++it)
{
delete it->second;
}
}
// ------------------------------------------------------------------------
void VBOMesh::BindAttributes() const
{
for (AttributeMap::const_iterator it = attributeSets.begin();
it != attributeSets.end(); ++it)
{
it->second->Bind();
}
}
// ------------------------------------------------------------------------
void VBOMesh::UnbindAttributes() const
{
for (AttributeMap::const_iterator it = attributeSets.begin();
it != attributeSets.end(); ++it)
{
it->second->Unbind();
}
}
// ------------------------------------------------------------------------
void VBOMesh::SetupAttributes(
const std::vector<GLAttributeInfo> requiredAttribs)
{
// Clear all attributes
for (AttributeMap::iterator it = this->customAttribs.begin();
it != this->customAttribs.end(); ++it)
{
it->second->DontUse();
}
// Set attributes used by the program
for (std::vector<GLAttributeInfo>::const_iterator it =
requiredAttribs.begin(); it != requiredAttribs.end(); ++it)
{
if (it->index >= 0)
{
AttributeMap::iterator ait = customAttribs.find(it->name);
if (ait != customAttribs.end())
{
ait->second->UseAsVertexAttrib(it->index);
}
else
{
// Set a default value for the attribute
// It seems we can ignore the size, as array elements are listed
// separately in requiredAttribs.
// Matrices seem to be listed once; rows need to be set separately
// TODO: type for mat4 is returned as vec4, how to distinguish?
std::vector<float> zeroes;
zeroes.resize(4 * 4);
switch (it->type)
{
case GL_FLOAT:
glVertexAttrib1fv(it->index, &zeroes[0]);
break;
case GL_FLOAT_MAT4x2:
glVertexAttrib2fv(it->index + 3, &zeroes[0]);
case GL_FLOAT_MAT3x2:
glVertexAttrib2fv(it->index + 2, &zeroes[0]);
case GL_FLOAT_MAT2:
glVertexAttrib2fv(it->index + 1, &zeroes[0]);
case GL_FLOAT_VEC2:
glVertexAttrib2fv(it->index, &zeroes[0]);
break;
case GL_FLOAT_MAT4x3:
glVertexAttrib3fv(it->index + 3, &zeroes[0]);
case GL_FLOAT_MAT3:
glVertexAttrib3fv(it->index + 2, &zeroes[0]);
case GL_FLOAT_MAT2x3:
glVertexAttrib3fv(it->index + 1, &zeroes[0]);
case GL_FLOAT_VEC3:
glVertexAttrib3fv(it->index, &zeroes[0]);
break;
case GL_FLOAT_MAT4:
glVertexAttrib4fv(it->index + 3, &zeroes[0]);
case GL_FLOAT_MAT3x4:
glVertexAttrib4fv(it->index + 2, &zeroes[0]);
case GL_FLOAT_MAT2x4:
glVertexAttrib4fv(it->index + 1, &zeroes[0]);
case GL_FLOAT_VEC4:
glVertexAttrib4fv(it->index, &zeroes[0]);
break;
default:
std::cerr << "Error! Attribute " << it->name <<
" has unsupported type " << it->type << std::endl;
}
}
}
}
}
// ------------------------------------------------------------------------
void VBOMesh::AddAttributeSet(const std::string &name,
AttributeSet *attribSet, bool isCustom)
{
AttributeSet *oldSet = attributeSets[name];
if (oldSet) delete oldSet;
attributeSets[name] = attribSet;
if (isCustom)
{
customAttribs[name] = attribSet;
}
}
// ------------------------------------------------------------------------
AttributeSet *VBOMesh::GetAttributeSet(const std::string &name)
{
AttributeMap::iterator it = attributeSets.find(name);
if (it != attributeSets.end())
{
return it->second;
}
return 0;
}
// ------------------------------------------------------------------------
AttributeSet *VBOMesh::ReplaceAttributeSet(const std::string &name,
AttributeSet *attribSet)
{
AttributeMap::iterator it = attributeSets.find(name);
assert(it != attributeSets.end());
AttributeSet *oldSet = it->second;
it->second = attribSet;
// Check the custom sets
it = customAttribs.find(name);
if (it != customAttribs.end())
{
it->second = attribSet;
}
return oldSet;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textdlgs.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:15:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#undef SC_DLLIMPLEMENTATION
// ohne precompiled Headers uebersetzen !!!
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include <svx/svxids.hrc>
#define ITEMID_FONTLIST SID_ATTR_CHAR_FONTLIST
#define ITEMID_TABSTOP 0
//CHINA001 #include <svx/chardlg.hxx>
#include <svx/flstitem.hxx>
//CHINA001 #include <svx/paragrph.hxx>
//CHINA001 #include <svx/tabstpge.hxx>
#include <sfx2/objsh.hxx>
#include <svtools/cjkoptions.hxx>
#include "textdlgs.hxx"
#include "scresid.hxx"
#include "sc.hrc"
#include <svx/svxids.hrc> //add CHINA001
#include <svtools/intitem.hxx> //add CHINA001
#include <svx/flagsdef.hxx> //CHINA001
// -----------------------------------------------------------------------
ScCharDlg::ScCharDlg( Window* pParent, const SfxItemSet* pAttr,
const SfxObjectShell* pDocShell ) :
SfxTabDialog ( pParent, ScResId( RID_SCDLG_CHAR ), pAttr ),
rOutAttrs ( *pAttr ),
rDocShell ( *pDocShell )
{
FreeResource();
AddTabPage( RID_SVXPAGE_CHAR_NAME ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_NAME, SvxCharNamePage::Create, 0);
AddTabPage( RID_SVXPAGE_CHAR_EFFECTS ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_EFFECTS, SvxCharEffectsPage::Create, 0);
AddTabPage( RID_SVXPAGE_CHAR_POSITION ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_POSITION, SvxCharPositionPage::Create, 0);
}
// -----------------------------------------------------------------------
void __EXPORT ScCharDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool())); //CHINA001
switch( nId )
{
case RID_SVXPAGE_CHAR_NAME:
{
SvxFontListItem aItem(*( (const SvxFontListItem*)
( rDocShell.GetItem( SID_ATTR_CHAR_FONTLIST) ) ) );
//CHINA001 ( (SvxCharNamePage&) rPage ).SetFontList( aItem );
aSet.Put (SvxFontListItem( aItem.GetFontList(), SID_ATTR_CHAR_FONTLIST));
rPage.PageCreated(aSet);
}
break;
case RID_SVXPAGE_CHAR_EFFECTS:
//CHINA001 ( (SvxCharEffectsPage&) rPage ).DisableControls(
//CHINA001 DISABLE_CASEMAP);
aSet.Put (SfxUInt16Item(SID_DISABLE_CTL,DISABLE_CASEMAP)); //CHINA001
rPage.PageCreated(aSet);
break;
default:
break;
}
}
// -----------------------------------------------------------------------
ScParagraphDlg::ScParagraphDlg( Window* pParent, const SfxItemSet* pAttr ) :
SfxTabDialog ( pParent, ScResId( RID_SCDLG_PARAGRAPH ), pAttr ),
rOutAttrs ( *pAttr )
{
FreeResource();
SvtCJKOptions aCJKOptions;
AddTabPage( RID_SVXPAGE_STD_PARAGRAPH );//CHINA001 AddTabPage( RID_SVXPAGE_STD_PARAGRAPH, SvxStdParagraphTabPage::Create, 0);
AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH );//CHINA001 AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH, SvxParaAlignTabPage::Create, 0);
//AddTabPage( RID_SVXPAGE_EXT_PARAGRAPH, SvxExtParagraphTabPage::Create, 0);
if ( aCJKOptions.IsAsianTypographyEnabled() )
AddTabPage( RID_SVXPAGE_PARA_ASIAN);//CHINA001 AddTabPage( RID_SVXPAGE_PARA_ASIAN, SvxAsianTabPage::Create,0);
else
RemoveTabPage( RID_SVXPAGE_PARA_ASIAN );
AddTabPage( RID_SVXPAGE_TABULATOR );//CHINA001 AddTabPage( RID_SVXPAGE_TABULATOR, SvxTabulatorTabPage::Create, 0);
}
// -----------------------------------------------------------------------
void __EXPORT ScParagraphDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
switch( nId )
{
case RID_SVXPAGE_TABULATOR:
{
//CHINA001 ( (SvxTabulatorTabPage&) rPage ).
//CHINA001 DisableControls( TABTYPE_ALL &~TABTYPE_LEFT |
//CHINA001 TABFILL_ALL &~TABFILL_NONE );
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001
aSet.Put(SfxUInt16Item(SID_SVXTABULATORTABPAGE_CONTROLFLAGS,TABTYPE_ALL &~TABTYPE_LEFT |
TABFILL_ALL &~TABFILL_NONE ));
rPage.PageCreated(aSet);//add CHINA001
}
break;
}
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.7.216); FILE MERGED 2006/07/12 10:02:46 kaib 1.7.216.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textdlgs.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2006-07-21 14:11:42 $
*
* 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_sc.hxx"
#undef SC_DLLIMPLEMENTATION
// ohne precompiled Headers uebersetzen !!!
// INCLUDE ---------------------------------------------------------------
#include <svx/svxids.hrc>
#define ITEMID_FONTLIST SID_ATTR_CHAR_FONTLIST
#define ITEMID_TABSTOP 0
//CHINA001 #include <svx/chardlg.hxx>
#include <svx/flstitem.hxx>
//CHINA001 #include <svx/paragrph.hxx>
//CHINA001 #include <svx/tabstpge.hxx>
#include <sfx2/objsh.hxx>
#include <svtools/cjkoptions.hxx>
#include "textdlgs.hxx"
#include "scresid.hxx"
#include "sc.hrc"
#include <svx/svxids.hrc> //add CHINA001
#include <svtools/intitem.hxx> //add CHINA001
#include <svx/flagsdef.hxx> //CHINA001
// -----------------------------------------------------------------------
ScCharDlg::ScCharDlg( Window* pParent, const SfxItemSet* pAttr,
const SfxObjectShell* pDocShell ) :
SfxTabDialog ( pParent, ScResId( RID_SCDLG_CHAR ), pAttr ),
rOutAttrs ( *pAttr ),
rDocShell ( *pDocShell )
{
FreeResource();
AddTabPage( RID_SVXPAGE_CHAR_NAME ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_NAME, SvxCharNamePage::Create, 0);
AddTabPage( RID_SVXPAGE_CHAR_EFFECTS ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_EFFECTS, SvxCharEffectsPage::Create, 0);
AddTabPage( RID_SVXPAGE_CHAR_POSITION ); //CHINA001 AddTabPage( RID_SVXPAGE_CHAR_POSITION, SvxCharPositionPage::Create, 0);
}
// -----------------------------------------------------------------------
void __EXPORT ScCharDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool())); //CHINA001
switch( nId )
{
case RID_SVXPAGE_CHAR_NAME:
{
SvxFontListItem aItem(*( (const SvxFontListItem*)
( rDocShell.GetItem( SID_ATTR_CHAR_FONTLIST) ) ) );
//CHINA001 ( (SvxCharNamePage&) rPage ).SetFontList( aItem );
aSet.Put (SvxFontListItem( aItem.GetFontList(), SID_ATTR_CHAR_FONTLIST));
rPage.PageCreated(aSet);
}
break;
case RID_SVXPAGE_CHAR_EFFECTS:
//CHINA001 ( (SvxCharEffectsPage&) rPage ).DisableControls(
//CHINA001 DISABLE_CASEMAP);
aSet.Put (SfxUInt16Item(SID_DISABLE_CTL,DISABLE_CASEMAP)); //CHINA001
rPage.PageCreated(aSet);
break;
default:
break;
}
}
// -----------------------------------------------------------------------
ScParagraphDlg::ScParagraphDlg( Window* pParent, const SfxItemSet* pAttr ) :
SfxTabDialog ( pParent, ScResId( RID_SCDLG_PARAGRAPH ), pAttr ),
rOutAttrs ( *pAttr )
{
FreeResource();
SvtCJKOptions aCJKOptions;
AddTabPage( RID_SVXPAGE_STD_PARAGRAPH );//CHINA001 AddTabPage( RID_SVXPAGE_STD_PARAGRAPH, SvxStdParagraphTabPage::Create, 0);
AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH );//CHINA001 AddTabPage( RID_SVXPAGE_ALIGN_PARAGRAPH, SvxParaAlignTabPage::Create, 0);
//AddTabPage( RID_SVXPAGE_EXT_PARAGRAPH, SvxExtParagraphTabPage::Create, 0);
if ( aCJKOptions.IsAsianTypographyEnabled() )
AddTabPage( RID_SVXPAGE_PARA_ASIAN);//CHINA001 AddTabPage( RID_SVXPAGE_PARA_ASIAN, SvxAsianTabPage::Create,0);
else
RemoveTabPage( RID_SVXPAGE_PARA_ASIAN );
AddTabPage( RID_SVXPAGE_TABULATOR );//CHINA001 AddTabPage( RID_SVXPAGE_TABULATOR, SvxTabulatorTabPage::Create, 0);
}
// -----------------------------------------------------------------------
void __EXPORT ScParagraphDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
switch( nId )
{
case RID_SVXPAGE_TABULATOR:
{
//CHINA001 ( (SvxTabulatorTabPage&) rPage ).
//CHINA001 DisableControls( TABTYPE_ALL &~TABTYPE_LEFT |
//CHINA001 TABFILL_ALL &~TABFILL_NONE );
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//add CHINA001
aSet.Put(SfxUInt16Item(SID_SVXTABULATORTABPAGE_CONTROLFLAGS,TABTYPE_ALL &~TABTYPE_LEFT |
TABFILL_ALL &~TABFILL_NONE ));
rPage.PageCreated(aSet);//add CHINA001
}
break;
}
}
<|endoftext|> |
<commit_before>// This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
static const char* kMimeTypes[][2] = {
{"image/jpeg", ".jpg"},
{"image/jpeg", ".jpeg"},
{"image/png", ".png"},
};
void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images)
{
for (size_t i = 0; i < data->materials_count; ++i)
{
const cgltf_material& material = data->materials[i];
if (material.has_pbr_metallic_roughness)
{
const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image)
images[pbr.base_color_texture.texture->image - data->images].srgb = true;
}
if (material.has_pbr_specular_glossiness)
{
const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image)
images[pbr.diffuse_texture.texture->image - data->images].srgb = true;
}
if (material.emissive_texture.texture && material.emissive_texture.texture->image)
images[material.emissive_texture.texture->image - data->images].srgb = true;
if (material.normal_texture.texture && material.normal_texture.texture->image)
images[material.normal_texture.texture->image - data->images].normal_map = true;
}
}
const char* inferMimeType(const char* path)
{
const char* ext = strrchr(path, '.');
if (!ext)
return "";
std::string extl = ext;
for (size_t i = 0; i < extl.length(); ++i)
extl[i] = char(tolower(extl[i]));
for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
if (extl == kMimeTypes[i][1])
return kMimeTypes[i][0];
return "";
}
static const char* mimeExtension(const char* mime_type)
{
for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
if (strcmp(kMimeTypes[i][0], mime_type) == 0)
return kMimeTypes[i][1];
return ".raw";
}
#ifdef __EMSCRIPTEN__
EM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), {
var cp = require('child_process');
var stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ];
var ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio });
return ret.status == null ? 256 : ret.status;
});
EM_JS(const char*, readenv, (const char* name), {
var val = process.env[UTF8ToString(name)];
if (!val) return 0;
var ret = _malloc(lengthBytesUTF8(val) + 1);
stringToUTF8(val, ret, lengthBytesUTF8(val) + 1);
return ret;
});
#else
static int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr)
{
#ifdef _WIN32
std::string ignore = "nul";
#else
std::string ignore = "/dev/null";
#endif
std::string cmd = cmd_;
if (ignore_stdout)
(cmd += " >") += ignore;
if (ignore_stderr)
(cmd += " 2>") += ignore;
return system(cmd.c_str());
}
static const char* readenv(const char* name)
{
return getenv(name);
}
#endif
bool checkBasis(bool verbose)
{
const char* basisu_path = readenv("BASISU_PATH");
std::string cmd = basisu_path ? basisu_path : "basisu";
cmd += " -version";
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0;
}
bool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
(void)scale;
TempFile temp_input(mimeExtension(mime_type));
TempFile temp_output(".basis");
if (!writeFile(temp_input.path.c_str(), data))
return false;
const char* basisu_path = readenv("BASISU_PATH");
std::string cmd = basisu_path ? basisu_path : "basisu";
char ql[16];
sprintf(ql, "%d", (quality * 255 + 50) / 100);
cmd += " -q ";
cmd += ql;
cmd += " -mipmap";
if (normal_map)
{
cmd += " -normal_map";
// for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness
}
else if (!srgb)
{
cmd += " -linear";
}
if (uastc)
{
cmd += " -uastc";
}
cmd += " -file ";
cmd += temp_input.path;
cmd += " -output_file ";
cmd += temp_output.path;
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ false);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0 && readFile(temp_output.path.c_str(), result);
}
bool checkKtx(bool verbose)
{
const char* toktx_path = readenv("TOKTX_PATH");
std::string cmd = toktx_path ? toktx_path : "toktx";
cmd += " --version";
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0;
}
bool encodeKtx(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
TempFile temp_input(mimeExtension(mime_type));
TempFile temp_output(".ktx2");
if (!writeFile(temp_input.path.c_str(), data))
return false;
const char* toktx_path = readenv("TOKTX_PATH");
std::string cmd = toktx_path ? toktx_path : "toktx";
cmd += " --2d";
cmd += " --t2";
cmd += " --automipmap";
if (scale < 1)
{
char sl[128];
sprintf(sl, "%g", scale);
cmd += " --scale ";
cmd += sl;
}
if (uastc)
{
cmd += " --uastc 2";
cmd += " --zcmp 9";
}
else
{
char ql[16];
sprintf(ql, "%d", (quality * 255 + 50) / 100);
cmd += " --bcmp";
cmd += " --qlevel ";
cmd += ql;
// for optimal quality we should specify separate_rg_to_color_alpha but this requires renderer awareness
if (normal_map)
cmd += " --normal_map";
}
if (srgb)
cmd += " --srgb";
else
cmd += " --linear";
cmd += " -- ";
cmd += temp_output.path;
cmd += " ";
cmd += temp_input.path;
int rc = execute(cmd.c_str(), /* ignore_stdout= */ false, /* ignore_stderr= */ false);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0 && readFile(temp_output.path.c_str(), result);
}
<commit_msg>gltfpack: Add --nowarn to command line options<commit_after>// This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
static const char* kMimeTypes[][2] = {
{"image/jpeg", ".jpg"},
{"image/jpeg", ".jpeg"},
{"image/png", ".png"},
};
void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images)
{
for (size_t i = 0; i < data->materials_count; ++i)
{
const cgltf_material& material = data->materials[i];
if (material.has_pbr_metallic_roughness)
{
const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image)
images[pbr.base_color_texture.texture->image - data->images].srgb = true;
}
if (material.has_pbr_specular_glossiness)
{
const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image)
images[pbr.diffuse_texture.texture->image - data->images].srgb = true;
}
if (material.emissive_texture.texture && material.emissive_texture.texture->image)
images[material.emissive_texture.texture->image - data->images].srgb = true;
if (material.normal_texture.texture && material.normal_texture.texture->image)
images[material.normal_texture.texture->image - data->images].normal_map = true;
}
}
const char* inferMimeType(const char* path)
{
const char* ext = strrchr(path, '.');
if (!ext)
return "";
std::string extl = ext;
for (size_t i = 0; i < extl.length(); ++i)
extl[i] = char(tolower(extl[i]));
for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
if (extl == kMimeTypes[i][1])
return kMimeTypes[i][0];
return "";
}
static const char* mimeExtension(const char* mime_type)
{
for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
if (strcmp(kMimeTypes[i][0], mime_type) == 0)
return kMimeTypes[i][1];
return ".raw";
}
#ifdef __EMSCRIPTEN__
EM_JS(int, execute, (const char* cmd, bool ignore_stdout, bool ignore_stderr), {
var cp = require('child_process');
var stdio = [ 'ignore', ignore_stdout ? 'ignore' : 'inherit', ignore_stderr ? 'ignore' : 'inherit' ];
var ret = cp.spawnSync(UTF8ToString(cmd), [], {shell:true, stdio:stdio });
return ret.status == null ? 256 : ret.status;
});
EM_JS(const char*, readenv, (const char* name), {
var val = process.env[UTF8ToString(name)];
if (!val) return 0;
var ret = _malloc(lengthBytesUTF8(val) + 1);
stringToUTF8(val, ret, lengthBytesUTF8(val) + 1);
return ret;
});
#else
static int execute(const char* cmd_, bool ignore_stdout, bool ignore_stderr)
{
#ifdef _WIN32
std::string ignore = "nul";
#else
std::string ignore = "/dev/null";
#endif
std::string cmd = cmd_;
if (ignore_stdout)
(cmd += " >") += ignore;
if (ignore_stderr)
(cmd += " 2>") += ignore;
return system(cmd.c_str());
}
static const char* readenv(const char* name)
{
return getenv(name);
}
#endif
bool checkBasis(bool verbose)
{
const char* basisu_path = readenv("BASISU_PATH");
std::string cmd = basisu_path ? basisu_path : "basisu";
cmd += " -version";
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0;
}
bool encodeBasis(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
(void)scale;
TempFile temp_input(mimeExtension(mime_type));
TempFile temp_output(".basis");
if (!writeFile(temp_input.path.c_str(), data))
return false;
const char* basisu_path = readenv("BASISU_PATH");
std::string cmd = basisu_path ? basisu_path : "basisu";
char ql[16];
sprintf(ql, "%d", (quality * 255 + 50) / 100);
cmd += " -q ";
cmd += ql;
cmd += " -mipmap";
if (normal_map)
{
cmd += " -normal_map";
// for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness
}
else if (!srgb)
{
cmd += " -linear";
}
if (uastc)
{
cmd += " -uastc";
}
cmd += " -file ";
cmd += temp_input.path;
cmd += " -output_file ";
cmd += temp_output.path;
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ false);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0 && readFile(temp_output.path.c_str(), result);
}
bool checkKtx(bool verbose)
{
const char* toktx_path = readenv("TOKTX_PATH");
std::string cmd = toktx_path ? toktx_path : "toktx";
cmd += " --version";
int rc = execute(cmd.c_str(), /* ignore_stdout= */ true, /* ignore_stderr= */ true);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0;
}
bool encodeKtx(const std::string& data, const char* mime_type, std::string& result, bool normal_map, bool srgb, int quality, float scale, bool uastc, bool verbose)
{
TempFile temp_input(mimeExtension(mime_type));
TempFile temp_output(".ktx2");
if (!writeFile(temp_input.path.c_str(), data))
return false;
const char* toktx_path = readenv("TOKTX_PATH");
std::string cmd = toktx_path ? toktx_path : "toktx";
cmd += " --t2";
cmd += " --2d";
cmd += " --automipmap";
cmd += " --nowarn";
if (scale < 1)
{
char sl[128];
sprintf(sl, "%g", scale);
cmd += " --scale ";
cmd += sl;
}
if (uastc)
{
cmd += " --uastc 2";
cmd += " --zcmp 9";
}
else
{
char ql[16];
sprintf(ql, "%d", (quality * 255 + 50) / 100);
cmd += " --bcmp";
cmd += " --qlevel ";
cmd += ql;
// for optimal quality we should specify separate_rg_to_color_alpha but this requires renderer awareness
if (normal_map)
cmd += " --normal_map";
}
if (srgb)
cmd += " --srgb";
else
cmd += " --linear";
cmd += " -- ";
cmd += temp_output.path;
cmd += " ";
cmd += temp_input.path;
int rc = execute(cmd.c_str(), /* ignore_stdout= */ false, /* ignore_stderr= */ false);
if (verbose)
printf("%s => %d\n", cmd.c_str(), rc);
return rc == 0 && readFile(temp_output.path.c_str(), result);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ViewShellBase.hxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:43:56 $
*
* 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 SD_VIEW_SHELL_BASE_HXX
#define SD_VIEW_SHELL_BASE_HXX
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_GLOB_HXX
#include "glob.hxx"
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _VIEWFAC_HXX
#include <sfx2/viewfac.hxx>
#endif
#include <memory>
#include <boost/shared_ptr.hpp>
class SdDrawDocument;
class SfxRequest;
namespace sd { namespace tools {
class EventMultiplexer;
} }
namespace sd {
class DrawController;
class DrawDocShell;
class FormShellManager;
class PrintManager;
class ToolBarManager;
class UpdateLockManager;
class ViewShell;
class ViewShellManager;
/** SfxViewShell descendant that the stacked Draw/Impress shells are
based on.
<p>The "base" part of the name does not mean that this is a base
class of some class hierarchy. It rather is the base of the
stacked shells.</p>
<p>This class starts as a new and relatively small class. Over
time as much code as possible should be moved from the stacked
shells to this class.</p>
*/
class ViewShellBase
: public SfxViewShell
{
public:
TYPEINFO();
SFX_DECL_VIEWFACTORY(ViewShellBase);
SFX_DECL_INTERFACE(SD_IF_SDVIEWSHELLBASE)
/** This constructor is used by the view factory of the SFX macros.
Note that LateInit() has to be called after the constructor
terminates and before doing anything else.
*/
ViewShellBase (
SfxViewFrame *pFrame,
SfxViewShell* pOldShell);
virtual ~ViewShellBase (void);
/** This method is part of the object construction. It HAS to be called
after the constructor has created a new object.
*/
virtual void LateInit (const ::rtl::OUString& rsDefaultView);
ViewShellManager& GetViewShellManager (void) const;
/** Return the main view shell stacked on the called ViewShellBase
object. This is usually the view shell displayed in the center
pane.
*/
::boost::shared_ptr<ViewShell> GetMainViewShell (void) const;
/** When given a view frame this static method returns the
corresponding sd::ViewShellBase object.
@return
When the SfxViewShell of the given frame is not a
ViewShellBase object then NULL is returned.
*/
static ViewShellBase* GetViewShellBase (SfxViewFrame* pFrame);
DrawDocShell* GetDocShell (void) const;
SdDrawDocument* GetDocument (void) const;
/** Callback function for retrieving item values related to menu entries.
*/
void GetMenuState (SfxItemSet& rSet);
/** Callback function for general slot calls. At the moment these are
slots for switching the pane docking windows on and off.
*/
virtual void Execute (SfxRequest& rRequest);
/** Callback function for retrieving item values related to certain
slots. This is the companion of Execute() and handles the slots
concerned with showing the pane docking windows.
*/
virtual void GetState (SfxItemSet& rSet);
SvBorder GetBorder (bool bOuterResize);
virtual void InnerResizePixel (const Point& rOrigin, const Size& rSize);
virtual void OuterResizePixel (const Point& rOrigin, const Size& rSize);
/** This call is forwarded to the main sub-shell.
*/
virtual ErrCode DoVerb (long nVerb);
/// Forwarded to the print manager.
virtual SfxPrinter* GetPrinter (BOOL bCreate = FALSE);
/// Forwarded to the print manager.
virtual USHORT SetPrinter (
SfxPrinter* pNewPrinter,
USHORT nDiffFlags = SFX_PRINTER_ALL);
/// Forwarded to the print manager.
virtual PrintDialog* CreatePrintDialog (::Window *pParent);
/// Forwarded to the print manager.
virtual SfxTabPage* CreatePrintOptionsPage (
::Window *pParent,
const SfxItemSet &rOptions);
/// Forwarded to the print manager.
virtual USHORT Print (SfxProgress& rProgress, BOOL bIsAPI, PrintDialog* pDialog);
/// Forwarded to the print manager.
virtual ErrCode DoPrint (
SfxPrinter *pPrinter,
PrintDialog *pPrintDialog,
BOOL bSilent, BOOL bIsAPI );
/// Forwarded to the print manager.
USHORT SetPrinterOptDlg (
SfxPrinter* pNewPrinter,
USHORT nDiffFlags = SFX_PRINTER_ALL,
BOOL _bShowDialog = TRUE);
virtual void PreparePrint (PrintDialog* pPrintDialog);
/// Forward methods to main sub shell.
virtual void WriteUserDataSequence (
::com::sun::star::uno::Sequence <
::com::sun::star::beans::PropertyValue >&,
sal_Bool bBrowse = sal_False);
/** Pass the given properties to the main view shell. After that we
ensure that the right view shell type is displayed in the center
pane.
*/
virtual void ReadUserDataSequence (
const ::com::sun::star::uno::Sequence <
::com::sun::star::beans::PropertyValue >&,
sal_Bool bBrowse = sal_False);
virtual void UIActivating( SfxInPlaceClient* );
virtual void UIDeactivated( SfxInPlaceClient* );
virtual void Activate (BOOL IsMDIActivate);
virtual void Deactivate (BOOL IsMDIActivate);
virtual void SetZoomFactor (
const Fraction &rZoomX,
const Fraction &rZoomY);
virtual USHORT PrepareClose (BOOL bUI = TRUE, BOOL bForBrowsing = FALSE);
virtual void WriteUserData (String&, BOOL bBrowse = FALSE);
virtual void ReadUserData (const String&, BOOL bBrowse = FALSE);
virtual SdrView* GetDrawView (void) const;
virtual void AdjustPosSizePixel (const Point &rOfs, const Size &rSize);
/** When <TRUE/> is given, then the mouse shape is set to hour glass (or
whatever the busy shape looks like on the system.)
*/
void SetBusyState (bool bBusy);
/** Call this method when the controls of this view shell or the
embedded sub shell need to be rearranged. This is necessary
e.g. when the border has been modified (UpdateBorder() calls this
method).
This method is like ResizePixel() with no arguments.
*/
void Rearrange (void);
/** Update the border that is set with SfxViewShell::SetBorderPixel().
This is done by adding the border used by the ViewShellBase itself
with the border used by the main view shell.
@param bForce if true the borders are also updated if old border
and new border are same.
*/
void UpdateBorder ( bool bForce = false );
/** With this method the UI controls can be turned on or off. It is
used by the FuSlideShow to hide the UI controls while showing a
non-full-screen or in-window presentation in the center pane.
*/
void ShowUIControls (bool bVisible);
/** this method starts the presentation by
executing the slot SID_PRESENTATION asynchronous */
void StartPresentation();
/** this methods ends the presentation by
executing the slot SID_PRESENTATION_END asynchronous */
void StopPresentation();
/** Return an event multiplexer. It is a single class that forwards
events from various sources. This method must not be called before
LateInit() has terminated.
*/
tools::EventMultiplexer& GetEventMultiplexer (void);
/** returns the complete area of the current view relative to the frame
window
*/
const Rectangle& getClientRectangle() const;
::boost::shared_ptr<UpdateLockManager> GetUpdateLockManager (void) const;
::boost::shared_ptr<ToolBarManager> GetToolBarManager (void) const;
FormShellManager& GetFormShellManager (void) const;
DrawController& GetDrawController (void) const;
void SetViewTabBar (const ::rtl::Reference<ViewTabBar>& rViewTabBar);
/** Return the window that is used by the main view shell to display its
view and other UI elements, like scroll bars and rulers. Ownership
of that window remains with the called ViewShellBase object.
*/
::Window* GetViewWindow (void);
protected:
osl::Mutex maMutex;
virtual void SFX_NOTIFY(SfxBroadcaster& rBC,
const TypeId& rBCType,
const SfxHint& rHint,
const TypeId& rHintType);
virtual void InitializeFramework (void);
private:
class Implementation;
::std::auto_ptr<Implementation> mpImpl;
::std::auto_ptr<ViewShellManager> mpViewShellManager;
DrawDocShell* mpDocShell;
SdDrawDocument* mpDocument;
/// The print manager is responsible for printing documents.
::std::auto_ptr<PrintManager> mpPrintManager;
::std::auto_ptr<FormShellManager> mpFormShellManager;
::std::auto_ptr<tools::EventMultiplexer> mpEventMultiplexer;
::boost::shared_ptr<UpdateLockManager> mpUpdateLockManager;
/** Determine from the properties of the document shell the initial type
of the view shell in the center pane. We use this method to avoid
starting with the wrong type. When ReadUserDataSequence() is called
we check that the right type is active and change again if that is
not the case because something went wrong.
*/
::rtl::OUString GetInitialViewShellType (void);
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS pathfinder01 (1.18.62); FILE MERGED 2007/07/03 13:03:16 cl 1.18.62.1: #i41800# implemented support for path animation editing for custom animations<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ViewShellBase.hxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: rt $ $Date: 2007-07-06 13:13:26 $
*
* 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 SD_VIEW_SHELL_BASE_HXX
#define SD_VIEW_SHELL_BASE_HXX
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_GLOB_HXX
#include "glob.hxx"
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _VIEWFAC_HXX
#include <sfx2/viewfac.hxx>
#endif
#include <memory>
#include <boost/shared_ptr.hpp>
#include <set>
class SdDrawDocument;
class SfxRequest;
namespace sd { namespace tools {
class EventMultiplexer;
} }
namespace sd {
class DrawController;
class DrawDocShell;
class FormShellManager;
class PrintManager;
class ToolBarManager;
class UpdateLockManager;
class ViewShell;
class ViewShellManager;
class CustomHandleManager;
/** SfxViewShell descendant that the stacked Draw/Impress shells are
based on.
<p>The "base" part of the name does not mean that this is a base
class of some class hierarchy. It rather is the base of the
stacked shells.</p>
<p>This class starts as a new and relatively small class. Over
time as much code as possible should be moved from the stacked
shells to this class.</p>
*/
class ViewShellBase
: public SfxViewShell
{
public:
TYPEINFO();
SFX_DECL_VIEWFACTORY(ViewShellBase);
SFX_DECL_INTERFACE(SD_IF_SDVIEWSHELLBASE)
/** This constructor is used by the view factory of the SFX macros.
Note that LateInit() has to be called after the constructor
terminates and before doing anything else.
*/
ViewShellBase (
SfxViewFrame *pFrame,
SfxViewShell* pOldShell);
virtual ~ViewShellBase (void);
/** This method is part of the object construction. It HAS to be called
after the constructor has created a new object.
*/
virtual void LateInit (const ::rtl::OUString& rsDefaultView);
ViewShellManager& GetViewShellManager (void) const;
/** Return the main view shell stacked on the called ViewShellBase
object. This is usually the view shell displayed in the center
pane.
*/
::boost::shared_ptr<ViewShell> GetMainViewShell (void) const;
/** When given a view frame this static method returns the
corresponding sd::ViewShellBase object.
@return
When the SfxViewShell of the given frame is not a
ViewShellBase object then NULL is returned.
*/
static ViewShellBase* GetViewShellBase (SfxViewFrame* pFrame);
DrawDocShell* GetDocShell (void) const;
SdDrawDocument* GetDocument (void) const;
/** Callback function for retrieving item values related to menu entries.
*/
void GetMenuState (SfxItemSet& rSet);
/** Callback function for general slot calls. At the moment these are
slots for switching the pane docking windows on and off.
*/
virtual void Execute (SfxRequest& rRequest);
/** Callback function for retrieving item values related to certain
slots. This is the companion of Execute() and handles the slots
concerned with showing the pane docking windows.
*/
virtual void GetState (SfxItemSet& rSet);
SvBorder GetBorder (bool bOuterResize);
virtual void InnerResizePixel (const Point& rOrigin, const Size& rSize);
virtual void OuterResizePixel (const Point& rOrigin, const Size& rSize);
/** This call is forwarded to the main sub-shell.
*/
virtual ErrCode DoVerb (long nVerb);
/// Forwarded to the print manager.
virtual SfxPrinter* GetPrinter (BOOL bCreate = FALSE);
/// Forwarded to the print manager.
virtual USHORT SetPrinter (
SfxPrinter* pNewPrinter,
USHORT nDiffFlags = SFX_PRINTER_ALL);
/// Forwarded to the print manager.
virtual PrintDialog* CreatePrintDialog (::Window *pParent);
/// Forwarded to the print manager.
virtual SfxTabPage* CreatePrintOptionsPage (
::Window *pParent,
const SfxItemSet &rOptions);
/// Forwarded to the print manager.
virtual USHORT Print (SfxProgress& rProgress, BOOL bIsAPI, PrintDialog* pDialog);
/// Forwarded to the print manager.
virtual ErrCode DoPrint (
SfxPrinter *pPrinter,
PrintDialog *pPrintDialog,
BOOL bSilent, BOOL bIsAPI );
/// Forwarded to the print manager.
USHORT SetPrinterOptDlg (
SfxPrinter* pNewPrinter,
USHORT nDiffFlags = SFX_PRINTER_ALL,
BOOL _bShowDialog = TRUE);
virtual void PreparePrint (PrintDialog* pPrintDialog);
/// Forward methods to main sub shell.
virtual void WriteUserDataSequence (
::com::sun::star::uno::Sequence <
::com::sun::star::beans::PropertyValue >&,
sal_Bool bBrowse = sal_False);
/** Pass the given properties to the main view shell. After that we
ensure that the right view shell type is displayed in the center
pane.
*/
virtual void ReadUserDataSequence (
const ::com::sun::star::uno::Sequence <
::com::sun::star::beans::PropertyValue >&,
sal_Bool bBrowse = sal_False);
virtual void UIActivating( SfxInPlaceClient* );
virtual void UIDeactivated( SfxInPlaceClient* );
virtual void Activate (BOOL IsMDIActivate);
virtual void Deactivate (BOOL IsMDIActivate);
virtual void SetZoomFactor (
const Fraction &rZoomX,
const Fraction &rZoomY);
virtual USHORT PrepareClose (BOOL bUI = TRUE, BOOL bForBrowsing = FALSE);
virtual void WriteUserData (String&, BOOL bBrowse = FALSE);
virtual void ReadUserData (const String&, BOOL bBrowse = FALSE);
virtual SdrView* GetDrawView (void) const;
virtual void AdjustPosSizePixel (const Point &rOfs, const Size &rSize);
/** When <TRUE/> is given, then the mouse shape is set to hour glass (or
whatever the busy shape looks like on the system.)
*/
void SetBusyState (bool bBusy);
/** Call this method when the controls of this view shell or the
embedded sub shell need to be rearranged. This is necessary
e.g. when the border has been modified (UpdateBorder() calls this
method).
This method is like ResizePixel() with no arguments.
*/
void Rearrange (void);
/** Update the border that is set with SfxViewShell::SetBorderPixel().
This is done by adding the border used by the ViewShellBase itself
with the border used by the main view shell.
@param bForce if true the borders are also updated if old border
and new border are same.
*/
void UpdateBorder ( bool bForce = false );
/** With this method the UI controls can be turned on or off. It is
used by the FuSlideShow to hide the UI controls while showing a
non-full-screen or in-window presentation in the center pane.
*/
void ShowUIControls (bool bVisible);
/** this method starts the presentation by
executing the slot SID_PRESENTATION asynchronous */
void StartPresentation();
/** this methods ends the presentation by
executing the slot SID_PRESENTATION_END asynchronous */
void StopPresentation();
/** Return an event multiplexer. It is a single class that forwards
events from various sources. This method must not be called before
LateInit() has terminated.
*/
tools::EventMultiplexer& GetEventMultiplexer (void);
/** returns the complete area of the current view relative to the frame
window
*/
const Rectangle& getClientRectangle() const;
::boost::shared_ptr<UpdateLockManager> GetUpdateLockManager (void) const;
::boost::shared_ptr<ToolBarManager> GetToolBarManager (void) const;
FormShellManager& GetFormShellManager (void) const;
DrawController& GetDrawController (void) const;
void SetViewTabBar (const ::rtl::Reference<ViewTabBar>& rViewTabBar);
/** Return the window that is used by the main view shell to display its
view and other UI elements, like scroll bars and rulers. Ownership
of that window remains with the called ViewShellBase object.
*/
::Window* GetViewWindow (void);
CustomHandleManager& getCustomHandleManager() const;
protected:
osl::Mutex maMutex;
virtual void SFX_NOTIFY(SfxBroadcaster& rBC,
const TypeId& rBCType,
const SfxHint& rHint,
const TypeId& rHintType);
virtual void InitializeFramework (void);
private:
class Implementation;
::std::auto_ptr<Implementation> mpImpl;
::std::auto_ptr<ViewShellManager> mpViewShellManager;
DrawDocShell* mpDocShell;
SdDrawDocument* mpDocument;
/// The print manager is responsible for printing documents.
::std::auto_ptr<PrintManager> mpPrintManager;
::std::auto_ptr<FormShellManager> mpFormShellManager;
::std::auto_ptr<tools::EventMultiplexer> mpEventMultiplexer;
::boost::shared_ptr<UpdateLockManager> mpUpdateLockManager;
::std::auto_ptr<CustomHandleManager> mpCustomHandleManager;
/** Determine from the properties of the document shell the initial type
of the view shell in the center pane. We use this method to avoid
starting with the wrong type. When ReadUserDataSequence() is called
we check that the right type is active and change again if that is
not the case because something went wrong.
*/
::rtl::OUString GetInitialViewShellType (void);
};
class ICustomhandleSupplier
{
public:
virtual void addCustomHandler( SdrView& rSourceView, ViewShell::ShellType eShellType, SdrHdlList& rHandlerList ) = 0;
};
class CustomHandleManager : public ICustomhandleSupplier
{
public:
CustomHandleManager( ViewShellBase& rViewShellBase );
virtual ~CustomHandleManager();
void registerSupplier( ICustomhandleSupplier* pSupplier );
void unRegisterSupplier( ICustomhandleSupplier* pSupplier );
virtual void addCustomHandler( SdrView& rSourceView, ViewShell::ShellType eShellType, SdrHdlList& rHandlerList );
private:
ViewShellBase& mrViewShellBase;
std::set< ICustomhandleSupplier* > maSupplier;
};
} // end of namespace sd
#endif
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* 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.
*
* @file JPetCmdParser.cpp
*/
#include "JPetCmdParser.h"
#include <iostream>
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../JPetLoggerInclude.h"
#include "../JPetScopeConfigParser/JPetScopeConfigParser.h"
#include <stdexcept>
JPetCmdParser::JPetCmdParser(): fOptionsDescriptions("Allowed options")
{
std::vector<int> tmp;
tmp.push_back(-1);
tmp.push_back(-1);
fOptionsDescriptions.add_options()
("help,h", "Displays this help message.")
("type,t", po::value<std::string>()->required()->implicit_value(""), "Type of file: hld, root or scope.")
("file,f", po::value< std::vector<std::string> >()->required()->multitoken(), "File(s) to open.")
("range,r", po::value< std::vector<int> >()->multitoken()->default_value(tmp, ""), "Range of events to process e.g. -r 1 1000 .")
("param,p", po::value<std::string>(), "xml file with TRB settings used by the unpacker program.")
("runId,i", po::value<int>(), "Run id.")
("progressBar,b", "Progress bar.")
("localDB,l", po::value<std::string>(), "The file to use as the parameter database.")
("localDBCreate,L", po::value<std::string>(), "File name to which the parameter database will be saved.");
}
JPetCmdParser::~JPetCmdParser()
{
/**/
}
std::vector<JPetOptions> JPetCmdParser::parseAndGenerateOptions(int argc, const char** argv)
{
po::variables_map variablesMap;
if (argc == 1) {
ERROR("No options provided.");
std::cerr << getOptionsDescription() << "\n";
throw std::invalid_argument("No options provided.");
}
po::store(po::parse_command_line(argc, argv, fOptionsDescriptions), variablesMap);
/* print out help */
if (variablesMap.count("help")) {
std::cout << getOptionsDescription() << "\n";
exit(0);
}
po::notify(variablesMap);
if (!areCorrectOptions(variablesMap)) {
throw std::invalid_argument("Wrong user options provided! Check the log!");
}
return generateOptions(variablesMap);
}
bool JPetCmdParser::areCorrectOptions(const po::variables_map& variablesMap) const
{
/* Parse range of events */
if (variablesMap.count("range")) {
if (variablesMap["range"].as< std::vector<int> >().size() != 2) {
ERROR("Wrong number of bounds in range.");
std::cerr << "Wrong number of bounds in range: " << variablesMap["range"].as< std::vector<int> >().size() << std::endl;
return false;
}
if (
variablesMap["range"].as< std::vector<int> >()[0]
> variablesMap["range"].as< std::vector<int> >()[1]) {
ERROR("Wrong range of events.");
std::cerr << "Wrong range of events." << std::endl;
return false;
}
}
if (!isCorrectFileType(getFileType(variablesMap))) {
ERROR("Wrong type of file.");
std::cerr << "Wrong type of file: " << getFileType(variablesMap) << std::endl;
std::cerr << "Possible options: hld, root or scope" << std::endl;
return false;
}
if (isRunNumberSet(variablesMap)) {
int l_runId = variablesMap["runId"].as<int>();
if (l_runId <= 0) {
ERROR("Run id must be a number larger than 0.");
std::cerr << "Run id must be a number larger than 0." << l_runId << std::endl;
return false;
}
}
if (isProgressBarSet(variablesMap)) {
int l_progressBar = variablesMap["progressBar"].as<int>();
if (l_progressBar != 0 && l_progressBar != 1) {
ERROR("Wrong parameter of progressbar.");
std::cerr << "Wrong parameter of progressbar: " << l_progressBar << std::endl;
return false;
}
}
if (isLocalDBSet(variablesMap)) {
std::string localDBName = getLocalDBName(variablesMap);
if ( !JPetCommonTools::ifFileExisting(localDBName) ) {
ERROR("File : " + localDBName + " does not exist.");
std::cerr << "File : " << localDBName << " does not exist" << std::endl;
return false;
}
}
std::vector<std::string> fileNames(variablesMap["file"].as< std::vector<std::string> >());
for (unsigned int i = 0; i < fileNames.size(); i++) {
if ( ! JPetCommonTools::ifFileExisting(fileNames[i]) ) {
std::string fileName = fileNames[i];
ERROR("File : " + fileName + " does not exist.");
std::cerr << "File : " << fileNames[i] << " does not exist" << std::endl;
return false;
}
}
/// The run number option is neclegted if the input file is set as "scope"
if (isRunNumberSet(variablesMap)) {
if (getFileType(variablesMap) =="scope") {
WARNING("Run number was specified but the input file type is a scope!\n The run number will be ignored!");
}
}
return true;
}
std::vector<JPetOptions> JPetCmdParser::generateOptions(const po::variables_map& optsMap) const
{
std::map<std::string, std::string> options = JPetOptions::getDefaultOptions();
auto fileType = getFileType(optsMap);
if (isCorrectFileType(fileType)) {
options.at("inputFileType") = fileType;
}
if (isRunNumberSet(optsMap)) {
options.at("runId") = std::to_string(getRunNumber(optsMap));
}
if (isProgressBarSet(optsMap)) {
options.at("progressBar") = "true";
}
if (isLocalDBSet(optsMap)) {
options["localDB"] = getLocalDBName(optsMap);
}
if (isLocalDBCreateSet(optsMap)) {
options["localDBCreate"] = getLocalDBCreateName(optsMap);
}
auto firstEvent = getLowerEventBound(optsMap);
auto lastEvent = getHigherEventBound(optsMap);
if (firstEvent >= 0) options.at("firstEvent") = std::to_string(firstEvent);
if (lastEvent >= 0) options.at("lastEvent") = std::to_string(lastEvent);
auto files = getFileNames(optsMap);
std::vector<JPetOptions> optionContainer;
/// In case of scope there is one special input file
/// which is a json config file which must be parsed.
/// Based on its content the set of input directories are generated.
/// The input directories contain data files.
/// The config input file name also should be stored in a special option field.
if (fileType == "scope") {
assert(files.size() == 1); /// there should be only file which is config.
auto configFileName = files.front();
options.at("scopeConfigFile") = configFileName;
JPetScopeConfigParser scopeConfigParser;
/// The scope module must use a fake input file name which will be used to
/// produce the correct output file names by the following modules.
/// At the same time, the input directory with true input files must be
/// also added. The container of pairs <directory, fileName> is generated
/// based on the content of the configuration file.
JPetScopeConfigParser::DirFileContainer dirsAndFiles = scopeConfigParser.getInputDirectoriesAndFakeInputFiles(configFileName);
for (auto dirAndFile : dirsAndFiles) {
options.at("scopeInputDirectory") = dirAndFile.first;
options.at("inputFile") = dirAndFile.second;
optionContainer.push_back(JPetOptions(options));
}
} else {
/// for every single input file we create separate JPetOptions
for (auto file : files) {
options.at("inputFile") = file;
optionContainer.push_back(JPetOptions(options));
}
}
return optionContainer;
}
//#endif /* __CINT__ */
<commit_msg>Remove unnecessary tmp vector in JPetCmdParser constructor<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* 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.
*
* @file JPetCmdParser.cpp
*/
#include "JPetCmdParser.h"
#include <iostream>
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../JPetLoggerInclude.h"
#include "../JPetScopeConfigParser/JPetScopeConfigParser.h"
#include <stdexcept>
JPetCmdParser::JPetCmdParser(): fOptionsDescriptions("Allowed options")
{
fOptionsDescriptions.add_options()
("help,h", "Displays this help message.")
("type,t", po::value<std::string>()->required()->implicit_value(""), "Type of file: hld, root or scope.")
("file,f", po::value< std::vector<std::string> >()->required()->multitoken(), "File(s) to open.")
("range,r", po::value< std::vector<int> >()->multitoken()->default_value({ -1, -1}, ""), "Range of events to process e.g. -r 1 1000 .")
("param,p", po::value<std::string>(), "xml file with TRB settings used by the unpacker program.")
("runId,i", po::value<int>(), "Run id.")
("progressBar,b", "Progress bar.")
("localDB,l", po::value<std::string>(), "The file to use as the parameter database.")
("localDBCreate,L", po::value<std::string>(), "File name to which the parameter database will be saved.");
}
JPetCmdParser::~JPetCmdParser()
{
/**/
}
std::vector<JPetOptions> JPetCmdParser::parseAndGenerateOptions(int argc, const char** argv)
{
po::variables_map variablesMap;
if (argc == 1) {
ERROR("No options provided.");
std::cerr << getOptionsDescription() << "\n";
throw std::invalid_argument("No options provided.");
}
po::store(po::parse_command_line(argc, argv, fOptionsDescriptions), variablesMap);
/* print out help */
if (variablesMap.count("help")) {
std::cout << getOptionsDescription() << "\n";
exit(0);
}
po::notify(variablesMap);
if (!areCorrectOptions(variablesMap)) {
throw std::invalid_argument("Wrong user options provided! Check the log!");
}
return generateOptions(variablesMap);
}
bool JPetCmdParser::areCorrectOptions(const po::variables_map& variablesMap) const
{
/* Parse range of events */
if (variablesMap.count("range")) {
if (variablesMap["range"].as< std::vector<int> >().size() != 2) {
ERROR("Wrong number of bounds in range.");
std::cerr << "Wrong number of bounds in range: " << variablesMap["range"].as< std::vector<int> >().size() << std::endl;
return false;
}
if (
variablesMap["range"].as< std::vector<int> >()[0]
> variablesMap["range"].as< std::vector<int> >()[1]) {
ERROR("Wrong range of events.");
std::cerr << "Wrong range of events." << std::endl;
return false;
}
}
if (!isCorrectFileType(getFileType(variablesMap))) {
ERROR("Wrong type of file.");
std::cerr << "Wrong type of file: " << getFileType(variablesMap) << std::endl;
std::cerr << "Possible options: hld, root or scope" << std::endl;
return false;
}
if (isRunNumberSet(variablesMap)) {
int l_runId = variablesMap["runId"].as<int>();
if (l_runId <= 0) {
ERROR("Run id must be a number larger than 0.");
std::cerr << "Run id must be a number larger than 0." << l_runId << std::endl;
return false;
}
}
if (isProgressBarSet(variablesMap)) {
int l_progressBar = variablesMap["progressBar"].as<int>();
if (l_progressBar != 0 && l_progressBar != 1) {
ERROR("Wrong parameter of progressbar.");
std::cerr << "Wrong parameter of progressbar: " << l_progressBar << std::endl;
return false;
}
}
if (isLocalDBSet(variablesMap)) {
std::string localDBName = getLocalDBName(variablesMap);
if ( !JPetCommonTools::ifFileExisting(localDBName) ) {
ERROR("File : " + localDBName + " does not exist.");
std::cerr << "File : " << localDBName << " does not exist" << std::endl;
return false;
}
}
std::vector<std::string> fileNames(variablesMap["file"].as< std::vector<std::string> >());
for (unsigned int i = 0; i < fileNames.size(); i++) {
if ( ! JPetCommonTools::ifFileExisting(fileNames[i]) ) {
std::string fileName = fileNames[i];
ERROR("File : " + fileName + " does not exist.");
std::cerr << "File : " << fileNames[i] << " does not exist" << std::endl;
return false;
}
}
/// The run number option is neclegted if the input file is set as "scope"
if (isRunNumberSet(variablesMap)) {
if (getFileType(variablesMap) == "scope") {
WARNING("Run number was specified but the input file type is a scope!\n The run number will be ignored!");
}
}
return true;
}
std::vector<JPetOptions> JPetCmdParser::generateOptions(const po::variables_map& optsMap) const
{
std::map<std::string, std::string> options = JPetOptions::getDefaultOptions();
auto fileType = getFileType(optsMap);
if (isCorrectFileType(fileType)) {
options.at("inputFileType") = fileType;
}
if (isRunNumberSet(optsMap)) {
options.at("runId") = std::to_string(getRunNumber(optsMap));
}
if (isProgressBarSet(optsMap)) {
options.at("progressBar") = "true";
}
if (isLocalDBSet(optsMap)) {
options["localDB"] = getLocalDBName(optsMap);
}
if (isLocalDBCreateSet(optsMap)) {
options["localDBCreate"] = getLocalDBCreateName(optsMap);
}
auto firstEvent = getLowerEventBound(optsMap);
auto lastEvent = getHigherEventBound(optsMap);
if (firstEvent >= 0) options.at("firstEvent") = std::to_string(firstEvent);
if (lastEvent >= 0) options.at("lastEvent") = std::to_string(lastEvent);
auto files = getFileNames(optsMap);
std::vector<JPetOptions> optionContainer;
/// In case of scope there is one special input file
/// which is a json config file which must be parsed.
/// Based on its content the set of input directories are generated.
/// The input directories contain data files.
/// The config input file name also should be stored in a special option field.
if (fileType == "scope") {
assert(files.size() == 1); /// there should be only file which is config.
auto configFileName = files.front();
options.at("scopeConfigFile") = configFileName;
JPetScopeConfigParser scopeConfigParser;
/// The scope module must use a fake input file name which will be used to
/// produce the correct output file names by the following modules.
/// At the same time, the input directory with true input files must be
/// also added. The container of pairs <directory, fileName> is generated
/// based on the content of the configuration file.
JPetScopeConfigParser::DirFileContainer dirsAndFiles = scopeConfigParser.getInputDirectoriesAndFakeInputFiles(configFileName);
for (auto dirAndFile : dirsAndFiles) {
options.at("scopeInputDirectory") = dirAndFile.first;
options.at("inputFile") = dirAndFile.second;
optionContainer.push_back(JPetOptions(options));
}
} else {
/// for every single input file we create separate JPetOptions
for (auto file : files) {
options.at("inputFile") = file;
optionContainer.push_back(JPetOptions(options));
}
}
return optionContainer;
}
//#endif /* __CINT__ */
<|endoftext|> |
<commit_before>/*
* OpenTyrian Classic: A modern cross-platform port of Tyrian
* Copyright (C) 2007-2009 The OpenTyrian Development Team
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "font.h"
#include "joystick.h"
#include "jukebox.h"
#include "keyboard.h"
#include "lds_play.h"
#include "loudness.h"
#include "mtrand.h"
#include "nortsong.h"
#include "opentyr.h"
#include "palette.h"
#include "sprite.h"
#include "starlib.h"
#include "vga_palette.h"
#include "video.h"
void jukebox( void )
{
bool trigger_quit = false, // true when user wants to quit
quitting = false;
bool hide_text = false;
bool fade_looped_songs = true, fading_song = false;
bool stopped = false;
bool fx = false;
int fx_num = 0;
int palette_fade_steps = 15;
int diff[256][3];
init_step_fade_palette(diff, vga_palette, 0, 255);
JE_starlib_init();
int fade_volume = tyrMusicVolume;
for (; ; )
{
if (!stopped && !audio_disabled)
{
if (songlooped && fade_looped_songs)
fading_song = true;
if (fading_song)
{
if (fade_volume > 5)
{
fade_volume -= 2;
}
else
{
fade_volume = tyrMusicVolume;
fading_song = false;
}
set_volume(fade_volume, fxVolume);
}
if (!playing || (songlooped && fade_looped_songs && !fading_song))
play_song(mt_rand() % MUSIC_NUM);
}
setdelay(1);
SDL_FillRect(VGAScreenSeg, NULL, 0);
// starlib input needs to be rewritten
JE_starlib_main();
push_joysticks_as_keyboard();
service_SDL_events(true);
if (!hide_text)
{
char buffer[60];
if (fx)
snprintf(buffer, sizeof(buffer), "%d %s", fx_num + 1, soundTitle[fx_num]);
else
snprintf(buffer, sizeof(buffer), "%d %s", song_playing + 1, musicTitle[song_playing]);
const int x = VGAScreen->w / 2;
draw_font_hv(VGAScreen, x, 170, "Press ESC to quit the jukebox.", small_font, centered, 1, 0);
draw_font_hv(VGAScreen, x, 180, "Arrow keys change the song being played.", small_font, centered, 1, 0);
draw_font_hv(VGAScreen, x, 190, buffer, small_font, centered, 1, 4);
}
if (palette_fade_steps > 0)
step_fade_palette(diff, palette_fade_steps--, 0, 255);
JE_showVGA();
wait_delay();
// quit on mouse click
Uint16 x, y;
if (JE_mousePosition(&x, &y) > 0)
trigger_quit = true;
if (newkey)
{
switch (lastkey_sym)
{
case SDLK_ESCAPE: // quit jukebox
case SDLK_q:
trigger_quit = true;
break;
case SDLK_SPACE:
hide_text = !hide_text;
break;
case SDLK_f:
fading_song = !fading_song;
break;
case SDLK_n:
fade_looped_songs = !fade_looped_songs;
break;
case SDLK_SLASH: // switch to sfx mode
fx = !fx;
break;
case SDLK_COMMA:
if (fx && --fx_num < 0)
fx_num = SAMPLE_COUNT - 1;
break;
case SDLK_PERIOD:
if (fx && ++fx_num >= SAMPLE_COUNT)
fx_num = 0;
break;
case SDLK_SEMICOLON:
if (fx)
JE_playSampleNum(fx_num + 1);
break;
case SDLK_LEFT:
case SDLK_UP:
case SDLK_LCTRL:
play_song((song_playing > 0 ? song_playing : MUSIC_NUM) - 1);
stopped = false;
break;
case SDLK_RETURN:
case SDLK_RIGHT:
case SDLK_DOWN:
case SDLK_LALT:
play_song((song_playing + 1) % MUSIC_NUM);
stopped = false;
break;
case SDLK_s: // stop song
stop_song();
stopped = true;
break;
case SDLK_r: // restart song
restart_song();
stopped = false;
break;
default:
break;
}
}
// user wants to quit, start fade-out
if (trigger_quit && !quitting)
{
palette_fade_steps = 15;
SDL_Color black = { 0, 0, 0 };
init_step_fade_solid(diff, black, 0, 255);
quitting = true;
}
// if fade-out finished, we can finally quit
if (quitting && palette_fade_steps == 0)
break;
}
set_volume(tyrMusicVolume, fxVolume);
}
// kate: tab-width 4; vim: set noet:
<commit_msg>Add touch input support in opentyrian menu, 4th commit: This adds support for changing the song in the Jukebox by touch.<commit_after>/*
* OpenTyrian Classic: A modern cross-platform port of Tyrian
* Copyright (C) 2007-2009 The OpenTyrian Development Team
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "font.h"
#include "joystick.h"
#include "jukebox.h"
#include "keyboard.h"
#include "lds_play.h"
#include "loudness.h"
#include "mtrand.h"
#include "nortsong.h"
#include "opentyr.h"
#include "palette.h"
#include "sprite.h"
#include "starlib.h"
#include "vga_palette.h"
#include "video.h"
void jukebox( void )
{
bool trigger_quit = false, // true when user wants to quit
quitting = false;
bool hide_text = false;
bool fade_looped_songs = true, fading_song = false;
bool stopped = false;
bool fx = false;
int fx_num = 0;
int palette_fade_steps = 15;
int diff[256][3];
init_step_fade_palette(diff, vga_palette, 0, 255);
JE_starlib_init();
int fade_volume = tyrMusicVolume;
for (; ; )
{
if (!stopped && !audio_disabled)
{
if (songlooped && fade_looped_songs)
fading_song = true;
if (fading_song)
{
if (fade_volume > 5)
{
fade_volume -= 2;
}
else
{
fade_volume = tyrMusicVolume;
fading_song = false;
}
set_volume(fade_volume, fxVolume);
}
if (!playing || (songlooped && fade_looped_songs && !fading_song))
play_song(mt_rand() % MUSIC_NUM);
}
setdelay(1);
SDL_FillRect(VGAScreenSeg, NULL, 0);
// starlib input needs to be rewritten
JE_starlib_main();
push_joysticks_as_keyboard();
service_SDL_events(true);
if (!hide_text)
{
char buffer[60];
if (fx)
snprintf(buffer, sizeof(buffer), "%d %s", fx_num + 1, soundTitle[fx_num]);
else
snprintf(buffer, sizeof(buffer), "%d %s", song_playing + 1, musicTitle[song_playing]);
const int x = VGAScreen->w / 2;
#ifdef ANDROID
draw_font_hv(VGAScreen, x, 170, "Press the Back button to quit the jukebox.", small_font, centered, 1, 0);
draw_font_hv(VGAScreen, x, 180, "Touch to change the song being played.", small_font, centered, 1, 0);
#else
draw_font_hv(VGAScreen, x, 170, "Press ESC to quit the jukebox.", small_font, centered, 1, 0);
draw_font_hv(VGAScreen, x, 180, "Arrow keys change the song being played.", small_font, centered, 1, 0);
#endif
draw_font_hv(VGAScreen, x, 190, buffer, small_font, centered, 1, 4);
}
if (palette_fade_steps > 0)
step_fade_palette(diff, palette_fade_steps--, 0, 255);
JE_showVGA();
wait_delay();
#ifdef ANDROID
if (mousedown)
{
wait_noinput(true, true, true);
newkey = true;
if (mouse_x < 160)
lastkey_sym = SDLK_LEFT;
else
lastkey_sym = SDLK_RIGHT;
}
#else
// quit on mouse click
Uint16 x, y;
if (JE_mousePosition(&x, &y) > 0)
trigger_quit = true;
#endif
if (newkey)
{
switch (lastkey_sym)
{
case SDLK_ESCAPE: // quit jukebox
case SDLK_q:
trigger_quit = true;
break;
case SDLK_SPACE:
hide_text = !hide_text;
break;
case SDLK_f:
fading_song = !fading_song;
break;
case SDLK_n:
fade_looped_songs = !fade_looped_songs;
break;
case SDLK_SLASH: // switch to sfx mode
fx = !fx;
break;
case SDLK_COMMA:
if (fx && --fx_num < 0)
fx_num = SAMPLE_COUNT - 1;
break;
case SDLK_PERIOD:
if (fx && ++fx_num >= SAMPLE_COUNT)
fx_num = 0;
break;
case SDLK_SEMICOLON:
if (fx)
JE_playSampleNum(fx_num + 1);
break;
case SDLK_LEFT:
case SDLK_UP:
case SDLK_LCTRL:
play_song((song_playing > 0 ? song_playing : MUSIC_NUM) - 1);
stopped = false;
break;
case SDLK_RETURN:
case SDLK_RIGHT:
case SDLK_DOWN:
case SDLK_LALT:
play_song((song_playing + 1) % MUSIC_NUM);
stopped = false;
break;
case SDLK_s: // stop song
stop_song();
stopped = true;
break;
case SDLK_r: // restart song
restart_song();
stopped = false;
break;
default:
break;
}
}
// user wants to quit, start fade-out
if (trigger_quit && !quitting)
{
palette_fade_steps = 15;
SDL_Color black = { 0, 0, 0 };
init_step_fade_solid(diff, black, 0, 255);
quitting = true;
}
// if fade-out finished, we can finally quit
if (quitting && palette_fade_steps == 0)
break;
}
set_volume(tyrMusicVolume, fxVolume);
}
// kate: tab-width 4; vim: set noet:
<|endoftext|> |
<commit_before>/*
* v8cgi main file. Loosely based on V8's "shell" sample app.
*/
#define _STRING(x) #x
#define STRING(x) _STRING(x)
#include <sstream>
#include <v8.h>
#ifdef FASTCGI
# include <fcgi_stdio.h>
#endif
#include "js_system.h"
#include "js_io.h"
#include "js_socket.h"
#include "js_common.h"
#include "js_macros.h"
#ifndef windows
# include <dlfcn.h>
#else
# include <windows.h>
# define dlopen(x,y) (void*)LoadLibrary(x)
# define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)
# define dlclose(x) FreeLibrary((HMODULE)x)
#endif
// chdir()
#ifndef HAVE_CHDIR
# include <direct.h>
# define chdir(name) _chdir(name)
#endif
// getcwd()
#ifndef HAVE_GETCWD
# include <direct.h>
# define getcwd(name, bytes) _getcwd(name, bytes)
#endif
v8::Handle<v8::Array> __onexit;
char * cfgfile = NULL;
char * execfile = NULL;
v8::Persistent<v8::Context> context;
int total = 0;
void js_error(const char * message) {
int cgi = 0;
v8::Local<v8::Function> fun;
v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
if (context->IsObject()) {
v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
if (print->IsObject()) {
fun = v8::Local<v8::Function>::Cast(print);
cgi = 1;
}
}
if (!cgi) {
context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
}
v8::Handle<v8::Value> data[1];
data[0] = JS_STR(message);
fun->Call(context->ToObject(), 1, data);
}
void js_exception(v8::TryCatch* try_catch) {
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch->Exception());
v8::Handle<v8::Message> message = try_catch->Message();
std::string msgstring = "";
std::stringstream ss;
if (message.IsEmpty()) {
msgstring += *exception;
msgstring += "\n";
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
msgstring += *filename;
msgstring += ":";
ss << linenum;
msgstring += ss.str();
msgstring += ": ";
msgstring += *exception;
msgstring += "\n";
}
js_error(msgstring.c_str());
}
v8::Handle<v8::String> js_read(const char* name) {
FILE* file = fopen(name, "rb");
if (file == NULL) { return v8::Handle<v8::String>(); }
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (unsigned int i = 0; i < size;) {
size_t read = fread(&chars[i], 1, size - i, file);
i += read;
}
fclose(file);
/* remove shebang line */
std::string str = chars;
if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
unsigned int pfix = str.find('\n',0);
str.erase(0,pfix);
};
v8::Handle<v8::String> result = JS_STR(str.c_str());
delete[] chars;
return result;
}
int js_execute(const char * str, bool change) {
v8::HandleScope handle_scope;
v8::TryCatch try_catch;
v8::Handle<v8::String> name = JS_STR(str);
v8::Handle<v8::String> source = js_read(str);
if (source.IsEmpty()) {
std::string s = "Error reading '";
s += str;
s += "'\n";
js_error(s.c_str());
return 1;
}
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (script.IsEmpty()) {
js_exception(&try_catch);
return 1;
} else {
char * old = getcwd(NULL, 0);
char * end = strrchr((char *)str, '/');
if (end == NULL) {
end = strrchr((char *)str, '\\');
}
if (end != NULL && change) {
int len = end-str;
char * base = (char *) malloc(len+1);
strncpy(base, str, len);
base[len] = '\0';
chdir(base);
free(base);
}
v8::Handle<v8::Value> result = script->Run();
chdir(old);
if (result.IsEmpty()) {
js_exception(&try_catch);
return 1;
}
}
return 0;
}
int js_library(char * name) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
std::string path = "";
path += *pfx;
path += "/";
path += name;
if (path.find(".so") != std::string::npos || path.find(".dll") != std::string::npos) {
void * handle;
std::string error;
if (!(handle = dlopen(path.c_str(), RTLD_LAZY))) {
error = "Cannot load shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
void (*func) (v8::Handle<v8::Object>);
if (!(func = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, "init")))) {
dlclose(handle);
error = "Cannot initialize shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
func(v8::Context::GetCurrent()->Global());
return 0;
} else {
return js_execute(path.c_str(), false);
}
}
int js_autoload() {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
int cnt = list->Length();
for (int i=0;i<cnt;i++) {
v8::Handle<v8::Value> item = list->Get(JS_INT(i));
v8::String::Utf8Value name(item);
if (js_library(*name)) { return 1; }
}
return 0;
}
v8::Handle<v8::Value> _include(const v8::Arguments& args) {
bool ok = true;
int result;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_execute(*file, true);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _library(const v8::Arguments & args) {
v8::HandleScope handle_scope;
bool ok = true;
int result;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_library(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
__onexit->Set(JS_INT(__onexit->Length()), args[0]);
return v8::Undefined();
}
void main_finish() {
v8::HandleScope handle_scope;
uint32_t max = __onexit->Length();
v8::Handle<v8::Function> fun;
for (unsigned int i=0;i<max;i++) {
fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
}
}
int main_execute() {
v8::HandleScope handle_scope;
char * name = execfile;
if (name == NULL) { // try the PATH_TRANSLATED env var
v8::Handle<v8::Context> test = v8::Context::GetCurrent();
v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
if (pt->IsString()) {
v8::String::Utf8Value jsname(pt);
name = *jsname;
}
}
if (name == NULL) {
js_error("Nothing to do.\n");
return 1;
} else {
return js_execute(name, true);
}
}
int main_prepare(char ** envp) {
__onexit = v8::Array::New();
v8::Handle<v8::Object> g = context->Global();
g->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
g->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
g->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
g->Set(JS_STR("global"), g);
g->Set(JS_STR("Config"), v8::Object::New());
setup_system(envp, g);
setup_io(g);
setup_socket(g);
if (js_execute(cfgfile, false)) {
js_error("Cannot load configuration, quitting...\n");
return 1;
}
if (js_autoload()) {
js_error("Cannot load default libraries, quitting...\n");
return 1;
}
return 0;
}
int main_initialize(int argc, char ** argv) {
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
cfgfile = STRING(CONFIG_PATH);
int argptr = 0;
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
argptr = i;
if (strcmp(str, "-c") == 0 && i + 1 < argc) {
cfgfile = argv[i+1];
argptr = 0;
i++;
}
}
if (argptr) { execfile = argv[argptr]; }
FILE* file = fopen(cfgfile, "rb");
if (file == NULL) {
printf("Invalid configuration file.\n");
return 1;
}
fclose(file);
return 0;
}
int main_cycle(char ** envp) {
int result = 0;
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
context = v8::Context::New(NULL, global);
v8::Context::Scope context_scope(context);
result = main_prepare(envp);
if (result == 0) {
result = main_execute();
}
main_finish();
return result;
}
int main(int argc, char ** argv, char ** envp) {
int result = 0;
result = main_initialize(argc, argv);
if (result) { exit(1); }
#ifdef FASTCGI
while(FCGI_Accept() >= 0) {
#endif
result = main_cycle(envp);
#ifdef FASTCGI
FCGI_SetExitStatus(result);
#endif
#ifdef FASTCGI
}
#endif
return result;
}
<commit_msg>dll/so unloading<commit_after>/*
* v8cgi main file. Loosely based on V8's "shell" sample app.
*/
#define _STRING(x) #x
#define STRING(x) _STRING(x)
#include <sstream>
#include <v8.h>
#ifdef FASTCGI
# include <fcgi_stdio.h>
#endif
#include "js_system.h"
#include "js_io.h"
#include "js_socket.h"
#include "js_common.h"
#include "js_macros.h"
#ifndef windows
# include <dlfcn.h>
#else
# include <windows.h>
# define dlopen(x,y) (void*)LoadLibrary(x)
# define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)
# define dlclose(x) FreeLibrary((HMODULE)x)
#endif
// chdir()
#ifndef HAVE_CHDIR
# include <direct.h>
# define chdir(name) _chdir(name)
#endif
// getcwd()
#ifndef HAVE_GETCWD
# include <direct.h>
# define getcwd(name, bytes) _getcwd(name, bytes)
#endif
v8::Handle<v8::Array> __onexit; /* what to do on exit */
char * cfgfile = NULL; /* config file */
char * execfile = NULL; /* command-line specified file */
void ** handles; /* shared libraries */
int handlecount = 0;
int total = 0; /* fcgi debug */
void js_error(const char * message) {
int cgi = 0;
v8::Local<v8::Function> fun;
v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
if (context->IsObject()) {
v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
if (print->IsObject()) {
fun = v8::Local<v8::Function>::Cast(print);
cgi = 1;
}
}
if (!cgi) {
context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
}
v8::Handle<v8::Value> data[1];
data[0] = JS_STR(message);
fun->Call(context->ToObject(), 1, data);
}
void js_exception(v8::TryCatch* try_catch) {
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch->Exception());
v8::Handle<v8::Message> message = try_catch->Message();
std::string msgstring = "";
std::stringstream ss;
if (message.IsEmpty()) {
msgstring += *exception;
msgstring += "\n";
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
msgstring += *filename;
msgstring += ":";
ss << linenum;
msgstring += ss.str();
msgstring += ": ";
msgstring += *exception;
msgstring += "\n";
}
js_error(msgstring.c_str());
}
v8::Handle<v8::String> js_read(const char* name) {
FILE* file = fopen(name, "rb");
if (file == NULL) { return v8::Handle<v8::String>(); }
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (unsigned int i = 0; i < size;) {
size_t read = fread(&chars[i], 1, size - i, file);
i += read;
}
fclose(file);
/* remove shebang line */
std::string str = chars;
if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
unsigned int pfix = str.find('\n',0);
str.erase(0,pfix);
};
v8::Handle<v8::String> result = JS_STR(str.c_str());
delete[] chars;
return result;
}
int js_execute(const char * str, bool change) {
v8::HandleScope handle_scope;
v8::TryCatch try_catch;
v8::Handle<v8::String> name = JS_STR(str);
v8::Handle<v8::String> source = js_read(str);
if (source.IsEmpty()) {
std::string s = "Error reading '";
s += str;
s += "'\n";
js_error(s.c_str());
return 1;
}
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (script.IsEmpty()) {
js_exception(&try_catch);
return 1;
} else {
char * old = getcwd(NULL, 0);
char * end = strrchr((char *)str, '/');
if (end == NULL) {
end = strrchr((char *)str, '\\');
}
if (end != NULL && change) {
int len = end-str;
char * base = (char *) malloc(len+1);
strncpy(base, str, len);
base[len] = '\0';
chdir(base);
free(base);
}
v8::Handle<v8::Value> result = script->Run();
chdir(old);
if (result.IsEmpty()) {
js_exception(&try_catch);
return 1;
}
}
return 0;
}
int js_library(char * name) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
std::string path = "";
path += *pfx;
path += "/";
path += name;
if (path.find(".so") != std::string::npos || path.find(".dll") != std::string::npos) {
void * handle;
std::string error;
if (!(handle = dlopen(path.c_str(), RTLD_LAZY))) {
error = "Cannot load shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
void (*func) (v8::Handle<v8::Object>);
if (!(func = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, "init")))) {
dlclose(handle);
error = "Cannot initialize shared library '";
error += path;
error += "'\n";
js_error(error.c_str());
return 1;
}
handlecount++;
handles = (void **) realloc(handles, sizeof(void*) * handlecount);
handles[handlecount-1] = handle;
func(v8::Context::GetCurrent()->Global());
return 0;
} else {
return js_execute(path.c_str(), false);
}
}
int js_autoload() {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
int cnt = list->Length();
for (int i=0;i<cnt;i++) {
v8::Handle<v8::Value> item = list->Get(JS_INT(i));
v8::String::Utf8Value name(item);
if (js_library(*name)) { return 1; }
}
return 0;
}
v8::Handle<v8::Value> _include(const v8::Arguments& args) {
bool ok = true;
int result;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_execute(*file, true);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _library(const v8::Arguments & args) {
v8::HandleScope handle_scope;
bool ok = true;
int result;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = js_library(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
__onexit->Set(JS_INT(__onexit->Length()), args[0]);
return v8::Undefined();
}
void main_finish() {
v8::HandleScope handle_scope;
uint32_t max = __onexit->Length();
v8::Handle<v8::Function> fun;
for (unsigned int i=0;i<max;i++) {
fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
}
for (int i=0;i<handlecount;i++) {
dlclose(handles[i]);
}
handlecount = 0;
free(handles);
handles = NULL;
}
int main_execute() {
v8::HandleScope handle_scope;
char * name = execfile;
if (name == NULL) { // try the PATH_TRANSLATED env var
v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
if (pt->IsString()) {
v8::String::Utf8Value jsname(pt);
name = *jsname;
}
}
if (name == NULL) {
js_error("Nothing to do.\n");
return 1;
} else {
return js_execute(name, true);
}
}
int main_prepare(char ** envp) {
__onexit = v8::Array::New();
v8::Handle<v8::Object> g = v8::Context::GetCurrent()->Global();
g->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
g->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
g->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
g->Set(JS_STR("total"), JS_INT(total++));
g->Set(JS_STR("global"), g);
g->Set(JS_STR("Config"), v8::Object::New());
setup_system(envp, g);
setup_io(g);
setup_socket(g);
if (js_execute(cfgfile, false)) {
js_error("Cannot load configuration, quitting...\n");
return 1;
}
if (js_autoload()) {
js_error("Cannot load default libraries, quitting...\n");
return 1;
}
return 0;
}
int main_initialize(int argc, char ** argv) {
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
cfgfile = STRING(CONFIG_PATH);
int argptr = 0;
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
argptr = i;
if (strcmp(str, "-c") == 0 && i + 1 < argc) {
cfgfile = argv[i+1];
argptr = 0;
i++;
}
}
if (argptr) { execfile = argv[argptr]; }
FILE* file = fopen(cfgfile, "rb");
if (file == NULL) {
printf("Invalid configuration file.\n");
return 1;
}
fclose(file);
return 0;
}
int main_cycle(char ** envp) {
int result = 0;
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
v8::Context::Scope context_scope(context);
result = main_prepare(envp);
if (result == 0) {
result = main_execute();
}
main_finish();
return result;
}
int main(int argc, char ** argv, char ** envp) {
int result = 0;
result = main_initialize(argc, argv);
if (result) { exit(1); }
#ifdef FASTCGI
while(FCGI_Accept() >= 0) {
#endif
result = main_cycle(envp);
#ifdef FASTCGI
FCGI_SetExitStatus(result);
#endif
#ifdef FASTCGI
}
#endif
return result;
}
<|endoftext|> |
<commit_before>/*
* v8cgi main file. Loosely based on V8's "shell" sample app.
*/
#include <v8.h>
#include "js_system.h"
#include "js_io.h"
#include "js_mysql.h"
#include "js_gd.h"
#include "js_common.h"
#include <sstream>
#include <libgen.h>
#define _STRING(x) #x
#define STRING(x) _STRING(x)
v8::Handle<v8::Array> __onexit;
void die(int code) {
uint32_t max = __onexit->Length();
v8::Handle<v8::Function> fun;
for (unsigned int i=0;i<max;i++) {
fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
}
exit(code);
}
v8::Handle<v8::String> read_file(const char* name) {
printf("%s",name);
FILE* file = fopen(name, "rb");
if (file == NULL) return v8::Handle<v8::String>();
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (unsigned int i = 0; i < size;) {
size_t read = fread(&chars[i], 1, size - i, file);
i += read;
}
fclose(file);
/* remove shebang line */
std::string str = chars;
if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
unsigned int pfix = str.find('\n',0);
str.erase(0,pfix);
};
v8::Handle<v8::String> result = JS_STR(str.c_str());
delete[] chars;
return result;
}
void report_exception(v8::TryCatch* try_catch) {
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch->Exception());
v8::Handle<v8::Message> message = try_catch->Message();
std::string msgstring = "";
std::stringstream ss;
std::string tmp;
if (message.IsEmpty()) {
msgstring += *exception;
msgstring += "\n";
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
msgstring += *filename;
msgstring += ":";
ss << linenum;
ss >> tmp;
msgstring += tmp;
msgstring += ": ";
msgstring += *exception;
msgstring += "\n";
v8::String::Utf8Value sourceline(message->GetSourceLine());
msgstring += *sourceline;
msgstring += "\n";
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn();
for (int i = 0; i < start; i++) {
msgstring += " ";
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++) {
msgstring += "^";
}
msgstring += "\n";
}
int cgi = 0;
v8::Local<v8::Function> fun;
v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
if (context->IsObject()) {
v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
if (print->IsObject()) {
fun = v8::Local<v8::Function>::Cast(print);
cgi = 1;
}
}
if (!cgi) {
context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
}
v8::Handle<v8::Value> data[1];
data[0] = JS_STR(msgstring.c_str());
fun->Call(context->ToObject(), 1, data);
}
int execute_file(const char * str) {
v8::HandleScope handle_scope;
v8::TryCatch try_catch;
v8::Handle<v8::String> name = JS_STR(str);
v8::Handle<v8::String> source = read_file(str);
if (source.IsEmpty()) {
printf("Error reading '%s'\n", str);
return 1;
}
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (script.IsEmpty()) {
report_exception(&try_catch);
return 1;
} else {
char * old = getcwd(NULL, 0);
char * end = strrchr(str, '/');
if (end == NULL) {
end = strrchr(str, '\\');
}
if (end != NULL) {
int len = end-str;
char * base = (char *) malloc(len+1);
strncpy(base, str, len);
base[len] = '\0';
chdir(base);
}
v8::Handle<v8::Value> result = script->Run();
chdir(old);
if (result.IsEmpty()) {
report_exception(&try_catch);
return 1;
}
}
return 0;
}
int library(char * name) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
std::string path = "";
path += *pfx;
path += "/";
path += name;
return execute_file(path.c_str());
}
v8::Handle<v8::Value> _include(const v8::Arguments& args) {
bool ok = true;
int result;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = execute_file(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _library(const v8::Arguments & args) {
bool ok = true;
int result;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = library(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _exit(const v8::Arguments& args) {
die(args[0]->Int32Value());
return v8::Undefined();
}
v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
__onexit->Set(JS_INT(__onexit->Length()), args[0]);
return v8::Undefined();
}
int library_autoload() {
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
int cnt = list->Length();
for (int i=0;i<cnt;i++) {
v8::Handle<v8::Value> item = list->Get(JS_INT(i));
v8::String::Utf8Value name(item);
if (library(*name)) { return 1; }
}
return 0;
}
void init(char * cfg) {
int result = execute_file(cfg);
if (result) {
printf("Cannot load configuration, quitting...\n");
die(1);
}
result = library_autoload();
if (result) {
printf("Cannot load default libraries, quitting...\n");
die(1);
}
}
int main(int argc, char ** argv, char ** envp) {
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
v8::Context::Scope context_scope(context);
__onexit = v8::Array::New();
context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction());
context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
context->Global()->Set(JS_STR("global"), context->Global());
context->Global()->Set(JS_STR("Config"), v8::Object::New());
setup_system(envp, context->Global());
setup_io(context->Global());
#ifdef HAVE_MYSQL
setup_mysql(context->Global());
#endif
#ifdef HAVE_GD
setup_gd(context->Global());
#endif
char * cfg = STRING(CONFIG_PATH);
int argptr = 0;
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
argptr = i;
if (strcmp(str, "-c") == 0 && i + 1 < argc) {
cfg = argv[i+1];
argptr = 0;
i++;
}
}
init(cfg);
if (!argptr) {
// try the PATH_TRANSLATED env var
v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
if (pt->IsString()) {
v8::String::Utf8Value name(pt);
int result = execute_file(*name);
if (result) { die(result); }
} else {
printf("Nothing to do.\n");
}
} else {
int result = execute_file(argv[argptr]);
if (result) { die(result); }
}
die(0);
}
<commit_msg>no libgen<commit_after>/*
* v8cgi main file. Loosely based on V8's "shell" sample app.
*/
#include <v8.h>
#include "js_system.h"
#include "js_io.h"
#include "js_mysql.h"
#include "js_gd.h"
#include "js_common.h"
#include <sstream>
#define _STRING(x) #x
#define STRING(x) _STRING(x)
v8::Handle<v8::Array> __onexit;
void die(int code) {
uint32_t max = __onexit->Length();
v8::Handle<v8::Function> fun;
for (unsigned int i=0;i<max;i++) {
fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
}
exit(code);
}
v8::Handle<v8::String> read_file(const char* name) {
printf("%s",name);
FILE* file = fopen(name, "rb");
if (file == NULL) return v8::Handle<v8::String>();
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (unsigned int i = 0; i < size;) {
size_t read = fread(&chars[i], 1, size - i, file);
i += read;
}
fclose(file);
/* remove shebang line */
std::string str = chars;
if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
unsigned int pfix = str.find('\n',0);
str.erase(0,pfix);
};
v8::Handle<v8::String> result = JS_STR(str.c_str());
delete[] chars;
return result;
}
void report_exception(v8::TryCatch* try_catch) {
v8::HandleScope handle_scope;
v8::String::Utf8Value exception(try_catch->Exception());
v8::Handle<v8::Message> message = try_catch->Message();
std::string msgstring = "";
std::stringstream ss;
std::string tmp;
if (message.IsEmpty()) {
msgstring += *exception;
msgstring += "\n";
} else {
v8::String::Utf8Value filename(message->GetScriptResourceName());
int linenum = message->GetLineNumber();
msgstring += *filename;
msgstring += ":";
ss << linenum;
ss >> tmp;
msgstring += tmp;
msgstring += ": ";
msgstring += *exception;
msgstring += "\n";
v8::String::Utf8Value sourceline(message->GetSourceLine());
msgstring += *sourceline;
msgstring += "\n";
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn();
for (int i = 0; i < start; i++) {
msgstring += " ";
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++) {
msgstring += "^";
}
msgstring += "\n";
}
int cgi = 0;
v8::Local<v8::Function> fun;
v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
if (context->IsObject()) {
v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
if (print->IsObject()) {
fun = v8::Local<v8::Function>::Cast(print);
cgi = 1;
}
}
if (!cgi) {
context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
}
v8::Handle<v8::Value> data[1];
data[0] = JS_STR(msgstring.c_str());
fun->Call(context->ToObject(), 1, data);
}
int execute_file(const char * str) {
v8::HandleScope handle_scope;
v8::TryCatch try_catch;
v8::Handle<v8::String> name = JS_STR(str);
v8::Handle<v8::String> source = read_file(str);
if (source.IsEmpty()) {
printf("Error reading '%s'\n", str);
return 1;
}
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (script.IsEmpty()) {
report_exception(&try_catch);
return 1;
} else {
char * old = getcwd(NULL, 0);
char * end = strrchr(str, '/');
if (end == NULL) {
end = strrchr(str, '\\');
}
if (end != NULL) {
int len = end-str;
char * base = (char *) malloc(len+1);
strncpy(base, str, len);
base[len] = '\0';
chdir(base);
}
v8::Handle<v8::Value> result = script->Run();
chdir(old);
if (result.IsEmpty()) {
report_exception(&try_catch);
return 1;
}
}
return 0;
}
int library(char * name) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
std::string path = "";
path += *pfx;
path += "/";
path += name;
return execute_file(path.c_str());
}
v8::Handle<v8::Value> _include(const v8::Arguments& args) {
bool ok = true;
int result;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = execute_file(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _library(const v8::Arguments & args) {
bool ok = true;
int result;
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
v8::String::Utf8Value pfx(prefix);
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope;
v8::String::Utf8Value file(args[i]);
result = library(*file);
if (result != 0) { ok = false; }
}
return JS_BOOL(ok);
}
v8::Handle<v8::Value> _exit(const v8::Arguments& args) {
die(args[0]->Int32Value());
return v8::Undefined();
}
v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
__onexit->Set(JS_INT(__onexit->Length()), args[0]);
return v8::Undefined();
}
int library_autoload() {
v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
int cnt = list->Length();
for (int i=0;i<cnt;i++) {
v8::Handle<v8::Value> item = list->Get(JS_INT(i));
v8::String::Utf8Value name(item);
if (library(*name)) { return 1; }
}
return 0;
}
void init(char * cfg) {
int result = execute_file(cfg);
if (result) {
printf("Cannot load configuration, quitting...\n");
die(1);
}
result = library_autoload();
if (result) {
printf("Cannot load default libraries, quitting...\n");
die(1);
}
}
int main(int argc, char ** argv, char ** envp) {
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
v8::Context::Scope context_scope(context);
__onexit = v8::Array::New();
context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction());
context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
context->Global()->Set(JS_STR("global"), context->Global());
context->Global()->Set(JS_STR("Config"), v8::Object::New());
setup_system(envp, context->Global());
setup_io(context->Global());
#ifdef HAVE_MYSQL
setup_mysql(context->Global());
#endif
#ifdef HAVE_GD
setup_gd(context->Global());
#endif
char * cfg = STRING(CONFIG_PATH);
int argptr = 0;
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
argptr = i;
if (strcmp(str, "-c") == 0 && i + 1 < argc) {
cfg = argv[i+1];
argptr = 0;
i++;
}
}
init(cfg);
if (!argptr) {
// try the PATH_TRANSLATED env var
v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
if (pt->IsString()) {
v8::String::Utf8Value name(pt);
int result = execute_file(*name);
if (result) { die(result); }
} else {
printf("Nothing to do.\n");
}
} else {
int result = execute_file(argv[argptr]);
if (result) { die(result); }
}
die(0);
}
<|endoftext|> |
<commit_before>
#include <stdio.h>
#include "../../network/network.h"
int main(int argc, char *argv[])
{
/* create Data */
FILE *fp;
const int trainingDataNum = 60000;
float *trainingData[trainingDataNum];
float *labelData[trainingDataNum];
fp = fopen("dataset/mnist/train-images.txt", "r");
if(!fp) return 0;
for(int i = 0; i < trainingDataNum; i++) {
trainingData[i] = new float[784];
for(int j = 0; j < 784; j++) {
fscanf(fp, " %f", trainingData[i] + j);
}
}
fclose(fp);
fp = fopen("dataset/mnist/train-labels.txt", "r");
if(!fp) return 0;
int label;
for(int i = 0; i < trainingDataNum; i++) {
fscanf(fp, " %d", &label);
labelData[i] = new float[10];
for(int j = 0; j < 10; j++) {
*(labelData[i] + j) = ((j == label) ? 1.0 : 0.0);
}
}
fclose(fp);
const int testDataNum = 10000;
float *testData[testDataNum];
float *testLabelData[testDataNum];
fp = fopen("dataset/mnist/test-images.txt", "r");
if(!fp) return 0;
for(int i = 0; i < testDataNum; i++) {
testData[i] = new float[784];
for(int j = 0; j < 784; j++) {
fscanf(fp, " %f", testData[i] + j);
}
}
fclose(fp);
fp = fopen("dataset/mnist/test-labels.txt", "r");
if(!fp) return 0;
for(int i = 0; i < testDataNum; i++) {
fscanf(fp, " %d", &label);
testLabelData[i] = new float[10];
for(int j = 0; j < 10; j++) {
*(testLabelData[i] + j) = ((j == label) ? 1.0 : 0.0);
}
}
fclose(fp);
puts("loaded!");
/* parameters */
int epoch = 50;
float lr = 0.01;
/* Create Network */
Network *net;
net = new Network();
FullyConnectedLayer *full1, *full2;
act_T *act1t, *act2t;
act1t = new act_T;
act1t->apply = logistic_apply;
act1t->diff = logistic_diff;
act2t = new act_T;
act2t->apply = logistic_apply;
act2t->diff = logistic_diff;
full1 = new FullyConnectedLayer(784, 100, act1t, lr);
full2 = new FullyConnectedLayer(100, 10, act2t, lr);
net->appendLayer(full1);
net->appendLayer(full2);
net->setTest(testData, testLabelData, testDataNum);
//net->loadParameters((char *)"parameters/mnist/50.param");
net->train(trainingData, labelData, trainingDataNum, epoch);
net->saveParameters((char *)"parameters/mnist/50.param");
//net->test(testData, testLabelData, testDataNum);
delete net;
delete act1t;
delete act2t;
delete full1;
delete full2;
return 0;
}
<commit_msg>Add process of convert type integer to float<commit_after>
#include <stdio.h>
#include "../../network/network.h"
int main(int argc, char *argv[])
{
/* create Data */
FILE *fp;
int value;
const int trainingDataNum = 60000;
float *trainingData[trainingDataNum];
float *labelData[trainingDataNum];
fp = fopen("dataset/mnist/train-images.txt", "r");
if(!fp) return 0;
for(int i = 0; i < trainingDataNum; i++) {
trainingData[i] = new float[784];
for(int j = 0; j < 784; j++) {
fscanf(fp, " %d", &value);
*(trainingData[i] + j) = value / 255.0;
}
}
fclose(fp);
fp = fopen("dataset/mnist/train-labels.txt", "r");
if(!fp) return 0;
int label;
for(int i = 0; i < trainingDataNum; i++) {
fscanf(fp, " %d", &label);
labelData[i] = new float[10];
for(int j = 0; j < 10; j++) {
*(labelData[i] + j) = ((j == label) ? 1.0 : 0.0);
}
}
fclose(fp);
const int testDataNum = 10000;
float *testData[testDataNum];
float *testLabelData[testDataNum];
fp = fopen("dataset/mnist/test-images.txt", "r");
if(!fp) return 0;
for(int i = 0; i < testDataNum; i++) {
testData[i] = new float[784];
for(int j = 0; j < 784; j++) {
fscanf(fp, " %d", &value);
*(testData[i] + j) = value / 255.0;
}
}
fclose(fp);
fp = fopen("dataset/mnist/test-labels.txt", "r");
if(!fp) return 0;
for(int i = 0; i < testDataNum; i++) {
fscanf(fp, " %d", &label);
testLabelData[i] = new float[10];
for(int j = 0; j < 10; j++) {
*(testLabelData[i] + j) = ((j == label) ? 1.0 : 0.0);
}
}
fclose(fp);
puts("loaded!");
/* parameters */
int epoch = 50;
float lr = 0.0005;
/* Create Network */
Network *net;
net = new Network();
FullyConnectedLayer *full1, *full2;
act_T *act1t, *act2t;
act1t = new act_T;
act1t->apply = logistic_apply;
act1t->diff = logistic_diff;
act2t = new act_T;
act2t->apply = logistic_apply;
act2t->diff = logistic_diff;
full1 = new FullyConnectedLayer(784, 100, act1t, lr);
full2 = new FullyConnectedLayer(100, 10, act2t, lr);
net->appendLayer(full1);
net->appendLayer(full2);
net->setTest(testData, testLabelData, testDataNum);
net->loadParameters((char *)"parameters/mnist/150.param");
net->train(trainingData, labelData, trainingDataNum, epoch);
net->saveParameters((char *)"parameters/mnist/200.param");
//net->test(testData, testLabelData, testDataNum);
delete net;
delete act1t;
delete act2t;
delete full1;
delete full2;
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>-Werror=undef<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gridwin.hxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:30: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 SC_GRIDWIN_HXX
#define SC_GRIDWIN_HXX
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif
// nur auf dem MAC Auto-Filter per Popup
#ifdef MAC
#define AUTOFILTER_POPUP
#else
#undef AUTOFILTER_POPUP
#endif
#ifndef SC_VIEWUTIL_HXX
#include "viewutil.hxx"
#endif
#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif
#ifndef SC_CBUTTON_HXX
#include "cbutton.hxx"
#endif
// ---------------------------------------------------------------------------
struct ScTableInfo;
class ScViewSelectionEngine;
class ScPivot;
class ScDPObject;
class ScOutputData;
class ScFilterListBox;
class AutoFilterPopup;
class SdrObject;
class SdrEditView;
class ScNoteMarker;
class FloatingWindow;
class SdrHdlList;
class ScTransferObj;
struct SpellCallbackInfo;
// Maus-Status (nMouseStatus)
#define SC_GM_NONE 0
#define SC_GM_TABDOWN 1
#define SC_GM_DBLDOWN 2
#define SC_GM_FILTER 3
#define SC_GM_IGNORE 4
#define SC_GM_WATERUNDO 5
#define SC_GM_URLDOWN 6
// Page-Drag-Modus
#define SC_PD_NONE 0
#define SC_PD_RANGE_L 1
#define SC_PD_RANGE_R 2
#define SC_PD_RANGE_T 4
#define SC_PD_RANGE_B 8
#define SC_PD_RANGE_TL (SC_PD_RANGE_T|SC_PD_RANGE_L)
#define SC_PD_RANGE_TR (SC_PD_RANGE_T|SC_PD_RANGE_R)
#define SC_PD_RANGE_BL (SC_PD_RANGE_B|SC_PD_RANGE_L)
#define SC_PD_RANGE_BR (SC_PD_RANGE_B|SC_PD_RANGE_R)
#define SC_PD_BREAK_H 16
#define SC_PD_BREAK_V 32
class ScHideTextCursor
{
private:
ScViewData* pViewData;
ScSplitPos eWhich;
public:
ScHideTextCursor( ScViewData* pData, ScSplitPos eW );
~ScHideTextCursor();
};
class ScGridWindow : public Window, public DropTargetHelper, public DragSourceHelper
{
// ScFilterListBox wird immer fuer Auswahlliste benutzt
friend class ScFilterListBox;
#ifdef AUTOFILTER_POPUP
friend class AutoFilterPopup;
#endif
private:
ScViewData* pViewData;
ScSplitPos eWhich;
ScHSplitPos eHWhich;
ScVSplitPos eVWhich;
ScNoteMarker* pNoteMarker;
ScFilterListBox* pFilterBox;
FloatingWindow* pFilterFloat;
USHORT nCursorHideCount;
BOOL bMarking;
USHORT nButtonDown;
BOOL bEEMouse; // Edit-Engine hat Maus
BYTE nMouseStatus;
BYTE nNestedButtonState; // track nested button up/down calls
BOOL bPivotMouse; // Pivot-D&D (alte Pivottabellen)
ScPivot* pDragPivot;
BOOL bPivotColField;
SCCOL nPivotCol;
SCCOL nPivotField;
BOOL bDPMouse; // DataPilot-D&D (neue Pivottabellen)
long nDPField;
ScDPObject* pDragDPObj; //! name?
BOOL bRFMouse; // RangeFinder-Drag
BOOL bRFSize;
USHORT nRFIndex;
SCsCOL nRFAddX;
SCsROW nRFAddY;
USHORT nPagebreakMouse; // Pagebreak-Modus Drag
SCCOLROW nPagebreakBreak;
SCCOLROW nPagebreakPrev;
ScRange aPagebreakSource;
ScRange aPagebreakDrag;
BOOL bPagebreakDrawn;
BYTE nPageScript;
long nLastClickX;
long nLastClickY;
BOOL bDragRect;
SCCOL nDragStartX;
SCROW nDragStartY;
SCCOL nDragEndX;
SCROW nDragEndY;
USHORT nCurrentPointer;
BOOL bIsInScroll;
BOOL bIsInPaint;
ScDDComboBoxButton aComboButton;
Point aCurMousePos;
USHORT nPaintCount;
Rectangle aRepaintPixel;
BOOL bNeedsRepaint;
BOOL bAutoMarkVisible;
ScAddress aAutoMarkPos;
BOOL bListValButton;
ScAddress aListValPos;
Rectangle aInvertRect;
DECL_LINK( PopupModeEndHdl, FloatingWindow* );
DECL_LINK( PopupSpellingHdl, SpellCallbackInfo* );
BOOL TestMouse( const MouseEvent& rMEvt, BOOL bAction );
BOOL DoPageFieldSelection( SCCOL nCol, SCROW nRow );
void DoPushButton( SCCOL nCol, SCROW nRow, const MouseEvent& rMEvt );
void PivotMouseMove( const MouseEvent& rMEvt );
void PivotMouseButtonUp( const MouseEvent& rMEvt );
BOOL PivotTestMouse( const MouseEvent& rMEvt, BOOL bMove );
void DoPivotDrop( BOOL bDelete, BOOL bToCols, SCSIZE nDestPos );
void DPMouseMove( const MouseEvent& rMEvt );
void DPMouseButtonUp( const MouseEvent& rMEvt );
void DPTestMouse( const MouseEvent& rMEvt, BOOL bMove );
void RFMouseMove( const MouseEvent& rMEvt, BOOL bUp );
void PagebreakMove( const MouseEvent& rMEvt, BOOL bUp );
void UpdateDragRect( BOOL bShowRange, const Rectangle& rPosRect );
BOOL IsAutoFilterActive( SCCOL nCol, SCROW nRow, SCTAB nTab );
void ExecFilter( ULONG nSel, SCCOL nCol, SCROW nRow,
const String& aValue );
void FilterSelect( ULONG nSel );
void ExecDataSelect( SCCOL nCol, SCROW nRow, const String& rStr );
void ExecPageFieldSelect( SCCOL nCol, SCROW nRow, BOOL bHasSelection, const String& rStr );
BOOL HasScenarioButton( const Point& rPosPixel, ScRange& rScenRange );
BOOL DropScroll( const Point& rMousePos );
sal_Int8 AcceptPrivateDrop( const AcceptDropEvent& rEvt );
sal_Int8 ExecutePrivateDrop( const ExecuteDropEvent& rEvt );
sal_Int8 DropTransferObj( ScTransferObj* pTransObj, SCCOL nDestPosX, SCROW nDestPosY,
const Point& rLogicPos, sal_Int8 nDndAction );
void HandleMouseButtonDown( const MouseEvent& rMEvt );
BOOL DrawMouseButtonDown(const MouseEvent& rMEvt);
BOOL DrawMouseButtonUp(const MouseEvent& rMEvt);
BOOL DrawMouseMove(const MouseEvent& rMEvt);
BOOL DrawKeyInput(const KeyEvent& rKEvt);
BOOL DrawCommand(const CommandEvent& rCEvt);
BOOL DrawHasMarkedObj();
void DrawEndAction();
void DrawMarkDropObj( SdrObject* pObj );
SdrObject* GetEditObject();
BOOL IsMyModel(SdrEditView* pSdrView);
void DrawStartTimer();
void DrawRedraw( ScOutputData& rOutputData, const Rectangle& rDrawingRect,
ScUpdateMode eMode, ULONG nLayer );
void DrawSdrGrid( const Rectangle& rDrawingRect );
BOOL DrawBeforeScroll();
void DrawAfterScroll(BOOL bVal);
void OutlinerViewPaint( const Rectangle& rRect );
void DrawMarks();
BOOL NeedDrawMarks();
void DrawComboButton( const Point& rCellPos,
long nCellSizeX,
long nCellSizeY,
BOOL bArrowState,
BOOL bBtnIn = FALSE );
Rectangle GetListValButtonRect( const ScAddress& rButtonPos );
void DrawPagePreview( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2 );
BOOL GetEditUrl( const Point& rPos,
String* pName=0, String* pUrl=0, String* pTarget=0 );
BOOL GetEditUrlOrError( BOOL bSpellErr, const Point& rPos,
String* pName=0, String* pUrl=0, String* pTarget=0 );
BOOL HitRangeFinder( const Point& rMouse, BOOL& rCorner, USHORT* pIndex = NULL,
SCsCOL* pAddX = NULL, SCsROW* pAddY = NULL );
USHORT HitPageBreak( const Point& rMouse, ScRange* pSource = NULL,
SCCOLROW* pBreak = NULL, SCCOLROW* pPrev = NULL );
#ifdef AUTOFILTER_POPUP
void DoAutoFilterPopup( SCCOL nCol, SCROW nRow, BOOL bDataSelect );
#endif
void PasteSelection( const Point& rPosPixel );
void SelectForContextMenu( const Point& rPosPixel );
protected:
virtual void Resize( const Size& rSize );
virtual void Paint( const Rectangle& rRect );
virtual void KeyInput(const KeyEvent& rKEvt);
virtual void GetFocus();
virtual void LoseFocus();
virtual void RequestHelp( const HelpEvent& rEvt );
virtual void Command( const CommandEvent& rCEvt );
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );
public:
ScGridWindow( Window* pParent, ScViewData* pData, ScSplitPos eWhichPos );
~ScGridWindow();
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void MouseMove( const MouseEvent& rMEvt );
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void Tracking( const TrackingEvent& rTEvt );
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();
void FakeButtonUp();
Point GetMousePosPixel() const;
void UpdateStatusPosSize();
void ClickExtern();
void SetPointer( const Pointer& rPointer );
void MoveMouseStatus( ScGridWindow &rDestWin );
void ScrollPixel( long nDifX, long nDifY );
void UpdateEditViewPos();
void UpdateFormulas();
void DoAutoFilterMenue( SCCOL nCol, SCROW nRow, BOOL bDataSelect );
void DoScenarioMenue( const ScRange& rScenRange );
void DoPageFieldMenue( SCCOL nCol, SCROW nRow );
BOOL HasPageFieldData( SCCOL nCol, SCROW nRow ) const;
void DrawButtons( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
ScTableInfo& rTabInfo );
void Draw( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
ScUpdateMode eMode = SC_UPDATE_ALL );
void InvertSimple( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
BOOL bTestMerge = FALSE, BOOL bRepeat = FALSE );
void DrawDragRect( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
BOOL bMarkDrop = TRUE );
void DrawRefMark( SCCOL nRefStartX, SCROW nRefStartY,
SCCOL nRefEndX, SCROW nRefEndY,
const Color& rColor, BOOL bHandle );
void CreateAnchorHandle(SdrHdlList& rHdl, const ScAddress& rAddress);
void HideCursor();
void ShowCursor();
void DrawCursor();
void DrawAutoFillMark();
void UpdateAutoFillMark(BOOL bMarked, const ScRange& rMarkRange);
void UpdateListValPos( BOOL bVisible, const ScAddress& rPos );
BOOL ShowNoteMarker( SCsCOL nPosX, SCsROW nPosY, BOOL bKeyboard );
void HideNoteMarker();
MapMode GetDrawMapMode( BOOL bForce = FALSE );
void ContinueDrag();
void StopMarking();
void UpdateInputContext();
void CheckInverted() { if (nPaintCount) bNeedsRepaint = TRUE; }
void DoInvertRect( const Rectangle& rPixel );
void CheckNeedsRepaint();
};
#endif
<commit_msg>INTEGRATION: CWS aw024 (1.20.18); FILE MERGED 2006/10/27 12:16:06 aw 1.20.18.9: #i39528# ::basegfx -> basegfx adaption 2006/10/25 16:25:44 aw 1.20.18.8: #i70788# secured access to OverlayManager 2006/07/27 15:51:14 aw 1.20.18.7: #114408# adaptions for overlay 2006/07/21 18:32:40 nn 1.20.18.6: #112209# use inverting overlay objects for now 2006/06/16 16:07:58 nn 1.20.18.5: #114409# more overlay objects instead of Invert calls 2006/03/15 11:18:35 aw 1.20.18.4: #114409# corrected sc overlay problems 2005/09/20 02:13:25 aw 1.20.18.3: RESYNC: (1.20-1.21); FILE MERGED 2005/07/29 17:43:19 nn 1.20.18.2: #114409# use OverlayObjectCell for cell cursor, selection and AutoFill handle 2005/05/19 12:08:10 aw 1.20.18.1: #i39529#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gridwin.hxx,v $
*
* $Revision: 1.22 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 15:53:58 $
*
* 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 SC_GRIDWIN_HXX
#define SC_GRIDWIN_HXX
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif
// nur auf dem MAC Auto-Filter per Popup
#ifdef MAC
#define AUTOFILTER_POPUP
#else
#undef AUTOFILTER_POPUP
#endif
#ifndef SC_VIEWUTIL_HXX
#include "viewutil.hxx"
#endif
#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif
#ifndef SC_CBUTTON_HXX
#include "cbutton.hxx"
#endif
#ifndef _SDR_OVERLAY_OVERLAYOBJECT_HXX
#include <svx/sdr/overlay/overlayobject.hxx>
#endif
#include <vector>
// ---------------------------------------------------------------------------
struct ScTableInfo;
class ScViewSelectionEngine;
class ScPivot;
class ScDPObject;
class ScOutputData;
class ScFilterListBox;
class AutoFilterPopup;
class SdrObject;
class SdrEditView;
class ScNoteMarker;
class FloatingWindow;
class SdrHdlList;
class ScTransferObj;
struct SpellCallbackInfo;
// Maus-Status (nMouseStatus)
#define SC_GM_NONE 0
#define SC_GM_TABDOWN 1
#define SC_GM_DBLDOWN 2
#define SC_GM_FILTER 3
#define SC_GM_IGNORE 4
#define SC_GM_WATERUNDO 5
#define SC_GM_URLDOWN 6
// Page-Drag-Modus
#define SC_PD_NONE 0
#define SC_PD_RANGE_L 1
#define SC_PD_RANGE_R 2
#define SC_PD_RANGE_T 4
#define SC_PD_RANGE_B 8
#define SC_PD_RANGE_TL (SC_PD_RANGE_T|SC_PD_RANGE_L)
#define SC_PD_RANGE_TR (SC_PD_RANGE_T|SC_PD_RANGE_R)
#define SC_PD_RANGE_BL (SC_PD_RANGE_B|SC_PD_RANGE_L)
#define SC_PD_RANGE_BR (SC_PD_RANGE_B|SC_PD_RANGE_R)
#define SC_PD_BREAK_H 16
#define SC_PD_BREAK_V 32
class ScHideTextCursor
{
private:
ScViewData* pViewData;
ScSplitPos eWhich;
public:
ScHideTextCursor( ScViewData* pData, ScSplitPos eW );
~ScHideTextCursor();
};
// ---------------------------------------------------------------------------
// predefines
class ScGridWindow;
enum ScOverlayType { SC_OVERLAY_INVERT, SC_OVERLAY_HATCH, SC_OVERLAY_TRANSPARENT, SC_OVERLAY_LIGHT_TRANSPARENT };
// #114409#
namespace sdr
{
namespace overlay
{
// predefines
class OverlayObjectList;
// OverlayObjectCell - used for cell cursor, selection and AutoFill handle
class OverlayObjectCell : public OverlayObject
{
public:
typedef ::std::vector< basegfx::B2DRange > RangeVector;
private:
ScOverlayType mePaintType;
RangeVector maRectangles;
virtual void drawGeometry(OutputDevice& rOutputDevice);
virtual void createBaseRange(OutputDevice& rOutputDevice);
public:
OverlayObjectCell( ScOverlayType eType, const Color& rColor, const RangeVector& rRects);
virtual ~OverlayObjectCell();
virtual void transform(const basegfx::B2DHomMatrix& rMatrix);
};
} // end of namespace overlay
} // end of namespace sdr
// ---------------------------------------------------------------------------
class ScGridWindow : public Window, public DropTargetHelper, public DragSourceHelper
{
// ScFilterListBox wird immer fuer Auswahlliste benutzt
friend class ScFilterListBox;
#ifdef AUTOFILTER_POPUP
friend class AutoFilterPopup;
#endif
private:
// #114409#
::sdr::overlay::OverlayObjectList* mpOOCursors;
::sdr::overlay::OverlayObjectList* mpOOSelection;
::sdr::overlay::OverlayObjectList* mpOOAutoFill;
::sdr::overlay::OverlayObjectList* mpOODragRect;
::sdr::overlay::OverlayObjectList* mpOOHeader;
::sdr::overlay::OverlayObjectList* mpOOShrink;
private:
ScViewData* pViewData;
ScSplitPos eWhich;
ScHSplitPos eHWhich;
ScVSplitPos eVWhich;
ScNoteMarker* pNoteMarker;
ScFilterListBox* pFilterBox;
FloatingWindow* pFilterFloat;
USHORT nCursorHideCount;
BOOL bMarking;
USHORT nButtonDown;
BOOL bEEMouse; // Edit-Engine hat Maus
BYTE nMouseStatus;
BYTE nNestedButtonState; // track nested button up/down calls
BOOL bPivotMouse; // Pivot-D&D (alte Pivottabellen)
ScPivot* pDragPivot;
BOOL bPivotColField;
SCCOL nPivotCol;
SCCOL nPivotField;
BOOL bDPMouse; // DataPilot-D&D (neue Pivottabellen)
long nDPField;
ScDPObject* pDragDPObj; //! name?
BOOL bRFMouse; // RangeFinder-Drag
BOOL bRFSize;
USHORT nRFIndex;
SCsCOL nRFAddX;
SCsROW nRFAddY;
USHORT nPagebreakMouse; // Pagebreak-Modus Drag
SCCOLROW nPagebreakBreak;
SCCOLROW nPagebreakPrev;
ScRange aPagebreakSource;
ScRange aPagebreakDrag;
BOOL bPagebreakDrawn;
BYTE nPageScript;
long nLastClickX;
long nLastClickY;
BOOL bDragRect;
SCCOL nDragStartX;
SCROW nDragStartY;
SCCOL nDragEndX;
SCROW nDragEndY;
USHORT nCurrentPointer;
BOOL bIsInScroll;
BOOL bIsInPaint;
ScDDComboBoxButton aComboButton;
Point aCurMousePos;
USHORT nPaintCount;
Rectangle aRepaintPixel;
BOOL bNeedsRepaint;
BOOL bAutoMarkVisible;
ScAddress aAutoMarkPos;
BOOL bListValButton;
ScAddress aListValPos;
Rectangle aInvertRect;
DECL_LINK( PopupModeEndHdl, FloatingWindow* );
DECL_LINK( PopupSpellingHdl, SpellCallbackInfo* );
BOOL TestMouse( const MouseEvent& rMEvt, BOOL bAction );
BOOL DoPageFieldSelection( SCCOL nCol, SCROW nRow );
void DoPushButton( SCCOL nCol, SCROW nRow, const MouseEvent& rMEvt );
void PivotMouseMove( const MouseEvent& rMEvt );
void PivotMouseButtonUp( const MouseEvent& rMEvt );
BOOL PivotTestMouse( const MouseEvent& rMEvt, BOOL bMove );
void DoPivotDrop( BOOL bDelete, BOOL bToCols, SCSIZE nDestPos );
void DPMouseMove( const MouseEvent& rMEvt );
void DPMouseButtonUp( const MouseEvent& rMEvt );
void DPTestMouse( const MouseEvent& rMEvt, BOOL bMove );
void RFMouseMove( const MouseEvent& rMEvt, BOOL bUp );
void PagebreakMove( const MouseEvent& rMEvt, BOOL bUp );
void UpdateDragRect( BOOL bShowRange, const Rectangle& rPosRect );
BOOL IsAutoFilterActive( SCCOL nCol, SCROW nRow, SCTAB nTab );
void ExecFilter( ULONG nSel, SCCOL nCol, SCROW nRow,
const String& aValue );
void FilterSelect( ULONG nSel );
void ExecDataSelect( SCCOL nCol, SCROW nRow, const String& rStr );
void ExecPageFieldSelect( SCCOL nCol, SCROW nRow, BOOL bHasSelection, const String& rStr );
BOOL HasScenarioButton( const Point& rPosPixel, ScRange& rScenRange );
BOOL DropScroll( const Point& rMousePos );
sal_Int8 AcceptPrivateDrop( const AcceptDropEvent& rEvt );
sal_Int8 ExecutePrivateDrop( const ExecuteDropEvent& rEvt );
sal_Int8 DropTransferObj( ScTransferObj* pTransObj, SCCOL nDestPosX, SCROW nDestPosY,
const Point& rLogicPos, sal_Int8 nDndAction );
void HandleMouseButtonDown( const MouseEvent& rMEvt );
BOOL DrawMouseButtonDown(const MouseEvent& rMEvt);
BOOL DrawMouseButtonUp(const MouseEvent& rMEvt);
BOOL DrawMouseMove(const MouseEvent& rMEvt);
BOOL DrawKeyInput(const KeyEvent& rKEvt);
BOOL DrawCommand(const CommandEvent& rCEvt);
BOOL DrawHasMarkedObj();
void DrawEndAction();
void DrawMarkDropObj( SdrObject* pObj );
SdrObject* GetEditObject();
BOOL IsMyModel(SdrEditView* pSdrView);
//void DrawStartTimer();
void DrawRedraw( ScOutputData& rOutputData, ScUpdateMode eMode, ULONG nLayer );
void DrawSdrGrid( const Rectangle& rDrawingRect );
//BOOL DrawBeforeScroll();
void DrawAfterScroll(/*BOOL bVal*/);
void OutlinerViewPaint( const Rectangle& rRect );
//void DrawMarks();
//BOOL NeedDrawMarks();
void DrawComboButton( const Point& rCellPos,
long nCellSizeX,
long nCellSizeY,
BOOL bArrowState,
BOOL bBtnIn = FALSE );
Rectangle GetListValButtonRect( const ScAddress& rButtonPos );
void DrawPagePreview( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2 );
BOOL GetEditUrl( const Point& rPos,
String* pName=0, String* pUrl=0, String* pTarget=0 );
BOOL GetEditUrlOrError( BOOL bSpellErr, const Point& rPos,
String* pName=0, String* pUrl=0, String* pTarget=0 );
BOOL HitRangeFinder( const Point& rMouse, BOOL& rCorner, USHORT* pIndex = NULL,
SCsCOL* pAddX = NULL, SCsROW* pAddY = NULL );
USHORT HitPageBreak( const Point& rMouse, ScRange* pSource = NULL,
SCCOLROW* pBreak = NULL, SCCOLROW* pPrev = NULL );
#ifdef AUTOFILTER_POPUP
void DoAutoFilterPopup( SCCOL nCol, SCROW nRow, BOOL bDataSelect );
#endif
void PasteSelection( const Point& rPosPixel );
void SelectForContextMenu( const Point& rPosPixel );
void GetSelectionRects( ::std::vector< Rectangle >& rPixelRects );
protected:
virtual void Resize( const Size& rSize );
virtual void Paint( const Rectangle& rRect );
virtual void KeyInput(const KeyEvent& rKEvt);
virtual void GetFocus();
virtual void LoseFocus();
virtual void RequestHelp( const HelpEvent& rEvt );
virtual void Command( const CommandEvent& rCEvt );
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );
public:
ScGridWindow( Window* pParent, ScViewData* pData, ScSplitPos eWhichPos );
~ScGridWindow();
// #i70788# flush and get overlay
::sdr::overlay::OverlayManager* getOverlayManager();
void flushOverlayManager();
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void MouseMove( const MouseEvent& rMEvt );
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void Tracking( const TrackingEvent& rTEvt );
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();
void FakeButtonUp();
Point GetMousePosPixel() const;
void UpdateStatusPosSize();
void ClickExtern();
void SetPointer( const Pointer& rPointer );
void MoveMouseStatus( ScGridWindow &rDestWin );
void ScrollPixel( long nDifX, long nDifY );
void UpdateEditViewPos();
void UpdateFormulas();
void DoAutoFilterMenue( SCCOL nCol, SCROW nRow, BOOL bDataSelect );
void DoScenarioMenue( const ScRange& rScenRange );
void DoPageFieldMenue( SCCOL nCol, SCROW nRow );
BOOL HasPageFieldData( SCCOL nCol, SCROW nRow ) const;
void DrawButtons( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
ScTableInfo& rTabInfo );
void Draw( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
ScUpdateMode eMode = SC_UPDATE_ALL );
void InvertSimple( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
BOOL bTestMerge = FALSE, BOOL bRepeat = FALSE );
void DrawDragRect( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
BOOL bMarkDrop = TRUE );
void DrawRefMark( SCCOL nRefStartX, SCROW nRefStartY,
SCCOL nRefEndX, SCROW nRefEndY,
const Color& rColor, BOOL bHandle );
void CreateAnchorHandle(SdrHdlList& rHdl, const ScAddress& rAddress);
void HideCursor();
void ShowCursor();
void DrawCursor();
void DrawAutoFillMark();
void UpdateAutoFillMark(BOOL bMarked, const ScRange& rMarkRange);
void UpdateListValPos( BOOL bVisible, const ScAddress& rPos );
BOOL ShowNoteMarker( SCsCOL nPosX, SCsROW nPosY, BOOL bKeyboard );
void HideNoteMarker();
MapMode GetDrawMapMode( BOOL bForce = FALSE );
void ContinueDrag();
void StopMarking();
void UpdateInputContext();
void CheckInverted() { if (nPaintCount) bNeedsRepaint = TRUE; }
void DoInvertRect( const Rectangle& rPixel );
void CheckNeedsRepaint();
// #114409#
void CursorChanged();
void DrawLayerCreated();
void DeleteCursorOverlay();
void UpdateCursorOverlay();
void DeleteSelectionOverlay();
void UpdateSelectionOverlay();
void DeleteAutoFillOverlay();
void UpdateAutoFillOverlay();
void DeleteDragRectOverlay();
void UpdateDragRectOverlay();
void DeleteHeaderOverlay();
void UpdateHeaderOverlay();
void DeleteShrinkOverlay();
void UpdateShrinkOverlay();
void UpdateAllOverlays();
protected:
// #114409#
void ImpCreateOverlayObjects();
void ImpDestroyOverlayObjects();
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pivotsh.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2007-02-27 13:25: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
*
************************************************************************/
#ifndef SC_PIVOTSH_HXX
#define SC_PIVOTSH_HXX
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#include "shellids.hxx"
class ScTabViewShell;
class ScDPObject;
class ScPivotShell : public SfxShell
{
public:
TYPEINFO();
SFX_DECL_INTERFACE(SCID_PIVOT_SHELL)
ScPivotShell( ScTabViewShell* pView );
~ScPivotShell();
void Execute ( SfxRequest& rReq );
void GetState( SfxItemSet& rSet );
private:
ScTabViewShell* pViewShell;
ScDPObject* GetCurrDPObject();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.330); FILE MERGED 2008/04/01 15:30:58 thb 1.4.330.2: #i85898# Stripping all external header guards 2008/03/31 17:15:46 rt 1.4.330.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: pivotsh.hxx,v $
* $Revision: 1.5 $
*
* 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 SC_PIVOTSH_HXX
#define SC_PIVOTSH_HXX
#include <sfx2/module.hxx>
#include <sfx2/shell.hxx>
#include "shellids.hxx"
class ScTabViewShell;
class ScDPObject;
class ScPivotShell : public SfxShell
{
public:
TYPEINFO();
SFX_DECL_INTERFACE(SCID_PIVOT_SHELL)
ScPivotShell( ScTabViewShell* pView );
~ScPivotShell();
void Execute ( SfxRequest& rReq );
void GetState( SfxItemSet& rSet );
private:
ScTabViewShell* pViewShell;
ScDPObject* GetCurrDPObject();
};
#endif
<|endoftext|> |
<commit_before>#include "LogManager.h"
#include <fstream>
using namespace OpenSim;
// Initialize static members
LogBuffer LogManager::out;
LogBuffer LogManager::err;
std::ostream LogManager::cout(std::cout.rdbuf()); // This cout writes to the actual standard out
std::ostream LogManager::cerr(std::cerr.rdbuf()); // This cerr writes to the actual standard error
// Initialize a static log manager to force the constructor to be called
LogManager logManager;
//=============================================================================
// LogBuffer
//=============================================================================
LogBuffer::LogBuffer() :
_outputStream(0),
_secondaryOutputStream(0)
{
}
// Assumes caller owns this output stream (will never be deleted)
void LogBuffer::
setOutputStream(std::ostream *aOutputStream)
{
_outputStream = aOutputStream;
}
// Assumes caller owns this output stream (will never be deleted)
void LogBuffer::
setSecondaryOutputStream(std::ostream *aSecondaryOutputStream)
{
_secondaryOutputStream = aSecondaryOutputStream;
}
int LogBuffer::
sync()
{
// Write to up to two output streams
if (_outputStream) (*_outputStream) << str() << std::flush;
if (_secondaryOutputStream) (*_secondaryOutputStream) << str() << std::flush;
// Reset current buffer contents
str("");
return std::stringbuf::sync();
}
//=============================================================================
// LogManager
//=============================================================================
LogManager::LogManager()
{
// Seems to be causing crashes in the GUI... maybe a multithreading issue.
#if 0
// Change the underlying streambuf for the standard cout/cerr to our custom buffers
std::cout.rdbuf(&out);
std::cerr.rdbuf(&err);
// Example setup: redirect output to both the terminal and an output file
out.setOutputStream(&cout);
out.setSecondaryOutputStream(new std::ofstream("out.log"));
err.setOutputStream(&cerr);
err.setSecondaryOutputStream(new std::ofstream("err.log"));
#endif
}
LogManager::~LogManager()
{
std::cout << std::flush;
std::cerr << std::flush;
}
<commit_msg>Reactivate LogManager to see if it crashes the GUI still or not...<commit_after>#include "LogManager.h"
#include <fstream>
using namespace OpenSim;
// Initialize static members
LogBuffer LogManager::out;
LogBuffer LogManager::err;
std::ostream LogManager::cout(std::cout.rdbuf()); // This cout writes to the actual standard out
std::ostream LogManager::cerr(std::cerr.rdbuf()); // This cerr writes to the actual standard error
// Initialize a static log manager to force the constructor to be called
LogManager logManager;
//=============================================================================
// LogBuffer
//=============================================================================
LogBuffer::LogBuffer() :
_outputStream(0),
_secondaryOutputStream(0)
{
}
// Assumes caller owns this output stream (will never be deleted)
void LogBuffer::
setOutputStream(std::ostream *aOutputStream)
{
_outputStream = aOutputStream;
}
// Assumes caller owns this output stream (will never be deleted)
void LogBuffer::
setSecondaryOutputStream(std::ostream *aSecondaryOutputStream)
{
_secondaryOutputStream = aSecondaryOutputStream;
}
int LogBuffer::
sync()
{
// Write to up to two output streams
if (_outputStream) (*_outputStream) << str() << std::flush;
if (_secondaryOutputStream) (*_secondaryOutputStream) << str() << std::flush;
// Reset current buffer contents
str("");
return std::stringbuf::sync();
}
//=============================================================================
// LogManager
//=============================================================================
LogManager::LogManager()
{
// Seems to be causing crashes in the GUI... maybe a multithreading issue.
#if 1
// Change the underlying streambuf for the standard cout/cerr to our custom buffers
std::cout.rdbuf(&out);
std::cerr.rdbuf(&err);
// Example setup: redirect output to both the terminal and an output file
out.setOutputStream(&cout);
out.setSecondaryOutputStream(new std::ofstream("out.log"));
err.setOutputStream(&cerr);
err.setSecondaryOutputStream(new std::ofstream("err.log"));
#endif
}
LogManager::~LogManager()
{
std::cout << std::flush;
std::cerr << std::flush;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/ref_counted.h"
#include "base/scoped_temp_dir.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/in_process_webkit/indexed_db_context.h"
#include "chrome/browser/in_process_webkit/webkit_context.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/testing_profile.h"
#include "chrome/test/thread_test_helper.h"
#include "chrome/test/ui_test_utils.h"
// This browser test is aimed towards exercising the IndexedDB bindings and
// the actual implementation that lives in the browser side (in_process_webkit).
class IndexedDBBrowserTest : public InProcessBrowserTest {
public:
IndexedDBBrowserTest() {
EnableDOMAutomation();
}
GURL testUrl(const FilePath& file_path) {
const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb"));
return ui_test_utils::GetTestUrl(kTestDir, file_path);
}
void SimpleTest(const GURL& test_url) {
// The test page will perform tests on IndexedDB, then navigate to either
// a #pass or #fail ref.
LOG(INFO) << "Navigating to URL and blocking.";
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), test_url, 2);
LOG(INFO) << "Navigation done.";
std::string result = browser()->GetSelectedTabContents()->GetURL().ref();
if (result != "pass") {
std::string js_result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(getLog())", &js_result));
FAIL() << "Failed: " << js_result;
}
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, IndexTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html"))));
}
// Flaky on windows, see http://crbug.com/67422 and http://crbug.com/69293.
#if defined(OS_WIN)
#define MAYBE_KeyPathTest FLAKY_KeyPathTest
#else
#define MAYBE_KeyPathTest KeyPathTest
#endif
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, MAYBE_KeyPathTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ObjectStoreTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DoesntHangTest) {
SimpleTest(testUrl(FilePath(
FILE_PATH_LITERAL("transaction_run_forever.html"))));
ui_test_utils::CrashTab(browser()->GetSelectedTabContents());
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) {
// Create test files.
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath indexeddb_dir = temp_dir.path().Append(
IndexedDBContext::kIndexedDBDirectory);
ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir));
FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0"));
file_name_1.append(IndexedDBContext::kIndexedDBExtension);
FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0"));
file_name_2.append(IndexedDBContext::kIndexedDBExtension);
FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1);
FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2);
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1));
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1));
// Create the scope which will ensure we run the destructor of the webkit
// context which should trigger the clean up.
{
TestingProfile profile;
WebKitContext *webkit_context = profile.GetWebKitContext();
webkit_context->indexed_db_context()->set_data_path(indexeddb_dir);
webkit_context->set_clear_local_state_on_exit(true);
}
// Make sure we wait until the destructor has run.
scoped_refptr<ThreadTestHelper> helper(
new ThreadTestHelper(BrowserThread::WEBKIT));
ASSERT_TRUE(helper->Run());
// Because we specified https for scheme to be skipped the second file
// should survive and the first go into vanity.
ASSERT_FALSE(file_util::PathExists(temp_file_path_1));
ASSERT_TRUE(file_util::PathExists(temp_file_path_2));
}
<commit_msg>Mark some IndexedDB browser tests as flaky.<commit_after>// Copyright (c) 2010 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 "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/ref_counted.h"
#include "base/scoped_temp_dir.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/in_process_webkit/indexed_db_context.h"
#include "chrome/browser/in_process_webkit/webkit_context.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/testing_profile.h"
#include "chrome/test/thread_test_helper.h"
#include "chrome/test/ui_test_utils.h"
// This browser test is aimed towards exercising the IndexedDB bindings and
// the actual implementation that lives in the browser side (in_process_webkit).
class IndexedDBBrowserTest : public InProcessBrowserTest {
public:
IndexedDBBrowserTest() {
EnableDOMAutomation();
}
GURL testUrl(const FilePath& file_path) {
const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb"));
return ui_test_utils::GetTestUrl(kTestDir, file_path);
}
void SimpleTest(const GURL& test_url) {
// The test page will perform tests on IndexedDB, then navigate to either
// a #pass or #fail ref.
LOG(INFO) << "Navigating to URL and blocking.";
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), test_url, 2);
LOG(INFO) << "Navigation done.";
std::string result = browser()->GetSelectedTabContents()->GetURL().ref();
if (result != "pass") {
std::string js_result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(getLog())", &js_result));
FAIL() << "Failed: " << js_result;
}
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}
// Flaky. See http://crbug.com/70643.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_IndexTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html"))));
}
// Flaky on windows, see http://crbug.com/67422 and http://crbug.com/69293.
#if defined(OS_WIN)
#define MAYBE_KeyPathTest FLAKY_KeyPathTest
#else
#define MAYBE_KeyPathTest KeyPathTest
#endif
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, MAYBE_KeyPathTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html"))));
}
// Flaky. See http://crbug.com/70643.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_ObjectStoreTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html"))));
}
// Flaky. See http://crbug.com/70643.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_TransactionTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// Flaky. See http://crbug.com/70643.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_DoesntHangTest) {
SimpleTest(testUrl(FilePath(
FILE_PATH_LITERAL("transaction_run_forever.html"))));
ui_test_utils::CrashTab(browser()->GetSelectedTabContents());
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) {
// Create test files.
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath indexeddb_dir = temp_dir.path().Append(
IndexedDBContext::kIndexedDBDirectory);
ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir));
FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0"));
file_name_1.append(IndexedDBContext::kIndexedDBExtension);
FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0"));
file_name_2.append(IndexedDBContext::kIndexedDBExtension);
FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1);
FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2);
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1));
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1));
// Create the scope which will ensure we run the destructor of the webkit
// context which should trigger the clean up.
{
TestingProfile profile;
WebKitContext *webkit_context = profile.GetWebKitContext();
webkit_context->indexed_db_context()->set_data_path(indexeddb_dir);
webkit_context->set_clear_local_state_on_exit(true);
}
// Make sure we wait until the destructor has run.
scoped_refptr<ThreadTestHelper> helper(
new ThreadTestHelper(BrowserThread::WEBKIT));
ASSERT_TRUE(helper->Run());
// Because we specified https for scheme to be skipped the second file
// should survive and the first go into vanity.
ASSERT_FALSE(file_util::PathExists(temp_file_path_1));
ASSERT_TRUE(file_util::PathExists(temp_file_path_2));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "chrome/browser/ui/ash/launcher/launcher_app_icon_loader.h"
#include "base/stl_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
namespace {
const extensions::Extension* GetExtensionByID(Profile* profile,
const std::string& id) {
ExtensionService* service = profile->GetExtensionService();
if (!service)
return NULL;
return service->extensions()->GetByID(id);
}
} // namespace
LauncherAppIconLoader::LauncherAppIconLoader(
Profile* profile,
ChromeLauncherController* controller)
: profile_(profile),
host_(controller) {
}
LauncherAppIconLoader::~LauncherAppIconLoader() {
STLDeleteContainerPairFirstPointers(map_.begin(), map_.end());
}
void LauncherAppIconLoader::FetchImage(const std::string& id) {
for (ImageToExtensionIDMap::const_iterator i = map_.begin();
i != map_.end(); ++i) {
if (i->second == id)
return; // Already loading the image.
}
const extensions::Extension* extension = GetExtensionByID(profile_, id);
if (!extension)
return;
extensions::IconImage* image = new extensions::IconImage(
extension,
extension->icons(),
extension_misc::EXTENSION_ICON_SMALL,
extensions::Extension::GetDefaultIcon(true),
this);
// |map_| takes ownership of |image|.
map_[image] = id;
host_->SetAppImage(id, image->image_skia());
}
void LauncherAppIconLoader::ClearImage(const std::string& id) {
for (ImageToExtensionIDMap::iterator i = map_.begin();
i != map_.end(); ++i) {
if (i->second == id) {
delete i->first;
map_.erase(i);
break;
}
}
}
void LauncherAppIconLoader::OnExtensionIconImageChanged(
extensions::IconImage* image) {
ImageToExtensionIDMap::iterator i = map_.find(image);
if (i == map_.end())
return; // The image has been removed, do nothing.
host_->SetAppImage(i->second, image->image_skia());
}
<commit_msg>cros: Make launcher explicitly starts app icon loading.<commit_after>// Copyright (c) 2012 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 "chrome/browser/ui/ash/launcher/launcher_app_icon_loader.h"
#include "base/stl_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
namespace {
const extensions::Extension* GetExtensionByID(Profile* profile,
const std::string& id) {
ExtensionService* service = profile->GetExtensionService();
if (!service)
return NULL;
return service->extensions()->GetByID(id);
}
} // namespace
LauncherAppIconLoader::LauncherAppIconLoader(
Profile* profile,
ChromeLauncherController* controller)
: profile_(profile),
host_(controller) {
}
LauncherAppIconLoader::~LauncherAppIconLoader() {
STLDeleteContainerPairFirstPointers(map_.begin(), map_.end());
}
void LauncherAppIconLoader::FetchImage(const std::string& id) {
for (ImageToExtensionIDMap::const_iterator i = map_.begin();
i != map_.end(); ++i) {
if (i->second == id)
return; // Already loading the image.
}
const extensions::Extension* extension = GetExtensionByID(profile_, id);
if (!extension)
return;
extensions::IconImage* image = new extensions::IconImage(
extension,
extension->icons(),
extension_misc::EXTENSION_ICON_SMALL,
extensions::Extension::GetDefaultIcon(true),
this);
// |map_| takes ownership of |image|.
map_[image] = id;
// Triggers image loading now instead of depending on paint message. This
// makes the temp blank image be shown for shorter time and improves user
// experience. See http://crbug.com/146114.
image->image_skia().EnsureRepsForSupportedScaleFactors();
}
void LauncherAppIconLoader::ClearImage(const std::string& id) {
for (ImageToExtensionIDMap::iterator i = map_.begin();
i != map_.end(); ++i) {
if (i->second == id) {
delete i->first;
map_.erase(i);
break;
}
}
}
void LauncherAppIconLoader::OnExtensionIconImageChanged(
extensions::IconImage* image) {
ImageToExtensionIDMap::iterator i = map_.find(image);
if (i == map_.end())
return; // The image has been removed, do nothing.
host_->SetAppImage(i->second, image->image_skia());
}
<|endoftext|> |
<commit_before>/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2015 Imperial College London
* Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
* Copyright 2013-2015 Andreas Schuh
*
* 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 "mirtk/Resampling.h"
#include "mirtk/Parallel.h"
#include "mirtk/Profiling.h"
#include "mirtk/InterpolateImageFunction.h"
namespace mirtk {
// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(double dx, double dy, double dz)
{
_X = 0;
_Y = 0;
_Z = 0;
_XSize = dx;
_YSize = dy;
_ZSize = dz;
_Interpolator = NULL;
}
// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(int x, int y, int z)
{
_X = x;
_Y = y;
_Z = z;
_XSize = 0;
_YSize = 0;
_ZSize = 0;
_Interpolator = NULL;
}
// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(int x, int y, int z, double dx, double dy, double dz)
{
_X = x;
_Y = y;
_Z = z;
_XSize = dx;
_YSize = dy;
_ZSize = dz;
_Interpolator = NULL;
}
// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::Initialize()
{
// Initialize base class
ImageToImage<VoxelType>::Initialize(false);
// Set up interpolator
if (_Interpolator == NULL) {
cerr << "Resampling::Initialize: No interpolator found!" << endl;
exit(1);
}
_Interpolator->Input(this->_Input);
_Interpolator->Initialize();
// Initialize output image
this->InitializeOutput();
}
// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::InitializeOutput()
{
ImageAttributes attr = this->_Input->Attributes();
if (_X > 0 && _XSize > 0) {
attr._x = _X;
attr._dx = _XSize;
} else if (_X > 0) {
attr._x = _X;
attr._dx = this->_Input->X() * this->_Input->XSize() / static_cast<double>(_X);
} else if (_XSize > 0 && this->_Input->XSize() > 0. && this->_Input->X() > 1) {
attr._x = iceil(this->_Input->X() * this->_Input->XSize() / this->_XSize);
attr._dx = _XSize;
}
if (_Y > 0 && _YSize > 0) {
attr._y = _Y;
attr._dy = _YSize;
} else if (_Y > 0) {
attr._y = _Y;
attr._dy = this->_Input->Y() * this->_Input->YSize() / static_cast<double>(_Y);
} else if (_YSize > 0 && this->_Input->YSize() > 0. && this->_Input->Y() > 1) {
attr._y = iceil(this->_Input->Y() * this->_Input->YSize() / this->_YSize);
attr._dy = _YSize;
}
if (_Z > 0 && _ZSize > 0) {
attr._z = _Z;
attr._dz = _ZSize;
} else if (_Z > 0) {
attr._z = _Z;
attr._dz = this->_Input->Z() * this->_Input->ZSize() / static_cast<double>(_Z);
} else if (_ZSize > 0 && this->_Input->ZSize() > 0. && this->_Input->Z() > 1) {
attr._z = iceil(this->_Input->Z() * this->_Input->ZSize() / this->_ZSize);
attr._dz = _ZSize;
}
this->_Output->Initialize(attr);
}
// ---------------------------------------------------------------------------
// Serial/Multi-threaded body of Resampling::Run method
class ResamplingRun
{
public:
// -------------------------------------------------------------------------
// Data members
const BaseImage *_Input;
BaseImage *_Output;
InterpolateImageFunction *_Interpolator;
mutable int _T;
// -------------------------------------------------------------------------
/// Default constructor
ResamplingRun()
:
_Input(NULL),
_Output(NULL),
_Interpolator(NULL),
_T(0)
{}
// -------------------------------------------------------------------------
/// Copy constructor
ResamplingRun(const ResamplingRun &other)
:
_Input(other._Input),
_Output(other._Output),
_Interpolator(other._Interpolator),
_T(other._T)
{}
// -------------------------------------------------------------------------
/// Resamples the image within given output region for frame _T
void operator() (const blocked_range3d<int> &r) const
{
double x, y, z;
for (int k = r.pages().begin(); k != r.pages().end(); ++k)
for (int j = r.rows ().begin(); j != r.rows ().end(); ++j)
for (int i = r.cols ().begin(); i != r.cols ().end(); ++i) {
x = i, y = j, z = k;
_Output->ImageToWorld(x, y, z);
_Input ->WorldToImage(x, y, z);
_Output->PutAsDouble(i, j, k, _T, _Interpolator->Evaluate(x, y, z, _T));
}
}
// -------------------------------------------------------------------------
/// Resamples the image for the given range of output frames
void operator() (const blocked_range<int> &r) const
{
blocked_range3d<int> voxels(0, _Output->Z(),
0, _Output->Y(),
0, _Output->X());
for (_T = r.begin(); _T != r.end(); _T++) {
parallel_for(voxels, ResamplingRun(*this));
}
}
};
// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::Run()
{
MIRTK_START_TIMING();
this->Initialize();
ResamplingRun body;
body._Input = this->_Input;
body._Output = this->_Output;
body._Interpolator = this->_Interpolator;
body(blocked_range<int>(0, this->_Output->T()));
this->Finalize();
MIRTK_DEBUG_TIMING(5, this->NameOfClass());
}
// ---------------------------------------------------------------------------
// Explicit template instantiations
template class Resampling<char>;
template class Resampling<unsigned char>;
template class Resampling<short>;
template class Resampling<unsigned short>;
template class Resampling<int>;
template class Resampling<float>;
template class Resampling<double>;
} // namespace mirtk
<commit_msg>enh: Use Throw instead of exit [Image]<commit_after>/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2008-2015 Imperial College London
* Copyright 2008-2013 Daniel Rueckert, Julia Schnabel
* Copyright 2013-2015 Andreas Schuh
*
* 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 "mirtk/Resampling.h"
#include "mirtk/Parallel.h"
#include "mirtk/Profiling.h"
#include "mirtk/InterpolateImageFunction.h"
namespace mirtk {
// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(double dx, double dy, double dz)
{
_X = 0;
_Y = 0;
_Z = 0;
_XSize = dx;
_YSize = dy;
_ZSize = dz;
_Interpolator = NULL;
}
// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(int x, int y, int z)
{
_X = x;
_Y = y;
_Z = z;
_XSize = 0;
_YSize = 0;
_ZSize = 0;
_Interpolator = NULL;
}
// ---------------------------------------------------------------------------
template <class VoxelType>
Resampling<VoxelType>::Resampling(int x, int y, int z, double dx, double dy, double dz)
{
_X = x;
_Y = y;
_Z = z;
_XSize = dx;
_YSize = dy;
_ZSize = dz;
_Interpolator = NULL;
}
// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::Initialize()
{
// Initialize base class
ImageToImage<VoxelType>::Initialize(false);
// Set up interpolator
if (_Interpolator == nullptr) {
Throw(ERR_InvalidArgument, __FUNCTION__, "Interpolator must be set");
}
_Interpolator->Input(this->_Input);
_Interpolator->Initialize();
// Initialize output image
this->InitializeOutput();
}
// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::InitializeOutput()
{
ImageAttributes attr = this->_Input->Attributes();
if (_X > 0 && _XSize > 0) {
attr._x = _X;
attr._dx = _XSize;
} else if (_X > 0) {
attr._x = _X;
attr._dx = this->_Input->X() * this->_Input->XSize() / static_cast<double>(_X);
} else if (_XSize > 0 && this->_Input->XSize() > 0. && this->_Input->X() > 1) {
attr._x = iceil(this->_Input->X() * this->_Input->XSize() / this->_XSize);
attr._dx = _XSize;
}
if (_Y > 0 && _YSize > 0) {
attr._y = _Y;
attr._dy = _YSize;
} else if (_Y > 0) {
attr._y = _Y;
attr._dy = this->_Input->Y() * this->_Input->YSize() / static_cast<double>(_Y);
} else if (_YSize > 0 && this->_Input->YSize() > 0. && this->_Input->Y() > 1) {
attr._y = iceil(this->_Input->Y() * this->_Input->YSize() / this->_YSize);
attr._dy = _YSize;
}
if (_Z > 0 && _ZSize > 0) {
attr._z = _Z;
attr._dz = _ZSize;
} else if (_Z > 0) {
attr._z = _Z;
attr._dz = this->_Input->Z() * this->_Input->ZSize() / static_cast<double>(_Z);
} else if (_ZSize > 0 && this->_Input->ZSize() > 0. && this->_Input->Z() > 1) {
attr._z = iceil(this->_Input->Z() * this->_Input->ZSize() / this->_ZSize);
attr._dz = _ZSize;
}
this->_Output->Initialize(attr);
}
// ---------------------------------------------------------------------------
// Serial/Multi-threaded body of Resampling::Run method
class ResamplingRun
{
public:
// -------------------------------------------------------------------------
// Data members
const BaseImage *_Input;
BaseImage *_Output;
InterpolateImageFunction *_Interpolator;
mutable int _T;
// -------------------------------------------------------------------------
/// Default constructor
ResamplingRun()
:
_Input(NULL),
_Output(NULL),
_Interpolator(NULL),
_T(0)
{}
// -------------------------------------------------------------------------
/// Copy constructor
ResamplingRun(const ResamplingRun &other)
:
_Input(other._Input),
_Output(other._Output),
_Interpolator(other._Interpolator),
_T(other._T)
{}
// -------------------------------------------------------------------------
/// Resamples the image within given output region for frame _T
void operator() (const blocked_range3d<int> &r) const
{
double x, y, z;
for (int k = r.pages().begin(); k != r.pages().end(); ++k)
for (int j = r.rows ().begin(); j != r.rows ().end(); ++j)
for (int i = r.cols ().begin(); i != r.cols ().end(); ++i) {
x = i, y = j, z = k;
_Output->ImageToWorld(x, y, z);
_Input ->WorldToImage(x, y, z);
_Output->PutAsDouble(i, j, k, _T, _Interpolator->Evaluate(x, y, z, _T));
}
}
// -------------------------------------------------------------------------
/// Resamples the image for the given range of output frames
void operator() (const blocked_range<int> &r) const
{
blocked_range3d<int> voxels(0, _Output->Z(),
0, _Output->Y(),
0, _Output->X());
for (_T = r.begin(); _T != r.end(); _T++) {
parallel_for(voxels, ResamplingRun(*this));
}
}
};
// ---------------------------------------------------------------------------
template <class VoxelType>
void Resampling<VoxelType>::Run()
{
MIRTK_START_TIMING();
this->Initialize();
ResamplingRun body;
body._Input = this->_Input;
body._Output = this->_Output;
body._Interpolator = this->_Interpolator;
body(blocked_range<int>(0, this->_Output->T()));
this->Finalize();
MIRTK_DEBUG_TIMING(5, this->NameOfClass());
}
// ---------------------------------------------------------------------------
// Explicit template instantiations
template class Resampling<char>;
template class Resampling<unsigned char>;
template class Resampling<short>;
template class Resampling<unsigned short>;
template class Resampling<int>;
template class Resampling<float>;
template class Resampling<double>;
} // namespace mirtk
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#include <vector>
#include <type_traits>
#include <dune/common/deprecated.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/mapper/interface.hh>
namespace Dune {
namespace GDT {
template <class VectorImp>
class ConstLocalDoFVector
{
static_assert(
std::is_base_of<Stuff::LA::VectorInterface<typename VectorImp::Traits, typename VectorImp::Traits::ScalarType>,
VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
public:
typedef VectorImp VectorType;
typedef typename VectorType::ScalarType ScalarType;
template <class M, class EntityType>
ConstLocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, const VectorType& vector)
: vector_(vector)
, indices_(mapper.numDofs(entity))
{
mapper.globalIndices(entity, indices_);
}
~ConstLocalDoFVector()
{
}
size_t size() const
{
return indices_.size();
}
ScalarType get(const size_t ii) const
{
assert(ii < indices_.size());
return vector_.get_entry(indices_[ii]);
}
private:
const VectorType& vector_;
protected:
Dune::DynamicVector<size_t> indices_;
private:
template <class V>
friend std::ostream& operator<<(std::ostream& /*out*/, const ConstLocalDoFVector<V>& /*vector*/);
}; // class ConstLocalDoFVector
template <class V>
std::ostream& operator<<(std::ostream& out, const ConstLocalDoFVector<V>& vector)
{
out << "[";
const size_t sz = vector.size();
if (sz > 0) {
out << vector.get(0);
for (size_t ii = 1; ii < sz; ++ii)
out << ", " << vector.get(ii);
} else
out << " ";
out << "]";
return out;
} // ... operator<<(...)
template <class VectorImp>
class LocalDoFVector : public ConstLocalDoFVector<VectorImp>
{
typedef ConstLocalDoFVector<VectorImp> BaseType;
public:
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::ScalarType ScalarType;
template <class M, class EntityType>
LocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, VectorType& vector)
: BaseType(mapper, entity, vector)
, vector_(vector)
{
}
~LocalDoFVector()
{
}
void set(const size_t ii, const ScalarType& val)
{
assert(ii < indices_.size());
vector_.set_entry(indices_[ii], val);
}
void add(const size_t ii, const ScalarType& val)
{
assert(ii < indices_.size());
vector_.add_to_entry(indices_[ii], val);
}
template <class OtherVectorImp>
void add(const OtherVectorImp& vector)
{
assert(vector.size() == indices_.size());
for (size_t ii = 0; ii < indices_.size(); ++ii)
add(ii, vector[ii]);
}
private:
using BaseType::indices_;
VectorType& vector_;
}; // class LocalDoFVector
template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction
: public Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols>
{
static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits, SpaceImp::dimDomain, SpaceImp::dimRange,
SpaceImp::dimRangeCols>,
SpaceImp>::value,
"SpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits,
typename VectorImp::Traits::ScalarType>,
VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
"Types do not match!");
typedef Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols> BaseType;
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRangeRows = BaseType::dimRangeCols;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;
ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent)
: BaseType(ent)
, space_(space)
, base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
, localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
{
assert(localVector_->size() == base_->size());
}
ConstLocalDiscreteFunction(ThisType&& source) = default;
ConstLocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~ConstLocalDiscreteFunction()
{
}
const SpaceType& space() const
{
return space_;
}
const DUNE_DEPRECATED_MSG("Use basis() instead (05.07.2015)!") BaseFunctionSetType& base() const
{
return basis();
}
const BaseFunctionSetType& basis() const
{
return *base_;
}
const ConstLocalDoFVectorType& vector() const
{
return *localVector_;
}
virtual size_t order() const override
{
return base_->order();
}
virtual void evaluate(const DomainType& xx, RangeType& ret) const override
{
assert(this->is_a_valid_point(xx));
ret *= 0.0;
std::vector<RangeType> tmpBaseValues(base_->size(), RangeType(0));
assert(localVector_->size() == tmpBaseValues.size());
base_->evaluate(xx, tmpBaseValues);
for (size_t ii = 0; ii < localVector_->size(); ++ii) {
tmpBaseValues[ii] *= localVector_->get(ii);
ret += tmpBaseValues[ii];
}
} // ... evaluate(...)
virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override
{
assert(this->is_a_valid_point(xx));
ret *= RangeFieldType(0);
std::vector<JacobianRangeType> tmpBaseJacobianValues(base_->size(), JacobianRangeType(0));
assert(localVector_->size() == tmpBaseJacobianValues.size());
base_->jacobian(xx, tmpBaseJacobianValues);
for (size_t ii = 0; ii < localVector_->size(); ++ii) {
tmpBaseJacobianValues[ii] *= localVector_->get(ii);
ret += tmpBaseJacobianValues[ii];
}
} // ... jacobian(...)
using BaseType::evaluate;
using BaseType::jacobian;
protected:
const SpaceType& space_;
std::unique_ptr<const BaseFunctionSetType> base_;
std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
}; // class ConstLocalDiscreteFunction
template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRangeRows = BaseType::dimRangeCols;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef LocalDoFVector<VectorType> LocalDoFVectorType;
LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
: BaseType(space, globalVector, ent)
, localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
{
assert(localVector_->size() == base_->size());
}
//! previous comment questioned validity, defaulting this doesn't touch that question
LocalDiscreteFunction(ThisType&& source) = default;
LocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~LocalDiscreteFunction()
{
}
LocalDoFVectorType& vector()
{
return *localVector_;
}
private:
using BaseType::space_;
using BaseType::entity_;
using BaseType::base_;
std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<commit_msg>[discretefunction.local] performance optimization for fv spaces<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#include <vector>
#include <type_traits>
#include <dune/common/deprecated.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/mapper/interface.hh>
namespace Dune {
namespace GDT {
template <class VectorImp>
class ConstLocalDoFVector
{
static_assert(
std::is_base_of<Stuff::LA::VectorInterface<typename VectorImp::Traits, typename VectorImp::Traits::ScalarType>,
VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
public:
typedef VectorImp VectorType;
typedef typename VectorType::ScalarType ScalarType;
template <class M, class EntityType>
ConstLocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, const VectorType& vector)
: vector_(vector)
, indices_(mapper.numDofs(entity))
{
mapper.globalIndices(entity, indices_);
}
~ConstLocalDoFVector()
{
}
size_t size() const
{
return indices_.size();
}
ScalarType get(const size_t ii) const
{
assert(ii < indices_.size());
return vector_.get_entry(indices_[ii]);
}
private:
const VectorType& vector_;
protected:
Dune::DynamicVector<size_t> indices_;
private:
template <class V>
friend std::ostream& operator<<(std::ostream& /*out*/, const ConstLocalDoFVector<V>& /*vector*/);
}; // class ConstLocalDoFVector
template <class V>
std::ostream& operator<<(std::ostream& out, const ConstLocalDoFVector<V>& vector)
{
out << "[";
const size_t sz = vector.size();
if (sz > 0) {
out << vector.get(0);
for (size_t ii = 1; ii < sz; ++ii)
out << ", " << vector.get(ii);
} else
out << " ";
out << "]";
return out;
} // ... operator<<(...)
template <class VectorImp>
class LocalDoFVector : public ConstLocalDoFVector<VectorImp>
{
typedef ConstLocalDoFVector<VectorImp> BaseType;
public:
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::ScalarType ScalarType;
template <class M, class EntityType>
LocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, VectorType& vector)
: BaseType(mapper, entity, vector)
, vector_(vector)
{
}
~LocalDoFVector()
{
}
void set(const size_t ii, const ScalarType& val)
{
assert(ii < indices_.size());
vector_.set_entry(indices_[ii], val);
}
void add(const size_t ii, const ScalarType& val)
{
assert(ii < indices_.size());
vector_.add_to_entry(indices_[ii], val);
}
template <class OtherVectorImp>
void add(const OtherVectorImp& vector)
{
assert(vector.size() == indices_.size());
for (size_t ii = 0; ii < indices_.size(); ++ii)
add(ii, vector[ii]);
}
private:
using BaseType::indices_;
VectorType& vector_;
}; // class LocalDoFVector
template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction
: public Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols>
{
static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits, SpaceImp::dimDomain, SpaceImp::dimRange,
SpaceImp::dimRangeCols>,
SpaceImp>::value,
"SpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits,
typename VectorImp::Traits::ScalarType>,
VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
"Types do not match!");
typedef Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols> BaseType;
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRangeRows = BaseType::dimRangeCols;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;
ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent)
: BaseType(ent)
, space_(space)
, base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
, localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
{
assert(localVector_->size() == base_->size());
}
ConstLocalDiscreteFunction(ThisType&& source) = default;
ConstLocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~ConstLocalDiscreteFunction()
{
}
const SpaceType& space() const
{
return space_;
}
const DUNE_DEPRECATED_MSG("Use basis() instead (05.07.2015)!") BaseFunctionSetType& base() const
{
return basis();
}
const BaseFunctionSetType& basis() const
{
return *base_;
}
const ConstLocalDoFVectorType& vector() const
{
return *localVector_;
}
virtual size_t order() const override
{
return base_->order();
}
void evaluate(const DomainType& xx, RangeType& ret) const override final
{
assert(this->is_a_valid_point(xx));
if (!(GDT::is_fv_space<SpaceType>::value || GDT::is_product_fv_space<SpaceType>::value)) {
std::fill(ret.begin(), ret.end(), RangeFieldType(0));
std::vector<RangeType> tmpBaseValues(base_->size(), RangeType(0));
assert(localVector_->size() == tmpBaseValues.size());
base_->evaluate(xx, tmpBaseValues);
for (size_t ii = 0; ii < localVector_->size(); ++ii) {
ret.axpy(localVector_->get(ii), tmpBaseValues[ii]);
}
} else {
for (size_t ii = 0; ii < localVector_->size(); ++ii)
ret[ii] = localVector_->get(ii);
}
} // ... evaluate(...)
virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override final
{
assert(this->is_a_valid_point(xx));
if (!(GDT::is_fv_space<SpaceType>::value || GDT::is_product_fv_space<SpaceType>::value)) {
std::fill(ret.begin(), ret.end(), RangeFieldType(0));
std::vector<JacobianRangeType> tmpBaseJacobianValues(base_->size(), JacobianRangeType(0));
assert(localVector_->size() == tmpBaseJacobianValues.size());
base_->jacobian(xx, tmpBaseJacobianValues);
for (size_t ii = 0; ii < localVector_->size(); ++ii)
ret.axpy(localVector_->get(ii), tmpBaseJacobianValues[ii]);
} else {
ret = JacobianRangeType(0);
}
} // ... jacobian(...)
using BaseType::evaluate;
using BaseType::jacobian;
protected:
const SpaceType& space_;
std::unique_ptr<const BaseFunctionSetType> base_;
std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
}; // class ConstLocalDiscreteFunction
template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRangeRows = BaseType::dimRangeCols;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef LocalDoFVector<VectorType> LocalDoFVectorType;
LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
: BaseType(space, globalVector, ent)
, localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
{
assert(localVector_->size() == base_->size());
}
//! previous comment questioned validity, defaulting this doesn't touch that question
LocalDiscreteFunction(ThisType&& source) = default;
LocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~LocalDiscreteFunction()
{
}
LocalDoFVectorType& vector()
{
return *localVector_;
}
private:
using BaseType::space_;
using BaseType::entity_;
using BaseType::base_;
std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<|endoftext|> |
<commit_before>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#include "ConnectionManager.h"
#include "Capture.h"
#include "TcpClient.h"
#include "TcpServer.h"
#include "TimerManager.h"
#include "Serialization.h"
#include "TestRemoteMessages.h"
#include "EventBuffer.h"
#include "ProcessUtils.h"
#include "LinuxPerf.h"
#if __linux__
#include "LinuxUtils.h"
#endif
#include <fstream>
#include <streambuf>
#include <sstream>
#include <iostream>
//-----------------------------------------------------------------------------
struct CrossPlatformMessage
{
CrossPlatformMessage();
void Fill();
void Save();
void Load();
void Dump();
std::string ToRaw();
void FromRaw(const char* data, uint32_t size);
ORBIT_SERIALIZABLE;
std::wstring m_WName;
uint32_t m_Id;
std::string m_Name;
std::vector<std::string> m_Strings;
std::map<uint32_t, std::string> m_StringMap;
std::string m_SerializationPath;
uint32_t m_Size;
uint32_t m_SizeOnSave;
};
//-----------------------------------------------------------------------------
CrossPlatformMessage::CrossPlatformMessage()
{
static uint32_t id = 0;
m_Id = ++id;
m_Size = sizeof(CrossPlatformMessage);
m_SizeOnSave = 0;
m_SerializationPath = ws2s( Path::GetBasePath() ) + "xmsg.orbit";
PRINT_VAR(m_SerializationPath);
}
//-----------------------------------------------------------------------------
ORBIT_SERIALIZE( CrossPlatformMessage, 1 )
{
ORBIT_NVP_VAL( 0, m_Name );
ORBIT_NVP_VAL( 0, m_Strings );
ORBIT_NVP_VAL( 0, m_StringMap );
ORBIT_NVP_VAL( 1, m_SizeOnSave );
ORBIT_NVP_VAL( 1, m_Id );
//ORBIT_NVP_VAL( 1, m_WName );
}
//-----------------------------------------------------------------------------
void CrossPlatformMessage::Fill()
{
m_Name = "Orbit CrossPlatformMessage";
m_WName = L"Wname";
for( int i = 0 ; i < 1000; ++i )
{
std::string val = std::to_string(i);
m_Strings.push_back(val);
m_StringMap[i] = val;
}
}
//-----------------------------------------------------------------------------
void CrossPlatformMessage::Save()
{
std::ofstream myfile( m_SerializationPath, std::ios::binary );
if( !myfile.fail() )
{
m_SizeOnSave = sizeof(CrossPlatformMessage);
SCOPE_TIMER_LOG( Format( L"Saving cross platform message" ) );
cereal::BinaryOutputArchive archive( myfile );
archive(*this);
myfile.close();
}
}
//-----------------------------------------------------------------------------
std::string CrossPlatformMessage::ToRaw()
{
m_SizeOnSave = sizeof(CrossPlatformMessage);
std::stringstream buffer;
cereal::BinaryOutputArchive archive( buffer );
archive(*this);
PRINT_VAR(buffer.str().size());
return buffer.str();
}
void CrossPlatformMessage::FromRaw(const char* data, uint32_t size)
{
PRINT_FUNC;
PRINT_VAR(size);
std::istringstream buffer(std::string(data, size));
cereal::BinaryInputArchive inputAr( buffer );
inputAr(*this);
}
//-----------------------------------------------------------------------------
void CrossPlatformMessage::Load()
{
std::ifstream myfile( m_SerializationPath, std::ios::binary );
if( !myfile.fail() )
{
cereal::BinaryInputArchive archive( myfile );
archive(*this);
myfile.close();
}
Dump();
}
//-----------------------------------------------------------------------------
void CrossPlatformMessage::Dump()
{
PRINT_VAR(m_Name);
for( std::string& str : m_Strings )
{
PRINT_VAR(str);
}
for( auto pair : m_StringMap )
{
PRINT_VAR(pair.first);
PRINT_VAR(pair.second);
}
}
//-----------------------------------------------------------------------------
ConnectionManager::ConnectionManager() : m_ExitRequested(false), m_IsRemote(false)
{
}
//-----------------------------------------------------------------------------
ConnectionManager::~ConnectionManager()
{
TerminateThread();
}
//-----------------------------------------------------------------------------
void ConnectionManager::TerminateThread()
{
if (m_Thread)
{
m_ExitRequested = true;
m_Thread->join();
m_Thread = nullptr;
}
}
//-----------------------------------------------------------------------------
ConnectionManager& ConnectionManager::Get()
{
static ConnectionManager instance;
return instance;
}
//-----------------------------------------------------------------------------
void ConnectionManager::Init()
{
SetupTestMessageHandler();
SetupServerCallbacks();
}
//-----------------------------------------------------------------------------
void ConnectionManager::InitAsRemote(std::string a_Host)
{
m_IsRemote = true;
m_Host = a_Host;
TerminateThread();
m_Thread = std::make_unique<std::thread>(&ConnectionManager::ConnectionThread, this);
//CrossPlatformMessage xmsg;
//xmsg.Fill();
//xmsg.Load();
}
//-----------------------------------------------------------------------------
void ConnectionManager::StartCaptureAsRemote()
{
Capture::StartCapture();
}
//-----------------------------------------------------------------------------
void ConnectionManager::StopCaptureAsRemote()
{
Capture::StopCapture();
}
//-----------------------------------------------------------------------------
void ConnectionManager::Stop()
{
m_ExitRequested = true;
}
//-----------------------------------------------------------------------------
void ConnectionManager::SetupTestMessageHandler()
{
GTcpServer->AddCallback( Msg_CrossPlatform, [=]( const Message & a_Msg )
{
CrossPlatformMessage msg;
PRINT_VAR(a_Msg.m_Size);
msg.FromRaw(a_Msg.m_Data, a_Msg.m_Size);
msg.Dump();
} );
}
//-----------------------------------------------------------------------------
void ConnectionManager::SetupClientCallbacks()
{
GTcpClient->AddCallback( Msg_StartCapture, [=]( const Message & a_Msg )
{
StartCaptureAsRemote();
} );
GTcpClient->AddCallback( Msg_StopCapture, [=]( const Message & a_Msg )
{
StopCaptureAsRemote();
} );
}
//-----------------------------------------------------------------------------
void ConnectionManager::SetupServerCallbacks()
{
GTcpServer->AddCallback( Msg_RemotePerf, [=]( const Message & a_Msg )
{
PRINT_VAR(a_Msg.m_Size);
std::istringstream buffer(std::string(a_Msg.m_Data, a_Msg.m_Size));
LinuxPerf perf(0);
perf.LoadPerfData(buffer);
} );
}
//-----------------------------------------------------------------------------
void ConnectionManager::SendTestMessage()
{
CrossPlatformMessage msg;
msg.Fill();
std::string rawMsg = msg.ToRaw();
GTcpClient->Send(Msg_CrossPlatform, (void*)rawMsg.data(), rawMsg.size());
//TestRemoteMessages::Get().Run();
}
//-----------------------------------------------------------------------------
void ConnectionManager::SendProcesses()
{
ProcessList processList;
std::string processData = SerializeObjectHumanReadable(processList);
PRINT_VAR(processData);
GTcpClient->Send(Msg_RemoteProcessList, (void*)processData.data(), processData.size());
}
//-----------------------------------------------------------------------------
void ConnectionManager::ConnectionThread()
{
while (!m_ExitRequested)
{
if (!GTcpClient || !GTcpClient->IsValid())
{
GTcpClient = std::make_unique<TcpClient>(m_Host);
if (GTcpClient->IsValid())
{
SetupClientCallbacks();
GTimerManager = std::make_unique<TimerManager>(true);
}
}
else
{
std::string msg("Hello from ConnectionManager");
GTcpClient->Send(msg);
SendProcesses();
Sleep(2000);
}
}
}
<commit_msg>Make sure we the remote process list contains cpu utilization.<commit_after>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#include "ConnectionManager.h"
#include "Capture.h"
#include "TcpClient.h"
#include "TcpServer.h"
#include "TimerManager.h"
#include "Serialization.h"
#include "TestRemoteMessages.h"
#include "EventBuffer.h"
#include "ProcessUtils.h"
#include "LinuxPerf.h"
#if __linux__
#include "LinuxUtils.h"
#endif
#include <fstream>
#include <streambuf>
#include <sstream>
#include <iostream>
//-----------------------------------------------------------------------------
struct CrossPlatformMessage
{
CrossPlatformMessage();
void Fill();
void Save();
void Load();
void Dump();
std::string ToRaw();
void FromRaw(const char* data, uint32_t size);
ORBIT_SERIALIZABLE;
std::wstring m_WName;
uint32_t m_Id;
std::string m_Name;
std::vector<std::string> m_Strings;
std::map<uint32_t, std::string> m_StringMap;
std::string m_SerializationPath;
uint32_t m_Size;
uint32_t m_SizeOnSave;
};
//-----------------------------------------------------------------------------
CrossPlatformMessage::CrossPlatformMessage()
{
static uint32_t id = 0;
m_Id = ++id;
m_Size = sizeof(CrossPlatformMessage);
m_SizeOnSave = 0;
m_SerializationPath = ws2s( Path::GetBasePath() ) + "xmsg.orbit";
PRINT_VAR(m_SerializationPath);
}
//-----------------------------------------------------------------------------
ORBIT_SERIALIZE( CrossPlatformMessage, 1 )
{
ORBIT_NVP_VAL( 0, m_Name );
ORBIT_NVP_VAL( 0, m_Strings );
ORBIT_NVP_VAL( 0, m_StringMap );
ORBIT_NVP_VAL( 1, m_SizeOnSave );
ORBIT_NVP_VAL( 1, m_Id );
//ORBIT_NVP_VAL( 1, m_WName );
}
//-----------------------------------------------------------------------------
void CrossPlatformMessage::Fill()
{
m_Name = "Orbit CrossPlatformMessage";
m_WName = L"Wname";
for( int i = 0 ; i < 1000; ++i )
{
std::string val = std::to_string(i);
m_Strings.push_back(val);
m_StringMap[i] = val;
}
}
//-----------------------------------------------------------------------------
void CrossPlatformMessage::Save()
{
std::ofstream myfile( m_SerializationPath, std::ios::binary );
if( !myfile.fail() )
{
m_SizeOnSave = sizeof(CrossPlatformMessage);
SCOPE_TIMER_LOG( Format( L"Saving cross platform message" ) );
cereal::BinaryOutputArchive archive( myfile );
archive(*this);
myfile.close();
}
}
//-----------------------------------------------------------------------------
std::string CrossPlatformMessage::ToRaw()
{
m_SizeOnSave = sizeof(CrossPlatformMessage);
std::stringstream buffer;
cereal::BinaryOutputArchive archive( buffer );
archive(*this);
PRINT_VAR(buffer.str().size());
return buffer.str();
}
void CrossPlatformMessage::FromRaw(const char* data, uint32_t size)
{
PRINT_FUNC;
PRINT_VAR(size);
std::istringstream buffer(std::string(data, size));
cereal::BinaryInputArchive inputAr( buffer );
inputAr(*this);
}
//-----------------------------------------------------------------------------
void CrossPlatformMessage::Load()
{
std::ifstream myfile( m_SerializationPath, std::ios::binary );
if( !myfile.fail() )
{
cereal::BinaryInputArchive archive( myfile );
archive(*this);
myfile.close();
}
Dump();
}
//-----------------------------------------------------------------------------
void CrossPlatformMessage::Dump()
{
PRINT_VAR(m_Name);
for( std::string& str : m_Strings )
{
PRINT_VAR(str);
}
for( auto pair : m_StringMap )
{
PRINT_VAR(pair.first);
PRINT_VAR(pair.second);
}
}
//-----------------------------------------------------------------------------
ConnectionManager::ConnectionManager() : m_ExitRequested(false), m_IsRemote(false)
{
}
//-----------------------------------------------------------------------------
ConnectionManager::~ConnectionManager()
{
TerminateThread();
}
//-----------------------------------------------------------------------------
void ConnectionManager::TerminateThread()
{
if (m_Thread)
{
m_ExitRequested = true;
m_Thread->join();
m_Thread = nullptr;
}
}
//-----------------------------------------------------------------------------
ConnectionManager& ConnectionManager::Get()
{
static ConnectionManager instance;
return instance;
}
//-----------------------------------------------------------------------------
void ConnectionManager::Init()
{
SetupTestMessageHandler();
SetupServerCallbacks();
}
//-----------------------------------------------------------------------------
void ConnectionManager::InitAsRemote(std::string a_Host)
{
m_IsRemote = true;
m_Host = a_Host;
TerminateThread();
m_Thread = std::make_unique<std::thread>(&ConnectionManager::ConnectionThread, this);
//CrossPlatformMessage xmsg;
//xmsg.Fill();
//xmsg.Load();
}
//-----------------------------------------------------------------------------
void ConnectionManager::StartCaptureAsRemote()
{
Capture::StartCapture();
}
//-----------------------------------------------------------------------------
void ConnectionManager::StopCaptureAsRemote()
{
Capture::StopCapture();
}
//-----------------------------------------------------------------------------
void ConnectionManager::Stop()
{
m_ExitRequested = true;
}
//-----------------------------------------------------------------------------
void ConnectionManager::SetupTestMessageHandler()
{
GTcpServer->AddCallback( Msg_CrossPlatform, [=]( const Message & a_Msg )
{
CrossPlatformMessage msg;
PRINT_VAR(a_Msg.m_Size);
msg.FromRaw(a_Msg.m_Data, a_Msg.m_Size);
msg.Dump();
} );
}
//-----------------------------------------------------------------------------
void ConnectionManager::SetupClientCallbacks()
{
GTcpClient->AddCallback( Msg_StartCapture, [=]( const Message & a_Msg )
{
StartCaptureAsRemote();
} );
GTcpClient->AddCallback( Msg_StopCapture, [=]( const Message & a_Msg )
{
StopCaptureAsRemote();
} );
}
//-----------------------------------------------------------------------------
void ConnectionManager::SetupServerCallbacks()
{
GTcpServer->AddCallback( Msg_RemotePerf, [=]( const Message & a_Msg )
{
PRINT_VAR(a_Msg.m_Size);
std::istringstream buffer(std::string(a_Msg.m_Data, a_Msg.m_Size));
LinuxPerf perf(0);
perf.LoadPerfData(buffer);
} );
}
//-----------------------------------------------------------------------------
void ConnectionManager::SendTestMessage()
{
CrossPlatformMessage msg;
msg.Fill();
std::string rawMsg = msg.ToRaw();
GTcpClient->Send(Msg_CrossPlatform, (void*)rawMsg.data(), rawMsg.size());
//TestRemoteMessages::Get().Run();
}
//-----------------------------------------------------------------------------
void ConnectionManager::SendProcesses()
{
ProcessList processList;
processList.UpdateCpuTimes();
std::string processData = SerializeObjectHumanReadable(processList);
PRINT_VAR(processData);
GTcpClient->Send(Msg_RemoteProcessList, (void*)processData.data(), processData.size());
}
//-----------------------------------------------------------------------------
void ConnectionManager::ConnectionThread()
{
while (!m_ExitRequested)
{
if (!GTcpClient || !GTcpClient->IsValid())
{
GTcpClient = std::make_unique<TcpClient>(m_Host);
if (GTcpClient->IsValid())
{
SetupClientCallbacks();
GTimerManager = std::make_unique<TimerManager>(true);
}
}
else
{
std::string msg("Hello from ConnectionManager");
GTcpClient->Send(msg);
SendProcesses();
Sleep(2000);
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <PluginFactory/details/NullPluginService.hpp>
#include <PluginFactory/details/PluginExtensionHelper.hpp>
#include <PluginFactory/details/PluginHandle.hpp>
#include <PluginFactory/details/PolicyHolder.hpp>
#include <PluginFactory/details/PluginLoader.hpp>
#include <PluginFactory/details/PolicyProperties.hpp>
#include <PluginFactory/Exceptions.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
namespace PluginFactory {
// A tag type to indicate we want to create a std::shared_ptr of the plugin
// rather than std::unique_ptr
struct AsSharedTagType {};
// <PluginInterface> is the abstract interface of the plugin object itself. You'll need
// a PluginFactory for each different type of plugin you wish to support.
//
// <PluginServiceInterface> is the interface given to the plugin to allow it to make
// modifications to the main program. This is to encourage plugin developers not to
// engage in crazy behavior like calling willy-nilly into the base process's code.
//
// NOTE: lifetime management using plugins can be difficult. It is essential
// the PluginFactory stays in scope longer than any instanced plugin. Failure
// to do so will most likely end in the process crashing.
template<class PluginInterface, class PluginServiceInterface = details::NullPluginService, class PolicyOwnershipProperty = details::PolicyIsInternal>
class PluginFactory : public details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty>
{
public:
static AsSharedTagType create_shared;
// @pluginDirectory is the directory path to load plugins from.
template<typename... Args>
PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... pluginServiceArguments);
void load(); // load all found plugins
void load(const boost::filesystem::path& pluginPath); // load a specific plugin (@pluginPath)
void unload(); // unload all loaded plugins
void unload(const boost::filesystem::path& pluginPath); // unload a specific plugin (@pluginPath)
std::unique_ptr<PluginInterface> instance(const std::string& plugin);
std::shared_ptr<PluginInterface> instance(const std::string& pluginName, AsSharedTagType /*create_shared*/);
std::vector<std::string> availablePlugins() const;
private:
using PluginPath = std::string;
using PluginInstanceMethod = std::function<PluginInterface* (PluginServiceInterface&)>;
std::unordered_map<PluginPath, PluginHandle<PluginInterface, PluginServiceInterface>> plugins_;
boost::filesystem::path pluginDirectory_;
std::string pluginVersion_;
std::string compilerToken_;
std::string serviceVersion_;
};
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
AsSharedTagType PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::create_shared;
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
template<typename... Args>
PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... pluginServiceArguments)
: details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty>(std::forward<Args>(pluginServiceArguments)...)
, pluginDirectory_(pluginDirectory)
{
if(!boost::filesystem::exists(pluginDirectory_))
{
throw PluginPathDoesntExist(pluginDirectory_);
}
if(!boost::filesystem::is_directory(pluginDirectory_))
{
throw PluginPathIsntDirectory(pluginDirectory_);
}
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load()
{
for(boost::filesystem::directory_iterator iter(pluginDirectory_), end; iter != end; ++iter)
{
const auto& path = iter->path();
if(boost::filesystem::is_directory(path))
{
continue;
}
if(path.extension().string() == details::PluginExtensionHelper::extension())
{
load(path);
}
}
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load(const boost::filesystem::path& pluginPath)
{
try
{
details::PluginLoader loader(pluginPath);
loader.validateCompiler(compilerToken_);
loader.validatePluginVersion(pluginVersion_);
loader.validatePluginServiceVersion(serviceVersion_);
auto pluginHandle = loader.getPluginCreatorHandle<PluginInterface, PluginServiceInterface>();
plugins_.emplace(pluginPath.string(), pluginHandle);
}
catch(const PluginLoaderValidationException& )
{
// ... eat the exception
}
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload()
{
plugins_.clear();
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload(const boost::filesystem::path& pluginPath)
{
auto iter = plugins_.find(pluginPath.string());
if(iter != plugins_.end())
{
plugins_.erase(iter);
}
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
std::unique_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName)
{
std::unique_ptr<PluginInterface> p;
auto iter = plugins_.find(pluginName);
if(iter != plugins_.end())
{
auto& createPlugin = iter->second;
p.reset(createPlugin(this->policy_));
}
return p;
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
std::shared_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName, AsSharedTagType)
{
std::shared_ptr<PluginInterface> p;
auto iter = plugins_.find(pluginName);
if(iter != plugins_.end())
{
auto& createPlugin = iter->second;
p.reset(createPlugin(this->policy_));
}
return p;
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
std::vector<std::string> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::availablePlugins() const
{
std::vector<std::string> plugins;
plugins.reserve(plugins_.size());
for(const auto& info : plugins_)
{
const auto& key = info.first;
plugins.push_back(key);
}
return plugins;
}
}
<commit_msg>PluginHandle -> details::PluginHandle, the namespace should have been there from the get go.<commit_after>#pragma once
#include <PluginFactory/details/NullPluginService.hpp>
#include <PluginFactory/details/PluginExtensionHelper.hpp>
#include <PluginFactory/details/PluginHandle.hpp>
#include <PluginFactory/details/PolicyHolder.hpp>
#include <PluginFactory/details/PluginLoader.hpp>
#include <PluginFactory/details/PolicyProperties.hpp>
#include <PluginFactory/Exceptions.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
namespace PluginFactory {
// A tag type to indicate we want to create a std::shared_ptr of the plugin
// rather than std::unique_ptr
struct AsSharedTagType {};
// <PluginInterface> is the abstract interface of the plugin object itself. You'll need
// a PluginFactory for each different type of plugin you wish to support.
//
// <PluginServiceInterface> is the interface given to the plugin to allow it to make
// modifications to the main program. This is to encourage plugin developers not to
// engage in crazy behavior like calling willy-nilly into the base process's code.
//
// NOTE: lifetime management using plugins can be difficult. It is essential
// the PluginFactory stays in scope longer than any instanced plugin. Failure
// to do so will most likely end in the process crashing.
template<class PluginInterface, class PluginServiceInterface = details::NullPluginService, class PolicyOwnershipProperty = details::PolicyIsInternal>
class PluginFactory : public details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty>
{
public:
static AsSharedTagType create_shared;
// @pluginDirectory is the directory path to load plugins from.
template<typename... Args>
PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... pluginServiceArguments);
void load(); // load all found plugins
void load(const boost::filesystem::path& pluginPath); // load a specific plugin (@pluginPath)
void unload(); // unload all loaded plugins
void unload(const boost::filesystem::path& pluginPath); // unload a specific plugin (@pluginPath)
std::unique_ptr<PluginInterface> instance(const std::string& plugin);
std::shared_ptr<PluginInterface> instance(const std::string& pluginName, AsSharedTagType /*create_shared*/);
std::vector<std::string> availablePlugins() const;
private:
using PluginPath = std::string;
using PluginInstanceMethod = std::function<PluginInterface* (PluginServiceInterface&)>;
std::unordered_map<PluginPath, details::PluginHandle<PluginInterface, PluginServiceInterface>> plugins_;
boost::filesystem::path pluginDirectory_;
std::string pluginVersion_;
std::string compilerToken_;
std::string serviceVersion_;
};
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
AsSharedTagType PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::create_shared;
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
template<typename... Args>
PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... pluginServiceArguments)
: details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty>(std::forward<Args>(pluginServiceArguments)...)
, pluginDirectory_(pluginDirectory)
{
if(!boost::filesystem::exists(pluginDirectory_))
{
throw PluginPathDoesntExist(pluginDirectory_);
}
if(!boost::filesystem::is_directory(pluginDirectory_))
{
throw PluginPathIsntDirectory(pluginDirectory_);
}
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load()
{
for(boost::filesystem::directory_iterator iter(pluginDirectory_), end; iter != end; ++iter)
{
const auto& path = iter->path();
if(boost::filesystem::is_directory(path))
{
continue;
}
if(path.extension().string() == details::PluginExtensionHelper::extension())
{
load(path);
}
}
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load(const boost::filesystem::path& pluginPath)
{
try
{
details::PluginLoader loader(pluginPath);
loader.validateCompiler(compilerToken_);
loader.validatePluginVersion(pluginVersion_);
loader.validatePluginServiceVersion(serviceVersion_);
auto pluginHandle = loader.getPluginCreatorHandle<PluginInterface, PluginServiceInterface>();
plugins_.emplace(pluginPath.string(), pluginHandle);
}
catch(const PluginLoaderValidationException& )
{
// ... eat the exception
}
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload()
{
plugins_.clear();
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload(const boost::filesystem::path& pluginPath)
{
auto iter = plugins_.find(pluginPath.string());
if(iter != plugins_.end())
{
plugins_.erase(iter);
}
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
std::unique_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName)
{
std::unique_ptr<PluginInterface> p;
auto iter = plugins_.find(pluginName);
if(iter != plugins_.end())
{
auto& createPlugin = iter->second;
p.reset(createPlugin(this->policy_));
}
return p;
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
std::shared_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName, AsSharedTagType)
{
std::shared_ptr<PluginInterface> p;
auto iter = plugins_.find(pluginName);
if(iter != plugins_.end())
{
auto& createPlugin = iter->second;
p.reset(createPlugin(this->policy_));
}
return p;
}
template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty>
std::vector<std::string> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::availablePlugins() const
{
std::vector<std::string> plugins;
plugins.reserve(plugins_.size());
for(const auto& info : plugins_)
{
const auto& key = info.first;
plugins.push_back(key);
}
return plugins;
}
}
<|endoftext|> |
<commit_before>/*
Author: Vytautas Vislavicius
Extention of Generic Flow (https://arxiv.org/abs/1312.3572)
*/
#include "AliGFWCuts.h"
const Int_t AliGFWCuts::fNTrackFlags=9;
const Int_t AliGFWCuts::fNEventFlags=8;
AliGFWCuts::AliGFWCuts():
fSystFlag(0),
fFilterBit(96),
fDCAxyCut(7),
fDCAzCut(2),
fTPCNcls(70),
fVtxZ(10),
fEta(0.8),
fRequiresExtraWeight(kTRUE)
{
};
AliGFWCuts::~AliGFWCuts() {
};
Int_t AliGFWCuts::AcceptTrack(AliAODTrack* l_Tr, Double_t* l_DCA, const Int_t &BitShift, const Bool_t &lDisableDCAxyCheck) {
if(TMath::Abs(l_Tr->Eta())>fEta) return 0;
if(!l_Tr->TestFilterBit(fFilterBit)) return 0;
if(fFilterBit!=2) {//Check is not valid for ITSsa tracks
if(l_Tr->GetTPCNclsF()<fTPCNcls) return 0;
} else {
UInt_t status = l_Tr->GetStatus();
if ((status&AliESDtrack::kITSrefit)==0) return 0;
if ((status & AliESDtrack::kITSin) == 0 || (status & AliESDtrack::kTPCin)) return 0;
};
if(!l_DCA) return 1<<BitShift;
if(l_DCA[0]>fDCAzCut) return 0;
if(lDisableDCAxyCheck) return 1<<BitShift;
Double_t DCAxycut;
if(fFilterBit!=2) DCAxycut = 0.0105+0.0350/TMath::Power(l_Tr->Pt(),1.1);//*fDCAxyCut/7.; //TPC tracks and my ITS cuts
else DCAxycut = 0.0231+0.0315/TMath::Power(l_Tr->Pt(),1.3);
if(l_DCA[1]>DCAxycut*(fDCAxyCut/7.))
return 0;
return 1<<BitShift;
};
Int_t AliGFWCuts::AcceptParticle(AliVParticle *l_Pa, Int_t BitShift, Double_t ptLow, Double_t ptHigh) {
if(TMath::Abs(l_Pa->Eta())>fEta) return 0;
if(ptLow>0) if(l_Pa->Pt()<ptLow) return 0;
if(ptHigh>0) if(l_Pa->Pt()>ptHigh) return 0;
return 1<<BitShift;
};
Int_t AliGFWCuts::AcceptVertex(AliAODEvent *l_Ev, Int_t BitShift) {
Double_t lvtxz = TMath::Abs(l_Ev->GetPrimaryVertex()->GetZ());
if(lvtxz>fVtxZ) return 0;
return 1<<BitShift;
};
void AliGFWCuts::ResetCuts() {
fSystFlag=0;
fFilterBit=96;
fDCAxyCut=7;
fDCAzCut=2;
fTPCNcls=70;
fVtxZ=10;
fEta=0.8;
fRequiresExtraWeight=kTRUE;
};
void AliGFWCuts::PrintSetup() {
printf("**********\n");
printf("Syst. flag: %i\n",fSystFlag);
printf("Eta: %f\n",fEta);
printf("(Flag 1) Filter bit: %i\n",fFilterBit);
printf("(Flag 2,3) DCAxy cut: %2.0f sigma\n",fDCAxyCut);
printf("(Flag 4,5) DCAz cut: %f\n",fDCAzCut);
printf("(Flag 6-8) TPC Ncls: %i\n",fTPCNcls);
printf("(Flag 9) ITS tracks\n");
printf("Rest of the flags are global per event. Total flag = %i + vtx/ev flag\n",fNTrackFlags);
printf("(Flag 1-3) Vertex selection: |z|<%2.1f\n",fVtxZ);
printf("(Flag 4-5) CL1, CL2 multi. estimator (no weights)\n");
printf("(Flag 6) pile-up 15000 (-> 1500) cut\n");
//printf("(Flag 12, disabled) ITS tracks (filter bit %i, TPC Ncls = %i)\n",fFilterBit,fTPCNcls);
printf("**********\n");
};
void AliGFWCuts::SetupTrackCuts(Int_t sysflag) {
switch(sysflag) {
case 1:
fFilterBit=768;
fRequiresExtraWeight=kTRUE;
break;
case 2:
fDCAxyCut=10.;
fRequiresExtraWeight=kTRUE;
break;
case 3:
fDCAxyCut=4.;
fRequiresExtraWeight=kTRUE;
break;
case 4:
fDCAzCut=1;
fRequiresExtraWeight=kTRUE;
break;
case 5:
fDCAzCut=0.5;
fRequiresExtraWeight=kTRUE;
break;
case 6:
fTPCNcls=80;
fRequiresExtraWeight=kTRUE;
break;
case 7:
fTPCNcls=90;
fRequiresExtraWeight=kTRUE;
break;
case 8:
fTPCNcls=100;
fRequiresExtraWeight=kTRUE;
break;
case 9:
fFilterBit=2;
fEta=1.6;
fRequiresExtraWeight=kTRUE;
default:
break;
};
};
void AliGFWCuts::SetupEventCuts(Int_t sysflag) {
switch(sysflag) {
case 1:
fVtxZ = 5;
fRequiresExtraWeight=kTRUE;
break;
case 2:
fVtxZ = 7;
fRequiresExtraWeight=kTRUE;
break;
case 3:
fVtxZ = 9;
fRequiresExtraWeight=kTRUE;
break;
case 4:
printf("Warning! Event flag %i (syst. flag %i), CL1 estmator: make sure the proper estimator is used in the task!\n",sysflag, sysflag+fNTrackFlags);
fRequiresExtraWeight=kFALSE;
break;
case 5:
printf("Warning! Event flag %i (syst. flag %i), CL0 estmator: make sure the proper estimator is used in the task!\n",sysflag, sysflag+fNTrackFlags);
fRequiresExtraWeight=kFALSE;
break;
case 6:
printf("Warning! Event flag %i (syst. flag %i), PU cuts: make sure proper PU cuts are used in the task!\n",sysflag, sysflag+fNTrackFlags);
fRequiresExtraWeight=kTRUE;
break;
case 7:
printf("Warning! Event flag %i (syst. flag %i), magnetic field configuration ++: no cuts here, please make sure the proper runlist is used!\n",sysflag,sysflag+fNTrackFlags);
fRequiresExtraWeight=kFALSE;
break;
case 8:
printf("Warning! Event flag %i (syst. flag %i), magnetic field configuration --: no cuts here, please make sure the proper runlist is used!\n",sysflag,sysflag+fNTrackFlags);
fRequiresExtraWeight=kFALSE;
break;
default:
break;
};
};
void AliGFWCuts::SetupCuts(Int_t sysflag) {
ResetCuts();
fSystFlag=sysflag;
if(sysflag==0 || sysflag>fNTrackFlags+fNEventFlags) return;
if(sysflag<=fNTrackFlags) SetupTrackCuts(sysflag);
else SetupEventCuts(sysflag-fNTrackFlags);
};
TString *AliGFWCuts::GetTrackFlagDescriptor(Int_t sysflag) {
TString *retstr = new TString("");
switch(sysflag) {
case 1:
retstr->Append("Filter bit 768");
break;
case 2:
retstr->Append("DCA_{xy} < 10 (old:8) sigma");
break;
case 3:
retstr->Append("DCA_{xy} < 4 (old:6) sigma");
break;
case 4:
retstr->Append("DCA_{z} < 1 cm");
break;
case 5:
retstr->Append("DCA_{z} < 0.5 cm");
break;
case 6:
retstr->Append("TPC N_{Cls} > 80");
break;
case 7:
retstr->Append("TPC N_{Cls} > 90");
break;
case 8:
retstr->Append("TPC N_{Cls} > 100");
break;
case 9:
retstr->Append("ITS tracklets");
break;
default:
break;
};
return retstr;
};
TString* AliGFWCuts::GetEventFlagDescriptor(Int_t sysflag) {
TString *retstr = new TString("");
switch(sysflag) {
case 1:
retstr->Append("|z_{vtx}| < 5 cm");
break;
case 2:
retstr->Append("|z_{vtx}| < 7 cm");
break;
case 3:
retstr->Append("|z_{vtx}| < 9 cm");
break;
case 4:
retstr->Append("CL1 multi.");
break;
case 5:
retstr->Append("CL0 multi.");
break;
case 6:
retstr->Append("PU cut 1500");
break;
case 7:
retstr->Append("MF ++");
break;
case 8:
retstr->Append("MF --");
break;
default:
break;
};
return retstr;
};
TString *AliGFWCuts::GetFlagDescription(Int_t sysflag) {
if(sysflag>0 && sysflag <= fNTrackFlags + fNEventFlags) {
if(sysflag>fNTrackFlags) return GetEventFlagDescriptor(sysflag-fNTrackFlags);
return GetTrackFlagDescriptor(sysflag);
};
TString *retst = new TString("");
if(sysflag==0) retst->Append("Nominal");
else retst->Append("Unknown_%i",sysflag);
return retst;
};
<commit_msg>Minor bug fix in AliGFWCut<commit_after>/*
Author: Vytautas Vislavicius
Extention of Generic Flow (https://arxiv.org/abs/1312.3572)
*/
#include "AliGFWCuts.h"
const Int_t AliGFWCuts::fNTrackFlags=9;
const Int_t AliGFWCuts::fNEventFlags=8;
AliGFWCuts::AliGFWCuts():
fSystFlag(0),
fFilterBit(96),
fDCAxyCut(7),
fDCAzCut(2),
fTPCNcls(70),
fVtxZ(10),
fEta(0.8),
fRequiresExtraWeight(kTRUE)
{
};
AliGFWCuts::~AliGFWCuts() {
};
Int_t AliGFWCuts::AcceptTrack(AliAODTrack* l_Tr, Double_t* l_DCA, const Int_t &BitShift, const Bool_t &lDisableDCAxyCheck) {
if(TMath::Abs(l_Tr->Eta())>fEta) return 0;
if(!l_Tr->TestFilterBit(fFilterBit)) return 0;
if(fFilterBit!=2) {//Check is not valid for ITSsa tracks
if(l_Tr->GetTPCNclsF()<fTPCNcls) return 0;
} else {
UInt_t status = l_Tr->GetStatus();
if ((status&AliESDtrack::kITSrefit)==0) return 0;
if ((status & AliESDtrack::kITSin) == 0 || (status & AliESDtrack::kTPCin)) return 0;
};
if(!l_DCA) return 1<<BitShift;
if(l_DCA[2]>fDCAzCut) return 0;
if(lDisableDCAxyCheck) return 1<<BitShift;
Double_t DCAxycut;
if(fFilterBit!=2) DCAxycut = 0.0105+0.0350/TMath::Power(l_Tr->Pt(),1.1);//*fDCAxyCut/7.; //TPC tracks and my ITS cuts
else DCAxycut = 0.0231+0.0315/TMath::Power(l_Tr->Pt(),1.3);
Double_t DCAxyValue = TMath::Sqrt(l_DCA[0]*l_DCA[0] + l_DCA[1]*l_DCA[1]);
if(DCAxyValue>DCAxycut*(fDCAxyCut/7.))
return 0;
return 1<<BitShift;
};
Int_t AliGFWCuts::AcceptParticle(AliVParticle *l_Pa, Int_t BitShift, Double_t ptLow, Double_t ptHigh) {
if(TMath::Abs(l_Pa->Eta())>fEta) return 0;
if(ptLow>0) if(l_Pa->Pt()<ptLow) return 0;
if(ptHigh>0) if(l_Pa->Pt()>ptHigh) return 0;
return 1<<BitShift;
};
Int_t AliGFWCuts::AcceptVertex(AliAODEvent *l_Ev, Int_t BitShift) {
Double_t lvtxz = TMath::Abs(l_Ev->GetPrimaryVertex()->GetZ());
if(lvtxz>fVtxZ) return 0;
return 1<<BitShift;
};
void AliGFWCuts::ResetCuts() {
fSystFlag=0;
fFilterBit=96;
fDCAxyCut=7;
fDCAzCut=2;
fTPCNcls=70;
fVtxZ=10;
fEta=0.8;
fRequiresExtraWeight=kTRUE;
};
void AliGFWCuts::PrintSetup() {
printf("**********\n");
printf("Syst. flag: %i\n",fSystFlag);
printf("Eta: %f\n",fEta);
printf("(Flag 1) Filter bit: %i\n",fFilterBit);
printf("(Flag 2,3) DCAxy cut: %2.0f sigma\n",fDCAxyCut);
printf("(Flag 4,5) DCAz cut: %f\n",fDCAzCut);
printf("(Flag 6-8) TPC Ncls: %i\n",fTPCNcls);
printf("(Flag 9) ITS tracks\n");
printf("Rest of the flags are global per event. Total flag = %i + vtx/ev flag\n",fNTrackFlags);
printf("(Flag 1-3) Vertex selection: |z|<%2.1f\n",fVtxZ);
printf("(Flag 4-5) CL1, CL2 multi. estimator (no weights)\n");
printf("(Flag 6) pile-up 15000 (-> 1500) cut\n");
//printf("(Flag 12, disabled) ITS tracks (filter bit %i, TPC Ncls = %i)\n",fFilterBit,fTPCNcls);
printf("**********\n");
};
void AliGFWCuts::SetupTrackCuts(Int_t sysflag) {
switch(sysflag) {
case 1:
fFilterBit=768;
fRequiresExtraWeight=kTRUE;
break;
case 2:
fDCAxyCut=10.;
fRequiresExtraWeight=kTRUE;
break;
case 3:
fDCAxyCut=4.;
fRequiresExtraWeight=kTRUE;
break;
case 4:
fDCAzCut=1;
fRequiresExtraWeight=kTRUE;
break;
case 5:
fDCAzCut=0.5;
fRequiresExtraWeight=kTRUE;
break;
case 6:
fTPCNcls=80;
fRequiresExtraWeight=kTRUE;
break;
case 7:
fTPCNcls=90;
fRequiresExtraWeight=kTRUE;
break;
case 8:
fTPCNcls=100;
fRequiresExtraWeight=kTRUE;
break;
case 9:
fFilterBit=2;
fEta=1.6;
fRequiresExtraWeight=kTRUE;
default:
break;
};
};
void AliGFWCuts::SetupEventCuts(Int_t sysflag) {
switch(sysflag) {
case 1:
fVtxZ = 5;
fRequiresExtraWeight=kTRUE;
break;
case 2:
fVtxZ = 7;
fRequiresExtraWeight=kTRUE;
break;
case 3:
fVtxZ = 9;
fRequiresExtraWeight=kTRUE;
break;
case 4:
printf("Warning! Event flag %i (syst. flag %i), CL1 estmator: make sure the proper estimator is used in the task!\n",sysflag, sysflag+fNTrackFlags);
fRequiresExtraWeight=kFALSE;
break;
case 5:
printf("Warning! Event flag %i (syst. flag %i), CL0 estmator: make sure the proper estimator is used in the task!\n",sysflag, sysflag+fNTrackFlags);
fRequiresExtraWeight=kFALSE;
break;
case 6:
printf("Warning! Event flag %i (syst. flag %i), PU cuts: make sure proper PU cuts are used in the task!\n",sysflag, sysflag+fNTrackFlags);
fRequiresExtraWeight=kTRUE;
break;
case 7:
printf("Warning! Event flag %i (syst. flag %i), magnetic field configuration ++: no cuts here, please make sure the proper runlist is used!\n",sysflag,sysflag+fNTrackFlags);
fRequiresExtraWeight=kFALSE;
break;
case 8:
printf("Warning! Event flag %i (syst. flag %i), magnetic field configuration --: no cuts here, please make sure the proper runlist is used!\n",sysflag,sysflag+fNTrackFlags);
fRequiresExtraWeight=kFALSE;
break;
default:
break;
};
};
void AliGFWCuts::SetupCuts(Int_t sysflag) {
ResetCuts();
fSystFlag=sysflag;
if(sysflag==0 || sysflag>fNTrackFlags+fNEventFlags) return;
if(sysflag<=fNTrackFlags) SetupTrackCuts(sysflag);
else SetupEventCuts(sysflag-fNTrackFlags);
};
TString *AliGFWCuts::GetTrackFlagDescriptor(Int_t sysflag) {
TString *retstr = new TString("");
switch(sysflag) {
case 1:
retstr->Append("Filter bit 768");
break;
case 2:
retstr->Append("DCA_{xy} < 10 (old:8) sigma");
break;
case 3:
retstr->Append("DCA_{xy} < 4 (old:6) sigma");
break;
case 4:
retstr->Append("DCA_{z} < 1 cm");
break;
case 5:
retstr->Append("DCA_{z} < 0.5 cm");
break;
case 6:
retstr->Append("TPC N_{Cls} > 80");
break;
case 7:
retstr->Append("TPC N_{Cls} > 90");
break;
case 8:
retstr->Append("TPC N_{Cls} > 100");
break;
case 9:
retstr->Append("ITS tracklets");
break;
default:
break;
};
return retstr;
};
TString* AliGFWCuts::GetEventFlagDescriptor(Int_t sysflag) {
TString *retstr = new TString("");
switch(sysflag) {
case 1:
retstr->Append("|z_{vtx}| < 5 cm");
break;
case 2:
retstr->Append("|z_{vtx}| < 7 cm");
break;
case 3:
retstr->Append("|z_{vtx}| < 9 cm");
break;
case 4:
retstr->Append("CL1 multi.");
break;
case 5:
retstr->Append("CL0 multi.");
break;
case 6:
retstr->Append("PU cut 1500");
break;
case 7:
retstr->Append("MF ++");
break;
case 8:
retstr->Append("MF --");
break;
default:
break;
};
return retstr;
};
TString *AliGFWCuts::GetFlagDescription(Int_t sysflag) {
if(sysflag>0 && sysflag <= fNTrackFlags + fNEventFlags) {
if(sysflag>fNTrackFlags) return GetEventFlagDescriptor(sysflag-fNTrackFlags);
return GetTrackFlagDescriptor(sysflag);
};
TString *retst = new TString("");
if(sysflag==0) retst->Append("Nominal");
else retst->Append("Unknown_%i",sysflag);
return retst;
};
<|endoftext|> |
<commit_before>#include "ServerException.h"
ServerException::ServerException(int code)
{
}
ServerException::const char* what()const throw()
{
return "ERROR!"
}
<commit_msg>rebuild exception<commit_after><|endoftext|> |
<commit_before>#include <atlconv.h>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include "VoiceroidFactory.h"
#include "Yukari.h"
#include "YukariEx.h"
#define DELIMITERS _T(".B")
using namespace boost::program_options;
// IvV\\
struct Options {
// ǂݏグ VOICEROID(Yukari, YukariEx)
std::string target_voiceroid_str;
// o̓t@CpX
std::wstring output_file;
// ̓t@CpX
std::wstring input_file;
// ̓t@CR[h UTF8 Ƃď
bool is_utf8;
// [h(ĐEۑ܂őҋ@܂)
bool is_sync_mode;
// ǂݏグ(Ƃēnꂽꍇ)
std::wstring echo_text;
// ǂݏグڈ̃TCY
size_t split_size;
} typedef Options;
// t@Ce擾
std::wstring getContents(std::wstring filepath, bool is_utf8);
// f~^ǂ肷
bool is_delimiter(std::wstring str);
// wstring string ɕϊ
std::string wstring2string(const std::wstring &src);
// string wstring ɕϊ
std::wstring string2wstring(const std::string &src);
// UTF8 SJIS ɂĕԂ
std::string utf8toSjis(std::string srcUTF8);
// R}hC
Options parseArgs(int argc, _TCHAR* argv[]);
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_CTYPE, "");
std::ios::sync_with_stdio(true);
// R}hC
Options options = parseArgs(argc, argv);
// w肳ꂽɉ
// R}hCt@Cǂݏグ擾B
std::wstring wcontents;
if (options.input_file.compare(_T("")) == 0) {
// t@Cw肪ȂR}hC擾
wcontents = options.echo_text;
} else {
// t@Cw肪t@Ce擾
wcontents = getContents(options.input_file, options.is_utf8);
}
// ɉĒNgp邩肷
VoiceroidType voiceroidType;
if (options.target_voiceroid_str.compare("Yukari") == 0) {
voiceroidType = VoiceroidType::YUKARI;
}
else if (options.target_voiceroid_str.compare("YukariEx") == 0) {
voiceroidType = VoiceroidType::YUKARI_EX;
}
// VOICEROID 쐬
Voiceroid* voiceroid = VoiceroidFactory::create(voiceroidType);
// w蕶Ȃ悤ɕȂǂݏグ邽߂̏B
std::list<std::wstring> list_string;
boost::split(list_string, wcontents, boost::is_any_of(DELIMITERS));
size_t size = 0;
std::wstringstream ss;
// ǂݏグ邩t@Cɕۑ邩
if (options.output_file.length() == 0) {
BOOST_FOREACH(std::wstring s, list_string) {
// w蕶ꍇA
// ܂łߍł̂ǂݏグB
// A璴Ăꍇ͂߂B
if (size != 0 && size + s.length() > options.split_size) {
// ǂݏグ
voiceroid->echo(wstring2string(ss.str()), options.is_sync_mode);
// ss Zbg
ss.str(_T(""));
ss.clear();
size = 0;
}
// TCY𑝂₵ĕ
size += s.length();
ss << s << _T("B");
}
// Ō̓ǂݏグ
voiceroid->echo(wstring2string(ss.str()), options.is_sync_mode);
} else {
size_t fileno = 0;
BOOST_FOREACH(std::wstring s, list_string) {
// w蕶ꍇA
// ܂łߍł̂ǂݏグB
// A璴Ăꍇ͂߂B
if (size != 0 && size + s.length() > options.split_size) {
// t@Cɕۑ
// t@Cgݗ
_TCHAR drive[_MAX_DRIVE];
_TCHAR dir[_MAX_DIR];
_TCHAR filename[_MAX_FNAME];
_TCHAR ext[_MAX_EXT];
_tsplitpath(options.output_file.c_str(), drive, dir, filename, ext);
std::wstringstream dest;
dest << drive << dir << filename << _T("_") << std::setfill(L'0') << std::setw(3) << std::right << fileno << ext;
voiceroid->save(wstring2string(ss.str()), wstring2string(dest.str()), options.is_sync_mode);
// ss Zbg
ss.str(_T(""));
ss.clear();
size = 0;
fileno++;
}
// TCY𑝂₵ĕ
size += s.length();
ss << s << _T("B");
}
// Ō̕ۑ
// t@Cgݗ
_TCHAR drive[_MAX_DRIVE];
_TCHAR dir[_MAX_DIR];
_TCHAR filename[_MAX_FNAME];
_TCHAR ext[_MAX_EXT];
_tsplitpath(options.output_file.c_str(), drive, dir, filename, ext);
std::wstringstream dest;
dest << drive << dir << filename << _T("_") << std::setfill(L'0') << std::setw(3) << std::right << fileno << ext;
voiceroid->save(wstring2string(ss.str()), wstring2string(dest.str()), options.is_sync_mode);
}
delete voiceroid;
exit(0);
}
Options parseArgs(int argc, _TCHAR* argv[]) {
options_description opt("IvV");
// R}hC`
opt.add_options()
("help,h", "wv\")
("voiceroid", value<std::string>()->default_value("YukariEx"), "ǂݏグ VOICEROID(Yukari, YukariEx)")
("output-file,o", wvalue<std::wstring>(), "o̓t@CpX")
("input-file,i", wvalue<std::wstring>(), "̓t@CpX")
("utf8,u", "̓t@CR[h UTF8 Ƃď")
("sync,s", "[h(ĐEۑ܂őҋ@܂)")
("split-size", value<size_t>()->default_value(20000), "ǂݏグڈ̃TCY");
// R}hC
variables_map argmap;
auto pr = parse_command_line(argc, argv, opt);
store(pr, argmap);
notify(argmap);
// ͌ʎ擾
Options options;
options.target_voiceroid_str = argmap["voiceroid"].as<std::string>();
// o̓t@CpX擾
// (gpĂo[W boost_program_options ł́A
// std::wstring ɑ default_value w肷ƃRpCG[ɂȂ邽߁A
// IvV̗L`FbNƑOŎ)
std::wstring woutput_file;
if (argmap.count("output-file")) {
options.output_file = argmap["output-file"].as<std::wstring>();
} else {
options.output_file = _T("");
}
// ̓t@CpX擾
// (gpĂo[W boost_program_options ł́A
// std::wstring ɑ default_value w肷ƃRpCG[ɂȂ邽߁A
// IvV̗L`FbNƑOŎ)
std::wstring winput_file;
if (argmap.count("input-file")) {
options.input_file = argmap["input-file"].as<std::wstring>();
} else {
options.input_file = _T("");
}
options.is_utf8 = argmap.count("utf8");
options.is_sync_mode = !argmap["sync"].empty();
options.echo_text = _T("");
options.split_size = argmap["split-size"].as<size_t>();
// IvVȊÕR}hC擾
for (auto const& str : collect_unrecognized(pr.options, include_positional)) {
options.echo_text.append(_T(" "));
options.echo_text.append(str);
}
// wv\w肪邩A
// echo_text, input_file Ƃ̏ꍇAwv\ďI
if (argmap.count("help") ||
(options.echo_text.compare(_T("")) == 0
&& options.input_file.compare(_T("")) == 0)) {
_TCHAR drive[_MAX_DRIVE];
_TCHAR dir[_MAX_DIR];
_TCHAR filename[_MAX_FNAME];
_TCHAR ext[_MAX_EXT];
_tsplitpath(argv[0], drive, dir, filename, ext);
wprintf(_T("Usage: %s%s [options] [text]\n"), filename, ext);
std::stringstream helpStream;
helpStream << opt << std::endl;
printf(helpStream.str().c_str());
exit(1);
}
return options;
}
std::string wstring2string(const std::wstring &src) {
char *mbs = new char[src.length() * MB_CUR_MAX + 1];
wcstombs(mbs, src.c_str(), src.length() * MB_CUR_MAX + 1);
std::string dest = mbs;
delete[] mbs;
return dest;
}
std::wstring string2wstring(const std::string &src) {
wchar_t *wcs = new wchar_t[src.length() + 1];
mbstowcs(wcs, src.c_str(), src.length() + 1);
std::wstring dest = wcs;
delete[] wcs;
return dest;
}
std::string utf8toSjis(std::string srcUTF8) {
//Unicode֕ϊ̕
int lenghtUnicode = MultiByteToWideChar(CP_UTF8, 0, srcUTF8.c_str(), srcUTF8.size() + 1, NULL, 0);
//KvȕUnicodẽobt@m
wchar_t* bufUnicode = new wchar_t[lenghtUnicode];
//UTF8Unicode֕ϊ
MultiByteToWideChar(CP_UTF8, 0, srcUTF8.c_str(), srcUTF8.size() + 1, bufUnicode, lenghtUnicode);
//ShiftJIS֕ϊ̕
int lengthSJis = WideCharToMultiByte(CP_THREAD_ACP, 0, bufUnicode, -1, NULL, 0, NULL, NULL);
//KvȕShiftJIS̃obt@m
char* bufShiftJis = new char[lengthSJis];
//UnicodeShiftJIS֕ϊ
WideCharToMultiByte(CP_THREAD_ACP, 0, bufUnicode, lenghtUnicode + 1, bufShiftJis, lengthSJis, NULL, NULL);
std::string strSJis(bufShiftJis);
delete bufUnicode;
delete bufShiftJis;
return strSJis;
}
// t@Ce擾
std::wstring getContents(std::wstring filepath, bool is_utf8) {
std::ifstream ifs (filepath);
// t@CI[v۔
if (ifs.fail())
{
std::cerr << "t@CI[vɎs܂B" << std::endl;
return NULL;
}
// TODO: ꉽĂł[ˁH
std::istreambuf_iterator<char> it(ifs);
std::istreambuf_iterator<char> last;
std::string str (it, last);
// t@CR[hɉĕϊ
if (is_utf8) {
// utf8
str = utf8toSjis(str);
}
return string2wstring(str);
}
bool is_delimiter(std::wstring str) {
for (wchar_t* it = DELIMITERS; *it; ++it) {
size_t index = str.find(*it);
if (index != std::string::npos) {
return TRUE;
}
}
return FALSE;
}
<commit_msg>繰り返し出てくるマジックナンバーを定数化した。<commit_after>#include <atlconv.h>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include "VoiceroidFactory.h"
#include "Yukari.h"
#include "YukariEx.h"
#define INSERT_DELIMITER _T("B")
#define DELIMITERS _T(".B")
#define EMPTY_STR _T("")
using namespace boost::program_options;
// IvV\\
struct Options {
// ǂݏグ VOICEROID(Yukari, YukariEx)
std::string target_voiceroid_str;
// o̓t@CpX
std::wstring output_file;
// ̓t@CpX
std::wstring input_file;
// ̓t@CR[h UTF8 Ƃď
bool is_utf8;
// [h(ĐEۑ܂őҋ@܂)
bool is_sync_mode;
// ǂݏグ(Ƃēnꂽꍇ)
std::wstring echo_text;
// ǂݏグڈ̃TCY
size_t split_size;
} typedef Options;
// t@Ce擾
std::wstring getContents(std::wstring filepath, bool is_utf8);
// f~^ǂ肷
bool is_delimiter(std::wstring str);
// wstring string ɕϊ
std::string wstring2string(const std::wstring &src);
// string wstring ɕϊ
std::wstring string2wstring(const std::string &src);
// UTF8 SJIS ɂĕԂ
std::string utf8toSjis(std::string srcUTF8);
// R}hC
Options parseArgs(int argc, _TCHAR* argv[]);
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_CTYPE, "");
std::ios::sync_with_stdio(true);
// R}hC
Options options = parseArgs(argc, argv);
// w肳ꂽɉ
// R}hCt@Cǂݏグ擾B
std::wstring wcontents;
if (options.input_file.compare(EMPTY_STR) == 0) {
// t@Cw肪ȂR}hC擾
wcontents = options.echo_text;
} else {
// t@Cw肪t@Ce擾
wcontents = getContents(options.input_file, options.is_utf8);
}
// ɉĒNgp邩肷
VoiceroidType voiceroidType;
if (options.target_voiceroid_str.compare("Yukari") == 0) {
voiceroidType = VoiceroidType::YUKARI;
}
else if (options.target_voiceroid_str.compare("YukariEx") == 0) {
voiceroidType = VoiceroidType::YUKARI_EX;
}
// VOICEROID 쐬
Voiceroid* voiceroid = VoiceroidFactory::create(voiceroidType);
// w蕶Ȃ悤ɕȂǂݏグ邽߂̏B
std::list<std::wstring> list_string;
boost::split(list_string, wcontents, boost::is_any_of(DELIMITERS));
size_t size = 0;
std::wstringstream ss;
// ǂݏグ邩t@Cɕۑ邩
if (options.output_file.length() == 0) {
BOOST_FOREACH(std::wstring s, list_string) {
// w蕶ꍇA
// ܂łߍł̂ǂݏグB
// A璴Ăꍇ͂߂B
if (size != 0 && size + s.length() > options.split_size) {
// ǂݏグ
voiceroid->echo(wstring2string(ss.str()), options.is_sync_mode);
// ss Zbg
ss.str(EMPTY_STR);
ss.clear();
size = 0;
}
// TCY𑝂₵ĕ
size += s.length();
ss << s << INSERT_DELIMITER;
}
// Ō̓ǂݏグ
voiceroid->echo(wstring2string(ss.str()), options.is_sync_mode);
} else {
size_t fileno = 0;
BOOST_FOREACH(std::wstring s, list_string) {
// w蕶ꍇA
// ܂łߍł̂ǂݏグB
// A璴Ăꍇ͂߂B
if (size != 0 && size + s.length() > options.split_size) {
// t@Cɕۑ
// t@Cgݗ
_TCHAR drive[_MAX_DRIVE];
_TCHAR dir[_MAX_DIR];
_TCHAR filename[_MAX_FNAME];
_TCHAR ext[_MAX_EXT];
_tsplitpath(options.output_file.c_str(), drive, dir, filename, ext);
std::wstringstream dest;
dest << drive << dir << filename << _T("_") << std::setfill(L'0') << std::setw(3) << std::right << fileno << ext;
voiceroid->save(wstring2string(ss.str()), wstring2string(dest.str()), options.is_sync_mode);
// ss Zbg
ss.str(EMPTY_STR);
ss.clear();
size = 0;
fileno++;
}
// TCY𑝂₵ĕ
size += s.length();
ss << s << INSERT_DELIMITER;
}
// Ō̕ۑ
// t@Cgݗ
_TCHAR drive[_MAX_DRIVE];
_TCHAR dir[_MAX_DIR];
_TCHAR filename[_MAX_FNAME];
_TCHAR ext[_MAX_EXT];
_tsplitpath(options.output_file.c_str(), drive, dir, filename, ext);
std::wstringstream dest;
dest << drive << dir << filename << _T("_") << std::setfill(L'0') << std::setw(3) << std::right << fileno << ext;
voiceroid->save(wstring2string(ss.str()), wstring2string(dest.str()), options.is_sync_mode);
}
delete voiceroid;
exit(0);
}
Options parseArgs(int argc, _TCHAR* argv[]) {
options_description opt("IvV");
// R}hC`
opt.add_options()
("help,h", "wv\")
("voiceroid", value<std::string>()->default_value("YukariEx"), "ǂݏグ VOICEROID(Yukari, YukariEx)")
("output-file,o", wvalue<std::wstring>(), "o̓t@CpX")
("input-file,i", wvalue<std::wstring>(), "̓t@CpX")
("utf8,u", "̓t@CR[h UTF8 Ƃď")
("sync,s", "[h(ĐEۑ܂őҋ@܂)")
("split-size", value<size_t>()->default_value(20000), "ǂݏグڈ̃TCY");
// R}hC
variables_map argmap;
auto pr = parse_command_line(argc, argv, opt);
store(pr, argmap);
notify(argmap);
// ͌ʎ擾
Options options;
options.target_voiceroid_str = argmap["voiceroid"].as<std::string>();
// o̓t@CpX擾
// (gpĂo[W boost_program_options ł́A
// std::wstring ɑ default_value w肷ƃRpCG[ɂȂ邽߁A
// IvV̗L`FbNƑOŎ)
std::wstring woutput_file;
if (argmap.count("output-file")) {
options.output_file = argmap["output-file"].as<std::wstring>();
} else {
options.output_file = EMPTY_STR;
}
// ̓t@CpX擾
// (gpĂo[W boost_program_options ł́A
// std::wstring ɑ default_value w肷ƃRpCG[ɂȂ邽߁A
// IvV̗L`FbNƑOŎ)
std::wstring winput_file;
if (argmap.count("input-file")) {
options.input_file = argmap["input-file"].as<std::wstring>();
} else {
options.input_file = EMPTY_STR;
}
options.is_utf8 = argmap.count("utf8");
options.is_sync_mode = !argmap["sync"].empty();
options.echo_text = EMPTY_STR;
options.split_size = argmap["split-size"].as<size_t>();
// IvVȊÕR}hC擾
for (auto const& str : collect_unrecognized(pr.options, include_positional)) {
options.echo_text.append(_T(" "));
options.echo_text.append(str);
}
// wv\w肪邩A
// echo_text, input_file Ƃ̏ꍇAwv\ďI
if (argmap.count("help") ||
(options.echo_text.compare(EMPTY_STR) == 0
&& options.input_file.compare(EMPTY_STR) == 0)) {
_TCHAR drive[_MAX_DRIVE];
_TCHAR dir[_MAX_DIR];
_TCHAR filename[_MAX_FNAME];
_TCHAR ext[_MAX_EXT];
_tsplitpath(argv[0], drive, dir, filename, ext);
wprintf(_T("Usage: %s%s [options] [text]\n"), filename, ext);
std::stringstream helpStream;
helpStream << opt << std::endl;
printf(helpStream.str().c_str());
exit(1);
}
return options;
}
std::string wstring2string(const std::wstring &src) {
char *mbs = new char[src.length() * MB_CUR_MAX + 1];
wcstombs(mbs, src.c_str(), src.length() * MB_CUR_MAX + 1);
std::string dest = mbs;
delete[] mbs;
return dest;
}
std::wstring string2wstring(const std::string &src) {
wchar_t *wcs = new wchar_t[src.length() + 1];
mbstowcs(wcs, src.c_str(), src.length() + 1);
std::wstring dest = wcs;
delete[] wcs;
return dest;
}
std::string utf8toSjis(std::string srcUTF8) {
//Unicode֕ϊ̕
int lenghtUnicode = MultiByteToWideChar(CP_UTF8, 0, srcUTF8.c_str(), srcUTF8.size() + 1, NULL, 0);
//KvȕUnicodẽobt@m
wchar_t* bufUnicode = new wchar_t[lenghtUnicode];
//UTF8Unicode֕ϊ
MultiByteToWideChar(CP_UTF8, 0, srcUTF8.c_str(), srcUTF8.size() + 1, bufUnicode, lenghtUnicode);
//ShiftJIS֕ϊ̕
int lengthSJis = WideCharToMultiByte(CP_THREAD_ACP, 0, bufUnicode, -1, NULL, 0, NULL, NULL);
//KvȕShiftJIS̃obt@m
char* bufShiftJis = new char[lengthSJis];
//UnicodeShiftJIS֕ϊ
WideCharToMultiByte(CP_THREAD_ACP, 0, bufUnicode, lenghtUnicode + 1, bufShiftJis, lengthSJis, NULL, NULL);
std::string strSJis(bufShiftJis);
delete bufUnicode;
delete bufShiftJis;
return strSJis;
}
// t@Ce擾
std::wstring getContents(std::wstring filepath, bool is_utf8) {
std::ifstream ifs (filepath);
// t@CI[v۔
if (ifs.fail())
{
std::cerr << "t@CI[vɎs܂B" << std::endl;
return NULL;
}
// TODO: ꉽĂł[ˁH
std::istreambuf_iterator<char> it(ifs);
std::istreambuf_iterator<char> last;
std::string str (it, last);
// t@CR[hɉĕϊ
if (is_utf8) {
// utf8
str = utf8toSjis(str);
}
return string2wstring(str);
}
bool is_delimiter(std::wstring str) {
for (wchar_t* it = DELIMITERS; *it; ++it) {
size_t index = str.find(*it);
if (index != std::string::npos) {
return TRUE;
}
}
return FALSE;
}
<|endoftext|> |
<commit_before>#include"core.hpp"
#include<stdexcept>
#include<sstream>
#include<fcntl.h> // for open FLAGS
#include<unistd.h> // for tty checks
#include<cstring> // for memset
#include<unordered_map> // for cash
ics::Core::Core(const std::string& path, speed_t baudrate)
: fd {open(path.c_str(), O_RDWR | O_NOCTTY)},
oldTio {}
{
if (fd < 0)
throw std::runtime_error {"Cannot open deveice"};
try {
if (!isatty(fd))
throw std::invalid_argument {"Not tty device"};
if (tcgetattr(fd, &oldTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
auto newTio = getTermios();
if (cfsetispeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (cfsetospeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (tcsetattr(fd, TCSANOW, &newTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
} catch (...) {
close(fd);
throw;
}
}
ics::Core::~Core() noexcept {
if (fd < 0) return;
tcsetattr(fd, TCSANOW, &oldTio);
close(fd);
}
ics::Core::Core(Core&& rhs) noexcept
: fd {rhs.fd},
oldTio {rhs.oldTio}
{
rhs.fd = -1;
}
ics::Core& ics::Core::operator=(Core&& rhs) noexcept {
fd = rhs.fd;
oldTio = rhs.oldTio;
rhs.fd = -1;
return *this;
}
std::shared_ptr<ics::Core> ics::Core::getCore(const std::string& path, speed_t baudrate) {
static std::unordered_map<std::string, std::weak_ptr<Core>> cache;
auto objPtr = cache[path].lock();
if (!objPtr) {
objPtr = std::make_shared<Core>(path, baudrate);
cache[path] = objPtr;
}
return objPtr;
}
void ics::Core::communicate(const std::vector<uint8_t>& tx, std::vector<uint8_t>& rx) {
write(fd, tx.data(), tx.size()); // send
for (auto& receive : rx) read(fd, &receive, 1); // receive
// check section
auto receive = rx.begin();
for (const auto& send : tx) {
if (send != *receive) {
std::stringstream ss;
ss << "Receive falied:" << receive - rx.begin() << ':' << static_cast<int>(send) << "<->" << static_cast<int>(*receive);
throw std::runtime_error {ss.str()};
}
++receive;
}
if ((tx[0] & 0x7F) != *receive) throw std::runtime_error {"Receive failed: fail make data"};
}
termios ics::Core::getTermios() noexcept {
termios newTio;
std::memset(&newTio, 0, sizeof(newTio));
newTio.c_iflag = 0;
newTio.c_oflag = 0;
newTio.c_cflag = CS8 | CREAD | CLOCAL | PARENB;
newTio.c_lflag = 0;
newTio.c_cc[VMIN] = 1;
newTio.c_cc[VTIME] = 1;
return newTio;
}
<commit_msg>Update error message for readability<commit_after>#include"core.hpp"
#include<stdexcept>
#include<sstream>
#include<fcntl.h> // for open FLAGS
#include<unistd.h> // for tty checks
#include<cstring> // for memset
#include<unordered_map> // for cash
ics::Core::Core(const std::string& path, speed_t baudrate)
: fd {open(path.c_str(), O_RDWR | O_NOCTTY)},
oldTio {}
{
if (fd < 0)
throw std::runtime_error {"Cannot open deveice"};
try {
if (!isatty(fd))
throw std::invalid_argument {"Not tty device"};
if (tcgetattr(fd, &oldTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
auto newTio = getTermios();
if (cfsetispeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (cfsetospeed(&newTio, baudrate) < 0)
throw std::runtime_error {"Cannot set baudrate"};
if (tcsetattr(fd, TCSANOW, &newTio) < 0)
throw std::runtime_error {"Cannot setup tty"};
} catch (...) {
close(fd);
throw;
}
}
ics::Core::~Core() noexcept {
if (fd < 0) return;
tcsetattr(fd, TCSANOW, &oldTio);
close(fd);
}
ics::Core::Core(Core&& rhs) noexcept
: fd {rhs.fd},
oldTio {rhs.oldTio}
{
rhs.fd = -1;
}
ics::Core& ics::Core::operator=(Core&& rhs) noexcept {
fd = rhs.fd;
oldTio = rhs.oldTio;
rhs.fd = -1;
return *this;
}
std::shared_ptr<ics::Core> ics::Core::getCore(const std::string& path, speed_t baudrate) {
static std::unordered_map<std::string, std::weak_ptr<Core>> cache;
auto objPtr = cache[path].lock();
if (!objPtr) {
objPtr = std::make_shared<Core>(path, baudrate);
cache[path] = objPtr;
}
return objPtr;
}
void ics::Core::communicate(const std::vector<uint8_t>& tx, std::vector<uint8_t>& rx) {
write(fd, tx.data(), tx.size()); // send
for (auto& receive : rx) read(fd, &receive, 1); // receive
// check section
auto receive = rx.begin();
for (const auto& send : tx) {
if (send != *receive) {
std::stringstream ss;
ss << "Receive falied(loopback):" << receive - rx.begin() << ':' << static_cast<int>(send) << "<->" << static_cast<int>(*receive);
throw std::runtime_error {ss.str()};
}
++receive;
}
if ((tx[0] & 0x7F) != *receive) throw std::runtime_error {"Receive failed: invalid target data"};
}
termios ics::Core::getTermios() noexcept {
termios newTio;
std::memset(&newTio, 0, sizeof(newTio));
newTio.c_iflag = 0;
newTio.c_oflag = 0;
newTio.c_cflag = CS8 | CREAD | CLOCAL | PARENB;
newTio.c_lflag = 0;
newTio.c_cc[VMIN] = 1;
newTio.c_cc[VTIME] = 1;
return newTio;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "bbudf.h"
#include "curl.h"
#include "logger.h"
namespace curl {
//TODO http://www.openssl.org/docs/crypto/threads.html#DESCRIPTION
__thread CURL* ch=NULL;
__thread long curl_response_code=0;
int curl_global_init_called=0;
size_t readfunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){
unsigned short length,actual_length;
length=size*nmemb;
blobcallback* blob=(blobcallback*) userdata;
int res;
res=blob->blob_get_segment(blob->blob_handle,(ISC_UCHAR*)ptr,length,&actual_length);
logger::syslog(0, "xmlreader::readfunction_blob() len=%d,res=%d,actual_length=%d",length,res,actual_length);
return actual_length;
}
size_t writefunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){
size_t length=size*nmemb;
if(length>0){
blobcallback* outblob=(blobcallback*) userdata;
outblob->blob_put_segment(outblob->blob_handle, (ISC_UCHAR*) ptr, length);
}
return length;
}
}
FBUDF_API void fn_curl_exec(const char* method,const char* url, const char* sslcert, const char* sslcertpassword,const char* cainfo, const char* headers, blobcallback* datablob, const char* cookies, blobcallback* outblob) {
curl::curl_response_code=0;
if (!outblob || !outblob->blob_handle){
return;
}
CURLcode code;
if(!curl::curl_global_init_called) {
code=curl_global_init(CURL_GLOBAL_ALL);
if(code != CURLE_OK){
logger::blobprinf(outblob,"curl_global_init() failed: %s\n",curl_easy_strerror(code));
return;
}
curl::curl_global_init_called=1;
}
CURL* ch;
if(curl::ch==NULL){
curl::ch=curl_easy_init();
if(!curl::ch){
logger::blobprinf(outblob,"curl_easy_init() failed\n");
return;
}
}
ch=curl::ch;
curl_easy_setopt(ch,CURLOPT_NOSIGNAL,1);
if (strcmp(method,"GET")==0){
curl_easy_setopt(ch,CURLOPT_HTTPGET,1);
}else if (strcmp(method,"POST")==0){
curl_easy_setopt(ch,CURLOPT_POST,1);
}else if (strcmp(method,"PUT")==0){
curl_easy_setopt(ch,CURLOPT_PUT,1);
}else if (strcmp(method,"HEAD")==0){
curl_easy_setopt(ch,CURLOPT_NOBODY,1);
}else{
logger::blobprinf(outblob,"unknown method '%s'",method);
return;
}
curl_easy_setopt(ch,CURLOPT_URL,url);
curl_easy_setopt(ch,CURLOPT_SSLCERT,sslcert);
curl_easy_setopt(ch,CURLOPT_SSLCERTPASSWD,sslcertpassword);
curl_easy_setopt(ch,CURLOPT_CAINFO,cainfo);
curl_easy_setopt(ch,CURLOPT_WRITEFUNCTION,curl::writefunction_blob);
curl_easy_setopt(ch,CURLOPT_WRITEDATA,outblob);
struct curl_slist *slist=NULL;
if(headers){
#if defined(WIN32)
#else
char *saveptr;
char *headersdup=strdup(headers);
char *token=strtok_r(headersdup, "\n", &saveptr);
while(token){
slist = curl_slist_append(slist, token);
token=strtok_r(NULL, "\n", &saveptr);
}
free(headersdup);
#endif
}
curl_easy_setopt(ch, CURLOPT_HTTPHEADER, slist);
curl_easy_setopt(ch, CURLOPT_COOKIE, cookies);
if(datablob && datablob->blob_handle){
//logger::syslog(0, "setup readfunction_blob(), data length=%d",datablob->blob_total_length);
curl_easy_setopt(ch,CURLOPT_READFUNCTION,curl::readfunction_blob);
curl_easy_setopt(ch,CURLOPT_READDATA,datablob);
curl_easy_setopt(ch,CURLOPT_POSTFIELDSIZE,datablob->blob_total_length);
}
code=curl_easy_perform(ch);
if(slist){
curl_slist_free_all(slist);
}
if(code != CURLE_OK){
logger::blobprinf(outblob,"curl_easy_perform() failed: %s\n",curl_easy_strerror(code));
return;
}
curl_easy_getinfo(ch, CURLINFO_RESPONSE_CODE, &curl::curl_response_code);
}
FBUDF_API long fn_curl_get_response_code() {
return curl::curl_response_code;
}<commit_msg>specify size of PUT with CURLOPT_INFILESIZE<commit_after>#include "stdafx.h"
#include "bbudf.h"
#include "curl.h"
#include "logger.h"
namespace curl {
//TODO http://www.openssl.org/docs/crypto/threads.html#DESCRIPTION
__thread CURL* ch=NULL;
__thread long curl_response_code=0;
int curl_global_init_called=0;
size_t readfunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){
unsigned short length,actual_length;
length=size*nmemb;
blobcallback* blob=(blobcallback*) userdata;
int res;
res=blob->blob_get_segment(blob->blob_handle,(ISC_UCHAR*)ptr,length,&actual_length);
logger::syslog(0, "xmlreader::readfunction_blob() len=%d,res=%d,actual_length=%d",length,res,actual_length);
return actual_length;
}
size_t writefunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){
size_t length=size*nmemb;
if(length>0){
blobcallback* outblob=(blobcallback*) userdata;
outblob->blob_put_segment(outblob->blob_handle, (ISC_UCHAR*) ptr, length);
}
return length;
}
}
FBUDF_API void fn_curl_exec(const char* method,const char* url, const char* sslcert, const char* sslcertpassword,const char* cainfo, const char* headers, blobcallback* datablob, const char* cookies, blobcallback* outblob) {
curl::curl_response_code=0;
if (!outblob || !outblob->blob_handle){
return;
}
CURLcode code;
if(!curl::curl_global_init_called) {
code=curl_global_init(CURL_GLOBAL_ALL);
if(code != CURLE_OK){
logger::blobprinf(outblob,"curl_global_init() failed: %s\n",curl_easy_strerror(code));
return;
}
curl::curl_global_init_called=1;
}
CURL* ch;
if(curl::ch==NULL){
curl::ch=curl_easy_init();
if(!curl::ch){
logger::blobprinf(outblob,"curl_easy_init() failed\n");
return;
}
}
ch=curl::ch;
curl_easy_setopt(ch,CURLOPT_NOSIGNAL,1);
if (strcmp(method,"GET")==0){
curl_easy_setopt(ch,CURLOPT_HTTPGET,1);
}else if (strcmp(method,"POST")==0){
curl_easy_setopt(ch,CURLOPT_POST,1);
}else if (strcmp(method,"PUT")==0){
curl_easy_setopt(ch,CURLOPT_PUT,1);
}else if (strcmp(method,"HEAD")==0){
curl_easy_setopt(ch,CURLOPT_NOBODY,1);
}else{
logger::blobprinf(outblob,"unknown method '%s'",method);
return;
}
curl_easy_setopt(ch,CURLOPT_URL,url);
curl_easy_setopt(ch,CURLOPT_SSLCERT,sslcert);
curl_easy_setopt(ch,CURLOPT_SSLCERTPASSWD,sslcertpassword);
curl_easy_setopt(ch,CURLOPT_CAINFO,cainfo);
curl_easy_setopt(ch,CURLOPT_WRITEFUNCTION,curl::writefunction_blob);
curl_easy_setopt(ch,CURLOPT_WRITEDATA,outblob);
struct curl_slist *slist=NULL;
if(headers){
#if defined(WIN32)
#else
char *saveptr;
char *headersdup=strdup(headers);
char *token=strtok_r(headersdup, "\n", &saveptr);
while(token){
slist = curl_slist_append(slist, token);
token=strtok_r(NULL, "\n", &saveptr);
}
free(headersdup);
#endif
}
curl_easy_setopt(ch, CURLOPT_HTTPHEADER, slist);
curl_easy_setopt(ch, CURLOPT_COOKIE, cookies);
if(datablob && datablob->blob_handle){
//logger::syslog(0, "setup readfunction_blob(), data length=%d",datablob->blob_total_length);
curl_easy_setopt(ch,CURLOPT_READFUNCTION,curl::readfunction_blob);
curl_easy_setopt(ch,CURLOPT_READDATA,datablob);
if (strcmp(method,"PUT")==0) {
curl_easy_setopt(ch,CURLOPT_INFILESIZE,datablob->blob_total_length);
}else{
curl_easy_setopt(ch,CURLOPT_POSTFIELDSIZE,datablob->blob_total_length);
}
}
code=curl_easy_perform(ch);
if(slist){
curl_slist_free_all(slist);
}
if(code != CURLE_OK){
logger::blobprinf(outblob,"curl_easy_perform() failed: %s\n",curl_easy_strerror(code));
return;
}
curl_easy_getinfo(ch, CURLINFO_RESPONSE_CODE, &curl::curl_response_code);
}
FBUDF_API long fn_curl_get_response_code() {
return curl::curl_response_code;
}<|endoftext|> |
<commit_before>#include "drawdevice.h"
#include <QFile>
DrawDevice::DrawDevice(Engine *eng, QWidget *parent) : QWidget(parent)
{
engine = eng;
setGeometry(parent->geometry());
bgm = 0;
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateEngine()));
timer->start(1000/25);
}
DrawDevice::~DrawDevice()
{
for (std::map<string, QPixmap *>::iterator i = images.begin();
i != images.end(); ++i)
{
delete i->second;
}
images.clear();
if (bgm) delete bgm;
delete timer;
}
void DrawDevice::initialize()
{
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
std::vector<string> images = engine->getImgNames();
for (std::vector<string>::iterator i = images.begin();
i != images.end(); ++i)
loadImage(*i);
}
bool DrawDevice::loadImage(string filename)
{
if (QFile::exists(QString::fromStdString(filename)))
{
images[filename] = new QPixmap(filename.c_str());
return true;
}
else
{
return false;
}
}
void DrawDevice::quit(int status)
{
qApp->exit(status);
}
void DrawDevice::paintEvent(QPaintEvent *)
{
QPainter painter(this);
drawRoom(painter);
}
void DrawDevice::mousePressEvent(QMouseEvent * event)
{
std::pair<float, float> coord = engine->absToRelCoord(event->x(), event->y());
engine->click(coord.first, coord.second);
update();
updateMusic();
}
void DrawDevice::mouseMoveEvent(QMouseEvent *event)
{
if (engine->state() == Engine::GAME)
{
std::pair<float, float> coord = engine->absToRelCoord(event->x(), event->y());
Item *item = engine->getRoomsManager()->currentRoom()->itemAt(coord.first,
coord.second);
Area *area = engine->getRoomsManager()->currentRoom()->areaAt(coord.first,
coord.second);
if (item != 0)
setCursor(Qt::OpenHandCursor);
else if (area != 0)
setCursor(Qt::PointingHandCursor);
else
setCursor(Qt::ArrowCursor);
}
else
setCursor(Qt::ArrowCursor);
}
void DrawDevice::resizeEvent(QResizeEvent *event)
{
engine->getRoomsManager()->setRoomSize(event->size().width(), event->size().height());
}
void DrawDevice::updateEngine()
{
if (engine->update())
repaint();
}
QPixmap optimizedSetOpacity(QPixmap img, int opacity)
{
QPixmap temp(img.size());
temp.fill(Qt::transparent);
QPainter p(&temp);
p.setCompositionMode(QPainter::CompositionMode_Source);
p.drawPixmap(0, 0, img);
QLinearGradient alpha_gradient(0, 0, img.width(), 0);
alpha_gradient.setColorAt(0, QColor(255, 255, 255, opacity));
alpha_gradient.setColorAt(1, QColor(255, 255, 255, opacity));
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
p.setBrush(alpha_gradient);
p.drawRect(0, 0, temp.width(), temp.height());
p.end();
return temp;
}
void DrawDevice::drawImage(QPainter &painter, string name, GuiRect rect, int opacity)
{
QPixmap img = *images[name];
QRect r(rect.x, rect.y, rect.w, rect.h);
painter.drawPixmap(r, optimizedSetOpacity(img, opacity));
}
void DrawDevice::drawText(QPainter &painter, string text, GuiRect rect)
{
int x = rect.x;
int y = rect.y + rect.h / 2;
painter.drawText(x, y, QString::fromUtf8(text.c_str()));
}
void DrawDevice::drawRoom(QPainter &painter)
{
GuiDataVect dv = engine->getVisibleData();
for (GuiDataVect::iterator i = dv.begin(); i != dv.end(); ++i)
{
GuiData data = (*i);
engine->relToAbsRect(data.rect);
if (data.image != "")
drawImage(painter, data.image, data.rect, data.alpha);
if (data.text != "")
drawText(painter, data.text, data.rect);
}
}
void DrawDevice::updateMusic()
{
// Background Music
if (!QSound::isAvailable()) return;
QString bgm_to_play(engine->getRoomsManager()->currentRoom()->bgm().c_str());
if (bgm_to_play != "" && bgm_to_play != last_bgm)
{
if (bgm) delete bgm;
bgm = new QSound(bgm_to_play);
last_bgm = bgm_to_play;
}
if (bgm_to_play == "" && bgm) delete bgm;
// SFX
std::vector<string> sfx = engine->getSFX();
for (std::vector<string>::iterator i = sfx.begin(); i != sfx.end(); ++i)
QSound::play((*i).c_str());
}
<commit_msg>removed QSound::isAvailable() fixes #10<commit_after>#include "drawdevice.h"
#include <QFile>
DrawDevice::DrawDevice(Engine *eng, QWidget *parent) : QWidget(parent)
{
engine = eng;
setGeometry(parent->geometry());
bgm = 0;
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateEngine()));
timer->start(1000/25);
}
DrawDevice::~DrawDevice()
{
for (std::map<string, QPixmap *>::iterator i = images.begin();
i != images.end(); ++i)
{
delete i->second;
}
images.clear();
if (bgm) delete bgm;
delete timer;
}
void DrawDevice::initialize()
{
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
std::vector<string> images = engine->getImgNames();
for (std::vector<string>::iterator i = images.begin();
i != images.end(); ++i)
loadImage(*i);
}
bool DrawDevice::loadImage(string filename)
{
if (QFile::exists(QString::fromStdString(filename)))
{
images[filename] = new QPixmap(filename.c_str());
return true;
}
else
{
return false;
}
}
void DrawDevice::quit(int status)
{
qApp->exit(status);
}
void DrawDevice::paintEvent(QPaintEvent *)
{
QPainter painter(this);
drawRoom(painter);
}
void DrawDevice::mousePressEvent(QMouseEvent * event)
{
std::pair<float, float> coord = engine->absToRelCoord(event->x(), event->y());
engine->click(coord.first, coord.second);
update();
updateMusic();
}
void DrawDevice::mouseMoveEvent(QMouseEvent *event)
{
if (engine->state() == Engine::GAME)
{
std::pair<float, float> coord = engine->absToRelCoord(event->x(), event->y());
Item *item = engine->getRoomsManager()->currentRoom()->itemAt(coord.first,
coord.second);
Area *area = engine->getRoomsManager()->currentRoom()->areaAt(coord.first,
coord.second);
if (item != 0)
setCursor(Qt::OpenHandCursor);
else if (area != 0)
setCursor(Qt::PointingHandCursor);
else
setCursor(Qt::ArrowCursor);
}
else
setCursor(Qt::ArrowCursor);
}
void DrawDevice::resizeEvent(QResizeEvent *event)
{
engine->getRoomsManager()->setRoomSize(event->size().width(), event->size().height());
}
void DrawDevice::updateEngine()
{
if (engine->update())
repaint();
}
QPixmap optimizedSetOpacity(QPixmap img, int opacity)
{
QPixmap temp(img.size());
temp.fill(Qt::transparent);
QPainter p(&temp);
p.setCompositionMode(QPainter::CompositionMode_Source);
p.drawPixmap(0, 0, img);
QLinearGradient alpha_gradient(0, 0, img.width(), 0);
alpha_gradient.setColorAt(0, QColor(255, 255, 255, opacity));
alpha_gradient.setColorAt(1, QColor(255, 255, 255, opacity));
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
p.setBrush(alpha_gradient);
p.drawRect(0, 0, temp.width(), temp.height());
p.end();
return temp;
}
void DrawDevice::drawImage(QPainter &painter, string name, GuiRect rect, int opacity)
{
QPixmap img = *images[name];
QRect r(rect.x, rect.y, rect.w, rect.h);
painter.drawPixmap(r, optimizedSetOpacity(img, opacity));
}
void DrawDevice::drawText(QPainter &painter, string text, GuiRect rect)
{
int x = rect.x;
int y = rect.y + rect.h / 2;
painter.drawText(x, y, QString::fromUtf8(text.c_str()));
}
void DrawDevice::drawRoom(QPainter &painter)
{
GuiDataVect dv = engine->getVisibleData();
for (GuiDataVect::iterator i = dv.begin(); i != dv.end(); ++i)
{
GuiData data = (*i);
engine->relToAbsRect(data.rect);
if (data.image != "")
drawImage(painter, data.image, data.rect, data.alpha);
if (data.text != "")
drawText(painter, data.text, data.rect);
}
}
void DrawDevice::updateMusic()
{
// Background Music
QString bgm_to_play(engine->getRoomsManager()->currentRoom()->bgm().c_str());
if (bgm_to_play != "" && bgm_to_play != last_bgm)
{
if (bgm) delete bgm;
bgm = new QSound(bgm_to_play);
last_bgm = bgm_to_play;
}
if (bgm_to_play == "" && bgm) delete bgm;
// SFX
std::vector<string> sfx = engine->getSFX();
for (std::vector<string>::iterator i = sfx.begin(); i != sfx.end(); ++i)
QSound::play((*i).c_str());
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 <cstring>
#include <inttypes.h>
#include "Allocator.h"
#include "Filesystem.h"
#include "StringUtils.h"
#include "JSONParser.h"
#include "SpriteResource.h"
#include "StringUtils.h"
#include "Array.h"
#include "Config.h"
#include "ReaderWriter.h"
#include <cfloat>
namespace crown
{
namespace sprite_resource
{
struct SpriteFrame
{
StringId32 name;
Vector4 region; // [x0, y0, x1, y1]
Vector2 scale; // [Sx, Sy]
Vector2 offset; // [Ox, Oy]
};
//-----------------------------------------------------------------------------
void parse_frame(JSONElement e, SpriteFrame& frame)
{
frame.name = e.key("name" ).to_string_id();
frame.region = e.key("region").to_vector4();
frame.offset = e.key("offset").to_vector2();
frame.scale = e.key("scale" ).to_vector2();
}
//-----------------------------------------------------------------------------
void parse_animation(JSONElement e, SpriteAnimation& anim)
{
anim.name = e.key("name").to_string_id();
anim.time = e.key("time").to_float();
anim.num_frames = 0;
anim.start_frame = 0;
}
//-----------------------------------------------------------------------------
void compile(Filesystem& fs, const char* resource_path, File* out_file)
{
File* file = fs.open(resource_path, FOM_READ);
JSONParser json(*file);
fs.close(file);
JSONElement root = json.root();
// Read width/height
const float width = root.key("width" ).to_float();
const float height = root.key("height").to_float();
const uint32_t num_frames = root.key("frames").size();
const uint32_t num_animations = root.key("animations").size();
BinaryWriter bw(*out_file);
Array<float> vertices(default_allocator());
Array<uint16_t> indices(default_allocator());
uint32_t num_idx = 0;
for (uint32_t i = 0; i < num_frames; i++)
{
JSONElement e(root.key("frames")[i]);
SpriteFrame frame;
parse_frame(e, frame);
const SpriteFrame& fd = frame;
// Compute uv coords
const float u0 = fd.region.x / width;
const float v0 = fd.region.y / height;
const float u1 = (fd.region.x + fd.region.z) / width;
const float v1 = (fd.region.y + fd.region.w) / height;
// Compute positions
const float w = fd.region.z / CE_PIXELS_PER_METER;
const float h = fd.region.w / CE_PIXELS_PER_METER;
const float x0 = fd.scale.x * (-w * 0.5) + fd.offset.x;
const float y0 = fd.scale.y * (-h * 0.5) + fd.offset.y;
const float x1 = fd.scale.x * ( w * 0.5) + fd.offset.x;
const float y1 = fd.scale.y * ( h * 0.5) + fd.offset.y;
array::push_back(vertices, x0); array::push_back(vertices, y0); // position
array::push_back(vertices, u0); array::push_back(vertices, v0); // uv
array::push_back(vertices, x1); array::push_back(vertices, y0); // position
array::push_back(vertices, u1); array::push_back(vertices, v0); // uv
array::push_back(vertices, x1); array::push_back(vertices, y1); // position
array::push_back(vertices, u1); array::push_back(vertices, v1); // uv
array::push_back(vertices, x0); array::push_back(vertices, y1); // position
array::push_back(vertices, u0); array::push_back(vertices, v1); // uv
array::push_back(indices, uint16_t(num_idx)); array::push_back(indices, uint16_t(num_idx + 1)); array::push_back(indices, uint16_t(num_idx + 2));
array::push_back(indices, uint16_t(num_idx)); array::push_back(indices, uint16_t(num_idx + 2)); array::push_back(indices, uint16_t(num_idx + 3));
num_idx += 4;
}
const uint32_t num_vertices = array::size(vertices) / 4; // 4 components per vertex
const uint32_t num_indices = array::size(indices);
// Write animations
Array<SpriteAnimation> animations(default_allocator());
Array<uint32_t> frames(default_allocator());
for (uint32_t i = 0; i < num_animations; i++)
{
JSONElement e(root.key("animations")[i]);
SpriteAnimation anim;
parse_animation(e, anim);
// Read frames
const uint32_t num_frames = e.key("frames").size();
anim.num_frames = num_frames;
anim.start_frame = array::size(frames); // Relative offset
for (uint32_t ff = 0; ff < num_frames; ff++)
array::push_back(frames, (uint32_t) e.key("frames")[ff].to_int());
array::push_back(animations, anim);
}
// Write header
bw.write(uint32_t(0)); // vb
bw.write(uint32_t(0)); // ib
bw.write(num_animations); uint32_t offt = sizeof(SpriteHeader);
bw.write(offt);
bw.write(num_vertices); offt += sizeof(SpriteAnimation) * array::size(animations) + sizeof(uint32_t) * array::size(frames);
bw.write(offt);
bw.write(num_indices); offt += sizeof(float) * array::size(vertices);
bw.write(offt);
if (array::size(animations))
bw.write(array::begin(animations), sizeof(SpriteAnimation) * array::size(animations));
if (array::size(frames))
bw.write(array::begin(frames), sizeof(uint32_t) * array::size(frames));
if (array::size(vertices))
bw.write(array::begin(vertices), sizeof(float) * array::size(vertices));
if (array::size(indices))
bw.write(array::begin(indices), sizeof(uint16_t) * array::size(indices));
}
} // namespace sprite_resource
} // namespace crown
<commit_msg>Add missing headers<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 <cstring>
#include <inttypes.h>
#include "Allocator.h"
#include "Filesystem.h"
#include "StringUtils.h"
#include "JSONParser.h"
#include "SpriteResource.h"
#include "StringUtils.h"
#include "Array.h"
#include "Config.h"
#include "ReaderWriter.h"
#include "Vector3.h"
#include "Vector4.h"
#include <cfloat>
namespace crown
{
namespace sprite_resource
{
struct SpriteFrame
{
StringId32 name;
Vector4 region; // [x0, y0, x1, y1]
Vector2 scale; // [Sx, Sy]
Vector2 offset; // [Ox, Oy]
};
//-----------------------------------------------------------------------------
void parse_frame(JSONElement e, SpriteFrame& frame)
{
frame.name = e.key("name" ).to_string_id();
frame.region = e.key("region").to_vector4();
frame.offset = e.key("offset").to_vector2();
frame.scale = e.key("scale" ).to_vector2();
}
//-----------------------------------------------------------------------------
void parse_animation(JSONElement e, SpriteAnimation& anim)
{
anim.name = e.key("name").to_string_id();
anim.time = e.key("time").to_float();
anim.num_frames = 0;
anim.start_frame = 0;
}
//-----------------------------------------------------------------------------
void compile(Filesystem& fs, const char* resource_path, File* out_file)
{
File* file = fs.open(resource_path, FOM_READ);
JSONParser json(*file);
fs.close(file);
JSONElement root = json.root();
// Read width/height
const float width = root.key("width" ).to_float();
const float height = root.key("height").to_float();
const uint32_t num_frames = root.key("frames").size();
const uint32_t num_animations = root.key("animations").size();
BinaryWriter bw(*out_file);
Array<float> vertices(default_allocator());
Array<uint16_t> indices(default_allocator());
uint32_t num_idx = 0;
for (uint32_t i = 0; i < num_frames; i++)
{
JSONElement e(root.key("frames")[i]);
SpriteFrame frame;
parse_frame(e, frame);
const SpriteFrame& fd = frame;
// Compute uv coords
const float u0 = fd.region.x / width;
const float v0 = fd.region.y / height;
const float u1 = (fd.region.x + fd.region.z) / width;
const float v1 = (fd.region.y + fd.region.w) / height;
// Compute positions
const float w = fd.region.z / CE_PIXELS_PER_METER;
const float h = fd.region.w / CE_PIXELS_PER_METER;
const float x0 = fd.scale.x * (-w * 0.5) + fd.offset.x;
const float y0 = fd.scale.y * (-h * 0.5) + fd.offset.y;
const float x1 = fd.scale.x * ( w * 0.5) + fd.offset.x;
const float y1 = fd.scale.y * ( h * 0.5) + fd.offset.y;
array::push_back(vertices, x0); array::push_back(vertices, y0); // position
array::push_back(vertices, u0); array::push_back(vertices, v0); // uv
array::push_back(vertices, x1); array::push_back(vertices, y0); // position
array::push_back(vertices, u1); array::push_back(vertices, v0); // uv
array::push_back(vertices, x1); array::push_back(vertices, y1); // position
array::push_back(vertices, u1); array::push_back(vertices, v1); // uv
array::push_back(vertices, x0); array::push_back(vertices, y1); // position
array::push_back(vertices, u0); array::push_back(vertices, v1); // uv
array::push_back(indices, uint16_t(num_idx)); array::push_back(indices, uint16_t(num_idx + 1)); array::push_back(indices, uint16_t(num_idx + 2));
array::push_back(indices, uint16_t(num_idx)); array::push_back(indices, uint16_t(num_idx + 2)); array::push_back(indices, uint16_t(num_idx + 3));
num_idx += 4;
}
const uint32_t num_vertices = array::size(vertices) / 4; // 4 components per vertex
const uint32_t num_indices = array::size(indices);
// Write animations
Array<SpriteAnimation> animations(default_allocator());
Array<uint32_t> frames(default_allocator());
for (uint32_t i = 0; i < num_animations; i++)
{
JSONElement e(root.key("animations")[i]);
SpriteAnimation anim;
parse_animation(e, anim);
// Read frames
const uint32_t num_frames = e.key("frames").size();
anim.num_frames = num_frames;
anim.start_frame = array::size(frames); // Relative offset
for (uint32_t ff = 0; ff < num_frames; ff++)
array::push_back(frames, (uint32_t) e.key("frames")[ff].to_int());
array::push_back(animations, anim);
}
// Write header
bw.write(uint32_t(0)); // vb
bw.write(uint32_t(0)); // ib
bw.write(num_animations); uint32_t offt = sizeof(SpriteHeader);
bw.write(offt);
bw.write(num_vertices); offt += sizeof(SpriteAnimation) * array::size(animations) + sizeof(uint32_t) * array::size(frames);
bw.write(offt);
bw.write(num_indices); offt += sizeof(float) * array::size(vertices);
bw.write(offt);
if (array::size(animations))
bw.write(array::begin(animations), sizeof(SpriteAnimation) * array::size(animations));
if (array::size(frames))
bw.write(array::begin(frames), sizeof(uint32_t) * array::size(frames));
if (array::size(vertices))
bw.write(array::begin(vertices), sizeof(float) * array::size(vertices));
if (array::size(indices))
bw.write(array::begin(indices), sizeof(uint16_t) * array::size(indices));
}
} // namespace sprite_resource
} // namespace crown
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "chrome/browser/autofill/autofill_ie_toolbar_import_win.h"
#include "base/basictypes.h"
#include "base/string16.h"
#include "base/win/registry.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/credit_card.h"
#include "chrome/browser/autofill/crypto/rc4_decryptor.h"
#include "chrome/browser/autofill/field_types.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/sync/util/data_encryption.h"
using base::win::RegKey;
// Forward declaration. This function is not in unnamed namespace as it
// is referenced in the unittest.
bool ImportCurrentUserProfiles(std::vector<AutoFillProfile>* profiles,
std::vector<CreditCard>* credit_cards);
namespace {
const wchar_t* const kProfileKey =
L"Software\\Google\\Google Toolbar\\4.0\\Autofill\\Profiles";
const wchar_t* const kCreditCardKey =
L"Software\\Google\\Google Toolbar\\4.0\\Autofill\\Credit Cards";
const wchar_t* const kPasswordHashValue = L"password_hash";
const wchar_t* const kSaltValue = L"salt";
// This is RC4 decryption for Toolbar credit card data. This is necessary
// because it is not standard, so Crypto api cannot be used.
std::wstring DecryptCCNumber(const std::wstring& data) {
const wchar_t* kEmptyKey =
L"\x3605\xCEE5\xCE49\x44F7\xCF4E\xF6CC\x604B\xFCBE\xC70A\x08FD";
const size_t kMacLen = 10;
if (data.length() <= kMacLen)
return std::wstring();
RC4Decryptor rc4_algorithm(kEmptyKey);
return rc4_algorithm.Run(data.substr(kMacLen));
}
bool IsEmptySalt(std::wstring const& salt) {
// Empty salt in IE Toolbar is \x1\x2...\x14
if (salt.length() != 20)
return false;
for (size_t i = 0; i < salt.length(); ++i) {
if (salt[i] != i + 1)
return false;
}
return true;
}
string16 ReadAndDecryptValue(RegKey* key, const wchar_t* value_name) {
DWORD data_type = REG_BINARY;
DWORD data_size = 0;
if (!key->ReadValue(value_name, NULL, &data_size, &data_type) ||
!data_size || data_type != REG_BINARY)
return string16();
std::vector<uint8> data;
data.resize(data_size);
if (key->ReadValue(value_name, &(data[0]), &data_size, &data_type)) {
std::string out_data;
if (DecryptData(data, &out_data)) {
// The actual data is in UTF16 already.
if (!(out_data.size() & 1) && (out_data.size() > 2) &&
!out_data[out_data.size() - 1] && !out_data[out_data.size() - 2]) {
return string16(
reinterpret_cast<const wchar_t *>(out_data.c_str()));
}
}
}
return string16();
}
struct {
AutoFillFieldType field_type;
const wchar_t *reg_value_name;
} profile_reg_values[] = {
{ NAME_FIRST, L"name_first" },
{ NAME_MIDDLE, L"name_middle" },
{ NAME_LAST, L"name_last" },
{ NAME_SUFFIX, L"name_suffix" },
{ EMAIL_ADDRESS, L"email" },
{ COMPANY_NAME, L"company_name" },
{ PHONE_HOME_NUMBER, L"phone_home_number" },
{ PHONE_HOME_CITY_CODE, L"phone_home_city_code" },
{ PHONE_HOME_COUNTRY_CODE, L"phone_home_country_code" },
{ PHONE_FAX_NUMBER, L"phone_fax_number" },
{ PHONE_FAX_CITY_CODE, L"phone_fax_city_code" },
{ PHONE_FAX_COUNTRY_CODE, L"phone_fax_country_code" },
{ ADDRESS_HOME_LINE1, L"address_home_line1" },
{ ADDRESS_HOME_LINE2, L"address_home_line2" },
{ ADDRESS_HOME_CITY, L"address_home_city" },
{ ADDRESS_HOME_STATE, L"address_home_state" },
{ ADDRESS_HOME_ZIP, L"address_home_zip" },
{ ADDRESS_HOME_COUNTRY, L"address_home_country" },
{ ADDRESS_BILLING_LINE1, L"address_billing_line1" },
{ ADDRESS_BILLING_LINE2, L"address_billing_line2" },
{ ADDRESS_BILLING_CITY, L"address_billing_city" },
{ ADDRESS_BILLING_STATE, L"address_billing_state" },
{ ADDRESS_BILLING_ZIP, L"address_billing_zip" },
{ ADDRESS_BILLING_COUNTRY, L"address_billing_country" },
{ CREDIT_CARD_NAME, L"credit_card_name" },
{ CREDIT_CARD_NUMBER, L"credit_card_number" },
{ CREDIT_CARD_EXP_MONTH, L"credit_card_exp_month" },
{ CREDIT_CARD_EXP_4_DIGIT_YEAR, L"credit_card_exp_4_digit_year" },
{ CREDIT_CARD_TYPE, L"credit_card_type" },
// We do not import verification code.
};
typedef std::map<std::wstring, AutoFillFieldType> RegToFieldMap;
bool ImportSingleProfile(FormGroup* profile,
RegKey* key,
const RegToFieldMap& reg_to_field ) {
DCHECK(profile != NULL);
if (!key->Valid())
return false;
bool has_non_empty_fields = false;
for (uint32 value_index = 0; value_index < key->ValueCount(); ++value_index) {
std::wstring value_name;
if (!key->ReadName(value_index, &value_name))
continue;
RegToFieldMap::const_iterator it = reg_to_field.find(value_name);
if (it == reg_to_field.end())
continue; // This field is not imported.
string16 field_value = ReadAndDecryptValue(key, value_name.c_str());
if (!field_value.empty()) {
has_non_empty_fields = true;
if (it->second == CREDIT_CARD_NUMBER) {
field_value = DecryptCCNumber(field_value);
}
profile->SetInfo(AutoFillType(it->second), field_value);
}
}
return has_non_empty_fields;
}
// Imports profiles from the IE toolbar and stores them. Asynchronous
// if PersonalDataManager has not been loaded yet. Deletes itself on completion.
class AutoFillImporter : public PersonalDataManager::Observer {
public:
explicit AutoFillImporter(PersonalDataManager* personal_data_manager)
: personal_data_manager_(personal_data_manager) {
personal_data_manager_->SetObserver(this);
}
bool ImportProfiles() {
if (!ImportCurrentUserProfiles(&profiles_, &credit_cards_)) {
delete this;
return false;
}
if (personal_data_manager_->IsDataLoaded())
OnPersonalDataLoaded();
return true;
}
// PersonalDataManager::Observer methods:
virtual void OnPersonalDataLoaded() {
if (!profiles_.empty())
personal_data_manager_->SetProfiles(&profiles_);
if (!credit_cards_.empty())
personal_data_manager_->SetCreditCards(&credit_cards_);
delete this;
}
private:
~AutoFillImporter() {
personal_data_manager_->RemoveObserver(this);
}
PersonalDataManager* personal_data_manager_;
std::vector<AutoFillProfile> profiles_;
std::vector<CreditCard> credit_cards_;
};
} // namespace
// Imports AutoFill profiles and credit cards from IE Toolbar if present and not
// password protected. Returns true if data is successfully retrieved. False if
// there is no data, data is password protected or error occurred.
bool ImportCurrentUserProfiles(std::vector<AutoFillProfile>* profiles,
std::vector<CreditCard>* credit_cards) {
DCHECK(profiles);
DCHECK(credit_cards);
// Create a map of possible fields for a quick access.
RegToFieldMap reg_to_field;
for (size_t i = 0; i < arraysize(profile_reg_values); ++i) {
reg_to_field[std::wstring(profile_reg_values[i].reg_value_name)] =
profile_reg_values[i].field_type;
}
base::win::RegistryKeyIterator iterator_profiles(HKEY_CURRENT_USER,
kProfileKey);
for (; iterator_profiles.Valid(); ++iterator_profiles) {
std::wstring key_name(kProfileKey);
key_name.append(L"\\");
key_name.append(iterator_profiles.Name());
RegKey key(HKEY_CURRENT_USER, key_name.c_str(), KEY_READ);
AutoFillProfile profile;
if (ImportSingleProfile(&profile, &key, reg_to_field)) {
// Combine phones into whole phone #.
string16 phone;
phone = profile.GetFieldText(AutoFillType(PHONE_HOME_COUNTRY_CODE));
phone.append(profile.GetFieldText(AutoFillType(PHONE_HOME_CITY_CODE)));
phone.append(profile.GetFieldText(AutoFillType(PHONE_HOME_NUMBER)));
profile.SetInfo(AutoFillType(PHONE_HOME_WHOLE_NUMBER), phone);
phone = profile.GetFieldText(AutoFillType(PHONE_FAX_COUNTRY_CODE));
phone.append(profile.GetFieldText(AutoFillType(PHONE_FAX_CITY_CODE)));
phone.append(profile.GetFieldText(AutoFillType(PHONE_FAX_NUMBER)));
profile.SetInfo(AutoFillType(PHONE_FAX_WHOLE_NUMBER), phone);
profiles->push_back(profile);
}
}
string16 password_hash;
string16 salt;
RegKey cc_key(HKEY_CURRENT_USER, kCreditCardKey, KEY_READ);
if (cc_key.Valid()) {
password_hash = ReadAndDecryptValue(&cc_key, kPasswordHashValue);
salt = ReadAndDecryptValue(&cc_key, kSaltValue);
}
// We import CC profiles only if they are not password protected.
if (password_hash.empty() && IsEmptySalt(salt)) {
base::win::RegistryKeyIterator iterator_cc(HKEY_CURRENT_USER,
kCreditCardKey);
for (; iterator_cc.Valid(); ++iterator_cc) {
std::wstring key_name(kCreditCardKey);
key_name.append(L"\\");
key_name.append(iterator_cc.Name());
RegKey key(HKEY_CURRENT_USER, key_name.c_str(), KEY_READ);
CreditCard credit_card;
if (ImportSingleProfile(&credit_card, &key, reg_to_field)) {
string16 cc_number = credit_card.GetFieldText(
AutoFillType(CREDIT_CARD_NUMBER));
if (!cc_number.empty())
credit_cards->push_back(credit_card);
}
}
}
return (profiles->size() + credit_cards->size()) > 0;
}
bool ImportAutofillDataWin(PersonalDataManager* pdm) {
AutoFillImporter *importer = new AutoFillImporter(pdm);
// importer will self delete.
return importer->ImportProfiles();
}
<commit_msg>Fix for bug 68588" crash occurs if the first run when mode is incognito BUG=68588 TEST=Should not crash in described circumstances Review URL: http://codereview.chromium.org/6134002<commit_after>// Copyright (c) 2010 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 "chrome/browser/autofill/autofill_ie_toolbar_import_win.h"
#include "base/basictypes.h"
#include "base/string16.h"
#include "base/win/registry.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/credit_card.h"
#include "chrome/browser/autofill/crypto/rc4_decryptor.h"
#include "chrome/browser/autofill/field_types.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/sync/util/data_encryption.h"
using base::win::RegKey;
// Forward declaration. This function is not in unnamed namespace as it
// is referenced in the unittest.
bool ImportCurrentUserProfiles(std::vector<AutoFillProfile>* profiles,
std::vector<CreditCard>* credit_cards);
namespace {
const wchar_t* const kProfileKey =
L"Software\\Google\\Google Toolbar\\4.0\\Autofill\\Profiles";
const wchar_t* const kCreditCardKey =
L"Software\\Google\\Google Toolbar\\4.0\\Autofill\\Credit Cards";
const wchar_t* const kPasswordHashValue = L"password_hash";
const wchar_t* const kSaltValue = L"salt";
// This is RC4 decryption for Toolbar credit card data. This is necessary
// because it is not standard, so Crypto api cannot be used.
std::wstring DecryptCCNumber(const std::wstring& data) {
const wchar_t* kEmptyKey =
L"\x3605\xCEE5\xCE49\x44F7\xCF4E\xF6CC\x604B\xFCBE\xC70A\x08FD";
const size_t kMacLen = 10;
if (data.length() <= kMacLen)
return std::wstring();
RC4Decryptor rc4_algorithm(kEmptyKey);
return rc4_algorithm.Run(data.substr(kMacLen));
}
bool IsEmptySalt(std::wstring const& salt) {
// Empty salt in IE Toolbar is \x1\x2...\x14
if (salt.length() != 20)
return false;
for (size_t i = 0; i < salt.length(); ++i) {
if (salt[i] != i + 1)
return false;
}
return true;
}
string16 ReadAndDecryptValue(RegKey* key, const wchar_t* value_name) {
DWORD data_type = REG_BINARY;
DWORD data_size = 0;
if (!key->ReadValue(value_name, NULL, &data_size, &data_type) ||
!data_size || data_type != REG_BINARY)
return string16();
std::vector<uint8> data;
data.resize(data_size);
if (key->ReadValue(value_name, &(data[0]), &data_size, &data_type)) {
std::string out_data;
if (DecryptData(data, &out_data)) {
// The actual data is in UTF16 already.
if (!(out_data.size() & 1) && (out_data.size() > 2) &&
!out_data[out_data.size() - 1] && !out_data[out_data.size() - 2]) {
return string16(
reinterpret_cast<const wchar_t *>(out_data.c_str()));
}
}
}
return string16();
}
struct {
AutoFillFieldType field_type;
const wchar_t *reg_value_name;
} profile_reg_values[] = {
{ NAME_FIRST, L"name_first" },
{ NAME_MIDDLE, L"name_middle" },
{ NAME_LAST, L"name_last" },
{ NAME_SUFFIX, L"name_suffix" },
{ EMAIL_ADDRESS, L"email" },
{ COMPANY_NAME, L"company_name" },
{ PHONE_HOME_NUMBER, L"phone_home_number" },
{ PHONE_HOME_CITY_CODE, L"phone_home_city_code" },
{ PHONE_HOME_COUNTRY_CODE, L"phone_home_country_code" },
{ PHONE_FAX_NUMBER, L"phone_fax_number" },
{ PHONE_FAX_CITY_CODE, L"phone_fax_city_code" },
{ PHONE_FAX_COUNTRY_CODE, L"phone_fax_country_code" },
{ ADDRESS_HOME_LINE1, L"address_home_line1" },
{ ADDRESS_HOME_LINE2, L"address_home_line2" },
{ ADDRESS_HOME_CITY, L"address_home_city" },
{ ADDRESS_HOME_STATE, L"address_home_state" },
{ ADDRESS_HOME_ZIP, L"address_home_zip" },
{ ADDRESS_HOME_COUNTRY, L"address_home_country" },
{ ADDRESS_BILLING_LINE1, L"address_billing_line1" },
{ ADDRESS_BILLING_LINE2, L"address_billing_line2" },
{ ADDRESS_BILLING_CITY, L"address_billing_city" },
{ ADDRESS_BILLING_STATE, L"address_billing_state" },
{ ADDRESS_BILLING_ZIP, L"address_billing_zip" },
{ ADDRESS_BILLING_COUNTRY, L"address_billing_country" },
{ CREDIT_CARD_NAME, L"credit_card_name" },
{ CREDIT_CARD_NUMBER, L"credit_card_number" },
{ CREDIT_CARD_EXP_MONTH, L"credit_card_exp_month" },
{ CREDIT_CARD_EXP_4_DIGIT_YEAR, L"credit_card_exp_4_digit_year" },
{ CREDIT_CARD_TYPE, L"credit_card_type" },
// We do not import verification code.
};
typedef std::map<std::wstring, AutoFillFieldType> RegToFieldMap;
bool ImportSingleProfile(FormGroup* profile,
RegKey* key,
const RegToFieldMap& reg_to_field ) {
DCHECK(profile != NULL);
if (!key->Valid())
return false;
bool has_non_empty_fields = false;
for (uint32 value_index = 0; value_index < key->ValueCount(); ++value_index) {
std::wstring value_name;
if (!key->ReadName(value_index, &value_name))
continue;
RegToFieldMap::const_iterator it = reg_to_field.find(value_name);
if (it == reg_to_field.end())
continue; // This field is not imported.
string16 field_value = ReadAndDecryptValue(key, value_name.c_str());
if (!field_value.empty()) {
has_non_empty_fields = true;
if (it->second == CREDIT_CARD_NUMBER) {
field_value = DecryptCCNumber(field_value);
}
profile->SetInfo(AutoFillType(it->second), field_value);
}
}
return has_non_empty_fields;
}
// Imports profiles from the IE toolbar and stores them. Asynchronous
// if PersonalDataManager has not been loaded yet. Deletes itself on completion.
class AutoFillImporter : public PersonalDataManager::Observer {
public:
explicit AutoFillImporter(PersonalDataManager* personal_data_manager)
: personal_data_manager_(personal_data_manager) {
personal_data_manager_->SetObserver(this);
}
bool ImportProfiles() {
if (!ImportCurrentUserProfiles(&profiles_, &credit_cards_)) {
delete this;
return false;
}
if (personal_data_manager_->IsDataLoaded())
OnPersonalDataLoaded();
return true;
}
// PersonalDataManager::Observer methods:
virtual void OnPersonalDataLoaded() {
if (!profiles_.empty())
personal_data_manager_->SetProfiles(&profiles_);
if (!credit_cards_.empty())
personal_data_manager_->SetCreditCards(&credit_cards_);
delete this;
}
private:
~AutoFillImporter() {
personal_data_manager_->RemoveObserver(this);
}
PersonalDataManager* personal_data_manager_;
std::vector<AutoFillProfile> profiles_;
std::vector<CreditCard> credit_cards_;
};
} // namespace
// Imports AutoFill profiles and credit cards from IE Toolbar if present and not
// password protected. Returns true if data is successfully retrieved. False if
// there is no data, data is password protected or error occurred.
bool ImportCurrentUserProfiles(std::vector<AutoFillProfile>* profiles,
std::vector<CreditCard>* credit_cards) {
DCHECK(profiles);
DCHECK(credit_cards);
// Create a map of possible fields for a quick access.
RegToFieldMap reg_to_field;
for (size_t i = 0; i < arraysize(profile_reg_values); ++i) {
reg_to_field[std::wstring(profile_reg_values[i].reg_value_name)] =
profile_reg_values[i].field_type;
}
base::win::RegistryKeyIterator iterator_profiles(HKEY_CURRENT_USER,
kProfileKey);
for (; iterator_profiles.Valid(); ++iterator_profiles) {
std::wstring key_name(kProfileKey);
key_name.append(L"\\");
key_name.append(iterator_profiles.Name());
RegKey key(HKEY_CURRENT_USER, key_name.c_str(), KEY_READ);
AutoFillProfile profile;
if (ImportSingleProfile(&profile, &key, reg_to_field)) {
// Combine phones into whole phone #.
string16 phone;
phone = profile.GetFieldText(AutoFillType(PHONE_HOME_COUNTRY_CODE));
phone.append(profile.GetFieldText(AutoFillType(PHONE_HOME_CITY_CODE)));
phone.append(profile.GetFieldText(AutoFillType(PHONE_HOME_NUMBER)));
profile.SetInfo(AutoFillType(PHONE_HOME_WHOLE_NUMBER), phone);
phone = profile.GetFieldText(AutoFillType(PHONE_FAX_COUNTRY_CODE));
phone.append(profile.GetFieldText(AutoFillType(PHONE_FAX_CITY_CODE)));
phone.append(profile.GetFieldText(AutoFillType(PHONE_FAX_NUMBER)));
profile.SetInfo(AutoFillType(PHONE_FAX_WHOLE_NUMBER), phone);
profiles->push_back(profile);
}
}
string16 password_hash;
string16 salt;
RegKey cc_key(HKEY_CURRENT_USER, kCreditCardKey, KEY_READ);
if (cc_key.Valid()) {
password_hash = ReadAndDecryptValue(&cc_key, kPasswordHashValue);
salt = ReadAndDecryptValue(&cc_key, kSaltValue);
}
// We import CC profiles only if they are not password protected.
if (password_hash.empty() && IsEmptySalt(salt)) {
base::win::RegistryKeyIterator iterator_cc(HKEY_CURRENT_USER,
kCreditCardKey);
for (; iterator_cc.Valid(); ++iterator_cc) {
std::wstring key_name(kCreditCardKey);
key_name.append(L"\\");
key_name.append(iterator_cc.Name());
RegKey key(HKEY_CURRENT_USER, key_name.c_str(), KEY_READ);
CreditCard credit_card;
if (ImportSingleProfile(&credit_card, &key, reg_to_field)) {
string16 cc_number = credit_card.GetFieldText(
AutoFillType(CREDIT_CARD_NUMBER));
if (!cc_number.empty())
credit_cards->push_back(credit_card);
}
}
}
return (profiles->size() + credit_cards->size()) > 0;
}
bool ImportAutofillDataWin(PersonalDataManager* pdm) {
// In incognito mode we do not have PDM - and we should not import anything.
if (!pdm)
return false;
AutoFillImporter *importer = new AutoFillImporter(pdm);
// importer will self delete.
return importer->ImportProfiles();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "chrome/browser/chromeos/browser_notification_observers.h"
#include <string>
#include "base/file_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/boot_times_loader.h"
#include "chrome/browser/chromeos/login/authentication_notification_details.h"
#include "chrome/common/notification_service.h"
namespace chromeos {
InitialTabNotificationObserver::InitialTabNotificationObserver() {
registrar_.Add(this, NotificationType::LOAD_START,
NotificationService::AllSources());
}
InitialTabNotificationObserver::~InitialTabNotificationObserver() {
}
void InitialTabNotificationObserver::Observe(
NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
// Only log for first tab to render. Make sure this is only done once.
if (type == NotificationType::LOAD_START && num_tabs_.GetNext() == 0) {
// Post difference between first tab and login succeess time as login time.
UMA_HISTOGRAM_TIMES("BootTime.Login",
base::Time::NowFromSystemTime() - login_success_time_);
// Post chrome first render stat.
BootTimesLoader::RecordCurrentStats("chrome-first-render");
registrar_.Remove(this, NotificationType::LOAD_START,
NotificationService::AllSources());
}
}
LogLoginSuccessObserver::LogLoginSuccessObserver() {
registrar_.Add(this, NotificationType::LOGIN_AUTHENTICATION,
NotificationService::AllSources());
}
LogLoginSuccessObserver::~LogLoginSuccessObserver() {
}
void LogLoginSuccessObserver::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::LOGIN_AUTHENTICATION);
Details<AuthenticationNotificationDetails> auth_details(details);
if (auth_details->success()) {
InitialTabNotificationObserver::Get()->SetLoginSuccessTime();
BootTimesLoader::RecordCurrentStats("login-successful");
registrar_.Remove(this, NotificationType::LOGIN_AUTHENTICATION,
NotificationService::AllSources());
}
}
} // namespace chromeos
<commit_msg>Chrome ARM build fix.<commit_after>// Copyright (c) 2010 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 "chrome/browser/chromeos/browser_notification_observers.h"
#include <string>
#include "base/file_util.h"
#include "base/histogram.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/boot_times_loader.h"
#include "chrome/browser/chromeos/login/authentication_notification_details.h"
#include "chrome/common/notification_service.h"
namespace chromeos {
InitialTabNotificationObserver::InitialTabNotificationObserver() {
registrar_.Add(this, NotificationType::LOAD_START,
NotificationService::AllSources());
}
InitialTabNotificationObserver::~InitialTabNotificationObserver() {
}
void InitialTabNotificationObserver::Observe(
NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
// Only log for first tab to render. Make sure this is only done once.
if (type == NotificationType::LOAD_START && num_tabs_.GetNext() == 0) {
// Post difference between first tab and login succeess time as login time.
UMA_HISTOGRAM_TIMES("BootTime.Login",
base::Time::NowFromSystemTime() - login_success_time_);
// Post chrome first render stat.
BootTimesLoader::RecordCurrentStats("chrome-first-render");
registrar_.Remove(this, NotificationType::LOAD_START,
NotificationService::AllSources());
}
}
LogLoginSuccessObserver::LogLoginSuccessObserver() {
registrar_.Add(this, NotificationType::LOGIN_AUTHENTICATION,
NotificationService::AllSources());
}
LogLoginSuccessObserver::~LogLoginSuccessObserver() {
}
void LogLoginSuccessObserver::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::LOGIN_AUTHENTICATION);
Details<AuthenticationNotificationDetails> auth_details(details);
if (auth_details->success()) {
InitialTabNotificationObserver::Get()->SetLoginSuccessTime();
BootTimesLoader::RecordCurrentStats("login-successful");
registrar_.Remove(this, NotificationType::LOGIN_AUTHENTICATION,
NotificationService::AllSources());
}
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "chrome/browser/debugger/devtools_http_protocol_handler.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop_proxy.h"
#include "base/string_number_conversions.h"
#include "base/thread.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "googleurl/src/gurl.h"
#include "net/base/io_buffer.h"
#include "net/base/listen_socket.h"
#include "net/server/http_server_request_info.h"
#include "net/url_request/url_request_context.h"
const int kBufferSize = 16 * 1024;
namespace {
// An internal implementation of DevToolsClientHost that delegates
// messages sent for DevToolsClient to a DebuggerShell instance.
class DevToolsClientHostImpl : public DevToolsClientHost {
public:
explicit DevToolsClientHostImpl(HttpListenSocket* socket)
: socket_(socket) {}
~DevToolsClientHostImpl() {}
// DevToolsClientHost interface
virtual void InspectedTabClosing() {
ChromeThread::PostTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(socket_,
&HttpListenSocket::Close));
}
virtual void SendMessageToClient(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg)
IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend,
OnDispatchOnInspectorFrontend);
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
}
void NotifyCloseListener() {
DevToolsClientHost::NotifyCloseListener();
}
private:
// Message handling routines
void OnDispatchOnInspectorFrontend(const std::string& data) {
std::string message;
message += "devtools$$dispatch(\"" + data + "\")";
socket_->SendOverWebSocket(message);
}
HttpListenSocket* socket_;
};
}
DevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() {
// Stop() must be called prior to this being called
DCHECK(server_.get() == NULL);
}
void DevToolsHttpProtocolHandler::Start() {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init));
}
void DevToolsHttpProtocolHandler::Stop() {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown));
}
void DevToolsHttpProtocolHandler::OnHttpRequest(
HttpListenSocket* socket,
const HttpServerRequestInfo& info) {
if (info.path == "" || info.path == "/") {
// Pages discovery request.
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(this,
&DevToolsHttpProtocolHandler::OnHttpRequestUI,
socket,
info));
return;
}
size_t pos = info.path.find("/devtools/");
if (pos != 0) {
socket->Send404();
return;
}
// Proxy static files from chrome://devtools/*.
URLRequest* request = new URLRequest(GURL("chrome:/" + info.path), this);
Bind(request, socket);
request->set_context(
Profile::GetDefaultRequestContext()->GetURLRequestContext());
request->Start();
}
void DevToolsHttpProtocolHandler::OnWebSocketRequest(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnWebSocketRequestUI,
socket,
request));
}
void DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket,
const std::string& data) {
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnWebSocketMessageUI,
socket,
data));
}
void DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) {
SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);
if (it != socket_to_requests_io_.end()) {
// Dispose delegating socket.
for (std::set<URLRequest*>::iterator it2 = it->second.begin();
it2 != it->second.end(); ++it2) {
URLRequest* request = *it2;
request->Cancel();
request_to_socket_io_.erase(request);
request_to_buffer_io_.erase(request);
delete request;
}
socket_to_requests_io_.erase(socket);
}
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnCloseUI,
socket));
}
void DevToolsHttpProtocolHandler::OnHttpRequestUI(
HttpListenSocket* socket,
const HttpServerRequestInfo& info) {
std::string response = "<html><body>";
for (BrowserList::const_iterator it = BrowserList::begin(),
end = BrowserList::end(); it != end; ++it) {
TabStripModel* model = (*it)->tabstrip_model();
for (int i = 0, size = model->count(); i < size; ++i) {
TabContents* tab_contents = model->GetTabContentsAt(i);
NavigationController& controller = tab_contents->controller();
NavigationEntry* entry = controller.GetActiveEntry();
if (entry == NULL)
continue;
if (!entry->url().is_valid())
continue;
DevToolsClientHost* client_host = DevToolsManager::GetInstance()->
GetDevToolsClientHostFor(tab_contents->render_view_host());
if (!client_host) {
response += StringPrintf(
"<a href='/devtools/devtools.html?page=%d'>%s (%s)</a><br>",
controller.session_id().id(),
UTF16ToUTF8(entry->title()).c_str(),
entry->url().spec().c_str());
} else {
response += StringPrintf(
"%s (%s)<br>",
UTF16ToUTF8(entry->title()).c_str(),
entry->url().spec().c_str());
}
}
}
response += "</body></html>";
Send200(socket, response, "text/html");
}
void DevToolsHttpProtocolHandler::OnWebSocketRequestUI(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
std::string prefix = "/devtools/page/";
size_t pos = request.path.find(prefix);
if (pos != 0) {
Send404(socket);
return;
}
std::string page_id = request.path.substr(prefix.length());
int id = 0;
if (!base::StringToInt(page_id, &id)) {
Send500(socket, "Invalid page id: " + page_id);
return;
}
TabContents* tab_contents = GetTabContents(id);
if (tab_contents == NULL) {
Send500(socket, "No such page id: " + page_id);
return;
}
DevToolsManager* manager = DevToolsManager::GetInstance();
if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) {
Send500(socket, "Page with given id is being inspected: " + page_id);
return;
}
DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket);
socket_to_client_host_ui_[socket] = client_host;
manager->RegisterDevToolsClientHostFor(
tab_contents->render_view_host(),
client_host);
AcceptWebSocket(socket, request);
}
void DevToolsHttpProtocolHandler::OnWebSocketMessageUI(
HttpListenSocket* socket,
const std::string& data) {
SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);
if (it == socket_to_client_host_ui_.end())
return;
DevToolsManager* manager = DevToolsManager::GetInstance();
manager->ForwardToDevToolsAgent(it->second,
DevToolsAgentMsg_DispatchOnInspectorBackend(data));
}
void DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) {
SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);
if (it == socket_to_client_host_ui_.end())
return;
DevToolsClientHostImpl* client_host =
static_cast<DevToolsClientHostImpl*>(it->second);
client_host->NotifyCloseListener();
delete client_host;
socket_to_client_host_ui_.erase(socket);
}
void DevToolsHttpProtocolHandler::OnResponseStarted(URLRequest* request) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
int expected_size = static_cast<int>(request->GetExpectedContentSize());
std::string content_type;
request->GetMimeType(&content_type);
if (request->status().is_success()) {
socket->Send(StringPrintf("HTTP/1.1 200 OK\r\n"
"Content-Type:%s\r\n"
"Content-Length:%d\r\n"
"\r\n",
content_type.c_str(),
expected_size));
} else {
socket->Send404();
}
int bytes_read = 0;
// Some servers may treat HEAD requests as GET requests. To free up the
// network connection as soon as possible, signal that the request has
// completed immediately, without trying to read any data back (all we care
// about is the response code and headers, which we already have).
net::IOBuffer* buffer = request_to_buffer_io_[request].get();
if (request->status().is_success())
request->Read(buffer, kBufferSize, &bytes_read);
OnReadCompleted(request, bytes_read);
}
void DevToolsHttpProtocolHandler::OnReadCompleted(URLRequest* request,
int bytes_read) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
net::IOBuffer* buffer = request_to_buffer_io_[request].get();
do {
if (!request->status().is_success() || bytes_read <= 0)
break;
socket->Send(buffer->data(), bytes_read);
} while (request->Read(buffer, kBufferSize, &bytes_read));
// See comments re: HEAD requests in OnResponseStarted().
if (!request->status().is_io_pending())
RequestCompleted(request);
}
DevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port)
: port_(port),
server_(NULL) {
}
void DevToolsHttpProtocolHandler::Init() {
server_ = HttpListenSocket::Listen("127.0.0.1", port_, this);
}
// Run on I/O thread
void DevToolsHttpProtocolHandler::Teardown() {
server_ = NULL;
}
void DevToolsHttpProtocolHandler::Bind(URLRequest* request,
HttpListenSocket* socket) {
request_to_socket_io_[request] = socket;
SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);
if (it == socket_to_requests_io_.end()) {
std::pair<HttpListenSocket*, std::set<URLRequest*> > value(
socket,
std::set<URLRequest*>());
it = socket_to_requests_io_.insert(value).first;
}
it->second.insert(request);
request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize);
}
void DevToolsHttpProtocolHandler::RequestCompleted(URLRequest* request) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
request_to_socket_io_.erase(request);
SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket);
it2->second.erase(request);
request_to_buffer_io_.erase(request);
delete request;
}
void DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket,
const std::string& data,
const std::string& mime_type) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send200,
data,
mime_type));
}
void DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send404));
}
void DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket,
const std::string& message) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send500,
message));
}
void DevToolsHttpProtocolHandler::AcceptWebSocket(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::AcceptWebSocket,
request));
}
TabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) {
for (BrowserList::const_iterator it = BrowserList::begin(),
end = BrowserList::end(); it != end; ++it) {
TabStripModel* model = (*it)->tabstrip_model();
for (int i = 0, size = model->count(); i < size; ++i) {
NavigationController& controller =
model->GetTabContentsAt(i)->controller();
if (controller.session_id().id() == session_id)
return controller.tab_contents();
}
}
return NULL;
}
<commit_msg>DevTools: fix remote debugging dispatch, provide encoding in the main connect page.<commit_after>// Copyright (c) 2010 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 "chrome/browser/debugger/devtools_http_protocol_handler.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop_proxy.h"
#include "base/string_number_conversions.h"
#include "base/thread.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "googleurl/src/gurl.h"
#include "net/base/io_buffer.h"
#include "net/base/listen_socket.h"
#include "net/server/http_server_request_info.h"
#include "net/url_request/url_request_context.h"
const int kBufferSize = 16 * 1024;
namespace {
// An internal implementation of DevToolsClientHost that delegates
// messages sent for DevToolsClient to a DebuggerShell instance.
class DevToolsClientHostImpl : public DevToolsClientHost {
public:
explicit DevToolsClientHostImpl(HttpListenSocket* socket)
: socket_(socket) {}
~DevToolsClientHostImpl() {}
// DevToolsClientHost interface
virtual void InspectedTabClosing() {
ChromeThread::PostTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(socket_,
&HttpListenSocket::Close));
}
virtual void SendMessageToClient(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg)
IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend,
OnDispatchOnInspectorFrontend);
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
}
void NotifyCloseListener() {
DevToolsClientHost::NotifyCloseListener();
}
private:
// Message handling routines
void OnDispatchOnInspectorFrontend(const std::string& data) {
socket_->SendOverWebSocket("devtools$$dispatch(" + data + ")");
}
HttpListenSocket* socket_;
};
}
DevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() {
// Stop() must be called prior to this being called
DCHECK(server_.get() == NULL);
}
void DevToolsHttpProtocolHandler::Start() {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init));
}
void DevToolsHttpProtocolHandler::Stop() {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown));
}
void DevToolsHttpProtocolHandler::OnHttpRequest(
HttpListenSocket* socket,
const HttpServerRequestInfo& info) {
if (info.path == "" || info.path == "/") {
// Pages discovery request.
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(this,
&DevToolsHttpProtocolHandler::OnHttpRequestUI,
socket,
info));
return;
}
size_t pos = info.path.find("/devtools/");
if (pos != 0) {
socket->Send404();
return;
}
// Proxy static files from chrome://devtools/*.
URLRequest* request = new URLRequest(GURL("chrome:/" + info.path), this);
Bind(request, socket);
request->set_context(
Profile::GetDefaultRequestContext()->GetURLRequestContext());
request->Start();
}
void DevToolsHttpProtocolHandler::OnWebSocketRequest(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnWebSocketRequestUI,
socket,
request));
}
void DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket,
const std::string& data) {
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnWebSocketMessageUI,
socket,
data));
}
void DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) {
SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);
if (it != socket_to_requests_io_.end()) {
// Dispose delegating socket.
for (std::set<URLRequest*>::iterator it2 = it->second.begin();
it2 != it->second.end(); ++it2) {
URLRequest* request = *it2;
request->Cancel();
request_to_socket_io_.erase(request);
request_to_buffer_io_.erase(request);
delete request;
}
socket_to_requests_io_.erase(socket);
}
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnCloseUI,
socket));
}
void DevToolsHttpProtocolHandler::OnHttpRequestUI(
HttpListenSocket* socket,
const HttpServerRequestInfo& info) {
std::string response = "<html><body>";
for (BrowserList::const_iterator it = BrowserList::begin(),
end = BrowserList::end(); it != end; ++it) {
TabStripModel* model = (*it)->tabstrip_model();
for (int i = 0, size = model->count(); i < size; ++i) {
TabContents* tab_contents = model->GetTabContentsAt(i);
NavigationController& controller = tab_contents->controller();
NavigationEntry* entry = controller.GetActiveEntry();
if (entry == NULL)
continue;
if (!entry->url().is_valid())
continue;
DevToolsClientHost* client_host = DevToolsManager::GetInstance()->
GetDevToolsClientHostFor(tab_contents->render_view_host());
if (!client_host) {
response += StringPrintf(
"<a href='/devtools/devtools.html?page=%d'>%s (%s)</a><br>",
controller.session_id().id(),
UTF16ToUTF8(entry->title()).c_str(),
entry->url().spec().c_str());
} else {
response += StringPrintf(
"%s (%s)<br>",
UTF16ToUTF8(entry->title()).c_str(),
entry->url().spec().c_str());
}
}
}
response += "</body></html>";
Send200(socket, response, "text/html; charset=UTF-8");
}
void DevToolsHttpProtocolHandler::OnWebSocketRequestUI(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
std::string prefix = "/devtools/page/";
size_t pos = request.path.find(prefix);
if (pos != 0) {
Send404(socket);
return;
}
std::string page_id = request.path.substr(prefix.length());
int id = 0;
if (!base::StringToInt(page_id, &id)) {
Send500(socket, "Invalid page id: " + page_id);
return;
}
TabContents* tab_contents = GetTabContents(id);
if (tab_contents == NULL) {
Send500(socket, "No such page id: " + page_id);
return;
}
DevToolsManager* manager = DevToolsManager::GetInstance();
if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) {
Send500(socket, "Page with given id is being inspected: " + page_id);
return;
}
DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket);
socket_to_client_host_ui_[socket] = client_host;
manager->RegisterDevToolsClientHostFor(
tab_contents->render_view_host(),
client_host);
AcceptWebSocket(socket, request);
}
void DevToolsHttpProtocolHandler::OnWebSocketMessageUI(
HttpListenSocket* socket,
const std::string& data) {
SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);
if (it == socket_to_client_host_ui_.end())
return;
DevToolsManager* manager = DevToolsManager::GetInstance();
manager->ForwardToDevToolsAgent(it->second,
DevToolsAgentMsg_DispatchOnInspectorBackend(data));
}
void DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) {
SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);
if (it == socket_to_client_host_ui_.end())
return;
DevToolsClientHostImpl* client_host =
static_cast<DevToolsClientHostImpl*>(it->second);
client_host->NotifyCloseListener();
delete client_host;
socket_to_client_host_ui_.erase(socket);
}
void DevToolsHttpProtocolHandler::OnResponseStarted(URLRequest* request) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
int expected_size = static_cast<int>(request->GetExpectedContentSize());
std::string content_type;
request->GetMimeType(&content_type);
if (request->status().is_success()) {
socket->Send(StringPrintf("HTTP/1.1 200 OK\r\n"
"Content-Type:%s\r\n"
"Content-Length:%d\r\n"
"\r\n",
content_type.c_str(),
expected_size));
} else {
socket->Send404();
}
int bytes_read = 0;
// Some servers may treat HEAD requests as GET requests. To free up the
// network connection as soon as possible, signal that the request has
// completed immediately, without trying to read any data back (all we care
// about is the response code and headers, which we already have).
net::IOBuffer* buffer = request_to_buffer_io_[request].get();
if (request->status().is_success())
request->Read(buffer, kBufferSize, &bytes_read);
OnReadCompleted(request, bytes_read);
}
void DevToolsHttpProtocolHandler::OnReadCompleted(URLRequest* request,
int bytes_read) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
net::IOBuffer* buffer = request_to_buffer_io_[request].get();
do {
if (!request->status().is_success() || bytes_read <= 0)
break;
socket->Send(buffer->data(), bytes_read);
} while (request->Read(buffer, kBufferSize, &bytes_read));
// See comments re: HEAD requests in OnResponseStarted().
if (!request->status().is_io_pending())
RequestCompleted(request);
}
DevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port)
: port_(port),
server_(NULL) {
}
void DevToolsHttpProtocolHandler::Init() {
server_ = HttpListenSocket::Listen("127.0.0.1", port_, this);
}
// Run on I/O thread
void DevToolsHttpProtocolHandler::Teardown() {
server_ = NULL;
}
void DevToolsHttpProtocolHandler::Bind(URLRequest* request,
HttpListenSocket* socket) {
request_to_socket_io_[request] = socket;
SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);
if (it == socket_to_requests_io_.end()) {
std::pair<HttpListenSocket*, std::set<URLRequest*> > value(
socket,
std::set<URLRequest*>());
it = socket_to_requests_io_.insert(value).first;
}
it->second.insert(request);
request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize);
}
void DevToolsHttpProtocolHandler::RequestCompleted(URLRequest* request) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
request_to_socket_io_.erase(request);
SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket);
it2->second.erase(request);
request_to_buffer_io_.erase(request);
delete request;
}
void DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket,
const std::string& data,
const std::string& mime_type) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send200,
data,
mime_type));
}
void DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send404));
}
void DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket,
const std::string& message) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send500,
message));
}
void DevToolsHttpProtocolHandler::AcceptWebSocket(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::AcceptWebSocket,
request));
}
TabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) {
for (BrowserList::const_iterator it = BrowserList::begin(),
end = BrowserList::end(); it != end; ++it) {
TabStripModel* model = (*it)->tabstrip_model();
for (int i = 0, size = model->count(); i < size; ++i) {
NavigationController& controller =
model->GetTabContentsAt(i)->controller();
if (controller.session_id().id() == session_id)
return controller.tab_contents();
}
}
return NULL;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "base/command_line.h"
#include "base/lock.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/safe_browsing/protocol_manager.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
// This starts the browser and keeps status of states related to SafeBrowsing.
class SafeBrowsingServiceTest : public InProcessBrowserTest {
public:
SafeBrowsingServiceTest()
: safe_browsing_service_(NULL),
is_update_in_progress_(false),
is_initial_request_(false),
is_update_scheduled_(false),
is_url_match_in_db_(false) {
}
void UpdateSafeBrowsingStatus() {
CHECK(safe_browsing_service_);
AutoLock lock(update_status_mutex_);
is_update_in_progress_ = safe_browsing_service_->IsUpdateInProgress();
is_initial_request_ =
safe_browsing_service_->protocol_manager_->is_initial_request();
last_update_ = safe_browsing_service_->protocol_manager_->last_update();
is_update_scheduled_ =
safe_browsing_service_->protocol_manager_->update_timer_.IsRunning();
}
void CheckUrl(SafeBrowsingService::Client* helper, const GURL& url) {
CHECK(safe_browsing_service_);
AutoLock lock(update_status_mutex_);
if (!safe_browsing_service_->CheckUrl(url, helper)) {
safe_browsing_service_->CancelCheck(helper);
is_url_match_in_db_ = false;
}
is_url_match_in_db_ = true;
}
bool is_url_match_in_db() {
AutoLock l(update_status_mutex_);
return is_url_match_in_db_;
}
bool is_update_in_progress() {
AutoLock l(update_status_mutex_);
return is_update_in_progress_;
}
bool is_initial_request() {
AutoLock l(update_status_mutex_);
return is_initial_request_;
}
base::Time last_update() {
AutoLock l(update_status_mutex_);
return last_update_;
}
bool is_update_scheduled() {
AutoLock l(update_status_mutex_);
return is_update_scheduled_;
}
protected:
void InitSafeBrowsingService() {
safe_browsing_service_ =
g_browser_process->resource_dispatcher_host()->safe_browsing_service();
}
virtual void SetUpCommandLine(CommandLine* command_line) {
// Makes sure the auto update is not triggered. This test will force the
// update when needed.
command_line->AppendSwitch(switches::kSbDisableAutoUpdate);
}
private:
SafeBrowsingService* safe_browsing_service_;
// Protects all variables below since they are updated on IO thread but
// read on UI thread.
Lock update_status_mutex_;
// States associated with safebrowsing service updates.
bool is_update_in_progress_;
bool is_initial_request_;
base::Time last_update_;
bool is_update_scheduled_;
// Indicates if there is a match between a URL's prefix and safebrowsing
// database (thus potentially it is a phishing url).
bool is_url_match_in_db_;
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceTest);
};
// A ref counted helper class that handles callbacks between IO thread and UI
// thread.
class SafeBrowsingServiceTestHelper
: public base::RefCountedThreadSafe<SafeBrowsingServiceTestHelper>,
public SafeBrowsingService::Client {
public:
explicit SafeBrowsingServiceTestHelper(
SafeBrowsingServiceTest* safe_browsing_test)
: safe_browsing_test_(safe_browsing_test) {
}
// Callbacks for SafeBrowsingService::Client. Not implemented yet.
virtual void OnUrlCheckResult(const GURL& url,
SafeBrowsingService::UrlCheckResult result) {
NOTREACHED() << "Not implemented.";
}
virtual void OnBlockingPageComplete(bool proceed) {
NOTREACHED() << "Not implemented.";
}
// Functions and callbacks related to CheckUrl. These are used to verify if
// a URL is a phishing URL.
void CheckUrl(const GURL& url) {
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE, NewRunnableMethod(this,
&SafeBrowsingServiceTestHelper::CheckUrlOnIOThread, url));
}
void CheckUrlOnIOThread(const GURL& url) {
CHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
safe_browsing_test_->CheckUrl(this, url);
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE, NewRunnableMethod(this,
&SafeBrowsingServiceTestHelper::OnCheckUrlOnIOThreadDone));
}
void OnCheckUrlOnIOThreadDone() {
StopUILoop();
}
// Functions and callbacks related to safebrowsing server status.
void CheckStatusOnIOThread() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
safe_browsing_test_->UpdateSafeBrowsingStatus();
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE, NewRunnableMethod(this,
&SafeBrowsingServiceTestHelper::OnCheckStatusOnIOThreadDone));
}
void OnCheckStatusOnIOThreadDone() {
StopUILoop();
}
void CheckStatusAfterDelay(int64 wait_time_sec) {
ChromeThread::PostDelayedTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(this,
&SafeBrowsingServiceTestHelper::CheckStatusOnIOThread),
wait_time_sec * 1000);
}
private:
// Stops UI loop after desired status is updated.
void StopUILoop() {
CHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
MessageLoopForUI::current()->Quit();
}
base::OneShotTimer<SafeBrowsingServiceTestHelper> check_update_timer_;
SafeBrowsingServiceTest* safe_browsing_test_;
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceTestHelper);
};
IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, SafeBrowsingSystemTest) {
InitSafeBrowsingService();
scoped_refptr<SafeBrowsingServiceTestHelper> safe_browsing_helper =
new SafeBrowsingServiceTestHelper(this);
// Waits for 1 sec and makes sure safebrowsing update is not happening.
safe_browsing_helper->CheckStatusAfterDelay(1);
// Loop will stop once OnCheckStatusOnIOThreadDone in safe_browsing_helper
// is called and status from safe_browsing_service_ is checked.
ui_test_utils::RunMessageLoop();
EXPECT_FALSE(is_update_in_progress());
EXPECT_TRUE(is_initial_request());
EXPECT_FALSE(is_update_scheduled());
EXPECT_TRUE(last_update().is_null());
// Verify URL.
const char test_url[] = "http://ianfette.org";
safe_browsing_helper->CheckUrl(GURL(test_url));
// Loop will stop once OnCheckUrlOnIOThreadDone in safe_browsing_helper
// is called and url check is done.
ui_test_utils::RunMessageLoop();
EXPECT_TRUE(is_url_match_in_db());
// TODO(lzheng): Add tests to launch a testing safebrowsing server
// and issue requests repeatedly:
// http://code.google.com/p/google-safe-browsing/wiki/ProtocolTesting
}
<commit_msg>Full end to end test using safebrowsing test server suite.<commit_after>// Copyright (c) 2010 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 <vector>
#include "base/command_line.h"
#include "base/lock.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/safe_browsing/protocol_manager.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/host_resolver.h"
#include "net/base/load_flags.h"
#include "net/base/net_log.h"
#include "net/socket/tcp_pinger.h"
#include "testing/gtest/include/gtest/gtest.h"
const char kHost[] = "127.0.0.1";
const char kPort[] = "40101";
const char kDataFile[] = "datafile.dat";
const char kUrlVerifyPath[] = "/safebrowsing/verify_urls";
const char kTestCompletePath[] = "/test_complete";
class SafeBrowsingTestServer {
public:
SafeBrowsingTestServer(const std::string& hostname,
const std::string& port,
const std::string& datafile)
: hostname_(hostname),
port_(port),
datafile_(datafile),
server_handle_(base::kNullProcessHandle) {
}
~SafeBrowsingTestServer() {
EXPECT_EQ(server_handle_, base::kNullProcessHandle);
}
// Start the python server test suite.
bool Start() {
// Get path to python server script
FilePath testserver_path;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &testserver_path))
return false;
testserver_path = testserver_path
.Append(FILE_PATH_LITERAL("chrome"))
.Append(FILE_PATH_LITERAL("browser"))
.Append(FILE_PATH_LITERAL("safe_browsing"))
.Append(FILE_PATH_LITERAL("testserver"));
AppendToPythonPath(testserver_path);
FilePath testserver = testserver_path.Append(
FILE_PATH_LITERAL("safebrowsing_test_server.py"));
#if defined(OS_WIN)
FilePath datafile = testserver_path.Append(ASCIIToWide(datafile_));
FilePath python_runtime;
// Get path to python interpreter
if (!PathService::Get(base::DIR_SOURCE_ROOT, &python_runtime))
return false;
python_runtime = python_runtime
.Append(FILE_PATH_LITERAL("third_party"))
.Append(FILE_PATH_LITERAL("python_24"))
.Append(FILE_PATH_LITERAL("python.exe"));
std::wstring command_line =
L"\"" + python_runtime.ToWStringHack() + L"\" " +
L"\"" + testserver.ToWStringHack() +
L"\" --port=" + UTF8ToWide(port_) +
L"\" --datafile=" + datafile.ToWStringHack() + L"\"";
if (!base::LaunchApp(command_line, false, true, &server_handle_)) {
LOG(ERROR) << "Failed to launch " << command_line;
return false;
}
#elif defined(OS_POSIX)
FilePath datafile = testserver_path.Append(datafile_);
std::vector<std::string> command_line;
command_line.push_back("python");
command_line.push_back(testserver.value());
command_line.push_back("--port=" + port_);
command_line.push_back("--datafile=" + datafile.value());
base::file_handle_mapping_vector no_mappings;
LOG(INFO) << "Trying to launch " << command_line[0] << " ...";
if (!base::LaunchApp(command_line, no_mappings, false, &server_handle_)) {
LOG(ERROR) << "Failed to launch " << command_line[0] << " ...";
return false;
}
#endif
// Let the server start, then verify that it's up.
// Our server is Python, and takes about 500ms to start
// up the first time, and about 200ms after that.
if (!WaitServerToStart(hostname_, StringToInt(port_))) {
LOG(ERROR) << "Failed to connect to server";
Stop();
return false;
}
LOG(INFO) << "Started on port " << port_;
return true;
}
// Stop the python server test suite.
bool Stop() {
if (!server_handle_) {
return true;
}
// First check if the process has already terminated.
bool ret = base::WaitForSingleProcess(server_handle_, 0);
if (!ret) {
ret = base::KillProcess(server_handle_, 1, true);
}
if (ret) {
base::CloseProcessHandle(server_handle_);
server_handle_ = base::kNullProcessHandle;
LOG(INFO) << "Stopped.";
} else {
LOG(INFO) << "Kill failed?";
return false;
}
return true;
}
private:
// Make sure the test server is actually started and ready to serve.
bool WaitServerToStart(const std::string& host_name, int port) {
net::AddressList addr;
scoped_refptr<net::HostResolver> resolver(net::CreateSystemHostResolver(
net::HostResolver::kDefaultParallelism));
net::HostResolver::RequestInfo info(host_name, port);
int rv = resolver->Resolve(info, &addr, NULL, NULL, net::BoundNetLog());
if (rv != net::OK)
return false;
net::TCPPinger pinger(addr);
rv = pinger.Ping(base::TimeDelta::FromSeconds(kConnectionTimeoutSec),
kRetryAttempts);
return rv == net::OK;
}
void AppendToPythonPath(const FilePath& dir) {
#if defined(OS_WIN)
const wchar_t kPythonPath[] = L"PYTHONPATH";
wchar_t oldpath[8192];
if (GetEnvironmentVariable(kPythonPath, oldpath, arraysize(oldpath)) == 0) {
SetEnvironmentVariableW(kPythonPath, dir.value().c_str());
} else if (!wcsstr(oldpath, dir.value().c_str())) {
std::wstring newpath(oldpath);
newpath.append(L";");
newpath.append(dir.value());
SetEnvironmentVariableW(kPythonPath, newpath.c_str());
}
#elif defined(OS_POSIX)
const char kPythonPath[] = "PYTHONPATH";
const char* oldpath = getenv(kPythonPath);
// setenv() leaks memory intentionally on Mac
if (!oldpath) {
setenv(kPythonPath, dir.value().c_str(), 1);
} else if (!strstr(oldpath, dir.value().c_str())) {
std::string newpath(oldpath);
newpath.append(":");
newpath.append(dir.value());
setenv(kPythonPath, newpath.c_str(), 1);
}
#endif
}
std::string hostname_;
std::string port_;
std::string datafile_;
static const int kConnectionTimeoutSec = 5;
static const int kRetryAttempts = 3;
base::ProcessHandle server_handle_;
};
typedef struct {
std::string url;
std::string list_name;
bool is_phishing;
} PhishingUrl;
// Parses server response for verify_urls. The expected format is:
//
// first.random.url.com/ internal-test-shavar yes
// second.random.url.com/ internal-test-shavar yes
// ...
static bool ParsePhishingUrls(const std::string& data,
std::vector<PhishingUrl>* phishing_urls) {
std::vector<std::string> urls;
SplitString(data, '\n', &urls);
for (size_t i = 0; i < urls.size(); ++i) {
PhishingUrl phishing_url;
std::vector<std::string> url_parts;
SplitStringAlongWhitespace(urls[i], &url_parts);
if (url_parts.size() < 3) {
CHECK(false) << "Unexpected URL format in phishing URL list: "
<< urls[i];
return false;
}
phishing_url.url = url_parts[0];
phishing_url.list_name = url_parts[1];
if (url_parts[2] == "yes") {
phishing_url.is_phishing = true;
} else {
CHECK_EQ("no", url_parts[2]);
phishing_url.is_phishing = false;
}
phishing_urls->push_back(phishing_url);
}
return true;
}
// This starts the browser and keeps status of states related to SafeBrowsing.
class SafeBrowsingServiceTest : public InProcessBrowserTest {
public:
SafeBrowsingServiceTest()
: safe_browsing_service_(NULL),
is_update_in_progress_(false),
is_initial_request_(false),
is_update_scheduled_(false),
is_checked_url_in_db_(false),
is_checked_url_safe_(false) {
}
void UpdateSafeBrowsingStatus() {
CHECK(safe_browsing_service_);
AutoLock lock(update_status_mutex_);
is_update_in_progress_ = safe_browsing_service_->IsUpdateInProgress();
is_initial_request_ =
safe_browsing_service_->protocol_manager_->is_initial_request();
last_update_ = safe_browsing_service_->protocol_manager_->last_update();
is_update_scheduled_ =
safe_browsing_service_->protocol_manager_->update_timer_.IsRunning();
}
void ForceUpdate() {
CHECK(safe_browsing_service_);
safe_browsing_service_->protocol_manager_->ForceScheduleNextUpdate(0);
}
void CheckUrl(SafeBrowsingService::Client* helper, const GURL& url) {
CHECK(safe_browsing_service_);
AutoLock lock(update_status_mutex_);
if (safe_browsing_service_->CheckUrl(url, helper)) {
is_checked_url_in_db_ = false;
return;
}
is_checked_url_in_db_ = true;
}
bool is_checked_url_in_db() {
AutoLock l(update_status_mutex_);
return is_checked_url_in_db_;
}
void set_is_checked_url_safe(bool safe) {
AutoLock l(update_status_mutex_);
is_checked_url_safe_ = safe;
}
bool is_checked_url_safe() {
AutoLock l(update_status_mutex_);
return is_checked_url_safe_;
}
bool is_update_in_progress() {
AutoLock l(update_status_mutex_);
return is_update_in_progress_;
}
bool is_initial_request() {
AutoLock l(update_status_mutex_);
return is_initial_request_;
}
base::Time last_update() {
AutoLock l(update_status_mutex_);
return last_update_;
}
bool is_update_scheduled() {
AutoLock l(update_status_mutex_);
return is_update_scheduled_;
}
protected:
void InitSafeBrowsingService() {
safe_browsing_service_ =
g_browser_process->resource_dispatcher_host()->safe_browsing_service();
}
virtual void SetUpCommandLine(CommandLine* command_line) {
// Makes sure the auto update is not triggered. This test will force the
// update when needed.
command_line->AppendSwitch(switches::kSbDisableAutoUpdate);
command_line->AppendSwitchWithValue(
switches::kSbInfoURLPrefix, "http://localhost:40101/safebrowsing");
command_line->AppendSwitchWithValue(
switches::kSbMacKeyURLPrefix, "http://localhost:40101/safebrowsing");
}
void SetTestStep(int step) {
std::string test_step = StringPrintf("&test_step=%d", step);
safe_browsing_service_->protocol_manager_->set_additional_query(test_step);
}
private:
SafeBrowsingService* safe_browsing_service_;
// Protects all variables below since they are updated on IO thread but
// read on UI thread.
Lock update_status_mutex_;
// States associated with safebrowsing service updates.
bool is_update_in_progress_;
bool is_initial_request_;
base::Time last_update_;
bool is_update_scheduled_;
// Indicates if there is a match between a URL's prefix and safebrowsing
// database (thus potentially it is a phishing url).
bool is_checked_url_in_db_;
// True if last verified URL is not a phishing URL and thus it is safe.
bool is_checked_url_safe_;
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceTest);
};
// A ref counted helper class that handles callbacks between IO thread and UI
// thread.
class SafeBrowsingServiceTestHelper
: public base::RefCountedThreadSafe<SafeBrowsingServiceTestHelper>,
public SafeBrowsingService::Client,
public URLFetcher::Delegate {
public:
explicit SafeBrowsingServiceTestHelper(
SafeBrowsingServiceTest* safe_browsing_test)
: safe_browsing_test_(safe_browsing_test) {
}
// Callbacks for SafeBrowsingService::Client.
virtual void OnUrlCheckResult(const GURL& url,
SafeBrowsingService::UrlCheckResult result) {
CHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
CHECK(safe_browsing_test_->is_checked_url_in_db());
safe_browsing_test_->set_is_checked_url_safe(
result == SafeBrowsingService::URL_SAFE);
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE, NewRunnableMethod(this,
&SafeBrowsingServiceTestHelper::OnCheckUrlOnIOThreadDone));
}
virtual void OnBlockingPageComplete(bool proceed) {
NOTREACHED() << "Not implemented.";
}
// Functions and callbacks to start the safebrowsing database update.
void ForceUpdate() {
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE, NewRunnableMethod(this,
&SafeBrowsingServiceTestHelper::ForceUpdateInIOThread));
}
void ForceUpdateInIOThread() {
CHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
safe_browsing_test_->ForceUpdate();
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE, NewRunnableMethod(this,
&SafeBrowsingServiceTestHelper::OnForceUpdateDone));
}
void OnForceUpdateDone() {
StopUILoop();
}
// Functions and callbacks related to CheckUrl. These are used to verify
// phishing URLs.
void CheckUrl(const GURL& url) {
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE, NewRunnableMethod(this,
&SafeBrowsingServiceTestHelper::CheckUrlOnIOThread, url));
}
void CheckUrlOnIOThread(const GURL& url) {
CHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
safe_browsing_test_->CheckUrl(this, url);
if (!safe_browsing_test_->is_checked_url_in_db()) {
// Ends the checking since this url's prefix is not in database.
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE, NewRunnableMethod(
this, &SafeBrowsingServiceTestHelper::OnCheckUrlOnIOThreadDone));
}
// Otherwise, OnCheckUrlOnIOThreadDone is called in OnUrlCheckResult since
// safebrowsing service further fetches hashes from safebrowsing server.
}
void OnCheckUrlOnIOThreadDone() {
StopUILoop();
}
// Functions and callbacks related to safebrowsing server status.
void CheckStatusAfterDelay(int64 wait_time_sec) {
ChromeThread::PostDelayedTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(this,
&SafeBrowsingServiceTestHelper::CheckStatusOnIOThread),
wait_time_sec * 1000);
}
void CheckStatusOnIOThread() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
safe_browsing_test_->UpdateSafeBrowsingStatus();
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE, NewRunnableMethod(this,
&SafeBrowsingServiceTestHelper::OnCheckStatusOnIOThreadDone));
}
void OnCheckStatusOnIOThreadDone() {
StopUILoop();
}
// Calls test server to fetch urls for verification.
void FetchUrlsToVerify(const std::string& host,
const std::string& port,
int test_step) {
GURL url(StringPrintf("http://%s:%s/%s?"
"client=chromium&appver=1.0&pver=2.2&test_step=%d",
host.c_str(), port.c_str(), kUrlVerifyPath,
test_step));
url_fetcher_.reset(new URLFetcher(url, URLFetcher::GET, this));
url_fetcher_->set_load_flags(net::LOAD_DISABLE_CACHE);
url_fetcher_->set_request_context(Profile::GetDefaultRequestContext());
url_fetcher_->Start();
}
// Calls test server to check if test data is done.
void VerifyTestComplete(const std::string& host,
const std::string& port,
int test_step) {
GURL url(StringPrintf("http://%s:%s/%s?test_step=%d",
host.c_str(), port.c_str(), kTestCompletePath,
test_step));
url_fetcher_.reset(new URLFetcher(url, URLFetcher::GET, this));
url_fetcher_->set_load_flags(net::LOAD_DISABLE_CACHE);
url_fetcher_->set_request_context(Profile::GetDefaultRequestContext());
url_fetcher_->Start();
}
// Callback for URLFetcher.
virtual void OnURLFetchComplete(const URLFetcher* source,
const GURL& url,
const URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
response_data_ = data;
StopUILoop();
}
const std::string& response_data() {
return response_data_;
}
private:
// Stops UI loop after desired status is updated.
void StopUILoop() {
CHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
MessageLoopForUI::current()->Quit();
}
base::OneShotTimer<SafeBrowsingServiceTestHelper> check_update_timer_;
SafeBrowsingServiceTest* safe_browsing_test_;
scoped_ptr<URLFetcher> url_fetcher_;
std::string response_data_;
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceTestHelper);
};
IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, SafeBrowsingSystemTest) {
InitSafeBrowsingService();
scoped_refptr<SafeBrowsingServiceTestHelper> safe_browsing_helper =
new SafeBrowsingServiceTestHelper(this);
// Waits for 1 sec and makes sure safebrowsing update is not happening.
// MessageLoop will stop once OnCheckStatusOnIOThreadDone in
// safe_browsing_helper is called and status from safe_browsing_service_
// is checked.
safe_browsing_helper->CheckStatusAfterDelay(1);
ui_test_utils::RunMessageLoop();
EXPECT_FALSE(is_update_in_progress());
EXPECT_TRUE(is_initial_request());
EXPECT_FALSE(is_update_scheduled());
EXPECT_TRUE(last_update().is_null());
// Verify with a test phishing URL. Loop will stop once
// OnCheckUrlOnIOThreadDone in safe_browsing_helper is called and URL check
// is done.
const char test_url[] = "http://ianfette.org";
safe_browsing_helper->CheckUrl(GURL(test_url));
ui_test_utils::RunMessageLoop();
EXPECT_TRUE(is_checked_url_in_db());
SafeBrowsingTestServer test_server(kHost, kPort, kDataFile);
test_server.Start();
// Limits max test steps so the test won't run wild.
const int kMaxSteps = 10;
int last_step = 0;
// Starts from test step 1.
for (int step = 1; step < kMaxSteps; step++) {
// Every step should be a fresh start.
EXPECT_FALSE(is_update_in_progress());
EXPECT_FALSE(is_update_scheduled());
// Starts safebrowsing update on IO thread. Waits till scheduled
// update finishes. Stops waiting after kMaxWaitSec if the update
// could not finish.
base::Time now = base::Time::Now();
SetTestStep(step);
safe_browsing_helper->ForceUpdate();
ui_test_utils::RunMessageLoop();
int wait_sec = 0;
const int kMaxWaitSec = 10;
while ((is_update_scheduled() || is_update_in_progress()) &&
wait_sec++ < kMaxWaitSec) {
safe_browsing_helper->CheckStatusAfterDelay(1);
ui_test_utils::RunMessageLoop();
}
EXPECT_LT(wait_sec, kMaxWaitSec)
<< "Can't finish update in required time limit!";
if (last_update() < now) {
// This means no data available anymore.
break;
}
// Fetches urls to verify and waits till server responses with data.
safe_browsing_helper->FetchUrlsToVerify(kHost, kPort, step);
ui_test_utils::RunMessageLoop();
LOG(INFO) << safe_browsing_helper->response_data();
std::vector<PhishingUrl> phishing_urls;
EXPECT_TRUE(ParsePhishingUrls(safe_browsing_helper->response_data(),
&phishing_urls));
for (size_t j = 0; j < phishing_urls.size(); ++j) {
// Verifes with server if a URL is a phishing URL and waits till server
// responses.
safe_browsing_helper->CheckUrl(GURL(phishing_urls[j].url));
ui_test_utils::RunMessageLoop();
if (phishing_urls[j].is_phishing) {
EXPECT_TRUE(is_checked_url_in_db());
EXPECT_FALSE(is_checked_url_safe());
} else {
EXPECT_TRUE(is_checked_url_in_db());
}
}
last_step = step;
}
// Verifies with server if test is done and waits till server responses.
safe_browsing_helper->VerifyTestComplete(kHost, kPort, last_step);
ui_test_utils::RunMessageLoop();
EXPECT_EQ("yes", safe_browsing_helper->response_data());
test_server.Stop();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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 "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/bookmarks/bookmark_editor.h"
#include "chrome/browser/ui/sync/sync_promo_ui.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view_observer.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_sync_promo_view.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/browser/bookmark_utils.h"
#include "content/public/browser/user_metrics.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/accessibility/ax_view_state.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/link.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
using base::UserMetricsAction;
using views::ColumnSet;
using views::GridLayout;
namespace {
// Width of the border of a button.
const int kControlBorderWidth = 2;
// This combobox prevents any lengthy content from stretching the bubble view.
class UnsizedCombobox : public views::Combobox {
public:
explicit UnsizedCombobox(ui::ComboboxModel* model) : views::Combobox(model) {}
virtual ~UnsizedCombobox() {}
virtual gfx::Size GetPreferredSize() const OVERRIDE {
return gfx::Size(0, views::Combobox::GetPreferredSize().height());
}
private:
DISALLOW_COPY_AND_ASSIGN(UnsizedCombobox);
};
} // namespace
BookmarkBubbleView* BookmarkBubbleView::bookmark_bubble_ = NULL;
// static
void BookmarkBubbleView::ShowBubble(views::View* anchor_view,
BookmarkBubbleViewObserver* observer,
scoped_ptr<BookmarkBubbleDelegate> delegate,
Profile* profile,
const GURL& url,
bool newly_bookmarked) {
if (IsShowing())
return;
bookmark_bubble_ = new BookmarkBubbleView(anchor_view,
observer,
delegate.Pass(),
profile,
url,
newly_bookmarked);
views::BubbleDelegateView::CreateBubble(bookmark_bubble_)->Show();
// Select the entire title textfield contents when the bubble is first shown.
bookmark_bubble_->title_tf_->SelectAll(true);
bookmark_bubble_->SetArrowPaintType(views::BubbleBorder::PAINT_NONE);
if (bookmark_bubble_->observer_)
bookmark_bubble_->observer_->OnBookmarkBubbleShown(url);
}
// static
bool BookmarkBubbleView::IsShowing() {
return bookmark_bubble_ != NULL;
}
void BookmarkBubbleView::Hide() {
if (IsShowing())
bookmark_bubble_->GetWidget()->Close();
}
BookmarkBubbleView::~BookmarkBubbleView() {
if (apply_edits_) {
ApplyEdits();
} else if (remove_bookmark_) {
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
const BookmarkNode* node = model->GetMostRecentlyAddedUserNodeForURL(url_);
if (node)
model->Remove(node->parent(), node->parent()->GetIndexOf(node));
}
// |parent_combobox_| needs to be destroyed before |parent_model_| as it
// uses |parent_model_| in its destructor.
delete parent_combobox_;
}
views::View* BookmarkBubbleView::GetInitiallyFocusedView() {
return title_tf_;
}
void BookmarkBubbleView::WindowClosing() {
// We have to reset |bubble_| here, not in our destructor, because we'll be
// destroyed asynchronously and the shown state will be checked before then.
DCHECK_EQ(bookmark_bubble_, this);
bookmark_bubble_ = NULL;
if (observer_)
observer_->OnBookmarkBubbleHidden();
}
bool BookmarkBubbleView::AcceleratorPressed(
const ui::Accelerator& accelerator) {
if (accelerator.key_code() == ui::VKEY_RETURN) {
if (edit_button_->HasFocus())
HandleButtonPressed(edit_button_);
else
HandleButtonPressed(close_button_);
return true;
} else if (accelerator.key_code() == ui::VKEY_ESCAPE) {
remove_bookmark_ = newly_bookmarked_;
apply_edits_ = false;
}
return BubbleDelegateView::AcceleratorPressed(accelerator);
}
void BookmarkBubbleView::Init() {
views::Label* title_label = new views::Label(
l10n_util::GetStringUTF16(
newly_bookmarked_ ? IDS_BOOKMARK_BUBBLE_PAGE_BOOKMARKED :
IDS_BOOKMARK_BUBBLE_PAGE_BOOKMARK));
ui::ResourceBundle* rb = &ui::ResourceBundle::GetSharedInstance();
title_label->SetFontList(rb->GetFontList(ui::ResourceBundle::MediumFont));
remove_button_ = new views::LabelButton(this, l10n_util::GetStringUTF16(
IDS_BOOKMARK_BUBBLE_REMOVE_BOOKMARK));
remove_button_->SetStyle(views::Button::STYLE_BUTTON);
edit_button_ = new views::LabelButton(
this, l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_OPTIONS));
edit_button_->SetStyle(views::Button::STYLE_BUTTON);
close_button_ = new views::LabelButton(
this, l10n_util::GetStringUTF16(IDS_DONE));
close_button_->SetStyle(views::Button::STYLE_BUTTON);
close_button_->SetIsDefault(true);
views::Label* combobox_label = new views::Label(
l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_FOLDER_TEXT));
parent_combobox_ = new UnsizedCombobox(&parent_model_);
parent_combobox_->set_listener(this);
parent_combobox_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_BOOKMARK_AX_BUBBLE_FOLDER_TEXT));
GridLayout* layout = new GridLayout(this);
SetLayoutManager(layout);
// Column sets used in the layout of the bubble.
enum ColumnSetID {
TITLE_COLUMN_SET_ID,
CONTENT_COLUMN_SET_ID,
SYNC_PROMO_COLUMN_SET_ID
};
ColumnSet* cs = layout->AddColumnSet(TITLE_COLUMN_SET_ID);
cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
cs->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::USE_PREF,
0, 0);
cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
// The column layout used for middle and bottom rows.
cs = layout->AddColumnSet(CONTENT_COLUMN_SET_ID);
cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
cs->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, views::kUnrelatedControlHorizontalSpacing);
cs->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(1, views::kUnrelatedControlLargeHorizontalSpacing);
cs->AddColumn(GridLayout::LEADING, GridLayout::TRAILING, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, views::kRelatedButtonHSpacing);
cs->AddColumn(GridLayout::LEADING, GridLayout::TRAILING, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
layout->StartRow(0, TITLE_COLUMN_SET_ID);
layout->AddView(title_label);
layout->AddPaddingRow(0, views::kUnrelatedControlHorizontalSpacing);
layout->StartRow(0, CONTENT_COLUMN_SET_ID);
views::Label* label = new views::Label(
l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_TITLE_TEXT));
layout->AddView(label);
title_tf_ = new views::Textfield();
title_tf_->SetText(GetTitle());
title_tf_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_BOOKMARK_AX_BUBBLE_TITLE_TEXT));
layout->AddView(title_tf_, 5, 1);
layout->AddPaddingRow(0, views::kUnrelatedControlHorizontalSpacing);
layout->StartRow(0, CONTENT_COLUMN_SET_ID);
layout->AddView(combobox_label);
layout->AddView(parent_combobox_, 5, 1);
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
layout->StartRow(0, CONTENT_COLUMN_SET_ID);
layout->SkipColumns(2);
layout->AddView(remove_button_);
layout->AddView(edit_button_);
layout->AddView(close_button_);
layout->AddPaddingRow(
0,
views::kUnrelatedControlVerticalSpacing - kControlBorderWidth);
if (SyncPromoUI::ShouldShowSyncPromo(profile_)) {
// The column layout used for the sync promo.
cs = layout->AddColumnSet(SYNC_PROMO_COLUMN_SET_ID);
cs->AddColumn(GridLayout::FILL,
GridLayout::FILL,
1,
GridLayout::USE_PREF,
0,
0);
layout->StartRow(0, SYNC_PROMO_COLUMN_SET_ID);
sync_promo_view_ = new BookmarkSyncPromoView(delegate_.get());
layout->AddView(sync_promo_view_);
}
AddAccelerator(ui::Accelerator(ui::VKEY_RETURN, ui::EF_NONE));
}
BookmarkBubbleView::BookmarkBubbleView(
views::View* anchor_view,
BookmarkBubbleViewObserver* observer,
scoped_ptr<BookmarkBubbleDelegate> delegate,
Profile* profile,
const GURL& url,
bool newly_bookmarked)
: BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_RIGHT),
observer_(observer),
delegate_(delegate.Pass()),
profile_(profile),
url_(url),
newly_bookmarked_(newly_bookmarked),
parent_model_(
BookmarkModelFactory::GetForProfile(profile_),
BookmarkModelFactory::GetForProfile(profile_)->
GetMostRecentlyAddedUserNodeForURL(url)),
remove_button_(NULL),
edit_button_(NULL),
close_button_(NULL),
title_tf_(NULL),
parent_combobox_(NULL),
sync_promo_view_(NULL),
remove_bookmark_(false),
apply_edits_(true) {
set_margins(gfx::Insets(views::kPanelVertMargin, 0, 0, 0));
// Compensate for built-in vertical padding in the anchor view's image.
set_anchor_view_insets(gfx::Insets(2, 0, 2, 0));
}
base::string16 BookmarkBubbleView::GetTitle() {
BookmarkModel* bookmark_model =
BookmarkModelFactory::GetForProfile(profile_);
const BookmarkNode* node =
bookmark_model->GetMostRecentlyAddedUserNodeForURL(url_);
if (node)
return node->GetTitle();
else
NOTREACHED();
return base::string16();
}
void BookmarkBubbleView::GetAccessibleState(ui::AXViewState* state) {
BubbleDelegateView::GetAccessibleState(state);
state->name =
l10n_util::GetStringUTF16(
newly_bookmarked_ ? IDS_BOOKMARK_BUBBLE_PAGE_BOOKMARKED :
IDS_BOOKMARK_AX_BUBBLE_PAGE_BOOKMARK);
}
void BookmarkBubbleView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
HandleButtonPressed(sender);
}
void BookmarkBubbleView::OnPerformAction(views::Combobox* combobox) {
if (combobox->selected_index() + 1 == parent_model_.GetItemCount()) {
content::RecordAction(UserMetricsAction("BookmarkBubble_EditFromCombobox"));
ShowEditor();
}
}
void BookmarkBubbleView::HandleButtonPressed(views::Button* sender) {
if (sender == remove_button_) {
content::RecordAction(UserMetricsAction("BookmarkBubble_Unstar"));
// Set this so we remove the bookmark after the window closes.
remove_bookmark_ = true;
apply_edits_ = false;
GetWidget()->Close();
} else if (sender == edit_button_) {
content::RecordAction(UserMetricsAction("BookmarkBubble_Edit"));
ShowEditor();
} else {
DCHECK_EQ(close_button_, sender);
GetWidget()->Close();
}
}
void BookmarkBubbleView::ShowEditor() {
const BookmarkNode* node = BookmarkModelFactory::GetForProfile(
profile_)->GetMostRecentlyAddedUserNodeForURL(url_);
views::Widget* parent = anchor_widget();
DCHECK(parent);
Profile* profile = profile_;
ApplyEdits();
GetWidget()->Close();
if (node && parent)
BookmarkEditor::Show(parent->GetNativeWindow(), profile,
BookmarkEditor::EditDetails::EditNode(node),
BookmarkEditor::SHOW_TREE);
}
void BookmarkBubbleView::ApplyEdits() {
// Set this to make sure we don't attempt to apply edits again.
apply_edits_ = false;
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
const BookmarkNode* node = model->GetMostRecentlyAddedUserNodeForURL(url_);
if (node) {
const base::string16 new_title = title_tf_->text();
if (new_title != node->GetTitle()) {
model->SetTitle(node, new_title);
content::RecordAction(
UserMetricsAction("BookmarkBubble_ChangeTitleInBubble"));
}
parent_model_.MaybeChangeParent(node, parent_combobox_->selected_index());
}
}
<commit_msg>Views: Implement keyboard shortcuts for the remove and edit button in the bookmark bubble.<commit_after>// Copyright (c) 2012 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 "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/bookmarks/bookmark_editor.h"
#include "chrome/browser/ui/sync/sync_promo_ui.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view_observer.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_sync_promo_view.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/browser/bookmark_utils.h"
#include "content/public/browser/user_metrics.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/accessibility/ax_view_state.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/link.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
using base::UserMetricsAction;
using views::ColumnSet;
using views::GridLayout;
namespace {
// Width of the border of a button.
const int kControlBorderWidth = 2;
// This combobox prevents any lengthy content from stretching the bubble view.
class UnsizedCombobox : public views::Combobox {
public:
explicit UnsizedCombobox(ui::ComboboxModel* model) : views::Combobox(model) {}
virtual ~UnsizedCombobox() {}
virtual gfx::Size GetPreferredSize() const OVERRIDE {
return gfx::Size(0, views::Combobox::GetPreferredSize().height());
}
private:
DISALLOW_COPY_AND_ASSIGN(UnsizedCombobox);
};
} // namespace
BookmarkBubbleView* BookmarkBubbleView::bookmark_bubble_ = NULL;
// static
void BookmarkBubbleView::ShowBubble(views::View* anchor_view,
BookmarkBubbleViewObserver* observer,
scoped_ptr<BookmarkBubbleDelegate> delegate,
Profile* profile,
const GURL& url,
bool newly_bookmarked) {
if (IsShowing())
return;
bookmark_bubble_ = new BookmarkBubbleView(anchor_view,
observer,
delegate.Pass(),
profile,
url,
newly_bookmarked);
views::BubbleDelegateView::CreateBubble(bookmark_bubble_)->Show();
// Select the entire title textfield contents when the bubble is first shown.
bookmark_bubble_->title_tf_->SelectAll(true);
bookmark_bubble_->SetArrowPaintType(views::BubbleBorder::PAINT_NONE);
if (bookmark_bubble_->observer_)
bookmark_bubble_->observer_->OnBookmarkBubbleShown(url);
}
// static
bool BookmarkBubbleView::IsShowing() {
return bookmark_bubble_ != NULL;
}
void BookmarkBubbleView::Hide() {
if (IsShowing())
bookmark_bubble_->GetWidget()->Close();
}
BookmarkBubbleView::~BookmarkBubbleView() {
if (apply_edits_) {
ApplyEdits();
} else if (remove_bookmark_) {
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
const BookmarkNode* node = model->GetMostRecentlyAddedUserNodeForURL(url_);
if (node)
model->Remove(node->parent(), node->parent()->GetIndexOf(node));
}
// |parent_combobox_| needs to be destroyed before |parent_model_| as it
// uses |parent_model_| in its destructor.
delete parent_combobox_;
}
views::View* BookmarkBubbleView::GetInitiallyFocusedView() {
return title_tf_;
}
void BookmarkBubbleView::WindowClosing() {
// We have to reset |bubble_| here, not in our destructor, because we'll be
// destroyed asynchronously and the shown state will be checked before then.
DCHECK_EQ(bookmark_bubble_, this);
bookmark_bubble_ = NULL;
if (observer_)
observer_->OnBookmarkBubbleHidden();
}
bool BookmarkBubbleView::AcceleratorPressed(
const ui::Accelerator& accelerator) {
ui::KeyboardCode key_code = accelerator.key_code();
if (key_code == ui::VKEY_RETURN) {
HandleButtonPressed(close_button_);
return true;
}
if (key_code == ui::VKEY_E && accelerator.IsAltDown()) {
HandleButtonPressed(edit_button_);
return true;
}
if (key_code == ui::VKEY_R && accelerator.IsAltDown()) {
HandleButtonPressed(remove_button_);
return true;
}
if (key_code == ui::VKEY_ESCAPE) {
remove_bookmark_ = newly_bookmarked_;
apply_edits_ = false;
}
return BubbleDelegateView::AcceleratorPressed(accelerator);
}
void BookmarkBubbleView::Init() {
views::Label* title_label = new views::Label(
l10n_util::GetStringUTF16(
newly_bookmarked_ ? IDS_BOOKMARK_BUBBLE_PAGE_BOOKMARKED :
IDS_BOOKMARK_BUBBLE_PAGE_BOOKMARK));
ui::ResourceBundle* rb = &ui::ResourceBundle::GetSharedInstance();
title_label->SetFontList(rb->GetFontList(ui::ResourceBundle::MediumFont));
remove_button_ = new views::LabelButton(this, l10n_util::GetStringUTF16(
IDS_BOOKMARK_BUBBLE_REMOVE_BOOKMARK));
remove_button_->SetStyle(views::Button::STYLE_BUTTON);
edit_button_ = new views::LabelButton(
this, l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_OPTIONS));
edit_button_->SetStyle(views::Button::STYLE_BUTTON);
close_button_ = new views::LabelButton(
this, l10n_util::GetStringUTF16(IDS_DONE));
close_button_->SetStyle(views::Button::STYLE_BUTTON);
close_button_->SetIsDefault(true);
views::Label* combobox_label = new views::Label(
l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_FOLDER_TEXT));
parent_combobox_ = new UnsizedCombobox(&parent_model_);
parent_combobox_->set_listener(this);
parent_combobox_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_BOOKMARK_AX_BUBBLE_FOLDER_TEXT));
GridLayout* layout = new GridLayout(this);
SetLayoutManager(layout);
// Column sets used in the layout of the bubble.
enum ColumnSetID {
TITLE_COLUMN_SET_ID,
CONTENT_COLUMN_SET_ID,
SYNC_PROMO_COLUMN_SET_ID
};
ColumnSet* cs = layout->AddColumnSet(TITLE_COLUMN_SET_ID);
cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
cs->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::USE_PREF,
0, 0);
cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
// The column layout used for middle and bottom rows.
cs = layout->AddColumnSet(CONTENT_COLUMN_SET_ID);
cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
cs->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, views::kUnrelatedControlHorizontalSpacing);
cs->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(1, views::kUnrelatedControlLargeHorizontalSpacing);
cs->AddColumn(GridLayout::LEADING, GridLayout::TRAILING, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, views::kRelatedButtonHSpacing);
cs->AddColumn(GridLayout::LEADING, GridLayout::TRAILING, 0,
GridLayout::USE_PREF, 0, 0);
cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
layout->StartRow(0, TITLE_COLUMN_SET_ID);
layout->AddView(title_label);
layout->AddPaddingRow(0, views::kUnrelatedControlHorizontalSpacing);
layout->StartRow(0, CONTENT_COLUMN_SET_ID);
views::Label* label = new views::Label(
l10n_util::GetStringUTF16(IDS_BOOKMARK_BUBBLE_TITLE_TEXT));
layout->AddView(label);
title_tf_ = new views::Textfield();
title_tf_->SetText(GetTitle());
title_tf_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_BOOKMARK_AX_BUBBLE_TITLE_TEXT));
layout->AddView(title_tf_, 5, 1);
layout->AddPaddingRow(0, views::kUnrelatedControlHorizontalSpacing);
layout->StartRow(0, CONTENT_COLUMN_SET_ID);
layout->AddView(combobox_label);
layout->AddView(parent_combobox_, 5, 1);
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
layout->StartRow(0, CONTENT_COLUMN_SET_ID);
layout->SkipColumns(2);
layout->AddView(remove_button_);
layout->AddView(edit_button_);
layout->AddView(close_button_);
layout->AddPaddingRow(
0,
views::kUnrelatedControlVerticalSpacing - kControlBorderWidth);
if (SyncPromoUI::ShouldShowSyncPromo(profile_)) {
// The column layout used for the sync promo.
cs = layout->AddColumnSet(SYNC_PROMO_COLUMN_SET_ID);
cs->AddColumn(GridLayout::FILL,
GridLayout::FILL,
1,
GridLayout::USE_PREF,
0,
0);
layout->StartRow(0, SYNC_PROMO_COLUMN_SET_ID);
sync_promo_view_ = new BookmarkSyncPromoView(delegate_.get());
layout->AddView(sync_promo_view_);
}
AddAccelerator(ui::Accelerator(ui::VKEY_RETURN, ui::EF_NONE));
AddAccelerator(ui::Accelerator(ui::VKEY_E, ui::EF_ALT_DOWN));
AddAccelerator(ui::Accelerator(ui::VKEY_R, ui::EF_ALT_DOWN));
}
BookmarkBubbleView::BookmarkBubbleView(
views::View* anchor_view,
BookmarkBubbleViewObserver* observer,
scoped_ptr<BookmarkBubbleDelegate> delegate,
Profile* profile,
const GURL& url,
bool newly_bookmarked)
: BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_RIGHT),
observer_(observer),
delegate_(delegate.Pass()),
profile_(profile),
url_(url),
newly_bookmarked_(newly_bookmarked),
parent_model_(
BookmarkModelFactory::GetForProfile(profile_),
BookmarkModelFactory::GetForProfile(profile_)->
GetMostRecentlyAddedUserNodeForURL(url)),
remove_button_(NULL),
edit_button_(NULL),
close_button_(NULL),
title_tf_(NULL),
parent_combobox_(NULL),
sync_promo_view_(NULL),
remove_bookmark_(false),
apply_edits_(true) {
set_margins(gfx::Insets(views::kPanelVertMargin, 0, 0, 0));
// Compensate for built-in vertical padding in the anchor view's image.
set_anchor_view_insets(gfx::Insets(2, 0, 2, 0));
}
base::string16 BookmarkBubbleView::GetTitle() {
BookmarkModel* bookmark_model =
BookmarkModelFactory::GetForProfile(profile_);
const BookmarkNode* node =
bookmark_model->GetMostRecentlyAddedUserNodeForURL(url_);
if (node)
return node->GetTitle();
else
NOTREACHED();
return base::string16();
}
void BookmarkBubbleView::GetAccessibleState(ui::AXViewState* state) {
BubbleDelegateView::GetAccessibleState(state);
state->name =
l10n_util::GetStringUTF16(
newly_bookmarked_ ? IDS_BOOKMARK_BUBBLE_PAGE_BOOKMARKED :
IDS_BOOKMARK_AX_BUBBLE_PAGE_BOOKMARK);
}
void BookmarkBubbleView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
HandleButtonPressed(sender);
}
void BookmarkBubbleView::OnPerformAction(views::Combobox* combobox) {
if (combobox->selected_index() + 1 == parent_model_.GetItemCount()) {
content::RecordAction(UserMetricsAction("BookmarkBubble_EditFromCombobox"));
ShowEditor();
}
}
void BookmarkBubbleView::HandleButtonPressed(views::Button* sender) {
if (sender == remove_button_) {
content::RecordAction(UserMetricsAction("BookmarkBubble_Unstar"));
// Set this so we remove the bookmark after the window closes.
remove_bookmark_ = true;
apply_edits_ = false;
GetWidget()->Close();
} else if (sender == edit_button_) {
content::RecordAction(UserMetricsAction("BookmarkBubble_Edit"));
ShowEditor();
} else {
DCHECK_EQ(close_button_, sender);
GetWidget()->Close();
}
}
void BookmarkBubbleView::ShowEditor() {
const BookmarkNode* node = BookmarkModelFactory::GetForProfile(
profile_)->GetMostRecentlyAddedUserNodeForURL(url_);
views::Widget* parent = anchor_widget();
DCHECK(parent);
Profile* profile = profile_;
ApplyEdits();
GetWidget()->Close();
if (node && parent)
BookmarkEditor::Show(parent->GetNativeWindow(), profile,
BookmarkEditor::EditDetails::EditNode(node),
BookmarkEditor::SHOW_TREE);
}
void BookmarkBubbleView::ApplyEdits() {
// Set this to make sure we don't attempt to apply edits again.
apply_edits_ = false;
BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
const BookmarkNode* node = model->GetMostRecentlyAddedUserNodeForURL(url_);
if (node) {
const base::string16 new_title = title_tf_->text();
if (new_title != node->GetTitle()) {
model->SetTitle(node, new_title);
content::RecordAction(
UserMetricsAction("BookmarkBubble_ChangeTitleInBubble"));
}
parent_model_.MaybeChangeParent(node, parent_combobox_->selected_index());
}
}
<|endoftext|> |
<commit_before>#define _POSIX_C_SOURCE 1
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <typeinfo>
#include "timer.h"
#include "trie.h"
#include "signatures.h"
/** Starting with demo-only includes. **/
#include "../mp_dpi_api.h"
#include <pcap.h>
#include <netinet/in.h>
#include <net/ethernet.h>
#include <stdint.h>
#include <ff/mapping_utils.hpp>
#include <ff/utils.hpp>
#include <ff/ubuffer.hpp>
// #define USE_PF_RING_CLUSTER 1
#define ALARM_SLEEP 1
#include <time.h>
#include <signal.h>
#include <pfring.h>
using namespace antivirus;
#define CAPACITY_CHUNK 1000
#define SCANNER_POOL_SIZE 4096
#define CLOCK_FREQ 2000000000L
#define AVAILABLE_CORES 16
static u_int16_t mapping[AVAILABLE_CORES]=
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
static struct timeval startTime;
unsigned long long numPkts = 0, numBytes = 0;
pfring *ring;
ff::SWSR_Ptr_Buffer *pkt_buff;
int verbose = 0;
static ff::uSWSR_Ptr_Buffer* scanner_pool;
dpi_mp_packet_reading_result_t reading_cb(void* user_data){
static unsigned long last_ts=getticks();
static u_int32_t last_sec=0;
#ifdef USE_PF_RING_CLUSTER
pfring_pkt_buff *pkt_handle = NULL;
#else
void *pkt_handle;
#endif
struct pfring_pkthdr hdr;
int rc;
if(numPkts == 0) gettimeofday(&startTime, NULL);
if(pkt_buff->empty()) {
printf("Not enough buffer available: please start over\n");
exit(-1);
}
pkt_buff->pop(&pkt_handle);
if(verbose) printf("pkt_buff->pop()\n");
while(1) {
#ifdef USE_PF_RING_CLUSTER
rc = pfring_recv_pkt_buff(ring, pkt_handle, &hdr, 1);
#else
rc = pfring_recv(ring, (u_char**)&pkt_handle, 1500, &hdr, 1);
#endif
if(rc < 0) {
printf("pfring_recv_pkt_buff() returned %d\n", rc);
exit(-1);
} else if(rc == 0) {
continue;
} else {
dpi_mp_packet_reading_result_t r;
const unsigned char *p = (const unsigned char*)pkt_handle;
r.pkt = &p[14];
if(getticks()-last_ts>CLOCK_FREQ){
last_ts = getticks();
++last_sec;
}
r.current_time=last_sec;
r.length=hdr.caplen-14;
r.user_pointer=pkt_handle;
numPkts++, numBytes += hdr.len;
return r;
}
} /* while */
}
void processing_cb(mp_dpi_processing_result_t* processing_result, void* user_data){
pkt_buff->push((void*)processing_result->user_pointer);
if(verbose) printf("pkt_buff->push()\n");
}
static void match_found(string::size_type position,
trie::value_type const &match){
using namespace std;
cout << "Matched '" << match.second << "' at " << position << endl;
}
void body_cb(dpi_http_message_informations_t* http_informations,
const u_char* app_data, u_int32_t data_length,
dpi_pkt_infos_t* pkt,
void** flow_specific_user_data, void* user_data,
u_int8_t last){
if(*flow_specific_user_data==NULL){
if(scanner_pool->mc_pop(flow_specific_user_data)==false){
*flow_specific_user_data=
new byte_scanner(*((trie*) user_data), match_found);
}
}
byte_scanner* scanner=(byte_scanner*) (*flow_specific_user_data);
for(u_int32_t i=0; i<data_length; i++){
scanner->match(app_data[i]);
}
}
void flow_cleaner(void* flow_specific_user_data){
if(scanner_pool->mp_push(flow_specific_user_data)==false){
delete (byte_scanner*) flow_specific_user_data;
}
}
/*
* The time difference in millisecond
*/
double delta_time (struct timeval * now,
struct timeval * before) {
time_t delta_seconds;
time_t delta_microseconds;
/*
* compute delta in second, 1/10's and 1/1000's second units
*/
delta_seconds = now -> tv_sec - before -> tv_sec;
delta_microseconds = now -> tv_usec - before -> tv_usec;
if(delta_microseconds < 0) {
/* manually carry a one from the seconds field */
delta_microseconds += 1000000; /* 1e6 */
-- delta_seconds;
}
return((double)(delta_seconds * 1000) + (double)delta_microseconds/1000);
}
void print_stats() {
pfring_stat pfringStat;
struct timeval endTime;
double deltaMillisec;
static u_int64_t lastPkts = 0;
u_int64_t diff;
static struct timeval lastTime;
if(startTime.tv_sec == 0) return;
gettimeofday(&endTime, NULL);
deltaMillisec = delta_time(&endTime, &startTime);
if(pfring_stats(ring, &pfringStat) >= 0)
fprintf(stderr, "=========================\n"
"Absolute Stats: [%u pkts rcvd][%u pkts dropped]\n"
"Total Pkts=%u/Dropped=%.1f %%\n",
(unsigned int)pfringStat.recv, (unsigned int)pfringStat.drop,
(unsigned int)(pfringStat.recv-pfringStat.drop),
pfringStat.recv == 0 ? 0 : (double)(pfringStat.drop*100)/(double)pfringStat.recv);
fprintf(stderr, "%llu pkts [%.1f pkt/sec] - %llu bytes [%.2f Mbit/sec]\n",
numPkts, (double)(numPkts*1000)/deltaMillisec,
numBytes, (double)8*numBytes/(double)(deltaMillisec));
if(lastTime.tv_sec > 0) {
deltaMillisec = delta_time(&endTime, &lastTime);
diff = pfringStat.recv-lastPkts;
fprintf(stderr, "=========================\n"
"Actual Stats: %llu pkts [%.1f ms][%.1f pkt/sec]\n",
(long long unsigned int)diff, deltaMillisec,
((double)diff/(double)(deltaMillisec/1000)));
}
lastPkts = pfringStat.recv;
lastTime.tv_sec = endTime.tv_sec, lastTime.tv_usec = endTime.tv_usec;
fprintf(stderr, "=========================\n");
}
/* ******************************** */
void sigproc(int sig) {
static int called = 0;
if(called) return; else called = 1;
print_stats();
pfring_close(ring);
exit(0);
}
void my_sigalarm(int sig) {
print_stats();
printf("\n");
alarm(ALARM_SLEEP);
signal(SIGALRM, my_sigalarm);
}
int main(int argc, char **argv){
using namespace std;
ff_mapThreadToCpu(mapping[0], -20);
try {
if (argc<4){
cerr << "Usage: " << argv[0] <<
" virus-signatures-file device "
"par_degree\n";
exit(EXIT_FAILURE);
}
string::size_type trie_depth=DEFAULT_TRIE_MAXIMUM_DEPTH;
char const *virus_signatures_file_name=argv[1];
char const *devide=argv[2];
u_int16_t num_workers=atoi(argv[3]);
ifstream signatures;
signatures.open(virus_signatures_file_name);
if(!signatures){
cerr << argv[0] << ": failed to open '" <<
virus_signatures_file_name << "'\n";
exit(EXIT_FAILURE);
}
signature_reader reader(signatures);
cout << "reading '" << virus_signatures_file_name << "'... ";
timer read_signatures_timer;
read_signatures_timer.start();
trie t(trie_depth);
while (reader.next()) {
t.insert(make_pair(reader.current_pattern(),
reader.current_name()));
}
read_signatures_timer.stop();
cout << setiosflags(ios_base::fixed) << setprecision(3) <<
read_signatures_timer.real_time() << " seconds.\n";
cout << "preparing '" << virus_signatures_file_name << "'... ";
timer prepare_signatures_timer;
prepare_signatures_timer.start();
t.prepare();
prepare_signatures_timer.stop();
cout << setiosflags(ios_base::fixed)
<< setprecision(3)
<< prepare_signatures_timer.real_time() << " seconds.\n";
cout << "# of allocated trie nodes: " << t.node_count() << endl;
timer full_timer;
full_timer.start();
/******************************************************/
/* Start scanning the files. */
/******************************************************/
dpi_mp_parallelism_details_t details;
bzero(&details, sizeof(dpi_mp_parallelism_details_t));
details.available_processors=AVAILABLE_CORES;
details.mapping=mapping;
details.single_farm_num_workers=num_workers;
dpi_mp_library_state_t* state=mp_dpi_init_stateful(
32767, 32767, 1000000, 1000000, details);
int num_pkt_buffers = 32768;
int snaplen = 1500, flags = PF_RING_PROMISC;
ring = pfring_open(device, snaplen, flags);
if(ring==NULL){
fprintf(stderr, "Couldn't open device %s\n", argv[1]);
return (2);
}
scanner_pool=new ff::uSWSR_Ptr_Buffer(SCANNER_POOL_SIZE);
scanner_pool->init();
for(uint i=0; i<SCANNER_POOL_SIZE; i++){
scanner_pool->push(new byte_scanner(t, match_found));
}
mp_dpi_set_read_and_process_callbacks(
state, &reading_cb, &processing_cb, (void*) &x);
mp_dpi_set_flow_cleaner_callback(state, &flow_cleaner);
dpi_http_callbacks_t callback={0, 0, 0, 0, 0, &body_cb};
mp_dpi_http_activate_callbacks(state, &callback, (void*)(&t));
pkt_buff = new ff::SWSR_Ptr_Buffer(num_pkt_buffers);
if(pkt_buff == NULL) {
printf("SWSR_Ptr_Buffer() failed\n");
return(-1);
}
pkt_buff->init();
for(int i=0; i<num_pkt_buffers; i++) {
#ifdef USE_PF_RING_CLUSTER
pfring_pkt_buff *pkt_handle;
if((pkt_handle = pfring_alloc_pkt_buff(ring)) == NULL) {
printf("Error allocating pkt buff\n");
return(-1);
} else
pkt_buff->push(pkt_handle);
#else
pkt_buff->push(malloc(1500));
if(verbose) printf("pkt_buff->push() empty buffer\n");
#endif
}
signal(SIGINT, sigproc);
signal(SIGALRM, my_sigalarm);
alarm(ALARM_SLEEP);
pfring_enable_ring(ring);
timer scan_timer;
scan_timer.start();
mp_dpi_run(state);
mp_dpi_wait_end(state);
mp_dpi_print_stats(state);
scan_timer.stop();
byte_scanner* bs;
while(!scanner_pool->empty()){
scanner_pool->pop((void**) &bs);
delete bs;
}
/* And close the session */
mp_dpi_terminate(state);
delete scanner_pool;
full_timer.stop();
cout << "Completion time: "
<< setiosflags(ios_base::fixed) << setprecision(3)
<< full_timer.real_time() << " seconds.\n";
u_int32_t i;
exit(EXIT_SUCCESS);
}catch(exception const &ex){
cout.flush();
cerr << typeid(ex).name() << " exception: " << ex.what() << "\n";
throw;
}
}
<commit_msg>Added PF_RING demo<commit_after>/*
* http_pm_mc_pfring.cc
*
* This demo application analyzes the HTTP traffic (reordering the TCP packets to have
* a well-formed stream), and searches for specific patterns (contained into a file
* specified by a command line parameter) inside the HTTP body.
* The traffic is captured by using PF_RING (low latency network capture mechanism).
*
* Over high bandwidth networks, getting the timestamp for each received packet
* could have a very negative impact over the bandwidth of the application. In order
* to have low latency timestamping, in this example we perform it by reading the
* CPU clock. To correctly perform this kind of timestamping the macro
* CLOCK_FREQ must be set with the correct CPU frequency (in Hz) and the
* 'cpu-freq' tool should be used to set the CPU frequency manager to 'performance'.
*
* For low bandwidth networks this is not really needed and time(NULL) or gettimeofday
* can be used for timestamping.
*
* Created on: 29/08/2013
*
* =========================================================================
* Copyright (C) 2012-2013, Daniele De Sensi ([email protected])
*
* This file is part of Peafowl.
*
* Peafowl is free software: you can redistribute it and/or
* modify it under the terms of the Lesser GNU General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
* Peafowl 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public
* License along with Peafowl.
* If not, see <http://www.gnu.org/licenses/>.
*
* =========================================================================
*/
#define _POSIX_C_SOURCE 1
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <typeinfo>
#include "pattern_matching_lib/timer.h"
#include "pattern_matching_lib/trie.h"
#include "pattern_matching_lib/signatures.h"
/** Starting with demo-only includes. **/
#include <mc_api.h>
#include <pcap.h>
#include <netinet/in.h>
#include <net/ethernet.h>
#include <stdint.h>
#include <ff/mapping_utils.hpp>
#include <ff/utils.hpp>
#include <ff/ubuffer.hpp>
// #define USE_PF_RING_CLUSTER 1
#define ALARM_SLEEP 10 //Interval (seconds) between two successive stats print
#include <time.h>
#include <signal.h>
extern "C" {
#include <pfring.h>
}
using namespace antivirus;
#define CAPACITY_CHUNK 1000
#define SCANNER_POOL_SIZE 8192 //4096
#define CLOCK_FREQ 2000000000L
#define TEST_DURATION_SECS 120
#define SNAPLEN 2000
#define AVAILABLE_CORES 16
static u_int16_t mapping[AVAILABLE_CORES]=
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
static struct timeval startTime;
u_int64_t numPkts = 0, numBytes = 0;
pfring *ring;
ff::SWSR_Ptr_Buffer *pkt_buff;
int verbose = 0;
unsigned long num_pkt_buffers = 128000;
//unsigned long num_pkt_buffers = 32000;
static ff::uSWSR_Ptr_Buffer* scanner_pool;
mc_dpi_packet_reading_result_t reading_cb(void* user_data){
static unsigned long last_ts=getticks();
static u_int32_t last_sec=0;
#ifdef USE_PF_RING_CLUSTER
pfring_pkt_buff *pkt_handle = NULL;
#else
void *pkt_handle;
#endif
struct pfring_pkthdr hdr;
int rc;
if(numPkts == 0) gettimeofday(&startTime, NULL);
while(pkt_buff->empty()){;}
/**
if(pkt_buff->empty()) {
printf("Not enough buffer available: please start over\n");
exit(-1);
}
**/
pkt_buff->pop(&pkt_handle);
if(verbose) printf("pkt_buff->pop()\n");
while(1) {
#ifdef USE_PF_RING_CLUSTER
rc = pfring_recv_pkt_buff(ring, pkt_handle, &hdr, 1);
#else
rc = pfring_recv(ring, (u_char**)&pkt_handle, SNAPLEN, &hdr, 1);
#endif
if(rc < 0) {
printf("pfring_recv_pkt_buff() returned %d\n", rc);
exit(-1);
} else if(rc == 0) {
continue;
} else {
mc_dpi_packet_reading_result_t r;
const unsigned char *p = (const unsigned char*)pkt_handle;
r.pkt = &p[14];
if(getticks()-last_ts>CLOCK_FREQ){
last_ts = getticks();
++last_sec;
}
r.current_time=last_sec;
r.length=hdr.caplen-14;
r.user_pointer=pkt_handle;
numPkts++, numBytes += r.length; // hdr.len;
return r;
}
} /* while */
}
void processing_cb(mc_dpi_processing_result_t* processing_result, void* user_data){
pkt_buff->push((void*)processing_result->user_pointer);
if(verbose) printf("pkt_buff->push()\n");
}
static void match_found(string::size_type position,
trie::value_type const &match){
using namespace std;
cout << "Matched '" << match.second << "' at " << position << endl;
}
void body_cb(dpi_http_message_informations_t* http_informations,
const u_char* app_data, u_int32_t data_length,
dpi_pkt_infos_t* pkt,
void** flow_specific_user_data, void* user_data,
u_int8_t last){
if(*flow_specific_user_data==NULL){
if(scanner_pool->mc_pop(flow_specific_user_data)==false){
*flow_specific_user_data=
new byte_scanner(*((trie*) user_data), match_found);
}
}
byte_scanner* scanner=(byte_scanner*) (*flow_specific_user_data);
for(u_int32_t i=0; i<data_length; i++){
scanner->match(app_data[i]);
}
}
void flow_cleaner(void* flow_specific_user_data){
if(scanner_pool->mp_push(flow_specific_user_data)==false){
delete (byte_scanner*) flow_specific_user_data;
}
}
/*
* The time difference in millisecond
*/
double delta_time (struct timeval * now,
struct timeval * before) {
time_t delta_seconds;
time_t delta_microseconds;
/*
* compute delta in second, 1/10's and 1/1000's second units
*/
delta_seconds = now -> tv_sec - before -> tv_sec;
delta_microseconds = now -> tv_usec - before -> tv_usec;
if(delta_microseconds < 0) {
/* manually carry a one from the seconds field */
delta_microseconds += 1000000; /* 1e6 */
-- delta_seconds;
}
return((double)(delta_seconds * 1000) + (double)delta_microseconds/1000);
}
void print_stats() {
pfring_stat pfringStat;
struct timeval endTime;
double deltaMillisecInterval, deltaMillisecSinceStart;
static u_int64_t lastPkts = 0;
static u_int64_t lastBytes = 0;
u_int64_t diffPkts, diffBytes;
static struct timeval lastTime;
if(startTime.tv_sec == 0) return;
gettimeofday(&endTime, NULL);
if(pfring_stats(ring, &pfringStat) >= 0){
fprintf(stderr,
"Absolute Stats: [%lu pkts rcvd][%lu pkts dropped]\n"
"Total Pkts=%lu/Dropped=%.1f %%\n",
(unsigned long)pfringStat.recv, (unsigned long)pfringStat.drop,
(unsigned long)(pfringStat.recv),
pfringStat.recv == 0 ? 0 : (double)(pfringStat.drop*100)/(double)(pfringStat.recv+pfringStat.drop));
}
if(lastTime.tv_sec > 0) {
deltaMillisecSinceStart = delta_time(&endTime, &startTime);
deltaMillisecInterval = delta_time(&endTime, &lastTime);
diffPkts = numPkts-lastPkts;
diffBytes = numBytes-lastBytes;
fprintf(stderr, "==================Average=====================\n"
"[%.1f pkt/sec][%.2f Gbit/sec]\n",
((double)(numPkts*1000)/(double)(deltaMillisecSinceStart)),
(double)8*numBytes/(double)(deltaMillisecSinceStart*1000000));
fprintf(stderr, "==================Current=====================\n"
"[%.1f pkt/sec][%.2f Gbit/sec]\n",
((double)(diffPkts*1000)/(double)(deltaMillisecInterval)),
(double)8*diffBytes/(double)(deltaMillisecInterval*1000000));
}
lastPkts = numPkts;
lastBytes = numBytes;
lastTime.tv_sec = endTime.tv_sec, lastTime.tv_usec = endTime.tv_usec;
fprintf(stderr, "==============================================\n");
if(deltaMillisecSinceStart/1000 > TEST_DURATION_SECS){
exit(-1);
}
}
/* ******************************** */
void sigproc(int sig) {
static int called = 0;
if(called) return; else called = 1;
print_stats();
pfring_close(ring);
exit(0);
}
void my_sigalarm(int sig) {
print_stats();
printf("\n");
alarm(ALARM_SLEEP);
signal(SIGALRM, my_sigalarm);
}
int main(int argc, char **argv){
using namespace std;
ff_mapThreadToCpu(mapping[0], -20);
try {
if (argc<4){
cerr << "Usage: " << argv[0] <<
" virus-signatures-file device "
"par_degree\n";
exit(EXIT_FAILURE);
}
string::size_type trie_depth=DEFAULT_TRIE_MAXIMUM_DEPTH;
char const *virus_signatures_file_name=argv[1];
char const *device=argv[2];
u_int16_t num_workers=atoi(argv[3]);
ifstream signatures;
signatures.open(virus_signatures_file_name);
if(!signatures){
cerr << argv[0] << ": failed to open '" <<
virus_signatures_file_name << "'\n";
exit(EXIT_FAILURE);
}
signature_reader reader(signatures);
cout << "reading '" << virus_signatures_file_name << "'... ";
timer read_signatures_timer;
read_signatures_timer.start();
trie t(trie_depth);
while (reader.next()) {
t.insert(make_pair(reader.current_pattern(),
reader.current_name()));
}
read_signatures_timer.stop();
cout << setiosflags(ios_base::fixed) << setprecision(3) <<
read_signatures_timer.real_time() << " seconds.\n";
cout << "preparing '" << virus_signatures_file_name << "'... ";
timer prepare_signatures_timer;
prepare_signatures_timer.start();
t.prepare();
prepare_signatures_timer.stop();
cout << setiosflags(ios_base::fixed)
<< setprecision(3)
<< prepare_signatures_timer.real_time() << " seconds.\n";
cout << "# of allocated trie nodes: " << t.node_count() << endl;
timer full_timer;
full_timer.start();
/******************************************************/
/* Start scanning the files. */
/******************************************************/
mc_dpi_parallelism_details_t details;
bzero(&details, sizeof(mc_dpi_parallelism_details_t));
details.available_processors=AVAILABLE_CORES;
details.mapping=mapping;
details.single_farm_num_workers=num_workers;
mc_dpi_library_state_t* state=mc_dpi_init_stateful(
32767, 32767, 1000000, 1000000, details);
int snaplen = SNAPLEN;
int flags = PF_RING_PROMISC;
ring = pfring_open(device, snaplen, flags);
if(ring==NULL){
fprintf(stderr, "Couldn't open device %s\n", argv[1]);
return (2);
}
pfring_set_direction(ring, rx_only_direction);
scanner_pool=new ff::uSWSR_Ptr_Buffer(SCANNER_POOL_SIZE, true);
scanner_pool->init();
for(uint i=0; i<SCANNER_POOL_SIZE; i++){
scanner_pool->push(new byte_scanner(t, match_found));
}
// mc_dpi_tcp_reordering_disable(state);
mc_dpi_set_read_and_process_callbacks(
state, &reading_cb, &processing_cb, (void*) NULL);
mc_dpi_set_flow_cleaner_callback(state, &flow_cleaner);
dpi_http_callbacks_t callback={0, 0, 0, 0, 0, &body_cb};
assert(mc_dpi_http_activate_callbacks(state, &callback, (void*)(&t))==DPI_STATE_UPDATE_SUCCESS);
pkt_buff = new ff::SWSR_Ptr_Buffer(num_pkt_buffers);
if(pkt_buff == NULL) {
printf("SWSR_Ptr_Buffer() failed\n");
return(-1);
}
pkt_buff->init();
for(int i=0; i<num_pkt_buffers; i++) {
#ifdef USE_PF_RING_CLUSTER
pfring_pkt_buff *pkt_handle;
if((pkt_handle = pfring_alloc_pkt_buff(ring)) == NULL) {
printf("Error allocating pkt buff\n");
return(-1);
} else
pkt_buff->push(pkt_handle);
#else
pkt_buff->push(malloc(SNAPLEN));
if(verbose) printf("pkt_buff->push() empty buffer\n");
#endif
}
signal(SIGINT, sigproc);
signal(SIGALRM, my_sigalarm);
alarm(ALARM_SLEEP);
pfring_enable_ring(ring);
timer scan_timer;
scan_timer.start();
mc_dpi_run(state);
mc_dpi_wait_end(state);
mc_dpi_print_stats(state);
scan_timer.stop();
byte_scanner* bs;
while(!scanner_pool->empty()){
scanner_pool->pop((void**) &bs);
delete bs;
}
/* And close the session */
mc_dpi_terminate(state);
delete scanner_pool;
full_timer.stop();
cout << "Completion time: "
<< setiosflags(ios_base::fixed) << setprecision(3)
<< full_timer.real_time() << " seconds.\n";
u_int32_t i;
exit(EXIT_SUCCESS);
}catch(exception const &ex){
cout.flush();
cerr << typeid(ex).name() << " exception: " << ex.what() << "\n";
throw;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 The University of Texas at Austin and the
* Institute of Human Machine Cognition. All rights reserved.
*
* This program 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. See
* <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>
*/
#include <controlit/robot_interface_library/RobotInterfaceSM.hpp>
#include <chrono>
#include <controlit/Command.hpp>
#include <controlit/RTControlModel.hpp>
#include <controlit/logging/RealTimeLogging.hpp>
#include <controlit/robot_interface_library/OdometryStateReceiverSM.hpp>
#include <controlit/addons/ros/ROSMsgToString.hpp>
namespace controlit {
namespace robot_interface_library {
// Uncomment one of the following lines to enable/disable detailed debug statements.
#define PRINT_INFO_STATEMENT(ss)
// #define PRINT_INFO_STATEMENT(ss) CONTROLIT_INFO << ss;
#define PRINT_INFO_STATEMENT_RT(ss)
// #define PRINT_INFO_STATEMENT_RT(ss) CONTROLIT_INFO_RT << ss;
#define PRINT_INFO_RT(ss)
// #define PRINT_INFO_RT(ss) CONTROLIT_INFO_RT << ss;
#define PRINT_INFO_STATEMENT_RT_ALWAYS(ss) CONTROLIT_INFO_RT << ss;
// #define PRINT_INFO_STATEMENT_RT_ALWAYS(ss) std::cout << ss << std::endl;
#define PRINT_RECEIVED_STATE 0
#define PRINT_COMMAND 0
// Parameters for shared memory subscribers
#define LISTEN_TO_ROS_TOPIC false
#define USE_POLLING false
RobotInterfaceSM::RobotInterfaceSM() :
RobotInterface(), // Call super-class' constructor
receivedRobotState(false),
robotStateSubscriber(LISTEN_TO_ROS_TOPIC, USE_POLLING),
rttRxSubscriber(LISTEN_TO_ROS_TOPIC, USE_POLLING),
rcvdJointState(false),
rcvdInitStateMsg(false),
rcvdInitRTTMsg(false),
rcvdFirstStateMsg(false),
rcvdFirstRTTMsg(false)
{
}
RobotInterfaceSM::~RobotInterfaceSM()
{
}
bool RobotInterfaceSM::init(ros::NodeHandle & nh, RTControlModel * model)
{
PRINT_INFO_STATEMENT("Method called!");
//---------------------------------------------------------------------------------
// Initialize the parent class. Abort if parent class fails to initialize.
//---------------------------------------------------------------------------------
if(!RobotInterface::init(nh, model))
{
CONTROLIT_ERROR_RT << "Super-class failed to initialize.";
return false;
}
//---------------------------------------------------------------------------------
// Initialize a torque command message that will be used to hold the torque
// command data.
//---------------------------------------------------------------------------------
const std::vector<std::string> & names = model->get()->getRealJointNamesVector();
PRINT_INFO_STATEMENT("Number of DoFs: " << names.size());
torqueCmdMsg.layout.dim.resize(names.size());
torqueCmdMsg.layout.dim[0].stride = names.size();
torqueCmdMsg.layout.dim[0].size = names.size();
torqueCmdMsg.layout.dim[1].stride = 1;
torqueCmdMsg.layout.dim[1].size = 1;
torqueCmdMsg.data.resize(names.size());
//---------------------------------------------------------------------------------
// Initialize the shared memory publshers and subscribers.
// There are two publishers:
//
// 1. command publisher on topic "/cmd"
// 2. seqno publisher on topic "/rtt_tx"
//
// There are two subscribers:
//
// 1. robot state subscriber on topic "/joint_states"
// 2. seqno receiver on topic "/rtt_rx"
//---------------------------------------------------------------------------------
cmdPublisher.advertise("/cmd");
rttTxPublisher.advertise("/rtt_tx");
rttRxSubscriber.subscribe("/rtt_rx", boost::bind(&RobotInterfaceSM::rttCallback, this, _1));
robotStateSubscriber.subscribe("/joint_states", boost::bind(&RobotInterfaceSM::jointStateCallback, this, _1));
// rttRxSubscriber.waitForMessage(rttRxMsg);
// robotStateSubscriber.waitForMessage(jointStateMsg);
// int checkCount = 0;
// while (!rttRxSubscriber.connected())
// {
// // if (checkCount++ < 300)
// // {
// // // ROS_WARN_THROTTLE(1.0, "Waiting for /rtt_rx shared memory topic.");
// // if (checkCount % 10 == 0)
// // {
// // CONTROLIT_WARN << "Waiting for shared memory topic /rtt_rx to be connected....";
// // }
// // std::this_thread::sleep_for(std::chrono::milliseconds(100));
// // }
// // else
// // {
// // CONTROLIT_ERROR << "Failed to subscribe to shared memory topic \"/rtt_rx\"!";
// // return false;
// // }
// }
// CONTROLIT_INFO << "Subscription to /rtt_rx connected.";
// checkCount = 0;
// while (!robotStateSubscriber.connected())
// {
// // if (checkCount++ < 300)
// // {
// // // ROS_WARN_THROTTLE(1.0, "Waiting for /joint_states shared memory topic.");
// // if (checkCount % 10 == 0)
// // {
// // CONTROLIT_WARN << "Waiting for shared memory topic /joint_states to be connected...";
// // }
// // std::this_thread::sleep_for(std::chrono::milliseconds(100));
// // }
// // else
// // {
// // CONTROLIT_ERROR << "Failed to subscribe to shared memory topic \"/joint_states\"!";
// // return false;
// // }
// }
// CONTROLIT_INFO << "Subscription to /joint_states connected.";
//---------------------------------------------------------------------------------
// Initialize odometry receiver.
//---------------------------------------------------------------------------------
CONTROLIT_INFO << "Creating and initializing the odometry state receiver...";
odometryStateReceiver.reset(new OdometryStateReceiverSM());
if (odometryStateReceiver->init(nh, model))
{
CONTROLIT_INFO << "Publishing dummy cmd and RTT TX messages...";
cmdPublisher.publish(torqueCmdMsg); // Send a dumy message to initialize shared memory connection
rttTxPublisher.publish(currentRTTMsg); // Send a dumy message to initialize shared memory connection
return true;
} else
return false;
}
void RobotInterfaceSM::rttCallback(std_msgs::Int64 & msg)
{
if (!rcvdInitRTTMsg)
{
CONTROLIT_INFO_RT << "Received initial RTT message!";
rcvdInitRTTMsg = true;
}
else
{
if (!rcvdFirstRTTMsg)
{
CONTROLIT_INFO_RT << "Received first RTT message!";
rcvdFirstRTTMsg = true;
}
rttRxMsgMutex.lock();
rttRxMsg = msg;
rttRxMsgMutex.unlock();
}
}
void RobotInterfaceSM::jointStateCallback(sensor_msgs::JointState & msg)
{
if (!rcvdInitStateMsg)
{
CONTROLIT_INFO_RT << "Received initial state message!";
rcvdInitStateMsg = true;
}
else
{
if (!rcvdFirstStateMsg)
{
CONTROLIT_INFO_RT << "Received first state message!";
rcvdFirstStateMsg = true;
}
jointStateMutex.lock();
jointStateMsg = msg;
rcvdJointState = true;
jointStateMutex.unlock();
}
}
bool RobotInterfaceSM::read(controlit::RobotState & latestRobotState, bool block)
{
bool result = true;
//---------------------------------------------------------------------------------
// Reset the timestamp within robot state to remember when the state was obtained.
//---------------------------------------------------------------------------------
latestRobotState.resetTimestamp();
//---------------------------------------------------------------------------------
// Check whether the sequence number was reflected. If it was, compute and publish
// the round trip communication latency.
//---------------------------------------------------------------------------------
rttRxMsgMutex.lock();
bool seqnoReflected = (rttRxMsg.data == seqno);
rttRxMsgMutex.unlock();
if(seqnoReflected)
{
double latency = rttTimer->getTime();
publishCommLatency(latency);
}
//---------------------------------------------------------------------------------
// Process the latest joint state information.
//---------------------------------------------------------------------------------
jointStateMutex.lock();
if (rcvdJointState)
{
//---------------------------------------------------------------------------------
// Sanity check to make sure the received joint state information is of
// the correct length.
//---------------------------------------------------------------------------------
if(latestRobotState.getNumJoints() != jointStateMsg.name.size())
{
CONTROLIT_ERROR << "Received joint state message of incorrect size!\n"
<< " - expected: " << latestRobotState.getNumJoints() << "\n"
<< " - received: " << jointStateMsg.name.size();
return false;
}
//---------------------------------------------------------------------------------
// Intialize jointNameMap if it has not already been initalized.
// This mapping stores each joint's index within the shared memory.
//---------------------------------------------------------------------------------
if (jointNameMap.size() == 0)
{
for (unsigned int ii = 0; ii < jointStateMsg.name.size(); ii++)
{
jointNameMap[jointStateMsg.name[ii]] = ii;
}
}
//---------------------------------------------------------------------------------
// Save the latest joint state information.
//---------------------------------------------------------------------------------
for(unsigned int ii = 0; ii < latestRobotState.getNumJoints(); ii++)
{
std::string name = latestRobotState.getJointNames()[ii];
unsigned int shmIndx;
try {
shmIndx = jointNameMap.at(name);
}
catch(std::out_of_range exception)
{
CONTROLIT_ERROR_RT << "Unknown joint name: " << name;
result = false;
}
if (result)
{
// Update the joint state
latestRobotState.setJointPosition(ii, jointStateMsg.position[shmIndx]);
latestRobotState.setJointVelocity(ii, jointStateMsg.velocity[shmIndx]);
latestRobotState.setJointEffort(ii, jointStateMsg.effort[shmIndx]);
// TEMPORARY!
if (std::abs(jointStateMsg.position[shmIndx]) > 1e3)
{
std::cerr << "RobotInterfaceSM: questionable position: shmIndx = " << shmIndx << ", pos = " << jointStateMsg.position[shmIndx];
assert(false);
}
}
}
//---------------------------------------------------------------------------------
// Check to ensure all receive states are valid.
// In this case, valid values are those less than 1000.
// This is optional and can be commented out to increase execution speed.
//---------------------------------------------------------------------------------
{
bool isValid = true;
for(unsigned int ii = 0; ii < jointStateMsg.name.size() && isValid; ii++)
{
if (std::abs(jointStateMsg.position[ii] >= 1e3)) isValid = false;
if (std::abs(jointStateMsg.velocity[ii] >= 1e3)) isValid = false;
if (std::abs(jointStateMsg.effort[ii] >= 1e3)) isValid = false;
}
if (!isValid)
CONTROLIT_ERROR_RT
<< "Received questionable robot state:\n"
<< controlit::addons::ros::jointStateMsgToString(jointStateMsg);
}
#if PRINT_RECEIVED_STATE
CONTROLIT_INFO_RT
<< "Received state:\n"
<< controlit::addons::ros::jointStateMsgToString(jointStateMsg);;
#endif
} else
result = false;
jointStateMutex.unlock();
//---------------------------------------------------------------------------------
// Abort if we failed to receive joint state.
//---------------------------------------------------------------------------------
if (!result) return false;
//---------------------------------------------------------------------------------
// Get and save the latest odometry data.
//---------------------------------------------------------------------------------
if (!odometryStateReceiver->getOdometry(latestRobotState, block))
return false;
//---------------------------------------------------------------------------------
// Call the the parent class' read method. This causes the latestrobot state
// to be published.
//---------------------------------------------------------------------------------
return controlit::RobotInterface::read(latestRobotState, block);
}
bool RobotInterfaceSM::write(const controlit::Command & command)
{
//---------------------------------------------------------------------------------
// Abort if jointNameMap is not initialized. It will be initialized the first
// time a state message is received.
//---------------------------------------------------------------------------------
if (jointNameMap.size() == 0) return false;
// The command may have fewer joints than the shared memory joint name map because
// of unactuated joints.
assert(torqueCmdMsg.data.size() >= command.getNumDOFs());
// The command only applies to actuated joints
const std::vector<std::string> & controlit_names = model->get()->getActuatedJointNamesVector();
// Save the command into the message
for(unsigned int ii = 0; ii < command.getNumDOFs(); ii++)
{
int shmIndx = jointNameMap[controlit_names[ii]]; //TODO: make sure the string is in the map!
// CONTROLIT_INFO << "Saving command, shmIndx = " << shmIndx;
// position_cmds[shmIndx] = command.getPositionCmd()[ii];
// velocity_cmds[shmIndx] = command.getVelocityCmd()[ii];
// torque_cmds[shmIndx] = command.getEffortCmd()[ii];
torqueCmdMsg.data[shmIndx] = command.getEffortCmd()[ii];
// #if PRINT_COMMAND
// // ss << " Joint: " << controlit_names[ii] << ", position_cmd: " << position_cmds[ii]
// // << ", velocity_cmd: " << velocity_cmds[ii] << ", torque_cmd: " << torque_cmds[ii] << std::endl;
// #endif
}
// Print command (useful for debugging purposes)
{
#if PRINT_COMMAND
std::stringstream ss;
for(unsigned int ii = 0; ii < command.getNumDOFs(); ii++)
{
int shmIndx = jointNameMap[controlit_names[ii]];
ss << " Joint: " << controlit_names[ii] << ", effort_cmd: " << torqueCmdMsg.data[shmIndx] << std::endl;
}
std::cerr << "Writing command: " << std::endl << ss.str();
#endif
}
cmdPublisher.publish(torqueCmdMsg);
//---------------------------------------------------------------------------------
// If necessary, send the next RTT sequence number.
//---------------------------------------------------------------------------------
if(sendSeqno)
{
sendSeqno = false;
currentRTTMsg.data = ++seqno;
rttTimer->start();
rttTxPublisher.publish(currentRTTMsg);
}
//---------------------------------------------------------------------------------
// Call the the parent class' write method. This causes the command to be
// published.
//---------------------------------------------------------------------------------
return controlit::RobotInterface::write(command);
}
} // namespace robot_interface_library
} // namespace controlit
<commit_msg>Abort controller if bad joint state is received.<commit_after>/*
* Copyright (C) 2015 The University of Texas at Austin and the
* Institute of Human Machine Cognition. All rights reserved.
*
* This program 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. See
* <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>
*/
#include <controlit/robot_interface_library/RobotInterfaceSM.hpp>
#include <chrono>
#include <controlit/Command.hpp>
#include <controlit/RTControlModel.hpp>
#include <controlit/logging/RealTimeLogging.hpp>
#include <controlit/robot_interface_library/OdometryStateReceiverSM.hpp>
#include <controlit/addons/ros/ROSMsgToString.hpp>
namespace controlit {
namespace robot_interface_library {
// Uncomment one of the following lines to enable/disable detailed debug statements.
#define PRINT_INFO_STATEMENT(ss)
// #define PRINT_INFO_STATEMENT(ss) CONTROLIT_INFO << ss;
#define PRINT_INFO_STATEMENT_RT(ss)
// #define PRINT_INFO_STATEMENT_RT(ss) CONTROLIT_INFO_RT << ss;
#define PRINT_INFO_RT(ss)
// #define PRINT_INFO_RT(ss) CONTROLIT_INFO_RT << ss;
#define PRINT_INFO_STATEMENT_RT_ALWAYS(ss) CONTROLIT_INFO_RT << ss;
// #define PRINT_INFO_STATEMENT_RT_ALWAYS(ss) std::cout << ss << std::endl;
#define PRINT_RECEIVED_STATE 0
#define PRINT_COMMAND 0
// Parameters for shared memory subscribers
#define LISTEN_TO_ROS_TOPIC false
#define USE_POLLING false
RobotInterfaceSM::RobotInterfaceSM() :
RobotInterface(), // Call super-class' constructor
receivedRobotState(false),
robotStateSubscriber(LISTEN_TO_ROS_TOPIC, USE_POLLING),
rttRxSubscriber(LISTEN_TO_ROS_TOPIC, USE_POLLING),
rcvdJointState(false),
rcvdInitStateMsg(false),
rcvdInitRTTMsg(false),
rcvdFirstStateMsg(false),
rcvdFirstRTTMsg(false)
{
}
RobotInterfaceSM::~RobotInterfaceSM()
{
}
bool RobotInterfaceSM::init(ros::NodeHandle & nh, RTControlModel * model)
{
PRINT_INFO_STATEMENT("Method called!");
//---------------------------------------------------------------------------------
// Initialize the parent class. Abort if parent class fails to initialize.
//---------------------------------------------------------------------------------
if(!RobotInterface::init(nh, model))
{
CONTROLIT_ERROR_RT << "Super-class failed to initialize.";
return false;
}
//---------------------------------------------------------------------------------
// Initialize a torque command message that will be used to hold the torque
// command data.
//---------------------------------------------------------------------------------
const std::vector<std::string> & names = model->get()->getRealJointNamesVector();
PRINT_INFO_STATEMENT("Number of DoFs: " << names.size());
torqueCmdMsg.layout.dim.resize(names.size());
torqueCmdMsg.layout.dim[0].stride = names.size();
torqueCmdMsg.layout.dim[0].size = names.size();
torqueCmdMsg.layout.dim[1].stride = 1;
torqueCmdMsg.layout.dim[1].size = 1;
torqueCmdMsg.data.resize(names.size());
//---------------------------------------------------------------------------------
// Initialize the shared memory publshers and subscribers.
// There are two publishers:
//
// 1. command publisher on topic "/cmd"
// 2. seqno publisher on topic "/rtt_tx"
//
// There are two subscribers:
//
// 1. robot state subscriber on topic "/joint_states"
// 2. seqno receiver on topic "/rtt_rx"
//---------------------------------------------------------------------------------
cmdPublisher.advertise("/cmd");
rttTxPublisher.advertise("/rtt_tx");
rttRxSubscriber.subscribe("/rtt_rx", boost::bind(&RobotInterfaceSM::rttCallback, this, _1));
robotStateSubscriber.subscribe("/joint_states", boost::bind(&RobotInterfaceSM::jointStateCallback, this, _1));
// rttRxSubscriber.waitForMessage(rttRxMsg);
// robotStateSubscriber.waitForMessage(jointStateMsg);
// int checkCount = 0;
// while (!rttRxSubscriber.connected())
// {
// // if (checkCount++ < 300)
// // {
// // // ROS_WARN_THROTTLE(1.0, "Waiting for /rtt_rx shared memory topic.");
// // if (checkCount % 10 == 0)
// // {
// // CONTROLIT_WARN << "Waiting for shared memory topic /rtt_rx to be connected....";
// // }
// // std::this_thread::sleep_for(std::chrono::milliseconds(100));
// // }
// // else
// // {
// // CONTROLIT_ERROR << "Failed to subscribe to shared memory topic \"/rtt_rx\"!";
// // return false;
// // }
// }
// CONTROLIT_INFO << "Subscription to /rtt_rx connected.";
// checkCount = 0;
// while (!robotStateSubscriber.connected())
// {
// // if (checkCount++ < 300)
// // {
// // // ROS_WARN_THROTTLE(1.0, "Waiting for /joint_states shared memory topic.");
// // if (checkCount % 10 == 0)
// // {
// // CONTROLIT_WARN << "Waiting for shared memory topic /joint_states to be connected...";
// // }
// // std::this_thread::sleep_for(std::chrono::milliseconds(100));
// // }
// // else
// // {
// // CONTROLIT_ERROR << "Failed to subscribe to shared memory topic \"/joint_states\"!";
// // return false;
// // }
// }
// CONTROLIT_INFO << "Subscription to /joint_states connected.";
//---------------------------------------------------------------------------------
// Initialize odometry receiver.
//---------------------------------------------------------------------------------
CONTROLIT_INFO << "Creating and initializing the odometry state receiver...";
odometryStateReceiver.reset(new OdometryStateReceiverSM());
if (odometryStateReceiver->init(nh, model))
{
CONTROLIT_INFO << "Publishing dummy cmd and RTT TX messages...";
cmdPublisher.publish(torqueCmdMsg); // Send a dumy message to initialize shared memory connection
rttTxPublisher.publish(currentRTTMsg); // Send a dumy message to initialize shared memory connection
return true;
} else
return false;
}
void RobotInterfaceSM::rttCallback(std_msgs::Int64 & msg)
{
if (!rcvdInitRTTMsg)
{
CONTROLIT_INFO_RT << "Received initial RTT message!";
rcvdInitRTTMsg = true;
}
else
{
if (!rcvdFirstRTTMsg)
{
CONTROLIT_INFO_RT << "Received first RTT message!";
rcvdFirstRTTMsg = true;
}
rttRxMsgMutex.lock();
rttRxMsg = msg;
rttRxMsgMutex.unlock();
}
}
void RobotInterfaceSM::jointStateCallback(sensor_msgs::JointState & msg)
{
if (!rcvdInitStateMsg)
{
CONTROLIT_INFO_RT << "Received initial state message!";
rcvdInitStateMsg = true;
}
else
{
if (!rcvdFirstStateMsg)
{
CONTROLIT_INFO_RT << "Received first state message!";
rcvdFirstStateMsg = true;
}
jointStateMutex.lock();
jointStateMsg = msg;
rcvdJointState = true;
jointStateMutex.unlock();
}
}
bool RobotInterfaceSM::read(controlit::RobotState & latestRobotState, bool block)
{
bool result = true;
//---------------------------------------------------------------------------------
// Reset the timestamp within robot state to remember when the state was obtained.
//---------------------------------------------------------------------------------
latestRobotState.resetTimestamp();
//---------------------------------------------------------------------------------
// Check whether the sequence number was reflected. If it was, compute and publish
// the round trip communication latency.
//---------------------------------------------------------------------------------
rttRxMsgMutex.lock();
bool seqnoReflected = (rttRxMsg.data == seqno);
rttRxMsgMutex.unlock();
if(seqnoReflected)
{
double latency = rttTimer->getTime();
publishCommLatency(latency);
}
//---------------------------------------------------------------------------------
// Process the latest joint state information.
//---------------------------------------------------------------------------------
jointStateMutex.lock();
if (rcvdJointState)
{
//---------------------------------------------------------------------------------
// Sanity check to make sure the received joint state information is of
// the correct length.
//---------------------------------------------------------------------------------
if(latestRobotState.getNumJoints() != jointStateMsg.name.size())
{
CONTROLIT_ERROR << "Received joint state message of incorrect size!\n"
<< " - expected: " << latestRobotState.getNumJoints() << "\n"
<< " - received: " << jointStateMsg.name.size();
return false;
}
//---------------------------------------------------------------------------------
// Intialize jointNameMap if it has not already been initalized.
// This mapping stores each joint's index within the shared memory.
//---------------------------------------------------------------------------------
if (jointNameMap.size() == 0)
{
for (unsigned int ii = 0; ii < jointStateMsg.name.size(); ii++)
{
jointNameMap[jointStateMsg.name[ii]] = ii;
}
}
//---------------------------------------------------------------------------------
// Save the latest joint state information.
//---------------------------------------------------------------------------------
for(unsigned int ii = 0; ii < latestRobotState.getNumJoints(); ii++)
{
std::string name = latestRobotState.getJointNames()[ii];
unsigned int shmIndx;
try {
shmIndx = jointNameMap.at(name);
}
catch(std::out_of_range exception)
{
CONTROLIT_ERROR_RT << "Unknown joint name: " << name;
result = false;
}
if (result)
{
// Update the joint state
latestRobotState.setJointPosition(ii, jointStateMsg.position[shmIndx]);
latestRobotState.setJointVelocity(ii, jointStateMsg.velocity[shmIndx]);
latestRobotState.setJointEffort(ii, jointStateMsg.effort[shmIndx]);
// TEMPORARY!
if (std::abs(jointStateMsg.position[shmIndx]) > 1e3)
{
std::cerr << "RobotInterfaceSM: questionable position: shmIndx = " << shmIndx << ", pos = " << jointStateMsg.position[shmIndx];
assert(false);
}
}
}
//---------------------------------------------------------------------------------
// Check to ensure all receive states are valid.
// In this case, valid values are those less than 1000.
// This is optional and can be commented out to increase execution speed.
//---------------------------------------------------------------------------------
{
bool isValid = true;
for(unsigned int ii = 0; ii < jointStateMsg.name.size() && isValid; ii++)
{
if (std::abs(jointStateMsg.position[ii] >= 1e3)) isValid = false;
if (std::abs(jointStateMsg.velocity[ii] >= 1e3)) isValid = false;
if (std::abs(jointStateMsg.effort[ii] >= 1e3)) isValid = false;
}
if (!isValid)
{
CONTROLIT_ERROR_RT
<< "Received questionable robot state:\n"
<< controlit::addons::ros::jointStateMsgToString(jointStateMsg);
assert(false);
}
}
#if PRINT_RECEIVED_STATE
CONTROLIT_INFO_RT
<< "Received state:\n"
<< controlit::addons::ros::jointStateMsgToString(jointStateMsg);;
#endif
} else
result = false;
jointStateMutex.unlock();
//---------------------------------------------------------------------------------
// Abort if we failed to receive joint state.
//---------------------------------------------------------------------------------
if (!result) return false;
//---------------------------------------------------------------------------------
// Get and save the latest odometry data.
//---------------------------------------------------------------------------------
if (!odometryStateReceiver->getOdometry(latestRobotState, block))
return false;
//---------------------------------------------------------------------------------
// Call the the parent class' read method. This causes the latestrobot state
// to be published.
//---------------------------------------------------------------------------------
return controlit::RobotInterface::read(latestRobotState, block);
}
bool RobotInterfaceSM::write(const controlit::Command & command)
{
//---------------------------------------------------------------------------------
// Abort if jointNameMap is not initialized. It will be initialized the first
// time a state message is received.
//---------------------------------------------------------------------------------
if (jointNameMap.size() == 0) return false;
// The command may have fewer joints than the shared memory joint name map because
// of unactuated joints.
assert(torqueCmdMsg.data.size() >= command.getNumDOFs());
// The command only applies to actuated joints
const std::vector<std::string> & controlit_names = model->get()->getActuatedJointNamesVector();
// Save the command into the message
for(unsigned int ii = 0; ii < command.getNumDOFs(); ii++)
{
int shmIndx = jointNameMap[controlit_names[ii]]; //TODO: make sure the string is in the map!
// CONTROLIT_INFO << "Saving command, shmIndx = " << shmIndx;
// position_cmds[shmIndx] = command.getPositionCmd()[ii];
// velocity_cmds[shmIndx] = command.getVelocityCmd()[ii];
// torque_cmds[shmIndx] = command.getEffortCmd()[ii];
torqueCmdMsg.data[shmIndx] = command.getEffortCmd()[ii];
// #if PRINT_COMMAND
// // ss << " Joint: " << controlit_names[ii] << ", position_cmd: " << position_cmds[ii]
// // << ", velocity_cmd: " << velocity_cmds[ii] << ", torque_cmd: " << torque_cmds[ii] << std::endl;
// #endif
}
// Print command (useful for debugging purposes)
{
#if PRINT_COMMAND
std::stringstream ss;
for(unsigned int ii = 0; ii < command.getNumDOFs(); ii++)
{
int shmIndx = jointNameMap[controlit_names[ii]];
ss << " Joint: " << controlit_names[ii] << ", effort_cmd: " << torqueCmdMsg.data[shmIndx] << std::endl;
}
std::cerr << "Writing command: " << std::endl << ss.str();
#endif
}
cmdPublisher.publish(torqueCmdMsg);
//---------------------------------------------------------------------------------
// If necessary, send the next RTT sequence number.
//---------------------------------------------------------------------------------
if(sendSeqno)
{
sendSeqno = false;
currentRTTMsg.data = ++seqno;
rttTimer->start();
rttTxPublisher.publish(currentRTTMsg);
}
//---------------------------------------------------------------------------------
// Call the the parent class' write method. This causes the command to be
// published.
//---------------------------------------------------------------------------------
return controlit::RobotInterface::write(command);
}
} // namespace robot_interface_library
} // namespace controlit
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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 <atlbase.h>
#include "base/logging.h"
#include "chrome_frame/crash_reporting/vectored_handler-impl.h"
#include "chrome_frame/crash_reporting/veh_test.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
ACTION_P(StackTraceDump, s) {
memcpy(arg2, s->stack_, s->count_ * sizeof(s->stack_[0]));
return s->count_;
}
namespace {
class MockApi : public Win32VEHTraits, public ModuleOfInterest {
public:
MockApi() {
Win32VEHTraits::InitializeIgnoredBlocks();
}
MOCK_METHOD1(WriteDump, void(const EXCEPTION_POINTERS*));
MOCK_METHOD0(RtlpGetExceptionList, const EXCEPTION_REGISTRATION_RECORD*());
MOCK_METHOD4(RtlCaptureStackBackTrace, WORD(DWORD FramesToSkip,
DWORD FramesToCapture, void** BackTrace, DWORD* BackTraceHash));
// Helpers
void SetSEH(const SEHChain& sehchain) {
EXPECT_CALL(*this, RtlpGetExceptionList())
.Times(testing::AnyNumber())
.WillRepeatedly(testing::Return(sehchain.chain_));
}
void SetStack(const StackHelper& s) {
EXPECT_CALL(*this, RtlCaptureStackBackTrace(_, _, _, _))
.Times(testing::AnyNumber())
.WillRepeatedly(StackTraceDump(&s));
}
enum {max_back_trace = 15};
};
}; // namespace
typedef VectoredHandlerT<MockApi> VectoredHandlerMock;
TEST(ChromeFrame, ExceptionReport) {
MockApi api;
VectoredHandlerMock veh(&api);
// Start address of our module.
char* s = reinterpret_cast<char*>(0x30000000);
char *e = s + 0x10000;
api.SetModule(s, e);
SEHChain have_seh(s - 0x1000, s + 0x1000, e + 0x7127, NULL);
SEHChain no_seh(s - 0x1000, e + 0x7127, NULL);
StackHelper on_stack(s - 0x11283, s - 0x278361, s + 0x9171, e + 1231, NULL);
StackHelper not_on_stack(s - 0x11283, s - 0x278361, e + 1231, NULL);
char* our_code = s + 0x1111;
char* not_our_code = s - 0x5555;
char* not_our_code2 = e + 0x5555;
// Exception in our code, but we have SEH filter => no dump.
api.SetSEH(have_seh);
api.SetStack(on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(0);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, our_code)));
testing::Mock::VerifyAndClearExpectations(&api);
// RPC_E_DISCONNECTED (0x80010108) is "The object invoked has disconnected
// from its clients", shall not be caught since it's a warning only.
EXPECT_CALL(api, WriteDump(_)).Times(0);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(RPC_E_DISCONNECTED, our_code)));
testing::Mock::VerifyAndClearExpectations(&api);
// Exception, not in our code, we do not have SEH and we are not in stack.
api.SetSEH(no_seh);
api.SetStack(not_on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(0);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_INTEGER_DIVIDE_BY_ZERO, not_our_code)));
testing::Mock::VerifyAndClearExpectations(&api);
// Exception, not in our code, no SEH, but we are on the stack.
api.SetSEH(no_seh);
api.SetStack(on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(1);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_INTEGER_DIVIDE_BY_ZERO,
not_our_code2)));
testing::Mock::VerifyAndClearExpectations(&api);
// Exception, in our code, no SEH, not on stack (assume FPO screwed us)
api.SetSEH(no_seh);
api.SetStack(not_on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(1);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_PRIVILEGED_INSTRUCTION, our_code)));
testing::Mock::VerifyAndClearExpectations(&api);
// Exception, in IsBadStringPtrA, we are on the stack.
api.SetSEH(no_seh);
api.SetStack(on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(0);
char* ignore_address = reinterpret_cast<char*>(GetProcAddress(
GetModuleHandleA("kernel32.dll"), "IsBadStringPtrA")) + 10;
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, ignore_address)));
testing::Mock::VerifyAndClearExpectations(&api);
// Exception, in IsBadStringPtrA, we are not on the stack.
api.SetSEH(no_seh);
api.SetStack(not_on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(0);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, ignore_address)));
testing::Mock::VerifyAndClearExpectations(&api);
}
MATCHER_P(ExceptionCodeIs, code, "") {
return (arg->ExceptionRecord->ExceptionCode == code);
}
void OverflowStack() {
char tmp[1024 * 2048];
ZeroMemory(tmp, sizeof(tmp));
}
DWORD WINAPI CrashingThread(PVOID tmp) {
__try {
OverflowStack();
} __except(EXCEPTION_EXECUTE_HANDLER) {
}
// This will cause STATUS_ACCESS_VIOLATION
__try {
OverflowStack();
} __except(EXCEPTION_EXECUTE_HANDLER) {
}
return 0;
}
static VectoredHandlerMock* g_mock_veh = NULL;
static LONG WINAPI VEH(EXCEPTION_POINTERS* exptrs) {
return g_mock_veh->Handler(exptrs);
}
TEST(ChromeFrame, TrickyStackOverflow) {
MockApi api;
VectoredHandlerMock veh(&api);
// Start address of our module.
char* s = reinterpret_cast<char*>(0x30000000);
char *e = s + 0x10000;
api.SetModule(s, e);
SEHChain no_seh(s - 0x1000, e + 0x7127, NULL);
StackHelper on_stack(s - 0x11283, s - 0x278361, s + 0x9171, e + 1231, NULL);
api.SetSEH(no_seh);
api.SetStack(on_stack);
EXPECT_CALL(api, WriteDump(ExceptionCodeIs(STATUS_STACK_OVERFLOW))).Times(1);
g_mock_veh = &veh;
void* id = ::AddVectoredExceptionHandler(FALSE, VEH);
DWORD tid;
HANDLE h = ::CreateThread(0, 0, CrashingThread, 0, 0, &tid);
::WaitForSingleObject(h, INFINITE);
::CloseHandle(h);
EXPECT_EQ(2, veh.get_exceptions_seen());
::RemoveVectoredExceptionHandler(id);
g_mock_veh = NULL;
}
<commit_msg>Committing for stoyan since we need this now...<commit_after>// Copyright (c) 2009 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 <atlbase.h>
#include "base/logging.h"
#include "chrome_frame/crash_reporting/vectored_handler-impl.h"
#include "chrome_frame/crash_reporting/veh_test.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
ACTION_P(StackTraceDump, s) {
memcpy(arg2, s->stack_, s->count_ * sizeof(s->stack_[0]));
return s->count_;
}
namespace {
class MockApi : public Win32VEHTraits, public ModuleOfInterest {
public:
MockApi() {
Win32VEHTraits::InitializeIgnoredBlocks();
}
MOCK_METHOD1(WriteDump, void(const EXCEPTION_POINTERS*));
MOCK_METHOD0(RtlpGetExceptionList, const EXCEPTION_REGISTRATION_RECORD*());
MOCK_METHOD4(RtlCaptureStackBackTrace, WORD(DWORD FramesToSkip,
DWORD FramesToCapture, void** BackTrace, DWORD* BackTraceHash));
// Helpers
void SetSEH(const SEHChain& sehchain) {
EXPECT_CALL(*this, RtlpGetExceptionList())
.Times(testing::AnyNumber())
.WillRepeatedly(testing::Return(sehchain.chain_));
}
void SetStack(const StackHelper& s) {
EXPECT_CALL(*this, RtlCaptureStackBackTrace(_, _, _, _))
.Times(testing::AnyNumber())
.WillRepeatedly(StackTraceDump(&s));
}
enum {max_back_trace = 15};
};
}; // namespace
typedef VectoredHandlerT<MockApi> VectoredHandlerMock;
TEST(ChromeFrame, ExceptionReport) {
MockApi api;
VectoredHandlerMock veh(&api);
// Start address of our module.
char* s = reinterpret_cast<char*>(0x30000000);
char *e = s + 0x10000;
api.SetModule(s, e);
SEHChain have_seh(s - 0x1000, s + 0x1000, e + 0x7127, NULL);
SEHChain no_seh(s - 0x1000, e + 0x7127, NULL);
StackHelper on_stack(s - 0x11283, s - 0x278361, s + 0x9171, e + 1231, NULL);
StackHelper not_on_stack(s - 0x11283, s - 0x278361, e + 1231, NULL);
char* our_code = s + 0x1111;
char* not_our_code = s - 0x5555;
char* not_our_code2 = e + 0x5555;
// Exception in our code, but we have SEH filter => no dump.
api.SetSEH(have_seh);
api.SetStack(on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(0);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, our_code)));
testing::Mock::VerifyAndClearExpectations(&api);
// RPC_E_DISCONNECTED (0x80010108) is "The object invoked has disconnected
// from its clients", shall not be caught since it's a warning only.
EXPECT_CALL(api, WriteDump(_)).Times(0);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(RPC_E_DISCONNECTED, our_code)));
testing::Mock::VerifyAndClearExpectations(&api);
// Exception, not in our code, we do not have SEH and we are not in stack.
api.SetSEH(no_seh);
api.SetStack(not_on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(0);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_INTEGER_DIVIDE_BY_ZERO, not_our_code)));
testing::Mock::VerifyAndClearExpectations(&api);
// Exception, not in our code, no SEH, but we are on the stack.
api.SetSEH(no_seh);
api.SetStack(on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(1);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_INTEGER_DIVIDE_BY_ZERO,
not_our_code2)));
testing::Mock::VerifyAndClearExpectations(&api);
// Exception, in our code, no SEH, not on stack (assume FPO screwed us)
api.SetSEH(no_seh);
api.SetStack(not_on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(1);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_PRIVILEGED_INSTRUCTION, our_code)));
testing::Mock::VerifyAndClearExpectations(&api);
// Exception, in IsBadStringPtrA, we are on the stack.
api.SetSEH(no_seh);
api.SetStack(on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(0);
char* ignore_address = reinterpret_cast<char*>(GetProcAddress(
GetModuleHandleA("kernel32.dll"), "IsBadStringPtrA")) + 10;
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, ignore_address)));
testing::Mock::VerifyAndClearExpectations(&api);
// Exception, in IsBadStringPtrA, we are not on the stack.
api.SetSEH(no_seh);
api.SetStack(not_on_stack);
EXPECT_CALL(api, WriteDump(_)).Times(0);
EXPECT_EQ(ExceptionContinueSearch,
veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, ignore_address)));
testing::Mock::VerifyAndClearExpectations(&api);
}
MATCHER_P(ExceptionCodeIs, code, "") {
return (arg->ExceptionRecord->ExceptionCode == code);
}
DECLSPEC_NOINLINE static void OverflowStack() {
char tmp[1024 * 2048] = {0};
GetSystemInfo(reinterpret_cast<SYSTEM_INFO*>(&tmp));
}
DWORD WINAPI CrashingThread(PVOID tmp) {
__try {
OverflowStack();
} __except(EXCEPTION_EXECUTE_HANDLER) {
}
// This will cause STATUS_ACCESS_VIOLATION
__try {
OverflowStack();
} __except(EXCEPTION_EXECUTE_HANDLER) {
}
return 0;
}
static VectoredHandlerMock* g_mock_veh = NULL;
static LONG WINAPI VEH(EXCEPTION_POINTERS* exptrs) {
return g_mock_veh->Handler(exptrs);
}
TEST(ChromeFrame, TrickyStackOverflow) {
MockApi api;
VectoredHandlerMock veh(&api);
// Start address of our module.
char* s = reinterpret_cast<char*>(0x30000000);
char *e = s + 0x10000;
api.SetModule(s, e);
SEHChain no_seh(s - 0x1000, e + 0x7127, NULL);
StackHelper on_stack(s - 0x11283, s - 0x278361, s + 0x9171, e + 1231, NULL);
api.SetSEH(no_seh);
api.SetStack(on_stack);
EXPECT_CALL(api, WriteDump(ExceptionCodeIs(STATUS_STACK_OVERFLOW))).Times(1);
g_mock_veh = &veh;
void* id = ::AddVectoredExceptionHandler(FALSE, VEH);
DWORD tid;
HANDLE h = ::CreateThread(0, 0, CrashingThread, 0, 0, &tid);
::WaitForSingleObject(h, INFINITE);
::CloseHandle(h);
EXPECT_EQ(2, veh.get_exceptions_seen());
::RemoveVectoredExceptionHandler(id);
g_mock_veh = NULL;
}
<|endoftext|> |
<commit_before>/*
SWARM
Copyright (C) 2012-2021 Torbjorn Rognes and Frederic Mahe
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/>.
Contact: Torbjorn Rognes <[email protected]>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
struct bucket
{
uint64_t hash;
unsigned int seqno_first;
unsigned int seqno_last;
uint64_t mass;
unsigned int size;
unsigned int singletons;
};
auto derep_compare(const void * a, const void * b) -> int;
auto derep_compare(const void * a, const void * b) -> int
{
const auto * x = static_cast<const struct bucket *>(a);
const auto * y = static_cast<const struct bucket *>(b);
int status {0};
/* highest abundance first, otherwise keep order */
if (x->mass < y->mass) {
status = +1;
}
else if (x->mass > y->mass) {
status = -1;
}
else {
if (x->seqno_first < y->seqno_first) {
status = -1;
}
else if (x->seqno_first > y->seqno_first) {
status = +1;
}
else {
status = 0;
}
}
return status;
}
auto compute_hashtable_size(const uint64_t sequence_count) -> uint64_t {
/* adjust size of hash table for 2/3 fill rate */
constexpr unsigned int hashfillpct {70};
constexpr unsigned int one_hundred_pct {100};
uint64_t hashtablesize {1};
// db seqs > 70% hash table size (avoid division to keep working with ints)
while (one_hundred_pct * sequence_count > hashfillpct * hashtablesize) {
hashtablesize <<= 1;
}
return hashtablesize;
}
auto write_stats_file(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable) -> void {
progress_init("Writing stats: ", swarmcount);
for(auto i = 0ULL; i < swarmcount; i++)
{
struct bucket * sp = hashtable + i;
fprintf(statsfile, "%u\t%" PRIu64 "\t", sp->size, sp->mass);
fprint_id_noabundance(statsfile, sp->seqno_first, p.opt_usearch_abundance);
fprintf(statsfile, "\t%" PRIu64 "\t%u\t%u\t%u\n",
db_getabundance(sp->seqno_first),
sp->singletons, 0U, 0U);
progress_update(i);
}
progress_done();
}
auto write_structure_file(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable,
unsigned int * nextseqtab) -> void {
progress_init("Writing structure:", swarmcount);
for(uint64_t i = 0; i < swarmcount; i++)
{
struct bucket * sp = hashtable + i;
uint64_t seed = sp->seqno_first;
unsigned int a = nextseqtab[seed];
while (a != 0U)
{
fprint_id_noabundance(internal_structure_file, seed, p.opt_usearch_abundance);
fprintf(internal_structure_file, "\t");
fprint_id_noabundance(internal_structure_file, a, p.opt_usearch_abundance);
fprintf(internal_structure_file, "\t%d\t%" PRIu64 "\t%d\n", 0, i+1, 0);
a = nextseqtab[a];
}
progress_update(i);
}
progress_done();
}
auto write_swarms_uclust_format(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable,
unsigned int * nextseqtab) -> void {
progress_init("Writing UCLUST: ", swarmcount);
for(auto swarmid = 0U; swarmid < swarmcount; swarmid++)
{
struct bucket * bp = hashtable + swarmid;
unsigned int seed = bp->seqno_first;
fprintf(uclustfile, "C\t%u\t%u\t*\t*\t*\t*\t*\t",
swarmid,
bp->size);
fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance);
fprintf(uclustfile, "\t*\n");
fprintf(uclustfile, "S\t%u\t%u\t*\t*\t*\t*\t*\t",
swarmid,
db_getsequencelen(seed));
fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance);
fprintf(uclustfile, "\t*\n");
unsigned int a = nextseqtab[seed];
while (a != 0U)
{
fprintf(uclustfile,
"H\t%u\t%u\t%.1f\t+\t0\t0\t%s\t",
swarmid,
db_getsequencelen(a),
100.0,
"=");
fprint_id(uclustfile, a, p.opt_usearch_abundance, p.opt_append_abundance);
fprintf(uclustfile, "\t");
fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance);
fprintf(uclustfile, "\n");
a = nextseqtab[a];
}
progress_update(swarmid+1);
}
progress_done();
}
auto write_representative_sequences(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable) -> void {
progress_init("Writing seeds: ", swarmcount);
for(auto i = 0U; i < swarmcount; i++)
{
unsigned int seed = hashtable[i].seqno_first;
fprintf(fp_seeds, ">");
fprint_id_with_new_abundance(fp_seeds, seed, hashtable[i].mass, p.opt_usearch_abundance);
fprintf(fp_seeds, "\n");
db_fprintseq(fp_seeds, seed, 0);
progress_update(i+1);
}
progress_done();
}
auto write_swarms_mothur_format(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable,
unsigned int * nextseqtab) -> void {
progress_init("Writing swarms: ", swarmcount);
fprintf(outfile, "swarm_%" PRId64 "\t%" PRIu64, p.opt_differences, swarmcount);
for(auto i = 0U; i < swarmcount; i++)
{
unsigned int seed = hashtable[i].seqno_first;
fputc('\t', outfile);
fprint_id(outfile, seed, p.opt_usearch_abundance, p.opt_append_abundance);
unsigned int a = nextseqtab[seed];
while (a != 0U)
{
fputc(',', outfile);
fprint_id(outfile, a, p.opt_usearch_abundance, p.opt_append_abundance);
a = nextseqtab[a];
}
progress_update(i+1);
}
fputc('\n', outfile);
progress_done();
}
auto write_swarms_default_format(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable,
unsigned int * nextseqtab) -> void {
progress_init("Writing swarms: ", swarmcount);
for(auto i = 0U; i < swarmcount; i++)
{
unsigned int seed = hashtable[i].seqno_first;
fprint_id(outfile, seed, p.opt_usearch_abundance, p.opt_append_abundance);
unsigned int a = nextseqtab[seed];
while (a != 0U)
{
fputc(sepchar, outfile);
fprint_id(outfile, a, p.opt_usearch_abundance, p.opt_append_abundance);
a = nextseqtab[a];
}
fputc('\n', outfile);
progress_update(i+1);
}
progress_done();
}
void dereplicate(struct Parameters const & p)
{
const uint64_t dbsequencecount = db_getsequencecount();
const uint64_t hashtablesize {compute_hashtable_size(dbsequencecount)};
const uint64_t derep_hash_mask = hashtablesize - 1;
auto * hashtable =
static_cast<struct bucket *>(xmalloc(sizeof(bucket) * hashtablesize));
memset(hashtable, 0, sizeof(bucket) * hashtablesize);
uint64_t swarmcount = 0;
uint64_t maxmass = 0;
unsigned int maxsize = 0;
/* alloc and init table of links to other sequences in cluster */
auto * nextseqtab = static_cast<unsigned int *>
(xmalloc(sizeof(unsigned int) * dbsequencecount));
memset(nextseqtab, 0, sizeof(unsigned int) * dbsequencecount);
progress_init("Dereplicating: ", dbsequencecount);
for(auto i = 0U; i < dbsequencecount; i++)
{
unsigned int seqlen = db_getsequencelen(i);
char * seq = db_getsequence(i);
/*
Find free bucket or bucket for identical sequence.
Make sure sequences are exactly identical
in case of any hash collision.
With 64-bit hashes, there is about 50% chance of a
collision when the number of sequences is about 5e9.
*/
uint64_t hash = zobrist_hash(reinterpret_cast<unsigned char *>(seq),
seqlen);
uint64_t j = hash & derep_hash_mask;
struct bucket * bp = hashtable + j;
while (((bp->mass) != 0U) &&
((bp->hash != hash) ||
(seqlen != db_getsequencelen(bp->seqno_first)) ||
(memcmp(seq,
db_getsequence(bp->seqno_first),
nt_bytelength(seqlen)) != 0)))
{
bp++;
j++;
if (bp >= hashtable + hashtablesize)
{
bp = hashtable;
j = 0;
}
}
uint64_t ab = db_getabundance(i);
if ((bp->mass) != 0U)
{
/* at least one identical sequence already */
nextseqtab[bp->seqno_last] = i;
}
else
{
/* no identical sequences yet, start a new cluster */
swarmcount++;
bp->hash = hash;
bp->seqno_first = i;
bp->size = 0;
bp->singletons = 0;
}
bp->size++;
bp->seqno_last = i;
bp->mass += ab;
if (ab == 1) {
bp->singletons++;
}
if (bp->mass > maxmass) {
maxmass = bp->mass;
}
if (bp->size > maxsize) {
maxsize = bp->size;
}
progress_update(i);
}
progress_done();
progress_init("Sorting: ", 1);
qsort(hashtable, hashtablesize, sizeof(bucket), derep_compare);
progress_done();
/* dump swarms */
if (p.opt_mothur) {
write_swarms_mothur_format(swarmcount, p, hashtable, nextseqtab);
}
else {
write_swarms_default_format(swarmcount, p, hashtable, nextseqtab);
}
/* dump seeds in fasta format with sum of abundances */
if (not p.opt_seeds.empty()) {
write_representative_sequences(swarmcount, p, hashtable);
}
/* output swarm in uclust format */
if (uclustfile != nullptr) {
write_swarms_uclust_format(swarmcount, p, hashtable, nextseqtab);
}
/* output internal structure to file */
if (not p.opt_internal_structure.empty()) {
write_structure_file(swarmcount, p, hashtable, nextseqtab);
}
/* output statistics to file */
if (statsfile != nullptr) {
write_stats_file(swarmcount, p, hashtable);
}
fprintf(logfile, "\n");
fprintf(logfile, "Number of swarms: %" PRIu64 "\n", swarmcount);
fprintf(logfile, "Largest swarm: %u\n", maxsize);
fprintf(logfile, "Heaviest swarm: %" PRIu64 "\n", maxmass);
xfree(nextseqtab);
xfree(hashtable);
}
<commit_msg>remove unnecessary function declaration<commit_after>/*
SWARM
Copyright (C) 2012-2021 Torbjorn Rognes and Frederic Mahe
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/>.
Contact: Torbjorn Rognes <[email protected]>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
struct bucket
{
uint64_t hash;
unsigned int seqno_first;
unsigned int seqno_last;
uint64_t mass;
unsigned int size;
unsigned int singletons;
};
auto derep_compare(const void * a, const void * b) -> int
{
const auto * x = static_cast<const struct bucket *>(a);
const auto * y = static_cast<const struct bucket *>(b);
int status {0};
/* highest abundance first, otherwise keep order */
if (x->mass < y->mass) {
status = +1;
}
else if (x->mass > y->mass) {
status = -1;
}
else {
if (x->seqno_first < y->seqno_first) {
status = -1;
}
else if (x->seqno_first > y->seqno_first) {
status = +1;
}
else {
status = 0;
}
}
return status;
}
auto compute_hashtable_size(const uint64_t sequence_count) -> uint64_t {
/* adjust size of hash table for 2/3 fill rate */
constexpr unsigned int hashfillpct {70};
constexpr unsigned int one_hundred_pct {100};
uint64_t hashtablesize {1};
// db seqs > 70% hash table size (avoid division to keep working with ints)
while (one_hundred_pct * sequence_count > hashfillpct * hashtablesize) {
hashtablesize <<= 1;
}
return hashtablesize;
}
auto write_stats_file(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable) -> void {
progress_init("Writing stats: ", swarmcount);
for(auto i = 0ULL; i < swarmcount; i++)
{
struct bucket * sp = hashtable + i;
fprintf(statsfile, "%u\t%" PRIu64 "\t", sp->size, sp->mass);
fprint_id_noabundance(statsfile, sp->seqno_first, p.opt_usearch_abundance);
fprintf(statsfile, "\t%" PRIu64 "\t%u\t%u\t%u\n",
db_getabundance(sp->seqno_first),
sp->singletons, 0U, 0U);
progress_update(i);
}
progress_done();
}
auto write_structure_file(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable,
unsigned int * nextseqtab) -> void {
progress_init("Writing structure:", swarmcount);
for(uint64_t i = 0; i < swarmcount; i++)
{
struct bucket * sp = hashtable + i;
uint64_t seed = sp->seqno_first;
unsigned int a = nextseqtab[seed];
while (a != 0U)
{
fprint_id_noabundance(internal_structure_file, seed, p.opt_usearch_abundance);
fprintf(internal_structure_file, "\t");
fprint_id_noabundance(internal_structure_file, a, p.opt_usearch_abundance);
fprintf(internal_structure_file, "\t%d\t%" PRIu64 "\t%d\n", 0, i+1, 0);
a = nextseqtab[a];
}
progress_update(i);
}
progress_done();
}
auto write_swarms_uclust_format(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable,
unsigned int * nextseqtab) -> void {
progress_init("Writing UCLUST: ", swarmcount);
for(auto swarmid = 0U; swarmid < swarmcount; swarmid++)
{
struct bucket * bp = hashtable + swarmid;
unsigned int seed = bp->seqno_first;
fprintf(uclustfile, "C\t%u\t%u\t*\t*\t*\t*\t*\t",
swarmid,
bp->size);
fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance);
fprintf(uclustfile, "\t*\n");
fprintf(uclustfile, "S\t%u\t%u\t*\t*\t*\t*\t*\t",
swarmid,
db_getsequencelen(seed));
fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance);
fprintf(uclustfile, "\t*\n");
unsigned int a = nextseqtab[seed];
while (a != 0U)
{
fprintf(uclustfile,
"H\t%u\t%u\t%.1f\t+\t0\t0\t%s\t",
swarmid,
db_getsequencelen(a),
100.0,
"=");
fprint_id(uclustfile, a, p.opt_usearch_abundance, p.opt_append_abundance);
fprintf(uclustfile, "\t");
fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance);
fprintf(uclustfile, "\n");
a = nextseqtab[a];
}
progress_update(swarmid+1);
}
progress_done();
}
auto write_representative_sequences(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable) -> void {
progress_init("Writing seeds: ", swarmcount);
for(auto i = 0U; i < swarmcount; i++)
{
unsigned int seed = hashtable[i].seqno_first;
fprintf(fp_seeds, ">");
fprint_id_with_new_abundance(fp_seeds, seed, hashtable[i].mass, p.opt_usearch_abundance);
fprintf(fp_seeds, "\n");
db_fprintseq(fp_seeds, seed, 0);
progress_update(i+1);
}
progress_done();
}
auto write_swarms_mothur_format(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable,
unsigned int * nextseqtab) -> void {
progress_init("Writing swarms: ", swarmcount);
fprintf(outfile, "swarm_%" PRId64 "\t%" PRIu64, p.opt_differences, swarmcount);
for(auto i = 0U; i < swarmcount; i++)
{
unsigned int seed = hashtable[i].seqno_first;
fputc('\t', outfile);
fprint_id(outfile, seed, p.opt_usearch_abundance, p.opt_append_abundance);
unsigned int a = nextseqtab[seed];
while (a != 0U)
{
fputc(',', outfile);
fprint_id(outfile, a, p.opt_usearch_abundance, p.opt_append_abundance);
a = nextseqtab[a];
}
progress_update(i+1);
}
fputc('\n', outfile);
progress_done();
}
auto write_swarms_default_format(const uint64_t swarmcount,
struct Parameters const & p,
struct bucket * hashtable,
unsigned int * nextseqtab) -> void {
progress_init("Writing swarms: ", swarmcount);
for(auto i = 0U; i < swarmcount; i++)
{
unsigned int seed = hashtable[i].seqno_first;
fprint_id(outfile, seed, p.opt_usearch_abundance, p.opt_append_abundance);
unsigned int a = nextseqtab[seed];
while (a != 0U)
{
fputc(sepchar, outfile);
fprint_id(outfile, a, p.opt_usearch_abundance, p.opt_append_abundance);
a = nextseqtab[a];
}
fputc('\n', outfile);
progress_update(i+1);
}
progress_done();
}
void dereplicate(struct Parameters const & p)
{
const uint64_t dbsequencecount = db_getsequencecount();
const uint64_t hashtablesize {compute_hashtable_size(dbsequencecount)};
const uint64_t derep_hash_mask = hashtablesize - 1;
auto * hashtable =
static_cast<struct bucket *>(xmalloc(sizeof(bucket) * hashtablesize));
memset(hashtable, 0, sizeof(bucket) * hashtablesize);
uint64_t swarmcount = 0;
uint64_t maxmass = 0;
unsigned int maxsize = 0;
/* alloc and init table of links to other sequences in cluster */
auto * nextseqtab = static_cast<unsigned int *>
(xmalloc(sizeof(unsigned int) * dbsequencecount));
memset(nextseqtab, 0, sizeof(unsigned int) * dbsequencecount);
progress_init("Dereplicating: ", dbsequencecount);
for(auto i = 0U; i < dbsequencecount; i++)
{
unsigned int seqlen = db_getsequencelen(i);
char * seq = db_getsequence(i);
/*
Find free bucket or bucket for identical sequence.
Make sure sequences are exactly identical
in case of any hash collision.
With 64-bit hashes, there is about 50% chance of a
collision when the number of sequences is about 5e9.
*/
uint64_t hash = zobrist_hash(reinterpret_cast<unsigned char *>(seq),
seqlen);
uint64_t j = hash & derep_hash_mask;
struct bucket * bp = hashtable + j;
while (((bp->mass) != 0U) &&
((bp->hash != hash) ||
(seqlen != db_getsequencelen(bp->seqno_first)) ||
(memcmp(seq,
db_getsequence(bp->seqno_first),
nt_bytelength(seqlen)) != 0)))
{
bp++;
j++;
if (bp >= hashtable + hashtablesize)
{
bp = hashtable;
j = 0;
}
}
uint64_t ab = db_getabundance(i);
if ((bp->mass) != 0U)
{
/* at least one identical sequence already */
nextseqtab[bp->seqno_last] = i;
}
else
{
/* no identical sequences yet, start a new cluster */
swarmcount++;
bp->hash = hash;
bp->seqno_first = i;
bp->size = 0;
bp->singletons = 0;
}
bp->size++;
bp->seqno_last = i;
bp->mass += ab;
if (ab == 1) {
bp->singletons++;
}
if (bp->mass > maxmass) {
maxmass = bp->mass;
}
if (bp->size > maxsize) {
maxsize = bp->size;
}
progress_update(i);
}
progress_done();
progress_init("Sorting: ", 1);
qsort(hashtable, hashtablesize, sizeof(bucket), derep_compare);
progress_done();
/* dump swarms */
if (p.opt_mothur) {
write_swarms_mothur_format(swarmcount, p, hashtable, nextseqtab);
}
else {
write_swarms_default_format(swarmcount, p, hashtable, nextseqtab);
}
/* dump seeds in fasta format with sum of abundances */
if (not p.opt_seeds.empty()) {
write_representative_sequences(swarmcount, p, hashtable);
}
/* output swarm in uclust format */
if (uclustfile != nullptr) {
write_swarms_uclust_format(swarmcount, p, hashtable, nextseqtab);
}
/* output internal structure to file */
if (not p.opt_internal_structure.empty()) {
write_structure_file(swarmcount, p, hashtable, nextseqtab);
}
/* output statistics to file */
if (statsfile != nullptr) {
write_stats_file(swarmcount, p, hashtable);
}
fprintf(logfile, "\n");
fprintf(logfile, "Number of swarms: %" PRIu64 "\n", swarmcount);
fprintf(logfile, "Largest swarm: %u\n", maxsize);
fprintf(logfile, "Heaviest swarm: %" PRIu64 "\n", maxmass);
xfree(nextseqtab);
xfree(hashtable);
}
<|endoftext|> |
<commit_before>#include "kernel.h"
#include "ilwisdata.h"
#include "range.h"
#include "itemrange.h"
#include "colorrange.h"
#include "numericrange.h"
#include "continuouscolorLookup.h"
using namespace Ilwis;
ContinuousColorLookup::ContinuousColorLookup(const QString &definition)
{
QStringList parts = definition.split(";");
for( QString group : parts){
QStringList groupdef = group.split("|");
if ( groupdef.size() != 3) {
ERROR2(ERR_ILLEGAL_VALUE_2,TR("Representation definition"), definition);
return;
}
QStringList limits = groupdef[0].split(":");
if ( limits.size() != 2){
ERROR2(ERR_ILLEGAL_VALUE_2,TR("Representation definition"), definition);
return;
}
bool ok1, ok2;
NumericRange numrange(limits[0].toDouble(&ok1), limits[1].toDouble(&ok2));
if ( !(ok1 && ok2)){
ERROR2(ERR_ILLEGAL_VALUE_2,TR("Representation definition"), definition);
return;
}
QColor color1 = string2color(groupdef[1]);
if ( !(color1.isValid())){
ERROR2(ERR_ILLEGAL_VALUE_2,TR("Representation definition"), definition);
return;
}
QColor color2 = string2color(groupdef[2]);
if ( !(color2.isValid())){
ERROR2(ERR_ILLEGAL_VALUE_2,TR("Representation definition"), definition);
return;
}
ContinuousColorRange colorrange(color1, color2);
addGroup(numrange,colorrange);
}
}
QColor ContinuousColorLookup::value2color(double value, const NumericRange& actualRange, const NumericRange& stretchRange) const
{
if ( stretchRange.isValid()) {
if ( _linear){
if ( value < stretchRange.center()){
double stretchFraction = (value - stretchRange.min())/ stretchRange.distance();
value = actualRange.min() + stretchFraction * actualRange.distance();
}else{
if ( value >= stretchRange.center()){
double stretchFraction = (stretchRange.max() - value)/ stretchRange.distance();
value = actualRange.max() - stretchFraction * actualRange.distance();
}
}
}
}
value = (value - actualRange.min()) / actualRange.distance(); // scale it between 0..1
for(int i = 0; i < _groups.size(); ++i){
if ( value <= _groups[i].max()){
double delta = _groups[i].distance();
double position = 0;
if ( _step == 0){
position = (value - _groups[i].min())/ delta;
}else
position = ((quint32)(value - _groups[i].min())/ _step)/( (quint32)(delta / _step));
return ContinuousColorRange::valueAt(position,&_colorranges[i]);
}
}
return QColor();
}
void ContinuousColorLookup::addGroup(const NumericRange &range, const ContinuousColorRange &colorrange)
{
if ( !(range.min() >= 0 && range.max() <= 1.0)){
ERROR2(ERR_INVALID_INIT_FOR_2, TR("Numerical range"), "Representation");
return;
}
if ( _colorranges.size() > 0){
if ( range.min() < _groups.back().min()){
kernel()->issues()->log(TR("Numerical ranges for representation must be added in order"));
return ;
}
}
_colorranges.push_back(colorrange);
_groups.push_back(range);
}
<commit_msg>undefines get transparent as color<commit_after>#include "kernel.h"
#include "ilwisdata.h"
#include "range.h"
#include "itemrange.h"
#include "colorrange.h"
#include "numericrange.h"
#include "continuouscolorLookup.h"
using namespace Ilwis;
ContinuousColorLookup::ContinuousColorLookup(const QString &definition)
{
QStringList parts = definition.split(";");
for( QString group : parts){
QStringList groupdef = group.split("|");
if ( groupdef.size() != 3) {
ERROR2(ERR_ILLEGAL_VALUE_2,TR("Representation definition"), definition);
return;
}
QStringList limits = groupdef[0].split(":");
if ( limits.size() != 2){
ERROR2(ERR_ILLEGAL_VALUE_2,TR("Representation definition"), definition);
return;
}
bool ok1, ok2;
NumericRange numrange(limits[0].toDouble(&ok1), limits[1].toDouble(&ok2));
if ( !(ok1 && ok2)){
ERROR2(ERR_ILLEGAL_VALUE_2,TR("Representation definition"), definition);
return;
}
QColor color1 = string2color(groupdef[1]);
if ( !(color1.isValid())){
ERROR2(ERR_ILLEGAL_VALUE_2,TR("Representation definition"), definition);
return;
}
QColor color2 = string2color(groupdef[2]);
if ( !(color2.isValid())){
ERROR2(ERR_ILLEGAL_VALUE_2,TR("Representation definition"), definition);
return;
}
ContinuousColorRange colorrange(color1, color2);
addGroup(numrange,colorrange);
}
}
QColor ContinuousColorLookup::value2color(double value, const NumericRange& actualRange, const NumericRange& stretchRange) const
{
if ( value == rUNDEF)
return QColor("transparent");
if ( stretchRange.isValid()) {
if ( _linear){
if ( value < stretchRange.center()){
double stretchFraction = (value - stretchRange.min())/ stretchRange.distance();
value = actualRange.min() + stretchFraction * actualRange.distance();
}else{
if ( value >= stretchRange.center()){
double stretchFraction = (stretchRange.max() - value)/ stretchRange.distance();
value = actualRange.max() - stretchFraction * actualRange.distance();
}
}
}
}
value = (value - actualRange.min()) / actualRange.distance(); // scale it between 0..1
for(int i = 0; i < _groups.size(); ++i){
if ( value <= _groups[i].max()){
double delta = _groups[i].distance();
double position = 0;
if ( _step == 0){
position = (value - _groups[i].min())/ delta;
}else
position = ((quint32)(value - _groups[i].min())/ _step)/( (quint32)(delta / _step));
return ContinuousColorRange::valueAt(position,&_colorranges[i]);
}
}
return QColor();
}
void ContinuousColorLookup::addGroup(const NumericRange &range, const ContinuousColorRange &colorrange)
{
if ( !(range.min() >= 0 && range.max() <= 1.0)){
ERROR2(ERR_INVALID_INIT_FOR_2, TR("Numerical range"), "Representation");
return;
}
if ( _colorranges.size() > 0){
if ( range.min() < _groups.back().min()){
kernel()->issues()->log(TR("Numerical ranges for representation must be added in order"));
return ;
}
}
_colorranges.push_back(colorrange);
_groups.push_back(range);
}
<|endoftext|> |
<commit_before>/*
SWARM
Copyright (C) 2012-2020 Torbjorn Rognes and Frederic Mahe
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/>.
Contact: Torbjorn Rognes <[email protected]>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
struct bucket
{
uint64_t hash;
unsigned int seqno_first;
unsigned int seqno_last;
uint64_t mass;
unsigned int size;
unsigned int singletons;
};
int derep_compare(const void * a, const void * b);
int derep_compare(const void * a, const void * b)
{
const auto * x = static_cast<const struct bucket *>(a);
const auto * y = static_cast<const struct bucket *>(b);
auto status {0};
/* highest abundance first, otherwise keep order */
if (x->mass < y->mass) {
status = +1;
}
else if (x->mass > y->mass) {
status = -1;
}
else {
if (x->seqno_first < y->seqno_first) {
status = -1;
}
else if (x->seqno_first > y->seqno_first) {
status = +1;
}
else {
status = 0;
}
}
return status;
}
void dereplicate()
{
/* adjust size of hash table for 2/3 fill rate */
uint64_t dbsequencecount = db_getsequencecount();
uint64_t hashtablesize = 1;
while (100 * dbsequencecount > 70 * hashtablesize) {
hashtablesize <<= 1;
}
uint64_t derep_hash_mask = hashtablesize - 1;
auto * hashtable =
static_cast<struct bucket *>(xmalloc(sizeof(bucket) * hashtablesize));
memset(hashtable, 0, sizeof(bucket) * hashtablesize);
uint64_t swarmcount = 0;
uint64_t maxmass = 0;
unsigned int maxsize = 0;
/* alloc and init table of links to other sequences in cluster */
auto * nextseqtab = static_cast<unsigned int *>
(xmalloc(sizeof(unsigned int) * dbsequencecount));
memset(nextseqtab, 0, sizeof(unsigned int) * dbsequencecount);
progress_init("Dereplicating: ", dbsequencecount);
for(auto i = 0U; i < dbsequencecount; i++)
{
unsigned int seqlen = db_getsequencelen(i);
char * seq = db_getsequence(i);
/*
Find free bucket or bucket for identical sequence.
Make sure sequences are exactly identical
in case of any hash collision.
With 64-bit hashes, there is about 50% chance of a
collision when the number of sequences is about 5e9.
*/
uint64_t hash = zobrist_hash(reinterpret_cast<unsigned char *>(seq),
seqlen);
uint64_t j = hash & derep_hash_mask;
struct bucket * bp = hashtable + j;
while ((bp->mass) &&
((bp->hash != hash) ||
(seqlen != db_getsequencelen(bp->seqno_first)) ||
(memcmp(seq,
db_getsequence(bp->seqno_first),
nt_bytelength(seqlen)))))
{
bp++;
j++;
if (bp >= hashtable + hashtablesize)
{
bp = hashtable;
j = 0;
}
}
uint64_t ab = db_getabundance(i);
if (bp->mass)
{
/* at least one identical sequence already */
nextseqtab[bp->seqno_last] = i;
}
else
{
/* no identical sequences yet, start a new cluster */
swarmcount++;
bp->hash = hash;
bp->seqno_first = i;
bp->size = 0;
bp->singletons = 0;
}
bp->size++;
bp->seqno_last = i;
bp->mass += ab;
if (ab == 1) {
bp->singletons++;
}
if (bp->mass > maxmass) {
maxmass = bp->mass;
}
if (bp->size > maxsize) {
maxsize = bp->size;
}
progress_update(i);
}
progress_done();
progress_init("Sorting: ", 1);
qsort(hashtable, hashtablesize, sizeof(bucket), derep_compare);
progress_done();
/* dump swarms */
progress_init("Writing swarms: ", swarmcount);
if (opt_mothur) {
fprintf(outfile, "swarm_%" PRId64 "\t%" PRIu64, opt_differences, swarmcount);
}
for(auto i = 0U; i < swarmcount; i++)
{
unsigned int seed = hashtable[i].seqno_first;
if (opt_mothur) {
fputc('\t', outfile);
}
fprint_id(outfile, seed);
unsigned int a = nextseqtab[seed];
while (a)
{
if (opt_mothur) {
fputc(',', outfile);
}
else {
fputc(sepchar, outfile);
}
fprint_id(outfile, a);
a = nextseqtab[a];
}
if (!opt_mothur) {
fputc('\n', outfile);
}
progress_update(i+1);
}
if (opt_mothur) {
fputc('\n', outfile);
}
progress_done();
/* dump seeds in fasta format with sum of abundances */
if (opt_seeds)
{
progress_init("Writing seeds: ", swarmcount);
for(auto i = 0U; i < swarmcount; i++)
{
unsigned int seed = hashtable[i].seqno_first;
fprintf(fp_seeds, ">");
fprint_id_with_new_abundance(fp_seeds, seed, hashtable[i].mass);
fprintf(fp_seeds, "\n");
db_fprintseq(fp_seeds, seed, 0);
progress_update(i+1);
}
progress_done();
}
/* output swarm in uclust format */
if (uclustfile)
{
progress_init("Writing UCLUST: ", swarmcount);
for(auto swarmid = 0U; swarmid < swarmcount; swarmid++)
{
struct bucket * bp = hashtable + swarmid;
unsigned int seed = bp->seqno_first;
fprintf(uclustfile, "C\t%u\t%u\t*\t*\t*\t*\t*\t",
swarmid,
bp->size);
fprint_id(uclustfile, seed);
fprintf(uclustfile, "\t*\n");
fprintf(uclustfile, "S\t%u\t%u\t*\t*\t*\t*\t*\t",
swarmid,
db_getsequencelen(seed));
fprint_id(uclustfile, seed);
fprintf(uclustfile, "\t*\n");
unsigned int a = nextseqtab[seed];
while (a)
{
fprintf(uclustfile,
"H\t%u\t%u\t%.1f\t+\t0\t0\t%s\t",
swarmid,
db_getsequencelen(a),
100.0,
"=");
fprint_id(uclustfile, a);
fprintf(uclustfile, "\t");
fprint_id(uclustfile, seed);
fprintf(uclustfile, "\n");
a = nextseqtab[a];
}
progress_update(swarmid+1);
}
progress_done();
}
/* output internal structure to file */
if (opt_internal_structure)
{
progress_init("Writing structure:", swarmcount);
for(auto i = 0UL; i < swarmcount; i++)
{
struct bucket * sp = hashtable + i;
uint64_t seed = sp->seqno_first;
unsigned int a = nextseqtab[seed];
while (a)
{
fprint_id_noabundance(internal_structure_file, seed);
fprintf(internal_structure_file, "\t");
fprint_id_noabundance(internal_structure_file, a);
fprintf(internal_structure_file, "\t%d\t%" PRIu64 "\t%d\n", 0, i+1, 0);
a = nextseqtab[a];
}
progress_update(i);
}
progress_done();
}
/* output statistics to file */
if (statsfile)
{
progress_init("Writing stats: ", swarmcount);
for(auto i = 0ULL; i < swarmcount; i++)
{
struct bucket * sp = hashtable + i;
fprintf(statsfile, "%u\t%" PRIu64 "\t", sp->size, sp->mass);
fprint_id_noabundance(statsfile, sp->seqno_first);
fprintf(statsfile, "\t%" PRIu64 "\t%u\t%u\t%u\n",
db_getabundance(sp->seqno_first),
sp->singletons, 0U, 0U);
progress_update(i);
}
progress_done();
}
fprintf(logfile, "\n");
fprintf(logfile, "Number of swarms: %" PRIu64 "\n", swarmcount);
fprintf(logfile, "Largest swarm: %u\n", maxsize);
fprintf(logfile, "Heaviest swarm: %" PRIu64 "\n", maxmass);
xfree(nextseqtab);
xfree(hashtable);
}
<commit_msg>function 'memcmp' is called without explicitly comparing result<commit_after>/*
SWARM
Copyright (C) 2012-2020 Torbjorn Rognes and Frederic Mahe
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/>.
Contact: Torbjorn Rognes <[email protected]>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
struct bucket
{
uint64_t hash;
unsigned int seqno_first;
unsigned int seqno_last;
uint64_t mass;
unsigned int size;
unsigned int singletons;
};
int derep_compare(const void * a, const void * b);
int derep_compare(const void * a, const void * b)
{
const auto * x = static_cast<const struct bucket *>(a);
const auto * y = static_cast<const struct bucket *>(b);
auto status {0};
/* highest abundance first, otherwise keep order */
if (x->mass < y->mass) {
status = +1;
}
else if (x->mass > y->mass) {
status = -1;
}
else {
if (x->seqno_first < y->seqno_first) {
status = -1;
}
else if (x->seqno_first > y->seqno_first) {
status = +1;
}
else {
status = 0;
}
}
return status;
}
void dereplicate()
{
/* adjust size of hash table for 2/3 fill rate */
uint64_t dbsequencecount = db_getsequencecount();
uint64_t hashtablesize = 1;
while (100 * dbsequencecount > 70 * hashtablesize) {
hashtablesize <<= 1;
}
uint64_t derep_hash_mask = hashtablesize - 1;
auto * hashtable =
static_cast<struct bucket *>(xmalloc(sizeof(bucket) * hashtablesize));
memset(hashtable, 0, sizeof(bucket) * hashtablesize);
uint64_t swarmcount = 0;
uint64_t maxmass = 0;
unsigned int maxsize = 0;
/* alloc and init table of links to other sequences in cluster */
auto * nextseqtab = static_cast<unsigned int *>
(xmalloc(sizeof(unsigned int) * dbsequencecount));
memset(nextseqtab, 0, sizeof(unsigned int) * dbsequencecount);
progress_init("Dereplicating: ", dbsequencecount);
for(auto i = 0U; i < dbsequencecount; i++)
{
unsigned int seqlen = db_getsequencelen(i);
char * seq = db_getsequence(i);
/*
Find free bucket or bucket for identical sequence.
Make sure sequences are exactly identical
in case of any hash collision.
With 64-bit hashes, there is about 50% chance of a
collision when the number of sequences is about 5e9.
*/
uint64_t hash = zobrist_hash(reinterpret_cast<unsigned char *>(seq),
seqlen);
uint64_t j = hash & derep_hash_mask;
struct bucket * bp = hashtable + j;
while ((bp->mass) &&
((bp->hash != hash) ||
(seqlen != db_getsequencelen(bp->seqno_first)) ||
(memcmp(seq,
db_getsequence(bp->seqno_first),
nt_bytelength(seqlen)) != 0)))
{
bp++;
j++;
if (bp >= hashtable + hashtablesize)
{
bp = hashtable;
j = 0;
}
}
uint64_t ab = db_getabundance(i);
if (bp->mass)
{
/* at least one identical sequence already */
nextseqtab[bp->seqno_last] = i;
}
else
{
/* no identical sequences yet, start a new cluster */
swarmcount++;
bp->hash = hash;
bp->seqno_first = i;
bp->size = 0;
bp->singletons = 0;
}
bp->size++;
bp->seqno_last = i;
bp->mass += ab;
if (ab == 1) {
bp->singletons++;
}
if (bp->mass > maxmass) {
maxmass = bp->mass;
}
if (bp->size > maxsize) {
maxsize = bp->size;
}
progress_update(i);
}
progress_done();
progress_init("Sorting: ", 1);
qsort(hashtable, hashtablesize, sizeof(bucket), derep_compare);
progress_done();
/* dump swarms */
progress_init("Writing swarms: ", swarmcount);
if (opt_mothur) {
fprintf(outfile, "swarm_%" PRId64 "\t%" PRIu64, opt_differences, swarmcount);
}
for(auto i = 0U; i < swarmcount; i++)
{
unsigned int seed = hashtable[i].seqno_first;
if (opt_mothur) {
fputc('\t', outfile);
}
fprint_id(outfile, seed);
unsigned int a = nextseqtab[seed];
while (a)
{
if (opt_mothur) {
fputc(',', outfile);
}
else {
fputc(sepchar, outfile);
}
fprint_id(outfile, a);
a = nextseqtab[a];
}
if (!opt_mothur) {
fputc('\n', outfile);
}
progress_update(i+1);
}
if (opt_mothur) {
fputc('\n', outfile);
}
progress_done();
/* dump seeds in fasta format with sum of abundances */
if (opt_seeds)
{
progress_init("Writing seeds: ", swarmcount);
for(auto i = 0U; i < swarmcount; i++)
{
unsigned int seed = hashtable[i].seqno_first;
fprintf(fp_seeds, ">");
fprint_id_with_new_abundance(fp_seeds, seed, hashtable[i].mass);
fprintf(fp_seeds, "\n");
db_fprintseq(fp_seeds, seed, 0);
progress_update(i+1);
}
progress_done();
}
/* output swarm in uclust format */
if (uclustfile)
{
progress_init("Writing UCLUST: ", swarmcount);
for(auto swarmid = 0U; swarmid < swarmcount; swarmid++)
{
struct bucket * bp = hashtable + swarmid;
unsigned int seed = bp->seqno_first;
fprintf(uclustfile, "C\t%u\t%u\t*\t*\t*\t*\t*\t",
swarmid,
bp->size);
fprint_id(uclustfile, seed);
fprintf(uclustfile, "\t*\n");
fprintf(uclustfile, "S\t%u\t%u\t*\t*\t*\t*\t*\t",
swarmid,
db_getsequencelen(seed));
fprint_id(uclustfile, seed);
fprintf(uclustfile, "\t*\n");
unsigned int a = nextseqtab[seed];
while (a)
{
fprintf(uclustfile,
"H\t%u\t%u\t%.1f\t+\t0\t0\t%s\t",
swarmid,
db_getsequencelen(a),
100.0,
"=");
fprint_id(uclustfile, a);
fprintf(uclustfile, "\t");
fprint_id(uclustfile, seed);
fprintf(uclustfile, "\n");
a = nextseqtab[a];
}
progress_update(swarmid+1);
}
progress_done();
}
/* output internal structure to file */
if (opt_internal_structure)
{
progress_init("Writing structure:", swarmcount);
for(auto i = 0UL; i < swarmcount; i++)
{
struct bucket * sp = hashtable + i;
uint64_t seed = sp->seqno_first;
unsigned int a = nextseqtab[seed];
while (a)
{
fprint_id_noabundance(internal_structure_file, seed);
fprintf(internal_structure_file, "\t");
fprint_id_noabundance(internal_structure_file, a);
fprintf(internal_structure_file, "\t%d\t%" PRIu64 "\t%d\n", 0, i+1, 0);
a = nextseqtab[a];
}
progress_update(i);
}
progress_done();
}
/* output statistics to file */
if (statsfile)
{
progress_init("Writing stats: ", swarmcount);
for(auto i = 0ULL; i < swarmcount; i++)
{
struct bucket * sp = hashtable + i;
fprintf(statsfile, "%u\t%" PRIu64 "\t", sp->size, sp->mass);
fprint_id_noabundance(statsfile, sp->seqno_first);
fprintf(statsfile, "\t%" PRIu64 "\t%u\t%u\t%u\n",
db_getabundance(sp->seqno_first),
sp->singletons, 0U, 0U);
progress_update(i);
}
progress_done();
}
fprintf(logfile, "\n");
fprintf(logfile, "Number of swarms: %" PRIu64 "\n", swarmcount);
fprintf(logfile, "Largest swarm: %u\n", maxsize);
fprintf(logfile, "Heaviest swarm: %" PRIu64 "\n", maxmass);
xfree(nextseqtab);
xfree(hashtable);
}
<|endoftext|> |
<commit_before>#include "FluidProperties3EqnMaterial.h"
#include "SinglePhaseFluidProperties.h"
#include "Numerics.h"
template <>
InputParameters
validParams<FluidProperties3EqnMaterial>()
{
InputParameters params = validParams<Material>();
params.addRequiredCoupledVar("area", "Cross-sectional area");
params.addRequiredCoupledVar("rhoA", "Conserved density");
params.addRequiredCoupledVar("rhouA", "Conserved momentum");
params.addRequiredCoupledVar("rhoEA", "Conserved total energy");
params.addRequiredParam<UserObjectName>("fp", "The name of the user object for fluid properties");
return params;
}
FluidProperties3EqnMaterial::FluidProperties3EqnMaterial(const InputParameters & parameters)
: DerivativeMaterialInterfaceRelap<Material>(parameters),
_area(coupledValue("area")),
_rhoA(coupledValue("rhoA")),
_rhouA(coupledValue("rhouA")),
_rhoEA(coupledValue("rhoEA")),
_rho(declareProperty<Real>("rho")),
_drho_drhoA(declarePropertyDerivativeRelap<Real>("rho", "rhoA")),
_v(declareProperty<Real>("specific_volume")),
_dv_drhoA(declarePropertyDerivativeRelap<Real>("specific_volume", "rhoA")),
_vel(declareProperty<Real>("vel")),
_dvel_drhoA(declarePropertyDerivativeRelap<Real>("vel", "rhoA")),
_dvel_drhouA(declarePropertyDerivativeRelap<Real>("vel", "rhouA")),
_e(declareProperty<Real>("specific_internal_energy")),
_de_drhoA(declarePropertyDerivativeRelap<Real>("specific_internal_energy", "rhoA")),
_de_drhouA(declarePropertyDerivativeRelap<Real>("specific_internal_energy", "rhouA")),
_de_drhoEA(declarePropertyDerivativeRelap<Real>("specific_internal_energy", "rhoEA")),
_p(declareProperty<Real>("pressure")),
_dp_drhoA(declarePropertyDerivativeRelap<Real>("pressure", "rhoA")),
_dp_drhouA(declarePropertyDerivativeRelap<Real>("pressure", "rhouA")),
_dp_drhoEA(declarePropertyDerivativeRelap<Real>("pressure", "rhoEA")),
_T(declareProperty<Real>("temperature")),
_dT_drhoA(declarePropertyDerivativeRelap<Real>("temperature", "rhoA")),
_dT_drhouA(declarePropertyDerivativeRelap<Real>("temperature", "rhouA")),
_dT_drhoEA(declarePropertyDerivativeRelap<Real>("temperature", "rhoEA")),
_c(declareProperty<Real>("c")),
_cp(declareProperty<Real>("cp")),
_cv(declareProperty<Real>("cv")),
_mu(declareProperty<Real>("mu")),
_k(declareProperty<Real>("k")),
_fp(getUserObject<SinglePhaseFluidProperties>("fp"))
{
}
void
FluidProperties3EqnMaterial::computeQpProperties()
{
_rho[_qp] = _rhoA[_qp] / _area[_qp];
_drho_drhoA[_qp] = 1.0 / _area[_qp];
_v[_qp] = 1.0 / _rho[_qp];
_dv_drhoA[_qp] = dv_darhoA(_area[_qp], _rhoA[_qp]);
_vel[_qp] = _rhouA[_qp] / _rhoA[_qp];
_dvel_drhoA[_qp] = -_rhouA[_qp] / (_rhoA[_qp] * _rhoA[_qp]);
_dvel_drhouA[_qp] = 1.0 / _rhoA[_qp];
_e[_qp] = (_rhoEA[_qp] - 0.5 * _rhouA[_qp] * _rhouA[_qp] / _rhoA[_qp]) / _rhoA[_qp];
_de_drhoA[_qp] = de_darhoA(_rhoA[_qp], _rhouA[_qp], _rhoEA[_qp]);
_de_drhouA[_qp] = de_darhouA(_rhoA[_qp], _rhouA[_qp]);
_de_drhoEA[_qp] = de_darhoEA(_rhoA[_qp]);
_p[_qp] = _fp.pressure(_v[_qp], _e[_qp]);
_T[_qp] = _fp.temperature(_v[_qp], _e[_qp]);
Real dp_dv, dp_de;
Real dT_dv, dT_de;
_fp.dp_duv(_v[_qp], _e[_qp], dp_dv, dp_de, dT_dv, dT_de);
_dp_drhoA[_qp] = dp_dv * _dv_drhoA[_qp] + dp_de * _de_drhoA[_qp];
_dp_drhouA[_qp] = dp_de * _de_drhouA[_qp];
_dT_drhoA[_qp] = dT_dv * _dv_drhoA[_qp] + dT_de * _de_drhoA[_qp];
_dT_drhouA[_qp] = dT_de * _de_drhouA[_qp];
_dp_drhoEA[_qp] = dp_de * _de_drhoEA[_qp];
_dT_drhoEA[_qp] = dT_de * _de_drhoEA[_qp];
_c[_qp] = _fp.c(_v[_qp], _e[_qp]);
_cp[_qp] = _fp.cp(_v[_qp], _e[_qp]);
_cv[_qp] = _fp.cv(_v[_qp], _e[_qp]);
_mu[_qp] = _fp.mu(_v[_qp], _e[_qp]);
_k[_qp] = _fp.k(_v[_qp], _e[_qp]);
}
<commit_msg>Applied naming conventions to pressure<commit_after>#include "FluidProperties3EqnMaterial.h"
#include "SinglePhaseFluidProperties.h"
#include "Numerics.h"
template <>
InputParameters
validParams<FluidProperties3EqnMaterial>()
{
InputParameters params = validParams<Material>();
params.addRequiredCoupledVar("area", "Cross-sectional area");
params.addRequiredCoupledVar("rhoA", "Conserved density");
params.addRequiredCoupledVar("rhouA", "Conserved momentum");
params.addRequiredCoupledVar("rhoEA", "Conserved total energy");
params.addRequiredParam<UserObjectName>("fp", "The name of the user object for fluid properties");
return params;
}
FluidProperties3EqnMaterial::FluidProperties3EqnMaterial(const InputParameters & parameters)
: DerivativeMaterialInterfaceRelap<Material>(parameters),
_area(coupledValue("area")),
_rhoA(coupledValue("rhoA")),
_rhouA(coupledValue("rhouA")),
_rhoEA(coupledValue("rhoEA")),
_rho(declareProperty<Real>("rho")),
_drho_drhoA(declarePropertyDerivativeRelap<Real>("rho", "rhoA")),
_v(declareProperty<Real>("v")),
_dv_drhoA(declarePropertyDerivativeRelap<Real>("v", "rhoA")),
_vel(declareProperty<Real>("vel")),
_dvel_drhoA(declarePropertyDerivativeRelap<Real>("vel", "rhoA")),
_dvel_drhouA(declarePropertyDerivativeRelap<Real>("vel", "rhouA")),
_e(declareProperty<Real>("e")),
_de_drhoA(declarePropertyDerivativeRelap<Real>("e", "rhoA")),
_de_drhouA(declarePropertyDerivativeRelap<Real>("e", "rhouA")),
_de_drhoEA(declarePropertyDerivativeRelap<Real>("e", "rhoEA")),
_p(declareProperty<Real>("p")),
_dp_drhoA(declarePropertyDerivativeRelap<Real>("p", "rhoA")),
_dp_drhouA(declarePropertyDerivativeRelap<Real>("p", "rhouA")),
_dp_drhoEA(declarePropertyDerivativeRelap<Real>("p", "rhoEA")),
_T(declareProperty<Real>("temperature")),
_dT_drhoA(declarePropertyDerivativeRelap<Real>("temperature", "rhoA")),
_dT_drhouA(declarePropertyDerivativeRelap<Real>("temperature", "rhouA")),
_dT_drhoEA(declarePropertyDerivativeRelap<Real>("temperature", "rhoEA")),
_c(declareProperty<Real>("c")),
_cp(declareProperty<Real>("cp")),
_cv(declareProperty<Real>("cv")),
_mu(declareProperty<Real>("mu")),
_k(declareProperty<Real>("k")),
_fp(getUserObject<SinglePhaseFluidProperties>("fp"))
{
}
void
FluidProperties3EqnMaterial::computeQpProperties()
{
_rho[_qp] = _rhoA[_qp] / _area[_qp];
_drho_drhoA[_qp] = 1.0 / _area[_qp];
_v[_qp] = 1.0 / _rho[_qp];
_dv_drhoA[_qp] = dv_darhoA(_area[_qp], _rhoA[_qp]);
_vel[_qp] = _rhouA[_qp] / _rhoA[_qp];
_dvel_drhoA[_qp] = -_rhouA[_qp] / (_rhoA[_qp] * _rhoA[_qp]);
_dvel_drhouA[_qp] = 1.0 / _rhoA[_qp];
_e[_qp] = (_rhoEA[_qp] - 0.5 * _rhouA[_qp] * _rhouA[_qp] / _rhoA[_qp]) / _rhoA[_qp];
_de_drhoA[_qp] = de_darhoA(_rhoA[_qp], _rhouA[_qp], _rhoEA[_qp]);
_de_drhouA[_qp] = de_darhouA(_rhoA[_qp], _rhouA[_qp]);
_de_drhoEA[_qp] = de_darhoEA(_rhoA[_qp]);
_p[_qp] = _fp.pressure(_v[_qp], _e[_qp]);
_T[_qp] = _fp.temperature(_v[_qp], _e[_qp]);
Real dp_dv, dp_de;
Real dT_dv, dT_de;
_fp.dp_duv(_v[_qp], _e[_qp], dp_dv, dp_de, dT_dv, dT_de);
_dp_drhoA[_qp] = dp_dv * _dv_drhoA[_qp] + dp_de * _de_drhoA[_qp];
_dp_drhouA[_qp] = dp_de * _de_drhouA[_qp];
_dT_drhoA[_qp] = dT_dv * _dv_drhoA[_qp] + dT_de * _de_drhoA[_qp];
_dT_drhouA[_qp] = dT_de * _de_drhouA[_qp];
_dp_drhoEA[_qp] = dp_de * _de_drhoEA[_qp];
_dT_drhoEA[_qp] = dT_de * _de_drhoEA[_qp];
_c[_qp] = _fp.c(_v[_qp], _e[_qp]);
_cp[_qp] = _fp.cp(_v[_qp], _e[_qp]);
_cv[_qp] = _fp.cv(_v[_qp], _e[_qp]);
_mu[_qp] = _fp.mu(_v[_qp], _e[_qp]);
_k[_qp] = _fp.k(_v[_qp], _e[_qp]);
}
<|endoftext|> |
<commit_before>#include "draw.hpp"
#include <algorithm>
#include <iostream>
#include <sstream>
#include "args.hpp"
#include "config.hpp"
#include "task.hpp"
#include "todolist.hpp"
#include "win.hpp"
using std::string;
using std::stringstream;
// ===================|
// internal functions |
// ===================|
void drawText(string text, int x, int y);
WINDOW* createWindow(int startX, int startY, int width, int height);
void setCurrentWindow(WINDOW *curWin);
std::string buildTitle(TodoList *list);
void drawTitle(TodoList* list);
void drawControls();
void drawTasks(TodoList* list, unsigned selected);
void inverseOn();
void inverseOff();
void colorOn(int pair);
void colorOff(int pair);
void colorMarkOn(string mark);
void colorMarkOff(string mark);
// ===================|
// internal variables |
// ===================|
WINDOW *taskWindow;
WINDOW *inputWindow;
WINDOW *controlWindow;
WINDOW *titleWindow;
WINDOW *taskWindowBorder;
WINDOW *inputWindowBorder;
WINDOW *controlWindowBorder;
WINDOW *currentWindow;
Win *titleWin;
int startX;
int startY;
int width;
int height;
unsigned xpos;
unsigned ypos;
unsigned startTask = 0;
unsigned endTask = 0;
unsigned int listOff = 0;
bool colors = false;
/////////////////////////////////////////
// start curses mode and create windows
void Draw::init()
{
std::cout << "\033]0;" << "todo" << "\7" << std::flush;
initscr();
raw();
use_default_colors();
if (useColors() && has_colors()){
start_color();
init_pair(TITLE_COLOR_PAIR, TITLE_FOREGROUND, TITLE_BACKGROUND);
init_pair(GUTTER_COLOR_PAIR, GUTTER_FOREGROUND, GUTTER_BACKGROUND);
init_pair(SELECT_COLOR_PAIR, SELECT_FOREGROUND, SELECT_BACKGROUND);
init_pair(BORDER_COLOR_PAIR, BORDER_FOREGROUND, BORDER_BACKGROUND);
init_pair(MARK_COLOR_PAIR, MARK_FOREGROUND, MARK_BACKGROUND);
init_pair(MARK_COLOR_PAIR_DONE, MARK_FOREGROUND_DONE,
MARK_BACKGROUND_DONE);
colors = true;
}
Win::setColors(colors);
mouseinterval(0);
keypad(stdscr, true);
noecho();
clear();
refresh();
curs_set(0);
startX = listStartX;
startY = listStartY;
width = COLS - startX - 2;
height = LINES * listHeight;
taskWindowBorder = createWindow(startX, startY, width, height);
taskWindow = createWindow(startX + 1, startY + 1,
width - 2, height - 2);
int inHeight = inputHeight * LINES;
inHeight = std::max(inHeight, 4);
inputWindowBorder = createWindow(inputStartX, inputStartY,
COLS - inputStartX - 2, inHeight);
inputWindow = createWindow(inputStartX + 1, inputStartY + 1,
COLS - inputStartX - 4, inHeight - 2);
controlWindowBorder = createWindow(inputStartX, inputStartY,
COLS - inputStartX - 2, inHeight);
controlWindow = createWindow(inputStartX + 1, inputStartY + 1,
COLS - inputStartX - 4, inHeight - 2);
titleWindow = createWindow(0, 0, COLS, titleHeight);
setCurrentWindow(taskWindow);
titleWin = new Win(0, 0, COLS, titleHeight, false);
}
//////////////////////
// main draw function
void Draw::draw(TodoList *list, unsigned selected)
{
werase(inputWindow);
werase(inputWindowBorder);
drawTitle(list);
drawControls();
drawTasks(list, selected);
}
////////////////////////
// act on mouse events
void Draw::mouse(MEVENT event, TodoList *list,
unsigned &selected, bool button)
{
int x = event.x;
int y = event.y;
if (wmouse_trafo(taskWindow, &y, &x, false)){
unsigned pos = listOff + y - 1;
if (pos < list->size()){
if (!button){
selected = pos;
} else{
list->at(pos).toggleComplete();
}
}
}
}
///////////////////////////////////////
// get an input string for a new task
string Draw::getInput()
{
echo();
werase(controlWindow);
werase(controlWindowBorder);
setCurrentWindow(inputWindowBorder);
if (colors){
colorOn(BORDER_COLOR_PAIR);
}
box(inputWindowBorder, 0, 0);
inverseOn();
drawText("[New task]", 0, 0);
inverseOff();
if (colors){
colorOff(BORDER_COLOR_PAIR);
}
setCurrentWindow(inputWindow);
wrefresh(inputWindowBorder);
wrefresh(inputWindow);
curs_set(1);
char tmp[charBufferSize];
mvwgetnstr(inputWindow, 0, 0, tmp, charBufferSize);
setCurrentWindow(taskWindow);
box(inputWindowBorder, ' ', ' ');
werase(inputWindow);
werase(inputWindowBorder);
curs_set(0);
noecho();
return std::string(tmp);
}
void drawTitle(TodoList* list)
{
titleWin->clear();
titleWin->inverse();
titleWin->color(TITLE_COLOR_PAIR);
titleWin->print(buildTitle(list), 0, 0);
titleWin->colorOff(TITLE_COLOR_PAIR);
titleWin->inverseOff();
titleWin->color(BORDER_COLOR_PAIR, true);
titleWin->draw();
}
// draw the control panel
void drawControls()
{
setCurrentWindow(controlWindow);
wmove(controlWindow, 0, 0);
stringstream line;
line << "[" << ((char) EXIT_KEY) << "]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " quit ");
line.str("");
line << "[Space]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " new task ");
line.str("");
line << "[" << ((char) MOVE_UP_KEY) << "]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " move task up ");
line.str("");
wmove(controlWindow, 1, 0);
line << "[" << ((char) REMOVE_KEY) << "]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " delete task ");
line.str("");
line << "[Return]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " mark task done ");
line.str("");
line << "[" << ((char) MOVE_DOWN_KEY) << "]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " move task down ");
line.str("");
setCurrentWindow(controlWindowBorder);
if (colors){
colorOn(BORDER_COLOR_PAIR);
}
box(controlWindowBorder, 0, 0);
inverseOn();
drawText("[Controls]", 0, 0);
inverseOff();
if (colors){
colorOff(BORDER_COLOR_PAIR);
}
wrefresh(controlWindowBorder);
wrefresh(controlWindow);
}
void drawTasks(TodoList* list, unsigned selected)
{
auto tasks = list->tasks();
setCurrentWindow(taskWindowBorder);
if (colors){
colorOn(BORDER_COLOR_PAIR);
}
box(taskWindowBorder, 0, 0);
inverseOn();
drawText("[Tasks]", 0, 0);
inverseOff();
if (colors){
colorOff(BORDER_COLOR_PAIR);
}
setCurrentWindow(taskWindow);
werase(taskWindow);
if (tasks && tasks->size() != 0){
xpos = 1;
ypos = 1;
unsigned numTasks = height - 2;
endTask = tasks->size();
if (endTask > numTasks){
endTask = numTasks;
}
if (numTasks <= tasks->size()){
while (selected > endTask + listOff - 2 && selected != 0){
listOff++;
}
while (selected < startTask + listOff && selected != list->size() - 1){
listOff--;
}
} else{
listOff = 0;
}
for (unsigned i = startTask + listOff; i < endTask + listOff; i++){
if (showNumbers){
inverseOn();
if (colors){
colorOn(GUTTER_COLOR_PAIR);
}
std::string number = std::to_string(i);
if (!zeroIndexNumbers){
number = std::to_string(i + 1);
}
if (number.size() < 2){
number = "0"+number;
}
drawText(number + ")", xpos, ypos);
if (colors){
colorOff(GUTTER_COLOR_PAIR);
}
inverseOff();
xpos += 5;
}
if (i == selected){
inverseOn();
std::string tmp = tasks->at(i).task();
std::string line = tmp;
if (highlightWholeLine){
for (int k = tmp.size() + xpos; k < width - 2; k++){
line += " ";
}
}
std::string mark = line.substr(0, STRING_COMPLETE.size());
line = line.substr(mark.size());
colorMarkOn(mark);
drawText(mark, xpos, ypos);
colorMarkOff(mark);
if (colors){
colorOn(SELECT_COLOR_PAIR);
}
drawText(line, xpos + mark.size(), ypos);
if (colors){
colorOff(SELECT_COLOR_PAIR);
}
inverseOff();
} else{
std::string tmp = tasks->at(i).task();
std::string text = tmp;
std::string mark = text.substr(0, STRING_COMPLETE.size());
text = text.substr(mark.size());
colorMarkOn(mark);
drawText(mark, xpos, ypos);
colorMarkOff(mark);
drawText(text, xpos + mark.size(), ypos);
}
ypos++;
if (ypos > numTasks || i >= tasks->size() - 1){
break;
}
if (showNumbers){
xpos -= 5;
}
}
}
wrefresh(taskWindowBorder);
wrefresh(taskWindow);
}
// draw text to the current window
void drawText(std::string text, int x, int y)
{
mvwprintw(currentWindow, y, x, text.c_str());
}
// create a new window
WINDOW* createWindow(int startX, int startY, int width, int height)
{
WINDOW *win;
win = newwin(height, width, startY, startX);
return win;
}
// set the current window
void setCurrentWindow(WINDOW* curWin)
{
currentWindow = curWin;
}
// draw text in inverse
void inverseOn()
{
wattron(currentWindow, A_STANDOUT);
}
// draw text normally
void inverseOff()
{
wattroff(currentWindow, A_STANDOUT);
}
// turn on a color pair
void colorOn(int pair)
{
wattron(currentWindow, COLOR_PAIR(pair));
}
// turn off a color pair
void colorOff(int pair)
{
wattroff(currentWindow, COLOR_PAIR(pair));
}
///////////////////////////////////
// stop curses and delete windows
void Draw::stop()
{
delwin(taskWindow);
delwin(inputWindow);
delwin(titleWindow);
delwin(taskWindowBorder);
delwin(inputWindowBorder);
delete titleWin;
endwin();
curs_set(1);
}
// create the title string
std::string buildTitle(TodoList *list)
{
std::string title = "[todo version "+vn+"]";
unsigned cent = (COLS - list->name.size() - 2) / 2;
for (unsigned i = title.size(); i < cent; i++){
title += division;
}
title += "[";
title += list->name;
title += "]";
std::string stats = "[";
stats += std::to_string(list->completed());
stats += "/";
stats += std::to_string(list->size());
stats += " -> ";
if (list->size() == 0){
stats += "NaN";
} else{
stats += std::to_string((int) ((float) list->completed() / (float) list->size() * 100));
stats += "%";
}
stats += "]";
for (unsigned i = title.size() + stats.size(); i < (unsigned)COLS; i++){
title += division;
}
title += stats;
return title;
}
void colorMarkOn(std::string mark)
{
if (colors){
if (mark == STRING_COMPLETE){
colorOn(MARK_COLOR_PAIR_DONE);
} else{
colorOn(MARK_COLOR_PAIR);
}
}
}
void colorMarkOff(std::string mark)
{
if (colors){
if (mark == STRING_COMPLETE){
colorOff(MARK_COLOR_PAIR_DONE);
} else{
colorOff(MARK_COLOR_PAIR);
}
}
}
<commit_msg>removed code for old title<commit_after>#include "draw.hpp"
#include <algorithm>
#include <iostream>
#include <sstream>
#include "args.hpp"
#include "config.hpp"
#include "task.hpp"
#include "todolist.hpp"
#include "win.hpp"
using std::string;
using std::stringstream;
// ===================|
// internal functions |
// ===================|
void drawText(string text, int x, int y);
WINDOW* createWindow(int startX, int startY, int width, int height);
void setCurrentWindow(WINDOW *curWin);
std::string buildTitle(TodoList *list);
void drawTitle(TodoList* list);
void drawControls();
void drawTasks(TodoList* list, unsigned selected);
void inverseOn();
void inverseOff();
void colorOn(int pair);
void colorOff(int pair);
void colorMarkOn(string mark);
void colorMarkOff(string mark);
// ===================|
// internal variables |
// ===================|
WINDOW *taskWindow;
WINDOW *inputWindow;
WINDOW *controlWindow;
WINDOW *taskWindowBorder;
WINDOW *inputWindowBorder;
WINDOW *controlWindowBorder;
WINDOW *currentWindow;
Win *titleWin;
int startX;
int startY;
int width;
int height;
unsigned xpos;
unsigned ypos;
unsigned startTask = 0;
unsigned endTask = 0;
unsigned int listOff = 0;
bool colors = false;
/////////////////////////////////////////
// start curses mode and create windows
void Draw::init()
{
std::cout << "\033]0;" << "todo" << "\7" << std::flush;
initscr();
raw();
use_default_colors();
if (useColors() && has_colors()){
start_color();
init_pair(TITLE_COLOR_PAIR, TITLE_FOREGROUND, TITLE_BACKGROUND);
init_pair(GUTTER_COLOR_PAIR, GUTTER_FOREGROUND, GUTTER_BACKGROUND);
init_pair(SELECT_COLOR_PAIR, SELECT_FOREGROUND, SELECT_BACKGROUND);
init_pair(BORDER_COLOR_PAIR, BORDER_FOREGROUND, BORDER_BACKGROUND);
init_pair(MARK_COLOR_PAIR, MARK_FOREGROUND, MARK_BACKGROUND);
init_pair(MARK_COLOR_PAIR_DONE, MARK_FOREGROUND_DONE,
MARK_BACKGROUND_DONE);
colors = true;
}
Win::setColors(colors);
mouseinterval(0);
keypad(stdscr, true);
noecho();
clear();
refresh();
curs_set(0);
startX = listStartX;
startY = listStartY;
width = COLS - startX - 2;
height = LINES * listHeight;
taskWindowBorder = createWindow(startX, startY, width, height);
taskWindow = createWindow(startX + 1, startY + 1,
width - 2, height - 2);
int inHeight = inputHeight * LINES;
inHeight = std::max(inHeight, 4);
inputWindowBorder = createWindow(inputStartX, inputStartY,
COLS - inputStartX - 2, inHeight);
inputWindow = createWindow(inputStartX + 1, inputStartY + 1,
COLS - inputStartX - 4, inHeight - 2);
controlWindowBorder = createWindow(inputStartX, inputStartY,
COLS - inputStartX - 2, inHeight);
controlWindow = createWindow(inputStartX + 1, inputStartY + 1,
COLS - inputStartX - 4, inHeight - 2);
setCurrentWindow(taskWindow);
titleWin = new Win(0, 0, COLS, titleHeight, false);
}
//////////////////////
// main draw function
void Draw::draw(TodoList *list, unsigned selected)
{
werase(inputWindow);
werase(inputWindowBorder);
drawTitle(list);
drawControls();
drawTasks(list, selected);
}
////////////////////////
// act on mouse events
void Draw::mouse(MEVENT event, TodoList *list,
unsigned &selected, bool button)
{
int x = event.x;
int y = event.y;
if (wmouse_trafo(taskWindow, &y, &x, false)){
unsigned pos = listOff + y - 1;
if (pos < list->size()){
if (!button){
selected = pos;
} else{
list->at(pos).toggleComplete();
}
}
}
}
///////////////////////////////////////
// get an input string for a new task
string Draw::getInput()
{
echo();
werase(controlWindow);
werase(controlWindowBorder);
setCurrentWindow(inputWindowBorder);
if (colors){
colorOn(BORDER_COLOR_PAIR);
}
box(inputWindowBorder, 0, 0);
inverseOn();
drawText("[New task]", 0, 0);
inverseOff();
if (colors){
colorOff(BORDER_COLOR_PAIR);
}
setCurrentWindow(inputWindow);
wrefresh(inputWindowBorder);
wrefresh(inputWindow);
curs_set(1);
char tmp[charBufferSize];
mvwgetnstr(inputWindow, 0, 0, tmp, charBufferSize);
setCurrentWindow(taskWindow);
box(inputWindowBorder, ' ', ' ');
werase(inputWindow);
werase(inputWindowBorder);
curs_set(0);
noecho();
return std::string(tmp);
}
////////////////////
// draw the title
void drawTitle(TodoList* list)
{
titleWin->clear();
titleWin->inverse();
titleWin->color(TITLE_COLOR_PAIR);
titleWin->print(buildTitle(list), 0, 0);
titleWin->colorOff(TITLE_COLOR_PAIR);
titleWin->inverseOff();
titleWin->color(BORDER_COLOR_PAIR, true);
titleWin->draw();
}
// draw the control panel
void drawControls()
{
setCurrentWindow(controlWindow);
wmove(controlWindow, 0, 0);
stringstream line;
line << "[" << ((char) EXIT_KEY) << "]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " quit ");
line.str("");
line << "[Space]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " new task ");
line.str("");
line << "[" << ((char) MOVE_UP_KEY) << "]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " move task up ");
line.str("");
wmove(controlWindow, 1, 0);
line << "[" << ((char) REMOVE_KEY) << "]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " delete task ");
line.str("");
line << "[Return]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " mark task done ");
line.str("");
line << "[" << ((char) MOVE_DOWN_KEY) << "]";
wprintw(controlWindow, line.str().c_str());
wprintw(controlWindow, " move task down ");
line.str("");
setCurrentWindow(controlWindowBorder);
if (colors){
colorOn(BORDER_COLOR_PAIR);
}
box(controlWindowBorder, 0, 0);
inverseOn();
drawText("[Controls]", 0, 0);
inverseOff();
if (colors){
colorOff(BORDER_COLOR_PAIR);
}
wrefresh(controlWindowBorder);
wrefresh(controlWindow);
}
void drawTasks(TodoList* list, unsigned selected)
{
auto tasks = list->tasks();
setCurrentWindow(taskWindowBorder);
if (colors){
colorOn(BORDER_COLOR_PAIR);
}
box(taskWindowBorder, 0, 0);
inverseOn();
drawText("[Tasks]", 0, 0);
inverseOff();
if (colors){
colorOff(BORDER_COLOR_PAIR);
}
setCurrentWindow(taskWindow);
werase(taskWindow);
if (tasks && tasks->size() != 0){
xpos = 1;
ypos = 1;
unsigned numTasks = height - 2;
endTask = tasks->size();
if (endTask > numTasks){
endTask = numTasks;
}
if (numTasks <= tasks->size()){
while (selected > endTask + listOff - 2 && selected != 0){
listOff++;
}
while (selected < startTask + listOff && selected != list->size() - 1){
listOff--;
}
} else{
listOff = 0;
}
for (unsigned i = startTask + listOff; i < endTask + listOff; i++){
if (showNumbers){
inverseOn();
if (colors){
colorOn(GUTTER_COLOR_PAIR);
}
std::string number = std::to_string(i);
if (!zeroIndexNumbers){
number = std::to_string(i + 1);
}
if (number.size() < 2){
number = "0"+number;
}
drawText(number + ")", xpos, ypos);
if (colors){
colorOff(GUTTER_COLOR_PAIR);
}
inverseOff();
xpos += 5;
}
if (i == selected){
inverseOn();
std::string tmp = tasks->at(i).task();
std::string line = tmp;
if (highlightWholeLine){
for (int k = tmp.size() + xpos; k < width - 2; k++){
line += " ";
}
}
std::string mark = line.substr(0, STRING_COMPLETE.size());
line = line.substr(mark.size());
colorMarkOn(mark);
drawText(mark, xpos, ypos);
colorMarkOff(mark);
if (colors){
colorOn(SELECT_COLOR_PAIR);
}
drawText(line, xpos + mark.size(), ypos);
if (colors){
colorOff(SELECT_COLOR_PAIR);
}
inverseOff();
} else{
std::string tmp = tasks->at(i).task();
std::string text = tmp;
std::string mark = text.substr(0, STRING_COMPLETE.size());
text = text.substr(mark.size());
colorMarkOn(mark);
drawText(mark, xpos, ypos);
colorMarkOff(mark);
drawText(text, xpos + mark.size(), ypos);
}
ypos++;
if (ypos > numTasks || i >= tasks->size() - 1){
break;
}
if (showNumbers){
xpos -= 5;
}
}
}
wrefresh(taskWindowBorder);
wrefresh(taskWindow);
}
// draw text to the current window
void drawText(std::string text, int x, int y)
{
mvwprintw(currentWindow, y, x, text.c_str());
}
// create a new window
WINDOW* createWindow(int startX, int startY, int width, int height)
{
WINDOW *win;
win = newwin(height, width, startY, startX);
return win;
}
// set the current window
void setCurrentWindow(WINDOW* curWin)
{
currentWindow = curWin;
}
// draw text in inverse
void inverseOn()
{
wattron(currentWindow, A_STANDOUT);
}
// draw text normally
void inverseOff()
{
wattroff(currentWindow, A_STANDOUT);
}
// turn on a color pair
void colorOn(int pair)
{
wattron(currentWindow, COLOR_PAIR(pair));
}
// turn off a color pair
void colorOff(int pair)
{
wattroff(currentWindow, COLOR_PAIR(pair));
}
///////////////////////////////////
// stop curses and delete windows
void Draw::stop()
{
delwin(taskWindow);
delwin(inputWindow);
delwin(taskWindowBorder);
delwin(inputWindowBorder);
delete titleWin;
endwin();
curs_set(1);
}
// create the title string
std::string buildTitle(TodoList *list)
{
std::string title = "[todo version "+vn+"]";
unsigned cent = (COLS - list->name.size() - 2) / 2;
for (unsigned i = title.size(); i < cent; i++){
title += division;
}
title += "[";
title += list->name;
title += "]";
std::string stats = "[";
stats += std::to_string(list->completed());
stats += "/";
stats += std::to_string(list->size());
stats += " -> ";
if (list->size() == 0){
stats += "NaN";
} else{
stats += std::to_string((int) ((float) list->completed() / (float) list->size() * 100));
stats += "%";
}
stats += "]";
for (unsigned i = title.size() + stats.size(); i < (unsigned)COLS; i++){
title += division;
}
title += stats;
return title;
}
void colorMarkOn(std::string mark)
{
if (colors){
if (mark == STRING_COMPLETE){
colorOn(MARK_COLOR_PAIR_DONE);
} else{
colorOn(MARK_COLOR_PAIR);
}
}
}
void colorMarkOff(std::string mark)
{
if (colors){
if (mark == STRING_COMPLETE){
colorOff(MARK_COLOR_PAIR_DONE);
} else{
colorOff(MARK_COLOR_PAIR);
}
}
}
<|endoftext|> |
<commit_before>/* Copyright 2021 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_lite_support/cc/task/processor/image_preprocessor.h"
#include <fstream>
#include <memory>
#include "absl/status/status.h"
#include "tensorflow/lite/core/shims/cc/shims_test_util.h"
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/port/status_matchers.h"
#include "tensorflow_lite_support/cc/task/core/task_utils.h"
#include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h"
namespace tflite {
namespace task {
namespace processor {
namespace {
using ::testing::HasSubstr;
using ::tflite::support::StatusOr;
using ::tflite::task::JoinPath;
using ::tflite::task::core::TfLiteEngine;
using ::tflite::task::vision::DecodeImageFromFile;
using ::tflite::task::vision::FrameBuffer;
using ::tflite::task::vision::ImageData;
constexpr char kTestDataDirectory[] =
"tensorflow_lite_support/cc/test/testdata/task/vision/";
constexpr char kDilatedConvolutionModelWithMetaData[] = "dilated_conv.tflite";
StatusOr<ImageData> LoadImage(std::string image_name) {
return DecodeImageFromFile(
JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name));
}
class DynamicInputTest : public tflite_shims::testing::Test {
public:
void SetUp() {
engine_ = absl::make_unique<TfLiteEngine>();
engine_->BuildModelFromFile(JoinPath("./", kTestDataDirectory,
kDilatedConvolutionModelWithMetaData));
engine_->InitInterpreter();
SUPPORT_ASSERT_OK_AND_ASSIGN(preprocessor_,
ImagePreprocessor::Create(engine_.get(), {0}));
SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg"));
frame_buffer_ = CreateFromRgbRawBuffer(
image.pixel_data, FrameBuffer::Dimension{image.width, image.height});
preprocessor_->Preprocess(*frame_buffer_);
}
protected:
std::unique_ptr<TfLiteEngine> engine_ = nullptr;
std::unique_ptr<FrameBuffer> frame_buffer_ = nullptr;
std::unique_ptr<ImagePreprocessor> preprocessor_ = nullptr;
};
// See if output tensor has been re-dimmed as per the input
// tensor. Expected shape: (1, input_height, input_width, 16).
TEST_F(DynamicInputTest, OutputDimensionCheck) {
EXPECT_TRUE(engine_->interpreter_wrapper()->InvokeWithoutFallback().ok());
EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[0], 1);
EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[1],
engine_->GetInputs()[0]->dims->data[1]);
EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[2],
engine_->GetInputs()[0]->dims->data[2]);
EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[3], 16);
}
// Compare pre-processed input with an already pre-processed
// golden image.
TEST_F(DynamicInputTest, GoldenImageComparison) {
// Get the processed input image.
float* processed_input_data =
tflite::task::core::AssertAndReturnTypedTensor<float>(
engine_->GetInputs()[0]);
bool is_equal = true;
const uint8* image_data = frame_buffer_->plane(0).buffer;
const size_t input_byte_size =
frame_buffer_->plane(0).stride.row_stride_bytes *
frame_buffer_->dimension().height;
for (size_t i = 0; i < input_byte_size / sizeof(uint8);
++i, ++image_data, ++processed_input_data)
is_equal &=
std::fabs(static_cast<float>(*image_data) - *processed_input_data) <=
std::numeric_limits<float>::epsilon();
EXPECT_TRUE(is_equal);
}
// Modifying batch/depth to invalid size after Init()
// call should throw error.
TEST_F(DynamicInputTest, InvalidBatchOrDepthResize) {
// Resized input tensor to invalid batch and depth size.
engine_->interpreter()->ResizeInputTensor(
0, {50, frame_buffer_->dimension().height,
frame_buffer_->dimension().width, 100});
auto process_status = preprocessor_->Preprocess(*frame_buffer_);
EXPECT_EQ(process_status.code(), absl::StatusCode::kInvalidArgument);
EXPECT_THAT(process_status.message(),
HasSubstr("The input tensor should have dimensions 1 x height x "
"width x 3. Got"));
}
} // namespace
} // namespace processor
} // namespace task
} // namespace tflite
<commit_msg>EXPECT_NEAR<commit_after>/* Copyright 2021 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_lite_support/cc/task/processor/image_preprocessor.h"
#include <fstream>
#include <memory>
#include "absl/status/status.h"
#include "tensorflow/lite/core/shims/cc/shims_test_util.h"
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/port/status_matchers.h"
#include "tensorflow_lite_support/cc/task/core/task_utils.h"
#include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h"
namespace tflite {
namespace task {
namespace processor {
namespace {
using ::testing::HasSubstr;
using ::tflite::support::StatusOr;
using ::tflite::task::JoinPath;
using ::tflite::task::core::TfLiteEngine;
using ::tflite::task::vision::DecodeImageFromFile;
using ::tflite::task::vision::FrameBuffer;
using ::tflite::task::vision::ImageData;
constexpr char kTestDataDirectory[] =
"tensorflow_lite_support/cc/test/testdata/task/vision/";
constexpr char kDilatedConvolutionModelWithMetaData[] = "dilated_conv.tflite";
StatusOr<ImageData> LoadImage(std::string image_name) {
return DecodeImageFromFile(
JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name));
}
class DynamicInputTest : public tflite_shims::testing::Test {
public:
void SetUp() {
engine_ = absl::make_unique<TfLiteEngine>();
engine_->BuildModelFromFile(JoinPath("./", kTestDataDirectory,
kDilatedConvolutionModelWithMetaData));
engine_->InitInterpreter();
SUPPORT_ASSERT_OK_AND_ASSIGN(preprocessor_,
ImagePreprocessor::Create(engine_.get(), {0}));
SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg"));
frame_buffer_ = CreateFromRgbRawBuffer(
image.pixel_data, FrameBuffer::Dimension{image.width, image.height});
preprocessor_->Preprocess(*frame_buffer_);
}
protected:
std::unique_ptr<TfLiteEngine> engine_ = nullptr;
std::unique_ptr<FrameBuffer> frame_buffer_ = nullptr;
std::unique_ptr<ImagePreprocessor> preprocessor_ = nullptr;
};
// See if output tensor has been re-dimmed as per the input
// tensor. Expected shape: (1, input_height, input_width, 16).
TEST_F(DynamicInputTest, OutputDimensionCheck) {
EXPECT_TRUE(engine_->interpreter_wrapper()->InvokeWithoutFallback().ok());
EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[0], 1);
EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[1],
engine_->GetInputs()[0]->dims->data[1]);
EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[2],
engine_->GetInputs()[0]->dims->data[2]);
EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[3], 16);
}
// Compare pre-processed input with an already pre-processed
// golden image.
TEST_F(DynamicInputTest, GoldenImageComparison) {
// Get the processed input image.
float* processed_input_data =
tflite::task::core::AssertAndReturnTypedTensor<float>(
engine_->GetInputs()[0]);
const uint8* image_data = frame_buffer_->plane(0).buffer;
const size_t input_byte_size =
frame_buffer_->plane(0).stride.row_stride_bytes *
frame_buffer_->dimension().height;
for (size_t i = 0; i < input_byte_size / sizeof(uint8);
++i, ++image_data, ++processed_input_data)
EXPECT_NEAR(static_cast<float>(*image_data), *processed_input_data,
std::numeric_limits<float>::epsilon());
}
// Modifying batch/depth to invalid size after Init()
// call should throw error.
TEST_F(DynamicInputTest, InvalidBatchOrDepthResize) {
// Resized input tensor to invalid batch and depth size.
engine_->interpreter()->ResizeInputTensor(
0, {50, frame_buffer_->dimension().height,
frame_buffer_->dimension().width, 100});
auto process_status = preprocessor_->Preprocess(*frame_buffer_);
EXPECT_EQ(process_status.code(), absl::StatusCode::kInvalidArgument);
EXPECT_THAT(process_status.message(),
HasSubstr("The input tensor should have dimensions 1 x height x "
"width x 3. Got"));
}
} // namespace
} // namespace processor
} // namespace task
} // namespace tflite
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.