text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: reginfo.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2007-07-18 08:53:24 $ * * 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_svtools.hxx" #include "reginfo.hxx" #ifndef _DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #define MAXREGVALUE 200 // ***************************************************************************** #if defined(WIN) || defined(WNT) #include <tools/svwin.h> #define DBG_HDL DBG_ASSERT(pImp->bValidGroup, "Keine Gruppe gesetzt"); \ if( !pImp->bValidGroup ) return struct RegInfo_Impl { HKEY aGroupHdl; BOOL bValidGroup; }; RegInfo::RegInfo() { pImp=new RegInfo_Impl; pImp->bValidGroup = FALSE; } RegInfo::~RegInfo() { if(pImp->bValidGroup) RegCloseKey( pImp->aGroupHdl ); delete pImp; } String RegInfo::GetKeyName( USHORT nKey ) const { DBG_HDL String::EmptyString(); char aBuffer[MAXREGVALUE]; RegEnumKey( pImp->aGroupHdl, nKey, aBuffer, MAXREGVALUE ); return String( UniString::CreateFromAscii(aBuffer) ); } USHORT RegInfo::GetKeyCount() const { DBG_HDL 0; #ifdef WNT DWORD nKeys; DWORD Dum1=10, Dum2, Dum3, Dum4, Dum5, Dum6, Dum7; char s[10]; FILETIME aDumFileTime; RegQueryInfoKey( pImp->aGroupHdl, s, &Dum1, 0, &nKeys, &Dum2, &Dum3, &Dum4, &Dum5, &Dum6, &Dum7, &aDumFileTime ); return (USHORT) nKeys; #else char aBuffer[MAXREGVALUE]; USHORT n=0; while(RegEnumKey( pImp->aGroupHdl, n, aBuffer, MAXREGVALUE) == ERROR_SUCCESS) n++; return n; #endif } inline String MakeAppGroupString_Impl( const String &rGroup ) { String aGroup( UniString::CreateFromAscii("SvAppGroups\\") ); aGroup+=rGroup; return aGroup; } void RegInfo::SetAppGroup( const String& rGroup ) { aCurrentGroup = MakeAppGroupString_Impl(rGroup); if( pImp->bValidGroup ) { RegCloseKey( pImp->aGroupHdl ); pImp->bValidGroup = FALSE; } ByteString aBStr( aCurrentGroup, osl_getThreadTextEncoding() ); RegCreateKey( HKEY_CLASSES_ROOT, aBStr.GetBuffer(), &pImp->aGroupHdl ); pImp->bValidGroup = TRUE; } void RegInfo::DeleteAppGroup( const String &rGroup ) { String aOldGroup = aCurrentGroup; SetAppGroup( rGroup ); DBG_HDL; USHORT nMax = GetKeyCount(); for( USHORT n = nMax; n--; ) { String aKey( GetKeyName( n )); DeleteKey( aKey ); } RegCloseKey( pImp->aGroupHdl ); ByteString aBStr( rGroup, osl_getThreadTextEncoding() ); RegDeleteKey( HKEY_CLASSES_ROOT, aBStr.GetBuffer() ); pImp->bValidGroup = FALSE; if( rGroup != aOldGroup ) SetAppGroup( aOldGroup ); } BOOL ReadKey_Impl( const String& rKey, HKEY aHdl, String& rResult ) { char s[MAXREGVALUE]; LONG aLen=MAXREGVALUE; ByteString aBStr( rKey, osl_getThreadTextEncoding() ); LONG nRes = RegQueryValue( aHdl, aBStr.GetBuffer(), s, &aLen); if(nRes == ERROR_SUCCESS) { rResult = UniString::CreateFromAscii(s); return TRUE; } else return FALSE; } String RegInfo::ReadKey( const String& rKey ) const { DBG_HDL String::EmptyString(); String aRes; if(ReadKey_Impl( rKey, pImp->aGroupHdl, aRes)) return aRes; else return String::EmptyString(); } String RegInfo::ReadKey( const String& rKey, const String &rDefault ) const { DBG_HDL String::EmptyString(); String aRes; if(ReadKey_Impl( rKey, pImp->aGroupHdl, aRes)) return aRes; else return rDefault; } void RegInfo::WriteKey( const String& rKey, const String& rValue ) { DBG_HDL; ByteString aBStr( rKey, osl_getThreadTextEncoding() ); ByteString aBStr1( rValue, osl_getThreadTextEncoding() ); RegSetValue( pImp->aGroupHdl, aBStr.GetBuffer(), REG_SZ, aBStr1.GetBuffer(), 0); } void RegInfo::DeleteKey( const String& rKey ) { DBG_HDL; ByteString aBStr( rKey, osl_getThreadTextEncoding() ); RegDeleteKey( pImp->aGroupHdl, aBStr.GetBuffer() ); } // ***************************************************************************** #elif defined(OS2) #define INCL_WINSHELLDATA #include <tools/svpm.h> struct RegInfo_Impl { char *pKeyList; String aCurrentApp; void BuildKeyList( const String &rGroup ); }; void RegInfo_Impl::BuildKeyList( const String &rGroup ) { USHORT nLen = 0; do { nLen+=1000; delete[] pKeyList; pKeyList = new char[nLen]; *(int *)pKeyList = 0; } while( PrfQueryProfileString( HINI_USERPROFILE, rGroup, 0, 0, pKeyList, nLen) == nLen); } RegInfo::RegInfo() { pImp=new RegInfo_Impl; pImp->pKeyList = 0; } RegInfo::~RegInfo() { delete[] pImp->pKeyList; delete pImp; } inline String MakeAppGroupString_Impl( const String &rGroup ) { String aGroup("SvAppGroups:"); aGroup+=rGroup; return aGroup; } String RegInfo::GetKeyName( USHORT nKey ) const { if( !pImp->pKeyList ) pImp->BuildKeyList(pImp->aCurrentApp); const char *pc=pImp->pKeyList; for( USHORT n=0; n<nKey; n++ ) while(*pc++); return String(pc); } USHORT RegInfo::GetKeyCount() const { if( !pImp->pKeyList ) pImp->BuildKeyList( pImp->aCurrentApp); const char *pc=pImp->pKeyList; USHORT nRet=0; while(*pc) { while(*pc++); nRet++; } return nRet; } void RegInfo::SetAppGroup( const String& rGroup ) { delete[] pImp->pKeyList; pImp->pKeyList = 0; aCurrentGroup = rGroup; pImp->aCurrentApp = MakeAppGroupString_Impl( rGroup ); } void RegInfo::DeleteAppGroup( const String &rGroup ) { PrfWriteProfileString( HINI_USERPROFILE, MakeAppGroupString_Impl( rGroup ), 0, 0); } String RegInfo::ReadKey( const String& rKey ) const { char *pBuffer= new char[MAXREGVALUE]; *pBuffer=0; PrfQueryProfileString( HINI_USERPROFILE, pImp->aCurrentApp, rKey, 0, pBuffer, MAXREGVALUE); String aRet(pBuffer); delete[] pBuffer; return aRet; } String RegInfo::ReadKey( const String& rKey, const String &rDefault ) const { char *pBuffer= new char[MAXREGVALUE]; *pBuffer=0; PrfQueryProfileString( HINI_USERPROFILE, pImp->aCurrentApp, rKey, rDefault, pBuffer, MAXREGVALUE); String aRet(pBuffer); delete[] pBuffer; return aRet; } void RegInfo::WriteKey( const String& rKey, const String& rValue ) { PrfWriteProfileString( HINI_USERPROFILE, pImp->aCurrentApp, rKey, rValue); } void RegInfo::DeleteKey( const String& rKey ) { PrfWriteProfileString( HINI_USERPROFILE, pImp->aCurrentApp, rKey, 0); } // ***************************************************************************** #else RegInfo::RegInfo() { } RegInfo::~RegInfo() { } String RegInfo::GetKeyName( USHORT ) const { return String::EmptyString(); } USHORT RegInfo::GetKeyCount() const { return 0; } void RegInfo::SetAppGroup( const String& ) { return ; } void RegInfo::DeleteAppGroup( const String& ) { return; } String RegInfo::ReadKey( const String& ) const { return String::EmptyString(); } String RegInfo::ReadKey( const String&, const String& ) const { return String::EmptyString(); } void RegInfo::WriteKey( const String&, const String& ) { return; } void RegInfo::DeleteKey( const String& ) { return; } #endif <commit_msg>INTEGRATION: CWS os2port01 (1.4.24); FILE MERGED 2007/09/05 10:12:15 obr 1.4.24.3: RESYNC: (1.5-1.6); FILE MERGED 2007/08/12 13:37:53 obr 1.4.24.2: RESYNC: (1.4-1.5); FILE MERGED 2006/12/28 15:06:03 ydario 1.4.24.1: OS/2 initial import.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: reginfo.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2007-09-20 16:29:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include "reginfo.hxx" #ifndef _DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #define MAXREGVALUE 200 // ***************************************************************************** #if defined(WIN) || defined(WNT) #include <tools/svwin.h> #define DBG_HDL DBG_ASSERT(pImp->bValidGroup, "Keine Gruppe gesetzt"); \ if( !pImp->bValidGroup ) return struct RegInfo_Impl { HKEY aGroupHdl; BOOL bValidGroup; }; RegInfo::RegInfo() { pImp=new RegInfo_Impl; pImp->bValidGroup = FALSE; } RegInfo::~RegInfo() { if(pImp->bValidGroup) RegCloseKey( pImp->aGroupHdl ); delete pImp; } String RegInfo::GetKeyName( USHORT nKey ) const { DBG_HDL String::EmptyString(); char aBuffer[MAXREGVALUE]; RegEnumKey( pImp->aGroupHdl, nKey, aBuffer, MAXREGVALUE ); return String( UniString::CreateFromAscii(aBuffer) ); } USHORT RegInfo::GetKeyCount() const { DBG_HDL 0; #ifdef WNT DWORD nKeys; DWORD Dum1=10, Dum2, Dum3, Dum4, Dum5, Dum6, Dum7; char s[10]; FILETIME aDumFileTime; RegQueryInfoKey( pImp->aGroupHdl, s, &Dum1, 0, &nKeys, &Dum2, &Dum3, &Dum4, &Dum5, &Dum6, &Dum7, &aDumFileTime ); return (USHORT) nKeys; #else char aBuffer[MAXREGVALUE]; USHORT n=0; while(RegEnumKey( pImp->aGroupHdl, n, aBuffer, MAXREGVALUE) == ERROR_SUCCESS) n++; return n; #endif } inline String MakeAppGroupString_Impl( const String &rGroup ) { String aGroup( UniString::CreateFromAscii("SvAppGroups\\") ); aGroup+=rGroup; return aGroup; } void RegInfo::SetAppGroup( const String& rGroup ) { aCurrentGroup = MakeAppGroupString_Impl(rGroup); if( pImp->bValidGroup ) { RegCloseKey( pImp->aGroupHdl ); pImp->bValidGroup = FALSE; } ByteString aBStr( aCurrentGroup, osl_getThreadTextEncoding() ); RegCreateKey( HKEY_CLASSES_ROOT, aBStr.GetBuffer(), &pImp->aGroupHdl ); pImp->bValidGroup = TRUE; } void RegInfo::DeleteAppGroup( const String &rGroup ) { String aOldGroup = aCurrentGroup; SetAppGroup( rGroup ); DBG_HDL; USHORT nMax = GetKeyCount(); for( USHORT n = nMax; n--; ) { String aKey( GetKeyName( n )); DeleteKey( aKey ); } RegCloseKey( pImp->aGroupHdl ); ByteString aBStr( rGroup, osl_getThreadTextEncoding() ); RegDeleteKey( HKEY_CLASSES_ROOT, aBStr.GetBuffer() ); pImp->bValidGroup = FALSE; if( rGroup != aOldGroup ) SetAppGroup( aOldGroup ); } BOOL ReadKey_Impl( const String& rKey, HKEY aHdl, String& rResult ) { char s[MAXREGVALUE]; LONG aLen=MAXREGVALUE; ByteString aBStr( rKey, osl_getThreadTextEncoding() ); LONG nRes = RegQueryValue( aHdl, aBStr.GetBuffer(), s, &aLen); if(nRes == ERROR_SUCCESS) { rResult = UniString::CreateFromAscii(s); return TRUE; } else return FALSE; } String RegInfo::ReadKey( const String& rKey ) const { DBG_HDL String::EmptyString(); String aRes; if(ReadKey_Impl( rKey, pImp->aGroupHdl, aRes)) return aRes; else return String::EmptyString(); } String RegInfo::ReadKey( const String& rKey, const String &rDefault ) const { DBG_HDL String::EmptyString(); String aRes; if(ReadKey_Impl( rKey, pImp->aGroupHdl, aRes)) return aRes; else return rDefault; } void RegInfo::WriteKey( const String& rKey, const String& rValue ) { DBG_HDL; ByteString aBStr( rKey, osl_getThreadTextEncoding() ); ByteString aBStr1( rValue, osl_getThreadTextEncoding() ); RegSetValue( pImp->aGroupHdl, aBStr.GetBuffer(), REG_SZ, aBStr1.GetBuffer(), 0); } void RegInfo::DeleteKey( const String& rKey ) { DBG_HDL; ByteString aBStr( rKey, osl_getThreadTextEncoding() ); RegDeleteKey( pImp->aGroupHdl, aBStr.GetBuffer() ); } // ***************************************************************************** #elif defined(OS2) #define INCL_WINSHELLDATA #include <svpm.h> struct RegInfo_Impl { char *pKeyList; String aCurrentApp; void BuildKeyList( const String &rGroup ); }; void RegInfo_Impl::BuildKeyList( const String &rGroup ) { ByteString aBStr( rGroup, osl_getThreadTextEncoding() ); USHORT nLen = 0; do { nLen+=1000; delete[] pKeyList; pKeyList = new char[nLen]; *(int *)pKeyList = 0; } while( PrfQueryProfileString( HINI_USERPROFILE, (PCSZ)aBStr.GetBuffer(), 0, 0, pKeyList, nLen) == nLen); } RegInfo::RegInfo() { pImp=new RegInfo_Impl; pImp->pKeyList = 0; } RegInfo::~RegInfo() { delete[] pImp->pKeyList; delete pImp; } inline String MakeAppGroupString_Impl( const String &rGroup ) { String aGroup(UniString::CreateFromAscii("SvAppGroups:")); aGroup+=rGroup; return aGroup; } String RegInfo::GetKeyName( USHORT nKey ) const { if( !pImp->pKeyList ) pImp->BuildKeyList(pImp->aCurrentApp); const char *pc=pImp->pKeyList; for( USHORT n=0; n<nKey; n++ ) while(*pc++); return String(UniString::CreateFromAscii(pc)); } USHORT RegInfo::GetKeyCount() const { if( !pImp->pKeyList ) pImp->BuildKeyList( pImp->aCurrentApp); const char *pc=pImp->pKeyList; USHORT nRet=0; while(*pc) { while(*pc++); nRet++; } return nRet; } void RegInfo::SetAppGroup( const String& rGroup ) { delete[] pImp->pKeyList; pImp->pKeyList = 0; aCurrentGroup = rGroup; pImp->aCurrentApp = MakeAppGroupString_Impl( rGroup ); } void RegInfo::DeleteAppGroup( const String &rGroup ) { ByteString aBStr( MakeAppGroupString_Impl( rGroup ), osl_getThreadTextEncoding() ); PrfWriteProfileString( HINI_USERPROFILE, (PCSZ)aBStr.GetBuffer(), 0, 0); } String RegInfo::ReadKey( const String& rKey ) const { ULONG ulBufferMax = MAXREGVALUE; char *pBuffer= new char[MAXREGVALUE]; ByteString aBStr( pImp->aCurrentApp, osl_getThreadTextEncoding() ); ByteString aBStr1( rKey, osl_getThreadTextEncoding() ); *pBuffer=0; PrfQueryProfileData( HINI_USERPROFILE, (PCSZ)aBStr.GetBuffer(), (PCSZ)aBStr1.GetBuffer(), pBuffer, &ulBufferMax); String aRet(UniString::CreateFromAscii(pBuffer)); delete[] pBuffer; return aRet; } String RegInfo::ReadKey( const String& rKey, const String &rDefault ) const { String aResult = ReadKey(rKey); if (!aResult.Len()) return rDefault; else return aResult; } void RegInfo::WriteKey( const String& rKey, const String& rValue ) { ByteString aBStr( pImp->aCurrentApp, osl_getThreadTextEncoding() ); ByteString aBStr1( rKey, osl_getThreadTextEncoding() ); PrfWriteProfileData( HINI_USERPROFILE, (PCSZ)aBStr.GetBuffer(), (PCSZ)aBStr1.GetBuffer(), (PVOID)rValue.GetBuffer(), rValue.Len()*2); } void RegInfo::DeleteKey( const String& rKey ) { ByteString aBStr( pImp->aCurrentApp, osl_getThreadTextEncoding() ); ByteString aBStr1( rKey, osl_getThreadTextEncoding() ); PrfWriteProfileString( HINI_USERPROFILE, (PCSZ)aBStr.GetBuffer(), (PCSZ)rKey.GetBuffer(), 0); } // ***************************************************************************** #else RegInfo::RegInfo() { } RegInfo::~RegInfo() { } String RegInfo::GetKeyName( USHORT ) const { return String::EmptyString(); } USHORT RegInfo::GetKeyCount() const { return 0; } void RegInfo::SetAppGroup( const String& ) { return ; } void RegInfo::DeleteAppGroup( const String& ) { return; } String RegInfo::ReadKey( const String& ) const { return String::EmptyString(); } String RegInfo::ReadKey( const String&, const String& ) const { return String::EmptyString(); } void RegInfo::WriteKey( const String&, const String& ) { return; } void RegInfo::DeleteKey( const String& ) { return; } #endif <|endoftext|>
<commit_before><commit_msg>unused define<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tresitem.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-06-27 21:46: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #ifndef SVTOOLS_TRESITEM_HXX #include <svtools/tresitem.hxx> #endif using namespace com::sun::star; //============================================================================ // // CntTransferResultItem // //============================================================================ TYPEINIT1_AUTOFACTORY(CntTransferResultItem, SfxPoolItem) //============================================================================ // virtual int CntTransferResultItem::operator ==(SfxPoolItem const & rItem) const { if (CntTransferResultItem * pResultItem = PTR_CAST(CntTransferResultItem, &rItem)) return m_aResult.Source == pResultItem->m_aResult.Source && m_aResult.Target == pResultItem->m_aResult.Target && m_aResult.Result == pResultItem->m_aResult.Result; return false; } //============================================================================ // virtual BOOL CntTransferResultItem::QueryValue(uno::Any & rVal, BYTE) const { rVal <<= m_aResult; return true; } //============================================================================ // virtual BOOL CntTransferResultItem::PutValue(uno::Any const & rVal, BYTE) { return rVal >>= m_aResult; } //============================================================================ // virtual SfxPoolItem * CntTransferResultItem::Clone(SfxItemPool *) const { return new CntTransferResultItem(*this); } <commit_msg>INTEGRATION: CWS changefileheader (1.5.246); FILE MERGED 2008/04/01 12:43:45 thb 1.5.246.2: #i85898# Stripping all external header guards 2008/03/31 13:02:11 rt 1.5.246.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: tresitem.cxx,v $ * $Revision: 1.6 $ * * 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_svtools.hxx" #include <svtools/tresitem.hxx> using namespace com::sun::star; //============================================================================ // // CntTransferResultItem // //============================================================================ TYPEINIT1_AUTOFACTORY(CntTransferResultItem, SfxPoolItem) //============================================================================ // virtual int CntTransferResultItem::operator ==(SfxPoolItem const & rItem) const { if (CntTransferResultItem * pResultItem = PTR_CAST(CntTransferResultItem, &rItem)) return m_aResult.Source == pResultItem->m_aResult.Source && m_aResult.Target == pResultItem->m_aResult.Target && m_aResult.Result == pResultItem->m_aResult.Result; return false; } //============================================================================ // virtual BOOL CntTransferResultItem::QueryValue(uno::Any & rVal, BYTE) const { rVal <<= m_aResult; return true; } //============================================================================ // virtual BOOL CntTransferResultItem::PutValue(uno::Any const & rVal, BYTE) { return rVal >>= m_aResult; } //============================================================================ // virtual SfxPoolItem * CntTransferResultItem::Clone(SfxItemPool *) const { return new CntTransferResultItem(*this); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: numhead.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2006-03-16 13:06: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 * ************************************************************************/ #ifndef NF_NUMHEAD_HXX #define NF_NUMHEAD_HXX #ifndef _STREAM_HXX //autogen #include <tools/stream.hxx> #endif // ----------------------------------------------------------------------- // "Automatischer" Record-Header mit Groessenangabe /* wird fuer SvNumberFormatter nicht gebraucht class SvNumReadHeader { private: SvStream& rStream; ULONG nDataEnd; public: SvNumReadHeader(SvStream& rNewStream); ~SvNumReadHeader(); ULONG BytesLeft() const; }; class SvNumWriteHeader { private: SvStream& rStream; ULONG nDataPos; ULONG nDataSize; public: SvNumWriteHeader(SvStream& rNewStream, ULONG nDefault = 0); ~SvNumWriteHeader(); }; */ // Header mit Groessenangaben fuer mehrere Objekte class ImpSvNumMultipleReadHeader { private: SvStream& rStream; char* pBuf; SvMemoryStream* pMemStream; ULONG nEndPos; ULONG nEntryEnd; public: ImpSvNumMultipleReadHeader(SvStream& rNewStream); ~ImpSvNumMultipleReadHeader(); void StartEntry(); void EndEntry(); ULONG BytesLeft() const; static void Skip( SvStream& ); // komplett ueberspringen }; class ImpSvNumMultipleWriteHeader { private: SvStream& rStream; SvMemoryStream aMemStream; ULONG nDataPos; sal_uInt32 nDataSize; ULONG nEntryStart; public: ImpSvNumMultipleWriteHeader(SvStream& rNewStream, ULONG nDefault = 0); ~ImpSvNumMultipleWriteHeader(); void StartEntry(); void EndEntry(); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.616); FILE MERGED 2008/04/01 15:45:24 thb 1.3.616.2: #i85898# Stripping all external header guards 2008/03/31 13:02:24 rt 1.3.616.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: numhead.hxx,v $ * $Revision: 1.4 $ * * 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 NF_NUMHEAD_HXX #define NF_NUMHEAD_HXX #include <tools/stream.hxx> // ----------------------------------------------------------------------- // "Automatischer" Record-Header mit Groessenangabe /* wird fuer SvNumberFormatter nicht gebraucht class SvNumReadHeader { private: SvStream& rStream; ULONG nDataEnd; public: SvNumReadHeader(SvStream& rNewStream); ~SvNumReadHeader(); ULONG BytesLeft() const; }; class SvNumWriteHeader { private: SvStream& rStream; ULONG nDataPos; ULONG nDataSize; public: SvNumWriteHeader(SvStream& rNewStream, ULONG nDefault = 0); ~SvNumWriteHeader(); }; */ // Header mit Groessenangaben fuer mehrere Objekte class ImpSvNumMultipleReadHeader { private: SvStream& rStream; char* pBuf; SvMemoryStream* pMemStream; ULONG nEndPos; ULONG nEntryEnd; public: ImpSvNumMultipleReadHeader(SvStream& rNewStream); ~ImpSvNumMultipleReadHeader(); void StartEntry(); void EndEntry(); ULONG BytesLeft() const; static void Skip( SvStream& ); // komplett ueberspringen }; class ImpSvNumMultipleWriteHeader { private: SvStream& rStream; SvMemoryStream aMemStream; ULONG nDataPos; sal_uInt32 nDataSize; ULONG nEntryStart; public: ImpSvNumMultipleWriteHeader(SvStream& rNewStream, ULONG nDefault = 0); ~ImpSvNumMultipleWriteHeader(); void StartEntry(); void EndEntry(); }; #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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <ctype.h> #include <stdio.h> #include <tools/urlobj.hxx> #ifndef _SVSTDARR_HXX #define _SVSTDARR_ULONGS #include <svl/svstdarr.hxx> #endif #include <svtools/parhtml.hxx> #include <svtools/htmltokn.h> #include <svtools/htmlkywd.hxx> /* */ // Table for converting option values into strings static HTMLOptionEnum const aScriptLangOptEnums[] = { { OOO_STRING_SVTOOLS_HTML_LG_starbasic, HTML_SL_STARBASIC }, { OOO_STRING_SVTOOLS_HTML_LG_javascript, HTML_SL_JAVASCRIPT }, { OOO_STRING_SVTOOLS_HTML_LG_javascript11,HTML_SL_JAVASCRIPT }, { OOO_STRING_SVTOOLS_HTML_LG_livescript, HTML_SL_JAVASCRIPT }, // { OOO_STRING_SVTOOLS_HTML_LG_unused_javascript, HTML_SL_UNUSEDJS }, // { OOO_STRING_SVTOOLS_HTML_LG_vbscript, HTML_SL_VBSCRIPT }, // { OOO_STRING_SVTOOLS_HTML_LG_starone, HTML_SL_STARONE }, { 0, 0 } }; sal_Bool HTMLParser::ParseScriptOptions( String& rLangString, const String& rBaseURL, HTMLScriptLanguage& rLang, String& rSrc, String& rLibrary, String& rModule ) { const HTMLOptions *pScriptOptions = GetOptions(); rLangString.Erase(); rLang = HTML_SL_JAVASCRIPT; rSrc.Erase(); rLibrary.Erase(); rModule.Erase(); for( sal_uInt16 i = pScriptOptions->Count(); i; ) { const HTMLOption *pOption = (*pScriptOptions)[ --i ]; switch( pOption->GetToken() ) { case HTML_O_LANGUAGE: { rLangString = pOption->GetString(); sal_uInt16 nLang; if( pOption->GetEnum( nLang, aScriptLangOptEnums ) ) rLang = (HTMLScriptLanguage)nLang; else rLang = HTML_SL_UNKNOWN; } break; case HTML_O_SRC: rSrc = INetURLObject::GetAbsURL( rBaseURL, pOption->GetString() ); break; case HTML_O_SDLIBRARY: rLibrary = pOption->GetString(); break; case HTML_O_SDMODULE: rModule = pOption->GetString(); break; } } return sal_True; } void HTMLParser::RemoveSGMLComment( String &rString, sal_Bool bFull ) { sal_Unicode c = 0; while( rString.Len() && ( ' '==(c=rString.GetChar(0)) || '\t'==c || '\r'==c || '\n'==c ) ) rString.Erase( 0, 1 ); while( rString.Len() && ( ' '==(c=rString.GetChar( rString.Len()-1)) || '\t'==c || '\r'==c || '\n'==c ) ) rString.Erase( rString.Len()-1 ); // remove SGML comments if( rString.Len() >= 4 && rString.CompareToAscii( "<!--", 4 ) == COMPARE_EQUAL ) { xub_StrLen nPos = 3; if( bFull ) { // the whole line nPos = 4; while( nPos < rString.Len() && ( ( c = rString.GetChar( nPos )) != '\r' && c != '\n' ) ) ++nPos; if( c == '\r' && nPos+1 < rString.Len() && '\n' == rString.GetChar( nPos+1 )) ++nPos; else if( c != '\n' ) nPos = 3; } rString.Erase( 0, ++nPos ); } if( rString.Len() >=3 && rString.Copy(rString.Len()-3).CompareToAscii("-->") == COMPARE_EQUAL ) { rString.Erase( rString.Len()-3 ); if( bFull ) { // "//" or "'", maybe preceding CR/LF rString.EraseTrailingChars(); xub_StrLen nDel = 0, nLen = rString.Len(); if( nLen >= 2 && rString.Copy(nLen-2).CompareToAscii("//") == COMPARE_EQUAL ) { nDel = 2; } else if( nLen && '\'' == rString.GetChar(nLen-1) ) { nDel = 1; } if( nDel && nLen >= nDel+1 ) { c = rString.GetChar( nLen-(nDel+1) ); if( '\r'==c || '\n'==c ) { nDel++; if( '\n'==c && nLen >= nDel+1 && '\r'==rString.GetChar( nLen-(nDel+1) ) ) nDel++; } } rString.Erase( nLen-nDel ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Removed comments/commented code<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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <ctype.h> #include <stdio.h> #include <tools/urlobj.hxx> #ifndef _SVSTDARR_HXX #define _SVSTDARR_ULONGS #include <svl/svstdarr.hxx> #endif #include <svtools/parhtml.hxx> #include <svtools/htmltokn.h> #include <svtools/htmlkywd.hxx> // Table for converting option values into strings static HTMLOptionEnum const aScriptLangOptEnums[] = { { OOO_STRING_SVTOOLS_HTML_LG_starbasic, HTML_SL_STARBASIC }, { OOO_STRING_SVTOOLS_HTML_LG_javascript, HTML_SL_JAVASCRIPT }, { OOO_STRING_SVTOOLS_HTML_LG_javascript11,HTML_SL_JAVASCRIPT }, { OOO_STRING_SVTOOLS_HTML_LG_livescript, HTML_SL_JAVASCRIPT }, { 0, 0 } }; sal_Bool HTMLParser::ParseScriptOptions( String& rLangString, const String& rBaseURL, HTMLScriptLanguage& rLang, String& rSrc, String& rLibrary, String& rModule ) { const HTMLOptions *pScriptOptions = GetOptions(); rLangString.Erase(); rLang = HTML_SL_JAVASCRIPT; rSrc.Erase(); rLibrary.Erase(); rModule.Erase(); for( sal_uInt16 i = pScriptOptions->Count(); i; ) { const HTMLOption *pOption = (*pScriptOptions)[ --i ]; switch( pOption->GetToken() ) { case HTML_O_LANGUAGE: { rLangString = pOption->GetString(); sal_uInt16 nLang; if( pOption->GetEnum( nLang, aScriptLangOptEnums ) ) rLang = (HTMLScriptLanguage)nLang; else rLang = HTML_SL_UNKNOWN; } break; case HTML_O_SRC: rSrc = INetURLObject::GetAbsURL( rBaseURL, pOption->GetString() ); break; case HTML_O_SDLIBRARY: rLibrary = pOption->GetString(); break; case HTML_O_SDMODULE: rModule = pOption->GetString(); break; } } return sal_True; } void HTMLParser::RemoveSGMLComment( String &rString, sal_Bool bFull ) { sal_Unicode c = 0; while( rString.Len() && ( ' '==(c=rString.GetChar(0)) || '\t'==c || '\r'==c || '\n'==c ) ) rString.Erase( 0, 1 ); while( rString.Len() && ( ' '==(c=rString.GetChar( rString.Len()-1)) || '\t'==c || '\r'==c || '\n'==c ) ) rString.Erase( rString.Len()-1 ); // remove SGML comments if( rString.Len() >= 4 && rString.CompareToAscii( "<!--", 4 ) == COMPARE_EQUAL ) { xub_StrLen nPos = 3; if( bFull ) { // the whole line nPos = 4; while( nPos < rString.Len() && ( ( c = rString.GetChar( nPos )) != '\r' && c != '\n' ) ) ++nPos; if( c == '\r' && nPos+1 < rString.Len() && '\n' == rString.GetChar( nPos+1 )) ++nPos; else if( c != '\n' ) nPos = 3; } rString.Erase( 0, ++nPos ); } if( rString.Len() >=3 && rString.Copy(rString.Len()-3).CompareToAscii("-->") == COMPARE_EQUAL ) { rString.Erase( rString.Len()-3 ); if( bFull ) { // "//" or "'", maybe preceding CR/LF rString.EraseTrailingChars(); xub_StrLen nDel = 0, nLen = rString.Len(); if( nLen >= 2 && rString.Copy(nLen-2).CompareToAscii("//") == COMPARE_EQUAL ) { nDel = 2; } else if( nLen && '\'' == rString.GetChar(nLen-1) ) { nDel = 1; } if( nDel && nLen >= nDel+1 ) { c = rString.GetChar( nLen-(nDel+1) ); if( '\r'==c || '\n'==c ) { nDel++; if( '\n'==c && nLen >= nDel+1 && '\r'==rString.GetChar( nLen-(nDel+1) ) ) nDel++; } } rString.Erase( nLen-nDel ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textprimitive2d.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hdu $ $Date: 2007-02-14 14:41: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 INCLUDED_DRAWINGLAYER_PRIMITIVE_TEXTPRIMITIVE2D_HXX #include <drawinglayer/primitive2d/textprimitive2d.hxx> #endif #ifndef INCLUDED_DRAWINGLAYER_TEXTLAYOUTDEVICE_HXX #include <drawinglayer/primitive2d/textlayoutdevice.hxx> #endif #ifndef _SV_VIRDEV_HXX #include <vcl/virdev.hxx> #endif #ifndef _BGFX_COLOR_BCOLOR_HXX #include <basegfx/color/bcolor.hxx> #endif #ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE2D_POLYPOLYGONPRIMITIVE2D_HXX #include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYGONTOOLS_HXX #include <basegfx/polygon/b2dpolygontools.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYGON_HXX #include <basegfx/polygon/b2dpolygon.hxx> #endif #ifndef _BGFX_NUMERIC_FTOOLS_HXX #include <basegfx/numeric/ftools.hxx> #endif #ifndef _BGFX_TOOLS_CANVASTOOLS_HXX #include <basegfx/tools/canvastools.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace drawinglayer { namespace primitive2d { Font getVclFontFromFontAttributes(const FontAttributes& rFontAttributes, const basegfx::B2DHomMatrix& rTransform) { // decompose matrix to have position and size of text basegfx::B2DVector aScale, aTranslate; double fRotate, fShearX; rTransform.decompose(aScale, aTranslate, fRotate, fShearX); return getVclFontFromFontAttributes(rFontAttributes, aScale, fRotate); } Font getVclFontFromFontAttributes(const FontAttributes& rFontAttributes, const basegfx::B2DVector& rFontSize, double fFontRotation) { sal_uInt32 nWidth(basegfx::fround(fabs(rFontSize.getX()))); sal_uInt32 nHeight(basegfx::fround(fabs(rFontSize.getY()))); if(nWidth == nHeight) { nWidth = 0L; } Font aRetval( rFontAttributes.maFamilyName, rFontAttributes.maStyleName, Size(nWidth, nHeight)); if(!basegfx::fTools::equalZero(fFontRotation)) { sal_Int16 aRotate10th((sal_Int16)(fFontRotation * (-1800.0/F_PI))); aRetval.SetOrientation(aRotate10th % 3600); } aRetval.SetAlign(ALIGN_BASELINE); aRetval.SetCharSet(rFontAttributes.mbSymbol ? RTL_TEXTENCODING_SYMBOL : RTL_TEXTENCODING_UNICODE); aRetval.SetVertical(rFontAttributes.mbVertical ? TRUE : FALSE); aRetval.SetWeight(static_cast<FontWeight>(rFontAttributes.mnWeight)); aRetval.SetItalic(rFontAttributes.mbItalic ? ITALIC_NORMAL : ITALIC_NONE); return aRetval; } FontAttributes getFontAttributesFromVclFont(basegfx::B2DVector& rSize, const Font& rFont) { FontAttributes aRetval; aRetval.maFamilyName = rFont.GetName(); aRetval.maStyleName = rFont.GetStyleName(); aRetval.mbSymbol = (RTL_TEXTENCODING_SYMBOL == rFont.GetCharSet()); aRetval.mbVertical = rFont.IsVertical(); aRetval.mnWeight = static_cast<sal_uInt16>(rFont.GetWeight()); aRetval.mbItalic = (rFont.GetItalic() != ITALIC_NONE); const sal_Int32 nWidth(rFont.GetSize().getWidth()); const sal_Int32 nHeight(rFont.GetSize().getHeight()); rSize.setX(nWidth ? nWidth : nHeight); rSize.setY(nHeight); return aRetval; } } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// using namespace com::sun::star; ////////////////////////////////////////////////////////////////////////////// namespace drawinglayer { namespace primitive2d { Primitive2DSequence TextSimplePortionPrimitive2D::createLocalDecomposition(const geometry::ViewInformation2D& /*rViewInformation*/) const { // get integer DXArray for getTextOutlines call (ATM uses vcl) ::std::vector< sal_Int32 > aNewIntegerDXArray; getIntegerDXArray(aNewIntegerDXArray); // prepare transformation matrices basegfx::B2DVector aScale, aTranslate; double fRotate, fShearX; getTextTransform().decompose(aScale, aTranslate, fRotate, fShearX); basegfx::B2DHomMatrix aUnscaledTransform; aUnscaledTransform.rotate( fRotate ); aUnscaledTransform.shearX( fShearX ); aUnscaledTransform.translate( aTranslate.getX(), aTranslate.getY() ); basegfx::B2DHomMatrix aUnrotatedTransform = getTextTransform(); aUnrotatedTransform.rotate( -fRotate ); // prepare textlayoutdevice TextLayouterDevice aTextLayouter; aTextLayouter.setFontAttributes(getFontAttributes(), aUnrotatedTransform ); // get the text outlines basegfx::B2DPolyPolygonVector aB2DPolyPolyVector; aTextLayouter.getTextOutlines( aB2DPolyPolyVector, getText(), 0L, getText().Len(), aNewIntegerDXArray); // create primitives for the outlines const sal_uInt32 nCount = aB2DPolyPolyVector.size(); if( nCount ) { // prepare retval Primitive2DSequence aRetval(nCount); for(sal_uInt32 a(0L); a < nCount; a++) { // prepare polygon basegfx::B2DPolyPolygon& rPolyPolygon = aB2DPolyPolyVector[a]; rPolyPolygon.transform(aUnscaledTransform); // create primitive const Primitive2DReference xRef(new PolyPolygonColorPrimitive2D(rPolyPolygon, getFontColor())); aRetval[a] = xRef; } return aRetval; } else { return Primitive2DSequence(); } } TextSimplePortionPrimitive2D::TextSimplePortionPrimitive2D( const basegfx::B2DHomMatrix& rNewTransform, const String& rText, const ::std::vector< double >& rDXArray, const FontAttributes& rFontAttributes, const basegfx::BColor& rFontColor) : BasePrimitive2D(), maTextTransform(rNewTransform), maText(rText), maDXArray(rDXArray), maFontAttributes(rFontAttributes), maFontColor(rFontColor) { } void TextSimplePortionPrimitive2D::getIntegerDXArray(::std::vector< sal_Int32 >& rDXArray) const { rDXArray.clear(); if(getDXArray().size()) { rDXArray.reserve(getDXArray().size()); const basegfx::B2DVector aPixelVector(getTextTransform() * basegfx::B2DVector(1.0, 0.0)); const double fPixelVectorLength(aPixelVector.getLength()); for(::std::vector< double >::const_iterator aStart(getDXArray().begin()); aStart != getDXArray().end(); aStart++) { rDXArray.push_back(basegfx::fround((*aStart) * fPixelVectorLength)); } } } bool TextSimplePortionPrimitive2D::operator==(const BasePrimitive2D& rPrimitive) const { if(BasePrimitive2D::operator==(rPrimitive)) { const TextSimplePortionPrimitive2D& rCompare = (TextSimplePortionPrimitive2D&)rPrimitive; return (getTextTransform() == rCompare.getTextTransform() && getText() == rCompare.getText() && getDXArray() == rCompare.getDXArray() && getFontAttributes() == rCompare.getFontAttributes() && getFontColor() == rCompare.getFontColor()); } return false; } basegfx::B2DRange TextSimplePortionPrimitive2D::getB2DRange(const geometry::ViewInformation2D& /*rViewInformation*/) const { const xub_StrLen aStrLen(getText().Len()); basegfx::B2DRange aRetval; if(aStrLen) { // get TextBoundRect as base size TextLayouterDevice aTextLayouter; aTextLayouter.setFontAttributes(getFontAttributes(), getTextTransform()); aRetval = aTextLayouter.getTextBoundRect(getText(), 0L, aStrLen); // apply textTransform to it, but without scaling. The scale defines the font size // which is already part of the fetched textRange basegfx::B2DVector aScale, aTranslate; double fRotate, fShearX; basegfx::B2DHomMatrix aTextTransformWithoutScale; getTextTransform().decompose(aScale, aTranslate, fRotate, fShearX); aTextTransformWithoutScale.shearX(fShearX); aTextTransformWithoutScale.rotate(fRotate); aTextTransformWithoutScale.translate(aTranslate.getX(), aTranslate.getY()); aRetval.transform(aTextTransformWithoutScale); } return aRetval; } // provide unique ID ImplPrimitrive2DIDBlock(TextSimplePortionPrimitive2D, '2','T','S','i') } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// namespace drawinglayer { namespace primitive2d { Primitive2DSequence TextComplexPortionPrimitive2D::createLocalDecomposition(const geometry::ViewInformation2D& /*rViewInformation*/) const { // TODO: need to take care of // -underline // -strikethrough // -emphasis mark // -relief (embosses/engraved) // -shadow // -outline // ATM: Just create a simple text primitive and ignore other attributes const Primitive2DReference xRef(new TextSimplePortionPrimitive2D(getTextTransform(), getText(), getDXArray(), getFontAttributes(), getFontColor())); return Primitive2DSequence(&xRef, 1L); } TextComplexPortionPrimitive2D::TextComplexPortionPrimitive2D( const basegfx::B2DHomMatrix& rNewTransform, const String& rText, const ::std::vector< double >& rDXArray, const FontAttributes& rFontAttributes, const basegfx::BColor& rFontColor, FontUnderline eFontUnderline, bool bUnderlineAbove, FontStrikeout eFontStrikeout, bool bWordLineMode, FontEmphasisMark eFontEmphasisMark, bool bEmphasisMarkAbove, bool bEmphasisMarkBelow, FontRelief eFontRelief, bool bShadow, bool bOutline) : TextSimplePortionPrimitive2D(rNewTransform, rText, rDXArray, rFontAttributes, rFontColor), meFontUnderline(eFontUnderline), meFontStrikeout(eFontStrikeout), meFontEmphasisMark(eFontEmphasisMark), meFontRelief(eFontRelief), mbUnderlineAbove(bUnderlineAbove), mbWordLineMode(bWordLineMode), mbEmphasisMarkAbove(bEmphasisMarkAbove), mbEmphasisMarkBelow(bEmphasisMarkBelow), mbShadow(bShadow), mbOutline(bOutline) { } bool TextComplexPortionPrimitive2D::operator==(const BasePrimitive2D& rPrimitive) const { if(TextSimplePortionPrimitive2D::operator==(rPrimitive)) { const TextComplexPortionPrimitive2D& rCompare = (TextComplexPortionPrimitive2D&)rPrimitive; return (getFontUnderline() == rCompare.getFontUnderline() && getFontStrikeout() == rCompare.getFontStrikeout() && getUnderlineAbove() == rCompare.getUnderlineAbove() && getWordLineMode() == rCompare.getWordLineMode() && getFontEmphasisMark() == rCompare.getFontEmphasisMark() && getEmphasisMarkAbove() == rCompare.getEmphasisMarkAbove() && getEmphasisMarkBelow() == rCompare.getEmphasisMarkBelow() && getFontRelief() == rCompare.getFontRelief() && getShadow() == rCompare.getShadow() && getOutline() == rCompare.getOutline()); } return false; } // provide unique ID ImplPrimitrive2DIDBlock(TextComplexPortionPrimitive2D, '2','T','C','o') } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>#i73860# implement outline font attribute<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textprimitive2d.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hdu $ $Date: 2007-02-15 13:25: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 INCLUDED_DRAWINGLAYER_PRIMITIVE_TEXTPRIMITIVE2D_HXX #include <drawinglayer/primitive2d/textprimitive2d.hxx> #endif #ifndef INCLUDED_DRAWINGLAYER_TEXTLAYOUTDEVICE_HXX #include <drawinglayer/primitive2d/textlayoutdevice.hxx> #endif #ifndef _SV_VIRDEV_HXX #include <vcl/virdev.hxx> #endif #ifndef _BGFX_COLOR_BCOLOR_HXX #include <basegfx/color/bcolor.hxx> #endif #ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE2D_POLYPOLYGONPRIMITIVE2D_HXX #include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx> #endif #ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE2D_POLYGONPRIMITIVE2D_HXX #include <drawinglayer/primitive2d/polygonprimitive2d.hxx> #endif #ifndef INCLUDED_DRAWINGLAYER_ATTRIBUTE_STROKEATTRIBUTE_HXX #include <drawinglayer/attribute/strokeattribute.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYGONTOOLS_HXX #include <basegfx/polygon/b2dpolygontools.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYGON_HXX #include <basegfx/polygon/b2dpolygon.hxx> #endif #ifndef _BGFX_POLYGON_B2DLINEGEOMETRY_HXX #include <basegfx/polygon/b2dlinegeometry.hxx> #endif #ifndef _BGFX_NUMERIC_FTOOLS_HXX #include <basegfx/numeric/ftools.hxx> #endif #ifndef _BGFX_TOOLS_CANVASTOOLS_HXX #include <basegfx/tools/canvastools.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace drawinglayer { namespace primitive2d { Font getVclFontFromFontAttributes(const FontAttributes& rFontAttributes, const basegfx::B2DHomMatrix& rTransform) { // decompose matrix to have position and size of text basegfx::B2DVector aScale, aTranslate; double fRotate, fShearX; rTransform.decompose(aScale, aTranslate, fRotate, fShearX); return getVclFontFromFontAttributes(rFontAttributes, aScale, fRotate); } Font getVclFontFromFontAttributes(const FontAttributes& rFontAttributes, const basegfx::B2DVector& rFontSize, double fFontRotation) { sal_uInt32 nWidth(basegfx::fround(fabs(rFontSize.getX()))); sal_uInt32 nHeight(basegfx::fround(fabs(rFontSize.getY()))); if(nWidth == nHeight) { nWidth = 0L; } Font aRetval( rFontAttributes.maFamilyName, rFontAttributes.maStyleName, Size(nWidth, nHeight)); if(!basegfx::fTools::equalZero(fFontRotation)) { sal_Int16 aRotate10th((sal_Int16)(fFontRotation * (-1800.0/F_PI))); aRetval.SetOrientation(aRotate10th % 3600); } aRetval.SetAlign(ALIGN_BASELINE); aRetval.SetCharSet(rFontAttributes.mbSymbol ? RTL_TEXTENCODING_SYMBOL : RTL_TEXTENCODING_UNICODE); aRetval.SetVertical(rFontAttributes.mbVertical ? TRUE : FALSE); aRetval.SetWeight(static_cast<FontWeight>(rFontAttributes.mnWeight)); aRetval.SetItalic(rFontAttributes.mbItalic ? ITALIC_NORMAL : ITALIC_NONE); aRetval.SetOutline(rFontAttributes.mbOutline); return aRetval; } FontAttributes getFontAttributesFromVclFont(basegfx::B2DVector& rSize, const Font& rFont) { FontAttributes aRetval; aRetval.maFamilyName = rFont.GetName(); aRetval.maStyleName = rFont.GetStyleName(); aRetval.mbSymbol = (RTL_TEXTENCODING_SYMBOL == rFont.GetCharSet()); aRetval.mbVertical = rFont.IsVertical(); aRetval.mnWeight = static_cast<sal_uInt16>(rFont.GetWeight()); aRetval.mbItalic = (rFont.GetItalic() != ITALIC_NONE); aRetval.mbOutline = rFont.IsOutline(); // TODO: eKerning const sal_Int32 nWidth(rFont.GetSize().getWidth()); const sal_Int32 nHeight(rFont.GetSize().getHeight()); rSize.setX(nWidth ? nWidth : nHeight); rSize.setY(nHeight); return aRetval; } } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// using namespace com::sun::star; ////////////////////////////////////////////////////////////////////////////// namespace drawinglayer { namespace primitive2d { Primitive2DSequence TextSimplePortionPrimitive2D::createLocalDecomposition(const geometry::ViewInformation2D& /*rViewInformation*/) const { // get integer DXArray for getTextOutlines call (ATM uses vcl) ::std::vector< sal_Int32 > aNewIntegerDXArray; getIntegerDXArray(aNewIntegerDXArray); // prepare transformation matrices basegfx::B2DVector aScale, aTranslate; double fRotate, fShearX; getTextTransform().decompose(aScale, aTranslate, fRotate, fShearX); basegfx::B2DHomMatrix aUnscaledTransform; aUnscaledTransform.rotate( fRotate ); aUnscaledTransform.shearX( fShearX ); aUnscaledTransform.translate( aTranslate.getX(), aTranslate.getY() ); basegfx::B2DHomMatrix aUnrotatedTransform = getTextTransform(); aUnrotatedTransform.rotate( -fRotate ); // prepare textlayoutdevice TextLayouterDevice aTextLayouter; aTextLayouter.setFontAttributes(getFontAttributes(), aUnrotatedTransform ); // get the text outlines basegfx::B2DPolyPolygonVector aB2DPolyPolyVector; aTextLayouter.getTextOutlines( aB2DPolyPolyVector, getText(), 0L, getText().Len(), aNewIntegerDXArray); // create primitives for the outlines const sal_uInt32 nCount = aB2DPolyPolyVector.size(); Primitive2DSequence aRetval; if( !nCount ) { // for invisible glyphs return aRetval; } else if( !getFontAttributes().mbOutline ) { aRetval.realloc(nCount); // for the glyph shapes as color-filled polypolygons for(sal_uInt32 a(0L); a < nCount; a++) { // prepare polypolygon basegfx::B2DPolyPolygon& rPolyPolygon = aB2DPolyPolyVector[a]; rPolyPolygon.transform(aUnscaledTransform); const Primitive2DReference xRef(new PolyPolygonColorPrimitive2D(rPolyPolygon, getFontColor())); aRetval[a] = xRef; } } else { // for the glyph outlines as stroked polygons // since there is no primitive for stroked polypolygons int nPolyCount = 0; for(sal_uInt32 a(0L); a < nCount; a++) nPolyCount += aB2DPolyPolyVector[a].count(); aRetval.realloc(nPolyCount); double fStrokeWidth = 1.0 + aScale.getY() * 0.02; if( getFontAttributes().mnWeight > WEIGHT_SEMIBOLD ) fStrokeWidth *= 1.4; else if( getFontAttributes().mnWeight < WEIGHT_SEMILIGHT ) fStrokeWidth *= 0.7; const drawinglayer::attribute::StrokeAttribute aStrokeAttr( getFontColor(), fStrokeWidth, basegfx::tools::B2DLINEJOIN_NONE ); for(sal_uInt32 a(0L), b(0L); a < nCount; a++) { basegfx::B2DPolyPolygon& rPolyPolygon = aB2DPolyPolyVector[a]; rPolyPolygon.transform(aUnscaledTransform); for( unsigned i(0L); i < rPolyPolygon.count(); ++i ) { const basegfx::B2DPolygon& rPolygon = rPolyPolygon.getB2DPolygon(i); const Primitive2DReference xRef(new PolygonStrokePrimitive2D(rPolygon, aStrokeAttr)); aRetval[b++] = xRef; } } } return aRetval; } TextSimplePortionPrimitive2D::TextSimplePortionPrimitive2D( const basegfx::B2DHomMatrix& rNewTransform, const String& rText, const ::std::vector< double >& rDXArray, const FontAttributes& rFontAttributes, const basegfx::BColor& rFontColor) : BasePrimitive2D(), maTextTransform(rNewTransform), maText(rText), maDXArray(rDXArray), maFontAttributes(rFontAttributes), maFontColor(rFontColor) { } void TextSimplePortionPrimitive2D::getIntegerDXArray(::std::vector< sal_Int32 >& rDXArray) const { rDXArray.clear(); if(getDXArray().size()) { rDXArray.reserve(getDXArray().size()); const basegfx::B2DVector aPixelVector(getTextTransform() * basegfx::B2DVector(1.0, 0.0)); const double fPixelVectorLength(aPixelVector.getLength()); for(::std::vector< double >::const_iterator aStart(getDXArray().begin()); aStart != getDXArray().end(); aStart++) { rDXArray.push_back(basegfx::fround((*aStart) * fPixelVectorLength)); } } } bool TextSimplePortionPrimitive2D::operator==(const BasePrimitive2D& rPrimitive) const { if(BasePrimitive2D::operator==(rPrimitive)) { const TextSimplePortionPrimitive2D& rCompare = (TextSimplePortionPrimitive2D&)rPrimitive; return (getTextTransform() == rCompare.getTextTransform() && getText() == rCompare.getText() && getDXArray() == rCompare.getDXArray() && getFontAttributes() == rCompare.getFontAttributes() && getFontColor() == rCompare.getFontColor()); } return false; } basegfx::B2DRange TextSimplePortionPrimitive2D::getB2DRange(const geometry::ViewInformation2D& /*rViewInformation*/) const { const xub_StrLen aStrLen(getText().Len()); basegfx::B2DRange aRetval; if(aStrLen) { // get TextBoundRect as base size TextLayouterDevice aTextLayouter; aTextLayouter.setFontAttributes(getFontAttributes(), getTextTransform()); aRetval = aTextLayouter.getTextBoundRect(getText(), 0L, aStrLen); // apply textTransform to it, but without scaling. The scale defines the font size // which is already part of the fetched textRange basegfx::B2DVector aScale, aTranslate; double fRotate, fShearX; basegfx::B2DHomMatrix aTextTransformWithoutScale; getTextTransform().decompose(aScale, aTranslate, fRotate, fShearX); aTextTransformWithoutScale.shearX(fShearX); aTextTransformWithoutScale.rotate(fRotate); aTextTransformWithoutScale.translate(aTranslate.getX(), aTranslate.getY()); aRetval.transform(aTextTransformWithoutScale); } return aRetval; } // provide unique ID ImplPrimitrive2DIDBlock(TextSimplePortionPrimitive2D, '2','T','S','i') } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// namespace drawinglayer { namespace primitive2d { Primitive2DSequence TextComplexPortionPrimitive2D::createLocalDecomposition(const geometry::ViewInformation2D& /*rViewInformation*/) const { Primitive2DSequence aRetval(1); // First create a simple text primitive and ignore other attributes aRetval[0] = new TextSimplePortionPrimitive2D(getTextTransform(), getText(), getDXArray(), getFontAttributes(), getFontColor()); // TODO: need to take care of // -underline // -strikethrough // -emphasis mark // -relief (embosses/engraved) // -shadow // -outline return aRetval; } TextComplexPortionPrimitive2D::TextComplexPortionPrimitive2D( const basegfx::B2DHomMatrix& rNewTransform, const String& rText, const ::std::vector< double >& rDXArray, const FontAttributes& rFontAttributes, const basegfx::BColor& rFontColor, FontUnderline eFontUnderline, bool bUnderlineAbove, FontStrikeout eFontStrikeout, bool bWordLineMode, FontEmphasisMark eFontEmphasisMark, bool bEmphasisMarkAbove, bool bEmphasisMarkBelow, FontRelief eFontRelief, bool bShadow, bool bOutline) : TextSimplePortionPrimitive2D(rNewTransform, rText, rDXArray, rFontAttributes, rFontColor), meFontUnderline(eFontUnderline), meFontStrikeout(eFontStrikeout), meFontEmphasisMark(eFontEmphasisMark), meFontRelief(eFontRelief), mbUnderlineAbove(bUnderlineAbove), mbWordLineMode(bWordLineMode), mbEmphasisMarkAbove(bEmphasisMarkAbove), mbEmphasisMarkBelow(bEmphasisMarkBelow), mbShadow(bShadow), mbOutline(bOutline) { } bool TextComplexPortionPrimitive2D::operator==(const BasePrimitive2D& rPrimitive) const { if(TextSimplePortionPrimitive2D::operator==(rPrimitive)) { const TextComplexPortionPrimitive2D& rCompare = (TextComplexPortionPrimitive2D&)rPrimitive; return (getFontUnderline() == rCompare.getFontUnderline() && getFontStrikeout() == rCompare.getFontStrikeout() && getUnderlineAbove() == rCompare.getUnderlineAbove() && getWordLineMode() == rCompare.getWordLineMode() && getFontEmphasisMark() == rCompare.getFontEmphasisMark() && getEmphasisMarkAbove() == rCompare.getEmphasisMarkAbove() && getEmphasisMarkBelow() == rCompare.getEmphasisMarkBelow() && getFontRelief() == rCompare.getFontRelief() && getShadow() == rCompare.getShadow() && getOutline() == rCompare.getOutline()); } return false; } // provide unique ID ImplPrimitrive2DIDBlock(TextComplexPortionPrimitive2D, '2','T','C','o') } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>/* * Copyright (c) 2022, Eyal Rozenberg, under the terms of the 3-clause * BSD software license; see the LICENSE file accompanying this * repository. * * Copyright notice and license for the original code: * Copyright (c) 1993-2015, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cuda_runtime.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> // Convenience function for checking CUDA runtime API results // can be wrapped around any runtime API call. No-op in release builds. inline cudaError_t checkCuda(cudaError_t result) { #if defined(DEBUG) || defined(_DEBUG) if (result != cudaSuccess) { fprintf(stderr, "CUDA Runtime Error: %s\n", cudaGetErrorString(result)); assert(result == cudaSuccess); } #endif return result; } void profileCopies(float *h_a, float *h_b, float *d, size_t nElements, char const *desc) { printf("\n%s transfers\n", desc); size_t bytes = nElements * sizeof(float); // events for timing cudaEvent_t startEvent, stopEvent; checkCuda( cudaEventCreate(&startEvent) ); checkCuda( cudaEventCreate(&stopEvent) ); checkCuda( cudaEventRecord(startEvent, 0) ); checkCuda( cudaMemcpy(d, h_a, bytes, cudaMemcpyHostToDevice) ); checkCuda( cudaEventRecord(stopEvent, 0) ); checkCuda( cudaEventSynchronize(stopEvent) ); float time; checkCuda( cudaEventElapsedTime(&time, startEvent, stopEvent) ); printf(" Host to Device bandwidth (GB/s): %f\n", bytes * 1e-6 / time); checkCuda( cudaEventRecord(startEvent, 0) ); checkCuda( cudaMemcpy(h_b, d, bytes, cudaMemcpyDeviceToHost) ); checkCuda( cudaEventRecord(stopEvent, 0) ); checkCuda( cudaEventSynchronize(stopEvent) ); checkCuda( cudaEventElapsedTime(&time, startEvent, stopEvent) ); printf(" Device to Host bandwidth (GB/s): %f\n", bytes * 1e-6 / time); for (size_t i = 0; i < nElements; ++i) { if (h_a[i] != h_b[i]) { printf("*** %s transfers failed ***", desc); break; } } // clean up events checkCuda( cudaEventDestroy(startEvent) ); checkCuda( cudaEventDestroy(stopEvent) ); } int main() { const size_t nElements = 4*1024*1024; const size_t bytes = nElements * sizeof(float); // host arrays float *h_aPageable, *h_bPageable; float *h_aPinned, *h_bPinned; // device array float *d_a; // allocate and initialize h_aPageable = (float*)malloc(bytes); // host pageable h_bPageable = (float*)malloc(bytes); // host pageable checkCuda( cudaMallocHost((void**)&h_aPinned, bytes) ); // host pinned checkCuda( cudaMallocHost((void**)&h_bPinned, bytes) ); // host pinned checkCuda( cudaMalloc((void**)&d_a, bytes) ); // device for (size_t i = 0; i < nElements; ++i) h_aPageable[i] = i; memcpy(h_aPinned, h_aPageable, bytes); memset(h_bPageable, 0, bytes); memset(h_bPinned, 0, bytes); // output device info and transfer size cudaDeviceProp prop; checkCuda( cudaGetDeviceProperties(&prop, 0) ); printf("\nDevice: %s\n", prop.name); printf("Transfer size (MB): %zu\n", bytes / (size_t) (1024 * 1024)); // perform copies and report bandwidth profileCopies(h_aPageable, h_bPageable, d_a, nElements, "Pageable"); profileCopies(h_aPinned, h_bPinned, d_a, nElements, "Pinned"); printf("\n"); // cleanup cudaFree(d_a); cudaFreeHost(h_aPinned); cudaFreeHost(h_bPinned); free(h_aPageable); free(h_bPageable); return 0; } <commit_msg>Fixes #398: Adapted the bandwidthtest program to use our wrappers.<commit_after>/* * Copyright (c) 2022, Eyal Rozenberg, under the terms of the 3-clause * BSD software license; see the LICENSE file accompanying this * repository. * * Copyright notice and license for the original code: * Copyright (c) 1993-2015, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cuda/api.hpp> #include <memory> #include <array> #include <utility> #include <algorithm> #include <numeric> void profileCopies(float *h_a, float *h_b, float *d, size_t nElements, char const *desc) { std::cout << desc << " transfers\n"; size_t bytes = nElements * sizeof(float); auto device = cuda::device::current::get(); auto stream = device.default_stream(); auto events = std::make_pair(device.create_event(), device.create_event()); stream.enqueue.event(events.first); stream.enqueue.copy(d, h_a, bytes); stream.enqueue.event(events.second); stream.synchronize(); auto duration = cuda::event::time_elapsed_between(events.first, events.second); std::cout << " Host to Device bandwidth (GB/s): " << (bytes * 1e-6 / duration.count()) << "\n"; stream.enqueue.event(events.first); stream.enqueue.copy(h_b, d, bytes); stream.enqueue.event(events.second); stream.synchronize(); duration = cuda::event::time_elapsed_between(events.first, events.second); std::cout << " Device to Host bandwidth (GB/s): " << (bytes * 1e-6 / duration.count()) << "\n"; bool are_equal = std::equal(h_a, h_a + nElements, h_b); if (not are_equal) { std::cout << "*** " << desc << " transfers failed ***\n"; } } int main() { constexpr const size_t Mi = 1024 * 1024; const size_t nElements = 4 * Mi; const size_t bytes = nElements * sizeof(float); auto pageable_host_buffers = std::make_pair( std::unique_ptr<float[]>(new float[nElements]), std::unique_ptr<float[]>(new float[nElements]) ); auto device_buffer = cuda::memory::device::make_unique<float[]>(nElements); auto pinned_host_buffers = std::make_pair( cuda::memory::host::make_unique<float[]>(nElements), cuda::memory::host::make_unique<float[]>(nElements) ); auto h_aPageable = pageable_host_buffers.first.get(); auto h_bPageable = pageable_host_buffers.second.get(); auto h_aPinned = pinned_host_buffers.first.get(); auto h_bPinned = pinned_host_buffers.second.get(); std::iota(h_aPageable, h_aPageable + nElements, 0); cuda::memory::copy(h_aPinned, h_aPageable, bytes); // Note: the following two instructions can be replaced with CUDA API wrappers // calls - cuda::memory::host::zero(), but that won't improve anything std::fill_n(h_bPageable, nElements, (float) 0); std::fill_n(h_bPinned, nElements, (float) 0); std::cout << "\nDevice: " << cuda::device::current::get().name() << "\n"; std::cout << "\nTransfer size (MB): " << (bytes / Mi) << "\n"; // perform copies and report bandwidth profileCopies(h_aPageable, h_bPageable, device_buffer.get(), nElements, "Pageable"); profileCopies(h_aPinned, h_bPinned, device_buffer.get(), nElements, "Pinned"); } <|endoftext|>
<commit_before>/*____________________________________________________________________________ MusicBrainz -- The Internet music metadatabase Portions Copyright (C) 2000 Relatable This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ ____________________________________________________________________________*/ //------------------------------------ // fft.cpp // The implementation of the // Fast Fourier Transform algorithm // modified by Sean Ward 2000 // portions (c) Reliable Software, 1996 //------------------------------------ #include "sigfft.h" #include <string.h> // log (1) = 0, log(2) = 1, log(3) = 2, log(4) = 2 ... #define PI (2.0 * asin(1.0)) // Points must be a power of 2 FFT::FFT (int Points, long sampleRate) : _Points (Points), _sampleRate (sampleRate) { _aTape = new double [_Points]; #if 0 // 1 kHz calibration wave for (int i = 0; i < _Points; i++) _aTape[i] = 1600 * sin (2 * PI * 1000. * i / _sampleRate); #else int i = 0; for (i = 0; i < _Points; i++) _aTape[i] = 0; #endif _sqrtPoints = sqrt((double)_Points); // calculate binary log _logPoints = 0; Points--; while (Points != 0) { Points >>= 1; _logPoints++; } _aBitRev = new int [_Points]; _test = new Complex[_Points]; _W = new Complex* [_logPoints+1]; // Precompute complex exponentials int _2_l = 2; for (int l = 1; l <= _logPoints; l++) { _W[l] = new Complex [_Points]; for ( int i = 0; i < _Points; i++ ) { double re = cos (2. * PI * i / _2_l); double im = -sin (2. * PI * i / _2_l); _W[l][i] = Complex (re, im); } _2_l *= 2; } // set up bit reverse mapping int rev = 0; int halfPoints = _Points/2; for (i = 0; i < _Points - 1; i++) { _aBitRev[i] = rev; int mask = halfPoints; // add 1 backwards while (rev >= mask) { rev -= mask; // turn off this bit mask >>= 1; } rev += mask; } _aBitRev [_Points-1] = _Points-1; } FFT::~FFT() { delete []_aTape; delete []_aBitRev; for (int l = 1; l <= _logPoints; l++) { delete []_W[l]; } delete []_W; delete []_test; } //void Fft::CopyIn (SampleIter& iter) void FFT::CopyIn(char* pBuffer, int nNumSamples) { if (nNumSamples > _Points) return; // make space for cSample samples at the end of tape // shifting previous samples towards the beginning memmove (_aTape, &_aTape[nNumSamples], (_Points - nNumSamples) * sizeof(double)); // copy samples from iterator to tail end of tape int iTail = _Points - nNumSamples; int i = 0; for (i = 0; i < nNumSamples; i++) { _aTape [i + iTail] = (double) pBuffer[i]; } // Initialize the FFT buffer for (i = 0; i < _Points; i++) PutAt (i, _aTape[i]); } // // 0 1 2 3 4 5 6 7 // level 1 // step 1 0 // increm 2 W // j = 0 <---> <---> <---> <---> 1 // level 2 // step 2 // increm 4 0 // j = 0 <-------> <-------> W 1 // j = 1 <-------> <-------> 2 W // level 3 2 // step 4 // increm 8 0 // j = 0 <---------------> W 1 // j = 1 <---------------> 3 W 2 // j = 2 <---------------> 3 W 3 // j = 3 <---------------> 3 W // 3 // void FFT::Transform () { // step = 2 ^ (level-1) // increm = 2 ^ level; int step = 1; for (int level = 1; level <= _logPoints; level++) { int increm = step * 2; for (int j = 0; j < step; j++) { // U = exp ( - 2 PI j / 2 ^ level ) Complex U = _W [level][j]; for (int i = j; i < _Points; i += increm) { // butterfly Complex T = U; T *= _test [i+step]; _test [i+step] = _test [i]; _test [i+step] -= T; _test [i] += T; } } step *= 2; } } <commit_msg>- testing the commits script<commit_after>/*____________________________________________________________________________ MusicBrainz -- The Internet music metadatabase Portions Copyright (C) 2000 Relatable This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ ____________________________________________________________________________*/ //------------------------------------ // fft.cpp // The implementation of the // Fast Fourier Transform algorithm // modified by Sean Ward 2000 // portions (c) Reliable Software, 1996 //------------------------------------ #include "sigfft.h" #include <string.h> // log (1) = 0, log(2) = 1, log(3) = 2, log(4) = 2 ... #define PI (2.0 * asin(1.0)) // Points must be a power of 2 FFT::FFT (int Points, long sampleRate) : _Points (Points), _sampleRate (sampleRate) { _aTape = new double [_Points]; #if 0 // 1 kHz calibration wave for (int i = 0; i < _Points; i++) _aTape[i] = 1600 * sin (2 * PI * 1000. * i / _sampleRate); #else int i = 0; for (i = 0; i < _Points; i++) _aTape[i] = 0; #endif _sqrtPoints = sqrt((double)_Points); // calculate binary log _logPoints = 0; Points--; while (Points != 0) { Points >>= 1; _logPoints++; } _aBitRev = new int [_Points]; _test = new Complex[_Points]; _W = new Complex* [_logPoints+1]; // Precompute complex exponentials int _2_l = 2; for (int l = 1; l <= _logPoints; l++) { _W[l] = new Complex [_Points]; for ( int i = 0; i < _Points; i++ ) { double re = cos (2. * PI * i / _2_l); double im = -sin (2. * PI * i / _2_l); _W[l][i] = Complex (re, im); } _2_l *= 2; } // set up bit reverse mapping int rev = 0; int halfPoints = _Points/2; for (i = 0; i < _Points - 1; i++) { _aBitRev[i] = rev; int mask = halfPoints; // add 1 backwards while (rev >= mask) { rev -= mask; // turn off this bit mask >>= 1; } rev += mask; } _aBitRev [_Points-1] = _Points-1; } FFT::~FFT() { delete []_aTape; delete []_aBitRev; for (int l = 1; l <= _logPoints; l++) { delete []_W[l]; } delete []_W; delete []_test; } //void Fft::CopyIn (SampleIter& iter) void FFT::CopyIn(char* pBuffer, int nNumSamples) { if (nNumSamples > _Points) return; // make space for cSample samples at the end of tape // shifting previous samples towards the beginning memmove (_aTape, &_aTape[nNumSamples], (_Points - nNumSamples) * sizeof(double)); // copy samples from iterator to tail end of tape int iTail = _Points - nNumSamples; int i = 0; for (i = 0; i < nNumSamples; i++) { _aTape [i + iTail] = (double) pBuffer[i]; } // Initialize the FFT buffer for (i = 0; i < _Points; i++) PutAt (i, _aTape[i]); } // // 0 1 2 3 4 5 6 7 // level 1 // step 1 0 // increm 2 W // j = 0 <---> <---> <---> <---> 1 // level 2 // step 2 // increm 4 0 // j = 0 <-------> <-------> W 1 // j = 1 <-------> <-------> 2 W // level 3 2 // step 4 // increm 8 0 // j = 0 <---------------> W 1 // j = 1 <---------------> 3 W 2 // j = 2 <---------------> 3 W 3 // j = 3 <---------------> 3 W // 3 // void FFT::Transform () { // step = 2 ^ (level-1) // increm = 2 ^ level; int step = 1; for (int level = 1; level <= _logPoints; level++) { int increm = step * 2; for (int j = 0; j < step; j++) { // U = exp ( - 2 PI j / 2 ^ level ) Complex U = _W [level][j]; for (int i = j; i < _Points; i += increm) { // butterfly Complex T = U; T *= _test [i+step]; _test [i+step] = _test [i]; _test [i+step] -= T; _test [i] += T; } } step *= 2; } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2013, 2017-2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /* * Simulated Low Level Driver for the PX4 audio alarm port. Subscribes to * tune_control and plays notes on this architecture specific * timer HW */ #include <px4_config.h> #include <px4_posix.h> #include <drivers/device/device.h> #include <drivers/drv_tone_alarm.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <math.h> #include <ctype.h> #include <board_config.h> #include <drivers/drv_hrt.h> #include <systemlib/err.h> #include <circuit_breaker/circuit_breaker.h> #include <lib/tunes/tunes.h> #include <uORB/uORB.h> #include <uORB/topics/tune_control.h> #include "VirtDevObj.hpp" using namespace DriverFramework; #if !defined(UNUSED) # define UNUSED(a) ((void)(a)) #endif #define CBRK_BUZZER_KEY 782097 class ToneAlarm : public VirtDevObj { public: ToneAlarm(); ~ToneAlarm(); virtual int init(); void status(); enum { CBRK_OFF = 0, CBRK_ON, CBRK_UNINIT }; private: volatile bool _running; volatile bool _should_run; bool _play_tone; Tunes _tunes; hrt_call _note_call; // HRT callout for note completion unsigned _silence_length; // if nonzero, silence before next note int _cbrk; ///< if true, no audio output int _tune_control_sub; tune_control_s _tune; // Convert a frequency value into a divisor for the configured timer's clock. // unsigned frequency_to_divisor(unsigned frequency); // Start playing the note // void start_note(unsigned frequency); // Stop playing the current note and make the player 'safe' // void stop_note(); // Parse the next note out of the string and play it // void next_note(); // hrt_call trampoline for next_note // static void next_trampoline(void *arg); // Unused virtual void _measure() {} }; /* * Driver 'main' command. */ extern "C" __EXPORT int tone_alarm_main(int argc, char *argv[]); ToneAlarm::ToneAlarm() : VirtDevObj("tone_alarm", TONEALARM0_DEVICE_PATH, nullptr, 0), _running(false), _should_run(true), _play_tone(false), _tunes(), _silence_length(0), _cbrk(CBRK_UNINIT), _tune_control_sub(-1) { } ToneAlarm::~ToneAlarm() { _should_run = false; int counter = 0; while (_running && ++counter < 10) { usleep(100000); } } int ToneAlarm::init() { int ret; ret = VirtDevObj::init(); if (ret != OK) { return ret; } _note_call = {}; hrt_call_after(&_note_call, (hrt_abstime)TUNE_MAX_UPDATE_INTERVAL_US, (hrt_callout)next_trampoline, this); _running = true; return OK; } void ToneAlarm::status() { if (_running) { PX4_INFO("running"); } else { PX4_INFO("stopped"); } } unsigned ToneAlarm::frequency_to_divisor(unsigned frequency) { const int TONE_ALARM_CLOCK = 120000000ul / 4; float period = 0.5f / frequency; // and the divisor, rounded to the nearest integer unsigned divisor = (period * TONE_ALARM_CLOCK) + 0.5f; return divisor; } void ToneAlarm::start_note(unsigned frequency) { // check if circuit breaker is enabled if (_cbrk == CBRK_UNINIT) { _cbrk = circuit_breaker_enabled("CBRK_BUZZER", CBRK_BUZZER_KEY); } if (_cbrk != CBRK_OFF) { return; } // compute the divisor unsigned divisor = frequency_to_divisor(frequency); // pick the lowest prescaler value that we can use // (note that the effective prescale value is 1 greater) unsigned prescale = divisor / 65536; // calculate the timer period for the selected prescaler value unsigned period = (divisor / (prescale + 1)) - 1; // Silence warning of unused var UNUSED(period); PX4_DEBUG("ToneAlarm::start_note %u", period); } void ToneAlarm::stop_note() { } void ToneAlarm::next_note() { if (!_should_run) { if (_tune_control_sub >= 0) { orb_unsubscribe(_tune_control_sub); } _running = false; return; } // subscribe to tune_control if (_tune_control_sub < 0) { _tune_control_sub = orb_subscribe(ORB_ID(tune_control)); } // do we have an inter-note gap to wait for? if (_silence_length > 0) { stop_note(); _note_call = {}; hrt_call_after(&_note_call, (hrt_abstime)_silence_length, (hrt_callout)next_trampoline, this); _silence_length = 0; return; } // check for updates bool updated = false; orb_check(_tune_control_sub, &updated); if (updated) { orb_copy(ORB_ID(tune_control), _tune_control_sub, &_tune); _play_tone = _tunes.set_control(_tune) == 0; } unsigned frequency = 0; unsigned duration = 0; if (_play_tone) { _play_tone = false; int parse_ret_val = _tunes.get_next_tune(frequency, duration, _silence_length); if (parse_ret_val >= 0) { // a frequency of 0 correspond to stop_note if (frequency > 0) { // start playing the note start_note(frequency); } else { stop_note(); } if (parse_ret_val > 0) { // continue playing _play_tone = true; } } } else { // schedule a call with the tunes max interval duration = _tunes.get_maximum_update_interval(); // stop playing the last note after the duration elapsed stop_note(); } // and arrange a callback when the note should stop assert(duration != 0); _note_call = {}; hrt_call_after(&_note_call, (hrt_abstime) duration, (hrt_callout)next_trampoline, this); } void ToneAlarm::next_trampoline(void *arg) { ToneAlarm *ta = (ToneAlarm *)arg; ta->next_note(); } /** * Local functions in support of the shell command. */ namespace { ToneAlarm *g_dev; } // namespace void tone_alarm_usage(); void tone_alarm_usage() { PX4_INFO("missing command, try 'start', status, 'stop'"); } int tone_alarm_main(int argc, char *argv[]) { if (argc > 1) { const char *argv1 = argv[1]; if (!strcmp(argv1, "start")) { if (g_dev != nullptr) { PX4_ERR("already started"); exit(1); } if (g_dev == nullptr) { g_dev = new ToneAlarm(); if (g_dev == nullptr) { PX4_ERR("couldn't allocate the ToneAlarm driver"); exit(1); } if (OK != g_dev->init()) { delete g_dev; g_dev = nullptr; PX4_ERR("ToneAlarm init failed"); exit(1); } } exit(0); } if (!strcmp(argv1, "stop")) { delete g_dev; g_dev = nullptr; exit(0); } if (!strcmp(argv1, "status")) { g_dev->status(); exit(0); } } tone_alarm_usage(); exit(0); } <commit_msg>posix:tonealrmsim: use workqueue<commit_after>/**************************************************************************** * * Copyright (c) 2013, 2017-2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /* * Simulated Low Level Driver for the PX4 audio alarm port. Subscribes to * tune_control and plays notes on this architecture specific * timer HW */ #include <px4_config.h> #include <px4_posix.h> #include <drivers/device/device.h> #include <drivers/drv_tone_alarm.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <math.h> #include <ctype.h> #include <board_config.h> #include <drivers/drv_hrt.h> #include <systemlib/err.h> #include <circuit_breaker/circuit_breaker.h> #include <px4_workqueue.h> #include <lib/tunes/tunes.h> #include <uORB/uORB.h> #include <uORB/topics/tune_control.h> #include "VirtDevObj.hpp" using namespace DriverFramework; #if !defined(UNUSED) # define UNUSED(a) ((void)(a)) #endif #define CBRK_BUZZER_KEY 782097 class ToneAlarm : public VirtDevObj { public: ToneAlarm(); ~ToneAlarm(); virtual int init(); void status(); enum { CBRK_OFF = 0, CBRK_ON, CBRK_UNINIT }; private: volatile bool _running; volatile bool _should_run; bool _play_tone; Tunes _tunes; unsigned _silence_length; // if nonzero, silence before next note int _cbrk; ///< if true, no audio output int _tune_control_sub; tune_control_s _tune; static work_s _work; // Convert a frequency value into a divisor for the configured timer's clock. // unsigned frequency_to_divisor(unsigned frequency); // Start playing the note // void start_note(unsigned frequency); // Stop playing the current note and make the player 'safe' // void stop_note(); // Parse the next note out of the string and play it // void next_note(); // work queue trampoline for next_note // static void next_trampoline(void *arg); // Unused virtual void _measure() {} }; struct work_s ToneAlarm::_work = {}; /* * Driver 'main' command. */ extern "C" __EXPORT int tone_alarm_main(int argc, char *argv[]); ToneAlarm::ToneAlarm() : VirtDevObj("tone_alarm", TONEALARM0_DEVICE_PATH, nullptr, 0), _running(false), _should_run(true), _play_tone(false), _tunes(), _silence_length(0), _cbrk(CBRK_UNINIT), _tune_control_sub(-1) { } ToneAlarm::~ToneAlarm() { _should_run = false; int counter = 0; while (_running && ++counter < 10) { usleep(100000); } } int ToneAlarm::init() { int ret; ret = VirtDevObj::init(); if (ret != OK) { return ret; } _running = true; work_queue(HPWORK, &_work, (worker_t)&ToneAlarm::next_trampoline, this, 0); return OK; } void ToneAlarm::status() { if (_running) { PX4_INFO("running"); } else { PX4_INFO("stopped"); } } unsigned ToneAlarm::frequency_to_divisor(unsigned frequency) { const int TONE_ALARM_CLOCK = 120000000ul / 4; float period = 0.5f / frequency; // and the divisor, rounded to the nearest integer unsigned divisor = (period * TONE_ALARM_CLOCK) + 0.5f; return divisor; } void ToneAlarm::start_note(unsigned frequency) { // check if circuit breaker is enabled if (_cbrk == CBRK_UNINIT) { _cbrk = circuit_breaker_enabled("CBRK_BUZZER", CBRK_BUZZER_KEY); } if (_cbrk != CBRK_OFF) { return; } // compute the divisor unsigned divisor = frequency_to_divisor(frequency); // pick the lowest prescaler value that we can use // (note that the effective prescale value is 1 greater) unsigned prescale = divisor / 65536; // calculate the timer period for the selected prescaler value unsigned period = (divisor / (prescale + 1)) - 1; // Silence warning of unused var UNUSED(period); PX4_DEBUG("ToneAlarm::start_note %u", period); } void ToneAlarm::stop_note() { } void ToneAlarm::next_note() { if (!_should_run) { if (_tune_control_sub >= 0) { orb_unsubscribe(_tune_control_sub); } _running = false; return; } // subscribe to tune_control if (_tune_control_sub < 0) { _tune_control_sub = orb_subscribe(ORB_ID(tune_control)); } // do we have an inter-note gap to wait for? if (_silence_length > 0) { stop_note(); work_queue(HPWORK, &_work, (worker_t)&ToneAlarm::next_trampoline, this, USEC2TICK(_silence_length)); _silence_length = 0; return; } // check for updates bool updated = false; orb_check(_tune_control_sub, &updated); if (updated) { orb_copy(ORB_ID(tune_control), _tune_control_sub, &_tune); } unsigned frequency = 0; unsigned duration = 0; if (_play_tone) { _play_tone = false; int parse_ret_val = _tunes.get_next_tune(frequency, duration, _silence_length); if (parse_ret_val >= 0) { // a frequency of 0 correspond to stop_note if (frequency > 0) { // start playing the note start_note(frequency); } else { stop_note(); } if (parse_ret_val > 0) { // continue playing _play_tone = true; } } } else { // schedule a call with the tunes max interval duration = _tunes.get_maximum_update_interval(); // stop playing the last note after the duration elapsed stop_note(); } // and arrange a callback when the note should stop work_queue(HPWORK, &_work, (worker_t)&ToneAlarm::next_trampoline, this, USEC2TICK(duration)); } void ToneAlarm::next_trampoline(void *arg) { ToneAlarm *ta = (ToneAlarm *)arg; ta->next_note(); } /** * Local functions in support of the shell command. */ namespace { ToneAlarm *g_dev; } // namespace void tone_alarm_usage(); void tone_alarm_usage() { PX4_INFO("missing command, try 'start', status, 'stop'"); } int tone_alarm_main(int argc, char *argv[]) { if (argc > 1) { const char *argv1 = argv[1]; if (!strcmp(argv1, "start")) { if (g_dev != nullptr) { PX4_ERR("already started"); exit(1); } if (g_dev == nullptr) { g_dev = new ToneAlarm(); if (g_dev == nullptr) { PX4_ERR("couldn't allocate the ToneAlarm driver"); exit(1); } if (OK != g_dev->init()) { delete g_dev; g_dev = nullptr; PX4_ERR("ToneAlarm init failed"); exit(1); } } exit(0); } if (!strcmp(argv1, "stop")) { delete g_dev; g_dev = nullptr; exit(0); } if (!strcmp(argv1, "status")) { g_dev->status(); exit(0); } } tone_alarm_usage(); exit(0); } <|endoftext|>
<commit_before>/* * CampSiteActiveAreaImplementation.cpp * * Created on: Jan 1, 2012 * Author: Kyle */ #include "CampSiteActiveArea.h" #include "CampSiteObserver.h" #include "server/zone/objects/structure/StructureObject.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/objects/tangible/terminal/Terminal.h" #include "server/zone/Zone.h" #include "server/zone/objects/area/events/CampAbandonTask.h" #include "server/zone/objects/area/events/CampDespawnTask.h" void CampSiteActiveAreaImplementation::initializeTransientMembers() { startTasks(); } void CampSiteActiveAreaImplementation::init(CampStructureTemplate* campData) { campStructureData = campData; setRadius(campStructureData->getRadius()); startTasks(); } void CampSiteActiveAreaImplementation::startTasks() { despawnTask = new CampDespawnTask(_this); abandonTask = new CampAbandonTask(_this); abandonTask->schedule(CampSiteActiveArea::ABANDONTIME); despawnTask->schedule(CampSiteActiveArea::DESPAWNTIME); } void CampSiteActiveAreaImplementation::notifyEnter(SceneObject* object) { if (!object->isPlayerCreature()) return; CreatureObject* player = cast<CreatureObject*> (object); if (player == NULL) return; camp->addTemplateSkillMods(player); if (campObserver == NULL) { campObserver = new CampSiteObserver(_this); campObserver->deploy(); } if(object == campOwner && !abandoned) { if(abandonTask->isScheduled()) abandonTask->cancel(); object->registerObserver(ObserverEventType::STARTCOMBAT, campObserver); } else { StringIdChatParameter stringID("camp", "prose_camp_enter"); stringID.setTO(terminal->getObjectName()->getDisplayedName()); player->sendSystemMessage(stringID); player->sendSystemMessage("@camp:sys_camp_heal"); } if (object->isPlayerCreature() && !visitors.contains(object->getObjectID())) visitors.add(object->getObjectID()); if (object->isPlayerCreature()) object->registerObserver(ObserverEventType::HEALINGPERFORMED, campObserver); } void CampSiteActiveAreaImplementation::notifyExit(SceneObject* object) { object->dropObserver(ObserverEventType::HEALINGPERFORMED, campObserver); if (!object->isPlayerCreature()) return; CreatureObject* player = cast<CreatureObject*> (object); if (player == NULL) return; camp->removeTemplateSkillMods(player); if(abandoned || object != campOwner) { StringIdChatParameter stringID("camp", "prose_camp_exit"); stringID.setTO(terminal->getObjectName()->getDisplayedName()); player->sendSystemMessage(stringID); return; } if(!abandoned && abandonTask != NULL) { abandonTask->schedule(CampSiteActiveArea::ABANDONTIME); } } int CampSiteActiveAreaImplementation::notifyHealEvent(int64 quantity) { // Increase XP Pool for heals currentXp += 5; return 1; } int CampSiteActiveAreaImplementation::notifyCombatEvent() { abandonCamp(); if(abandonTask != NULL) if(abandonTask->isScheduled()) abandonTask->cancel(); if(campOwner != NULL) campOwner->sendSystemMessage("@camp:sys_abandoned_camp"); return 1; } void CampSiteActiveAreaImplementation::abandonCamp() { abandoned = true; currentXp = 0; if(despawnTask != NULL && despawnTask->isScheduled()) { despawnTask->cancel(); int newTime = (CampSiteActiveArea::DESPAWNTIME / 6); int maxTime = CampSiteActiveArea::DESPAWNTIME - ((System::getTime() - timeCreated) * 1000); despawnTask->schedule(newTime < maxTime ? newTime : maxTime); } if(terminal != NULL) terminal->setCustomObjectName("Abandoned Camp", true); if(campOwner != NULL) { campOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver); campOwner->sendSystemMessage("@camp:sys_abandoned_camp"); } } bool CampSiteActiveAreaImplementation::despawnCamp() { if(!abandoned && campOwner != NULL && campOwner->getZoneServer() != NULL) { /// Get Player Manager PlayerManager* playerManager = campOwner->getZoneServer()->getPlayerManager(); if (playerManager == NULL) { error("playerManager is null"); return false; } float durationUsed = ((float)(System::getTime() - timeCreated)) / (campStructureData->getDuration()); int amount = 0; amount += (int)(campStructureData->getExperience() * durationUsed); amount += ((visitors.size() -1) * 15); amount += currentXp; int awarded = (amount > campStructureData->getExperience() ? campStructureData->getExperience() : amount); playerManager->awardExperience(campOwner, "camp", awarded, true); } if(despawnTask != NULL ) { if(despawnTask->isScheduled()) despawnTask->cancel(); despawnTask = NULL; } if(abandonTask != NULL) { if(abandonTask->isScheduled()) abandonTask->cancel(); abandonTask = NULL; } if(campOwner != NULL) campOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver); if(camp->getZone() == NULL) return false; ManagedReference<StructureManager*> structureManager = camp->getZone()->getStructureManager(); if (structureManager == NULL) { error("Unable to get StructureManager when placing camp"); return false; } destroyObjectFromWorld(true); destroyObjectFromDatabase(true); structureManager->destroyStructure(camp); return true; } void CampSiteActiveAreaImplementation::assumeOwnership(CreatureObject* player) { /// Get Ghost PlayerObject* ghost = campOwner->getPlayerObject(); if (ghost != NULL) { ghost->removeOwnedStructure(camp); } setOwner(player); abandoned = false; currentXp = 0; /// Get Ghost ghost = campOwner->getPlayerObject(); if (ghost != NULL) { ghost->addOwnedStructure(camp); } player->registerObserver(ObserverEventType::STARTCOMBAT, campObserver); if(abandonTask != NULL && abandonTask->isScheduled()) abandonTask->cancel(); if(terminal != NULL) { String campName = player->getFirstName(); if(!player->getLastName().isEmpty()) campName += " " + player->getLastName(); campName += "'s Camp"; terminal->setCustomObjectName(campName, true); } } <commit_msg>[Fixed] Camps abandoning after 1 minute<commit_after>/* * CampSiteActiveAreaImplementation.cpp * * Created on: Jan 1, 2012 * Author: Kyle */ #include "CampSiteActiveArea.h" #include "CampSiteObserver.h" #include "server/zone/objects/structure/StructureObject.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/objects/tangible/terminal/Terminal.h" #include "server/zone/Zone.h" #include "server/zone/objects/area/events/CampAbandonTask.h" #include "server/zone/objects/area/events/CampDespawnTask.h" void CampSiteActiveAreaImplementation::initializeTransientMembers() { startTasks(); } void CampSiteActiveAreaImplementation::init(CampStructureTemplate* campData) { campStructureData = campData; setRadius(campStructureData->getRadius()); startTasks(); } void CampSiteActiveAreaImplementation::startTasks() { if(despawnTask == NULL) { despawnTask = new CampDespawnTask(_this); } else { if(despawnTask->isScheduled()) despawnTask->cancel(); } if(abandonTask == NULL) { abandonTask = new CampAbandonTask(_this); } else { if(abandonTask->isScheduled()) abandonTask->cancel(); } despawnTask->schedule(CampSiteActiveArea::DESPAWNTIME); abandonTask->schedule(CampSiteActiveArea::ABANDONTIME); } void CampSiteActiveAreaImplementation::notifyEnter(SceneObject* object) { if (!object->isPlayerCreature()) return; CreatureObject* player = cast<CreatureObject*> (object); if (player == NULL) return; camp->addTemplateSkillMods(player); if (campObserver == NULL) { campObserver = new CampSiteObserver(_this); campObserver->deploy(); } if(object == campOwner && !abandoned) { if(abandonTask->isScheduled()) abandonTask->cancel(); object->registerObserver(ObserverEventType::STARTCOMBAT, campObserver); } else { StringIdChatParameter stringID("camp", "prose_camp_enter"); stringID.setTO(terminal->getObjectName()->getDisplayedName()); player->sendSystemMessage(stringID); player->sendSystemMessage("@camp:sys_camp_heal"); } if (object->isPlayerCreature() && !visitors.contains(object->getObjectID())) visitors.add(object->getObjectID()); if (object->isPlayerCreature()) object->registerObserver(ObserverEventType::HEALINGPERFORMED, campObserver); } void CampSiteActiveAreaImplementation::notifyExit(SceneObject* object) { object->dropObserver(ObserverEventType::HEALINGPERFORMED, campObserver); if (!object->isPlayerCreature()) return; CreatureObject* player = cast<CreatureObject*> (object); if (player == NULL) return; camp->removeTemplateSkillMods(player); if(abandoned || object != campOwner) { StringIdChatParameter stringID("camp", "prose_camp_exit"); stringID.setTO(terminal->getObjectName()->getDisplayedName()); player->sendSystemMessage(stringID); return; } if(!abandoned && abandonTask != NULL) { abandonTask->schedule(CampSiteActiveArea::ABANDONTIME); } } int CampSiteActiveAreaImplementation::notifyHealEvent(int64 quantity) { // Increase XP Pool for heals currentXp += 5; return 1; } int CampSiteActiveAreaImplementation::notifyCombatEvent() { abandonCamp(); if(abandonTask != NULL) if(abandonTask->isScheduled()) abandonTask->cancel(); if(campOwner != NULL) campOwner->sendSystemMessage("@camp:sys_abandoned_camp"); return 1; } void CampSiteActiveAreaImplementation::abandonCamp() { abandoned = true; currentXp = 0; if(despawnTask != NULL && despawnTask->isScheduled()) { despawnTask->cancel(); int newTime = (CampSiteActiveArea::DESPAWNTIME / 6); int maxTime = CampSiteActiveArea::DESPAWNTIME - ((System::getTime() - timeCreated) * 1000); despawnTask->schedule(newTime < maxTime ? newTime : maxTime); } if(terminal != NULL) terminal->setCustomObjectName("Abandoned Camp", true); if(campOwner != NULL) { campOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver); campOwner->sendSystemMessage("@camp:sys_abandoned_camp"); } } bool CampSiteActiveAreaImplementation::despawnCamp() { if(!abandoned && campOwner != NULL && campOwner->getZoneServer() != NULL) { /// Get Player Manager PlayerManager* playerManager = campOwner->getZoneServer()->getPlayerManager(); if (playerManager == NULL) { error("playerManager is null"); return false; } float durationUsed = ((float)(System::getTime() - timeCreated)) / (campStructureData->getDuration()); int amount = 0; amount += (int)(campStructureData->getExperience() * durationUsed); amount += ((visitors.size() -1) * 15); amount += currentXp; int awarded = (amount > campStructureData->getExperience() ? campStructureData->getExperience() : amount); playerManager->awardExperience(campOwner, "camp", awarded, true); } if(despawnTask != NULL ) { if(despawnTask->isScheduled()) despawnTask->cancel(); despawnTask = NULL; } if(abandonTask != NULL) { if(abandonTask->isScheduled()) abandonTask->cancel(); abandonTask = NULL; } if(campOwner != NULL) campOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver); if(camp->getZone() == NULL) return false; ManagedReference<StructureManager*> structureManager = camp->getZone()->getStructureManager(); if (structureManager == NULL) { error("Unable to get StructureManager when placing camp"); return false; } destroyObjectFromWorld(true); destroyObjectFromDatabase(true); structureManager->destroyStructure(camp); return true; } void CampSiteActiveAreaImplementation::assumeOwnership(CreatureObject* player) { /// Get Ghost PlayerObject* ghost = campOwner->getPlayerObject(); if (ghost != NULL) { ghost->removeOwnedStructure(camp); } setOwner(player); abandoned = false; currentXp = 0; /// Get Ghost ghost = campOwner->getPlayerObject(); if (ghost != NULL) { ghost->addOwnedStructure(camp); } player->registerObserver(ObserverEventType::STARTCOMBAT, campObserver); if(abandonTask != NULL && abandonTask->isScheduled()) abandonTask->cancel(); if(terminal != NULL) { String campName = player->getFirstName(); if(!player->getLastName().isEmpty()) campName += " " + player->getLastName(); campName += "'s Camp"; terminal->setCustomObjectName(campName, true); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: flyincnt.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: obo $ $Date: 2006-09-15 11:42:31 $ * * 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 * ************************************************************************/ #pragma hdrstop #include "cntfrm.hxx" #include "doc.hxx" #include "flyfrm.hxx" #include "frmtool.hxx" #include "frmfmt.hxx" #include "hints.hxx" #ifndef _FMTORNT_HXX //autogen #include <fmtornt.hxx> #endif #ifndef _FMTFSIZE_HXX //autogen #include <fmtfsize.hxx> #endif #include "txtfrm.hxx" //fuer IsLocked() #include "flyfrms.hxx" // OD 2004-01-19 #110582# #ifndef _DFLYOBJ_HXX #include <dflyobj.hxx> #endif //aus FlyCnt.cxx void DeepCalc( const SwFrm *pFrm ); /************************************************************************* |* |* SwFlyInCntFrm::SwFlyInCntFrm(), ~SwFlyInCntFrm() |* |* Ersterstellung MA 01. Dec. 92 |* Letzte Aenderung MA 09. Apr. 99 |* |*************************************************************************/ SwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm *pAnch ) : SwFlyFrm( pFmt, pAnch ) { bInCnt = bInvalidLayout = bInvalidCntnt = TRUE; SwTwips nRel = pFmt->GetVertOrient().GetPos(); // OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject> Point aRelPos; if( pAnch && pAnch->IsVertical() ) aRelPos.X() = pAnch->IsReverse() ? nRel : -nRel; else aRelPos.Y() = nRel; SetCurrRelPos( aRelPos ); } SwFlyInCntFrm::~SwFlyInCntFrm() { //und Tschuess. if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchorFrm() ) { SwRect aTmp( GetObjRectWithSpaces() ); SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE ); } } // --> OD 2004-06-29 #i28701# TYPEINIT1(SwFlyInCntFrm,SwFlyFrm); // <-- /************************************************************************* |* |* SwFlyInCntFrm::SetRefPoint(), |* |* Ersterstellung MA 01. Dec. 92 |* Letzte Aenderung MA 06. Aug. 95 |* |*************************************************************************/ void SwFlyInCntFrm::SetRefPoint( const Point& rPoint, const Point& rRelAttr, const Point& rRelPos ) { // OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject> ASSERT( rPoint != aRef || rRelAttr != GetCurrRelPos(), "SetRefPoint: no change" ); SwFlyNotify *pNotify = NULL; // No notify at a locked fly frame, if a fly frame is locked, there's // already a SwFlyNotify object on the stack (MakeAll). if( !IsLocked() ) pNotify = new SwFlyNotify( this ); aRef = rPoint; SetCurrRelPos( rRelAttr ); SWRECTFN( GetAnchorFrm() ) (Frm().*fnRect->fnSetPos)( rPoint + rRelPos ); // --> OD 2006-08-25 #i68520# InvalidateObjRectWithSpaces(); // <-- if( pNotify ) { InvalidatePage(); bValidPos = FALSE; bInvalid = TRUE; Calc(); delete pNotify; } } /************************************************************************* |* |* SwFlyInCntFrm::Modify() |* |* Ersterstellung MA 16. Dec. 92 |* Letzte Aenderung MA 02. Sep. 93 |* |*************************************************************************/ void SwFlyInCntFrm::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew ) { BOOL bCallPrepare = FALSE; USHORT nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0; if( RES_ATTRSET_CHG == nWhich ) { if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()-> GetItemState( RES_SURROUND, FALSE ) || SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()-> GetItemState( RES_FRMMACRO, FALSE ) ) { SwAttrSetChg aOld( *(SwAttrSetChg*)pOld ); SwAttrSetChg aNew( *(SwAttrSetChg*)pNew ); aOld.ClearItem( RES_SURROUND ); aNew.ClearItem( RES_SURROUND ); aOld.ClearItem( RES_FRMMACRO ); aNew.ClearItem( RES_FRMMACRO ); if( aNew.Count() ) { SwFlyFrm::Modify( &aOld, &aNew ); bCallPrepare = TRUE; } } else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count()) { SwFlyFrm::Modify( pOld, pNew ); bCallPrepare = TRUE; } } else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich ) { SwFlyFrm::Modify( pOld, pNew ); bCallPrepare = TRUE; } if ( bCallPrepare && GetAnchorFrm() ) AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() ); } /************************************************************************* |* |* SwFlyInCntFrm::Format() |* |* Beschreibung: Hier wird der Inhalt initial mit Formatiert. |* Ersterstellung MA 16. Dec. 92 |* Letzte Aenderung MA 19. May. 93 |* |*************************************************************************/ void SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs ) { if ( !Frm().Height() ) { Lock(); //nicht hintenherum den Anker formatieren. SwCntntFrm *pCntnt = ContainsCntnt(); while ( pCntnt ) { pCntnt->Calc(); pCntnt = pCntnt->GetNextCntntFrm(); } Unlock(); } SwFlyFrm::Format( pAttrs ); } /************************************************************************* |* |* SwFlyInCntFrm::MakeFlyPos() |* |* Beschreibung Im Unterschied zu anderen Frms wird hier nur die |* die RelPos berechnet. Die absolute Position wird ausschliesslich |* per SetAbsPos errechnet. |* Ersterstellung MA 03. Dec. 92 |* Letzte Aenderung MA 12. Apr. 96 |* |*************************************************************************/ // OD 2004-03-23 #i26791# //void SwFlyInCntFrm::MakeFlyPos() void SwFlyInCntFrm::MakeObjPos() { if ( !bValidPos ) { // --> OD 2004-08-12 #i32795# - calling methods <::DeepCalc(..)> and // <GetAnchorFrm()->GetFormatted()> no longer needed due to the changed // formatting of floating screen objects. It also causes layout loops. // if ( !GetAnchorFrm()->IsTxtFrm() || !((SwTxtFrm*)GetAnchorFrm())->IsLocked() ) // ::DeepCalc( GetAnchorFrm() ); // if( GetAnchorFrm()->IsTxtFrm() ) // ((SwTxtFrm*)GetAnchorFrm())->GetFormatted(); // <-- bValidPos = TRUE; SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt(); const SwFmtVertOrient &rVert = pFmt->GetVertOrient(); //Und ggf. noch die aktuellen Werte im Format updaten, dabei darf //zu diesem Zeitpunkt natuerlich kein Modify verschickt werden. SWRECTFN( GetAnchorFrm() ) SwTwips nOld = rVert.GetPos(); SwTwips nAct = bVert ? -GetCurrRelPos().X() : GetCurrRelPos().Y(); if( bRev ) nAct = -nAct; if( nAct != nOld ) { SwFmtVertOrient aVert( rVert ); aVert.SetPos( nAct ); pFmt->LockModify(); pFmt->SetAttr( aVert ); pFmt->UnlockModify(); } } } // --> OD 2004-12-02 #115759# void SwFlyInCntFrm::_ActionOnInvalidation( const InvalidationType _nInvalid ) { switch ( _nInvalid ) { case INVALID_POS: case INVALID_ALL: { AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, &GetFrmFmt() ); } break; } } // <-- /************************************************************************* |* |* SwFlyInCntFrm::NotifyBackground() |* |* Ersterstellung MA 03. Dec. 92 |* Letzte Aenderung MA 26. Aug. 93 |* |*************************************************************************/ void SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect, PrepareHint eHint) { if ( eHint == PREP_FLY_ATTR_CHG ) AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG ); else AnchorFrm()->Prepare( eHint, (void*)&rRect ); } /************************************************************************* |* |* SwFlyInCntFrm::GetRelPos() |* |* Ersterstellung MA 04. Dec. 92 |* Letzte Aenderung MA 04. Dec. 92 |* |*************************************************************************/ const Point SwFlyInCntFrm::GetRelPos() const { Calc(); return GetCurrRelPos(); } /************************************************************************* |* |* SwFlyInCntFrm::RegistFlys() |* |* Ersterstellung MA 26. Nov. 93 |* Letzte Aenderung MA 26. Nov. 93 |* |*************************************************************************/ void SwFlyInCntFrm::RegistFlys() { // vgl. SwRowFrm::RegistFlys() SwPageFrm *pPage = FindPageFrm(); ASSERT( pPage, "Flys ohne Seite anmelden?" ); ::RegistFlys( pPage, this ); } /************************************************************************* |* |* SwFlyInCntFrm::MakeAll() |* |* Ersterstellung MA 18. Feb. 94 |* Letzte Aenderung MA 13. Jun. 96 |* |*************************************************************************/ void SwFlyInCntFrm::MakeAll() { // OD 2004-01-19 #110582# if ( !GetFmt()->GetDoc()->IsVisibleLayerId( GetVirtDrawObj()->GetLayer() ) ) { return; } if ( !GetAnchorFrm() || IsLocked() || IsColLocked() || !FindPageFrm() ) return; Lock(); //Der Vorhang faellt //uebernimmt im DTor die Benachrichtigung const SwFlyNotify aNotify( this ); SwBorderAttrAccess aAccess( SwFrm::GetCache(), this ); const SwBorderAttrs &rAttrs = *aAccess.Get(); if ( IsClipped() ) bValidSize = bHeightClipped = bWidthClipped = FALSE; while ( !bValidPos || !bValidSize || !bValidPrtArea ) { //Nur einstellen wenn das Flag gesetzt ist!! if ( !bValidSize ) { bValidPrtArea = FALSE; /* // This is also done in the Format function, so I think // this code is not necessary anymore: long nOldWidth = aFrm.Width(); const Size aRelSize( CalcRel( rFrmSz ) ); aFrm.Width( aRelSize.Width() ); if ( aFrm.Width() > nOldWidth ) //Damit sich der Inhalt anpasst aFrm.Height( aRelSize.Height() ); */ } if ( !bValidPrtArea ) MakePrtArea( rAttrs ); if ( !bValidSize ) Format( &rAttrs ); if ( !bValidPos ) { // OD 2004-03-23 #i26791# //MakeFlyPos(); MakeObjPos(); } // --> OD 2006-04-13 #b6402800# // re-activate clipping of as-character anchored Writer fly frames // depending on compatibility option <ClipAsCharacterAnchoredWriterFlyFrames> if ( bValidPos && bValidSize && GetFmt()->getIDocumentSettingAccess()->get( IDocumentSettingAccess::CLIP_AS_CHARACTER_ANCHORED_WRITER_FLY_FRAME ) ) { SwFrm* pFrm = AnchorFrm(); if ( Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) && Frm().Width() > pFrm->Prt().Width() ) { Frm().Width( pFrm->Prt().Width() ); bValidPrtArea = FALSE; bWidthClipped = TRUE; } } // <-- } Unlock(); } <commit_msg>INTEGRATION: CWS pchfix02 (1.15.2); FILE MERGED 2006/09/01 17:51:48 kaib 1.15.2.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: flyincnt.cxx,v $ * * $Revision: 1.17 $ * * last change: $Author: obo $ $Date: 2006-09-16 21:18:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include "cntfrm.hxx" #include "doc.hxx" #include "flyfrm.hxx" #include "frmtool.hxx" #include "frmfmt.hxx" #include "hints.hxx" #ifndef _FMTORNT_HXX //autogen #include <fmtornt.hxx> #endif #ifndef _FMTFSIZE_HXX //autogen #include <fmtfsize.hxx> #endif #include "txtfrm.hxx" //fuer IsLocked() #include "flyfrms.hxx" // OD 2004-01-19 #110582# #ifndef _DFLYOBJ_HXX #include <dflyobj.hxx> #endif //aus FlyCnt.cxx void DeepCalc( const SwFrm *pFrm ); /************************************************************************* |* |* SwFlyInCntFrm::SwFlyInCntFrm(), ~SwFlyInCntFrm() |* |* Ersterstellung MA 01. Dec. 92 |* Letzte Aenderung MA 09. Apr. 99 |* |*************************************************************************/ SwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm *pAnch ) : SwFlyFrm( pFmt, pAnch ) { bInCnt = bInvalidLayout = bInvalidCntnt = TRUE; SwTwips nRel = pFmt->GetVertOrient().GetPos(); // OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject> Point aRelPos; if( pAnch && pAnch->IsVertical() ) aRelPos.X() = pAnch->IsReverse() ? nRel : -nRel; else aRelPos.Y() = nRel; SetCurrRelPos( aRelPos ); } SwFlyInCntFrm::~SwFlyInCntFrm() { //und Tschuess. if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchorFrm() ) { SwRect aTmp( GetObjRectWithSpaces() ); SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE ); } } // --> OD 2004-06-29 #i28701# TYPEINIT1(SwFlyInCntFrm,SwFlyFrm); // <-- /************************************************************************* |* |* SwFlyInCntFrm::SetRefPoint(), |* |* Ersterstellung MA 01. Dec. 92 |* Letzte Aenderung MA 06. Aug. 95 |* |*************************************************************************/ void SwFlyInCntFrm::SetRefPoint( const Point& rPoint, const Point& rRelAttr, const Point& rRelPos ) { // OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject> ASSERT( rPoint != aRef || rRelAttr != GetCurrRelPos(), "SetRefPoint: no change" ); SwFlyNotify *pNotify = NULL; // No notify at a locked fly frame, if a fly frame is locked, there's // already a SwFlyNotify object on the stack (MakeAll). if( !IsLocked() ) pNotify = new SwFlyNotify( this ); aRef = rPoint; SetCurrRelPos( rRelAttr ); SWRECTFN( GetAnchorFrm() ) (Frm().*fnRect->fnSetPos)( rPoint + rRelPos ); // --> OD 2006-08-25 #i68520# InvalidateObjRectWithSpaces(); // <-- if( pNotify ) { InvalidatePage(); bValidPos = FALSE; bInvalid = TRUE; Calc(); delete pNotify; } } /************************************************************************* |* |* SwFlyInCntFrm::Modify() |* |* Ersterstellung MA 16. Dec. 92 |* Letzte Aenderung MA 02. Sep. 93 |* |*************************************************************************/ void SwFlyInCntFrm::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew ) { BOOL bCallPrepare = FALSE; USHORT nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0; if( RES_ATTRSET_CHG == nWhich ) { if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()-> GetItemState( RES_SURROUND, FALSE ) || SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()-> GetItemState( RES_FRMMACRO, FALSE ) ) { SwAttrSetChg aOld( *(SwAttrSetChg*)pOld ); SwAttrSetChg aNew( *(SwAttrSetChg*)pNew ); aOld.ClearItem( RES_SURROUND ); aNew.ClearItem( RES_SURROUND ); aOld.ClearItem( RES_FRMMACRO ); aNew.ClearItem( RES_FRMMACRO ); if( aNew.Count() ) { SwFlyFrm::Modify( &aOld, &aNew ); bCallPrepare = TRUE; } } else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count()) { SwFlyFrm::Modify( pOld, pNew ); bCallPrepare = TRUE; } } else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich ) { SwFlyFrm::Modify( pOld, pNew ); bCallPrepare = TRUE; } if ( bCallPrepare && GetAnchorFrm() ) AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() ); } /************************************************************************* |* |* SwFlyInCntFrm::Format() |* |* Beschreibung: Hier wird der Inhalt initial mit Formatiert. |* Ersterstellung MA 16. Dec. 92 |* Letzte Aenderung MA 19. May. 93 |* |*************************************************************************/ void SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs ) { if ( !Frm().Height() ) { Lock(); //nicht hintenherum den Anker formatieren. SwCntntFrm *pCntnt = ContainsCntnt(); while ( pCntnt ) { pCntnt->Calc(); pCntnt = pCntnt->GetNextCntntFrm(); } Unlock(); } SwFlyFrm::Format( pAttrs ); } /************************************************************************* |* |* SwFlyInCntFrm::MakeFlyPos() |* |* Beschreibung Im Unterschied zu anderen Frms wird hier nur die |* die RelPos berechnet. Die absolute Position wird ausschliesslich |* per SetAbsPos errechnet. |* Ersterstellung MA 03. Dec. 92 |* Letzte Aenderung MA 12. Apr. 96 |* |*************************************************************************/ // OD 2004-03-23 #i26791# //void SwFlyInCntFrm::MakeFlyPos() void SwFlyInCntFrm::MakeObjPos() { if ( !bValidPos ) { // --> OD 2004-08-12 #i32795# - calling methods <::DeepCalc(..)> and // <GetAnchorFrm()->GetFormatted()> no longer needed due to the changed // formatting of floating screen objects. It also causes layout loops. // if ( !GetAnchorFrm()->IsTxtFrm() || !((SwTxtFrm*)GetAnchorFrm())->IsLocked() ) // ::DeepCalc( GetAnchorFrm() ); // if( GetAnchorFrm()->IsTxtFrm() ) // ((SwTxtFrm*)GetAnchorFrm())->GetFormatted(); // <-- bValidPos = TRUE; SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt(); const SwFmtVertOrient &rVert = pFmt->GetVertOrient(); //Und ggf. noch die aktuellen Werte im Format updaten, dabei darf //zu diesem Zeitpunkt natuerlich kein Modify verschickt werden. SWRECTFN( GetAnchorFrm() ) SwTwips nOld = rVert.GetPos(); SwTwips nAct = bVert ? -GetCurrRelPos().X() : GetCurrRelPos().Y(); if( bRev ) nAct = -nAct; if( nAct != nOld ) { SwFmtVertOrient aVert( rVert ); aVert.SetPos( nAct ); pFmt->LockModify(); pFmt->SetAttr( aVert ); pFmt->UnlockModify(); } } } // --> OD 2004-12-02 #115759# void SwFlyInCntFrm::_ActionOnInvalidation( const InvalidationType _nInvalid ) { switch ( _nInvalid ) { case INVALID_POS: case INVALID_ALL: { AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, &GetFrmFmt() ); } break; } } // <-- /************************************************************************* |* |* SwFlyInCntFrm::NotifyBackground() |* |* Ersterstellung MA 03. Dec. 92 |* Letzte Aenderung MA 26. Aug. 93 |* |*************************************************************************/ void SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect, PrepareHint eHint) { if ( eHint == PREP_FLY_ATTR_CHG ) AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG ); else AnchorFrm()->Prepare( eHint, (void*)&rRect ); } /************************************************************************* |* |* SwFlyInCntFrm::GetRelPos() |* |* Ersterstellung MA 04. Dec. 92 |* Letzte Aenderung MA 04. Dec. 92 |* |*************************************************************************/ const Point SwFlyInCntFrm::GetRelPos() const { Calc(); return GetCurrRelPos(); } /************************************************************************* |* |* SwFlyInCntFrm::RegistFlys() |* |* Ersterstellung MA 26. Nov. 93 |* Letzte Aenderung MA 26. Nov. 93 |* |*************************************************************************/ void SwFlyInCntFrm::RegistFlys() { // vgl. SwRowFrm::RegistFlys() SwPageFrm *pPage = FindPageFrm(); ASSERT( pPage, "Flys ohne Seite anmelden?" ); ::RegistFlys( pPage, this ); } /************************************************************************* |* |* SwFlyInCntFrm::MakeAll() |* |* Ersterstellung MA 18. Feb. 94 |* Letzte Aenderung MA 13. Jun. 96 |* |*************************************************************************/ void SwFlyInCntFrm::MakeAll() { // OD 2004-01-19 #110582# if ( !GetFmt()->GetDoc()->IsVisibleLayerId( GetVirtDrawObj()->GetLayer() ) ) { return; } if ( !GetAnchorFrm() || IsLocked() || IsColLocked() || !FindPageFrm() ) return; Lock(); //Der Vorhang faellt //uebernimmt im DTor die Benachrichtigung const SwFlyNotify aNotify( this ); SwBorderAttrAccess aAccess( SwFrm::GetCache(), this ); const SwBorderAttrs &rAttrs = *aAccess.Get(); if ( IsClipped() ) bValidSize = bHeightClipped = bWidthClipped = FALSE; while ( !bValidPos || !bValidSize || !bValidPrtArea ) { //Nur einstellen wenn das Flag gesetzt ist!! if ( !bValidSize ) { bValidPrtArea = FALSE; /* // This is also done in the Format function, so I think // this code is not necessary anymore: long nOldWidth = aFrm.Width(); const Size aRelSize( CalcRel( rFrmSz ) ); aFrm.Width( aRelSize.Width() ); if ( aFrm.Width() > nOldWidth ) //Damit sich der Inhalt anpasst aFrm.Height( aRelSize.Height() ); */ } if ( !bValidPrtArea ) MakePrtArea( rAttrs ); if ( !bValidSize ) Format( &rAttrs ); if ( !bValidPos ) { // OD 2004-03-23 #i26791# //MakeFlyPos(); MakeObjPos(); } // --> OD 2006-04-13 #b6402800# // re-activate clipping of as-character anchored Writer fly frames // depending on compatibility option <ClipAsCharacterAnchoredWriterFlyFrames> if ( bValidPos && bValidSize && GetFmt()->getIDocumentSettingAccess()->get( IDocumentSettingAccess::CLIP_AS_CHARACTER_ANCHORED_WRITER_FLY_FRAME ) ) { SwFrm* pFrm = AnchorFrm(); if ( Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) && Frm().Width() > pFrm->Prt().Width() ) { Frm().Width( pFrm->Prt().Width() ); bValidPrtArea = FALSE; bWidthClipped = TRUE; } } // <-- } Unlock(); } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbVectorDataFileReader.h" #include "otbImageFileWriter.h" #include "otbVectorData.h" #include "otbVectorDataProjectionFilter.h" #include <fstream> #include <iostream> #include "itkRGBAPixel.h" #include "otbImage.h" #include "otbVectorDataToMapFilter.h" int otbVectorDataToMapFilterWorld(int argc, char * argv []) { if (argc < 11) { std::cout << argv[0] << " <input vector filename> <input image filename>" << " <output vector filename> " << " <sizeX> <sizeY> " << " <origin lon> <origin lat> " << " <spacing lon> <spacing lat> " << " <font filename>" << std::endl; return EXIT_FAILURE; } //Read the vector data typedef otb::VectorData<> VectorDataType; typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType; //Reproject the vector data in the proper projection typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType; VectorDataFileReaderType::Pointer reader0 = VectorDataFileReaderType::New(); reader0->SetFileName(argv[1]); ProjectionFilterType::Pointer projection0 = ProjectionFilterType::New(); projection0->SetInput(reader0->GetOutput()); VectorDataFileReaderType::Pointer reader1 = VectorDataFileReaderType::New(); reader1->SetFileName(argv[2]); ProjectionFilterType::Pointer projection1 = ProjectionFilterType::New(); projection1->SetInput(reader1->GetOutput()); //Convert the vector data into an image typedef itk::RGBAPixel<unsigned char> PixelType; typedef otb::Image<PixelType, 2> ImageType; ImageType::SizeType size; size[0] = atoi(argv[4]); size[1] = atoi(argv[5]); ImageType::PointType origin; origin[0] = atof(argv[6]); origin[1] = atof(argv[7]); ImageType::SpacingType spacing; spacing[0] = atof(argv[8]); spacing[1] = atof(argv[9]); typedef otb::VectorDataToMapFilter<VectorDataType, ImageType> VectorDataToMapFilterType; VectorDataToMapFilterType::Pointer vectorDataRendering = VectorDataToMapFilterType::New(); vectorDataRendering->SetInput(0, projection0->GetOutput()); vectorDataRendering->SetInput(1, projection1->GetOutput()); vectorDataRendering->SetSize(size); vectorDataRendering->SetOrigin(origin); vectorDataRendering->SetSpacing(spacing); vectorDataRendering->SetFontFileName(argv[10]); vectorDataRendering->AddStyle("world"); vectorDataRendering->AddStyle("city"); vectorDataRendering->UseAsOverlayOff(); //Save the image in a file typedef otb::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput(vectorDataRendering->GetOutput()); writer->SetFileName(argv[3]); writer->Update(); return EXIT_SUCCESS; } <commit_msg>TEST: explicit definition of the output projRef<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbVectorDataFileReader.h" #include "otbImageFileWriter.h" #include "otbVectorData.h" #include "otbVectorDataProjectionFilter.h" #include <fstream> #include <iostream> #include "itkRGBAPixel.h" #include "otbImage.h" #include "otbVectorDataToMapFilter.h" int otbVectorDataToMapFilterWorld(int argc, char * argv []) { if (argc < 11) { std::cout << argv[0] << " <input vector filename> <input image filename>" << " <output vector filename> " << " <sizeX> <sizeY> " << " <origin lon> <origin lat> " << " <spacing lon> <spacing lat> " << " <font filename>" << std::endl; return EXIT_FAILURE; } //Read the vector data typedef otb::VectorData<> VectorDataType; typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType; //Reproject the vector data in the proper projection typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType; std::string outputProjRef("GEOGCS[\"GCS_WGS_1984\", DATUM[\"D_WGS_1984\", " "SPHEROID[\"WGS_1984\", 6378137, 298.257223563]], PRIMEM[\"Greenwich\", 0]," " UNIT[\"Degree\", 0.017453292519943295]]"); VectorDataFileReaderType::Pointer reader0 = VectorDataFileReaderType::New(); reader0->SetFileName(argv[1]); ProjectionFilterType::Pointer projection0 = ProjectionFilterType::New(); projection0->SetInput(reader0->GetOutput()); projection0->SetOutputProjectionRef(outputProjRef); VectorDataFileReaderType::Pointer reader1 = VectorDataFileReaderType::New(); reader1->SetFileName(argv[2]); ProjectionFilterType::Pointer projection1 = ProjectionFilterType::New(); projection1->SetInput(reader1->GetOutput()); projection1->SetOutputProjectionRef(outputProjRef); //Convert the vector data into an image typedef itk::RGBAPixel<unsigned char> PixelType; typedef otb::Image<PixelType, 2> ImageType; ImageType::SizeType size; size[0] = atoi(argv[4]); size[1] = atoi(argv[5]); ImageType::PointType origin; origin[0] = atof(argv[6]); origin[1] = atof(argv[7]); ImageType::SpacingType spacing; spacing[0] = atof(argv[8]); spacing[1] = atof(argv[9]); typedef otb::VectorDataToMapFilter<VectorDataType, ImageType> VectorDataToMapFilterType; VectorDataToMapFilterType::Pointer vectorDataRendering = VectorDataToMapFilterType::New(); vectorDataRendering->SetInput(0, projection0->GetOutput()); vectorDataRendering->SetInput(1, projection1->GetOutput()); vectorDataRendering->SetSize(size); vectorDataRendering->SetOrigin(origin); vectorDataRendering->SetSpacing(spacing); vectorDataRendering->SetFontFileName(argv[10]); vectorDataRendering->AddStyle("world"); vectorDataRendering->AddStyle("city"); vectorDataRendering->UseAsOverlayOff(); //Save the image in a file typedef otb::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput(vectorDataRendering->GetOutput()); writer->SetFileName(argv[3]); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // SampleView plugin //============================================================================== #include "sampleviewplugin.h" //============================================================================== #include <QIcon> //============================================================================== namespace OpenCOR { namespace SampleView { //============================================================================== PLUGININFO_FUNC SampleViewPluginInfo() { Descriptions descriptions; descriptions.insert("en", QString::fromUtf8("a plugin that provides a test view.")); descriptions.insert("fr", QString::fromUtf8("une extension qui fournit une vue de test.")); return new PluginInfo(PluginInfo::Sample, true, false, QStringList() << "Core" << "Sample", descriptions); } //============================================================================== // File handling interface //============================================================================== bool SampleViewPlugin::saveFile(const QString &pOldFileName, const QString &pNewFileName) { Q_UNUSED(pOldFileName); Q_UNUSED(pNewFileName); // We don't handle this interface... return false; } //============================================================================== void SampleViewPlugin::fileOpened(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::filePermissionsChanged(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::fileModified(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::fileReloaded(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::fileRenamed(const QString &pOldFileName, const QString &pNewFileName) { Q_UNUSED(pOldFileName); Q_UNUSED(pNewFileName); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::fileClosed(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== // I18n interface //============================================================================== void SampleViewPlugin::retranslateUi() { // We don't handle this interface... } //============================================================================== // Plugin interface //============================================================================== void SampleViewPlugin::initializePlugin(QMainWindow *pMainWindow) { Q_UNUSED(pMainWindow); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::finalizePlugin() { // We don't handle this interface... } //============================================================================== void SampleViewPlugin::pluginInitialized(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::loadSettings(QSettings *pSettings) { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::saveSettings(QSettings *pSettings) const { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::handleAction(const QUrl &pUrl) { Q_UNUSED(pUrl); // We don't handle this interface... } //============================================================================== // View interface //============================================================================== ViewInterface::Mode SampleViewPlugin::viewMode() const { // Return our mode return ViewInterface::Sample; } //============================================================================== QStringList SampleViewPlugin::viewMimeTypes() const { // Return the MIME types we support // Note: we allow any kind of file, hence our empty string list... return QStringList(); } //============================================================================== void SampleViewPlugin::initializeView() { // We don't handle this interface... } //============================================================================== void SampleViewPlugin::finalizeView() { // We don't handle this interface... } //============================================================================== QWidget * SampleViewPlugin::viewWidget(const QString &pFileName, const bool &pCreate) { // We don't handle this interface... return 0; } //============================================================================== void SampleViewPlugin::removeViewWidget(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== QString SampleViewPlugin::viewName() const { // Return our raw view's name return tr("Sample"); } //============================================================================== QIcon SampleViewPlugin::fileTabIcon(const QString &pFileName) const { Q_UNUSED(pFileName); // We don't handle this interface... return QIcon(); } //============================================================================== } // namespace SampleView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // SampleView plugin //============================================================================== #include "sampleviewplugin.h" //============================================================================== #include <QIcon> //============================================================================== namespace OpenCOR { namespace SampleView { //============================================================================== PLUGININFO_FUNC SampleViewPluginInfo() { Descriptions descriptions; descriptions.insert("en", QString::fromUtf8("a plugin that provides a test view.")); descriptions.insert("fr", QString::fromUtf8("une extension qui fournit une vue de test.")); return new PluginInfo(PluginInfo::Sample, true, false, QStringList() << "Core" << "Sample", descriptions); } //============================================================================== // File handling interface //============================================================================== bool SampleViewPlugin::saveFile(const QString &pOldFileName, const QString &pNewFileName) { Q_UNUSED(pOldFileName); Q_UNUSED(pNewFileName); // We don't handle this interface... return false; } //============================================================================== void SampleViewPlugin::fileOpened(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::filePermissionsChanged(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::fileModified(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::fileReloaded(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::fileRenamed(const QString &pOldFileName, const QString &pNewFileName) { Q_UNUSED(pOldFileName); Q_UNUSED(pNewFileName); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::fileClosed(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== // I18n interface //============================================================================== void SampleViewPlugin::retranslateUi() { // We don't handle this interface... } //============================================================================== // Plugin interface //============================================================================== void SampleViewPlugin::initializePlugin(QMainWindow *pMainWindow) { Q_UNUSED(pMainWindow); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::finalizePlugin() { // We don't handle this interface... } //============================================================================== void SampleViewPlugin::pluginInitialized(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::loadSettings(QSettings *pSettings) { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::saveSettings(QSettings *pSettings) const { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void SampleViewPlugin::handleAction(const QUrl &pUrl) { Q_UNUSED(pUrl); // We don't handle this interface... } //============================================================================== // View interface //============================================================================== ViewInterface::Mode SampleViewPlugin::viewMode() const { // Return our mode return ViewInterface::Sample; } //============================================================================== QStringList SampleViewPlugin::viewMimeTypes() const { // Return the MIME types we support // Note: we allow any kind of file, hence our empty string list... return QStringList(); } //============================================================================== void SampleViewPlugin::initializeView() { // We don't handle this interface... } //============================================================================== void SampleViewPlugin::finalizeView() { // We don't handle this interface... } //============================================================================== QWidget * SampleViewPlugin::viewWidget(const QString &pFileName, const bool &pCreate) { Q_UNUSED(pFileName); Q_UNUSED(pCreate); // We don't handle this interface... return 0; } //============================================================================== void SampleViewPlugin::removeViewWidget(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== QString SampleViewPlugin::viewName() const { // Return our raw view's name return tr("Sample"); } //============================================================================== QIcon SampleViewPlugin::fileTabIcon(const QString &pFileName) const { Q_UNUSED(pFileName); // We don't handle this interface... return QIcon(); } //============================================================================== } // namespace SampleView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before><commit_msg>re-enable histo clearing<commit_after><|endoftext|>
<commit_before>// Conway's Game of Life // // Wikipedia // https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life // It From Bit: Is The Universe A Cellular Automaton? // https://medium.com/starts-with-a-bang/it-from-bit-is-the-universe-a-cellular-automaton-4a5b1426ba6d // // build & run // cmake -A x64 .. && cmake --build . --config Release && Release\gameoflife.exe #include "config.h" #include "olcPixelGameEngine.h" #include <chrono> #include <thread> #include <fstream> #include <algorithm> std::vector<std::string> glider = { " o", "o o", " oo" }; std::vector<std::string> lwss = { // lightweight spaceship " oooo", "o o", " o", "o o" }; std::vector<std::string> mwss = { // middleweight spaceship " ooo", "ooooo", "ooo oo", " oo" }; std::vector<std::string> pulsar = { // middleweight spaceship " ", " o o ", " o o ", " oo oo ", " ", " ooo oo oo ooo ", " o o o o o o ", " oo oo ", " ", " oo oo ", " o o o o o o ", " ooo oo oo ooo ", " ", " oo oo ", " o o ", " o o ", " ", }; std::vector<std::string> glider_gun = { " ", " o ", " o o ", " oo oo oo ", " o o oo oo ", " oo o o oo ", " oo o o oo o o ", " o o o ", " o o ", " oo ", " ", }; class GameOfLife : public olc::PixelGameEngine { std::vector<bool> worldA; ///< state A of the world std::vector<bool> worldB; ///< state B of the world std::vector<bool> *world0; ///< pointer to the old state std::vector<bool> *world1; ///< pointer to the new state float timesum = 0.0; ///< internal variable which stores the accumulted time between 2 updates int fps = 5; ///< update frequency int ox = 20; ///< x origin of the world int oy = 20; ///< y origin of the world int width; ///< horizontal dimension of the world int height; ///< vertical dimension of the world int scale = 3; std::vector<std::vector<std::string> > objects; int object = 0; public: GameOfLife() { sAppName = "Game of life"; objects.push_back(glider); objects.push_back(lwss); objects.push_back(mwss); objects.push_back(pulsar); objects.push_back(glider_gun); auto object = load_lif(std::string(CMAKE_SOURCE_DIR) + "/life/RABBITS.LIF"); objects.push_back(object); } public: std::vector<std::string> tokenize(std::string const &line) { std::vector<std::string> tokens; std::string token; std::stringstream iss(line); while (std::getline(iss, token,' ')) tokens.push_back(token); // for(auto &t : tokens) // std::cout << "token: " << t << '\n'; return tokens; } std::vector<std::string> load_lif(std::string const &filename) { std::cout << "loading " << filename << '\n'; std::ifstream infile(filename); if (! infile.is_open()) { std::cerr << "ERROR: "<< filename << " file not found!\n"; return std::vector<std::string>(); } std::vector<std::string> object; int ox = 0; int oy = 0; std::string line; while (std::getline(infile, line)) { // std::cout << "next line...\n"; if (line[0]=='#') { auto tokens = tokenize(line); if(tokens[0]=="#Life") { // std::cout << "file version: " << tokens[1] << '\n'; } else if(tokens[0]=="#P") { ox = std::stoi(tokens[1]); oy = std::stoi(tokens[2]); // std::cout << "ox=" << ox << "; "; // std::cout << "oy=" << oy << '\n'; } } else { std::replace( line.begin(), line.end(), '*', 'o'); std::replace( line.begin(), line.end(), '.', ' '); object.push_back(line); } } return object; } /// convert indices i,j to a 1D array index int idx(int i, int j) const { return i*width+j; } void set_random(std::vector<bool> &world) { // random array for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) world[idx(i,j)] = !static_cast<bool> (rand() % 5); } void set_empty(std::vector<bool> &world) { for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) world[idx(i,j)] = false; } bool OnUserCreate() override { // compute size of the world from margins and scale width = (this->ScreenWidth()-2*ox)/scale; height = (this->ScreenHeight()-2*oy)/scale; // allocate world arrays worldA.resize(width*height); worldB.resize(width*height); set_random(worldA); world0 = &worldA; world1 = &worldB; return true; } void calculate_new_world() { // calculate the new world as a function of the old one for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) { // count neighbours int neigh = - static_cast<int>( (*world0)[idx(i,j)] ); for(int ii=-1; ii<=1; ii++) for(int jj=-1; jj<=1; jj++) if (i+ii>0 && i+ii<height && j+jj>0 && jj+jj<width ) neigh += static_cast<int>( (*world0)[idx(i+ii,j+jj)] ); if(neigh<2) // underpopulation (*world1)[idx(i,j)] = false; else if(neigh>3) // overpopulation (*world1)[idx(i,j)] = false; else if(neigh==3) // reproduction (*world1)[idx(i,j)] = true; else (*world1)[idx(i,j)] = (*world0)[idx(i,j)]; } } void draw_world() { for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) { int colour = 0; if ((*world0)[idx(i,j)]) colour = 255; FillRect (ox+(j*scale), oy+(i*scale), scale, scale, olc::Pixel(colour, colour, colour)); } } bool OnUserUpdate(float fElapsedTime) override { // Erase previous frame Clear(olc::BLACK); if (GetKey(olc::Key::C).bHeld) set_empty(*world0); if (GetKey(olc::Key::R).bHeld) set_random(*world0); if (GetKey(olc::Key::LEFT).bPressed || GetMouseWheel() > 0) { object+=1; if (object==objects.size()) object=0; std::cout << "setting object to " << object << std::endl; } if (GetKey(olc::Key::RIGHT).bPressed || GetMouseWheel() < 0) { object-=1; if (object<0) object=objects.size()-1; std::cout << "setting object to " << object << std::endl; } if (GetKey(olc::Key::UP).bPressed) { fps*=2; if (fps>120) fps=120; std::cout << "setting fps to " << fps << std::endl; } if (GetKey(olc::Key::DOWN).bPressed) { fps/=2; if (fps<1) fps=1; std::cout << "setting fps to " << fps << std::endl; } // get mouse pos olc::vi2d mpos = {(GetMouseX() - ox)/scale, (GetMouseY() - oy)/scale}; // accumulate time timesum = timesum + fElapsedTime; float frametime = 1.0/fps; // check that it whether it is time to create a new generation if (timesum>frametime) { while(timesum>frametime) timesum -= frametime; calculate_new_world(); // swap world auto w = world0; world0 = world1; world1 = w; } draw_world(); // draw borders DrawRect(ox-1, oy-1, scale*width+1, scale*height+1, olc::GREEN); // draw current object at mouse pos in red auto &curobj = objects[object]; for(int i=0; i<curobj.size(); ++i) for(int j=0; j<curobj[i].size(); ++j) { if(curobj[i][j]!=' ') { int posx = mpos.x+j; int posy = mpos.y+i; if (posx>=0 && posx<width && posy>=0 && posy<height) FillRect (ox+(posx*scale), oy+(posy*scale), scale, scale, olc::RED); } } if (GetMouse(0).bPressed) { std::cout << "creating object\n"; for(int i=0; i<curobj.size(); ++i) for(int j=0; j<curobj[i].size(); ++j) { bool value = false; if(curobj[i][j]!=' ') value=true; int posx = mpos.x+j; int posy = mpos.y+i; if (posx>=0 && posx<width && posy>=0 && posy<height) (*world0)[idx(posy,posx)] = value; } } // draw title this->DrawString({5,5}, "Game of Life"); return true; } }; int main() { GameOfLife demo; //demo.load_lif(std::string(CMAKE_SOURCE_DIR) + "/life/RABBITS.LIF"); if (demo.Construct(600, 300, 2, 2)) demo.Start(); return 0; } <commit_msg>add doc<commit_after>// Conway's Game of Life // using "Pixel Game Engine" from Javidx9 // https://community.onelonecoder.com/ // // // Wikipedia // https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life // It From Bit: Is The Universe A Cellular Automaton? // https://medium.com/starts-with-a-bang/it-from-bit-is-the-universe-a-cellular-automaton-4a5b1426ba6d // Cellular Automata FAQ // http://cafaq.com/lifefaq/index.php // best 152 patterns from the first quarter-century of Conway's Game of Life (Alan W. Hensel) // http://www.ibiblio.org/lifepatterns/lifep.zip // // build & run // cmake -A x64 .. && cmake --build . --config Release && Release\gameoflife.exe #include "config.h" #include "olcPixelGameEngine.h" #include <chrono> #include <thread> #include <fstream> #include <algorithm> std::vector<std::string> glider = { " o", "o o", " oo" }; std::vector<std::string> lwss = { // lightweight spaceship " oooo", "o o", " o", "o o" }; std::vector<std::string> mwss = { // middleweight spaceship " ooo", "ooooo", "ooo oo", " oo" }; std::vector<std::string> pulsar = { // middleweight spaceship " ", " o o ", " o o ", " oo oo ", " ", " ooo oo oo ooo ", " o o o o o o ", " oo oo ", " ", " oo oo ", " o o o o o o ", " ooo oo oo ooo ", " ", " oo oo ", " o o ", " o o ", " ", }; std::vector<std::string> glider_gun = { " ", " o ", " o o ", " oo oo oo ", " o o oo oo ", " oo o o oo ", " oo o o oo o o ", " o o o ", " o o ", " oo ", " ", }; class GameOfLife : public olc::PixelGameEngine { std::vector<bool> worldA; ///< state A of the world std::vector<bool> worldB; ///< state B of the world std::vector<bool> *world0; ///< pointer to the old state std::vector<bool> *world1; ///< pointer to the new state float timesum = 0.0; ///< internal variable which stores the accumulted time between 2 updates int fps = 5; ///< update frequency int ox = 20; ///< x origin of the world int oy = 20; ///< y origin of the world int width; ///< horizontal dimension of the world int height; ///< vertical dimension of the world int scale = 3; std::vector<std::vector<std::string> > objects; ///< array storing interesting objects int object = 0; ///< current object public: GameOfLife() { sAppName = "Game of life"; // fill "objects" with interesting patterns objects.push_back(glider); objects.push_back(lwss); objects.push_back(mwss); objects.push_back(pulsar); objects.push_back(glider_gun); objects.push_back(load_lif(std::string(CMAKE_SOURCE_DIR) + "/life/RABBITS.LIF")); } private: /// split a line of text into an array of tokens (words) /// "a few words" => {"a", "few", "words"} std::vector<std::string> tokenize(std::string const &line) { std::vector<std::string> tokens; std::string token; std::stringstream iss(line); while (std::getline(iss, token,' ')) tokens.push_back(token); // for(auto &t : tokens) // std::cout << "token: " << t << '\n'; return tokens; } /// load a .LIF file from Alan W. Hensel's library /// see std::vector<std::string> load_lif(std::string const &filename) { std::cout << "loading " << filename << '\n'; std::ifstream infile(filename); if (! infile.is_open()) { std::cerr << "ERROR: "<< filename << " file not found!\n"; return std::vector<std::string>(); } std::vector<std::string> object; int ox = 0; int oy = 0; std::string line; while (std::getline(infile, line)) { // std::cout << "next line...\n"; if (line[0]=='#') { auto tokens = tokenize(line); if(tokens[0]=="#Life") { // TODO: check version // std::cout << "file version: " << tokens[1] << '\n'; } else if(tokens[0]=="#P") { ox = std::stoi(tokens[1]); oy = std::stoi(tokens[2]); // std::cout << "ox=" << ox << "; "; // std::cout << "oy=" << oy << '\n'; } } else { std::replace( line.begin(), line.end(), '*', 'o'); std::replace( line.begin(), line.end(), '.', ' '); object.push_back(line); } } return object; } /// convert i, j indices to a 1D array index int idx(int i, int j) const { return i*width+j; } /// fill the world with a random set of dots void set_random(std::vector<bool> &world) { // random array for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) world[idx(i,j)] = !static_cast<bool> (rand() % 5); } /// clear the world void set_empty(std::vector<bool> &world) { for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) world[idx(i,j)] = false; } /// PGE function called when aplication starts bool OnUserCreate() override { // compute size of the world from margins and scale width = (this->ScreenWidth()-2*ox)/scale; height = (this->ScreenHeight()-2*oy)/scale; // allocate world arrays worldA.resize(width*height); worldB.resize(width*height); set_random(worldA); world0 = &worldA; world1 = &worldB; return true; } /// calculate the new world as a function of the old one /// apply the rules of the game of life void calculate_new_world() { for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) { // count neighbours int neigh = - static_cast<int>( (*world0)[idx(i,j)] ); for(int ii=-1; ii<=1; ii++) for(int jj=-1; jj<=1; jj++) if (i+ii>0 && i+ii<height && j+jj>0 && jj+jj<width ) neigh += static_cast<int>( (*world0)[idx(i+ii,j+jj)] ); if(neigh<2) // underpopulation (*world1)[idx(i,j)] = false; else if(neigh>3) // overpopulation (*world1)[idx(i,j)] = false; else if(neigh==3) // reproduction (*world1)[idx(i,j)] = true; else (*world1)[idx(i,j)] = (*world0)[idx(i,j)]; } } /// draw the current state of the world onto the screen void draw_world() { for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) { int colour = 0; // black if ((*world0)[idx(i,j)]) colour = 255; // white FillRect (ox+(j*scale), oy+(i*scale), scale, scale, olc::Pixel(colour, colour, colour)); } } /// PGE function called at every new frame bool OnUserUpdate(float fElapsedTime) override { // Erase previous frame Clear(olc::BLACK); // User interaction management if (GetKey(olc::Key::C).bHeld) set_empty(*world0); if (GetKey(olc::Key::R).bHeld) set_random(*world0); if (GetKey(olc::Key::LEFT).bPressed || GetMouseWheel() > 0) { object+=1; if (object==objects.size()) object=0; std::cout << "setting object to " << object << std::endl; } if (GetKey(olc::Key::RIGHT).bPressed || GetMouseWheel() < 0) { object-=1; if (object<0) object=objects.size()-1; std::cout << "setting object to " << object << std::endl; } if (GetKey(olc::Key::UP).bPressed) { fps*=2; if (fps>120) fps=120; std::cout << "setting fps to " << fps << std::endl; } if (GetKey(olc::Key::DOWN).bPressed) { fps/=2; if (fps<1) fps=1; std::cout << "setting fps to " << fps << std::endl; } // get mouse pos olc::vi2d mpos = {(GetMouseX() - ox)/scale, (GetMouseY() - oy)/scale}; // accumulate time timesum = timesum + fElapsedTime; float frametime = 1.0/fps; // check that it whether it is time to create a new generation if (timesum>frametime) { while(timesum>frametime) timesum -= frametime; calculate_new_world(); // swap world auto w = world0; world0 = world1; world1 = w; } draw_world(); // draw borders DrawRect(ox-1, oy-1, scale*width+1, scale*height+1, olc::GREEN); // draw current object at mouse pos in red auto &curobj = objects[object]; for(int i=0; i<curobj.size(); ++i) for(int j=0; j<curobj[i].size(); ++j) { if(curobj[i][j]!=' ') { int posx = mpos.x+j; int posy = mpos.y+i; if (posx>=0 && posx<width && posy>=0 && posy<height) FillRect (ox+(posx*scale), oy+(posy*scale), scale, scale, olc::RED); } } if (GetMouse(0).bPressed) { std::cout << "creating object\n"; for(int i=0; i<curobj.size(); ++i) for(int j=0; j<curobj[i].size(); ++j) { bool value = false; if(curobj[i][j]!=' ') value=true; int posx = mpos.x+j; int posy = mpos.y+i; if (posx>=0 && posx<width && posy>=0 && posy<height) (*world0)[idx(posy,posx)] = value; } } // draw title this->DrawString({5,5}, "Game of Life"); return true; } }; int main() { GameOfLife demo; //demo.load_lif(std::string(CMAKE_SOURCE_DIR) + "/life/RABBITS.LIF"); if (demo.Construct(600, 300, 2, 2)) demo.Start(); return 0; } <|endoftext|>
<commit_before>/* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // $Id$ #include <qdir.h> #include <qfile.h> #include <qtextstream.h> #include <klocale.h> #include <kdebug.h> #include <kstandarddirs.h> #include "event.h" #include "freebusy.h" #include "icalformat.h" #include "calendar.h" #include "scheduler.h" using namespace KCal; ScheduleMessage::ScheduleMessage(IncidenceBase *incidence,int method,ScheduleMessage::Status status) { mIncidence = incidence; mMethod = method; mStatus = status; } QString ScheduleMessage::statusName(ScheduleMessage::Status status) { switch (status) { case PublishNew: return i18n("Publish"); case Obsolete: return i18n("Obsolete"); case RequestNew: return i18n("New Request"); case RequestUpdate: return i18n("Updated Request"); default: return i18n("Unknown Status: %1").arg(QString::number(status)); } } Scheduler::Scheduler(Calendar *calendar) { mCalendar = calendar; mFormat = mCalendar->iCalFormat(); } Scheduler::~Scheduler() { } bool Scheduler::acceptTransaction(IncidenceBase *incidence,Method method,ScheduleMessage::Status status) { kdDebug() << "Scheduler::acceptTransaction " << endl; switch (method) { case Publish: return acceptPublish(incidence, status, method); case Request: return acceptRequest(incidence, status); case Add: return acceptAdd(incidence, status); case Cancel: return acceptCancel(incidence, status); case Declinecounter: return acceptDeclineCounter(incidence, status); case Reply: return acceptReply(incidence, status, method); case Refresh: return acceptRefresh(incidence, status); case Counter: return acceptCounter(incidence, status); default: deleteTransaction(incidence); return false; } deleteTransaction(incidence); return false; } QString Scheduler::methodName(Method method) { switch (method) { case Publish: return i18n("Publish"); case Request: return i18n("Request"); case Refresh: return i18n("Refresh"); case Cancel: return i18n("Cancel"); case Add: return i18n("Add"); case Reply: return i18n("Reply"); case Counter: return i18n("Counter"); case Declinecounter: return i18n("Decline Counter"); default: return i18n("Unknown"); } } bool Scheduler::deleteTransaction(IncidenceBase *) { return true; } bool Scheduler::acceptPublish(IncidenceBase *incidence,ScheduleMessage::Status status, Method method) { if(incidence->type()=="FreeBusy") { return acceptFreeBusy(incidence, method); } switch (status) { case ScheduleMessage::PublishNew: if (!mCalendar->getEvent(incidence->uid())) { Incidence *inc = static_cast<Incidence *>(incidence); mCalendar->addIncidence(inc); deleteTransaction(incidence); } return true; case ScheduleMessage::Obsolete: return true; default: deleteTransaction(incidence); return false; } deleteTransaction(incidence); return false; } bool Scheduler::acceptRequest(IncidenceBase *incidence,ScheduleMessage::Status status) { Incidence *inc = static_cast<Incidence *>(incidence); switch (status) { case ScheduleMessage::Obsolete: return true; case ScheduleMessage::RequestNew: mCalendar->addIncidence(inc); deleteTransaction(incidence); return true; case ScheduleMessage::RequestUpdate: Event *even; even = mCalendar->getEvent(incidence->uid()); if (even) { mCalendar->deleteEvent(even); } mCalendar->addIncidence(inc); deleteTransaction(incidence); return true; default: return false; } deleteTransaction(incidence); return false; } bool Scheduler::acceptAdd(IncidenceBase *incidence,ScheduleMessage::Status status) { deleteTransaction(incidence); return false; } bool Scheduler::acceptCancel(IncidenceBase *incidence,ScheduleMessage::Status status) { bool ret = false; //get event in calendar QPtrList<Event> eventList; eventList=mCalendar->getEvents(incidence->dtStart().date(),incidence->dtStart().date(),false); Event *ev; for ( ev = eventList.first(); ev; ev = eventList.next() ) { if (ev->uid()==incidence->uid()) { //get matching attendee in calendar kdDebug() << "Scheduler::acceptTransaction match found!" << endl; mCalendar->deleteEvent(ev); ret = true; } } deleteTransaction(incidence); return ret; } bool Scheduler::acceptDeclineCounter(IncidenceBase *incidence,ScheduleMessage::Status status) { deleteTransaction(incidence); return false; } //bool Scheduler::acceptFreeBusy(Incidence *incidence,ScheduleMessage::Status status) //{ // deleteTransaction(incidence); // return false; //} bool Scheduler::acceptReply(IncidenceBase *incidence,ScheduleMessage::Status status, Method method) { if(incidence->type()=="FreeBusy") { return acceptFreeBusy(incidence, method); } bool ret = false; Event *ev = mCalendar->getEvent(incidence->uid()); if (ev) { //get matching attendee in calendar kdDebug(5800) << "Scheduler::acceptTransaction match found!" << endl; QPtrList<Attendee> attendeesIn = incidence->attendees(); QPtrList<Attendee> attendeesEv = ev->attendees(); Attendee *attIn; Attendee *attEv; for ( attIn = attendeesIn.first(); attIn; attIn = attendeesIn.next() ) { for ( attEv = attendeesEv.first(); attEv; attEv = attendeesEv.next() ) { if (attIn->email()==attEv->email()) { //update attendee-info kdDebug(5800) << "Scheduler::acceptTransaction update attendee" << endl; //attEv->setRole(attIn->role()); attEv->setStatus(attIn->status()); //attEv->setRSVP(attIn->RSVP()); ev->setRevision(ev->revision()+1); ret = true; } } } } deleteTransaction(incidence); return ret; } bool Scheduler::acceptRefresh(IncidenceBase *incidence,ScheduleMessage::Status status) { // handled in korganizer's IncomingDialog deleteTransaction(incidence); return false; } bool Scheduler::acceptCounter(IncidenceBase *incidence,ScheduleMessage::Status status) { deleteTransaction(incidence); return false; } bool Scheduler::acceptFreeBusy(IncidenceBase *incidence, Method method) { FreeBusy *freebusy = static_cast<FreeBusy *>(incidence); QString freeBusyDirName = locateLocal("appdata","freebusy"); kdDebug() << "acceptFreeBusy:: freeBusyDirName: " << freeBusyDirName << endl; QString from; if(method == Scheduler::Publish) { from = freebusy->organizer(); } if((method == Scheduler::Reply) && (freebusy->attendeeCount() == 1)) { Attendee *attendee = freebusy->attendees().first(); from = attendee->email(); } QDir freeBusyDir(freeBusyDirName); if (!freeBusyDir.exists()) { kdDebug() << "Directory " << freeBusyDirName << " does not exist!" << endl; kdDebug() << "Creating directory: " << freeBusyDirName << endl; if(!freeBusyDir.mkdir(freeBusyDirName, TRUE)) { kdDebug() << "Could not create directory: " << freeBusyDirName << endl; return false; } } QString filename(freeBusyDirName); filename += "/"; filename += from; filename += ".ifb"; QFile f(filename); kdDebug() << "acceptFreeBusy: filename" << filename << endl; freebusy->clearAttendees(); freebusy->setOrganizer(from); QString messageText = mFormat->createScheduleMessage(freebusy, Publish); if (!f.open(IO_ReadWrite)) { kdDebug() << "acceptFreeBusy: Can't open:" << filename << " for writing" << endl; return false; } QTextStream t(&f); t << messageText; f.close(); deleteTransaction(incidence); return true; } <commit_msg>minor fix<commit_after>/* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // $Id$ #include <qdir.h> #include <qfile.h> #include <qtextstream.h> #include <klocale.h> #include <kdebug.h> #include <kstandarddirs.h> #include "event.h" #include "freebusy.h" #include "icalformat.h" #include "calendar.h" #include "scheduler.h" using namespace KCal; ScheduleMessage::ScheduleMessage(IncidenceBase *incidence,int method,ScheduleMessage::Status status) { mIncidence = incidence; mMethod = method; mStatus = status; } QString ScheduleMessage::statusName(ScheduleMessage::Status status) { switch (status) { case PublishNew: return i18n("Publish"); case Obsolete: return i18n("Obsolete"); case RequestNew: return i18n("New Request"); case RequestUpdate: return i18n("Updated Request"); default: return i18n("Unknown Status: %1").arg(QString::number(status)); } } Scheduler::Scheduler(Calendar *calendar) { mCalendar = calendar; mFormat = mCalendar->iCalFormat(); } Scheduler::~Scheduler() { } bool Scheduler::acceptTransaction(IncidenceBase *incidence,Method method,ScheduleMessage::Status status) { kdDebug() << "Scheduler::acceptTransaction " << endl; switch (method) { case Publish: return acceptPublish(incidence, status, method); case Request: return acceptRequest(incidence, status); case Add: return acceptAdd(incidence, status); case Cancel: return acceptCancel(incidence, status); case Declinecounter: return acceptDeclineCounter(incidence, status); case Reply: return acceptReply(incidence, status, method); case Refresh: return acceptRefresh(incidence, status); case Counter: return acceptCounter(incidence, status); default: deleteTransaction(incidence); return false; } deleteTransaction(incidence); return false; } QString Scheduler::methodName(Method method) { switch (method) { case Publish: return i18n("Publish"); case Request: return i18n("Request"); case Refresh: return i18n("Refresh"); case Cancel: return i18n("Cancel"); case Add: return i18n("Add"); case Reply: return i18n("Reply"); case Counter: return i18n("Counter"); case Declinecounter: return i18n("Decline Counter"); default: return i18n("Unknown"); } } bool Scheduler::deleteTransaction(IncidenceBase *) { return true; } bool Scheduler::acceptPublish(IncidenceBase *incidence,ScheduleMessage::Status status, Method method) { if(incidence->type()=="FreeBusy") { return acceptFreeBusy(incidence, method); } switch (status) { case ScheduleMessage::PublishNew: if (!mCalendar->getEvent(incidence->uid())) { Incidence *inc = static_cast<Incidence *>(incidence); mCalendar->addIncidence(inc); deleteTransaction(incidence); } return true; case ScheduleMessage::Obsolete: return true; default: deleteTransaction(incidence); return false; } deleteTransaction(incidence); return false; } bool Scheduler::acceptRequest(IncidenceBase *incidence,ScheduleMessage::Status status) { Incidence *inc = static_cast<Incidence *>(incidence); switch (status) { case ScheduleMessage::Obsolete: return true; case ScheduleMessage::RequestNew: mCalendar->addIncidence(inc); deleteTransaction(incidence); return true; case ScheduleMessage::RequestUpdate: Event *even; even = mCalendar->getEvent(incidence->uid()); if (even) { mCalendar->deleteEvent(even); } mCalendar->addIncidence(inc); deleteTransaction(incidence); return true; default: return false; } deleteTransaction(incidence); return false; } bool Scheduler::acceptAdd(IncidenceBase *incidence,ScheduleMessage::Status status) { deleteTransaction(incidence); return false; } bool Scheduler::acceptCancel(IncidenceBase *incidence,ScheduleMessage::Status status) { bool ret = false; //get event in calendar QPtrList<Event> eventList; eventList=mCalendar->getEvents(incidence->dtStart().date(),incidence->dtStart().date(),false); Event *ev; for ( ev = eventList.first(); ev; ev = eventList.next() ) { if (ev->uid()==incidence->uid()) { //get matching attendee in calendar kdDebug() << "Scheduler::acceptTransaction match found!" << endl; mCalendar->deleteEvent(ev); ret = true; } } deleteTransaction(incidence); return ret; } bool Scheduler::acceptDeclineCounter(IncidenceBase *incidence,ScheduleMessage::Status status) { deleteTransaction(incidence); return false; } //bool Scheduler::acceptFreeBusy(Incidence *incidence,ScheduleMessage::Status status) //{ // deleteTransaction(incidence); // return false; //} bool Scheduler::acceptReply(IncidenceBase *incidence,ScheduleMessage::Status status, Method method) { if(incidence->type()=="FreeBusy") { return acceptFreeBusy(incidence, method); } bool ret = false; Event *ev = mCalendar->getEvent(incidence->uid()); if (ev) { //get matching attendee in calendar kdDebug(5800) << "Scheduler::acceptTransaction match found!" << endl; QPtrList<Attendee> attendeesIn = incidence->attendees(); QPtrList<Attendee> attendeesEv = ev->attendees(); Attendee *attIn; Attendee *attEv; for ( attIn = attendeesIn.first(); attIn; attIn = attendeesIn.next() ) { for ( attEv = attendeesEv.first(); attEv; attEv = attendeesEv.next() ) { if (attIn->email()==attEv->email()) { //update attendee-info kdDebug(5800) << "Scheduler::acceptTransaction update attendee" << endl; //attEv->setRole(attIn->role()); attEv->setStatus(attIn->status()); //attEv->setRSVP(attIn->RSVP()); ev->setRevision(ev->revision()+1); ret = true; } } } } if (ret) deleteTransaction(incidence); return ret; } bool Scheduler::acceptRefresh(IncidenceBase *incidence,ScheduleMessage::Status status) { // handled in korganizer's IncomingDialog deleteTransaction(incidence); return false; } bool Scheduler::acceptCounter(IncidenceBase *incidence,ScheduleMessage::Status status) { deleteTransaction(incidence); return false; } bool Scheduler::acceptFreeBusy(IncidenceBase *incidence, Method method) { FreeBusy *freebusy = static_cast<FreeBusy *>(incidence); QString freeBusyDirName = locateLocal("appdata","freebusy"); kdDebug() << "acceptFreeBusy:: freeBusyDirName: " << freeBusyDirName << endl; QString from; if(method == Scheduler::Publish) { from = freebusy->organizer(); } if((method == Scheduler::Reply) && (freebusy->attendeeCount() == 1)) { Attendee *attendee = freebusy->attendees().first(); from = attendee->email(); } QDir freeBusyDir(freeBusyDirName); if (!freeBusyDir.exists()) { kdDebug() << "Directory " << freeBusyDirName << " does not exist!" << endl; kdDebug() << "Creating directory: " << freeBusyDirName << endl; if(!freeBusyDir.mkdir(freeBusyDirName, TRUE)) { kdDebug() << "Could not create directory: " << freeBusyDirName << endl; return false; } } QString filename(freeBusyDirName); filename += "/"; filename += from; filename += ".ifb"; QFile f(filename); kdDebug() << "acceptFreeBusy: filename" << filename << endl; freebusy->clearAttendees(); freebusy->setOrganizer(from); QString messageText = mFormat->createScheduleMessage(freebusy, Publish); if (!f.open(IO_ReadWrite)) { kdDebug() << "acceptFreeBusy: Can't open:" << filename << " for writing" << endl; return false; } QTextStream t(&f); t << messageText; f.close(); deleteTransaction(incidence); return true; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cellkeytranslator.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2007-07-24 09:23:06 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "cellkeytranslator.hxx" #include "rtl/ustring.hxx" using ::com::sun::star::lang::Locale; using ::std::list; using ::std::hash_map; using ::rtl::OUString; enum LocaleMatch { LOCALE_MATCH_NONE = 0, LOCALE_MATCH_LANG, LOCALE_MATCH_LANG_COUNTRY, LOCALE_MATCH_ALL }; static LocaleMatch lclLocaleCompare(const Locale& rLocale1, const Locale& rLocale2) { LocaleMatch eMatchLevel = LOCALE_MATCH_NONE; if ( !rLocale1.Language.compareTo(rLocale1.Language) ) eMatchLevel = LOCALE_MATCH_LANG; else return eMatchLevel; if ( !rLocale1.Country.compareTo(rLocale2.Country) ) eMatchLevel = LOCALE_MATCH_LANG_COUNTRY; else return eMatchLevel; if ( !rLocale1.Variant.compareTo(rLocale2.Variant) ) eMatchLevel = LOCALE_MATCH_ALL; return eMatchLevel; } ScCellKeyword::ScCellKeyword(const sal_Char* pName, OpCode eOpCode, const Locale& rLocale) : mpName(pName), meOpCode(eOpCode), mrLocale(rLocale) { } ::std::auto_ptr<ScCellKeywordTranslator> ScCellKeywordTranslator::spInstance(NULL); static void lclMatchKeyword(String& rName, const ScCellKeywordHashMap& aMap, OpCode eOpCode = ocNone, const Locale* pLocale = NULL) { ScCellKeywordHashMap::const_iterator itrEnd = aMap.end(); ScCellKeywordHashMap::const_iterator itr = aMap.find(rName); if ( itr == itrEnd || itr->second.empty() ) // No candidate strings exist. Bail out. return; if ( eOpCode == ocNone && !pLocale ) { // Since no locale nor opcode matching is needed, simply return // the first item on the list. rName = String::CreateFromAscii( itr->second.front().mpName ); return; } const sal_Char* aBestMatchName = itr->second.front().mpName; LocaleMatch eLocaleMatchLevel = LOCALE_MATCH_NONE; bool bOpCodeMatched = false; list<ScCellKeyword>::const_iterator itrListEnd = itr->second.end(); list<ScCellKeyword>::const_iterator itrList = itr->second.begin(); for ( ; itrList != itrListEnd; ++itrList ) { if ( eOpCode != ocNone && pLocale ) { if ( itrList->meOpCode == eOpCode ) { LocaleMatch eLevel = lclLocaleCompare(itrList->mrLocale, *pLocale); if ( eLevel == LOCALE_MATCH_ALL ) { // Name with matching opcode and locale found. rName = String::CreateFromAscii( itrList->mpName ); return; } else if ( eLevel > eLocaleMatchLevel ) { // Name with a better matching locale. eLocaleMatchLevel = eLevel; aBestMatchName = itrList->mpName; } else if ( !bOpCodeMatched ) // At least the opcode matches. aBestMatchName = itrList->mpName; bOpCodeMatched = true; } } else if ( eOpCode != ocNone && !pLocale ) { if ( itrList->meOpCode == eOpCode ) { // Name with a matching opcode preferred. rName = String::CreateFromAscii( itrList->mpName ); return; } } else if ( !eOpCode && pLocale ) { LocaleMatch eLevel = lclLocaleCompare(itrList->mrLocale, *pLocale); if ( eLevel == LOCALE_MATCH_ALL ) { // Name with matching locale preferred. rName = String::CreateFromAscii( itrList->mpName ); return; } else if ( eLevel > eLocaleMatchLevel ) { // Name with a better matching locale. eLocaleMatchLevel = eLevel; aBestMatchName = itrList->mpName; } } } // No preferred strings found. Return the best matching name. rName = String::CreateFromAscii(aBestMatchName); } void ScCellKeywordTranslator::transKeyword(String& rName, const Locale* pLocale, OpCode eOpCode) { if ( !spInstance.get() ) spInstance.reset( new ScCellKeywordTranslator ); lclMatchKeyword(rName, spInstance->maStringNameMap, eOpCode, pLocale); } ScCellKeywordTranslator::ScCellKeywordTranslator() { init(); } ScCellKeywordTranslator::~ScCellKeywordTranslator() { } struct TransItem { const sal_Char* from; const sal_Char* to; OpCode func; }; void ScCellKeywordTranslator::init() { // 1. Keywords must be all uppercase. // 2. Mapping must be <localized string name> to <English string name>. // French language locale. static const Locale aFr(OUString::createFromAscii("fr"), OUString(), OUString()); static const TransItem pFr[] = { // CELL {"ADRESSE", "ADDRESS", ocCell}, {"COLONNE", "COL", ocCell}, {"CONTENU", "CONTENTS", ocCell}, {"COULEUR", "COLOR", ocCell}, {"LARGEUR", "WIDTH", ocCell}, {"LIGNE", "ROW", ocCell}, {"NOMFICHIER", "FILENAME", ocCell}, {"PREFIXE", "PREFIX", ocCell}, {"PROTEGE", "PROTECT", ocCell}, // INFO {"NBFICH", "NUMFILE", ocInfo}, {"RECALCUL", "RECALC", ocInfo}, {"SYSTEXPL", "SYSTEM", ocInfo}, {"VERSION", "RELEASE", ocInfo}, {"VERSIONSE", "OSVERSION", ocInfo}, {NULL, NULL, ocNone} }; addToMap(pFr, aFr); } void ScCellKeywordTranslator::addToMap(const String& rKey, const sal_Char* pName, const Locale& rLocale, OpCode eOpCode) { ScCellKeyword aKeyItem( pName, eOpCode, rLocale ); ScCellKeywordHashMap::iterator itrEnd = maStringNameMap.end(); ScCellKeywordHashMap::iterator itr = maStringNameMap.find(rKey); if ( itr == itrEnd ) { // New keyword. list<ScCellKeyword> aList; aList.push_back(aKeyItem); maStringNameMap.insert( ScCellKeywordHashMap::value_type(rKey, aList) ); } else itr->second.push_back(aKeyItem); } void ScCellKeywordTranslator::addToMap(const TransItem* pItems, const Locale& rLocale) { for (sal_uInt16 i = 0; pItems[i].from != NULL; ++i) addToMap(String::CreateFromAscii(pItems[i].from), pItems[i].to, rLocale, pItems[i].func); } <commit_msg>INTEGRATION: CWS celltrans02 (1.2.50); FILE MERGED 2007/09/06 17:50:33 kohei 1.2.50.5: minor tweak in the in-line comment. 2007/09/06 16:36:52 kohei 1.2.50.4: Added more in-line comment about the keyword file. 2007/09/06 16:23:30 kohei 1.2.50.3: use transliteration object to upcase the strings, instead of character classification object. 2007/09/06 03:19:23 kohei 1.2.50.2: added mutex guard to protect statically instantiated variables. 2007/09/06 03:02:22 kohei 1.2.50.1: added Hungarian keywords & made changes so that the keywords are stored in unicode instead of in ascii.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cellkeytranslator.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2007-11-01 14:21: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 * ************************************************************************/ #include "cellkeytranslator.hxx" #include "comphelper/processfactory.hxx" #include "i18npool/mslangid.hxx" #include "i18npool/lang.h" #include "rtl/ustring.hxx" #include <com/sun/star/i18n/TransliterationModules.hpp> using ::com::sun::star::lang::Locale; using ::com::sun::star::uno::Sequence; using ::std::list; using ::std::hash_map; using ::rtl::OUString; using namespace ::com::sun::star; enum LocaleMatch { LOCALE_MATCH_NONE = 0, LOCALE_MATCH_LANG, LOCALE_MATCH_LANG_COUNTRY, LOCALE_MATCH_ALL }; static LocaleMatch lclLocaleCompare(const Locale& rLocale1, const Locale& rLocale2) { LocaleMatch eMatchLevel = LOCALE_MATCH_NONE; if ( !rLocale1.Language.compareTo(rLocale1.Language) ) eMatchLevel = LOCALE_MATCH_LANG; else return eMatchLevel; if ( !rLocale1.Country.compareTo(rLocale2.Country) ) eMatchLevel = LOCALE_MATCH_LANG_COUNTRY; else return eMatchLevel; if ( !rLocale1.Variant.compareTo(rLocale2.Variant) ) eMatchLevel = LOCALE_MATCH_ALL; return eMatchLevel; } ScCellKeyword::ScCellKeyword(const sal_Char* pName, OpCode eOpCode, const Locale& rLocale) : mpName(pName), meOpCode(eOpCode), mrLocale(rLocale) { } ::std::auto_ptr<ScCellKeywordTranslator> ScCellKeywordTranslator::spInstance(NULL); static void lclMatchKeyword(String& rName, const ScCellKeywordHashMap& aMap, OpCode eOpCode = ocNone, const Locale* pLocale = NULL) { ScCellKeywordHashMap::const_iterator itrEnd = aMap.end(); ScCellKeywordHashMap::const_iterator itr = aMap.find(rName); if ( itr == itrEnd || itr->second.empty() ) // No candidate strings exist. Bail out. return; if ( eOpCode == ocNone && !pLocale ) { // Since no locale nor opcode matching is needed, simply return // the first item on the list. rName = String::CreateFromAscii( itr->second.front().mpName ); return; } const sal_Char* aBestMatchName = itr->second.front().mpName; LocaleMatch eLocaleMatchLevel = LOCALE_MATCH_NONE; bool bOpCodeMatched = false; list<ScCellKeyword>::const_iterator itrListEnd = itr->second.end(); list<ScCellKeyword>::const_iterator itrList = itr->second.begin(); for ( ; itrList != itrListEnd; ++itrList ) { if ( eOpCode != ocNone && pLocale ) { if ( itrList->meOpCode == eOpCode ) { LocaleMatch eLevel = lclLocaleCompare(itrList->mrLocale, *pLocale); if ( eLevel == LOCALE_MATCH_ALL ) { // Name with matching opcode and locale found. rName = String::CreateFromAscii( itrList->mpName ); return; } else if ( eLevel > eLocaleMatchLevel ) { // Name with a better matching locale. eLocaleMatchLevel = eLevel; aBestMatchName = itrList->mpName; } else if ( !bOpCodeMatched ) // At least the opcode matches. aBestMatchName = itrList->mpName; bOpCodeMatched = true; } } else if ( eOpCode != ocNone && !pLocale ) { if ( itrList->meOpCode == eOpCode ) { // Name with a matching opcode preferred. rName = String::CreateFromAscii( itrList->mpName ); return; } } else if ( !eOpCode && pLocale ) { LocaleMatch eLevel = lclLocaleCompare(itrList->mrLocale, *pLocale); if ( eLevel == LOCALE_MATCH_ALL ) { // Name with matching locale preferred. rName = String::CreateFromAscii( itrList->mpName ); return; } else if ( eLevel > eLocaleMatchLevel ) { // Name with a better matching locale. eLocaleMatchLevel = eLevel; aBestMatchName = itrList->mpName; } } } // No preferred strings found. Return the best matching name. rName = String::CreateFromAscii(aBestMatchName); } void ScCellKeywordTranslator::transKeyword(String& rName, const Locale* pLocale, OpCode eOpCode) { if ( !spInstance.get() ) spInstance.reset( new ScCellKeywordTranslator ); LanguageType eLang = pLocale ? MsLangId::convertLocaleToLanguageWithFallback(*pLocale) : LANGUAGE_SYSTEM; Sequence<sal_Int32> aOffsets; rName = spInstance->maTransWrapper.transliterate(rName, eLang, 0, rName.Len(), &aOffsets); lclMatchKeyword(rName, spInstance->maStringNameMap, eOpCode, pLocale); } ScCellKeywordTranslator::ScCellKeywordTranslator() : maTransWrapper( ::comphelper::getProcessServiceFactory(), i18n::TransliterationModules_LOWERCASE_UPPERCASE ) { init(); } ScCellKeywordTranslator::~ScCellKeywordTranslator() { } struct TransItem { const sal_Unicode* from; const sal_Char* to; OpCode func; }; void ScCellKeywordTranslator::init() { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); // The file below has been autogenerated by sc/workben/celltrans/parse.py. // To add new locale keywords, edit sc/workben/celltrans/keywords_utf16.txt // and re-run the parse.py script. // // All keywords must be uppercase, and the mapping must be from the // localized keyword to the English keyword. // // Make sure that the original keyword file (keywords_utf16.txt) is // encoded in UCS-2/UTF-16! #include "cellkeywords.inl" } void ScCellKeywordTranslator::addToMap(const String& rKey, const sal_Char* pName, const Locale& rLocale, OpCode eOpCode) { ScCellKeyword aKeyItem( pName, eOpCode, rLocale ); ScCellKeywordHashMap::iterator itrEnd = maStringNameMap.end(); ScCellKeywordHashMap::iterator itr = maStringNameMap.find(rKey); if ( itr == itrEnd ) { // New keyword. list<ScCellKeyword> aList; aList.push_back(aKeyItem); maStringNameMap.insert( ScCellKeywordHashMap::value_type(rKey, aList) ); } else itr->second.push_back(aKeyItem); } void ScCellKeywordTranslator::addToMap(const TransItem* pItems, const Locale& rLocale) { for (sal_uInt16 i = 0; pItems[i].from != NULL; ++i) addToMap(String(pItems[i].from), pItems[i].to, rLocale, pItems[i].func); } <|endoftext|>
<commit_before><commit_msg>fdo #50343: Fixed crash on xlsx import of file with array formula<commit_after><|endoftext|>
<commit_before><commit_msg>improve conditional formatting height calculations.<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "condformatmgr.hxx" #include "scresid.hxx" #include "globstr.hrc" #include "condformatdlg.hxx" #include <vcl/msgbox.hxx> #include "document.hxx" ScCondFormatManagerWindow::ScCondFormatManagerWindow(SvSimpleTableContainer& rParent, ScDocument* pDoc, ScConditionalFormatList* pFormatList) : SvSimpleTable(rParent, WB_HSCROLL | WB_SORT | WB_TABSTOP) , mpDoc(pDoc) , mpFormatList(pFormatList) { OUString aConditionStr(ScGlobal::GetRscString(STR_HEADER_COND)); OUString aRangeStr(ScGlobal::GetRscString(STR_HEADER_RANGE)); OUStringBuffer sHeader; sHeader.append(aRangeStr).append("\t").append(aConditionStr); InsertHeaderEntry(sHeader.makeStringAndClear(), HEADERBAR_APPEND, HIB_LEFT | HIB_VCENTER); setColSizes(); Init(); Show(); SetSelectionMode(MULTIPLE_SELECTION); } OUString ScCondFormatManagerWindow::createEntryString(const ScConditionalFormat& rFormat) { ScRangeList aRange = rFormat.GetRange(); OUString aStr; aRange.Format(aStr, SCA_VALID, mpDoc, mpDoc->GetAddressConvention()); aStr += "\t"; aStr += ScCondFormatHelper::GetExpression(rFormat, aRange.GetTopLeftCorner()); return aStr; } void ScCondFormatManagerWindow::Init() { SetUpdateMode(false); for(ScConditionalFormatList::iterator itr = mpFormatList->begin(); itr != mpFormatList->end(); ++itr) { SvTreeListEntry* pEntry = InsertEntryToColumn( createEntryString(*itr), TREELIST_APPEND, 0xffff ); maMapLBoxEntryToCondIndex.insert(std::pair<SvTreeListEntry*,sal_Int32>(pEntry,itr->GetKey())); } SetUpdateMode(true); if (mpFormatList->size()) SelectRow(0); } void ScCondFormatManagerWindow::Resize() { SvSimpleTable::Resize(); if (GetParentDialog()->isCalculatingInitialLayoutSize()) setColSizes(); } void ScCondFormatManagerWindow::DeleteSelection() { if(GetSelectionCount()) { for(SvTreeListEntry* pEntry = FirstSelected(); pEntry != NULL; pEntry = NextSelected(pEntry)) { sal_Int32 nIndex = maMapLBoxEntryToCondIndex.find(pEntry)->second; mpFormatList->erase(nIndex); } RemoveSelection(); } } ScConditionalFormat* ScCondFormatManagerWindow::GetSelection() { SvTreeListEntry* pEntry = FirstSelected(); if(!pEntry) return NULL; sal_Int32 nIndex = maMapLBoxEntryToCondIndex.find(pEntry)->second; return mpFormatList->GetFormat(nIndex); } void ScCondFormatManagerWindow::Update() { Clear(); maMapLBoxEntryToCondIndex.clear(); Init(); } void ScCondFormatManagerWindow::setColSizes() { HeaderBar &rBar = GetTheHeaderBar(); if (rBar.GetItemCount() < 2) return; long aStaticTabs[]= { 2, 0, 0 }; aStaticTabs[2] = rBar.GetSizePixel().Width() / 2; SvSimpleTable::SetTabs(aStaticTabs, MAP_PIXEL); } ScCondFormatManagerDlg::ScCondFormatManagerDlg(vcl::Window* pParent, ScDocument* pDoc, const ScConditionalFormatList* pFormatList, const ScAddress& rPos): ModalDialog(pParent, "CondFormatManager", "modules/scalc/ui/condformatmanager.ui"), mpFormatList( pFormatList ? new ScConditionalFormatList(*pFormatList) : NULL), mpDoc(pDoc), maPos(rPos), mbModified(false) { SvSimpleTableContainer *pContainer = get<SvSimpleTableContainer>("CONTAINER"); Size aSize(LogicToPixel(Size(290, 220), MAP_APPFONT)); pContainer->set_width_request(aSize.Width()); pContainer->set_height_request(aSize.Height()); m_pCtrlManager = new ScCondFormatManagerWindow(*pContainer, mpDoc, mpFormatList); get(m_pBtnAdd, "add"); get(m_pBtnRemove, "remove"); get(m_pBtnEdit, "edit"); m_pBtnRemove->SetClickHdl(LINK(this, ScCondFormatManagerDlg, RemoveBtnHdl)); m_pBtnEdit->SetClickHdl(LINK(this, ScCondFormatManagerDlg, EditBtnHdl)); m_pBtnAdd->SetClickHdl(LINK(this, ScCondFormatManagerDlg, AddBtnHdl)); m_pCtrlManager->SetDoubleClickHdl(LINK(this, ScCondFormatManagerDlg, EditBtnHdl)); } ScCondFormatManagerDlg::~ScCondFormatManagerDlg() { delete m_pCtrlManager; delete mpFormatList; } bool ScCondFormatManagerDlg::IsInRefMode() const { return true; } ScConditionalFormatList* ScCondFormatManagerDlg::GetConditionalFormatList() { ScConditionalFormatList* pList = mpFormatList; mpFormatList = NULL; return pList; } IMPL_LINK_NOARG(ScCondFormatManagerDlg, RemoveBtnHdl) { m_pCtrlManager->DeleteSelection(); mbModified = true; return 0; } IMPL_LINK_NOARG(ScCondFormatManagerDlg, EditBtnHdl) { ScConditionalFormat* pFormat = m_pCtrlManager->GetSelection(); if(!pFormat) return 0; sal_uInt16 nId = 1; ScModule* pScMod = SC_MOD(); pScMod->SetRefDialog( nId, true ); boost::scoped_ptr<ScCondFormatDlg> pDlg(new ScCondFormatDlg(this, mpDoc, pFormat, pFormat->GetRange(), pFormat->GetRange().GetTopLeftCorner(), condformat::dialog::NONE)); Show(false, 0); if(pDlg->Execute() == RET_OK) { sal_Int32 nKey = pFormat->GetKey(); mpFormatList->erase(nKey); ScConditionalFormat* pNewFormat = pDlg->GetConditionalFormat(); if(pNewFormat) { pNewFormat->SetKey(nKey); mpFormatList->InsertNew(pNewFormat); } m_pCtrlManager->Update(); mbModified = true; } Show(true, 0); pScMod->SetRefDialog( nId, false ); return 0; } namespace { sal_uInt32 FindKey(ScConditionalFormatList* pFormatList) { sal_uInt32 nKey = 0; for(ScConditionalFormatList::const_iterator itr = pFormatList->begin(), itrEnd = pFormatList->end(); itr != itrEnd; ++itr) { if(itr->GetKey() > nKey) nKey = itr->GetKey(); } return nKey + 1; } } IMPL_LINK_NOARG(ScCondFormatManagerDlg, AddBtnHdl) { sal_uInt16 nId = 1; ScModule* pScMod = SC_MOD(); pScMod->SetRefDialog( nId, true ); boost::scoped_ptr<ScCondFormatDlg> pDlg(new ScCondFormatDlg(this, mpDoc, NULL, ScRangeList(), maPos, condformat::dialog::CONDITION)); Show(false, 0); if(pDlg->Execute() == RET_OK) { ScConditionalFormat* pNewFormat = pDlg->GetConditionalFormat(); if(pNewFormat) { mpFormatList->InsertNew(pNewFormat); pNewFormat->SetKey(FindKey(mpFormatList)); m_pCtrlManager->Update(); mbModified = true; } } Show(true, 0); pScMod->SetRefDialog( nId, false ); return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#1242431 Explicit null dereferenced<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "condformatmgr.hxx" #include "scresid.hxx" #include "globstr.hrc" #include "condformatdlg.hxx" #include <vcl/msgbox.hxx> #include "document.hxx" ScCondFormatManagerWindow::ScCondFormatManagerWindow(SvSimpleTableContainer& rParent, ScDocument* pDoc, ScConditionalFormatList* pFormatList) : SvSimpleTable(rParent, WB_HSCROLL | WB_SORT | WB_TABSTOP) , mpDoc(pDoc) , mpFormatList(pFormatList) { OUString aConditionStr(ScGlobal::GetRscString(STR_HEADER_COND)); OUString aRangeStr(ScGlobal::GetRscString(STR_HEADER_RANGE)); OUStringBuffer sHeader; sHeader.append(aRangeStr).append("\t").append(aConditionStr); InsertHeaderEntry(sHeader.makeStringAndClear(), HEADERBAR_APPEND, HIB_LEFT | HIB_VCENTER); setColSizes(); Init(); Show(); SetSelectionMode(MULTIPLE_SELECTION); } OUString ScCondFormatManagerWindow::createEntryString(const ScConditionalFormat& rFormat) { ScRangeList aRange = rFormat.GetRange(); OUString aStr; aRange.Format(aStr, SCA_VALID, mpDoc, mpDoc->GetAddressConvention()); aStr += "\t"; aStr += ScCondFormatHelper::GetExpression(rFormat, aRange.GetTopLeftCorner()); return aStr; } void ScCondFormatManagerWindow::Init() { SetUpdateMode(false); if (mpFormatList) { for(ScConditionalFormatList::iterator itr = mpFormatList->begin(); itr != mpFormatList->end(); ++itr) { SvTreeListEntry* pEntry = InsertEntryToColumn( createEntryString(*itr), TREELIST_APPEND, 0xffff ); maMapLBoxEntryToCondIndex.insert(std::pair<SvTreeListEntry*,sal_Int32>(pEntry,itr->GetKey())); } } SetUpdateMode(true); if (mpFormatList && mpFormatList->size()) SelectRow(0); } void ScCondFormatManagerWindow::Resize() { SvSimpleTable::Resize(); if (GetParentDialog()->isCalculatingInitialLayoutSize()) setColSizes(); } void ScCondFormatManagerWindow::DeleteSelection() { if(GetSelectionCount()) { for(SvTreeListEntry* pEntry = FirstSelected(); pEntry != NULL; pEntry = NextSelected(pEntry)) { sal_Int32 nIndex = maMapLBoxEntryToCondIndex.find(pEntry)->second; mpFormatList->erase(nIndex); } RemoveSelection(); } } ScConditionalFormat* ScCondFormatManagerWindow::GetSelection() { SvTreeListEntry* pEntry = FirstSelected(); if(!pEntry) return NULL; sal_Int32 nIndex = maMapLBoxEntryToCondIndex.find(pEntry)->second; return mpFormatList->GetFormat(nIndex); } void ScCondFormatManagerWindow::Update() { Clear(); maMapLBoxEntryToCondIndex.clear(); Init(); } void ScCondFormatManagerWindow::setColSizes() { HeaderBar &rBar = GetTheHeaderBar(); if (rBar.GetItemCount() < 2) return; long aStaticTabs[]= { 2, 0, 0 }; aStaticTabs[2] = rBar.GetSizePixel().Width() / 2; SvSimpleTable::SetTabs(aStaticTabs, MAP_PIXEL); } ScCondFormatManagerDlg::ScCondFormatManagerDlg(vcl::Window* pParent, ScDocument* pDoc, const ScConditionalFormatList* pFormatList, const ScAddress& rPos): ModalDialog(pParent, "CondFormatManager", "modules/scalc/ui/condformatmanager.ui"), mpFormatList( pFormatList ? new ScConditionalFormatList(*pFormatList) : NULL), mpDoc(pDoc), maPos(rPos), mbModified(false) { SvSimpleTableContainer *pContainer = get<SvSimpleTableContainer>("CONTAINER"); Size aSize(LogicToPixel(Size(290, 220), MAP_APPFONT)); pContainer->set_width_request(aSize.Width()); pContainer->set_height_request(aSize.Height()); m_pCtrlManager = new ScCondFormatManagerWindow(*pContainer, mpDoc, mpFormatList); get(m_pBtnAdd, "add"); get(m_pBtnRemove, "remove"); get(m_pBtnEdit, "edit"); m_pBtnRemove->SetClickHdl(LINK(this, ScCondFormatManagerDlg, RemoveBtnHdl)); m_pBtnEdit->SetClickHdl(LINK(this, ScCondFormatManagerDlg, EditBtnHdl)); m_pBtnAdd->SetClickHdl(LINK(this, ScCondFormatManagerDlg, AddBtnHdl)); m_pCtrlManager->SetDoubleClickHdl(LINK(this, ScCondFormatManagerDlg, EditBtnHdl)); } ScCondFormatManagerDlg::~ScCondFormatManagerDlg() { delete m_pCtrlManager; delete mpFormatList; } bool ScCondFormatManagerDlg::IsInRefMode() const { return true; } ScConditionalFormatList* ScCondFormatManagerDlg::GetConditionalFormatList() { ScConditionalFormatList* pList = mpFormatList; mpFormatList = NULL; return pList; } IMPL_LINK_NOARG(ScCondFormatManagerDlg, RemoveBtnHdl) { m_pCtrlManager->DeleteSelection(); mbModified = true; return 0; } IMPL_LINK_NOARG(ScCondFormatManagerDlg, EditBtnHdl) { ScConditionalFormat* pFormat = m_pCtrlManager->GetSelection(); if(!pFormat) return 0; sal_uInt16 nId = 1; ScModule* pScMod = SC_MOD(); pScMod->SetRefDialog( nId, true ); boost::scoped_ptr<ScCondFormatDlg> pDlg(new ScCondFormatDlg(this, mpDoc, pFormat, pFormat->GetRange(), pFormat->GetRange().GetTopLeftCorner(), condformat::dialog::NONE)); Show(false, 0); if(pDlg->Execute() == RET_OK) { sal_Int32 nKey = pFormat->GetKey(); mpFormatList->erase(nKey); ScConditionalFormat* pNewFormat = pDlg->GetConditionalFormat(); if(pNewFormat) { pNewFormat->SetKey(nKey); mpFormatList->InsertNew(pNewFormat); } m_pCtrlManager->Update(); mbModified = true; } Show(true, 0); pScMod->SetRefDialog( nId, false ); return 0; } namespace { sal_uInt32 FindKey(ScConditionalFormatList* pFormatList) { sal_uInt32 nKey = 0; for(ScConditionalFormatList::const_iterator itr = pFormatList->begin(), itrEnd = pFormatList->end(); itr != itrEnd; ++itr) { if(itr->GetKey() > nKey) nKey = itr->GetKey(); } return nKey + 1; } } IMPL_LINK_NOARG(ScCondFormatManagerDlg, AddBtnHdl) { sal_uInt16 nId = 1; ScModule* pScMod = SC_MOD(); pScMod->SetRefDialog( nId, true ); boost::scoped_ptr<ScCondFormatDlg> pDlg(new ScCondFormatDlg(this, mpDoc, NULL, ScRangeList(), maPos, condformat::dialog::CONDITION)); Show(false, 0); if(pDlg->Execute() == RET_OK) { ScConditionalFormat* pNewFormat = pDlg->GetConditionalFormat(); if(pNewFormat) { mpFormatList->InsertNew(pNewFormat); pNewFormat->SetKey(FindKey(mpFormatList)); m_pCtrlManager->Update(); mbModified = true; } } Show(true, 0); pScMod->SetRefDialog( nId, false ); return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// SafeArryGUID.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <objbase.h> #include <string> #include<atlsafe.h> #include<iostream> using namespace std; string GuidToString(const GUID &guid) { char buf[64] = { 0 }; sprintf_s(buf, sizeof(buf), "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); return string(buf); } void Put1GuidInSafeArry() { GUID guid; CoCreateGuid(&guid); auto guidStri = GuidToString(guid); cout << guidStri << endl; //TODO... put the guid into safearry.. SAFEARRAY* p_safe_arry; SAFEARRAYBOUND safe_arry_bound[2] = { 0 }; auto guidsize = sizeof(GUID); safe_arry_bound[0].cElements = guidsize; safe_arry_bound[0].lLbound = 0; safe_arry_bound[1].cElements = guidsize; safe_arry_bound[1].lLbound = 0; p_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound); auto pnData = reinterpret_cast<char*>(p_safe_arry->pvData); memcpy_s(pnData, guidsize, guidStri.c_str(), guidsize); //TODO... //do something.. SafeArrayDestroy(p_safe_arry); } void Put2GuidInSafeArry() { GUID guid, guid2; CoCreateGuid(&guid); CoCreateGuid(&guid2); //TODO... put the guid into safearry.. SAFEARRAY* p_safe_arry; SAFEARRAYBOUND safe_arry_bound[2] = { 0 }; safe_arry_bound[0].cElements = 2; safe_arry_bound[0].lLbound = 0; safe_arry_bound[1].cElements = 16; safe_arry_bound[1].lLbound = 0; p_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound); auto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData); pnData[0] = guid; pnData[1] = guid2; //TODO... //do something.. //TODO... SafeArrayDestroy(p_safe_arry); } void Put1GuidInSafeArryByStack() { GUID guid; //TODO... put the guid into safearry.. SAFEARRAY* pArray = nullptr; auto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray); pArray->cbElements = sizeof(GUID); pArray->rgsabound[0].cElements = 1; pArray->rgsabound[0].lLbound = 16; pArray->pvData = &guid; pArray->fFeatures = FADF_AUTO; //_bstr_t bstr; } void CComSafeArrayGUID() { //CComSafeArray<GUID> comsafeguid(10); } void LearnSafeArray() { VARIANT var_Chunk; SAFEARRAY *psa; SAFEARRAYBOUND rgsabund[1]; rgsabund[0].cElements = sizeof(GUID); rgsabund[0].lLbound = 0; //psa = SafeArrayCreate(VT_UI1,1,rgsabund); var_Chunk.vt = VT_RECORD | VT_ARRAY; //var_Chunk.parray = } int _tmain(int argc, _TCHAR* argv[]) { Put1GuidInSafeArry(); Put2GuidInSafeArry(); Put1GuidInSafeArryByStack(); return 0; }<commit_msg>update test<commit_after>// SafeArryGUID.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <objbase.h> #include <string> //#include<atlsafe.h> //#include<atlcomcli.h> #include<iostream> using namespace std; string GuidToString(const GUID &guid) { char buf[64] = { 0 }; sprintf_s(buf, sizeof(buf), "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); return string(buf); } void Put1GuidInSafeArry() { GUID guid; CoCreateGuid(&guid); auto guidStri = GuidToString(guid); cout << guidStri << endl; //TODO... put the guid into safearry.. SAFEARRAY* p_safe_arry; SAFEARRAYBOUND safe_arry_bound[2] = { 0 }; auto guidsize = sizeof(GUID); safe_arry_bound[0].cElements = guidsize; safe_arry_bound[0].lLbound = 0; safe_arry_bound[1].cElements = guidsize; safe_arry_bound[1].lLbound = 0; p_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound); auto pnData = reinterpret_cast<char*>(p_safe_arry->pvData); memcpy_s(pnData, guidsize, guidStri.c_str(), guidsize); //TODO... //do something.. SafeArrayDestroy(p_safe_arry); } void Put2GuidInSafeArry() { GUID guid, guid2; CoCreateGuid(&guid); CoCreateGuid(&guid2); //TODO... put the guid into safearry.. SAFEARRAY* p_safe_arry; SAFEARRAYBOUND safe_arry_bound[2] = { 0 }; safe_arry_bound[0].cElements = 2; safe_arry_bound[0].lLbound = 0; safe_arry_bound[1].cElements = 16; safe_arry_bound[1].lLbound = 0; p_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound); auto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData); pnData[0] = guid; pnData[1] = guid2; //TODO... //do something.. //TODO... SafeArrayDestroy(p_safe_arry); } void Put1GuidInSafeArryByStack() { GUID guid; //TODO... put the guid into safearry.. SAFEARRAY* pArray = nullptr; auto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray); pArray->cbElements = sizeof(GUID); pArray->rgsabound[0].cElements = 1; pArray->rgsabound[0].lLbound = 16; pArray->pvData = &guid; pArray->fFeatures = FADF_AUTO; //_bstr_t bstr; } void CComSafeArrayGUID() { //CComSafeArray<GUID> comsafeguid(10); } void LearnSafeArray() { VARIANT var_Chunk; SAFEARRAY *psa; SAFEARRAYBOUND rgsabund[1]; rgsabund[0].cElements = sizeof(GUID); rgsabund[0].lLbound = 0; //psa = SafeArrayCreate(VT_UI1,1,rgsabund); var_Chunk.vt = VT_RECORD | VT_ARRAY; //var_Chunk.parray = } void TestSafeArry() { CComSafeArray<GUID> guid_Array; //GUID guid, guid2; //CoCreateGuid(&guid); //CoCreateGuid(&guid2); //guid_Array.Add(guid); //guid_Array.Add(guid2); //auto count = guid_Array.GetCount(); //auto demention = guid_Array.GetDimensions(); //auto upperbound = guid_Array.GetUpperBound(); //auto p_safeArry = &guid_Array; //GUID guid3; //CoCreateGuid(&guid3); //p_safeArry->SetAt(1, guid3); } int _tmain(int argc, _TCHAR* argv[]) { TestSafeArry(); Put1GuidInSafeArry(); Put2GuidInSafeArry(); Put1GuidInSafeArryByStack(); return 0; }<|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "../../vendor/catch/catch.hpp" #include "thread_utility.hpp" #include "version_monitor.hpp" TEST_CASE("initialize") { krbn::thread_utility::register_main_thread(); } TEST_CASE("version_monitor") { system("rm -rf target"); system("mkdir -p target/sub/"); system("echo 1.0.0 > target/sub/version"); { krbn::version_monitor version_monitor("target/sub/version"); std::string last_changed_version; version_monitor.changed.connect([&](auto&& version) { last_changed_version = version; }); version_monitor.start(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // Update version // ======================================== last_changed_version.clear(); system("echo 1.1.0 > target/sub/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.1.0"); // ======================================== // The callback is not called if the file contents is not changed. // ======================================== last_changed_version.clear(); system("touch target/sub/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // `manual_check` does not invoke callback if the version file is not actually changed. // ======================================== last_changed_version.clear(); version_monitor.manual_check(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // Self update is ignored by `kFSEventStreamCreateFlagIgnoreSelf` // ======================================== last_changed_version.clear(); { std::ofstream("target/sub/version") << "1.2.0"; } std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // `manual_check` // ======================================== last_changed_version.clear(); version_monitor.manual_check(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.2.0"); // ======================================== // Update version again // ======================================== last_changed_version.clear(); system("echo 1.3.0 > target/sub/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.3.0"); } } <commit_msg>update tests<commit_after>#define CATCH_CONFIG_MAIN #include "../../vendor/catch/catch.hpp" #include "thread_utility.hpp" #include "version_monitor.hpp" TEST_CASE("initialize") { krbn::thread_utility::register_main_thread(); } TEST_CASE("version_monitor") { system("rm -rf target"); system("mkdir -p target"); system("echo 1.0.0 > target/version"); { krbn::version_monitor version_monitor("target/version"); std::string last_changed_version; version_monitor.changed.connect([&](auto&& version) { last_changed_version = version; }); version_monitor.start(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // Update version // ======================================== last_changed_version.clear(); system("echo 1.1.0 > target/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.1.0"); // ======================================== // The callback is not called if the file contents is not changed. // ======================================== last_changed_version.clear(); system("touch target/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // `manual_check` does not invoke callback if the version file is not actually changed. // ======================================== last_changed_version.clear(); version_monitor.manual_check(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // Self update is ignored by `kFSEventStreamCreateFlagIgnoreSelf` // ======================================== last_changed_version.clear(); { std::ofstream("target/version") << "1.2.0"; } std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // `manual_check` // ======================================== last_changed_version.clear(); version_monitor.manual_check(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.2.0"); // ======================================== // Update version again // ======================================== last_changed_version.clear(); system("echo 1.3.0 > target/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.3.0"); } } <|endoftext|>
<commit_before>#include "config/Base.hh" #include "containers/PointCloud.hh" #include "distances/Euclidean.hh" #include "filtrations/Data.hh" #include "geometry/BruteForce.hh" #include "geometry/RipsSkeleton.hh" #include "tests/Base.hh" #include "persistentHomology/Calculation.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include <vector> using namespace aleph::geometry; using namespace aleph::topology; using namespace aleph; template <class T> void test() { ALEPH_TEST_BEGIN( "Point cloud loading" ); using PointCloud = PointCloud<T>; using Distance = aleph::distances::Euclidean<T>; PointCloud pointCloud = load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_colon_separated.txt" ) ); ALEPH_ASSERT_THROW( pointCloud.size() == 150 ); ALEPH_ASSERT_THROW( pointCloud.dimension() == 4); ALEPH_TEST_END(); ALEPH_TEST_BEGIN( "Rips skeleton calculation" ); using Wrapper = BruteForce<PointCloud, Distance>; using RipsSkeleton = RipsSkeleton<Wrapper>; Wrapper wrapper( pointCloud ); RipsSkeleton ripsSkeleton; auto K = ripsSkeleton( wrapper, 1.0 ); using Simplex = typename decltype(K)::ValueType; ALEPH_ASSERT_THROW( K.empty() == false ); ALEPH_ASSERT_THROW( std::count_if( K.begin(), K.end(), [] ( const Simplex& s ) { return s.dimension() == 1; } ) != 0 ); ALEPH_TEST_END(); ALEPH_TEST_BEGIN( "Zero-dimensional persistent homology calculation" ); K.sort( filtrations::Data<Simplex>() ); auto diagrams = calculatePersistenceDiagrams( K ); ALEPH_ASSERT_THROW( diagrams.empty() == false ); auto diagram1 = diagrams.front(); ALEPH_ASSERT_THROW( diagram1.empty() == false ); ALEPH_ASSERT_THROW( diagram1.size() == pointCloud.size() ); ALEPH_TEST_END(); } int main() { test<float> (); test<double>(); } <commit_msg>Extended test for connected component calculations<commit_after>#include "config/Base.hh" #include "containers/PointCloud.hh" #include "distances/Euclidean.hh" #include "filtrations/Data.hh" #include "geometry/BruteForce.hh" #include "geometry/RipsSkeleton.hh" #include "tests/Base.hh" #include "persistentHomology/Calculation.hh" #include "persistentHomology/ConnectedComponents.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include <vector> using namespace aleph::geometry; using namespace aleph::topology; using namespace aleph; template <class T> void test() { ALEPH_TEST_BEGIN( "Point cloud loading" ); using PointCloud = PointCloud<T>; using Distance = aleph::distances::Euclidean<T>; PointCloud pointCloud = load<T>( CMAKE_SOURCE_DIR + std::string( "/tests/input/Iris_colon_separated.txt" ) ); ALEPH_ASSERT_THROW( pointCloud.size() == 150 ); ALEPH_ASSERT_THROW( pointCloud.dimension() == 4); ALEPH_TEST_END(); ALEPH_TEST_BEGIN( "Rips skeleton calculation" ); using Wrapper = BruteForce<PointCloud, Distance>; using RipsSkeleton = RipsSkeleton<Wrapper>; Wrapper wrapper( pointCloud ); RipsSkeleton ripsSkeleton; auto K = ripsSkeleton( wrapper, 1.0 ); using Simplex = typename decltype(K)::ValueType; ALEPH_ASSERT_THROW( K.empty() == false ); ALEPH_ASSERT_THROW( std::count_if( K.begin(), K.end(), [] ( const Simplex& s ) { return s.dimension() == 1; } ) != 0 ); ALEPH_TEST_END(); ALEPH_TEST_BEGIN( "Zero-dimensional persistent homology calculation" ); K.sort( filtrations::Data<Simplex>() ); auto diagrams = calculatePersistenceDiagrams( K ); auto diagram2 = calculateZeroDimensionalPersistenceDiagram( K ); ALEPH_ASSERT_THROW( diagrams.empty() == false ); auto diagram1 = diagrams.front(); ALEPH_ASSERT_THROW( diagram1.empty() == false ); ALEPH_ASSERT_THROW( diagram1.size() == pointCloud.size() ); ALEPH_ASSERT_THROW( diagram2.empty() == false ); ALEPH_ASSERT_THROW( diagram1.size() == diagram2.size() ); ALEPH_TEST_END(); } int main() { test<float> (); test<double>(); } <|endoftext|>
<commit_before>#pragma once #include "iokit_utility.hpp" #include "logger.hpp" #include "types.hpp" #include <mach/mach_time.h> #include <optional> #include <pqrs/dispatcher.hpp> #include <pqrs/osx/iokit_hid_device.hpp> #include <pqrs/osx/iokit_hid_element.hpp> namespace krbn { class hid_keyboard_caps_lock_led_state_manager final : public pqrs::dispatcher::extra::dispatcher_client { public: hid_keyboard_caps_lock_led_state_manager(IOHIDDeviceRef device) : dispatcher_client(), device_(device), timer_(*this), started_(false) { if (device_) { pqrs::osx::iokit_hid_device hid_device(*device_); for (const auto& element : hid_device.make_elements()) { pqrs::osx::iokit_hid_element e(*element); if (e.get_usage_page() == pqrs::hid::usage_page::leds && e.get_usage() == pqrs::hid::usage::led::caps_lock && e.get_type() == pqrs::osx::iokit_hid_element_type::output) { logger::get_logger()->info( "caps lock is found on {0}", iokit_utility::make_device_name(*device_)); element_ = e; } } } } ~hid_keyboard_caps_lock_led_state_manager(void) { detach_from_dispatcher([this] { timer_.stop(); }); } void set_state(std::optional<led_state> value) { std::lock_guard<std::mutex> lock(state_mutex_); // Skip if new state is same as the last state in order to avoid a possibility of infinite calling of set_state. if (state_ == value) { return; } state_ = value; enqueue_to_dispatcher([this] { update_caps_lock_led(); }); } void async_start(void) { enqueue_to_dispatcher([this] { started_ = true; timer_.start( [this] { update_caps_lock_led(); }, std::chrono::milliseconds(3000)); }); } void async_stop(void) { enqueue_to_dispatcher([this] { started_ = false; timer_.stop(); }); } private: void update_caps_lock_led(void) const { if (!started_) { return; } // macOS 10.12 sometimes synchronize caps lock LED to internal keyboard caps lock state. // The behavior causes LED state mismatch because // the caps lock state of karabiner_grabber is independent from the hardware caps lock state. // Thus, we monitor the LED state and update it if needed. if (auto integer_value = make_integer_value()) { if (device_ && element_) { if (auto value = IOHIDValueCreateWithIntegerValue(kCFAllocatorDefault, element_.get_raw_ptr(), mach_absolute_time(), *integer_value)) { IOHIDDeviceSetValue(*device_, element_.get_raw_ptr(), value); CFRelease(value); } } } } std::optional<CFIndex> make_integer_value(void) const { std::lock_guard<std::mutex> lock(state_mutex_); if (state_ && element_) { if (*state_ == led_state::on) { return element_.get_logical_max(); } else { return element_.get_logical_min(); } } return std::nullopt; } pqrs::cf::cf_ptr<IOHIDDeviceRef> device_; pqrs::osx::iokit_hid_element element_; std::optional<led_state> state_; mutable std::mutex state_mutex_; pqrs::dispatcher::extra::timer timer_; bool started_; }; } // namespace krbn <commit_msg>Improve caps lock led handling<commit_after>#pragma once #include "iokit_utility.hpp" #include "logger.hpp" #include "types.hpp" #include <mach/mach_time.h> #include <optional> #include <pqrs/dispatcher.hpp> #include <pqrs/osx/iokit_hid_device.hpp> #include <pqrs/osx/iokit_hid_element.hpp> #include <pqrs/osx/iokit_return.hpp> namespace krbn { class hid_keyboard_caps_lock_led_state_manager final : public pqrs::dispatcher::extra::dispatcher_client { public: hid_keyboard_caps_lock_led_state_manager(IOHIDDeviceRef device) : dispatcher_client(), device_(device), timer_(*this), started_(false) { if (device_) { pqrs::osx::iokit_hid_device hid_device(*device_); for (const auto& element : hid_device.make_elements()) { pqrs::osx::iokit_hid_element e(*element); if (e.get_usage_page() == pqrs::hid::usage_page::leds && e.get_usage() == pqrs::hid::usage::led::caps_lock && e.get_type() == pqrs::osx::iokit_hid_element_type::output) { logger::get_logger()->info( "caps lock is found on {0}", iokit_utility::make_device_name(*device_)); element_ = e; } } } } ~hid_keyboard_caps_lock_led_state_manager(void) { detach_from_dispatcher([this] { timer_.stop(); }); } void set_state(std::optional<led_state> value) { std::lock_guard<std::mutex> lock(state_mutex_); // Skip if new state is same as the last state in order to avoid a possibility of infinite calling of set_state. if (state_ == value) { return; } state_ = value; enqueue_to_dispatcher([this] { update_caps_lock_led(); }); } void async_start(void) { enqueue_to_dispatcher([this] { started_ = true; timer_.start( [this] { update_caps_lock_led(); }, std::chrono::milliseconds(3000)); }); } void async_stop(void) { enqueue_to_dispatcher([this] { started_ = false; timer_.stop(); }); } private: void update_caps_lock_led(void) const { if (!started_) { return; } // macOS 10.12 sometimes synchronize caps lock LED to internal keyboard caps lock state. // The behavior causes LED state mismatch because // the caps lock state of karabiner_grabber is independent from the hardware caps lock state. // Thus, we monitor the LED state and update it if needed. if (auto integer_value = make_integer_value()) { if (device_ && element_) { if (auto value = IOHIDValueCreateWithIntegerValue(kCFAllocatorDefault, element_.get_raw_ptr(), mach_absolute_time(), *integer_value)) { // We have to use asynchronous method in order to prevent deadlock. IOHIDDeviceSetValueWithCallback( *device_, element_.get_raw_ptr(), value, 0.1, [](void* context, IOReturn result, void* sender, IOHIDValueRef value) { pqrs::osx::iokit_return r(result); if (!r) { logger::get_logger()->warn("update_caps_lock_led is failed: {0}", r); } }, nullptr); CFRelease(value); } } } } std::optional<CFIndex> make_integer_value(void) const { std::lock_guard<std::mutex> lock(state_mutex_); if (state_ && element_) { if (*state_ == led_state::on) { return element_.get_logical_max(); } else { return element_.get_logical_min(); } } return std::nullopt; } pqrs::cf::cf_ptr<IOHIDDeviceRef> device_; pqrs::osx::iokit_hid_element element_; std::optional<led_state> state_; mutable std::mutex state_mutex_; pqrs::dispatcher::extra::timer timer_; bool started_; }; } // namespace krbn <|endoftext|>
<commit_before>// RUN: %clangxx_asan -O %s -o %t && %run %t #include <assert.h> #include <stdio.h> #include <sanitizer/asan_interface.h> __attribute__((noinline)) void Throw() { int local; fprintf(stderr, "Throw: %p\n", &local); throw 1; } __attribute__((noinline)) void ThrowAndCatch() { int local; try { Throw(); } catch(...) { fprintf(stderr, "Catch: %p\n", &local); } } void TestThrow() { char x[32]; fprintf(stderr, "Before: %p poisoned: %d\n", &x, __asan_address_is_poisoned(x + 32)); assert(__asan_address_is_poisoned(x + 32)); ThrowAndCatch(); fprintf(stderr, "After: %p poisoned: %d\n", &x, __asan_address_is_poisoned(x + 32)); // FIXME: Invert this assertion once we fix // https://code.google.com/p/address-sanitizer/issues/detail?id=258 // This assertion works only w/o UAR. if (!__asan_get_current_fake_stack()) assert(!__asan_address_is_poisoned(x + 32)); } void TestThrowInline() { char x[32]; fprintf(stderr, "Before: %p poisoned: %d\n", &x, __asan_address_is_poisoned(x + 32)); assert(__asan_address_is_poisoned(x + 32)); try { Throw(); } catch(...) { fprintf(stderr, "Catch\n"); } fprintf(stderr, "After: %p poisoned: %d\n", &x, __asan_address_is_poisoned(x + 32)); // FIXME: Invert this assertion once we fix // https://code.google.com/p/address-sanitizer/issues/detail?id=258 // This assertion works only w/o UAR. if (!__asan_get_current_fake_stack()) assert(!__asan_address_is_poisoned(x + 32)); } int main(int argc, char **argv) { TestThrowInline(); TestThrow(); } <commit_msg>[asan] Fix test case failure on SystemZ<commit_after>// RUN: %clangxx_asan -O %s -o %t && %run %t #include <assert.h> #include <stdio.h> #include <sanitizer/asan_interface.h> __attribute__((noinline)) void Throw() { int local; fprintf(stderr, "Throw: %p\n", &local); throw 1; } __attribute__((noinline)) void ThrowAndCatch() { int local; try { Throw(); } catch(...) { fprintf(stderr, "Catch: %p\n", &local); } } __attribute__((noinline)) void TestThrow() { char x[32]; fprintf(stderr, "Before: %p poisoned: %d\n", &x, __asan_address_is_poisoned(x + 32)); assert(__asan_address_is_poisoned(x + 32)); ThrowAndCatch(); fprintf(stderr, "After: %p poisoned: %d\n", &x, __asan_address_is_poisoned(x + 32)); // FIXME: Invert this assertion once we fix // https://code.google.com/p/address-sanitizer/issues/detail?id=258 // This assertion works only w/o UAR. if (!__asan_get_current_fake_stack()) assert(!__asan_address_is_poisoned(x + 32)); } __attribute__((noinline)) void TestThrowInline() { char x[32]; fprintf(stderr, "Before: %p poisoned: %d\n", &x, __asan_address_is_poisoned(x + 32)); assert(__asan_address_is_poisoned(x + 32)); try { Throw(); } catch(...) { fprintf(stderr, "Catch\n"); } fprintf(stderr, "After: %p poisoned: %d\n", &x, __asan_address_is_poisoned(x + 32)); // FIXME: Invert this assertion once we fix // https://code.google.com/p/address-sanitizer/issues/detail?id=258 // This assertion works only w/o UAR. if (!__asan_get_current_fake_stack()) assert(!__asan_address_is_poisoned(x + 32)); } int main(int argc, char **argv) { TestThrowInline(); TestThrow(); } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // Antioch - A Gas Dynamics Thermochemistry Library // // Copyright (C) 2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // // $Id$ // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- #include "antioch_config.h" #include <valarray> #ifdef ANTIOCH_HAVE_EIGEN #include "Eigen/Dense" #endif #ifdef ANTIOCH_HAVE_METAPHYSICL #include "metaphysicl/numberarray.h" #endif // Declare metaprogramming overloads before they're used #include "antioch/eigen_utils_decl.h" #include "antioch/metaphysicl_utils_decl.h" #include "antioch/valarray_utils_decl.h" // C++ #include <cmath> #include <iostream> #include <limits> // Antioch #include "antioch/blottner_viscosity.h" #include "antioch/eigen_utils.h" #include "antioch/metaphysicl_utils.h" #include "antioch/valarray_utils.h" template <typename Scalar, typename PairScalars> int test_viscosity( const PairScalars mu, const PairScalars mu_exact, const Scalar tol ) { int return_flag = 0; const PairScalars rel_error = std::abs( (mu - mu_exact)/mu_exact); if( Antioch::max(rel_error) > tol ) { std::cerr << "Error: Mismatch in viscosity" << std::endl << "mu(T) = (" << mu[0] << ',' << mu[1] << ')' << std::endl << "mu_exact = (" << mu_exact[0] << ',' << mu_exact[1] << ')' << std::endl << "rel_error = (" << rel_error[0] << ',' << rel_error[1] << ')' << std::endl << "tol = " << tol << std::endl; return_flag = 1; } return return_flag; } template <typename PairScalars> int vectester(const PairScalars& example) { typedef typename Antioch::value_type<PairScalars>::type Scalar; const Scalar a = 3.14e-3L; const Scalar b = 2.71e-2L; const Scalar c = 42.0e-5L; Antioch::BlottnerViscosity<Scalar> mu(a,b,c); std::cout << mu << std::endl; PairScalars T = example; T[0] = 1521.2L; T[1] = 1621.2L; // bc gives PairScalars mu_exact = example; mu_exact[0] = 0.1444222341677025337305172031086891L; mu_exact[1] = 0.1450979382180072302532592937776388L; int return_flag = 0; // How are we getting such high error in the long double case? const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 2; return_flag = test_viscosity( mu(T), mu_exact, tol ); const Scalar a2 = 1e-3L; const Scalar b2 = 2e-2L; const Scalar c2 = 3e-5L; mu.reset_coeffs( a2, b2, c2 ); // octave gives PairScalars mu_exact2 = example; mu_exact2[0] = .1221724955488799960527696821225472L; mu_exact2[1] = .1224428450807678499433510473203746L; return_flag = test_viscosity( mu(T), mu_exact2, tol ); return return_flag; } int main() { int returnval = 0; returnval = returnval || vectester (std::valarray<float>(2)); returnval = returnval || vectester (std::valarray<double>(2)); returnval = returnval || vectester (std::valarray<long double>(2)); #ifdef ANTIOCH_HAVE_EIGEN returnval = returnval || vectester (Eigen::Array2f()); returnval = returnval || vectester (Eigen::Array2d()); returnval = returnval || vectester (Eigen::Array<long double, 2, 1>()); #endif #ifdef ANTIOCH_HAVE_METAPHYSICL returnval = returnval || vectester (MetaPhysicL::NumberArray<2, float> (0)); returnval = returnval || vectester (MetaPhysicL::NumberArray<2, double> (0)); returnval = returnval || vectester (MetaPhysicL::NumberArray<2, long double> (0)); #endif return returnval; } <commit_msg>[Antioch]: Forgot to remove now out-of-date comment.<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // Antioch - A Gas Dynamics Thermochemistry Library // // Copyright (C) 2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // // $Id$ // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- #include "antioch_config.h" #include <valarray> #ifdef ANTIOCH_HAVE_EIGEN #include "Eigen/Dense" #endif #ifdef ANTIOCH_HAVE_METAPHYSICL #include "metaphysicl/numberarray.h" #endif // Declare metaprogramming overloads before they're used #include "antioch/eigen_utils_decl.h" #include "antioch/metaphysicl_utils_decl.h" #include "antioch/valarray_utils_decl.h" // C++ #include <cmath> #include <iostream> #include <limits> // Antioch #include "antioch/blottner_viscosity.h" #include "antioch/eigen_utils.h" #include "antioch/metaphysicl_utils.h" #include "antioch/valarray_utils.h" template <typename Scalar, typename PairScalars> int test_viscosity( const PairScalars mu, const PairScalars mu_exact, const Scalar tol ) { int return_flag = 0; const PairScalars rel_error = std::abs( (mu - mu_exact)/mu_exact); if( Antioch::max(rel_error) > tol ) { std::cerr << "Error: Mismatch in viscosity" << std::endl << "mu(T) = (" << mu[0] << ',' << mu[1] << ')' << std::endl << "mu_exact = (" << mu_exact[0] << ',' << mu_exact[1] << ')' << std::endl << "rel_error = (" << rel_error[0] << ',' << rel_error[1] << ')' << std::endl << "tol = " << tol << std::endl; return_flag = 1; } return return_flag; } template <typename PairScalars> int vectester(const PairScalars& example) { typedef typename Antioch::value_type<PairScalars>::type Scalar; const Scalar a = 3.14e-3L; const Scalar b = 2.71e-2L; const Scalar c = 42.0e-5L; Antioch::BlottnerViscosity<Scalar> mu(a,b,c); std::cout << mu << std::endl; PairScalars T = example; T[0] = 1521.2L; T[1] = 1621.2L; // bc gives PairScalars mu_exact = example; mu_exact[0] = 0.1444222341677025337305172031086891L; mu_exact[1] = 0.1450979382180072302532592937776388L; int return_flag = 0; const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 2; return_flag = test_viscosity( mu(T), mu_exact, tol ); const Scalar a2 = 1e-3L; const Scalar b2 = 2e-2L; const Scalar c2 = 3e-5L; mu.reset_coeffs( a2, b2, c2 ); // octave gives PairScalars mu_exact2 = example; mu_exact2[0] = .1221724955488799960527696821225472L; mu_exact2[1] = .1224428450807678499433510473203746L; return_flag = test_viscosity( mu(T), mu_exact2, tol ); return return_flag; } int main() { int returnval = 0; returnval = returnval || vectester (std::valarray<float>(2)); returnval = returnval || vectester (std::valarray<double>(2)); returnval = returnval || vectester (std::valarray<long double>(2)); #ifdef ANTIOCH_HAVE_EIGEN returnval = returnval || vectester (Eigen::Array2f()); returnval = returnval || vectester (Eigen::Array2d()); returnval = returnval || vectester (Eigen::Array<long double, 2, 1>()); #endif #ifdef ANTIOCH_HAVE_METAPHYSICL returnval = returnval || vectester (MetaPhysicL::NumberArray<2, float> (0)); returnval = returnval || vectester (MetaPhysicL::NumberArray<2, double> (0)); returnval = returnval || vectester (MetaPhysicL::NumberArray<2, long double> (0)); #endif return returnval; } <|endoftext|>
<commit_before>#include <stdio.h> #include "Halide.h" #include <time.h> // Test the simplifier in Halide by testing for equivalence of randomly generated expressions. using namespace std; using namespace Halide; using namespace Halide::Internal; const int fuzz_var_count = 5; Type fuzz_types[] = { UInt(1), UInt(8), UInt(16), UInt(32), Int(8), Int(16), Int(32) }; const int fuzz_type_count = sizeof(fuzz_types)/sizeof(fuzz_types[0]); std::string fuzz_var(int i) { return std::string(1, 'a' + i); } Expr random_var() { return Variable::make(Int(0), fuzz_var(rand()%fuzz_var_count)); } Type random_type(int width) { Type T = fuzz_types[rand()%fuzz_type_count]; if (width > 1) { T = T.with_lanes(width); } return T; } Expr random_leaf(Type T, bool overflow_undef = false, bool imm_only = false) { if (T.is_int() && T.bits() == 32) { overflow_undef = true; } if (T.is_scalar()) { int var = rand()%fuzz_var_count + 1; if (!imm_only && var < fuzz_var_count) { return cast(T, random_var()); } else { if (overflow_undef) { // For Int(32), we don't care about correctness during // overflow, so just use numbers that are unlikely to // overflow. return cast(T, rand()%256 - 128); } else { return cast(T, rand() - RAND_MAX/2); } } } else { if (rand() % 2 == 0) { return Ramp::make(random_leaf(T.element_of(), overflow_undef), random_leaf(T.element_of(), overflow_undef), T.lanes()); } else { return Broadcast::make(random_leaf(T.element_of(), overflow_undef), T.lanes()); } } } Expr random_expr(Type T, int depth, bool overflow_undef = false); Expr random_condition(Type T, int depth, bool maybe_scalar) { typedef Expr (*make_bin_op_fn)(Expr, Expr); static make_bin_op_fn make_bin_op[] = { EQ::make, NE::make, LT::make, LE::make, GT::make, GE::make, }; const int op_count = sizeof(make_bin_op)/sizeof(make_bin_op[0]); if (maybe_scalar && rand() % T.lanes() == 0) { T = T.element_of(); } Expr a = random_expr(T, depth); Expr b = random_expr(T, depth); int op = rand()%op_count; return make_bin_op[op](a, b); } Expr random_expr(Type T, int depth, bool overflow_undef) { typedef Expr (*make_bin_op_fn)(Expr, Expr); static make_bin_op_fn make_bin_op[] = { Add::make, Sub::make, Mul::make, Min::make, Max::make, Div::make, Mod::make, }; static make_bin_op_fn make_bool_bin_op[] = { And::make, Or::make, }; if (T.is_int() && T.bits() == 32) { overflow_undef = true; } if (depth-- <= 0) { return random_leaf(T, overflow_undef); } const int bin_op_count = sizeof(make_bin_op) / sizeof(make_bin_op[0]); const int bool_bin_op_count = sizeof(make_bool_bin_op) / sizeof(make_bool_bin_op[0]); const int op_count = bin_op_count + bool_bin_op_count + 5; int op = rand() % op_count; switch(op) { case 0: return random_leaf(T); case 1: return Select::make(random_condition(T, depth, true), random_expr(T, depth, overflow_undef), random_expr(T, depth, overflow_undef)); case 2: if (T.lanes() != 1) { return Broadcast::make(random_expr(T.element_of(), depth, overflow_undef), T.lanes()); } break; case 3: if (T.lanes() != 1) { return Ramp::make(random_expr(T.element_of(), depth, overflow_undef), random_expr(T.element_of(), depth, overflow_undef), T.lanes()); } break; case 4: if (T.is_bool()) { return Not::make(random_expr(T, depth)); } break; case 5: // When generating boolean expressions, maybe throw in a condition on non-bool types. if (T.is_bool()) { return random_condition(T, depth, false); } break; case 6: { // Get a random type that isn't T or int32 (int32 can overflow and we don't care about that). Type subT; do { subT = random_type(T.lanes()); } while (subT == T || (subT.is_int() && subT.bits() == 32)); return Cast::make(T, random_expr(subT, depth, overflow_undef)); } default: make_bin_op_fn maker; if (T.is_bool()) { maker = make_bool_bin_op[op%bool_bin_op_count]; } else { maker = make_bin_op[op%bin_op_count]; } Expr a = random_expr(T, depth, overflow_undef); Expr b = random_expr(T, depth, overflow_undef); return maker(a, b); } // If we got here, try again. return random_expr(T, depth, overflow_undef); } bool test_simplification(Expr a, Expr b, Type T, const map<string, Expr> &vars) { for (int j = 0; j < T.lanes(); j++) { Expr a_j = a; Expr b_j = b; if (T.lanes() != 1) { a_j = extract_lane(a, j); b_j = extract_lane(b, j); } Expr a_j_v = simplify(substitute(vars, a_j)); Expr b_j_v = simplify(substitute(vars, b_j)); // If the simplifier didn't produce constants, there must be // undefined behavior in this expression. Ignore it. if (!Internal::is_const(a_j_v) || !Internal::is_const(b_j_v)) { continue; } if (!equal(a_j_v, b_j_v)) { for(map<string, Expr>::const_iterator i = vars.begin(); i != vars.end(); i++) { std::cout << i->first << " = " << i->second << '\n'; } std::cout << a << '\n'; std::cout << b << '\n'; std::cout << "In vector lane " << j << ":\n"; std::cout << a_j << " -> " << a_j_v << '\n'; std::cout << b_j << " -> " << b_j_v << '\n'; return false; } } return true; } bool test_expression(Expr test, int samples) { Expr simplified = simplify(test); map<string, Expr> vars; for (int i = 0; i < fuzz_var_count; i++) { vars[fuzz_var(i)] = Expr(); } for (int i = 0; i < samples; i++) { for (std::map<string, Expr>::iterator v = vars.begin(); v != vars.end(); v++) { v->second = random_leaf(test.type().element_of(), true); } if (!test_simplification(test, simplified, test.type(), vars)) { return false; } } return true; } Expr ramp(Expr b, Expr s, int w) { return Ramp::make(b, s, w); } Expr x1(Expr x) { return Broadcast::make(x, 2); } Expr x2(Expr x) { return Broadcast::make(x, 2); } Expr x4(Expr x) { return Broadcast::make(x, 2); } Expr uint1(Expr x) { return Cast::make(UInt(1), x); } Expr uint8(Expr x) { return Cast::make(UInt(8), x); } Expr uint16(Expr x) { return Cast::make(UInt(16), x); } Expr uint32(Expr x) { return Cast::make(UInt(32), x); } Expr int8(Expr x) { return Cast::make(Int(8), x); } Expr int16(Expr x) { return Cast::make(Int(16), x); } Expr int32(Expr x) { return Cast::make(Int(32), x); } Expr uint1x2(Expr x) { return Cast::make(UInt(1).with_lanes(2), x); } Expr uint8x2(Expr x) { return Cast::make(UInt(8).with_lanes(2), x); } Expr uint16x2(Expr x) { return Cast::make(UInt(16).with_lanes(2), x); } Expr uint32x2(Expr x) { return Cast::make(UInt(32).with_lanes(2), x); } Expr int8x2(Expr x) { return Cast::make(Int(8).with_lanes(2), x); } Expr int16x2(Expr x) { return Cast::make(Int(16).with_lanes(2), x); } Expr int32x2(Expr x) { return Cast::make(Int(32).with_lanes(2), x); } Expr a(Variable::make(Int(0), fuzz_var(0))); Expr b(Variable::make(Int(0), fuzz_var(1))); Expr c(Variable::make(Int(0), fuzz_var(2))); Expr d(Variable::make(Int(0), fuzz_var(3))); Expr e(Variable::make(Int(0), fuzz_var(4))); int main(int argc, char **argv) { // Number of random expressions to test. const int count = 1000; // Depth of the randomly generated expression trees. const int depth = 5; // Number of samples to test the generated expressions for. const int samples = 3; // We want different fuzz tests every time, to increase coverage. // We also report the seed to enable reproducing failures. int fuzz_seed = argc > 1 ? atoi(argv[1]) : time(NULL); srand(fuzz_seed); std::cout << "Simplify fuzz test seed: " << fuzz_seed << '\n'; int max_fuzz_vector_width = 4; for (int i = 0; i < fuzz_type_count; i++) { Type T = fuzz_types[i]; for (int w = 1; w < max_fuzz_vector_width; w *= 2) { Type VT = T.with_lanes(w); for (int n = 0; n < count; n++) { // Generate a random expr... Expr test = random_expr(VT, depth); if (!test_expression(test, samples)) { return -1; } } } } std::cout << "Success!" << std::endl; return 0; } <commit_msg>Use std::endl to ensure buffer flush.<commit_after>#include <stdio.h> #include "Halide.h" #include <time.h> // Test the simplifier in Halide by testing for equivalence of randomly generated expressions. using namespace std; using namespace Halide; using namespace Halide::Internal; const int fuzz_var_count = 5; Type fuzz_types[] = { UInt(1), UInt(8), UInt(16), UInt(32), Int(8), Int(16), Int(32) }; const int fuzz_type_count = sizeof(fuzz_types)/sizeof(fuzz_types[0]); std::string fuzz_var(int i) { return std::string(1, 'a' + i); } Expr random_var() { return Variable::make(Int(0), fuzz_var(rand()%fuzz_var_count)); } Type random_type(int width) { Type T = fuzz_types[rand()%fuzz_type_count]; if (width > 1) { T = T.with_lanes(width); } return T; } Expr random_leaf(Type T, bool overflow_undef = false, bool imm_only = false) { if (T.is_int() && T.bits() == 32) { overflow_undef = true; } if (T.is_scalar()) { int var = rand()%fuzz_var_count + 1; if (!imm_only && var < fuzz_var_count) { return cast(T, random_var()); } else { if (overflow_undef) { // For Int(32), we don't care about correctness during // overflow, so just use numbers that are unlikely to // overflow. return cast(T, rand()%256 - 128); } else { return cast(T, rand() - RAND_MAX/2); } } } else { if (rand() % 2 == 0) { return Ramp::make(random_leaf(T.element_of(), overflow_undef), random_leaf(T.element_of(), overflow_undef), T.lanes()); } else { return Broadcast::make(random_leaf(T.element_of(), overflow_undef), T.lanes()); } } } Expr random_expr(Type T, int depth, bool overflow_undef = false); Expr random_condition(Type T, int depth, bool maybe_scalar) { typedef Expr (*make_bin_op_fn)(Expr, Expr); static make_bin_op_fn make_bin_op[] = { EQ::make, NE::make, LT::make, LE::make, GT::make, GE::make, }; const int op_count = sizeof(make_bin_op)/sizeof(make_bin_op[0]); if (maybe_scalar && rand() % T.lanes() == 0) { T = T.element_of(); } Expr a = random_expr(T, depth); Expr b = random_expr(T, depth); int op = rand()%op_count; return make_bin_op[op](a, b); } Expr random_expr(Type T, int depth, bool overflow_undef) { typedef Expr (*make_bin_op_fn)(Expr, Expr); static make_bin_op_fn make_bin_op[] = { Add::make, Sub::make, Mul::make, Min::make, Max::make, Div::make, Mod::make, }; static make_bin_op_fn make_bool_bin_op[] = { And::make, Or::make, }; if (T.is_int() && T.bits() == 32) { overflow_undef = true; } if (depth-- <= 0) { return random_leaf(T, overflow_undef); } const int bin_op_count = sizeof(make_bin_op) / sizeof(make_bin_op[0]); const int bool_bin_op_count = sizeof(make_bool_bin_op) / sizeof(make_bool_bin_op[0]); const int op_count = bin_op_count + bool_bin_op_count + 5; int op = rand() % op_count; switch(op) { case 0: return random_leaf(T); case 1: return Select::make(random_condition(T, depth, true), random_expr(T, depth, overflow_undef), random_expr(T, depth, overflow_undef)); case 2: if (T.lanes() != 1) { return Broadcast::make(random_expr(T.element_of(), depth, overflow_undef), T.lanes()); } break; case 3: if (T.lanes() != 1) { return Ramp::make(random_expr(T.element_of(), depth, overflow_undef), random_expr(T.element_of(), depth, overflow_undef), T.lanes()); } break; case 4: if (T.is_bool()) { return Not::make(random_expr(T, depth)); } break; case 5: // When generating boolean expressions, maybe throw in a condition on non-bool types. if (T.is_bool()) { return random_condition(T, depth, false); } break; case 6: { // Get a random type that isn't T or int32 (int32 can overflow and we don't care about that). Type subT; do { subT = random_type(T.lanes()); } while (subT == T || (subT.is_int() && subT.bits() == 32)); return Cast::make(T, random_expr(subT, depth, overflow_undef)); } default: make_bin_op_fn maker; if (T.is_bool()) { maker = make_bool_bin_op[op%bool_bin_op_count]; } else { maker = make_bin_op[op%bin_op_count]; } Expr a = random_expr(T, depth, overflow_undef); Expr b = random_expr(T, depth, overflow_undef); return maker(a, b); } // If we got here, try again. return random_expr(T, depth, overflow_undef); } bool test_simplification(Expr a, Expr b, Type T, const map<string, Expr> &vars) { for (int j = 0; j < T.lanes(); j++) { Expr a_j = a; Expr b_j = b; if (T.lanes() != 1) { a_j = extract_lane(a, j); b_j = extract_lane(b, j); } Expr a_j_v = simplify(substitute(vars, a_j)); Expr b_j_v = simplify(substitute(vars, b_j)); // If the simplifier didn't produce constants, there must be // undefined behavior in this expression. Ignore it. if (!Internal::is_const(a_j_v) || !Internal::is_const(b_j_v)) { continue; } if (!equal(a_j_v, b_j_v)) { for(map<string, Expr>::const_iterator i = vars.begin(); i != vars.end(); i++) { std::cout << i->first << " = " << i->second << '\n'; } std::cout << a << '\n'; std::cout << b << '\n'; std::cout << "In vector lane " << j << ":\n"; std::cout << a_j << " -> " << a_j_v << '\n'; std::cout << b_j << " -> " << b_j_v << '\n'; return false; } } return true; } bool test_expression(Expr test, int samples) { Expr simplified = simplify(test); map<string, Expr> vars; for (int i = 0; i < fuzz_var_count; i++) { vars[fuzz_var(i)] = Expr(); } for (int i = 0; i < samples; i++) { for (std::map<string, Expr>::iterator v = vars.begin(); v != vars.end(); v++) { v->second = random_leaf(test.type().element_of(), true); } if (!test_simplification(test, simplified, test.type(), vars)) { return false; } } return true; } Expr ramp(Expr b, Expr s, int w) { return Ramp::make(b, s, w); } Expr x1(Expr x) { return Broadcast::make(x, 2); } Expr x2(Expr x) { return Broadcast::make(x, 2); } Expr x4(Expr x) { return Broadcast::make(x, 2); } Expr uint1(Expr x) { return Cast::make(UInt(1), x); } Expr uint8(Expr x) { return Cast::make(UInt(8), x); } Expr uint16(Expr x) { return Cast::make(UInt(16), x); } Expr uint32(Expr x) { return Cast::make(UInt(32), x); } Expr int8(Expr x) { return Cast::make(Int(8), x); } Expr int16(Expr x) { return Cast::make(Int(16), x); } Expr int32(Expr x) { return Cast::make(Int(32), x); } Expr uint1x2(Expr x) { return Cast::make(UInt(1).with_lanes(2), x); } Expr uint8x2(Expr x) { return Cast::make(UInt(8).with_lanes(2), x); } Expr uint16x2(Expr x) { return Cast::make(UInt(16).with_lanes(2), x); } Expr uint32x2(Expr x) { return Cast::make(UInt(32).with_lanes(2), x); } Expr int8x2(Expr x) { return Cast::make(Int(8).with_lanes(2), x); } Expr int16x2(Expr x) { return Cast::make(Int(16).with_lanes(2), x); } Expr int32x2(Expr x) { return Cast::make(Int(32).with_lanes(2), x); } Expr a(Variable::make(Int(0), fuzz_var(0))); Expr b(Variable::make(Int(0), fuzz_var(1))); Expr c(Variable::make(Int(0), fuzz_var(2))); Expr d(Variable::make(Int(0), fuzz_var(3))); Expr e(Variable::make(Int(0), fuzz_var(4))); int main(int argc, char **argv) { // Number of random expressions to test. const int count = 1000; // Depth of the randomly generated expression trees. const int depth = 5; // Number of samples to test the generated expressions for. const int samples = 3; // We want different fuzz tests every time, to increase coverage. // We also report the seed to enable reproducing failures. int fuzz_seed = argc > 1 ? atoi(argv[1]) : time(NULL); srand(fuzz_seed); std::cout << "Simplify fuzz test seed: " << fuzz_seed << std::endl; int max_fuzz_vector_width = 4; for (int i = 0; i < fuzz_type_count; i++) { Type T = fuzz_types[i]; for (int w = 1; w < max_fuzz_vector_width; w *= 2) { Type VT = T.with_lanes(w); for (int n = 0; n < count; n++) { // Generate a random expr... Expr test = random_expr(VT, depth); if (!test_expression(test, samples)) { return -1; } } } } std::cout << "Success!" << std::endl; return 0; } <|endoftext|>
<commit_before>#include <windows.h> #include "pluginsdk\_plugins.h" #include "pluginsdk\_exports.h" // modified _exports.h to use _dbg_addrinfoget export #include "pluginsdk\bridgemain.h" #ifdef _WIN64 #pragma comment(lib, "pluginsdk\\x64dbg.lib") #pragma comment(lib, "pluginsdk\\x64bridge.lib") #else #pragma comment(lib, "pluginsdk\\x32dbg.lib") #pragma comment(lib, "pluginsdk\\x32bridge.lib") #endif #ifndef DLL_EXPORT #define DLL_EXPORT extern "C" __declspec(dllexport) #endif //DLL_EXPORT #define plugin_name "XrefInfo" #define plugin_version 1 int pluginHandle; HWND hwndDlg; int compareFunc(const void* a, const void* b) { XREF_RECORD* A, *B; A = (XREF_RECORD*)a; B = (XREF_RECORD*)b; if(A->type > B->type) return 1; else if(A->type < B->type) return -1; else if(A->addr > B->addr) return 1; else if(A->addr < B->addr) return -1; else return 0; } void cbPlugin(CBTYPE cbType, LPVOID generic_param) { PLUG_CB_SELCHANGED* param = (PLUG_CB_SELCHANGED*)generic_param; if(param->hWindow == GUI_DISASSEMBLY) { XREF_INFO info; if(DbgXrefGet(param->VA, &info) && info.refcount > 0) { std::string output; std::qsort(info.references, info.refcount, sizeof(info.references[0]), &compareFunc); int t = -1; for(int i = 0; i < info.refcount; i++) { if(t != info.references[i].type) { if(t != -1) output += ","; switch(info.references[i].type) { case XREF_JMP: output += "Jump from "; break; case XREF_CALL: output += "Call from "; break; default: output += "Reference from "; break; } t = info.references[i].type; } ADDRINFO label; label.flags = flaglabel; _dbg_addrinfoget(info.references[i].addr, SEG_DEFAULT, &label); output += label.label; if(i != info.refcount - 1) output += ","; } GuiAddInfoLine(output.c_str()); } } } DLL_EXPORT bool pluginit(PLUG_INITSTRUCT* initStruct) { initStruct->pluginVersion = plugin_version; initStruct->sdkVersion = PLUG_SDKVERSION; strcpy(initStruct->pluginName, plugin_name); pluginHandle = initStruct->pluginHandle; return true; } DLL_EXPORT bool plugstop() { return true; } DLL_EXPORT void plugsetup(PLUG_SETUPSTRUCT* setupStruct) { hwndDlg = setupStruct->hwndDlg; _plugin_registercallback(pluginHandle, CB_SELCHANGED, &cbPlugin); } extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if(fdwReason == DLL_PROCESS_ATTACH) DisableThreadLibraryCalls(hinstDLL); return TRUE; } <commit_msg>rebrand this plugin<commit_after>#include <windows.h> #include "pluginsdk\_plugins.h" #include "pluginsdk\_exports.h" // modified _exports.h to use _dbg_addrinfoget export #include "pluginsdk\bridgemain.h" #ifdef _WIN64 #pragma comment(lib, "pluginsdk\\x64dbg.lib") #pragma comment(lib, "pluginsdk\\x64bridge.lib") #else #pragma comment(lib, "pluginsdk\\x32dbg.lib") #pragma comment(lib, "pluginsdk\\x32bridge.lib") #endif #ifndef DLL_EXPORT #define DLL_EXPORT extern "C" __declspec(dllexport) #endif //DLL_EXPORT #define plugin_name "ExtraInfo" #define plugin_version 1 int pluginHandle; HWND hwndDlg; int compareFunc(const void* a, const void* b) { XREF_RECORD* A, *B; A = (XREF_RECORD*)a; B = (XREF_RECORD*)b; if(A->type > B->type) return 1; else if(A->type < B->type) return -1; else if(A->addr > B->addr) return 1; else if(A->addr < B->addr) return -1; else return 0; } void cbPlugin(CBTYPE cbType, LPVOID generic_param) { PLUG_CB_SELCHANGED* param = (PLUG_CB_SELCHANGED*)generic_param; if(param->hWindow == GUI_DISASSEMBLY) { XREF_INFO info; if(DbgXrefGet(param->VA, &info) && info.refcount > 0) { std::string output; std::qsort(info.references, info.refcount, sizeof(info.references[0]), &compareFunc); int t = -1; for(int i = 0; i < info.refcount; i++) { if(t != info.references[i].type) { if(t != -1) output += ","; switch(info.references[i].type) { case XREF_JMP: output += "Jump from "; break; case XREF_CALL: output += "Call from "; break; default: output += "Reference from "; break; } t = info.references[i].type; } ADDRINFO label; label.flags = flaglabel; _dbg_addrinfoget(info.references[i].addr, SEG_DEFAULT, &label); output += label.label; if(i != info.refcount - 1) output += ","; } GuiAddInfoLine(output.c_str()); } } } DLL_EXPORT bool pluginit(PLUG_INITSTRUCT* initStruct) { initStruct->pluginVersion = plugin_version; initStruct->sdkVersion = PLUG_SDKVERSION; strcpy(initStruct->pluginName, plugin_name); pluginHandle = initStruct->pluginHandle; return true; } DLL_EXPORT bool plugstop() { return true; } DLL_EXPORT void plugsetup(PLUG_SETUPSTRUCT* setupStruct) { hwndDlg = setupStruct->hwndDlg; _plugin_registercallback(pluginHandle, CB_SELCHANGED, &cbPlugin); } extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if(fdwReason == DLL_PROCESS_ATTACH) DisableThreadLibraryCalls(hinstDLL); return TRUE; } <|endoftext|>
<commit_before> #include "potentialfunctioncbspl.h" PotentialFunctionCBSPL::PotentialFunctionCBSPL(const int nlam_, const int ncutcoeff_, const double min_, const double max_) : PotentialFunction(nlam_,min_,max_) { /* Here nlam_ is the total number of coeff values that are to be optimized * To ensure that potential and force go to zero smoothly near cut-off, * as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to * cut-off and beyond take a value of zero. * * Since region less than rmin is not sampled sufficiently for stability * first _nexcl coefficients are not optimized instead their values are * extrapolated from first statistically significant knot values near rmin */ // number of break points = _lam.size() - 2 _nbreak = _lam.size() - 2; _dr = ( _cut_off )/( double (_nbreak - 1) ); // break point locations // since ncoeff = nbreak +2 , r values for last two coefficients are also // computed _rbreak.resize(_lam.size(),false); _rbreak.clear(); for( int i = 0; i < _lam.size(); i++) _rbreak(i) = i*_dr; // exclude knots corresponding to r <= _min _nexcl = min( int( ( _min )/_dr ), _nbreak - 2 ) + 1; // account for finite numerical division of _min/_dr // e.g. 0.24/0.02 may result in 11.99999999999999 if( _rbreak(_nexcl) == _min ) _nexcl++; _ncutcoeff = ncutcoeff_; _M.resize(4,4,false); _M.clear(); _M(0,0) = 1.0; _M(0,1) = 4.0; _M(0,2) = 1.0; _M(0,3) = 0.0; _M(1,0) = -3.0; _M(1,1) = 0.0; _M(1,2) = 3.0; _M(1,3) = 0.0; _M(2,0) = 3.0; _M(2,1) = -6.0; _M(2,2) = 3.0; _M(2,3) = 0.0; _M(3,0) = -1.0; _M(3,1) = 3.0; _M(3,2) = -3.0; _M(3,3) = 1.0; _M /= 6.0; } int PotentialFunctionCBSPL::getOptParamSize() const { return _lam.size() - _nexcl - _ncutcoeff; } void PotentialFunctionCBSPL::setParam(string filename) { Table param; param.Load(filename); _lam.clear(); if( param.size() != _lam.size()) { throw std::runtime_error("Potential parameters size mismatch!\n" "Check input parameter file \"" + filename + "\" \nThere should be " + boost::lexical_cast<string>( _lam.size() ) + " parameters"); } else { // force last _ncutcoeff to be zero for( int i = 0; i < _lam.size() - _ncutcoeff; i++){ _rbreak(i) = param.x(i); _lam(i) = param.y(i); } } } void PotentialFunctionCBSPL::SaveParam(const string& filename){ extrapolExclParam(); Table param; param.SetHasYErr(false); param.resize(_lam.size(), false); // write extrapolated knots with flag 'o' for (int i = 0; i < _nexcl; i++){ param.set(i, _rbreak(i), _lam(i), 'o'); } for (int i = _nexcl; i < _lam.size(); i++){ param.set(i, _rbreak(i), _lam(i), 'i'); } param.Save(filename); } void PotentialFunctionCBSPL::SavePotTab(const string& filename, const double step) { extrapolExclParam(); PotentialFunction::SavePotTab(filename,step,0.0,_cut_off); } void PotentialFunctionCBSPL::extrapolExclParam(){ // extrapolate first _nexcl knot values using exponential extrapolation // u(r) = a * exp( b * r) // a = u0 * exp ( - m * r0/u0 ) // b = m/u0 // m = (u1-u0)/(r1-r0) double u0 = _lam(_nexcl); if( u0 < 0.0 ) { throw std::runtime_error("min r value for cbspl is too large.\n" "reference value for exponential extrapolation can not be negative"); } double r0 = _rbreak(_nexcl); double m = (_lam(_nexcl + 1) - _lam(_nexcl)) / (_rbreak(_nexcl + 1) - _rbreak(_nexcl)); double a = u0 * exp(-m * r0 / u0); double b = m / u0; for (int i = 0; i < _nexcl; i++) { double r = _rbreak(i); double u = a * exp(b * r); _lam(i) = u; } } void PotentialFunctionCBSPL::setOptParam(const int i, const double val){ _lam( i + _nexcl ) = val; } double PotentialFunctionCBSPL::getOptParam(const int i) const{ return _lam( i + _nexcl ); } double PotentialFunctionCBSPL::CalculateF (const double r) const { if( r <= _cut_off){ ub::vector<double> R; ub::vector<double> B; int indx = min( int( r /_dr ) , _nbreak-2 ); double rk = indx*_dr; double t = ( r - rk)/_dr; R.resize(4,false); R.clear(); R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t; ub::vector<double> RM = ub::prod(R,_M); B.resize(4,false); B.clear(); B(0) = _lam(indx); B(1) = _lam(indx+1); B(2) = _lam(indx+2); B(3) = _lam(indx+3); double u = ub::inner_prod(B,RM); return u; } else { return 0.0; } } // calculate first derivative w.r.t. ith parameter double PotentialFunctionCBSPL::CalculateDF(const int i, const double r) const{ // since first _nexcl parameters are not optimized for stability reasons //i = i + _nexcl; if ( r <= _cut_off ) { int indx = min( int( ( r )/_dr ), _nbreak-2 ); if ( i + _nexcl >= indx && i + _nexcl <= indx+3 ){ ub::vector<double> R; double rk = indx*_dr; double t = ( r - rk)/_dr; R.resize(4,false); R.clear(); R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t; ub::vector<double> RM = ub::prod(R,_M); return RM(i + _nexcl-indx); }else{ return 0.0; } } else { return 0; } } // calculate second derivative w.r.t. ith parameter double PotentialFunctionCBSPL::CalculateD2F(const int i, const int j, const double r) const { // for cubic B-SPlines D2F is zero for all lamdas return 0.0; } <commit_msg>cbspl knot extrapolation: also check for zero reference knot value<commit_after> #include "potentialfunctioncbspl.h" PotentialFunctionCBSPL::PotentialFunctionCBSPL(const int nlam_, const int ncutcoeff_, const double min_, const double max_) : PotentialFunction(nlam_,min_,max_) { /* Here nlam_ is the total number of coeff values that are to be optimized * To ensure that potential and force go to zero smoothly near cut-off, * as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to * cut-off and beyond take a value of zero. * * Since region less than rmin is not sampled sufficiently for stability * first _nexcl coefficients are not optimized instead their values are * extrapolated from first statistically significant knot values near rmin */ // number of break points = _lam.size() - 2 _nbreak = _lam.size() - 2; _dr = ( _cut_off )/( double (_nbreak - 1) ); // break point locations // since ncoeff = nbreak +2 , r values for last two coefficients are also // computed _rbreak.resize(_lam.size(),false); _rbreak.clear(); for( int i = 0; i < _lam.size(); i++) _rbreak(i) = i*_dr; // exclude knots corresponding to r <= _min _nexcl = min( int( ( _min )/_dr ), _nbreak - 2 ) + 1; // account for finite numerical division of _min/_dr // e.g. 0.24/0.02 may result in 11.99999999999999 if( _rbreak(_nexcl) == _min ) _nexcl++; _ncutcoeff = ncutcoeff_; _M.resize(4,4,false); _M.clear(); _M(0,0) = 1.0; _M(0,1) = 4.0; _M(0,2) = 1.0; _M(0,3) = 0.0; _M(1,0) = -3.0; _M(1,1) = 0.0; _M(1,2) = 3.0; _M(1,3) = 0.0; _M(2,0) = 3.0; _M(2,1) = -6.0; _M(2,2) = 3.0; _M(2,3) = 0.0; _M(3,0) = -1.0; _M(3,1) = 3.0; _M(3,2) = -3.0; _M(3,3) = 1.0; _M /= 6.0; } int PotentialFunctionCBSPL::getOptParamSize() const { return _lam.size() - _nexcl - _ncutcoeff; } void PotentialFunctionCBSPL::setParam(string filename) { Table param; param.Load(filename); _lam.clear(); if( param.size() != _lam.size()) { throw std::runtime_error("Potential parameters size mismatch!\n" "Check input parameter file \"" + filename + "\" \nThere should be " + boost::lexical_cast<string>( _lam.size() ) + " parameters"); } else { // force last _ncutcoeff to be zero for( int i = 0; i < _lam.size() - _ncutcoeff; i++){ _rbreak(i) = param.x(i); _lam(i) = param.y(i); } } } void PotentialFunctionCBSPL::SaveParam(const string& filename){ extrapolExclParam(); Table param; param.SetHasYErr(false); param.resize(_lam.size(), false); // write extrapolated knots with flag 'o' for (int i = 0; i < _nexcl; i++){ param.set(i, _rbreak(i), _lam(i), 'o'); } for (int i = _nexcl; i < _lam.size(); i++){ param.set(i, _rbreak(i), _lam(i), 'i'); } param.Save(filename); } void PotentialFunctionCBSPL::SavePotTab(const string& filename, const double step) { extrapolExclParam(); PotentialFunction::SavePotTab(filename,step,0.0,_cut_off); } void PotentialFunctionCBSPL::extrapolExclParam(){ // extrapolate first _nexcl knot values using exponential extrapolation // u(r) = a * exp( b * r) // a = u0 * exp ( - m * r0/u0 ) // b = m/u0 // m = (u1-u0)/(r1-r0) double u0 = _lam(_nexcl); if( u0 <= 0.0 ) { throw std::runtime_error("min r value for cbspl is too large,\n" "choose min r such that knot value at (rmin+dr) > 0,\n" "else exponentially extrapolated knot values in " "the repulsive core would be negative or zero.\n"); } double r0 = _rbreak(_nexcl); double m = (_lam(_nexcl + 1) - _lam(_nexcl)) / (_rbreak(_nexcl + 1) - _rbreak(_nexcl)); double a = u0 * exp(-m * r0 / u0); double b = m / u0; for (int i = 0; i < _nexcl; i++) { double r = _rbreak(i); double u = a * exp(b * r); _lam(i) = u; } } void PotentialFunctionCBSPL::setOptParam(const int i, const double val){ _lam( i + _nexcl ) = val; } double PotentialFunctionCBSPL::getOptParam(const int i) const{ return _lam( i + _nexcl ); } double PotentialFunctionCBSPL::CalculateF (const double r) const { if( r <= _cut_off){ ub::vector<double> R; ub::vector<double> B; int indx = min( int( r /_dr ) , _nbreak-2 ); double rk = indx*_dr; double t = ( r - rk)/_dr; R.resize(4,false); R.clear(); R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t; ub::vector<double> RM = ub::prod(R,_M); B.resize(4,false); B.clear(); B(0) = _lam(indx); B(1) = _lam(indx+1); B(2) = _lam(indx+2); B(3) = _lam(indx+3); double u = ub::inner_prod(B,RM); return u; } else { return 0.0; } } // calculate first derivative w.r.t. ith parameter double PotentialFunctionCBSPL::CalculateDF(const int i, const double r) const{ // since first _nexcl parameters are not optimized for stability reasons //i = i + _nexcl; if ( r <= _cut_off ) { int indx = min( int( ( r )/_dr ), _nbreak-2 ); if ( i + _nexcl >= indx && i + _nexcl <= indx+3 ){ ub::vector<double> R; double rk = indx*_dr; double t = ( r - rk)/_dr; R.resize(4,false); R.clear(); R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t; ub::vector<double> RM = ub::prod(R,_M); return RM(i + _nexcl-indx); }else{ return 0.0; } } else { return 0; } } // calculate second derivative w.r.t. ith parameter double PotentialFunctionCBSPL::CalculateD2F(const int i, const int j, const double r) const { // for cubic B-SPlines D2F is zero for all lamdas return 0.0; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_BINARY_OPERATOR_HPP #define STAN_MATH_OPENCL_KERNEL_GENERATOR_BINARY_OPERATOR_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/err/check_matching_dims.hpp> #include <stan/math/opencl/multiply.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/opencl/kernel_generator/type_str.hpp> #include <stan/math/opencl/kernel_generator/name_generator.hpp> #include <stan/math/opencl/kernel_generator/operation.hpp> #include <stan/math/opencl/kernel_generator/scalar.hpp> #include <stan/math/opencl/kernel_generator/as_operation.hpp> #include <stan/math/opencl/kernel_generator/is_valid_expression.hpp> #include <string> #include <type_traits> #include <set> #include <utility> namespace stan { namespace math { /** * Represents a binary operation in kernel generator expressions. * @tparam Derived derived type * @tparam T_a type of first argument * @tparam T_b type of second argument */ template <typename Derived, typename T_a, typename T_b> class binary_operation : public operation< Derived, typename std::common_type< typename std::remove_reference_t<T_a>::ReturnScalar, typename std::remove_reference_t<T_b>::ReturnScalar>::type> { public: static_assert( std::is_base_of<operation_base, std::remove_reference_t<T_a>>::value, "binary_operation: a must be an operation!"); static_assert( std::is_base_of<operation_base, std::remove_reference_t<T_b>>::value, "binary_operation: b must be an operation!"); using ReturnScalar = typename std::common_type< typename std::remove_reference_t<T_a>::ReturnScalar, typename std::remove_reference_t<T_b>::ReturnScalar>::type; using base = operation<Derived, ReturnScalar>; using base::instance; using base::var_name; /** * Constructor * @param a first argument * @param b sedond argument * @param op operation */ binary_operation(T_a&& a, T_b&& b, const std::string& op) //NOLINT : a_(std::forward<T_a>(a)), b_(std::forward<T_b>(b)), op_(op) { const std::string function = "binary_operator" + op; if (a.rows() != base::dynamic && b.rows() != base::dynamic) { check_size_match(function.c_str(), "Rows of ", "a", a.rows(), "rows of ", "b", b.rows()); } if (a.cols() != base::dynamic && b.cols() != base::dynamic) { check_size_match(function.c_str(), "Columns of ", "a", a.cols(), "columns of ", "b", b.cols()); } } /** * generates kernel code for this and nested expressions. * @param ng name generator for this kernel * @param[in,out] generated set of already generated operations * @param i row index variable name * @param j column index variable name * @return part of kernel with code for this and nested expressions */ inline kernel_parts generate(name_generator& ng, std::set<int>& generated, const std::string& i, const std::string& j) const { if (generated.count(instance) == 0) { kernel_parts a_parts = a_.generate(ng, generated, i, j); kernel_parts b_parts = b_.generate(ng, generated, i, j); generated.insert(instance); var_name = ng.generate(); kernel_parts res; res.body = a_parts.body + b_parts.body + type_str<ReturnScalar>::name + " " + var_name + " = " + a_.var_name + op_ + b_.var_name + ";\n"; res.args = a_parts.args + b_parts.args; return res; } else { return {}; } } /** * Sets kernel arguments for this and nested expressions. * @param[in,out] generated set of expressions that already set their kernel * arguments * @param kernel kernel to set arguments on * @param[in,out] arg_num consecutive number of the first argument to set. * This is incremented for each argument set by this function. */ inline void set_args(std::set<int>& generated, cl::Kernel& kernel, int& arg_num) const { if (generated.count(instance) == 0) { generated.insert(instance); a_.set_args(generated, kernel, arg_num); b_.set_args(generated, kernel, arg_num); } } /** * Adds event for any matrices used by this or nested expressions. * @param e the event to add */ inline void add_event(cl::Event& e) const { a_.add_event(e); b_.add_event(e); } /** * Number of rows of a matrix that would be the result of evaluating this * expression. * @return number of rows */ inline int rows() const { int a_rows = a_.rows(); return a_rows == base::dynamic ? b_.rows() : a_rows; } /** * Number of columns of a matrix that would be the result of evaluating this * expression. * @return number of columns */ inline int cols() const { int a_cols = a_.cols(); return a_cols == base::dynamic ? b_.cols() : a_cols; } /** * View of a matrix that would be the result of evaluating this expression. * @return view */ inline matrix_cl_view view() const { return either(a_.view(), b_.view()); } protected: T_a a_; T_b b_; std::string op_; }; /** * Represents addition in kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression */ template <typename T_a, typename T_b> class addition__ : public binary_operation<addition__<T_a, T_b>, T_a, T_b> { public: /** * Constructor. * @param a first expression * @param b second expression */ addition__(T_a&& a, T_b&& b) //NOLINT : binary_operation<addition__<T_a, T_b>, T_a, T_b>( std::forward<T_a>(a), std::forward<T_b>(b), "+") {} }; /** * Addition of two kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression * @param a first argument * @param b second argument * @return Addition of given expressions */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions<T_a, T_b>> inline addition__<as_operation_t<T_a>, as_operation_t<T_b>> operator+(T_a&& a, T_b&& b) { //NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(std::forward<T_b>(b))}; } /** * Represents subtraction in kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression */ template <typename T_a, typename T_b> class subtraction__ : public binary_operation<subtraction__<T_a, T_b>, T_a, T_b> { public: /** * Constructor. * @param a first expression * @param b second expression */ subtraction__(T_a&& a, T_b&& b) //NOLINT : binary_operation<subtraction__<T_a, T_b>, T_a, T_b>( std::forward<T_a>(a), std::forward<T_b>(b), "-") {} }; /** * Subtraction of two kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression * @param a first expression * @param b second expression * @return Subtraction of given expressions */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions<T_a, T_b>> inline subtraction__<as_operation_t<T_a>, as_operation_t<T_b>> operator-( T_a&& a, T_b&& b) { //NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(std::forward<T_b>(b))}; } /** * Represents element-wise multiplication in kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions<T_a, T_b>> class elewise_multiplication__ : public binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b> { public: /** * Constructor. * @param a first expression * @param b second expression */ elewise_multiplication__(T_a&& a, T_b&& b) //NOLINT : binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b>( std::forward<T_a>(a), std::forward<T_b>(b), "*") {} /** * View of a matrix that would be the result of evaluating this expression. * @return view */ inline matrix_cl_view view() const { using base = binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b>; return both(base::a_.view(), base::b_.view()); } }; /** * Element-wise multiplication of two kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression * @param a first expression * @param b second expression * @return Element-wise multiplication of given expressions */ template <typename T_a, typename T_b> inline elewise_multiplication__<as_operation_t<T_a>, as_operation_t<T_b>> elewise_multiplication(T_a&& a, T_b&& b) { //NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(std::forward<T_b>(b))}; } /** * Multiplication of a scalar and a kernel generator expression. * @tparam T_a type of scalar * @tparam T_b type of expression * @param a scalar * @param b expression * @return Multiplication of given arguments */ template <typename T_a, typename T_b, typename = enable_if_arithmetic<T_a>, typename = enable_if_all_valid_expressions<T_b>> inline elewise_multiplication__<scalar__<T_a>, as_operation_t<T_b>> operator*(T_a&& a, T_b&& b) { //NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(std::forward<T_b>(b))}; } /** * Multiplication of a kernel generator expression and a scalar. * @tparam T_a type of expression * @tparam T_b type of scalar * @param a expression * @param b scalar * @return Multiplication of given arguments */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions<T_a>, typename = enable_if_arithmetic<T_b>> inline elewise_multiplication__<as_operation_t<T_a>, scalar__<T_b>> operator*(T_a&& a, const T_b b) { //NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(b)}; } /** * Matrix multiplication of two kernel generator expressions. Evaluates both * expressions before calculating the matrix product. * @tparam T_a type of first expression * @tparam T_b type of second expression * @param a first expression * @param b second expression * @return Matrix product of given arguments */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions_and_none_scalar<T_a, T_b>> inline matrix_cl<double> operator*(const T_a& a, const T_b& b) { // no need for perfect forwarding as operations are evaluated return as_operation(a).eval() * as_operation(b).eval(); } /** * Represents element-wise division in kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression */ template <typename T_a, typename T_b> class elewise_division__ : public binary_operation<elewise_division__<T_a, T_b>, T_a, T_b> { public: /** * Constructor. * @param a first expression * @param b second expression */ elewise_division__(T_a&& a, T_b&& b) //NOLINT : binary_operation<elewise_division__<T_a, T_b>, T_a, T_b>( std::forward<T_a>(a), std::forward<T_b>(b), "/") {} /** * View of a matrix that would be the result of evaluating this expression. * @return view */ inline matrix_cl_view view() const { using base = binary_operation<elewise_division__<T_a, T_b>, T_a, T_b>; return either(base::a_.view(), invert(base::b_.view())); } }; /** * Element-wise division of two kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression * @param a first expression * @param b second expression * @return Element-wise division of given expressions */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions<T_a, T_b>> inline elewise_division__<as_operation_t<T_a>, as_operation_t<T_b>> elewise_division(T_a&& a, T_b&& b) { //NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(std::forward<T_b>(b))}; } } // namespace math } // namespace stan #endif #endif <commit_msg>format<commit_after>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_BINARY_OPERATOR_HPP #define STAN_MATH_OPENCL_KERNEL_GENERATOR_BINARY_OPERATOR_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/err/check_matching_dims.hpp> #include <stan/math/opencl/multiply.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/opencl/kernel_generator/type_str.hpp> #include <stan/math/opencl/kernel_generator/name_generator.hpp> #include <stan/math/opencl/kernel_generator/operation.hpp> #include <stan/math/opencl/kernel_generator/scalar.hpp> #include <stan/math/opencl/kernel_generator/as_operation.hpp> #include <stan/math/opencl/kernel_generator/is_valid_expression.hpp> #include <string> #include <type_traits> #include <set> #include <utility> namespace stan { namespace math { /** * Represents a binary operation in kernel generator expressions. * @tparam Derived derived type * @tparam T_a type of first argument * @tparam T_b type of second argument */ template <typename Derived, typename T_a, typename T_b> class binary_operation : public operation< Derived, typename std::common_type< typename std::remove_reference_t<T_a>::ReturnScalar, typename std::remove_reference_t<T_b>::ReturnScalar>::type> { public: static_assert( std::is_base_of<operation_base, std::remove_reference_t<T_a>>::value, "binary_operation: a must be an operation!"); static_assert( std::is_base_of<operation_base, std::remove_reference_t<T_b>>::value, "binary_operation: b must be an operation!"); using ReturnScalar = typename std::common_type< typename std::remove_reference_t<T_a>::ReturnScalar, typename std::remove_reference_t<T_b>::ReturnScalar>::type; using base = operation<Derived, ReturnScalar>; using base::instance; using base::var_name; /** * Constructor * @param a first argument * @param b sedond argument * @param op operation */ binary_operation(T_a&& a, T_b&& b, const std::string& op) //NOLINT : a_(std::forward<T_a>(a)), b_(std::forward<T_b>(b)), op_(op) { const std::string function = "binary_operator" + op; if (a.rows() != base::dynamic && b.rows() != base::dynamic) { check_size_match(function.c_str(), "Rows of ", "a", a.rows(), "rows of ", "b", b.rows()); } if (a.cols() != base::dynamic && b.cols() != base::dynamic) { check_size_match(function.c_str(), "Columns of ", "a", a.cols(), "columns of ", "b", b.cols()); } } /** * generates kernel code for this and nested expressions. * @param ng name generator for this kernel * @param[in,out] generated set of already generated operations * @param i row index variable name * @param j column index variable name * @return part of kernel with code for this and nested expressions */ inline kernel_parts generate(name_generator& ng, std::set<int>& generated, const std::string& i, const std::string& j) const { if (generated.count(instance) == 0) { kernel_parts a_parts = a_.generate(ng, generated, i, j); kernel_parts b_parts = b_.generate(ng, generated, i, j); generated.insert(instance); var_name = ng.generate(); kernel_parts res; res.body = a_parts.body + b_parts.body + type_str<ReturnScalar>::name + " " + var_name + " = " + a_.var_name + op_ + b_.var_name + ";\n"; res.args = a_parts.args + b_parts.args; return res; } else { return {}; } } /** * Sets kernel arguments for this and nested expressions. * @param[in,out] generated set of expressions that already set their kernel * arguments * @param kernel kernel to set arguments on * @param[in,out] arg_num consecutive number of the first argument to set. * This is incremented for each argument set by this function. */ inline void set_args(std::set<int>& generated, cl::Kernel& kernel, int& arg_num) const { if (generated.count(instance) == 0) { generated.insert(instance); a_.set_args(generated, kernel, arg_num); b_.set_args(generated, kernel, arg_num); } } /** * Adds event for any matrices used by this or nested expressions. * @param e the event to add */ inline void add_event(cl::Event& e) const { a_.add_event(e); b_.add_event(e); } /** * Number of rows of a matrix that would be the result of evaluating this * expression. * @return number of rows */ inline int rows() const { int a_rows = a_.rows(); return a_rows == base::dynamic ? b_.rows() : a_rows; } /** * Number of columns of a matrix that would be the result of evaluating this * expression. * @return number of columns */ inline int cols() const { int a_cols = a_.cols(); return a_cols == base::dynamic ? b_.cols() : a_cols; } /** * View of a matrix that would be the result of evaluating this expression. * @return view */ inline matrix_cl_view view() const { return either(a_.view(), b_.view()); } protected: T_a a_; T_b b_; std::string op_; }; /** * Represents addition in kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression */ template <typename T_a, typename T_b> class addition__ : public binary_operation<addition__<T_a, T_b>, T_a, T_b> { public: /** * Constructor. * @param a first expression * @param b second expression */ addition__(T_a&& a, T_b&& b) //NOLINT : binary_operation<addition__<T_a, T_b>, T_a, T_b>( std::forward<T_a>(a), std::forward<T_b>(b), "+") {} }; /** * Addition of two kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression * @param a first argument * @param b second argument * @return Addition of given expressions */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions<T_a, T_b>> inline addition__<as_operation_t<T_a>, as_operation_t<T_b>> operator+( T_a&& a, T_b&& b) { // NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(std::forward<T_b>(b))}; } /** * Represents subtraction in kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression */ template <typename T_a, typename T_b> class subtraction__ : public binary_operation<subtraction__<T_a, T_b>, T_a, T_b> { public: /** * Constructor. * @param a first expression * @param b second expression */ subtraction__(T_a&& a, T_b&& b) //NOLINT : binary_operation<subtraction__<T_a, T_b>, T_a, T_b>( std::forward<T_a>(a), std::forward<T_b>(b), "-") {} }; /** * Subtraction of two kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression * @param a first expression * @param b second expression * @return Subtraction of given expressions */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions<T_a, T_b>> inline subtraction__<as_operation_t<T_a>, as_operation_t<T_b>> operator-( T_a&& a, T_b&& b) { //NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(std::forward<T_b>(b))}; } /** * Represents element-wise multiplication in kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions<T_a, T_b>> class elewise_multiplication__ : public binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b> { public: /** * Constructor. * @param a first expression * @param b second expression */ elewise_multiplication__(T_a&& a, T_b&& b) //NOLINT : binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b>( std::forward<T_a>(a), std::forward<T_b>(b), "*") {} /** * View of a matrix that would be the result of evaluating this expression. * @return view */ inline matrix_cl_view view() const { using base = binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b>; return both(base::a_.view(), base::b_.view()); } }; /** * Element-wise multiplication of two kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression * @param a first expression * @param b second expression * @return Element-wise multiplication of given expressions */ template <typename T_a, typename T_b> inline elewise_multiplication__<as_operation_t<T_a>, as_operation_t<T_b>> elewise_multiplication(T_a&& a, T_b&& b) { //NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(std::forward<T_b>(b))}; } /** * Multiplication of a scalar and a kernel generator expression. * @tparam T_a type of scalar * @tparam T_b type of expression * @param a scalar * @param b expression * @return Multiplication of given arguments */ template <typename T_a, typename T_b, typename = enable_if_arithmetic<T_a>, typename = enable_if_all_valid_expressions<T_b>> inline elewise_multiplication__<scalar__<T_a>, as_operation_t<T_b>> operator*( T_a&& a, T_b&& b) { // NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(std::forward<T_b>(b))}; } /** * Multiplication of a kernel generator expression and a scalar. * @tparam T_a type of expression * @tparam T_b type of scalar * @param a expression * @param b scalar * @return Multiplication of given arguments */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions<T_a>, typename = enable_if_arithmetic<T_b>> inline elewise_multiplication__<as_operation_t<T_a>, scalar__<T_b>> operator*( T_a&& a, const T_b b) { // NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(b)}; } /** * Matrix multiplication of two kernel generator expressions. Evaluates both * expressions before calculating the matrix product. * @tparam T_a type of first expression * @tparam T_b type of second expression * @param a first expression * @param b second expression * @return Matrix product of given arguments */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions_and_none_scalar<T_a, T_b>> inline matrix_cl<double> operator*(const T_a& a, const T_b& b) { // no need for perfect forwarding as operations are evaluated return as_operation(a).eval() * as_operation(b).eval(); } /** * Represents element-wise division in kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression */ template <typename T_a, typename T_b> class elewise_division__ : public binary_operation<elewise_division__<T_a, T_b>, T_a, T_b> { public: /** * Constructor. * @param a first expression * @param b second expression */ elewise_division__(T_a&& a, T_b&& b) //NOLINT : binary_operation<elewise_division__<T_a, T_b>, T_a, T_b>( std::forward<T_a>(a), std::forward<T_b>(b), "/") {} /** * View of a matrix that would be the result of evaluating this expression. * @return view */ inline matrix_cl_view view() const { using base = binary_operation<elewise_division__<T_a, T_b>, T_a, T_b>; return either(base::a_.view(), invert(base::b_.view())); } }; /** * Element-wise division of two kernel generator expressions. * @tparam T_a type of first expression * @tparam T_b type of second expression * @param a first expression * @param b second expression * @return Element-wise division of given expressions */ template <typename T_a, typename T_b, typename = enable_if_all_valid_expressions<T_a, T_b>> inline elewise_division__<as_operation_t<T_a>, as_operation_t<T_b>> elewise_division(T_a&& a, T_b&& b) { //NOLINT return {as_operation(std::forward<T_a>(a)), as_operation(std::forward<T_b>(b))}; } } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>/* tnt/object.cpp * Copyright (C) 2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <tnt/object.h> #include <cxxtools/log.h> log_define("tntnet.object") namespace tnt { unsigned Object::addRef() { return ++refs; } unsigned Object::release() { if (--refs == 0) { delete this; return 0; } else return refs; } } <commit_msg>remove unused logging-declarations<commit_after>/* tnt/object.cpp * Copyright (C) 2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <tnt/object.h> namespace tnt { unsigned Object::addRef() { return ++refs; } unsigned Object::release() { if (--refs == 0) { delete this; return 0; } else return refs; } } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/platform/platform.h" #if !defined(IS_MOBILE_PLATFORM) && defined(PLATFORM_POSIX) && \ (defined(__clang__) || defined(__GNUC__)) #define TF_GENERATE_STACKTRACE #endif #if defined(TF_GENERATE_STACKTRACE) #include <errno.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #include <string> #include "tensorflow/core/platform/stacktrace.h" #endif // defined(TF_GENERATE_STACKTRACE) namespace tensorflow { namespace testing { #if defined(TF_GENERATE_STACKTRACE) // This function will print stacktrace to STDERR. // It avoids using malloc, so it makes sure to dump the stack even when the heap // is corrupted. However, it can dump mangled symbols. inline void SafePrintStackTrace() { static const char begin_msg[] = "*** BEGIN MANGLED STACK TRACE ***\n"; (void)write(STDERR_FILENO, begin_msg, strlen(begin_msg)); int buffer_size = 128; void *trace[128]; // Run backtrace to get the size of the stacktrace buffer_size = backtrace(trace, buffer_size); // Print a mangled stacktrace to STDERR as safely as possible. backtrace_symbols_fd(trace, buffer_size, STDERR_FILENO); static const char end_msg[] = "*** END MANGLED STACK TRACE ***\n\n"; (void)write(STDERR_FILENO, end_msg, strlen(end_msg)); } static void StacktraceHandler(int sig, siginfo_t *si, void *v) { // Make sure our handler does not deadlock. And this should be the last thing // our program does. Therefore, set a timer to kill the program in 60 // seconds. struct itimerval timer; timer.it_value.tv_sec = 60; timer.it_value.tv_usec = 0; timer.it_interval.tv_sec = 0; timer.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &timer, 0); struct sigaction sa_timeout; memset(&sa_timeout, 0, sizeof(sa_timeout)); sa_timeout.sa_handler = SIG_DFL; sigaction(SIGALRM, &sa_timeout, 0); char buf[128]; snprintf(buf, sizeof(buf), "*** Received signal %d ***\n", sig); (void)write(STDERR_FILENO, buf, strlen(buf)); // Print "a" stack trace, as safely as possible. SafePrintStackTrace(); // Up until this line, we made sure not to allocate memory, to be able to dump // a stack trace even in the event of heap corruption. After this line, we // will try to print more human readable things to the terminal. // But these have a higher probability to fail. std::string stacktrace = CurrentStackTrace(); (void)write(STDERR_FILENO, stacktrace.c_str(), stacktrace.length()); // Abort the program. struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = SIG_DFL; sigaction(SIGABRT, &sa, NULL); abort(); } void InstallStacktraceHandler() { int handled_signals[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE}; for (int i = 0; i < sizeof(handled_signals) / sizeof(int); i++) { int sig = handled_signals[i]; struct sigaction sa; struct sigaction osa; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_SIGINFO | SA_RESETHAND; sa.sa_sigaction = &StacktraceHandler; if (sigaction(sig, &sa, &osa) != 0) { char buf[128]; snprintf(buf, sizeof(buf), "Warning, can't install backtrace signal handler for signal %d, " "errno:%d \n", sig, errno); (void)write(STDERR_FILENO, buf, strlen(buf)); } else if (osa.sa_handler != SIG_DFL) { char buf[128]; snprintf(buf, sizeof(buf), "Warning, backtrace signal handler for signal %d overwrote " "previous handler.\n", sig); (void)write(STDERR_FILENO, buf, strlen(buf)); } } } #else void InstallStacktraceHandler() {} #endif // defined(TF_GENERATE_STACKTRACE) } // namespace testing } // namespace tensorflow <commit_msg>in resolution of [Wsign-compare] warning id 7<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/platform/platform.h" #if !defined(IS_MOBILE_PLATFORM) && defined(PLATFORM_POSIX) && \ (defined(__clang__) || defined(__GNUC__)) #define TF_GENERATE_STACKTRACE #endif #if defined(TF_GENERATE_STACKTRACE) #include <errno.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #include <string> #include "tensorflow/core/platform/stacktrace.h" #endif // defined(TF_GENERATE_STACKTRACE) namespace tensorflow { namespace testing { #if defined(TF_GENERATE_STACKTRACE) // This function will print stacktrace to STDERR. // It avoids using malloc, so it makes sure to dump the stack even when the heap // is corrupted. However, it can dump mangled symbols. inline void SafePrintStackTrace() { static const char begin_msg[] = "*** BEGIN MANGLED STACK TRACE ***\n"; (void)write(STDERR_FILENO, begin_msg, strlen(begin_msg)); int buffer_size = 128; void *trace[128]; // Run backtrace to get the size of the stacktrace buffer_size = backtrace(trace, buffer_size); // Print a mangled stacktrace to STDERR as safely as possible. backtrace_symbols_fd(trace, buffer_size, STDERR_FILENO); static const char end_msg[] = "*** END MANGLED STACK TRACE ***\n\n"; (void)write(STDERR_FILENO, end_msg, strlen(end_msg)); } static void StacktraceHandler(int sig, siginfo_t *si, void *v) { // Make sure our handler does not deadlock. And this should be the last thing // our program does. Therefore, set a timer to kill the program in 60 // seconds. struct itimerval timer; timer.it_value.tv_sec = 60; timer.it_value.tv_usec = 0; timer.it_interval.tv_sec = 0; timer.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &timer, 0); struct sigaction sa_timeout; memset(&sa_timeout, 0, sizeof(sa_timeout)); sa_timeout.sa_handler = SIG_DFL; sigaction(SIGALRM, &sa_timeout, 0); char buf[128]; snprintf(buf, sizeof(buf), "*** Received signal %d ***\n", sig); (void)write(STDERR_FILENO, buf, strlen(buf)); // Print "a" stack trace, as safely as possible. SafePrintStackTrace(); // Up until this line, we made sure not to allocate memory, to be able to dump // a stack trace even in the event of heap corruption. After this line, we // will try to print more human readable things to the terminal. // But these have a higher probability to fail. std::string stacktrace = CurrentStackTrace(); (void)write(STDERR_FILENO, stacktrace.c_str(), stacktrace.length()); // Abort the program. struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = SIG_DFL; sigaction(SIGABRT, &sa, NULL); abort(); } void InstallStacktraceHandler() { int handled_signals[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE}; size_t array_limit = sizeof(handled_signals) / sizeof(int); for (size_t i = 0; i < array_limit; i++) { int sig = handled_signals[i]; struct sigaction sa; struct sigaction osa; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_SIGINFO | SA_RESETHAND; sa.sa_sigaction = &StacktraceHandler; if (sigaction(sig, &sa, &osa) != 0) { char buf[128]; snprintf(buf, sizeof(buf), "Warning, can't install backtrace signal handler for signal %d, " "errno:%d \n", sig, errno); (void)write(STDERR_FILENO, buf, strlen(buf)); } else if (osa.sa_handler != SIG_DFL) { char buf[128]; snprintf(buf, sizeof(buf), "Warning, backtrace signal handler for signal %d overwrote " "previous handler.\n", sig); (void)write(STDERR_FILENO, buf, strlen(buf)); } } } #else void InstallStacktraceHandler() {} #endif // defined(TF_GENERATE_STACKTRACE) } // namespace testing } // namespace tensorflow <|endoftext|>
<commit_before>#include "../lib/matrix.hpp" #include "../lib/image.hpp" #include "../lib/time.hpp" void conv(matrix &x, const matrix &k) { matrix y; y.create(x.rows + k.rows, x.cols + k.cols); for (unsigned row = 0; row < x.rows; row++) { for (unsigned col = 0; col < x.cols; col++) { auto yrow = row + k.rows / 2; auto ycol = col + k.cols / 2; y(yrow, ycol) = x(row, col); } } // Compute sum of k int weight = 0; for (unsigned row = 0; row < k.rows; row++) { for (unsigned col = 0; col < k.cols; col++) { weight += k(row, col); } } // Do the convolution for (unsigned row = 0; row < x.rows; row++) { for (unsigned col = 0; col < x.cols; col++) { int t = 0; auto yrow = row; for (int krow = k.rows - 1; krow >= 0; krow--, yrow++) { auto ycol = col; for (int kcol = k.cols - 1; kcol >= 0; kcol--, ycol++) { t += y(yrow, ycol) * k(krow, kcol); } } if (weight != 0) { t /= weight; } x(row, col) = t; } } } int binomial_coefficient(int n, int k) { if (n <= 1 || k == 0) { return 1; } else { return binomial_coefficient(n - 1, k - 1) * n / k; } } matrix binomial(int n) { if ((n & 1) == 0) { throw std::invalid_argument("n must be odd"); } matrix x, y; x.create(1, n); y.create(n, 1); for (int i = 0; i < n / 2; i++) { x(0, i) = x(0, n - i - 1) = binomial_coefficient(n - 1, i); y(i, 0) = y(n - i - 1, 0) = binomial_coefficient(n - 1, i); } x(0, n / 2) = binomial_coefficient(n - 1, n / 2); y(n / 2, 0) = binomial_coefficient(n - 1, n / 2); return y * x; } int main(int argc, char **argv) { auto bmp = load_image("C:\\Users\\Joe\\Desktop\\test.jpg"); auto orig = bmp; matrix kernel = binomial(3); auto start = now(); conv(bmp, kernel); auto stop = now(); printf("%g\n", to_seconds(start, stop)); save_png(bmp, "C:\\Users\\Joe\\Desktop\\test.png"); return 0; } <commit_msg>Fix formatting<commit_after>#include "../lib/matrix.hpp" #include "../lib/image.hpp" #include "../lib/time.hpp" void conv(matrix &x, const matrix &k) { matrix y; y.create(x.rows + k.rows, x.cols + k.cols); for (unsigned row = 0; row < x.rows; row++) { for (unsigned col = 0; col < x.cols; col++) { auto yrow = row + k.rows / 2; auto ycol = col + k.cols / 2; y(yrow, ycol) = x(row, col); } } // Compute sum of k int weight = 0; for (unsigned row = 0; row < k.rows; row++) { for (unsigned col = 0; col < k.cols; col++) { weight += k(row, col); } } // Do the convolution for (unsigned row = 0; row < x.rows; row++) { for (unsigned col = 0; col < x.cols; col++) { int t = 0; auto yrow = row; for (int krow = k.rows - 1; krow >= 0; krow--, yrow++) { auto ycol = col; for (int kcol = k.cols - 1; kcol >= 0; kcol--, ycol++) { t += y(yrow, ycol) * k(krow, kcol); } } if (weight != 0) { t /= weight; } x(row, col) = t; } } } int binomial_coefficient(int n, int k) { if (n <= 1 || k == 0) { return 1; } else { return binomial_coefficient(n - 1, k - 1) * n / k; } } matrix binomial(int n) { if ((n & 1) == 0) { throw std::invalid_argument("n must be odd"); } matrix x, y; x.create(1, n); y.create(n, 1); for (int i = 0; i < n / 2; i++) { x(0, i) = x(0, n - i - 1) = binomial_coefficient(n - 1, i); y(i, 0) = y(n - i - 1, 0) = binomial_coefficient(n - 1, i); } x(0, n / 2) = binomial_coefficient(n - 1, n / 2); y(n / 2, 0) = binomial_coefficient(n - 1, n / 2); return y * x; } int main(int argc, char **argv) { auto bmp = load_image("C:\\Users\\Joe\\Desktop\\test.jpg"); auto orig = bmp; matrix kernel = binomial(3); auto start = now(); conv(bmp, kernel); auto stop = now(); printf("%g\n", to_seconds(start, stop)); save_png(bmp, "C:\\Users\\Joe\\Desktop\\test.png"); return 0; } <|endoftext|>
<commit_before>#include "TCP.h" #include "os.h" #include "Endian.h" #if defined( __POSIX__ ) #include <arpa/inet.h> #include <sys/socket.h> #include <string.h> #if !defined( SOCKET_ERROR ) #define SOCKET_ERROR ( -1 ) #endif #elif defined( __WIN_API__ ) #include <WinSock2.h> #endif #if defined( __OS_X__ ) #define INVALID_SOCKET ( -1 ) #endif #ifdef __WIN_API__ typedef int socklen_t; #endif /* ==================== xiTCPListen::CreateOnPort Allocates memory and constructs a TCP listen server socket If it fails, the memory is cleaned up and a nullptr returned ==================== */ xiTCPListen * xiTCPListen::CreateOnPort( const uint16_t port ) { xiTCPListen * const self = new xiTCPListen(); if ( self->status == STATUS_INVALID ) { delete( self ); return nullptr; } if ( !self->BindToPortV4( port ) ) { delete( self ); return nullptr; } self->Grab(); return self; } /* ==================== xiTCPListen::xiTCPListen Protected constructor This is called internally Starts a native TCP socket ==================== */ xiTCPListen::xiTCPListen() { status = STATUS_NOT_BOUND; nativeHandle = OpenNativeSocket( SOCK_STREAM ); if ( nativeHandle == INVALID_SOCKET ) { status = STATUS_INVALID; } } /* ==================== xiTCPListen::~xiTCPListen Protected destructor The parent Protobase class does the important destruction ==================== */ xiTCPListen::~xiTCPListen() { } /* ==================== xiTCPListen::Listen Listens for incoming TCP connections Returns a new xiTCP socket for communicating on new connections ==================== */ xiTCP * xiTCPListen::Listen( addressInfo_s * const senderInfo ) { const int listenStatus = listen( nativeHandle, 1 ); if ( !listenStatus ) { // worked, open connection xiTCP * const newConnection = CreateOnSocket( nativeHandle, senderInfo ); return newConnection; } else { status = STATUS_ERROR; } return nullptr; } /* ==================== xiTCPListen::CreateOnSocket Internally used to construct the listen socket The native handle is given to the method, as opposed to created by the method ==================== */ xiTCP * xiTCPListen::CreateOnSocket( const socketHandle_t _nativeHandle, addressInfo_s * const senderInfo ) { xiTCP * const self = new xiTCP(); self->Accept( _nativeHandle, senderInfo ); if ( self->status == STATUS_INVALID ) { delete( self ); return nullptr; } self->Grab(); return self; } /* ==================== xiTCP::ConnectTo Use this to create a TCP socket for connecting with a TCP listen server The address information of the server is needed for the connection It will attempt the connection and only return a valid pointer if the connection is successful ==================== */ xiTCP * xiTCP::ConnectTo( const addressInfo_s * const listenInfo ) { xiTCP * const self = new xiTCP(); self->nativeHandle = OpenNativeSocket( SOCK_STREAM ); if ( self->nativeHandle == INVALID_SOCKET ) { self->status = STATUS_INVALID; } if ( self->status == STATUS_INVALID ) { delete( self ); return nullptr; } if ( !self->BindToPortV4( 0 ) ) { delete( self ); return nullptr; } const bool isConnected = self->Connect( listenInfo ); if ( !isConnected ) { delete( self ); return nullptr; } self->Grab(); return self; } /* ==================== xiTCP::Accept Used internally when a xiTCP socket is created by a listen server This method is "accepts" the socket as being bound by the listen socket ==================== */ void xiTCP::Accept( const socketHandle_t _nativeHandle, addressInfo_s * const senderInfo ) { sockaddr_in target; socklen_t targetLength = ( int )sizeof( target ); memset( &target, 0, sizeof( target ) ); nativeHandle = accept( _nativeHandle, ( sockaddr * )&target, &targetLength ); if ( nativeHandle == INVALID_SOCKET ) { status = STATUS_INVALID; } else { #ifdef __WIN_API__ senderInfo->address.protocolV4[0] = target.sin_addr.S_un.S_un_b.s_b1; senderInfo->address.protocolV4[1] = target.sin_addr.S_un.S_un_b.s_b2; senderInfo->address.protocolV4[2] = target.sin_addr.S_un.S_un_b.s_b3; senderInfo->address.protocolV4[3] = target.sin_addr.S_un.S_un_b.s_b4; #elif defined( __POSIX__ ) memcpy( &senderInfo->address.protocolV4[0], &target.sin_addr.s_addr, sizeof( target.sin_addr.s_addr ) ); #endif senderInfo->port = ( uint16_t )Endian::NetworkToHostUnsigned( target.sin_port, sizeof( target.sin_port ) ); } } /* ==================== xiTCP::Connect Used internally to start the client to server connection ==================== */ bool xiTCP::Connect( const addressInfo_s * const listenInfo ) { sockaddr_in target; int targetLength = ( int )sizeof( target ); memset( &target, 0, sizeof( target ) ); #ifdef __WIN_API__ target.sin_family = AF_INET; target.sin_addr.S_un.S_un_b.s_b1 = listenInfo->address.protocolV4[0]; target.sin_addr.S_un.S_un_b.s_b2 = listenInfo->address.protocolV4[1]; target.sin_addr.S_un.S_un_b.s_b3 = listenInfo->address.protocolV4[2]; target.sin_addr.S_un.S_un_b.s_b4 = listenInfo->address.protocolV4[3]; #else memcpy( &target.sin_addr.s_addr, &listenInfo->address.protocolV4[0], sizeof( target.sin_addr.s_addr ) ); #endif target.sin_port = ( uint16_t )Endian::HostToNetworkUnsigned( listenInfo->port, sizeof( listenInfo->port ) ); const int connectResult = connect( nativeHandle, ( sockaddr * )&target, targetLength ); if ( connectResult == SOCKET_ERROR ) { return false; } return true; } /* ==================== xiTCP::ReadIntoBuffer Calls the operating system's recv function to read from the TCP connection ==================== */ byteLen_t xiTCP::ReadIntoBuffer( char * const buffer, const int32_t bufferLength ) { return recv( nativeHandle, buffer, bufferLength, 0 ); } /* ==================== xiTCP::SendBuffer Calls the operating system's send function to send a buffer down the connection ==================== */ byteLen_t xiTCP::SendBuffer( const char * const buffer, const int32_t bufferLength ) { return send( nativeHandle, buffer, bufferLength, 0 ); } /* ==================== xiTCP::xiTCP Constructor Defaults a TCP connection as not bound ==================== */ xiTCP::xiTCP() { status = STATUS_NOT_BOUND; } /* ==================== xiTCP::~xiTCP Deconstructor Protobase does the important destruction ==================== */ xiTCP::~xiTCP() { }<commit_msg>Replaced #else defined with #elif to better help compile errors<commit_after>#include "TCP.h" #include "os.h" #include "Endian.h" #if defined( __POSIX__ ) #include <arpa/inet.h> #include <sys/socket.h> #include <string.h> #if !defined( SOCKET_ERROR ) #define SOCKET_ERROR ( -1 ) #endif #elif defined( __WIN_API__ ) #include <WinSock2.h> #endif #if defined( __OS_X__ ) #define INVALID_SOCKET ( -1 ) #endif #if defined( __WIN_API__ ) typedef int socklen_t; #endif /* ==================== xiTCPListen::CreateOnPort Allocates memory and constructs a TCP listen server socket If it fails, the memory is cleaned up and a nullptr returned ==================== */ xiTCPListen * xiTCPListen::CreateOnPort( const uint16_t port ) { xiTCPListen * const self = new xiTCPListen(); if ( self->status == STATUS_INVALID ) { delete( self ); return nullptr; } if ( !self->BindToPortV4( port ) ) { delete( self ); return nullptr; } self->Grab(); return self; } /* ==================== xiTCPListen::xiTCPListen Protected constructor This is called internally Starts a native TCP socket ==================== */ xiTCPListen::xiTCPListen() { status = STATUS_NOT_BOUND; nativeHandle = OpenNativeSocket( SOCK_STREAM ); if ( nativeHandle == INVALID_SOCKET ) { status = STATUS_INVALID; } } /* ==================== xiTCPListen::~xiTCPListen Protected destructor The parent Protobase class does the important destruction ==================== */ xiTCPListen::~xiTCPListen() { } /* ==================== xiTCPListen::Listen Listens for incoming TCP connections Returns a new xiTCP socket for communicating on new connections ==================== */ xiTCP * xiTCPListen::Listen( addressInfo_s * const senderInfo ) { const int listenStatus = listen( nativeHandle, 1 ); if ( !listenStatus ) { // worked, open connection xiTCP * const newConnection = CreateOnSocket( nativeHandle, senderInfo ); return newConnection; } else { status = STATUS_ERROR; } return nullptr; } /* ==================== xiTCPListen::CreateOnSocket Internally used to construct the listen socket The native handle is given to the method, as opposed to created by the method ==================== */ xiTCP * xiTCPListen::CreateOnSocket( const socketHandle_t _nativeHandle, addressInfo_s * const senderInfo ) { xiTCP * const self = new xiTCP(); self->Accept( _nativeHandle, senderInfo ); if ( self->status == STATUS_INVALID ) { delete( self ); return nullptr; } self->Grab(); return self; } /* ==================== xiTCP::ConnectTo Use this to create a TCP socket for connecting with a TCP listen server The address information of the server is needed for the connection It will attempt the connection and only return a valid pointer if the connection is successful ==================== */ xiTCP * xiTCP::ConnectTo( const addressInfo_s * const listenInfo ) { xiTCP * const self = new xiTCP(); self->nativeHandle = OpenNativeSocket( SOCK_STREAM ); if ( self->nativeHandle == INVALID_SOCKET ) { self->status = STATUS_INVALID; } if ( self->status == STATUS_INVALID ) { delete( self ); return nullptr; } if ( !self->BindToPortV4( 0 ) ) { delete( self ); return nullptr; } const bool isConnected = self->Connect( listenInfo ); if ( !isConnected ) { delete( self ); return nullptr; } self->Grab(); return self; } /* ==================== xiTCP::Accept Used internally when a xiTCP socket is created by a listen server This method is "accepts" the socket as being bound by the listen socket ==================== */ void xiTCP::Accept( const socketHandle_t _nativeHandle, addressInfo_s * const senderInfo ) { sockaddr_in target; socklen_t targetLength = ( int )sizeof( target ); memset( &target, 0, sizeof( target ) ); nativeHandle = accept( _nativeHandle, ( sockaddr * )&target, &targetLength ); if ( nativeHandle == INVALID_SOCKET ) { status = STATUS_INVALID; } else { #if defined( __WIN_API__ ) senderInfo->address.protocolV4[0] = target.sin_addr.S_un.S_un_b.s_b1; senderInfo->address.protocolV4[1] = target.sin_addr.S_un.S_un_b.s_b2; senderInfo->address.protocolV4[2] = target.sin_addr.S_un.S_un_b.s_b3; senderInfo->address.protocolV4[3] = target.sin_addr.S_un.S_un_b.s_b4; #elif defined( __POSIX__ ) memcpy( &senderInfo->address.protocolV4[0], &target.sin_addr.s_addr, sizeof( target.sin_addr.s_addr ) ); #endif senderInfo->port = ( uint16_t )Endian::NetworkToHostUnsigned( target.sin_port, sizeof( target.sin_port ) ); } } /* ==================== xiTCP::Connect Used internally to start the client to server connection ==================== */ bool xiTCP::Connect( const addressInfo_s * const listenInfo ) { sockaddr_in target; int targetLength = ( int )sizeof( target ); memset( &target, 0, sizeof( target ) ); #if defined( __WIN_API__ ) target.sin_family = AF_INET; target.sin_addr.S_un.S_un_b.s_b1 = listenInfo->address.protocolV4[0]; target.sin_addr.S_un.S_un_b.s_b2 = listenInfo->address.protocolV4[1]; target.sin_addr.S_un.S_un_b.s_b3 = listenInfo->address.protocolV4[2]; target.sin_addr.S_un.S_un_b.s_b4 = listenInfo->address.protocolV4[3]; #elif defined( __POSIX__ ) memcpy( &target.sin_addr.s_addr, &listenInfo->address.protocolV4[0], sizeof( target.sin_addr.s_addr ) ); #endif target.sin_port = ( uint16_t )Endian::HostToNetworkUnsigned( listenInfo->port, sizeof( listenInfo->port ) ); const int connectResult = connect( nativeHandle, ( sockaddr * )&target, targetLength ); if ( connectResult == SOCKET_ERROR ) { return false; } return true; } /* ==================== xiTCP::ReadIntoBuffer Calls the operating system's recv function to read from the TCP connection ==================== */ byteLen_t xiTCP::ReadIntoBuffer( char * const buffer, const int32_t bufferLength ) { return recv( nativeHandle, buffer, bufferLength, 0 ); } /* ==================== xiTCP::SendBuffer Calls the operating system's send function to send a buffer down the connection ==================== */ byteLen_t xiTCP::SendBuffer( const char * const buffer, const int32_t bufferLength ) { return send( nativeHandle, buffer, bufferLength, 0 ); } /* ==================== xiTCP::xiTCP Constructor Defaults a TCP connection as not bound ==================== */ xiTCP::xiTCP() { status = STATUS_NOT_BOUND; } /* ==================== xiTCP::~xiTCP Deconstructor Protobase does the important destruction ==================== */ xiTCP::~xiTCP() { } <|endoftext|>
<commit_before>#include "DuplicateSession.h" #include <MessageDuplicateDataRequest.pb.h> #include <BlockHub.h> #include <MRT.h> #include <MasterSession.h> #include <MessageSyncBlock.pb.h> DuplicateSession::DuplicateSession() { } DuplicateSession::DuplicateSession( uptr<MessageDuplicateBlock> msg ) { this->message_block_ = move_ptr( msg ); this->path_ = this->message_block_->path(); this->part_id_ = this->message_block_->partid(); this->file_offset_ = this->message_block_->fileoffset(); this->remote_index_ = this->message_block_->index(); this->remote_ip_ = this->message_block_->address(); this->index_ = BlockHub::Instance()->FindBlock( this->path_ , this->part_id_ ); if(this->index_ == nullptr ) this->index_ = BlockHub::Instance()->CreateBlock( (int)this->part_id_ , this->file_offset_ , this->path_ ); Logger::Log( "duplicate session created % part:% size:% from %" , this->index_->Path , this->index_->PartId , this->index_->Size , this->remote_ip_ ); } DuplicateSession::~DuplicateSession() { if ( this->worker_ != nullptr ) { MRT::SyncWorker::Stop( this->worker_ ); } } void DuplicateSession::SendRequest() { uptr<MessageDuplicateDataRequest> message = make_uptr( MessageDuplicateDataRequest ); message->set_index ( this->remote_index_ ); message->set_token ( "" ); message->set_offset ( this->block_offset_ ); message->set_size ( BLOCK_TRANSFER_SIZE ); message->set_sessionid ( this->Id() ); this->SendMessage ( move_ptr( message ) ); RetryTimer (); Logger::Log( "duplicate session send request % part:% size:% from %" , this->index_->Path , this->index_->PartId , this->index_->Size , this->remote_ip_ ); } void DuplicateSession::OnConnect() { } bool DuplicateSession::DuplicateFinish() { return this->finish_; } void DuplicateSession::RetryTimer() { if ( this->worker_ != nullptr ) { MRT::SyncWorker::Stop( this->worker_ ); } this->worker_ = MRT::SyncWorker::Create( 15000 , [] ( MRT::SyncWorker* worker ) { DuplicateSession* session = (DuplicateSession*) worker->Data(); if ( session == nullptr ) return true; session->SendRequest(); return false; } , nullptr , this ); } void DuplicateSession::AcceptBlock( uptr<MessageDuplicateData> msg ) { auto wsize = BlockHub::Instance()->WriteBlock( this->index_->Index , msg->offset() , msg->data().c_str() , msg->data().size() ); this->index_->Size = msg->offset() + wsize; if ( msg->islast() ) { BlockHub::Instance()->SaveBlockIndex( this->index_ ); auto sync = make_uptr ( MessageBlockMeta ); sync->set_fileoffset ( this->index_->FileOffset ); sync->set_index ( this->index_->Index ); sync->set_partid ( this->index_->PartId ); sync->set_path ( this->index_->Path ); sync->set_size ( this->index_->Size ); sync->set_status ( 0 ); MasterSession::Instance ()->SendMessage( move_ptr( sync ) ); Logger::Log( "duplicate path % part:% size:% from %" , this->index_->Path , this->index_->PartId , this->index_->Size , this->remote_ip_ ); if ( this->worker_ != nullptr ) { MRT::SyncWorker::Stop( this->worker_ ); } this->finish_ = true; Logger::Log( "duplicate session close % part:% size:% from %" , this->index_->Path , this->index_->PartId , this->index_->Size , this->remote_ip_ ); this->Close(); return; } this->block_offset_ = msg->offset() + wsize; this->SendRequest(); } <commit_msg>try fix bugs<commit_after>#include "DuplicateSession.h" #include <MessageDuplicateDataRequest.pb.h> #include <BlockHub.h> #include <MRT.h> #include <MasterSession.h> #include <MessageSyncBlock.pb.h> #include <DuplicateConnector.h> DuplicateSession::DuplicateSession() { } DuplicateSession::DuplicateSession( uptr<MessageDuplicateBlock> msg ) { this->message_block_ = move_ptr( msg ); this->path_ = this->message_block_->path(); this->part_id_ = this->message_block_->partid(); this->file_offset_ = this->message_block_->fileoffset(); this->remote_index_ = this->message_block_->index(); this->remote_ip_ = this->message_block_->address(); this->index_ = BlockHub::Instance()->FindBlock( this->path_ , this->part_id_ ); if(this->index_ == nullptr ) this->index_ = BlockHub::Instance()->CreateBlock( (int)this->part_id_ , this->file_offset_ , this->path_ ); Logger::Log( "duplicate session created % part:% size:% from %" , this->index_->Path , this->index_->PartId , this->index_->Size , this->remote_ip_ ); } DuplicateSession::~DuplicateSession() { if ( this->worker_ != nullptr ) { MRT::SyncWorker::Stop( this->worker_ ); } } void DuplicateSession::SendRequest() { uptr<MessageDuplicateDataRequest> message = make_uptr( MessageDuplicateDataRequest ); message->set_index ( this->remote_index_ ); message->set_token ( "" ); message->set_offset ( this->block_offset_ ); message->set_size ( BLOCK_TRANSFER_SIZE ); message->set_sessionid ( this->Id() ); this->SendMessage ( move_ptr( message ) ); RetryTimer (); Logger::Log( "duplicate session send request % part:% size:% from %" , this->index_->Path , this->index_->PartId , this->index_->Size , this->remote_ip_ ); } void DuplicateSession::OnConnect() { } bool DuplicateSession::DuplicateFinish() { return this->finish_; } void DuplicateSession::RetryTimer() { if ( this->worker_ != nullptr ) { MRT::SyncWorker::Stop( this->worker_ ); } this->worker_ = MRT::SyncWorker::Create( 15000 , [] ( MRT::SyncWorker* worker ) { DuplicateSession* session = (DuplicateSession*) worker->Data(); sptr<DuplicateConnector> connector = make_sptr( DuplicateConnector , move_ptr( session->message_block_ ) ); MRT::Maraton::Instance()->Regist( connector ); session->Close(); return false; } , nullptr , this ); } void DuplicateSession::AcceptBlock( uptr<MessageDuplicateData> msg ) { auto wsize = BlockHub::Instance()->WriteBlock( this->index_->Index , msg->offset() , msg->data().c_str() , msg->data().size() ); this->index_->Size = msg->offset() + wsize; if ( msg->islast() ) { BlockHub::Instance()->SaveBlockIndex( this->index_ ); auto sync = make_uptr ( MessageBlockMeta ); sync->set_fileoffset ( this->index_->FileOffset ); sync->set_index ( this->index_->Index ); sync->set_partid ( this->index_->PartId ); sync->set_path ( this->index_->Path ); sync->set_size ( this->index_->Size ); sync->set_status ( 0 ); MasterSession::Instance ()->SendMessage( move_ptr( sync ) ); Logger::Log( "duplicate path % part:% size:% from %" , this->index_->Path , this->index_->PartId , this->index_->Size , this->remote_ip_ ); if ( this->worker_ != nullptr ) { MRT::SyncWorker::Stop( this->worker_ ); } this->finish_ = true; Logger::Log( "duplicate session close % part:% size:% from %" , this->index_->Path , this->index_->PartId , this->index_->Size , this->remote_ip_ ); this->Close(); return; } this->block_offset_ = msg->offset() + wsize; this->SendRequest(); } <|endoftext|>
<commit_before>#include "Base64.h" #include <cassert> static char alphabet1[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static char alphabet2[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; using namespace std; string Base64::encode(const unsigned char * input, size_t length, const char * indent, int max_line_length) { string out; int line_len = 0; if (indent) out += indent; size_t pos = 0, rem = length; for (; rem >= 3; pos += 3, rem -= 3) { unsigned int tmp = (input[pos] << 16) | (input[pos + 1] << 8) | input[pos + 2]; out += alphabet1[(tmp >> 18)]; out += alphabet1[(tmp >> 12) & 0x3f]; out += alphabet1[(tmp >> 6) & 0x3f]; out += alphabet1[tmp & 0x3f ]; line_len += 4; if (max_line_length && line_len >= max_line_length) { out += "\n"; if (indent) out += indent; line_len = 0; } } if (rem == 2) { unsigned int tmp = (input[pos] << 16) | (input[pos + 1] << 8); out += alphabet1[(tmp >> 18)]; out += alphabet1[(tmp >> 12) & 0x3f]; out += alphabet1[(tmp >> 6) & 0x3f]; out += '='; } else if (rem == 1) { unsigned int tmp = (input[pos] << 16); out += alphabet1[(tmp >> 18)]; out += alphabet1[(tmp >> 12) & 0x3f]; out += '='; out += '='; } return out; } unsigned char base64_decode_digit(char c) { switch (c) { case '+': case '-': return 62; case '/': case '_': return 63; default: if (isdigit(c)) return (unsigned char)(c - '0' + 26 + 26); else if (islower(c)) return (unsigned char)(c - 'a' + 26); else if (isupper(c)) return (unsigned char)(c - 'A'); else assert(0); } return 0xff; } unsigned long long Base64::decode64BitId(const std::string & input) { unsigned long long n = 0; for (unsigned int i = 0; i < input.size(); i++) { int c = base64_decode_digit(input[i]); n = 64 * n + c; } return n; } string Base64::encode64BitId(unsigned long long a) { string s; while (a) { int b = a & 63; a = a >> 6; s = alphabet2[b] + s; } return s; } <commit_msg>add inline<commit_after>#include "Base64.h" #include <cassert> static char alphabet1[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static char alphabet2[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; using namespace std; string Base64::encode(const unsigned char * input, size_t length, const char * indent, int max_line_length) { string out; int line_len = 0; if (indent) out += indent; size_t pos = 0, rem = length; for (; rem >= 3; pos += 3, rem -= 3) { unsigned int tmp = (input[pos] << 16) | (input[pos + 1] << 8) | input[pos + 2]; out += alphabet1[(tmp >> 18)]; out += alphabet1[(tmp >> 12) & 0x3f]; out += alphabet1[(tmp >> 6) & 0x3f]; out += alphabet1[tmp & 0x3f ]; line_len += 4; if (max_line_length && line_len >= max_line_length) { out += "\n"; if (indent) out += indent; line_len = 0; } } if (rem == 2) { unsigned int tmp = (input[pos] << 16) | (input[pos + 1] << 8); out += alphabet1[(tmp >> 18)]; out += alphabet1[(tmp >> 12) & 0x3f]; out += alphabet1[(tmp >> 6) & 0x3f]; out += '='; } else if (rem == 1) { unsigned int tmp = (input[pos] << 16); out += alphabet1[(tmp >> 18)]; out += alphabet1[(tmp >> 12) & 0x3f]; out += '='; out += '='; } return out; } static inline unsigned char base64_decode_digit(char c) { switch (c) { case '+': case '-': return 62; case '/': case '_': return 63; default: if (isdigit(c)) return (unsigned char)(c - '0' + 26 + 26); else if (islower(c)) return (unsigned char)(c - 'a' + 26); else if (isupper(c)) return (unsigned char)(c - 'A'); else assert(0); } return 0xff; } unsigned long long Base64::decode64BitId(const std::string & input) { unsigned long long n = 0; for (unsigned int i = 0; i < input.size(); i++) { int c = base64_decode_digit(input[i]); n = 64 * n + c; } return n; } string Base64::encode64BitId(unsigned long long a) { string s; while (a) { int b = a & 63; a = a >> 6; s = alphabet2[b] + s; } return s; } <|endoftext|>
<commit_before>#include <math.h> #include <stdio.h> #include <ratio> #include "pyramid.h" #include "HalideBuffer.h" #include <vector> using std::vector; using namespace Halide; template<bool B, typename T> struct cond { static constexpr bool value = B; using type = T; }; template <typename First, typename... Rest> struct select : std::conditional<First::value, First, typename select<Rest...>::type> { }; template<typename First> struct select<First> { //static_assert(T::value, "No case of select was chosen"); using type = std::conditional<First::value, typename First::type, void>; }; template<int a> struct tester : public select<cond<a == 0, std::ratio<1, 2>>, cond<a == 1, std::ratio<3, 2>>, cond<a == 2, std::ratio<7, 2>>>::type {}; int main(int argc, char **argv) { Image<float> input(1024, 1024); using T0 = tester<0>::type; printf("t0 %d %d\n", (int)T0::num, (int)T0::den); using T1 = tester<1>::type; printf("t0 %d %d\n", (int)T1::num, (int)T1::den); using T2 = tester<2>::type; printf("t0 %d %d\n", (int)T2::num, (int)T2::den); //using T3 = tester<3>::type; printf("t0 %d %d\n", (int)T3::num, (int)T3::den); // Put some junk in the input. Keep it to small integers so the float averaging stays exact. for (int y = 0; y < input.height(); y++) { for (int x = 0; x < input.width(); x++) { input(x, y) = ((x * 17 + y)/8) % 32; } } vector<Image<float>> levels(10); for (int l = 0; l < 10; l++) { levels[l] = Image<float>(1024 >> l, 1024 >> l); } // Will throw a compiler error if we didn't compile the generator with 10 levels. pyramid(input, levels[0], levels[1], levels[2], levels[3], levels[4], levels[5], levels[6], levels[7], levels[8], levels[9]); // The bottom level should be the input for (int y = 0; y < input.height(); y++) { for (int x = 0; x < input.width(); x++) { if (input(x, y) != levels[0](x, y)) { printf("input(%d, %d) = %f, but levels[0](%d, %d) = %f\n", x, y, input(x, y), x, y, levels[0](x, y)); return -1; } } } // The remaining levels should be averaging of the levels above them. for (int l = 1; l < 10; l++) { for (int y = 0; y < input.height() >> l; y++) { for (int x = 0; x < input.width() >> l; x++) { float correct = (levels[l-1](2*x, 2*y) + levels[l-1](2*x+1, 2*y) + levels[l-1](2*x, 2*y+1) + levels[l-1](2*x+1, 2*y+1))/4; float actual = levels[l](x, y); if (correct != actual) { printf("levels[%d](%d, %d) = %f instead of %f\n", l, x, y, actual, correct); return -1; } } } } printf("Success!\n"); return 0; } <commit_msg>remove scalpel left in patient<commit_after>#include <math.h> #include <stdio.h> #include "pyramid.h" #include "HalideBuffer.h" #include <vector> using std::vector; using namespace Halide; int main(int argc, char **argv) { Image<float> input(1024, 1024); // Put some junk in the input. Keep it to small integers so the float averaging stays exact. for (int y = 0; y < input.height(); y++) { for (int x = 0; x < input.width(); x++) { input(x, y) = ((x * 17 + y)/8) % 32; } } vector<Image<float>> levels(10); for (int l = 0; l < 10; l++) { levels[l] = Image<float>(1024 >> l, 1024 >> l); } // Will throw a compiler error if we didn't compile the generator with 10 levels. pyramid(input, levels[0], levels[1], levels[2], levels[3], levels[4], levels[5], levels[6], levels[7], levels[8], levels[9]); // The bottom level should be the input for (int y = 0; y < input.height(); y++) { for (int x = 0; x < input.width(); x++) { if (input(x, y) != levels[0](x, y)) { printf("input(%d, %d) = %f, but levels[0](%d, %d) = %f\n", x, y, input(x, y), x, y, levels[0](x, y)); return -1; } } } // The remaining levels should be averaging of the levels above them. for (int l = 1; l < 10; l++) { for (int y = 0; y < input.height() >> l; y++) { for (int x = 0; x < input.width() >> l; x++) { float correct = (levels[l-1](2*x, 2*y) + levels[l-1](2*x+1, 2*y) + levels[l-1](2*x, 2*y+1) + levels[l-1](2*x+1, 2*y+1))/4; float actual = levels[l](x, y); if (correct != actual) { printf("levels[%d](%d, %d) = %f instead of %f\n", l, x, y, actual, correct); return -1; } } } } printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: addrdlg.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 17:14:38 $ * * 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 _ADDRDLG_HXX #define _ADDRDLG_HXX #ifndef _BASEDLGS_HXX //autogen #include <sfx2/basedlgs.hxx> #endif class SwAddrDlg : public SfxSingleTabDialog { public: SwAddrDlg( Window* pParent, SfxItemSet& rSet ); ~SwAddrDlg(); }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1462); FILE MERGED 2005/09/05 13:44:55 rt 1.1.1.1.1462.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: addrdlg.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 08:58:21 $ * * 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 _ADDRDLG_HXX #define _ADDRDLG_HXX #ifndef _BASEDLGS_HXX //autogen #include <sfx2/basedlgs.hxx> #endif class SwAddrDlg : public SfxSingleTabDialog { public: SwAddrDlg( Window* pParent, SfxItemSet& rSet ); ~SwAddrDlg(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: colwd.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2003-04-17 15:45:41 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SVX_DLGUTIL_HXX //autogen #include <svx/dlgutil.hxx> #endif #ifndef _COLWD_HXX #include <colwd.hxx> #endif #ifndef _TABLEMGR_HXX #include <tablemgr.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _WDOCSH_HXX #include <wdocsh.hxx> #endif #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _SWMODULE_HXX #include <swmodule.hxx> #endif #ifndef _MODCFG_HXX #include <modcfg.hxx> #endif #ifndef _USRPREF_HXX #include <usrpref.hxx> #endif #ifndef _CMDID_H #include <cmdid.h> #endif #ifndef _COLWD_HRC #include <colwd.hrc> #endif #ifndef _TABLE_HRC #include <table.hrc> #endif IMPL_LINK_INLINE_START( SwTableWidthDlg, LoseFocusHdl, Edit *, EMPTYARG ) { USHORT nId = (USHORT)aColEdit.GetValue()-1; const SwTwips lWidth = rFnc.GetColWidth(nId); aWidthEdit.SetValue(aWidthEdit.Normalize(lWidth), FUNIT_TWIP); aWidthEdit.SetMax(aWidthEdit.Normalize(rFnc.GetMaxColWidth(nId)), FUNIT_TWIP); return 0; } IMPL_LINK_INLINE_END( SwTableWidthDlg, LoseFocusHdl, Edit *, EMPTYARG ) SwTableWidthDlg::SwTableWidthDlg(Window *pParent, SwTableFUNC &rTableFnc ) : SvxStandardDialog( pParent, SW_RES(DLG_COL_WIDTH) ), aColFT(this, SW_RES(FT_COL)), aColEdit(this, SW_RES(ED_COL)), aWidthFT(this, SW_RES(FT_WIDTH)), aWidthEdit(this, SW_RES(ED_WIDTH)), aWidthFL(this, SW_RES(FL_WIDTH)), aOKBtn(this, SW_RES(BT_OK)), aCancelBtn(this, SW_RES(BT_CANCEL)), aHelpBtn(this, SW_RES(BT_HELP)), rFnc(rTableFnc) { FreeResource(); BOOL bIsWeb = rTableFnc.GetShell() ? 0 != PTR_CAST( SwWebDocShell, rTableFnc.GetShell()->GetView().GetDocShell() ) : FALSE; FieldUnit eFieldUnit = SW_MOD()->GetUsrPref( bIsWeb )->GetMetric(); ::SetFieldUnit(aWidthEdit, eFieldUnit ); aColEdit.SetValue( rFnc.GetCurColNum() +1 ); aWidthEdit.SetMin(aWidthEdit.Normalize(MINLAY), FUNIT_TWIP); if(!aWidthEdit.GetMin()) aWidthEdit.SetMin(1); if(rFnc.GetColCount() == 0) aWidthEdit.SetMin(aWidthEdit.Normalize(rFnc.GetColWidth(0)), FUNIT_TWIP); aColEdit.SetMax(rFnc.GetColCount() +1 ); aColEdit.SetModifyHdl(LINK(this,SwTableWidthDlg, LoseFocusHdl)); LoseFocusHdl(); } void SwTableWidthDlg::Apply() { rFnc.InitTabCols(); rFnc.SetColWidth( aColEdit.GetValue()-1, aWidthEdit.Denormalize(aWidthEdit.GetValue(FUNIT_TWIP))); } <commit_msg>INTEGRATION: CWS tune03 (1.6.580); FILE MERGED 2004/07/19 19:11:42 mhu 1.6.580.1: #i29979# Added SW_DLLPUBLIC/PRIVATE (see swdllapi.h) to exported symbols/classes.<commit_after>/************************************************************************* * * $RCSfile: colwd.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2004-08-23 09:08:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #pragma hdrstop #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SVX_DLGUTIL_HXX //autogen #include <svx/dlgutil.hxx> #endif #ifndef _COLWD_HXX #include <colwd.hxx> #endif #ifndef _TABLEMGR_HXX #include <tablemgr.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _WDOCSH_HXX #include <wdocsh.hxx> #endif #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _SWMODULE_HXX #include <swmodule.hxx> #endif #ifndef _MODCFG_HXX #include <modcfg.hxx> #endif #ifndef _USRPREF_HXX #include <usrpref.hxx> #endif #ifndef _CMDID_H #include <cmdid.h> #endif #ifndef _COLWD_HRC #include <colwd.hrc> #endif #ifndef _TABLE_HRC #include <table.hrc> #endif IMPL_LINK_INLINE_START( SwTableWidthDlg, LoseFocusHdl, Edit *, EMPTYARG ) { USHORT nId = (USHORT)aColEdit.GetValue()-1; const SwTwips lWidth = rFnc.GetColWidth(nId); aWidthEdit.SetValue(aWidthEdit.Normalize(lWidth), FUNIT_TWIP); aWidthEdit.SetMax(aWidthEdit.Normalize(rFnc.GetMaxColWidth(nId)), FUNIT_TWIP); return 0; } IMPL_LINK_INLINE_END( SwTableWidthDlg, LoseFocusHdl, Edit *, EMPTYARG ) SwTableWidthDlg::SwTableWidthDlg(Window *pParent, SwTableFUNC &rTableFnc ) : SvxStandardDialog( pParent, SW_RES(DLG_COL_WIDTH) ), aColFT(this, SW_RES(FT_COL)), aColEdit(this, SW_RES(ED_COL)), aWidthFT(this, SW_RES(FT_WIDTH)), aWidthEdit(this, SW_RES(ED_WIDTH)), aWidthFL(this, SW_RES(FL_WIDTH)), aOKBtn(this, SW_RES(BT_OK)), aCancelBtn(this, SW_RES(BT_CANCEL)), aHelpBtn(this, SW_RES(BT_HELP)), rFnc(rTableFnc) { FreeResource(); BOOL bIsWeb = rTableFnc.GetShell() ? 0 != PTR_CAST( SwWebDocShell, rTableFnc.GetShell()->GetView().GetDocShell() ) : FALSE; FieldUnit eFieldUnit = SW_MOD()->GetUsrPref( bIsWeb )->GetMetric(); ::SetFieldUnit(aWidthEdit, eFieldUnit ); aColEdit.SetValue( rFnc.GetCurColNum() +1 ); aWidthEdit.SetMin(aWidthEdit.Normalize(MINLAY), FUNIT_TWIP); if(!aWidthEdit.GetMin()) aWidthEdit.SetMin(1); if(rFnc.GetColCount() == 0) aWidthEdit.SetMin(aWidthEdit.Normalize(rFnc.GetColWidth(0)), FUNIT_TWIP); aColEdit.SetMax(rFnc.GetColCount() +1 ); aColEdit.SetModifyHdl(LINK(this,SwTableWidthDlg, LoseFocusHdl)); LoseFocusHdl(); } void SwTableWidthDlg::Apply() { rFnc.InitTabCols(); rFnc.SetColWidth( aColEdit.GetValue()-1, aWidthEdit.Denormalize(aWidthEdit.GetValue(FUNIT_TWIP))); } <|endoftext|>
<commit_before>#include "nanocv.h" #include "models/forward_network.h" #include <boost/program_options.hpp> #include <set> using namespace ncv; static void test_grad_params( const string_t& header, const string_t& loss_id, const model_t& model, accumulator_t& acc_params) { random_t<size_t> rand(2, 16); const size_t n_tests = 64; const size_t n_samples = rand(); const rloss_t rloss = loss_manager_t::instance().get(loss_id); const loss_t& loss = *rloss; const size_t psize = model.psize(); const size_t isize = model.isize(); const size_t osize = model.osize(); vector_t params(psize); vectors_t targets(n_samples, vector_t(osize)); tensors_t inputs(n_samples, tensor_t(model.idims(), model.irows(), model.icols())); // optimization problem (wrt parameters & inputs): size auto fn_params_size = [&] () { return psize; }; // optimization problem (wrt parameters & inputs): function value auto fn_params_fval = [&] (const vector_t& x) { acc_params.reset(x); acc_params.update(inputs, targets, loss); return acc_params.value(); }; // optimization problem (wrt parameters & inputs): function value & gradient auto fn_params_grad = [&] (const vector_t& x, vector_t& gx) { acc_params.reset(x); acc_params.update(inputs, targets, loss); gx = acc_params.vgrad(); return acc_params.value(); }; // construct optimization problem: analytic gradient and finite difference approximation const opt_problem_t problem_analytic_params(fn_params_size, fn_params_fval, fn_params_grad); const opt_problem_t problem_aproxdif_params(fn_params_size, fn_params_fval); for (size_t t = 0; t < n_tests; t ++) { random_t<scalar_t> prgen(-1.0, +1.0); random_t<scalar_t> irgen(-0.1, +0.1); random_t<size_t> trgen(0, osize - 1); prgen(params.data(), params.data() + psize); for (vector_t& target : targets) { target = ncv::class_target(trgen(), osize); } for (tensor_t& input : inputs) { irgen(input.data(), input.data() + isize); } vector_t analytic_params_grad, aproxdif_params_grad; problem_analytic_params(params, analytic_params_grad); problem_aproxdif_params(params, aproxdif_params_grad); const scalar_t dg_params = (analytic_params_grad - aproxdif_params_grad).lpNorm<Eigen::Infinity>(); const bool ok = math::almost_equal(dg_params, scalar_t(0)); log_info() << header << " [" << (t + 1) << "/" << n_tests << "]: samples = " << n_samples << ", dg_params = " << dg_params << " (" << (ok ? "ERROR" : "OK") << ")."; } } static void test_grad_inputs(const string_t& header, const string_t& loss_id, const model_t& model) { rmodel_t rmodel_inputs = model.clone(); const size_t n_tests = 64; const size_t n_samples = rand(); const rloss_t rloss = loss_manager_t::instance().get(loss_id); const loss_t& loss = *rloss; const size_t psize = model.psize(); const size_t isize = model.isize(); const size_t osize = model.osize(); vector_t params(psize); vector_t target(osize); tensor_t input(model.idims(), model.irows(), model.icols()); // optimization problem (wrt parameters & inputs): size auto fn_inputs_size = [&] () { return isize; }; // optimization problem (wrt parameters & inputs): function value auto fn_inputs_fval = [&] (const vector_t& x) { rmodel_inputs->load_params(params); const vector_t output = rmodel_inputs->output(x).vector(); return loss.value(target, output); }; // optimization problem (wrt parameters & inputs): function value & gradient auto fn_inputs_grad = [&] (const vector_t& x, vector_t& gx) { rmodel_inputs->load_params(params); const vector_t output = rmodel_inputs->output(x).vector(); gx = rmodel_inputs->igrad(loss.vgrad(target, output)).vector(); return loss.value(target, output); }; // construct optimization problem: analytic gradient and finite difference approximation const opt_problem_t problem_analytic_inputs(fn_inputs_size, fn_inputs_fval, fn_inputs_grad); const opt_problem_t problem_aproxdif_inputs(fn_inputs_size, fn_inputs_fval); for (size_t t = 0; t < n_tests; t ++) { random_t<scalar_t> prgen(-1.0, +1.0); random_t<scalar_t> irgen(-0.1, +0.1); random_t<size_t> trgen(0, osize - 1); prgen(params.data(), params.data() + psize); target = ncv::class_target(trgen(), osize); irgen(input.data(), input.data() + isize); vector_t analytic_inputs_grad, aproxdif_inputs_grad; problem_analytic_inputs(input.vector(), analytic_inputs_grad); problem_aproxdif_inputs(input.vector(), aproxdif_inputs_grad); const scalar_t dg_inputs = (analytic_inputs_grad - aproxdif_inputs_grad).lpNorm<Eigen::Infinity>(); const scalar_t eps = 1e-6; log_info() << header << " [" << (t + 1) << "/" << n_tests << "]: samples = " << n_samples << ", dg_inputs = " << dg_inputs << " (" << (dg_inputs > eps ? "ERROR" : "OK") << ")."; } } static void test_grad(const string_t& header, const string_t& loss_id, const model_t& model) { // check all criteria const strings_t criteria = criterion_manager_t::instance().ids(); for (const string_t& criterion : criteria) { random_t<size_t> rand(2, 16); const size_t n_threads = 1 + (rand() % 2); accumulator_t acc_params(model, n_threads, criterion, criterion_t::type::vgrad, 1.0); test_grad_params(header + "[criterion = " + criterion + "]", loss_id, model, acc_params); } // check gradients wrt the input test_grad_inputs(header, loss_id, model); } int main(int argc, char *argv[]) { ncv::init(); const strings_t conv_layer_ids { "", "conv" }; const strings_t pool_layer_ids { "", "pool-max", "pool-min", "pool-avg" }; const strings_t full_layer_ids { "", "linear" }; const strings_t actv_layer_ids { "", "act-unit", "act-tanh", "act-snorm", "act-splus" }; const strings_t loss_ids = loss_manager_t::instance().ids(); const color_mode cmd_color = color_mode::luma; const size_t cmd_irows = 10; const size_t cmd_icols = 10; const size_t cmd_outputs = 4; const size_t cmd_max_layers = 2; // evaluate the analytical gradient vs. the finite difference approximation for various: // * convolution layers // * pooling layers // * fully connected layers // * activation layers std::set<string_t> descs; for (size_t n_layers = 0; n_layers <= cmd_max_layers; n_layers ++) { for (const string_t& actv_layer_id : actv_layer_ids) { for (const string_t& pool_layer_id : pool_layer_ids) { for (const string_t& conv_layer_id : conv_layer_ids) { for (const string_t& full_layer_id : full_layer_ids) { string_t desc; // convolution part for (size_t l = 0; l < n_layers && !conv_layer_id.empty(); l ++) { random_t<size_t> rgen(2, 3); string_t params; params += "dims=" + text::to_string(rgen()); params += (rgen() % 2 == 0) ? ",rows=3,cols=3" : ",rows=4,cols=4"; desc += conv_layer_id + ":" + params + ";"; desc += pool_layer_id + ";"; desc += actv_layer_id + ";"; } // fully-connected part for (size_t l = 0; l < n_layers && !full_layer_id.empty(); l ++) { random_t<size_t> rgen(1, 8); string_t params; params += "dims=" + text::to_string(rgen()); desc += full_layer_id + ":" + params + ";"; desc += actv_layer_id + ";"; } desc += "linear:dims=" + text::to_string(cmd_outputs) + ";"; desc += "softmax:type=global;"; descs.insert(desc); } } } } } for (const string_t& desc : descs) { // create network forward_network_t network(desc); network.resize(cmd_irows, cmd_icols, cmd_outputs, cmd_color, true); // test network for (const string_t& loss_id : loss_ids) { test_grad("[loss = " + loss_id + "]", loss_id, network); } } // OK log_info() << done; return EXIT_SUCCESS; } <commit_msg>fix logging message<commit_after>#include "nanocv.h" #include "models/forward_network.h" #include <boost/program_options.hpp> #include <set> using namespace ncv; static void test_grad_params( const string_t& header, const string_t& loss_id, const model_t& model, accumulator_t& acc_params) { random_t<size_t> rand(2, 16); const size_t n_tests = 64; const size_t n_samples = rand(); const rloss_t rloss = loss_manager_t::instance().get(loss_id); const loss_t& loss = *rloss; const size_t psize = model.psize(); const size_t isize = model.isize(); const size_t osize = model.osize(); vector_t params(psize); vectors_t targets(n_samples, vector_t(osize)); tensors_t inputs(n_samples, tensor_t(model.idims(), model.irows(), model.icols())); // optimization problem (wrt parameters & inputs): size auto fn_params_size = [&] () { return psize; }; // optimization problem (wrt parameters & inputs): function value auto fn_params_fval = [&] (const vector_t& x) { acc_params.reset(x); acc_params.update(inputs, targets, loss); return acc_params.value(); }; // optimization problem (wrt parameters & inputs): function value & gradient auto fn_params_grad = [&] (const vector_t& x, vector_t& gx) { acc_params.reset(x); acc_params.update(inputs, targets, loss); gx = acc_params.vgrad(); return acc_params.value(); }; // construct optimization problem: analytic gradient and finite difference approximation const opt_problem_t problem_analytic_params(fn_params_size, fn_params_fval, fn_params_grad); const opt_problem_t problem_aproxdif_params(fn_params_size, fn_params_fval); for (size_t t = 0; t < n_tests; t ++) { random_t<scalar_t> prgen(-1.0, +1.0); random_t<scalar_t> irgen(-0.1, +0.1); random_t<size_t> trgen(0, osize - 1); prgen(params.data(), params.data() + psize); for (vector_t& target : targets) { target = ncv::class_target(trgen(), osize); } for (tensor_t& input : inputs) { irgen(input.data(), input.data() + isize); } vector_t analytic_params_grad, aproxdif_params_grad; problem_analytic_params(params, analytic_params_grad); problem_aproxdif_params(params, aproxdif_params_grad); const scalar_t dg_params = (analytic_params_grad - aproxdif_params_grad).lpNorm<Eigen::Infinity>(); const bool ok = math::almost_equal(dg_params, scalar_t(0)); log_info() << header << " [" << (t + 1) << "/" << n_tests << "]: samples = " << n_samples << ", dg_params = " << dg_params << " (" << (ok ? "OK" : "ERROR") << ")."; } } static void test_grad_inputs(const string_t& header, const string_t& loss_id, const model_t& model) { rmodel_t rmodel_inputs = model.clone(); const size_t n_tests = 64; const size_t n_samples = rand(); const rloss_t rloss = loss_manager_t::instance().get(loss_id); const loss_t& loss = *rloss; const size_t psize = model.psize(); const size_t isize = model.isize(); const size_t osize = model.osize(); vector_t params(psize); vector_t target(osize); tensor_t input(model.idims(), model.irows(), model.icols()); // optimization problem (wrt parameters & inputs): size auto fn_inputs_size = [&] () { return isize; }; // optimization problem (wrt parameters & inputs): function value auto fn_inputs_fval = [&] (const vector_t& x) { rmodel_inputs->load_params(params); const vector_t output = rmodel_inputs->output(x).vector(); return loss.value(target, output); }; // optimization problem (wrt parameters & inputs): function value & gradient auto fn_inputs_grad = [&] (const vector_t& x, vector_t& gx) { rmodel_inputs->load_params(params); const vector_t output = rmodel_inputs->output(x).vector(); gx = rmodel_inputs->igrad(loss.vgrad(target, output)).vector(); return loss.value(target, output); }; // construct optimization problem: analytic gradient and finite difference approximation const opt_problem_t problem_analytic_inputs(fn_inputs_size, fn_inputs_fval, fn_inputs_grad); const opt_problem_t problem_aproxdif_inputs(fn_inputs_size, fn_inputs_fval); for (size_t t = 0; t < n_tests; t ++) { random_t<scalar_t> prgen(-1.0, +1.0); random_t<scalar_t> irgen(-0.1, +0.1); random_t<size_t> trgen(0, osize - 1); prgen(params.data(), params.data() + psize); target = ncv::class_target(trgen(), osize); irgen(input.data(), input.data() + isize); vector_t analytic_inputs_grad, aproxdif_inputs_grad; problem_analytic_inputs(input.vector(), analytic_inputs_grad); problem_aproxdif_inputs(input.vector(), aproxdif_inputs_grad); const scalar_t dg_inputs = (analytic_inputs_grad - aproxdif_inputs_grad).lpNorm<Eigen::Infinity>(); const scalar_t eps = 1e-6; log_info() << header << " [" << (t + 1) << "/" << n_tests << "]: samples = " << n_samples << ", dg_inputs = " << dg_inputs << " (" << (dg_inputs > eps ? "ERROR" : "OK") << ")."; } } static void test_grad(const string_t& header, const string_t& loss_id, const model_t& model) { // check all criteria const strings_t criteria = criterion_manager_t::instance().ids(); for (const string_t& criterion : criteria) { random_t<size_t> rand(2, 16); const size_t n_threads = 1 + (rand() % 2); accumulator_t acc_params(model, n_threads, criterion, criterion_t::type::vgrad, 1.0); test_grad_params(header + "[criterion = " + criterion + "]", loss_id, model, acc_params); } // check gradients wrt the input test_grad_inputs(header, loss_id, model); } int main(int argc, char *argv[]) { ncv::init(); const strings_t conv_layer_ids { "", "conv" }; const strings_t pool_layer_ids { "", "pool-max", "pool-min", "pool-avg" }; const strings_t full_layer_ids { "", "linear" }; const strings_t actv_layer_ids { "", "act-unit", "act-tanh", "act-snorm", "act-splus" }; const strings_t loss_ids = loss_manager_t::instance().ids(); const color_mode cmd_color = color_mode::luma; const size_t cmd_irows = 10; const size_t cmd_icols = 10; const size_t cmd_outputs = 4; const size_t cmd_max_layers = 2; // evaluate the analytical gradient vs. the finite difference approximation for various: // * convolution layers // * pooling layers // * fully connected layers // * activation layers std::set<string_t> descs; for (size_t n_layers = 0; n_layers <= cmd_max_layers; n_layers ++) { for (const string_t& actv_layer_id : actv_layer_ids) { for (const string_t& pool_layer_id : pool_layer_ids) { for (const string_t& conv_layer_id : conv_layer_ids) { for (const string_t& full_layer_id : full_layer_ids) { string_t desc; // convolution part for (size_t l = 0; l < n_layers && !conv_layer_id.empty(); l ++) { random_t<size_t> rgen(2, 3); string_t params; params += "dims=" + text::to_string(rgen()); params += (rgen() % 2 == 0) ? ",rows=3,cols=3" : ",rows=4,cols=4"; desc += conv_layer_id + ":" + params + ";"; desc += pool_layer_id + ";"; desc += actv_layer_id + ";"; } // fully-connected part for (size_t l = 0; l < n_layers && !full_layer_id.empty(); l ++) { random_t<size_t> rgen(1, 8); string_t params; params += "dims=" + text::to_string(rgen()); desc += full_layer_id + ":" + params + ";"; desc += actv_layer_id + ";"; } desc += "linear:dims=" + text::to_string(cmd_outputs) + ";"; desc += "softmax:type=global;"; descs.insert(desc); } } } } } for (const string_t& desc : descs) { // create network forward_network_t network(desc); network.resize(cmd_irows, cmd_icols, cmd_outputs, cmd_color, true); // test network for (const string_t& loss_id : loss_ids) { test_grad("[loss = " + loss_id + "]", loss_id, network); } } // OK log_info() << done; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/irange.hpp> #include <seastar/util/defer.hh> #include <seastar/core/app-template.hh> #include <seastar/core/thread.hh> #include "partition_slice_builder.hh" #include "schema_builder.hh" #include "memtable.hh" #include "row_cache.hh" #include "frozen_mutation.hh" #include "test/lib/tmpdir.hh" #include "sstables/sstables.hh" #include "canonical_mutation.hh" #include "test/lib/sstable_utils.hh" #include "test/lib/test_services.hh" #include "test/lib/sstable_test_env.hh" class size_calculator { class nest { public: static thread_local int level; nest() { ++level; } ~nest() { --level; } }; static std::string prefix() { std::string s(" "); for (int i = 0; i < nest::level; ++i) { s += "-- "; } return s; } public: static void print_cache_entry_size() { std::cout << prefix() << "sizeof(cache_entry) = " << sizeof(cache_entry) << "\n"; { nest n; std::cout << prefix() << "sizeof(decorated_key) = " << sizeof(dht::decorated_key) << "\n"; std::cout << prefix() << "sizeof(cache_link_type) = " << sizeof(cache_entry::cache_link_type) << "\n"; print_mutation_partition_size(); } std::cout << "\n"; std::cout << prefix() << "sizeof(rows_entry) = " << sizeof(rows_entry) << "\n"; std::cout << prefix() << "sizeof(lru_link_type) = " << sizeof(rows_entry::lru_link_type) << "\n"; std::cout << prefix() << "sizeof(deletable_row) = " << sizeof(deletable_row) << "\n"; std::cout << prefix() << "sizeof(row) = " << sizeof(row) << "\n"; std::cout << prefix() << "sizeof(atomic_cell_or_collection) = " << sizeof(atomic_cell_or_collection) << "\n"; } static void print_mutation_partition_size() { std::cout << prefix() << "sizeof(mutation_partition) = " << sizeof(mutation_partition) << "\n"; { nest n; std::cout << prefix() << "sizeof(_static_row) = " << sizeof(mutation_partition::_static_row) << "\n"; std::cout << prefix() << "sizeof(_rows) = " << sizeof(mutation_partition::_rows) << "\n"; std::cout << prefix() << "sizeof(_row_tombstones) = " << sizeof(mutation_partition::_row_tombstones) << "\n"; } } }; thread_local int size_calculator::nest::level = 0; static schema_ptr cassandra_stress_schema() { return schema_builder("ks", "cf") .with_column("KEY", bytes_type, column_kind::partition_key) .with_column("C0", bytes_type) .with_column("C1", bytes_type) .with_column("C2", bytes_type) .with_column("C3", bytes_type) .with_column("C4", bytes_type) .build(); } [[gnu::unused]] static mutation make_cs_mutation() { auto s = cassandra_stress_schema(); mutation m(s, partition_key::from_single_value(*s, bytes_type->from_string("4b343050393536353531"))); for (auto&& col : s->regular_columns()) { m.set_clustered_cell(clustering_key::make_empty(), col, atomic_cell::make_live(*bytes_type, 1, bytes_type->from_string("8f75da6b3dcec90c8a404fb9a5f6b0621e62d39c69ba5758e5f41b78311fbb26cc7a"))); } return m; } bytes random_bytes(size_t size) { bytes result(bytes::initialized_later(), size); for (size_t i = 0; i < size; ++i) { result[i] = std::rand() % std::numeric_limits<uint8_t>::max(); } return result; } sstring random_string(size_t size) { sstring result = uninitialized_string(size); static const char chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (size_t i = 0; i < size; ++i) { result[i] = chars[std::rand() % sizeof(chars)]; } return result; } struct mutation_settings { size_t column_count; size_t column_name_size; size_t row_count; size_t partition_key_size; size_t clustering_key_size; size_t data_size; }; static mutation make_mutation(mutation_settings settings) { auto builder = schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key); for (size_t i = 0; i < settings.column_count; ++i) { builder.with_column(to_bytes(random_string(settings.column_name_size)), bytes_type); } auto s = builder.build(); mutation m(s, partition_key::from_single_value(*s, bytes_type->decompose(data_value(random_bytes(settings.partition_key_size))))); for (size_t i = 0; i < settings.row_count; ++i) { auto ck = clustering_key::from_single_value(*s, bytes_type->decompose(data_value(random_bytes(settings.clustering_key_size)))); for (auto&& col : s->regular_columns()) { m.set_clustered_cell(ck, col, atomic_cell::make_live(*bytes_type, 1, bytes_type->decompose(data_value(random_bytes(settings.data_size))))); } } return m; } struct sizes { size_t memtable; size_t cache; size_t sstable; size_t frozen; size_t canonical; size_t query_result; }; static sizes calculate_sizes(const mutation& m) { sizes result; auto s = m.schema(); auto mt = make_lw_shared<memtable>(s); cache_tracker tracker; row_cache cache(s, make_empty_snapshot_source(), tracker); auto cache_initial_occupancy = tracker.region().occupancy().used_space(); assert(mt->occupancy().used_space() == 0); mt->apply(m); cache.populate(m); result.memtable = mt->occupancy().used_space(); result.cache = tracker.region().occupancy().used_space() - cache_initial_occupancy; result.frozen = freeze(m).representation().size(); result.canonical = canonical_mutation(m).representation().size(); result.query_result = m.query(partition_slice_builder(*s).build(), query::result_options::only_result()).buf().size(); tmpdir sstable_dir; sstables::test_env env; auto sst = env.make_sstable(s, sstable_dir.path().string(), 1 /* generation */, sstables::sstable::version_types::la, sstables::sstable::format_types::big); write_memtable_to_sstable_for_test(*mt, sst).get(); sst->load().get(); result.sstable = sst->data_size(); return result; } int main(int argc, char** argv) { namespace bpo = boost::program_options; app_template app; app.add_options() ("column-count", bpo::value<size_t>()->default_value(5), "column count") ("column-name-size", bpo::value<size_t>()->default_value(2), "column name size") ("row-count", bpo::value<size_t>()->default_value(1), "row count") ("partition-key-size", bpo::value<size_t>()->default_value(10), "partition key size") ("clustering-key-size", bpo::value<size_t>()->default_value(10), "clustering key size") ("data-size", bpo::value<size_t>()->default_value(32), "cell data size"); return app.run(argc, argv, [&] { if (smp::count != 1) { throw std::runtime_error("This test has to be run with -c1"); } return seastar::async([&] { storage_service_for_tests ssft; mutation_settings settings; settings.column_count = app.configuration()["column-count"].as<size_t>(); settings.column_name_size = app.configuration()["column-name-size"].as<size_t>(); settings.row_count = app.configuration()["row-count"].as<size_t>(); settings.partition_key_size = app.configuration()["partition-key-size"].as<size_t>(); settings.clustering_key_size = app.configuration()["clustering-key-size"].as<size_t>(); settings.data_size = app.configuration()["data-size"].as<size_t>(); auto m = make_mutation(settings); auto sizes = calculate_sizes(m); std::cout << "mutation footprint:" << "\n"; std::cout << " - in cache: " << sizes.cache << "\n"; std::cout << " - in memtable: " << sizes.memtable << "\n"; std::cout << " - in sstable: " << sizes.sstable << "\n"; std::cout << " - frozen: " << sizes.frozen << "\n"; std::cout << " - canonical: " << sizes.canonical << "\n"; std::cout << " - query result: " << sizes.query_result << "\n"; std::cout << "\n"; size_calculator::print_cache_entry_size(); }); }); } <commit_msg>test: memory_footprint: Calculate sstable size for each format version<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/irange.hpp> #include <seastar/util/defer.hh> #include <seastar/core/app-template.hh> #include <seastar/core/thread.hh> #include "partition_slice_builder.hh" #include "schema_builder.hh" #include "memtable.hh" #include "row_cache.hh" #include "frozen_mutation.hh" #include "test/lib/tmpdir.hh" #include "sstables/sstables.hh" #include "canonical_mutation.hh" #include "test/lib/sstable_utils.hh" #include "test/lib/test_services.hh" #include "test/lib/sstable_test_env.hh" class size_calculator { class nest { public: static thread_local int level; nest() { ++level; } ~nest() { --level; } }; static std::string prefix() { std::string s(" "); for (int i = 0; i < nest::level; ++i) { s += "-- "; } return s; } public: static void print_cache_entry_size() { std::cout << prefix() << "sizeof(cache_entry) = " << sizeof(cache_entry) << "\n"; { nest n; std::cout << prefix() << "sizeof(decorated_key) = " << sizeof(dht::decorated_key) << "\n"; std::cout << prefix() << "sizeof(cache_link_type) = " << sizeof(cache_entry::cache_link_type) << "\n"; print_mutation_partition_size(); } std::cout << "\n"; std::cout << prefix() << "sizeof(rows_entry) = " << sizeof(rows_entry) << "\n"; std::cout << prefix() << "sizeof(lru_link_type) = " << sizeof(rows_entry::lru_link_type) << "\n"; std::cout << prefix() << "sizeof(deletable_row) = " << sizeof(deletable_row) << "\n"; std::cout << prefix() << "sizeof(row) = " << sizeof(row) << "\n"; std::cout << prefix() << "sizeof(atomic_cell_or_collection) = " << sizeof(atomic_cell_or_collection) << "\n"; } static void print_mutation_partition_size() { std::cout << prefix() << "sizeof(mutation_partition) = " << sizeof(mutation_partition) << "\n"; { nest n; std::cout << prefix() << "sizeof(_static_row) = " << sizeof(mutation_partition::_static_row) << "\n"; std::cout << prefix() << "sizeof(_rows) = " << sizeof(mutation_partition::_rows) << "\n"; std::cout << prefix() << "sizeof(_row_tombstones) = " << sizeof(mutation_partition::_row_tombstones) << "\n"; } } }; thread_local int size_calculator::nest::level = 0; static schema_ptr cassandra_stress_schema() { return schema_builder("ks", "cf") .with_column("KEY", bytes_type, column_kind::partition_key) .with_column("C0", bytes_type) .with_column("C1", bytes_type) .with_column("C2", bytes_type) .with_column("C3", bytes_type) .with_column("C4", bytes_type) .build(); } [[gnu::unused]] static mutation make_cs_mutation() { auto s = cassandra_stress_schema(); mutation m(s, partition_key::from_single_value(*s, bytes_type->from_string("4b343050393536353531"))); for (auto&& col : s->regular_columns()) { m.set_clustered_cell(clustering_key::make_empty(), col, atomic_cell::make_live(*bytes_type, 1, bytes_type->from_string("8f75da6b3dcec90c8a404fb9a5f6b0621e62d39c69ba5758e5f41b78311fbb26cc7a"))); } return m; } bytes random_bytes(size_t size) { bytes result(bytes::initialized_later(), size); for (size_t i = 0; i < size; ++i) { result[i] = std::rand() % std::numeric_limits<uint8_t>::max(); } return result; } sstring random_string(size_t size) { sstring result = uninitialized_string(size); static const char chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (size_t i = 0; i < size; ++i) { result[i] = chars[std::rand() % sizeof(chars)]; } return result; } struct mutation_settings { size_t column_count; size_t column_name_size; size_t row_count; size_t partition_key_size; size_t clustering_key_size; size_t data_size; }; static mutation make_mutation(mutation_settings settings) { auto builder = schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key); for (size_t i = 0; i < settings.column_count; ++i) { builder.with_column(to_bytes(random_string(settings.column_name_size)), bytes_type); } auto s = builder.build(); mutation m(s, partition_key::from_single_value(*s, bytes_type->decompose(data_value(random_bytes(settings.partition_key_size))))); for (size_t i = 0; i < settings.row_count; ++i) { auto ck = clustering_key::from_single_value(*s, bytes_type->decompose(data_value(random_bytes(settings.clustering_key_size)))); for (auto&& col : s->regular_columns()) { m.set_clustered_cell(ck, col, atomic_cell::make_live(*bytes_type, 1, bytes_type->decompose(data_value(random_bytes(settings.data_size))))); } } return m; } struct sizes { size_t memtable; size_t cache; std::map<sstables::sstable::version_types, size_t> sstable; size_t frozen; size_t canonical; size_t query_result; }; static sizes calculate_sizes(const mutation& m) { sizes result; auto s = m.schema(); auto mt = make_lw_shared<memtable>(s); cache_tracker tracker; row_cache cache(s, make_empty_snapshot_source(), tracker); auto cache_initial_occupancy = tracker.region().occupancy().used_space(); assert(mt->occupancy().used_space() == 0); mt->apply(m); cache.populate(m); result.memtable = mt->occupancy().used_space(); result.cache = tracker.region().occupancy().used_space() - cache_initial_occupancy; result.frozen = freeze(m).representation().size(); result.canonical = canonical_mutation(m).representation().size(); result.query_result = m.query(partition_slice_builder(*s).build(), query::result_options::only_result()).buf().size(); tmpdir sstable_dir; sstables::test_env env; for (auto v : sstables::all_sstable_versions) { auto sst = env.make_sstable(s, sstable_dir.path().string(), 1 /* generation */, v, sstables::sstable::format_types::big); write_memtable_to_sstable_for_test(*mt, sst).get(); sst->load().get(); result.sstable[v] = sst->data_size(); } return result; } int main(int argc, char** argv) { namespace bpo = boost::program_options; app_template app; app.add_options() ("column-count", bpo::value<size_t>()->default_value(5), "column count") ("column-name-size", bpo::value<size_t>()->default_value(2), "column name size") ("row-count", bpo::value<size_t>()->default_value(1), "row count") ("partition-key-size", bpo::value<size_t>()->default_value(10), "partition key size") ("clustering-key-size", bpo::value<size_t>()->default_value(10), "clustering key size") ("data-size", bpo::value<size_t>()->default_value(32), "cell data size"); return app.run(argc, argv, [&] { if (smp::count != 1) { throw std::runtime_error("This test has to be run with -c1"); } return seastar::async([&] { storage_service_for_tests ssft; mutation_settings settings; settings.column_count = app.configuration()["column-count"].as<size_t>(); settings.column_name_size = app.configuration()["column-name-size"].as<size_t>(); settings.row_count = app.configuration()["row-count"].as<size_t>(); settings.partition_key_size = app.configuration()["partition-key-size"].as<size_t>(); settings.clustering_key_size = app.configuration()["clustering-key-size"].as<size_t>(); settings.data_size = app.configuration()["data-size"].as<size_t>(); auto m = make_mutation(settings); auto sizes = calculate_sizes(m); std::cout << "mutation footprint:" << "\n"; std::cout << " - in cache: " << sizes.cache << "\n"; std::cout << " - in memtable: " << sizes.memtable << "\n"; std::cout << " - in sstable:\n"; for (auto v : sizes.sstable) { std::cout << " " << sstables::to_string(v.first) << ": " << v.second << "\n"; } std::cout << " - frozen: " << sizes.frozen << "\n"; std::cout << " - canonical: " << sizes.canonical << "\n"; std::cout << " - query result: " << sizes.query_result << "\n"; std::cout << "\n"; size_calculator::print_cache_entry_size(); }); }); } <|endoftext|>
<commit_before>/* TwoWire.cpp - TWI/I2C library for Arduino & Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. 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 Modified 2012 by Todd Krein ([email protected]) to implement repeated starts Modified December 2014 by Ivan Grokhotkov ([email protected]) - esp8266 support Modified April 2015 by Hrsto Gochkov ([email protected]) - alternative esp8266 support */ extern "C" { #include <stdlib.h> #include <string.h> #include <inttypes.h> } #include "twi.h" #include "Wire.h" // Initialize Class Variables ////////////////////////////////////////////////// uint8_t TwoWire::rxBuffer[BUFFER_LENGTH]; uint8_t TwoWire::rxBufferIndex = 0; uint8_t TwoWire::rxBufferLength = 0; uint8_t TwoWire::txAddress = 0; uint8_t TwoWire::txBuffer[BUFFER_LENGTH]; uint8_t TwoWire::txBufferIndex = 0; uint8_t TwoWire::txBufferLength = 0; uint8_t TwoWire::transmitting = 0; void (*TwoWire::user_onRequest)(void); void (*TwoWire::user_onReceive)(int); static int default_sda_pin = SDA; static int default_scl_pin = SCL; // Constructors //////////////////////////////////////////////////////////////// TwoWire::TwoWire(){} // Public Methods ////////////////////////////////////////////////////////////// void TwoWire::begin(int sda, int scl){ twi_init(sda, scl); flush(); } void TwoWire::pins(int sda, int scl){ default_sda_pin = sda; default_scl_pin = scl; } void TwoWire::begin(void){ begin(default_sda_pin, default_scl_pin); } void TwoWire::begin(uint8_t address){ // twi_setAddress(address); // twi_attachSlaveTxEvent(onRequestService); // twi_attachSlaveRxEvent(onReceiveService); begin(); } void TwoWire::begin(int address){ begin((uint8_t)address); } void TwoWire::setClock(uint32_t frequency){ twi_setClock(frequency); } size_t TwoWire::requestFrom(uint8_t address, size_t size, bool sendStop){ if(size > BUFFER_LENGTH){ size = BUFFER_LENGTH; } size_t read = (twi_readFrom(address, rxBuffer, size, sendStop) == 0)?size:0; rxBufferIndex = 0; rxBufferLength = read; return read; } uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop){ return requestFrom(address, static_cast<size_t>(quantity), static_cast<bool>(sendStop)); } uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity){ return requestFrom(address, static_cast<size_t>(quantity), true); } uint8_t TwoWire::requestFrom(int address, int quantity){ return requestFrom(static_cast<uint8_t>(address), static_cast<size_t>(quantity), true); } uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop){ return requestFrom(static_cast<uint8_t>(address), static_cast<size_t>(quantity), static_cast<bool>(sendStop)); } void TwoWire::beginTransmission(uint8_t address){ transmitting = 1; txAddress = address; txBufferIndex = 0; txBufferLength = 0; } void TwoWire::beginTransmission(int address){ beginTransmission((uint8_t)address); } uint8_t TwoWire::endTransmission(uint8_t sendStop){ int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, sendStop); txBufferIndex = 0; txBufferLength = 0; transmitting = 0; return ret; } uint8_t TwoWire::endTransmission(void){ return endTransmission(true); } size_t TwoWire::write(uint8_t data){ if(transmitting){ if(txBufferLength >= BUFFER_LENGTH){ setWriteError(); return 0; } txBuffer[txBufferIndex] = data; ++txBufferIndex; txBufferLength = txBufferIndex; } else { // i2c_slave_transmit(&data, 1); } return 1; } size_t TwoWire::write(const uint8_t *data, size_t quantity){ if(transmitting){ for(size_t i = 0; i < quantity; ++i){ if(!write(data[i])) return i; } }else{ // i2c_slave_transmit(data, quantity); } return quantity; } int TwoWire::available(void){ return rxBufferLength - rxBufferIndex; } int TwoWire::read(void){ int value = -1; if(rxBufferIndex < rxBufferLength){ value = rxBuffer[rxBufferIndex]; ++rxBufferIndex; } return value; } int TwoWire::peek(void){ int value = -1; if(rxBufferIndex < rxBufferLength){ value = rxBuffer[rxBufferIndex]; } return value; } void TwoWire::flush(void){ rxBufferIndex = 0; rxBufferLength = 0; txBufferIndex = 0; txBufferLength = 0; } void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes) { // don't bother if user hasn't registered a callback // if(!user_onReceive){ // return; // } // // don't bother if rx buffer is in use by a master requestFrom() op // // i know this drops data, but it allows for slight stupidity // // meaning, they may not have read all the master requestFrom() data yet // if(rxBufferIndex < rxBufferLength){ // return; // } // // copy twi rx buffer into local read buffer // // this enables new reads to happen in parallel // for(uint8_t i = 0; i < numBytes; ++i){ // rxBuffer[i] = inBytes[i]; // } // // set rx iterator vars // rxBufferIndex = 0; // rxBufferLength = numBytes; // // alert user program // user_onReceive(numBytes); } void TwoWire::onRequestService(void){ // // don't bother if user hasn't registered a callback // if(!user_onRequest){ // return; // } // // reset tx buffer iterator vars // // !!! this will kill any pending pre-master sendTo() activity // txBufferIndex = 0; // txBufferLength = 0; // // alert user program // user_onRequest(); } void TwoWire::onReceive( void (*function)(int) ){ //user_onReceive = function; } void TwoWire::onRequest( void (*function)(void) ){ //user_onRequest = function; } // Preinstantiate Objects ////////////////////////////////////////////////////// TwoWire Wire = TwoWire(); <commit_msg>fix I2C case where using different pins would not work with libs calling begin internally<commit_after>/* TwoWire.cpp - TWI/I2C library for Arduino & Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. 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 Modified 2012 by Todd Krein ([email protected]) to implement repeated starts Modified December 2014 by Ivan Grokhotkov ([email protected]) - esp8266 support Modified April 2015 by Hrsto Gochkov ([email protected]) - alternative esp8266 support */ extern "C" { #include <stdlib.h> #include <string.h> #include <inttypes.h> } #include "twi.h" #include "Wire.h" // Initialize Class Variables ////////////////////////////////////////////////// uint8_t TwoWire::rxBuffer[BUFFER_LENGTH]; uint8_t TwoWire::rxBufferIndex = 0; uint8_t TwoWire::rxBufferLength = 0; uint8_t TwoWire::txAddress = 0; uint8_t TwoWire::txBuffer[BUFFER_LENGTH]; uint8_t TwoWire::txBufferIndex = 0; uint8_t TwoWire::txBufferLength = 0; uint8_t TwoWire::transmitting = 0; void (*TwoWire::user_onRequest)(void); void (*TwoWire::user_onReceive)(int); static int default_sda_pin = SDA; static int default_scl_pin = SCL; // Constructors //////////////////////////////////////////////////////////////// TwoWire::TwoWire(){} // Public Methods ////////////////////////////////////////////////////////////// void TwoWire::begin(int sda, int scl){ default_sda_pin = sda; default_scl_pin = scl; twi_init(sda, scl); flush(); } void TwoWire::pins(int sda, int scl){ default_sda_pin = sda; default_scl_pin = scl; } void TwoWire::begin(void){ begin(default_sda_pin, default_scl_pin); } void TwoWire::begin(uint8_t address){ // twi_setAddress(address); // twi_attachSlaveTxEvent(onRequestService); // twi_attachSlaveRxEvent(onReceiveService); begin(); } void TwoWire::begin(int address){ begin((uint8_t)address); } void TwoWire::setClock(uint32_t frequency){ twi_setClock(frequency); } size_t TwoWire::requestFrom(uint8_t address, size_t size, bool sendStop){ if(size > BUFFER_LENGTH){ size = BUFFER_LENGTH; } size_t read = (twi_readFrom(address, rxBuffer, size, sendStop) == 0)?size:0; rxBufferIndex = 0; rxBufferLength = read; return read; } uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop){ return requestFrom(address, static_cast<size_t>(quantity), static_cast<bool>(sendStop)); } uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity){ return requestFrom(address, static_cast<size_t>(quantity), true); } uint8_t TwoWire::requestFrom(int address, int quantity){ return requestFrom(static_cast<uint8_t>(address), static_cast<size_t>(quantity), true); } uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop){ return requestFrom(static_cast<uint8_t>(address), static_cast<size_t>(quantity), static_cast<bool>(sendStop)); } void TwoWire::beginTransmission(uint8_t address){ transmitting = 1; txAddress = address; txBufferIndex = 0; txBufferLength = 0; } void TwoWire::beginTransmission(int address){ beginTransmission((uint8_t)address); } uint8_t TwoWire::endTransmission(uint8_t sendStop){ int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, sendStop); txBufferIndex = 0; txBufferLength = 0; transmitting = 0; return ret; } uint8_t TwoWire::endTransmission(void){ return endTransmission(true); } size_t TwoWire::write(uint8_t data){ if(transmitting){ if(txBufferLength >= BUFFER_LENGTH){ setWriteError(); return 0; } txBuffer[txBufferIndex] = data; ++txBufferIndex; txBufferLength = txBufferIndex; } else { // i2c_slave_transmit(&data, 1); } return 1; } size_t TwoWire::write(const uint8_t *data, size_t quantity){ if(transmitting){ for(size_t i = 0; i < quantity; ++i){ if(!write(data[i])) return i; } }else{ // i2c_slave_transmit(data, quantity); } return quantity; } int TwoWire::available(void){ return rxBufferLength - rxBufferIndex; } int TwoWire::read(void){ int value = -1; if(rxBufferIndex < rxBufferLength){ value = rxBuffer[rxBufferIndex]; ++rxBufferIndex; } return value; } int TwoWire::peek(void){ int value = -1; if(rxBufferIndex < rxBufferLength){ value = rxBuffer[rxBufferIndex]; } return value; } void TwoWire::flush(void){ rxBufferIndex = 0; rxBufferLength = 0; txBufferIndex = 0; txBufferLength = 0; } void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes) { // don't bother if user hasn't registered a callback // if(!user_onReceive){ // return; // } // // don't bother if rx buffer is in use by a master requestFrom() op // // i know this drops data, but it allows for slight stupidity // // meaning, they may not have read all the master requestFrom() data yet // if(rxBufferIndex < rxBufferLength){ // return; // } // // copy twi rx buffer into local read buffer // // this enables new reads to happen in parallel // for(uint8_t i = 0; i < numBytes; ++i){ // rxBuffer[i] = inBytes[i]; // } // // set rx iterator vars // rxBufferIndex = 0; // rxBufferLength = numBytes; // // alert user program // user_onReceive(numBytes); } void TwoWire::onRequestService(void){ // // don't bother if user hasn't registered a callback // if(!user_onRequest){ // return; // } // // reset tx buffer iterator vars // // !!! this will kill any pending pre-master sendTo() activity // txBufferIndex = 0; // txBufferLength = 0; // // alert user program // user_onRequest(); } void TwoWire::onReceive( void (*function)(int) ){ //user_onReceive = function; } void TwoWire::onRequest( void (*function)(void) ){ //user_onRequest = function; } // Preinstantiate Objects ////////////////////////////////////////////////////// TwoWire Wire = TwoWire(); <|endoftext|>
<commit_before>#include <QThread> int main() { QThread::sleep(60); } <commit_msg>Fix "inifiniteLoop" test for Qt 4.<commit_after>#include <QThread> class MyThread : public QThread { public: static void mySleep(unsigned long secs) { sleep(secs); } // sleep() is protected in Qt 4. }; int main() { MyThread::mySleep(60); } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/popo/waitset/condition.hpp" #include "iceoryx_posh/internal/popo/waitset/condition_variable_data.hpp" #include "iceoryx_posh/internal/popo/waitset/guard_condition.hpp" #include "iceoryx_posh/internal/popo/waitset/wait_set.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "test.hpp" #include <memory> using namespace ::testing; using ::testing::Return; using namespace iox::popo; using namespace iox::cxx; using namespace iox::units::duration_literals; class MockSubscriber : public Condition { public: bool isConditionVariableAttached() noexcept override { return m_condVarAttached; } bool attachConditionVariable(ConditionVariableData* ConditionVariableDataPtr) noexcept override { m_condVarAttached = true; m_condVarPtr = ConditionVariableDataPtr; return m_condVarAttached; } bool hasTriggered() const noexcept override { return m_wasTriggered; } bool detachConditionVariable() noexcept override { m_condVarAttached = false; m_condVarPtr = nullptr; return m_condVarAttached; } /// @note done in ChunkQueuePusher void notify() { m_wasTriggered = true; ConditionVariableSignaler signaler{m_condVarPtr}; signaler.notifyOne(); } /// @note members reside in ChunkQueueData in SHM bool m_condVarAttached{false}; bool m_wasTriggered{false}; ConditionVariableData* m_condVarPtr{nullptr}; }; class WaitSet_test : public Test { public: ConditionVariableData m_condVarData; WaitSet m_sut{&m_condVarData}; vector<MockSubscriber, iox::MAX_NUMBER_OF_CONDITIONS> m_subscriberVector; iox::posix::Semaphore m_syncSemaphore = iox::posix::Semaphore::create(0u).get_value(); void SetUp() { MockSubscriber subscriber; while (m_subscriberVector.size() != m_subscriberVector.capacity()) { m_subscriberVector.push_back(subscriber); } }; void TearDown() { m_subscriberVector.clear(); m_sut.clear(); ConditionVariableWaiter waiter{&m_condVarData}; waiter.reset(); }; }; TEST_F(WaitSet_test, AttachSingleConditionSuccessful) { EXPECT_TRUE(m_sut.attachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, AttachSameConditionTwiceResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_FALSE(m_sut.attachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, AttachMultipleConditionSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { EXPECT_TRUE(m_sut.attachCondition(currentSubscriber)); } } TEST_F(WaitSet_test, AttachTooManyConditionsResultsInFailure) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } MockSubscriber extraCondition; EXPECT_FALSE(m_sut.attachCondition(extraCondition)); } TEST_F(WaitSet_test, DetachSingleConditionSuccessful) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_TRUE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachMultipleleConditionsSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } for (auto& currentSubscriber : m_subscriberVector) { EXPECT_TRUE(m_sut.detachCondition(currentSubscriber)); } } TEST_F(WaitSet_test, DetachConditionNotInListResultsInFailure) { EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachUnknownConditionResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.back())); } TEST_F(WaitSet_test, TimedWaitWithInvalidTimeResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(0_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, NoAttachTimedWaitResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(1_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, TimedWaitWithNotificationResultsInImmediateTrigger) { m_sut.attachCondition(m_subscriberVector.front()); m_subscriberVector.front().notify(); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); } TEST_F(WaitSet_test, TimeoutOfTimedWaitResultsInEmptyVector) { m_sut.attachCondition(m_subscriberVector.front()); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(0)); } TEST_F(WaitSet_test, NotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector[0]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector[0].notify(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyManyBeforeWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); m_syncSemaphore.wait(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(2)); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; m_syncSemaphore.post(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyManyWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(2)); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; waiter.join(); } TEST_F(WaitSet_test, WaitWithoutNotifyResultsInBlockingMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); m_sut.wait(); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, NotifyGuardConditionWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; GuardCondition guardCond; m_sut.attachCondition(guardCond); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &guardCond); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; guardCond.notify(); waiter.join(); } TEST_F(WaitSet_test, NotifyGuardConditionOnceTimedWaitResultsInResetOfTrigger) { GuardCondition guardCond; m_sut.attachCondition(guardCond); guardCond.notify(); auto fulfilledConditions1 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions1.size(), Eq(1)); EXPECT_THAT(fulfilledConditions1.front(), &guardCond); guardCond.resetTrigger(); auto fulfilledConditions2 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions2.size(), Eq(0)); } <commit_msg>iox-#25 Add further test case for WaitSet<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/popo/waitset/condition.hpp" #include "iceoryx_posh/internal/popo/waitset/condition_variable_data.hpp" #include "iceoryx_posh/internal/popo/waitset/guard_condition.hpp" #include "iceoryx_posh/internal/popo/waitset/wait_set.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "test.hpp" #include <memory> using namespace ::testing; using ::testing::Return; using namespace iox::popo; using namespace iox::cxx; using namespace iox::units::duration_literals; class MockSubscriber : public Condition { public: bool isConditionVariableAttached() noexcept override { return m_condVarAttached; } bool attachConditionVariable(ConditionVariableData* ConditionVariableDataPtr) noexcept override { m_condVarAttached = true; m_condVarPtr = ConditionVariableDataPtr; return m_condVarAttached; } bool hasTriggered() const noexcept override { return m_wasTriggered; } bool detachConditionVariable() noexcept override { m_condVarAttached = false; m_condVarPtr = nullptr; return m_condVarAttached; } /// @note done in ChunkQueuePusher void notify() { m_wasTriggered = true; ConditionVariableSignaler signaler{m_condVarPtr}; signaler.notifyOne(); } /// @note members reside in ChunkQueueData in SHM bool m_condVarAttached{false}; bool m_wasTriggered{false}; ConditionVariableData* m_condVarPtr{nullptr}; }; class WaitSet_test : public Test { public: ConditionVariableData m_condVarData; WaitSet m_sut{&m_condVarData}; vector<MockSubscriber, iox::MAX_NUMBER_OF_CONDITIONS> m_subscriberVector; iox::posix::Semaphore m_syncSemaphore = iox::posix::Semaphore::create(0u).get_value(); void SetUp() { MockSubscriber subscriber; while (m_subscriberVector.size() != m_subscriberVector.capacity()) { m_subscriberVector.push_back(subscriber); } }; void TearDown() { m_subscriberVector.clear(); m_sut.clear(); ConditionVariableWaiter waiter{&m_condVarData}; waiter.reset(); }; }; TEST_F(WaitSet_test, AttachSingleConditionSuccessful) { EXPECT_TRUE(m_sut.attachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, AttachSameConditionTwiceResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_FALSE(m_sut.attachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, AttachMultipleConditionSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { EXPECT_TRUE(m_sut.attachCondition(currentSubscriber)); } } TEST_F(WaitSet_test, AttachTooManyConditionsResultsInFailure) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } MockSubscriber extraCondition; EXPECT_FALSE(m_sut.attachCondition(extraCondition)); } TEST_F(WaitSet_test, DetachSingleConditionSuccessful) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_TRUE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachMultipleleConditionsSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } for (auto& currentSubscriber : m_subscriberVector) { EXPECT_TRUE(m_sut.detachCondition(currentSubscriber)); } } TEST_F(WaitSet_test, DetachConditionNotInListResultsInFailure) { EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachUnknownConditionResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.back())); } TEST_F(WaitSet_test, TimedWaitWithInvalidTimeResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(0_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, NoAttachTimedWaitResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(1_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, TimedWaitWithMaximumNumberOfConditionsResultsInReturnOfMaximumNumberOfConditions) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); currentSubscriber.notify(); } auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(iox::MAX_NUMBER_OF_CONDITIONS)); } TEST_F(WaitSet_test, TimedWaitWithNotificationResultsInImmediateTrigger) { m_sut.attachCondition(m_subscriberVector.front()); m_subscriberVector.front().notify(); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); } TEST_F(WaitSet_test, TimeoutOfTimedWaitResultsInEmptyVector) { m_sut.attachCondition(m_subscriberVector.front()); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(0)); } TEST_F(WaitSet_test, NotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector[0]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector[0].notify(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyManyBeforeWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); m_syncSemaphore.wait(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(2)); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; m_syncSemaphore.post(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyManyWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(2)); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; waiter.join(); } TEST_F(WaitSet_test, WaitWithoutNotifyResultsInBlockingMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); m_sut.wait(); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, NotifyGuardConditionWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; GuardCondition guardCond; m_sut.attachCondition(guardCond); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &guardCond); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; guardCond.notify(); waiter.join(); } TEST_F(WaitSet_test, NotifyGuardConditionOnceTimedWaitResultsInResetOfTrigger) { GuardCondition guardCond; m_sut.attachCondition(guardCond); guardCond.notify(); auto fulfilledConditions1 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions1.size(), Eq(1)); EXPECT_THAT(fulfilledConditions1.front(), &guardCond); guardCond.resetTrigger(); auto fulfilledConditions2 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions2.size(), Eq(0)); } <|endoftext|>
<commit_before>#pragma once #include <unordered_map> #include <vector> #include "depthai-shared/datatype/RawCameraControl.hpp" #include "depthai/pipeline/datatype/Buffer.hpp" namespace dai { // protected inheritance, so serialize isn't visible to users class CameraControl : public Buffer { std::shared_ptr<RawBuffer> serialize() const override; RawCameraControl& cfg; using AutoFocusMode = RawCameraControl::AutoFocusMode; using AntiBandingMode = RawCameraControl::AntiBandingMode; using AutoWhiteBalanceMode = RawCameraControl::AutoWhiteBalanceMode; using SceneMode = RawCameraControl::SceneMode; using EffectMode = RawCameraControl::EffectMode; public: CameraControl(); explicit CameraControl(std::shared_ptr<RawCameraControl> ptr); virtual ~CameraControl() = default; // Functions to set properties void setCaptureStill(bool capture); void setStartStreaming(); void setStopStreaming(); // Focus void setAutoFocusMode(AutoFocusMode mode); void setAutoFocusTrigger(); void setAutoFocusRegion(uint16_t startX, uint16_t startY, uint16_t width, uint16_t height); void setManualFocus(uint8_t lensPosition); // Exposure void setAutoExposureEnable(); void setAutoExposureLock(bool lock); void setAutoExposureRegion(uint16_t startX, uint16_t startY, uint16_t width, uint16_t height); void setAutoExposureCompensation(int8_t compensation); void setAntiBandingMode(AntiBandingMode mode); void setManualExposure(uint32_t exposureTimeUs, uint32_t sensitivityIso); // White Balance void setAutoWhiteBalanceMode(AutoWhiteBalanceMode mode); void setAutoWhiteBalanceLock(bool lock); // Other image controls void setBrightness(uint16_t value); // TODO move to AE? void setContrast(uint16_t value); void setSaturation(uint16_t value); void setSharpness(uint16_t value); void setNoiseReductionStrength(uint16_t value); void setLumaDenoise(uint16_t value); void setChromaDenoise(uint16_t value); void setSceneMode(SceneMode mode); void setEffectMode(EffectMode mode); // Functions to retrieve properties bool getCaptureStill() const; }; } // namespace dai <commit_msg>CameraControl.hpp: make non-Raw types public<commit_after>#pragma once #include <unordered_map> #include <vector> #include "depthai-shared/datatype/RawCameraControl.hpp" #include "depthai/pipeline/datatype/Buffer.hpp" namespace dai { // protected inheritance, so serialize isn't visible to users class CameraControl : public Buffer { std::shared_ptr<RawBuffer> serialize() const override; RawCameraControl& cfg; public: using AutoFocusMode = RawCameraControl::AutoFocusMode; using AntiBandingMode = RawCameraControl::AntiBandingMode; using AutoWhiteBalanceMode = RawCameraControl::AutoWhiteBalanceMode; using SceneMode = RawCameraControl::SceneMode; using EffectMode = RawCameraControl::EffectMode; CameraControl(); explicit CameraControl(std::shared_ptr<RawCameraControl> ptr); virtual ~CameraControl() = default; // Functions to set properties void setCaptureStill(bool capture); void setStartStreaming(); void setStopStreaming(); // Focus void setAutoFocusMode(AutoFocusMode mode); void setAutoFocusTrigger(); void setAutoFocusRegion(uint16_t startX, uint16_t startY, uint16_t width, uint16_t height); void setManualFocus(uint8_t lensPosition); // Exposure void setAutoExposureEnable(); void setAutoExposureLock(bool lock); void setAutoExposureRegion(uint16_t startX, uint16_t startY, uint16_t width, uint16_t height); void setAutoExposureCompensation(int8_t compensation); void setAntiBandingMode(AntiBandingMode mode); void setManualExposure(uint32_t exposureTimeUs, uint32_t sensitivityIso); // White Balance void setAutoWhiteBalanceMode(AutoWhiteBalanceMode mode); void setAutoWhiteBalanceLock(bool lock); // Other image controls void setBrightness(uint16_t value); // TODO move to AE? void setContrast(uint16_t value); void setSaturation(uint16_t value); void setSharpness(uint16_t value); void setNoiseReductionStrength(uint16_t value); void setLumaDenoise(uint16_t value); void setChromaDenoise(uint16_t value); void setSceneMode(SceneMode mode); void setEffectMode(EffectMode mode); // Functions to retrieve properties bool getCaptureStill() const; }; } // namespace dai <|endoftext|>
<commit_before>// @(#)root/proof:$Id$ // Author: G. Ganis, Mar 2010 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // pq2wrappers // // // // This file implements the wrapper functions used in PQ2 // // // ////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "pq2wrappers.h" #include "redirguard.h" #include "TDataSetManager.h" #include "TEnv.h" #include "TFileInfo.h" #include "TPluginManager.h" #include "TProof.h" #include "TROOT.h" TDataSetManager *gDataSetManager = 0; // Global variables defined by other PQ2 components extern TUrl gUrl; extern Bool_t gIsProof; extern TString flog; extern TString ferr; extern TString fres; extern Int_t gverbose; Int_t getProof(const char *where, Int_t verbose = 1); Int_t getDSMgr(const char *where); //_______________________________________________________________________________________ void DataSetCache(bool clear, const char *ds) { // ShowCache wrapper if (gIsProof) { if (!gProof && getProof("DataSetCache", 0) != 0) return; return (clear ? gProof->ClearDataSetCache(ds) : gProof->ShowDataSetCache(ds)); } else { if (!gDataSetManager && getDSMgr("DataSetCache") != 0) return; Int_t rc = (clear) ? gDataSetManager->ClearCache(ds) : gDataSetManager->ShowCache(ds); if (rc != 0) Printf("DataSetCache: problems running '%s'", (clear ? "clear" : "show")); return; } // Done return; } //_______________________________________________________________________________________ void ShowDataSets(const char *ds, const char *opt) { // ShowDataSets wrapper if (gIsProof) { if (!gProof && getProof("ShowDataSets", 0) != 0) return; return gProof->ShowDataSets(ds, opt); } else { if (!gDataSetManager && getDSMgr("ShowDataSets") != 0) return; return gDataSetManager->ShowDataSets(ds, opt); } // Done return; } //_______________________________________________________________________________________ TFileCollection *GetDataSet(const char *ds, const char *server) { // GetDataSet wrapper TFileCollection *fc = 0; if (gIsProof) { if (!gProof && getProof("GetDataSet") != 0) return fc; return gProof->GetDataSet(ds, server); } else { if (!gDataSetManager && getDSMgr("ShowDataSets") != 0) return fc; return gDataSetManager->GetDataSet(ds, server); } // Done return fc; } //_______________________________________________________________________________________ TMap *GetDataSets(const char *owner, const char *server, const char *opt) { // GetDataSets wrapper TMap *dss = 0; if (gIsProof) { if (!gProof && getProof("GetDataSets") != 0) return dss; return gProof->GetDataSets(owner, server); } else { if (!gDataSetManager && getDSMgr("GetDataSets") != 0) return dss; // Get the datasets and fill a map UInt_t oo = (opt && !strcmp(opt, "list")) ? (UInt_t)TDataSetManager::kList : (UInt_t)TDataSetManager::kExport; dss = gDataSetManager->GetDataSets(owner, oo); // If defines, option gives the name of a server for which to extract the information if (dss) { if (server && strlen(server) > 0) { // The return map will be in the form </group/user/datasetname> --> <dataset> TMap *rmap = new TMap; TObject *k = 0; TFileCollection *fc = 0, *xfc = 0; TIter nxd(dss); while ((k = nxd()) && (fc = (TFileCollection *) dss->GetValue(k))) { // Get subset on specified server, if any if ((xfc = fc->GetFilesOnServer(server))) { rmap->Add(new TObjString(k->GetName()), xfc); } } dss->DeleteAll(); delete dss; dss = 0; if (rmap->GetSize() > 0) { dss = rmap; } else { Printf("GetDataSets: no dataset found on server '%s' for owner '%s'", server, owner); delete rmap; } } } else { Printf("GetDataSets: no dataset found for '%s'", owner); } } // Done return dss; } //_______________________________________________________________________________________ Int_t RemoveDataSet(const char *dsname) { // RemoveDataSet wrapper if (gIsProof) { if (!gProof && getProof("RemoveDataSet") != 0) return -1; return gProof->RemoveDataSet(dsname); } else { if (!gDataSetManager && getDSMgr("RemoveDataSet") != 0) return -1; return gDataSetManager->RemoveDataSet(dsname); } // Done return -1; } //_______________________________________________________________________________________ Int_t VerifyDataSet(const char *dsname, const char *opt, const char *redir) { // VerifyDataSet wrapper Int_t rc = -1; // Honour the 'redir' if required TString srvmaps; if (redir && strlen(redir) > 0) srvmaps.Form("|%s", redir); if (gIsProof) { // Honour the 'redir' if required if (!(srvmaps.IsNull())) { TProof::AddEnvVar("DATASETSRVMAPS", srvmaps); } if (!gProof && getProof("VerifyDataSet") != 0) return -1; if ((rc = gProof->VerifyDataSet(dsname, opt)) == 0) { // Success; partial at least. Check if all files are staged TFileCollection *fcs = gProof->GetDataSet(dsname, "S:"); if (fcs && fcs->GetStagedPercentage() < 99.99999) rc = 1; } } else { // Honour the 'redir' if required if (!(srvmaps.IsNull())) { gEnv->SetValue("DataSet.SrvMaps", srvmaps); } if (!gDataSetManager && getDSMgr("VerifyDataSet") != 0) return -1; if ((rc = gDataSetManager->ScanDataSet(dsname, opt)) == 0) { // Success; partial at least. Check if all files are staged TFileCollection *fcs = gDataSetManager->GetDataSet(dsname, "S:"); if (fcs && fcs->GetStagedPercentage() < 99.99999) rc = 1; } } // Done return rc; } //_______________________________________________________________________________________ Bool_t ExistsDataSet(const char *dsname) { // ExistsDataSet wrapper if (gIsProof) { if (!gProof && getProof("ExistsDataSet") != 0) return kFALSE; return gProof->ExistsDataSet(dsname); } else { if (!gDataSetManager && getDSMgr("ExistsDataSet") != 0) return kFALSE; return gDataSetManager->ExistsDataSet(dsname); } return kFALSE; } //_______________________________________________________________________________________ Int_t RegisterDataSet(const char *dsname, TFileCollection *fc, const char* opt) { // RegisterDataSet wrapper if (gIsProof) { if (!gProof && getProof("GetDataSet") != 0) return -1; return gProof->RegisterDataSet(dsname, fc, opt); } else { if (!gDataSetManager && getDSMgr("RegisterDataSet") != 0) return -1; return gDataSetManager->RegisterDataSet(dsname, fc, opt); } return -1; } //_______________________________________________________________________________________ Int_t getProof(const char *where, Int_t verbose) { // Open a PROOF session at gUrl { redirguard rog(flog.Data(), "a", verbose); TProof::Open(gUrl.GetUrl(), "masteronly"); } if (!gProof || !gProof->IsValid()) { Printf("getProof:%s: problems starting a PROOF session at '%s'", where, gUrl.GetUrl()); return -1; } if (gverbose >= 2) gProof->SetLogLevel(2); // Done return 0; } //_______________________________________________________________________________________ Int_t getDSMgr(const char *where) { // Open a dataset manager for gUrl Int_t rc = -1; if (gROOT->GetPluginManager()) { // Find the appropriate handler TPluginHandler *h = gROOT->GetPluginManager()->FindHandler("TDataSetManager", "file"); if (h && h->LoadPlugin() != -1) { TString group(getenv("PQ2GROUP")), user(getenv("PQ2USER")); TString dsm, opt("opt:-Ar:-Av:"); const char *o = getenv("PQ2DSMGROPTS"); if (o) { opt = ""; if (strlen(o) > 0) opt.Form("opt:%s", o); } dsm.Form("file dir:%s %s", gUrl.GetUrl(), opt.Data()); gDataSetManager = reinterpret_cast<TDataSetManager*>(h->ExecPlugin(3, group.Data(), user.Data(), dsm.Data())); if (gDataSetManager) { rc = 0; } else { Printf("getDSMgr:%s: problems creating a dataset manager at '%s'", where, gUrl.GetUrl()); } } } // Done return rc; } <commit_msg>Make sure that pq2-verify copes well with parallel verification (Savannah #99603)<commit_after>// @(#)root/proof:$Id$ // Author: G. Ganis, Mar 2010 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // pq2wrappers // // // // This file implements the wrapper functions used in PQ2 // // // ////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "pq2wrappers.h" #include "redirguard.h" #include "TDataSetManager.h" #include "TEnv.h" #include "TFileInfo.h" #include "TPluginManager.h" #include "TProof.h" #include "TROOT.h" TDataSetManager *gDataSetManager = 0; // Global variables defined by other PQ2 components extern TUrl gUrl; extern Bool_t gIsProof; extern TString flog; extern TString ferr; extern TString fres; extern Int_t gverbose; // How to start PROOF (new VerifyDataSet wants it parallel) static bool doParallel = kFALSE; Int_t getProof(const char *where, Int_t verbose = 1); Int_t getDSMgr(const char *where); //_______________________________________________________________________________________ void DataSetCache(bool clear, const char *ds) { // ShowCache wrapper if (gIsProof) { doParallel = kFALSE; if (!gProof && getProof("DataSetCache", 0) != 0) return; return (clear ? gProof->ClearDataSetCache(ds) : gProof->ShowDataSetCache(ds)); } else { if (!gDataSetManager && getDSMgr("DataSetCache") != 0) return; Int_t rc = (clear) ? gDataSetManager->ClearCache(ds) : gDataSetManager->ShowCache(ds); if (rc != 0) Printf("DataSetCache: problems running '%s'", (clear ? "clear" : "show")); return; } // Done return; } //_______________________________________________________________________________________ void ShowDataSets(const char *ds, const char *opt) { // ShowDataSets wrapper if (gIsProof) { doParallel = kFALSE; if (!gProof && getProof("ShowDataSets", 0) != 0) return; return gProof->ShowDataSets(ds, opt); } else { if (!gDataSetManager && getDSMgr("ShowDataSets") != 0) return; return gDataSetManager->ShowDataSets(ds, opt); } // Done return; } //_______________________________________________________________________________________ TFileCollection *GetDataSet(const char *ds, const char *server) { // GetDataSet wrapper TFileCollection *fc = 0; if (gIsProof) { doParallel = kFALSE; if (!gProof && getProof("GetDataSet") != 0) return fc; return gProof->GetDataSet(ds, server); } else { if (!gDataSetManager && getDSMgr("ShowDataSets") != 0) return fc; return gDataSetManager->GetDataSet(ds, server); } // Done return fc; } //_______________________________________________________________________________________ TMap *GetDataSets(const char *owner, const char *server, const char *opt) { // GetDataSets wrapper TMap *dss = 0; if (gIsProof) { doParallel = kFALSE; if (!gProof && getProof("GetDataSets") != 0) return dss; return gProof->GetDataSets(owner, server); } else { if (!gDataSetManager && getDSMgr("GetDataSets") != 0) return dss; // Get the datasets and fill a map UInt_t oo = (opt && !strcmp(opt, "list")) ? (UInt_t)TDataSetManager::kList : (UInt_t)TDataSetManager::kExport; dss = gDataSetManager->GetDataSets(owner, oo); // If defines, option gives the name of a server for which to extract the information if (dss) { if (server && strlen(server) > 0) { // The return map will be in the form </group/user/datasetname> --> <dataset> TMap *rmap = new TMap; TObject *k = 0; TFileCollection *fc = 0, *xfc = 0; TIter nxd(dss); while ((k = nxd()) && (fc = (TFileCollection *) dss->GetValue(k))) { // Get subset on specified server, if any if ((xfc = fc->GetFilesOnServer(server))) { rmap->Add(new TObjString(k->GetName()), xfc); } } dss->DeleteAll(); delete dss; dss = 0; if (rmap->GetSize() > 0) { dss = rmap; } else { Printf("GetDataSets: no dataset found on server '%s' for owner '%s'", server, owner); delete rmap; } } } else { Printf("GetDataSets: no dataset found for '%s'", owner); } } // Done return dss; } //_______________________________________________________________________________________ Int_t RemoveDataSet(const char *dsname) { // RemoveDataSet wrapper if (gIsProof) { doParallel = kFALSE; if (!gProof && getProof("RemoveDataSet") != 0) return -1; return gProof->RemoveDataSet(dsname); } else { if (!gDataSetManager && getDSMgr("RemoveDataSet") != 0) return -1; return gDataSetManager->RemoveDataSet(dsname); } // Done return -1; } //_______________________________________________________________________________________ Int_t VerifyDataSet(const char *dsname, const char *opt, const char *redir) { // VerifyDataSet wrapper Int_t rc = -1; // Honour the 'redir' if required TString srvmaps; if (redir && strlen(redir) > 0) srvmaps.Form("|%s", redir); if (gIsProof) { // Honour the 'redir' if required if (!(srvmaps.IsNull())) { TProof::AddEnvVar("DATASETSRVMAPS", srvmaps); } TString sopt(opt); doParallel = (sopt.Contains("S")) ? kFALSE : kTRUE; if (gProof && doParallel && gProof->GetParallel() == 0) { gProof->Close(); delete gProof; gProof = 0; } if (!gProof && getProof("VerifyDataSet") != 0) return -1; if ((rc = gProof->VerifyDataSet(dsname, opt)) == 0) { // Success; partial at least. Check if all files are staged TFileCollection *fcs = gProof->GetDataSet(dsname, "S:"); if (fcs && fcs->GetStagedPercentage() < 99.99999) rc = 1; } } else { // Honour the 'redir' if required if (!(srvmaps.IsNull())) { gEnv->SetValue("DataSet.SrvMaps", srvmaps); } if (!gDataSetManager && getDSMgr("VerifyDataSet") != 0) return -1; if ((rc = gDataSetManager->ScanDataSet(dsname, opt)) == 0) { // Success; partial at least. Check if all files are staged TFileCollection *fcs = gDataSetManager->GetDataSet(dsname, "S:"); if (fcs && fcs->GetStagedPercentage() < 99.99999) rc = 1; } } // Done return rc; } //_______________________________________________________________________________________ Bool_t ExistsDataSet(const char *dsname) { // ExistsDataSet wrapper if (gIsProof) { doParallel = kFALSE; if (!gProof && getProof("ExistsDataSet") != 0) return kFALSE; return gProof->ExistsDataSet(dsname); } else { if (!gDataSetManager && getDSMgr("ExistsDataSet") != 0) return kFALSE; return gDataSetManager->ExistsDataSet(dsname); } return kFALSE; } //_______________________________________________________________________________________ Int_t RegisterDataSet(const char *dsname, TFileCollection *fc, const char* opt) { // RegisterDataSet wrapper if (gIsProof) { doParallel = kFALSE; if (!gProof && getProof("GetDataSet") != 0) return -1; return gProof->RegisterDataSet(dsname, fc, opt); } else { if (!gDataSetManager && getDSMgr("RegisterDataSet") != 0) return -1; return gDataSetManager->RegisterDataSet(dsname, fc, opt); } return -1; } //_______________________________________________________________________________________ Int_t getProof(const char *where, Int_t verbose) { // Open a PROOF session at gUrl { redirguard rog(flog.Data(), "a", verbose); const char *popt = (doParallel) ? "" : "masteronly"; TProof::Open(gUrl.GetUrl(), popt); } if (!gProof || !gProof->IsValid()) { Printf("getProof:%s: problems starting a PROOF session at '%s'", where, gUrl.GetUrl()); return -1; } if (gverbose >= 2) gProof->SetLogLevel(2); // Done return 0; } //_______________________________________________________________________________________ Int_t getDSMgr(const char *where) { // Open a dataset manager for gUrl Int_t rc = -1; if (gROOT->GetPluginManager()) { // Find the appropriate handler TPluginHandler *h = gROOT->GetPluginManager()->FindHandler("TDataSetManager", "file"); if (h && h->LoadPlugin() != -1) { TString group(getenv("PQ2GROUP")), user(getenv("PQ2USER")); TString dsm, opt("opt:-Ar:-Av:"); const char *o = getenv("PQ2DSMGROPTS"); if (o) { opt = ""; if (strlen(o) > 0) opt.Form("opt:%s", o); } dsm.Form("file dir:%s %s", gUrl.GetUrl(), opt.Data()); gDataSetManager = reinterpret_cast<TDataSetManager*>(h->ExecPlugin(3, group.Data(), user.Data(), dsm.Data())); if (gDataSetManager) { rc = 0; } else { Printf("getDSMgr:%s: problems creating a dataset manager at '%s'", where, gUrl.GetUrl()); } } } // Done return rc; } <|endoftext|>
<commit_before><commit_msg>mapGen.cc file setup<commit_after> /****************************************************************************************************/ // Global includes #include <random> /****************************************************************************************************/ // Local includes /****************************************************************************************************/ // Using statements using std::vector; typedef uchar unsigned char /****************************************************************************************************/ // Main int main(int args, char* argv[]) { vector<vector<uchar>> world; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#pragma once #include <vector> #include <algorithm> // ---------------------------------------------------------------------- namespace acmacs { template <typename T> class flat_set_t { public: flat_set_t() = default; flat_set_t(std::initializer_list<T> source) : data_(source) {} auto begin() const { return data_.begin(); } auto end() const { return data_.end(); } auto empty() const { return data_.empty(); } auto size() const { return data_.size(); } auto clear() { data_.clear(); } const auto& front() const { return data_.front(); } void sort() { std::sort(std::begin(data_), std::end(data_)); } template <typename Predicate> void erase_if(Predicate&& pred) { data_.erase(std::remove_if(std::begin(data_), std::end(data_), std::forward<Predicate>(pred)), std::end(data_)); } void add(const T& elt) { if (std::find(std::begin(data_), std::end(data_), elt) == std::end(data_)) data_.push_back(elt); } void add(T&& elt) { if (std::find(std::begin(data_), std::end(data_), elt) == std::end(data_)) data_.push_back(std::move(elt)); } void add_and_sort(const T& elt) { if (std::find(std::begin(data_), std::end(data_), elt) == std::end(data_)) { data_.push_back(elt); sort(); } } void merge_from(const flat_set_t& source) { for (const auto& src : source) add(src); } private: std::vector<T> data_; }; } // namespace acmacs // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>flat_set improvement<commit_after>#pragma once #include <vector> #include <algorithm> // ---------------------------------------------------------------------- namespace acmacs { enum class flat_set_sort_afterwards { no, yes }; template <typename T> class flat_set_t { public: flat_set_t() = default; flat_set_t(std::initializer_list<T> source) : data_(source) {} auto begin() const { return data_.begin(); } auto end() const { return data_.end(); } auto empty() const { return data_.empty(); } auto size() const { return data_.size(); } auto clear() { data_.clear(); } const auto& front() const { return data_.front(); } void sort() { std::sort(std::begin(data_), std::end(data_)); } template <typename Predicate> void erase_if(Predicate&& pred) { data_.erase(std::remove_if(std::begin(data_), std::end(data_), std::forward<Predicate>(pred)), std::end(data_)); } void add(const T& elt, flat_set_sort_afterwards a_sort = flat_set_sort_afterwards::no) { if (std::find(std::begin(data_), std::end(data_), elt) == std::end(data_)) { data_.push_back(elt); if (a_sort == flat_set_sort_afterwards::yes) sort(); } } void add(T&& elt, flat_set_sort_afterwards a_sort = flat_set_sort_afterwards::no) { if (std::find(std::begin(data_), std::end(data_), elt) == std::end(data_)) { data_.push_back(std::move(elt)); if (a_sort == flat_set_sort_afterwards::yes) sort(); } } void merge_from(const flat_set_t& source, flat_set_sort_afterwards a_sort = flat_set_sort_afterwards::no) { for (const auto& src : source) add(src, flat_set_sort_afterwards::no); if (a_sort == flat_set_sort_afterwards::yes) sort(); } private: std::vector<T> data_; }; } // namespace acmacs // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#include <algorithm> #include <array> #include <iostream> #include <string> #include "gtest/gtest.h" #include "sparse-array.h" namespace cs375 { // Test with nastier types to additionally test memory correctness. class SparseArrayTest : public ::testing::Test { protected: sparse_array<std::string> array{17}; }; TEST_F(SparseArrayTest, StartsEmpty) { EXPECT_EQ(0, array.size()); } TEST_F(SparseArrayTest, Contains_Nonexistent) { EXPECT_FALSE(array.contains(0)); } TEST_F(SparseArrayTest, At_Nonexistent) { EXPECT_EQ(nullptr, array.at(0)); } TEST_F(SparseArrayTest, Erase_Nonexistent) { EXPECT_FALSE(array.erase(0)); } TEST_F(SparseArrayTest, Insert_Nonexistent) { auto result = array.emplace(0, "Hello"); ASSERT_NE(nullptr, result); EXPECT_EQ("Hello", *result); } TEST_F(SparseArrayTest, Insert_Nonexistent_IncreasesSize) { array.emplace(0, "Hello"); EXPECT_EQ(1, array.size()); } TEST_F(SparseArrayTest, Contains_Existent) { array.emplace(0, "Hello"); EXPECT_TRUE(array.contains(0)); } TEST_F(SparseArrayTest, At_Existent) { auto expected = array.emplace(0, "Hello"); EXPECT_EQ(expected, array.at(0)); } TEST_F(SparseArrayTest, Erase_Existent) { array.emplace(0, "Hello"); EXPECT_TRUE(array.erase(0)); } TEST_F(SparseArrayTest, Erase_Existent_DecreasesSize) { array.emplace(0, "Hello"); array.erase(0); EXPECT_EQ(0, array.size()); } TEST_F(SparseArrayTest, Insert_Existent) { array.emplace(0, "Hello"); EXPECT_EQ(nullptr, array.emplace(0, "Goodbye")); } TEST_F(SparseArrayTest, Insert_Twice) { array.emplace(1, "Hello"); auto result = array.emplace(0, "Goodbye"); ASSERT_NE(nullptr, result); EXPECT_EQ("Goodbye", *result); } TEST_F(SparseArrayTest, Erase_FirstInserted) { array.emplace(1, "Hello"); array.emplace(0, "Goodbye"); EXPECT_TRUE(array.erase(1)); } TEST_F(SparseArrayTest, Erase_SecondInserted) { array.emplace(1, "Hello"); array.emplace(0, "Goodbye"); EXPECT_TRUE(array.erase(0)); } TEST_F(SparseArrayTest, Iteration_Empty) { std::array<std::string, 0> expected; EXPECT_TRUE(std::is_permutation(array.begin(), array.end(), expected.begin())); } TEST_F(SparseArrayTest, Iteration_SizeOne) { array.emplace(0, "Hello"); std::string expected[] = {"Hello"}; EXPECT_TRUE(std::is_permutation(array.begin(), array.end(), expected)); } TEST_F(SparseArrayTest, Iteration_SizeTwo) { array.emplace(1, "Hello"); array.emplace(0, "Goodbye"); std::string expected[] = {"Hello", "Goodbye"}; EXPECT_TRUE(std::is_permutation(array.begin(), array.end(), expected)); } TEST(SparseArrayDestructorTest, DoesDestroy) { bool destroyed = false; struct nontrivally_destroyable { bool &destroyed; ~nontrivally_destroyable() { destroyed = true; } }; { sparse_array<nontrivally_destroyable> arr(17); arr.emplace(1, destroyed); } ASSERT_TRUE(destroyed); } } <commit_msg>Make iteration tests more robust<commit_after>#include <algorithm> #include <array> #include <iostream> #include <iterator> #include <string> #include "gtest/gtest.h" #include "sparse-array.h" namespace cs375 { // Test with nastier types to additionally test memory correctness. class SparseArrayTest : public ::testing::Test { protected: sparse_array<std::string> array{17}; }; TEST_F(SparseArrayTest, StartsEmpty) { EXPECT_EQ(0, array.size()); } TEST_F(SparseArrayTest, Contains_Nonexistent) { EXPECT_FALSE(array.contains(0)); } TEST_F(SparseArrayTest, At_Nonexistent) { EXPECT_EQ(nullptr, array.at(0)); } TEST_F(SparseArrayTest, Erase_Nonexistent) { EXPECT_FALSE(array.erase(0)); } TEST_F(SparseArrayTest, Insert_Nonexistent) { auto result = array.emplace(0, "Hello"); ASSERT_NE(nullptr, result); EXPECT_EQ("Hello", *result); } TEST_F(SparseArrayTest, Insert_Nonexistent_IncreasesSize) { array.emplace(0, "Hello"); EXPECT_EQ(1, array.size()); } TEST_F(SparseArrayTest, Contains_Existent) { array.emplace(0, "Hello"); EXPECT_TRUE(array.contains(0)); } TEST_F(SparseArrayTest, At_Existent) { auto expected = array.emplace(0, "Hello"); EXPECT_EQ(expected, array.at(0)); } TEST_F(SparseArrayTest, Erase_Existent) { array.emplace(0, "Hello"); EXPECT_TRUE(array.erase(0)); } TEST_F(SparseArrayTest, Erase_Existent_DecreasesSize) { array.emplace(0, "Hello"); array.erase(0); EXPECT_EQ(0, array.size()); } TEST_F(SparseArrayTest, Insert_Existent) { array.emplace(0, "Hello"); EXPECT_EQ(nullptr, array.emplace(0, "Goodbye")); } TEST_F(SparseArrayTest, Insert_Twice) { array.emplace(1, "Hello"); auto result = array.emplace(0, "Goodbye"); ASSERT_NE(nullptr, result); EXPECT_EQ("Goodbye", *result); } TEST_F(SparseArrayTest, Erase_FirstInserted) { array.emplace(1, "Hello"); array.emplace(0, "Goodbye"); EXPECT_TRUE(array.erase(1)); } TEST_F(SparseArrayTest, Erase_SecondInserted) { array.emplace(1, "Hello"); array.emplace(0, "Goodbye"); EXPECT_TRUE(array.erase(0)); } TEST_F(SparseArrayTest, Iteration_Empty) { EXPECT_EQ(array.end(), array.begin()); } TEST_F(SparseArrayTest, Iteration_SizeOne) { array.emplace(0, "Hello"); ASSERT_EQ(1, std::distance(array.begin(), array.end())); std::string expected[] = {"Hello"}; EXPECT_TRUE(std::is_permutation(std::begin(expected), std::end(expected), array.begin())); } TEST_F(SparseArrayTest, Iteration_SizeTwo) { array.emplace(1, "Hello"); array.emplace(0, "Goodbye"); ASSERT_EQ(2, std::distance(array.begin(), array.end())); std::string expected[] = {"Hello", "Goodbye"}; EXPECT_TRUE(std::is_permutation(std::begin(expected), std::end(expected), array.begin())); } TEST(SparseArrayDestructorTest, DoesDestroy) { bool destroyed = false; struct nontrivally_destroyable { bool &destroyed; ~nontrivally_destroyable() { destroyed = true; } }; { sparse_array<nontrivally_destroyable> arr(17); arr.emplace(1, destroyed); } ASSERT_TRUE(destroyed); } } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file whisperMessage.cpp * @author Vladislav Gluhovsky <[email protected]> * @date July 2015 */ #include <thread> #include <boost/test/unit_test.hpp> #include <libwhisper/WhisperDB.h> using namespace std; using namespace dev; using namespace dev::shh; BOOST_AUTO_TEST_SUITE(whisperDB) BOOST_AUTO_TEST_CASE(basic) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Whisper DB..."; string s; string const text1 = "lorem"; string const text2 = "ipsum"; h256 h1(0xBEEF); h256 h2(0xC0FFEE); WhisperDB db; db.kill(h1); db.kill(h2); s = db.lookup(h1); BOOST_REQUIRE(s.empty()); db.insert(h1, text2); s = db.lookup(h2); BOOST_REQUIRE(s.empty()); s = db.lookup(h1); BOOST_REQUIRE(!s.compare(text2)); db.insert(h1, text1); s = db.lookup(h2); BOOST_REQUIRE(s.empty()); s = db.lookup(h1); BOOST_REQUIRE(!s.compare(text1)); db.insert(h2, text2); s = db.lookup(h2); BOOST_REQUIRE(!s.compare(text2)); s = db.lookup(h1); BOOST_REQUIRE(!s.compare(text1)); db.kill(h1); db.kill(h2); s = db.lookup(h2); BOOST_REQUIRE(s.empty()); s = db.lookup(h1); BOOST_REQUIRE(s.empty()); } BOOST_AUTO_TEST_CASE(persistence) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing persistence of Whisper DB..."; string s; string const text1 = "sator"; string const text2 = "arepo"; h256 const h1(0x12345678); h256 const h2(0xBADD00DE); { WhisperDB db; db.kill(h1); db.kill(h2); s = db.lookup(h1); BOOST_REQUIRE(s.empty()); db.insert(h1, text2); s = db.lookup(h2); BOOST_REQUIRE(s.empty()); s = db.lookup(h1); BOOST_REQUIRE(!s.compare(text2)); } this_thread::sleep_for(chrono::milliseconds(20)); { WhisperDB db; db.insert(h1, text1); db.insert(h2, text2); } this_thread::sleep_for(chrono::milliseconds(20)); { WhisperDB db; s = db.lookup(h2); BOOST_REQUIRE(!s.compare(text2)); s = db.lookup(h1); BOOST_REQUIRE(!s.compare(text1)); db.kill(h1); db.kill(h2); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>test added<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file whisperMessage.cpp * @author Vladislav Gluhovsky <[email protected]> * @date July 2015 */ #include <thread> #include <boost/test/unit_test.hpp> #include <libp2p/Host.h> #include <libwhisper/WhisperDB.h> #include <libwhisper/WhisperHost.h> using namespace std; using namespace dev; using namespace dev::shh; BOOST_AUTO_TEST_SUITE(whisperDB) BOOST_AUTO_TEST_CASE(basic) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Whisper DB..."; string s; string const text1 = "lorem"; string const text2 = "ipsum"; h256 h1(0xBEEF); h256 h2(0xC0FFEE); WhisperDB db; db.kill(h1); db.kill(h2); s = db.lookup(h1); BOOST_REQUIRE(s.empty()); db.insert(h1, text2); s = db.lookup(h2); BOOST_REQUIRE(s.empty()); s = db.lookup(h1); BOOST_REQUIRE(!s.compare(text2)); db.insert(h1, text1); s = db.lookup(h2); BOOST_REQUIRE(s.empty()); s = db.lookup(h1); BOOST_REQUIRE(!s.compare(text1)); db.insert(h2, text2); s = db.lookup(h2); BOOST_REQUIRE(!s.compare(text2)); s = db.lookup(h1); BOOST_REQUIRE(!s.compare(text1)); db.kill(h1); db.kill(h2); s = db.lookup(h2); BOOST_REQUIRE(s.empty()); s = db.lookup(h1); BOOST_REQUIRE(s.empty()); } BOOST_AUTO_TEST_CASE(persistence) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing persistence of Whisper DB..."; string s; string const text1 = "sator"; string const text2 = "arepo"; h256 const h1(0x12345678); h256 const h2(0xBADD00DE); { WhisperDB db; db.kill(h1); db.kill(h2); s = db.lookup(h1); BOOST_REQUIRE(s.empty()); db.insert(h1, text2); s = db.lookup(h2); BOOST_REQUIRE(s.empty()); s = db.lookup(h1); BOOST_REQUIRE(!s.compare(text2)); } this_thread::sleep_for(chrono::milliseconds(20)); { WhisperDB db; db.insert(h1, text1); db.insert(h2, text2); } this_thread::sleep_for(chrono::milliseconds(20)); { WhisperDB db; s = db.lookup(h2); BOOST_REQUIRE(!s.compare(text2)); s = db.lookup(h1); BOOST_REQUIRE(!s.compare(text1)); db.kill(h1); db.kill(h2); } } BOOST_AUTO_TEST_CASE(messages) { cnote << "Testing load/save Whisper messages..."; const unsigned TestSize = 3; map<h256, Envelope> m1; map<h256, Envelope> preexisting; KeyPair us = KeyPair::create(); { p2p::Host h("Test"); auto wh = h.registerCapability(new WhisperHost()); preexisting = wh->all(); cnote << preexisting.size() << "preexisting messages in DB"; for (int i = 0; i < TestSize; ++i) wh->post(us.sec(), RLPStream().append(i).out(), BuildTopic("test"), 0xFFFFF); m1 = wh->all(); } { p2p::Host h("Test"); auto wh = h.registerCapability(new WhisperHost()); map<h256, Envelope> m2 = wh->all(); BOOST_REQUIRE_EQUAL(m1.size(), m2.size()); BOOST_REQUIRE_EQUAL(m1.size() - preexisting.size(), TestSize); for (auto i: m1) { RLPStream rlp1; RLPStream rlp2; i.second.streamRLP(rlp1); m2[i.first].streamRLP(rlp2); BOOST_REQUIRE_EQUAL(rlp1.out().size(), rlp2.out().size()); for (unsigned j = 0; j < rlp1.out().size(); ++j) BOOST_REQUIRE_EQUAL(rlp1.out()[j], rlp2.out()[j]); } } WhisperDB db; unsigned x = 0; for (auto i: m1) if (preexisting.find(i.first) == preexisting.end()) { db.kill(i.first); ++x; } BOOST_REQUIRE_EQUAL(x, TestSize); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* ____________________________________________________________________________ Semantics and Coding Component Implementation for the Micro Compiler mcode.cpp Version 2007 James L. Richards Last Update: August 28, 2007 Update by M. J. Wolf: January 21,2016 The routines in this unit are based on those provided in the book "Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr., Benjamin Cummings Publishing Co. (1991). See Section 2.3-2.4, pp. 31-40. ____________________________________________________________________________ */ #include <iostream> #include <fstream> using namespace std; extern ifstream sourceFile; extern ofstream outFile, listFile; #include "mscan.h" // Scanner class definition #include "mcode.h" // CodeGen class definition extern Scanner scan; // global Scanner object declared in micro.cpp // ******************* // ** Constructor ** // ******************* CodeGen::CodeGen() { maxTemp = 0; } // ******************************* // ** Private Member Functions ** // ******************************* void CodeGen::CheckId(ExprRec& var) { if (!LookUp(var.name)) { // variable not declared yet /* FIXME: check variable type */ Enter(var); } } void CodeGen::Enter(ExprRec& var) { /* Create the key and fill it */ symbol_node_t variable; variable.name = var.name; variable.type = var.var_type; /* Check variable size */ switch (var.var_type) { case BOOL: variable.size = 1; /* 1x8 = 8bits */ break; case INT: variable.size = 2; /* 2x8 = 16 bits */ break; case FLOAT: variable.size = 4; /* 4x8 = 32 bits */ break; default: /* TODO: check what to do. Check for cheese? */ break; } /* Add the record to the symbol table */ symbolTable.push_back(variable); } void CodeGen::ExtractExpr(const ExprRec & e, string& s) { string t; int k, n; /* TODO: check variable type */ switch (e.kind) { case ID_EXPR: case TEMP_EXPR: // operand form: +k(R15) s = e.name; k = n = 0; while (symbolTable[n].name != s) { n++; k += symbolTable[n].size; } /* FIXME: check what to do for other types */ IntToAlpha(k, t); s = "+" + t + "(R15)"; break; case LITERAL_EXPR: IntToAlpha(e.ival, t); s = "#" + t; } } string CodeGen::ExtractOp(const OpRec & o) { if (o.op == PLUS) { return "IA "; } else if (o.op == MINUS) { return "IS "; } else if (o.op == MULT) { return "IM "; } else { return "ID "; } } /* TODO: please check this for float + - / * */ string CodeGen::ExtractOpFloat(const OpRec & o) { if (o.op == PLUS) { return "FADD "; } else if (o.op == MINUS) { return "FSUB "; } else if (o.op == MULT) { return "FMUL "; } else { return "FDIV "; } } void CodeGen::Generate(const string & s1, const string & s2, const string & s3) { listFile.width(20); listFile << ' ' << s1; outFile << s1; if (s2.length() > 0) { listFile << s2; outFile << s2; if (s3.length() > 0) { listFile << ',' << s3; outFile << ',' << s3; } } listFile << endl; outFile << endl; } string CodeGen::GetTemp() { /* FIXME: check what to do for other types */ string s; static string t; t = "Temp&"; IntToAlpha(++maxTemp, s); t += s; ExprRec var; var.name = t; var.var_type = INT; CheckId(var); return t; } void CodeGen::IntToAlpha(int val, string& str) { int k; char temp; str = ""; if (val == 0) str = "0"; while (val > 0) { str.append(1, (char)(val % 10 + (int)'0')); val /= 10; } k = int(str.length()); for (int i = 0; i < k/2; i++) { temp = str[i]; str[i] = str[k-i-1]; str[k-i-1] = temp; } } bool CodeGen::LookUp(const string & s) { for (unsigned i = 0; i < symbolTable.size(); i++) if (symbolTable[i].name == s) { return true; } return false; } // ****************************** // ** Public Member Functions ** // ****************************** void CodeGen::Assign(const ExprRec & target, const ExprRec & source) { /* TODO check variable types, add other types */ string s; ExtractExpr(source, s); Generate("LD ", "R0", s); ExtractExpr(target, s); Generate("STO ", "R0", s); } vector<string> str_vect; int str_cnt = 0; int CodeGen::CalcTableSize() { int i, index = 0; for (i = 0; i < symbolTable.size(); i++) { index += symbolTable[i].size; } return index; } void CodeGen::Finish() { string s; listFile.width(6); listFile << ++scan.lineNumber << " " << scan.lineBuffer << endl; Generate("HALT ", "", ""); Generate("LABEL ", "VARS", ""); int table_size = CalcTableSize(); IntToAlpha(table_size, s); Generate("SKIP ", s, ""); Generate("LABEL ", "STRS", ""); while (!str_vect.empty()) { s = str_vect.front(); str_vect.erase(str_vect.begin()); Generate("STRING ", s, ""); } outFile.close(); listFile << endl << endl; listFile << " _____________________________________________\n"; listFile << " <><><><> S Y M B O L T A B L E <><><><>\n" << endl; listFile << " Relative" << endl; listFile << " Address Identifier" << endl; listFile << " -------- --------------------------------" << endl; int i, index = 0; for (i = 0; i < symbolTable.size(); i++) { listFile.width(7); listFile << index << " " << symbolTable[i].name << endl; index += symbolTable[i].size; } listFile << " _____________________________________________" << endl; listFile << endl; listFile << " Normal successful compilation." << endl; listFile.close(); } void CodeGen::GenInfix(const ExprRec & e1, const OpRec & op, const ExprRec & e2, ExprRec& e) { string opnd; /* TODO: check variable type -- should var_type be used for literals? */ if (e1.kind == LITERAL_EXPR && e2.kind == LITERAL_EXPR) { e.kind = LITERAL_EXPR; switch (op.op) { case PLUS: e.ival = e1.ival + e2.ival; break; case MINUS: e.ival = e1.ival - e2.ival; break; case MULT: e.ival = e1.ival * e2.ival; break; case DIV: e.ival = e1.ival / e2.ival; break; } } else { e.kind = TEMP_EXPR; e.name = GetTemp(); ExtractExpr(e1, opnd); Generate("LD ", "R0", opnd); ExtractExpr(e2, opnd); Generate(ExtractOp(op), "R0", opnd); ExtractExpr(e, opnd); Generate("STO ", "R0", opnd); } } void CodeGen::NewLine() { Generate("WRNL ", "", ""); } void CodeGen::ProcessVar(ExprRec& e) { if (!LookUp(e.name)) { /* variable not declared yet */ SemanticError("Variable " + e.name + \ " was not declared before usage."); } else { e.kind = ID_EXPR; e.var_type = INT; /* FIXME: this should be retrieve from the symbol table in the codegen */ } } void CodeGen::ProcessLit(ExprRec& e) { e.kind = LITERAL_EXPR; switch (e.var_type) { case BOOL: /* TODO: check if this works */ e.bval = (scan.tokenBuffer == "True"); break; case INT: e.ival = atoi(scan.tokenBuffer.data()); break; case FLOAT: /* TODO: check size of float, is it float or double? it is double :) */ e.fval = atof(scan.tokenBuffer.data()); break; case CHEESE: e.sval = scan.tokenBuffer; break; } } void CodeGen::ProcessOp(OpRec& o) { string c = scan.tokenBuffer; if (c == "+") { o.op = PLUS; } else if (c == "-") { o.op = MINUS; } else if (c == "*") { o.op = MULT; } else { o.op = DIV; } } void CodeGen::Listen(const ExprRec & inVar) { /* TODO check variable types, add other types */ string s; ExtractExpr(inVar, s); Generate("RDI ", s, ""); } void CodeGen::Start() { Generate("LDA ", "R15", "VARS"); Generate("LDA ", "R14", "STRS"); } void CodeGen::Shout(const ExprRec & outExpr) { switch (outExpr.var_type) { case CHEESE: WriteString(outExpr); break; default: WriteExpr(outExpr); break; } } void CodeGen::WriteExpr(const ExprRec & outExpr) { string s; switch (outExpr.var_type) { case BOOL: /*TODO: please check this statement and check if it is * right how I am vverifying if it is true or false */ //ExtractExpr(outExpr, s); cerr << outExpr.bval << endl; if(outExpr.bval){ Generate("WRI ", "bl", "1"); }else{ Generate("WRI ", "bl", "0"); } break; case INT: ExtractExpr(outExpr, s); Generate("WRI ", s, ""); break; case FLOAT: /*TODO*/ break; default: /*TODO*/ //error as there will always be one of the above. //otherwise we will have the warning after compiling that cheese wasnt handle(but it is in previous function) break; } } void CodeGen::WriteString(const ExprRec & outExpr) { string s, t; /* Save the string */ s = outExpr.sval; str_vect.push_back(s); /* Update counter and Generate ASM */ IntToAlpha(str_cnt, t); str_cnt += scan.cheese_size; if (str_cnt % 2) { str_cnt++; } s = "+" + t + "(R14)"; Generate("WRST ", s, ""); } void CodeGen::DefineVar(ExprRec& var) { /* TODO Start checking variable type */ string varname = scan.tokenBuffer; if (LookUp(varname)) { /* FIXME is this a semantic error? */ SemanticError("Variable " + varname + \ " was already declared before."); } else { /* variable not declared yet */ var.name = varname; Enter(var); /* declare it */ /* TODO Assign 0 to the variable, check if SAM does. */ } } void CodeGen::SemanticError(string msg) { /* FIXME should this be here? */ cout << "Semantic Error: " + msg << endl; exit(1); // abort on any semantic error } <commit_msg>Errors for mixed mode or wrong type arith. operation.<commit_after>/* ____________________________________________________________________________ Semantics and Coding Component Implementation for the Micro Compiler mcode.cpp Version 2007 James L. Richards Last Update: August 28, 2007 Update by M. J. Wolf: January 21,2016 The routines in this unit are based on those provided in the book "Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr., Benjamin Cummings Publishing Co. (1991). See Section 2.3-2.4, pp. 31-40. ____________________________________________________________________________ */ #include <iostream> #include <fstream> using namespace std; extern ifstream sourceFile; extern ofstream outFile, listFile; #include "mscan.h" // Scanner class definition #include "mcode.h" // CodeGen class definition extern Scanner scan; // global Scanner object declared in micro.cpp // ******************* // ** Constructor ** // ******************* CodeGen::CodeGen() { maxTemp = 0; } // ******************************* // ** Private Member Functions ** // ******************************* void CodeGen::CheckId(ExprRec& var) { if (!LookUp(var.name)) { // variable not declared yet /* FIXME: check variable type */ Enter(var); } } void CodeGen::Enter(ExprRec& var) { /* Create the key and fill it */ symbol_node_t variable; variable.name = var.name; variable.type = var.var_type; /* Check variable size */ switch (var.var_type) { case BOOL: variable.size = 1; /* 1x8 = 8bits */ break; case INT: variable.size = 2; /* 2x8 = 16 bits */ break; case FLOAT: variable.size = 4; /* 4x8 = 32 bits */ break; default: /* TODO: check what to do. Check for cheese? */ break; } /* Add the record to the symbol table */ symbolTable.push_back(variable); } void CodeGen::ExtractExpr(const ExprRec & e, string& s) { string t; int k, n; /* TODO: check variable type */ switch (e.kind) { case ID_EXPR: case TEMP_EXPR: // operand form: +k(R15) s = e.name; k = n = 0; while (symbolTable[n].name != s) { n++; k += symbolTable[n].size; } /* FIXME: check what to do for other types */ IntToAlpha(k, t); s = "+" + t + "(R15)"; break; case LITERAL_EXPR: IntToAlpha(e.ival, t); s = "#" + t; } } string CodeGen::ExtractOp(const OpRec & o) { if (o.op == PLUS) { return "IA "; } else if (o.op == MINUS) { return "IS "; } else if (o.op == MULT) { return "IM "; } else { return "ID "; } } /* TODO: please check this for float + - / * */ string CodeGen::ExtractOpFloat(const OpRec & o) { if (o.op == PLUS) { return "FADD "; } else if (o.op == MINUS) { return "FSUB "; } else if (o.op == MULT) { return "FMUL "; } else { return "FDIV "; } } void CodeGen::Generate(const string & s1, const string & s2, const string & s3) { listFile.width(20); listFile << ' ' << s1; outFile << s1; if (s2.length() > 0) { listFile << s2; outFile << s2; if (s3.length() > 0) { listFile << ',' << s3; outFile << ',' << s3; } } listFile << endl; outFile << endl; } string CodeGen::GetTemp() { /* FIXME: check what to do for other types */ string s; static string t; t = "Temp&"; IntToAlpha(++maxTemp, s); t += s; ExprRec var; var.name = t; var.var_type = INT; CheckId(var); return t; } void CodeGen::IntToAlpha(int val, string& str) { int k; char temp; str = ""; if (val == 0) str = "0"; while (val > 0) { str.append(1, (char)(val % 10 + (int)'0')); val /= 10; } k = int(str.length()); for (int i = 0; i < k/2; i++) { temp = str[i]; str[i] = str[k-i-1]; str[k-i-1] = temp; } } bool CodeGen::LookUp(const string & s) { for (unsigned i = 0; i < symbolTable.size(); i++) if (symbolTable[i].name == s) { return true; } return false; } // ****************************** // ** Public Member Functions ** // ****************************** void CodeGen::Assign(const ExprRec & target, const ExprRec & source) { /* TODO check variable types, add other types */ string s; ExtractExpr(source, s); Generate("LD ", "R0", s); ExtractExpr(target, s); Generate("STO ", "R0", s); } vector<string> str_vect; int str_cnt = 0; int CodeGen::CalcTableSize() { int i, index = 0; for (i = 0; i < symbolTable.size(); i++) { index += symbolTable[i].size; } return index; } void CodeGen::Finish() { string s; listFile.width(6); listFile << ++scan.lineNumber << " " << scan.lineBuffer << endl; Generate("HALT ", "", ""); Generate("LABEL ", "VARS", ""); int table_size = CalcTableSize(); IntToAlpha(table_size, s); Generate("SKIP ", s, ""); Generate("LABEL ", "STRS", ""); while (!str_vect.empty()) { s = str_vect.front(); str_vect.erase(str_vect.begin()); Generate("STRING ", s, ""); } outFile.close(); listFile << endl << endl; listFile << " _____________________________________________\n"; listFile << " <><><><> S Y M B O L T A B L E <><><><>\n" << endl; listFile << " Relative" << endl; listFile << " Address Identifier" << endl; listFile << " -------- --------------------------------" << endl; int i, index = 0; for (i = 0; i < symbolTable.size(); i++) { listFile.width(7); listFile << index << " " << symbolTable[i].name << endl; index += symbolTable[i].size; } listFile << " _____________________________________________" << endl; listFile << endl; listFile << " Normal successful compilation." << endl; listFile.close(); } void CodeGen::GenInfix(const ExprRec & e1, const OpRec & op, const ExprRec & e2, ExprRec& e) { if (e1.var_type != e2.var_type) { SemanticError(" mixed-mode arithmetic operations" " are not allowed."); } else if ((e1.var_type != INT) && (e1.var_type != FLOAT)) { SemanticError(" arithmetic opertions are allowed only for" " INTs and FLOATs."); } if (e1.kind == LITERAL_EXPR && e2.kind == LITERAL_EXPR) { e.kind = LITERAL_EXPR; switch (op.op) { case PLUS: e.ival = e1.ival + e2.ival; break; case MINUS: e.ival = e1.ival - e2.ival; break; case MULT: e.ival = e1.ival * e2.ival; break; case DIV: e.ival = e1.ival / e2.ival; break; } } else { string opnd; /* TODO: check variable type */ e.kind = TEMP_EXPR; e.name = GetTemp(); ExtractExpr(e1, opnd); Generate("LD ", "R0", opnd); ExtractExpr(e2, opnd); Generate(ExtractOp(op), "R0", opnd); ExtractExpr(e, opnd); Generate("STO ", "R0", opnd); } } void CodeGen::NewLine() { Generate("WRNL ", "", ""); } void CodeGen::ProcessVar(ExprRec& e) { if (!LookUp(e.name)) { /* variable not declared yet */ SemanticError("Variable " + e.name + \ " was not declared before usage."); } else { e.kind = ID_EXPR; e.var_type = INT; /* FIXME: this should be retrieve from the symbol table in the codegen */ } } void CodeGen::ProcessLit(ExprRec& e) { e.kind = LITERAL_EXPR; switch (e.var_type) { case BOOL: /* TODO: check if this works */ e.bval = (scan.tokenBuffer == "True"); break; case INT: e.ival = atoi(scan.tokenBuffer.data()); break; case FLOAT: /* TODO: check size of float, is it float or double? it is double :) */ e.fval = atof(scan.tokenBuffer.data()); break; case CHEESE: e.sval = scan.tokenBuffer; break; } } void CodeGen::ProcessOp(OpRec& o) { string c = scan.tokenBuffer; if (c == "+") { o.op = PLUS; } else if (c == "-") { o.op = MINUS; } else if (c == "*") { o.op = MULT; } else { o.op = DIV; } } void CodeGen::Listen(const ExprRec & inVar) { /* TODO check variable types, add other types */ string s; ExtractExpr(inVar, s); Generate("RDI ", s, ""); } void CodeGen::Start() { Generate("LDA ", "R15", "VARS"); Generate("LDA ", "R14", "STRS"); } void CodeGen::Shout(const ExprRec & outExpr) { switch (outExpr.var_type) { case CHEESE: WriteString(outExpr); break; default: WriteExpr(outExpr); break; } } void CodeGen::WriteExpr(const ExprRec & outExpr) { string s; switch (outExpr.var_type) { case BOOL: /*TODO: please check this statement and check if it is * right how I am vverifying if it is true or false */ //ExtractExpr(outExpr, s); cerr << outExpr.bval << endl; if(outExpr.bval){ Generate("WRI ", "bl", "1"); }else{ Generate("WRI ", "bl", "0"); } break; case INT: ExtractExpr(outExpr, s); Generate("WRI ", s, ""); break; case FLOAT: /*TODO*/ break; default: /*TODO*/ //error as there will always be one of the above. //otherwise we will have the warning after compiling that cheese wasnt handle(but it is in previous function) break; } } void CodeGen::WriteString(const ExprRec & outExpr) { string s, t; /* Save the string */ s = outExpr.sval; str_vect.push_back(s); /* Update counter and Generate ASM */ IntToAlpha(str_cnt, t); str_cnt += scan.cheese_size; if (str_cnt % 2) { str_cnt++; } s = "+" + t + "(R14)"; Generate("WRST ", s, ""); } void CodeGen::DefineVar(ExprRec& var) { /* TODO Start checking variable type */ string varname = scan.tokenBuffer; if (LookUp(varname)) { /* FIXME is this a semantic error? */ SemanticError("Variable " + varname + \ " was already declared before."); } else { /* variable not declared yet */ var.name = varname; Enter(var); /* declare it */ /* TODO Assign 0 to the variable, check if SAM does. */ } } void CodeGen::SemanticError(string msg) { /* FIXME should this be here? */ cout << " *** Semantic Error: " + msg << endl; exit(1); // abort on any semantic error } <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrInOrderDrawBuffer.h" // We will use the reordering buffer, unless we have NVPR. // TODO move NVPR to batch so we can reorder static inline bool allow_reordering(const GrGpu* gpu) { const GrCaps* caps = gpu->caps(); return caps && caps->shaderCaps() && !caps->shaderCaps()->pathRenderingSupport(); } GrInOrderDrawBuffer::GrInOrderDrawBuffer(GrContext* context) : INHERITED(context) , fCommands(GrCommandBuilder::Create(context->getGpu(), allow_reordering(context->getGpu()))) , fPathIndexBuffer(kPathIdxBufferMinReserve * sizeof(char)/4) , fPathTransformBuffer(kPathXformBufferMinReserve * sizeof(float)/4) , fPipelineBuffer(kPipelineBufferMinReserve) , fDrawID(0) { } GrInOrderDrawBuffer::~GrInOrderDrawBuffer() { this->reset(); } void GrInOrderDrawBuffer::onDrawBatch(GrBatch* batch, const PipelineInfo& pipelineInfo) { State* state = this->setupPipelineAndShouldDraw(batch, pipelineInfo); if (!state) { return; } GrTargetCommands::Cmd* cmd = fCommands->recordDrawBatch(state, batch); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::onStencilPath(const GrPipelineBuilder& pipelineBuilder, const GrPathProcessor* pathProc, const GrPath* path, const GrScissorState& scissorState, const GrStencilSettings& stencilSettings) { GrTargetCommands::Cmd* cmd = fCommands->recordStencilPath(pipelineBuilder, pathProc, path, scissorState, stencilSettings); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::onDrawPath(const GrPathProcessor* pathProc, const GrPath* path, const GrStencilSettings& stencilSettings, const PipelineInfo& pipelineInfo) { State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo); if (!state) { return; } GrTargetCommands::Cmd* cmd = fCommands->recordDrawPath(state, pathProc, path, stencilSettings); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::onDrawPaths(const GrPathProcessor* pathProc, const GrPathRange* pathRange, const void* indices, PathIndexType indexType, const float transformValues[], PathTransformType transformType, int count, const GrStencilSettings& stencilSettings, const PipelineInfo& pipelineInfo) { State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo); if (!state) { return; } GrTargetCommands::Cmd* cmd = fCommands->recordDrawPaths(state, this, pathProc, pathRange, indices, indexType, transformValues, transformType, count, stencilSettings, pipelineInfo); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::onClear(const SkIRect* rect, GrColor color, bool canIgnoreRect, GrRenderTarget* renderTarget) { GrTargetCommands::Cmd* cmd = fCommands->recordClear(rect, color, canIgnoreRect, renderTarget); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::clearStencilClip(const SkIRect& rect, bool insideClip, GrRenderTarget* renderTarget) { GrTargetCommands::Cmd* cmd = fCommands->recordClearStencilClip(rect, insideClip, renderTarget); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::discard(GrRenderTarget* renderTarget) { if (!this->caps()->discardRenderTargetSupport()) { return; } GrTargetCommands::Cmd* cmd = fCommands->recordDiscard(renderTarget); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::onReset() { fCommands->reset(); fPathIndexBuffer.rewind(); fPathTransformBuffer.rewind(); fGpuCmdMarkers.reset(); fPrevState.reset(NULL); // Note, fPrevState points into fPipelineBuffer's allocation, so we have to reset first. // Furthermore, we have to reset fCommands before fPipelineBuffer too. if (fDrawID % kPipelineBufferHighWaterMark) { fPipelineBuffer.rewind(); } else { fPipelineBuffer.reset(); } } void GrInOrderDrawBuffer::onFlush() { fCommands->flush(this); ++fDrawID; } void GrInOrderDrawBuffer::onCopySurface(GrSurface* dst, GrSurface* src, const SkIRect& srcRect, const SkIPoint& dstPoint) { SkASSERT(this->getGpu()->canCopySurface(dst, src, srcRect, dstPoint)); GrTargetCommands::Cmd* cmd = fCommands->recordCopySurface(dst, src, srcRect, dstPoint); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::recordTraceMarkersIfNecessary(GrTargetCommands::Cmd* cmd) { if (!cmd) { return; } const GrTraceMarkerSet& activeTraceMarkers = this->getActiveTraceMarkers(); if (activeTraceMarkers.count() > 0) { if (cmd->isTraced()) { fGpuCmdMarkers[cmd->markerID()].addSet(activeTraceMarkers); } else { cmd->setMarkerID(fGpuCmdMarkers.count()); fGpuCmdMarkers.push_back(activeTraceMarkers); } } } GrTargetCommands::State* GrInOrderDrawBuffer::setupPipelineAndShouldDraw(const GrPrimitiveProcessor* primProc, const GrDrawTarget::PipelineInfo& pipelineInfo) { State* state = this->allocState(primProc); this->setupPipeline(pipelineInfo, state->pipelineLocation()); if (state->getPipeline()->mustSkip()) { this->unallocState(state); return NULL; } state->fPrimitiveProcessor->initBatchTracker(&state->fBatchTracker, state->getPipeline()->getInitBatchTracker()); if (fPrevState && fPrevState->fPrimitiveProcessor.get() && fPrevState->fPrimitiveProcessor->canMakeEqual(fPrevState->fBatchTracker, *state->fPrimitiveProcessor, state->fBatchTracker) && fPrevState->getPipeline()->isEqual(*state->getPipeline())) { this->unallocState(state); } else { fPrevState.reset(state); } this->recordTraceMarkersIfNecessary( fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps())); return fPrevState; } GrTargetCommands::State* GrInOrderDrawBuffer::setupPipelineAndShouldDraw(GrBatch* batch, const GrDrawTarget::PipelineInfo& pipelineInfo) { State* state = this->allocState(); this->setupPipeline(pipelineInfo, state->pipelineLocation()); if (state->getPipeline()->mustSkip()) { this->unallocState(state); return NULL; } batch->initBatchTracker(state->getPipeline()->getInitBatchTracker()); if (fPrevState && !fPrevState->fPrimitiveProcessor.get() && fPrevState->getPipeline()->isEqual(*state->getPipeline())) { this->unallocState(state); } else { fPrevState.reset(state); } this->recordTraceMarkersIfNecessary( fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps())); return fPrevState; } <commit_msg>revert reordering<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrInOrderDrawBuffer.h" // We will use the reordering buffer, unless we have NVPR. // TODO move NVPR to batch so we can reorder static inline bool allow_reordering(const GrGpu* gpu) { //const GrCaps* caps = gpu->caps(); //return caps && caps->shaderCaps() && !caps->shaderCaps()->pathRenderingSupport(); return false; } GrInOrderDrawBuffer::GrInOrderDrawBuffer(GrContext* context) : INHERITED(context) , fCommands(GrCommandBuilder::Create(context->getGpu(), allow_reordering(context->getGpu()))) , fPathIndexBuffer(kPathIdxBufferMinReserve * sizeof(char)/4) , fPathTransformBuffer(kPathXformBufferMinReserve * sizeof(float)/4) , fPipelineBuffer(kPipelineBufferMinReserve) , fDrawID(0) { } GrInOrderDrawBuffer::~GrInOrderDrawBuffer() { this->reset(); } void GrInOrderDrawBuffer::onDrawBatch(GrBatch* batch, const PipelineInfo& pipelineInfo) { State* state = this->setupPipelineAndShouldDraw(batch, pipelineInfo); if (!state) { return; } GrTargetCommands::Cmd* cmd = fCommands->recordDrawBatch(state, batch); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::onStencilPath(const GrPipelineBuilder& pipelineBuilder, const GrPathProcessor* pathProc, const GrPath* path, const GrScissorState& scissorState, const GrStencilSettings& stencilSettings) { GrTargetCommands::Cmd* cmd = fCommands->recordStencilPath(pipelineBuilder, pathProc, path, scissorState, stencilSettings); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::onDrawPath(const GrPathProcessor* pathProc, const GrPath* path, const GrStencilSettings& stencilSettings, const PipelineInfo& pipelineInfo) { State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo); if (!state) { return; } GrTargetCommands::Cmd* cmd = fCommands->recordDrawPath(state, pathProc, path, stencilSettings); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::onDrawPaths(const GrPathProcessor* pathProc, const GrPathRange* pathRange, const void* indices, PathIndexType indexType, const float transformValues[], PathTransformType transformType, int count, const GrStencilSettings& stencilSettings, const PipelineInfo& pipelineInfo) { State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo); if (!state) { return; } GrTargetCommands::Cmd* cmd = fCommands->recordDrawPaths(state, this, pathProc, pathRange, indices, indexType, transformValues, transformType, count, stencilSettings, pipelineInfo); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::onClear(const SkIRect* rect, GrColor color, bool canIgnoreRect, GrRenderTarget* renderTarget) { GrTargetCommands::Cmd* cmd = fCommands->recordClear(rect, color, canIgnoreRect, renderTarget); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::clearStencilClip(const SkIRect& rect, bool insideClip, GrRenderTarget* renderTarget) { GrTargetCommands::Cmd* cmd = fCommands->recordClearStencilClip(rect, insideClip, renderTarget); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::discard(GrRenderTarget* renderTarget) { if (!this->caps()->discardRenderTargetSupport()) { return; } GrTargetCommands::Cmd* cmd = fCommands->recordDiscard(renderTarget); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::onReset() { fCommands->reset(); fPathIndexBuffer.rewind(); fPathTransformBuffer.rewind(); fGpuCmdMarkers.reset(); fPrevState.reset(NULL); // Note, fPrevState points into fPipelineBuffer's allocation, so we have to reset first. // Furthermore, we have to reset fCommands before fPipelineBuffer too. if (fDrawID % kPipelineBufferHighWaterMark) { fPipelineBuffer.rewind(); } else { fPipelineBuffer.reset(); } } void GrInOrderDrawBuffer::onFlush() { fCommands->flush(this); ++fDrawID; } void GrInOrderDrawBuffer::onCopySurface(GrSurface* dst, GrSurface* src, const SkIRect& srcRect, const SkIPoint& dstPoint) { SkASSERT(this->getGpu()->canCopySurface(dst, src, srcRect, dstPoint)); GrTargetCommands::Cmd* cmd = fCommands->recordCopySurface(dst, src, srcRect, dstPoint); this->recordTraceMarkersIfNecessary(cmd); } void GrInOrderDrawBuffer::recordTraceMarkersIfNecessary(GrTargetCommands::Cmd* cmd) { if (!cmd) { return; } const GrTraceMarkerSet& activeTraceMarkers = this->getActiveTraceMarkers(); if (activeTraceMarkers.count() > 0) { if (cmd->isTraced()) { fGpuCmdMarkers[cmd->markerID()].addSet(activeTraceMarkers); } else { cmd->setMarkerID(fGpuCmdMarkers.count()); fGpuCmdMarkers.push_back(activeTraceMarkers); } } } GrTargetCommands::State* GrInOrderDrawBuffer::setupPipelineAndShouldDraw(const GrPrimitiveProcessor* primProc, const GrDrawTarget::PipelineInfo& pipelineInfo) { State* state = this->allocState(primProc); this->setupPipeline(pipelineInfo, state->pipelineLocation()); if (state->getPipeline()->mustSkip()) { this->unallocState(state); return NULL; } state->fPrimitiveProcessor->initBatchTracker(&state->fBatchTracker, state->getPipeline()->getInitBatchTracker()); if (fPrevState && fPrevState->fPrimitiveProcessor.get() && fPrevState->fPrimitiveProcessor->canMakeEqual(fPrevState->fBatchTracker, *state->fPrimitiveProcessor, state->fBatchTracker) && fPrevState->getPipeline()->isEqual(*state->getPipeline())) { this->unallocState(state); } else { fPrevState.reset(state); } this->recordTraceMarkersIfNecessary( fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps())); return fPrevState; } GrTargetCommands::State* GrInOrderDrawBuffer::setupPipelineAndShouldDraw(GrBatch* batch, const GrDrawTarget::PipelineInfo& pipelineInfo) { State* state = this->allocState(); this->setupPipeline(pipelineInfo, state->pipelineLocation()); if (state->getPipeline()->mustSkip()) { this->unallocState(state); return NULL; } batch->initBatchTracker(state->getPipeline()->getInitBatchTracker()); if (fPrevState && !fPrevState->fPrimitiveProcessor.get() && fPrevState->getPipeline()->isEqual(*state->getPipeline())) { this->unallocState(state); } else { fPrevState.reset(state); } this->recordTraceMarkersIfNecessary( fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps())); return fPrevState; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <iomanip> #include <cstdint> #include <string> #include <sys/types.h> #include <dirent.h> #include <sstream> #include <sys/stat.h> #include <cstring> #include "message.H" #include <time.h> #include <stddef.h> #include <cstdio> const uint32_t g_eyecatcher = 0x4F424D43; // OBMC const uint16_t g_version = 1; struct logheader_t { uint32_t eyecatcher; uint16_t version; uint16_t logid; time_t timestamp; uint16_t detailsoffset; uint16_t messagelen; uint16_t severitylen; uint16_t associationlen; uint16_t reportedbylen; uint16_t debugdatalen; }; event_manager::event_manager(string path) { uint16_t x; eventpath = path; latestid = 0; dirp = NULL; logcount = 0; // examine the files being managed and advance latestid to that value while ( (x = next_log()) ) { logcount++; if ( x > latestid ) latestid = x; } return; } event_manager::~event_manager() { if (dirp) closedir(dirp); return; } bool event_manager::is_file_a_log(string str) { std::ostringstream buffer; ifstream f; logheader_t hdr; if (!str.compare(".")) return 0; if (!str.compare("..")) return 0; buffer << eventpath << "/" << str; f.open( buffer.str(), ios::binary); if (!f.good()) { return 0; } f.read((char*)&hdr, sizeof(hdr)); if (hdr.eyecatcher != g_eyecatcher) return 0; return 1; } uint16_t event_manager::log_count(void) { return logcount; } uint16_t event_manager::latest_log_id(void) { return latestid; } uint16_t event_manager::new_log_id(void) { return ++latestid; } void event_manager::next_log_refresh(void) { if (dirp) { closedir(dirp); dirp = NULL; } return; } uint16_t event_manager::next_log(void) { std::ostringstream buffer; struct dirent *ent; uint16_t id; if (dirp == NULL) dirp = opendir(eventpath.c_str()); if (dirp) { do { ent = readdir(dirp); if (ent == NULL) break; string str(ent->d_name); if (is_file_a_log(str)) { id = (uint16_t) atoi(str.c_str()); break; } } while( 1 ); } else { cerr << "Error opening directory " << eventpath << endl; ent = NULL; id = 0; } if (ent == NULL) { closedir(dirp); dirp = NULL; } return ((ent == NULL) ? 0 : id); } uint16_t event_manager::create(event_record_t *rec) { rec->logid = new_log_id(); rec->timestamp = time(NULL); return create_log_event(rec); } inline uint16_t getlen(const char *s) { return (uint16_t) (1 + strlen(s)); } size_t event_manager::get_managed_size(void) { DIR *dirp; std::ostringstream buffer; struct dirent *ent; ifstream f; size_t db_size = 0; dirp = opendir(eventpath.c_str()); if (dirp) { while ( (ent = readdir(dirp)) != NULL ) { string str(ent->d_name); if (is_file_a_log(str)) { buffer.str(""); buffer << eventpath << "/" << str.c_str(); f.open(buffer.str() , ios::in|ios::binary|ios::ate); db_size += f.tellg(); f.close(); } } } closedir(dirp); return (db_size); } uint16_t event_manager::create_log_event(event_record_t *rec) { std::ostringstream buffer; ofstream myfile; logheader_t hdr = {0}; buffer << eventpath << "/" << int(rec->logid) ; hdr.eyecatcher = g_eyecatcher; hdr.version = g_version; hdr.logid = rec->logid; hdr.timestamp = rec->timestamp; hdr.detailsoffset = offsetof(logheader_t, messagelen); hdr.messagelen = getlen(rec->message); hdr.severitylen = getlen(rec->severity); hdr.associationlen = getlen(rec->association); hdr.reportedbylen = getlen(rec->reportedby); hdr.debugdatalen = rec->n; myfile.open(buffer.str() , ios::out|ios::binary); myfile.write((char*) &hdr, sizeof(hdr)); myfile.write((char*) rec->message, hdr.messagelen); myfile.write((char*) rec->severity, hdr.severitylen); myfile.write((char*) rec->association, hdr.associationlen); myfile.write((char*) rec->reportedby, hdr.reportedbylen); myfile.write((char*) rec->p, hdr.debugdatalen); myfile.close(); logcount++; return rec->logid; } int event_manager::open(uint16_t logid, event_record_t **rec) { std::ostringstream buffer; ifstream f; logheader_t hdr; buffer << eventpath << "/" << int(logid); f.open( buffer.str(), ios::binary ); if (!f.good()) { return 0; } *rec = new event_record_t; f.read((char*)&hdr, sizeof(hdr)); (*rec)->logid = hdr.logid; (*rec)->timestamp = hdr.timestamp; (*rec)->message = new char[hdr.messagelen]; f.read((*rec)->message, hdr.messagelen); (*rec)->severity = new char[hdr.severitylen]; f.read((*rec)->severity, hdr.severitylen); (*rec)->association = new char[hdr.associationlen]; f.read((*rec)->association, hdr.associationlen); (*rec)->reportedby = new char[hdr.reportedbylen]; f.read((*rec)->reportedby, hdr.reportedbylen); (*rec)->p = new uint8_t[hdr.debugdatalen]; f.read((char*)(*rec)->p, hdr.debugdatalen); (*rec)->n = hdr.debugdatalen; f.close(); return logid; } void event_manager::close(event_record_t *rec) { delete[] rec->message; delete[] rec->severity; delete[] rec->association; delete[] rec->reportedby; delete[] rec->p; delete rec; logcount--; return ; } int event_manager::remove(uint16_t logid) { std::stringstream buffer; string s; buffer << eventpath << "/" << int(logid); s = buffer.str(); std::remove(s.c_str()); return 0; } <commit_msg>Add flush after writing<commit_after>#include <iostream> #include <fstream> #include <iomanip> #include <cstdint> #include <string> #include <sys/types.h> #include <dirent.h> #include <sstream> #include <sys/stat.h> #include <cstring> #include "message.H" #include <time.h> #include <stddef.h> #include <cstdio> const uint32_t g_eyecatcher = 0x4F424D43; // OBMC const uint16_t g_version = 1; struct logheader_t { uint32_t eyecatcher; uint16_t version; uint16_t logid; time_t timestamp; uint16_t detailsoffset; uint16_t messagelen; uint16_t severitylen; uint16_t associationlen; uint16_t reportedbylen; uint16_t debugdatalen; }; event_manager::event_manager(string path) { uint16_t x; eventpath = path; latestid = 0; dirp = NULL; logcount = 0; // examine the files being managed and advance latestid to that value while ( (x = next_log()) ) { logcount++; if ( x > latestid ) latestid = x; } return; } event_manager::~event_manager() { if (dirp) closedir(dirp); return; } bool event_manager::is_file_a_log(string str) { std::ostringstream buffer; ifstream f; logheader_t hdr; if (!str.compare(".")) return 0; if (!str.compare("..")) return 0; buffer << eventpath << "/" << str; f.open( buffer.str(), ios::binary); if (!f.good()) { f.close(); return 0; } f.read((char*)&hdr, sizeof(hdr)); f.close(); if (hdr.eyecatcher != g_eyecatcher) return 0; return 1; } uint16_t event_manager::log_count(void) { return logcount; } uint16_t event_manager::latest_log_id(void) { return latestid; } uint16_t event_manager::new_log_id(void) { return ++latestid; } void event_manager::next_log_refresh(void) { if (dirp) { closedir(dirp); dirp = NULL; } return; } uint16_t event_manager::next_log(void) { std::ostringstream buffer; struct dirent *ent; uint16_t id; if (dirp == NULL) dirp = opendir(eventpath.c_str()); if (dirp) { do { ent = readdir(dirp); if (ent == NULL) break; string str(ent->d_name); if (is_file_a_log(str)) { id = (uint16_t) atoi(str.c_str()); break; } } while( 1 ); } else { cerr << "Error opening directory " << eventpath << endl; ent = NULL; id = 0; } if (ent == NULL) { closedir(dirp); dirp = NULL; } return ((ent == NULL) ? 0 : id); } uint16_t event_manager::create(event_record_t *rec) { rec->logid = new_log_id(); rec->timestamp = time(NULL); return create_log_event(rec); } inline uint16_t getlen(const char *s) { return (uint16_t) (1 + strlen(s)); } size_t event_manager::get_managed_size(void) { DIR *dirp; std::ostringstream buffer; struct dirent *ent; ifstream f; size_t db_size = 0; dirp = opendir(eventpath.c_str()); if (dirp) { while ( (ent = readdir(dirp)) != NULL ) { string str(ent->d_name); if (is_file_a_log(str)) { buffer.str(""); buffer << eventpath << "/" << str.c_str(); f.open(buffer.str() , ios::in|ios::binary|ios::ate); db_size += f.tellg(); f.close(); } } } closedir(dirp); return (db_size); } uint16_t event_manager::create_log_event(event_record_t *rec) { std::ostringstream buffer; ofstream myfile; logheader_t hdr = {0}; buffer << eventpath << "/" << int(rec->logid) ; hdr.eyecatcher = g_eyecatcher; hdr.version = g_version; hdr.logid = rec->logid; hdr.timestamp = rec->timestamp; hdr.detailsoffset = offsetof(logheader_t, messagelen); hdr.messagelen = getlen(rec->message); hdr.severitylen = getlen(rec->severity); hdr.associationlen = getlen(rec->association); hdr.reportedbylen = getlen(rec->reportedby); hdr.debugdatalen = rec->n; myfile.open(buffer.str() , ios::out|ios::binary); myfile.write((char*) &hdr, sizeof(hdr)); myfile.write((char*) rec->message, hdr.messagelen); myfile.write((char*) rec->severity, hdr.severitylen); myfile.write((char*) rec->association, hdr.associationlen); myfile.write((char*) rec->reportedby, hdr.reportedbylen); myfile.write((char*) rec->p, hdr.debugdatalen); myfile.flush(); myfile.close(); logcount++; return rec->logid; } int event_manager::open(uint16_t logid, event_record_t **rec) { std::ostringstream buffer; ifstream f; logheader_t hdr; buffer << eventpath << "/" << int(logid); f.open( buffer.str(), ios::binary ); if (!f.good()) { return 0; } *rec = new event_record_t; f.read((char*)&hdr, sizeof(hdr)); (*rec)->logid = hdr.logid; (*rec)->timestamp = hdr.timestamp; (*rec)->message = new char[hdr.messagelen]; f.read((*rec)->message, hdr.messagelen); (*rec)->severity = new char[hdr.severitylen]; f.read((*rec)->severity, hdr.severitylen); (*rec)->association = new char[hdr.associationlen]; f.read((*rec)->association, hdr.associationlen); (*rec)->reportedby = new char[hdr.reportedbylen]; f.read((*rec)->reportedby, hdr.reportedbylen); (*rec)->p = new uint8_t[hdr.debugdatalen]; f.read((char*)(*rec)->p, hdr.debugdatalen); (*rec)->n = hdr.debugdatalen; f.close(); return logid; } void event_manager::close(event_record_t *rec) { delete[] rec->message; delete[] rec->severity; delete[] rec->association; delete[] rec->reportedby; delete[] rec->p; delete rec; logcount--; return ; } int event_manager::remove(uint16_t logid) { std::stringstream buffer; string s; buffer << eventpath << "/" << int(logid); s = buffer.str(); std::remove(s.c_str()); return 0; } <|endoftext|>
<commit_before>/* * References: * [FTE1] http://eprint.iacr.org/2012/494.pdf * [FTE2] (to appear summer 2014) */ #include <math.h> #include "fte/fte.h" #include "ffx/ffx.h" namespace fte { Fte::Fte() { ffx_ = ffx::Ffx(kFfxRadix); key_is_set_ = false; languages_are_set_ = false; } /* * Here we set our input/output langauges and verify that the output langauge has * capacity at least as large as the input language. */ bool Fte::SetLanguages(const std::string & plaintext_dfa, uint32_t plaintext_max_len, const std::string & ciphertext_dfa, uint32_t ciphertext_max_len) { plaintext_ranker_ = ranking::DfaRanker(); plaintext_ranker_.SetLanguage(plaintext_dfa, plaintext_max_len); plaintext_ranker_.WordsInLanguage(&words_in_plaintext_language_); plaintext_language_capacity_in_bits_ = mpz_sizeinbase(words_in_plaintext_language_.get_mpz_t(), kFfxRadix); bool languages_are_the_same = (plaintext_dfa == ciphertext_dfa) && (plaintext_max_len == ciphertext_max_len); if (languages_are_the_same) { ciphertext_ranker_ = plaintext_ranker_; } else { ciphertext_ranker_ = ranking::DfaRanker(); ciphertext_ranker_.SetLanguage(ciphertext_dfa, ciphertext_max_len); } ciphertext_ranker_.WordsInLanguage(&words_in_ciphertext_language_); ciphertext_language_capacity_in_bits_ = mpz_sizeinbase( words_in_ciphertext_language_.get_mpz_t(), kFfxRadix); if(words_in_plaintext_language_ > words_in_ciphertext_language_) { return false; } languages_are_set_ = true; return true; } bool Fte::set_key(const std::string & key) { bool success = ffx_.SetKey(key); key_is_set_ = success; return success; } /* * This is an implementation of rank-encipher-unrank, as described in [FTE2]. * We perform cycle walking to ensure that we have a ciphertext in the input * domain of the ciphertext ranker. */ bool Fte::Encrypt(const std::string & plaintext, std::string * ciphertext) { if (!key_is_set_) { return false; } if (!languages_are_set_) { return false; } mpz_class plaintext_rank; plaintext_ranker_.Rank(plaintext, &plaintext_rank); mpz_class C = 0; ffx_.Encrypt(plaintext_rank, ciphertext_language_capacity_in_bits_, &C); while (C >= words_in_ciphertext_language_) { ffx_.Encrypt(C, ciphertext_language_capacity_in_bits_, &C); } ciphertext_ranker_.Unrank(C, ciphertext); return true; } /* * Here we recover a plaintext using rank-decipher-unrank. * See [FTE2] for more details. */ bool Fte::Decrypt(const std::string & ciphertext, std::string * plaintext) { if (!key_is_set_) { return false; } if (!languages_are_set_) { return false; } mpz_class C; ciphertext_ranker_.Rank(ciphertext, &C); mpz_class plaintext_rank = 0; ffx_.Decrypt(C, ciphertext_language_capacity_in_bits_, &plaintext_rank); while (plaintext_rank >= words_in_plaintext_language_) { ffx_.Decrypt(plaintext_rank, ciphertext_language_capacity_in_bits_, &plaintext_rank); } plaintext_ranker_.Unrank(plaintext_rank, plaintext); return true; } } // namespace fte <commit_msg>Issue #13: use the plaintext size as the VIL-blockcipher width<commit_after>/* * References: * [FTE1] http://eprint.iacr.org/2012/494.pdf * [FTE2] (to appear summer 2014) */ #include <math.h> #include "fte/fte.h" #include "ffx/ffx.h" namespace fte { Fte::Fte() { ffx_ = ffx::Ffx(kFfxRadix); key_is_set_ = false; languages_are_set_ = false; } /* * Here we set our input/output langauges and verify that the output langauge has * capacity at least as large as the input language. */ bool Fte::SetLanguages(const std::string & plaintext_dfa, uint32_t plaintext_max_len, const std::string & ciphertext_dfa, uint32_t ciphertext_max_len) { plaintext_ranker_ = ranking::DfaRanker(); plaintext_ranker_.SetLanguage(plaintext_dfa, plaintext_max_len); plaintext_ranker_.WordsInLanguage(&words_in_plaintext_language_); plaintext_language_capacity_in_bits_ = mpz_sizeinbase(words_in_plaintext_language_.get_mpz_t(), kFfxRadix); bool languages_are_the_same = (plaintext_dfa == ciphertext_dfa) && (plaintext_max_len == ciphertext_max_len); if (languages_are_the_same) { ciphertext_ranker_ = plaintext_ranker_; } else { ciphertext_ranker_ = ranking::DfaRanker(); ciphertext_ranker_.SetLanguage(ciphertext_dfa, ciphertext_max_len); } ciphertext_ranker_.WordsInLanguage(&words_in_ciphertext_language_); ciphertext_language_capacity_in_bits_ = mpz_sizeinbase( words_in_ciphertext_language_.get_mpz_t(), kFfxRadix); if(words_in_plaintext_language_ > words_in_ciphertext_language_) { return false; } languages_are_set_ = true; return true; } bool Fte::set_key(const std::string & key) { bool success = ffx_.SetKey(key); key_is_set_ = success; return success; } /* * This is an implementation of rank-encipher-unrank, as described in [FTE2]. * We perform cycle walking to ensure that we have a ciphertext in the input * domain of the ciphertext ranker. */ bool Fte::Encrypt(const std::string & plaintext, std::string * ciphertext) { if (!key_is_set_) { return false; } if (!languages_are_set_) { return false; } mpz_class plaintext_rank; plaintext_ranker_.Rank(plaintext, &plaintext_rank); mpz_class C = 0; ffx_.Encrypt(plaintext_rank, plaintext_language_capacity_in_bits_, &C); while (C >= words_in_ciphertext_language_) { ffx_.Encrypt(C, plaintext_language_capacity_in_bits_, &C); } ciphertext_ranker_.Unrank(C, ciphertext); return true; } /* * Here we recover a plaintext using rank-decipher-unrank. * See [FTE2] for more details. */ bool Fte::Decrypt(const std::string & ciphertext, std::string * plaintext) { if (!key_is_set_) { return false; } if (!languages_are_set_) { return false; } mpz_class C; ciphertext_ranker_.Rank(ciphertext, &C); mpz_class plaintext_rank = 0; ffx_.Decrypt(C, plaintext_language_capacity_in_bits_, &plaintext_rank); while (plaintext_rank >= words_in_plaintext_language_) { ffx_.Decrypt(plaintext_rank, plaintext_language_capacity_in_bits_, &plaintext_rank); } plaintext_ranker_.Unrank(plaintext_rank, plaintext); return true; } } // namespace fte <|endoftext|>
<commit_before>#include "mainwindow.h" #include "types.h" #include "connectiontester.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->startButton, SIGNAL(clicked()), this, SLOT(startClicked())); connect(ui->actionConnection_does_not_work, SIGNAL(triggered()), this, SLOT(noConnectionClicked())); connect(ui->actionConnection_is_slow, SIGNAL(triggered()), this, SLOT(connectionSlowClicked())); connect(ui->action_Quit, SIGNAL(triggered()), qApp, SLOT(quit())); #ifndef Q_OS_MAC // Mac applications don't use icons setWindowIcon(QIcon(":/tray.png")); #endif // Q_OS_MAC // No reason to continue when there is no system tray supported if (!QSystemTrayIcon::isSystemTrayAvailable()) return; QIcon trayIcon; #ifdef Q_OS_MAC trayIcon.addFile(":/tray_mac.png"); trayIcon.addFile(":/tray_mac_active.png", QSize(), QIcon::Selected); #else // Q_OS_MAC trayIcon.addFile(":/tray.png"); #endif // Q_OS_MAC m_tray.setIcon(trayIcon); m_tray.setContextMenu(ui->menu_File); m_tray.setToolTip(tr("mPlane client")); m_tray.show(); } MainWindow::~MainWindow() { m_tray.hide(); delete ui; } void MainWindow::setClient(Client *client) { if (client == m_client) return; if (m_client) { disconnect(m_client.data(), SIGNAL(statusChanged()), this, SLOT(statusChanged())); } m_client = client; if (m_client) { connect(m_client.data(), SIGNAL(statusChanged()), this, SLOT(statusChanged())); // Update methods statusChanged(); // Update variables m_negotiator.setManagerSocket(m_client->managerSocket()); } } Client *MainWindow::client() const { return m_client; } void MainWindow::startClicked() { // Don't continue when client is no registered if (m_client->status() != Client::Registered) { return; } Q_ASSERT(m_client); RemoteInfoList remotes = m_client->remoteInfo(); Q_ASSERT(!remotes.isEmpty()); RemoteInfo remote = remotes.first(); m_negotiator.sendRequest(remote.peerAddress, remote.peerPort); } void MainWindow::noConnectionClicked() { ConnectionTester tester; connect(&tester, SIGNAL(message(QString,MessageType)), ui->textEdit, SLOT(append(QString))); tester.start(); } void MainWindow::connectionSlowClicked() { } void MainWindow::statusChanged() { ui->startButton->setEnabled( m_client->status() == Client::Registered ); ui->statusbar->showMessage( enumToString(Client, "Status", m_client->status()) ); } <commit_msg>Mac can't handle selected state in tray area, so we remove it.<commit_after>#include "mainwindow.h" #include "types.h" #include "connectiontester.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->startButton, SIGNAL(clicked()), this, SLOT(startClicked())); connect(ui->actionConnection_does_not_work, SIGNAL(triggered()), this, SLOT(noConnectionClicked())); connect(ui->actionConnection_is_slow, SIGNAL(triggered()), this, SLOT(connectionSlowClicked())); connect(ui->action_Quit, SIGNAL(triggered()), qApp, SLOT(quit())); #ifndef Q_OS_MAC // Mac applications don't use icons setWindowIcon(QIcon(":/tray.png")); #endif // Q_OS_MAC // No reason to continue when there is no system tray supported if (!QSystemTrayIcon::isSystemTrayAvailable()) return; QIcon trayIcon; #ifdef Q_OS_MAC trayIcon.addFile(":/tray_mac.png"); #else // Q_OS_MAC trayIcon.addFile(":/tray.png"); #endif // Q_OS_MAC m_tray.setIcon(trayIcon); m_tray.setContextMenu(ui->menu_File); m_tray.setToolTip(tr("mPlane client")); m_tray.show(); } MainWindow::~MainWindow() { m_tray.hide(); delete ui; } void MainWindow::setClient(Client *client) { if (client == m_client) return; if (m_client) { disconnect(m_client.data(), SIGNAL(statusChanged()), this, SLOT(statusChanged())); } m_client = client; if (m_client) { connect(m_client.data(), SIGNAL(statusChanged()), this, SLOT(statusChanged())); // Update methods statusChanged(); // Update variables m_negotiator.setManagerSocket(m_client->managerSocket()); } } Client *MainWindow::client() const { return m_client; } void MainWindow::startClicked() { // Don't continue when client is no registered if (m_client->status() != Client::Registered) { return; } Q_ASSERT(m_client); RemoteInfoList remotes = m_client->remoteInfo(); Q_ASSERT(!remotes.isEmpty()); RemoteInfo remote = remotes.first(); m_negotiator.sendRequest(remote.peerAddress, remote.peerPort); } void MainWindow::noConnectionClicked() { ConnectionTester tester; connect(&tester, SIGNAL(message(QString,MessageType)), ui->textEdit, SLOT(append(QString))); tester.start(); } void MainWindow::connectionSlowClicked() { } void MainWindow::statusChanged() { ui->startButton->setEnabled( m_client->status() == Client::Registered ); ui->statusbar->showMessage( enumToString(Client, "Status", m_client->status()) ); } <|endoftext|>
<commit_before>/** * \file * <!-- * Copyright 2015 Develer S.r.l. (http://www.develer.com/) * --> * * \brief main cutecom-ng window * * \author Aurelien Rainone <[email protected]> */ #include <algorithm> #include <iterator> #include <QUiLoader> #include <QLineEdit> #include <QPropertyAnimation> #include "mainwindow.h" #include "ui_mainwindow.h" #include "connectdialog.h" #include "sessionmanager.h" #include "outputmanager.h" #include "searchhighlighter.h" /// line ending char appended to the commands sent to the serial port const QString LINE_ENDING = "\n"; /// maximum count of document blocks for the bootom output const int MAX_OUTPUT_LINES = 100; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), search_widget(0), search_input(0) { ui->setupUi(this); // create session and output managers output_mgr = new OutputManager(this); session_mgr = new SessionManager(this); connect_dlg = new ConnectDialog(this); // load search widget and hide it QUiLoader loader; QFile file(":/searchwidget.ui"); file.open(QFile::ReadOnly); search_widget = loader.load(&file, ui->mainOutput); Q_ASSERT_X(search_widget, "MainWindow::MainWindow", "error while loading searchwidget.ui"); file.close(); search_input = search_widget->findChild<QLineEdit*>("searchInput"); Q_ASSERT_X(search_input, "MainWindow::MainWindow", "didn't find searchInput"); // to make widget appear on top of : NOT WORKING // search_widget->setWindowFlags(search_widget->windowFlags() | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint); // search_widget->setWindowModality(Qt::WindowModal); search_widget->hide(); // show connection dialog connect(ui->connectButton, &QAbstractButton::clicked, connect_dlg, &ConnectDialog::show); // handle reception of new data from serial port connect(session_mgr, &SessionManager::dataReceived, this, &MainWindow::handleDataReceived); // get data formatted for display and show it in output view connect(output_mgr, &OutputManager::dataConverted, this, &MainWindow::addDataToView); // get data formatted for display and show it in output view connect(ui->inputBox, &HistoryComboBox::lineEntered, this, &MainWindow::handleNewInput); // clear output manager buffer at session start connect(session_mgr, &SessionManager::sessionStarted, output_mgr, &OutputManager::clear); // clear output text connect(session_mgr, &SessionManager::sessionStarted, ui->mainOutput, &QPlainTextEdit::clear); // call openSession when user accepts/closes connection dialog connect(connect_dlg, &ConnectDialog::openDeviceClicked, session_mgr, &SessionManager::openSession); connect(ui->splitOutputBtn, &QToolButton::clicked, this, &MainWindow::toggleOutputSplitter); // additional configuration for bottom output ui->bottomOutput->hide(); ui->bottomOutput->document()->setMaximumBlockCount(MAX_OUTPUT_LINES); ui->bottomOutput->viewport()->installEventFilter(this); // create the search results highlighter and connect search-related signals/slots search_highlighter = new SearchHighlighter(ui->mainOutput->document()); connect(ui->searchButton, &QToolButton::toggled, this, &MainWindow::showSearchWidget); connect(search_input, &QLineEdit::textChanged, search_highlighter, &SearchHighlighter::setSearchString); } MainWindow::~MainWindow() { delete ui; } void MainWindow::handleNewInput(QString entry) { // if session is not open, this also keeps user input if (session_mgr->isSessionOpen()) { entry.append(LINE_ENDING); session_mgr->sendToSerial(entry.toLocal8Bit()); ui->inputBox->clearEditText(); } } void MainWindow::addDataToView(const QString & textdata) { // problem : QTextEdit interprets a '\r' as a new line, so if a buffer ending // with '\r\n' happens to be cut in the middle, there will be 1 extra // line jump in the QTextEdit. To prevent we remove ending '\r' and // prepend them to the next received buffer // flag indicating that the previously received buffer ended with CR static bool prev_ends_with_CR = false; QString newdata; if (prev_ends_with_CR) { // CR was removed at the previous buffer, so now we prepend it newdata.append('\r'); prev_ends_with_CR = false; } if (textdata.length() > 0) { QString::const_iterator end_cit = textdata.cend(); if (textdata.endsWith('\r')) { // if buffer ends with CR, we don't copy it end_cit--; prev_ends_with_CR = true; } std::copy(textdata.begin(), end_cit, std::back_inserter(newdata)); } // record end cursor position before adding text QTextCursor prev_end_cursor(ui->mainOutput->document()); prev_end_cursor.movePosition(QTextCursor::End); if (ui->bottomOutput->isVisible()) { // append text to the top output and stay at current position QTextCursor cursor(ui->mainOutput->document()); cursor.movePosition(QTextCursor::End); cursor.insertText(newdata); } else { // append text to the top output and scroll down ui->mainOutput->moveCursor(QTextCursor::End); ui->mainOutput->insertPlainText(newdata); } // append text to bottom output and scroll ui->bottomOutput->moveCursor(QTextCursor::End); ui->bottomOutput->insertPlainText(newdata); // handleSearchTextChanged(search_input->text()); } void MainWindow::handleDataReceived(const QByteArray &data) { (*output_mgr) << data; } void MainWindow::toggleOutputSplitter() { ui->bottomOutput->setVisible(!ui->bottomOutput->isVisible()); } bool MainWindow::eventFilter(QObject *target, QEvent *event) { if (event->type() == QEvent::Wheel) return true; // base class behaviour return QMainWindow::eventFilter(target, event); } void MainWindow::resizeEvent(QResizeEvent *event) { // todo :remove hardcoded values search_widget->setGeometry(event->size().width() - search_widget->width() - 40, -2, 300, 40); // base class implementations QMainWindow::resizeEvent(event); } void MainWindow::showSearchWidget(bool show) { QPropertyAnimation *animation = new QPropertyAnimation(search_widget, "geometry"); animation->setDuration(150); QRect showed_pos(this->size().width() - search_widget->width() - 40, -2, 300, 40); QRect hidden_pos(this->size().width() - search_widget->width() - 40, -40, 300, 40); animation->setStartValue(show ? hidden_pos : showed_pos); animation->setEndValue(show ? showed_pos : hidden_pos); animation->start(); search_widget->setVisible(true); } <commit_msg>hide search widget on ESC keypress<commit_after>/** * \file * <!-- * Copyright 2015 Develer S.r.l. (http://www.develer.com/) * --> * * \brief main cutecom-ng window * * \author Aurelien Rainone <[email protected]> */ #include <algorithm> #include <iterator> #include <QUiLoader> #include <QLineEdit> #include <QPropertyAnimation> #include "mainwindow.h" #include "ui_mainwindow.h" #include "connectdialog.h" #include "sessionmanager.h" #include "outputmanager.h" #include "searchhighlighter.h" /// line ending char appended to the commands sent to the serial port const QString LINE_ENDING = "\n"; /// maximum count of document blocks for the bootom output const int MAX_OUTPUT_LINES = 100; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), search_widget(0), search_input(0) { ui->setupUi(this); // create session and output managers output_mgr = new OutputManager(this); session_mgr = new SessionManager(this); connect_dlg = new ConnectDialog(this); // load search widget and hide it QUiLoader loader; QFile file(":/searchwidget.ui"); file.open(QFile::ReadOnly); search_widget = loader.load(&file, ui->mainOutput); Q_ASSERT_X(search_widget, "MainWindow::MainWindow", "error while loading searchwidget.ui"); file.close(); search_input = search_widget->findChild<QLineEdit*>("searchInput"); Q_ASSERT_X(search_input, "MainWindow::MainWindow", "didn't find searchInput"); // to make widget appear on top of : NOT WORKING // search_widget->setWindowFlags(search_widget->windowFlags() | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint); // search_widget->setWindowModality(Qt::WindowModal); search_widget->hide(); // show connection dialog connect(ui->connectButton, &QAbstractButton::clicked, connect_dlg, &ConnectDialog::show); // handle reception of new data from serial port connect(session_mgr, &SessionManager::dataReceived, this, &MainWindow::handleDataReceived); // get data formatted for display and show it in output view connect(output_mgr, &OutputManager::dataConverted, this, &MainWindow::addDataToView); // get data formatted for display and show it in output view connect(ui->inputBox, &HistoryComboBox::lineEntered, this, &MainWindow::handleNewInput); // clear output manager buffer at session start connect(session_mgr, &SessionManager::sessionStarted, output_mgr, &OutputManager::clear); // clear output text connect(session_mgr, &SessionManager::sessionStarted, ui->mainOutput, &QPlainTextEdit::clear); // call openSession when user accepts/closes connection dialog connect(connect_dlg, &ConnectDialog::openDeviceClicked, session_mgr, &SessionManager::openSession); connect(ui->splitOutputBtn, &QToolButton::clicked, this, &MainWindow::toggleOutputSplitter); // additional configuration for bottom output ui->bottomOutput->hide(); ui->bottomOutput->document()->setMaximumBlockCount(MAX_OUTPUT_LINES); ui->bottomOutput->viewport()->installEventFilter(this); // create the search results highlighter and connect search-related signals/slots search_highlighter = new SearchHighlighter(ui->mainOutput->document()); connect(ui->searchButton, &QToolButton::toggled, this, &MainWindow::showSearchWidget); connect(search_input, &QLineEdit::textChanged, search_highlighter, &SearchHighlighter::setSearchString); search_input->installEventFilter(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::handleNewInput(QString entry) { // if session is not open, this also keeps user input if (session_mgr->isSessionOpen()) { entry.append(LINE_ENDING); session_mgr->sendToSerial(entry.toLocal8Bit()); ui->inputBox->clearEditText(); } } void MainWindow::addDataToView(const QString & textdata) { // problem : QTextEdit interprets a '\r' as a new line, so if a buffer ending // with '\r\n' happens to be cut in the middle, there will be 1 extra // line jump in the QTextEdit. To prevent we remove ending '\r' and // prepend them to the next received buffer // flag indicating that the previously received buffer ended with CR static bool prev_ends_with_CR = false; QString newdata; if (prev_ends_with_CR) { // CR was removed at the previous buffer, so now we prepend it newdata.append('\r'); prev_ends_with_CR = false; } if (textdata.length() > 0) { QString::const_iterator end_cit = textdata.cend(); if (textdata.endsWith('\r')) { // if buffer ends with CR, we don't copy it end_cit--; prev_ends_with_CR = true; } std::copy(textdata.begin(), end_cit, std::back_inserter(newdata)); } // record end cursor position before adding text QTextCursor prev_end_cursor(ui->mainOutput->document()); prev_end_cursor.movePosition(QTextCursor::End); if (ui->bottomOutput->isVisible()) { // append text to the top output and stay at current position QTextCursor cursor(ui->mainOutput->document()); cursor.movePosition(QTextCursor::End); cursor.insertText(newdata); } else { // append text to the top output and scroll down ui->mainOutput->moveCursor(QTextCursor::End); ui->mainOutput->insertPlainText(newdata); } // append text to bottom output and scroll ui->bottomOutput->moveCursor(QTextCursor::End); ui->bottomOutput->insertPlainText(newdata); // handleSearchTextChanged(search_input->text()); } void MainWindow::handleDataReceived(const QByteArray &data) { (*output_mgr) << data; } void MainWindow::toggleOutputSplitter() { ui->bottomOutput->setVisible(!ui->bottomOutput->isVisible()); } bool MainWindow::eventFilter(QObject *target, QEvent *event) { if (event->type() == QEvent::Wheel) return true; if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Escape && search_widget->isVisible()) { emit ui->searchButton->toggle(); } } // base class behaviour return QMainWindow::eventFilter(target, event); } void MainWindow::resizeEvent(QResizeEvent *event) { // todo :remove hardcoded values search_widget->setGeometry(event->size().width() - search_widget->width() - 40, -2, 300, 40); // base class implementations QMainWindow::resizeEvent(event); } void MainWindow::showSearchWidget(bool show) { QPropertyAnimation *animation = new QPropertyAnimation(search_widget, "geometry"); animation->setDuration(150); QRect showed_pos(this->size().width() - search_widget->width() - 40, -2, 300, 40); QRect hidden_pos(this->size().width() - search_widget->width() - 40, -40, 300, 40); animation->setStartValue(show ? hidden_pos : showed_pos); animation->setEndValue(show ? showed_pos : hidden_pos); animation->start(); search_widget->setVisible(true); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include <cmath> /** * Performs appropriate actions every time timer is called. * grab keyboard x error bad window merrick said it seems like an issue that you can't fix with my code, but rather something about qt or the vm get rid of player image, set player coordinates, set explosion image to that location, recreate player * @return nothing */ void MainWindow::handleTimer() { bg->scroll(0, WINDOW_MAX_X); bg2->scroll(0, WINDOW_MAX_X); c->move(); a->move(); d->move(); mb->move(); t->move(); moveCount++; /** if(mousePressed) { p->moveUp(game_min_y); } else if(moveCount == 15) { moveCount = 0; p->moveDown(game_min_y); } **/ } /** * Function is called every time a tile is clicked. * * @param e Mouse event * @return nothing */ void MainWindow::keyPressEvent(QKeyEvent *e) { //setFocusPolicy(Qt::StrongFocus); //std::cout<<"key"; switch(e->key()) { case Qt::Key_Up: std::cout<<"Up\n"; p->moveUp(game_min_y); p->moveUp(game_min_y); p->moveUp(game_min_y); break; case Qt::Key_Down: std::cout<<"Down\n"; p->moveDown(game_max_y); p->moveDown(game_max_y); p->moveDown(game_max_y); break; default: QWidget::keyPressEvent(e); } /** if(e->key() == Qt::Key_Q) { std::cout<<"Up\n"; //p->moveUp(); } else if(e->key() == Qt::Key_Down) { std::cout<<"Down\n"; //p->moveDown(); } **/ } /** * Pauses the app. * * @return nothing */ void MainWindow::pauseApp() { //p->moveDown(game_max_y); p->moveUp(game_min_y); /** if(timer->isActive()) { timer->stop(); } else { timer->start(); } **/ } /** * Sets up the game every time the start button is pressed. * * @return nothing */ void MainWindow::startGame() { userName = userNameLine->text(); if(userName != "") { gameStarted = true; nameLine->setText(userName); userNameLine->setText(""); errors->setText(""); livesLine->setText("3"); pointsLine->setText("0"); popupView->close(); userName = userNameLine->text(); createBackground(); playerImage = new QPixmap("images/astronaut.jpg"); *playerImage = playerImage->scaledToHeight(70); p = new Player(playerImage); timer->start(); //p->setPos(500, 500); scene->addItem(p); c = new Coin(coinImage, WINDOW_MAX_X - 50, 300, this); scene->addItem(c); a = new Alien(alienImage, WINDOW_MAX_X - 75, 400, this); scene->addItem(a); d = new Doctor(doctorImage, WINDOW_MAX_X, WINDOW_MAX_Y -100, this); scene->addItem(d); mb = new MoneyBag(moneybagImage, WINDOW_MAX_X, 250, this); scene->addItem(mb); t = new Turtle(turtleImage, WINDOW_MAX_X, WINDOW_MAX_Y-45, this); scene->addItem(t); this->grabKeyboard(); } else { errorsExists = true; errors->setText("Enter a name above!"); } } void MainWindow::callPopup() { popupView->show(); } void MainWindow::cancelPopup() { userNameLine->setText(""); errors->setText(""); popupView->close(); } /** * Constructor for the MainWindow * * @return nothing */ //MainWindow::MainWindow(QWidget* parent) : QWidget(parent) MainWindow::MainWindow(QMainWindow* parent) : QMainWindow(parent) { //this->setFocusPolicy(Qt::StrongFocus); scene = new QGraphicsScene(); view = new QGraphicsView( scene ); layout = new QFormLayout(); window = new QWidget(); gameStarted = false; initializeVariables(); createPopup(); createButtons(); createOutput(); QPalette pal(palette()); //pal.setColor(QPalette::Background, QColor(152, 251, 152, 200)); //pal.setColor(QPalette::Background, QColor(138, 43, 226, 50)); pal.setColor(QPalette::Background, QColor(75, 209, 214, 100)); window->setAutoFillBackground(true); window->setPalette(pal); view->setLayout(layout); window->setLayout(layout); window->setFixedSize(WINDOW_MAX_X-3, game_min_y); view->setAlignment(Qt::AlignLeft | Qt::AlignTop); scene->addWidget(window); view->setFixedSize( WINDOW_MAX_X, WINDOW_MAX_Y); qreal _w = WINDOW_MAX_X - 3; qreal _h = WINDOW_MAX_Y - 3; qreal _x = 0; qreal _y = 0; scene->setSceneRect(_x, _y, _w, _h); view->setWindowTitle( "Space Invasion"); //setting IMAGES of 5 things! coinImage = new QPixmap("images/coin.png"); *coinImage = coinImage->scaledToHeight(30); alienImage = new QPixmap("images/alien2.jpg"); *alienImage = alienImage->scaledToHeight(60); doctorImage = new QPixmap("images/doctor.jpg"); *doctorImage = doctorImage->scaledToHeight(60); moneybagImage = new QPixmap("images/money-bag.png"); *moneybagImage = moneybagImage->scaledToHeight(40); turtleImage = new QPixmap("images/spaceturtle.gif"); *turtleImage = turtleImage->scaledToHeight(45); //This is how we do animation. We use a timer with an interval of 20 milliseconds //We connect the signal from the timer - the timeout() function to a function //of our own - called handleTimer - which is in this same MainWindow class timer = new QTimer(this); timer->setInterval(35); //connects connect(timer, SIGNAL(timeout()), this, SLOT(handleTimer())); connect(quit, SIGNAL(clicked()), qApp, SLOT(quit())); connect(start, SIGNAL(clicked()), this, SLOT(callPopup())); connect(popupStart, SIGNAL(clicked()), this, SLOT(startGame())); connect(popupCancel, SIGNAL(clicked()), this, SLOT(cancelPopup())); connect(pause, SIGNAL(clicked()), this, SLOT(pauseApp())); //setFocus(); view->setFocus(); //std::cout<<QApplication::focusWidget(); } /** * Displays the MainWindow * * @return nothing */ void MainWindow::show() { //This is how we get our view displayed. window->show(); view->show(); } void MainWindow::initializeVariables() { game_max_y = WINDOW_MAX_Y; game_min_y = WINDOW_MAX_Y/5 - 20; mousePressed = false; moveCount = 0; } void MainWindow::createPopup() { popupScene = new QGraphicsScene(); popupView = new QGraphicsView(popupScene); popupLayout = new QFormLayout(); popupWindow = new QWidget(); popupView->setAlignment(Qt::AlignLeft | Qt::AlignTop); popupView->setGeometry(WINDOW_MAX_X/2 - 80, WINDOW_MAX_Y/2, 300, 120); popupWindow->setGeometry(0, 0, 300 -3, 120 -3); popupNameLabel = new QLabel(); popupNameLine = new QLineEdit(); popupStart = new QPushButton("Start"); popupCancel = new QPushButton("Cancel"); userNameLabel = new QLabel("Enter name: "); userNameLine = new QLineEdit(); errorsExists = false; errors = new QLineEdit(); h1 = new QHBoxLayout(); h1->addWidget(userNameLabel); h1->addWidget(userNameLine); h2 = new QHBoxLayout(); h2->addWidget(popupStart); h2->addWidget(popupCancel); popupLayout->addItem(h2); popupLayout->addItem(h1); popupLayout->addWidget(errors); //popupLayout->addRow(userNameLabel, userNameLine); //popupLayout->addRow(popupStart, popupCancel); //popupView->setLayout(popupLayout); popupWindow->setLayout(popupLayout); errors->setText(""); errors->setReadOnly(true); popupView->setAlignment(Qt::AlignLeft | Qt::AlignTop); popupScene->addWidget(popupWindow); popupView->setWindowTitle( "Start Screen"); } void MainWindow::createButtons() { startStopLayout = new QHBoxLayout(); start = new QPushButton("Start Game"); pause = new QPushButton("Pause"); quit = new QPushButton("Quit"); startStopLayout->addWidget(start); startStopLayout->addWidget(pause); startStopLayout->addWidget(quit); layout->addRow(startStopLayout); } void MainWindow::createOutput() { labelsLayout = new QHBoxLayout(); outputLayout = new QHBoxLayout(); nameLabel = new QLabel("Name:"); livesLabel = new QLabel("Lives:"); pointsLabel = new QLabel("Points:"); labelsLayout->addWidget(nameLabel); labelsLayout->addWidget(livesLabel); labelsLayout->addWidget(pointsLabel); layout->addRow(labelsLayout); nameLine = new QLineEdit(); livesLine = new QLineEdit(); pointsLine = new QLineEdit(); nameLine->setReadOnly(true); livesLine->setReadOnly(true); pointsLine->setReadOnly(true); outputLayout->addWidget(nameLine); outputLayout->addWidget(livesLine); outputLayout->addWidget(pointsLine); layout->addRow(outputLayout); } void MainWindow::removeCoin(Coin *c) { scene->removeItem(c); } void MainWindow::createBackground() { bgImage = new QPixmap("images/stars.jpg"); *bgImage = bgImage->scaled(WINDOW_MAX_X + 3, game_max_y - game_min_y, Qt::IgnoreAspectRatio, Qt::FastTransformation); bg = new Background(bgImage, 0, game_min_y); scene->addItem(bg); bg2 = new Background(bgImage, WINDOW_MAX_X, game_min_y); scene->addItem(bg2); } /** * Destructor * * @return nothing */ MainWindow::~MainWindow() { timer->stop(); delete timer; delete scene; delete view; } <commit_msg>Trying to debug error messages<commit_after>#include "mainwindow.h" #include <cmath> /** * Performs appropriate actions every time timer is called. * grab keyboard x error bad window merrick said it seems like an issue that you can't fix with my code, but rather something about qt or the vm get rid of player image, set player coordinates, set explosion image to that location, recreate player * @return nothing */ void MainWindow::handleTimer() { bg->scroll(0, WINDOW_MAX_X); bg2->scroll(0, WINDOW_MAX_X); c->move(); a->move(); d->move(); mb->move(); t->move(); moveCount++; /** if(mousePressed) { p->moveUp(game_min_y); } else if(moveCount == 15) { moveCount = 0; p->moveDown(game_min_y); } **/ } /** * Function is called every time a tile is clicked. * * @param e Mouse event * @return nothing */ void MainWindow::keyPressEvent(QKeyEvent *e) { //setFocusPolicy(Qt::StrongFocus); //std::cout<<"key"; switch(e->key()) { case Qt::Key_Up: std::cout<<"Up\n"; p->moveUp(game_min_y); p->moveUp(game_min_y); p->moveUp(game_min_y); break; case Qt::Key_Down: std::cout<<"Down\n"; p->moveDown(game_max_y); p->moveDown(game_max_y); p->moveDown(game_max_y); break; default: QWidget::keyPressEvent(e); } /** if(e->key() == Qt::Key_Q) { std::cout<<"Up\n"; //p->moveUp(); } else if(e->key() == Qt::Key_Down) { std::cout<<"Down\n"; //p->moveDown(); } **/ } /** * Pauses the app. * * @return nothing */ void MainWindow::pauseApp() { //p->moveDown(game_max_y); p->moveUp(game_min_y); /** if(timer->isActive()) { timer->stop(); } else { timer->start(); } **/ } /** * Sets up the game every time the start button is pressed. * * @return nothing */ void MainWindow::startGame() { userName = userNameLine->text(); if(userName != "") { gameStarted = true; nameLine->setText(userName); userNameLine->setText(""); errors->setText(""); livesLine->setText("3"); pointsLine->setText("0"); popupView->close(); userName = userNameLine->text(); createBackground(); playerImage = new QPixmap("images/astronaut.jpg"); *playerImage = playerImage->scaledToHeight(70); p = new Player(playerImage); timer->start(); //p->setPos(500, 500); scene->addItem(p); c = new Coin(coinImage, WINDOW_MAX_X - 50, 300, this); scene->addItem(c); a = new Alien(alienImage, WINDOW_MAX_X - 75, 400, this); scene->addItem(a); d = new Doctor(doctorImage, WINDOW_MAX_X, WINDOW_MAX_Y -100, this); scene->addItem(d); mb = new MoneyBag(moneybagImage, WINDOW_MAX_X, 250, this); scene->addItem(mb); t = new Turtle(turtleImage, WINDOW_MAX_X, WINDOW_MAX_Y-45, this); scene->addItem(t); this->grabKeyboard(); } else { errorsExists = true; errors->setText("Enter a name above!"); } } void MainWindow::callPopup() { popupView->grabKeyboard(); popupView->show(); } void MainWindow::cancelPopup() { userNameLine->setText(""); errors->setText(""); popupView->close(); } /** * Constructor for the MainWindow * * @return nothing */ //MainWindow::MainWindow(QWidget* parent) : QWidget(parent) MainWindow::MainWindow(QMainWindow* parent) : QMainWindow(parent) { //this->setFocusPolicy(Qt::StrongFocus); scene = new QGraphicsScene(); view = new QGraphicsView( scene ); layout = new QFormLayout(); window = new QWidget(); gameStarted = false; initializeVariables(); createPopup(); createButtons(); createOutput(); QPalette pal(palette()); //pal.setColor(QPalette::Background, QColor(152, 251, 152, 200)); //pal.setColor(QPalette::Background, QColor(138, 43, 226, 50)); pal.setColor(QPalette::Background, QColor(75, 209, 214, 100)); window->setAutoFillBackground(true); window->setPalette(pal); view->setLayout(layout); window->setLayout(layout); window->setFixedSize(WINDOW_MAX_X-3, game_min_y); view->setAlignment(Qt::AlignLeft | Qt::AlignTop); scene->addWidget(window); view->setFixedSize( WINDOW_MAX_X, WINDOW_MAX_Y); qreal _w = WINDOW_MAX_X - 3; qreal _h = WINDOW_MAX_Y - 3; qreal _x = 0; qreal _y = 0; scene->setSceneRect(_x, _y, _w, _h); view->setWindowTitle( "Space Invasion"); //setting IMAGES of 5 things! coinImage = new QPixmap("images/coin.png"); *coinImage = coinImage->scaledToHeight(30); alienImage = new QPixmap("images/alien2.jpg"); *alienImage = alienImage->scaledToHeight(60); doctorImage = new QPixmap("images/doctor.jpg"); *doctorImage = doctorImage->scaledToHeight(60); moneybagImage = new QPixmap("images/money-bag.png"); *moneybagImage = moneybagImage->scaledToHeight(40); turtleImage = new QPixmap("images/spaceturtle.gif"); *turtleImage = turtleImage->scaledToHeight(45); //This is how we do animation. We use a timer with an interval of 20 milliseconds //We connect the signal from the timer - the timeout() function to a function //of our own - called handleTimer - which is in this same MainWindow class timer = new QTimer(this); timer->setInterval(35); //connects connect(timer, SIGNAL(timeout()), this, SLOT(handleTimer())); connect(quit, SIGNAL(clicked()), qApp, SLOT(quit())); connect(start, SIGNAL(clicked()), this, SLOT(callPopup())); connect(popupStart, SIGNAL(clicked()), this, SLOT(startGame())); connect(popupCancel, SIGNAL(clicked()), this, SLOT(cancelPopup())); connect(pause, SIGNAL(clicked()), this, SLOT(pauseApp())); //setFocus(); view->setFocus(); //std::cout<<QApplication::focusWidget(); } /** * Displays the MainWindow * * @return nothing */ void MainWindow::show() { //This is how we get our view displayed. window->show(); view->show(); } void MainWindow::initializeVariables() { game_max_y = WINDOW_MAX_Y; game_min_y = WINDOW_MAX_Y/5 - 20; mousePressed = false; moveCount = 0; } void MainWindow::createPopup() { popupScene = new QGraphicsScene(); popupView = new QGraphicsView(popupScene); popupLayout = new QFormLayout(); popupWindow = new QWidget(); popupView->setAlignment(Qt::AlignLeft | Qt::AlignTop); popupView->setGeometry(WINDOW_MAX_X/2 - 80, WINDOW_MAX_Y/2, 300, 120); popupWindow->setGeometry(0, 0, 300 -3, 120 -3); popupNameLabel = new QLabel(); popupNameLine = new QLineEdit(); popupStart = new QPushButton("Start"); popupCancel = new QPushButton("Cancel"); userNameLabel = new QLabel("Enter name: "); userNameLine = new QLineEdit(); errorsExists = false; errors = new QLineEdit(); h1 = new QHBoxLayout(); h1->addWidget(userNameLabel); h1->addWidget(userNameLine); h2 = new QHBoxLayout(); h2->addWidget(popupStart); h2->addWidget(popupCancel); popupLayout->addItem(h2); popupLayout->addItem(h1); popupLayout->addWidget(errors); //popupLayout->addRow(userNameLabel, userNameLine); //popupLayout->addRow(popupStart, popupCancel); //popupView->setLayout(popupLayout); popupWindow->setLayout(popupLayout); errors->setText(""); errors->setReadOnly(true); popupView->setAlignment(Qt::AlignLeft | Qt::AlignTop); popupScene->addWidget(popupWindow); popupView->setWindowTitle( "Start Screen"); } void MainWindow::createButtons() { startStopLayout = new QHBoxLayout(); start = new QPushButton("Start Game"); pause = new QPushButton("Pause"); quit = new QPushButton("Quit"); startStopLayout->addWidget(start); startStopLayout->addWidget(pause); startStopLayout->addWidget(quit); layout->addRow(startStopLayout); } void MainWindow::createOutput() { labelsLayout = new QHBoxLayout(); outputLayout = new QHBoxLayout(); nameLabel = new QLabel("Name:"); livesLabel = new QLabel("Lives:"); pointsLabel = new QLabel("Points:"); labelsLayout->addWidget(nameLabel); labelsLayout->addWidget(livesLabel); labelsLayout->addWidget(pointsLabel); layout->addRow(labelsLayout); nameLine = new QLineEdit(); livesLine = new QLineEdit(); pointsLine = new QLineEdit(); nameLine->setReadOnly(true); livesLine->setReadOnly(true); pointsLine->setReadOnly(true); outputLayout->addWidget(nameLine); outputLayout->addWidget(livesLine); outputLayout->addWidget(pointsLine); layout->addRow(outputLayout); } void MainWindow::removeCoin(Coin *c) { scene->removeItem(c); } void MainWindow::createBackground() { bgImage = new QPixmap("images/stars.jpg"); *bgImage = bgImage->scaled(WINDOW_MAX_X + 3, game_max_y - game_min_y, Qt::IgnoreAspectRatio, Qt::FastTransformation); bg = new Background(bgImage, 0, game_min_y); scene->addItem(bg); bg2 = new Background(bgImage, WINDOW_MAX_X, game_min_y); scene->addItem(bg2); } /** * Destructor * * @return nothing */ MainWindow::~MainWindow() { timer->stop(); delete timer; delete scene; delete view; } <|endoftext|>
<commit_before>#include "source.h" #include <iostream> #include "sourcefile.h" #include <boost/property_tree/json_parser.hpp> #include <fstream> #include <boost/timer/timer.hpp> #define log( var ) \ std::cout << "source.cc (" << __LINE__ << ") " << #var << std::endl Source::Location:: Location(int line_number, int column_offset) : line_number_(line_number), column_offset_(column_offset) { } Source::Location:: Location(const Source::Location &org) : line_number_(org.line_number_), column_offset_(org.column_offset_) { } Source::Range:: Range(const Location &start, const Location &end, int kind) : start_(start), end_(end), kind_(kind) { } Source::Range:: Range(const Source::Range &org) : start_(org.start_), end_(org.end_), kind_(org.kind_) { } ////////////// //// View //// ////////////// Source::View::View() { override_font(Pango::FontDescription("Monospace")); } string Source::View::GetLine(const Gtk::TextIter &begin) { Gtk::TextIter end(begin); while (!end.ends_line()) end++; return begin.get_text(end); } // Source::View::ApplyTheme() // Applies theme in textview void Source::View::ApplyConfig(const Source::Config &config) { for (auto &item : config.tagtable()) { get_buffer()->create_tag(item.first)->property_foreground() = item.second; } } // Source::View::Config::Config(Config &config) // copy-constructor Source::Config::Config(const Source::Config &original) { SetTagTable(original.tagtable()); SetTypeTable(original.typetable()); } Source::Config::Config() {} // Source::View::Config::tagtable() // returns a const refrence to the tagtable const std::unordered_map<string, string>& Source::Config::tagtable() const { return tagtable_; } // Source::View::Config::tagtable() // returns a const refrence to the tagtable const std::unordered_map<string, string>& Source::Config::typetable() const { return typetable_; } void Source::Config::InsertTag(const string &key, const string &value) { tagtable_[key] = value; } // Source::View::Config::SetTagTable() // sets the tagtable for the view void Source::Config:: SetTypeTable(const std::unordered_map<string, string> &typetable) { typetable_ = typetable; } void Source::Config::InsertType(const string &key, const string &value) { typetable_[key] = value; } // Source::View::Config::SetTagTable() // sets the tagtable for the view void Source::Config:: SetTagTable(const std::unordered_map<string, string> &tagtable) { tagtable_ = tagtable; } /////////////// //// Model //// /////////////// Source::Model::Model(const Source::Config &config) : config_(config) { } void Source::Model:: InitSyntaxHighlighting(const std::string &filepath, const std::string &project_path, const std::string &text, int start_offset, int end_offset) { set_file_path(filepath); set_project_path(project_path); std::vector<const char*> arguments = get_compilation_commands(); tu_ = clang::TranslationUnit(true, filepath, arguments, text); } // Source::View::UpdateLine void Source::View:: OnLineEdit(const std::vector<Source::Range> &locations, const Source::Config &config) { log("before onupdatesyntax"); OnUpdateSyntax(locations, config); log("after onupdatesyntax"); } // Source::Model::UpdateLine int Source::Model:: ReParse(const std::string &buffer) { return tu_.ReparseTranslationUnit(file_path(), buffer); } // Source::Controller::OnLineEdit() // fired when a line in the buffer is edited void Source::Controller::OnLineEdit() { } // sets the filepath for this mvc void Source::Model:: set_file_path(const std::string &file_path) { file_path_ = file_path; } // sets the project path for this mvc void Source::Model:: set_project_path(const std::string &project_path) { project_path_ = project_path; } // gets the file_path member const std::string& Source::Model::file_path() const { return file_path_; } // gets the project_path member const std::string& Source::Model::project_path() const { return project_path_; } // gets the config member const Source::Config& Source::Model::config() const { return config_; } std::vector<const char*> Source::Model:: get_compilation_commands() { clang::CompilationDatabase db(project_path()+"/"); clang::CompileCommands commands(file_path(), &db); std::vector<clang::CompileCommand> cmds = commands.get_commands(); std::vector<const char*> arguments; for (auto &i : cmds) { std::vector<std::string> lol = i.get_command_as_args(); for (int a = 1; a < lol.size()-4; a++) { arguments.emplace_back(lol[a].c_str()); } } return arguments; } std::vector<Source::Range> Source::Model:: ExtractTokens(int start_offset, int end_offset) { std::vector<Source::Range> ranges; clang::SourceLocation start(&tu_, file_path(), start_offset); clang::SourceLocation end(&tu_, file_path(), end_offset); clang::SourceRange range(&start, &end); clang::Tokens tokens(&tu_, &range); std::vector<clang::Token> tks = tokens.tokens(); for (auto &token : tks) { switch (token.kind()) { case 0: HighlightCursor(&token, &ranges); break; // PunctuationToken case 1: HighlightToken(&token, &ranges, 702); break; // KeywordToken case 2: HighlightCursor(&token, &ranges); break; // IdentifierToken case 3: HighlightToken(&token, &ranges, 109); break; // LiteralToken case 4: HighlightToken(&token, &ranges, 705); break; // CommentToken } } log("returns ranges"); return ranges; } void Source::Model:: HighlightCursor(clang::Token *token, std::vector<Source::Range> *source_ranges) { clang::SourceLocation location = token->get_source_location(&tu_); clang::Cursor cursor(&tu_, &location); clang::SourceRange range(&cursor); clang::SourceLocation begin(&range, true); clang::SourceLocation end(&range, false); unsigned begin_line_num, begin_offset, end_line_num, end_offset; begin.get_location_info(NULL, &begin_line_num, &begin_offset, NULL); end.get_location_info(NULL, &end_line_num, &end_offset, NULL); source_ranges->emplace_back(Source::Location(begin_line_num, begin_offset), Source::Location(end_line_num, end_offset), (int) cursor.kind()); } void Source::Model:: HighlightToken(clang::Token *token, std::vector<Source::Range> *source_ranges, int token_kind) { clang::SourceRange range = token->get_source_range(&tu_); unsigned begin_line_num, begin_offset, end_line_num, end_offset; clang::SourceLocation begin(&range, true); clang::SourceLocation end(&range, false); begin.get_location_info(NULL, &begin_line_num, &begin_offset, NULL); end.get_location_info(NULL, &end_line_num, &end_offset, NULL); source_ranges->emplace_back(Source::Location(begin_line_num, begin_offset), Source::Location(end_line_num, end_offset), token_kind); } //////////////////// //// Controller //// //////////////////// // Source::Controller::Controller() // Constructor for Controller Source::Controller::Controller(const Source::Config &config) : model_(config) { } // Source::Controller::view() // return shared_ptr to the view Source::View& Source::Controller::view() { return view_; } // Source::Controller::model() // return shared_ptr to the model() Source::Model& Source::Controller::model() { return model_; } void Source::Controller::OnNewEmptyFile() { string filename("/tmp/juci_t"); sourcefile s(filename); model().set_file_path(filename); model().set_project_path(filename); s.save(""); } string extract_file_path(const std::string &file_path) { return file_path.substr(0, file_path.find_last_of('/')); } std::vector<std::string> extentions() { return {".h", ".cc", ".cpp", ".hpp"}; } bool check_extention(const std::string &file_path) { std::string extention = file_path.substr(file_path.find_last_of('.'), file_path.size()); for (auto &ex : extentions()) { if (extention == ex) { return true; } } return false; } void Source::View::OnUpdateSyntax(const std::vector<Source::Range> &ranges, const Source::Config &config) { if (ranges.empty() || ranges.size() == 0) { log("ranges empty"); return; } Glib::RefPtr<Gtk::TextBuffer> buffer = get_buffer(); log("after getting buffer"); int i = 0; log("after i int"); std::cout << "rangeslengde: " << ranges.size() << std::endl; for (auto &range : ranges) { string type = std::to_string(range.kind()); try { config.typetable().at(type); } catch (std::exception) { continue; } int linum_start = range.start().line_number()-1; int linum_end = range.end().line_number()-1; int begin = range.start().column_offset()-1; int end = range.end().column_offset()-1; if (end < 0) end = 0; if (begin < 0) begin = 0; Gtk::TextIter begin_iter = buffer->get_iter_at_line_offset(linum_start, begin); Gtk::TextIter end_iter = buffer->get_iter_at_line_offset(linum_end, end); buffer->remove_all_tags(begin_iter, end_iter); if (begin_iter.get_line() == end_iter.get_line()) { buffer->apply_tag_by_name(config.typetable().at(type), begin_iter, end_iter); } i++; } log("End of onupdatesyntax"); } void Source::Controller::OnOpenFile(const string &filepath) { sourcefile s(filepath); buffer()->set_text(s.get_content()); int start_offset = buffer()->begin().get_offset(); int end_offset = buffer()->end().get_offset(); if (check_extention(filepath)) { view().ApplyConfig(model().config()); model().InitSyntaxHighlighting(filepath, extract_file_path(filepath), buffer()->get_text().raw(), start_offset, end_offset); view().OnUpdateSyntax(model().ExtractTokens(start_offset, end_offset), model().config()); } buffer()->signal_end_user_action().connect([this]() { if (!go) { std::thread parse([this]() { if(parsing.try_lock()) { const std::string raw = buffer()->get_text().raw(); int b = model().ReParse(raw); if (b == 0) { if (raw == buffer()->get_text().raw()) { log("alike!"); syntax.lock(); go = true; syntax.unlock(); } else { log("buffer changed"); } } parsing.unlock(); } }); parse.detach(); } }); buffer()->signal_begin_user_action().connect([this]() { if (go) { syntax.lock(); view(). OnUpdateSyntax(model().ExtractTokens(0, buffer()->get_text().size()), model().config()); go = false; syntax.unlock(); } }); } Glib::RefPtr<Gtk::TextBuffer> Source::Controller::buffer() { return view().get_buffer(); } <commit_msg>fix syntax<commit_after>#include "source.h" #include <iostream> #include "sourcefile.h" #include <boost/property_tree/json_parser.hpp> #include <fstream> #include <boost/timer/timer.hpp> #define log( var ) \ std::cout << "source.cc (" << __LINE__ << ") " << #var << std::endl Source::Location:: Location(int line_number, int column_offset) : line_number_(line_number), column_offset_(column_offset) { } Source::Location:: Location(const Source::Location &org) : line_number_(org.line_number_), column_offset_(org.column_offset_) { } Source::Range:: Range(const Location &start, const Location &end, int kind) : start_(start), end_(end), kind_(kind) { } Source::Range:: Range(const Source::Range &org) : start_(org.start_), end_(org.end_), kind_(org.kind_) { } ////////////// //// View //// ////////////// Source::View::View() { override_font(Pango::FontDescription("Monospace")); } string Source::View::GetLine(const Gtk::TextIter &begin) { Gtk::TextIter end(begin); while (!end.ends_line()) end++; return begin.get_text(end); } // Source::View::ApplyTheme() // Applies theme in textview void Source::View::ApplyConfig(const Source::Config &config) { for (auto &item : config.tagtable()) { get_buffer()->create_tag(item.first)->property_foreground() = item.second; } } // Source::View::Config::Config(Config &config) // copy-constructor Source::Config::Config(const Source::Config &original) { SetTagTable(original.tagtable()); SetTypeTable(original.typetable()); } Source::Config::Config() {} // Source::View::Config::tagtable() // returns a const refrence to the tagtable const std::unordered_map<string, string>& Source::Config::tagtable() const { return tagtable_; } // Source::View::Config::tagtable() // returns a const refrence to the tagtable const std::unordered_map<string, string>& Source::Config::typetable() const { return typetable_; } void Source::Config::InsertTag(const string &key, const string &value) { tagtable_[key] = value; } // Source::View::Config::SetTagTable() // sets the tagtable for the view void Source::Config:: SetTypeTable(const std::unordered_map<string, string> &typetable) { typetable_ = typetable; } void Source::Config::InsertType(const string &key, const string &value) { typetable_[key] = value; } // Source::View::Config::SetTagTable() // sets the tagtable for the view void Source::Config:: SetTagTable(const std::unordered_map<string, string> &tagtable) { tagtable_ = tagtable; } /////////////// //// Model //// /////////////// Source::Model::Model(const Source::Config &config) : config_(config) { } void Source::Model:: InitSyntaxHighlighting(const std::string &filepath, const std::string &project_path, const std::string &text, int start_offset, int end_offset) { set_file_path(filepath); set_project_path(project_path); std::vector<const char*> arguments = get_compilation_commands(); tu_ = clang::TranslationUnit(true, filepath, arguments, text); } // Source::View::UpdateLine void Source::View:: OnLineEdit(const std::vector<Source::Range> &locations, const Source::Config &config) { OnUpdateSyntax(locations, config); } // Source::Model::UpdateLine int Source::Model:: ReParse(const std::string &buffer) { return tu_.ReparseTranslationUnit(file_path(), buffer); } // Source::Controller::OnLineEdit() // fired when a line in the buffer is edited void Source::Controller::OnLineEdit() { } // sets the filepath for this mvc void Source::Model:: set_file_path(const std::string &file_path) { file_path_ = file_path; } // sets the project path for this mvc void Source::Model:: set_project_path(const std::string &project_path) { project_path_ = project_path; } // gets the file_path member const std::string& Source::Model::file_path() const { return file_path_; } // gets the project_path member const std::string& Source::Model::project_path() const { return project_path_; } // gets the config member const Source::Config& Source::Model::config() const { return config_; } std::vector<const char*> Source::Model:: get_compilation_commands() { clang::CompilationDatabase db(project_path()+"/"); clang::CompileCommands commands(file_path(), &db); std::vector<clang::CompileCommand> cmds = commands.get_commands(); std::vector<const char*> arguments; for (auto &i : cmds) { std::vector<std::string> lol = i.get_command_as_args(); for (int a = 1; a < lol.size()-4; a++) { arguments.emplace_back(lol[a].c_str()); } } return arguments; } std::vector<Source::Range> Source::Model:: ExtractTokens(int start_offset, int end_offset) { std::vector<Source::Range> ranges; clang::SourceLocation start(&tu_, file_path(), start_offset); clang::SourceLocation end(&tu_, file_path(), end_offset); clang::SourceRange range(&start, &end); clang::Tokens tokens(&tu_, &range); std::vector<clang::Token> tks = tokens.tokens(); for (auto &token : tks) { switch (token.kind()) { case 0: HighlightCursor(&token, &ranges); break; // PunctuationToken case 1: HighlightToken(&token, &ranges, 702); break; // KeywordToken case 2: HighlightCursor(&token, &ranges); break; // IdentifierToken case 3: HighlightToken(&token, &ranges, 109); break; // LiteralToken case 4: HighlightToken(&token, &ranges, 705); break; // CommentToken } } return ranges; } void Source::Model:: HighlightCursor(clang::Token *token, std::vector<Source::Range> *source_ranges) { clang::SourceLocation location = token->get_source_location(&tu_); clang::Cursor cursor(&tu_, &location); clang::SourceRange range(&cursor); clang::SourceLocation begin(&range, true); clang::SourceLocation end(&range, false); unsigned begin_line_num, begin_offset, end_line_num, end_offset; begin.get_location_info(NULL, &begin_line_num, &begin_offset, NULL); end.get_location_info(NULL, &end_line_num, &end_offset, NULL); source_ranges->emplace_back(Source::Location(begin_line_num, begin_offset), Source::Location(end_line_num, end_offset), (int) cursor.kind()); } void Source::Model:: HighlightToken(clang::Token *token, std::vector<Source::Range> *source_ranges, int token_kind) { clang::SourceRange range = token->get_source_range(&tu_); unsigned begin_line_num, begin_offset, end_line_num, end_offset; clang::SourceLocation begin(&range, true); clang::SourceLocation end(&range, false); begin.get_location_info(NULL, &begin_line_num, &begin_offset, NULL); end.get_location_info(NULL, &end_line_num, &end_offset, NULL); source_ranges->emplace_back(Source::Location(begin_line_num, begin_offset), Source::Location(end_line_num, end_offset), token_kind); } //////////////////// //// Controller //// //////////////////// // Source::Controller::Controller() // Constructor for Controller Source::Controller::Controller(const Source::Config &config) : model_(config) { } // Source::Controller::view() // return shared_ptr to the view Source::View& Source::Controller::view() { return view_; } // Source::Controller::model() // return shared_ptr to the model() Source::Model& Source::Controller::model() { return model_; } void Source::Controller::OnNewEmptyFile() { string filename("/tmp/juci_t"); sourcefile s(filename); model().set_file_path(filename); model().set_project_path(filename); s.save(""); } string extract_file_path(const std::string &file_path) { return file_path.substr(0, file_path.find_last_of('/')); } std::vector<std::string> extentions() { return {".h", ".cc", ".cpp", ".hpp"}; } bool check_extention(const std::string &file_path) { std::string extention = file_path.substr(file_path.find_last_of('.'), file_path.size()); for (auto &ex : extentions()) { if (extention == ex) { return true; } } return false; } void Source::View::OnUpdateSyntax(const std::vector<Source::Range> &ranges, const Source::Config &config) { if (ranges.empty() || ranges.size() == 0) { return; } Glib::RefPtr<Gtk::TextBuffer> buffer = get_buffer(); buffer->remove_all_tags(buffer->begin(), buffer->end()); int i = 0; for (auto &range : ranges) { string type = std::to_string(range.kind()); try { config.typetable().at(type); } catch (std::exception) { continue; } int linum_start = range.start().line_number()-1; int linum_end = range.end().line_number()-1; int begin = range.start().column_offset()-1; int end = range.end().column_offset()-1; if (end < 0) end = 0; if (begin < 0) begin = 0; Gtk::TextIter begin_iter = buffer->get_iter_at_line_offset(linum_start, begin); Gtk::TextIter end_iter = buffer->get_iter_at_line_offset(linum_end, end); if (begin_iter.get_line() == end_iter.get_line()) { buffer->apply_tag_by_name(config.typetable().at(type), begin_iter, end_iter); } i++; } } void Source::Controller::OnOpenFile(const string &filepath) { sourcefile s(filepath); buffer()->set_text(s.get_content()); int start_offset = buffer()->begin().get_offset(); int end_offset = buffer()->end().get_offset(); if (check_extention(filepath)) { view().ApplyConfig(model().config()); model().InitSyntaxHighlighting(filepath, extract_file_path(filepath), buffer()->get_text().raw(), start_offset, end_offset); view().OnUpdateSyntax(model().ExtractTokens(start_offset, end_offset), model().config()); } buffer()->signal_end_user_action().connect([this]() { if (!go) { std::thread parse([this]() { if (parsing.try_lock()) { while (true) { const std::string raw = buffer()->get_text().raw(); if (model().ReParse(raw) == 0 && raw == buffer()->get_text().raw()) { syntax.lock(); go = true; syntax.unlock(); break; } } parsing.unlock(); } }); parse.detach(); } }); buffer()->signal_begin_user_action().connect([this]() { if (go) { syntax.lock(); view(). OnUpdateSyntax(model().ExtractTokens(0, buffer()->get_text().size()), model().config()); go = false; syntax.unlock(); } }); } Glib::RefPtr<Gtk::TextBuffer> Source::Controller::buffer() { return view().get_buffer(); } <|endoftext|>
<commit_before>#include "model.h" #include <string> #include <algorithm> #include <map> double figures::Segment::getApproximateDistanceToBorder(const Point &p) { double res = std::min((p - a).length(), (p - b).length()); // Please note that here we do not care about floatint-point error, // as if 'start' falls near 'a' or 'b', we've already calculated it if (Point::dotProduct(p - a, b - a) >= 0 && Point::dotProduct(p - b, a - b) >= 0) { res = std::min(res, getDistanceToLine(p)); } return res; } double figures::Segment::getDistanceToLine(const Point &p) { // Coefficients of A*x + B*y + C = 0 double A = b.y - a.y; double B = a.x - b.x; double C = -A * a.x - B * a.y; // normalization of the equation double D = sqrt(A * A + B * B); if (fabs(D) < 1e-8) { return HUGE_VAL; } // degenerate case A /= D; B /= D; C /= D; return fabs(A * p.x + B * p.y + C); } double figures::Rectangle::getApproximateDistanceToBorder(const Point &p) { bool inX = box.leftDown.x <= p.x && p.x <= box.rightUp.x; bool inY = box.leftDown.y <= p.y && p.y <= box.rightUp.y; double res = HUGE_VAL; if (inX) { // Point lies in a vertical bar bounded by Left and Right res = std::min(res, fabs(p.y - box.leftDown.y)); res = std::min(res, fabs(p.y - box.rightUp.y)); } if (inY) { // Point lies in a horizontal bar res = std::min(res, fabs(p.x - box.leftDown.x)); res = std::min(res, fabs(p.x - box.rightUp.x)); } if (!inX && !inY) { res = std::min(res, (p - box.leftDown).length()); res = std::min(res, (p - box.rightUp).length()); res = std::min(res, (p - box.leftUp()).length()); res = std::min(res, (p - box.rightDown()).length()); } return res; } double figures::Ellipse::getApproximateDistanceToBorder(const Point &_p) { Point p = _p - box.center(); if (p.length() < 1e-7) { return std::min(box.width(), box.height()) / 2; } double a = box.width() / 2; double b = box.height() / 2; Point near = p; near.x /= a; near.y /= b; double d = near.length(); near.x /= d; near.y /= d; near.x *= a; near.y *= b; return (p - near).length(); } std::vector<Point> getMiddleBorderPoints(BoundingBox box) { std::vector<Point> res; res.push_back(Point(box.center().x, box.leftDown.y)); res.push_back(Point(box.center().x, box.rightUp.y)); res.push_back(Point(box.leftDown.x, box.center().y)); res.push_back(Point(box.rightUp.x, box.center().y)); return res; } void figures::SegmentConnection::recalculate() { using std::vector; using std::get; vector<Point> as = getMiddleBorderPoints(figA->getBoundingBox()); vector<Point> bs = getMiddleBorderPoints(figB->getBoundingBox()); double minDistSquared = HUGE_VAL; for (Point a : as) { for (Point b : bs) { double curDistSquared = (a - b).lengthSquared(); if (minDistSquared > curDistSquared) { minDistSquared = curDistSquared; this->a = a; this->b = b; } } } } std::istream &operator>>(std::istream &in, Model &model) { int count; if (!(in >> count)) { throw model_format_error("unable to read number of figures"); } std::vector<PFigure> figures; while (count -- > 0) { std::string type; if (!(in >> type)) { throw model_format_error("unable to read fngure type"); } if (type == "segment" || type == "segment_connection") { std::shared_ptr<figures::Segment> segm; if (type == "segment_connection") { size_t aId, bId; if (!(in >> aId >> bId)) { throw model_format_error("unable to read connection information"); } aId--, bId--; if (aId >= figures.size() || bId >= figures.size()) { throw model_format_error("invalid figures in connection"); } auto figA = std::dynamic_pointer_cast<figures::BoundedFigure>(figures.at(aId)); auto figB = std::dynamic_pointer_cast<figures::BoundedFigure>(figures.at(bId)); if (!figA || !figB) { throw model_format_error("invalid reference in connection"); } segm = std::make_shared<figures::SegmentConnection>(figA, figB); } else { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read segment"); } segm = std::make_shared<figures::Segment>(Point(x1, y1), Point(x2, y2)); } bool arrowA, arrowB; if (!(in >> arrowA >> arrowB)) { throw model_format_error("unable to read segment"); } segm->setArrowedA(arrowA); segm->setArrowedB(arrowB); figures.push_back(segm); } else if (type == "rectangle") { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read rectangle"); } figures.push_back(std::make_shared<figures::Rectangle>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else if (type == "ellipse") { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read ellipse"); } figures.push_back(std::make_shared<figures::Ellipse>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else { throw model_format_error("unknown type: '" + type + "'"); } } for (PFigure figure : figures) { model.addFigure(figure); } return in; } class FigurePrinter : public FigureVisitor { public: FigurePrinter(std::ostream &out, const std::map<PFigure, size_t> &ids) : out(out), ids(ids) {} virtual void accept(figures::Segment &segm) { out << "segment "; printPoint(segm.getA()); out << " "; printPoint(segm.getB()); out << " " << segm.getArrowedA() << " " << segm.getArrowedB() << "\n"; } virtual void accept(figures::SegmentConnection &segm) { out << "segment_connection "; out << ids.at(segm.getFigureA()) << " "; out << ids.at(segm.getFigureB()) << " "; out << " " << segm.getArrowedA() << " " << segm.getArrowedB() << "\n"; } virtual void accept(figures::Ellipse &fig) { out << "ellipse "; printBoundingBox(fig.getBoundingBox()); out << "\n"; } virtual void accept(figures::Rectangle &fig) { out << "rectangle "; printBoundingBox(fig.getBoundingBox()); out << "\n"; } private: std::ostream &out; const std::map<PFigure, size_t> &ids; void printPoint(const Point &p) { out << p.x << " " << p.y; } void printBoundingBox(const BoundingBox &box) { printPoint(box.leftDown); out << " "; printPoint(box.rightUp); } }; std::ostream &operator<<(std::ostream &out, Model &model) { out << model.size() << '\n'; std::map<PFigure, size_t> ids; for (PFigure figure : model) { int id = ids.size() + 1; ids[figure] = id; } FigurePrinter printer(out, ids); for (PFigure figure : model) { figure->visit(printer); } return out; } class CloningVisitor : public FigureVisitor { public: CloningVisitor(const std::map<PFigure, PFigure> &mapping) : mapping(mapping) {} PFigure getResult() { return result; } virtual void accept(figures::Segment &fig) override { result = std::make_shared<figures::Segment>(fig); } virtual void accept(figures::SegmentConnection &fig) { auto res = std::make_shared<figures::SegmentConnection>(fig.getFigureA(), fig.getFigureB()); res->setArrowedA(fig.getArrowedA()); res->setArrowedB(fig.getArrowedB()); result = res; } virtual void accept(figures::Ellipse &fig) { result = std::make_shared<figures::Ellipse>(fig); } virtual void accept(figures::Rectangle &fig) { result = std::make_shared<figures::Rectangle>(fig); } private: const std::map<PFigure, PFigure> &mapping; PFigure result; }; PFigure clone(PFigure figure, const std::map<PFigure, PFigure> &othersMapping) { CloningVisitor visitor(othersMapping); figure->visit(visitor); return visitor.getResult(); } <commit_msg>model.cpp: got rid of warning: int --> size_t<commit_after>#include "model.h" #include <string> #include <algorithm> #include <map> double figures::Segment::getApproximateDistanceToBorder(const Point &p) { double res = std::min((p - a).length(), (p - b).length()); // Please note that here we do not care about floatint-point error, // as if 'start' falls near 'a' or 'b', we've already calculated it if (Point::dotProduct(p - a, b - a) >= 0 && Point::dotProduct(p - b, a - b) >= 0) { res = std::min(res, getDistanceToLine(p)); } return res; } double figures::Segment::getDistanceToLine(const Point &p) { // Coefficients of A*x + B*y + C = 0 double A = b.y - a.y; double B = a.x - b.x; double C = -A * a.x - B * a.y; // normalization of the equation double D = sqrt(A * A + B * B); if (fabs(D) < 1e-8) { return HUGE_VAL; } // degenerate case A /= D; B /= D; C /= D; return fabs(A * p.x + B * p.y + C); } double figures::Rectangle::getApproximateDistanceToBorder(const Point &p) { bool inX = box.leftDown.x <= p.x && p.x <= box.rightUp.x; bool inY = box.leftDown.y <= p.y && p.y <= box.rightUp.y; double res = HUGE_VAL; if (inX) { // Point lies in a vertical bar bounded by Left and Right res = std::min(res, fabs(p.y - box.leftDown.y)); res = std::min(res, fabs(p.y - box.rightUp.y)); } if (inY) { // Point lies in a horizontal bar res = std::min(res, fabs(p.x - box.leftDown.x)); res = std::min(res, fabs(p.x - box.rightUp.x)); } if (!inX && !inY) { res = std::min(res, (p - box.leftDown).length()); res = std::min(res, (p - box.rightUp).length()); res = std::min(res, (p - box.leftUp()).length()); res = std::min(res, (p - box.rightDown()).length()); } return res; } double figures::Ellipse::getApproximateDistanceToBorder(const Point &_p) { Point p = _p - box.center(); if (p.length() < 1e-7) { return std::min(box.width(), box.height()) / 2; } double a = box.width() / 2; double b = box.height() / 2; Point near = p; near.x /= a; near.y /= b; double d = near.length(); near.x /= d; near.y /= d; near.x *= a; near.y *= b; return (p - near).length(); } std::vector<Point> getMiddleBorderPoints(BoundingBox box) { std::vector<Point> res; res.push_back(Point(box.center().x, box.leftDown.y)); res.push_back(Point(box.center().x, box.rightUp.y)); res.push_back(Point(box.leftDown.x, box.center().y)); res.push_back(Point(box.rightUp.x, box.center().y)); return res; } void figures::SegmentConnection::recalculate() { using std::vector; using std::get; vector<Point> as = getMiddleBorderPoints(figA->getBoundingBox()); vector<Point> bs = getMiddleBorderPoints(figB->getBoundingBox()); double minDistSquared = HUGE_VAL; for (Point a : as) { for (Point b : bs) { double curDistSquared = (a - b).lengthSquared(); if (minDistSquared > curDistSquared) { minDistSquared = curDistSquared; this->a = a; this->b = b; } } } } std::istream &operator>>(std::istream &in, Model &model) { int count; if (!(in >> count)) { throw model_format_error("unable to read number of figures"); } std::vector<PFigure> figures; while (count -- > 0) { std::string type; if (!(in >> type)) { throw model_format_error("unable to read fngure type"); } if (type == "segment" || type == "segment_connection") { std::shared_ptr<figures::Segment> segm; if (type == "segment_connection") { size_t aId, bId; if (!(in >> aId >> bId)) { throw model_format_error("unable to read connection information"); } aId--, bId--; if (aId >= figures.size() || bId >= figures.size()) { throw model_format_error("invalid figures in connection"); } auto figA = std::dynamic_pointer_cast<figures::BoundedFigure>(figures.at(aId)); auto figB = std::dynamic_pointer_cast<figures::BoundedFigure>(figures.at(bId)); if (!figA || !figB) { throw model_format_error("invalid reference in connection"); } segm = std::make_shared<figures::SegmentConnection>(figA, figB); } else { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read segment"); } segm = std::make_shared<figures::Segment>(Point(x1, y1), Point(x2, y2)); } bool arrowA, arrowB; if (!(in >> arrowA >> arrowB)) { throw model_format_error("unable to read segment"); } segm->setArrowedA(arrowA); segm->setArrowedB(arrowB); figures.push_back(segm); } else if (type == "rectangle") { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read rectangle"); } figures.push_back(std::make_shared<figures::Rectangle>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else if (type == "ellipse") { double x1, y1, x2, y2; if (!(in >> x1 >> y1 >> x2 >> y2)) { throw model_format_error("unable to read ellipse"); } figures.push_back(std::make_shared<figures::Ellipse>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else { throw model_format_error("unknown type: '" + type + "'"); } } for (PFigure figure : figures) { model.addFigure(figure); } return in; } class FigurePrinter : public FigureVisitor { public: FigurePrinter(std::ostream &out, const std::map<PFigure, size_t> &ids) : out(out), ids(ids) {} virtual void accept(figures::Segment &segm) { out << "segment "; printPoint(segm.getA()); out << " "; printPoint(segm.getB()); out << " " << segm.getArrowedA() << " " << segm.getArrowedB() << "\n"; } virtual void accept(figures::SegmentConnection &segm) { out << "segment_connection "; out << ids.at(segm.getFigureA()) << " "; out << ids.at(segm.getFigureB()) << " "; out << " " << segm.getArrowedA() << " " << segm.getArrowedB() << "\n"; } virtual void accept(figures::Ellipse &fig) { out << "ellipse "; printBoundingBox(fig.getBoundingBox()); out << "\n"; } virtual void accept(figures::Rectangle &fig) { out << "rectangle "; printBoundingBox(fig.getBoundingBox()); out << "\n"; } private: std::ostream &out; const std::map<PFigure, size_t> &ids; void printPoint(const Point &p) { out << p.x << " " << p.y; } void printBoundingBox(const BoundingBox &box) { printPoint(box.leftDown); out << " "; printPoint(box.rightUp); } }; std::ostream &operator<<(std::ostream &out, Model &model) { out << model.size() << '\n'; std::map<PFigure, size_t> ids; for (PFigure figure : model) { size_t id = ids.size() + 1; ids[figure] = id; } FigurePrinter printer(out, ids); for (PFigure figure : model) { figure->visit(printer); } return out; } class CloningVisitor : public FigureVisitor { public: CloningVisitor(const std::map<PFigure, PFigure> &mapping) : mapping(mapping) {} PFigure getResult() { return result; } virtual void accept(figures::Segment &fig) override { result = std::make_shared<figures::Segment>(fig); } virtual void accept(figures::SegmentConnection &fig) { auto res = std::make_shared<figures::SegmentConnection>(fig.getFigureA(), fig.getFigureB()); res->setArrowedA(fig.getArrowedA()); res->setArrowedB(fig.getArrowedB()); result = res; } virtual void accept(figures::Ellipse &fig) { result = std::make_shared<figures::Ellipse>(fig); } virtual void accept(figures::Rectangle &fig) { result = std::make_shared<figures::Rectangle>(fig); } private: const std::map<PFigure, PFigure> &mapping; PFigure result; }; PFigure clone(PFigure figure, const std::map<PFigure, PFigure> &othersMapping) { CloningVisitor visitor(othersMapping); figure->visit(visitor); return visitor.getResult(); } <|endoftext|>
<commit_before>/* * @COPYRIGHT@ * * 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 */ // clxx/platform_layer.hpp /** // doc: clxx/platform_layer.hpp {{{ * \file clxx/platform_layer.hpp * \todo Write documentation */ // }}} #ifndef CLXX_PLATFORM_LAYER_HPP_INCLUDED #define CLXX_PLATFORM_LAYER_HPP_INCLUDED #include <clxx/platforms.hpp> #include <clxx/devices.hpp> #include <clxx/platform_layer_info.hpp> #include <clxx/platform_query.hpp> #include <clxx/device_query.hpp> #include <set> #include <map> #include <vector> namespace clxx { /** // doc: class platform_layer {{{ * \ingroup Clxx_Cl_platform * * Simple associative container to store \ref clxx::device "devices", * \ref clxx::platform "platforms" and relations between these. It represents * information about devices belonging to given platforms, and provides simple * interface to create and modify its contents and relations. * * Note, that this is just a container. It's not synchronized with OpenCL * platform layer by definition (it may be filled quite arbitrarily by user). * However, it has an interface that allows to initialize it with the actual * data retrieved from OpenCL, see \ref load_opencl(). * * The implemented relations have the following properties * * - each \ref clxx::device "device" stored in the container refers to exactly * one \ref clxx::platform "platform" (also stored in the container), * - each \ref clxx::platform "platform" stored in the container refers on one * or more \ref clxx::device "devices" (stored in the container). * * These constraints are enforced internally by the class. The contents may be * accessed by the following methods: * * - \ref get_devices() const get_devices() returns a plain sequence of * \ref clxx::device "devices", where the \ref clxx::device "devices" appear * in the same order as they were added to the container, * - \ref get_platforms() const get_platforms() returns a plain sequence of * \ref clxx::platform "platforms", where the \ref clxx::platform "platforms" * appear in the same order as they were added to the container, * - \ref get_devices(platform const&) const get_devices(platform const&) * returns plain sequence of \ref clxx::device "devices" related to a given * platform, * - \ref get_platform(device const&) const get_platform(device const&) * returns a \ref clxx::platform "platform" related to a given device, * * The contents may be modified by the following methods: * * - \ref add(device const&, platform const&) stores device, platform and * relation between device and platform in the container, * - \ref add(devices const&, platform const&) stores multiple devices and a * single platform at once and establishes relations between devices and * the platform, * - \ref erase(device const&) removes device from the container, if it was * the last device referencing its platform, the platform will also be * removed from container, * - \ref clear() clears the container entirely. * * and * * - \ref load_opencl(device_type_t) retrieves the platforms, devices and * relations from OpenCL platform layer and adds them to the container. * Note, that this appends stuff to or overrides the existing content. * * The container may also be filled-in with a data obtained from OpenCL at * initialization phase (in constructor). */ // }}} class platform_layer { public: typedef std::map<device, platform> device_platform_map; public: /** // doc: platform_layer() {{{ * \brief Default constructor * * Initializes empty container. */ // }}} platform_layer() noexcept; /** // doc: platform_layer(device_type_t) {{{ * \brief Constructor * * Initializes container with OpenCL data. * * \param type OpenCL device type, retrieve only devices of a given type. * * \code * platform_layer pl(t); * \endcode * * is equivalent to: * * \code * platform_layer pl; * pl.load_opencl(t); * \endcode * * \throws clerror_no<status_t::invalid_device_type> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_platform> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_value> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_host_memory> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_resources> * propagated from clxx::get_device_ids() * \throws std::bad_alloc * may be raised occasionally */ // }}} platform_layer(device_type_t type); /** // doc: platform_layer(bool, device_type_t) {{{ * \brief Constructor * * Either, initializes empty container or retrieves data from OpenCL, * depending on the value of \e load flag. The following calls are * equivalent * * \code * platform_layer(false); // => platform_layer(); * platform_layer(false, type); // => platform_layer(); * platform_layer(true); // => platform_layer(device_type_t::all); * platform_layer(true, type); // => platform_layer(type); * \endcode * * * \param load decides whether to load OpenCL platform layer layout or not, * \param type if \e load is \c true, then retrieve from OpenCL only devices * of this \e type * * \throws clerror_no<status_t::invalid_device_type> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_platform> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_value> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_host_memory> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_resources> * propagated from clxx::get_device_ids() * \throws std::bad_alloc * may be raised occasionally */ // }}} platform_layer(bool load, device_type_t type = device_type_t::all); /** // doc: ~platform_layer() {{{ * \brief Destructor */ // }}} virtual ~platform_layer() noexcept; /** // doc: get_platforms() {{{ * \fn get_platforms() const * \brief Get platforms * * Return flat sequence of platforms stored in container. The order of * elements in sequence is same as the order of their insertion to the * container. * * \returns flat sequence of platforms stored in container. */ // }}} platforms const& get_platforms() const noexcept; /** // doc: get_devices() {{{ * \fn get_devices() const * \brief Get devices * * Returns flat sequence of devices stored in container. The order of * elements in sequence is same as the order of their insertion to the * container. * * \returns sequence of devices stored in container. */ // }}} devices const& get_devices() const noexcept; /** // doc: get_devices(platform const&) {{{ * \fn get_devices(platform const&) const * \brief Get devices that refer platform \e p * \param p the platform * \returns flat sequence of devices that reference platform \e p * \throws std::bad_alloc may be raised occasionally */ // }}} devices get_devices(platform const& p) const; /** // doc: get_platform(device const&) {{{ * \fn get_platform(device const&) const * \brief Get platform referenced by given device * \param d the device * \throws invalid_key_error if \e d does not exist in the container * \returns a platform referred by \e d. */ // }}} platform const& get_platform(device const& d) const; /** // doc: has_device(device const&) {{{ * \brief Check presence of device \e d in container * \param d the clxx::device "device" to check * \returns \c true if device is found in container, otherwise \c false */ // }}} bool has_device(device const& d) const noexcept; /** // doc: has_platform(platform const&) {{{ * \brief Check presence of platform \e p in container * \param p the \ref clxx::platform "platform" to check * \returns \c true if device is found in container, otherwise \c false */ // }}} bool has_platform(platform const& p) const noexcept; /** // doc: add(platform const&, device const&) {{{ * \brief Add device to container * \param d device, * \param p platform referenced by device \e d * \returns \c true if the number of devices in container increased, * if the device already existed in container returns \c false * \throws std::bad_alloc may be raised occasionally */ // }}} bool add(device const& d, platform const& p); /** // doc: add(platform const&, devices const&) {{{ * \brief Add device to container * \param ds devices * \param p platform referenced by devices \e ds * \returns number of new devices added to container, the devices that * already existed in container are not counted in the return value * \throws std::bad_alloc may be raised occasionally */ // }}} size_t add(devices const& ds, platform const& p); /** // doc: erase(device const&) {{{ * \brief Remove device from container * \param d the device to remove from container * \throws invalid_key_error if \e d does not exist in the container * \throws std::bad_alloc may be raised occasionally */ // }}} void erase(device const& d); /** // doc: clear() {{{ * \brief Clear the container entirelly * \throws std::bad_alloc may be raised occasionally */ // }}} void clear() noexcept; /** // doc: load_opencl(device_type_t) {{{ * \brief Retrieve and load data from OpenCL * * This function retrieves from OpenCL and stores in container the platform * layer layout (devices, platforms and relations). * * \param type retrieve only devices of given type * * \throws clerror_no<status_t::invalid_device_type> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_platform> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_value> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_host_memory> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_resources> * propagated from clxx::get_device_ids() * \throws std::bad_alloc * may be raised occasionally */ // }}} void load_opencl(device_type_t type = device_type_t::all); private: platforms _platforms; devices _devices; device_platform_map _device_platform; }; /** // doc: query_platform_layer_info(layer,pquery,dquery) {{{ * \todo Write documentation */ // }}} platform_layer_info query_platform_layer_info( platform_layer const& layer = platform_layer(device_type_t::all), platform_query const& pquery = platform_query(), device_query const& dquery = device_query() ); } // end namespace clxx #endif /* CLXX_PLATFORM_LAYER_HPP_INCLUDED */ // vim: set expandtab tabstop=2 shiftwidth=2: // vim: set foldmethod=marker foldcolumn=4: <commit_msg>revised docs in platform_layer.hpp<commit_after>/* * @COPYRIGHT@ * * 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 */ // clxx/platform_layer.hpp /** // doc: clxx/platform_layer.hpp {{{ * \file clxx/platform_layer.hpp * \todo Write documentation */ // }}} #ifndef CLXX_PLATFORM_LAYER_HPP_INCLUDED #define CLXX_PLATFORM_LAYER_HPP_INCLUDED #include <clxx/platforms.hpp> #include <clxx/devices.hpp> #include <clxx/platform_layer_info.hpp> #include <clxx/platform_query.hpp> #include <clxx/device_query.hpp> #include <set> #include <map> #include <vector> namespace clxx { /** // doc: class platform_layer {{{ * \ingroup Clxx_Cl_platform * * Simple associative container to store \ref clxx::device "devices", * \ref clxx::platform "platforms" and relations between them. Note, that this * is just a container. It's not synchronized with OpenCL platform layer by * definition (it may be filled-in quite arbitrarily by user). However, it has * an interface that allows to initialize it with the actual data retrieved * from OpenCL, see \ref load_opencl(). * * The implemented relations fulfill the following constraints (enforced * internally by the class): * * - each \ref clxx::device "device" stored in the container refers exactly * one \ref clxx::platform "platform" (also stored in the container), * - each \ref clxx::platform "platform" stored in the container is referred * by one or more \ref clxx::device "devices" (stored in the container). * * The contents may be accessed by the following methods: * * - \ref get_devices() const get_devices() returns a plain sequence of * \ref clxx::device "devices", where the \ref clxx::device "devices" appear * in the same order as they were added to the container, * - \ref get_platforms() const get_platforms() returns a plain sequence of * \ref clxx::platform "platforms", where the \ref clxx::platform "platforms" * appear in the same order as they were added to the container, * - \ref get_devices(platform const&) const get_devices(platform const&) * returns plain sequence of \ref clxx::device "devices" that refer given * platform, * - \ref get_platform(device const&) const get_platform(device const&) * returns a \ref clxx::platform "platform" referred by given device, * * The contents may be modified by the following methods: * * - \ref add(device const&, platform const&) stores device, platform and * relation between device and platform in the container, * - \ref add(devices const&, platform const&) stores multiple devices and a * single platform at once and establishes relations between devices and * the platform, * - \ref erase(device const&) removes device from the container, if it was * the last device referencing its platform, the platform will also be * removed from container, * - \ref clear() clears the container entirely. * * and * * - \ref load_opencl(device_type_t) retrieves the platforms, devices and * relations from OpenCL platform layer and adds them to the container. * Note, that this appends stuff to- or overrides the existing content. * * The container may also be filled-in with a data obtained from OpenCL at * initialization phase (in constructor). */ // }}} class platform_layer { public: typedef std::map<device, platform> device_platform_map; public: /** // doc: platform_layer() {{{ * \brief Default constructor * * Initializes empty container. */ // }}} platform_layer() noexcept; /** // doc: platform_layer(device_type_t) {{{ * \brief Constructor * * Initializes container with OpenCL data. * * \param type OpenCL device type, retrieve only devices of a given type. * * \code * platform_layer pl(t); * \endcode * * is equivalent to: * * \code * platform_layer pl; * pl.load_opencl(t); * \endcode * * \throws clerror_no<status_t::invalid_device_type> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_platform> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_value> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_host_memory> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_resources> * propagated from clxx::get_device_ids() * \throws std::bad_alloc * may be raised occasionally */ // }}} platform_layer(device_type_t type); /** // doc: platform_layer(bool, device_type_t) {{{ * \brief Constructor * * Either, initializes empty container or retrieves data from OpenCL, * depending on the value of \e load flag. The following calls are * equivalent * * \code * platform_layer(false); // => platform_layer(); * platform_layer(false, type); // => platform_layer(); * platform_layer(true); // => platform_layer(device_type_t::all); * platform_layer(true, type); // => platform_layer(type); * \endcode * * * \param load decides whether to load OpenCL platform layer layout or not, * \param type if \e load is \c true, then retrieve from OpenCL only devices * of this \e type * * \throws clerror_no<status_t::invalid_device_type> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_platform> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_value> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_host_memory> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_resources> * propagated from clxx::get_device_ids() * \throws std::bad_alloc * may be raised occasionally */ // }}} platform_layer(bool load, device_type_t type = device_type_t::all); /** // doc: ~platform_layer() {{{ * \brief Destructor */ // }}} virtual ~platform_layer() noexcept; /** // doc: get_platforms() {{{ * \fn get_platforms() const * \brief Get platforms * * Return flat sequence of platforms stored in container. The order of * elements in sequence is same as the order of their insertion to the * container. * * \returns flat sequence of platforms stored in container. */ // }}} platforms const& get_platforms() const noexcept; /** // doc: get_devices() {{{ * \fn get_devices() const * \brief Get devices * * Returns flat sequence of devices stored in container. The order of * elements in sequence is same as the order of their insertion to the * container. * * \returns sequence of devices stored in container. */ // }}} devices const& get_devices() const noexcept; /** // doc: get_devices(platform const&) {{{ * \fn get_devices(platform const&) const * \brief Get devices that refer platform \e p * \param p the platform * \returns flat sequence of devices that reference platform \e p * \throws std::bad_alloc may be raised occasionally */ // }}} devices get_devices(platform const& p) const; /** // doc: get_platform(device const&) {{{ * \fn get_platform(device const&) const * \brief Get platform referenced by given device * \param d the device * \throws invalid_key_error if \e d does not exist in the container * \returns a platform referred by \e d. */ // }}} platform const& get_platform(device const& d) const; /** // doc: has_device(device const&) {{{ * \brief Check presence of device \e d in container * \param d the clxx::device "device" to check * \returns \c true if device is found in container, otherwise \c false */ // }}} bool has_device(device const& d) const noexcept; /** // doc: has_platform(platform const&) {{{ * \brief Check presence of platform \e p in container * \param p the \ref clxx::platform "platform" to check * \returns \c true if device is found in container, otherwise \c false */ // }}} bool has_platform(platform const& p) const noexcept; /** // doc: add(platform const&, device const&) {{{ * \brief Add device to container * \param d device, * \param p platform referenced by device \e d * \returns \c true if the number of devices in container increased, * if the device already existed in container returns \c false * \throws std::bad_alloc may be raised occasionally */ // }}} bool add(device const& d, platform const& p); /** // doc: add(platform const&, devices const&) {{{ * \brief Add device to container * \param ds devices * \param p platform referenced by devices \e ds * \returns number of new devices added to container, the devices that * already existed in container are not counted in the return value * \throws std::bad_alloc may be raised occasionally */ // }}} size_t add(devices const& ds, platform const& p); /** // doc: erase(device const&) {{{ * \brief Remove device from container * \param d the device to remove from container * \throws invalid_key_error if \e d does not exist in the container * \throws std::bad_alloc may be raised occasionally */ // }}} void erase(device const& d); /** // doc: clear() {{{ * \brief Clear the container entirelly * \throws std::bad_alloc may be raised occasionally */ // }}} void clear() noexcept; /** // doc: load_opencl(device_type_t) {{{ * \brief Retrieve and load data from OpenCL * * This function retrieves from OpenCL and stores in container the platform * layer layout (devices, platforms and relations). * * \param type retrieve only devices of given type * * \throws clerror_no<status_t::invalid_device_type> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_platform> * propagated from clxx::get_device_ids() * \throws clerror_no<status_t::invalid_value> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_host_memory> * propagated from clxx::get_device_ids() and clxx::get_platform_ids() * \throws clerror_no<status_t::out_of_resources> * propagated from clxx::get_device_ids() * \throws std::bad_alloc * may be raised occasionally */ // }}} void load_opencl(device_type_t type = device_type_t::all); private: platforms _platforms; devices _devices; device_platform_map _device_platform; }; /** // doc: query_platform_layer_info(layer,pquery,dquery) {{{ * \todo Write documentation */ // }}} platform_layer_info query_platform_layer_info( platform_layer const& layer = platform_layer(device_type_t::all), platform_query const& pquery = platform_query(), device_query const& dquery = device_query() ); } // end namespace clxx #endif /* CLXX_PLATFORM_LAYER_HPP_INCLUDED */ // vim: set expandtab tabstop=2 shiftwidth=2: // vim: set foldmethod=marker foldcolumn=4: <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010,2011 Bernhard Beschow <[email protected]> // // Own #include "ServerLayout.h" #include "GeoSceneTiled.h" #include "MarbleGlobal.h" #include "TileId.h" #if QT_VERSION >= 0x050000 #include <QUrlQuery> #endif #include <math.h> namespace Marble { ServerLayout::ServerLayout( GeoSceneTiled *textureLayer ) : m_textureLayer( textureLayer ) { } ServerLayout::~ServerLayout() { } MarbleServerLayout::MarbleServerLayout( GeoSceneTiled *textureLayer ) : ServerLayout( textureLayer ) { } QUrl MarbleServerLayout::downloadUrl( const QUrl &prototypeUrl, const TileId &id ) const { QUrl url = prototypeUrl; url.setPath( url.path() + m_textureLayer->relativeTileFileName( id ) ); return url; } QString MarbleServerLayout::name() const { return "Marble"; } OsmServerLayout::OsmServerLayout( GeoSceneTiled *textureLayer ) : ServerLayout( textureLayer ) { } QUrl OsmServerLayout::downloadUrl( const QUrl &prototypeUrl, const TileId &id ) const { const QString suffix = m_textureLayer->fileFormat().toLower(); const QString path = QString( "%1/%2/%3.%4" ).arg( id.zoomLevel() ) .arg( id.x() ) .arg( id.y() ) .arg( suffix ); QUrl url = prototypeUrl; url.setPath( url.path() + path ); return url; } QString OsmServerLayout::name() const { return "OpenStreetMap"; } CustomServerLayout::CustomServerLayout( GeoSceneTiled *texture ) : ServerLayout( texture ) { } QUrl CustomServerLayout::downloadUrl( const QUrl &prototypeUrl, const TileId &id ) const { #if QT_VERSION < 0x050000 QString urlStr = prototypeUrl.toString(); #else QString urlStr = prototypeUrl.toString( QUrl::DecodeReserved ); #endif urlStr.replace( "{zoomLevel}", QString::number( id.zoomLevel() ) ); urlStr.replace( "{x}", QString::number( id.x() ) ); urlStr.replace( "{y}", QString::number( id.y() ) ); return QUrl( urlStr ); } QString CustomServerLayout::name() const { return "Custom"; } WmsServerLayout::WmsServerLayout( GeoSceneTiled *texture ) : ServerLayout( texture ) { } QUrl WmsServerLayout::downloadUrl( const QUrl &prototypeUrl, const Marble::TileId &tileId ) const { GeoDataLatLonBox box = tileId.toLatLonBox( m_textureLayer ); #if QT_VERSION < 0x050000 QUrl url = prototypeUrl; #else QUrlQuery url(prototypeUrl.query()); #endif url.addQueryItem( "service", "WMS" ); url.addQueryItem( "request", "GetMap" ); url.addQueryItem( "version", "1.1.1" ); if ( !url.hasQueryItem( "styles" ) ) url.addQueryItem( "styles", "" ); if ( !url.hasQueryItem( "format" ) ) { if ( m_textureLayer->fileFormat().toLower() == "jpg" ) url.addQueryItem( "format", "image/jpeg" ); else url.addQueryItem( "format", "image/" + m_textureLayer->fileFormat().toLower() ); } if ( !url.hasQueryItem( "srs" ) ) { url.addQueryItem( "srs", epsgCode() ); } if ( !url.hasQueryItem( "layers" ) ) url.addQueryItem( "layers", m_textureLayer->name() ); url.addQueryItem( "width", QString::number( m_textureLayer->tileSize().width() ) ); url.addQueryItem( "height", QString::number( m_textureLayer->tileSize().height() ) ); url.addQueryItem( "bbox", QString( "%1,%2,%3,%4" ).arg( QString::number( box.west( GeoDataCoordinates::Degree ), 'f', 12 ) ) .arg( QString::number( box.south( GeoDataCoordinates::Degree ), 'f', 12 ) ) .arg( QString::number( box.east( GeoDataCoordinates::Degree ), 'f', 12 ) ) .arg( QString::number( box.north( GeoDataCoordinates::Degree ), 'f', 12 ) ) ); #if QT_VERSION < 0x050000 return url; #else QUrl finalUrl = prototypeUrl; finalUrl.setQuery(url); return finalUrl; #endif } QString WmsServerLayout::name() const { return "WebMapService"; } QString WmsServerLayout::epsgCode() const { switch ( m_textureLayer->projection() ) { case GeoSceneTiled::Equirectangular: return "EPSG:4326"; case GeoSceneTiled::Mercator: return "EPSG:3785"; } Q_ASSERT( false ); // not reached return QString(); } QuadTreeServerLayout::QuadTreeServerLayout( GeoSceneTiled *textureLayer ) : ServerLayout( textureLayer ) { } QUrl QuadTreeServerLayout::downloadUrl( const QUrl &prototypeUrl, const Marble::TileId &id ) const { #if QT_VERSION < 0x050000 QString urlStr = prototypeUrl.toString(); #else QString urlStr = prototypeUrl.toString( QUrl::DecodeReserved ); #endif urlStr.replace( "{quadIndex}", encodeQuadTree( id ) ); return QUrl( urlStr ); } QString QuadTreeServerLayout::name() const { return "QuadTree"; } QString QuadTreeServerLayout::encodeQuadTree( const Marble::TileId &id ) { QString tileNum; for ( int i = id.zoomLevel(); i >= 0; i-- ) { const int tileX = (id.x() >> i) % 2; const int tileY = (id.y() >> i) % 2; const int num = ( 2 * tileY ) + tileX; tileNum += QString::number( num ); } return tileNum; } TmsServerLayout::TmsServerLayout(GeoSceneTiled *textureLayer ) : ServerLayout( textureLayer ) { } QUrl TmsServerLayout::downloadUrl( const QUrl &prototypeUrl, const TileId &id ) const { const QString suffix = m_textureLayer->fileFormat().toLower(); // y coordinate in TMS start at the bottom of the map (South) and go upwards, // opposed to OSM which start at the top. // // http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification int y_frombottom = ( 1<<id.zoomLevel() ) - id.y() - 1 ; const QString path = QString( "%1/%2/%3.%4" ).arg( id.zoomLevel() ) .arg( id.x() ) .arg( y_frombottom ) .arg( suffix ); QUrl url = prototypeUrl; url.setPath( url.path() + path ); return url; } QString TmsServerLayout::name() const { return "TileMapService"; } } <commit_msg>decouple remote and local tile paths a bit<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010,2011 Bernhard Beschow <[email protected]> // // Own #include "ServerLayout.h" #include "GeoSceneTiled.h" #include "MarbleGlobal.h" #include "TileId.h" #if QT_VERSION >= 0x050000 #include <QUrlQuery> #endif #include <math.h> namespace Marble { ServerLayout::ServerLayout( GeoSceneTiled *textureLayer ) : m_textureLayer( textureLayer ) { } ServerLayout::~ServerLayout() { } MarbleServerLayout::MarbleServerLayout( GeoSceneTiled *textureLayer ) : ServerLayout( textureLayer ) { } QUrl MarbleServerLayout::downloadUrl( const QUrl &prototypeUrl, const TileId &id ) const { const QString path = QString( "%1maps/%2/%3/%4/%4_%5.%6" ) .arg( prototypeUrl.path() ) .arg( m_textureLayer->sourceDir() ) .arg( id.zoomLevel() ) .arg( id.y(), tileDigits, 10, QChar('0') ) .arg( id.x(), tileDigits, 10, QChar('0') ) .arg( m_textureLayer->fileFormat().toLower() ); QUrl url = prototypeUrl; url.setPath( path ); return url; } QString MarbleServerLayout::name() const { return "Marble"; } OsmServerLayout::OsmServerLayout( GeoSceneTiled *textureLayer ) : ServerLayout( textureLayer ) { } QUrl OsmServerLayout::downloadUrl( const QUrl &prototypeUrl, const TileId &id ) const { const QString suffix = m_textureLayer->fileFormat().toLower(); const QString path = QString( "%1/%2/%3.%4" ).arg( id.zoomLevel() ) .arg( id.x() ) .arg( id.y() ) .arg( suffix ); QUrl url = prototypeUrl; url.setPath( url.path() + path ); return url; } QString OsmServerLayout::name() const { return "OpenStreetMap"; } CustomServerLayout::CustomServerLayout( GeoSceneTiled *texture ) : ServerLayout( texture ) { } QUrl CustomServerLayout::downloadUrl( const QUrl &prototypeUrl, const TileId &id ) const { #if QT_VERSION < 0x050000 QString urlStr = prototypeUrl.toString(); #else QString urlStr = prototypeUrl.toString( QUrl::DecodeReserved ); #endif urlStr.replace( "{zoomLevel}", QString::number( id.zoomLevel() ) ); urlStr.replace( "{x}", QString::number( id.x() ) ); urlStr.replace( "{y}", QString::number( id.y() ) ); return QUrl( urlStr ); } QString CustomServerLayout::name() const { return "Custom"; } WmsServerLayout::WmsServerLayout( GeoSceneTiled *texture ) : ServerLayout( texture ) { } QUrl WmsServerLayout::downloadUrl( const QUrl &prototypeUrl, const Marble::TileId &tileId ) const { GeoDataLatLonBox box = tileId.toLatLonBox( m_textureLayer ); #if QT_VERSION < 0x050000 QUrl url = prototypeUrl; #else QUrlQuery url(prototypeUrl.query()); #endif url.addQueryItem( "service", "WMS" ); url.addQueryItem( "request", "GetMap" ); url.addQueryItem( "version", "1.1.1" ); if ( !url.hasQueryItem( "styles" ) ) url.addQueryItem( "styles", "" ); if ( !url.hasQueryItem( "format" ) ) { if ( m_textureLayer->fileFormat().toLower() == "jpg" ) url.addQueryItem( "format", "image/jpeg" ); else url.addQueryItem( "format", "image/" + m_textureLayer->fileFormat().toLower() ); } if ( !url.hasQueryItem( "srs" ) ) { url.addQueryItem( "srs", epsgCode() ); } if ( !url.hasQueryItem( "layers" ) ) url.addQueryItem( "layers", m_textureLayer->name() ); url.addQueryItem( "width", QString::number( m_textureLayer->tileSize().width() ) ); url.addQueryItem( "height", QString::number( m_textureLayer->tileSize().height() ) ); url.addQueryItem( "bbox", QString( "%1,%2,%3,%4" ).arg( QString::number( box.west( GeoDataCoordinates::Degree ), 'f', 12 ) ) .arg( QString::number( box.south( GeoDataCoordinates::Degree ), 'f', 12 ) ) .arg( QString::number( box.east( GeoDataCoordinates::Degree ), 'f', 12 ) ) .arg( QString::number( box.north( GeoDataCoordinates::Degree ), 'f', 12 ) ) ); #if QT_VERSION < 0x050000 return url; #else QUrl finalUrl = prototypeUrl; finalUrl.setQuery(url); return finalUrl; #endif } QString WmsServerLayout::name() const { return "WebMapService"; } QString WmsServerLayout::epsgCode() const { switch ( m_textureLayer->projection() ) { case GeoSceneTiled::Equirectangular: return "EPSG:4326"; case GeoSceneTiled::Mercator: return "EPSG:3785"; } Q_ASSERT( false ); // not reached return QString(); } QuadTreeServerLayout::QuadTreeServerLayout( GeoSceneTiled *textureLayer ) : ServerLayout( textureLayer ) { } QUrl QuadTreeServerLayout::downloadUrl( const QUrl &prototypeUrl, const Marble::TileId &id ) const { #if QT_VERSION < 0x050000 QString urlStr = prototypeUrl.toString(); #else QString urlStr = prototypeUrl.toString( QUrl::DecodeReserved ); #endif urlStr.replace( "{quadIndex}", encodeQuadTree( id ) ); return QUrl( urlStr ); } QString QuadTreeServerLayout::name() const { return "QuadTree"; } QString QuadTreeServerLayout::encodeQuadTree( const Marble::TileId &id ) { QString tileNum; for ( int i = id.zoomLevel(); i >= 0; i-- ) { const int tileX = (id.x() >> i) % 2; const int tileY = (id.y() >> i) % 2; const int num = ( 2 * tileY ) + tileX; tileNum += QString::number( num ); } return tileNum; } TmsServerLayout::TmsServerLayout(GeoSceneTiled *textureLayer ) : ServerLayout( textureLayer ) { } QUrl TmsServerLayout::downloadUrl( const QUrl &prototypeUrl, const TileId &id ) const { const QString suffix = m_textureLayer->fileFormat().toLower(); // y coordinate in TMS start at the bottom of the map (South) and go upwards, // opposed to OSM which start at the top. // // http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification int y_frombottom = ( 1<<id.zoomLevel() ) - id.y() - 1 ; const QString path = QString( "%1/%2/%3.%4" ).arg( id.zoomLevel() ) .arg( id.x() ) .arg( y_frombottom ) .arg( suffix ); QUrl url = prototypeUrl; url.setPath( url.path() + path ); return url; } QString TmsServerLayout::name() const { return "TileMapService"; } } <|endoftext|>
<commit_before> #include "../lib_graphs/defs.h" #include "DebugPrinter.h" #include "AuctionDefs.h" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> const size_t __num_nodes = 9; const size_t __num_edges = 36; Edge __edges[__num_edges] = { Edge(_a, _b), Edge(_a, _c), Edge(_a, _d), Edge(_a, _e), Edge(_a, _f), Edge(_a, _g), Edge(_a, _h), Edge(_a, _i), Edge(_b, _c), Edge(_b, _d), Edge(_b, _e), Edge(_b, _f), Edge(_b, _g), Edge(_b, _h), Edge(_b, _i), Edge(_c, _d), Edge(_c, _e), Edge(_c, _f), Edge(_c, _g), Edge(_c, _h), Edge(_c, _i), Edge(_d, _e), Edge(_d, _f), Edge(_d, _g), Edge(_d, _h), Edge(_d, _i), Edge(_e, _f), Edge(_e, _g), Edge(_e, _h), Edge(_e, _i), Edge(_f, _g), Edge(_f, _h), Edge(_f, _i), Edge(_g, _h), Edge(_g, _i), Edge(_h, _i) }; int __weights[__num_edges] = { 4, 8, 11, 8, 7, 4, 2, 9, 14, 10, 2, 1, 6, 7, 4, 8, 11, 8, 7, 4, 2, 9, 14, 10, 2, 1, 6, 7, 4, 8, 11, 8, 7, 4, 2, 9 }; Loc __locations[__num_nodes] = { Loc(7, 0), Loc(15, 15), Loc(30, 15), Loc(45, 15), Loc(60, 0), Loc(45, -15), Loc(30, -15), Loc(15, -15), Loc(22, 0) }; //Loc __locations[__num_nodes] = { // Loc(0.5, 0), Loc(1, 1), Loc(2, 1), Loc(3, 1), // Loc(4, 0), Loc(3, -1), Loc(2, -1), Loc(1, -1), Loc(1.5, 0) //}; std::string pathToString(Loc path[], const size_t pathSize) { std::stringstream ss; size_t i; // Cycle through all but last one for (i = 0; i < pathSize - 1; i++) ss << path[i].first << "," << path[i].second << ":"; // Finish with last one ss << path[i].first << "," << path[i].second; return ss.str(); } template<typename U, typename V> std::string pairToString(std::pair<U,V> pair) { std::stringstream ss; ss << pair.first << "," << pair.second; return ss.str(); } std::string bidToString(Bid bid) { return pairToString(bid); } Bid bidFromString(std::string str) { Bid bid; std::vector<std::string> strs; boost::split(strs, str, boost::is_any_of(",")); bid = std::make_pair( boost::lexical_cast<Vertex>(strs[0]), boost::lexical_cast<mbogo_weight_t>(strs[1])); return bid; } std::string winningBidToString(WinningBid bid) { std::stringstream ss; ss << bid.winner << "," << bid.target << "," << bid.bid; return ss.str(); } WinningBid winningBidFromString(std::string str) { WinningBid bid; std::vector<std::string> strs; boost::split(strs, str, boost::is_any_of(",")); bid.winner = boost::lexical_cast<int>(strs[0]); bid.target = boost::lexical_cast<Vertex>(strs[1]); bid.bid = boost::lexical_cast<mbogo_weight_t>(strs[2]); return bid; } int getBidder(std::string bidHeader) { int bidder; std::vector<std::string> strs; boost::split(strs, bidHeader, boost::is_any_of("_V")); bidder = boost::lexical_cast<int>(strs.back()); return bidder; } std::string getVar(std::string header, const int id) { std::stringstream ss; ss << header << id; return ss.str(); } std::string getBidVar(const int id) { return getVar(MVAR_BID_HEADER, id); } std::string getPathVar(int id) { return getVar(MVAR_PATH_HEADER, id); } std::string getPathVarVal(std::string sPath) { std::stringstream ss; ss << MVAR_PATH << "=" << sPath; return ss.str(); } <commit_msg>Moved sample locs even further apart<commit_after> #include "../lib_graphs/defs.h" #include "DebugPrinter.h" #include "AuctionDefs.h" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> const size_t __num_nodes = 9; const size_t __num_edges = 36; Edge __edges[__num_edges] = { Edge(_a, _b), Edge(_a, _c), Edge(_a, _d), Edge(_a, _e), Edge(_a, _f), Edge(_a, _g), Edge(_a, _h), Edge(_a, _i), Edge(_b, _c), Edge(_b, _d), Edge(_b, _e), Edge(_b, _f), Edge(_b, _g), Edge(_b, _h), Edge(_b, _i), Edge(_c, _d), Edge(_c, _e), Edge(_c, _f), Edge(_c, _g), Edge(_c, _h), Edge(_c, _i), Edge(_d, _e), Edge(_d, _f), Edge(_d, _g), Edge(_d, _h), Edge(_d, _i), Edge(_e, _f), Edge(_e, _g), Edge(_e, _h), Edge(_e, _i), Edge(_f, _g), Edge(_f, _h), Edge(_f, _i), Edge(_g, _h), Edge(_g, _i), Edge(_h, _i) }; int __weights[__num_edges] = { 4, 8, 11, 8, 7, 4, 2, 9, 14, 10, 2, 1, 6, 7, 4, 8, 11, 8, 7, 4, 2, 9, 14, 10, 2, 1, 6, 7, 4, 8, 11, 8, 7, 4, 2, 9 }; Loc __locations[__num_nodes] = { Loc(25, 0), Loc(50, 50), Loc(100, 50), Loc(150, 50), Loc(200, 0), Loc(150, -50), Loc(100, -50), Loc(50, -50), Loc(75, 0) }; //Loc __locations[__num_nodes] = { // Loc(0.5, 0), Loc(1, 1), Loc(2, 1), Loc(3, 1), // Loc(4, 0), Loc(3, -1), Loc(2, -1), Loc(1, -1), Loc(1.5, 0) //}; std::string pathToString(Loc path[], const size_t pathSize) { std::stringstream ss; size_t i; // Cycle through all but last one for (i = 0; i < pathSize - 1; i++) ss << path[i].first << "," << path[i].second << ":"; // Finish with last one ss << path[i].first << "," << path[i].second; return ss.str(); } template<typename U, typename V> std::string pairToString(std::pair<U,V> pair) { std::stringstream ss; ss << pair.first << "," << pair.second; return ss.str(); } std::string bidToString(Bid bid) { return pairToString(bid); } Bid bidFromString(std::string str) { Bid bid; std::vector<std::string> strs; boost::split(strs, str, boost::is_any_of(",")); bid = std::make_pair( boost::lexical_cast<Vertex>(strs[0]), boost::lexical_cast<mbogo_weight_t>(strs[1])); return bid; } std::string winningBidToString(WinningBid bid) { std::stringstream ss; ss << bid.winner << "," << bid.target << "," << bid.bid; return ss.str(); } WinningBid winningBidFromString(std::string str) { WinningBid bid; std::vector<std::string> strs; boost::split(strs, str, boost::is_any_of(",")); bid.winner = boost::lexical_cast<int>(strs[0]); bid.target = boost::lexical_cast<Vertex>(strs[1]); bid.bid = boost::lexical_cast<mbogo_weight_t>(strs[2]); return bid; } int getBidder(std::string bidHeader) { int bidder; std::vector<std::string> strs; boost::split(strs, bidHeader, boost::is_any_of("_V")); bidder = boost::lexical_cast<int>(strs.back()); return bidder; } std::string getVar(std::string header, const int id) { std::stringstream ss; ss << header << id; return ss.str(); } std::string getBidVar(const int id) { return getVar(MVAR_BID_HEADER, id); } std::string getPathVar(int id) { return getVar(MVAR_PATH_HEADER, id); } std::string getPathVarVal(std::string sPath) { std::stringstream ss; ss << MVAR_PATH << "=" << sPath; return ss.str(); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2018 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/addresstablemodel.h> #include <qt/guiutil.h> #include <qt/walletmodel.h> #include <base58.h> #include <wallet/wallet.h> #include <QFont> #include <QDebug> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type _type, const QString &_label, const QString &_address): type(_type), label(_label), address(_address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const { return a.address < b.address; } bool operator()(const AddressTableEntry &a, const QString &b) const { return a.address < b; } bool operator()(const QString &a, const AddressTableEntry &b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet *wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel *parent; AddressTablePriv(CWallet *_wallet, AddressTableModel *_parent): wallet(_wallet), parent(_parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); for (const std::pair<CTxDestination, CAddressBookData>& item : wallet->mapAddressBook) { const CTxDestination& address = item.first; bool fMine = IsMine(*wallet, address); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(EncodeDestination(address)))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch(status) { case CT_NEW: if(inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet *_wallet, WalletModel *parent) : QAbstractTableModel(parent),walletModel(parent),wallet(_wallet),priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: if(rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if(index.column() == Address) { font = GUIUtil::fixedPitchFont(); } return font; } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if(role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = DecodeDestination(rec->address.toStdString()); if(index.column() == Label) { // Do nothing, if old label == new label if(rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if(index.column() == Address) { CTxDestination newAddress = DecodeDestination(value.toString().toStdString()); // Refuse to set invalid address, set error status and return false if(boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if(newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if(wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if(rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if(rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column()==Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Update address book model from Chaincoin core priv->updateEntry(address, label, isMine, purpose, status); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address, const OutputType address_type) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if(type == Send) { if(!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if(wallet->mapAddressBook.count(DecodeDestination(strAddress))) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if(type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if(!wallet->GetKeyFromPool(newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if(!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } wallet->LearnRelatedScripts(newKey, address_type); strAddress = EncodeDestination(GetDestinationForKey(newKey, address_type)); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBook(DecodeDestination(strAddress), strLabel, (type == Send ? "send" : "receive")); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBook(DecodeDestination(rec->address.toStdString())); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString &address) const { { LOCK(wallet->cs_wallet); CTxDestination destination = DecodeDestination(address.toStdString()); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(destination); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString &address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); } <commit_msg>Remove redundant locks<commit_after>// Copyright (c) 2011-2018 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/addresstablemodel.h> #include <qt/guiutil.h> #include <qt/walletmodel.h> #include <base58.h> #include <wallet/wallet.h> #include <QFont> #include <QDebug> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type _type, const QString &_label, const QString &_address): type(_type), label(_label), address(_address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const { return a.address < b.address; } bool operator()(const AddressTableEntry &a, const QString &b) const { return a.address < b; } bool operator()(const QString &a, const AddressTableEntry &b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet *wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel *parent; AddressTablePriv(CWallet *_wallet, AddressTableModel *_parent): wallet(_wallet), parent(_parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); for (const std::pair<CTxDestination, CAddressBookData>& item : wallet->mapAddressBook) { const CTxDestination& address = item.first; bool fMine = IsMine(*wallet, address); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(EncodeDestination(address)))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch(status) { case CT_NEW: if(inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet *_wallet, WalletModel *parent) : QAbstractTableModel(parent),walletModel(parent),wallet(_wallet),priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: if(rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if(index.column() == Address) { font = GUIUtil::fixedPitchFont(); } return font; } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if(role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = DecodeDestination(rec->address.toStdString()); if(index.column() == Label) { // Do nothing, if old label == new label if(rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if(index.column() == Address) { CTxDestination newAddress = DecodeDestination(value.toString().toStdString()); // Refuse to set invalid address, set error status and return false if(boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if(newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if(wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if(rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if(rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column()==Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Update address book model from Chaincoin core priv->updateEntry(address, label, isMine, purpose, status); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address, const OutputType address_type) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if(type == Send) { if(!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if(wallet->mapAddressBook.count(DecodeDestination(strAddress))) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if(type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if(!wallet->GetKeyFromPool(newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if(!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } wallet->LearnRelatedScripts(newKey, address_type); strAddress = EncodeDestination(GetDestinationForKey(newKey, address_type)); } else { return QString(); } // Add entry wallet->SetAddressBook(DecodeDestination(strAddress), strLabel, (type == Send ? "send" : "receive")); return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } wallet->DelAddressBook(DecodeDestination(rec->address.toStdString())); return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString &address) const { { LOCK(wallet->cs_wallet); CTxDestination destination = DecodeDestination(address.toStdString()); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(destination); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString &address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); } <|endoftext|>
<commit_before>/*********************************************************************** vallist.cpp - Implements utility functions for building value lists. This is internal functionality used within the library. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004-2007 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "vallist.h" #include "result.h" #include "row.h" using std::string; namespace mysqlpp { void create_vector(size_t size, std::vector<bool>& v, bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) { v.reserve(size); v.push_back(t0); if (size == 1) return; v.push_back(t1); if (size == 2) return; v.push_back(t2); if (size == 3) return; v.push_back(t3); if (size == 4) return; v.push_back(t4); if (size == 5) return; v.push_back(t5); if (size == 6) return; v.push_back(t6); if (size == 7) return; v.push_back(t7); if (size == 8) return; v.push_back(t8); if (size == 9) return; v.push_back(t9); if (size == 10) return; v.push_back(ta); if (size == 11) return; v.push_back(tb); if (size == 12) return; v.push_back(tc); } template <class Container> void create_vector(const Container& c, std::vector<bool>& v, std::string s0, std::string s1, std::string s2, std::string s3, std::string s4, std::string s5, std::string s6, std::string s7, std::string s8, std::string s9, std::string sa, std::string sb, std::string sc) { v.insert(v.begin(), c.size(), false); v[c.parent().field_num(s0)] = true; if (s1.empty()) return; v[c.parent().field_num(s1)] = true; if (s2.empty()) return; v[c.parent().field_num(s2)] = true; if (s3.empty()) return; v[c.parent().field_num(s3)] = true; if (s4.empty()) return; v[c.parent().field_num(s4)] = true; if (s5.empty()) return; v[c.parent().field_num(s5)] = true; if (s6.empty()) return; v[c.parent().field_num(s6)] = true; if (s7.empty()) return; v[c.parent().field_num(s7)] = true; if (s8.empty()) return; v[c.parent().field_num(s8)] = true; if (s9.empty()) return; v[c.parent().field_num(s9)] = true; if (sa.empty()) return; v[c.parent().field_num(sa)] = true; if (sb.empty()) return; v[c.parent().field_num(sb)] = true; if (sc.empty()) return; v[c.parent().field_num(sc)] = true; } // Instantiate above template. Not sure why this is necessary. template void create_vector(const Row& c, std::vector<bool>& v, string s0, string s1, string s2, string s3, string s4, string s5, string s6, string s7, string s8, string s9, string sa, string sb, string sc); } // end namespace mysqlpp <commit_msg>Final (?) Doxygen warning squish<commit_after>/*********************************************************************** vallist.cpp - Implements utility functions for building value lists. This is internal functionality used within the library. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004-2007 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "vallist.h" #include "result.h" #include "row.h" using std::string; namespace mysqlpp { void create_vector(size_t size, std::vector<bool>& v, bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) { v.reserve(size); v.push_back(t0); if (size == 1) return; v.push_back(t1); if (size == 2) return; v.push_back(t2); if (size == 3) return; v.push_back(t3); if (size == 4) return; v.push_back(t4); if (size == 5) return; v.push_back(t5); if (size == 6) return; v.push_back(t6); if (size == 7) return; v.push_back(t7); if (size == 8) return; v.push_back(t8); if (size == 9) return; v.push_back(t9); if (size == 10) return; v.push_back(ta); if (size == 11) return; v.push_back(tb); if (size == 12) return; v.push_back(tc); } template <class Container> void create_vector(const Container& c, std::vector<bool>& v, std::string s0, std::string s1, std::string s2, std::string s3, std::string s4, std::string s5, std::string s6, std::string s7, std::string s8, std::string s9, std::string sa, std::string sb, std::string sc) { v.insert(v.begin(), c.size(), false); v[c.parent().field_num(s0)] = true; if (s1.empty()) return; v[c.parent().field_num(s1)] = true; if (s2.empty()) return; v[c.parent().field_num(s2)] = true; if (s3.empty()) return; v[c.parent().field_num(s3)] = true; if (s4.empty()) return; v[c.parent().field_num(s4)] = true; if (s5.empty()) return; v[c.parent().field_num(s5)] = true; if (s6.empty()) return; v[c.parent().field_num(s6)] = true; if (s7.empty()) return; v[c.parent().field_num(s7)] = true; if (s8.empty()) return; v[c.parent().field_num(s8)] = true; if (s9.empty()) return; v[c.parent().field_num(s9)] = true; if (sa.empty()) return; v[c.parent().field_num(sa)] = true; if (sb.empty()) return; v[c.parent().field_num(sb)] = true; if (sc.empty()) return; v[c.parent().field_num(sc)] = true; } #if !defined(DOXYGEN_IGNORE) // Instantiate above template. Not sure why this is necessary. Hide it // from Doxygen, because we clearly cannot appease it by documenting it. template void create_vector(const Row& c, std::vector<bool>& v, string s0, string s1, string s2, string s3, string s4, string s5, string s6, string s7, string s8, string s9, string sa, string sb, string sc); #endif } // end namespace mysqlpp <|endoftext|>
<commit_before>// BrainCloudClient.cpp // BrainCloudLib // Copyright 2016 bitHeads, Inc. All Rights Reserved. #include <cstring> #include <iomanip> #include <iostream> #include <sstream> #include <vector> #include "braincloud/BrainCloudClient.h" #include "braincloud/internal/Device.h" #include "braincloud/internal/JsonUtil.h" #include "braincloud/internal/URLRequestMethod.h" namespace BrainCloud { // Define all static member variables. bool BrainCloudClient::EnableSingletonMode = false; const char * BrainCloudClient::SingletonUseErrorMessage = "Singleton usage is disabled. If called by mistake, use your own variable that holds an instance of the bcWrapper/bcClient."; BrainCloudClient * BrainCloudClient::_instance = NULL; std::string BrainCloudClient::s_brainCloudClientVersion = "4.4.0"; const char* BC_SERVER_URL = "https://sharedprod.braincloudservers.com/dispatcherv2"; /** * Constructor */ BrainCloudClient::BrainCloudClient() : _brainCloudComms(IBrainCloudComms::create(this)), _rttComms(new RTTComms(this)), _asyncMatchService(new BrainCloudAsyncMatch(this)), _authenticationService(new BrainCloudAuthentication(this)), _chatService(new BrainCloudChat(this)), _dataStreamService(new BrainCloudDataStream(this)), _entityService(new BrainCloudEntity(this)), _eventService(new BrainCloudEvent(this)), _fileService(new BrainCloudFile(this)), _friendService(new BrainCloudFriend(this)), _gamificationService(new BrainCloudGamification(this)), _globalAppService(new BrainCloudGlobalApp(this)), _globalEntityService(new BrainCloudGlobalEntity(this)), _globalStatisticsService(new BrainCloudGlobalStatistics(this)), _groupService(new BrainCloudGroup(this)), _identityService(new BrainCloudIdentity(this)), _lobbyService(new BrainCloudLobby(this)), _mailService(new BrainCloudMail(this)), _matchmakingService(new BrainCloudMatchmaking(this)), _messagingService(new BrainCloudMessaging(this)), _oneWayMatchService(new BrainCloudOneWayMatch(this)), _playbackStreamService(new BrainCloudPlaybackStream(this)), _playerStateService(new BrainCloudPlayerState(this)), _playerStatisticsService(new BrainCloudPlayerStatistics(this)), _playerStatisticsEventService(new BrainCloudPlayerStatisticsEvent(this)), _presenceService(new BrainCloudPresence(this)), _productService(new BrainCloudProduct(this)), _virtualCurrencyService(new BrainCloudVirtualCurrency(this)), _appStoreService(new BrainCloudAppStore(this)), _profanityService(new BrainCloudProfanity(this)), _pushNotificationService(new BrainCloudPushNotification(this)), _redemptionCodeService(new BrainCloudRedemptionCode(this)), _s3HandlingService(new BrainCloudS3Handling(this)), _scriptService(new BrainCloudScript(this)), _socialLeaderboardService(new BrainCloudSocialLeaderboard(this)), _steamService(new BrainCloudSteam(this)), _timeService(new BrainCloudTime(this)), _tournamentService(new BrainCloudTournament(this)), _customEntityService(new BrainCloudCustomEntity(this)), _itemCatalogService(new BrainCloudItemCatalog(this)), _userItemsService(new BrainCloudUserItems(this)), _releasePlatform(""), _appVersion(""), _timezoneOffset(0.0) { //needed this here otherwise out of scope compiler error _rttService = new BrainCloudRTT(_rttComms, this); } BrainCloudClient::~BrainCloudClient() { delete _rttService; delete _tournamentService; delete _customEntityService; delete _itemCatalogService; delete _timeService; delete _steamService; delete _socialLeaderboardService; delete _scriptService; delete _s3HandlingService; delete _redemptionCodeService; delete _pushNotificationService; delete _profanityService; delete _appStoreService; delete _virtualCurrencyService; delete _productService; delete _presenceService; delete _playerStatisticsEventService; delete _playerStatisticsService; delete _playerStateService; delete _playbackStreamService; delete _oneWayMatchService; delete _messagingService; delete _matchmakingService; delete _mailService; delete _lobbyService; delete _identityService; delete _groupService; delete _globalStatisticsService; delete _globalEntityService; delete _globalAppService; delete _gamificationService; delete _friendService; delete _fileService; delete _eventService; delete _entityService; delete _dataStreamService; delete _chatService; delete _authenticationService; delete _asyncMatchService; delete _rttComms; delete _brainCloudComms; } //////////////////////////////////////////////////// // Public Methods //////////////////////////////////////////////////// const char * BrainCloudClient::getSessionId() const { return(_brainCloudComms->getSessionId().c_str()); } const char * BrainCloudClient::getRttConnectionId() const{ return(_rttComms->getConnectionId().c_str()); } void BrainCloudClient::initializeComms(const char * in_serverURL, const char * in_appId, const std::map<std::string, std::string>& in_secretMap) { if (_brainCloudComms) { // automatically upgrade any older clients using "dispatcher" url // to "dispatcherv2" endpoint. Comms supports this now and otherwise // the change is transparent to the client. const char * urlToUse = in_serverURL; std::string url = in_serverURL; if (url.find("dispatcherv2") == std::string::npos) { size_t index = url.find("dispatcher"); if (index != std::string::npos) { url = url.substr(0, index); url += "dispatcherv2"; urlToUse = url.c_str(); } } _brainCloudComms->initializeWithApps(urlToUse, in_appId, in_secretMap); } if (_rttComms) { _rttComms->initialize(); } } void BrainCloudClient::initialize(const char * in_serverURL, const char * in_secretKey, const char * in_appId, const char * in_appVersion) { std::string error = ""; if (in_serverURL == NULL || strlen(in_serverURL) <= 0) error = "serverURL was null or empty"; else if (in_secretKey == NULL || strlen(in_secretKey) <= 0) error = "secretKey was null or empty"; else if (in_appId == NULL || strlen(in_appId) <= 0) error = "appId was null or empty"; else if (in_appVersion == NULL || strlen(in_appVersion) <= 0) error = "appVersion was null or empty"; if (error.length() > 0) { std::cout << "ERROR | Failed to initialize brainCloud - " << error; return; } std::map<std::string, std::string> secretMap; secretMap[in_appId] = in_secretKey; initializeComms(in_serverURL, in_appId, secretMap); setupOSLocaleData(); _releasePlatform = Device::getPlatformName(); _appVersion = in_appVersion; } void BrainCloudClient::initialize(const char * in_secretKey, const char * in_appId, const char * in_appVersion) { initialize(BC_SERVER_URL, in_secretKey, in_appId, in_appVersion); } void BrainCloudClient::initializeWithApps(const char * in_serverURL, const char * in_defaultAppId, const std::map<std::string, std::string>& in_secretMap, const char * in_appVersion) { std::string error = ""; if (in_serverURL == NULL || strlen(in_serverURL) <= 0) error = "serverURL was null or empty"; else if (in_defaultAppId == NULL || strlen(in_defaultAppId) <= 0) error = "appId was null or empty"; else if (in_appVersion == NULL || strlen(in_appVersion) <= 0) error = "appVersion was null or empty"; else if (in_secretMap.find(in_defaultAppId) == in_secretMap.end()) error = "not secretKey match for appid"; if (error.length() > 0) { std::cout << "ERROR | Failed to initialize brainCloud - " << error; return; } initializeComms(in_serverURL, in_defaultAppId, in_secretMap); setupOSLocaleData(); _releasePlatform = Device::getPlatformName(); _appVersion = in_appVersion; } void BrainCloudClient::initializeWithApps(const char* in_defaultAppId, const std::map<std::string, std::string>& in_secretMap, const char* in_appVersion) { initializeWithApps(BC_SERVER_URL, in_defaultAppId, in_secretMap, in_appVersion); } void BrainCloudClient::initializeIdentity(const char * in_profileId, const char * in_anonymousId) { _authenticationService->initialize(in_profileId, in_anonymousId); } void BrainCloudClient::runCallbacks() { _brainCloudComms->runCallbacks(); _lobbyService->runPingCallbacks(); _rttComms->runCallbacks(); } void BrainCloudClient::registerEventCallback(IEventCallback *in_eventCallback) { _brainCloudComms->registerEventCallback(in_eventCallback); } void BrainCloudClient::deregisterEventCallback() { _brainCloudComms->deregisterEventCallback(); } void BrainCloudClient::registerRewardCallback(IRewardCallback *in_rewardCallback) { _brainCloudComms->registerRewardCallback(in_rewardCallback); } void BrainCloudClient::deregisterRewardCallback() { _brainCloudComms->deregisterRewardCallback(); } void BrainCloudClient::registerFileUploadCallback(IFileUploadCallback * in_fileUploadCallback) { _brainCloudComms->registerFileUploadCallback(in_fileUploadCallback); } void BrainCloudClient::deregisterFileUploadCallback() { _brainCloudComms->deregisterFileUploadCallback(); } void BrainCloudClient::registerGlobalErrorCallback(IGlobalErrorCallback * in_globalErrorCallback) { _brainCloudComms->registerGlobalErrorCallback(in_globalErrorCallback); } void BrainCloudClient::deregisterGlobalErrorCallback() { _brainCloudComms->deregisterGlobalErrorCallback(); } void BrainCloudClient::registerNetworkErrorCallback(INetworkErrorCallback * in_networkErrorCallback) { _brainCloudComms->registerNetworkErrorCallback(in_networkErrorCallback); } void BrainCloudClient::deregisterNetworkErrorCallback() { _brainCloudComms->deregisterNetworkErrorCallback(); } void BrainCloudClient::enableLogging(bool shouldEnable) { _brainCloudComms->enableLogging(shouldEnable); _lobbyService->enableLogging(shouldEnable); _rttComms->enableLogging(shouldEnable); } /** * Heart beat to keep session(s) current, and retrieve any pending events... */ void BrainCloudClient::heartbeat() { _brainCloudComms->sendHeartbeat(); } void BrainCloudClient::sendRequest(ServerCall * in_serviceMessage) { _brainCloudComms->addToQueue(in_serviceMessage); } void BrainCloudClient::resetCommunication() { _rttComms->resetCommunication(); _brainCloudComms->resetCommunication(); _brainCloudComms->setSessionId(""); _authenticationService->setProfileId(""); } void BrainCloudClient::shutdown() { _rttComms->shutdown(); _brainCloudComms->shutdown(); _brainCloudComms->setSessionId(""); _authenticationService->setProfileId(""); } bool BrainCloudClient::isAuthenticated() { return _brainCloudComms->isAuthenticated(); } bool BrainCloudClient::isInitialized() { return _brainCloudComms->isInitialized() && _rttComms->isInitialized(); } void BrainCloudClient::setImmediateRetryOnError(bool value) { _brainCloudComms->setImmediateRetryOnError(value); } /** * Retrieve the pointer to the singleton BrainCloudClient instance. */ BrainCloudClient * BrainCloudClient::getInstance() { if(EnableSingletonMode == false) { throw std::invalid_argument(SingletonUseErrorMessage); } if (_instance == NULL) { _instance = new BrainCloudClient(); } return _instance; } void BrainCloudClient::setHeartbeatInterval(int in_intervalInMilliseconds) { _brainCloudComms->setHeartbeatInterval(in_intervalInMilliseconds); } const std::vector<int> & BrainCloudClient::getPacketTimeouts() { return _brainCloudComms->getPacketTimeouts(); } void BrainCloudClient::setPacketTimeouts(const std::vector<int> & in_packetTimeouts) { _brainCloudComms->setPacketTimeouts(in_packetTimeouts); } void BrainCloudClient::setPacketTimeoutsToDefault() { _brainCloudComms->setPacketTimeoutsToDefault(); } void BrainCloudClient::setAuthenticationPacketTimeout(int in_timeoutSecs) { _brainCloudComms->setAuthenticationPacketTimeout(in_timeoutSecs); } int BrainCloudClient::getAuthenticationPacketTimeout() { return _brainCloudComms->getAuthenticationPacketTimeout(); } void BrainCloudClient::setOldStyleStatusMessageErrorCallback(bool in_enabled) { _brainCloudComms->setOldStyleStatusMessageErrorCallback(in_enabled); } void BrainCloudClient::setErrorCallbackOn202Status(bool in_isError) { _brainCloudComms->setErrorCallbackOn202Status(in_isError); } int BrainCloudClient::getUploadLowTransferRateTimeout() { return _brainCloudComms->getUploadLowTransferRateTimeout(); } void BrainCloudClient::setUploadLowTransferRateTimeout(int in_timeoutSecs) { _brainCloudComms->setUploadLowTransferRateTimeout(in_timeoutSecs); } int BrainCloudClient::getUploadLowTransferRateThreshold() { return _brainCloudComms->getUploadLowTransferRateThreshold(); } void BrainCloudClient::setUploadLowTransferRateThreshold(int in_bytesPerSec) { _brainCloudComms->setUploadLowTransferRateThreshold(in_bytesPerSec); } void BrainCloudClient::enableNetworkErrorMessageCaching(bool in_enabled) { _brainCloudComms->enableNetworkErrorMessageCaching(in_enabled); } void BrainCloudClient::retryCachedMessages() { _brainCloudComms->retryCachedMessages(); } void BrainCloudClient::flushCachedMessages(bool in_sendApiErrorCallbacks) { _brainCloudComms->flushCachedMessages(in_sendApiErrorCallbacks); } void BrainCloudClient::insertEndOfMessageBundleMarker() { _brainCloudComms->insertEndOfMessageBundleMarker(); } //////////////////////////////////////////////////// // Private Methods //////////////////////////////////////////////////// void BrainCloudClient::setupOSLocaleData() { Device::getLocale(&_timezoneOffset, &_languageCode, &_countryCode); } } // end namespace <commit_msg>Updated version<commit_after>// BrainCloudClient.cpp // BrainCloudLib // Copyright 2016 bitHeads, Inc. All Rights Reserved. #include <cstring> #include <iomanip> #include <iostream> #include <sstream> #include <vector> #include "braincloud/BrainCloudClient.h" #include "braincloud/internal/Device.h" #include "braincloud/internal/JsonUtil.h" #include "braincloud/internal/URLRequestMethod.h" namespace BrainCloud { // Define all static member variables. bool BrainCloudClient::EnableSingletonMode = false; const char * BrainCloudClient::SingletonUseErrorMessage = "Singleton usage is disabled. If called by mistake, use your own variable that holds an instance of the bcWrapper/bcClient."; BrainCloudClient * BrainCloudClient::_instance = NULL; std::string BrainCloudClient::s_brainCloudClientVersion = "4.4.1"; const char* BC_SERVER_URL = "https://sharedprod.braincloudservers.com/dispatcherv2"; /** * Constructor */ BrainCloudClient::BrainCloudClient() : _brainCloudComms(IBrainCloudComms::create(this)), _rttComms(new RTTComms(this)), _asyncMatchService(new BrainCloudAsyncMatch(this)), _authenticationService(new BrainCloudAuthentication(this)), _chatService(new BrainCloudChat(this)), _dataStreamService(new BrainCloudDataStream(this)), _entityService(new BrainCloudEntity(this)), _eventService(new BrainCloudEvent(this)), _fileService(new BrainCloudFile(this)), _friendService(new BrainCloudFriend(this)), _gamificationService(new BrainCloudGamification(this)), _globalAppService(new BrainCloudGlobalApp(this)), _globalEntityService(new BrainCloudGlobalEntity(this)), _globalStatisticsService(new BrainCloudGlobalStatistics(this)), _groupService(new BrainCloudGroup(this)), _identityService(new BrainCloudIdentity(this)), _lobbyService(new BrainCloudLobby(this)), _mailService(new BrainCloudMail(this)), _matchmakingService(new BrainCloudMatchmaking(this)), _messagingService(new BrainCloudMessaging(this)), _oneWayMatchService(new BrainCloudOneWayMatch(this)), _playbackStreamService(new BrainCloudPlaybackStream(this)), _playerStateService(new BrainCloudPlayerState(this)), _playerStatisticsService(new BrainCloudPlayerStatistics(this)), _playerStatisticsEventService(new BrainCloudPlayerStatisticsEvent(this)), _presenceService(new BrainCloudPresence(this)), _productService(new BrainCloudProduct(this)), _virtualCurrencyService(new BrainCloudVirtualCurrency(this)), _appStoreService(new BrainCloudAppStore(this)), _profanityService(new BrainCloudProfanity(this)), _pushNotificationService(new BrainCloudPushNotification(this)), _redemptionCodeService(new BrainCloudRedemptionCode(this)), _s3HandlingService(new BrainCloudS3Handling(this)), _scriptService(new BrainCloudScript(this)), _socialLeaderboardService(new BrainCloudSocialLeaderboard(this)), _steamService(new BrainCloudSteam(this)), _timeService(new BrainCloudTime(this)), _tournamentService(new BrainCloudTournament(this)), _customEntityService(new BrainCloudCustomEntity(this)), _itemCatalogService(new BrainCloudItemCatalog(this)), _userItemsService(new BrainCloudUserItems(this)), _releasePlatform(""), _appVersion(""), _timezoneOffset(0.0) { //needed this here otherwise out of scope compiler error _rttService = new BrainCloudRTT(_rttComms, this); } BrainCloudClient::~BrainCloudClient() { delete _rttService; delete _tournamentService; delete _customEntityService; delete _itemCatalogService; delete _timeService; delete _steamService; delete _socialLeaderboardService; delete _scriptService; delete _s3HandlingService; delete _redemptionCodeService; delete _pushNotificationService; delete _profanityService; delete _appStoreService; delete _virtualCurrencyService; delete _productService; delete _presenceService; delete _playerStatisticsEventService; delete _playerStatisticsService; delete _playerStateService; delete _playbackStreamService; delete _oneWayMatchService; delete _messagingService; delete _matchmakingService; delete _mailService; delete _lobbyService; delete _identityService; delete _groupService; delete _globalStatisticsService; delete _globalEntityService; delete _globalAppService; delete _gamificationService; delete _friendService; delete _fileService; delete _eventService; delete _entityService; delete _dataStreamService; delete _chatService; delete _authenticationService; delete _asyncMatchService; delete _rttComms; delete _brainCloudComms; } //////////////////////////////////////////////////// // Public Methods //////////////////////////////////////////////////// const char * BrainCloudClient::getSessionId() const { return(_brainCloudComms->getSessionId().c_str()); } const char * BrainCloudClient::getRttConnectionId() const{ return(_rttComms->getConnectionId().c_str()); } void BrainCloudClient::initializeComms(const char * in_serverURL, const char * in_appId, const std::map<std::string, std::string>& in_secretMap) { if (_brainCloudComms) { // automatically upgrade any older clients using "dispatcher" url // to "dispatcherv2" endpoint. Comms supports this now and otherwise // the change is transparent to the client. const char * urlToUse = in_serverURL; std::string url = in_serverURL; if (url.find("dispatcherv2") == std::string::npos) { size_t index = url.find("dispatcher"); if (index != std::string::npos) { url = url.substr(0, index); url += "dispatcherv2"; urlToUse = url.c_str(); } } _brainCloudComms->initializeWithApps(urlToUse, in_appId, in_secretMap); } if (_rttComms) { _rttComms->initialize(); } } void BrainCloudClient::initialize(const char * in_serverURL, const char * in_secretKey, const char * in_appId, const char * in_appVersion) { std::string error = ""; if (in_serverURL == NULL || strlen(in_serverURL) <= 0) error = "serverURL was null or empty"; else if (in_secretKey == NULL || strlen(in_secretKey) <= 0) error = "secretKey was null or empty"; else if (in_appId == NULL || strlen(in_appId) <= 0) error = "appId was null or empty"; else if (in_appVersion == NULL || strlen(in_appVersion) <= 0) error = "appVersion was null or empty"; if (error.length() > 0) { std::cout << "ERROR | Failed to initialize brainCloud - " << error; return; } std::map<std::string, std::string> secretMap; secretMap[in_appId] = in_secretKey; initializeComms(in_serverURL, in_appId, secretMap); setupOSLocaleData(); _releasePlatform = Device::getPlatformName(); _appVersion = in_appVersion; } void BrainCloudClient::initialize(const char * in_secretKey, const char * in_appId, const char * in_appVersion) { initialize(BC_SERVER_URL, in_secretKey, in_appId, in_appVersion); } void BrainCloudClient::initializeWithApps(const char * in_serverURL, const char * in_defaultAppId, const std::map<std::string, std::string>& in_secretMap, const char * in_appVersion) { std::string error = ""; if (in_serverURL == NULL || strlen(in_serverURL) <= 0) error = "serverURL was null or empty"; else if (in_defaultAppId == NULL || strlen(in_defaultAppId) <= 0) error = "appId was null or empty"; else if (in_appVersion == NULL || strlen(in_appVersion) <= 0) error = "appVersion was null or empty"; else if (in_secretMap.find(in_defaultAppId) == in_secretMap.end()) error = "not secretKey match for appid"; if (error.length() > 0) { std::cout << "ERROR | Failed to initialize brainCloud - " << error; return; } initializeComms(in_serverURL, in_defaultAppId, in_secretMap); setupOSLocaleData(); _releasePlatform = Device::getPlatformName(); _appVersion = in_appVersion; } void BrainCloudClient::initializeWithApps(const char* in_defaultAppId, const std::map<std::string, std::string>& in_secretMap, const char* in_appVersion) { initializeWithApps(BC_SERVER_URL, in_defaultAppId, in_secretMap, in_appVersion); } void BrainCloudClient::initializeIdentity(const char * in_profileId, const char * in_anonymousId) { _authenticationService->initialize(in_profileId, in_anonymousId); } void BrainCloudClient::runCallbacks() { _brainCloudComms->runCallbacks(); _lobbyService->runPingCallbacks(); _rttComms->runCallbacks(); } void BrainCloudClient::registerEventCallback(IEventCallback *in_eventCallback) { _brainCloudComms->registerEventCallback(in_eventCallback); } void BrainCloudClient::deregisterEventCallback() { _brainCloudComms->deregisterEventCallback(); } void BrainCloudClient::registerRewardCallback(IRewardCallback *in_rewardCallback) { _brainCloudComms->registerRewardCallback(in_rewardCallback); } void BrainCloudClient::deregisterRewardCallback() { _brainCloudComms->deregisterRewardCallback(); } void BrainCloudClient::registerFileUploadCallback(IFileUploadCallback * in_fileUploadCallback) { _brainCloudComms->registerFileUploadCallback(in_fileUploadCallback); } void BrainCloudClient::deregisterFileUploadCallback() { _brainCloudComms->deregisterFileUploadCallback(); } void BrainCloudClient::registerGlobalErrorCallback(IGlobalErrorCallback * in_globalErrorCallback) { _brainCloudComms->registerGlobalErrorCallback(in_globalErrorCallback); } void BrainCloudClient::deregisterGlobalErrorCallback() { _brainCloudComms->deregisterGlobalErrorCallback(); } void BrainCloudClient::registerNetworkErrorCallback(INetworkErrorCallback * in_networkErrorCallback) { _brainCloudComms->registerNetworkErrorCallback(in_networkErrorCallback); } void BrainCloudClient::deregisterNetworkErrorCallback() { _brainCloudComms->deregisterNetworkErrorCallback(); } void BrainCloudClient::enableLogging(bool shouldEnable) { _brainCloudComms->enableLogging(shouldEnable); _lobbyService->enableLogging(shouldEnable); _rttComms->enableLogging(shouldEnable); } /** * Heart beat to keep session(s) current, and retrieve any pending events... */ void BrainCloudClient::heartbeat() { _brainCloudComms->sendHeartbeat(); } void BrainCloudClient::sendRequest(ServerCall * in_serviceMessage) { _brainCloudComms->addToQueue(in_serviceMessage); } void BrainCloudClient::resetCommunication() { _rttComms->resetCommunication(); _brainCloudComms->resetCommunication(); _brainCloudComms->setSessionId(""); _authenticationService->setProfileId(""); } void BrainCloudClient::shutdown() { _rttComms->shutdown(); _brainCloudComms->shutdown(); _brainCloudComms->setSessionId(""); _authenticationService->setProfileId(""); } bool BrainCloudClient::isAuthenticated() { return _brainCloudComms->isAuthenticated(); } bool BrainCloudClient::isInitialized() { return _brainCloudComms->isInitialized() && _rttComms->isInitialized(); } void BrainCloudClient::setImmediateRetryOnError(bool value) { _brainCloudComms->setImmediateRetryOnError(value); } /** * Retrieve the pointer to the singleton BrainCloudClient instance. */ BrainCloudClient * BrainCloudClient::getInstance() { if(EnableSingletonMode == false) { throw std::invalid_argument(SingletonUseErrorMessage); } if (_instance == NULL) { _instance = new BrainCloudClient(); } return _instance; } void BrainCloudClient::setHeartbeatInterval(int in_intervalInMilliseconds) { _brainCloudComms->setHeartbeatInterval(in_intervalInMilliseconds); } const std::vector<int> & BrainCloudClient::getPacketTimeouts() { return _brainCloudComms->getPacketTimeouts(); } void BrainCloudClient::setPacketTimeouts(const std::vector<int> & in_packetTimeouts) { _brainCloudComms->setPacketTimeouts(in_packetTimeouts); } void BrainCloudClient::setPacketTimeoutsToDefault() { _brainCloudComms->setPacketTimeoutsToDefault(); } void BrainCloudClient::setAuthenticationPacketTimeout(int in_timeoutSecs) { _brainCloudComms->setAuthenticationPacketTimeout(in_timeoutSecs); } int BrainCloudClient::getAuthenticationPacketTimeout() { return _brainCloudComms->getAuthenticationPacketTimeout(); } void BrainCloudClient::setOldStyleStatusMessageErrorCallback(bool in_enabled) { _brainCloudComms->setOldStyleStatusMessageErrorCallback(in_enabled); } void BrainCloudClient::setErrorCallbackOn202Status(bool in_isError) { _brainCloudComms->setErrorCallbackOn202Status(in_isError); } int BrainCloudClient::getUploadLowTransferRateTimeout() { return _brainCloudComms->getUploadLowTransferRateTimeout(); } void BrainCloudClient::setUploadLowTransferRateTimeout(int in_timeoutSecs) { _brainCloudComms->setUploadLowTransferRateTimeout(in_timeoutSecs); } int BrainCloudClient::getUploadLowTransferRateThreshold() { return _brainCloudComms->getUploadLowTransferRateThreshold(); } void BrainCloudClient::setUploadLowTransferRateThreshold(int in_bytesPerSec) { _brainCloudComms->setUploadLowTransferRateThreshold(in_bytesPerSec); } void BrainCloudClient::enableNetworkErrorMessageCaching(bool in_enabled) { _brainCloudComms->enableNetworkErrorMessageCaching(in_enabled); } void BrainCloudClient::retryCachedMessages() { _brainCloudComms->retryCachedMessages(); } void BrainCloudClient::flushCachedMessages(bool in_sendApiErrorCallbacks) { _brainCloudComms->flushCachedMessages(in_sendApiErrorCallbacks); } void BrainCloudClient::insertEndOfMessageBundleMarker() { _brainCloudComms->insertEndOfMessageBundleMarker(); } //////////////////////////////////////////////////// // Private Methods //////////////////////////////////////////////////// void BrainCloudClient::setupOSLocaleData() { Device::getLocale(&_timezoneOffset, &_languageCode, &_countryCode); } } // end namespace <|endoftext|>
<commit_before>/** @file CollisionManager.cpp @author Philip Abbet Implementation of the class 'Athena::Physics::CollisionManager' */ #include <Athena-Physics/CollisionManager.h> #include <Athena-Physics/Body.h> #include <Athena-Physics/GhostObject.h> #include <Athena-Physics/Conversions.h> using namespace Athena; using namespace Athena::Physics; using namespace Athena::Entities; using namespace Athena::Signals; using namespace std; /********************************** STATIC ATTRIBUTES **********************************/ CollisionManager CollisionManager::DefaultManager; CollisionManager* CollisionManager::_CurrentManager = 0; /***************************** CONSTRUCTION / DESTRUCTION ******************************/ CollisionManager::CollisionManager() : m_pFilter(0) { unsigned int offset = 0; for (unsigned int i = 0; i < NB_GROUPS; ++i) { m_indexedPairs[i] = &m_collisionPairs[offset]; offset += NB_GROUPS - i; } } //----------------------------------------------------------------------- CollisionManager::~CollisionManager() { } /*********************** IMPLEMENTATION OF btOverlapFilterCallback *********************/ bool CollisionManager::needBroadphaseCollision(btBroadphaseProxy* pProxy1, btBroadphaseProxy* pProxy2) const { tCollisionGroup group1 = getGroupOfCollisionObject((btCollisionObject*) pProxy1->m_clientObject); tCollisionGroup group2 = getGroupOfCollisionObject((btCollisionObject*) pProxy2->m_clientObject); if ((group1 == -1) || (group2 == -1)) return true; tPairState state; if (group1 <= group2) state = m_indexedPairs[group1][group2]; else state = m_indexedPairs[group2][group1]; return (state != PAIR_DISABLED); } /************************************* METHODS ****************************************/ void CollisionManager::enableCollision(tCollisionGroup group1, tCollisionGroup group2, bool bEnableFilter) { tPairState* pState; if (group1 <= group2) pState = &m_indexedPairs[group1][group2]; else pState = &m_indexedPairs[group2][group1]; *pState = (bEnableFilter ? PAIR_ENABLED_WITH_FILTER : PAIR_ENABLED); } /********************************* STATIC METHODS **************************************/ void CollisionManager::customNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo) { if (CollisionManager::_CurrentManager) { tCollisionGroup group1, group2; PhysicalComponent* pComponent1 = getComponentOfCollisionObject((btCollisionObject*) collisionPair.m_pProxy0->m_clientObject, group1); PhysicalComponent* pComponent2 = getComponentOfCollisionObject((btCollisionObject*) collisionPair.m_pProxy1->m_clientObject, group2); if ((group1 == -1) || (group2 == -1)) { dispatcher.defaultNearCallback(collisionPair, dispatcher, dispatchInfo); return; } tPairState state; if (group1 <= group2) state = CollisionManager::_CurrentManager->m_indexedPairs[group1][group2]; else state = CollisionManager::_CurrentManager->m_indexedPairs[group2][group1]; assert(state != PAIR_DISABLED); bool bContinue = (state == PAIR_ENABLED) || !CollisionManager::_CurrentManager->m_pFilter || CollisionManager::_CurrentManager->m_pFilter->needsCollision(pComponent1, pComponent2); if (bContinue) dispatcher.defaultNearCallback(collisionPair, dispatcher, dispatchInfo); } } //----------------------------------------------------------------------- tCollisionGroup CollisionManager::getGroupOfCollisionObject(btCollisionObject* pObject) { btRigidBody* pRigidBody = btRigidBody::upcast(pObject); if (pRigidBody) return static_cast<Body*>(pRigidBody->getUserPointer())->getCollisionGroup(); btGhostObject* pGhostObject = btGhostObject::upcast(pObject); if (pGhostObject) return static_cast<GhostObject*>(pGhostObject->getUserPointer())->getCollisionGroup(); return -1; } //----------------------------------------------------------------------- PhysicalComponent* CollisionManager::getComponentOfCollisionObject(btCollisionObject* pObject, tCollisionGroup &group) { btRigidBody* pRigidBody = btRigidBody::upcast(pObject); if (pRigidBody) { Body* pBody = static_cast<Body*>(pRigidBody->getUserPointer()); group = pBody->getCollisionGroup(); return pBody; } btGhostObject* pGhostObject = btGhostObject::upcast(pObject); if (pGhostObject) { GhostObject* pGhost = static_cast<GhostObject*>(pGhostObject->getUserPointer()); group = pGhost->getCollisionGroup(); return pGhost; } group = -1; return 0; } <commit_msg>Bugfix: incorrect indexing in the internal collision pairs array<commit_after>/** @file CollisionManager.cpp @author Philip Abbet Implementation of the class 'Athena::Physics::CollisionManager' */ #include <Athena-Physics/CollisionManager.h> #include <Athena-Physics/Body.h> #include <Athena-Physics/GhostObject.h> #include <Athena-Physics/Conversions.h> using namespace Athena; using namespace Athena::Physics; using namespace Athena::Entities; using namespace Athena::Signals; using namespace std; /********************************** STATIC ATTRIBUTES **********************************/ CollisionManager CollisionManager::DefaultManager; CollisionManager* CollisionManager::_CurrentManager = 0; /***************************** CONSTRUCTION / DESTRUCTION ******************************/ CollisionManager::CollisionManager() : m_pFilter(0) { unsigned int offset = 0; for (unsigned int i = 0; i < NB_GROUPS; ++i) { m_indexedPairs[i] = &m_collisionPairs[offset]; offset += NB_GROUPS - i; } } //----------------------------------------------------------------------- CollisionManager::~CollisionManager() { } /*********************** IMPLEMENTATION OF btOverlapFilterCallback *********************/ bool CollisionManager::needBroadphaseCollision(btBroadphaseProxy* pProxy1, btBroadphaseProxy* pProxy2) const { tCollisionGroup group1 = getGroupOfCollisionObject((btCollisionObject*) pProxy1->m_clientObject); tCollisionGroup group2 = getGroupOfCollisionObject((btCollisionObject*) pProxy2->m_clientObject); if ((group1 == -1) || (group2 == -1)) return true; tPairState state; if (group1 <= group2) state = m_indexedPairs[1 << group1][1 << group2]; else state = m_indexedPairs[1 << group2][1 << group1]; return (state != PAIR_DISABLED); } /************************************* METHODS ****************************************/ void CollisionManager::enableCollision(tCollisionGroup group1, tCollisionGroup group2, bool bEnableFilter) { tPairState* pState; if (group1 <= group2) pState = &m_indexedPairs[1 << group1][1 << group2]; else pState = &m_indexedPairs[1 << group2][1 << group1]; *pState = (bEnableFilter ? PAIR_ENABLED_WITH_FILTER : PAIR_ENABLED); } /********************************* STATIC METHODS **************************************/ void CollisionManager::customNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo) { if (CollisionManager::_CurrentManager) { tCollisionGroup group1, group2; PhysicalComponent* pComponent1 = getComponentOfCollisionObject((btCollisionObject*) collisionPair.m_pProxy0->m_clientObject, group1); PhysicalComponent* pComponent2 = getComponentOfCollisionObject((btCollisionObject*) collisionPair.m_pProxy1->m_clientObject, group2); if ((group1 == -1) || (group2 == -1)) { dispatcher.defaultNearCallback(collisionPair, dispatcher, dispatchInfo); return; } tPairState state; if (group1 <= group2) state = CollisionManager::_CurrentManager->m_indexedPairs[1 << group1][1 << group2]; else state = CollisionManager::_CurrentManager->m_indexedPairs[1 << group2][1 << group1]; assert(state != PAIR_DISABLED); bool bContinue = (state == PAIR_ENABLED) || !CollisionManager::_CurrentManager->m_pFilter || CollisionManager::_CurrentManager->m_pFilter->needsCollision(pComponent1, pComponent2); if (bContinue) dispatcher.defaultNearCallback(collisionPair, dispatcher, dispatchInfo); } } //----------------------------------------------------------------------- tCollisionGroup CollisionManager::getGroupOfCollisionObject(btCollisionObject* pObject) { btRigidBody* pRigidBody = btRigidBody::upcast(pObject); if (pRigidBody) return static_cast<Body*>(pRigidBody->getUserPointer())->getCollisionGroup(); btGhostObject* pGhostObject = btGhostObject::upcast(pObject); if (pGhostObject) return static_cast<GhostObject*>(pGhostObject->getUserPointer())->getCollisionGroup(); return -1; } //----------------------------------------------------------------------- PhysicalComponent* CollisionManager::getComponentOfCollisionObject(btCollisionObject* pObject, tCollisionGroup &group) { btRigidBody* pRigidBody = btRigidBody::upcast(pObject); if (pRigidBody) { Body* pBody = static_cast<Body*>(pRigidBody->getUserPointer()); group = pBody->getCollisionGroup(); return pBody; } btGhostObject* pGhostObject = btGhostObject::upcast(pObject); if (pGhostObject) { GhostObject* pGhost = static_cast<GhostObject*>(pGhostObject->getUserPointer()); group = pGhost->getCollisionGroup(); return pGhost; } group = -1; return 0; } <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * libtest * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <libtest/common.h> #include <curl/curl.h> namespace libtest { namespace http { #define YATL_USERAGENT "YATL/1.0" extern "C" size_t http_get_result_callback(void *ptr, size_t size, size_t nmemb, void *data) { size_t body_size= size * nmemb; vchar_t *_body= (vchar_t*)data; _body->get().resize(size * nmemb); memcpy(&(_body)[0], ptr, _body->get().size()); return _body->get().size(); } bool GET::execute() { if (HAVE_LIBCURL) { CURL *curl= curl_easy_init();; curl_easy_setopt(curl, CURLOPT_URL, url().c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&_body); curl_easy_setopt(curl, CURLOPT_USERAGENT, YATL_USERAGENT); CURLcode retref= curl_easy_perform(curl); curl_easy_cleanup(curl); return retref == CURLE_OK; } return false; } bool POST::execute() { if (HAVE_LIBCURL) { CURL *curl= curl_easy_init();; curl_easy_cleanup(curl); } return false; } } // namespace http } // namespace libtest <commit_msg>Fix curl reference via include<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * libtest * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <libtest/common.h> #ifdef HAVE_LIBCURL #include <curl/curl.h> #endif namespace libtest { namespace http { #define YATL_USERAGENT "YATL/1.0" extern "C" size_t http_get_result_callback(void *ptr, size_t size, size_t nmemb, void *data) { size_t body_size= size * nmemb; vchar_t *_body= (vchar_t*)data; _body->get().resize(size * nmemb); memcpy(&(_body)[0], ptr, _body->get().size()); return _body->get().size(); } bool GET::execute() { if (HAVE_LIBCURL) { CURL *curl= curl_easy_init();; curl_easy_setopt(curl, CURLOPT_URL, url().c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_result_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&_body); curl_easy_setopt(curl, CURLOPT_USERAGENT, YATL_USERAGENT); CURLcode retref= curl_easy_perform(curl); curl_easy_cleanup(curl); return retref == CURLE_OK; } return false; } bool POST::execute() { if (HAVE_LIBCURL) { CURL *curl= curl_easy_init();; curl_easy_cleanup(curl); } return false; } } // namespace http } // namespace libtest <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2010 by Alex Novichkov email : [email protected] copyright : (C) 2006 by Lukáš Lalinský email : [email protected] (original WavPack implementation) ***************************************************************************/ /*************************************************************************** * 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., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tstring.h> #include <tdebug.h> #include <bitset> #include "id3v2tag.h" #include "apeproperties.h" #include "apefile.h" using namespace TagLib; class APE::Properties::PropertiesPrivate { public: PropertiesPrivate(File *file, long streamLength) : length(0), bitrate(0), sampleRate(0), channels(0), version(0), bitsPerSample(0), sampleFrames(0), file(file), streamLength(streamLength) {} int length; int bitrate; int sampleRate; int channels; int version; int bitsPerSample; uint sampleFrames; File *file; long streamLength; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// APE::Properties::Properties(File *file, ReadStyle style) : AudioProperties(style) { d = new PropertiesPrivate(file, file->length()); read(); } APE::Properties::~Properties() { delete d; } int APE::Properties::length() const { return d->length; } int APE::Properties::bitrate() const { return d->bitrate; } int APE::Properties::sampleRate() const { return d->sampleRate; } int APE::Properties::channels() const { return d->channels; } int APE::Properties::version() const { return d->version; } int APE::Properties::bitsPerSample() const { return d->bitsPerSample; } TagLib::uint APE::Properties::sampleFrames() const { return d->sampleFrames; } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// void APE::Properties::read() { // First we are searching the descriptor long offset = findDescriptor(); if(offset < 0) return; // Then we read the header common for all versions of APE d->file->seek(offset); ByteVector commonHeader = d->file->readBlock(6); if(!commonHeader.startsWith("MAC ")) return; d->version = commonHeader.toUShort(4, false); if(d->version >= 3980) { analyzeCurrent(); } else { analyzeOld(); } } long APE::Properties::findDescriptor() { long ID3v2Location = findID3v2(); long ID3v2OriginalSize = 0; bool hasID3v2 = false; if(ID3v2Location >= 0) { ID3v2::Tag tag(d->file, ID3v2Location); ID3v2OriginalSize = tag.header()->completeTagSize(); if(tag.header()->tagSize() > 0) hasID3v2 = true; } long offset = 0; if(hasID3v2) offset = d->file->find("MAC ", ID3v2Location + ID3v2OriginalSize); else offset = d->file->find("MAC "); if(offset < 0) { debug("APE::Properties::findDescriptor() -- APE descriptor not found"); return -1; } return offset; } long APE::Properties::findID3v2() { if(!d->file->isValid()) return -1; d->file->seek(0); if(d->file->readBlock(3) == ID3v2::Header::fileIdentifier()) return 0; return -1; } void APE::Properties::analyzeCurrent() { // Read the descriptor d->file->seek(2, File::Current); ByteVector descriptor = d->file->readBlock(44); const uint descriptorBytes = descriptor.toUInt(0, false); if ((descriptorBytes - 52) > 0) d->file->seek(descriptorBytes - 52, File::Current); // Read the header ByteVector header = d->file->readBlock(24); // Get the APE info d->channels = header.toShort(18, false); d->sampleRate = header.toUInt(20, false); d->bitsPerSample = header.toShort(16, false); //d->compressionLevel = const uint totalFrames = header.toUInt(12, false); const uint blocksPerFrame = header.toUInt(4, false); const uint finalFrameBlocks = header.toUInt(8, false); d->sampleFrames = totalFrames > 0 ? (totalFrames - 1) * blocksPerFrame + finalFrameBlocks : 0; d->length = d->sampleRate > 0 ? d->sampleFrames / d->sampleRate : 0; d->bitrate = d->length > 0 ? ((d->streamLength * 8L) / d->length) / 1000 : 0; } void APE::Properties::analyzeOld() { ByteVector header = d->file->readBlock(26); const uint totalFrames = header.toUInt(18, false); // Fail on 0 length APE files (catches non-finalized APE files) if(totalFrames == 0) return; const short compressionLevel = header.toShort(0, false); uint blocksPerFrame; if(d->version >= 3950) blocksPerFrame = 73728 * 4; else if(d->version >= 3900 || (d->version >= 3800 && compressionLevel == 4000)) blocksPerFrame = 73728; else blocksPerFrame = 9216; d->channels = header.toShort(4, false); d->sampleRate = header.toUInt(6, false); const uint finalFrameBlocks = header.toUInt(22, false); const uint totalBlocks = totalFrames > 0 ? (totalFrames - 1) * blocksPerFrame + finalFrameBlocks : 0; d->length = totalBlocks / d->sampleRate; d->bitrate = d->length > 0 ? ((d->streamLength * 8L) / d->length) / 1000 : 0; } <commit_msg>Fix a division by zero error when parsing an APE file.<commit_after>/*************************************************************************** copyright : (C) 2010 by Alex Novichkov email : [email protected] copyright : (C) 2006 by Lukáš Lalinský email : [email protected] (original WavPack implementation) ***************************************************************************/ /*************************************************************************** * 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., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tstring.h> #include <tdebug.h> #include <bitset> #include "id3v2tag.h" #include "apeproperties.h" #include "apefile.h" using namespace TagLib; class APE::Properties::PropertiesPrivate { public: PropertiesPrivate(File *file, long streamLength) : length(0), bitrate(0), sampleRate(0), channels(0), version(0), bitsPerSample(0), sampleFrames(0), file(file), streamLength(streamLength) {} int length; int bitrate; int sampleRate; int channels; int version; int bitsPerSample; uint sampleFrames; File *file; long streamLength; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// APE::Properties::Properties(File *file, ReadStyle style) : AudioProperties(style) { d = new PropertiesPrivate(file, file->length()); read(); } APE::Properties::~Properties() { delete d; } int APE::Properties::length() const { return d->length; } int APE::Properties::bitrate() const { return d->bitrate; } int APE::Properties::sampleRate() const { return d->sampleRate; } int APE::Properties::channels() const { return d->channels; } int APE::Properties::version() const { return d->version; } int APE::Properties::bitsPerSample() const { return d->bitsPerSample; } TagLib::uint APE::Properties::sampleFrames() const { return d->sampleFrames; } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// void APE::Properties::read() { // First we are searching the descriptor long offset = findDescriptor(); if(offset < 0) return; // Then we read the header common for all versions of APE d->file->seek(offset); ByteVector commonHeader = d->file->readBlock(6); if(!commonHeader.startsWith("MAC ")) return; d->version = commonHeader.toUShort(4, false); if(d->version >= 3980) { analyzeCurrent(); } else { analyzeOld(); } } long APE::Properties::findDescriptor() { long ID3v2Location = findID3v2(); long ID3v2OriginalSize = 0; bool hasID3v2 = false; if(ID3v2Location >= 0) { ID3v2::Tag tag(d->file, ID3v2Location); ID3v2OriginalSize = tag.header()->completeTagSize(); if(tag.header()->tagSize() > 0) hasID3v2 = true; } long offset = 0; if(hasID3v2) offset = d->file->find("MAC ", ID3v2Location + ID3v2OriginalSize); else offset = d->file->find("MAC "); if(offset < 0) { debug("APE::Properties::findDescriptor() -- APE descriptor not found"); return -1; } return offset; } long APE::Properties::findID3v2() { if(!d->file->isValid()) return -1; d->file->seek(0); if(d->file->readBlock(3) == ID3v2::Header::fileIdentifier()) return 0; return -1; } void APE::Properties::analyzeCurrent() { // Read the descriptor d->file->seek(2, File::Current); ByteVector descriptor = d->file->readBlock(44); const uint descriptorBytes = descriptor.toUInt(0, false); if ((descriptorBytes - 52) > 0) d->file->seek(descriptorBytes - 52, File::Current); // Read the header ByteVector header = d->file->readBlock(24); // Get the APE info d->channels = header.toShort(18, false); d->sampleRate = header.toUInt(20, false); d->bitsPerSample = header.toShort(16, false); //d->compressionLevel = const uint totalFrames = header.toUInt(12, false); const uint blocksPerFrame = header.toUInt(4, false); const uint finalFrameBlocks = header.toUInt(8, false); d->sampleFrames = totalFrames > 0 ? (totalFrames - 1) * blocksPerFrame + finalFrameBlocks : 0; d->length = d->sampleRate > 0 ? d->sampleFrames / d->sampleRate : 0; d->bitrate = d->length > 0 ? ((d->streamLength * 8L) / d->length) / 1000 : 0; } void APE::Properties::analyzeOld() { ByteVector header = d->file->readBlock(26); const uint totalFrames = header.toUInt(18, false); // Fail on 0 length APE files (catches non-finalized APE files) if(totalFrames == 0) return; const short compressionLevel = header.toShort(0, false); uint blocksPerFrame; if(d->version >= 3950) blocksPerFrame = 73728 * 4; else if(d->version >= 3900 || (d->version >= 3800 && compressionLevel == 4000)) blocksPerFrame = 73728; else blocksPerFrame = 9216; d->channels = header.toShort(4, false); d->sampleRate = header.toUInt(6, false); const uint finalFrameBlocks = header.toUInt(22, false); uint totalBlocks = 0; if(totalFrames > 0) totalBlocks = (totalFrames - 1) * blocksPerFrame + finalFrameBlocks; if(d->sampleRate > 0) d->length = totalBlocks / d->sampleRate; if(d->length > 0) d->bitrate = ((d->streamLength * 8L) / d->length) / 1000; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "rvdbg.h" BOOLEAN tDSend; CRITICAL_SECTION repr; CONDITION_VARIABLE reprcondition; static void HandleSSE() { if (r_registers.bxmm0 == 1) __asm movsd xmm0, r_registers.dxmm0; else if (r_registers.bxmm0 == 2) __asm movss xmm0, r_registers.xmm0; if (r_registers.bxmm1) __asm movsd xmm1, r_registers.dxmm1; else if (r_registers.bxmm1 == 2) __asm movss xmm1, r_registers.xmm1; if (r_registers.bxmm2) __asm movsd xmm2, r_registers.dxmm2; else if (r_registers.bxmm2 == 2) __asm movss xmm2, r_registers.xmm2; if (r_registers.bxmm3) __asm movsd xmm3, r_registers.dxmm3; else if (r_registers.bxmm3 == 2) __asm movss xmm3, r_registers.xmm3; if (r_registers.bxmm4) __asm movsd xmm4, r_registers.dxmm4; else if (r_registers.bxmm4 == 2) __asm movss xmm4, r_registers.xmm4; if (r_registers.bxmm5) __asm movsd xmm5, r_registers.dxmm5; else if (r_registers.bxmm5 == 2) __asm movss xmm5, r_registers.xmm5; if (r_registers.bxmm6) __asm movsd xmm6, r_registers.dxmm6; else if (r_registers.bxmm6 == 2) __asm movss xmm6, r_registers.xmm6; if (r_registers.bxmm7) __asm movsd xmm7, r_registers.dxmm7; else if (r_registers.bxmm7 == 2) __asm movss xmm7, r_registers.xmm7; r_registers.bxmm0 = 0; r_registers.bxmm1 = 0; r_registers.bxmm2 = 0; r_registers.bxmm3 = 0; r_registers.bxmm4 = 0; r_registers.bxmm5 = 0; r_registers.bxmm6 = 0; r_registers.bxmm7 = 0; } static PVOID CallChain() { size_t ExceptionElement = SearchSector(Sector, 128, ExceptionComparator); if (ExceptionElement > 128) { if (ExceptionMode == 2) { SuspendThreads(GetCurrentProcessId(), GetCurrentThreadId()); DWORD swap_ad = SwapAccess(AccessException, AccessException); if (!swap_ad) { ChunkExecutable = FALSE; return NULL; } Swaps.push_back((PVOID)swap_ad); return (PVOID)swap_ad; } return NULL; } SuspendThreads(GetCurrentProcessId(), GetCurrentThreadId()); Debugger = TRUE; tDSend = TRUE; for (size_t iterator = 0; iterator < sizeof(Threads); iterator++) { if (Threads[iterator] != NULL) ResumeThread(Threads[iterator]); } Sector[ExceptionElement].ExceptionCode = ExceptionCode; PVOID ReturnException = HandleException(Sector[ExceptionElement], Sector[ExceptionElement].ModuleName); r_registers.eip = ReturnException; Sector[ExceptionElement].Thread = GetCurrentThread(); Sector[ExceptionElement].IsAEHPresent = TRUE; Sector[ExceptionElement].ReturnAddress = r_registers.ReturnAddress; CurrentPool = Sector[ExceptionElement]; EnterCriticalSection(&RunLock); SleepConditionVariableCS(&Runnable, &RunLock, INFINITE); LeaveCriticalSection(&RunLock); ResumeThreads(GetCurrentProcessId(), GetCurrentThreadId()); UnlockSector(Sector, ExceptionElement); return r_registers.eip; } static __declspec(naked) VOID NTAPI KiUserExceptionDispatcher(PEXCEPTION_RECORD ExceptionRecord, PCONTEXT Context) { __asm { movss r_registers.xmm0, xmm0; movss r_registers.xmm1, xmm1; movss r_registers.xmm2, xmm2; movss r_registers.xmm3, xmm3; movss r_registers.xmm4, xmm4; movss r_registers.xmm5, xmm5; movss r_registers.xmm6, xmm6; movss r_registers.xmm7, xmm7; movsd r_registers.dxmm0, xmm0; movsd r_registers.dxmm1, xmm1; movsd r_registers.dxmm2, xmm2; movsd r_registers.dxmm3, xmm3; movsd r_registers.dxmm4, xmm4; movsd r_registers.dxmm5, xmm5; movsd r_registers.dxmm6, xmm6; movsd r_registers.dxmm7, xmm7; mov r_registers.eax, eax; mov r_registers.ebx, ebx; mov r_registers.ecx, ecx; mov r_registers.edx, edx; mov r_registers.esi, esi; mov r_registers.edi, edi; mov r_registers.ebp, ebp; mov eax, [esp + 0x11c]; // Reserved former esp mov r_registers.esp, eax; mov eax, [eax]; mov r_registers.ReturnAddress, eax; mov eax, [esp + 0x14]; // [esp + 0x14] contains the exception address mov[ExceptionComparator], eax; // move into the exception comparator, aka the address to be compared with the exception address mov eax, [esp + 0x08]; // [esp + 0x0C] contains the exception code mov[ExceptionCode], eax; // move into the ExceptionCode global. mov eax, [esp + 20]; // when access exceptions are enabled, move the accessed memoryh ere mov[AccessException], eax; } Decision = (PVOID)CallChain(); // Initiate the CallChain function if (!Decision) // if the decision is null, then jump back to the real dispatcher { __asm { mov eax, r_registers.eax; mov ecx, [esp + 04]; mov ebx, [esp]; jmp KiUserRealDispatcher; } } if (r_registers.SSESet == TRUE) HandleSSE(); r_registers.SSESet = FALSE; __asm { mov eax, r_registers.eax; mov ebx, r_registers.ebx; mov ecx, r_registers.ecx; mov edx, r_registers.edx; mov esi, r_registers.esi; mov edi, r_registers.edi; mov esp, r_registers.esp; // [esp + 0x11c] contains stack initation information such as the return address, arguments, etc... jmp Decision; // jump to the catch block } } static void SetKiUser() { KiUser = (PVOID)GetProcAddress(GetModuleHandleA("ntdll.dll"), "KiUserExceptionDispatcher"); // Hook, tampered exception dispatcher later KiUserRealDispatcher = (PVOID)GetProcAddress(GetModuleHandleA("ntdll.dll"), "KiUserExceptionDispatcher"); // If something fails, will jump back to the real dispatcher DWORD KiUserRealDispatcher2 = (DWORD)KiUserRealDispatcher + 8; DWORD KiUser2 = (DWORD)KiUser + 1; KiUser = (PVOID)KiUser2; KiUserRealDispatcher = (PVOID)KiUserRealDispatcher2; } static IMP_AT GetIAT(LPCSTR ModuleName) { HMODULE mod = GetModuleHandleA(ModuleName); PIMAGE_DOS_HEADER img_dos_headers = (PIMAGE_DOS_HEADER)mod; PIMAGE_NT_HEADERS img_nt_headers = (PIMAGE_NT_HEADERS)((BYTE*)img_dos_headers + img_dos_headers->e_lfanew); PIMAGE_IMPORT_DESCRIPTOR img_import_desc = (PIMAGE_IMPORT_DESCRIPTOR)((BYTE*)img_dos_headers + img_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); DWORD IATSize = (img_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size * 4); IMP_AT Retn; Retn.Size = IATSize; Retn.Address = (PVOID)((DWORD)mod + img_import_desc->FirstThunk - 0x1DC); return Retn; } static void SetImportAddressTable(const char* ModuleName) { DWORD OldProtect; MEMORY_BASIC_INFORMATION inf; IMP_AT CopyModule = GetIAT(0); IMP_AT SelfModule = GetIAT(ModuleName); printf("_iat: %p\n", CopyModule.Address); printf("iat: %p\n", SelfModule.Address); VirtualProtect(SelfModule.Address, 1, PAGE_EXECUTE_READWRITE, &OldProtect); printf("Error1: %d\n", GetLastError()); VirtualQuery(SelfModule.Address, &inf, sizeof(inf)); memcpy(SelfModule.Address, CopyModule.Address, inf.RegionSize); VirtualProtect(SelfModule.Address, 1, OldProtect, &OldProtect); } int WaitOptModule(const char* OptModuleName) { if (!UseModule) return -1; volatile PVOID ModPtr = NULL; while (!ModPtr) ModPtr = (PVOID)GetModuleHandleA(OptModuleName); SetImportAddressTable(OptModuleName); return 0; } void SetModule(BOOLEAN use) { UseModule = use; } int AssignThread(HANDLE Thread) { for (size_t iterator = 0; iterator < sizeof(Threads); iterator++) { if (Threads[iterator] == NULL) { Threads[iterator] = Thread; return iterator; } } return -1; } void RemoveThread(HANDLE Thread) { for (size_t iterator = 0; iterator < sizeof(Threads); iterator++) { if (Threads[iterator] == Thread) { CloseHandle(Threads[iterator]); Threads[iterator] = NULL; return; } } } void AttachRVDbg() { InitializeConditionVariable(&Runnable); InitializeCriticalSection(&RunLock); SetKiUser(); HookFunction(KiUser, (PVOID)KiUserExceptionDispatcher, "ntdll.dll:KiUserExceptionDispatcher"); } void DetachRVDbg() { UnhookFunction(KiUser, (PVOID)KiUserExceptionDispatcher, "ntdll.dll:KiUserExceptionDispatcher"); } void ContinueDebugger() { WakeConditionVariable(&Runnable); } BOOLEAN IsAEHPresent() { return CurrentPool.IsAEHPresent; } void SetRegister(DWORD Register, DWORD Value) { switch (Register) { case GPRegisters::EAX: r_registers.eax = Value; return; case GPRegisters::EBX: r_registers.ebx = Value; return; case GPRegisters::ECX: r_registers.ecx = Value; return; case GPRegisters::EDX: r_registers.edx = Value; return; case GPRegisters::ESI: r_registers.esi = Value; return; case GPRegisters::EDI: r_registers.edi = Value; return; case GPRegisters::EBP: r_registers.ebp = Value; return; case GPRegisters::ESP: r_registers.esp = Value; return; case GPRegisters::EIP: r_registers.eip = (PVOID)Value; } } void SetRegisterFP(DWORD Register, BOOLEAN Precision, double Value) { r_registers.SSESet = TRUE; switch (Register) { case SSERegisters::xmm0: if (Precision) { r_registers.bxmm0 = 1; r_registers.dxmm0 = Value; return; } r_registers.bxmm0 = 2; r_registers.xmm0 = (float)Value; return; case SSERegisters::xmm1: if (Precision) { r_registers.bxmm1 = 1; r_registers.dxmm1 = Value; return; } r_registers.bxmm1 = 2; r_registers.xmm1 = (float)Value; return; case SSERegisters::xmm2: if (Precision) { r_registers.bxmm2 = 1; r_registers.dxmm2 = Value; return; } r_registers.bxmm2 = 2; r_registers.xmm2 = (float)Value; return; case SSERegisters::xmm3: if (Precision) { r_registers.bxmm3 = 1; r_registers.dxmm3 = Value; return; } r_registers.bxmm3 = 2; r_registers.xmm3 = (float)Value; return; case SSERegisters::xmm4: if (Precision) { r_registers.bxmm4 = 1; r_registers.dxmm4 = Value; return; } r_registers.bxmm4 = 2; r_registers.xmm4 = (float)Value; return; case SSERegisters::xmm5: if (Precision) { r_registers.bxmm5 = 1; r_registers.dxmm5 = Value; return; } r_registers.bxmm5 = 2; r_registers.xmm5 = (float)Value; return; case SSERegisters::xmm6: if (Precision) { r_registers.bxmm6 = 1; r_registers.dxmm6 = Value; return; } r_registers.bxmm6 = 2; r_registers.xmm6 = (float)Value; return; case SSERegisters::xmm7: if (Precision) { r_registers.bxmm7 = 1; r_registers.dxmm7 = Value; return; } r_registers.bxmm7 = 2; r_registers.xmm7 = (float)Value; return; } } void SetExceptionMode(BOOLEAN lExceptionMode) { ExceptionMode = lExceptionMode; } BOOLEAN GetExceptionMode() { return ExceptionMode; } DWORD GetExceptionAddress() { return CurrentPool.ExceptionAddress; } VirtualRegisters GetRegisters() { return r_registers; } PoolSect GetPool() { return CurrentPool; } PoolSect* GetSector() { return Sector; } int GetSectorSize() { return sizeof(Sector) / sizeof(PoolSect); } <commit_msg>Update rvdbg.cpp<commit_after>#include "stdafx.h" #include "rvdbg.h" BOOLEAN tDSend; CRITICAL_SECTION repr; CONDITION_VARIABLE reprcondition; static void Dbg::HandleSSE() { if (r_registers.bxmm0 == 1) __asm movsd xmm0, r_registers.dxmm0; else if (r_registers.bxmm0 == 2) __asm movss xmm0, r_registers.xmm0; if (r_registers.bxmm1) __asm movsd xmm1, r_registers.dxmm1; else if (r_registers.bxmm1 == 2) __asm movss xmm1, r_registers.xmm1; if (r_registers.bxmm2) __asm movsd xmm2, r_registers.dxmm2; else if (r_registers.bxmm2 == 2) __asm movss xmm2, r_registers.xmm2; if (r_registers.bxmm3) __asm movsd xmm3, r_registers.dxmm3; else if (r_registers.bxmm3 == 2) __asm movss xmm3, r_registers.xmm3; if (r_registers.bxmm4) __asm movsd xmm4, r_registers.dxmm4; else if (r_registers.bxmm4 == 2) __asm movss xmm4, r_registers.xmm4; if (r_registers.bxmm5) __asm movsd xmm5, r_registers.dxmm5; else if (r_registers.bxmm5 == 2) __asm movss xmm5, r_registers.xmm5; if (r_registers.bxmm6) __asm movsd xmm6, r_registers.dxmm6; else if (r_registers.bxmm6 == 2) __asm movss xmm6, r_registers.xmm6; if (r_registers.bxmm7) __asm movsd xmm7, r_registers.dxmm7; else if (r_registers.bxmm7 == 2) __asm movss xmm7, r_registers.xmm7; r_registers.bxmm0 = 0; r_registers.bxmm1 = 0; r_registers.bxmm2 = 0; r_registers.bxmm3 = 0; r_registers.bxmm4 = 0; r_registers.bxmm5 = 0; r_registers.bxmm6 = 0; r_registers.bxmm7 = 0; } static PVOID Dbg::CallChain() { size_t ExceptionElement = SearchSector(Sector, 128, ExceptionComparator); if (ExceptionElement > 128) { if (ExceptionMode == 2) { SuspendThreads(GetCurrentProcessId(), GetCurrentThreadId()); DWORD swap_ad = Dispatcher::SwapAccess(AccessException, AccessException); if (!swap_ad) { ChunkExecutable = FALSE; return NULL; } Swaps.push_back((PVOID)swap_ad); return (PVOID)swap_ad; } return NULL; } SuspendThreads(GetCurrentProcessId(), GetCurrentThreadId()); Debugger = TRUE; tDSend = TRUE; WakeConditionVariable(&reprcondition); for (size_t iterator = 0; iterator < sizeof(Threads); iterator++) { if (Threads[iterator] != NULL) ResumeThread(Threads[iterator]); } Sector[ExceptionElement].ExceptionCode = ExceptionCode; PVOID ReturnException = Dispatcher::HandleException(Sector[ExceptionElement], Sector[ExceptionElement].ModuleName); r_registers.eip = ReturnException; Sector[ExceptionElement].Thread = GetCurrentThread(); Sector[ExceptionElement].IsAEHPresent = TRUE; Sector[ExceptionElement].ReturnAddress = r_registers.ReturnAddress; CurrentPool = Sector[ExceptionElement]; EnterCriticalSection(&RunLock); SleepConditionVariableCS(&Runnable, &RunLock, INFINITE); LeaveCriticalSection(&RunLock); ResumeThreads(GetCurrentProcessId(), GetCurrentThreadId()); Dispatcher::UnlockSector(Sector, ExceptionElement); return r_registers.eip; } static __declspec(naked) VOID NTAPI KiUserExceptionDispatcher(PEXCEPTION_RECORD ExceptionRecord, PCONTEXT Context) { __asm { movss r_registers.xmm0, xmm0; movss r_registers.xmm1, xmm1; movss r_registers.xmm2, xmm2; movss r_registers.xmm3, xmm3; movss r_registers.xmm4, xmm4; movss r_registers.xmm5, xmm5; movss r_registers.xmm6, xmm6; movss r_registers.xmm7, xmm7; movsd r_registers.dxmm0, xmm0; movsd r_registers.dxmm1, xmm1; movsd r_registers.dxmm2, xmm2; movsd r_registers.dxmm3, xmm3; movsd r_registers.dxmm4, xmm4; movsd r_registers.dxmm5, xmm5; movsd r_registers.dxmm6, xmm6; movsd r_registers.dxmm7, xmm7; mov r_registers.eax, eax; mov r_registers.ebx, ebx; mov r_registers.ecx, ecx; mov r_registers.edx, edx; mov r_registers.esi, esi; mov r_registers.edi, edi; mov r_registers.ebp, ebp; mov eax, [esp + 0x11c]; // Reserved former esp mov r_registers.esp, eax; mov eax, [eax]; mov r_registers.ReturnAddress, eax; mov eax, [esp + 0x14]; // [esp + 0x14] contains the exception address mov[ExceptionComparator], eax; // move into the exception comparator, aka the address to be compared with the exception address mov eax, [esp + 0x08]; // [esp + 0x0C] contains the exception code mov[ExceptionCode], eax; // move into the ExceptionCode global. mov eax, [esp + 20]; // when access exceptions are enabled, move the accessed memoryh ere mov[AccessException], eax; } Decision = (PVOID)Dbg::CallChain(); // Initiate the CallChain function if (!Decision) // if the decision is null, then jump back to the real dispatcher { __asm { mov eax, r_registers.eax; mov ecx, [esp + 04]; mov ebx, [esp]; jmp KiUserRealDispatcher; } } if (r_registers.SSESet == TRUE) Dbg::HandleSSE(); r_registers.SSESet = FALSE; __asm { mov eax, r_registers.eax; mov ebx, r_registers.ebx; mov ecx, r_registers.ecx; mov edx, r_registers.edx; mov esi, r_registers.esi; mov edi, r_registers.edi; mov esp, r_registers.esp; // [esp + 0x11c] contains stack initation information such as the return address, arguments, etc... jmp Decision; // jump to the catch block } } static void Dbg::SetKiUser() { KiUser = (PVOID)GetProcAddress(GetModuleHandleA("ntdll.dll"), "KiUserExceptionDispatcher"); // Hook, tampered exception dispatcher later KiUserRealDispatcher = (PVOID)GetProcAddress(GetModuleHandleA("ntdll.dll"), "KiUserExceptionDispatcher"); // If something fails, will jump back to the real dispatcher DWORD KiUserRealDispatcher2 = (DWORD)KiUserRealDispatcher + 8; DWORD KiUser2 = (DWORD)KiUser + 1; KiUser = (PVOID)KiUser2; KiUserRealDispatcher = (PVOID)KiUserRealDispatcher2; } static Dbg::IMP_AT Dbg::GetIAT(LPCSTR ModuleName) { HMODULE mod = GetModuleHandleA(ModuleName); PIMAGE_DOS_HEADER img_dos_headers = (PIMAGE_DOS_HEADER)mod; PIMAGE_NT_HEADERS img_nt_headers = (PIMAGE_NT_HEADERS)((BYTE*)img_dos_headers + img_dos_headers->e_lfanew); PIMAGE_IMPORT_DESCRIPTOR img_import_desc = (PIMAGE_IMPORT_DESCRIPTOR)((BYTE*)img_dos_headers + img_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); DWORD IATSize = (img_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size * 4); IMP_AT Retn; Retn.Size = IATSize; Retn.Address = (PVOID)((DWORD)mod + img_import_desc->FirstThunk - 0x1DC); return Retn; } int Dbg::WaitOptModule(const char* OriginalModuleName, const char* OptModuleName) { if (!UseModule) return -1; volatile PVOID ModPtr = NULL; while (!ModPtr) ModPtr = (PVOID)GetModuleHandleA(OptModuleName); IATResolver::ResolveIAT(OriginalModuleName, OptModuleName); return 0; } void Dbg::SetModule(BOOLEAN use) { UseModule = use; } int Dbg::AssignThread(HANDLE Thread) { for (size_t iterator = 0; iterator < sizeof(Threads); iterator++) { if (Threads[iterator] == NULL) { Threads[iterator] = Thread; return iterator; } } return -1; } void Dbg::RemoveThread(HANDLE Thread) { for (size_t iterator = 0; iterator < sizeof(Threads); iterator++) { if (Threads[iterator] == Thread) { CloseHandle(Threads[iterator]); Threads[iterator] = NULL; return; } } } void Dbg::AttachRVDbg() { InitializeConditionVariable(&Runnable); InitializeCriticalSection(&RunLock); Dbg::SetKiUser(); HookFunction(KiUser, (PVOID)KiUserExceptionDispatcher, "ntdll.dll:KiUserExceptionDispatcher"); } void Dbg::DetachRVDbg() { UnhookFunction(KiUser, (PVOID)KiUserExceptionDispatcher, "ntdll.dll:KiUserExceptionDispatcher"); } void Dbg::ContinueDebugger() { WakeConditionVariable(&Runnable); } BOOLEAN Dbg::IsAEHPresent() { return CurrentPool.IsAEHPresent; } void Dbg::SetRegister(DWORD Register, DWORD Value) { switch (Register) { case Dbg::GPRegisters::EAX: r_registers.eax = Value; return; case Dbg::GPRegisters::EBX: r_registers.ebx = Value; return; case Dbg::GPRegisters::ECX: r_registers.ecx = Value; return; case Dbg::GPRegisters::EDX: r_registers.edx = Value; return; case Dbg::GPRegisters::ESI: r_registers.esi = Value; return; case Dbg::GPRegisters::EDI: r_registers.edi = Value; return; case Dbg::GPRegisters::EBP: r_registers.ebp = Value; return; case Dbg::GPRegisters::ESP: r_registers.esp = Value; return; case Dbg::GPRegisters::EIP: r_registers.eip = (PVOID)Value; } } void Dbg::SetRegisterFP(DWORD Register, BOOLEAN Precision, double Value) { r_registers.SSESet = TRUE; switch (Register) { case Dbg::SSERegisters::xmm0: if (Precision) { r_registers.bxmm0 = 1; r_registers.dxmm0 = Value; return; } r_registers.bxmm0 = 2; r_registers.xmm0 = (float)Value; return; case Dbg::SSERegisters::xmm1: if (Precision) { r_registers.bxmm1 = 1; r_registers.dxmm1 = Value; return; } r_registers.bxmm1 = 2; r_registers.xmm1 = (float)Value; return; case Dbg::SSERegisters::xmm2: if (Precision) { r_registers.bxmm2 = 1; r_registers.dxmm2 = Value; return; } r_registers.bxmm2 = 2; r_registers.xmm2 = (float)Value; return; case Dbg::SSERegisters::xmm3: if (Precision) { r_registers.bxmm3 = 1; r_registers.dxmm3 = Value; return; } r_registers.bxmm3 = 2; r_registers.xmm3 = (float)Value; return; case Dbg::SSERegisters::xmm4: if (Precision) { r_registers.bxmm4 = 1; r_registers.dxmm4 = Value; return; } r_registers.bxmm4 = 2; r_registers.xmm4 = (float)Value; return; case Dbg::SSERegisters::xmm5: if (Precision) { r_registers.bxmm5 = 1; r_registers.dxmm5 = Value; return; } r_registers.bxmm5 = 2; r_registers.xmm5 = (float)Value; return; case Dbg::SSERegisters::xmm6: if (Precision) { r_registers.bxmm6 = 1; r_registers.dxmm6 = Value; return; } r_registers.bxmm6 = 2; r_registers.xmm6 = (float)Value; return; case Dbg::SSERegisters::xmm7: if (Precision) { r_registers.bxmm7 = 1; r_registers.dxmm7 = Value; return; } r_registers.bxmm7 = 2; r_registers.xmm7 = (float)Value; return; } } void Dbg::SetExceptionMode(BOOLEAN lExceptionMode) { ExceptionMode = lExceptionMode; } BOOLEAN Dbg::GetExceptionMode() { return ExceptionMode; } DWORD Dbg::GetExceptionAddress() { return CurrentPool.ExceptionAddress; } Dbg::VirtualRegisters Dbg::GetRegisters() { return r_registers; } Dispatcher::PoolSect Dbg::GetPool() { return CurrentPool; } Dispatcher::PoolSect* Dbg::GetSector() { return Sector; } int Dbg::GetSectorSize() { return sizeof(Sector) / sizeof(Dispatcher::PoolSect); } <|endoftext|>
<commit_before>#ifdef _WIN32 #include "win_fsnotifier.h" using namespace std; // // WatchPoint // WatchPoint::WatchPoint(Server* server, const u16string& path, HANDLE directoryHandle) { this->server = server; this->path = path; this->buffer = (FILE_NOTIFY_INFORMATION*) malloc(EVENT_BUFFER_SIZE); ZeroMemory(&this->overlapped, sizeof(OVERLAPPED)); this->overlapped.hEvent = this; this->directoryHandle = directoryHandle; this->status = WATCH_UNINITIALIZED; } WatchPoint::~WatchPoint() { free(buffer); } void WatchPoint::close() { BOOL ret = CancelIo(directoryHandle); if (!ret) { log_severe(server->getThreadEnv(), L"Couldn't cancel I/O %p for '%ls': %d", directoryHandle, path.c_str(), GetLastError()); } ret = CloseHandle(directoryHandle); if (!ret) { log_severe(server->getThreadEnv(), L"Couldn't close handle %p for '%ls': %d", directoryHandle, path.c_str(), GetLastError()); } } static void CALLBACK startWatchCallback(_In_ ULONG_PTR arg) { WatchPoint* watchPoint = (WatchPoint*) arg; watchPoint->listen(); } int WatchPoint::awaitListeningStarted(HANDLE threadHandle) { unique_lock<mutex> lock(listenerMutex); QueueUserAPC(startWatchCallback, threadHandle, (ULONG_PTR) this); listenerStarted.wait(lock); return status; } void WatchPoint::listen() { BOOL success = ReadDirectoryChangesW( directoryHandle, // handle to directory buffer, // read results buffer EVENT_BUFFER_SIZE, // length of buffer TRUE, // include children EVENT_MASK, // filter conditions NULL, // bytes returned &overlapped, // overlapped buffer &handleEventCallback // completion routine ); unique_lock<mutex> lock(listenerMutex); if (success) { status = WATCH_LISTENING; } else { status = WATCH_FAILED_TO_LISTEN; log_warning(server->getThreadEnv(), L"Couldn't start watching %p for '%ls', error = %d", directoryHandle, path.c_str(), GetLastError()); // TODO Error handling } listenerStarted.notify_all(); } static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransferred, LPOVERLAPPED overlapped) { WatchPoint* watchPoint = (WatchPoint*) overlapped->hEvent; watchPoint->handleEvent(errorCode, bytesTransferred); } void WatchPoint::handleEvent(DWORD errorCode, DWORD bytesTransferred) { status = WATCH_NOT_LISTENING; if (errorCode == ERROR_OPERATION_ABORTED) { log_info(server->getThreadEnv(), L"Finished watching '%ls'", path.c_str()); status = WATCH_FINISHED; server->reportFinished(this); return; } if (bytesTransferred == 0) { // don't send dirty too much, everything is changed anyway // TODO Understand what this does // if (WaitForSingleObject(stopEventHandle, 500) == WAIT_OBJECT_0) // break; // Got a buffer overflow => current changes lost => send INVALIDATE on root server->reportEvent(FILE_EVENT_INVALIDATE, path); } else { FILE_NOTIFY_INFORMATION* current = buffer; for (;;) { handlePathChanged(current); if (current->NextEntryOffset == 0) { break; } current = (FILE_NOTIFY_INFORMATION*) (((BYTE*) current) + current->NextEntryOffset); } } listen(); if (status != WATCH_LISTENING) { server->reportFinished(this); } } void WatchPoint::handlePathChanged(FILE_NOTIFY_INFORMATION* info) { wstring changedPathW = wstring(info->FileName, 0, info->FileNameLength / sizeof(wchar_t)); u16string changedPath(changedPathW.begin(), changedPathW.end()); if (!changedPath.empty()) { changedPath.insert(0, 1, u'\\'); changedPath.insert(0, path); } // TODO Remove long prefix for path once? if (changedPath.length() >= 4 && changedPath.substr(0, 4) == u"\\\\?\\") { if (changedPath.length() >= 8 && changedPath.substr(0, 8) == u"\\\\?\\UNC\\") { changedPath.erase(0, 8).insert(0, u"\\\\"); } else { changedPath.erase(0, 4); } } log_fine(server->getThreadEnv(), L"Change detected: 0x%x '%ls'", info->Action, changedPathW.c_str()); jint type; if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) { type = FILE_EVENT_CREATED; } else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) { type = FILE_EVENT_REMOVED; } else if (info->Action == FILE_ACTION_MODIFIED) { type = FILE_EVENT_MODIFIED; } else { log_warning(server->getThreadEnv(), L"Unknown event 0x%x for %ls", info->Action, changedPathW.c_str()); type = FILE_EVENT_UNKNOWN; } server->reportEvent(type, changedPath); } // // Server // Server::Server(JNIEnv* env, jobject watcherCallback) : AbstractServer(env, watcherCallback) { startThread(); // TODO Error handling SetThreadPriority(this->watcherThread.native_handle(), THREAD_PRIORITY_ABOVE_NORMAL); } Server::~Server() { } void Server::runLoop(JNIEnv* env, function<void()> notifyStarted) { log_info(env, L"Server thread %d with handle %p running", GetCurrentThreadId(), watcherThread.native_handle()); notifyStarted(); while (!terminate || watchPoints.size() > 0) { SleepEx(INFINITE, true); } log_info(env, L"Server thread %d finishing", GetCurrentThreadId()); } void Server::startWatching(JNIEnv* env, const u16string& path) { wstring pathW(path.begin(), path.end()); HANDLE directoryHandle = CreateFileW( pathW.c_str(), // pointer to the file name FILE_LIST_DIRECTORY, // access (read/write) mode CREATE_SHARE, // share mode NULL, // security descriptor OPEN_EXISTING, // how to create CREATE_FLAGS, // file attributes NULL // file with attributes to copy ); if (directoryHandle == INVALID_HANDLE_VALUE) { log_severe(env, L"Couldn't get file handle for '%ls': %d", pathW.c_str(), GetLastError()); // TODO Error handling return; } WatchPoint* watchPoint = new WatchPoint(this, path, directoryHandle); HANDLE threadHandle = watcherThread.native_handle(); int ret = watchPoint->awaitListeningStarted(threadHandle); switch (ret) { case WATCH_LISTENING: watchPoints.push_back(watchPoint); break; default: log_severe(env, L"Couldn't start listening to '%ls': %d", pathW.c_str(), ret); delete watchPoint; // TODO Error handling break; } } void Server::reportFinished(WatchPoint* watchPoint) { watchPoints.remove(watchPoint); delete watchPoint; } void Server::reportEvent(jint type, const u16string& changedPath) { JNIEnv* env = getThreadEnv(); reportChange(env, type, changedPath); } static void CALLBACK requestTerminationCallback(_In_ ULONG_PTR arg) { Server* server = (Server*) arg; server->requestTermination(); } void Server::requestTermination() { terminate = true; // Make copy so terminated entries can be removed list<WatchPoint*> copyWatchPoints(watchPoints); for (auto& watchPoint : copyWatchPoints) { watchPoint->close(); } } void Server::close(JNIEnv* env) { HANDLE threadHandle = watcherThread.native_handle(); log_fine(env, L"Requesting termination of server thread %p", threadHandle); int ret = QueueUserAPC(requestTerminationCallback, threadHandle, (ULONG_PTR) this); if (ret == 0) { log_severe(env, L"Couldn't send termination request to thread %p: %d", threadHandle, GetLastError()); } else { watcherThread.join(); } } bool isAbsoluteLocalPath(const u16string& path) { if (path.length() < 3) { return false; } return ((u'a' <= path[0] && path[0] <= u'z') || (u'A' <= path[0] && path[0] <= u'Z')) && path[1] == u':' && path[2] == u'\\'; } bool isAbsoluteUncPath(const u16string& path) { if (path.length() < 3) { return false; } return path[0] == u'\\' && path[1] == u'\\'; } void convertToLongPathIfNeeded(u16string& path) { // Technically, this should be MAX_PATH (i.e. 260), except some Win32 API related // to working with directory paths are actually limited to 240. It is just // safer/simpler to cover both cases in one code path. if (path.length() <= 240) { return; } if (isAbsoluteLocalPath(path)) { // Format: C:\... -> \\?\C:\... path.insert(0, u"\\\\?\\"); } else if (isAbsoluteUncPath(path)) { // In this case, we need to skip the first 2 characters: // Format: \\server\share\... -> \\?\UNC\server\share\... path.erase(0, 2); path.insert(0, u"\\\\?\\UNC\\"); } else { // It is some sort of unknown format, don't mess with it } } // // JNI calls // JNIEXPORT jobject JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatching(JNIEnv* env, jclass target, jobjectArray paths, jobject javaCallback, jobject result) { Server* server = new Server(env, javaCallback); int watchPointCount = env->GetArrayLength(paths); for (int i = 0; i < watchPointCount; i++) { jstring javaPath = (jstring) env->GetObjectArrayElement(paths, i); jsize javaPathLength = env->GetStringLength(javaPath); const jchar* javaPathChars = env->GetStringCritical(javaPath, nullptr); if (javaPathChars == NULL) { throw FileWatcherException("Could not get Java string character"); } u16string pathStr((char16_t*) javaPathChars, javaPathLength); env->ReleaseStringCritical(javaPath, javaPathChars); convertToLongPathIfNeeded(pathStr); server->startWatching(env, pathStr); } jclass clsWatch = env->FindClass("net/rubygrapefruit/platform/internal/jni/WindowsFileEventFunctions$WatcherImpl"); jmethodID constructor = env->GetMethodID(clsWatch, "<init>", "(Ljava/lang/Object;)V"); return env->NewObject(clsWatch, constructor, env->NewDirectByteBuffer(server, sizeof(server))); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_stopWatching(JNIEnv* env, jclass target, jobject detailsObj, jobject result) { Server* server = (Server*) env->GetDirectBufferAddress(detailsObj); server->close(env); delete server; } #endif <commit_msg>Add comment<commit_after>#ifdef _WIN32 #include "win_fsnotifier.h" using namespace std; // // WatchPoint // WatchPoint::WatchPoint(Server* server, const u16string& path, HANDLE directoryHandle) { this->server = server; this->path = path; this->buffer = (FILE_NOTIFY_INFORMATION*) malloc(EVENT_BUFFER_SIZE); ZeroMemory(&this->overlapped, sizeof(OVERLAPPED)); this->overlapped.hEvent = this; this->directoryHandle = directoryHandle; this->status = WATCH_UNINITIALIZED; } WatchPoint::~WatchPoint() { free(buffer); } void WatchPoint::close() { BOOL ret = CancelIo(directoryHandle); if (!ret) { log_severe(server->getThreadEnv(), L"Couldn't cancel I/O %p for '%ls': %d", directoryHandle, path.c_str(), GetLastError()); } ret = CloseHandle(directoryHandle); if (!ret) { log_severe(server->getThreadEnv(), L"Couldn't close handle %p for '%ls': %d", directoryHandle, path.c_str(), GetLastError()); } } static void CALLBACK startWatchCallback(_In_ ULONG_PTR arg) { WatchPoint* watchPoint = (WatchPoint*) arg; watchPoint->listen(); } int WatchPoint::awaitListeningStarted(HANDLE threadHandle) { unique_lock<mutex> lock(listenerMutex); QueueUserAPC(startWatchCallback, threadHandle, (ULONG_PTR) this); listenerStarted.wait(lock); return status; } void WatchPoint::listen() { BOOL success = ReadDirectoryChangesW( directoryHandle, // handle to directory buffer, // read results buffer EVENT_BUFFER_SIZE, // length of buffer TRUE, // include children EVENT_MASK, // filter conditions NULL, // bytes returned &overlapped, // overlapped buffer &handleEventCallback // completion routine ); unique_lock<mutex> lock(listenerMutex); if (success) { status = WATCH_LISTENING; } else { status = WATCH_FAILED_TO_LISTEN; log_warning(server->getThreadEnv(), L"Couldn't start watching %p for '%ls', error = %d", directoryHandle, path.c_str(), GetLastError()); // TODO Error handling } listenerStarted.notify_all(); } static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransferred, LPOVERLAPPED overlapped) { WatchPoint* watchPoint = (WatchPoint*) overlapped->hEvent; watchPoint->handleEvent(errorCode, bytesTransferred); } void WatchPoint::handleEvent(DWORD errorCode, DWORD bytesTransferred) { status = WATCH_NOT_LISTENING; if (errorCode == ERROR_OPERATION_ABORTED) { log_info(server->getThreadEnv(), L"Finished watching '%ls'", path.c_str()); status = WATCH_FINISHED; server->reportFinished(this); return; } if (bytesTransferred == 0) { // don't send dirty too much, everything is changed anyway // TODO Understand what this does // if (WaitForSingleObject(stopEventHandle, 500) == WAIT_OBJECT_0) // break; // Got a buffer overflow => current changes lost => send INVALIDATE on root server->reportEvent(FILE_EVENT_INVALIDATE, path); } else { FILE_NOTIFY_INFORMATION* current = buffer; for (;;) { handlePathChanged(current); if (current->NextEntryOffset == 0) { break; } current = (FILE_NOTIFY_INFORMATION*) (((BYTE*) current) + current->NextEntryOffset); } } listen(); if (status != WATCH_LISTENING) { server->reportFinished(this); } } void WatchPoint::handlePathChanged(FILE_NOTIFY_INFORMATION* info) { wstring changedPathW = wstring(info->FileName, 0, info->FileNameLength / sizeof(wchar_t)); u16string changedPath(changedPathW.begin(), changedPathW.end()); // TODO Do we ever get an empty path? if (!changedPath.empty()) { changedPath.insert(0, 1, u'\\'); changedPath.insert(0, path); } // TODO Remove long prefix for path once? if (changedPath.length() >= 4 && changedPath.substr(0, 4) == u"\\\\?\\") { if (changedPath.length() >= 8 && changedPath.substr(0, 8) == u"\\\\?\\UNC\\") { changedPath.erase(0, 8).insert(0, u"\\\\"); } else { changedPath.erase(0, 4); } } log_fine(server->getThreadEnv(), L"Change detected: 0x%x '%ls'", info->Action, changedPathW.c_str()); jint type; if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) { type = FILE_EVENT_CREATED; } else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) { type = FILE_EVENT_REMOVED; } else if (info->Action == FILE_ACTION_MODIFIED) { type = FILE_EVENT_MODIFIED; } else { log_warning(server->getThreadEnv(), L"Unknown event 0x%x for %ls", info->Action, changedPathW.c_str()); type = FILE_EVENT_UNKNOWN; } server->reportEvent(type, changedPath); } // // Server // Server::Server(JNIEnv* env, jobject watcherCallback) : AbstractServer(env, watcherCallback) { startThread(); // TODO Error handling SetThreadPriority(this->watcherThread.native_handle(), THREAD_PRIORITY_ABOVE_NORMAL); } Server::~Server() { } void Server::runLoop(JNIEnv* env, function<void()> notifyStarted) { log_info(env, L"Server thread %d with handle %p running", GetCurrentThreadId(), watcherThread.native_handle()); notifyStarted(); while (!terminate || watchPoints.size() > 0) { SleepEx(INFINITE, true); } log_info(env, L"Server thread %d finishing", GetCurrentThreadId()); } void Server::startWatching(JNIEnv* env, const u16string& path) { wstring pathW(path.begin(), path.end()); HANDLE directoryHandle = CreateFileW( pathW.c_str(), // pointer to the file name FILE_LIST_DIRECTORY, // access (read/write) mode CREATE_SHARE, // share mode NULL, // security descriptor OPEN_EXISTING, // how to create CREATE_FLAGS, // file attributes NULL // file with attributes to copy ); if (directoryHandle == INVALID_HANDLE_VALUE) { log_severe(env, L"Couldn't get file handle for '%ls': %d", pathW.c_str(), GetLastError()); // TODO Error handling return; } WatchPoint* watchPoint = new WatchPoint(this, path, directoryHandle); HANDLE threadHandle = watcherThread.native_handle(); int ret = watchPoint->awaitListeningStarted(threadHandle); switch (ret) { case WATCH_LISTENING: watchPoints.push_back(watchPoint); break; default: log_severe(env, L"Couldn't start listening to '%ls': %d", pathW.c_str(), ret); delete watchPoint; // TODO Error handling break; } } void Server::reportFinished(WatchPoint* watchPoint) { watchPoints.remove(watchPoint); delete watchPoint; } void Server::reportEvent(jint type, const u16string& changedPath) { JNIEnv* env = getThreadEnv(); reportChange(env, type, changedPath); } static void CALLBACK requestTerminationCallback(_In_ ULONG_PTR arg) { Server* server = (Server*) arg; server->requestTermination(); } void Server::requestTermination() { terminate = true; // Make copy so terminated entries can be removed list<WatchPoint*> copyWatchPoints(watchPoints); for (auto& watchPoint : copyWatchPoints) { watchPoint->close(); } } void Server::close(JNIEnv* env) { HANDLE threadHandle = watcherThread.native_handle(); log_fine(env, L"Requesting termination of server thread %p", threadHandle); int ret = QueueUserAPC(requestTerminationCallback, threadHandle, (ULONG_PTR) this); if (ret == 0) { log_severe(env, L"Couldn't send termination request to thread %p: %d", threadHandle, GetLastError()); } else { watcherThread.join(); } } bool isAbsoluteLocalPath(const u16string& path) { if (path.length() < 3) { return false; } return ((u'a' <= path[0] && path[0] <= u'z') || (u'A' <= path[0] && path[0] <= u'Z')) && path[1] == u':' && path[2] == u'\\'; } bool isAbsoluteUncPath(const u16string& path) { if (path.length() < 3) { return false; } return path[0] == u'\\' && path[1] == u'\\'; } void convertToLongPathIfNeeded(u16string& path) { // Technically, this should be MAX_PATH (i.e. 260), except some Win32 API related // to working with directory paths are actually limited to 240. It is just // safer/simpler to cover both cases in one code path. if (path.length() <= 240) { return; } if (isAbsoluteLocalPath(path)) { // Format: C:\... -> \\?\C:\... path.insert(0, u"\\\\?\\"); } else if (isAbsoluteUncPath(path)) { // In this case, we need to skip the first 2 characters: // Format: \\server\share\... -> \\?\UNC\server\share\... path.erase(0, 2); path.insert(0, u"\\\\?\\UNC\\"); } else { // It is some sort of unknown format, don't mess with it } } // // JNI calls // JNIEXPORT jobject JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatching(JNIEnv* env, jclass target, jobjectArray paths, jobject javaCallback, jobject result) { Server* server = new Server(env, javaCallback); int watchPointCount = env->GetArrayLength(paths); for (int i = 0; i < watchPointCount; i++) { jstring javaPath = (jstring) env->GetObjectArrayElement(paths, i); jsize javaPathLength = env->GetStringLength(javaPath); const jchar* javaPathChars = env->GetStringCritical(javaPath, nullptr); if (javaPathChars == NULL) { throw FileWatcherException("Could not get Java string character"); } u16string pathStr((char16_t*) javaPathChars, javaPathLength); env->ReleaseStringCritical(javaPath, javaPathChars); convertToLongPathIfNeeded(pathStr); server->startWatching(env, pathStr); } jclass clsWatch = env->FindClass("net/rubygrapefruit/platform/internal/jni/WindowsFileEventFunctions$WatcherImpl"); jmethodID constructor = env->GetMethodID(clsWatch, "<init>", "(Ljava/lang/Object;)V"); return env->NewObject(clsWatch, constructor, env->NewDirectByteBuffer(server, sizeof(server))); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_stopWatching(JNIEnv* env, jclass target, jobject detailsObj, jobject result) { Server* server = (Server*) env->GetDirectBufferAddress(detailsObj); server->close(env); delete server; } #endif <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "BackendPasses.h" #include "llvm/Analysis/InlineCost.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/InlinerPass.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Transforms/Scalar.h" //#include "clang/Basic/LangOptions.h" //#include "clang/Basic/TargetOptions.h" #include "clang/Frontend/CodeGenOptions.h" using namespace cling; using namespace clang; using namespace llvm; using namespace llvm::legacy; namespace { class KeepLocalFuncPass: public FunctionPass { static char ID; public: KeepLocalFuncPass() : FunctionPass(ID) {} bool runOnFunction(Function &F) override { if (F.isDeclaration()) return false; // no change. // F is a definition. if (!F.isDiscardableIfUnused()) return false; llvm::GlobalValue::LinkageTypes LT = F.getLinkage(); if (LT == llvm::GlobalValue::InternalLinkage || LT == llvm::GlobalValue::PrivateLinkage) { F.setLinkage(llvm::GlobalValue::ExternalLinkage); return true; // a change! } return false; } }; } char KeepLocalFuncPass::ID = 0; BackendPasses::~BackendPasses() { //delete m_PMBuilder->Inliner; } void BackendPasses::CreatePasses(llvm::Module& M) { // From BackEndUtil's clang::EmitAssemblyHelper::CreatePasses(). CodeGenOptions& CGOpts_ = const_cast<CodeGenOptions&>(m_CGOpts); // DON'T: we will not find our symbols... //CGOpts_.CXXCtorDtorAliases = 1; #if 0 // Default clang -O2 on Linux 64bit also has the following, but see // CIFactory.cpp. CGOpts_.DisableFPElim = 0; CGOpts_.DiscardValueNames = 1; CGOpts_.OmitLeafFramePointer = 1; CGOpts_.OptimizationLevel = 2; CGOpts_.RelaxAll = 0; CGOpts_.UnrollLoops = 1; CGOpts_.VectorizeLoop = 1; CGOpts_.VectorizeSLP = 1; #endif // Better inlining is pending https://bugs.llvm.org//show_bug.cgi?id=19668 // and its consequence https://sft.its.cern.ch/jira/browse/ROOT-7111 // shown e.g. by roottest/cling/stl/map/badstringMap CGOpts_.setInlining(CodeGenOptions::NormalInlining); unsigned OptLevel = m_CGOpts.OptimizationLevel; CodeGenOptions::InliningMethod Inlining = m_CGOpts.getInlining(); // Handle disabling of LLVM optimization, where we want to preserve the // internal module before any optimization. if (m_CGOpts.DisableLLVMOpts) { OptLevel = 0; // Always keep at least ForceInline - NoInlining is deadly for libc++. // Inlining = CGOpts.NoInlining; } llvm::PassManagerBuilder PMBuilder; PMBuilder.OptLevel = OptLevel; PMBuilder.SizeLevel = m_CGOpts.OptimizeSize; PMBuilder.BBVectorize = m_CGOpts.VectorizeBB; PMBuilder.SLPVectorize = m_CGOpts.VectorizeSLP; PMBuilder.LoopVectorize = m_CGOpts.VectorizeLoop; PMBuilder.DisableTailCalls = m_CGOpts.DisableTailCalls; PMBuilder.DisableUnitAtATime = !m_CGOpts.UnitAtATime; PMBuilder.DisableUnrollLoops = !m_CGOpts.UnrollLoops; PMBuilder.MergeFunctions = m_CGOpts.MergeFunctions; PMBuilder.RerollLoops = m_CGOpts.RerollLoops; PMBuilder.LibraryInfo = new TargetLibraryInfoImpl(m_TM.getTargetTriple()); switch (Inlining) { case CodeGenOptions::OnlyHintInlining: // fall-through: case CodeGenOptions::NoInlining: { assert(0 && "libc++ requires at least OnlyAlwaysInlining!"); break; } case CodeGenOptions::NormalInlining: { PMBuilder.Inliner = createFunctionInliningPass(OptLevel, m_CGOpts.OptimizeSize); break; } case CodeGenOptions::OnlyAlwaysInlining: // Respect always_inline. if (OptLevel == 0) // Do not insert lifetime intrinsics at -O0. PMBuilder.Inliner = createAlwaysInlinerPass(false); else PMBuilder.Inliner = createAlwaysInlinerPass(); break; } // Set up the per-module pass manager. m_MPM.reset(new legacy::PassManager()); m_MPM->add(createTargetTransformInfoWrapperPass(m_TM.getTargetIRAnalysis())); // Add target-specific passes that need to run as early as possible. PMBuilder.addExtension( PassManagerBuilder::EP_EarlyAsPossible, [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) { m_TM.addEarlyAsPossiblePasses(PM); }); PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) { PM.add(createAddDiscriminatorsPass()); }); //if (!CGOpts.RewriteMapFiles.empty()) // addSymbolRewriterPass(CGOpts, m_MPM); PMBuilder.populateModulePassManager(*m_MPM); m_FPM.reset(new legacy::FunctionPassManager(&M)); m_FPM->add(new KeepLocalFuncPass()); m_FPM->add(createTargetTransformInfoWrapperPass(m_TM.getTargetIRAnalysis())); if (m_CGOpts.VerifyModule) m_FPM->add(createVerifierPass()); PMBuilder.populateFunctionPassManager(*m_FPM); } void BackendPasses::runOnModule(Module& M) { if (!m_MPM) CreatePasses(M); // Set up the per-function pass manager. // Run the per-function passes on the module. m_FPM->doInitialization(); for (auto&& I: M.functions()) if (!I.isDeclaration()) m_FPM->run(I); m_FPM->doFinalization(); m_MPM->run(M); } <commit_msg>Also handle GlobalVariables. Fixes Recursion/RecursiveClingInstances.C.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "BackendPasses.h" #include "llvm/Analysis/InlineCost.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/InlinerPass.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Transforms/Scalar.h" //#include "clang/Basic/LangOptions.h" //#include "clang/Basic/TargetOptions.h" #include "clang/Frontend/CodeGenOptions.h" using namespace cling; using namespace clang; using namespace llvm; using namespace llvm::legacy; namespace { class KeepLocalGVPass: public ModulePass { static char ID; bool runOnGlobal(GlobalValue& GV) { if (GV.isDeclaration()) return false; // no change. // GV is a definition. llvm::GlobalValue::LinkageTypes LT = GV.getLinkage(); if (!GV.isDiscardableIfUnused(LT)) return false; if (LT == llvm::GlobalValue::InternalLinkage || LT == llvm::GlobalValue::PrivateLinkage) { GV.setLinkage(llvm::GlobalValue::ExternalLinkage); return true; // a change! } return false; } public: KeepLocalGVPass() : ModulePass(ID) {} bool runOnModule(Module &M) override { bool ret = false; for (auto &&F: M) ret |= runOnGlobal(F); for (auto &&G: M.globals()) ret |= runOnGlobal(G); return ret; } }; } char KeepLocalGVPass::ID = 0; BackendPasses::~BackendPasses() { //delete m_PMBuilder->Inliner; } void BackendPasses::CreatePasses(llvm::Module& M) { // From BackEndUtil's clang::EmitAssemblyHelper::CreatePasses(). CodeGenOptions& CGOpts_ = const_cast<CodeGenOptions&>(m_CGOpts); // DON'T: we will not find our symbols... //CGOpts_.CXXCtorDtorAliases = 1; #if 0 // Default clang -O2 on Linux 64bit also has the following, but see // CIFactory.cpp. CGOpts_.DisableFPElim = 0; CGOpts_.DiscardValueNames = 1; CGOpts_.OmitLeafFramePointer = 1; CGOpts_.OptimizationLevel = 2; CGOpts_.RelaxAll = 0; CGOpts_.UnrollLoops = 1; CGOpts_.VectorizeLoop = 1; CGOpts_.VectorizeSLP = 1; #endif // Better inlining is pending https://bugs.llvm.org//show_bug.cgi?id=19668 // and its consequence https://sft.its.cern.ch/jira/browse/ROOT-7111 // shown e.g. by roottest/cling/stl/map/badstringMap CGOpts_.setInlining(CodeGenOptions::NormalInlining); unsigned OptLevel = m_CGOpts.OptimizationLevel; CodeGenOptions::InliningMethod Inlining = m_CGOpts.getInlining(); // Handle disabling of LLVM optimization, where we want to preserve the // internal module before any optimization. if (m_CGOpts.DisableLLVMOpts) { OptLevel = 0; // Always keep at least ForceInline - NoInlining is deadly for libc++. // Inlining = CGOpts.NoInlining; } llvm::PassManagerBuilder PMBuilder; PMBuilder.OptLevel = OptLevel; PMBuilder.SizeLevel = m_CGOpts.OptimizeSize; PMBuilder.BBVectorize = m_CGOpts.VectorizeBB; PMBuilder.SLPVectorize = m_CGOpts.VectorizeSLP; PMBuilder.LoopVectorize = m_CGOpts.VectorizeLoop; PMBuilder.DisableTailCalls = m_CGOpts.DisableTailCalls; PMBuilder.DisableUnitAtATime = !m_CGOpts.UnitAtATime; PMBuilder.DisableUnrollLoops = !m_CGOpts.UnrollLoops; PMBuilder.MergeFunctions = m_CGOpts.MergeFunctions; PMBuilder.RerollLoops = m_CGOpts.RerollLoops; PMBuilder.LibraryInfo = new TargetLibraryInfoImpl(m_TM.getTargetTriple()); switch (Inlining) { case CodeGenOptions::OnlyHintInlining: // fall-through: case CodeGenOptions::NoInlining: { assert(0 && "libc++ requires at least OnlyAlwaysInlining!"); break; } case CodeGenOptions::NormalInlining: { PMBuilder.Inliner = createFunctionInliningPass(OptLevel, m_CGOpts.OptimizeSize); break; } case CodeGenOptions::OnlyAlwaysInlining: // Respect always_inline. if (OptLevel == 0) // Do not insert lifetime intrinsics at -O0. PMBuilder.Inliner = createAlwaysInlinerPass(false); else PMBuilder.Inliner = createAlwaysInlinerPass(); break; } // Set up the per-module pass manager. m_MPM.reset(new legacy::PassManager()); m_MPM->add(new KeepLocalGVPass()); m_MPM->add(createTargetTransformInfoWrapperPass(m_TM.getTargetIRAnalysis())); // Add target-specific passes that need to run as early as possible. PMBuilder.addExtension( PassManagerBuilder::EP_EarlyAsPossible, [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) { m_TM.addEarlyAsPossiblePasses(PM); }); PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) { PM.add(createAddDiscriminatorsPass()); }); //if (!CGOpts.RewriteMapFiles.empty()) // addSymbolRewriterPass(CGOpts, m_MPM); PMBuilder.populateModulePassManager(*m_MPM); m_FPM.reset(new legacy::FunctionPassManager(&M)); m_FPM->add(createTargetTransformInfoWrapperPass(m_TM.getTargetIRAnalysis())); if (m_CGOpts.VerifyModule) m_FPM->add(createVerifierPass()); PMBuilder.populateFunctionPassManager(*m_FPM); } void BackendPasses::runOnModule(Module& M) { if (!m_MPM) CreatePasses(M); // Set up the per-function pass manager. // Run the per-function passes on the module. m_FPM->doInitialization(); for (auto&& I: M.functions()) if (!I.isDeclaration()) m_FPM->run(I); m_FPM->doFinalization(); m_MPM->run(M); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "DeclCollector.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" using namespace clang; namespace cling { // pin the vtable here. DeclCollector::~DeclCollector() { } bool DeclCollector::HandleTopLevelDecl(DeclGroupRef DGR) { m_CurTransaction->appendUnique(DGR); return true; } void DeclCollector::HandleInterestingDecl(DeclGroupRef DGR) { assert("Not implemented yet!"); } // Does more than we want: // if there is class A {enum E {kEnum = 1};}; // we get two different tag decls one for A and one for E. This is not that // bad because esentially it has no effect on codegen but it differs from what // one'd expect. For now rely on the HandleTopLevelDecl to provide all the // declarations in the transaction. void DeclCollector::HandleTagDeclDefinition(TagDecl* TD) { // Intentional no-op. } void DeclCollector::HandleVTable(CXXRecordDecl* RD, bool DefinitionRequired) { assert(0 && "Not implemented yet!"); } void DeclCollector::CompleteTentativeDefinition(VarDecl* VD) { assert(0 && "Not implemented yet!"); } void DeclCollector::HandleTranslationUnit(ASTContext& Ctx) { } } // namespace cling <commit_msg>HandleVTable assert is far too intrusive to stay.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "DeclCollector.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" using namespace clang; namespace cling { // pin the vtable here. DeclCollector::~DeclCollector() { } bool DeclCollector::HandleTopLevelDecl(DeclGroupRef DGR) { m_CurTransaction->appendUnique(DGR); return true; } void DeclCollector::HandleInterestingDecl(DeclGroupRef DGR) { assert(0 && "Not implemented yet!"); } // Does more than we want: // if there is class A {enum E {kEnum = 1};}; // we get two different tag decls one for A and one for E. This is not that // bad because esentially it has no effect on codegen but it differs from what // one'd expect. For now rely on the HandleTopLevelDecl to provide all the // declarations in the transaction. void DeclCollector::HandleTagDeclDefinition(TagDecl* TD) { // Intentional no-op. } void DeclCollector::HandleVTable(CXXRecordDecl* RD, bool DefinitionRequired) { // Intentional no-op. It comes through Sema::DefineUsedVTables, which // comes either Sema::ActOnEndOfTranslationUnit or while instantiating a // template. In our case we will do it on transaction commit, without // keeping track of used vtables, because we have cases where we bypass the // clang/AST and directly ask the module so that we have to generate // everything without extra smartness. } void DeclCollector::CompleteTentativeDefinition(VarDecl* VD) { assert(0 && "Not implemented yet!"); } void DeclCollector::HandleTranslationUnit(ASTContext& Ctx) { } } // namespace cling <|endoftext|>
<commit_before>#ifndef SIMPLESPMV_H #define SIMPLESPMV_H #include <sstream> #include <Spark/Spmv.hpp> #include <Spark/Utils.hpp> namespace spark { namespace spmv { using EigenSparseMatrix = Eigen::SparseMatrix<double, Eigen::RowMajor, int32_t>; // pack values and colptr to reduce number of streams #pragma pack(1) struct indptr_value { double value; int indptr; indptr_value(double _value, int _indptr) : value(_value), indptr(_indptr) {} indptr_value() : value(0), indptr(0) {} } __attribute__((packed)); #pragma pack() struct Partition { int nBlocks, n, paddingCycles, totalCycles, vector_load_cycles, outSize; int reductionCycles, emptyCycles; int m_colptr_unpaddedLength; int m_indptr_values_unpaddedLength; std::vector<int> m_colptr; std::vector<indptr_value> m_indptr_values; std::string to_string() { std::stringstream s; s << "Vector load cycles " << vector_load_cycles << std::endl; s << "Padding cycles = " << paddingCycles << std::endl; s << "Total cycles = " << totalCycles << std::endl; s << "Nrows = " << n << std::endl; s << "Partitions = " << nBlocks << std::endl; s << "Reduction cycles = " << reductionCycles << std::endl; std::cout << "Empty cycles = " << emptyCycles << std::endl; return s.str(); } }; // A parameterised, generic architecture for SpMV. Supported parameters are: // - input width // - number of pipes // - cache size per pipe // - TODO data type class SimpleSpmvArchitecture : public SpmvArchitecture { // architecture specific properties protected: int cacheSize, inputWidth, numPipes; EigenSparseMatrix mat; std::vector<Partition> partitions; virtual int countComputeCycles(uint32_t* v, int size, int inputWidth); public: SimpleSpmvArchitecture() : cacheSize(getPartitionSize()), inputWidth(getInputWidth()), numPipes(getNumPipes()) {} SimpleSpmvArchitecture(int _cacheSize, int _inputWidth, int _numPipes) : cacheSize(_cacheSize), inputWidth(_inputWidth), numPipes(_numPipes) {} virtual ~SimpleSpmvArchitecture() {} virtual double getEstimatedClockCycles() { auto res = std::max_element(partitions.begin(), partitions.end(), [](const Partition& a, const Partition& b) { return a.totalCycles < b.totalCycles; }); return res->totalCycles; } virtual double getGFlopsCount() { return 2 * this->mat.nonZeros() / 1E9; } // NOTE: only call this after a call to preprocessMatrix virtual ImplementationParameters getImplementationParameters() { // XXX bram usage for altera in double precision only (512 deep, 40 bits wide, so need 2 BRAMs) //int brams = (double)cacheSize * (double)inputWidth / 512.0 * 2.0; // XXX these should be architecture params int maxRows = 200000; const int virtex6EntriesPerBram = 512; LogicResourceUsage interPartitionReductionKernel(2768,1505, maxRows / virtex6EntriesPerBram, 0); LogicResourceUsage paddingKernel{400, 500, 0, 0}; LogicResourceUsage spmvKernelPerInput{1466, 2060, cacheSize / virtex6EntriesPerBram, 10}; // includes cache LogicResourceUsage sm{800, 500, 0, 0}; LogicResourceUsage spmvPerPipe = interPartitionReductionKernel + paddingKernel + spmvKernelPerInput * inputWidth + sm; LogicResourceUsage memoryPerPipe{3922, 8393, 160, 0}; LogicResourceUsage memory{24000, 32000, 0, 0}; //LogicResourceUsage designOther{}; LogicResourceUsage designUsage = (spmvPerPipe + memoryPerPipe) * numPipes + memory; double memoryBandwidth =(double)inputWidth * numPipes * getFrequency() * 12.0 / 1E9; ImplementationParameters ip{designUsage, memoryBandwidth}; //ip.clockFrequency = getFrequency() / 1E6; // MHz return ip; } virtual std::string to_string() { std::stringstream s; s << get_name(); s << " " << cacheSize; s << " " << inputWidth; s << " " << numPipes; s << " " << getEstimatedClockCycles(); s << " " << getEstimatedGFlops(); return s.str(); } virtual void preprocess(const EigenSparseMatrix& mat) override; virtual Eigen::VectorXd dfespmv(Eigen::VectorXd x) override; virtual std::string get_name() override { return std::string("Simple"); } private: std::vector<EigenSparseMatrix> do_partition( const EigenSparseMatrix& mat, int numPipes); Partition do_blocking( const Eigen::SparseMatrix<double, Eigen::RowMajor, int32_t>& mat, int blockSize, int inputWidth); }; template<typename T> class SimpleSpmvArchitectureSpace : public SpmvArchitectureSpace { // NOTE any raw pointers returned through the API of this class // are assumed to be wrapped in smart pointers by the base class spark::utils::Range cacheSizeR{1024, 4096, 512}; spark::utils::Range inputWidthR{8, 100, 8}; spark::utils::Range numPipesR{1, 6, 1}; bool last = false; public: SimpleSpmvArchitectureSpace( spark::utils::Range numPipesRange, spark::utils::Range inputWidthRange, spark::utils::Range cacheSizeRange) { cacheSizeR = cacheSizeRange; inputWidthR = inputWidthRange; numPipesR = numPipesRange; } SimpleSpmvArchitectureSpace() { } protected: void restart() override { cacheSizeR.restart(); inputWidthR.restart(); numPipesR.restart(); last = false; } T* doNext(){ if (last) return nullptr; T* result = new T(cacheSizeR.crt, inputWidthR.crt, numPipesR.crt); ++cacheSizeR; if (cacheSizeR.at_start()) { ++inputWidthR; if (inputWidthR.at_start()) { ++numPipesR; if (numPipesR.at_start()) last = true; } } return result; } }; // FST based architecture, for now we assume it's the same though it probably isn't class FstSpmvArchitecture : public SimpleSpmvArchitecture { protected: virtual int countComputeCycles(uint32_t* v, int size, int inputWidth) override { int cycles = 0; for (int i = 0; i < size; i++) { int toread = v[i] - (i > 0 ? v[i - 1] : 0); do { toread -= std::min(toread, inputWidth); cycles++; } while (toread > 0); } return cycles; } public: FstSpmvArchitecture() : SimpleSpmvArchitecture() {} FstSpmvArchitecture(int _cacheSize, int _inputWidth, int _numPipes) : SimpleSpmvArchitecture(_cacheSize, _inputWidth, _numPipes) {} virtual std::string get_name() override { return std::string("Fst"); } }; // Model for an architecture which can skip sequences of empty rows class SkipEmptyRowsArchitecture : public SimpleSpmvArchitecture { protected: std::vector<uint32_t> encodeEmptyRows(std::vector<uint32_t> pin, bool encode) { std::vector<uint32_t> encoded; if (!encode) { return pin; } int emptyRunLength = 0; for (size_t i = 0; i < pin.size(); i++) { uint32_t rowLength = pin[i] - (i == 0 ? 0 : pin[i - 1]); if (rowLength == 0) { emptyRunLength++; } else { if (emptyRunLength != 0) { encoded.push_back(emptyRunLength | (1 << 31)); } emptyRunLength = 0; encoded.push_back(pin[i]); } } if (emptyRunLength != 0) { encoded.push_back(emptyRunLength | (1 << 31)); } return encoded; } virtual spark::sparse::CsrMatrix preprocessBlock( const spark::sparse::CsrMatrix& in, int blockNumber, int nBlocks) override { bool encode = blockNumber != 0 && blockNumber != nBlocks - 1; return std::make_tuple( encodeEmptyRows(std::get<0>(in), encode), std::get<1>(in), std::get<2>(in)); } public: SkipEmptyRowsArchitecture() : SimpleSpmvArchitecture(){} SkipEmptyRowsArchitecture(int _cacheSize, int _inputWidth, int _numPipes) : SimpleSpmvArchitecture(_cacheSize, _inputWidth, _numPipes) {} virtual std::string get_name() override { return std::string("SkipEmpty"); } }; class PrefetchingArchitecture : public SkipEmptyRowsArchitecture { protected: public: PrefetchingArchitecture() : SkipEmptyRowsArchitecture(){} PrefetchingArchitecture(int _cacheSize, int _inputWidth, int _numPipes) : SkipEmptyRowsArchitecture(_cacheSize, _inputWidth, _numPipes) {} virtual std::string get_name() override { return std::string("PrefetchingArchitecture"); } }; } } #endif /* end of include guard: SIMPLESPMV_H */ <commit_msg>Account for max rows based on matrix size<commit_after>#ifndef SIMPLESPMV_H #define SIMPLESPMV_H #include <sstream> #include <Spark/Spmv.hpp> #include <Spark/Utils.hpp> namespace spark { namespace spmv { using EigenSparseMatrix = Eigen::SparseMatrix<double, Eigen::RowMajor, int32_t>; // pack values and colptr to reduce number of streams #pragma pack(1) struct indptr_value { double value; int indptr; indptr_value(double _value, int _indptr) : value(_value), indptr(_indptr) {} indptr_value() : value(0), indptr(0) {} } __attribute__((packed)); #pragma pack() struct Partition { int nBlocks, n, paddingCycles, totalCycles, vector_load_cycles, outSize; int reductionCycles, emptyCycles; int m_colptr_unpaddedLength; int m_indptr_values_unpaddedLength; std::vector<int> m_colptr; std::vector<indptr_value> m_indptr_values; std::string to_string() { std::stringstream s; s << "Vector load cycles " << vector_load_cycles << std::endl; s << "Padding cycles = " << paddingCycles << std::endl; s << "Total cycles = " << totalCycles << std::endl; s << "Nrows = " << n << std::endl; s << "Partitions = " << nBlocks << std::endl; s << "Reduction cycles = " << reductionCycles << std::endl; std::cout << "Empty cycles = " << emptyCycles << std::endl; return s.str(); } }; // A parameterised, generic architecture for SpMV. Supported parameters are: // - input width // - number of pipes // - cache size per pipe // - TODO data type class SimpleSpmvArchitecture : public SpmvArchitecture { // architecture specific properties protected: int cacheSize, inputWidth, numPipes; EigenSparseMatrix mat; std::vector<Partition> partitions; virtual int countComputeCycles(uint32_t* v, int size, int inputWidth); public: SimpleSpmvArchitecture() : cacheSize(getPartitionSize()), inputWidth(getInputWidth()), numPipes(getNumPipes()) {} SimpleSpmvArchitecture(int _cacheSize, int _inputWidth, int _numPipes) : cacheSize(_cacheSize), inputWidth(_inputWidth), numPipes(_numPipes) {} virtual ~SimpleSpmvArchitecture() {} virtual double getEstimatedClockCycles() { auto res = std::max_element(partitions.begin(), partitions.end(), [](const Partition& a, const Partition& b) { return a.totalCycles < b.totalCycles; }); return res->totalCycles; } virtual double getGFlopsCount() { return 2 * this->mat.nonZeros() / 1E9; } // NOTE: only call this after a call to preprocessMatrix virtual ImplementationParameters getImplementationParameters() { // XXX bram usage for altera in double precision only (512 deep, 40 bits wide, so need 2 BRAMs) //int brams = (double)cacheSize * (double)inputWidth / 512.0 * 2.0; // XXX these should be architecture params int maxRows = (this->mat.rows() / 512) * 512; const int virtex6EntriesPerBram = 512; LogicResourceUsage interPartitionReductionKernel(2768,1505, maxRows / virtex6EntriesPerBram, 0); LogicResourceUsage paddingKernel{400, 500, 0, 0}; LogicResourceUsage spmvKernelPerInput{1466, 2060, cacheSize / virtex6EntriesPerBram, 10}; // includes cache LogicResourceUsage sm{800, 500, 0, 0}; LogicResourceUsage spmvPerPipe = interPartitionReductionKernel + paddingKernel + spmvKernelPerInput * inputWidth + sm; LogicResourceUsage memoryPerPipe{3922, 8393, 160, 0}; LogicResourceUsage memory{24000, 32000, 0, 0}; //LogicResourceUsage designOther{}; LogicResourceUsage designUsage = (spmvPerPipe + memoryPerPipe) * numPipes + memory; double memoryBandwidth =(double)inputWidth * numPipes * getFrequency() * 12.0 / 1E9; ImplementationParameters ip{designUsage, memoryBandwidth}; //ip.clockFrequency = getFrequency() / 1E6; // MHz return ip; } virtual std::string to_string() { std::stringstream s; s << get_name(); s << " " << cacheSize; s << " " << inputWidth; s << " " << numPipes; s << " " << getEstimatedClockCycles(); s << " " << getEstimatedGFlops(); return s.str(); } virtual void preprocess(const EigenSparseMatrix& mat) override; virtual Eigen::VectorXd dfespmv(Eigen::VectorXd x) override; virtual std::string get_name() override { return std::string("Simple"); } private: std::vector<EigenSparseMatrix> do_partition( const EigenSparseMatrix& mat, int numPipes); Partition do_blocking( const Eigen::SparseMatrix<double, Eigen::RowMajor, int32_t>& mat, int blockSize, int inputWidth); }; template<typename T> class SimpleSpmvArchitectureSpace : public SpmvArchitectureSpace { // NOTE any raw pointers returned through the API of this class // are assumed to be wrapped in smart pointers by the base class spark::utils::Range cacheSizeR{1024, 4096, 512}; spark::utils::Range inputWidthR{8, 100, 8}; spark::utils::Range numPipesR{1, 6, 1}; bool last = false; public: SimpleSpmvArchitectureSpace( spark::utils::Range numPipesRange, spark::utils::Range inputWidthRange, spark::utils::Range cacheSizeRange) { cacheSizeR = cacheSizeRange; inputWidthR = inputWidthRange; numPipesR = numPipesRange; } SimpleSpmvArchitectureSpace() { } protected: void restart() override { cacheSizeR.restart(); inputWidthR.restart(); numPipesR.restart(); last = false; } T* doNext(){ if (last) return nullptr; T* result = new T(cacheSizeR.crt, inputWidthR.crt, numPipesR.crt); ++cacheSizeR; if (cacheSizeR.at_start()) { ++inputWidthR; if (inputWidthR.at_start()) { ++numPipesR; if (numPipesR.at_start()) last = true; } } return result; } }; // FST based architecture, for now we assume it's the same though it probably isn't class FstSpmvArchitecture : public SimpleSpmvArchitecture { protected: virtual int countComputeCycles(uint32_t* v, int size, int inputWidth) override { int cycles = 0; for (int i = 0; i < size; i++) { int toread = v[i] - (i > 0 ? v[i - 1] : 0); do { toread -= std::min(toread, inputWidth); cycles++; } while (toread > 0); } return cycles; } public: FstSpmvArchitecture() : SimpleSpmvArchitecture() {} FstSpmvArchitecture(int _cacheSize, int _inputWidth, int _numPipes) : SimpleSpmvArchitecture(_cacheSize, _inputWidth, _numPipes) {} virtual std::string get_name() override { return std::string("Fst"); } }; // Model for an architecture which can skip sequences of empty rows class SkipEmptyRowsArchitecture : public SimpleSpmvArchitecture { protected: std::vector<uint32_t> encodeEmptyRows(std::vector<uint32_t> pin, bool encode) { std::vector<uint32_t> encoded; if (!encode) { return pin; } int emptyRunLength = 0; for (size_t i = 0; i < pin.size(); i++) { uint32_t rowLength = pin[i] - (i == 0 ? 0 : pin[i - 1]); if (rowLength == 0) { emptyRunLength++; } else { if (emptyRunLength != 0) { encoded.push_back(emptyRunLength | (1 << 31)); } emptyRunLength = 0; encoded.push_back(pin[i]); } } if (emptyRunLength != 0) { encoded.push_back(emptyRunLength | (1 << 31)); } return encoded; } virtual spark::sparse::CsrMatrix preprocessBlock( const spark::sparse::CsrMatrix& in, int blockNumber, int nBlocks) override { bool encode = blockNumber != 0 && blockNumber != nBlocks - 1; return std::make_tuple( encodeEmptyRows(std::get<0>(in), encode), std::get<1>(in), std::get<2>(in)); } public: SkipEmptyRowsArchitecture() : SimpleSpmvArchitecture(){} SkipEmptyRowsArchitecture(int _cacheSize, int _inputWidth, int _numPipes) : SimpleSpmvArchitecture(_cacheSize, _inputWidth, _numPipes) {} virtual std::string get_name() override { return std::string("SkipEmpty"); } }; class PrefetchingArchitecture : public SkipEmptyRowsArchitecture { protected: public: PrefetchingArchitecture() : SkipEmptyRowsArchitecture(){} PrefetchingArchitecture(int _cacheSize, int _inputWidth, int _numPipes) : SkipEmptyRowsArchitecture(_cacheSize, _inputWidth, _numPipes) {} virtual std::string get_name() override { return std::string("PrefetchingArchitecture"); } }; } } #endif /* end of include guard: SIMPLESPMV_H */ <|endoftext|>
<commit_before> #include "Globals.h" #include "../BoundingBox.h" #include "../Chunk.h" #include "Floater.h" #include "Player.h" #include "../ClientHandle.h" /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cFloaterEntityCollisionCallback class cFloaterEntityCollisionCallback : public cEntityCallback { public: cFloaterEntityCollisionCallback(cFloater * a_Floater, const Vector3d & a_Pos, const Vector3d & a_NextPos) : m_Floater(a_Floater), m_Pos(a_Pos), m_NextPos(a_NextPos), m_MinCoeff(1), m_HitEntity(NULL) { } virtual bool Item(cEntity * a_Entity) override { if (!a_Entity->IsMob()) // Floaters can only pull mobs not other entities. { return false; } cBoundingBox EntBox(a_Entity->GetPosition(), a_Entity->GetWidth() / 2, a_Entity->GetHeight()); double LineCoeff; char Face; EntBox.Expand(m_Floater->GetWidth() / 2, m_Floater->GetHeight() / 2, m_Floater->GetWidth() / 2); if (!EntBox.CalcLineIntersection(m_Pos, m_NextPos, LineCoeff, Face)) { // No intersection whatsoever return false; } if (LineCoeff < m_MinCoeff) { // The entity is closer than anything we've stored so far, replace it as the potential victim m_MinCoeff = LineCoeff; m_HitEntity = a_Entity; } // Don't break the enumeration, we want all the entities return false; } /// Returns the nearest entity that was hit, after the enumeration has been completed cEntity * GetHitEntity(void) const { return m_HitEntity; } /// Returns true if the callback has encountered a true hit bool HasHit(void) const { return (m_MinCoeff < 1); } protected: cFloater * m_Floater; const Vector3d & m_Pos; const Vector3d & m_NextPos; double m_MinCoeff; // The coefficient of the nearest hit on the Pos line // Although it's bad(tm) to store entity ptrs from a callback, we can afford it here, because the entire callback // is processed inside the tick thread, so the entities won't be removed in between the calls and the final processing cEntity * m_HitEntity; // The nearest hit entity } ; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cFloaterCheckEntityExist class cFloaterCheckEntityExist : public cEntityCallback { public: cFloaterCheckEntityExist(void) : m_EntityExists(false) { } bool Item(cEntity * a_Entity) override { m_EntityExists = true; return false; } bool DoesExist(void) const { return m_EntityExists; } protected: bool m_EntityExists; } ; cFloater::cFloater(double a_X, double a_Y, double a_Z, Vector3d a_Speed, int a_PlayerID, int a_CountDownTime) : cEntity(etFloater, a_X, a_Y, a_Z, 0.2, 0.2), m_PickupCountDown(0), m_PlayerID(a_PlayerID), m_CanPickupItem(false), m_CountDownTime(a_CountDownTime), m_AttachedMobID(-1) { SetSpeed(a_Speed); } void cFloater::SpawnOn(cClientHandle & a_Client) { a_Client.SendSpawnObject(*this, 90, m_PlayerID, 0, 0); } void cFloater::Tick(float a_Dt, cChunk & a_Chunk) { HandlePhysics(a_Dt, a_Chunk); if (IsBlockWater(m_World->GetBlock((int) GetPosX(), (int) GetPosY(), (int) GetPosZ())) && m_World->GetBlockMeta((int) GetPosX(), (int) GetPosY(), (int) GetPosZ()) == 0) { if (!m_CanPickupItem && m_AttachedMobID == -1) // Check if you can't already pickup a fish and if the floater isn't attached to a mob. { if (m_CountDownTime <= 0) { m_World->BroadcastSoundEffect("random.splash", (int) floor(GetPosX() * 8), (int) floor(GetPosY() * 8), (int) floor(GetPosZ() * 8), 1, 1); SetPosY(GetPosY() - 1); m_CanPickupItem = true; m_PickupCountDown = 20; m_CountDownTime = 100 + m_World->GetTickRandomNumber(800); LOGD("Floater %i can be picked up", GetUniqueID()); } else if (m_CountDownTime == 20) // Calculate the position where the particles should spawn and start producing them. { LOGD("Started producing particles for floater %i", GetUniqueID()); m_ParticlePos.Set(GetPosX() + (-4 + m_World->GetTickRandomNumber(8)), GetPosY(), GetPosZ() + (-4 + m_World->GetTickRandomNumber(8))); m_World->BroadcastParticleEffect("splash", (float) m_ParticlePos.x, (float) m_ParticlePos.y, (float) m_ParticlePos.z, 0, 0, 0, 0, 15); } else if (m_CountDownTime < 20) { m_ParticlePos = (m_ParticlePos + (GetPosition() - m_ParticlePos) / 6); m_World->BroadcastParticleEffect("splash", (float) m_ParticlePos.x, (float) m_ParticlePos.y, (float) m_ParticlePos.z, 0, 0, 0, 0, 15); } m_CountDownTime--; if (m_World->GetHeight((int) GetPosX(), (int) GetPosZ()) == (int) GetPosY()) { if (m_World->IsWeatherWet() && m_World->GetTickRandomNumber(3) == 0) // 25% chance of an extra countdown when being rained on. { m_CountDownTime--; } } else // if the floater is underground it has a 50% chance of not decreasing the countdown. { if (m_World->GetTickRandomNumber(1) == 0) { m_CountDownTime++; } } } SetSpeedY(0.7); } if (CanPickup()) // Make sure the floater "loses its fish" { m_PickupCountDown--; if (m_PickupCountDown == 0) { m_CanPickupItem = false; LOGD("The fish is gone. Floater %i can not pick an item up.", GetUniqueID()); } } if (GetSpeed().Length() > 4 && m_AttachedMobID == -1) { cFloaterEntityCollisionCallback Callback(this, GetPosition(), GetPosition() + GetSpeed() / 20); a_Chunk.ForEachEntity(Callback); if (Callback.HasHit()) { AttachTo(Callback.GetHitEntity()); Callback.GetHitEntity()->TakeDamage(*this); // TODO: the player attacked the mob not the floater. m_AttachedMobID = Callback.GetHitEntity()->GetUniqueID(); } } cFloaterCheckEntityExist EntityCallback; m_World->DoWithEntityByID(m_PlayerID, EntityCallback); if (!EntityCallback.DoesExist()) // The owner doesn't exist anymore. Destroy the floater entity. { Destroy(true); } if (m_AttachedMobID != -1) { m_World->DoWithEntityByID(m_AttachedMobID, EntityCallback); // The mob the floater was attached to doesn't exist anymore. if (!EntityCallback.DoesExist()) { m_AttachedMobID = -1; } } SetSpeedX(GetSpeedX() * 0.95); SetSpeedZ(GetSpeedZ() * 0.95); BroadcastMovementUpdate(); }<commit_msg>Fixed Parentheses.<commit_after> #include "Globals.h" #include "../BoundingBox.h" #include "../Chunk.h" #include "Floater.h" #include "Player.h" #include "../ClientHandle.h" /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cFloaterEntityCollisionCallback class cFloaterEntityCollisionCallback : public cEntityCallback { public: cFloaterEntityCollisionCallback(cFloater * a_Floater, const Vector3d & a_Pos, const Vector3d & a_NextPos) : m_Floater(a_Floater), m_Pos(a_Pos), m_NextPos(a_NextPos), m_MinCoeff(1), m_HitEntity(NULL) { } virtual bool Item(cEntity * a_Entity) override { if (!a_Entity->IsMob()) // Floaters can only pull mobs not other entities. { return false; } cBoundingBox EntBox(a_Entity->GetPosition(), a_Entity->GetWidth() / 2, a_Entity->GetHeight()); double LineCoeff; char Face; EntBox.Expand(m_Floater->GetWidth() / 2, m_Floater->GetHeight() / 2, m_Floater->GetWidth() / 2); if (!EntBox.CalcLineIntersection(m_Pos, m_NextPos, LineCoeff, Face)) { // No intersection whatsoever return false; } if (LineCoeff < m_MinCoeff) { // The entity is closer than anything we've stored so far, replace it as the potential victim m_MinCoeff = LineCoeff; m_HitEntity = a_Entity; } // Don't break the enumeration, we want all the entities return false; } /// Returns the nearest entity that was hit, after the enumeration has been completed cEntity * GetHitEntity(void) const { return m_HitEntity; } /// Returns true if the callback has encountered a true hit bool HasHit(void) const { return (m_MinCoeff < 1); } protected: cFloater * m_Floater; const Vector3d & m_Pos; const Vector3d & m_NextPos; double m_MinCoeff; // The coefficient of the nearest hit on the Pos line // Although it's bad(tm) to store entity ptrs from a callback, we can afford it here, because the entire callback // is processed inside the tick thread, so the entities won't be removed in between the calls and the final processing cEntity * m_HitEntity; // The nearest hit entity } ; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cFloaterCheckEntityExist class cFloaterCheckEntityExist : public cEntityCallback { public: cFloaterCheckEntityExist(void) : m_EntityExists(false) { } bool Item(cEntity * a_Entity) override { m_EntityExists = true; return false; } bool DoesExist(void) const { return m_EntityExists; } protected: bool m_EntityExists; } ; cFloater::cFloater(double a_X, double a_Y, double a_Z, Vector3d a_Speed, int a_PlayerID, int a_CountDownTime) : cEntity(etFloater, a_X, a_Y, a_Z, 0.2, 0.2), m_PickupCountDown(0), m_PlayerID(a_PlayerID), m_CanPickupItem(false), m_CountDownTime(a_CountDownTime), m_AttachedMobID(-1) { SetSpeed(a_Speed); } void cFloater::SpawnOn(cClientHandle & a_Client) { a_Client.SendSpawnObject(*this, 90, m_PlayerID, 0, 0); } void cFloater::Tick(float a_Dt, cChunk & a_Chunk) { HandlePhysics(a_Dt, a_Chunk); if (IsBlockWater(m_World->GetBlock((int) GetPosX(), (int) GetPosY(), (int) GetPosZ())) && m_World->GetBlockMeta((int) GetPosX(), (int) GetPosY(), (int) GetPosZ()) == 0) { if ((!m_CanPickupItem) && (m_AttachedMobID == -1)) // Check if you can't already pickup a fish and if the floater isn't attached to a mob. { if (m_CountDownTime <= 0) { m_World->BroadcastSoundEffect("random.splash", (int) floor(GetPosX() * 8), (int) floor(GetPosY() * 8), (int) floor(GetPosZ() * 8), 1, 1); SetPosY(GetPosY() - 1); m_CanPickupItem = true; m_PickupCountDown = 20; m_CountDownTime = 100 + m_World->GetTickRandomNumber(800); LOGD("Floater %i can be picked up", GetUniqueID()); } else if (m_CountDownTime == 20) // Calculate the position where the particles should spawn and start producing them. { LOGD("Started producing particles for floater %i", GetUniqueID()); m_ParticlePos.Set(GetPosX() + (-4 + m_World->GetTickRandomNumber(8)), GetPosY(), GetPosZ() + (-4 + m_World->GetTickRandomNumber(8))); m_World->BroadcastParticleEffect("splash", (float) m_ParticlePos.x, (float) m_ParticlePos.y, (float) m_ParticlePos.z, 0, 0, 0, 0, 15); } else if (m_CountDownTime < 20) { m_ParticlePos = (m_ParticlePos + (GetPosition() - m_ParticlePos) / 6); m_World->BroadcastParticleEffect("splash", (float) m_ParticlePos.x, (float) m_ParticlePos.y, (float) m_ParticlePos.z, 0, 0, 0, 0, 15); } m_CountDownTime--; if (m_World->GetHeight((int) GetPosX(), (int) GetPosZ()) == (int) GetPosY()) { if (m_World->IsWeatherWet() && m_World->GetTickRandomNumber(3) == 0) // 25% chance of an extra countdown when being rained on. { m_CountDownTime--; } } else // if the floater is underground it has a 50% chance of not decreasing the countdown. { if (m_World->GetTickRandomNumber(1) == 0) { m_CountDownTime++; } } } SetSpeedY(0.7); } if (CanPickup()) // Make sure the floater "loses its fish" { m_PickupCountDown--; if (m_PickupCountDown == 0) { m_CanPickupItem = false; LOGD("The fish is gone. Floater %i can not pick an item up.", GetUniqueID()); } } if ((GetSpeed().Length() > 4) && (m_AttachedMobID == -1)) { cFloaterEntityCollisionCallback Callback(this, GetPosition(), GetPosition() + GetSpeed() / 20); a_Chunk.ForEachEntity(Callback); if (Callback.HasHit()) { AttachTo(Callback.GetHitEntity()); Callback.GetHitEntity()->TakeDamage(*this); // TODO: the player attacked the mob not the floater. m_AttachedMobID = Callback.GetHitEntity()->GetUniqueID(); } } cFloaterCheckEntityExist EntityCallback; m_World->DoWithEntityByID(m_PlayerID, EntityCallback); if (!EntityCallback.DoesExist()) // The owner doesn't exist anymore. Destroy the floater entity. { Destroy(true); } if (m_AttachedMobID != -1) { m_World->DoWithEntityByID(m_AttachedMobID, EntityCallback); // The mob the floater was attached to doesn't exist anymore. if (!EntityCallback.DoesExist()) { m_AttachedMobID = -1; } } SetSpeedX(GetSpeedX() * 0.95); SetSpeedZ(GetSpeedZ() * 0.95); BroadcastMovementUpdate(); }<|endoftext|>
<commit_before>/* ____________________________________________________________________________ Scanner Component for the Micro A Compiler mscan.h Version 2007 - 2016 James L. Richards Last Update: August 28, 2007 Nelson A Castillo Last Update: January 31, 2016 The routines in this unit are based on those provided in the book "Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr., Benjamin Cummings Publishing Co. (1991). See Section 2.2, pp. 25-29. ____________________________________________________________________________ */ #include <iostream> #include <fstream> #include <string> #include <algorithm> using namespace std; extern ifstream sourceFile; extern ofstream outFile, listFile; #include "mscan.h" // ******************* // ** Constructor ** // ******************* Scanner::Scanner() { tokenBuffer = ""; lineBuffer = ""; lineNumber = 0; } // ******************************** // ** Private Member Functions ** // ******************************** void Scanner::BufferChar(char c) { if (tokenBuffer.length() < ID_STRING_LEN){ tokenBuffer += c; } } Token Scanner::CheckReserved() { /* Convert the string to lower case */ transform(tokenBuffer.begin(), tokenBuffer.end(), \ tokenBuffer.begin(), ::tolower); /* Check the converted words */ if ((tokenBuffer) == "bool") return BOOL_SYM; if ((tokenBuffer) == "break") return BREAK_SYM; if ((tokenBuffer) == "case") return CASE_SYM; if ((tokenBuffer) == "cheese") return CHEESE_SYM; if ((tokenBuffer) == "decs") return DECS_SYM; if ((tokenBuffer) == "do") return DO_SYM; if ((tokenBuffer) == "else") return ELSE_SYM; if ((tokenBuffer) == "end") return END_SYM; if ((tokenBuffer) == "false") return FALSE_SYM; if ((tokenBuffer) == "float") return FLOAT_SYM; if ((tokenBuffer) == "for") return FOR_SYM; if ((tokenBuffer) == "hiphip") return HIPHIP_SYM; if ((tokenBuffer) == "if") return IF_SYM; if ((tokenBuffer) == "int") return INT_SYM; if ((tokenBuffer) == "listen") return LISTEN_SYM; if ((tokenBuffer) == "otherwise") return OTHERWISE_SYM; if ((tokenBuffer) == "until") return UNTIL_SYM; if ((tokenBuffer) == "select") return SELECT_SYM; if ((tokenBuffer) == "shout") return SHOUT_SYM; if ((tokenBuffer) == "then") return THEN_SYM; if ((tokenBuffer) == "true") return TRUE_SYM; if ((tokenBuffer) == "while") return WHILE_SYM; return ID; } void Scanner::ClearBuffer() { tokenBuffer = ""; } void Scanner::LexicalError(char& c) { cout << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << endl; listFile << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << endl; c = NextChar(); } void Scanner::LexicalError(char& c, const string& errorExp) { cout << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << '\n' << errorExp << endl; listFile << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << '\n' << errorExp << endl; c = NextChar(); } char Scanner::NextChar() { char c; sourceFile.get(c); if (c == '\n') { listFile.width(6); listFile << ++lineNumber << " " << lineBuffer << endl; lineBuffer = ""; } else{ lineBuffer += c; } return c; } // ******************************* // ** Public Member Functions ** // ******************************* Token Scanner::GetNextToken() { char currentChar, c; ClearBuffer(); currentChar = NextChar(); while (!sourceFile.eof()) { if (isspace(currentChar)) { /* do nothing */ currentChar = NextChar(); } else if (isalpha(currentChar)) { /* identifier */ BufferChar(currentChar); c = sourceFile.peek(); while (isalnum(c) || c == '_') { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } return CheckReserved(); } else if (isdigit(currentChar)) { /* integer or float literals */ BufferChar(currentChar); c = sourceFile.peek(); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } /* check if it is a float */ if (c == '.') { currentChar = NextChar(); c = sourceFile.peek(); /* check for a digit after the '.' */ if (!isdigit(c)) LexicalError(currentChar, to_string(c) \ + " Boolean needs a digit" \ " after the '.'"); BufferChar(currentChar); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } /* check for power of 10 multipliers */ if (c == 'e' || c == 'E') { currentChar = NextChar(); c = sourceFile.peek(); if (c != '+' && c!= '-') { LexicalError(currentChar, \ to_string(c) + \ " Boolean needs a " "'+'/'-' after 'E'"); } BufferChar(currentChar); currentChar = NextChar(); c = sourceFile.peek(); if (!isdigit(c)) LexicalError(currentChar, \ to_string(c) + \ " Boolean needs a " \ "digit after '+'/'-'"); BufferChar(currentChar); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } } return FLOAT_LIT; } return INT_LIT; } else if (currentChar == '"') { /* string literal */ BufferChar(currentChar); c = sourceFile.peek(); /* while not end of string */ while (c != '"') { /* escape sequences */ if (c == '\\') { /* * Replace the '\' for a ':' * which's SAM's escape char */ currentChar = NextChar(); c = sourceFile.peek(); currentChar = ':'; if (c == '\\') { /* '\\' sequence */ /* Just remove one '\' */ currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } else if (c == '"') { /* '\"' sequence */ /* replace '"' for ':' */ BufferChar(currentChar); currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } else if (c == 'n') { /* \n sequence */ /* replace for ascii '\n'(012)*/ currentChar = NextChar(); currentChar = '0'; BufferChar(currentChar); currentChar = '1'; BufferChar(currentChar); currentChar = '2'; BufferChar(currentChar); c = sourceFile.peek(); } else if (isdigit(c)) { /* '\ddd' sequence */ int ind; for (ind = 0; ind < 3; ind++) { /* check for 3 digits */ if (!isdigit(c)) LexicalError(c, to_string(c) + "received. Expected three digits after \\."); currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } } else { LexicalError(currentChar, to_string(currentChar) + \ " was followed by the wrong character -options are \\ or \"."); } } else if (c == ':') { /* * ':' is the escape char used * by the SAM assembler. So it * needs to be escaped. */ currentChar = NextChar(); BufferChar(currentChar); BufferChar(currentChar); c = sourceFile.peek(); } else { /* regular characters */ currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } } /* buffer the final '"' */ currentChar = NextChar(); BufferChar(currentChar); return CHEESE_LIT; } else if (currentChar == '(') { BufferChar(currentChar); return LBANANA; } else if (currentChar == ')') { BufferChar(currentChar); return RBANANA; } else if (currentChar == '[') { BufferChar(currentChar); return LSTAPLE; } else if (currentChar == ']') { BufferChar(currentChar); return RSTAPLE; } else if (currentChar == '{') { BufferChar(currentChar); return LMUSTACHE; } else if (currentChar == '}') { BufferChar(currentChar); return RMUSTACHE; } else if (currentChar == ';') { BufferChar(currentChar); return SEMICOLON; } else if (currentChar == ':') { BufferChar(currentChar); return COLON; } else if (currentChar == ',') { BufferChar(currentChar); return COMMA; } else if (currentChar == '+') { BufferChar(currentChar); return PLUS_OP; } else if (currentChar == '*') { BufferChar(currentChar); return MULT_OP; } else if (currentChar == '/') { /* check if it is a multiline comment */ if (sourceFile.peek() == ':') { do { /* skip comment */ currentChar = NextChar(); if (currentChar == ':') { currentChar = NextChar(); if (currentChar == '/') { currentChar = NextChar(); break; } } } while (!sourceFile.eof()); } else { /* if it is a division operator */ BufferChar(currentChar); return DIV_OP; } } else if (currentChar == '=') { BufferChar(currentChar); if (sourceFile.peek() == '=') { currentChar = NextChar(); BufferChar(currentChar); return EQ_OP1; } currentChar = NextChar(); return ASSIGN_OP; } else if (currentChar == '!') { BufferChar(currentChar); if (sourceFile.peek() == '!') { currentChar = NextChar(); BufferChar(currentChar); return EQ_OP2; } else if (sourceFile.peek() == '=') { currentChar = NextChar(); BufferChar(currentChar); return NE_OP; } else { LexicalError(currentChar, to_string(c) + \ " The not operator is not" \ " supported by MnC"); } currentChar = NextChar(); } else if (currentChar == '<') { BufferChar(currentChar); if (sourceFile.peek() == '=') { currentChar = NextChar(); BufferChar(currentChar); return LE_OP; } currentChar = NextChar(); return LT_OP; } else if (currentChar == '>') { BufferChar(currentChar); if (sourceFile.peek() == '=') { currentChar = NextChar(); BufferChar(currentChar); return GE_OP; } currentChar = NextChar(); return GT_OP; } else if (currentChar == '-') { /* check if it is a comment or a minus symbol */ if (sourceFile.peek() == '-') { /* comment */ do { /* skip comment */ currentChar = NextChar(); } while (currentChar != '\n'); } else { /* minus operator */ BufferChar(currentChar); currentChar = NextChar(); return MINUS_OP; } } else { /* Unrecognized character */ LexicalError(currentChar, to_string(c) + \ " Unrecognized character"); } } /* end while */ return EOF_SYM; } <commit_msg>Use '//' instead of '--' for single line comments.<commit_after>/* ____________________________________________________________________________ Scanner Component for the Micro A Compiler mscan.h Version 2007 - 2016 James L. Richards Last Update: August 28, 2007 Nelson A Castillo Last Update: January 31, 2016 The routines in this unit are based on those provided in the book "Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr., Benjamin Cummings Publishing Co. (1991). See Section 2.2, pp. 25-29. ____________________________________________________________________________ */ #include <iostream> #include <fstream> #include <string> #include <algorithm> using namespace std; extern ifstream sourceFile; extern ofstream outFile, listFile; #include "mscan.h" // ******************* // ** Constructor ** // ******************* Scanner::Scanner() { tokenBuffer = ""; lineBuffer = ""; lineNumber = 0; } // ******************************** // ** Private Member Functions ** // ******************************** void Scanner::BufferChar(char c) { if (tokenBuffer.length() < ID_STRING_LEN){ tokenBuffer += c; } } Token Scanner::CheckReserved() { /* Convert the string to lower case */ transform(tokenBuffer.begin(), tokenBuffer.end(), \ tokenBuffer.begin(), ::tolower); /* Check the converted words */ if ((tokenBuffer) == "bool") return BOOL_SYM; if ((tokenBuffer) == "break") return BREAK_SYM; if ((tokenBuffer) == "case") return CASE_SYM; if ((tokenBuffer) == "cheese") return CHEESE_SYM; if ((tokenBuffer) == "decs") return DECS_SYM; if ((tokenBuffer) == "do") return DO_SYM; if ((tokenBuffer) == "else") return ELSE_SYM; if ((tokenBuffer) == "end") return END_SYM; if ((tokenBuffer) == "false") return FALSE_SYM; if ((tokenBuffer) == "float") return FLOAT_SYM; if ((tokenBuffer) == "for") return FOR_SYM; if ((tokenBuffer) == "hiphip") return HIPHIP_SYM; if ((tokenBuffer) == "if") return IF_SYM; if ((tokenBuffer) == "int") return INT_SYM; if ((tokenBuffer) == "listen") return LISTEN_SYM; if ((tokenBuffer) == "otherwise") return OTHERWISE_SYM; if ((tokenBuffer) == "until") return UNTIL_SYM; if ((tokenBuffer) == "select") return SELECT_SYM; if ((tokenBuffer) == "shout") return SHOUT_SYM; if ((tokenBuffer) == "then") return THEN_SYM; if ((tokenBuffer) == "true") return TRUE_SYM; if ((tokenBuffer) == "while") return WHILE_SYM; return ID; } void Scanner::ClearBuffer() { tokenBuffer = ""; } void Scanner::LexicalError(char& c) { cout << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << endl; listFile << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << endl; c = NextChar(); } void Scanner::LexicalError(char& c, const string& errorExp) { cout << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << '\n' << errorExp << endl; listFile << " *** Lexical Error: '" << c << "' ignored at position " << int(lineBuffer.size()) << " on line #" << lineNumber + 1 << '.' << '\n' << errorExp << endl; c = NextChar(); } char Scanner::NextChar() { char c; sourceFile.get(c); if (c == '\n') { listFile.width(6); listFile << ++lineNumber << " " << lineBuffer << endl; lineBuffer = ""; } else{ lineBuffer += c; } return c; } // ******************************* // ** Public Member Functions ** // ******************************* Token Scanner::GetNextToken() { char currentChar, c; ClearBuffer(); currentChar = NextChar(); while (!sourceFile.eof()) { if (isspace(currentChar)) { /* do nothing */ currentChar = NextChar(); } else if (isalpha(currentChar)) { /* identifier */ BufferChar(currentChar); c = sourceFile.peek(); while (isalnum(c) || c == '_') { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } return CheckReserved(); } else if (isdigit(currentChar)) { /* integer or float literals */ BufferChar(currentChar); c = sourceFile.peek(); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } /* check if it is a float */ if (c == '.') { currentChar = NextChar(); c = sourceFile.peek(); /* check for a digit after the '.' */ if (!isdigit(c)) LexicalError(currentChar, to_string(c) \ + " Boolean needs a digit" \ " after the '.'"); BufferChar(currentChar); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } /* check for power of 10 multipliers */ if (c == 'e' || c == 'E') { currentChar = NextChar(); c = sourceFile.peek(); if (c != '+' && c!= '-') { LexicalError(currentChar, \ to_string(c) + \ " Boolean needs a " "'+'/'-' after 'E'"); } BufferChar(currentChar); currentChar = NextChar(); c = sourceFile.peek(); if (!isdigit(c)) LexicalError(currentChar, \ to_string(c) + \ " Boolean needs a " \ "digit after '+'/'-'"); BufferChar(currentChar); while (isdigit(c)) { currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } } return FLOAT_LIT; } return INT_LIT; } else if (currentChar == '"') { /* string literal */ BufferChar(currentChar); c = sourceFile.peek(); /* while not end of string */ while (c != '"') { /* escape sequences */ if (c == '\\') { /* * Replace the '\' for a ':' * which's SAM's escape char */ currentChar = NextChar(); c = sourceFile.peek(); currentChar = ':'; if (c == '\\') { /* '\\' sequence */ /* Just remove one '\' */ currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } else if (c == '"') { /* '\"' sequence */ /* replace '"' for ':' */ BufferChar(currentChar); currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } else if (c == 'n') { /* \n sequence */ /* replace for ascii '\n'(012)*/ currentChar = NextChar(); currentChar = '0'; BufferChar(currentChar); currentChar = '1'; BufferChar(currentChar); currentChar = '2'; BufferChar(currentChar); c = sourceFile.peek(); } else if (isdigit(c)) { /* '\ddd' sequence */ int ind; for (ind = 0; ind < 3; ind++) { /* check for 3 digits */ if (!isdigit(c)) LexicalError(c, to_string(c) + "received. Expected three digits after \\."); currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } } else { LexicalError(currentChar, to_string(currentChar) + \ " was followed by the wrong character -options are \\ or \"."); } } else if (c == ':') { /* * ':' is the escape char used * by the SAM assembler. So it * needs to be escaped. */ currentChar = NextChar(); BufferChar(currentChar); BufferChar(currentChar); c = sourceFile.peek(); } else { /* regular characters */ currentChar = NextChar(); BufferChar(currentChar); c = sourceFile.peek(); } } /* buffer the final '"' */ currentChar = NextChar(); BufferChar(currentChar); return CHEESE_LIT; } else if (currentChar == '(') { BufferChar(currentChar); return LBANANA; } else if (currentChar == ')') { BufferChar(currentChar); return RBANANA; } else if (currentChar == '[') { BufferChar(currentChar); return LSTAPLE; } else if (currentChar == ']') { BufferChar(currentChar); return RSTAPLE; } else if (currentChar == '{') { BufferChar(currentChar); return LMUSTACHE; } else if (currentChar == '}') { BufferChar(currentChar); return RMUSTACHE; } else if (currentChar == ';') { BufferChar(currentChar); return SEMICOLON; } else if (currentChar == ':') { BufferChar(currentChar); return COLON; } else if (currentChar == ',') { BufferChar(currentChar); return COMMA; } else if (currentChar == '+') { BufferChar(currentChar); return PLUS_OP; } else if (currentChar == '*') { BufferChar(currentChar); return MULT_OP; } else if (currentChar == '/') { /* check if it is a multiline comment */ c = sourceFile.peek(); if (c == ':') { do { /* skip comment */ currentChar = NextChar(); if (currentChar == ':') { currentChar = NextChar(); if (currentChar == '/') { currentChar = NextChar(); break; } } } while (!sourceFile.eof()); } else if (c == '/') { /* single line commment */ do { /* skip comment */ currentChar = NextChar(); } while (currentChar != '\n'); } else { /* if it is a division operator */ BufferChar(currentChar); return DIV_OP; } } else if (currentChar == '=') { BufferChar(currentChar); if (sourceFile.peek() == '=') { currentChar = NextChar(); BufferChar(currentChar); return EQ_OP1; } currentChar = NextChar(); return ASSIGN_OP; } else if (currentChar == '!') { BufferChar(currentChar); if (sourceFile.peek() == '!') { currentChar = NextChar(); BufferChar(currentChar); return EQ_OP2; } else if (sourceFile.peek() == '=') { currentChar = NextChar(); BufferChar(currentChar); return NE_OP; } else { LexicalError(currentChar, to_string(c) + \ " The not operator is not" \ " supported by MnC"); } currentChar = NextChar(); } else if (currentChar == '<') { BufferChar(currentChar); if (sourceFile.peek() == '=') { currentChar = NextChar(); BufferChar(currentChar); return LE_OP; } currentChar = NextChar(); return LT_OP; } else if (currentChar == '>') { BufferChar(currentChar); if (sourceFile.peek() == '=') { currentChar = NextChar(); BufferChar(currentChar); return GE_OP; } currentChar = NextChar(); return GT_OP; } else if (currentChar == '-') { /* minus operator */ BufferChar(currentChar); currentChar = NextChar(); return MINUS_OP; } else { /* Unrecognized character */ LexicalError(currentChar, to_string(c) + \ " Unrecognized character"); } } /* end while */ return EOF_SYM; } <|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. **/ #ifndef QUICKSTEP_QUERY_EXECUTION_SHIFTBOSS_HPP_ #define QUICKSTEP_QUERY_EXECUTION_SHIFTBOSS_HPP_ #include <cstddef> #include <cstdint> #include <memory> #include <unordered_map> #include "catalog/CatalogDatabaseCache.hpp" #include "catalog/CatalogTypedefs.hpp" #include "query_execution/QueryContext.hpp" #include "query_execution/QueryExecutionTypedefs.hpp" #include "query_execution/WorkerDirectory.hpp" #include "storage/Flags.hpp" #include "storage/StorageConfig.h" // For QUICKSTEP_HAVE_FILE_MANAGER_HDFS. #include "threading/Thread.hpp" #include "utility/Macros.hpp" #include "glog/logging.h" #include "tmb/address.h" #include "tmb/id_typedefs.h" namespace tmb { class MessageBus; }; namespace quickstep { class StorageManager; namespace serialization { class CatalogDatabase; class QueryContext; } // namespace serialization /** \addtogroup QueryExecution * @{ */ /** * @brief The Shiftboss accepts workorder protos from shiftboss, and assigns * the workorders to workers. **/ class Shiftboss : public Thread { public: /** * @brief Constructor. * * @param bus_global A pointer to the TMB for Foreman. * @param bus_local A pointer to the TMB for Workers. * @param storage_manager The StorageManager to use. * @param workers A pointer to the WorkerDirectory. * @param hdfs The HDFS connector via libhdfs3. * @param cpu_id The ID of the CPU to which the Shiftboss thread can be pinned. * * @note If cpu_id is not specified, Shiftboss thread can be possibly moved * around on different CPUs by the OS. **/ Shiftboss(tmb::MessageBus *bus_global, tmb::MessageBus *bus_local, StorageManager *storage_manager, WorkerDirectory *workers, void *hdfs, const int cpu_id = -1); ~Shiftboss() override { } /** * @brief Get the TMB client ID of Shiftboss thread. * * @return TMB client ID of shiftboss thread. **/ inline tmb::client_id getBusClientID() const { return shiftboss_client_id_global_; } /** * @brief Get the Work Order processing capacity of all Workers managed by * Shiftboss during a single round of WorkOrder dispatch. **/ inline std::size_t getWorkOrderCapacity() const { DCHECK_NE(max_msgs_per_worker_, 0u); return max_msgs_per_worker_ * workers_->getNumWorkers(); } /** * @brief Get the Worker to assign WorkOrders for execution. Block to wait if * all Workers have reached their capacity for queued WorkOrders. **/ // TODO(zuyu): To achieve non-blocking, we need a queue to cache received // normal Work Order protos from Foreman and the generated rebuild Work Orders. inline std::size_t getSchedulableWorker(); /** * @brief Set the maximum number of messages that should be allocated to each * worker during a single round of WorkOrder dispatch. * * @param max_msgs_per_worker Maximum number of messages. **/ inline void setMaxMessagesPerWorker(const std::size_t max_msgs_per_worker) { max_msgs_per_worker_ = max_msgs_per_worker; } protected: /** * @brief The shiftboss receives workorders, and based on the response it * assigns workorders to workers. * * @note The workers who get the messages from the Shiftboss execute and * subsequently delete the WorkOrder contained in the message. **/ void run() override; private: void registerWithForeman(); void processShiftbossRegistrationResponseMessage(); /** * @brief Process the Shiftboss initiate message and ack back. * * @param query_id The given query id. * @param catalog_database_cache_proto The proto used to update * CatalogDatabaseCache. * @param query_context_proto The QueryContext proto. **/ void processQueryInitiateMessage(const std::size_t query_id, const serialization::CatalogDatabase &catalog_database_cache_proto, const serialization::QueryContext &query_context_proto); /** * @brief Process the RebuildWorkOrder initiate message and ack back. * * @param query_id The ID of the query to which this RebuildWorkOrder initiate * message belongs. * @param op_index The index of the operator for rebuild work orders. * @param dest_index The InsertDestination index in QueryContext to rebuild. * @param rel_id The relation that needs to generate rebuild work orders. **/ void processInitiateRebuildMessage(const std::size_t query_id, const std::size_t op_index, const QueryContext::insert_destination_id dest_index, const relation_id rel_id); tmb::MessageBus *bus_global_, *bus_local_; CatalogDatabaseCache database_cache_; StorageManager *storage_manager_; WorkerDirectory *workers_; // Not owned. void *hdfs_; // The ID of the CPU that the Shiftboss thread can optionally be pinned to. const int cpu_id_; tmb::client_id shiftboss_client_id_global_, shiftboss_client_id_local_, foreman_client_id_; // Unique per Shiftboss instance. std::uint64_t shiftboss_index_; // TMB recipients for all workers managed by this Shiftboss. tmb::Address worker_addresses_; // During a single round of WorkOrder dispatch, a Worker should be allocated // at most these many WorkOrders. std::size_t max_msgs_per_worker_; // The worker index for scheduling Work Order. std::size_t start_worker_index_; // QueryContexts per query. std::unordered_map<std::size_t, std::unique_ptr<QueryContext>> query_contexts_; DISALLOW_COPY_AND_ASSIGN(Shiftboss); }; /** @} */ } // namespace quickstep #endif // QUICKSTEP_QUERY_EXECUTION_SHIFTBOSS_HPP_ <commit_msg>Fixed a pedantic warning.<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. **/ #ifndef QUICKSTEP_QUERY_EXECUTION_SHIFTBOSS_HPP_ #define QUICKSTEP_QUERY_EXECUTION_SHIFTBOSS_HPP_ #include <cstddef> #include <cstdint> #include <memory> #include <unordered_map> #include "catalog/CatalogDatabaseCache.hpp" #include "catalog/CatalogTypedefs.hpp" #include "query_execution/QueryContext.hpp" #include "query_execution/QueryExecutionTypedefs.hpp" #include "query_execution/WorkerDirectory.hpp" #include "storage/Flags.hpp" #include "storage/StorageConfig.h" // For QUICKSTEP_HAVE_FILE_MANAGER_HDFS. #include "threading/Thread.hpp" #include "utility/Macros.hpp" #include "glog/logging.h" #include "tmb/address.h" #include "tmb/id_typedefs.h" namespace tmb { class MessageBus; } namespace quickstep { class StorageManager; namespace serialization { class CatalogDatabase; class QueryContext; } // namespace serialization /** \addtogroup QueryExecution * @{ */ /** * @brief The Shiftboss accepts workorder protos from shiftboss, and assigns * the workorders to workers. **/ class Shiftboss : public Thread { public: /** * @brief Constructor. * * @param bus_global A pointer to the TMB for Foreman. * @param bus_local A pointer to the TMB for Workers. * @param storage_manager The StorageManager to use. * @param workers A pointer to the WorkerDirectory. * @param hdfs The HDFS connector via libhdfs3. * @param cpu_id The ID of the CPU to which the Shiftboss thread can be pinned. * * @note If cpu_id is not specified, Shiftboss thread can be possibly moved * around on different CPUs by the OS. **/ Shiftboss(tmb::MessageBus *bus_global, tmb::MessageBus *bus_local, StorageManager *storage_manager, WorkerDirectory *workers, void *hdfs, const int cpu_id = -1); ~Shiftboss() override { } /** * @brief Get the TMB client ID of Shiftboss thread. * * @return TMB client ID of shiftboss thread. **/ inline tmb::client_id getBusClientID() const { return shiftboss_client_id_global_; } /** * @brief Get the Work Order processing capacity of all Workers managed by * Shiftboss during a single round of WorkOrder dispatch. **/ inline std::size_t getWorkOrderCapacity() const { DCHECK_NE(max_msgs_per_worker_, 0u); return max_msgs_per_worker_ * workers_->getNumWorkers(); } /** * @brief Get the Worker to assign WorkOrders for execution. Block to wait if * all Workers have reached their capacity for queued WorkOrders. **/ // TODO(zuyu): To achieve non-blocking, we need a queue to cache received // normal Work Order protos from Foreman and the generated rebuild Work Orders. inline std::size_t getSchedulableWorker(); /** * @brief Set the maximum number of messages that should be allocated to each * worker during a single round of WorkOrder dispatch. * * @param max_msgs_per_worker Maximum number of messages. **/ inline void setMaxMessagesPerWorker(const std::size_t max_msgs_per_worker) { max_msgs_per_worker_ = max_msgs_per_worker; } protected: /** * @brief The shiftboss receives workorders, and based on the response it * assigns workorders to workers. * * @note The workers who get the messages from the Shiftboss execute and * subsequently delete the WorkOrder contained in the message. **/ void run() override; private: void registerWithForeman(); void processShiftbossRegistrationResponseMessage(); /** * @brief Process the Shiftboss initiate message and ack back. * * @param query_id The given query id. * @param catalog_database_cache_proto The proto used to update * CatalogDatabaseCache. * @param query_context_proto The QueryContext proto. **/ void processQueryInitiateMessage(const std::size_t query_id, const serialization::CatalogDatabase &catalog_database_cache_proto, const serialization::QueryContext &query_context_proto); /** * @brief Process the RebuildWorkOrder initiate message and ack back. * * @param query_id The ID of the query to which this RebuildWorkOrder initiate * message belongs. * @param op_index The index of the operator for rebuild work orders. * @param dest_index The InsertDestination index in QueryContext to rebuild. * @param rel_id The relation that needs to generate rebuild work orders. **/ void processInitiateRebuildMessage(const std::size_t query_id, const std::size_t op_index, const QueryContext::insert_destination_id dest_index, const relation_id rel_id); tmb::MessageBus *bus_global_, *bus_local_; CatalogDatabaseCache database_cache_; StorageManager *storage_manager_; WorkerDirectory *workers_; // Not owned. void *hdfs_; // The ID of the CPU that the Shiftboss thread can optionally be pinned to. const int cpu_id_; tmb::client_id shiftboss_client_id_global_, shiftboss_client_id_local_, foreman_client_id_; // Unique per Shiftboss instance. std::uint64_t shiftboss_index_; // TMB recipients for all workers managed by this Shiftboss. tmb::Address worker_addresses_; // During a single round of WorkOrder dispatch, a Worker should be allocated // at most these many WorkOrders. std::size_t max_msgs_per_worker_; // The worker index for scheduling Work Order. std::size_t start_worker_index_; // QueryContexts per query. std::unordered_map<std::size_t, std::unique_ptr<QueryContext>> query_contexts_; DISALLOW_COPY_AND_ASSIGN(Shiftboss); }; /** @} */ } // namespace quickstep #endif // QUICKSTEP_QUERY_EXECUTION_SHIFTBOSS_HPP_ <|endoftext|>
<commit_before>#include "Header.h" using namespace ATM; //------------------------------------------------------------------------------// Account::Account(){/* Initialize the Customer Data from the .txt file */} //------------------------------------------------------------------------------// //random comment <commit_msg>Delete Account.cpp<commit_after><|endoftext|>
<commit_before>#include "../includes/FileWatcherLinux.h" namespace NSFW { FileWatcherLinux::FileWatcherLinux(std::string path, std::queue<Event> &eventsQueue, bool &watchFiles) : mEventsQueue(eventsQueue), mInotify(0), mPath(path), mWatchFiles(watchFiles) {} FileWatcherLinux::~FileWatcherLinux() {} void FileWatcherLinux::addEvent(std::string action, inotify_event *inEvent) { Directory *parent = mWDtoDirNode[inEvent->wd]; addEvent(action, parent->path + "/" + parent->name, new std::string(inEvent->name)); } void FileWatcherLinux::addEvent(std::string action, std::string directory, std::string *file) { std::cout << action << ":" << directory << ":" << *file << std::endl; Event event; event.action = action; event.directory = directory; event.file = file; mEventsQueue.push(event); } Directory *FileWatcherLinux::buildDirTree(std::string path) { std::queue<Directory *> dirQueue; Directory *topRoot = new Directory; // create root of snapshot if (path[path.length() - 1] == '/') { path = path.substr(0, path.length() - 1); } size_t lastSlash = path.find_last_of("/"); if (lastSlash != std::string::npos) { topRoot->name = path.substr(lastSlash + 1); topRoot->path = path.substr(0, lastSlash); } else { topRoot->name = ""; topRoot->path = "/"; } topRoot->watchDescriptor = -1; dirQueue.push(topRoot); bool checkRootOnExit = false; while (!dirQueue.empty()) { Directory *root = dirQueue.front(); dirent ** directoryContents = NULL; std::string fullPath = root->path + "/" + root->name; int n = scandir(fullPath.c_str(), &directoryContents, NULL, alphasort); if (n < 0) { if (topRoot == root) { return NULL; // top directory no longer exists } else { checkRootOnExit = true; dirQueue.pop(); continue; } } // find all the directories within this directory // this breaks the alphabetical sorting of directories for (int i = 0; i < n; ++i) { if (!strcmp(directoryContents[i]->d_name, ".") || !strcmp(directoryContents[i]->d_name, "..")) { continue; // skip navigation folder } // Certain *nix do not support dirent->d_type and may return DT_UNKOWN for every file returned in scandir // in order to make this work on all *nix, we need to stat the file to determine if it is a directory std::string filePath = root->path + "/" + root->name + "/" + directoryContents[i]->d_name; struct stat file; if (stat(filePath.c_str(), &file) < 0) { continue; } if (S_ISDIR(file.st_mode)) { // create the directory struct for this directory and add a reference of this directory to its root Directory *dir = new Directory; dir->path = root->path + "/" + root->name; dir->name = directoryContents[i]->d_name; dir->watchDescriptor = -1; root->childDirectories[dir->name] = dir; dirQueue.push(dir); } } for (int i = 0; i < n; ++i) { delete directoryContents[i]; } delete[] directoryContents; dirQueue.pop(); } if (checkRootOnExit) { struct stat rootStat; if (!stat((topRoot->path + "/" + topRoot->name).c_str(), &rootStat) || !S_ISDIR(rootStat.st_mode)) { // delete tree as far as we can go destroyDirTree(topRoot); return NULL; } } return topRoot; } void FileWatcherLinux::destroyDirTree(Directory *tree) { if (tree == NULL) return; std::queue<Directory *> dirQueue; dirQueue.push(tree); while (!dirQueue.empty()) { Directory *root = dirQueue.front(); // Add directories to the queue to continue listing events for (std::map<std::string, Directory *>::iterator dirIter = root->childDirectories.begin(); dirIter != root->childDirectories.end(); ++dirIter) { dirQueue.push(dirIter->second); } dirQueue.pop(); delete root; } } void FileWatcherLinux::destroyWatchTree(Directory *tree) { std::queue<Directory *> dirQueue; dirQueue.push(tree); if (fcntl(mInotify, F_GETFD) != -1 || errno != EBADF) { // need to pass errors back here so that the next call to poll // can clean up after this type of error return; // panic } while (!dirQueue.empty()) { Directory *root = dirQueue.front(); inotify_rm_watch(mInotify, root->watchDescriptor); // Add directories to the queue to continue listing events for (std::map<std::string, Directory *>::iterator dirIter = root->childDirectories.begin(); dirIter != root->childDirectories.end(); ++dirIter) { dirQueue.push(dirIter->second); } dirQueue.pop(); delete root; } } std::string FileWatcherLinux::getPath() { return mPath; } void *FileWatcherLinux::mainLoop(void *params) { FileWatcherLinux *fwLinux = (FileWatcherLinux *)params; // build the directory tree before listening for events Directory *dirTree = fwLinux->buildDirTree(fwLinux->getPath()); std::cout << "i finished building" << std::endl; // check that the directory can be watched before trying to watch it if (dirTree == NULL) { // throw error if the directory didn't exists return NULL; } std::cout << "start watching" << std::endl; fwLinux->setDirTree(dirTree); fwLinux->startWatchTree(dirTree); fwLinux->processEvents(); return NULL; } void FileWatcherLinux::processEvents() { size_t count = sizeof(struct inotify_event) + NAME_MAX + 1; char *buffer = new char[1024*count]; int watchDescriptor = -1; unsigned int bytesRead, position = 0, cookie = 0; Event lastMovedFromEvent; while(mWatchFiles && (bytesRead = read(mInotify, buffer, count)) > 0) { std::cout << "finish read" << std::endl; std::cout << position << std::endl << bytesRead << std::endl; inotify_event *inEvent; do { inEvent = (inotify_event *)(buffer + position); Event event; // if the event is not a moved to event and the cookie exists // we should reset the cookie and push the last moved from event if (cookie != 0 && inEvent->mask != IN_MOVED_TO) { cookie = 0; watchDescriptor = -1; mEventsQueue.push(lastMovedFromEvent); } std::cout << inEvent->mask << std::endl; bool isDir = inEvent->mask & IN_ISDIR; inEvent->mask = isDir ? inEvent->mask ^ IN_ISDIR : inEvent->mask; switch(inEvent->mask) { case IN_ATTRIB: case IN_MODIFY: std::cout << "changed" <<std::endl; addEvent("CHANGED", inEvent); break; case IN_CREATE: { std::cout << "created" <<std::endl; // check stats on the item CREATED // if it is a dir, create a watch for all of its directories if (isDir) { Directory *parent = mWDtoDirNode[inEvent->wd]; std::string newPath = parent->path + "/" + parent->name + "/" + inEvent->name; // add the directory tree Directory *child = buildDirTree(newPath); if (child == NULL) break; parent->childDirectories[child->name] = child; startWatchTree(child); } addEvent("CREATED", inEvent); break; } case IN_DELETE: std::cout << "deleted" <<std::endl; if (isDir) { Directory *parent = mWDtoDirNode[inEvent->wd]; Directory *child = parent->childDirectories[inEvent->name]; parent->childDirectories.erase(child->name); destroyWatchTree(child); child = NULL; } addEvent("DELETED", inEvent); break; case IN_MOVED_FROM: std::cout << "moved from" <<std::endl; fd_set checkWD; FD_ZERO(&checkWD); FD_SET(mInotify, &checkWD); timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 250000; if (position + sizeof(struct inotify_event) + inEvent->len < bytesRead || select(mInotify+1, &checkWD, 0, 0, &timeout) > 0) { lastMovedFromEvent.action = "DELETED"; lastMovedFromEvent.directory = mWDtoDirNode[inEvent->wd]->path; lastMovedFromEvent.file = new std::string(inEvent->name); cookie = inEvent->cookie; watchDescriptor = inEvent->wd; } else { addEvent("DELETED", inEvent); } break; case IN_MOVED_TO: std::cout << "moved to" <<std::endl; // check if this is a move event if (cookie != 0 && inEvent->cookie == cookie && inEvent->wd == watchDescriptor) { cookie = 0; watchDescriptor = -1; event.action = "RENAMED"; event.directory = mWDtoDirNode[inEvent->wd]->path; event.file = new std::string[2]; event.file[0] = *lastMovedFromEvent.file; event.file[1] = inEvent->name; delete lastMovedFromEvent.file; mEventsQueue.push(event); std::cout << "renamed" <<std::endl; } else { addEvent("CREATED", inEvent); } break; } std::cout << "finished one parse" << std::endl; } while ((position += sizeof(struct inotify_event) + inEvent->len) < bytesRead); std::cout << "finish parse events" << std::endl; std::cout << position << std::endl << bytesRead << std::endl; position = 0; } } bool FileWatcherLinux::start() { mInotify = inotify_init(); if (mInotify < 0) { return false; } if (mWatchFiles && pthread_create(&mThread, 0, &FileWatcherLinux::mainLoop, (void *)this)) { return true; } else { return false; } } void FileWatcherLinux::startWatchTree(Directory *tree) { std::queue<Directory *> dirQueue; dirQueue.push(tree); while (!dirQueue.empty()) { Directory *root = dirQueue.front(); root->watchDescriptor = inotify_add_watch( mInotify, (root->path + "/" + root->name).c_str(), IN_ATTRIB | IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO ); if (root->watchDescriptor < 0) { // error return; // ? } mWDtoDirNode[root->watchDescriptor] = root; // find all the directories within this directory // this breaks the alphabetical sorting of directories for (std::map<std::string, Directory *>::iterator dirIter = root->childDirectories.begin(); dirIter != root->childDirectories.end(); ++dirIter) { dirQueue.push(dirIter->second); } dirQueue.pop(); } } void FileWatcherLinux::stop() {} void FileWatcherLinux::setDirTree(Directory *tree) { mDirTree = tree; } } <commit_msg>removed debug statements<commit_after>#include "../includes/FileWatcherLinux.h" namespace NSFW { FileWatcherLinux::FileWatcherLinux(std::string path, std::queue<Event> &eventsQueue, bool &watchFiles) : mEventsQueue(eventsQueue), mInotify(0), mPath(path), mWatchFiles(watchFiles) {} FileWatcherLinux::~FileWatcherLinux() {} void FileWatcherLinux::addEvent(std::string action, inotify_event *inEvent) { Directory *parent = mWDtoDirNode[inEvent->wd]; addEvent(action, parent->path + "/" + parent->name, new std::string(inEvent->name)); } void FileWatcherLinux::addEvent(std::string action, std::string directory, std::string *file) { Event event; event.action = action; event.directory = directory; event.file = file; mEventsQueue.push(event); } Directory *FileWatcherLinux::buildDirTree(std::string path) { std::queue<Directory *> dirQueue; Directory *topRoot = new Directory; // create root of snapshot if (path[path.length() - 1] == '/') { path = path.substr(0, path.length() - 1); } size_t lastSlash = path.find_last_of("/"); if (lastSlash != std::string::npos) { topRoot->name = path.substr(lastSlash + 1); topRoot->path = path.substr(0, lastSlash); } else { topRoot->name = ""; topRoot->path = "/"; } topRoot->watchDescriptor = -1; dirQueue.push(topRoot); bool checkRootOnExit = false; while (!dirQueue.empty()) { Directory *root = dirQueue.front(); dirent ** directoryContents = NULL; std::string fullPath = root->path + "/" + root->name; int n = scandir(fullPath.c_str(), &directoryContents, NULL, alphasort); if (n < 0) { if (topRoot == root) { return NULL; // top directory no longer exists } else { checkRootOnExit = true; dirQueue.pop(); continue; } } // find all the directories within this directory // this breaks the alphabetical sorting of directories for (int i = 0; i < n; ++i) { if (!strcmp(directoryContents[i]->d_name, ".") || !strcmp(directoryContents[i]->d_name, "..")) { continue; // skip navigation folder } // Certain *nix do not support dirent->d_type and may return DT_UNKOWN for every file returned in scandir // in order to make this work on all *nix, we need to stat the file to determine if it is a directory std::string filePath = root->path + "/" + root->name + "/" + directoryContents[i]->d_name; struct stat file; if (stat(filePath.c_str(), &file) < 0) { continue; } if (S_ISDIR(file.st_mode)) { // create the directory struct for this directory and add a reference of this directory to its root Directory *dir = new Directory; dir->path = root->path + "/" + root->name; dir->name = directoryContents[i]->d_name; dir->watchDescriptor = -1; root->childDirectories[dir->name] = dir; dirQueue.push(dir); } } for (int i = 0; i < n; ++i) { delete directoryContents[i]; } delete[] directoryContents; dirQueue.pop(); } if (checkRootOnExit) { struct stat rootStat; if (!stat((topRoot->path + "/" + topRoot->name).c_str(), &rootStat) || !S_ISDIR(rootStat.st_mode)) { // delete tree as far as we can go destroyDirTree(topRoot); return NULL; } } return topRoot; } void FileWatcherLinux::destroyDirTree(Directory *tree) { if (tree == NULL) return; std::queue<Directory *> dirQueue; dirQueue.push(tree); while (!dirQueue.empty()) { Directory *root = dirQueue.front(); // Add directories to the queue to continue listing events for (std::map<std::string, Directory *>::iterator dirIter = root->childDirectories.begin(); dirIter != root->childDirectories.end(); ++dirIter) { dirQueue.push(dirIter->second); } dirQueue.pop(); delete root; } } void FileWatcherLinux::destroyWatchTree(Directory *tree) { std::queue<Directory *> dirQueue; dirQueue.push(tree); if (fcntl(mInotify, F_GETFD) != -1 || errno != EBADF) { // need to pass errors back here so that the next call to poll // can clean up after this type of error return; // panic } while (!dirQueue.empty()) { Directory *root = dirQueue.front(); inotify_rm_watch(mInotify, root->watchDescriptor); // Add directories to the queue to continue listing events for (std::map<std::string, Directory *>::iterator dirIter = root->childDirectories.begin(); dirIter != root->childDirectories.end(); ++dirIter) { dirQueue.push(dirIter->second); } dirQueue.pop(); delete root; } } std::string FileWatcherLinux::getPath() { return mPath; } void *FileWatcherLinux::mainLoop(void *params) { FileWatcherLinux *fwLinux = (FileWatcherLinux *)params; // build the directory tree before listening for events Directory *dirTree = fwLinux->buildDirTree(fwLinux->getPath()); // check that the directory can be watched before trying to watch it if (dirTree == NULL) { // throw error if the directory didn't exists return NULL; } fwLinux->setDirTree(dirTree); fwLinux->startWatchTree(dirTree); fwLinux->processEvents(); return NULL; } void FileWatcherLinux::processEvents() { size_t count = sizeof(struct inotify_event) + NAME_MAX + 1; char *buffer = new char[1024*count]; int watchDescriptor = -1; unsigned int bytesRead, position = 0, cookie = 0; Event lastMovedFromEvent; while(mWatchFiles && (bytesRead = read(mInotify, buffer, count)) > 0) { inotify_event *inEvent; do { inEvent = (inotify_event *)(buffer + position); Event event; // if the event is not a moved to event and the cookie exists // we should reset the cookie and push the last moved from event if (cookie != 0 && inEvent->mask != IN_MOVED_TO) { cookie = 0; watchDescriptor = -1; mEventsQueue.push(lastMovedFromEvent); } bool isDir = inEvent->mask & IN_ISDIR; inEvent->mask = isDir ? inEvent->mask ^ IN_ISDIR : inEvent->mask; switch(inEvent->mask) { case IN_ATTRIB: case IN_MODIFY: addEvent("CHANGED", inEvent); break; case IN_CREATE: { // check stats on the item CREATED // if it is a dir, create a watch for all of its directories if (isDir) { Directory *parent = mWDtoDirNode[inEvent->wd]; std::string newPath = parent->path + "/" + parent->name + "/" + inEvent->name; // add the directory tree Directory *child = buildDirTree(newPath); if (child == NULL) break; parent->childDirectories[child->name] = child; startWatchTree(child); } addEvent("CREATED", inEvent); break; } case IN_DELETE: if (isDir) { Directory *parent = mWDtoDirNode[inEvent->wd]; Directory *child = parent->childDirectories[inEvent->name]; parent->childDirectories.erase(child->name); destroyWatchTree(child); child = NULL; } addEvent("DELETED", inEvent); break; case IN_MOVED_FROM: fd_set checkWD; FD_ZERO(&checkWD); FD_SET(mInotify, &checkWD); timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 250000; if (position + sizeof(struct inotify_event) + inEvent->len < bytesRead || select(mInotify+1, &checkWD, 0, 0, &timeout) > 0) { lastMovedFromEvent.action = "DELETED"; lastMovedFromEvent.directory = mWDtoDirNode[inEvent->wd]->path; lastMovedFromEvent.file = new std::string(inEvent->name); cookie = inEvent->cookie; watchDescriptor = inEvent->wd; } else { addEvent("DELETED", inEvent); } break; case IN_MOVED_TO: // check if this is a move event if (cookie != 0 && inEvent->cookie == cookie && inEvent->wd == watchDescriptor) { cookie = 0; watchDescriptor = -1; event.action = "RENAMED"; event.directory = mWDtoDirNode[inEvent->wd]->path; event.file = new std::string[2]; event.file[0] = *lastMovedFromEvent.file; event.file[1] = inEvent->name; delete lastMovedFromEvent.file; mEventsQueue.push(event); } else { addEvent("CREATED", inEvent); } break; } } while ((position += sizeof(struct inotify_event) + inEvent->len) < bytesRead); position = 0; } } bool FileWatcherLinux::start() { mInotify = inotify_init(); if (mInotify < 0) { return false; } if (mWatchFiles && pthread_create(&mThread, 0, &FileWatcherLinux::mainLoop, (void *)this)) { return true; } else { return false; } } void FileWatcherLinux::startWatchTree(Directory *tree) { std::queue<Directory *> dirQueue; dirQueue.push(tree); while (!dirQueue.empty()) { Directory *root = dirQueue.front(); root->watchDescriptor = inotify_add_watch( mInotify, (root->path + "/" + root->name).c_str(), IN_ATTRIB | IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO ); if (root->watchDescriptor < 0) { // error return; // ? } mWDtoDirNode[root->watchDescriptor] = root; // find all the directories within this directory // this breaks the alphabetical sorting of directories for (std::map<std::string, Directory *>::iterator dirIter = root->childDirectories.begin(); dirIter != root->childDirectories.end(); ++dirIter) { dirQueue.push(dirIter->second); } dirQueue.pop(); } } void FileWatcherLinux::stop() {} void FileWatcherLinux::setDirTree(Directory *tree) { mDirTree = tree; } } <|endoftext|>
<commit_before>#ifndef COMPONENTMANAGER_H #define COMPONENTMANAGER_H #include "components.hpp" #include "animationcomponent.hpp" #include "movecomponent.hpp" #include "rendercomponent.hpp" #include "inputcomponent.hpp" #include "tilecomponent.hpp" #include "sizecomponent.hpp" #include "namecomponent.hpp" #include "soundcomponent.hpp" #include "healthcomponent.hpp" #include "attackcomponent.hpp" #include "commandcomponent.hpp" #include "accelerationcomponent.hpp" #include "birdcomponent.hpp" typedef unsigned int ID; class ComponentManager { public: Components<MoveComponent> moveComponents; Components<RenderComponent> renderComponents; Components<InputComponent> inputComponents; Components<TileComponent> tileComponents; Components<SizeComponent> sizeComponents; Components<NameComponent> nameComponents; Components<SoundComponent> soundComponents; Components<AnimationComponent> animationComponents; Components<HealthComponent> healthComponents; Components<AttackComponent> attackComponents; Components<CommandComponent> commandComponents; Components<AccelerationComponent> accelerationComponents; Components<BirdComponent> birdComponents; //Components<MoveComponent> moveComponentsDiff; //Components<RenderComponent> renderComponentsDiff; MoveComponent& createMoveComponent(const ID id) { return moveComponents[id] = MoveComponent(); } RenderComponent& createRenderComponent(const ID id) { return renderComponents[id] = RenderComponent(); } InputComponent& createInputComponent(const ID id) { return inputComponents[id] = InputComponent(); } TileComponent& createTileComponent(const ID id) { return tileComponents[id] = TileComponent(); } SizeComponent& createSizeComponent(const ID id) { return sizeComponents[id] = SizeComponent(); } NameComponent& createNameComponent(const ID id) { return nameComponents[id] = NameComponent(); } SoundComponent& createSoundComponent(const ID id) { return soundComponents[id] = SoundComponent(); } AnimationComponent& createAnimationComponent(const ID id) { return animationComponents[id] = AnimationComponent(); } HealthComponent& createHealthComponent(const ID id) { return healthComponents[id] = HealthComponent(); } AttackComponent& createAttackComponent(const ID id) { return attackComponents[id] = AttackComponent(); } CommandComponent& createCommandComponent(const ID id) { return commandComponents[id] = CommandComponent(); } AccelerationComponent& createAccelerationComponent(const ID id) { return accelerationComponents[id] = AccelerationComponent(); } BirdComponent& createBirdComponent(const ID id) { return birdComponents[id] = BirdComponent(); } static constexpr uint sizePerEntity() { return sizeof(MoveComponent) + sizeof(RenderComponent) + sizeof(InputComponent) + sizeof(TileComponent) + sizeof(SizeComponent) + sizeof(NameComponent) + sizeof(SoundComponent) + sizeof(AnimationComponent) + sizeof(HealthComponent) + sizeof(AttackComponent) + sizeof(CommandComponent) + sizeof(AccelerationComponent); } void clearComponents(ID id); }; #endif //COMPONENTMANAGER_H <commit_msg>fixed bug where BirdComponent wasnt counted in sizePerEntity<commit_after>#ifndef COMPONENTMANAGER_H #define COMPONENTMANAGER_H #include "components.hpp" #include "animationcomponent.hpp" #include "movecomponent.hpp" #include "rendercomponent.hpp" #include "inputcomponent.hpp" #include "tilecomponent.hpp" #include "sizecomponent.hpp" #include "namecomponent.hpp" #include "soundcomponent.hpp" #include "healthcomponent.hpp" #include "attackcomponent.hpp" #include "commandcomponent.hpp" #include "accelerationcomponent.hpp" #include "birdcomponent.hpp" typedef unsigned int ID; class ComponentManager { public: Components<MoveComponent> moveComponents; Components<RenderComponent> renderComponents; Components<InputComponent> inputComponents; Components<TileComponent> tileComponents; Components<SizeComponent> sizeComponents; Components<NameComponent> nameComponents; Components<SoundComponent> soundComponents; Components<AnimationComponent> animationComponents; Components<HealthComponent> healthComponents; Components<AttackComponent> attackComponents; Components<CommandComponent> commandComponents; Components<AccelerationComponent> accelerationComponents; Components<BirdComponent> birdComponents; //Components<MoveComponent> moveComponentsDiff; //Components<RenderComponent> renderComponentsDiff; MoveComponent& createMoveComponent(const ID id) { return moveComponents[id] = MoveComponent(); } RenderComponent& createRenderComponent(const ID id) { return renderComponents[id] = RenderComponent(); } InputComponent& createInputComponent(const ID id) { return inputComponents[id] = InputComponent(); } TileComponent& createTileComponent(const ID id) { return tileComponents[id] = TileComponent(); } SizeComponent& createSizeComponent(const ID id) { return sizeComponents[id] = SizeComponent(); } NameComponent& createNameComponent(const ID id) { return nameComponents[id] = NameComponent(); } SoundComponent& createSoundComponent(const ID id) { return soundComponents[id] = SoundComponent(); } AnimationComponent& createAnimationComponent(const ID id) { return animationComponents[id] = AnimationComponent(); } HealthComponent& createHealthComponent(const ID id) { return healthComponents[id] = HealthComponent(); } AttackComponent& createAttackComponent(const ID id) { return attackComponents[id] = AttackComponent(); } CommandComponent& createCommandComponent(const ID id) { return commandComponents[id] = CommandComponent(); } AccelerationComponent& createAccelerationComponent(const ID id) { return accelerationComponents[id] = AccelerationComponent(); } BirdComponent& createBirdComponent(const ID id) { return birdComponents[id] = BirdComponent(); } static constexpr uint sizePerEntity() { return sizeof(MoveComponent) + sizeof(RenderComponent) + sizeof(InputComponent) + sizeof(TileComponent) + sizeof(SizeComponent) + sizeof(NameComponent) + sizeof(SoundComponent) + sizeof(AnimationComponent) + sizeof(HealthComponent) + sizeof(AttackComponent) + sizeof(CommandComponent) + sizeof(AccelerationComponent) + sizeof(BirdComponent); } void clearComponents(ID id); }; #endif //COMPONENTMANAGER_H <|endoftext|>
<commit_before>/* * _aaaa, _aa. sa, aaa _aaaa,_ ac .aa. .aa. .aa, _a, sa * .wWV!!!T |Wm; dQ[ $WF _mWT!"?Y ]QE :Q#: ]QW[ :WWk. ]Q[ dW * .jWf :WW: .dQ[ dQ[ .mW( )WE :Q#: .mSQh. :mWQa.]W[ dQ * |QW: :Wm; mQ[ dQ[ ]Qk )Qmi_aQW: <B:$Qc :WBWQ()W[ dQ * |W#: .ww ;WW; dQ[ dQ[ ....... ]Qk )QB?YYW#: jf ]Qp.:mE)Qm]Q[ )W * +WQ; :Wm |Wm; .mQ[ dQ[ :qgggggga ]Qm. ]WE :Q# :=QasuQm;:Wk 3QQW[ )Y * ]Wmi.:Wm +$Q; .mW( dQ[ !"!!"!!^ dQk, ._ ]WE :Q# :3D"!!$Qc.Wk -$WQ[ * "?????? ` "?!=m?! ??' -??????! -?! -?? -?' "?"-?" "??' "? * * Copyright (c) 2004 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of darkbits nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GCN_GRAPHICS_HPP #define GCN_GRAPHICS_HPP #include "guichan/cliprectangle.hpp" #include "guichan/color.hpp" #include "guichan/image.hpp" #include <stack> #include <string> namespace gcn { class Font; /** * This is the graphics object used for drawing in the Gui-chan library. * It contains all vital member functions for drawing. The class is abstract * and should be overloaded, to create graphic drivers to specific platforms. * We have included graphic drivers for some common platforms, like the SDL * library and the Allegro library. * * In the graphics object you can set clip areas to limit drawing to certain * areas of the screen. Clip areas are put on a stack, which means that you * can push smaller and smaller clip areas onto the stack. All coordinates * will be relative to the topmost clip area. In most cases you won't have * to worry about the clip areas, unless you want to implement some really * complex widget. Pushing and poping of clip areas are handled automatically * by container widgets when their child widgets are drawn. * * IMPORTANT: Remember to pop each clip area that you pushed on the stack * after you are done with it. * * If you feel that the graphics object is to restrictive for your needs, * there is nothing stopping you from using your own code for drawing, for * example with a library like SDL. However, this might hurt the portability * of your application. * * If you implement a new graphics driver for a platform we don't support, * we would be very pleased to add it to Gui-chan. * * @see AllegroGraphics, OpenGLGraphics, SDLGraphics, Image */ class Graphics { public: Graphics(); virtual ~Graphics() { } /** * This function is called by the Gui class when Gui::draw() is * called. It is needed by some graphics objects to perform * preparations before they draw (for example, OpenGLGraphics). * * NOTE: You will never need to call this function yourself, the * Gui object will do it for you. * * @see _endDraw, Gui::draw */ virtual void _beginDraw() { } /** * This function is called by the Gui class when a Gui::draw() is * done. It should reset any state changes made by _beginDraw(). * * NOTE: You will never need to call this function yourself, the * Gui object will do it for you. * * @see _beginDraw, Gui::draw */ virtual void _endDraw() { } /** * This function pushes a clip area onto the stack. The x and y * coordinates in the Rectangle will be relative to the last * pushed clip area. If the new area falls outside the current * clip area it will be clipped as necessary. * * @param area the clip area to be pushed onto the stack. * @return false if the the new area lays totally outside the * current clip area. Note that an empty clip area * will be pused in this case. * @see Rectangle */ virtual bool pushClipArea(Rectangle area); /** * Removes the topmost clip area from the stack. * * @throws Exception if the stack is empty when calling this function. */ virtual void popClipArea(); /** * Draws a part of an image. Note that the width and height * arguments will not scale the image, but specifies the size * of the part to be drawn. If you want to draw the whole image * there is a simplified version of this function. * * EXAMPLE: drawImage(myImage, 10, 10, 20, 20, 40, 40); * will draw a rectangular piece of myImage starting at coordinate * (10, 10) in myImage, with width and height 40. The piece will be * drawn with it's top left corner at coordinate (20, 20). * * @param image the image to draw. * @param srcX source image x coordinate * @param srcY source image y coordinate * @param dstX destination x coordinate * @param dstY destination y coordinate * @param width the width of the piece * @param height the height of the piece * @see Image */ virtual void drawImage(const Image* image, int srcX, int srcY, int dstX, int dstY, int width, int height) = 0; /** * This is a simplified version of the other drawImage. It will * draw a whole image at the coordinate you specify. It is equivalent * to calling: * drawImage(myImage, 0, 0, dstX, dstY, image->getWidth(), image->getHeight()); * * @see drawImage */ virtual void drawImage(const Image* image, int dstX, int dstY); /** * This function draws a single point (pixel). * * @param x the x coordinate * @param y the y coordinate */ virtual void drawPoint(int x, int y) = 0; /** * This function draws a line. * * @param x1 the first x coordinate * @param y1 the first y coordinate * @param x2 the second x coordinate * @param y2 the second y coordinate */ virtual void drawLine(int x1, int y1, int x2, int y2) = 0; /** * This function draws a simple, non-filled, rectangle with one pixel border. * * @param rectangle the rectangle to draw * @see Rectangle */ virtual void drawRectangle(const Rectangle& rectangle) = 0; /** * This function draws a filled rectangle. * * @param rectangle the filled rectangle to draw * @see Rectangle */ virtual void fillRectangle(const Rectangle& rectangle) = 0; /** * @see Color */ virtual void setColor(const Color& color); // /** // * // */ // void setHorizontalGradient(const Color& color1, const Color& color2){} // /** // * // */ // void setVerticalGradient(const Color& color1, const Color& color2){} /** * */ virtual void setFont(Font* font); /** * */ virtual void drawText(const std::string& text, const int x, const int y); // /** // * // */ // virtual void drawTextCenter(const std::string& text, const int x, const int y) = 0; // /** // * // */ // void setBlender(const std::string blenderMode){} protected: std::stack<ClipRectangle> mClipStack; Color mColor; Font* mFont; }; // end graphics } // end gcn #endif // end GCN_GRAPHICS_HPP /* * yakslem - "little cake on cake, but that's the fall" * finalman - "skall jag skriva det?" * yakslem - "ja, varfor inte?" */ <commit_msg>Change drawText so it uses Font::drawString<commit_after>/* * _aaaa, _aa. sa, aaa _aaaa,_ ac .aa. .aa. .aa, _a, sa * .wWV!!!T |Wm; dQ[ $WF _mWT!"?Y ]QE :Q#: ]QW[ :WWk. ]Q[ dW * .jWf :WW: .dQ[ dQ[ .mW( )WE :Q#: .mSQh. :mWQa.]W[ dQ * |QW: :Wm; mQ[ dQ[ ]Qk )Qmi_aQW: <B:$Qc :WBWQ()W[ dQ * |W#: .ww ;WW; dQ[ dQ[ ....... ]Qk )QB?YYW#: jf ]Qp.:mE)Qm]Q[ )W * +WQ; :Wm |Wm; .mQ[ dQ[ :qgggggga ]Qm. ]WE :Q# :=QasuQm;:Wk 3QQW[ )Y * ]Wmi.:Wm +$Q; .mW( dQ[ !"!!"!!^ dQk, ._ ]WE :Q# :3D"!!$Qc.Wk -$WQ[ * "?????? ` "?!=m?! ??' -??????! -?! -?? -?' "?"-?" "??' "? * * Copyright (c) 2004 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of darkbits nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GCN_GRAPHICS_HPP #define GCN_GRAPHICS_HPP #include "guichan/cliprectangle.hpp" #include "guichan/color.hpp" #include "guichan/image.hpp" #include <stack> #include <string> namespace gcn { class Font; /** * This is the graphics object used for drawing in the Gui-chan library. * It contains all vital member functions for drawing. The class is abstract * and should be overloaded, to create graphic drivers to specific platforms. * We have included graphic drivers for some common platforms, like the SDL * library and the Allegro library. * * In the graphics object you can set clip areas to limit drawing to certain * areas of the screen. Clip areas are put on a stack, which means that you * can push smaller and smaller clip areas onto the stack. All coordinates * will be relative to the topmost clip area. In most cases you won't have * to worry about the clip areas, unless you want to implement some really * complex widget. Pushing and poping of clip areas are handled automatically * by container widgets when their child widgets are drawn. * * IMPORTANT: Remember to pop each clip area that you pushed on the stack * after you are done with it. * * If you feel that the graphics object is to restrictive for your needs, * there is nothing stopping you from using your own code for drawing, for * example with a library like SDL. However, this might hurt the portability * of your application. * * If you implement a new graphics driver for a platform we don't support, * we would be very pleased to add it to Gui-chan. * * @see AllegroGraphics, OpenGLGraphics, SDLGraphics, Image */ class Graphics { public: Graphics(); virtual ~Graphics() { } /** * This function is called by the Gui class when Gui::draw() is * called. It is needed by some graphics objects to perform * preparations before they draw (for example, OpenGLGraphics). * * NOTE: You will never need to call this function yourself, the * Gui object will do it for you. * * @see _endDraw, Gui::draw */ virtual void _beginDraw() { } /** * This function is called by the Gui class when a Gui::draw() is * done. It should reset any state changes made by _beginDraw(). * * NOTE: You will never need to call this function yourself, the * Gui object will do it for you. * * @see _beginDraw, Gui::draw */ virtual void _endDraw() { } /** * This function pushes a clip area onto the stack. The x and y * coordinates in the Rectangle will be relative to the last * pushed clip area. If the new area falls outside the current * clip area it will be clipped as necessary. * * @param area the clip area to be pushed onto the stack. * @return false if the the new area lays totally outside the * current clip area. Note that an empty clip area * will be pused in this case. * @see Rectangle */ virtual bool pushClipArea(Rectangle area); /** * Removes the topmost clip area from the stack. * * @throws Exception if the stack is empty when calling this function. */ virtual void popClipArea(); /** * Draws a part of an image. Note that the width and height * arguments will not scale the image, but specifies the size * of the part to be drawn. If you want to draw the whole image * there is a simplified version of this function. * * EXAMPLE: drawImage(myImage, 10, 10, 20, 20, 40, 40); * will draw a rectangular piece of myImage starting at coordinate * (10, 10) in myImage, with width and height 40. The piece will be * drawn with it's top left corner at coordinate (20, 20). * * @param image the image to draw. * @param srcX source image x coordinate * @param srcY source image y coordinate * @param dstX destination x coordinate * @param dstY destination y coordinate * @param width the width of the piece * @param height the height of the piece * @see Image */ virtual void drawImage(const Image* image, int srcX, int srcY, int dstX, int dstY, int width, int height) = 0; /** * This is a simplified version of the other drawImage. It will * draw a whole image at the coordinate you specify. It is equivalent * to calling: * drawImage(myImage, 0, 0, dstX, dstY, image->getWidth(), image->getHeight()); * * @see drawImage */ virtual void drawImage(const Image* image, int dstX, int dstY); /** * This function draws a single point (pixel). * * @param x the x coordinate * @param y the y coordinate */ virtual void drawPoint(int x, int y) = 0; /** * This function draws a line. * * @param x1 the first x coordinate * @param y1 the first y coordinate * @param x2 the second x coordinate * @param y2 the second y coordinate */ virtual void drawLine(int x1, int y1, int x2, int y2) = 0; /** * This function draws a simple, non-filled, rectangle with one pixel border. * * @param rectangle the rectangle to draw * @see Rectangle */ virtual void drawRectangle(const Rectangle& rectangle) = 0; /** * This function draws a filled rectangle. * * @param rectangle the filled rectangle to draw * @see Rectangle */ virtual void fillRectangle(const Rectangle& rectangle) = 0; /** * @see Color */ virtual void setColor(const Color& color); // /** // * // */ // void setHorizontalGradient(const Color& color1, const Color& color2){} // /** // * // */ // void setVerticalGradient(const Color& color1, const Color& color2){} /** * */ virtual void setFont(Font* font); /** * */ virtual void drawText(const std::string& text, int x, int y); // /** // * // */ // virtual void drawTextCenter(const std::string& text, const int x, const int y) = 0; // /** // * // */ // void setBlender(const std::string blenderMode){} protected: std::stack<ClipRectangle> mClipStack; Color mColor; Font* mFont; }; // end graphics } // end gcn #endif // end GCN_GRAPHICS_HPP /* * yakslem - "little cake on cake, but that's the fall" * finalman - "skall jag skriva det?" * yakslem - "ja, varfor inte?" */ <|endoftext|>
<commit_before>// // MIT License // // Copyright (c) 2017 Thibault Martinez // // 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. // // #pragma once #include <iostream> #include <cpr/cpr.h> #include <json.hpp> using json = nlohmann::json; namespace IOTA { namespace API { class Service { public: Service(const std::string& host, const unsigned int& port); virtual ~Service(); public: template <typename Request, typename Response, typename... Args> Response request(Args&&... args) const { auto request = Request(args...); json data; request.serialize(data); auto url = cpr::Url{ "http://" + host_ + ":" + std::to_string(port_) }; auto body = cpr::Body{ data.dump() }; auto headers = cpr::Header{ { "Content-Type", "text/json" }, { "Content-Length", std::to_string(body.size()) } }; auto res = cpr::Post(url, body, headers); Response response; response.deserialize(json::parse(res.text)); response.setStatusCode(res.status_code); return response; } private: std::string host_; unsigned int port_; }; } // namespace API } // namespace IOTA <commit_msg>text/json to application/json<commit_after>// // MIT License // // Copyright (c) 2017 Thibault Martinez // // 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. // // #pragma once #include <iostream> #include <cpr/cpr.h> #include <json.hpp> using json = nlohmann::json; namespace IOTA { namespace API { class Service { public: Service(const std::string& host, const unsigned int& port); virtual ~Service(); public: template <typename Request, typename Response, typename... Args> Response request(Args&&... args) const { auto request = Request(args...); json data; request.serialize(data); auto url = cpr::Url{ "http://" + host_ + ":" + std::to_string(port_) }; auto body = cpr::Body{ data.dump() }; auto headers = cpr::Header{ { "Content-Type", "application/json" }, { "Content-Length", std::to_string(body.size()) } }; auto res = cpr::Post(url, body, headers); Response response; response.deserialize(json::parse(res.text)); response.setStatusCode(res.status_code); return response; } private: std::string host_; unsigned int port_; }; } // namespace API } // namespace IOTA <|endoftext|>
<commit_before>#pragma once #include <string> #include <stdexcept> #include <cstdint> #include <utility> #include <iostream> #include "optional.hpp" namespace jest { namespace detail { struct default_test {}; } /* TODO: Access to test data? */ template <typename T, size_t N> void test() { throw detail::default_test{}; } namespace detail { using failure = std::string; using optional_failure = optional<optional<failure>>; struct tally_results { size_t const total, failed; }; void log_failure(size_t const n, std::string const &msg) { std::cerr << " test " << n << " failure: " << msg << std::endl; } void log_success(size_t const n) { std::cerr << " test " << n << " success" << std::endl; } template <typename Group, size_t TN> optional_failure test_impl(Group &g) { try { g.test<TN>(); return {{}}; } catch(std::exception const &e) { return {{ e.what() }}; } catch(default_test) { return {}; } catch(...) { return {{ "unknown exception thrown" }}; } } template <typename Group, size_t... Ns> tally_results run_impl(Group &g, std::string const &name, std::integer_sequence<size_t, Ns...>) { std::cerr << "running group '" + name << "'" << std::endl; optional_failure const results[]{ test_impl<Group, Ns>(g)... }; size_t total{}, failed{}; for(size_t i{}; i < sizeof...(Ns); ++i) { if(results[i]) { ++total; if(results[i].value()) { log_failure(i, results[i].value().value()); ++failed; } else { log_success(i); } } } std::cerr << "finished group '" + name << "'\n" << std::endl; return { total, failed }; } } } <commit_msg>Fixed clang-specific errors on OS X<commit_after>#pragma once #include <string> #include <stdexcept> #include <cstdint> #include <utility> #include <iostream> #include "optional.hpp" namespace jest { namespace detail { struct default_test {}; } /* TODO: Access to test data? */ template <typename T, size_t N> void test() { throw detail::default_test{}; } namespace detail { using failure = std::string; using optional_failure = optional<optional<failure>>; struct tally_results { size_t const total, failed; }; void log_failure(size_t const n, std::string const &msg) { std::cerr << " test " << n << " failure: " << msg << std::endl; } void log_success(size_t const n) { std::cerr << " test " << n << " success" << std::endl; } template <typename Group, size_t TN> optional_failure test_impl(Group &g) { try { g.template test<TN>(); return {{}}; } catch(std::exception const &e) { return {{ e.what() }}; } catch(default_test) { return {}; } catch(...) { return {{ "unknown exception thrown" }}; } } template <typename Group, size_t... Ns> tally_results run_impl(Group &g, std::string const &name, std::integer_sequence<size_t, Ns...>) { std::cerr << "running group '" + name << "'" << std::endl; optional_failure const results[]{ test_impl<Group, Ns>(g)... }; size_t total{}, failed{}; for(size_t i{}; i < sizeof...(Ns); ++i) { if(results[i]) { ++total; if(results[i].value()) { log_failure(i, results[i].value().value()); ++failed; } else { log_success(i); } } } std::cerr << "finished group '" + name << "'\n" << std::endl; return { total, failed }; } } } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #include <string> #include <fstream> #include <iostream> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/lexical_cast.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { // DEBUG API namespace fs = boost::filesystem; struct logger { logger(fs::path const& filename, int instance, bool append = true) { fs::path dir(fs::complete("libtorrent_logs" + boost::lexical_cast<std::string>(instance))); if (!fs::exists(dir)) fs::create_directories(dir); m_file.open((dir / filename).string().c_str(), std::ios_base::out | (append ? std::ios_base::app : std::ios_base::out)); *this << "\n\n\n*** starting log ***\n"; } template <class T> logger& operator<<(T const& v) { m_file << v; m_file.flush(); return *this; } std::ofstream m_file; }; } #endif // TORRENT_DEBUG_HPP_INCLUDED <commit_msg>fixes issue whith failure to create logs causes libtorrent to quit, fixes ticket #168<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #include <string> #include <fstream> #include <iostream> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/lexical_cast.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { // DEBUG API namespace fs = boost::filesystem; struct logger { logger(fs::path const& filename, int instance, bool append = true) { try { fs::path dir(fs::complete("libtorrent_logs" + boost::lexical_cast<std::string>(instance))); if (!fs::exists(dir)) fs::create_directories(dir); m_file.open((dir / filename).string().c_str(), std::ios_base::out | (append ? std::ios_base::app : std::ios_base::out)); *this << "\n\n\n*** starting log ***\n"; } catch (std::exception& e) { std::cerr << "failed to create log '" << filename << "': " << e.what() << std::endl; } } template <class T> logger& operator<<(T const& v) { m_file << v; m_file.flush(); return *this; } std::ofstream m_file; }; } #endif // TORRENT_DEBUG_HPP_INCLUDED <|endoftext|>
<commit_before>// KMail startup and initialize code // Author: Stefan Taferner <[email protected]> #include <config.h> #include <kuniqueapplication.h> #include <kglobal.h> #include <knotifyclient.h> #include <dcopclient.h> #include "kmkernel.h" //control center #include <kcmdlineargs.h> #include <qtimer.h> #undef Status // stupid X headers #include "aboutdata.h" #include "kmstartup.h" // OLD about text. This is horrbly outdated. /*const char* aboutText = "KMail [" KMAIL_VERSION "] by\n\n" "Stefan Taferner <[email protected]>,\n" "Markus Wbben <[email protected]>\n\n" "based on the work of:\n" "Lynx <[email protected]>,\n" "Stephan Meyer <[email protected]>,\n" "and the above authors.\n\n" "This program is covered by the GPL.\n\n" "Please send bugreports to [email protected]"; */ static KCmdLineOptions kmoptions[] = { { "s", 0 , 0 }, { "subject <subject>", I18N_NOOP("Set subject of message."), 0 }, { "c", 0 , 0 }, { "cc <address>", I18N_NOOP("Send CC: to 'address'."), 0 }, { "b", 0 , 0 }, { "bcc <address>", I18N_NOOP("Send BCC: to 'address'."), 0 }, { "h", 0 , 0 }, { "header <header>", I18N_NOOP("Add 'header' to message."), 0 }, { "msg <file>", I18N_NOOP("Read message body from 'file'."), 0 }, { "body <text>", I18N_NOOP("Set body of message."), 0 }, { "attach <url>", I18N_NOOP("Add an attachment to the mail. This can be repeated."), 0 }, { "check", I18N_NOOP("Only check for new mail."), 0 }, { "composer", I18N_NOOP("Only open composer window."), 0 }, { "+[address]", I18N_NOOP("Send message to 'address'."), 0 }, // { "+[file]", I18N_NOOP("Show message from file 'file'."), 0 }, { 0, 0, 0} }; //----------------------------------------------------------------------------- class KMailApplication : public KUniqueApplication { public: KMailApplication() : KUniqueApplication() { }; virtual int newInstance(); void commitData(QSessionManager& sm); }; void KMailApplication::commitData(QSessionManager& sm) { kmkernel->dumpDeadLetters(); kmkernel->setShuttingDown( true ); // Prevent further dumpDeadLetters calls KApplication::commitData( sm ); } int KMailApplication::newInstance() { QString to, cc, bcc, subj, body; KURL messageFile = QString::null; KURL::List attachURLs; bool mailto = false; bool checkMail = false; //bool viewOnly = false; if (dcopClient()->isSuspended()) { // Try again later. QTimer::singleShot( 100, this, SLOT(newInstance()) ); return 0; } // process args: KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->getOption("subject")) { mailto = true; subj = QString::fromLocal8Bit(args->getOption("subject")); } if (args->getOption("cc")) { mailto = true; cc = QString::fromLocal8Bit(args->getOption("cc")); } if (args->getOption("bcc")) { mailto = true; bcc = QString::fromLocal8Bit(args->getOption("bcc")); } if (args->getOption("msg")) { mailto = true; messageFile.setPath( QString::fromLocal8Bit(args->getOption("msg")) ); } if (args->getOption("body")) { mailto = true; body = QString::fromLocal8Bit(args->getOption("body")); } QCStringList attachList = args->getOptionList("attach"); if (!attachList.isEmpty()) { mailto = true; for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it ) if ( !(*it).isEmpty() ) attachURLs += KURL( QString::fromLocal8Bit( *it ) ); } if (args->isSet("composer")) mailto = true; if (args->isSet("check")) checkMail = true; for(int i= 0; i < args->count(); i++) { if (!to.isEmpty()) to += ", "; if (strncasecmp(args->arg(i),"mailto:",7)==0) to += args->url(i).path(); else to += QString::fromLocal8Bit( args->arg(i) ); mailto = true; } args->clear(); if (!kmkernel->firstInstance() || !kapp->isRestored()) kmkernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs); kmkernel->setFirstInstance(FALSE); return 0; } int main(int argc, char *argv[]) { // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging // a bit harder: You should pass --nofork as commandline argument when using // a debugger. In gdb you can do this by typing "set args --nofork" before // typing "run". KMail::AboutData about; KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options if (!KMailApplication::start()) return 0; KMailApplication app; // import i18n data from libraries: KMail::insertLibraryCatalogues(); // Check that all updates have been run on the config file: KMail::checkConfigUpdates(); // Make sure that the KNotify Daemon is running (this is necessary for people // using KMail without KDE) KNotifyClient::startDaemon(); KMail::lockOrDie(); kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet //local, do the init KMKernel kmailKernel; kmailKernel.init(); kapp->dcopClient()->setDefaultObject( kmailKernel.objId() ); // and session management kmailKernel.doSessionManagement(); // any dead letters? kmailKernel.recoverDeadLetters(); kmsetSignalHandler(kmsignalHandler); kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests. kmkernel->setStartingUp( false ); // Starting up is finished // Go! int ret = kapp->exec(); // clean up if (kmkernel->shuttingDown()) kmailKernel.notClosedByUser(); else kmailKernel.cleanup(); KMail::cleanup(); return ret; } <commit_msg>Make it possible to pass a URL to kmail without the --attachment flag. According to Laurent this is done automatically in case a file is dropped on the KMail icon in Kicker. Based on patch by Laurent Montel.<commit_after>// -*- mode: C++; c-file-style: "gnu" -*- // KMail startup and initialize code // Author: Stefan Taferner <[email protected]> #include <config.h> #include <kuniqueapplication.h> #include <kglobal.h> #include <knotifyclient.h> #include <dcopclient.h> #include "kmkernel.h" //control center #include <kcmdlineargs.h> #include <qtimer.h> #undef Status // stupid X headers #include "aboutdata.h" #include "kmstartup.h" // OLD about text. This is horrbly outdated. /*const char* aboutText = "KMail [" KMAIL_VERSION "] by\n\n" "Stefan Taferner <[email protected]>,\n" "Markus Wbben <[email protected]>\n\n" "based on the work of:\n" "Lynx <[email protected]>,\n" "Stephan Meyer <[email protected]>,\n" "and the above authors.\n\n" "This program is covered by the GPL.\n\n" "Please send bugreports to [email protected]"; */ static KCmdLineOptions kmoptions[] = { { "s", 0 , 0 }, { "subject <subject>", I18N_NOOP("Set subject of message."), 0 }, { "c", 0 , 0 }, { "cc <address>", I18N_NOOP("Send CC: to 'address'."), 0 }, { "b", 0 , 0 }, { "bcc <address>", I18N_NOOP("Send BCC: to 'address'."), 0 }, { "h", 0 , 0 }, { "header <header>", I18N_NOOP("Add 'header' to message."), 0 }, { "msg <file>", I18N_NOOP("Read message body from 'file'."), 0 }, { "body <text>", I18N_NOOP("Set body of message."), 0 }, { "attach <url>", I18N_NOOP("Add an attachment to the mail. This can be repeated."), 0 }, { "check", I18N_NOOP("Only check for new mail."), 0 }, { "composer", I18N_NOOP("Only open composer window."), 0 }, { "+[address|URL]", I18N_NOOP("Send message to 'address' resp. " "attach the file the 'URL' points " "to."), 0 }, // { "+[file]", I18N_NOOP("Show message from file 'file'."), 0 }, { 0, 0, 0} }; //----------------------------------------------------------------------------- class KMailApplication : public KUniqueApplication { public: KMailApplication() : KUniqueApplication() { }; virtual int newInstance(); void commitData(QSessionManager& sm); }; void KMailApplication::commitData(QSessionManager& sm) { kmkernel->dumpDeadLetters(); kmkernel->setShuttingDown( true ); // Prevent further dumpDeadLetters calls KApplication::commitData( sm ); } int KMailApplication::newInstance() { QString to, cc, bcc, subj, body; KURL messageFile = QString::null; KURL::List attachURLs; bool mailto = false; bool checkMail = false; //bool viewOnly = false; if (dcopClient()->isSuspended()) { // Try again later. QTimer::singleShot( 100, this, SLOT(newInstance()) ); return 0; } // process args: KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->getOption("subject")) { mailto = true; subj = QString::fromLocal8Bit(args->getOption("subject")); } if (args->getOption("cc")) { mailto = true; cc = QString::fromLocal8Bit(args->getOption("cc")); } if (args->getOption("bcc")) { mailto = true; bcc = QString::fromLocal8Bit(args->getOption("bcc")); } if (args->getOption("msg")) { mailto = true; messageFile.setPath( QString::fromLocal8Bit(args->getOption("msg")) ); } if (args->getOption("body")) { mailto = true; body = QString::fromLocal8Bit(args->getOption("body")); } QCStringList attachList = args->getOptionList("attach"); if (!attachList.isEmpty()) { mailto = true; for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it ) if ( !(*it).isEmpty() ) attachURLs += KURL( QString::fromLocal8Bit( *it ) ); } if (args->isSet("composer")) mailto = true; if (args->isSet("check")) checkMail = true; for(int i= 0; i < args->count(); i++) { if (strncasecmp(args->arg(i),"mailto:",7)==0) to += args->url(i).path() + ", "; else { QString tmpArg = QString::fromLocal8Bit( args->arg(i) ); KURL url( tmpArg ); if ( url.isValid() ) attachURLs += url; else to += tmpArg + ", "; } mailto = true; } if ( !to.isEmpty() ) { // cut off the superfluous trailing ", " to.truncate( to.length() - 2 ); } args->clear(); if (!kmkernel->firstInstance() || !kapp->isRestored()) kmkernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs); kmkernel->setFirstInstance(FALSE); return 0; } int main(int argc, char *argv[]) { // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging // a bit harder: You should pass --nofork as commandline argument when using // a debugger. In gdb you can do this by typing "set args --nofork" before // typing "run". KMail::AboutData about; KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options if (!KMailApplication::start()) return 0; KMailApplication app; // import i18n data from libraries: KMail::insertLibraryCatalogues(); // Check that all updates have been run on the config file: KMail::checkConfigUpdates(); // Make sure that the KNotify Daemon is running (this is necessary for people // using KMail without KDE) KNotifyClient::startDaemon(); KMail::lockOrDie(); kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet //local, do the init KMKernel kmailKernel; kmailKernel.init(); kapp->dcopClient()->setDefaultObject( kmailKernel.objId() ); // and session management kmailKernel.doSessionManagement(); // any dead letters? kmailKernel.recoverDeadLetters(); kmsetSignalHandler(kmsignalHandler); kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests. kmkernel->setStartingUp( false ); // Starting up is finished // Go! int ret = kapp->exec(); // clean up if (kmkernel->shuttingDown()) kmailKernel.notClosedByUser(); else kmailKernel.cleanup(); KMail::cleanup(); return ret; } <|endoftext|>
<commit_before>// KMail startup and initialize code // Author: Stefan Taferner <[email protected]> #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <errno.h> #include <sys/types.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <qtimer.h> #include <kuniqueapplication.h> #include <klocale.h> #include <kglobal.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> #include <knotifyclient.h> #include <dcopclient.h> #include <kcrash.h> #include "kmkernel.h" //control center #undef Status // stupid X headers #include "kmailIface_stub.h" // to call control center of master kmail #include <kaboutdata.h> #include "kmversion.h" // OLD about text. This is horrbly outdated. /*const char* aboutText = "KMail [" KMAIL_VERSION "] by\n\n" "Stefan Taferner <[email protected]>,\n" "Markus Wbben <[email protected]>\n\n" "based on the work of:\n" "Lynx <[email protected]>,\n" "Stephan Meyer <[email protected]>,\n" "and the above authors.\n\n" "This program is covered by the GPL.\n\n" "Please send bugreports to [email protected]"; */ static KCmdLineOptions kmoptions[] = { { "s", 0 , 0 }, { "subject <subject>", I18N_NOOP("Set subject of message."), 0 }, { "c", 0 , 0 }, { "cc <address>", I18N_NOOP("Send CC: to 'address'."), 0 }, { "b", 0 , 0 }, { "bcc <address>", I18N_NOOP("Send BCC: to 'address'."), 0 }, { "h", 0 , 0 }, { "header <header>", I18N_NOOP("Add 'header' to message."), 0 }, { "msg <file>", I18N_NOOP("Read message body from 'file'."), 0 }, { "body <text>", I18N_NOOP("Set body of message."), 0 }, { "attach <url>", I18N_NOOP("Add an attachment to the mail. This can be repeated."), 0 }, { "check", I18N_NOOP("Only check for new mail."), 0 }, { "composer", I18N_NOOP("Only open composer window."), 0 }, { "+[address]", I18N_NOOP("Send message to 'address'."), 0 }, // { "+[file]", I18N_NOOP("Show message from file 'file'."), 0 }, { 0, 0, 0} }; //----------------------------------------------------------------------------- extern "C" { static void setSignalHandler(void (*handler)(int)); // Crash recovery signal handler static void signalHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); ::exit(-1); // } // Crash recovery signal handler static void crashHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); // Return to DrKonqi. } //----------------------------------------------------------------------------- static void setSignalHandler(void (*handler)(int)) { signal(SIGKILL, handler); signal(SIGTERM, handler); signal(SIGHUP, handler); KCrash::setEmergencySaveFunction(crashHandler); } } //----------------------------------------------------------------------------- class KMailApplication : public KUniqueApplication { public: KMailApplication() : KUniqueApplication() { }; virtual int newInstance(); void commitData(QSessionManager& sm) { kernel->notClosedByUser(); KApplication::commitData( sm ); } }; int KMailApplication::newInstance() { QString to, cc, bcc, subj, body; KURL messageFile = QString::null; KURL::List attachURLs; bool mailto = false; bool checkMail = false; //bool viewOnly = false; // process args: KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->getOption("subject")) { mailto = true; subj = QString::fromLocal8Bit(args->getOption("subject")); } if (args->getOption("cc")) { mailto = true; cc = QString::fromLocal8Bit(args->getOption("cc")); } if (args->getOption("bcc")) { mailto = true; bcc = QString::fromLocal8Bit(args->getOption("bcc")); } if (args->getOption("msg")) { mailto = true; messageFile = QString::fromLocal8Bit(args->getOption("msg")); } if (args->getOption("body")) { mailto = true; body = QString::fromLocal8Bit(args->getOption("body")); } QCStringList attachList = args->getOptionList("attach"); if (!attachList.isEmpty()) { mailto = true; for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it ) if ( !(*it).isEmpty() ) attachURLs += KURL( QString::fromLocal8Bit( *it ) ); } if (args->isSet("composer")) mailto = true; if (args->isSet("check")) checkMail = true; for(int i= 0; i < args->count(); i++) { if (!to.isEmpty()) to += ", "; if (strncasecmp(args->arg(i),"mailto:",7)==0) to += args->arg(i); else to += args->arg(i); mailto = true; } args->clear(); if (!kernel->firstInstance() || !kapp->isRestored()) kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs); kernel->setFirstInstance(FALSE); return 0; } namespace { QString getMyHostName(void) { char hostNameC[256]; // null terminate this C string hostNameC[255] = 0; // set the string to 0 length if gethostname fails if(gethostname(hostNameC, 255)) hostNameC[0] = 0; return QString::fromLocal8Bit(hostNameC); } } static void checkConfigUpdates() { #if KDE_VERSION >= 306 KConfig * config = kapp->config(); const QString updateFile = QString::fromLatin1("kmail.upd"); QStringList updates; updates << "9" << "3.1-update-identities" << "3.1-use-identity-uoids"; for ( QStringList::const_iterator it = updates.begin() ; it != updates.end() ; ++it ) config->checkUpdate( *it, updateFile ); #endif } int main(int argc, char *argv[]) { // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging // a bit harder: You should pass --nofork as commandline argument when using // a debugger. In gdb you can do this by typing "set args --nofork" before // typing "run". KAboutData about("kmail", I18N_NOOP("KMail"), KMAIL_VERSION, I18N_NOOP("The KDE Email client."), KAboutData::License_GPL, I18N_NOOP("(c) 1997-2002, The KMail developers"), 0, "http://kmail.kde.org"); about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "[email protected]" ); about.addAuthor( "Don Sanders", I18N_NOOP("Core developer and former maintainer"), "[email protected]" ); about.addAuthor( "Stefan Taferner ", I18N_NOOP("Original author"), "[email protected]" ); about.addAuthor( "Ingo Kl\303\266cker", I18N_NOOP("Encryption"), "[email protected]" ); about.addAuthor( "Marc Mutz", I18N_NOOP("Core developer"), "[email protected]" ); about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "[email protected]" ); about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "[email protected]" ); about.addAuthor( "Toyohiro Asukai", 0, "[email protected]" ); about.addAuthor( "Waldo Bastian", 0, "[email protected]" ); about.addAuthor( "Carsten Burghardt", 0, "[email protected]" ); about.addAuthor( "Steven Brown", 0, "[email protected]" ); about.addAuthor( "Cristi Dumitrescu", 0, "[email protected]" ); about.addAuthor( "Philippe Fremy", 0, "[email protected]" ); about.addAuthor( "Kurt Granroth", 0, "[email protected]" ); about.addAuthor( "Heiko Hund", 0, "[email protected]" ); about.addAuthor( "Igor Janssen", 0, "[email protected]" ); about.addAuthor( "Matt Johnston", 0, "[email protected]" ); about.addAuthor( "Christer Kaivo-oja", 0, "[email protected]" ); about.addAuthor( "Lars Knoll", 0, "[email protected]" ); about.addAuthor( "J. Nick Koston", 0, "[email protected]" ); about.addAuthor( "Stephan Kulow", 0, "[email protected]" ); about.addAuthor( "Guillaume Laurent", 0, "[email protected]" ); about.addAuthor( "Sam Magnuson", 0, "[email protected]" ); about.addAuthor( "Laurent Montel", 0, "[email protected]" ); about.addAuthor( "Matt Newell", 0, "[email protected]" ); about.addAuthor( "Denis Perchine", 0, "[email protected]" ); about.addAuthor( "Samuel Penn", 0, "[email protected]" ); about.addAuthor( "Carsten Pfeiffer", 0, "[email protected]" ); about.addAuthor( "Sven Radej", 0, "[email protected]" ); about.addAuthor( "Mark Roberts", 0, "[email protected]" ); about.addAuthor( "Wolfgang Rohdewald", 0, "[email protected]" ); about.addAuthor( "Espen Sand", 0, "[email protected]" ); about.addAuthor( "Jan Simonson", 0, "[email protected]" ); about.addAuthor( "George Staikos", 0, "[email protected]" ); about.addAuthor( "Jason Stephenson", 0, "[email protected]" ); about.addAuthor( "Jacek Stolarczyk", 0, "[email protected]" ); about.addAuthor( "Roberto S. Teixeira", 0, "[email protected]" ); about.addAuthor( "Ronen Tzur", 0, "[email protected]" ); about.addAuthor( "Mario Weilguni", 0, "[email protected]" ); about.addAuthor( "Wynn Wilkes", 0, "[email protected]" ); about.addAuthor( "Robert D. Williams", 0, "[email protected]" ); about.addAuthor( "Markus Wuebben", 0, "[email protected]" ); about.addAuthor( "Thorsten Zachmann", 0, "[email protected]" ); about.addAuthor( "Karl-Heinz Zimmer", 0, "[email protected]" ); KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options if (!KMailApplication::start()) return 0; KMailApplication app; KGlobal::locale()->insertCatalogue("libkdenetwork"); // Check that all updates have been run on the config file: checkConfigUpdates(); // Check and create a lock file to prevent concurrent access to kmail files const QString lockLocation = locateLocal("appdata", "lock"); KSimpleConfig config(lockLocation); int oldPid = config.readNumEntry("pid", -1); const QString oldHostName = config.readEntry("hostname"); const QString hostName = getMyHostName(); // proceed if there is no lock at present if (oldPid != -1 && // proceed if the lock is our pid, or if the lock is from the same host oldPid != getpid() && hostName != oldHostName && // proceed if the pid doesn't exist (kill(oldPid, 0) != -1 || errno != ESRCH)) { QString msg = i18n("Only one instance of KMail can be run at " "any one time. It is already running on a different display " "with PID %1 on host %2 according to the lock file located " "at %3.").arg(oldPid).arg(oldHostName).arg(lockLocation); KNotifyClient::userEvent( msg, KNotifyClient::Messagebox, KNotifyClient::Error ); fprintf(stderr, "*** KMail is already running with PID %d on host %s\n", oldPid, oldHostName.local8Bit().data()); return 1; } config.writeEntry("pid", getpid()); config.writeEntry("hostname", hostName); config.sync(); kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet //local, do the init KMKernel kmailKernel; kmailKernel.init(); kapp->dcopClient()->setDefaultObject( kmailKernel.objId() ); // and session management kmailKernel.doSessionManagement(); // any dead letters? kmailKernel.recoverDeadLetters(); setSignalHandler(signalHandler); kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests. // Go! int ret = kapp->exec(); // clean up kmailKernel.cleanup(); config.writeEntry("pid", -1); config.sync(); return ret; } <commit_msg>Restore my position as a maintainer. Because:<commit_after>// KMail startup and initialize code // Author: Stefan Taferner <[email protected]> #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <errno.h> #include <sys/types.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <qtimer.h> #include <kuniqueapplication.h> #include <klocale.h> #include <kglobal.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> #include <knotifyclient.h> #include <dcopclient.h> #include <kcrash.h> #include "kmkernel.h" //control center #undef Status // stupid X headers #include "kmailIface_stub.h" // to call control center of master kmail #include <kaboutdata.h> #include "kmversion.h" // OLD about text. This is horrbly outdated. /*const char* aboutText = "KMail [" KMAIL_VERSION "] by\n\n" "Stefan Taferner <[email protected]>,\n" "Markus Wbben <[email protected]>\n\n" "based on the work of:\n" "Lynx <[email protected]>,\n" "Stephan Meyer <[email protected]>,\n" "and the above authors.\n\n" "This program is covered by the GPL.\n\n" "Please send bugreports to [email protected]"; */ static KCmdLineOptions kmoptions[] = { { "s", 0 , 0 }, { "subject <subject>", I18N_NOOP("Set subject of message."), 0 }, { "c", 0 , 0 }, { "cc <address>", I18N_NOOP("Send CC: to 'address'."), 0 }, { "b", 0 , 0 }, { "bcc <address>", I18N_NOOP("Send BCC: to 'address'."), 0 }, { "h", 0 , 0 }, { "header <header>", I18N_NOOP("Add 'header' to message."), 0 }, { "msg <file>", I18N_NOOP("Read message body from 'file'."), 0 }, { "body <text>", I18N_NOOP("Set body of message."), 0 }, { "attach <url>", I18N_NOOP("Add an attachment to the mail. This can be repeated."), 0 }, { "check", I18N_NOOP("Only check for new mail."), 0 }, { "composer", I18N_NOOP("Only open composer window."), 0 }, { "+[address]", I18N_NOOP("Send message to 'address'."), 0 }, // { "+[file]", I18N_NOOP("Show message from file 'file'."), 0 }, { 0, 0, 0} }; //----------------------------------------------------------------------------- extern "C" { static void setSignalHandler(void (*handler)(int)); // Crash recovery signal handler static void signalHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); ::exit(-1); // } // Crash recovery signal handler static void crashHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); // Return to DrKonqi. } //----------------------------------------------------------------------------- static void setSignalHandler(void (*handler)(int)) { signal(SIGKILL, handler); signal(SIGTERM, handler); signal(SIGHUP, handler); KCrash::setEmergencySaveFunction(crashHandler); } } //----------------------------------------------------------------------------- class KMailApplication : public KUniqueApplication { public: KMailApplication() : KUniqueApplication() { }; virtual int newInstance(); void commitData(QSessionManager& sm) { kernel->notClosedByUser(); KApplication::commitData( sm ); } }; int KMailApplication::newInstance() { QString to, cc, bcc, subj, body; KURL messageFile = QString::null; KURL::List attachURLs; bool mailto = false; bool checkMail = false; //bool viewOnly = false; // process args: KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->getOption("subject")) { mailto = true; subj = QString::fromLocal8Bit(args->getOption("subject")); } if (args->getOption("cc")) { mailto = true; cc = QString::fromLocal8Bit(args->getOption("cc")); } if (args->getOption("bcc")) { mailto = true; bcc = QString::fromLocal8Bit(args->getOption("bcc")); } if (args->getOption("msg")) { mailto = true; messageFile = QString::fromLocal8Bit(args->getOption("msg")); } if (args->getOption("body")) { mailto = true; body = QString::fromLocal8Bit(args->getOption("body")); } QCStringList attachList = args->getOptionList("attach"); if (!attachList.isEmpty()) { mailto = true; for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it ) if ( !(*it).isEmpty() ) attachURLs += KURL( QString::fromLocal8Bit( *it ) ); } if (args->isSet("composer")) mailto = true; if (args->isSet("check")) checkMail = true; for(int i= 0; i < args->count(); i++) { if (!to.isEmpty()) to += ", "; if (strncasecmp(args->arg(i),"mailto:",7)==0) to += args->arg(i); else to += args->arg(i); mailto = true; } args->clear(); if (!kernel->firstInstance() || !kapp->isRestored()) kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs); kernel->setFirstInstance(FALSE); return 0; } namespace { QString getMyHostName(void) { char hostNameC[256]; // null terminate this C string hostNameC[255] = 0; // set the string to 0 length if gethostname fails if(gethostname(hostNameC, 255)) hostNameC[0] = 0; return QString::fromLocal8Bit(hostNameC); } } static void checkConfigUpdates() { #if KDE_VERSION >= 306 KConfig * config = kapp->config(); const QString updateFile = QString::fromLatin1("kmail.upd"); QStringList updates; updates << "9" << "3.1-update-identities" << "3.1-use-identity-uoids"; for ( QStringList::const_iterator it = updates.begin() ; it != updates.end() ; ++it ) config->checkUpdate( *it, updateFile ); #endif } int main(int argc, char *argv[]) { // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging // a bit harder: You should pass --nofork as commandline argument when using // a debugger. In gdb you can do this by typing "set args --nofork" before // typing "run". KAboutData about("kmail", I18N_NOOP("KMail"), KMAIL_VERSION, I18N_NOOP("The KDE Email client."), KAboutData::License_GPL, I18N_NOOP("(c) 1997-2002, The KMail developers"), 0, "http://kmail.kde.org"); about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "[email protected]" ); about.addAuthor( "Don Sanders", I18N_NOOP("Core developer and maintainer"), "[email protected]" ); about.addAuthor( "Stefan Taferner ", I18N_NOOP("Original author"), "[email protected]" ); about.addAuthor( "Ingo Kl\303\266cker", I18N_NOOP("Encryption"), "[email protected]" ); about.addAuthor( "Marc Mutz", I18N_NOOP("Core developer"), "[email protected]" ); about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "[email protected]" ); about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "[email protected]" ); about.addAuthor( "Toyohiro Asukai", 0, "[email protected]" ); about.addAuthor( "Waldo Bastian", 0, "[email protected]" ); about.addAuthor( "Carsten Burghardt", 0, "[email protected]" ); about.addAuthor( "Steven Brown", 0, "[email protected]" ); about.addAuthor( "Cristi Dumitrescu", 0, "[email protected]" ); about.addAuthor( "Philippe Fremy", 0, "[email protected]" ); about.addAuthor( "Kurt Granroth", 0, "[email protected]" ); about.addAuthor( "Heiko Hund", 0, "[email protected]" ); about.addAuthor( "Igor Janssen", 0, "[email protected]" ); about.addAuthor( "Matt Johnston", 0, "[email protected]" ); about.addAuthor( "Christer Kaivo-oja", 0, "[email protected]" ); about.addAuthor( "Lars Knoll", 0, "[email protected]" ); about.addAuthor( "J. Nick Koston", 0, "[email protected]" ); about.addAuthor( "Stephan Kulow", 0, "[email protected]" ); about.addAuthor( "Guillaume Laurent", 0, "[email protected]" ); about.addAuthor( "Sam Magnuson", 0, "[email protected]" ); about.addAuthor( "Laurent Montel", 0, "[email protected]" ); about.addAuthor( "Matt Newell", 0, "[email protected]" ); about.addAuthor( "Denis Perchine", 0, "[email protected]" ); about.addAuthor( "Samuel Penn", 0, "[email protected]" ); about.addAuthor( "Carsten Pfeiffer", 0, "[email protected]" ); about.addAuthor( "Sven Radej", 0, "[email protected]" ); about.addAuthor( "Mark Roberts", 0, "[email protected]" ); about.addAuthor( "Wolfgang Rohdewald", 0, "[email protected]" ); about.addAuthor( "Espen Sand", 0, "[email protected]" ); about.addAuthor( "Jan Simonson", 0, "[email protected]" ); about.addAuthor( "George Staikos", 0, "[email protected]" ); about.addAuthor( "Jason Stephenson", 0, "[email protected]" ); about.addAuthor( "Jacek Stolarczyk", 0, "[email protected]" ); about.addAuthor( "Roberto S. Teixeira", 0, "[email protected]" ); about.addAuthor( "Ronen Tzur", 0, "[email protected]" ); about.addAuthor( "Mario Weilguni", 0, "[email protected]" ); about.addAuthor( "Wynn Wilkes", 0, "[email protected]" ); about.addAuthor( "Robert D. Williams", 0, "[email protected]" ); about.addAuthor( "Markus Wuebben", 0, "[email protected]" ); about.addAuthor( "Thorsten Zachmann", 0, "[email protected]" ); about.addAuthor( "Karl-Heinz Zimmer", 0, "[email protected]" ); KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options if (!KMailApplication::start()) return 0; KMailApplication app; KGlobal::locale()->insertCatalogue("libkdenetwork"); // Check that all updates have been run on the config file: checkConfigUpdates(); // Check and create a lock file to prevent concurrent access to kmail files const QString lockLocation = locateLocal("appdata", "lock"); KSimpleConfig config(lockLocation); int oldPid = config.readNumEntry("pid", -1); const QString oldHostName = config.readEntry("hostname"); const QString hostName = getMyHostName(); // proceed if there is no lock at present if (oldPid != -1 && // proceed if the lock is our pid, or if the lock is from the same host oldPid != getpid() && hostName != oldHostName && // proceed if the pid doesn't exist (kill(oldPid, 0) != -1 || errno != ESRCH)) { QString msg = i18n("Only one instance of KMail can be run at " "any one time. It is already running on a different display " "with PID %1 on host %2 according to the lock file located " "at %3.").arg(oldPid).arg(oldHostName).arg(lockLocation); KNotifyClient::userEvent( msg, KNotifyClient::Messagebox, KNotifyClient::Error ); fprintf(stderr, "*** KMail is already running with PID %d on host %s\n", oldPid, oldHostName.local8Bit().data()); return 1; } config.writeEntry("pid", getpid()); config.writeEntry("hostname", hostName); config.sync(); kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet //local, do the init KMKernel kmailKernel; kmailKernel.init(); kapp->dcopClient()->setDefaultObject( kmailKernel.objId() ); // and session management kmailKernel.doSessionManagement(); // any dead letters? kmailKernel.recoverDeadLetters(); setSignalHandler(signalHandler); kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests. // Go! int ret = kapp->exec(); // clean up kmailKernel.cleanup(); config.writeEntry("pid", -1); config.sync(); return ret; } <|endoftext|>
<commit_before>/* Definition of the pqxx::stream_from class. * * pqxx::stream_from enables optimized batch reads from a database table. * * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/stream_from instead. * * Copyright (c) 2000-2021, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this * mistake, or contact the author. */ #ifndef PQXX_H_STREAM_FROM #define PQXX_H_STREAM_FROM #include "pqxx/compiler-public.hxx" #include "pqxx/internal/compiler-internal-pre.hxx" #include <cassert> #include <functional> #include <variant> #include "pqxx/except.hxx" #include "pqxx/internal/concat.hxx" #include "pqxx/internal/encoding_group.hxx" #include "pqxx/internal/stream_iterator.hxx" #include "pqxx/separated_list.hxx" #include "pqxx/transaction_base.hxx" #include "pqxx/transaction_focus.hxx" namespace pqxx { /// Pass this to a @c stream_from constructor to stream table contents. /** @deprecated Use stream_from::table() instead. */ constexpr from_table_t from_table; /// Pass this to a @c stream_from constructor to stream query results. /** @deprecated Use stream_from::query() instead. */ constexpr from_query_t from_query; /// Stream data from the database. /** Retrieving data this way is likely to be faster than executing a query and * then iterating and converting the rows fields. You will also be able to * start processing before all of the data has come in. * * There are also downsides. If there's an error, it may leave the entire * connection in an unusable state, so you'll have to give the whole thing up. * Also, your connection to the database may break before you've received all * the data, so you may end up processing only part of the data. Finally, * opening a stream puts the connection in a special state, so you won't be * able to do many other things with the connection or the transaction while * the stream is open. * * There are two ways of starting a stream: you stream either all rows in a * table (using one of the factories, @c table() or @c raw_table()), or the * results of a query (using the @c query() factory). * * Usually you'll want the @c stream convenience wrapper in transaction_base, * so you don't need to deal with this class directly. * * @warning While a stream is active, you cannot execute queries, open a * pipeline, etc. on the same transaction. A transaction can have at most one * object of a type derived from @c pqxx::transaction_focus active on it at a * time. */ class PQXX_LIBEXPORT stream_from : transaction_focus { public: using raw_line = std::pair<std::unique_ptr<char, std::function<void(char *)>>, std::size_t>; /// Factory: Execute query, and stream the results. /** The query can be a SELECT query or a VALUES query; or it can be an * UPDATE, INSERT, or DELETE with a RETURNING clause. * * The query is executed as part of a COPY statement, so there are additional * restrictions on what kind of query you can use here. See the PostgreSQL * documentation for the COPY command: * * https://www.postgresql.org/docs/current/sql-copy.html */ static stream_from query(transaction_base &tx, std::string_view q) { #include "pqxx/internal/ignore-deprecated-pre.hxx" return stream_from{tx, from_query, q}; #include "pqxx/internal/ignore-deprecated-post.hxx" } /** * @name Streaming data from tables * * You can use @c stream_from to read a table's contents. This is a quick * and easy way to read a table, but it comes with limitations. It cannot * stream from a view, only from a table. It does not support conditions. * And there are no guarantees about ordering. If you need any of those * things, consider streaming from a query instead. */ //@{ /// Factory: Stream data from a pre-quoted table and columns. /** Use this factory if you need to create multiple streams using the same * table path and/or columns list, and you want to save a bit of work on * composing the internal SQL statement for starting the stream. It lets you * compose the string representations for the table path and the columns * list, so you can compute these once and then re-use them later. * * @param tx The transaction within which the stream will operate. * @param path Name or path for the table upon which the stream will * operate. If any part of the table path may contain special * characters or be case-sensitive, quote the path using * pqxx::connection::quote_table(). * @param columns Columns which the stream will read. They should be * comma-separated and, if needed, quoted. You can produce the string * using pqxx::connection::quote_columns(). If you omit this argument, * the stream will read all columns in the table, in schema order. */ static stream_from raw_table( transaction_base &tx, std::string_view path, std::string_view columns = ""sv); /// Factory: Stream data from a given table. /** This is the convenient way to stream from a table. */ static stream_from table( transaction_base &tx, table_path path, std::initializer_list<std::string_view> columns = {}); //@} /// Execute query, and stream over the results. /** @deprecated Use factory function @c query() instead. */ PQXX_DEPRECATED("Use query() factory instead.") stream_from(transaction_base &, from_query_t, std::string_view query); /// Stream all rows in table, all columns. /** @deprecated Use factory function @c table() or @c raw_table() instead. */ PQXX_DEPRECATED("Use table() or raw_table() factory instead.") stream_from(transaction_base &, from_table_t, std::string_view table); /// Stream given columns from all rows in table. /** @deprecated Use factory function @c table() or @c raw_table() instead. */ template<typename Iter> PQXX_DEPRECATED("Use table() or raw_table() factory instead.") stream_from( transaction_base &, from_table_t, std::string_view table, Iter columns_begin, Iter columns_end); /// Stream given columns from all rows in table. /** @deprecated Use factory function @c query() instead. */ template<typename Columns> PQXX_DEPRECATED("Use table() or raw_table() factory instead.") stream_from( transaction_base &tx, from_table_t, std::string_view table, Columns const &columns); #include "pqxx/internal/ignore-deprecated-pre.hxx" /// @deprecated Use factory function @c table() or @c raw_table() instead. PQXX_DEPRECATED("Use the from_table_t overload instead.") stream_from(transaction_base &tx, std::string_view table) : stream_from{tx, from_table, table} {} #include "pqxx/internal/ignore-deprecated-post.hxx" /// @deprecated Use factory function @c table() or @c raw_table() instead. template<typename Columns> PQXX_DEPRECATED("Use the from_table_t overload instead.") stream_from( transaction_base &tx, std::string_view table, Columns const &columns) : stream_from{tx, from_table, table, columns} {} /// @deprecated Use factory function @c table() or @c raw_table() instead. template<typename Iter> PQXX_DEPRECATED("Use the from_table_t overload instead.") stream_from( transaction_base &, std::string_view table, Iter columns_begin, Iter columns_end); ~stream_from() noexcept; /// May this stream still produce more data? [[nodiscard]] operator bool() const noexcept { return not m_finished; } /// Has this stream produced all the data it is going to produce? [[nodiscard]] bool operator!() const noexcept { return m_finished; } /// Finish this stream. Call this before continuing to use the connection. /** Consumes all remaining lines, and closes the stream. * * This may take a while if you're abandoning the stream before it's done, so * skip it in error scenarios where you're not planning to use the connection * again afterwards. */ void complete(); /// Read one row into a tuple. /** Converts the row's fields into the fields making up the tuple. * * For a column which can contain nulls, be sure to give the corresponding * tuple field a type which can be null. For example, to read a field as * @c int when it may contain nulls, read it as @c std::optional<int>. * Using @c std::shared_ptr or @c std::unique_ptr will also work. */ template<typename Tuple> stream_from &operator>>(Tuple &); /// Doing this with a @c std::variant is going to be horrifically borked. template<typename... Vs> stream_from &operator>>(std::variant<Vs...> &) = delete; // TODO: Hide this from the public. /// Iterate over this stream. Supports range-based "for" loops. /** Produces an input iterator over the stream. * * Do not call this yourself. Use it like "for (auto data : stream.iter())". */ template<typename... TYPE> [[nodiscard]] auto iter() { return pqxx::internal::stream_input_iteration<TYPE...>{*this}; } /// Read a row. Return fields as views, valid until you read the next row. /** Returns @c nullptr when there are no more rows to read. Do not attempt * to read any further rows after that. * * Do not access the vector, or the storage referenced by the views, after * closing or completing the stream, or after attempting to read a next row. * * A @c pqxx::zview is like a @c std::string_view, but with the added * guarantee that if its data pointer is non-null, the string is followed by * a terminating zero (which falls just outside the view itself). * * If any of the views' data pointer is null, that means that the * corresponding SQL field is null. * * @warning The return type may change in the future, to support C++20 * coroutine-based usage. */ std::vector<zview> const *read_row(); /// Read a raw line of text from the COPY command. /** @warning Do not use this unless you really know what you're doing. */ raw_line get_raw_line(); private: // TODO: Clean up this signature once we cull the deprecated constructors. /// @deprecated stream_from( transaction_base &tx, std::string_view table, std::string_view columns, from_table_t); // TODO: Clean up this signature once we cull the deprecated constructors. /// @deprecated stream_from( transaction_base &, std::string_view unquoted_table, std::string_view columns, from_table_t, int); template<typename Tuple, std::size_t... indexes> void extract_fields(Tuple &t, std::index_sequence<indexes...>) const { (extract_value<Tuple, indexes>(t), ...); } pqxx::internal::glyph_scanner_func *m_glyph_scanner; /// Current row's fields' text, combined into one reusable string. std::string m_row; /// The current row's fields. std::vector<zview> m_fields; bool m_finished = false; void close(); template<typename Tuple, std::size_t index> void extract_value(Tuple &) const; /// Read a line of COPY data, write @c m_row and @c m_fields. void parse_line(); }; template<typename Columns> inline stream_from::stream_from( transaction_base &tb, from_table_t, std::string_view table_name, Columns const &columns) : stream_from{ tb, from_table, table_name, std::begin(columns), std::end(columns)} {} template<typename Iter> inline stream_from::stream_from( transaction_base &tx, from_table_t, std::string_view table, Iter columns_begin, Iter columns_end) : stream_from{ tx, table, separated_list(",", columns_begin, columns_end), from_table, 1} {} template<typename Tuple> inline stream_from &stream_from::operator>>(Tuple &t) { if (m_finished) return *this; constexpr auto tup_size{std::tuple_size_v<Tuple>}; m_fields.reserve(tup_size); parse_line(); if (m_finished) return *this; if (std::size(m_fields) != tup_size) throw usage_error{internal::concat( "Tried to extract ", tup_size, " field(s) from a stream of ", std::size(m_fields), ".")}; extract_fields(t, std::make_index_sequence<tup_size>{}); return *this; } template<typename Tuple, std::size_t index> inline void stream_from::extract_value(Tuple &t) const { using field_type = strip_t<decltype(std::get<index>(t))>; using nullity = nullness<field_type>; assert(index < std::size(m_fields)); if constexpr (nullity::always_null) { if (m_fields[index].data() != nullptr) throw conversion_error{"Streaming non-null value into null field."}; } else if (m_fields[index].data() == nullptr) { if constexpr (nullity::has_null) std::get<index>(t) = nullity::null(); else internal::throw_null_conversion(type_name<field_type>); } else { // Don't ever try to convert a non-null value to nullptr_t! std::get<index>(t) = from_string<field_type>(m_fields[index]); } } } // namespace pqxx #include "pqxx/internal/compiler-internal-post.hxx" #endif <commit_msg>Retire a TODO.<commit_after>/* Definition of the pqxx::stream_from class. * * pqxx::stream_from enables optimized batch reads from a database table. * * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/stream_from instead. * * Copyright (c) 2000-2021, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this * mistake, or contact the author. */ #ifndef PQXX_H_STREAM_FROM #define PQXX_H_STREAM_FROM #include "pqxx/compiler-public.hxx" #include "pqxx/internal/compiler-internal-pre.hxx" #include <cassert> #include <functional> #include <variant> #include "pqxx/except.hxx" #include "pqxx/internal/concat.hxx" #include "pqxx/internal/encoding_group.hxx" #include "pqxx/internal/stream_iterator.hxx" #include "pqxx/separated_list.hxx" #include "pqxx/transaction_base.hxx" #include "pqxx/transaction_focus.hxx" namespace pqxx { /// Pass this to a @c stream_from constructor to stream table contents. /** @deprecated Use stream_from::table() instead. */ constexpr from_table_t from_table; /// Pass this to a @c stream_from constructor to stream query results. /** @deprecated Use stream_from::query() instead. */ constexpr from_query_t from_query; /// Stream data from the database. /** Retrieving data this way is likely to be faster than executing a query and * then iterating and converting the rows fields. You will also be able to * start processing before all of the data has come in. * * There are also downsides. If there's an error, it may leave the entire * connection in an unusable state, so you'll have to give the whole thing up. * Also, your connection to the database may break before you've received all * the data, so you may end up processing only part of the data. Finally, * opening a stream puts the connection in a special state, so you won't be * able to do many other things with the connection or the transaction while * the stream is open. * * There are two ways of starting a stream: you stream either all rows in a * table (using one of the factories, @c table() or @c raw_table()), or the * results of a query (using the @c query() factory). * * Usually you'll want the @c stream convenience wrapper in transaction_base, * so you don't need to deal with this class directly. * * @warning While a stream is active, you cannot execute queries, open a * pipeline, etc. on the same transaction. A transaction can have at most one * object of a type derived from @c pqxx::transaction_focus active on it at a * time. */ class PQXX_LIBEXPORT stream_from : transaction_focus { public: using raw_line = std::pair<std::unique_ptr<char, std::function<void(char *)>>, std::size_t>; /// Factory: Execute query, and stream the results. /** The query can be a SELECT query or a VALUES query; or it can be an * UPDATE, INSERT, or DELETE with a RETURNING clause. * * The query is executed as part of a COPY statement, so there are additional * restrictions on what kind of query you can use here. See the PostgreSQL * documentation for the COPY command: * * https://www.postgresql.org/docs/current/sql-copy.html */ static stream_from query(transaction_base &tx, std::string_view q) { #include "pqxx/internal/ignore-deprecated-pre.hxx" return stream_from{tx, from_query, q}; #include "pqxx/internal/ignore-deprecated-post.hxx" } /** * @name Streaming data from tables * * You can use @c stream_from to read a table's contents. This is a quick * and easy way to read a table, but it comes with limitations. It cannot * stream from a view, only from a table. It does not support conditions. * And there are no guarantees about ordering. If you need any of those * things, consider streaming from a query instead. */ //@{ /// Factory: Stream data from a pre-quoted table and columns. /** Use this factory if you need to create multiple streams using the same * table path and/or columns list, and you want to save a bit of work on * composing the internal SQL statement for starting the stream. It lets you * compose the string representations for the table path and the columns * list, so you can compute these once and then re-use them later. * * @param tx The transaction within which the stream will operate. * @param path Name or path for the table upon which the stream will * operate. If any part of the table path may contain special * characters or be case-sensitive, quote the path using * pqxx::connection::quote_table(). * @param columns Columns which the stream will read. They should be * comma-separated and, if needed, quoted. You can produce the string * using pqxx::connection::quote_columns(). If you omit this argument, * the stream will read all columns in the table, in schema order. */ static stream_from raw_table( transaction_base &tx, std::string_view path, std::string_view columns = ""sv); /// Factory: Stream data from a given table. /** This is the convenient way to stream from a table. */ static stream_from table( transaction_base &tx, table_path path, std::initializer_list<std::string_view> columns = {}); //@} /// Execute query, and stream over the results. /** @deprecated Use factory function @c query() instead. */ PQXX_DEPRECATED("Use query() factory instead.") stream_from(transaction_base &, from_query_t, std::string_view query); /// Stream all rows in table, all columns. /** @deprecated Use factory function @c table() or @c raw_table() instead. */ PQXX_DEPRECATED("Use table() or raw_table() factory instead.") stream_from(transaction_base &, from_table_t, std::string_view table); /// Stream given columns from all rows in table. /** @deprecated Use factory function @c table() or @c raw_table() instead. */ template<typename Iter> PQXX_DEPRECATED("Use table() or raw_table() factory instead.") stream_from( transaction_base &, from_table_t, std::string_view table, Iter columns_begin, Iter columns_end); /// Stream given columns from all rows in table. /** @deprecated Use factory function @c query() instead. */ template<typename Columns> PQXX_DEPRECATED("Use table() or raw_table() factory instead.") stream_from( transaction_base &tx, from_table_t, std::string_view table, Columns const &columns); #include "pqxx/internal/ignore-deprecated-pre.hxx" /// @deprecated Use factory function @c table() or @c raw_table() instead. PQXX_DEPRECATED("Use the from_table_t overload instead.") stream_from(transaction_base &tx, std::string_view table) : stream_from{tx, from_table, table} {} #include "pqxx/internal/ignore-deprecated-post.hxx" /// @deprecated Use factory function @c table() or @c raw_table() instead. template<typename Columns> PQXX_DEPRECATED("Use the from_table_t overload instead.") stream_from( transaction_base &tx, std::string_view table, Columns const &columns) : stream_from{tx, from_table, table, columns} {} /// @deprecated Use factory function @c table() or @c raw_table() instead. template<typename Iter> PQXX_DEPRECATED("Use the from_table_t overload instead.") stream_from( transaction_base &, std::string_view table, Iter columns_begin, Iter columns_end); ~stream_from() noexcept; /// May this stream still produce more data? [[nodiscard]] operator bool() const noexcept { return not m_finished; } /// Has this stream produced all the data it is going to produce? [[nodiscard]] bool operator!() const noexcept { return m_finished; } /// Finish this stream. Call this before continuing to use the connection. /** Consumes all remaining lines, and closes the stream. * * This may take a while if you're abandoning the stream before it's done, so * skip it in error scenarios where you're not planning to use the connection * again afterwards. */ void complete(); /// Read one row into a tuple. /** Converts the row's fields into the fields making up the tuple. * * For a column which can contain nulls, be sure to give the corresponding * tuple field a type which can be null. For example, to read a field as * @c int when it may contain nulls, read it as @c std::optional<int>. * Using @c std::shared_ptr or @c std::unique_ptr will also work. */ template<typename Tuple> stream_from &operator>>(Tuple &); /// Doing this with a @c std::variant is going to be horrifically borked. template<typename... Vs> stream_from &operator>>(std::variant<Vs...> &) = delete; /// Iterate over this stream. Supports range-based "for" loops. /** Produces an input iterator over the stream. * * Do not call this yourself. Use it like "for (auto data : stream.iter())". */ template<typename... TYPE> [[nodiscard]] auto iter() { return pqxx::internal::stream_input_iteration<TYPE...>{*this}; } /// Read a row. Return fields as views, valid until you read the next row. /** Returns @c nullptr when there are no more rows to read. Do not attempt * to read any further rows after that. * * Do not access the vector, or the storage referenced by the views, after * closing or completing the stream, or after attempting to read a next row. * * A @c pqxx::zview is like a @c std::string_view, but with the added * guarantee that if its data pointer is non-null, the string is followed by * a terminating zero (which falls just outside the view itself). * * If any of the views' data pointer is null, that means that the * corresponding SQL field is null. * * @warning The return type may change in the future, to support C++20 * coroutine-based usage. */ std::vector<zview> const *read_row(); /// Read a raw line of text from the COPY command. /** @warning Do not use this unless you really know what you're doing. */ raw_line get_raw_line(); private: // TODO: Clean up this signature once we cull the deprecated constructors. /// @deprecated stream_from( transaction_base &tx, std::string_view table, std::string_view columns, from_table_t); // TODO: Clean up this signature once we cull the deprecated constructors. /// @deprecated stream_from( transaction_base &, std::string_view unquoted_table, std::string_view columns, from_table_t, int); template<typename Tuple, std::size_t... indexes> void extract_fields(Tuple &t, std::index_sequence<indexes...>) const { (extract_value<Tuple, indexes>(t), ...); } pqxx::internal::glyph_scanner_func *m_glyph_scanner; /// Current row's fields' text, combined into one reusable string. std::string m_row; /// The current row's fields. std::vector<zview> m_fields; bool m_finished = false; void close(); template<typename Tuple, std::size_t index> void extract_value(Tuple &) const; /// Read a line of COPY data, write @c m_row and @c m_fields. void parse_line(); }; template<typename Columns> inline stream_from::stream_from( transaction_base &tb, from_table_t, std::string_view table_name, Columns const &columns) : stream_from{ tb, from_table, table_name, std::begin(columns), std::end(columns)} {} template<typename Iter> inline stream_from::stream_from( transaction_base &tx, from_table_t, std::string_view table, Iter columns_begin, Iter columns_end) : stream_from{ tx, table, separated_list(",", columns_begin, columns_end), from_table, 1} {} template<typename Tuple> inline stream_from &stream_from::operator>>(Tuple &t) { if (m_finished) return *this; constexpr auto tup_size{std::tuple_size_v<Tuple>}; m_fields.reserve(tup_size); parse_line(); if (m_finished) return *this; if (std::size(m_fields) != tup_size) throw usage_error{internal::concat( "Tried to extract ", tup_size, " field(s) from a stream of ", std::size(m_fields), ".")}; extract_fields(t, std::make_index_sequence<tup_size>{}); return *this; } template<typename Tuple, std::size_t index> inline void stream_from::extract_value(Tuple &t) const { using field_type = strip_t<decltype(std::get<index>(t))>; using nullity = nullness<field_type>; assert(index < std::size(m_fields)); if constexpr (nullity::always_null) { if (m_fields[index].data() != nullptr) throw conversion_error{"Streaming non-null value into null field."}; } else if (m_fields[index].data() == nullptr) { if constexpr (nullity::has_null) std::get<index>(t) = nullity::null(); else internal::throw_null_conversion(type_name<field_type>); } else { // Don't ever try to convert a non-null value to nullptr_t! std::get<index>(t) = from_string<field_type>(m_fields[index]); } } } // namespace pqxx #include "pqxx/internal/compiler-internal-post.hxx" #endif <|endoftext|>
<commit_before>#ifndef VSMC_HELPER_BASE_HPP #define VSMC_HELPER_BASE_HPP #include <vsmc/internal/common.hpp> #include <vsmc/helper/single_particle.hpp> namespace vsmc { namespace internal { /// \brief Particle::value_type subtype /// \ingroup Helper /// /// \tparam Dim The dimension of the state parameter vector /// \tparam T The type of the value of the state parameter vector template <unsigned Dim, typename T> class StateBase { public : /// The type of the number of particles typedef VSMC_SIZE_TYPE size_type; /// The type of state parameters typedef T state_type; /// The type of the matrix of states typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> state_mat_type; /// Construct a StateBase object with given number of particles explicit StateBase (size_type N) : size_(N), state_(Dim, N) {} virtual ~StateBase () {} /// The dimension of the problem static unsigned dim () { return Dim; } /// The number of particles size_type size () const { return size_; } /// \brief Read and write access to a signle particle state /// /// \param id The position of the particle /// \param pos The position of the parameter in the state array /// /// \return A reference to the parameter at position pos of the states /// array of the particle at position id state_type &state (size_type id, unsigned pos) { return state_(pos, id); } /// Read only access to a signle particle state const state_type &state (size_type id, unsigned pos) const { return state_(pos, id); } /// \brief Read and write access to the array of a single particle states /// /// \param id The position of the particle, 0 to size() - 1 state_type *state (size_type id) { return state_.col(id).data(); } /// Read only access to the array of a single particle states const state_type *state (size_type id) const { return state_.col(id).data(); } /// \brief Read and write access to the matrix of all particle states /// /// \note The matrix is of column marjor as it's the default of Eigen. /// Therefore state()(pos, id) == state(id, pos). Best avoid this feature. state_mat_type &state () { return state_; } /// Read only access to the matrix of all particle states const state_mat_type &state () const { return state_; } private : size_type size_; state_mat_type state_; }; // class StateBase template <typename T, typename Derived> class InitializeBase { public : unsigned initialize_state (SingleParticle<T> part) { return initialize_state_dispatch<Derived>(part, 0); } void initialize_param (Particle<T> &particle, void *param) { initialize_param_dispatch<Derived>(particle, param, 0); } void post_processor (Particle<T> &particle) { post_processor_dispatch<Derived>(particle, 0); } void pre_processor (Particle<T> &particle) { pre_processor_dispatch<Derived>(particle, 0); } private : template <typename D, unsigned (D::*) (SingleParticle<T>)> class initialize_state_sfinae_ {}; template <typename D, void (D::*) (Particle<T> &, void *)> class initialize_param_sfinae_ {}; template <typename D, void (D::*) (Particle<T> &)> class processor_sfinae_ {}; template <typename D> unsigned initialize_state_dispatch (SingleParticle<T> part, initialize_state_sfinae_<D, &D::initialize_state> *) { return static_cast<Derived *>(this)->initialize_state(part); } template <typename D> void initialize_param_dispatch (Particle<T> &particle, void *param, initialize_param_sfinae_<D, &D::initialize_param> *) { static_cast<Derived *>(this)->initialize_param(particle, param); } template <typename D> void pre_processor_dispatch (Particle<T> &particle, processor_sfinae_<D, &D::pre_processor> *) { static_cast<Derived *>(this)->pre_processor(particle); } template <typename D> void post_processor_dispatch (Particle<T> &particle, processor_sfinae_<D, &D::post_processor> *) { static_cast<Derived *>(this)->post_processor(particle); } template <typename D> unsigned initialize_state_dispatch (SingleParticle<T>, ...) { return 0; } template <typename D> void initialize_param_dispatch (Particle<T>, void *, ...) {} template <typename D> void pre_processor_dispatch (Particle<T> &, ...) {} template <typename D> void post_processor_dispatch (Particle<T> &, ...) {} }; // class InitializeBase template <typename T> class InitializeBase<T, internal::VBase> { public : virtual unsigned initialize_state (SingleParticle<T>) {return 0;} virtual void initialize_param (Particle<T> &, void *) {} virtual void post_processor (Particle<T> &) {} virtual void pre_processor (Particle<T> &) {} }; // class InitializeBase<T, internal::VBase> template <typename T, typename Derived> class MoveBase { public : unsigned move_state (unsigned iter, SingleParticle<T> part) { return move_state_dispatch<Derived>(iter, part, 0); } void post_processor (unsigned iter, Particle<T> &particle) { post_processor_dispatch<Derived>(iter, particle, 0); } void pre_processor (unsigned iter, Particle<T> &particle) { pre_processor_dispatch<Derived>(iter, particle, 0); } private : template <typename D, unsigned (D::*) (unsigned, SingleParticle<T>)> class move_state_sfinae_ {}; template <typename D, void (D::*) (unsigned, Particle<T> &)> class processor_sfinae_ {}; template <typename D> unsigned move_state_dispatch (unsigned iter, SingleParticle<T> part, move_state_sfinae_<D, &D::move_state> *) { return static_cast<Derived *>(this)->move_state(iter, part); } template <typename D> void pre_processor_dispatch (unsigned iter, Particle<T> &particle, processor_sfinae_<D, &D::pre_processor> *) { static_cast<Derived *>(this)->pre_processor(iter, particle); } template <typename D> void post_processor_dispatch (unsigned iter, Particle<T> &particle, processor_sfinae_<D, &D::post_processor> *) { static_cast<Derived *>(this)->post_processor(iter, particle); } template <typename D> unsigned move_state_dispatch (unsigned, SingleParticle<T>, ...) { return 0; } template <typename D> void pre_processor_dispatch (unsigned iter, Particle<T> &, ...) {} template <typename D> void post_processor_dispatch (unsigned iter, Particle<T> &, ...) {} }; // class MoveBase template <typename T> class MoveBase<T, internal::VBase> { public : virtual unsigned move_state (unsigned, SingleParticle<T>) {return 0;} virtual void post_processor (unsigned, Particle<T> &) {} virtual void pre_processor (unsigned, Particle<T> &) {} }; // class MoveBase<T, internal::VBase> template <typename T, typename Derived> class MonitorBase { public : void monitor_state (unsigned iter, ConstSingleParticle<T> part, double *res) { monitor_state_dispatch<Derived>(iter, part, res, 0); } void pre_processor (unsigned iter, const Particle<T> &particle) { pre_processor_dispatch<Derived>(iter, particle, 0); } void post_processor (unsigned iter, const Particle<T> &particle) { post_processor_dispatch<Derived>(iter, particle, 0); } private : template <typename D, void (D::*) (unsigned, ConstSingleParticle<T>, double *)> class monitor_state_sfinae_ {}; template <typename D, void (D::*) (unsigned, const Particle<T> &)> class processor_sfinae_ {}; template <typename D> void monitor_state_dispatch (unsigned iter, ConstSingleParticle<T> part, double *res, monitor_state_sfinae_<D, &D::monitor_state> *) { static_cast<Derived *>(this)->monitor_state(iter, part, res); } template <typename D> void pre_processor_dispatch (unsigned iter, const Particle<T> &particle, processor_sfinae_<D, &D::pre_processor> *) { static_cast<Derived *>(this)->pre_processor(iter, particle); } template <typename D> void post_processor_dispatch (unsigned iter, const Particle<T> &particle, processor_sfinae_<D, &D::post_processor> *) { static_cast<Derived *>(this)->post_processor(iter, particle); } template <typename D> void monitor_state_dispatch (unsigned, ConstSingleParticle<T>, double *, ...) {} template <typename D> void pre_processor_dispatch (unsigned iter, const Particle<T> &, ...) {} template <typename D> void post_processor_dispatch (unsigned iter, const Particle<T> &, ...) {} }; // class MonitorBase template <typename T> class MonitorBase<T, internal::VBase> { public : virtual void monitor_state (unsigned, ConstSingleParticle<T>, double *) {} virtual void post_processor (unsigned, const Particle<T> &) {} virtual void pre_processor (unsigned, const Particle<T> &) {} }; // class MonitorBase<T, internal::VBase> template <typename T, typename Derived> class PathBase { public : double path_state (unsigned iter, ConstSingleParticle<T> part) { return path_state_dispatch<Derived>(iter, part, 0); } double path_width (unsigned iter, Particle<T> &particle) { return path_width_dispatch<Derived>(iter, particle, 0); } void pre_processor (unsigned iter, const Particle<T> &particle) { pre_processor_dispatch<Derived>(iter, particle, 0); } void post_processor (unsigned iter, const Particle<T> &particle) { post_processor_dispatch<Derived>(iter, particle, 0); } private : template <typename D, double (D::*) (unsigned, ConstSingleParticle<T>)> class path_state_sfinae_ {}; template <typename D, double (D::*) (unsigned, const Particle<T> &)> class path_width_sfinae_ {}; template <typename D, void (D::*) (unsigned, const Particle<T> &)> class processor_sfinae_ {}; template <typename D> double path_state_dispatch (unsigned iter, ConstSingleParticle<T> part, path_state_sfinae_<D, &D::path_state> *) { return static_cast<Derived *>(this)->path_state(iter, part); } template <typename D> double path_width_dispatch (unsigned iter, const Particle<T> &particle, path_width_sfinae_<D, &D::path_state> *) { return static_cast<Derived *>(this)->path_width(iter, particle); } template <typename D> void pre_processor_dispatch (unsigned iter, const Particle<T> &particle, processor_sfinae_<D, &D::pre_processor> *) { static_cast<Derived *>(this)->pre_processor(iter, particle); } template <typename D> void post_processor_dispatch (unsigned iter, const Particle<T> &particle, processor_sfinae_<D, &D::post_processor> *) { static_cast<Derived *>(this)->post_processor(iter, particle); } template <typename D> double path_state_dispatch (unsigned, ConstSingleParticle<T>, ...) { return 0; } template <typename D> double path_width_dispatch (unsigned, const Particle<T> &) { return 0; } template <typename D> void pre_processor_dispatch (unsigned iter, const Particle<T> &, ...) {} template <typename D> void post_processor_dispatch (unsigned iter, const Particle<T> &, ...) {} }; // class PathBase template <typename T> class PathBase<T, internal::VBase> { public : virtual double path_state (unsigned, ConstSingleParticle<T>) {return 0;} virtual double path_width (unsigned, const Particle<T> &) {return 0;} virtual void post_processor (unsigned, const Particle<T> &) {} virtual void pre_processor (unsigned, const Particle<T> &) {} }; // class MonitorBase<T, internal::VBase> } } // namespace vsmc::internal #endif // VSMC_HELPER_BASE_HPP <commit_msg>simplify dispatch logic<commit_after>#ifndef VSMC_HELPER_BASE_HPP #define VSMC_HELPER_BASE_HPP #include <vsmc/internal/common.hpp> #include <vsmc/helper/single_particle.hpp> namespace vsmc { namespace internal { /// \brief Particle::value_type subtype /// \ingroup Helper /// /// \tparam Dim The dimension of the state parameter vector /// \tparam T The type of the value of the state parameter vector template <unsigned Dim, typename T> class StateBase { public : /// The type of the number of particles typedef VSMC_SIZE_TYPE size_type; /// The type of state parameters typedef T state_type; /// The type of the matrix of states typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> state_mat_type; /// Construct a StateBase object with given number of particles explicit StateBase (size_type N) : size_(N), state_(Dim, N) {} virtual ~StateBase () {} /// The dimension of the problem static unsigned dim () { return Dim; } /// The number of particles size_type size () const { return size_; } /// \brief Read and write access to a signle particle state /// /// \param id The position of the particle /// \param pos The position of the parameter in the state array /// /// \return A reference to the parameter at position pos of the states /// array of the particle at position id state_type &state (size_type id, unsigned pos) { return state_(pos, id); } /// Read only access to a signle particle state const state_type &state (size_type id, unsigned pos) const { return state_(pos, id); } /// \brief Read and write access to the array of a single particle states /// /// \param id The position of the particle, 0 to size() - 1 state_type *state (size_type id) { return state_.col(id).data(); } /// Read only access to the array of a single particle states const state_type *state (size_type id) const { return state_.col(id).data(); } /// \brief Read and write access to the matrix of all particle states /// /// \note The matrix is of column marjor as it's the default of Eigen. /// Therefore state()(pos, id) == state(id, pos). Best avoid this feature. state_mat_type &state () { return state_; } /// Read only access to the matrix of all particle states const state_mat_type &state () const { return state_; } private : size_type size_; state_mat_type state_; }; // class StateBase template <typename T, typename Derived> class InitializeBase { public : unsigned initialize_state (SingleParticle<T> part) { return initialize_state_dispatch(part, &Derived::initialize_state); } void initialize_param (Particle<T> &particle, void *param) { initialize_param_dispatch(particle, param, &Derived::initialize_param); } void post_processor (Particle<T> &particle) { post_processor_dispatch(particle, &Derived::pre_processor); } void pre_processor (Particle<T> &particle) { pre_processor_dispatch(particle, &Derived::post_processor); } private : template <typename D> unsigned initialize_state_dispatch (SingleParticle<T> part, unsigned (D::*) (SingleParticle<T>)) { return static_cast<Derived *>(this)->initialize_state(part); } template <typename D> void initialize_param_dispatch (Particle<T> &particle, void *param, void (D::*) (Particle<T> &, void *)) { static_cast<Derived *>(this)->initialize_param(particle, param); } template <typename D> void pre_processor_dispatch (Particle<T> &particle, void (D::*) (Particle<T> &)) { static_cast<Derived *>(this)->pre_processor(particle); } template <typename D> void post_processor_dispatch (Particle<T> &particle, void (D::*) (Particle<T> &)) { static_cast<Derived *>(this)->post_processor(particle); } unsigned initialize_state_dispatch (SingleParticle<T> part, unsigned (InitializeBase::*) (SingleParticle<T>)) {return 0;} void initialize_param_dispatch (Particle<T> &particle, void *param, void (InitializeBase::*) (Particle<T> &, void *)) {} void pre_processor_dispatch (Particle<T> &particle, void (InitializeBase::*) (Particle<T> &)) {} void post_processor_dispatch (Particle<T> &particle, void (InitializeBase::*) (Particle<T> &)) {} }; // class InitializeBase<T, Derived> template <typename T> class InitializeBase<T, internal::VBase> { public : virtual unsigned initialize_state (SingleParticle<T>) {return 0;} virtual void initialize_param (Particle<T> &, void *) {} virtual void post_processor (Particle<T> &) {} virtual void pre_processor (Particle<T> &) {} }; // class InitializeBase<T> template <typename T, typename Derived> class MoveBase { public : unsigned move_state (unsigned iter, SingleParticle<T> part) { return move_state_dispatch(iter, part, &Derived::move_state); } void pre_processor (unsigned iter, Particle<T> &particle) { pre_processor_dispatch(iter, particle, &Derived::pre_processor); } void post_processor (unsigned iter, Particle<T> &particle) { post_processor_dispatch(iter, particle, &Derived::post_processor); } private : template <typename D> unsigned move_state_dispatch (unsigned iter, SingleParticle<T> part, unsigned (D::*) (unsigned, SingleParticle<T>)) { return static_cast<Derived *>(this)->move_state(iter, part); } template <typename D> void pre_processor_dispatch (unsigned iter, Particle<T> &particle, void (D::*) (unsigned, Particle<T> &)) { static_cast<Derived *>(this)->pre_processor(iter, particle); } template <typename D> void post_processor_dispatch (unsigned iter, Particle<T> &particle, void (D::*) (unsigned, Particle<T> &)) { static_cast<Derived *>(this)->post_processor(iter, particle); } unsigned move_state_dispatch (unsigned, SingleParticle<T>, unsigned (MoveBase::*) (unsigned, SingleParticle<T>)) {return 0;} void pre_processor_dispatch (unsigned iter, Particle<T> &, void (MoveBase::*) (unsigned, Particle<T> &)) {} void post_processor_dispatch (unsigned iter, Particle<T> &, void (MoveBase::*) (unsigned, Particle<T> &)) {} }; // class MoveBase<T, Derived> template <typename T> class MoveBase<T, internal::VBase> { public : virtual unsigned move_state (unsigned, SingleParticle<T>) {return 0;} virtual void post_processor (unsigned, Particle<T> &) {} virtual void pre_processor (unsigned, Particle<T> &) {} }; // class MoveBase<T> template <typename T, typename Derived> class MonitorBase { public : void monitor_state (unsigned iter, ConstSingleParticle<T> part, double *res) { monitor_state_dispatch(iter, part, res, &Derived::monitor_state); } void pre_processor (unsigned iter, const Particle<T> &particle) { pre_processor_dispatch(iter, particle, &Derived::pre_processor); } void post_processor (unsigned iter, const Particle<T> &particle) { post_processor_dispatch(iter, particle, &Derived::post_processor); } private : template <typename D> void monitor_state_dispatch (unsigned iter, ConstSingleParticle<T> part, double *res, void (D::*) (unsigned, ConstSingleParticle<T>, double *)) { static_cast<Derived *>(this)->monitor_state(iter, part, res); } template <typename D> void pre_processor_dispatch (unsigned iter, const Particle<T> &particle, void (D::*) (unsigned, const Particle<T> &)) { static_cast<Derived *>(this)->pre_processor(iter, particle); } template <typename D> void post_processor_dispatch (unsigned iter, const Particle<T> &particle, void (D::*) (unsigned, const Particle<T> &)) { static_cast<Derived *>(this)->post_processor(iter, particle); } void monitor_state_dispatch (unsigned, ConstSingleParticle<T>, double *res, void (MonitorBase::*) (unsigned, ConstSingleParticle<T>, double *)) {} void pre_processor_dispatch (unsigned iter, const Particle<T> &, void (MonitorBase::*) (unsigned, const Particle<T> &)) {} void post_processor_dispatch (unsigned iter, const Particle<T> &, void (MonitorBase::*) (unsigned, const Particle<T> &)) {} }; // class MonitorBase<T, Derived> template <typename T> class MonitorBase<T, internal::VBase> { public : virtual void monitor_state (unsigned, ConstSingleParticle<T>, double *) {} virtual void post_processor (unsigned, const Particle<T> &) {} virtual void pre_processor (unsigned, const Particle<T> &) {} }; // class MonitorBase<T> template <typename T, typename Derived> class PathBase { public : double path_state (unsigned iter, ConstSingleParticle<T> part) { return path_state_dispatch(iter, part, &Derived::path_state); } double path_width (unsigned iter, Particle<T> &particle) { return path_width_dispatch(iter, particle, &Derived::path_width); } void pre_processor (unsigned iter, const Particle<T> &particle) { pre_processor_dispatch(iter, particle, &Derived::pre_processor); } void post_processor (unsigned iter, const Particle<T> &particle) { post_processor_dispatch(iter, particle, &Derived::post_processor); } private : template <typename D> double path_state_dispatch (unsigned iter, ConstSingleParticle<T> part, double (D::*) (unsigned, ConstSingleParticle<T>)) { return static_cast<Derived *>(this)->path_state(iter, part); } template <typename D> double path_width_dispatch (unsigned iter, const Particle<T> &particle, double (D::*) (unsigned, const Particle<T> &)) { return static_cast<Derived *>(this)->path_width(iter, particle); } template <typename D> void pre_processor_dispatch (unsigned iter, const Particle<T> &particle, void (D::*) (unsigned, const Particle<T> &)) { static_cast<Derived *>(this)->pre_processor(iter, particle); } template <typename D> void post_processor_dispatch (unsigned iter, const Particle<T> &particle, void (D::*) (unsigned, const Particle<T> &)) { static_cast<Derived *>(this)->post_processor(iter, particle); } double path_state_dispatch (unsigned, ConstSingleParticle<T>, double (PathBase::*) (unsigned, ConstSingleParticle<T>)) {return 0;} double path_width_dispatch (unsigned, const Particle<T> &, double (PathBase::*) (unsigned, const Particle<T> &)) {return 0;} void pre_processor_dispatch (unsigned iter, const Particle<T> &, void (PathBase::*) (unsigned, const Particle<T> &)) {} void post_processor_dispatch (unsigned iter, const Particle<T> &, void (PathBase::*) (unsigned, const Particle<T> &)) {} }; // class PathBase<T, Derived> template <typename T> class PathBase<T, internal::VBase> { public : virtual double path_state (unsigned, ConstSingleParticle<T>) {return 0;} virtual double path_width (unsigned, const Particle<T> &) {return 0;} virtual void post_processor (unsigned, const Particle<T> &) {} virtual void pre_processor (unsigned, const Particle<T> &) {} }; // class MonitorBase<T> } } // namespace vsmc::internal #endif // VSMC_HELPER_BASE_HPP <|endoftext|>
<commit_before>#ifndef VSMC_RNG_GSL_RNG_HPP #define VSMC_RNG_GSL_RNG_HPP #include <vsmc/rng/generator_wrapper.hpp> #include <gsl/gsl_rng.h> #define VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(Name, pointer) \ template <> struct GSLRngTypePointer< GSL_RNG_TYPE_##Name > \ {static const gsl_rng_type *get () {return gsl_rng_##pointer ;}}; #define VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(Name, Min, Max) \ template <> struct GSLRngMinMaxTrait< GSL_RNG_TYPE_##Name > \ { \ static VSMC_CONSTEXPR const uint32_t _Min = \ static_cast<uint32_t>(Min##UL); \ static VSMC_CONSTEXPR const uint32_t _Max = \ static_cast<uint32_t>(Max##UL); \ static VSMC_CONSTEXPR uint32_t min VSMC_MNE () {return _Min;} \ static VSMC_CONSTEXPR uint32_t max VSMC_MNE () {return _Max;} \ }; namespace vsmc { /// \brief GSL RNG algorithms /// \ingroup GSLRNG enum GSLRngType { GSL_RNG_TYPE_MT19937, ///< gsl_rng_mt19937 GSL_RNG_TYPE_RANLXS0, ///< gsl_rng_ranlxs0 GSL_RNG_TYPE_RANLXS1, ///< gsl_rng_ranlxs1 GSL_RNG_TYPE_RANLXS2, ///< gsl_rng_ranlxs2 GSL_RNG_TYPE_RANLXD1, ///< gsl_rng_ranlxd1 GSL_RNG_TYPE_RANLXD2, ///< gsl_rng_ranlxd2 GSL_RNG_TYPE_RANLUX, ///< gsl_rng_ranlux GSL_RNG_TYPE_RANLUX389, ///< gsl_rng_ranlux389 GSL_RNG_TYPE_CMRG, ///< gsl_rng_cmrg GSL_RNG_TYPE_MRG, ///< gsl_rng_mrg GSL_RNG_TYPE_TAUS, ///< gsl_rng_taus GSL_RNG_TYPE_TAUS2, ///< gsl_rng_taus2 GSL_RNG_TYPE_GFSR4 ///< gsl_rng_gfsr4 }; // enum GSLRngType namespace internal { template <GSLRngType> struct GSLRngTypePointer; VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(MT19937, mt19937) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLXS0, ranlxs0) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLXS1, ranlxs1) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLXS2, ranlxs2) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLXD1, ranlxd1) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLXD2, ranlxd2) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLUX, ranlux) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLUX389, ranlux389) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(CMRG, cmrg) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(MRG, mrg) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(TAUS, taus) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(TAUS2, taus2) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(GFSR4, gfsr4) template <GSLRngType RngType> struct GSLRngMinMaxTrait; VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(MT19937, 0, 4294967295) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLXS0, 0, 16777215) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLXS1, 0, 16777215) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLXS2, 0, 16777215) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLXD1, 0, 4294967295) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLXD2, 0, 4294967295) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLUX, 0, 16777215) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLUX389, 0, 16777215) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(CMRG, 0, 2147483646) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(MRG, 0, 2147483646) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(TAUS, 0, 4294967295) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(TAUS2, 0, 4294967295) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(GFSR4, 0, 4294967295) template <GSLRngType RngType> class GSLRngGenerator { public : GSLRngGenerator () : rng_(gsl_rng_alloc(internal::GSLRngTypePointer<RngType>::get())) {} GSLRngGenerator (const GSLRngGenerator<RngType> &other) : rng_(gsl_rng_clone(other.rng_)) {} GSLRngGenerator<RngType> &operator= (const GSLRngGenerator<RngType> &other) { if (this != &other) { if (rng_ != VSMC_NULLPTR) gsl_rng_free(rng_); rng_ = gsl_rng_memcpy(other.rng_); } return *this; } #if VSMC_HAS_CXX11_RVALUE_REFERENCES GSLRngGenerator (GSLRngGenerator<RngType> &&other) : rng_(other.rng_) {other.rng_ = VSMC_NULLPTR;} GSLRngGenerator<RngType> &operator= (GSLRngGenerator<RngType> &&other) { if (this != &other) { if (rng_ != VSMC_NULLPTR) gsl_rng_free(rng_); rng_ = other.rng_; other.rng_ = VSMC_NULLPTR; } return *this; } #endif ~GSLRngGenerator () { if (rng_ != VSMC_NULLPTR) gsl_rng_free(rng_); } void seed (unsigned long s) { if (rng_ != VSMC_NULLPTR) gsl_rng_set(rng_, s); } unsigned long generate () { if (rng_ != VSMC_NULLPTR) return gsl_rng_get(rng_); return 0; } unsigned long min VSMC_MNE () const {return gsl_rng_min(rng_);} unsigned long max VSMC_MNE () const {return gsl_rng_max(rng_);} private : gsl_rng *rng_; }; // class GSLRngGenerator } // namespace vsmc::internal /// \brief GSL RNG Engine /// \ingroup GSLRNG template <GSLRngType RngType> class GSLRngEngine : public GeneratorWrapper<uint32_t, internal::GSLRngGenerator<RngType>, internal::GSLRngMinMaxTrait<RngType> > { typedef GeneratorWrapper<uint32_t, internal::GSLRngGenerator<RngType>, internal::GSLRngMinMaxTrait<RngType> > base; public : typedef uint32_t result_type; GSLRngEngine (result_type s = 0) : base(s) {seed(s);} template <typename SeedSeq> explicit GSLRngEngine (SeedSeq &seq, typename cxx11::enable_if< !internal::is_seed_sequence<SeedSeq, result_type>::value>::type * = VSMC_NULLPTR) : base(seq) {seed(seq);} void seed (result_type s) {this->generator().seed(static_cast<unsigned long>(s));} template <typename SeedSeq> void seed (SeedSeq &seq, typename cxx11::enable_if< !internal::is_seed_sequence<SeedSeq, result_type>::value>::type * = VSMC_NULLPTR) { unsigned long s; seq.generate(&s, &s + 1); this->generator().seed(s); } }; // class GSLRngEngine /// \brief A Mersenne-Twister pseudoranom number genertor /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_MT19937> GSL_MT19937; /// \brief A RANLUX generator with luxury level 0 /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_RANLXS0> GSL_RANLXS0; /// \brief A RANLUX generator with luxury level 0 /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_RANLXS1> GSL_RANLXS1; /// \brief A RANLUX generator with luxury level 0 /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_RANLXS2> GSL_RANLXS2; /// \brief A RANLXS generator with luxury level 1 /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_RANLXD1> GSL_RANLXD1; /// \brief A RANLXS generator with luxury level 2 /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_RANLXD2> GSL_RANLXD2; /// \brief A RANLUX generator /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_RANLUX> GSL_RANLUX; /// \brief A RANLUX generator with the highest level of randomness /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_RANLUX389> GSL_RANLUX389; /// \brief A combined multiple recursive generator /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_CMRG> GSL_CMRG; /// \brief A fifth-order multiple recursive generator /// \ingroup GSL typedef GSLRngEngine<GSL_RNG_TYPE_MRG> GSL_MRG; /// \brief A maximally equidistributed combined Tausworthe generator /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_TAUS> GSL_TAUS; /// \brief A maximally equidistributed combined Tausworthe generator with /// improved seeding procedure /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_TAUS2> GSL_TAUS2; /// \brief A a lagged-fibonacci alike generator /// \ingroup GSLRNG typedef GSLRngEngine<GSL_RNG_TYPE_GFSR4> GSL_GFSR4; } // namespace vsmc #endif // VSMC_RNG_GSL_RNG_HPP <commit_msg>move GSLGenerator to namespace vsmc<commit_after>#ifndef VSMC_RNG_GSL_RNG_HPP #define VSMC_RNG_GSL_RNG_HPP #include <vsmc/rng/generator_wrapper.hpp> #include <gsl/gsl_rng.h> #define VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(Name, pointer) \ template <> struct GSLRngTypePointer< GSL_RNG_TYPE_##Name > \ {static const gsl_rng_type *get () {return gsl_rng_##pointer ;}}; #define VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(Name, Min, Max) \ template <> struct GSLRngMinMaxTrait< GSL_RNG_TYPE_##Name > \ { \ static VSMC_CONSTEXPR const uint32_t _Min = \ static_cast<uint32_t>(Min##UL); \ static VSMC_CONSTEXPR const uint32_t _Max = \ static_cast<uint32_t>(Max##UL); \ static VSMC_CONSTEXPR uint32_t min VSMC_MNE () {return _Min;} \ static VSMC_CONSTEXPR uint32_t max VSMC_MNE () {return _Max;} \ }; namespace vsmc { /// \brief GSL RNG algorithms /// \ingroup GSLRNG enum GSLRngType { GSL_RNG_TYPE_MT19937, ///< gsl_rng_mt19937 GSL_RNG_TYPE_RANLXS0, ///< gsl_rng_ranlxs0 GSL_RNG_TYPE_RANLXS1, ///< gsl_rng_ranlxs1 GSL_RNG_TYPE_RANLXS2, ///< gsl_rng_ranlxs2 GSL_RNG_TYPE_RANLXD1, ///< gsl_rng_ranlxd1 GSL_RNG_TYPE_RANLXD2, ///< gsl_rng_ranlxd2 GSL_RNG_TYPE_RANLUX, ///< gsl_rng_ranlux GSL_RNG_TYPE_RANLUX389, ///< gsl_rng_ranlux389 GSL_RNG_TYPE_CMRG, ///< gsl_rng_cmrg GSL_RNG_TYPE_MRG, ///< gsl_rng_mrg GSL_RNG_TYPE_TAUS, ///< gsl_rng_taus GSL_RNG_TYPE_TAUS2, ///< gsl_rng_taus2 GSL_RNG_TYPE_GFSR4 ///< gsl_rng_gfsr4 }; // enum GSLRngType namespace internal { template <GSLRngType> struct GSLRngTypePointer; VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(MT19937, mt19937) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLXS0, ranlxs0) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLXS1, ranlxs1) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLXS2, ranlxs2) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLXD1, ranlxd1) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLXD2, ranlxd2) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLUX, ranlux) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(RANLUX389, ranlux389) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(CMRG, cmrg) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(MRG, mrg) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(TAUS, taus) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(TAUS2, taus2) VSMC_DEFINE_RNG_GSL_RNG_TYPE_POINTER(GFSR4, gfsr4) template <GSLRngType RngType> struct GSLRngMinMaxTrait; VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(MT19937, 0, 4294967295) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLXS0, 0, 16777215) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLXS1, 0, 16777215) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLXS2, 0, 16777215) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLXD1, 0, 4294967295) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLXD2, 0, 4294967295) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLUX, 0, 16777215) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(RANLUX389, 0, 16777215) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(CMRG, 0, 2147483646) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(MRG, 0, 2147483646) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(TAUS, 0, 4294967295) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(TAUS2, 0, 4294967295) VSMC_DEFINE_RNG_GSL_RNG_MIN_MAX_TRAIT(GFSR4, 0, 4294967295) } // namespace vsmc::internal /// \brief GSL RNG generator for use with GeneratorWrapper /// \ingroup GSLRNG template <GSLRngType RngType> class GSLGenerator { public : GSLGenerator () : rng_(gsl_rng_alloc(internal::GSLRngTypePointer<RngType>::get())) {} GSLGenerator (const GSLGenerator<RngType> &other) : rng_(gsl_rng_clone(other.rng_)) {} GSLGenerator<RngType> &operator= (const GSLGenerator<RngType> &other) { if (this != &other) { if (rng_ != VSMC_NULLPTR) gsl_rng_free(rng_); rng_ = gsl_rng_memcpy(other.rng_); } return *this; } #if VSMC_HAS_CXX11_RVALUE_REFERENCES GSLGenerator (GSLGenerator<RngType> &&other) : rng_(other.rng_) {other.rng_ = VSMC_NULLPTR;} GSLGenerator<RngType> &operator= (GSLGenerator<RngType> &&other) { if (this != &other) { if (rng_ != VSMC_NULLPTR) gsl_rng_free(rng_); rng_ = other.rng_; other.rng_ = VSMC_NULLPTR; } return *this; } #endif ~GSLGenerator () { if (rng_ != VSMC_NULLPTR) gsl_rng_free(rng_); } void seed (unsigned long s) { if (rng_ != VSMC_NULLPTR) gsl_rng_set(rng_, s); } unsigned long generate () { if (rng_ != VSMC_NULLPTR) return gsl_rng_get(rng_); return 0; } unsigned long min VSMC_MNE () const {return gsl_rng_min(rng_);} unsigned long max VSMC_MNE () const {return gsl_rng_max(rng_);} private : gsl_rng *rng_; }; // class GSLGenerator /// \brief GSL RNG Engine /// \ingroup GSLRNG template <GSLRngType RngType> class GSLEngine : public GeneratorWrapper<uint32_t, GSLGenerator<RngType>, internal::GSLRngMinMaxTrait<RngType> > { typedef GeneratorWrapper<uint32_t, GSLGenerator<RngType>, internal::GSLRngMinMaxTrait<RngType> > base; public : typedef uint32_t result_type; GSLEngine (result_type s = 0) : base(s) {seed(s);} template <typename SeedSeq> explicit GSLEngine (SeedSeq &seq, typename cxx11::enable_if< !internal::is_seed_sequence<SeedSeq, result_type>::value>::type * = VSMC_NULLPTR) : base(seq) {seed(seq);} void seed (result_type s) {this->generator().seed(static_cast<unsigned long>(s));} template <typename SeedSeq> void seed (SeedSeq &seq, typename cxx11::enable_if< !internal::is_seed_sequence<SeedSeq, result_type>::value>::type * = VSMC_NULLPTR) { unsigned long s; seq.generate(&s, &s + 1); this->generator().seed(s); } }; // class GSLEngine /// \brief A Mersenne-Twister pseudoranom number genertor /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_MT19937> GSL_MT19937; /// \brief A RANLUX generator with luxury level 0 /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_RANLXS0> GSL_RANLXS0; /// \brief A RANLUX generator with luxury level 0 /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_RANLXS1> GSL_RANLXS1; /// \brief A RANLUX generator with luxury level 0 /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_RANLXS2> GSL_RANLXS2; /// \brief A RANLXS generator with luxury level 1 /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_RANLXD1> GSL_RANLXD1; /// \brief A RANLXS generator with luxury level 2 /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_RANLXD2> GSL_RANLXD2; /// \brief A RANLUX generator /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_RANLUX> GSL_RANLUX; /// \brief A RANLUX generator with the highest level of randomness /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_RANLUX389> GSL_RANLUX389; /// \brief A combined multiple recursive generator /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_CMRG> GSL_CMRG; /// \brief A fifth-order multiple recursive generator /// \ingroup GSL typedef GSLEngine<GSL_RNG_TYPE_MRG> GSL_MRG; /// \brief A maximally equidistributed combined Tausworthe generator /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_TAUS> GSL_TAUS; /// \brief A maximally equidistributed combined Tausworthe generator with /// improved seeding procedure /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_TAUS2> GSL_TAUS2; /// \brief A a lagged-fibonacci alike generator /// \ingroup GSLRNG typedef GSLEngine<GSL_RNG_TYPE_GFSR4> GSL_GFSR4; } // namespace vsmc #endif // VSMC_RNG_GSL_RNG_HPP <|endoftext|>
<commit_before>/* * @file llimagepng.cpp * @brief LLImageFormatted glue to encode / decode PNG files. * * $LicenseInfo:firstyear=2007&license=viewergpl$ * * Copyright (c) 2007-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "linden_common.h" #include "stdtypes.h" #include "llerror.h" #include "llimage.h" #include "llpngwrapper.h" #include "llimagepng.h" // --------------------------------------------------------------------------- // LLImagePNG // --------------------------------------------------------------------------- LLImagePNG::LLImagePNG() : LLImageFormatted(IMG_CODEC_PNG), mTmpWriteBuffer(NULL) { } LLImagePNG::~LLImagePNG() { if (mTmpWriteBuffer) { delete[] mTmpWriteBuffer; } } // Virtual // Parse PNG image information and set the appropriate // width, height and component (channel) information. BOOL LLImagePNG::updateData() { resetLastError(); // Check to make sure that this instance has been initialized with data if (!getData() || (0 == getDataSize())) { setLastError("Uninitialized instance of LLImagePNG"); return FALSE; } // Decode the PNG data and extract sizing information LLPngWrapper pngWrapper; LLPngWrapper::ImageInfo infop; if (! pngWrapper.readPng(getData(), NULL, &infop)) { setLastError(pngWrapper.getErrorMessage()); return FALSE; } setSize(infop.mWidth, infop.mHeight, infop.mComponents); return TRUE; } // Virtual // Decode an in-memory PNG image into the raw RGB or RGBA format // used within SecondLife. BOOL LLImagePNG::decode(LLImageRaw* raw_image, F32 decode_time) { llassert_always(raw_image); resetLastError(); // Check to make sure that this instance has been initialized with data if (!getData() || (0 == getDataSize())) { setLastError("LLImagePNG trying to decode an image with no data!"); return FALSE; } // Decode the PNG data into the raw image LLPngWrapper pngWrapper; if (! pngWrapper.readPng(getData(), raw_image)) { setLastError(pngWrapper.getErrorMessage()); return FALSE; } return TRUE; } // Virtual // Encode the in memory RGB image into PNG format. BOOL LLImagePNG::encode(const LLImageRaw* raw_image, F32 encode_time) { llassert_always(raw_image); resetLastError(); // Image logical size setSize(raw_image->getWidth(), raw_image->getHeight(), raw_image->getComponents()); // Temporary buffer to hold the encoded image. Note: the final image // size should be much smaller due to compression. if (mTmpWriteBuffer) { delete[] mTmpWriteBuffer; } U32 bufferSize = getWidth() * getHeight() * getComponents() + 1024; U8* mTmpWriteBuffer = new U8[ bufferSize ]; // Delegate actual encoding work to wrapper LLPngWrapper pngWrapper; if (! pngWrapper.writePng(raw_image, mTmpWriteBuffer)) { setLastError(pngWrapper.getErrorMessage()); return FALSE; } // Resize internal buffer and copy from temp U32 encodedSize = pngWrapper.getFinalSize(); allocateData(encodedSize); memcpy(getData(), mTmpWriteBuffer, encodedSize); delete[] mTmpWriteBuffer; return TRUE; } <commit_msg>EXT-7851 FIXED Memory leak in LLImagePNG::encode()<commit_after>/* * @file llimagepng.cpp * @brief LLImageFormatted glue to encode / decode PNG files. * * $LicenseInfo:firstyear=2007&license=viewergpl$ * * Copyright (c) 2007-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "linden_common.h" #include "stdtypes.h" #include "llerror.h" #include "llimage.h" #include "llpngwrapper.h" #include "llimagepng.h" // --------------------------------------------------------------------------- // LLImagePNG // --------------------------------------------------------------------------- LLImagePNG::LLImagePNG() : LLImageFormatted(IMG_CODEC_PNG), mTmpWriteBuffer(NULL) { } LLImagePNG::~LLImagePNG() { if (mTmpWriteBuffer) { delete[] mTmpWriteBuffer; } } // Virtual // Parse PNG image information and set the appropriate // width, height and component (channel) information. BOOL LLImagePNG::updateData() { resetLastError(); // Check to make sure that this instance has been initialized with data if (!getData() || (0 == getDataSize())) { setLastError("Uninitialized instance of LLImagePNG"); return FALSE; } // Decode the PNG data and extract sizing information LLPngWrapper pngWrapper; LLPngWrapper::ImageInfo infop; if (! pngWrapper.readPng(getData(), NULL, &infop)) { setLastError(pngWrapper.getErrorMessage()); return FALSE; } setSize(infop.mWidth, infop.mHeight, infop.mComponents); return TRUE; } // Virtual // Decode an in-memory PNG image into the raw RGB or RGBA format // used within SecondLife. BOOL LLImagePNG::decode(LLImageRaw* raw_image, F32 decode_time) { llassert_always(raw_image); resetLastError(); // Check to make sure that this instance has been initialized with data if (!getData() || (0 == getDataSize())) { setLastError("LLImagePNG trying to decode an image with no data!"); return FALSE; } // Decode the PNG data into the raw image LLPngWrapper pngWrapper; if (! pngWrapper.readPng(getData(), raw_image)) { setLastError(pngWrapper.getErrorMessage()); return FALSE; } return TRUE; } // Virtual // Encode the in memory RGB image into PNG format. BOOL LLImagePNG::encode(const LLImageRaw* raw_image, F32 encode_time) { llassert_always(raw_image); resetLastError(); // Image logical size setSize(raw_image->getWidth(), raw_image->getHeight(), raw_image->getComponents()); // Temporary buffer to hold the encoded image. Note: the final image // size should be much smaller due to compression. if (mTmpWriteBuffer) { delete[] mTmpWriteBuffer; } U32 bufferSize = getWidth() * getHeight() * getComponents() + 1024; U8* mTmpWriteBuffer = new U8[ bufferSize ]; // Delegate actual encoding work to wrapper LLPngWrapper pngWrapper; if (! pngWrapper.writePng(raw_image, mTmpWriteBuffer)) { setLastError(pngWrapper.getErrorMessage()); delete[] mTmpWriteBuffer; return FALSE; } // Resize internal buffer and copy from temp U32 encodedSize = pngWrapper.getFinalSize(); allocateData(encodedSize); memcpy(getData(), mTmpWriteBuffer, encodedSize); delete[] mTmpWriteBuffer; return TRUE; } <|endoftext|>
<commit_before>//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/linearAlg2D.h" //Distance from point to line. #include "MergeInfillLines.h" namespace cura { MergeInfillLines::MergeInfillLines(ExtruderPlan& plan, const coord_t nozzle_size, const coord_t maximum_resolution) : extruder_plan(plan), nozzle_size(nozzle_size), maximum_resolution(maximum_resolution) { //Just copy the parameters to their fields. } coord_t MergeInfillLines::calcPathLength(const Point path_start, GCodePath& path) const { Point previous_point = path_start; coord_t result = 0; for (const Point point : path.points) { result += vSize(point - previous_point); previous_point = point; } return result; } /* * first_is_already_merged == false * * o o * / / * / / * / + / ---> -(t)-o-----o * / / * / / * o o * * travel (t) to first location is done through first_path_start_changed and new_first_path_start. * this gets rid of the tiny "blips". Depending on the merged line distance a small gap may appear, but this is * accounted for in the volume. * * first_is_already_merged == true * * o * / * / * o-----o + / ---> o-----------o or with slight o-----o-----o * / / / bend / * / / / / * o o o o * */ bool MergeInfillLines::mergeLinesSideBySide(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start, coord_t& error_area) const { Point average_first_path; coord_t first_path_length = calcPathLength(first_path_start, first_path); coord_t first_path_length_flow = first_path_length * first_path.flow; //To get the volume we don't need to include the line width since it's the same for both lines. const coord_t line_width = first_path.config->getLineWidth(); if (first_is_already_merged) { // take second point of path, first_path.points[0] average_first_path = first_path.points[0]; } else { average_first_path += first_path_start; for (const Point point : first_path.points) { average_first_path += point; } average_first_path /= (first_path.points.size() + 1); } coord_t second_path_length = calcPathLength(second_path_start, second_path); Point average_second_path = second_path_start; for (const Point point : second_path.points) { average_second_path += point; } coord_t second_path_length_flow = second_path_length *= second_path.flow; average_second_path /= (coord_t) (second_path.points.size() + 1); // predict new length and flow and if the new flow is to big, don't merge. conditions in this part must exactly match the actual merging coord_t new_path_length = first_path_length; coord_t dist2_from_line = 0; coord_t new_error_area = 0; coord_t merged_part_length = 0; if (first_is_already_merged) { // check if the new point is a good extension of last part of existing polyline // because of potential accumulation of errors introduced each time a line is merged, we do not allow any error. if (first_path.points.size() > 1) { dist2_from_line = LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size() - 2], first_path.points[first_path.points.size() - 1]); merged_part_length = vSize(first_path.points[first_path.points.size() - 2] - average_second_path); new_error_area = sqrt(dist2_from_line) * merged_part_length / 2; } // The max error margin uses the meshfix_maximum_resolution setting if (first_path.points.size() > 1 && error_area + new_error_area < merged_part_length * maximum_resolution) { new_path_length -= vSize(first_path.points[first_path.points.size() - 2] - first_path.points[first_path.points.size() - 1]); new_path_length += vSize(first_path.points[first_path.points.size() - 2] - average_second_path); } else { new_path_length += vSize(first_path.points[first_path.points.size() - 1] - average_second_path); } } else { new_path_length -= vSize(first_path.points.back() - first_path_start); new_path_length += vSize(average_second_path - average_first_path); } double new_flow = ((first_path_length_flow + second_path_length_flow) / static_cast<double>(new_path_length)); if (new_flow > 2 * nozzle_size / line_width) // line width becomes too wide. { return false; } // do the actual merging if (first_is_already_merged) { // check if the new point is a good extension of last part of existing polyline // because of potential accumulation of errors introduced each time a line is merged, we do not allow any error. if (first_path.points.size() > 1 && error_area + new_error_area < line_width * line_width) { first_path.points[first_path.points.size() - 1] = average_second_path; error_area += new_error_area; } else { first_path.points.push_back(average_second_path); error_area = 0; } } else { new_first_path_start = average_first_path; first_path.points.clear(); first_path.points.push_back(average_second_path); error_area = 0; } first_path.flow = static_cast<double>(first_path_length_flow + second_path_length_flow) / new_path_length; return true; } bool MergeInfillLines::tryMerge(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start, coord_t& error_area) const { const Point first_path_end = first_path.points.back(); const Point second_path_end = second_path.points.back(); const coord_t line_width = first_path.config->getLineWidth(); // Reintroduction of this check prevents [CURA-5674] printing spurious infill-lines to origin: const auto line_width_sqrd = line_width * line_width; if (vSize2(first_path_end - second_path_start) < line_width_sqrd && vSize2(first_path_start - second_path_end) < line_width_sqrd) { return false; } //Lines may be adjacent side-by-side then. Point first_path_leave_point; coord_t merged_size2; if (first_is_already_merged) { first_path_leave_point = first_path.points.back(); // this is the point that's going to merge } else { first_path_leave_point = (first_path_start + first_path_end) / 2; } const Point second_path_destination_point = (second_path_start + second_path_end) / 2; const Point merged_direction = second_path_destination_point - first_path_leave_point; if (first_is_already_merged) { merged_size2 = vSize2(second_path_destination_point - first_path.points.back()); // check distance with last point in merged line that is to be replaced } else { merged_size2 = vSize2(merged_direction); } if (merged_size2 > 25 * line_width * line_width) { return false; //Lines are too far away from each other. } if (merged_direction.X == 0 && merged_direction.Y == 0) { return true; // we can just disregard the second point as it's exactly at the leave point of the first path. } // Max 1 line width to the side of the merged_direction if (LinearAlg2D::getDist2FromLine(first_path_end, second_path_destination_point, second_path_destination_point + merged_direction) > line_width * line_width || LinearAlg2D::getDist2FromLine(second_path_start, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width || LinearAlg2D::getDist2FromLine(second_path_end, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width //|| abs(dot(normal(merged_direction, 1000), normal(second_path_end - second_path_start, 1000))) > 866000 // 866000 angle of old second_path with new merged direction should not be too small (30 degrees), as it will introduce holes ) { return false; //One of the lines is too far from the merged line. Lines would be too wide or too far off. } if (first_is_already_merged && first_path.points.size() > 1 && first_path.points[first_path.points.size() - 2] == second_path_destination_point) // yes this can actually happen { return false; } return mergeLinesSideBySide(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start, error_area); } bool MergeInfillLines::mergeInfillLines(std::vector<GCodePath>& paths, const Point& starting_position) const { /* Algorithm overview: 1. Loop over all lines to see if they can be merged. 1a. Check if two adjacent lines can be merged (skipping travel moves in between). 1b. If they can, merge both lines into the first line. 1c. If they are merged, check next that the first line can be merged with the line after the second line. 2. Do a second iteration over all paths to remove the tombstones. */ std::vector<size_t> remove_path_indices; std::set<size_t> is_merged; std::set<size_t> removed; // keep track of what we already removed, so don't remove it again //For each two adjacent lines, see if they can be merged. size_t first_path_index = 0; Point first_path_start = Point(starting_position.X, starting_position.Y); // this one is not going to be overwritten size_t second_path_index = 1; coord_t error_area = 0; for (; second_path_index < paths.size(); second_path_index++) { GCodePath& first_path = paths[first_path_index]; GCodePath& second_path = paths[second_path_index]; Point second_path_start = paths[second_path_index - 1].points.back(); if (second_path.config->isTravelPath()) { continue; //Skip travel paths, we're looking for the first non-travel path. } bool allow_try_merge = true; // see if we meet criteria to merge. should be: travel - path1 not travel - (...) - travel - path2 not travel - travel // we're checking the travels here if (first_path_index <= 1 || !paths[first_path_index - 1].isTravelPath()) // "<= 1" because we don't want the first travel being changed. That may introduce a hole somewhere { allow_try_merge = false; } if (second_path_index + 1 >= paths.size() || !paths[second_path_index + 1].isTravelPath()) { allow_try_merge = false; } if (first_path.config->isTravelPath()) //Don't merge travel moves. { allow_try_merge = false; } if (first_path.config != second_path.config) //Only merge lines that have the same type. { allow_try_merge = false; } if (first_path.config->type != PrintFeatureType::Infill && first_path.config->type != PrintFeatureType::Skin) //Only merge skin and infill lines. { allow_try_merge = false; } const bool first_is_already_merged = is_merged.find(first_path_index) != is_merged.end(); if ((!first_is_already_merged && first_path.points.size() > 1) || second_path.points.size() > 1) { // For now we only merge simple lines, not polylines, to keep it simple. // If the first line is already a merged line, then allow it. allow_try_merge = false; } Point new_first_path_start; if (allow_try_merge && tryMerge(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start, error_area)) { if (!first_is_already_merged) { paths[first_path_index - 1].points.back().X = new_first_path_start.X; paths[first_path_index - 1].points.back().Y = new_first_path_start.Y; } /* If we combine two lines, the next path may also be merged into the fist line, so we do NOT update first_path_index. */ for (size_t to_delete_index = first_path_index + 1; to_delete_index <= second_path_index; to_delete_index++) { if (removed.find(to_delete_index) == removed.end()) // if there are line(s) between first and second, then those lines are already marked as to be deleted, only add the new line(s) { remove_path_indices.push_back(to_delete_index); removed.insert(to_delete_index); } } is_merged.insert(first_path_index); } else { /* If we do not combine, the next iteration we must simply merge the second path with the line after it. */ first_path_index = second_path_index; first_path_start = second_path_start; } } //Delete all removed lines in one pass so that we need to move lines less often. if (!remove_path_indices.empty()) { size_t path_index = remove_path_indices[0]; for (size_t removed_position = 1; removed_position < remove_path_indices.size(); removed_position++) { for (; path_index < remove_path_indices[removed_position] - removed_position; path_index++) { paths[path_index] = paths[path_index + removed_position]; //Shift all paths. } } for (; path_index < paths.size() - remove_path_indices.size(); path_index++) //Remaining shifts at the end. { paths[path_index] = paths[path_index + remove_path_indices.size()]; } paths.erase(paths.begin() + path_index, paths.end()); return true; } else { return false; } } }//namespace cura <commit_msg>[CURA-5742] Small refactor of check in case it isn't removed after all.<commit_after>//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/linearAlg2D.h" //Distance from point to line. #include "MergeInfillLines.h" namespace cura { MergeInfillLines::MergeInfillLines(ExtruderPlan& plan, const coord_t nozzle_size, const coord_t maximum_resolution) : extruder_plan(plan), nozzle_size(nozzle_size), maximum_resolution(maximum_resolution) { //Just copy the parameters to their fields. } coord_t MergeInfillLines::calcPathLength(const Point path_start, GCodePath& path) const { Point previous_point = path_start; coord_t result = 0; for (const Point point : path.points) { result += vSize(point - previous_point); previous_point = point; } return result; } /* * first_is_already_merged == false * * o o * / / * / / * / + / ---> -(t)-o-----o * / / * / / * o o * * travel (t) to first location is done through first_path_start_changed and new_first_path_start. * this gets rid of the tiny "blips". Depending on the merged line distance a small gap may appear, but this is * accounted for in the volume. * * first_is_already_merged == true * * o * / * / * o-----o + / ---> o-----------o or with slight o-----o-----o * / / / bend / * / / / / * o o o o * */ bool MergeInfillLines::mergeLinesSideBySide(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start, coord_t& error_area) const { Point average_first_path; coord_t first_path_length = calcPathLength(first_path_start, first_path); coord_t first_path_length_flow = first_path_length * first_path.flow; //To get the volume we don't need to include the line width since it's the same for both lines. const coord_t line_width = first_path.config->getLineWidth(); if (first_is_already_merged) { // take second point of path, first_path.points[0] average_first_path = first_path.points[0]; } else { average_first_path += first_path_start; for (const Point point : first_path.points) { average_first_path += point; } average_first_path /= (first_path.points.size() + 1); } coord_t second_path_length = calcPathLength(second_path_start, second_path); Point average_second_path = second_path_start; for (const Point point : second_path.points) { average_second_path += point; } coord_t second_path_length_flow = second_path_length *= second_path.flow; average_second_path /= (coord_t) (second_path.points.size() + 1); // predict new length and flow and if the new flow is to big, don't merge. conditions in this part must exactly match the actual merging coord_t new_path_length = first_path_length; coord_t dist2_from_line = 0; coord_t new_error_area = 0; coord_t merged_part_length = 0; if (first_is_already_merged) { // check if the new point is a good extension of last part of existing polyline // because of potential accumulation of errors introduced each time a line is merged, we do not allow any error. if (first_path.points.size() > 1) { dist2_from_line = LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size() - 2], first_path.points[first_path.points.size() - 1]); merged_part_length = vSize(first_path.points[first_path.points.size() - 2] - average_second_path); new_error_area = sqrt(dist2_from_line) * merged_part_length / 2; } // The max error margin uses the meshfix_maximum_resolution setting if (first_path.points.size() > 1 && error_area + new_error_area < merged_part_length * maximum_resolution) { new_path_length -= vSize(first_path.points[first_path.points.size() - 2] - first_path.points[first_path.points.size() - 1]); new_path_length += vSize(first_path.points[first_path.points.size() - 2] - average_second_path); } else { new_path_length += vSize(first_path.points[first_path.points.size() - 1] - average_second_path); } } else { new_path_length -= vSize(first_path.points.back() - first_path_start); new_path_length += vSize(average_second_path - average_first_path); } double new_flow = ((first_path_length_flow + second_path_length_flow) / static_cast<double>(new_path_length)); if (new_flow > 2 * nozzle_size / line_width) // line width becomes too wide. { return false; } // do the actual merging if (first_is_already_merged) { // check if the new point is a good extension of last part of existing polyline // because of potential accumulation of errors introduced each time a line is merged, we do not allow any error. if (first_path.points.size() > 1 && error_area + new_error_area < line_width * line_width) { first_path.points[first_path.points.size() - 1] = average_second_path; error_area += new_error_area; } else { first_path.points.push_back(average_second_path); error_area = 0; } } else { new_first_path_start = average_first_path; first_path.points.clear(); first_path.points.push_back(average_second_path); error_area = 0; } first_path.flow = static_cast<double>(first_path_length_flow + second_path_length_flow) / new_path_length; return true; } bool MergeInfillLines::tryMerge(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start, coord_t& error_area) const { const Point first_path_end = first_path.points.back(); const Point second_path_end = second_path.points.back(); const coord_t line_width = first_path.config->getLineWidth(); // Reintroduction of this check prevents [CURA-5674] printing spurious infill-lines to origin: const coord_t line_width_squared = line_width * line_width; if (vSize2(first_path_end - second_path_start) < line_width_squared && vSize2(first_path_start - second_path_end) < line_width_squared) { return false; } //Lines may be adjacent side-by-side then. Point first_path_leave_point; coord_t merged_size2; if (first_is_already_merged) { first_path_leave_point = first_path.points.back(); // this is the point that's going to merge } else { first_path_leave_point = (first_path_start + first_path_end) / 2; } const Point second_path_destination_point = (second_path_start + second_path_end) / 2; const Point merged_direction = second_path_destination_point - first_path_leave_point; if (first_is_already_merged) { merged_size2 = vSize2(second_path_destination_point - first_path.points.back()); // check distance with last point in merged line that is to be replaced } else { merged_size2 = vSize2(merged_direction); } if (merged_size2 > 25 * line_width * line_width) { return false; //Lines are too far away from each other. } if (merged_direction.X == 0 && merged_direction.Y == 0) { return true; // we can just disregard the second point as it's exactly at the leave point of the first path. } // Max 1 line width to the side of the merged_direction if (LinearAlg2D::getDist2FromLine(first_path_end, second_path_destination_point, second_path_destination_point + merged_direction) > line_width * line_width || LinearAlg2D::getDist2FromLine(second_path_start, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width || LinearAlg2D::getDist2FromLine(second_path_end, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width //|| abs(dot(normal(merged_direction, 1000), normal(second_path_end - second_path_start, 1000))) > 866000 // 866000 angle of old second_path with new merged direction should not be too small (30 degrees), as it will introduce holes ) { return false; //One of the lines is too far from the merged line. Lines would be too wide or too far off. } if (first_is_already_merged && first_path.points.size() > 1 && first_path.points[first_path.points.size() - 2] == second_path_destination_point) // yes this can actually happen { return false; } return mergeLinesSideBySide(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start, error_area); } bool MergeInfillLines::mergeInfillLines(std::vector<GCodePath>& paths, const Point& starting_position) const { /* Algorithm overview: 1. Loop over all lines to see if they can be merged. 1a. Check if two adjacent lines can be merged (skipping travel moves in between). 1b. If they can, merge both lines into the first line. 1c. If they are merged, check next that the first line can be merged with the line after the second line. 2. Do a second iteration over all paths to remove the tombstones. */ std::vector<size_t> remove_path_indices; std::set<size_t> is_merged; std::set<size_t> removed; // keep track of what we already removed, so don't remove it again //For each two adjacent lines, see if they can be merged. size_t first_path_index = 0; Point first_path_start = Point(starting_position.X, starting_position.Y); // this one is not going to be overwritten size_t second_path_index = 1; coord_t error_area = 0; for (; second_path_index < paths.size(); second_path_index++) { GCodePath& first_path = paths[first_path_index]; GCodePath& second_path = paths[second_path_index]; Point second_path_start = paths[second_path_index - 1].points.back(); if (second_path.config->isTravelPath()) { continue; //Skip travel paths, we're looking for the first non-travel path. } bool allow_try_merge = true; // see if we meet criteria to merge. should be: travel - path1 not travel - (...) - travel - path2 not travel - travel // we're checking the travels here if (first_path_index <= 1 || !paths[first_path_index - 1].isTravelPath()) // "<= 1" because we don't want the first travel being changed. That may introduce a hole somewhere { allow_try_merge = false; } if (second_path_index + 1 >= paths.size() || !paths[second_path_index + 1].isTravelPath()) { allow_try_merge = false; } if (first_path.config->isTravelPath()) //Don't merge travel moves. { allow_try_merge = false; } if (first_path.config != second_path.config) //Only merge lines that have the same type. { allow_try_merge = false; } if (first_path.config->type != PrintFeatureType::Infill && first_path.config->type != PrintFeatureType::Skin) //Only merge skin and infill lines. { allow_try_merge = false; } const bool first_is_already_merged = is_merged.find(first_path_index) != is_merged.end(); if ((!first_is_already_merged && first_path.points.size() > 1) || second_path.points.size() > 1) { // For now we only merge simple lines, not polylines, to keep it simple. // If the first line is already a merged line, then allow it. allow_try_merge = false; } Point new_first_path_start; if (allow_try_merge && tryMerge(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start, error_area)) { if (!first_is_already_merged) { paths[first_path_index - 1].points.back().X = new_first_path_start.X; paths[first_path_index - 1].points.back().Y = new_first_path_start.Y; } /* If we combine two lines, the next path may also be merged into the fist line, so we do NOT update first_path_index. */ for (size_t to_delete_index = first_path_index + 1; to_delete_index <= second_path_index; to_delete_index++) { if (removed.find(to_delete_index) == removed.end()) // if there are line(s) between first and second, then those lines are already marked as to be deleted, only add the new line(s) { remove_path_indices.push_back(to_delete_index); removed.insert(to_delete_index); } } is_merged.insert(first_path_index); } else { /* If we do not combine, the next iteration we must simply merge the second path with the line after it. */ first_path_index = second_path_index; first_path_start = second_path_start; } } //Delete all removed lines in one pass so that we need to move lines less often. if (!remove_path_indices.empty()) { size_t path_index = remove_path_indices[0]; for (size_t removed_position = 1; removed_position < remove_path_indices.size(); removed_position++) { for (; path_index < remove_path_indices[removed_position] - removed_position; path_index++) { paths[path_index] = paths[path_index + removed_position]; //Shift all paths. } } for (; path_index < paths.size() - remove_path_indices.size(); path_index++) //Remaining shifts at the end. { paths[path_index] = paths[path_index + remove_path_indices.size()]; } paths.erase(paths.begin() + path_index, paths.end()); return true; } else { return false; } } }//namespace cura <|endoftext|>
<commit_before>#include "Atm_pulse.h" Atm_pulse & Atm_pulse::begin( int attached_pin, int minimum_duration ) { const static state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_TIMER EVT_HIGH EVT_LOW ELSE */ /* IDLE */ -1, -1, -1, -1, WAIT, -1, -1, /* WAIT */ -1, -1, -1, PULSE, -1, IDLE, -1, /* PULSE */ ACT_PULSE, -1, -1, -1, -1, IDLE, -1, }; Machine::begin( state_table, ELSE ); pin = attached_pin; timer.set( minimum_duration ); pinMode( pin, INPUT ); return *this; } Atm_pulse & Atm_pulse::onPulse( Machine * machine, uint8_t event ) { client_machine = machine; client_event = event; return *this; } Atm_pulse & Atm_pulse::onPulse( pulsecb_t pulse_callback ) { callback = pulse_callback; return *this; } int Atm_pulse::event( int id ) { switch ( id ) { case EVT_TIMER : return timer.expired( this ); case EVT_HIGH : return digitalRead( pin ); case EVT_LOW : return !digitalRead( pin ); } return 0; } void Atm_pulse::action( int id ) { switch ( id ) { case ACT_PULSE : if ( callback ) { (*callback)(); return; } client_machine->trigger( client_event ); return; } } Atm_pulse & Atm_pulse::trace( Stream & stream ) { setTrace( &stream, atm_serial_debug::trace, "EVT_TIMER\0EVT_HIGH\0EVT_LOW\0ELSE\0IDLE\0WAIT\0PULSE" ); return *this; } // TinyMachine version Att_pulse & Att_pulse::begin( int attached_pin, int minimum_duration ) { const static tiny_state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_TIMER EVT_HIGH EVT_LOW ELSE */ /* IDLE */ -1, -1, -1, -1, WAIT, -1, -1, /* WAIT */ -1, -1, -1, PULSE, -1, IDLE, -1, /* PULSE */ ACT_PULSE, -1, -1, -1, -1, IDLE, -1, }; TinyMachine::begin( state_table, ELSE ); pin = attached_pin; timer.set( minimum_duration ); pinMode( pin, INPUT ); return *this; } Att_pulse & Att_pulse::onPulse( TinyMachine * machine, uint8_t event ) { client_machine = machine; client_event = event; return *this; } Att_pulse & Att_pulse::onPulse( pulsecb_t pulse_callback ) { callback = pulse_callback; return *this; } int Att_pulse::event( int id ) { switch ( id ) { case EVT_TIMER : return timer.expired( this ); case EVT_HIGH : return digitalRead( pin ); case EVT_LOW : return !digitalRead( pin ); } return 0; } void Att_pulse::action( int id ) { switch ( id ) { case ACT_PULSE : if ( callback ) { (*callback)(); return; } client_machine->trigger( client_event ); return; } } <commit_msg>Fixed machine trigger<commit_after>#include "Atm_pulse.h" Atm_pulse & Atm_pulse::begin( int attached_pin, int minimum_duration ) { const static state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_TIMER EVT_HIGH EVT_LOW ELSE */ /* IDLE */ -1, -1, -1, -1, WAIT, -1, -1, /* WAIT */ -1, -1, -1, PULSE, -1, IDLE, -1, /* PULSE */ ACT_PULSE, -1, -1, -1, -1, IDLE, -1, }; Machine::begin( state_table, ELSE ); pin = attached_pin; timer.set( minimum_duration ); pinMode( pin, INPUT ); return *this; } Atm_pulse & Atm_pulse::onPulse( Machine * machine, uint8_t event ) { client_machine = machine; client_event = event; return *this; } Atm_pulse & Atm_pulse::onPulse( pulsecb_t pulse_callback ) { callback = pulse_callback; return *this; } int Atm_pulse::event( int id ) { switch ( id ) { case EVT_TIMER : return timer.expired( this ); case EVT_HIGH : return digitalRead( pin ); case EVT_LOW : return !digitalRead( pin ); } return 0; } void Atm_pulse::action( int id ) { switch ( id ) { case ACT_PULSE : if ( callback ) { (*callback)(); return; } if ( client_machine ) client_machine->trigger( client_event ); return; } } Atm_pulse & Atm_pulse::trace( Stream & stream ) { setTrace( &stream, atm_serial_debug::trace, "EVT_TIMER\0EVT_HIGH\0EVT_LOW\0ELSE\0IDLE\0WAIT\0PULSE" ); return *this; } // TinyMachine version Att_pulse & Att_pulse::begin( int attached_pin, int minimum_duration ) { const static tiny_state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_TIMER EVT_HIGH EVT_LOW ELSE */ /* IDLE */ -1, -1, -1, -1, WAIT, -1, -1, /* WAIT */ -1, -1, -1, PULSE, -1, IDLE, -1, /* PULSE */ ACT_PULSE, -1, -1, -1, -1, IDLE, -1, }; TinyMachine::begin( state_table, ELSE ); pin = attached_pin; timer.set( minimum_duration ); pinMode( pin, INPUT ); return *this; } Att_pulse & Att_pulse::onPulse( TinyMachine * machine, uint8_t event ) { client_machine = machine; client_event = event; return *this; } Att_pulse & Att_pulse::onPulse( pulsecb_t pulse_callback ) { callback = pulse_callback; return *this; } int Att_pulse::event( int id ) { switch ( id ) { case EVT_TIMER : return timer.expired( this ); case EVT_HIGH : return digitalRead( pin ); case EVT_LOW : return !digitalRead( pin ); } return 0; } void Att_pulse::action( int id ) { switch ( id ) { case ACT_PULSE : if ( callback ) { (*callback)(); return; } if ( client_machine ) client_machine->trigger( client_event ); return; } } <|endoftext|>
<commit_before>/* Automaton.cpp - Library for creating and running Finite State Machines. Published under the MIT License (MIT), Copyright (c) 2015, J.P. van der Landen */ #include "Automaton.h" void atm_timer::set( uint32_t v ) { value = v; } void atm_timer::begin( BaseMachine * machine, uint32_t v ) { pmachine = machine; value = v; } int atm_timer_millis::expired( void ) { return value == ATM_TIMER_OFF ? 0 : millis() - pmachine->state_millis >= value; } int atm_timer_micros::expired( void ) { return value == ATM_TIMER_OFF ? 0 : micros() - pmachine->state_micros >= value; } void atm_counter::set( uint16_t v ) { value = v; } uint16_t atm_counter::decrement( void ) { return value > 0 && value != ATM_COUNTER_OFF ? --value : 0; } uint8_t atm_counter::expired() { return value == ATM_COUNTER_OFF ? 0 : ( value > 0 ? 0 : 1 ); } Machine & Machine::state(state_t state) { next = state; last_trigger = -1; sleep = 0; if ( msg_autoclear ) msgClear(); return *this; } state_t Machine::state() { return current; } int Machine::trigger( int evt ) { if ( current > -1 ) { int new_state = read_state( state_table + ( current * state_width ) + evt + ATM_ON_EXIT + 1 ); if ( new_state > -1 ) { state( new_state ); last_trigger = evt; return 1; } } return 0; } Machine & Machine::toggle( state_t state1, state_t state2 ) { state( current == state1 ? state2 : state1 ); return *this; } Machine & Machine::onSwitch( swcb_num_t callback ) { callback_num = callback; return *this; } Machine & Machine::onSwitch( swcb_sym_t callback, const char sym_s[], const char sym_e[] ) { callback_sym = callback; sym_states = sym_s; sym_events = sym_e; return *this; } Machine & Machine::label( const char label[] ) { inst_label = label; return *this; } int8_t Machine::priority() { return prio; } Machine & Machine::priority( int8_t priority ) { prio = priority; return *this; } // .asleep() Returns true if the machine is in a sleeping state uint8_t BaseMachine::asleep() { return sleep; } Machine & Machine::begin( const state_t* tbl, int width ) { state_table = tbl; state_width = ATM_ON_EXIT + width + 2; prio = ATM_DEFAULT_PRIO; if ( !inst_label ) inst_label = class_label; return *this; } Machine & Machine::msgQueue( atm_msg_t msg[], int width ) { msg_table = msg; msg_width = width; return *this; } Machine & Machine::msgQueue( atm_msg_t msg[], int width, uint8_t autoclear ) { msg_table = msg; msg_width = width; msg_autoclear = autoclear; return *this; } unsigned char Machine::pinChange( uint8_t pin ) { unsigned char v = digitalRead( pin ) ? 1 : 0; if ( (( pinstate >> pin ) & 1 ) != ( v == 1 ) ) { pinstate ^= ( (uint32_t)1 << pin ); return 1; } return 0; } int Machine::msgRead( uint8_t id_msg ) // Checks msg queue and removes 1 msg { if ( msg_table[id_msg] > 0 ) { msg_table[id_msg]--; return 1; } return 0; } int Machine::msgRead( uint8_t id_msg, int cnt ) { if ( msg_table[id_msg] > 0 ) { if ( cnt >= msg_table[id_msg] ) { msg_table[id_msg] = 0; } else { msg_table[id_msg] -= cnt; } return 1; } return 0; } int Machine::msgRead( uint8_t id_msg, int cnt, int clear ) { if ( msg_table[id_msg] > 0 ) { if ( cnt >= msg_table[id_msg] ) { msg_table[id_msg] = 0; } else { msg_table[id_msg] -= cnt; } if ( clear ) { for ( int i = 0; i < msg_width; i++ ) { msg_table[i] = 0; } } return 1; } return 0; } int Machine::msgPeek( uint8_t id_msg ) { return msg_table[id_msg]; } int Machine::msgClear( uint8_t id_msg ) // Destructive read (clears queue for this type) { sleep = 0; if ( msg_table[id_msg] > 0 ) { msg_table[id_msg] = 0; return 1; } return 0; } Machine & Machine::msgClear() { sleep = 0; for ( int i = 0; i < msg_width; i++ ) { msg_table[i] = 0; } return *this; } Machine & Machine::msgWrite( uint8_t id_msg ) { sleep = 0; msg_table[id_msg]++; return *this; } Machine & Machine::msgWrite( uint8_t id_msg, int cnt ) { sleep = 0; msg_table[id_msg] += cnt; return *this; } const char * Machine::map_symbol( int id, const char map[] ) { int cnt = 0; int i = 0; if ( id == -1 ) return "*NONE*"; if ( id == 0 ) return map; while ( 1 ) { if ( map[i] == '\0' && ++cnt == id ) { i++; break; } i++; } return &map[i]; } // .cycle() Executes one cycle of a state machine Machine & Machine::cycle() { if ( !sleep ) { cycles++; if ( next != -1 ) { action( ATM_ON_SWITCH ); if ( callback_sym || callback_num ) { if ( callback_sym ) { callback_sym( inst_label, map_symbol( current, sym_states ), map_symbol( next, sym_states ), map_symbol( last_trigger, sym_events ), millis() - state_millis, cycles ); } else { callback_num( inst_label, current, next, last_trigger, millis() - state_millis, cycles ); } } if ( current > -1 ) action( read_state( state_table + ( current * state_width ) + ATM_ON_EXIT ) ); previous = current; current = next; next = -1; state_millis = millis(); state_micros = micros(); action( read_state( state_table + ( current * state_width ) + ATM_ON_ENTER ) ); sleep = read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ) == ATM_SLEEP; cycles = 0; } state_t i = read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ); if ( i != -1 ) { action( i ); } for ( i = ATM_ON_EXIT + 1; i < state_width; i++ ) { if ( ( read_state( state_table + ( current * state_width ) + i ) != -1 ) && ( i == state_width - 1 || event( i - ATM_ON_EXIT - 1 ) ) ) { state( read_state( state_table + ( current * state_width ) + i ) ); last_trigger = i - ATM_ON_EXIT - 1; return *this; } } } return *this; } // TINY MACHINE TinyMachine & TinyMachine::state(tiny_state_t state) { next = state; sleep = 0; return *this; } tiny_state_t TinyMachine::state() { return current; } int TinyMachine::trigger( int evt ) { if ( current > -1 ) { int new_state = tiny_read_state( state_table + ( current * state_width ) + evt + ATM_ON_EXIT + 1 ); if ( new_state > -1 ) { state( new_state ); return 1; } } return 0; } TinyMachine & TinyMachine::begin( const tiny_state_t* tbl, int width ) { state_table = tbl; state_width = ATM_ON_EXIT + width + 2; return *this; } // .cycle() Executes one cycle of a state machine TinyMachine & TinyMachine::cycle() { if ( !sleep ) { if ( next != -1 ) { action( ATM_ON_SWITCH ); if ( current > -1 ) action( tiny_read_state( state_table + ( current * state_width ) + ATM_ON_EXIT ) ); previous = current; current = next; next = -1; state_millis = millis(); state_micros = micros(); action( tiny_read_state( state_table + ( current * state_width ) + ATM_ON_ENTER ) ); sleep = tiny_read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ) == ATM_SLEEP; } tiny_state_t i = tiny_read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ); if ( i != -1 ) { action( i ); } for ( i = ATM_ON_EXIT + 1; i < state_width; i++ ) { if ( ( tiny_read_state( state_table + ( current * state_width ) + i ) != -1 ) && ( i == state_width - 1 || event( i - ATM_ON_EXIT - 1 ) ) ) { state( tiny_read_state( state_table + ( current * state_width ) + i ) ); return *this; } } } return *this; } // FACTORY // .calibrate() Distributes the machines in the inventory to the appropriate priority queues void Factory::calibrate( void ) { // Reset all priority queues to empty lists for ( int8_t i = 0; i < ATM_NO_OF_QUEUES; i++ ) priority_root[i] = 0; // Walk the inventory list that contains all state machines in this factory Machine * m = inventory_root; while ( m ) { // Prepend every machine to the appropriate priority queue if ( m->prio < ATM_NO_OF_QUEUES ) { m->priority_next = priority_root[m->prio]; priority_root[m->prio] = m; } m = m->inventory_next; } recalibrate = 0; } // .run( q ) Traverses an individual priority queue and cycles the machines in it once (except for queue 0) void Factory::run( int q ) { Machine * m = priority_root[ q ]; while ( m ) { if ( q > 0 && !m->sleep ) m->cycle(); // Request a recalibrate if the prio field doesn't match the current queue if ( m->prio != q ) recalibrate = 1; // Move to the next machine m = m->priority_next; } } // .add( machine ) Adds a state machine to the factory by prepending it to the inventory list Factory & Factory::add( Machine & machine ) { machine.inventory_next = inventory_root; inventory_root = &machine; machine.factory = this; recalibrate = 1; machine.cycle(); return *this; } // .find() Search the factory inventory for a machine by instance label Machine * Factory::find( const char label[] ) { Machine * m = inventory_root; while ( m ) { if ( strcmp( label, m->inst_label ) == 0 ) { return m; } m = m->inventory_next; } return 0; } int Factory::msgSend( const char label[], int msg ) { Machine * m = find( label ); if ( m ) { m->msgWrite( msg ); return 1; } return 0; } int Factory::msgSendClass( const char label[], int msg ) { int r = 0; Machine * m = inventory_root; while ( m ) { if ( strcmp( label, m->class_label ) == 0 ) { m->msgWrite( msg ); r = 1; } m = m->inventory_next; } return 0; } // .cycle() executes one factory cycle (runs all priority queues a certain number of times) Factory & Factory::cycle( void ) { if ( recalibrate ) calibrate(); run( 1 ); run( 2 ); run( 1 ); run( 2 ); run( 1 ); run( 3 ); run( 1 ); run( 4 ); run( 1 ); run( 2 ); run( 1 ); run( 3 ); run( 1 ); run( 2 ); run( 1 ); run( 0 ); return *this; } // TINYFACTORY - A factory for TinyMachines // .add( machine ) Adds a state machine to the factory by prepending it to the inventory list TinyFactory & TinyFactory::add( TinyMachine & machine ) { machine.inventory_next = inventory_root; inventory_root = &machine; machine.cycle(); return *this; } // .cycle() executes the factory cycle TinyFactory & TinyFactory::cycle( void ) { TinyMachine * m = inventory_root; while ( m ) { if ( !m->sleep ) m->cycle(); // Move to the next machine m = m->inventory_next; } return *this; } <commit_msg>Adapted factory::msgSend()<commit_after>/* Automaton.cpp - Library for creating and running Finite State Machines. Published under the MIT License (MIT), Copyright (c) 2015, J.P. van der Landen */ #include "Automaton.h" void atm_timer::set( uint32_t v ) { value = v; } void atm_timer::begin( BaseMachine * machine, uint32_t v ) { pmachine = machine; value = v; } int atm_timer_millis::expired( void ) { return value == ATM_TIMER_OFF ? 0 : millis() - pmachine->state_millis >= value; } int atm_timer_micros::expired( void ) { return value == ATM_TIMER_OFF ? 0 : micros() - pmachine->state_micros >= value; } void atm_counter::set( uint16_t v ) { value = v; } uint16_t atm_counter::decrement( void ) { return value > 0 && value != ATM_COUNTER_OFF ? --value : 0; } uint8_t atm_counter::expired() { return value == ATM_COUNTER_OFF ? 0 : ( value > 0 ? 0 : 1 ); } Machine & Machine::state(state_t state) { next = state; last_trigger = -1; sleep = 0; if ( msg_autoclear ) msgClear(); return *this; } state_t Machine::state() { return current; } int Machine::trigger( int evt ) { if ( current > -1 ) { int new_state = read_state( state_table + ( current * state_width ) + evt + ATM_ON_EXIT + 1 ); if ( new_state > -1 ) { state( new_state ); last_trigger = evt; return 1; } } return 0; } Machine & Machine::toggle( state_t state1, state_t state2 ) { state( current == state1 ? state2 : state1 ); return *this; } Machine & Machine::onSwitch( swcb_num_t callback ) { callback_num = callback; return *this; } Machine & Machine::onSwitch( swcb_sym_t callback, const char sym_s[], const char sym_e[] ) { callback_sym = callback; sym_states = sym_s; sym_events = sym_e; return *this; } Machine & Machine::label( const char label[] ) { inst_label = label; return *this; } int8_t Machine::priority() { return prio; } Machine & Machine::priority( int8_t priority ) { prio = priority; return *this; } // .asleep() Returns true if the machine is in a sleeping state uint8_t BaseMachine::asleep() { return sleep; } Machine & Machine::begin( const state_t* tbl, int width ) { state_table = tbl; state_width = ATM_ON_EXIT + width + 2; prio = ATM_DEFAULT_PRIO; if ( !inst_label ) inst_label = class_label; return *this; } Machine & Machine::msgQueue( atm_msg_t msg[], int width ) { msg_table = msg; msg_width = width; return *this; } Machine & Machine::msgQueue( atm_msg_t msg[], int width, uint8_t autoclear ) { msg_table = msg; msg_width = width; msg_autoclear = autoclear; return *this; } unsigned char Machine::pinChange( uint8_t pin ) { unsigned char v = digitalRead( pin ) ? 1 : 0; if ( (( pinstate >> pin ) & 1 ) != ( v == 1 ) ) { pinstate ^= ( (uint32_t)1 << pin ); return 1; } return 0; } int Machine::msgRead( uint8_t id_msg ) // Checks msg queue and removes 1 msg { if ( msg_table[id_msg] > 0 ) { msg_table[id_msg]--; return 1; } return 0; } int Machine::msgRead( uint8_t id_msg, int cnt ) { if ( msg_table[id_msg] > 0 ) { if ( cnt >= msg_table[id_msg] ) { msg_table[id_msg] = 0; } else { msg_table[id_msg] -= cnt; } return 1; } return 0; } int Machine::msgRead( uint8_t id_msg, int cnt, int clear ) { if ( msg_table[id_msg] > 0 ) { if ( cnt >= msg_table[id_msg] ) { msg_table[id_msg] = 0; } else { msg_table[id_msg] -= cnt; } if ( clear ) { for ( int i = 0; i < msg_width; i++ ) { msg_table[i] = 0; } } return 1; } return 0; } int Machine::msgPeek( uint8_t id_msg ) { return msg_table[id_msg]; } int Machine::msgClear( uint8_t id_msg ) // Destructive read (clears queue for this type) { sleep = 0; if ( msg_table[id_msg] > 0 ) { msg_table[id_msg] = 0; return 1; } return 0; } Machine & Machine::msgClear() { sleep = 0; for ( int i = 0; i < msg_width; i++ ) { msg_table[i] = 0; } return *this; } Machine & Machine::msgWrite( uint8_t id_msg ) { sleep = 0; msg_table[id_msg]++; return *this; } Machine & Machine::msgWrite( uint8_t id_msg, int cnt ) { sleep = 0; msg_table[id_msg] += cnt; return *this; } const char * Machine::map_symbol( int id, const char map[] ) { int cnt = 0; int i = 0; if ( id == -1 ) return "*NONE*"; if ( id == 0 ) return map; while ( 1 ) { if ( map[i] == '\0' && ++cnt == id ) { i++; break; } i++; } return &map[i]; } // .cycle() Executes one cycle of a state machine Machine & Machine::cycle() { if ( !sleep ) { cycles++; if ( next != -1 ) { action( ATM_ON_SWITCH ); if ( callback_sym || callback_num ) { if ( callback_sym ) { callback_sym( inst_label, map_symbol( current, sym_states ), map_symbol( next, sym_states ), map_symbol( last_trigger, sym_events ), millis() - state_millis, cycles ); } else { callback_num( inst_label, current, next, last_trigger, millis() - state_millis, cycles ); } } if ( current > -1 ) action( read_state( state_table + ( current * state_width ) + ATM_ON_EXIT ) ); previous = current; current = next; next = -1; state_millis = millis(); state_micros = micros(); action( read_state( state_table + ( current * state_width ) + ATM_ON_ENTER ) ); sleep = read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ) == ATM_SLEEP; cycles = 0; } state_t i = read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ); if ( i != -1 ) { action( i ); } for ( i = ATM_ON_EXIT + 1; i < state_width; i++ ) { if ( ( read_state( state_table + ( current * state_width ) + i ) != -1 ) && ( i == state_width - 1 || event( i - ATM_ON_EXIT - 1 ) ) ) { state( read_state( state_table + ( current * state_width ) + i ) ); last_trigger = i - ATM_ON_EXIT - 1; return *this; } } } return *this; } // TINY MACHINE TinyMachine & TinyMachine::state(tiny_state_t state) { next = state; sleep = 0; return *this; } tiny_state_t TinyMachine::state() { return current; } int TinyMachine::trigger( int evt ) { if ( current > -1 ) { int new_state = tiny_read_state( state_table + ( current * state_width ) + evt + ATM_ON_EXIT + 1 ); if ( new_state > -1 ) { state( new_state ); return 1; } } return 0; } TinyMachine & TinyMachine::begin( const tiny_state_t* tbl, int width ) { state_table = tbl; state_width = ATM_ON_EXIT + width + 2; return *this; } // .cycle() Executes one cycle of a state machine TinyMachine & TinyMachine::cycle() { if ( !sleep ) { if ( next != -1 ) { action( ATM_ON_SWITCH ); if ( current > -1 ) action( tiny_read_state( state_table + ( current * state_width ) + ATM_ON_EXIT ) ); previous = current; current = next; next = -1; state_millis = millis(); state_micros = micros(); action( tiny_read_state( state_table + ( current * state_width ) + ATM_ON_ENTER ) ); sleep = tiny_read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ) == ATM_SLEEP; } tiny_state_t i = tiny_read_state( state_table + ( current * state_width ) + ATM_ON_LOOP ); if ( i != -1 ) { action( i ); } for ( i = ATM_ON_EXIT + 1; i < state_width; i++ ) { if ( ( tiny_read_state( state_table + ( current * state_width ) + i ) != -1 ) && ( i == state_width - 1 || event( i - ATM_ON_EXIT - 1 ) ) ) { state( tiny_read_state( state_table + ( current * state_width ) + i ) ); return *this; } } } return *this; } // FACTORY // .calibrate() Distributes the machines in the inventory to the appropriate priority queues void Factory::calibrate( void ) { // Reset all priority queues to empty lists for ( int8_t i = 0; i < ATM_NO_OF_QUEUES; i++ ) priority_root[i] = 0; // Walk the inventory list that contains all state machines in this factory Machine * m = inventory_root; while ( m ) { // Prepend every machine to the appropriate priority queue if ( m->prio < ATM_NO_OF_QUEUES ) { m->priority_next = priority_root[m->prio]; priority_root[m->prio] = m; } m = m->inventory_next; } recalibrate = 0; } // .run( q ) Traverses an individual priority queue and cycles the machines in it once (except for queue 0) void Factory::run( int q ) { Machine * m = priority_root[ q ]; while ( m ) { if ( q > 0 && !m->sleep ) m->cycle(); // Request a recalibrate if the prio field doesn't match the current queue if ( m->prio != q ) recalibrate = 1; // Move to the next machine m = m->priority_next; } } // .add( machine ) Adds a state machine to the factory by prepending it to the inventory list Factory & Factory::add( Machine & machine ) { machine.inventory_next = inventory_root; inventory_root = &machine; machine.factory = this; recalibrate = 1; machine.cycle(); return *this; } // .find() Search the factory inventory for a machine by instance label Machine * Factory::find( const char label[] ) { Machine * m = inventory_root; while ( m ) { if ( strcmp( label, m->inst_label ) == 0 ) { return m; } m = m->inventory_next; } return 0; } int Factory::msgSend( const char label[], int msg ) { int r = 0; Machine * m = inventory_root; while ( m ) { if ( strcmp( label, m->inst_label ) == 0 ) { m->msgWrite( msg ); r = 1; } m = m->inventory_next; } return 0; } int Factory::msgSendClass( const char label[], int msg ) { int r = 0; Machine * m = inventory_root; while ( m ) { if ( strcmp( label, m->class_label ) == 0 ) { m->msgWrite( msg ); r = 1; } m = m->inventory_next; } return 0; } // .cycle() executes one factory cycle (runs all priority queues a certain number of times) Factory & Factory::cycle( void ) { if ( recalibrate ) calibrate(); run( 1 ); run( 2 ); run( 1 ); run( 2 ); run( 1 ); run( 3 ); run( 1 ); run( 4 ); run( 1 ); run( 2 ); run( 1 ); run( 3 ); run( 1 ); run( 2 ); run( 1 ); run( 0 ); return *this; } // TINYFACTORY - A factory for TinyMachines // .add( machine ) Adds a state machine to the factory by prepending it to the inventory list TinyFactory & TinyFactory::add( TinyMachine & machine ) { machine.inventory_next = inventory_root; inventory_root = &machine; machine.cycle(); return *this; } // .cycle() executes the factory cycle TinyFactory & TinyFactory::cycle( void ) { TinyMachine * m = inventory_root; while ( m ) { if ( !m->sleep ) m->cycle(); // Move to the next machine m = m->inventory_next; } return *this; } <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <sstream> #include <cstring> #include <string> #include "BoyerMoore.h" using namespace v8; using namespace node; namespace { // this is an application of the Curiously Recurring Template Pattern template <class Derived> struct UnaryAction { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope); Handle<Value> operator()(const Arguments& args) { HandleScope scope; Local<Object> self = args.This(); if (!Buffer::HasInstance(self)) { return ThrowException(Exception::TypeError(String::New( "Argument should be a buffer object."))); } return static_cast<Derived*>(this)->apply(self, args, scope); } }; template <class Derived> struct BinaryAction { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope); Handle<Value> operator()(const Arguments& args) { HandleScope scope; Local<Object> self = args.This(); if (!Buffer::HasInstance(self)) { return ThrowException(Exception::TypeError(String::New( "Argument should be a buffer object."))); } if (args[0]->IsString()) { String::Utf8Value s(args[0]->ToString()); return static_cast<Derived*>(this)->apply(self, *s, s.length(), args, scope); } if (Buffer::HasInstance(args[0])) { Local<Object> other = args[0]->ToObject(); return static_cast<Derived*>(this)->apply( self, Buffer::Data(other), Buffer::Length(other), args, scope); } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New( "Second argument must be a string or a buffer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; // // helper functions // Handle<Value> clear(Handle<Object>& buffer, int c) { size_t length = Buffer::Length(buffer); char* data = Buffer::Data(buffer); memset(data, c, length); return buffer; } Handle<Value> fill(Handle<Object>& buffer, void* pattern, size_t size) { size_t length = Buffer::Length(buffer); char* data = Buffer::Data(buffer); if (size >= length) { memcpy(data, pattern, length); } else { const int n_copies = length / size; const int remainder = length % size; for (int i = 0; i < n_copies; i++) { memcpy(data + size * i, pattern, size); } memcpy(data + size * n_copies, pattern, remainder); } return buffer; } int compare(Handle<Object>& buffer, const char* data2, size_t length2) { size_t length = Buffer::Length(buffer); if (length != length2) { return length > length2 ? 1 : -1; } char* data = Buffer::Data(buffer); return memcmp(data, data2, length); } // // actions // struct ClearAction: UnaryAction<ClearAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { return clear(buffer, 0); } }; struct FillAction: UnaryAction<FillAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { if (args[0]->IsInt32()) { int c = args[0]->ToInt32()->Int32Value(); return clear(buffer, c); } if (args[0]->IsString()) { String::Utf8Value s(args[0]->ToString()); return fill(buffer, *s, s.length()); } if (Buffer::HasInstance(args[0])) { Handle<Object> other = args[0]->ToObject(); size_t length = Buffer::Length(other); char* data = Buffer::Data(other); return fill(buffer, data, length); } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New( "Second argument should be either a string, a buffer or an integer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; struct ReverseAction: UnaryAction<ReverseAction> { // O(n/2) for all cases which is okay, might be optimized some more with whole-word swaps // XXX won't this trash the L1 cache something awful? Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { char* head = Buffer::Data(buffer); char* tail = head + Buffer::Length(buffer) - 1; // xor swap, just because I can while (head < tail) *head ^= *tail, *tail ^= *head, *head ^= *tail, ++head, --tail; return buffer; } }; struct EqualsAction: BinaryAction<EqualsAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) { return compare(buffer, data, size) == 0 ? True() : False(); } }; struct CompareAction: BinaryAction<CompareAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) { return scope.Close(Integer::New(compare(buffer, data, size))); } }; struct IndexOfAction: BinaryAction<IndexOfAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data2, size_t size2, const Arguments& args, HandleScope& scope) { const char* data = Buffer::Data(buffer); size_t size = Buffer::Length(buffer); const char* p = boyermoore_search(data, size, data2, size2); const ptrdiff_t offset = p ? (p - data) : -1; return scope.Close(Integer::New(offset)); } }; static char toHexTable[] = "0123456789abcdef"; // CHECKME is this cache efficient? static char fromHexTable[] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1, 10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; inline Handle<Value> decodeHex(const char* data, size_t size, const Arguments& args, HandleScope& scope) { if (size & 1) { return ThrowException(Exception::Error(String::New( "Odd string length, this is not hexadecimal data."))); } if (size == 0) { return String::Empty(); } Handle<Object>& buffer = Buffer::New(size / 2)->handle_; for (char* s = Buffer::Data(buffer); size > 0; size -= 2) { int a = fromHexTable[*data++]; int b = fromHexTable[*data++]; if (a == -1 || b == -1) { return ThrowException(Exception::Error(String::New( "This is not hexadecimal data."))); } *s++ = b | (a << 4); } return buffer; } struct FromHexAction: UnaryAction<FromHexAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { const char* data = Buffer::Data(buffer); size_t length = Buffer::Length(buffer); return decodeHex(data, length, args, scope); } }; struct ToHexAction: UnaryAction<ToHexAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { const size_t size = Buffer::Length(buffer); const char* data = Buffer::Data(buffer); if (size == 0) { return String::Empty(); } std::string s(size * 2, 0); for (size_t i = 0; i < size; ++i) { const int c = data[i]; s[i * 2] = toHexTable[c >> 4]; s[i * 2 + 1] = toHexTable[c & 15]; } return scope.Close(String::New(s.c_str(), s.size())); } }; // // V8 function callbacks // Handle<Value> Clear(const Arguments& args) { return ClearAction()(args); } Handle<Value> Fill(const Arguments& args) { return FillAction()(args); } Handle<Value> Reverse(const Arguments& args) { return ReverseAction()(args); } Handle<Value> Equals(const Arguments& args) { return EqualsAction()(args); } Handle<Value> Compare(const Arguments& args) { return CompareAction()(args); } Handle<Value> IndexOf(const Arguments& args) { return IndexOfAction()(args); } Handle<Value> FromHex(const Arguments& args) { return FromHexAction()(args); } Handle<Value> ToHex(const Arguments& args) { return ToHexAction()(args); } Handle<Value> Concat(const Arguments& args) { HandleScope scope; size_t size = 0; for (int index = 0, length = args.Length(); index < length; ++index) { Local<Value> arg = args[index]; if (arg->IsString()) { // Utf8Length() because we need the length in bytes, not characters size += arg->ToString()->Utf8Length(); } else if (Buffer::HasInstance(arg)) { size += Buffer::Length(arg->ToObject()); } else { std::stringstream s; s << "Argument #" << index << " is neither a string nor a buffer object."; const char* message = s.str().c_str(); return ThrowException(Exception::TypeError(String::New(message))); } } Buffer& dst = *Buffer::New(size); char* s = Buffer::Data(dst.handle_); for (int index = 0, length = args.Length(); index < length; ++index) { Local<Value> arg = args[index]; if (arg->IsString()) { String::Utf8Value v(arg->ToString()); memcpy(s, *v, v.length()); s += v.length(); } else if (Buffer::HasInstance(arg)) { Local<Object> b = arg->ToObject(); const char* data = Buffer::Data(b); size_t length = Buffer::Length(b); memcpy(s, data, length); s += length; } else { return ThrowException(Exception::Error(String::New( "Congratulations! You have run into a bug: argument is neither a string nor a buffer object. " "Please make the world a better place and report it."))); } } return scope.Close(dst.handle_); } extern "C" void init(Handle<Object> target) { target->Set(String::NewSymbol("concat"), FunctionTemplate::New(Concat)->GetFunction()); target->Set(String::NewSymbol("fill"), FunctionTemplate::New(Fill)->GetFunction()); target->Set(String::NewSymbol("clear"), FunctionTemplate::New(Clear)->GetFunction()); target->Set(String::NewSymbol("reverse"), FunctionTemplate::New(Reverse)->GetFunction()); target->Set(String::NewSymbol("equals"), FunctionTemplate::New(Equals)->GetFunction()); target->Set(String::NewSymbol("compare"), FunctionTemplate::New(Compare)->GetFunction()); target->Set(String::NewSymbol("indexOf"), FunctionTemplate::New(IndexOf)->GetFunction()); target->Set(String::NewSymbol("fromHex"), FunctionTemplate::New(FromHex)->GetFunction()); target->Set(String::NewSymbol("toHex"), FunctionTemplate::New(ToHex)->GetFunction()); } } <commit_msg>Register module with NODE_MODULE.<commit_after>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <sstream> #include <cstring> #include <string> #include "BoyerMoore.h" using namespace v8; using namespace node; namespace { // this is an application of the Curiously Recurring Template Pattern template <class Derived> struct UnaryAction { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope); Handle<Value> operator()(const Arguments& args) { HandleScope scope; Local<Object> self = args.This(); if (!Buffer::HasInstance(self)) { return ThrowException(Exception::TypeError(String::New( "Argument should be a buffer object."))); } return static_cast<Derived*>(this)->apply(self, args, scope); } }; template <class Derived> struct BinaryAction { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope); Handle<Value> operator()(const Arguments& args) { HandleScope scope; Local<Object> self = args.This(); if (!Buffer::HasInstance(self)) { return ThrowException(Exception::TypeError(String::New( "Argument should be a buffer object."))); } if (args[0]->IsString()) { String::Utf8Value s(args[0]->ToString()); return static_cast<Derived*>(this)->apply(self, *s, s.length(), args, scope); } if (Buffer::HasInstance(args[0])) { Local<Object> other = args[0]->ToObject(); return static_cast<Derived*>(this)->apply( self, Buffer::Data(other), Buffer::Length(other), args, scope); } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New( "Second argument must be a string or a buffer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; // // helper functions // Handle<Value> clear(Handle<Object>& buffer, int c) { size_t length = Buffer::Length(buffer); char* data = Buffer::Data(buffer); memset(data, c, length); return buffer; } Handle<Value> fill(Handle<Object>& buffer, void* pattern, size_t size) { size_t length = Buffer::Length(buffer); char* data = Buffer::Data(buffer); if (size >= length) { memcpy(data, pattern, length); } else { const int n_copies = length / size; const int remainder = length % size; for (int i = 0; i < n_copies; i++) { memcpy(data + size * i, pattern, size); } memcpy(data + size * n_copies, pattern, remainder); } return buffer; } int compare(Handle<Object>& buffer, const char* data2, size_t length2) { size_t length = Buffer::Length(buffer); if (length != length2) { return length > length2 ? 1 : -1; } char* data = Buffer::Data(buffer); return memcmp(data, data2, length); } // // actions // struct ClearAction: UnaryAction<ClearAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { return clear(buffer, 0); } }; struct FillAction: UnaryAction<FillAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { if (args[0]->IsInt32()) { int c = args[0]->ToInt32()->Int32Value(); return clear(buffer, c); } if (args[0]->IsString()) { String::Utf8Value s(args[0]->ToString()); return fill(buffer, *s, s.length()); } if (Buffer::HasInstance(args[0])) { Handle<Object> other = args[0]->ToObject(); size_t length = Buffer::Length(other); char* data = Buffer::Data(other); return fill(buffer, data, length); } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New( "Second argument should be either a string, a buffer or an integer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; struct ReverseAction: UnaryAction<ReverseAction> { // O(n/2) for all cases which is okay, might be optimized some more with whole-word swaps // XXX won't this trash the L1 cache something awful? Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { char* head = Buffer::Data(buffer); char* tail = head + Buffer::Length(buffer) - 1; // xor swap, just because I can while (head < tail) *head ^= *tail, *tail ^= *head, *head ^= *tail, ++head, --tail; return buffer; } }; struct EqualsAction: BinaryAction<EqualsAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) { return compare(buffer, data, size) == 0 ? True() : False(); } }; struct CompareAction: BinaryAction<CompareAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data, size_t size, const Arguments& args, HandleScope& scope) { return scope.Close(Integer::New(compare(buffer, data, size))); } }; struct IndexOfAction: BinaryAction<IndexOfAction> { Handle<Value> apply(Handle<Object>& buffer, const char* data2, size_t size2, const Arguments& args, HandleScope& scope) { const char* data = Buffer::Data(buffer); size_t size = Buffer::Length(buffer); const char* p = boyermoore_search(data, size, data2, size2); const ptrdiff_t offset = p ? (p - data) : -1; return scope.Close(Integer::New(offset)); } }; static char toHexTable[] = "0123456789abcdef"; // CHECKME is this cache efficient? static char fromHexTable[] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1, 10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; inline Handle<Value> decodeHex(const char* data, size_t size, const Arguments& args, HandleScope& scope) { if (size & 1) { return ThrowException(Exception::Error(String::New( "Odd string length, this is not hexadecimal data."))); } if (size == 0) { return String::Empty(); } Handle<Object>& buffer = Buffer::New(size / 2)->handle_; for (char* s = Buffer::Data(buffer); size > 0; size -= 2) { int a = fromHexTable[*data++]; int b = fromHexTable[*data++]; if (a == -1 || b == -1) { return ThrowException(Exception::Error(String::New( "This is not hexadecimal data."))); } *s++ = b | (a << 4); } return buffer; } struct FromHexAction: UnaryAction<FromHexAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { const char* data = Buffer::Data(buffer); size_t length = Buffer::Length(buffer); return decodeHex(data, length, args, scope); } }; struct ToHexAction: UnaryAction<ToHexAction> { Handle<Value> apply(Handle<Object>& buffer, const Arguments& args, HandleScope& scope) { const size_t size = Buffer::Length(buffer); const char* data = Buffer::Data(buffer); if (size == 0) { return String::Empty(); } std::string s(size * 2, 0); for (size_t i = 0; i < size; ++i) { const int c = data[i]; s[i * 2] = toHexTable[c >> 4]; s[i * 2 + 1] = toHexTable[c & 15]; } return scope.Close(String::New(s.c_str(), s.size())); } }; // // V8 function callbacks // Handle<Value> Clear(const Arguments& args) { return ClearAction()(args); } Handle<Value> Fill(const Arguments& args) { return FillAction()(args); } Handle<Value> Reverse(const Arguments& args) { return ReverseAction()(args); } Handle<Value> Equals(const Arguments& args) { return EqualsAction()(args); } Handle<Value> Compare(const Arguments& args) { return CompareAction()(args); } Handle<Value> IndexOf(const Arguments& args) { return IndexOfAction()(args); } Handle<Value> FromHex(const Arguments& args) { return FromHexAction()(args); } Handle<Value> ToHex(const Arguments& args) { return ToHexAction()(args); } Handle<Value> Concat(const Arguments& args) { HandleScope scope; size_t size = 0; for (int index = 0, length = args.Length(); index < length; ++index) { Local<Value> arg = args[index]; if (arg->IsString()) { // Utf8Length() because we need the length in bytes, not characters size += arg->ToString()->Utf8Length(); } else if (Buffer::HasInstance(arg)) { size += Buffer::Length(arg->ToObject()); } else { std::stringstream s; s << "Argument #" << index << " is neither a string nor a buffer object."; const char* message = s.str().c_str(); return ThrowException(Exception::TypeError(String::New(message))); } } Buffer& dst = *Buffer::New(size); char* s = Buffer::Data(dst.handle_); for (int index = 0, length = args.Length(); index < length; ++index) { Local<Value> arg = args[index]; if (arg->IsString()) { String::Utf8Value v(arg->ToString()); memcpy(s, *v, v.length()); s += v.length(); } else if (Buffer::HasInstance(arg)) { Local<Object> b = arg->ToObject(); const char* data = Buffer::Data(b); size_t length = Buffer::Length(b); memcpy(s, data, length); s += length; } else { return ThrowException(Exception::Error(String::New( "Congratulations! You have run into a bug: argument is neither a string nor a buffer object. " "Please make the world a better place and report it."))); } } return scope.Close(dst.handle_); } void RegisterModule(Handle<Object> target) { target->Set(String::NewSymbol("concat"), FunctionTemplate::New(Concat)->GetFunction()); target->Set(String::NewSymbol("fill"), FunctionTemplate::New(Fill)->GetFunction()); target->Set(String::NewSymbol("clear"), FunctionTemplate::New(Clear)->GetFunction()); target->Set(String::NewSymbol("reverse"), FunctionTemplate::New(Reverse)->GetFunction()); target->Set(String::NewSymbol("equals"), FunctionTemplate::New(Equals)->GetFunction()); target->Set(String::NewSymbol("compare"), FunctionTemplate::New(Compare)->GetFunction()); target->Set(String::NewSymbol("indexOf"), FunctionTemplate::New(IndexOf)->GetFunction()); target->Set(String::NewSymbol("fromHex"), FunctionTemplate::New(FromHex)->GetFunction()); target->Set(String::NewSymbol("toHex"), FunctionTemplate::New(ToHex)->GetFunction()); } } // anonymous namespace NODE_MODULE(buffertools, RegisterModule); <|endoftext|>
<commit_before>//===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file defines the WebAssembly-specific subclass of TargetMachine. /// //===----------------------------------------------------------------------===// #include "WebAssembly.h" #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" #include "WebAssemblyTargetMachine.h" #include "WebAssemblyTargetObjectFile.h" #include "WebAssemblyTargetTransformInfo.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/RegAllocRegistry.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; #define DEBUG_TYPE "wasm" extern "C" void LLVMInitializeWebAssemblyTarget() { // Register the target. RegisterTargetMachine<WebAssemblyTargetMachine> X(TheWebAssemblyTarget32); RegisterTargetMachine<WebAssemblyTargetMachine> Y(TheWebAssemblyTarget64); } //===----------------------------------------------------------------------===// // WebAssembly Lowering public interface. //===----------------------------------------------------------------------===// /// Create an WebAssembly architecture model. /// WebAssemblyTargetMachine::WebAssemblyTargetMachine( const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : LLVMTargetMachine(T, TT.isArch64Bit() ? "e-p:64:64-i64:64-v128:8:128-n32:64-S128" : "e-p:32:32-i64:64-v128:8:128-n32:64-S128", TT, CPU, FS, Options, RM, CM, OL), TLOF(make_unique<WebAssemblyTargetObjectFile>()) { initAsmInfo(); // We need a reducible CFG, so disable some optimizations which tend to // introduce irreducibility. setRequiresStructuredCFG(true); } WebAssemblyTargetMachine::~WebAssemblyTargetMachine() {} const WebAssemblySubtarget * WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const { Attribute CPUAttr = F.getFnAttribute("target-cpu"); Attribute FSAttr = F.getFnAttribute("target-features"); std::string CPU = !CPUAttr.hasAttribute(Attribute::None) ? CPUAttr.getValueAsString().str() : TargetCPU; std::string FS = !FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString().str() : TargetFS; auto &I = SubtargetMap[CPU + FS]; if (!I) { // This needs to be done before we create a new subtarget since any // creation will depend on the TM and the code generation flags on the // function that reside in TargetOptions. resetTargetOptions(F); I = make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this); } return I.get(); } namespace { /// WebAssembly Code Generator Pass Configuration Options. class WebAssemblyPassConfig final : public TargetPassConfig { public: WebAssemblyPassConfig(WebAssemblyTargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const { return getTM<WebAssemblyTargetMachine>(); } FunctionPass *createTargetRegisterAllocator(bool) override; void addFastRegAlloc(FunctionPass *RegAllocPass) override; void addOptimizedRegAlloc(FunctionPass *RegAllocPass) override; void addIRPasses() override; bool addPreISel() override; bool addInstSelector() override; bool addILPOpts() override; void addPreRegAlloc() override; void addRegAllocPasses(bool Optimized); void addPostRegAlloc() override; void addPreSched2() override; void addPreEmitPass() override; }; } // end anonymous namespace TargetIRAnalysis WebAssemblyTargetMachine::getTargetIRAnalysis() { return TargetIRAnalysis([this](Function &F) { return TargetTransformInfo(WebAssemblyTTIImpl(this, F)); }); } TargetPassConfig * WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) { return new WebAssemblyPassConfig(this, PM); } FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) { return nullptr; // No reg alloc } void WebAssemblyPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) { assert(!RegAllocPass && "WebAssembly uses no regalloc!"); addRegAllocPasses(false); } void WebAssemblyPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) { assert(!RegAllocPass && "WebAssembly uses no regalloc!"); addRegAllocPasses(true); } //===----------------------------------------------------------------------===// // The following functions are called from lib/CodeGen/Passes.cpp to modify // the CodeGen pass sequence. //===----------------------------------------------------------------------===// void WebAssemblyPassConfig::addIRPasses() { // FIXME: the default for this option is currently POSIX, whereas // WebAssembly's MVP should default to Single. if (TM->Options.ThreadModel == ThreadModel::Single) addPass(createLowerAtomicPass()); else // Expand some atomic operations. WebAssemblyTargetLowering has hooks which // control specifically what gets lowered. addPass(createAtomicExpandPass(TM)); TargetPassConfig::addIRPasses(); } bool WebAssemblyPassConfig::addPreISel() { return false; } bool WebAssemblyPassConfig::addInstSelector() { addPass( createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel())); return false; } bool WebAssemblyPassConfig::addILPOpts() { return true; } void WebAssemblyPassConfig::addPreRegAlloc() {} void WebAssemblyPassConfig::addRegAllocPasses(bool Optimized) {} void WebAssemblyPassConfig::addPostRegAlloc() { // FIXME: the following passes dislike virtual registers. Disable them for now // so that basic tests can pass. Future patches will remedy this. // // Fails with: Regalloc must assign all vregs. disablePass(&PrologEpilogCodeInserterID); // Fails with: should be run after register allocation. disablePass(&MachineCopyPropagationID); } void WebAssemblyPassConfig::addPreSched2() {} void WebAssemblyPassConfig::addPreEmitPass() {} <commit_msg>Use llvm::make_unique to fix the MSVC build.<commit_after>//===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file defines the WebAssembly-specific subclass of TargetMachine. /// //===----------------------------------------------------------------------===// #include "WebAssembly.h" #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" #include "WebAssemblyTargetMachine.h" #include "WebAssemblyTargetObjectFile.h" #include "WebAssemblyTargetTransformInfo.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/RegAllocRegistry.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; #define DEBUG_TYPE "wasm" extern "C" void LLVMInitializeWebAssemblyTarget() { // Register the target. RegisterTargetMachine<WebAssemblyTargetMachine> X(TheWebAssemblyTarget32); RegisterTargetMachine<WebAssemblyTargetMachine> Y(TheWebAssemblyTarget64); } //===----------------------------------------------------------------------===// // WebAssembly Lowering public interface. //===----------------------------------------------------------------------===// /// Create an WebAssembly architecture model. /// WebAssemblyTargetMachine::WebAssemblyTargetMachine( const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : LLVMTargetMachine(T, TT.isArch64Bit() ? "e-p:64:64-i64:64-v128:8:128-n32:64-S128" : "e-p:32:32-i64:64-v128:8:128-n32:64-S128", TT, CPU, FS, Options, RM, CM, OL), TLOF(make_unique<WebAssemblyTargetObjectFile>()) { initAsmInfo(); // We need a reducible CFG, so disable some optimizations which tend to // introduce irreducibility. setRequiresStructuredCFG(true); } WebAssemblyTargetMachine::~WebAssemblyTargetMachine() {} const WebAssemblySubtarget * WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const { Attribute CPUAttr = F.getFnAttribute("target-cpu"); Attribute FSAttr = F.getFnAttribute("target-features"); std::string CPU = !CPUAttr.hasAttribute(Attribute::None) ? CPUAttr.getValueAsString().str() : TargetCPU; std::string FS = !FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString().str() : TargetFS; auto &I = SubtargetMap[CPU + FS]; if (!I) { // This needs to be done before we create a new subtarget since any // creation will depend on the TM and the code generation flags on the // function that reside in TargetOptions. resetTargetOptions(F); I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this); } return I.get(); } namespace { /// WebAssembly Code Generator Pass Configuration Options. class WebAssemblyPassConfig final : public TargetPassConfig { public: WebAssemblyPassConfig(WebAssemblyTargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const { return getTM<WebAssemblyTargetMachine>(); } FunctionPass *createTargetRegisterAllocator(bool) override; void addFastRegAlloc(FunctionPass *RegAllocPass) override; void addOptimizedRegAlloc(FunctionPass *RegAllocPass) override; void addIRPasses() override; bool addPreISel() override; bool addInstSelector() override; bool addILPOpts() override; void addPreRegAlloc() override; void addRegAllocPasses(bool Optimized); void addPostRegAlloc() override; void addPreSched2() override; void addPreEmitPass() override; }; } // end anonymous namespace TargetIRAnalysis WebAssemblyTargetMachine::getTargetIRAnalysis() { return TargetIRAnalysis([this](Function &F) { return TargetTransformInfo(WebAssemblyTTIImpl(this, F)); }); } TargetPassConfig * WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) { return new WebAssemblyPassConfig(this, PM); } FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) { return nullptr; // No reg alloc } void WebAssemblyPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) { assert(!RegAllocPass && "WebAssembly uses no regalloc!"); addRegAllocPasses(false); } void WebAssemblyPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) { assert(!RegAllocPass && "WebAssembly uses no regalloc!"); addRegAllocPasses(true); } //===----------------------------------------------------------------------===// // The following functions are called from lib/CodeGen/Passes.cpp to modify // the CodeGen pass sequence. //===----------------------------------------------------------------------===// void WebAssemblyPassConfig::addIRPasses() { // FIXME: the default for this option is currently POSIX, whereas // WebAssembly's MVP should default to Single. if (TM->Options.ThreadModel == ThreadModel::Single) addPass(createLowerAtomicPass()); else // Expand some atomic operations. WebAssemblyTargetLowering has hooks which // control specifically what gets lowered. addPass(createAtomicExpandPass(TM)); TargetPassConfig::addIRPasses(); } bool WebAssemblyPassConfig::addPreISel() { return false; } bool WebAssemblyPassConfig::addInstSelector() { addPass( createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel())); return false; } bool WebAssemblyPassConfig::addILPOpts() { return true; } void WebAssemblyPassConfig::addPreRegAlloc() {} void WebAssemblyPassConfig::addRegAllocPasses(bool Optimized) {} void WebAssemblyPassConfig::addPostRegAlloc() { // FIXME: the following passes dislike virtual registers. Disable them for now // so that basic tests can pass. Future patches will remedy this. // // Fails with: Regalloc must assign all vregs. disablePass(&PrologEpilogCodeInserterID); // Fails with: should be run after register allocation. disablePass(&MachineCopyPropagationID); } void WebAssemblyPassConfig::addPreSched2() {} void WebAssemblyPassConfig::addPreEmitPass() {} <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <cstring> using namespace v8; using namespace node; namespace { // this is an application of the Curiously Recurring Template Pattern template <class T> struct UnaryAction { Handle<Value> apply(Buffer& buffer, const Arguments& args); Handle<Value> operator()(const Arguments& args) { if (args[0]->IsObject()) { Local<Object> object = args[0]->ToObject(); if (Buffer::HasInstance(object)) { Buffer& buffer = *ObjectWrap::Unwrap<Buffer>(object); return static_cast<T*>(this)->apply(buffer, args); } } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New("First argument should be a buffer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; template <class T> struct BinaryAction { Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args); Handle<Value> operator()(const Arguments& args) { if (args[0]->IsObject() && args[1]->IsObject()) { Local<Object> arg0 = args[0]->ToObject(); Local<Object> arg1 = args[0]->ToObject(); if (Buffer::HasInstance(arg0) && Buffer::HasInstance(arg1)) { Buffer& a = *ObjectWrap::Unwrap<Buffer>(arg0); Buffer& b = *ObjectWrap::Unwrap<Buffer>(arg1); return static_cast<T*>(this)->apply(a, b, args); } } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New("First and second argument should be a buffer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; // // helper functions // Handle<Value> clear(Buffer& buffer, int c) { memset(buffer.data(), c, buffer.length()); return buffer.handle_; } Handle<Value> fill(Buffer& buffer, void* pattern, size_t size) { if (size >= buffer.length()) { memcpy(buffer.data(), pattern, buffer.length()); } else { const int n_copies = buffer.length() / size; const int remainder = buffer.length() % size; for (int i = 0; i < n_copies; i++) { memcpy(buffer.data() + size * i, pattern, size); } memcpy(buffer.data() + size * n_copies, pattern, remainder); } return buffer.handle_; } int compare(Buffer& a, Buffer& b) { if (a.length() != b.length()) { return a.length() > b.length() ? 1 : -1; } return memcmp(a.data(), b.data(), a.length()); } // // actions // struct ClearAction: UnaryAction<ClearAction> { Handle<Value> apply(Buffer& buffer, const Arguments& args) { const int c = args[1]->IsInt32() ? args[1]->ToInt32()->Int32Value() : 0; return clear(buffer, c); } }; struct FillAction: UnaryAction<FillAction> { Handle<Value> apply(Buffer& buffer, const Arguments& args) { if (args[1]->IsInt32()) { int c = args[1]->ToInt32()->Int32Value(); return clear(buffer, c); } if (args[1]->IsString()) { String::AsciiValue s(args[1]->ToString()); return fill(buffer, *s, s.length()); } if (args[1]->IsObject()) { Local<Object> o = args[1]->ToObject(); if (Buffer::HasInstance(o)) { Buffer& src = *Buffer::Unwrap<Buffer>(o); return fill(buffer, src.data(), src.length()); } } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New( "Second argument should be either a string, a buffer or an integer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; struct EqualsAction: BinaryAction<EqualsAction> { Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args) { HandleScope scope; return scope.Close(Boolean::New(compare(a, b))); } }; struct CompareAction: BinaryAction<CompareAction> { Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args) { HandleScope scope; return scope.Close(Integer::New(compare(a, b))); } }; // // V8 function callbacks // Handle<Value> Clear(const Arguments& args) { return ClearAction()(args); } Handle<Value> Fill(const Arguments& args) { return FillAction()(args); } Handle<Value> Equals(const Arguments& args) { return CompareAction()(args); } Handle<Value> Compare(const Arguments& args) { return CompareAction()(args); } extern "C" void init(Handle<Object> target) { HandleScope scope; target->Set(String::New("fill"), FunctionTemplate::New(Fill)->GetFunction()); target->Set(String::New("clear"), FunctionTemplate::New(Clear)->GetFunction()); target->Set(String::New("equals"), FunctionTemplate::New(Equals)->GetFunction()); target->Set(String::New("compare"), FunctionTemplate::New(Compare)->GetFunction()); } } <commit_msg>Bug fix: Equals() should of course invoke EqualsAction, not CompareAction.<commit_after>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <cstring> using namespace v8; using namespace node; namespace { // this is an application of the Curiously Recurring Template Pattern template <class T> struct UnaryAction { Handle<Value> apply(Buffer& buffer, const Arguments& args); Handle<Value> operator()(const Arguments& args) { if (args[0]->IsObject()) { Local<Object> object = args[0]->ToObject(); if (Buffer::HasInstance(object)) { Buffer& buffer = *ObjectWrap::Unwrap<Buffer>(object); return static_cast<T*>(this)->apply(buffer, args); } } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New("First argument should be a buffer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; template <class T> struct BinaryAction { Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args); Handle<Value> operator()(const Arguments& args) { if (args[0]->IsObject() && args[1]->IsObject()) { Local<Object> arg0 = args[0]->ToObject(); Local<Object> arg1 = args[0]->ToObject(); if (Buffer::HasInstance(arg0) && Buffer::HasInstance(arg1)) { Buffer& a = *ObjectWrap::Unwrap<Buffer>(arg0); Buffer& b = *ObjectWrap::Unwrap<Buffer>(arg1); return static_cast<T*>(this)->apply(a, b, args); } } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New("First and second argument should be a buffer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; // // helper functions // Handle<Value> clear(Buffer& buffer, int c) { memset(buffer.data(), c, buffer.length()); return buffer.handle_; } Handle<Value> fill(Buffer& buffer, void* pattern, size_t size) { if (size >= buffer.length()) { memcpy(buffer.data(), pattern, buffer.length()); } else { const int n_copies = buffer.length() / size; const int remainder = buffer.length() % size; for (int i = 0; i < n_copies; i++) { memcpy(buffer.data() + size * i, pattern, size); } memcpy(buffer.data() + size * n_copies, pattern, remainder); } return buffer.handle_; } int compare(Buffer& a, Buffer& b) { if (a.length() != b.length()) { return a.length() > b.length() ? 1 : -1; } return memcmp(a.data(), b.data(), a.length()); } // // actions // struct ClearAction: UnaryAction<ClearAction> { Handle<Value> apply(Buffer& buffer, const Arguments& args) { const int c = args[1]->IsInt32() ? args[1]->ToInt32()->Int32Value() : 0; return clear(buffer, c); } }; struct FillAction: UnaryAction<FillAction> { Handle<Value> apply(Buffer& buffer, const Arguments& args) { if (args[1]->IsInt32()) { int c = args[1]->ToInt32()->Int32Value(); return clear(buffer, c); } if (args[1]->IsString()) { String::AsciiValue s(args[1]->ToString()); return fill(buffer, *s, s.length()); } if (args[1]->IsObject()) { Local<Object> o = args[1]->ToObject(); if (Buffer::HasInstance(o)) { Buffer& src = *Buffer::Unwrap<Buffer>(o); return fill(buffer, src.data(), src.length()); } } static Persistent<String> illegalArgumentException = Persistent<String>::New(String::New( "Second argument should be either a string, a buffer or an integer.")); return ThrowException(Exception::TypeError(illegalArgumentException)); } }; struct EqualsAction: BinaryAction<EqualsAction> { Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args) { return compare(a, b) == 0 ? True() : False(); } }; struct CompareAction: BinaryAction<CompareAction> { Handle<Value> apply(Buffer& a, Buffer& b, const Arguments& args) { HandleScope scope; return scope.Close(Integer::New(compare(a, b))); } }; // // V8 function callbacks // Handle<Value> Clear(const Arguments& args) { return ClearAction()(args); } Handle<Value> Fill(const Arguments& args) { return FillAction()(args); } Handle<Value> Equals(const Arguments& args) { return EqualsAction()(args); } Handle<Value> Compare(const Arguments& args) { return CompareAction()(args); } extern "C" void init(Handle<Object> target) { HandleScope scope; target->Set(String::New("fill"), FunctionTemplate::New(Fill)->GetFunction()); target->Set(String::New("clear"), FunctionTemplate::New(Clear)->GetFunction()); target->Set(String::New("equals"), FunctionTemplate::New(Equals)->GetFunction()); target->Set(String::New("compare"), FunctionTemplate::New(Compare)->GetFunction()); } } <|endoftext|>
<commit_before>#include "platform/tizen/TizenApplication.h" using namespace Tizen::Graphics::Opengl; namespace lime { int gFixedOrientation = -1; int mSingleTouchID; FrameCreationCallback sgCallback; unsigned int sgFlags; int sgHeight; const char *sgTitle; TizenFrame *sgTizenFrame; int sgWidth; enum { NO_TOUCH = -1 }; void CreateMainFrame (FrameCreationCallback inOnFrame, int inWidth, int inHeight, unsigned int inFlags, const char *inTitle, Surface *inIcon) { sgCallback = inOnFrame; sgWidth = inWidth; sgHeight = inHeight; sgFlags = inFlags; sgTitle = inTitle; mSingleTouchID = NO_TOUCH; //if (sgWidth == 0 && sgHeight == 0) { // Hard-code screen size for now sgWidth = 720; sgHeight = 1280; //} // For now, swap the width/height for proper EGL initialization, when landscape if (gFixedOrientation == 3 || gFixedOrientation == 4) { int temp = sgWidth; sgWidth = sgHeight; sgHeight = temp; } Tizen::Base::Collection::ArrayList args (Tizen::Base::Collection::SingleObjectDeleter); args.Construct (); result r = Tizen::App::Application::Execute (TizenApplication::CreateInstance, &args); } void StartAnimation () {} void PauseAnimation () {} void ResumeAnimation () {} void StopAnimation () {} TizenApplication::TizenApplication (void) { mEGLDisplay = EGL_NO_DISPLAY; mEGLSurface = EGL_NO_SURFACE; mEGLConfig = null; mEGLContext = EGL_NO_CONTEXT; mForm = null; mTimer = null; } TizenApplication::~TizenApplication (void) {} void TizenApplication::Cleanup (void) { if (mTimer != null) { mTimer->Cancel (); delete mTimer; mTimer = null; } Event close (etQuit); sgTizenFrame->HandleEvent (close); Event lostFocus (etLostInputFocus); sgTizenFrame->HandleEvent (lostFocus); Event deactivate (etDeactivate); sgTizenFrame->HandleEvent (deactivate); Event kill (etDestroyHandler); sgTizenFrame->HandleEvent (kill); } Tizen::App::Application* TizenApplication::CreateInstance (void) { return new (std::nothrow) TizenApplication (); } bool TizenApplication::OnAppInitializing (Tizen::App::AppRegistry& appRegistry) { Tizen::Ui::Controls::Frame* appFrame = new (std::nothrow) Tizen::Ui::Controls::Frame (); appFrame->Construct (); this->AddFrame (*appFrame); mForm = new (std::nothrow) TizenForm (this); mForm->Construct (Tizen::Ui::Controls::FORM_STYLE_NORMAL); if (gFixedOrientation == 3 || gFixedOrientation == 4) { mForm->SetOrientation (Tizen::Ui::ORIENTATION_LANDSCAPE); } GetAppFrame ()->GetFrame ()->AddControl (mForm); mForm->AddKeyEventListener (*this); mForm->AddTouchEventListener (*this); mForm->SetMultipointTouchEnabled (true); bool ok = limeEGLCreate (mForm, sgWidth, sgHeight, 2, (sgFlags & wfDepthBuffer) ? 16 : 0, (sgFlags & wfStencilBuffer) ? 8 : 0, 0); mTimer = new (std::nothrow) Tizen::Base::Runtime::Timer; mTimer->Construct (*this); Tizen::System::PowerManager::AddScreenEventListener (*this); sgTizenFrame = new TizenFrame (sgWidth, sgHeight); sgCallback (sgTizenFrame); return true; } bool TizenApplication::OnAppTerminating (Tizen::App::AppRegistry& appRegistry, bool forcedTermination) { Cleanup (); return true; } void TizenApplication::OnBackground (void) { if (mTimer != null) { mTimer->Cancel (); } Event lostFocus (etLostInputFocus); sgTizenFrame->HandleEvent (lostFocus); Event deactivate (etDeactivate); sgTizenFrame->HandleEvent (deactivate); } void TizenApplication::OnBatteryLevelChanged (Tizen::System::BatteryLevel batteryLevel) {} void TizenApplication::OnForeground (void) { Event activate (etActivate); sgTizenFrame->HandleEvent (activate); Event gotFocus (etGotInputFocus); sgTizenFrame->HandleEvent (gotFocus); Event poll (etPoll); sgTizenFrame->HandleEvent (poll); double next = sgTizenFrame->GetStage ()->GetNextWake () - GetTimeStamp (); if (mTimer != null) { if (next > 0) { mTimer->Start (next * 1000.0); } else { mTimer->Start (10); } } } void TizenApplication::OnKeyLongPressed (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) {} void TizenApplication::OnKeyPressed (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) { } void TizenApplication::OnKeyReleased (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) { if (keyCode == Tizen::Ui::KEY_BACK || keyCode == Tizen::Ui::KEY_ESC) { Terminate (); } } void TizenApplication::OnLowMemory (void) {} void TizenApplication::OnScreenOn (void) {} void TizenApplication::OnScreenOff (void) {} void TizenApplication::OnTimerExpired (Tizen::Base::Runtime::Timer& timer) { if (mTimer == null) { return; } Event poll (etPoll); sgTizenFrame->HandleEvent (poll); double next = sgTizenFrame->GetStage ()->GetNextWake () - GetTimeStamp (); if (next > 0) { mTimer->Start (next * 1000.0); } else { mTimer->Start (10); } } void TizenApplication::OnTouchCanceled (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchFocusIn (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchFocusOut (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchMoved (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchMove, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } sgTizenFrame->HandleEvent (mouse); } void TizenApplication::OnTouchPressed (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchBegin, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } sgTizenFrame->HandleEvent (mouse); } void TizenApplication::OnTouchReleased (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchEnd, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } if (mSingleTouchID == mouse.value) { mSingleTouchID = NO_TOUCH; } sgTizenFrame->HandleEvent (mouse); } } <commit_msg>Adjustments to timer<commit_after>#include "platform/tizen/TizenApplication.h" using namespace Tizen::Graphics::Opengl; namespace lime { int gFixedOrientation = -1; int mSingleTouchID; FrameCreationCallback sgCallback; unsigned int sgFlags; int sgHeight; const char *sgTitle; TizenFrame *sgTizenFrame; int sgWidth; enum { NO_TOUCH = -1 }; void CreateMainFrame (FrameCreationCallback inOnFrame, int inWidth, int inHeight, unsigned int inFlags, const char *inTitle, Surface *inIcon) { sgCallback = inOnFrame; sgWidth = inWidth; sgHeight = inHeight; sgFlags = inFlags; sgTitle = inTitle; mSingleTouchID = NO_TOUCH; //if (sgWidth == 0 && sgHeight == 0) { // Hard-code screen size for now sgWidth = 720; sgHeight = 1280; //} // For now, swap the width/height for proper EGL initialization, when landscape if (gFixedOrientation == 3 || gFixedOrientation == 4) { int temp = sgWidth; sgWidth = sgHeight; sgHeight = temp; } Tizen::Base::Collection::ArrayList args (Tizen::Base::Collection::SingleObjectDeleter); args.Construct (); result r = Tizen::App::Application::Execute (TizenApplication::CreateInstance, &args); } void StartAnimation () {} void PauseAnimation () {} void ResumeAnimation () {} void StopAnimation () {} TizenApplication::TizenApplication (void) { mEGLDisplay = EGL_NO_DISPLAY; mEGLSurface = EGL_NO_SURFACE; mEGLConfig = null; mEGLContext = EGL_NO_CONTEXT; mForm = null; mTimer = null; } TizenApplication::~TizenApplication (void) {} void TizenApplication::Cleanup (void) { if (mTimer != null) { mTimer->Cancel (); delete mTimer; mTimer = null; } Event close (etQuit); sgTizenFrame->HandleEvent (close); Event lostFocus (etLostInputFocus); sgTizenFrame->HandleEvent (lostFocus); Event deactivate (etDeactivate); sgTizenFrame->HandleEvent (deactivate); Event kill (etDestroyHandler); sgTizenFrame->HandleEvent (kill); } Tizen::App::Application* TizenApplication::CreateInstance (void) { return new (std::nothrow) TizenApplication (); } bool TizenApplication::OnAppInitializing (Tizen::App::AppRegistry& appRegistry) { Tizen::Ui::Controls::Frame* appFrame = new (std::nothrow) Tizen::Ui::Controls::Frame (); appFrame->Construct (); this->AddFrame (*appFrame); mForm = new (std::nothrow) TizenForm (this); mForm->Construct (Tizen::Ui::Controls::FORM_STYLE_NORMAL); if (gFixedOrientation == 3 || gFixedOrientation == 4) { mForm->SetOrientation (Tizen::Ui::ORIENTATION_LANDSCAPE); } GetAppFrame ()->GetFrame ()->AddControl (mForm); mForm->AddKeyEventListener (*this); mForm->AddTouchEventListener (*this); mForm->SetMultipointTouchEnabled (true); bool ok = limeEGLCreate (mForm, sgWidth, sgHeight, 2, (sgFlags & wfDepthBuffer) ? 16 : 0, (sgFlags & wfStencilBuffer) ? 8 : 0, 0); mTimer = new (std::nothrow) Tizen::Base::Runtime::Timer; mTimer->Construct (*this); Tizen::System::PowerManager::AddScreenEventListener (*this); sgTizenFrame = new TizenFrame (sgWidth, sgHeight); sgCallback (sgTizenFrame); return true; } bool TizenApplication::OnAppTerminating (Tizen::App::AppRegistry& appRegistry, bool forcedTermination) { Cleanup (); return true; } void TizenApplication::OnBackground (void) { if (mTimer != null) { mTimer->Cancel (); } Event lostFocus (etLostInputFocus); sgTizenFrame->HandleEvent (lostFocus); Event deactivate (etDeactivate); sgTizenFrame->HandleEvent (deactivate); } void TizenApplication::OnBatteryLevelChanged (Tizen::System::BatteryLevel batteryLevel) {} void TizenApplication::OnForeground (void) { Event activate (etActivate); sgTizenFrame->HandleEvent (activate); Event gotFocus (etGotInputFocus); sgTizenFrame->HandleEvent (gotFocus); Event poll (etPoll); sgTizenFrame->HandleEvent (poll); double next = sgTizenFrame->GetStage ()->GetNextWake () - GetTimeStamp (); if (mTimer != null) { if (next > 0.001) { mTimer->Start (next * 1000.0); } else { mTimer->Start (1); } } } void TizenApplication::OnKeyLongPressed (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) {} void TizenApplication::OnKeyPressed (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) { } void TizenApplication::OnKeyReleased (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) { if (keyCode == Tizen::Ui::KEY_BACK || keyCode == Tizen::Ui::KEY_ESC) { Terminate (); } } void TizenApplication::OnLowMemory (void) {} void TizenApplication::OnScreenOn (void) {} void TizenApplication::OnScreenOff (void) {} void TizenApplication::OnTimerExpired (Tizen::Base::Runtime::Timer& timer) { if (mTimer == null) { return; } Event poll (etPoll); sgTizenFrame->HandleEvent (poll); double next = sgTizenFrame->GetStage ()->GetNextWake () - GetTimeStamp (); if (next > 0.001) { mTimer->Start (next * 1000.0); } else { mTimer->Start (1); } } void TizenApplication::OnTouchCanceled (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchFocusIn (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchFocusOut (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchMoved (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchMove, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } sgTizenFrame->HandleEvent (mouse); } void TizenApplication::OnTouchPressed (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchBegin, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } sgTizenFrame->HandleEvent (mouse); } void TizenApplication::OnTouchReleased (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchEnd, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } if (mSingleTouchID == mouse.value) { mSingleTouchID = NO_TOUCH; } sgTizenFrame->HandleEvent (mouse); } } <|endoftext|>
<commit_before>#include "Script.hpp" /* Assets */ #include "../ResourceManager/AssetManager.hpp" /* Logger */ #include "../Logger/Logger.hpp" /* GUI */ #include "../GUI/Window.hpp" #include "../GUI/Containers/Column.hpp" #include "../GUI/Containers/Row.hpp" #include "../GUI/Widgets/Button.hpp" #include "../GUI/Widgets/Label.hpp" #include "../GUI/Widgets/Slider.hpp" #include "../GUI/Widgets/Spacer.hpp" #include "../GUI/Widgets/TextBox.hpp" #include "../GUI/Widgets/Toggle.hpp" /* EntitySystem */ #include "../EntitySystem/Entity.hpp" #include "../World/World.hpp" namespace swift { sf::RenderWindow* Script::window = nullptr; AssetManager* Script::assets = nullptr; sf::Clock* Script::clock = nullptr; Settings* Script::settings = nullptr; Logger* Script::log = nullptr; Script::Script() : gui(nullptr), keyboard(nullptr), stateReturn(nullptr), world(nullptr) { deleteMe = false; // We don't want to give the scripts access to os commands or file writing abilities luaState.OpenLib("base", luaopen_base); luaState.OpenLib("math", luaopen_math); luaState.OpenLib("string", luaopen_string); luaState.OpenLib("table", luaopen_table); addVariables(); addClasses(); addFunctions(); } Script::~Script() { } bool Script::loadFromFile(const std::string& file) { bool r = luaState.Load(file); // r will be false if errors, true otherwise return r; } void Script::start() { luaState["Start"](); if(static_cast<bool>(luaState["Done"]) == true) { deleteMe = true; } } void Script::run() { luaState["Update"](); if(static_cast<bool>(luaState["Done"]) == true) { deleteMe = true; } } bool Script::toDelete() { return deleteMe; } void Script::setWindow(sf::RenderWindow& win) { window = &win; } void Script::setAssetManager(AssetManager& am) { assets = &am; } void Script::setClock(sf::Clock& c) { clock = &c; } void Script::setSettings(Settings& s) { settings = &s; } void Script::setLogger(Logger& l) { log = &l; } void Script::setGUI(cstr::Window& ui) { gui = &ui; } void Script::setKeyboard(KeyboardManager& k) { keyboard = &k; } void Script::setStateReturn(State::Type& t) { stateReturn = &t; } void Script::setWorld(World& w) { world = &w; } void Script::addVariables() { luaState["states"]["MainMenu"] = 0; luaState["states"]["Settings"] = 1; luaState["states"]["Play"] = 2; luaState["states"]["Exit"] = 3; } void Script::addClasses() { // vectors luaState["Vector2f"].SetClass<sf::Vector2f>("x", &sf::Vector2f::x, "y", &sf::Vector2f::y); luaState["Vector2i"].SetClass<sf::Vector2i>("x", &sf::Vector2i::x, "y", &sf::Vector2i::y); luaState["Vector2u"].SetClass<sf::Vector2u>("x", &sf::Vector2u::x, "y", &sf::Vector2u::y); // ECS luaState["Entity"].SetClass<Entity>("add", static_cast<bool (Entity::*)(std::string)>(&Entity::add), "remove", static_cast<bool (Entity::*)(std::string)>(&Entity::remove), "has", static_cast<bool (Entity::*)(std::string) const>(&Entity::has), "getDrawable", static_cast<Drawable* (Entity::*)()>(&Entity::get<Drawable>), "getMovable", static_cast<Movable* (Entity::*)()>(&Entity::get<Movable>), "getPhysical", static_cast<Physical* (Entity::*)()>(&Entity::get<Physical>), "getName", static_cast<Name* (Entity::*)()>(&Entity::get<Name>)); // each Component type luaState["Drawable"].SetClass<Drawable>(); luaState["Movable"].SetClass<Movable>(); luaState["Physical"].SetClass<Physical>(); luaState["Name"].SetClass<Name>(); // GUI /*luaState["Column"].SetClass<cstr::Column>(); luaState["Row"].SetClass<cstr::Row>(); luaState["Button"].SetClass<cstr::Button>(); luaState["Label"].SetClass<cstr::Label>(); luaState["Slider"].SetClass<cstr::Slider>(); luaState["Spacer"].SetClass<cstr::Spacer>(); luaState["TextBox"].SetClass<cstr::TextBox>(); luaState["Toggle"].SetClass<cstr::Toggle>();*/ } void Script::addFunctions() { /* utility functions */ luaState["getWindowSize"] = [&]() { if(window) return std::make_tuple(window->getSize().x, window->getSize().y); else return std::make_tuple(0u, 0u); }; luaState["getTime"] = [&]() { if(clock) return clock->getElapsedTime().asSeconds(); else return 0.f; }; luaState["doKeypress"] = [&](std::string k) { if(keyboard) keyboard->call(k); }; luaState["log"] = [&](std::string m) { if(log) *log << m; }; /* EntitySystem */ // World luaState["newEntity"] = [&]() -> Entity* { if(world) return world->addEntity(); else return nullptr; }; luaState["getTotalEntities"] = [&]() { if(world) return static_cast<unsigned>(world->getEntities().size()); else return 0u; }; luaState["getEntity"] = [&](unsigned e) -> Entity* { if(world && e < world->getEntities().size()) return world->getEntities()[e]; else return nullptr; }; // Drawable luaState["setTexture"] = [&](Drawable* d, std::string t) { if(d) { d->sprite.setTexture(assets->getTexture(t)); return true; } else return false; }; luaState["setTextureRect"] = [&](Drawable* d, int x, int y, int w, int h) { if(d) d->sprite.setTextureRect({x, y, w, h}); }; luaState["getSpriteSize"] = [&](Drawable* d) { if(d) return std::make_tuple(d->sprite.getGlobalBounds().width, d->sprite.getGlobalBounds().height); else return std::make_tuple(0.f, 0.f); }; luaState["setScale"] = [&](Drawable* d, float x, float y) { if(d) d->sprite.setScale(x, y); }; // Movable luaState["setMoveVelocity"] = [&](Movable* m, float v) { if(m) { m->moveVelocity = v; } }; luaState["getVelocity"] = [&](Movable* m) { if(m) return std::make_tuple(m->velocity.x, m->velocity.y); else return std::make_tuple(0.f, 0.f); }; // Physical luaState["setPosition"] = [&](Physical* p, float x, float y) { if(p) p->position = {x, y}; else if(p) p->position = {0, 0}; }; luaState["getPosition"] = [&](Physical* p) { if(p) return std::make_tuple(p->position.x, p->position.y); else return std::make_tuple(0.f, 0.f); }; luaState["setSize"] = [&](Physical* p, unsigned x, unsigned y) { if(p) p->size = {x, y}; else if(p) p->size = {0, 0}; }; luaState["getSize"] = [&](Physical* p) { if(p) return std::make_tuple(p->size.x, p->size.y); else return std::make_tuple(0u, 0u); }; // Name luaState["setName"] = [&](Name* n, std::string s) { if(n) n->name = s; }; luaState["getName"] = [&](Name* n) -> std::string { if(n) return n->name; else return "null"; }; /* gui functions */ /* State */ luaState["setStateReturn"] = [&](unsigned s) { *stateReturn = static_cast<State::Type>(s); }; /* Settings */ luaState["getSettingStr"] = [&](std::string n) { std::string v; return std::make_tuple(settings->get(n, v), v); }; luaState["setSettingStr"] = [&](std::string n, std::string v) { return settings->set(n, v); }; luaState["getSettingBool"] = [&](std::string n) { bool v; return std::make_tuple(settings->get(n, v), v); }; luaState["setSettingBool"] = [&](std::string n, bool v) { return settings->set(n, v); }; luaState["getSettingNum"] = [&](std::string n) { int v; return std::make_tuple(settings->get(n, v), v); }; luaState["setSettingNum"] = [&](std::string n, int v) { return settings->set(n, v); }; } }<commit_msg>Added Lua functions for getting Entities around a point in the world<commit_after>#include "Script.hpp" /* Assets */ #include "../ResourceManager/AssetManager.hpp" /* Logger */ #include "../Logger/Logger.hpp" /* GUI */ #include "../GUI/Window.hpp" #include "../GUI/Containers/Column.hpp" #include "../GUI/Containers/Row.hpp" #include "../GUI/Widgets/Button.hpp" #include "../GUI/Widgets/Label.hpp" #include "../GUI/Widgets/Slider.hpp" #include "../GUI/Widgets/Spacer.hpp" #include "../GUI/Widgets/TextBox.hpp" #include "../GUI/Widgets/Toggle.hpp" /* EntitySystem */ #include "../EntitySystem/Entity.hpp" #include "../World/World.hpp" namespace swift { sf::RenderWindow* Script::window = nullptr; AssetManager* Script::assets = nullptr; sf::Clock* Script::clock = nullptr; Settings* Script::settings = nullptr; Logger* Script::log = nullptr; Script::Script() : gui(nullptr), keyboard(nullptr), stateReturn(nullptr), world(nullptr) { deleteMe = false; // We don't want to give the scripts access to os commands or file writing abilities luaState.OpenLib("base", luaopen_base); luaState.OpenLib("math", luaopen_math); luaState.OpenLib("string", luaopen_string); luaState.OpenLib("table", luaopen_table); addVariables(); addClasses(); addFunctions(); } Script::~Script() { } bool Script::loadFromFile(const std::string& file) { bool r = luaState.Load(file); // r will be false if errors, true otherwise return r; } void Script::start() { luaState["Start"](); if(static_cast<bool>(luaState["Done"]) == true) { deleteMe = true; } } void Script::run() { luaState["Update"](); if(static_cast<bool>(luaState["Done"]) == true) { deleteMe = true; } } bool Script::toDelete() { return deleteMe; } void Script::setWindow(sf::RenderWindow& win) { window = &win; } void Script::setAssetManager(AssetManager& am) { assets = &am; } void Script::setClock(sf::Clock& c) { clock = &c; } void Script::setSettings(Settings& s) { settings = &s; } void Script::setLogger(Logger& l) { log = &l; } void Script::setGUI(cstr::Window& ui) { gui = &ui; } void Script::setKeyboard(KeyboardManager& k) { keyboard = &k; } void Script::setStateReturn(State::Type& t) { stateReturn = &t; } void Script::setWorld(World& w) { world = &w; } void Script::addVariables() { luaState["states"]["MainMenu"] = 0; luaState["states"]["Settings"] = 1; luaState["states"]["Play"] = 2; luaState["states"]["Exit"] = 3; } void Script::addClasses() { // vectors luaState["Vector2f"].SetClass<sf::Vector2f>("x", &sf::Vector2f::x, "y", &sf::Vector2f::y); luaState["Vector2i"].SetClass<sf::Vector2i>("x", &sf::Vector2i::x, "y", &sf::Vector2i::y); luaState["Vector2u"].SetClass<sf::Vector2u>("x", &sf::Vector2u::x, "y", &sf::Vector2u::y); // c++ containers luaState["entityList"].SetClass<std::vector<Entity*>>(); // ECS luaState["Entity"].SetClass<Entity>("add", static_cast<bool (Entity::*)(std::string)>(&Entity::add), "remove", static_cast<bool (Entity::*)(std::string)>(&Entity::remove), "has", static_cast<bool (Entity::*)(std::string) const>(&Entity::has), "getDrawable", static_cast<Drawable* (Entity::*)()>(&Entity::get<Drawable>), "getMovable", static_cast<Movable* (Entity::*)()>(&Entity::get<Movable>), "getPhysical", static_cast<Physical* (Entity::*)()>(&Entity::get<Physical>), "getName", static_cast<Name* (Entity::*)()>(&Entity::get<Name>)); // each Component type luaState["Drawable"].SetClass<Drawable>(); luaState["Movable"].SetClass<Movable>(); luaState["Physical"].SetClass<Physical>(); luaState["Name"].SetClass<Name>(); // GUI /*luaState["Column"].SetClass<cstr::Column>(); luaState["Row"].SetClass<cstr::Row>(); luaState["Button"].SetClass<cstr::Button>(); luaState["Label"].SetClass<cstr::Label>(); luaState["Slider"].SetClass<cstr::Slider>(); luaState["Spacer"].SetClass<cstr::Spacer>(); luaState["TextBox"].SetClass<cstr::TextBox>(); luaState["Toggle"].SetClass<cstr::Toggle>();*/ } void Script::addFunctions() { /* utility functions */ luaState["getWindowSize"] = [&]() { if(window) return std::make_tuple(window->getSize().x, window->getSize().y); else return std::make_tuple(0u, 0u); }; luaState["getTime"] = [&]() { if(clock) return clock->getElapsedTime().asSeconds(); else return 0.f; }; luaState["doKeypress"] = [&](std::string k) { if(keyboard) keyboard->call(k); }; luaState["log"] = [&](std::string m) { if(log) *log << m; }; /* EntitySystem */ // World luaState["newEntity"] = [&]() -> Entity* { if(world) return world->addEntity(); else return nullptr; }; luaState["getTotalEntities"] = [&]() { if(world) return static_cast<unsigned>(world->getEntities().size()); else return 0u; }; luaState["getEntity"] = [&](unsigned e) -> Entity* { if(world && e < world->getEntities().size()) return world->getEntities()[e]; else return nullptr; }; luaState["calculateEntitiesAround"] = [&](float x, float y, float radius) { if(world) world->calculateEntitiesAround({x, y}, radius); }; luaState["getTotalEntitiesAround"] = [&]() { if(world) return static_cast<unsigned>(world->getEntitiesAround().size()); else return 0u; }; luaState["getEntityAround"] = [&](unsigned e) -> Entity* { if(world && e < world->getEntitiesAround().size()) return world->getEntities()[e]; else return nullptr; }; // Drawable luaState["setTexture"] = [&](Drawable* d, std::string t) { if(d) { d->sprite.setTexture(assets->getTexture(t)); return true; } else return false; }; luaState["setTextureRect"] = [&](Drawable* d, int x, int y, int w, int h) { if(d) d->sprite.setTextureRect({x, y, w, h}); }; luaState["getSpriteSize"] = [&](Drawable* d) { if(d) return std::make_tuple(d->sprite.getGlobalBounds().width, d->sprite.getGlobalBounds().height); else return std::make_tuple(0.f, 0.f); }; luaState["setScale"] = [&](Drawable* d, float x, float y) { if(d) d->sprite.setScale(x, y); }; // Movable luaState["setMoveVelocity"] = [&](Movable* m, float v) { if(m) { m->moveVelocity = v; } }; luaState["getVelocity"] = [&](Movable* m) { if(m) return std::make_tuple(m->velocity.x, m->velocity.y); else return std::make_tuple(0.f, 0.f); }; // Physical luaState["setPosition"] = [&](Physical* p, float x, float y) { if(p) p->position = {x, y}; else if(p) p->position = {0, 0}; }; luaState["getPosition"] = [&](Physical* p) { if(p) return std::make_tuple(p->position.x, p->position.y); else return std::make_tuple(0.f, 0.f); }; luaState["setSize"] = [&](Physical* p, unsigned x, unsigned y) { if(p) p->size = {x, y}; else if(p) p->size = {0, 0}; }; luaState["getSize"] = [&](Physical* p) { if(p) return std::make_tuple(p->size.x, p->size.y); else return std::make_tuple(0u, 0u); }; // Name luaState["setName"] = [&](Name* n, std::string s) { if(n) n->name = s; }; luaState["getName"] = [&](Name* n) -> std::string { if(n) return n->name; else return "null"; }; /* gui functions */ /* State */ luaState["setStateReturn"] = [&](unsigned s) { *stateReturn = static_cast<State::Type>(s); }; /* Settings */ luaState["getSettingStr"] = [&](std::string n) { std::string v; return std::make_tuple(settings->get(n, v), v); }; luaState["setSettingStr"] = [&](std::string n, std::string v) { return settings->set(n, v); }; luaState["getSettingBool"] = [&](std::string n) { bool v; return std::make_tuple(settings->get(n, v), v); }; luaState["setSettingBool"] = [&](std::string n, bool v) { return settings->set(n, v); }; luaState["getSettingNum"] = [&](std::string n) { int v; return std::make_tuple(settings->get(n, v), v); }; luaState["setSettingNum"] = [&](std::string n, int v) { return settings->set(n, v); }; } }<|endoftext|>
<commit_before>class tup_seatraffic_factions { title = " Enable Ambient Air Factions"; values[]= {0,1,2}; texts[]= {"All Factions","Civilian Only","None"}; default = 1; }; class tup_seatraffic_amount { title = " Enable Ambient Sea Traffic"; values[]= {0,1}; texts[]= {"Full","Reduced"}; default = 1; }; class tup_seatraffic_ROE { title = " Ambient Sea Traffic Rules of Engagement"; values[]= {1,2,3,4,5}; texts[]= {"Never fire","Hold fire - defend only","Hold fire, engage at will","Fire at will","Fire at will, engage at will"}; default = 2; }; class tup_seatraffic_LHD { title = " Ambient LHD Helicopter Dock"; values[]= {0,1,2}; texts[]= {"Never","Always","Random"}; default = 2; }; <commit_msg>[TUP_SEATRAFFIC] - Typo in params<commit_after>class tup_seatraffic_factions { title = " Enable Ambient Sea Factions"; values[]= {0,1,2}; texts[]= {"All Factions","Civilian Only","None"}; default = 1; }; class tup_seatraffic_amount { title = " Enable Ambient Sea Traffic"; values[]= {0,1}; texts[]= {"Full","Reduced"}; default = 1; }; class tup_seatraffic_ROE { title = " Ambient Sea Traffic Rules of Engagement"; values[]= {1,2,3,4,5}; texts[]= {"Never fire","Hold fire - defend only","Hold fire, engage at will","Fire at will","Fire at will, engage at will"}; default = 2; }; class tup_seatraffic_LHD { title = " Ambient LHD Helicopter Dock"; values[]= {0,1,2}; texts[]= {"Never","Always","Random"}; default = 2; }; <|endoftext|>
<commit_before>#include "blinkyBlocksVM.h" #include "blinkyBlocksBlock.h" #include "blinkyBlocksBlockCode.h" #include <boost/asio/io_service.hpp> #include <sys/wait.h> #include <stdio.h> #include <boost/bind.hpp> #include "trace.h" #include <stdexcept> #include <string.h> #include "events.h" #include "blinkyBlocksEvents.h" #include "openglViewer.h" #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> using namespace boost; using asio::ip::tcp; namespace BlinkyBlocks { boost::asio::io_service *BlinkyBlocksVM::ios = NULL; boost::interprocess::interprocess_mutex BlinkyBlocksVM::mutex_ios; tcp::acceptor *BlinkyBlocksVM::acceptor = NULL; string BlinkyBlocksVM::vmPath; string BlinkyBlocksVM::programPath; bool BlinkyBlocksVM::debugging = false; BlinkyBlocksVM::BlinkyBlocksVM(BlinkyBlocksBlock* bb){ int ret; boost::system::error_code error; stringstream vmLogFile; assert(ios != NULL && acceptor != NULL); hostBlock = bb; vmLogFile << "VM" << hostBlock->blockId << ".log"; OUTPUT << "VM "<< hostBlock->blockId << " constructor" << endl; // Start the VM pid = 0; mutex_ios.lock(); ios->notify_fork(boost::asio::io_service::fork_prepare); pid = fork(); if(pid < 0) {ERRPUT << "Error when starting the VM" << endl;} if(pid == 0) { ios->notify_fork(boost::asio::io_service::fork_child); mutex_ios.unlock(); acceptor->close(); getWorld()->closeAllSockets(); #ifdef LOGFILE log_file.close(); #endif int fd = open(vmLogFile.str().c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); dup2(fd, 1); dup2(fd, 2); close(fd); if (debugging) { //./meld -f /home/ubuntu/Bureau/CMU/meld/examples/ends.m -c sl -D SIM char* cmd[] = {(char*)vmPath.c_str(), /*(char*)"-a", (char*)"bbsim",*/ (char*)"-f", (char*)programPath.c_str(), (char*)"-c", (char*) "sl", (char*) "-D", (char*) "SIM", NULL }; ret = execv(vmPath.c_str(), const_cast<char**>(cmd)); } else { //./meld -f /home/ubuntu/Bureau/CMU/meld/examples/ends.m -c sl char* cmd[] = {(char*)vmPath.c_str(), /*(char*)"-a", (char*)"bbsim",*/ (char*)"-f", (char*)programPath.c_str(), (char*)"-c", (char*) "sl", NULL }; ret = execv(vmPath.c_str(), const_cast<char**>(cmd)); } if(ret == -1) { cerr << "Error: VM executable, " << vmPath.c_str() << ", does not exist or is not executable" << endl; exit(EXIT_FAILURE); } } ios->notify_fork(boost::asio::io_service::fork_parent); mutex_ios.unlock(); socket = boost::shared_ptr<tcp::socket>(new tcp::socket(*ios)); if (hostBlock->blockId == 1) { bool connected = false; acceptor->async_accept(*(socket.get()), boost::bind(&BlinkyBlocksVM::asyncAcceptHandler, this, error , &connected)); while(!connected && (pid != waitpid(pid, NULL, WNOHANG))) { if (!BlinkyBlocksVM::isInDebuggingMode()) { // In debugging mode the scheduler thread is looking for connections checkForReceivedVMCommands(); // it is actually check for connection usleep(10000); } } if(!connected) { ifstream file (vmLogFile.str().c_str()); string line; cerr << "VisibleSim error: unable to connect to the VM" << endl; cerr << vmLogFile.str() << ":" << endl; if (file.is_open()) { while (!file.eof()) { getline(file,line); cerr << line; } cerr << endl; file.close(); } acceptor->close(); exit(EXIT_FAILURE); } } else { acceptor->accept(*(socket.get())); } idSent = false; deterministicSet = false; nbSentCommands = 0; asyncReadCommand(); } void BlinkyBlocksVM::asyncAcceptHandler(boost::system::error_code& error, bool* connected) { if (error) { *connected = false; } else { *connected = true; } } BlinkyBlocksVM::~BlinkyBlocksVM() { closeSocket(); killProcess(); } void BlinkyBlocksVM::terminate() { waitpid(pid, NULL, 0); } void BlinkyBlocksVM::killProcess() { kill(pid, SIGTERM); waitpid(pid, NULL, 0); } void BlinkyBlocksVM::closeSocket() { if (socket != NULL) { socket->cancel(); socket->close(); socket.reset(); } } void BlinkyBlocksVM::asyncReadCommandHandler(const boost::system::error_code& error, std::size_t bytes_transferred) { if(error) { ERRPUT << "An error occurred while receiving a tcp command from VM " << hostBlock->blockId << " (socket closed ?) " <<endl; return; } try { memset(inBuffer+1, 0, inBuffer[0]); boost::asio::read(getSocket(),boost::asio::buffer((void*)(inBuffer + 1), inBuffer[0]) ); } catch (std::exception& e) { ERRPUT << "Connection to the VM "<< hostBlock->blockId << " lost" << endl; } handleInBuffer(); while (socket->available()) { try { boost::asio::read(getSocket(), boost::asio::buffer(inBuffer, sizeof(commandType))); boost::asio::read(getSocket(),boost::asio::buffer((void*)(inBuffer + 1), inBuffer[0])); } catch (std::exception& e) { ERRPUT << "Connection to the VM "<< hostBlock->blockId << " lost" << endl; } handleInBuffer(); } this->asyncReadCommand(); } void BlinkyBlocksVM::handleInBuffer() { BlinkyBlocksBlockCode *bbc = (BlinkyBlocksBlockCode*)hostBlock->blockCode; VMCommand command(inBuffer); bbc->handleCommand(command); } void BlinkyBlocksVM::asyncReadCommand() { if (socket == NULL) { ERRPUT << "Simulator is not connected to the VM "<< hostBlock->blockId << endl; return; } try { inBuffer[0] = 0; boost::asio::async_read(getSocket(), boost::asio::buffer(inBuffer, sizeof(commandType)), boost::bind(&BlinkyBlocksVM::asyncReadCommandHandler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } catch (std::exception& e) { ERRPUT << "Connection to the VM "<< hostBlock->blockId << " lost" << endl; } } int BlinkyBlocksVM::sendCommand(VMCommand &command){ if (socket == NULL) { ERRPUT << "Simulator is not connected to the VM "<< hostBlock->blockId << endl; return 0; } if (command.getType() != VM_COMMAND_DEBUG) { nbSentCommands++; ((BlinkyBlocksBlockCode*)hostBlock->blockCode)->handleDeterministicMode(command); } try { boost::asio::write(getSocket(), boost::asio::buffer(command.getData(), command.getSize())); //boost::asio::async_write(getSocket(), boost::asio::buffer(command.getData(), command.getSize()), boost::bind(&BlinkyBlocksVM::handle_write, this, // boost::asio::placeholders::error)); } catch (std::exception& e) { ERRPUT << "Connection to the VM "<< hostBlock->blockId << " lost" << endl; return 0; } return 1; } void BlinkyBlocksVM::handle_write(const boost::system::error_code& error) { if (!error) { cout << "ok" << endl; } } void BlinkyBlocksVM::checkForReceivedCommands() { if (ios != NULL) { mutex_ios.lock(); try { ios->poll(); ios->reset(); } catch (boost::exception& e) { } mutex_ios.unlock(); } } void BlinkyBlocksVM::waitForOneCommand() { if (ios != NULL) { mutex_ios.lock(); try { ios->run_one(); ios->reset(); } catch (boost::exception& e) { } mutex_ios.unlock(); } checkForReceivedCommands(); } void BlinkyBlocksVM::setConfiguration(string v, string p, bool d) { vmPath = v; programPath = p; debugging = d; } void BlinkyBlocksVM::createServer(int p) { assert(ios == NULL); ios = new boost::asio::io_service(); acceptor = new tcp::acceptor(*ios, tcp::endpoint(tcp::v4(), p)); } void BlinkyBlocksVM::deleteServer() { ios->stop(); delete acceptor; delete ios; ios = NULL; acceptor = NULL; } } <commit_msg>use -a parameter<commit_after>#include "blinkyBlocksVM.h" #include "blinkyBlocksBlock.h" #include "blinkyBlocksBlockCode.h" #include <boost/asio/io_service.hpp> #include <sys/wait.h> #include <stdio.h> #include <boost/bind.hpp> #include "trace.h" #include <stdexcept> #include <string.h> #include "events.h" #include "blinkyBlocksEvents.h" #include "openglViewer.h" #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> using namespace boost; using asio::ip::tcp; namespace BlinkyBlocks { boost::asio::io_service *BlinkyBlocksVM::ios = NULL; boost::interprocess::interprocess_mutex BlinkyBlocksVM::mutex_ios; tcp::acceptor *BlinkyBlocksVM::acceptor = NULL; string BlinkyBlocksVM::vmPath; string BlinkyBlocksVM::programPath; bool BlinkyBlocksVM::debugging = false; BlinkyBlocksVM::BlinkyBlocksVM(BlinkyBlocksBlock* bb){ int ret; boost::system::error_code error; stringstream vmLogFile; assert(ios != NULL && acceptor != NULL); hostBlock = bb; vmLogFile << "VM" << hostBlock->blockId << ".log"; OUTPUT << "VM "<< hostBlock->blockId << " constructor" << endl; // Start the VM pid = 0; mutex_ios.lock(); ios->notify_fork(boost::asio::io_service::fork_prepare); pid = fork(); if(pid < 0) {ERRPUT << "Error when starting the VM" << endl;} if(pid == 0) { ios->notify_fork(boost::asio::io_service::fork_child); mutex_ios.unlock(); acceptor->close(); getWorld()->closeAllSockets(); #ifdef LOGFILE log_file.close(); #endif int fd = open(vmLogFile.str().c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); dup2(fd, 1); dup2(fd, 2); close(fd); if (debugging) { //./meld -f /home/ubuntu/Bureau/CMU/meld/examples/ends.m -c sl -D SIM char* cmd[] = {(char*)vmPath.c_str(), (char*)"-a", (char*)"bbsim", (char*)"-f", (char*)programPath.c_str(), (char*)"-c", (char*) "sl", (char*) "-D", (char*) "SIM", NULL }; ret = execv(vmPath.c_str(), const_cast<char**>(cmd)); } else { //./meld -f /home/ubuntu/Bureau/CMU/meld/examples/ends.m -c sl char* cmd[] = {(char*)vmPath.c_str(), (char*)"-a", (char*)"bbsim", (char*)"-f", (char*)programPath.c_str(), (char*)"-c", (char*) "sl", NULL }; ret = execv(vmPath.c_str(), const_cast<char**>(cmd)); } if(ret == -1) { cerr << "Error: VM executable, " << vmPath.c_str() << ", does not exist or is not executable" << endl; exit(EXIT_FAILURE); } } ios->notify_fork(boost::asio::io_service::fork_parent); mutex_ios.unlock(); socket = boost::shared_ptr<tcp::socket>(new tcp::socket(*ios)); if (hostBlock->blockId == 1) { bool connected = false; acceptor->async_accept(*(socket.get()), boost::bind(&BlinkyBlocksVM::asyncAcceptHandler, this, error , &connected)); while(!connected && (pid != waitpid(pid, NULL, WNOHANG))) { if (!BlinkyBlocksVM::isInDebuggingMode()) { // In debugging mode the scheduler thread is looking for connections checkForReceivedVMCommands(); // it is actually check for connection usleep(10000); } } if(!connected) { ifstream file (vmLogFile.str().c_str()); string line; cerr << "VisibleSim error: unable to connect to the VM" << endl; cerr << vmLogFile.str() << ":" << endl; if (file.is_open()) { while (!file.eof()) { getline(file,line); cerr << line; } cerr << endl; file.close(); } acceptor->close(); exit(EXIT_FAILURE); } } else { acceptor->accept(*(socket.get())); } idSent = false; deterministicSet = false; nbSentCommands = 0; asyncReadCommand(); } void BlinkyBlocksVM::asyncAcceptHandler(boost::system::error_code& error, bool* connected) { if (error) { *connected = false; } else { *connected = true; } } BlinkyBlocksVM::~BlinkyBlocksVM() { closeSocket(); killProcess(); } void BlinkyBlocksVM::terminate() { waitpid(pid, NULL, 0); } void BlinkyBlocksVM::killProcess() { kill(pid, SIGTERM); waitpid(pid, NULL, 0); } void BlinkyBlocksVM::closeSocket() { if (socket != NULL) { socket->cancel(); socket->close(); socket.reset(); } } void BlinkyBlocksVM::asyncReadCommandHandler(const boost::system::error_code& error, std::size_t bytes_transferred) { if(error) { ERRPUT << "An error occurred while receiving a tcp command from VM " << hostBlock->blockId << " (socket closed ?) " <<endl; return; } try { memset(inBuffer+1, 0, inBuffer[0]); boost::asio::read(getSocket(),boost::asio::buffer((void*)(inBuffer + 1), inBuffer[0]) ); } catch (std::exception& e) { ERRPUT << "Connection to the VM "<< hostBlock->blockId << " lost" << endl; } handleInBuffer(); while (socket->available()) { try { boost::asio::read(getSocket(), boost::asio::buffer(inBuffer, sizeof(commandType))); boost::asio::read(getSocket(),boost::asio::buffer((void*)(inBuffer + 1), inBuffer[0])); } catch (std::exception& e) { ERRPUT << "Connection to the VM "<< hostBlock->blockId << " lost" << endl; } handleInBuffer(); } this->asyncReadCommand(); } void BlinkyBlocksVM::handleInBuffer() { BlinkyBlocksBlockCode *bbc = (BlinkyBlocksBlockCode*)hostBlock->blockCode; VMCommand command(inBuffer); bbc->handleCommand(command); } void BlinkyBlocksVM::asyncReadCommand() { if (socket == NULL) { ERRPUT << "Simulator is not connected to the VM "<< hostBlock->blockId << endl; return; } try { inBuffer[0] = 0; boost::asio::async_read(getSocket(), boost::asio::buffer(inBuffer, sizeof(commandType)), boost::bind(&BlinkyBlocksVM::asyncReadCommandHandler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } catch (std::exception& e) { ERRPUT << "Connection to the VM "<< hostBlock->blockId << " lost" << endl; } } int BlinkyBlocksVM::sendCommand(VMCommand &command){ if (socket == NULL) { ERRPUT << "Simulator is not connected to the VM "<< hostBlock->blockId << endl; return 0; } if (command.getType() != VM_COMMAND_DEBUG) { nbSentCommands++; ((BlinkyBlocksBlockCode*)hostBlock->blockCode)->handleDeterministicMode(command); } try { boost::asio::write(getSocket(), boost::asio::buffer(command.getData(), command.getSize())); //boost::asio::async_write(getSocket(), boost::asio::buffer(command.getData(), command.getSize()), boost::bind(&BlinkyBlocksVM::handle_write, this, // boost::asio::placeholders::error)); } catch (std::exception& e) { ERRPUT << "Connection to the VM "<< hostBlock->blockId << " lost" << endl; return 0; } return 1; } void BlinkyBlocksVM::handle_write(const boost::system::error_code& error) { if (!error) { cout << "ok" << endl; } } void BlinkyBlocksVM::checkForReceivedCommands() { if (ios != NULL) { mutex_ios.lock(); try { ios->poll(); ios->reset(); } catch (boost::exception& e) { } mutex_ios.unlock(); } } void BlinkyBlocksVM::waitForOneCommand() { if (ios != NULL) { mutex_ios.lock(); try { ios->run_one(); ios->reset(); } catch (boost::exception& e) { } mutex_ios.unlock(); } checkForReceivedCommands(); } void BlinkyBlocksVM::setConfiguration(string v, string p, bool d) { vmPath = v; programPath = p; debugging = d; } void BlinkyBlocksVM::createServer(int p) { assert(ios == NULL); ios = new boost::asio::io_service(); acceptor = new tcp::acceptor(*ios, tcp::endpoint(tcp::v4(), p)); } void BlinkyBlocksVM::deleteServer() { ios->stop(); delete acceptor; delete ios; ios = NULL; acceptor = NULL; } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "CommandSpecs.h" CommandSpecs::CommandSpecs() { } CommandSpecs::~CommandSpecs() { } bool CommandSpecs::ShouldRunThisCommand(ParsedCommand * Parsed) { return (Parsed->Words->at(0) == "specs"); } void CommandSpecs::Run(ParsedCommand* Parsed) { this->GetOSInfo(); this->GetProcessorInfo(); } string* CommandSpecs::GetName() { return new string("Specs"); } string* CommandSpecs::GetHelp() { return new string("Writes to the console some detailed information about your computer."); } void CommandSpecs::GetOSInfo() { __int64 major = 0; __int64 minor = 0; __int64 serviceMajor = 0; //Determine major version number. while (IsWindowsVersionOrGreater(major, minor, serviceMajor)) { ++major; } --major; //Determine minor version number. while (IsWindowsVersionOrGreater(major, minor, serviceMajor)) { ++minor; } --minor; //Determine service pack major version number. while (IsWindowsVersionOrGreater(major, minor, serviceMajor)) { serviceMajor++; } serviceMajor--; Console->WriteLine("OS Info: "); Console->WriteLine(&("Major: " + to_string(major))); Console->WriteLine(&("Minor: " + to_string(minor))); Console->WriteLine(&("Service: " + to_string(serviceMajor))); } void CommandSpecs::GetProcessorInfo() { Console->WriteLine("\r\n"); Console->WriteLine("Processor Information: "); Console->WriteLine("\r\n"); SYSTEM_INFO SysInfo; GetSystemInfo(&SysInfo); //SysInfo->dwNumberOfProcessors _PROCESSOR_POWER_INFORMATION* ProcessorInformations = new _PROCESSOR_POWER_INFORMATION[SysInfo.dwNumberOfProcessors]; CallNtPowerInformation(POWER_INFORMATION_LEVEL::ProcessorInformation, NULL, NULL, ProcessorInformations, (sizeof(_PROCESSOR_POWER_INFORMATION) * SysInfo.dwNumberOfProcessors)); __int8 i = 0; while (i != SysInfo.dwNumberOfProcessors) { Console->WriteLine(&("Processor " + to_string(ProcessorInformations[i].Number))); //Console->WriteLine(&("Current Mhz: " + to_string(ProcessorInformations[i].CurrentMhz))); Console->WriteLine(&("Max Mhz: " + to_string(ProcessorInformations[i].MaxMhz))); //Console->WriteLine(&("Mhz Limit: " + to_string(ProcessorInformations[i].MhzLimit))); Console->WriteLine("\r\n"); ++i; } } <commit_msg>Added back some things.<commit_after>#include "stdafx.h" #include "CommandSpecs.h" CommandSpecs::CommandSpecs() { } CommandSpecs::~CommandSpecs() { } bool CommandSpecs::ShouldRunThisCommand(ParsedCommand * Parsed) { return (Parsed->Words->at(0) == "specs"); } void CommandSpecs::Run(ParsedCommand* Parsed) { this->GetOSInfo(); this->GetProcessorInfo(); } string* CommandSpecs::GetName() { return new string("Specs"); } string* CommandSpecs::GetHelp() { return new string("Writes to the console some detailed information about your computer."); } void CommandSpecs::GetOSInfo() { __int64 major = 0; __int64 minor = 0; __int64 serviceMajor = 0; //Determine major version number. while (IsWindowsVersionOrGreater(major, minor, serviceMajor)) { ++major; } --major; //Determine minor version number. while (IsWindowsVersionOrGreater(major, minor, serviceMajor)) { ++minor; } --minor; //Determine service pack major version number. while (IsWindowsVersionOrGreater(major, minor, serviceMajor)) { serviceMajor++; } serviceMajor--; Console->WriteLine("OS Info: "); Console->WriteLine(&("Major: " + to_string(major))); Console->WriteLine(&("Minor: " + to_string(minor))); Console->WriteLine(&("Service: " + to_string(serviceMajor))); } void CommandSpecs::GetProcessorInfo() { Console->WriteLine("\r\n"); Console->WriteLine("Processor Information: "); Console->WriteLine("\r\n"); SYSTEM_INFO SysInfo; GetSystemInfo(&SysInfo); //SysInfo->dwNumberOfProcessors _PROCESSOR_POWER_INFORMATION* ProcessorInformations = new _PROCESSOR_POWER_INFORMATION[SysInfo.dwNumberOfProcessors]; CallNtPowerInformation(POWER_INFORMATION_LEVEL::ProcessorInformation, NULL, NULL, ProcessorInformations, (sizeof(_PROCESSOR_POWER_INFORMATION) * SysInfo.dwNumberOfProcessors)); __int8 i = 0; while (i != SysInfo.dwNumberOfProcessors) { Console->WriteLine(&("Processor " + to_string(ProcessorInformations[i].Number))); Console->WriteLine(&("Current Mhz: " + to_string(ProcessorInformations[i].CurrentMhz))); Console->WriteLine(&("Max Mhz: " + to_string(ProcessorInformations[i].MaxMhz))); Console->WriteLine(&("Mhz Limit: " + to_string(ProcessorInformations[i].MhzLimit))); Console->WriteLine("\r\n"); ++i; } } <|endoftext|>