text
stringlengths
54
60.6k
<commit_before>#include <ciri/gfx/dx/DXSamplerState.hpp> #include <ciri/gfx/dx/DXGraphicsDevice.hpp> namespace ciri { DXSamplerState::DXSamplerState( DXGraphicsDevice* device ) : ISamplerState(), _device(device), _samplerState(nullptr) { } DXSamplerState::~DXSamplerState() { destroy(); } bool DXSamplerState::create( const SamplerDesc& desc ) { if( _samplerState != nullptr ) { return false; } D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); samplerDesc.AddressU = ciriToDxWrap(desc.wrapU); samplerDesc.AddressV = ciriToDxWrap(desc.wrapV); samplerDesc.AddressW = ciriToDxWrap(desc.wrapW); samplerDesc.BorderColor[0] = desc.borderColor[0]; samplerDesc.BorderColor[1] = desc.borderColor[1]; samplerDesc.BorderColor[2] = desc.borderColor[2]; samplerDesc.BorderColor[3] = desc.borderColor[3]; samplerDesc.ComparisonFunc = ciriToDxFunc(desc.comparisonFunc); samplerDesc.Filter = ciriToDxFilter(desc.filter, desc.comparisonFunc != SamplerComparison::Never); samplerDesc.MaxAnisotropy = desc.maxAnisotropy; samplerDesc.MaxLOD = desc.maxLod; samplerDesc.MinLOD = desc.minLod; samplerDesc.MipLODBias = desc.lodBias; if( FAILED(_device->getDevice()->CreateSamplerState(&samplerDesc, &_samplerState)) ) { destroy(); return false; } return true; } void DXSamplerState::destroy() { if( _samplerState != nullptr ) { _samplerState->Release(); _samplerState = nullptr; } } ID3D11SamplerState* DXSamplerState::getSamplerState() const { return _samplerState; } D3D11_TEXTURE_ADDRESS_MODE DXSamplerState::ciriToDxWrap( SamplerWrap::Mode mode ) const { switch( mode ) { case SamplerWrap::Wrap: { return D3D11_TEXTURE_ADDRESS_WRAP; } case SamplerWrap::Mirror: { return D3D11_TEXTURE_ADDRESS_MIRROR; } case SamplerWrap::Clamp: { return D3D11_TEXTURE_ADDRESS_CLAMP; } case SamplerWrap::Border: { return D3D11_TEXTURE_ADDRESS_BORDER; } case SamplerWrap::MirrorOnce: { return D3D11_TEXTURE_ADDRESS_MIRROR_ONCE; } default: { return D3D11_TEXTURE_ADDRESS_WRAP; // no fail available } } } D3D11_COMPARISON_FUNC DXSamplerState::ciriToDxFunc( SamplerComparison::Mode mode ) const { switch( mode ) { case SamplerComparison::Never: { return D3D11_COMPARISON_NEVER; } case SamplerComparison::Always: { return D3D11_COMPARISON_ALWAYS; } case SamplerComparison::Less: { return D3D11_COMPARISON_LESS; } case SamplerComparison::Equal: { return D3D11_COMPARISON_EQUAL; } case SamplerComparison::LessEqual: { return D3D11_COMPARISON_LESS_EQUAL; } case SamplerComparison::Greater: { return D3D11_COMPARISON_GREATER; } case SamplerComparison::GreaterEqual: { return D3D11_COMPARISON_GREATER_EQUAL; } case SamplerComparison::NotEqual: { return D3D11_COMPARISON_NOT_EQUAL; } default: { return D3D11_COMPARISON_NEVER; // no fail available } } } D3D11_FILTER DXSamplerState::ciriToDxFilter( SamplerFilter::Mode mode, bool comparison ) const { int filter = 0; switch( mode ) { case SamplerFilter::Point: { filter = D3D11_FILTER_MIN_MAG_MIP_POINT; } case SamplerFilter::PointLinear: { filter = D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT; } case SamplerFilter::LinearPoint: { filter = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT; } case SamplerFilter::Bilinear: { filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; } case SamplerFilter::Trilinear: { filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; } case SamplerFilter::Anisotropic: { filter = D3D11_FILTER_ANISOTROPIC; } default: { filter = D3D11_FILTER_MIN_MAG_MIP_POINT; // point filtering by default } } // thanks, http://www.humus.name/! if( comparison ) { filter |= 0x80; } return (D3D11_FILTER)filter; } } // ciri<commit_msg>Fixed a bug added by the previous commit where break statements were missing. Also<commit_after>#include <ciri/gfx/dx/DXSamplerState.hpp> #include <ciri/gfx/dx/DXGraphicsDevice.hpp> namespace ciri { DXSamplerState::DXSamplerState( DXGraphicsDevice* device ) : ISamplerState(), _device(device), _samplerState(nullptr) { } DXSamplerState::~DXSamplerState() { destroy(); } bool DXSamplerState::create( const SamplerDesc& desc ) { if( _samplerState != nullptr ) { return false; } D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); samplerDesc.AddressU = ciriToDxWrap(desc.wrapU); samplerDesc.AddressV = ciriToDxWrap(desc.wrapV); samplerDesc.AddressW = ciriToDxWrap(desc.wrapW); samplerDesc.BorderColor[0] = desc.borderColor[0]; samplerDesc.BorderColor[1] = desc.borderColor[1]; samplerDesc.BorderColor[2] = desc.borderColor[2]; samplerDesc.BorderColor[3] = desc.borderColor[3]; samplerDesc.ComparisonFunc = ciriToDxFunc(desc.comparisonFunc); samplerDesc.Filter = ciriToDxFilter(desc.filter, desc.comparisonFunc != SamplerComparison::Never); samplerDesc.MaxAnisotropy = desc.maxAnisotropy; samplerDesc.MaxLOD = desc.maxLod; samplerDesc.MinLOD = desc.minLod; samplerDesc.MipLODBias = desc.lodBias; if( FAILED(_device->getDevice()->CreateSamplerState(&samplerDesc, &_samplerState)) ) { destroy(); return false; } return true; } void DXSamplerState::destroy() { if( _samplerState != nullptr ) { _samplerState->Release(); _samplerState = nullptr; } } ID3D11SamplerState* DXSamplerState::getSamplerState() const { return _samplerState; } D3D11_TEXTURE_ADDRESS_MODE DXSamplerState::ciriToDxWrap( SamplerWrap::Mode mode ) const { switch( mode ) { case SamplerWrap::Wrap: { return D3D11_TEXTURE_ADDRESS_WRAP; } case SamplerWrap::Mirror: { return D3D11_TEXTURE_ADDRESS_MIRROR; } case SamplerWrap::Clamp: { return D3D11_TEXTURE_ADDRESS_CLAMP; } case SamplerWrap::Border: { return D3D11_TEXTURE_ADDRESS_BORDER; } case SamplerWrap::MirrorOnce: { return D3D11_TEXTURE_ADDRESS_MIRROR_ONCE; } default: { return D3D11_TEXTURE_ADDRESS_WRAP; // no fail available } } } D3D11_COMPARISON_FUNC DXSamplerState::ciriToDxFunc( SamplerComparison::Mode mode ) const { switch( mode ) { case SamplerComparison::Never: { return D3D11_COMPARISON_NEVER; } case SamplerComparison::Always: { return D3D11_COMPARISON_ALWAYS; } case SamplerComparison::Less: { return D3D11_COMPARISON_LESS; } case SamplerComparison::Equal: { return D3D11_COMPARISON_EQUAL; } case SamplerComparison::LessEqual: { return D3D11_COMPARISON_LESS_EQUAL; } case SamplerComparison::Greater: { return D3D11_COMPARISON_GREATER; } case SamplerComparison::GreaterEqual: { return D3D11_COMPARISON_GREATER_EQUAL; } case SamplerComparison::NotEqual: { return D3D11_COMPARISON_NOT_EQUAL; } default: { return D3D11_COMPARISON_NEVER; // no fail available } } } D3D11_FILTER DXSamplerState::ciriToDxFilter( SamplerFilter::Mode mode, bool comparison ) const { int filter = 0; switch( mode ) { case SamplerFilter::Point: { filter = D3D11_FILTER_MIN_MAG_MIP_POINT; break; } case SamplerFilter::PointLinear: { filter = D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT; break; } case SamplerFilter::LinearPoint: { filter = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT; break; } case SamplerFilter::Bilinear: { filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; break; } case SamplerFilter::Trilinear: { filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; break; } case SamplerFilter::Anisotropic: { filter = D3D11_FILTER_ANISOTROPIC; break; } default: { filter = D3D11_FILTER_MIN_MAG_MIP_POINT; // point filtering by default break; } } // thanks, http://www.humus.name/! if( comparison ) { filter |= 0x80; } return (D3D11_FILTER)filter; } } // ciri<|endoftext|>
<commit_before><commit_msg>ByteString->rtl::OString<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * 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_sot.hxx" #include "stg.hxx" #include "stgelem.hxx" #include "stgcache.hxx" #include "stgstrms.hxx" #include "stgdir.hxx" #include "stgio.hxx" #include <rtl/instance.hxx> ///////////////////////////// class StgIo ////////////////////////////// // This class holds the storage header and all internal streams. StgIo::StgIo() : StgCache() { pTOC = NULL; pDataFAT = NULL; pDataStrm = NULL; pFAT = NULL; bCopied = FALSE; } StgIo::~StgIo() { delete pTOC; delete pDataFAT; delete pDataStrm; delete pFAT; } // Load the header. Do not set an error code if the header is invalid. BOOL StgIo::Load() { if( pStrm ) { if( aHdr.Load( *this ) ) { if( aHdr.Check() ) SetupStreams(); else return FALSE; } } return Good(); } // Set up an initial, empty storage BOOL StgIo::Init() { aHdr.Init(); SetupStreams(); return CommitAll(); } void StgIo::SetupStreams() { delete pTOC; delete pDataFAT; delete pDataStrm; delete pFAT; pTOC = NULL; pDataFAT = NULL; pDataStrm = NULL; pFAT = NULL; ResetError(); SetPhysPageSize( 1 << aHdr.GetPageSize() ); pFAT = new StgFATStrm( *this ); pTOC = new StgDirStrm( *this ); if( !GetError() ) { StgDirEntry* pRoot = pTOC->GetRoot(); if( pRoot ) { pDataFAT = new StgDataStrm( *this, aHdr.GetDataFATStart(), -1 ); pDataStrm = new StgDataStrm( *this, pRoot ); pDataFAT->SetIncrement( 1 << aHdr.GetPageSize() ); pDataStrm->SetIncrement( GetDataPageSize() ); pDataStrm->SetEntry( *pRoot ); } else SetError( SVSTREAM_FILEFORMAT_ERROR ); } } // get the logical data page size short StgIo::GetDataPageSize() { return 1 << aHdr.GetDataPageSize(); } // Commit everything BOOL StgIo::CommitAll() { // Store the data (all streams and the TOC) if( pTOC->Store() ) { if( Commit( NULL ) ) { aHdr.SetDataFATStart( pDataFAT->GetStart() ); aHdr.SetDataFATSize( pDataFAT->GetPages() ); aHdr.SetTOCStart( pTOC->GetStart() ); if( aHdr.Store( *this ) ) { pStrm->Flush(); ULONG n = pStrm->GetError(); SetError( n ); #ifdef DBG_UTIL if( n==0 ) ValidateFATs(); #endif return BOOL( n == 0 ); } } } SetError( SVSTREAM_WRITE_ERROR ); return FALSE; } class EasyFat { INT32 *pFat; BOOL *pFree; INT32 nPages; INT32 nPageSize; public: EasyFat( StgIo & rIo, StgStrm *pFatStream, INT32 nPSize ); ~EasyFat() { delete pFat; delete pFree; } INT32 GetPageSize() { return nPageSize; } INT32 Count() { return nPages; } INT32 operator[]( INT32 nOffset ) { return pFat[ nOffset ]; } ULONG Mark( INT32 nPage, INT32 nCount, INT32 nExpect ); BOOL HasUnrefChains(); }; EasyFat::EasyFat( StgIo& rIo, StgStrm* pFatStream, INT32 nPSize ) { nPages = pFatStream->GetSize() >> 2; nPageSize = nPSize; pFat = new INT32[ nPages ]; pFree = new BOOL[ nPages ]; StgPage *pPage = NULL; INT32 nFatPageSize = (1 << rIo.aHdr.GetPageSize()) - 2; for( INT32 nPage = 0; nPage < nPages; nPage++ ) { if( ! (nPage % nFatPageSize) ) { pFatStream->Pos2Page( nPage << 2 ); INT32 nPhysPage = pFatStream->GetPage(); pPage = rIo.Get( nPhysPage, TRUE ); } pFat[ nPage ] = pPage->GetPage( short( nPage % nFatPageSize ) ); pFree[ nPage ] = TRUE; } } BOOL EasyFat::HasUnrefChains() { for( INT32 nPage = 0; nPage < nPages; nPage++ ) { if( pFree[ nPage ] && pFat[ nPage ] != -1 ) return TRUE; } return FALSE; } ULONG EasyFat::Mark( INT32 nPage, INT32 nCount, INT32 nExpect ) { if( nCount > 0 ) --nCount /= GetPageSize(), nCount++; INT32 nCurPage = nPage; while( nCount != 0 ) { pFree[ nCurPage ] = FALSE; nCurPage = pFat[ nCurPage ]; //Stream zu lang if( nCurPage != nExpect && nCount == 1 ) return FAT_WRONGLENGTH; //Stream zu kurz if( nCurPage == nExpect && nCount != 1 && nCount != -1 ) return FAT_WRONGLENGTH; // letzter Block bei Stream ohne Laenge if( nCurPage == nExpect && nCount == -1 ) nCount = 1; if( nCount != -1 ) nCount--; // Naechster Block nicht in der FAT if( nCount && ( nCurPage < 0 || nCurPage >= nPages ) ) return FAT_OUTOFBOUNDS; } return FAT_OK; } class Validator { ULONG nError; EasyFat aSmallFat; EasyFat aFat; StgIo &rIo; ULONG ValidateMasterFATs(); ULONG ValidateDirectoryEntries(); ULONG FindUnrefedChains(); ULONG MarkAll( StgDirEntry *pEntry ); public: Validator( StgIo &rIo ); BOOL IsError() { return nError != 0; } }; Validator::Validator( StgIo &rIoP ) : aSmallFat( rIoP, rIoP.pDataFAT, 1 << rIoP.aHdr.GetDataPageSize() ), aFat( rIoP, rIoP.pFAT, 1 << rIoP.aHdr.GetPageSize() ), rIo( rIoP ) { ULONG nErr = nError = FAT_OK; if( ( nErr = ValidateMasterFATs() ) != FAT_OK ) nError = nErr; else if( ( nErr = ValidateDirectoryEntries() ) != FAT_OK ) nError = nErr; else if( ( nErr = FindUnrefedChains()) != FAT_OK ) nError = nErr; } ULONG Validator::ValidateMasterFATs() { INT32 nCount = rIo.aHdr.GetFATSize(); ULONG nErr; for( INT32 i = 0; i < nCount; i++ ) { if( ( nErr = aFat.Mark(rIo.pFAT->GetPage( short(i), FALSE ), aFat.GetPageSize(), -3 )) != FAT_OK ) return nErr; } if( rIo.aHdr.GetMasters() ) if( ( nErr = aFat.Mark(rIo.aHdr.GetFATChain( ), aFat.GetPageSize(), -4 )) != FAT_OK ) return nErr; return FAT_OK; } ULONG Validator::MarkAll( StgDirEntry *pEntry ) { StgIterator aIter( *pEntry ); ULONG nErr = FAT_OK; for( StgDirEntry* p = aIter.First(); p ; p = aIter.Next() ) { if( p->aEntry.GetType() == STG_STORAGE ) { nErr = MarkAll( p ); if( nErr != FAT_OK ) return nErr; } else { INT32 nSize = p->aEntry.GetSize(); if( nSize < rIo.aHdr.GetThreshold() ) nErr = aSmallFat.Mark( p->aEntry.GetStartPage(),nSize, -2 ); else nErr = aFat.Mark( p->aEntry.GetStartPage(),nSize, -2 ); if( nErr != FAT_OK ) return nErr; } } return FAT_OK; } ULONG Validator::ValidateDirectoryEntries() { // Normale DirEntries ULONG nErr = MarkAll( rIo.pTOC->GetRoot() ); if( nErr != FAT_OK ) return nErr; // Small Data nErr = aFat.Mark( rIo.pTOC->GetRoot()->aEntry.GetStartPage(), rIo.pTOC->GetRoot()->aEntry.GetSize(), -2 ); if( nErr != FAT_OK ) return nErr; // Small Data FAT nErr = aFat.Mark( rIo.aHdr.GetDataFATStart(), rIo.aHdr.GetDataFATSize() * aFat.GetPageSize(), -2 ); if( nErr != FAT_OK ) return nErr; // TOC nErr = aFat.Mark( rIo.aHdr.GetTOCStart(), -1, -2 ); return nErr; } ULONG Validator::FindUnrefedChains() { if( aSmallFat.HasUnrefChains() || aFat.HasUnrefChains() ) return FAT_UNREFCHAIN; else return FAT_OK; } namespace { struct ErrorLink : public rtl::Static<Link, ErrorLink > {}; } void StgIo::SetErrorLink( const Link& rLink ) { ErrorLink::get() = rLink; } const Link& StgIo::GetErrorLink() { return ErrorLink::get(); } ULONG StgIo::ValidateFATs() { if( bFile ) { Validator *pV = new Validator( *this ); BOOL bRet1 = !pV->IsError(), bRet2 = TRUE ; delete pV; SvFileStream *pFileStrm = ( SvFileStream *) GetStrm(); StgIo aIo; if( aIo.Open( pFileStrm->GetFileName(), STREAM_READ | STREAM_SHARE_DENYNONE) && aIo.Load() ) { pV = new Validator( aIo ); bRet2 = !pV->IsError(); delete pV; } ULONG nErr; if( bRet1 != bRet2 ) nErr = bRet1 ? FAT_ONFILEERROR : FAT_INMEMORYERROR; else nErr = bRet1 ? FAT_OK : FAT_BOTHERROR; if( nErr != FAT_OK && !bCopied ) { StgLinkArg aArg; aArg.aFile = pFileStrm->GetFileName(); aArg.nErr = nErr; ErrorLink::get().Call( &aArg ); bCopied = TRUE; } // DBG_ASSERT( nErr == FAT_OK ,"Storage kaputt"); return nErr; } // DBG_ERROR("Validiere nicht (kein FileStorage)"); return FAT_OK; } <commit_msg>sw33bf08: #i113623#: stgio.cxx: fix operator delete mismatch<commit_after>/************************************************************************* * * 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_sot.hxx" #include "stg.hxx" #include "stgelem.hxx" #include "stgcache.hxx" #include "stgstrms.hxx" #include "stgdir.hxx" #include "stgio.hxx" #include <rtl/instance.hxx> ///////////////////////////// class StgIo ////////////////////////////// // This class holds the storage header and all internal streams. StgIo::StgIo() : StgCache() { pTOC = NULL; pDataFAT = NULL; pDataStrm = NULL; pFAT = NULL; bCopied = FALSE; } StgIo::~StgIo() { delete pTOC; delete pDataFAT; delete pDataStrm; delete pFAT; } // Load the header. Do not set an error code if the header is invalid. BOOL StgIo::Load() { if( pStrm ) { if( aHdr.Load( *this ) ) { if( aHdr.Check() ) SetupStreams(); else return FALSE; } } return Good(); } // Set up an initial, empty storage BOOL StgIo::Init() { aHdr.Init(); SetupStreams(); return CommitAll(); } void StgIo::SetupStreams() { delete pTOC; delete pDataFAT; delete pDataStrm; delete pFAT; pTOC = NULL; pDataFAT = NULL; pDataStrm = NULL; pFAT = NULL; ResetError(); SetPhysPageSize( 1 << aHdr.GetPageSize() ); pFAT = new StgFATStrm( *this ); pTOC = new StgDirStrm( *this ); if( !GetError() ) { StgDirEntry* pRoot = pTOC->GetRoot(); if( pRoot ) { pDataFAT = new StgDataStrm( *this, aHdr.GetDataFATStart(), -1 ); pDataStrm = new StgDataStrm( *this, pRoot ); pDataFAT->SetIncrement( 1 << aHdr.GetPageSize() ); pDataStrm->SetIncrement( GetDataPageSize() ); pDataStrm->SetEntry( *pRoot ); } else SetError( SVSTREAM_FILEFORMAT_ERROR ); } } // get the logical data page size short StgIo::GetDataPageSize() { return 1 << aHdr.GetDataPageSize(); } // Commit everything BOOL StgIo::CommitAll() { // Store the data (all streams and the TOC) if( pTOC->Store() ) { if( Commit( NULL ) ) { aHdr.SetDataFATStart( pDataFAT->GetStart() ); aHdr.SetDataFATSize( pDataFAT->GetPages() ); aHdr.SetTOCStart( pTOC->GetStart() ); if( aHdr.Store( *this ) ) { pStrm->Flush(); ULONG n = pStrm->GetError(); SetError( n ); #ifdef DBG_UTIL if( n==0 ) ValidateFATs(); #endif return BOOL( n == 0 ); } } } SetError( SVSTREAM_WRITE_ERROR ); return FALSE; } class EasyFat { INT32 *pFat; BOOL *pFree; INT32 nPages; INT32 nPageSize; public: EasyFat( StgIo & rIo, StgStrm *pFatStream, INT32 nPSize ); ~EasyFat() { delete[] pFat; delete[] pFree; } INT32 GetPageSize() { return nPageSize; } INT32 Count() { return nPages; } INT32 operator[]( INT32 nOffset ) { return pFat[ nOffset ]; } ULONG Mark( INT32 nPage, INT32 nCount, INT32 nExpect ); BOOL HasUnrefChains(); }; EasyFat::EasyFat( StgIo& rIo, StgStrm* pFatStream, INT32 nPSize ) { nPages = pFatStream->GetSize() >> 2; nPageSize = nPSize; pFat = new INT32[ nPages ]; pFree = new BOOL[ nPages ]; StgPage *pPage = NULL; INT32 nFatPageSize = (1 << rIo.aHdr.GetPageSize()) - 2; for( INT32 nPage = 0; nPage < nPages; nPage++ ) { if( ! (nPage % nFatPageSize) ) { pFatStream->Pos2Page( nPage << 2 ); INT32 nPhysPage = pFatStream->GetPage(); pPage = rIo.Get( nPhysPage, TRUE ); } pFat[ nPage ] = pPage->GetPage( short( nPage % nFatPageSize ) ); pFree[ nPage ] = TRUE; } } BOOL EasyFat::HasUnrefChains() { for( INT32 nPage = 0; nPage < nPages; nPage++ ) { if( pFree[ nPage ] && pFat[ nPage ] != -1 ) return TRUE; } return FALSE; } ULONG EasyFat::Mark( INT32 nPage, INT32 nCount, INT32 nExpect ) { if( nCount > 0 ) --nCount /= GetPageSize(), nCount++; INT32 nCurPage = nPage; while( nCount != 0 ) { pFree[ nCurPage ] = FALSE; nCurPage = pFat[ nCurPage ]; //Stream zu lang if( nCurPage != nExpect && nCount == 1 ) return FAT_WRONGLENGTH; //Stream zu kurz if( nCurPage == nExpect && nCount != 1 && nCount != -1 ) return FAT_WRONGLENGTH; // letzter Block bei Stream ohne Laenge if( nCurPage == nExpect && nCount == -1 ) nCount = 1; if( nCount != -1 ) nCount--; // Naechster Block nicht in der FAT if( nCount && ( nCurPage < 0 || nCurPage >= nPages ) ) return FAT_OUTOFBOUNDS; } return FAT_OK; } class Validator { ULONG nError; EasyFat aSmallFat; EasyFat aFat; StgIo &rIo; ULONG ValidateMasterFATs(); ULONG ValidateDirectoryEntries(); ULONG FindUnrefedChains(); ULONG MarkAll( StgDirEntry *pEntry ); public: Validator( StgIo &rIo ); BOOL IsError() { return nError != 0; } }; Validator::Validator( StgIo &rIoP ) : aSmallFat( rIoP, rIoP.pDataFAT, 1 << rIoP.aHdr.GetDataPageSize() ), aFat( rIoP, rIoP.pFAT, 1 << rIoP.aHdr.GetPageSize() ), rIo( rIoP ) { ULONG nErr = nError = FAT_OK; if( ( nErr = ValidateMasterFATs() ) != FAT_OK ) nError = nErr; else if( ( nErr = ValidateDirectoryEntries() ) != FAT_OK ) nError = nErr; else if( ( nErr = FindUnrefedChains()) != FAT_OK ) nError = nErr; } ULONG Validator::ValidateMasterFATs() { INT32 nCount = rIo.aHdr.GetFATSize(); ULONG nErr; for( INT32 i = 0; i < nCount; i++ ) { if( ( nErr = aFat.Mark(rIo.pFAT->GetPage( short(i), FALSE ), aFat.GetPageSize(), -3 )) != FAT_OK ) return nErr; } if( rIo.aHdr.GetMasters() ) if( ( nErr = aFat.Mark(rIo.aHdr.GetFATChain( ), aFat.GetPageSize(), -4 )) != FAT_OK ) return nErr; return FAT_OK; } ULONG Validator::MarkAll( StgDirEntry *pEntry ) { StgIterator aIter( *pEntry ); ULONG nErr = FAT_OK; for( StgDirEntry* p = aIter.First(); p ; p = aIter.Next() ) { if( p->aEntry.GetType() == STG_STORAGE ) { nErr = MarkAll( p ); if( nErr != FAT_OK ) return nErr; } else { INT32 nSize = p->aEntry.GetSize(); if( nSize < rIo.aHdr.GetThreshold() ) nErr = aSmallFat.Mark( p->aEntry.GetStartPage(),nSize, -2 ); else nErr = aFat.Mark( p->aEntry.GetStartPage(),nSize, -2 ); if( nErr != FAT_OK ) return nErr; } } return FAT_OK; } ULONG Validator::ValidateDirectoryEntries() { // Normale DirEntries ULONG nErr = MarkAll( rIo.pTOC->GetRoot() ); if( nErr != FAT_OK ) return nErr; // Small Data nErr = aFat.Mark( rIo.pTOC->GetRoot()->aEntry.GetStartPage(), rIo.pTOC->GetRoot()->aEntry.GetSize(), -2 ); if( nErr != FAT_OK ) return nErr; // Small Data FAT nErr = aFat.Mark( rIo.aHdr.GetDataFATStart(), rIo.aHdr.GetDataFATSize() * aFat.GetPageSize(), -2 ); if( nErr != FAT_OK ) return nErr; // TOC nErr = aFat.Mark( rIo.aHdr.GetTOCStart(), -1, -2 ); return nErr; } ULONG Validator::FindUnrefedChains() { if( aSmallFat.HasUnrefChains() || aFat.HasUnrefChains() ) return FAT_UNREFCHAIN; else return FAT_OK; } namespace { struct ErrorLink : public rtl::Static<Link, ErrorLink > {}; } void StgIo::SetErrorLink( const Link& rLink ) { ErrorLink::get() = rLink; } const Link& StgIo::GetErrorLink() { return ErrorLink::get(); } ULONG StgIo::ValidateFATs() { if( bFile ) { Validator *pV = new Validator( *this ); BOOL bRet1 = !pV->IsError(), bRet2 = TRUE ; delete pV; SvFileStream *pFileStrm = ( SvFileStream *) GetStrm(); StgIo aIo; if( aIo.Open( pFileStrm->GetFileName(), STREAM_READ | STREAM_SHARE_DENYNONE) && aIo.Load() ) { pV = new Validator( aIo ); bRet2 = !pV->IsError(); delete pV; } ULONG nErr; if( bRet1 != bRet2 ) nErr = bRet1 ? FAT_ONFILEERROR : FAT_INMEMORYERROR; else nErr = bRet1 ? FAT_OK : FAT_BOTHERROR; if( nErr != FAT_OK && !bCopied ) { StgLinkArg aArg; aArg.aFile = pFileStrm->GetFileName(); aArg.nErr = nErr; ErrorLink::get().Call( &aArg ); bCopied = TRUE; } // DBG_ASSERT( nErr == FAT_OK ,"Storage kaputt"); return nErr; } // DBG_ERROR("Validiere nicht (kein FileStorage)"); return FAT_OK; } <|endoftext|>
<commit_before>// Copyright (c) 2014 Ross Kinder. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file contains implementations of the functions declared in the public // header. #include <errno.h> #include <ringfile.h> #include "ringfile_internal.h" struct RINGFILE { Ringfile impl_; }; RINGFILE * ringfile_create(const char * path, size_t size) { RINGFILE * self = new RINGFILE(); if (!self->impl_.Create(path, size)) { errno = self->impl_.error(); delete self; return NULL; } return self; } RINGFILE * ringfile_open(const char * path, const char * mode_str) { Ringfile::Mode mode; if (strcmp(mode_str, "r") == 0) { mode = Ringfile::kRead; } else if (strcmp(mode_str, "a") == 0) { mode = Ringfile::kAppend; } else { return NULL; } RINGFILE * self = new RINGFILE(); if (!self->impl_.Open(path, mode)) { errno = self->impl_.error(); delete self; return NULL; } return self; } size_t ringfile_write(const void * ptr, size_t size, RINGFILE * self) { if (!self->impl_.Write(ptr, size)) { errno = self->impl_.error(); return -1; } return size; } size_t ringfile_read(void * ptr, size_t size, RINGFILE * self) { return self->impl_.Read(ptr, size); } size_t ringfile_next_record_size(RINGFILE * self) { return self->impl_.NextRecordSize(); } int ringfile_close(RINGFILE * self) { self->impl_.Close(); // redundant with the delete below delete self; } <commit_msg>add missing include (gcc)<commit_after>// Copyright (c) 2014 Ross Kinder. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file contains implementations of the functions declared in the public // header. #include <errno.h> #include <ringfile.h> #include <string.h> #include "ringfile_internal.h" struct RINGFILE { Ringfile impl_; }; RINGFILE * ringfile_create(const char * path, size_t size) { RINGFILE * self = new RINGFILE(); if (!self->impl_.Create(path, size)) { errno = self->impl_.error(); delete self; return NULL; } return self; } RINGFILE * ringfile_open(const char * path, const char * mode_str) { Ringfile::Mode mode; if (strcmp(mode_str, "r") == 0) { mode = Ringfile::kRead; } else if (strcmp(mode_str, "a") == 0) { mode = Ringfile::kAppend; } else { return NULL; } RINGFILE * self = new RINGFILE(); if (!self->impl_.Open(path, mode)) { errno = self->impl_.error(); delete self; return NULL; } return self; } size_t ringfile_write(const void * ptr, size_t size, RINGFILE * self) { if (!self->impl_.Write(ptr, size)) { errno = self->impl_.error(); return -1; } return size; } size_t ringfile_read(void * ptr, size_t size, RINGFILE * self) { return self->impl_.Read(ptr, size); } size_t ringfile_next_record_size(RINGFILE * self) { return self->impl_.NextRecordSize(); } int ringfile_close(RINGFILE * self) { self->impl_.Close(); // redundant with the delete below delete self; } <|endoftext|>
<commit_before>#include "pointers.h" #include <boost/python.hpp> #include <dart/dynamics/dynamics.h> #include "util.h" #include "types.h" using ::boost::python::object; using ::boost::python::throw_error_already_set; using ::dart::dynamics::Joint; using ::dart::dynamics::BodyNode; using ::dart::dynamics::BodyNodePtr; using ::dart::dynamics::BallJoint; using ::dart::dynamics::EulerJoint; using ::dart::dynamics::FreeJoint; using ::dart::dynamics::PlanarJoint; using ::dart::dynamics::PrismaticJoint; using ::dart::dynamics::RevoluteJoint; using ::dart::dynamics::ScrewJoint; using ::dart::dynamics::TranslationalJoint; using ::dart::dynamics::UniversalJoint; using ::dart::dynamics::WeldJoint; using ::dart::dynamics::SkeletonPtr; using ::dart::python::JointType; template <class T> T const &convert_properties(Joint::Properties const *properties) { static T const default_properties; auto cast_properties = dynamic_cast<T const *>(properties); if (properties && !cast_properties) { PyErr_SetString(PyExc_ValueError, "Properties has incorrect type."); throw_error_already_set(); } if (cast_properties) { return *cast_properties; } else { return default_properties; } } template <class T> T *moveTo_impl(BodyNode *node, SkeletonPtr newSkeleton, BodyNodePtr newParent, Joint::Properties const *props) { if (!newParent) { PyErr_SetString(PyExc_ValueError, "Parent BodyNode is None."); throw_error_already_set(); return nullptr; } return node->moveTo<T>(newSkeleton, newParent.get(), convert_properties<typename T::Properties>(props)); } static Joint *BodyNode_moveTo4( BodyNode *node, SkeletonPtr newSkeleton, BodyNodePtr newParent, JointType::Enum joint_type, Joint::Properties const *props) { using boost::python::extract; switch (joint_type) { case JointType::PRISMATIC: return moveTo_impl<PrismaticJoint>(node, newSkeleton, newParent, props); case JointType::REVOLUTE: return moveTo_impl<RevoluteJoint>(node, newSkeleton, newParent, props); case JointType::SCREW: return moveTo_impl<ScrewJoint>(node, newSkeleton, newParent, props); case JointType::WELD: return moveTo_impl<WeldJoint>(node, newSkeleton, newParent, props); case JointType::UNIVERSAL: return moveTo_impl<UniversalJoint>(node, newSkeleton, newParent, props); case JointType::BALL: return moveTo_impl<BallJoint>(node, newSkeleton, newParent, props); case JointType::EULER: return moveTo_impl<EulerJoint>(node, newSkeleton, newParent, props); case JointType::PLANAR: return moveTo_impl<PlanarJoint>(node, newSkeleton, newParent, props); case JointType::TRANSLATIONAL: return moveTo_impl<TranslationalJoint>(node, newSkeleton, newParent, props); case JointType::FREE: return moveTo_impl<FreeJoint>(node, newSkeleton, newParent, props); default: PyErr_SetString(PyExc_ValueError, "Invalid joint type."); throw_error_already_set(); return nullptr; }; } static Joint *BodyNode_moveTo3( BodyNode *node, BodyNodePtr newParent, JointType::Enum joint_type, Joint::Properties const *props) { if (!newParent) { PyErr_SetString(PyExc_ValueError, "Parent BodyNode is None."); throw_error_already_set(); return nullptr; } return BodyNode_moveTo4(node, newParent->getSkeleton(), newParent, joint_type, props); } static Joint *BodyNode_moveTo2( BodyNode *node, BodyNodePtr newParent, JointType::Enum joint_type) { return BodyNode_moveTo3(node, newParent, joint_type, nullptr); } void python_BodyNode() { using namespace ::boost::python; using ::dart::dynamics::BodyNode; using ::dart::dynamics::BodyNodePtr; using ::dart::dynamics::SkeletonPtr; smart_ptr_from_python<BodyNode, BodyNodePtr>(); class_<BodyNode, BodyNodePtr, boost::noncopyable>("BodyNode", no_init) .add_property("name", make_function(&BodyNode::getName, return_value_policy<copy_const_reference>()), static_cast<void (*)(BodyNode *, std::string const &)>( &DISCARD_METHOD_RETURN(BodyNode, BodyNode::setName)) ) .add_property("skeleton", static_cast<SkeletonPtr (BodyNode::*)()>( &BodyNode::getSkeleton)) .def("moveTo", static_cast<void (BodyNode::*)(BodyNode *)>( &BodyNode::moveTo)) .def("moveTo", static_cast<void (BodyNode::*)(SkeletonPtr, BodyNode *)>( &BodyNode::moveTo)) .def("moveTo", &BodyNode_moveTo2, return_value_policy<reference_existing_object>()) .def("moveTo", &BodyNode_moveTo3, return_value_policy<reference_existing_object>()) .def("moveTo", &BodyNode_moveTo4, return_value_policy<reference_existing_object>()) .def("split", static_cast<SkeletonPtr (BodyNode::*)(std::string const &)>( &BodyNode::split)) ; } <commit_msg>Crazy std::forward is working.<commit_after>#include "pointers.h" #include <boost/python.hpp> #include <dart/dynamics/dynamics.h> #include "util.h" #include "types.h" using ::boost::python::object; using ::boost::python::throw_error_already_set; using ::dart::dynamics::Joint; using ::dart::dynamics::BodyNode; using ::dart::dynamics::BodyNodePtr; using ::dart::dynamics::BallJoint; using ::dart::dynamics::EulerJoint; using ::dart::dynamics::FreeJoint; using ::dart::dynamics::PlanarJoint; using ::dart::dynamics::PrismaticJoint; using ::dart::dynamics::RevoluteJoint; using ::dart::dynamics::ScrewJoint; using ::dart::dynamics::TranslationalJoint; using ::dart::dynamics::UniversalJoint; using ::dart::dynamics::WeldJoint; using ::dart::dynamics::SkeletonPtr; using ::dart::python::JointType; template <class T> T const &convert_properties(Joint::Properties const *properties) { static T const default_properties; auto cast_properties = dynamic_cast<T const *>(properties); if (properties && !cast_properties) { PyErr_SetString(PyExc_ValueError, "Properties has incorrect type."); throw_error_already_set(); } if (cast_properties) { return *cast_properties; } else { return default_properties; } } #if 0 template <class T> T *moveTo_impl(BodyNode *node, SkeletonPtr newSkeleton, BodyNodePtr newParent, Joint::Properties const *props) { if (!newParent) { PyErr_SetString(PyExc_ValueError, "Parent BodyNode is None."); throw_error_already_set(); return nullptr; } return node->moveTo<T>(newSkeleton, newParent.get(), convert_properties<typename T::Properties>(props)); } #endif template <typename T> struct moveTo3_wrapper { static void call(BodyNode *node, SkeletonPtr newSkeleton, BodyNodePtr newParent, Joint::Properties const *props) { if (!newParent) { PyErr_SetString(PyExc_ValueError, "Parent BodyNode is None."); throw_error_already_set(); //return nullptr; } node->moveTo<T>(newSkeleton, newParent.get(), convert_properties<typename T::Properties>(props)); } }; template <typename T> struct test_wrapper { static void call(int x) { } }; // template <template <typename T> class Fn, typename... Args> void Joint_unpack(JointType::Enum joint_type, Args&&... args) { switch (joint_type) { case JointType::PRISMATIC: Fn<PrismaticJoint>::call(std::forward<Args>(args)...); break; default: PyErr_SetString(PyExc_ValueError, "Invalid joint type."); throw_error_already_set(); }; } #if 0 static Joint *BodyNode_moveTo4( BodyNode *node, SkeletonPtr newSkeleton, BodyNodePtr newParent, JointType::Enum joint_type, Joint::Properties const *props) { using boost::python::extract; switch (joint_type) { case JointType::PRISMATIC: return moveTo_impl<PrismaticJoint>(node, newSkeleton, newParent, props); case JointType::REVOLUTE: return moveTo_impl<RevoluteJoint>(node, newSkeleton, newParent, props); case JointType::SCREW: return moveTo_impl<ScrewJoint>(node, newSkeleton, newParent, props); case JointType::WELD: return moveTo_impl<WeldJoint>(node, newSkeleton, newParent, props); case JointType::UNIVERSAL: return moveTo_impl<UniversalJoint>(node, newSkeleton, newParent, props); case JointType::BALL: return moveTo_impl<BallJoint>(node, newSkeleton, newParent, props); case JointType::EULER: return moveTo_impl<EulerJoint>(node, newSkeleton, newParent, props); case JointType::PLANAR: return moveTo_impl<PlanarJoint>(node, newSkeleton, newParent, props); case JointType::TRANSLATIONAL: return moveTo_impl<TranslationalJoint>(node, newSkeleton, newParent, props); case JointType::FREE: return moveTo_impl<FreeJoint>(node, newSkeleton, newParent, props); default: PyErr_SetString(PyExc_ValueError, "Invalid joint type."); throw_error_already_set(); return nullptr; }; } static Joint *BodyNode_moveTo3( BodyNode *node, BodyNodePtr newParent, JointType::Enum joint_type, Joint::Properties const *props) { if (!newParent) { PyErr_SetString(PyExc_ValueError, "Parent BodyNode is None."); throw_error_already_set(); return nullptr; } return BodyNode_moveTo4(node, newParent->getSkeleton(), newParent, joint_type, props); } static Joint *BodyNode_moveTo2( BodyNode *node, BodyNodePtr newParent, JointType::Enum joint_type) { return BodyNode_moveTo3(node, newParent, joint_type, nullptr); } #endif void python_BodyNode() { using namespace ::boost::python; using ::dart::dynamics::BodyNode; using ::dart::dynamics::BodyNodePtr; using ::dart::dynamics::SkeletonPtr; smart_ptr_from_python<BodyNode, BodyNodePtr>(); &Joint_unpack<moveTo3_wrapper, BodyNode *, SkeletonPtr, BodyNodePtr, Joint::Properties const *>; class_<BodyNode, BodyNodePtr, boost::noncopyable>("BodyNode", no_init) .add_property("name", make_function(&BodyNode::getName, return_value_policy<copy_const_reference>()), static_cast<void (*)(BodyNode *, std::string const &)>( &DISCARD_METHOD_RETURN(BodyNode, BodyNode::setName)) ) .add_property("skeleton", static_cast<SkeletonPtr (BodyNode::*)()>( &BodyNode::getSkeleton)) .def("moveTo", static_cast<void (BodyNode::*)(BodyNode *)>( &BodyNode::moveTo)) .def("moveTo", static_cast<void (BodyNode::*)(SkeletonPtr, BodyNode *)>( &BodyNode::moveTo)) #if 0 .def("moveTo", &BodyNode_moveTo2, return_value_policy<reference_existing_object>()) .def("moveTo", &BodyNode_moveTo3, return_value_policy<reference_existing_object>()) .def("moveTo", &BodyNode_moveTo4, return_value_policy<reference_existing_object>()) #endif .def("split", static_cast<SkeletonPtr (BodyNode::*)(std::string const &)>( &BodyNode::split)) ; } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Youssef Kashef // Copyright (c) 2015, ELM Library Project // 3-clause BSD License // //M*/ #include "elm/layers/layergraph.h" #include "gtest/gtest.h" #include "elm/core/debug_utils.h" #include "elm/core/exception.h" #include "elm/core/inputname.h" #include "elm/core/layerconfig.h" #include "elm/layers/layers_interim/base_featuretransformationlayer.h" using cv::Mat1f; using namespace elm; namespace { class LayerA : public base_FeatureTransformationLayer { public: void Clear() {} void Reconfigure(const LayerConfig &config) { } void Activate(const Signal &signal) { ELM_COUT_VAR("LayerA::Activate()") m_ = Mat1f(1, 1, 3.f); } }; class LayerB : public base_FeatureTransformationLayer { public: void Clear() {} void Reconfigure(const LayerConfig &config) { } void Activate(const Signal &signal) { ELM_COUT_VAR("LayerB::Activate()") m_ = Mat1f(1, 1, 4.f); } }; class LayerC : public base_FeatureTransformationLayer { public: void Clear() {} void Reconfigure(const LayerConfig &config) { } void Activate(const Signal &signal) { ELM_COUT_VAR("LayerC::Activate()") m_ = Mat1f(1, 1, 4.f); } }; class LayerD : public base_FeatureTransformationLayer { public: void Clear() {} void Reconfigure(const LayerConfig &config) { } void Activate(const Signal &signal) { ELM_COUT_VAR("LayerD::Activate()") m_ = Mat1f(1, 1, 5.f); } }; class LayerGraphProtected : public LayerGraph { public: LayerGraphProtected() : LayerGraph() { } }; class LayerGraphProtectedTest : public ::testing::Test { }; TEST_F(LayerGraphProtectedTest, Test) { } class LayerGraphTest : public ::testing::Test { }; TEST_F(LayerGraphTest, Test) { LayerGraph to; std::shared_ptr<base_Layer> a(new LayerA); std::shared_ptr<base_Layer> b(new LayerB); std::shared_ptr<base_Layer> c(new LayerC); { LayerConfig cfg; PTree p; p.put("pb", "pb1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "outa"); io.Output(LayerA::KEY_INPUT_STIMULUS, "outb"); to.Add("b", a, cfg, io); } { LayerConfig cfg; PTree p; p.put("pc", "pc1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "outb"); io.Output(LayerA::KEY_INPUT_STIMULUS, "outc"); to.Add("c", a, cfg, io); } { LayerConfig cfg; PTree p; p.put("pa", "pa1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "ina"); io.Output(LayerA::KEY_INPUT_STIMULUS, "outa"); to.Add("a", a, cfg, io); } to.print(); } TEST_F(LayerGraphTest, ClearActive_empty) { EXPECT_NO_THROW(LayerGraph().ClearActive()); } TEST_F(LayerGraphTest, ClearActive) { LayerGraph to; std::shared_ptr<base_Layer> a(new LayerA); LayerConfig cfg; PTree p; p.put("pa", "pa1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "ina"); io.Output(LayerA::KEY_OUTPUT_RESPONSE, "outa"); to.Add("a", a, cfg, io); ASSERT_TRUE(to.Outputs().empty()); to.AddOutput("outa"); ASSERT_FALSE(to.Outputs().empty()); to.ClearActive(); EXPECT_TRUE(to.Outputs().empty()); } TEST_F(LayerGraphTest, Outputs_empty) { EXPECT_TRUE(LayerGraph().Outputs().empty()); } TEST_F(LayerGraphTest, Outputs_single) { LayerGraph to; std::shared_ptr<base_Layer> a(new LayerA); LayerConfig cfg; PTree p; p.put("pa", "pa1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "ina"); io.Output(LayerA::KEY_OUTPUT_RESPONSE, "outa"); to.Add("a", a, cfg, io); EXPECT_TRUE(to.Outputs().empty()); to.AddOutput("outa"); SetS outputs = to.Outputs(); ASSERT_FALSE(outputs.empty()); EXPECT_EQ(SetS({"outa"}), to.Outputs()) << "Unexpected outputs"; EXPECT_NE(SetS({"ina"}), to.Outputs()) << "Inputs confused with outputs."; } TEST_F(LayerGraphTest, AddOutput) { LayerGraph to; std::shared_ptr<base_Layer> a(new LayerA); std::shared_ptr<base_Layer> b(new LayerB); std::shared_ptr<base_Layer> c(new LayerC); std::shared_ptr<base_Layer> d(new LayerD); { LayerConfig cfg; PTree p; p.put("pb", "pb1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "outa"); io.Output(LayerA::KEY_OUTPUT_RESPONSE, "outb"); to.Add("b", b, cfg, io); } { LayerConfig cfg; PTree p; p.put("pc", "pc1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "outb"); io.Output(LayerA::KEY_OUTPUT_RESPONSE, "outc"); to.Add("c", c, cfg, io); } { LayerConfig cfg; PTree p; p.put("pa", "pa1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "ina"); io.Output(LayerA::KEY_OUTPUT_RESPONSE, "outa"); to.Add("a", a, cfg, io); } { LayerConfig cfg; PTree p; p.put("pd", "pd1"); LayerIONames io; io.Input(LayerD::KEY_INPUT_STIMULUS, "ind"); io.Output(LayerD::KEY_OUTPUT_RESPONSE, "outd"); to.Add("d", d, cfg, io); } to.AddOutput("outc"); EXPECT_EQ(SetS({"outc", "outb", "outa"}), to.Outputs()) << "Unexpected outputs"; to.ClearActive(); EXPECT_TRUE(to.Outputs().empty()) << "Outputs inspite of clearing active layers."; to.AddOutput("outd"); EXPECT_EQ(SetS({"outd"}), to.Outputs()) << "Unexpected outputs"; to.ClearActive(); to.AddOutput("outb"); EXPECT_EQ(SetS({"outb", "outa"}), to.Outputs()) << "Unexpected outputs"; to.AddOutput("outd"); // add second output without clearing EXPECT_NE(SetS({"outb", "outa", "outd"}), to.Outputs()) << "Unexpected outputs"; to.ClearActive(); } TEST_F(LayerGraphTest, AddOutput_invalid) { LayerGraph to; EXPECT_THROW(to.AddOutput("outa"), ExceptionKeyError); std::shared_ptr<base_Layer> a(new LayerA); { LayerConfig cfg; PTree p; p.put("pb", "pb1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "outa"); io.Output(LayerA::KEY_INPUT_STIMULUS, "outb"); to.Add("b", a, cfg, io); } EXPECT_THROW(to.AddOutput("out"), ExceptionKeyError); EXPECT_THROW(to.AddOutput("outa"), ExceptionKeyError); } TEST_F(LayerGraphTest, GenVtxColor_name) { LayerGraph to; VtxColor a = to.genVtxColor("a", LayerConfig(), LayerIONames()); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), LayerIONames())); EXPECT_NE(a, to.genVtxColor("a ", LayerConfig(), LayerIONames())); EXPECT_NE(a, to.genVtxColor("a1", LayerConfig(), LayerIONames())); EXPECT_NE(a, to.genVtxColor("b", LayerConfig(), LayerIONames())); } TEST_F(LayerGraphTest, GenVtxColor_cfg) { LayerGraph to; LayerConfig cfg; VtxColor a = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_EQ(a, to.genVtxColor("a", cfg, LayerIONames())); PTree p; p.put("foo", 1); cfg.Params(p); VtxColor a1 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_NE(a, a1); VtxColor a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_EQ(a1, a2); p = cfg.Params(); p.put("foo", 2); cfg.Params(p); a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_NE(a1, a2); p = cfg.Params(); p.put("bar", 1); cfg.Params(p); a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_NE(a1, a2); p = PTree(); p.put("bar", 1); cfg.Params(p); a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_NE(a1, a2); p = cfg.Params(); p.put("bar", 3); cfg.Params(p); a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_NE(a1, a2); p = PTree(); p.put("foo", 1); cfg.Params(p); a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_EQ(a1, a2); } TEST_F(LayerGraphTest, GenVtxColor_io_input) { LayerGraph to; LayerIONames io; io.Input("foo", "bar"); VtxColor a = to.genVtxColor("a", LayerConfig(), io); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); EXPECT_NE(a, to.genVtxColor("a ", LayerConfig(), LayerIONames())); io.Input("foo", "bar"); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); io.Input("foo", "x"); EXPECT_NE(a, to.genVtxColor("a ", LayerConfig(), LayerIONames())); io.Input("foo", "bar"); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); LayerIONames io2; io2.Input("x", "bar"); EXPECT_NE(a, to.genVtxColor("a", LayerConfig(), io2)) << "Match inspite of different keys"; } TEST_F(LayerGraphTest, GenVtxColor_io_output) { LayerGraph to; LayerIONames io; io.Output("foo", "bar"); VtxColor a = to.genVtxColor("a", LayerConfig(), io); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); EXPECT_NE(a, to.genVtxColor("a ", LayerConfig(), LayerIONames())); io.Output("foo", "bar"); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); io.Output("foo", "x"); EXPECT_NE(a, to.genVtxColor("a ", LayerConfig(), LayerIONames())); io.Output("foo", "bar"); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); LayerIONames io2; io2.Output("x", "bar"); EXPECT_NE(a, to.genVtxColor("a", LayerConfig(), io2)) << "Match inspite of different keys"; } } // annonymous namespace for unit tests <commit_msg>undo failing test on purpose<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Youssef Kashef // Copyright (c) 2015, ELM Library Project // 3-clause BSD License // //M*/ #include "elm/layers/layergraph.h" #include "gtest/gtest.h" #include "elm/core/debug_utils.h" #include "elm/core/exception.h" #include "elm/core/inputname.h" #include "elm/core/layerconfig.h" #include "elm/layers/layers_interim/base_featuretransformationlayer.h" using cv::Mat1f; using namespace elm; namespace { class LayerA : public base_FeatureTransformationLayer { public: void Clear() {} void Reconfigure(const LayerConfig &config) { } void Activate(const Signal &signal) { ELM_COUT_VAR("LayerA::Activate()") m_ = Mat1f(1, 1, 3.f); } }; class LayerB : public base_FeatureTransformationLayer { public: void Clear() {} void Reconfigure(const LayerConfig &config) { } void Activate(const Signal &signal) { ELM_COUT_VAR("LayerB::Activate()") m_ = Mat1f(1, 1, 4.f); } }; class LayerC : public base_FeatureTransformationLayer { public: void Clear() {} void Reconfigure(const LayerConfig &config) { } void Activate(const Signal &signal) { ELM_COUT_VAR("LayerC::Activate()") m_ = Mat1f(1, 1, 4.f); } }; class LayerD : public base_FeatureTransformationLayer { public: void Clear() {} void Reconfigure(const LayerConfig &config) { } void Activate(const Signal &signal) { ELM_COUT_VAR("LayerD::Activate()") m_ = Mat1f(1, 1, 5.f); } }; class LayerGraphProtected : public LayerGraph { public: LayerGraphProtected() : LayerGraph() { } }; class LayerGraphProtectedTest : public ::testing::Test { }; TEST_F(LayerGraphProtectedTest, Test) { } class LayerGraphTest : public ::testing::Test { }; TEST_F(LayerGraphTest, Test) { LayerGraph to; std::shared_ptr<base_Layer> a(new LayerA); std::shared_ptr<base_Layer> b(new LayerB); std::shared_ptr<base_Layer> c(new LayerC); { LayerConfig cfg; PTree p; p.put("pb", "pb1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "outa"); io.Output(LayerA::KEY_INPUT_STIMULUS, "outb"); to.Add("b", a, cfg, io); } { LayerConfig cfg; PTree p; p.put("pc", "pc1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "outb"); io.Output(LayerA::KEY_INPUT_STIMULUS, "outc"); to.Add("c", a, cfg, io); } { LayerConfig cfg; PTree p; p.put("pa", "pa1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "ina"); io.Output(LayerA::KEY_INPUT_STIMULUS, "outa"); to.Add("a", a, cfg, io); } to.print(); } TEST_F(LayerGraphTest, ClearActive_empty) { EXPECT_NO_THROW(LayerGraph().ClearActive()); } TEST_F(LayerGraphTest, ClearActive) { LayerGraph to; std::shared_ptr<base_Layer> a(new LayerA); LayerConfig cfg; PTree p; p.put("pa", "pa1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "ina"); io.Output(LayerA::KEY_OUTPUT_RESPONSE, "outa"); to.Add("a", a, cfg, io); ASSERT_TRUE(to.Outputs().empty()); to.AddOutput("outa"); ASSERT_FALSE(to.Outputs().empty()); to.ClearActive(); EXPECT_TRUE(to.Outputs().empty()); } TEST_F(LayerGraphTest, Outputs_empty) { EXPECT_TRUE(LayerGraph().Outputs().empty()); } TEST_F(LayerGraphTest, Outputs_single) { LayerGraph to; std::shared_ptr<base_Layer> a(new LayerA); LayerConfig cfg; PTree p; p.put("pa", "pa1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "ina"); io.Output(LayerA::KEY_OUTPUT_RESPONSE, "outa"); to.Add("a", a, cfg, io); EXPECT_TRUE(to.Outputs().empty()); to.AddOutput("outa"); SetS outputs = to.Outputs(); ASSERT_FALSE(outputs.empty()); EXPECT_EQ(SetS({"outa"}), to.Outputs()) << "Unexpected outputs"; EXPECT_NE(SetS({"ina"}), to.Outputs()) << "Inputs confused with outputs."; } TEST_F(LayerGraphTest, AddOutput) { LayerGraph to; std::shared_ptr<base_Layer> a(new LayerA); std::shared_ptr<base_Layer> b(new LayerB); std::shared_ptr<base_Layer> c(new LayerC); std::shared_ptr<base_Layer> d(new LayerD); { LayerConfig cfg; PTree p; p.put("pb", "pb1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "outa"); io.Output(LayerA::KEY_OUTPUT_RESPONSE, "outb"); to.Add("b", b, cfg, io); } { LayerConfig cfg; PTree p; p.put("pc", "pc1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "outb"); io.Output(LayerA::KEY_OUTPUT_RESPONSE, "outc"); to.Add("c", c, cfg, io); } { LayerConfig cfg; PTree p; p.put("pa", "pa1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "ina"); io.Output(LayerA::KEY_OUTPUT_RESPONSE, "outa"); to.Add("a", a, cfg, io); } { LayerConfig cfg; PTree p; p.put("pd", "pd1"); LayerIONames io; io.Input(LayerD::KEY_INPUT_STIMULUS, "ind"); io.Output(LayerD::KEY_OUTPUT_RESPONSE, "outd"); to.Add("d", d, cfg, io); } to.AddOutput("outc"); EXPECT_EQ(SetS({"outc", "outb", "outa"}), to.Outputs()) << "Unexpected outputs"; to.ClearActive(); EXPECT_TRUE(to.Outputs().empty()) << "Outputs inspite of clearing active layers."; to.AddOutput("outd"); EXPECT_EQ(SetS({"outd"}), to.Outputs()) << "Unexpected outputs"; to.ClearActive(); to.AddOutput("outb"); EXPECT_EQ(SetS({"outb", "outa"}), to.Outputs()) << "Unexpected outputs"; to.AddOutput("outd"); // add second output without clearing EXPECT_EQ(SetS({"outb", "outa", "outd"}), to.Outputs()) << "Unexpected outputs"; to.ClearActive(); } TEST_F(LayerGraphTest, AddOutput_invalid) { LayerGraph to; EXPECT_THROW(to.AddOutput("outa"), ExceptionKeyError); std::shared_ptr<base_Layer> a(new LayerA); { LayerConfig cfg; PTree p; p.put("pb", "pb1"); LayerIONames io; io.Input(LayerA::KEY_INPUT_STIMULUS, "outa"); io.Output(LayerA::KEY_INPUT_STIMULUS, "outb"); to.Add("b", a, cfg, io); } EXPECT_THROW(to.AddOutput("out"), ExceptionKeyError); EXPECT_THROW(to.AddOutput("outa"), ExceptionKeyError); } TEST_F(LayerGraphTest, GenVtxColor_name) { LayerGraph to; VtxColor a = to.genVtxColor("a", LayerConfig(), LayerIONames()); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), LayerIONames())); EXPECT_NE(a, to.genVtxColor("a ", LayerConfig(), LayerIONames())); EXPECT_NE(a, to.genVtxColor("a1", LayerConfig(), LayerIONames())); EXPECT_NE(a, to.genVtxColor("b", LayerConfig(), LayerIONames())); } TEST_F(LayerGraphTest, GenVtxColor_cfg) { LayerGraph to; LayerConfig cfg; VtxColor a = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_EQ(a, to.genVtxColor("a", cfg, LayerIONames())); PTree p; p.put("foo", 1); cfg.Params(p); VtxColor a1 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_NE(a, a1); VtxColor a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_EQ(a1, a2); p = cfg.Params(); p.put("foo", 2); cfg.Params(p); a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_NE(a1, a2); p = cfg.Params(); p.put("bar", 1); cfg.Params(p); a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_NE(a1, a2); p = PTree(); p.put("bar", 1); cfg.Params(p); a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_NE(a1, a2); p = cfg.Params(); p.put("bar", 3); cfg.Params(p); a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_NE(a1, a2); p = PTree(); p.put("foo", 1); cfg.Params(p); a2 = to.genVtxColor("a", cfg, LayerIONames()); EXPECT_EQ(a1, a2); } TEST_F(LayerGraphTest, GenVtxColor_io_input) { LayerGraph to; LayerIONames io; io.Input("foo", "bar"); VtxColor a = to.genVtxColor("a", LayerConfig(), io); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); EXPECT_NE(a, to.genVtxColor("a ", LayerConfig(), LayerIONames())); io.Input("foo", "bar"); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); io.Input("foo", "x"); EXPECT_NE(a, to.genVtxColor("a ", LayerConfig(), LayerIONames())); io.Input("foo", "bar"); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); LayerIONames io2; io2.Input("x", "bar"); EXPECT_NE(a, to.genVtxColor("a", LayerConfig(), io2)) << "Match inspite of different keys"; } TEST_F(LayerGraphTest, GenVtxColor_io_output) { LayerGraph to; LayerIONames io; io.Output("foo", "bar"); VtxColor a = to.genVtxColor("a", LayerConfig(), io); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); EXPECT_NE(a, to.genVtxColor("a ", LayerConfig(), LayerIONames())); io.Output("foo", "bar"); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); io.Output("foo", "x"); EXPECT_NE(a, to.genVtxColor("a ", LayerConfig(), LayerIONames())); io.Output("foo", "bar"); EXPECT_EQ(a, to.genVtxColor("a", LayerConfig(), io)); LayerIONames io2; io2.Output("x", "bar"); EXPECT_NE(a, to.genVtxColor("a", LayerConfig(), io2)) << "Match inspite of different keys"; } } // annonymous namespace for unit tests <|endoftext|>
<commit_before>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/iomgr/port.h" #ifdef GRPC_POSIX_SOCKET #include "src/core/lib/iomgr/socket_utils.h" #include "src/core/lib/iomgr/socket_utils_posix.h" #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include "src/core/lib/gpr/host_port.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/iomgr/sockaddr.h" #include "src/core/lib/iomgr/sockaddr_utils.h" /* set a socket to non blocking mode */ grpc_error* grpc_set_socket_nonblocking(int fd, int non_blocking) { int oldflags = fcntl(fd, F_GETFL, 0); if (oldflags < 0) { return GRPC_OS_ERROR(errno, "fcntl"); } if (non_blocking) { oldflags |= O_NONBLOCK; } else { oldflags &= ~O_NONBLOCK; } if (fcntl(fd, F_SETFL, oldflags) != 0) { return GRPC_OS_ERROR(errno, "fcntl"); } return GRPC_ERROR_NONE; } grpc_error* grpc_set_socket_no_sigpipe_if_possible(int fd) { #ifdef GRPC_HAVE_SO_NOSIGPIPE int val = 1; int newval; socklen_t intlen = sizeof(newval); if (0 != setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &val, sizeof(val))) { return GRPC_OS_ERROR(errno, "setsockopt(SO_NOSIGPIPE)"); } if (0 != getsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &newval, &intlen)) { return GRPC_OS_ERROR(errno, "getsockopt(SO_NOSIGPIPE)"); } if ((newval != 0) != (val != 0)) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_NOSIGPIPE"); } #endif return GRPC_ERROR_NONE; } grpc_error* grpc_set_socket_ip_pktinfo_if_possible(int fd) { #ifdef GRPC_HAVE_IP_PKTINFO int get_local_ip = 1; if (0 != setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &get_local_ip, sizeof(get_local_ip))) { return GRPC_OS_ERROR(errno, "setsockopt(IP_PKTINFO)"); } #endif return GRPC_ERROR_NONE; } grpc_error* grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd) { #ifdef GRPC_HAVE_IPV6_RECVPKTINFO int get_local_ip = 1; if (0 != setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &get_local_ip, sizeof(get_local_ip))) { return GRPC_OS_ERROR(errno, "setsockopt(IPV6_RECVPKTINFO)"); } #endif return GRPC_ERROR_NONE; } grpc_error* grpc_set_socket_sndbuf(int fd, int buffer_size_bytes) { return 0 == setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffer_size_bytes, sizeof(buffer_size_bytes)) ? GRPC_ERROR_NONE : GRPC_OS_ERROR(errno, "setsockopt(SO_SNDBUF)"); } grpc_error* grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes) { return 0 == setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buffer_size_bytes, sizeof(buffer_size_bytes)) ? GRPC_ERROR_NONE : GRPC_OS_ERROR(errno, "setsockopt(SO_RCVBUF)"); } /* set a socket to close on exec */ grpc_error* grpc_set_socket_cloexec(int fd, int close_on_exec) { int oldflags = fcntl(fd, F_GETFD, 0); if (oldflags < 0) { return GRPC_OS_ERROR(errno, "fcntl"); } if (close_on_exec) { oldflags |= FD_CLOEXEC; } else { oldflags &= ~FD_CLOEXEC; } if (fcntl(fd, F_SETFD, oldflags) != 0) { return GRPC_OS_ERROR(errno, "fcntl"); } return GRPC_ERROR_NONE; } /* set a socket to reuse old addresses */ grpc_error* grpc_set_socket_reuse_addr(int fd, int reuse) { int val = (reuse != 0); int newval; socklen_t intlen = sizeof(newval); if (0 != setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) { return GRPC_OS_ERROR(errno, "setsockopt(SO_REUSEADDR)"); } if (0 != getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &newval, &intlen)) { return GRPC_OS_ERROR(errno, "getsockopt(SO_REUSEADDR)"); } if ((newval != 0) != val) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_REUSEADDR"); } return GRPC_ERROR_NONE; } /* set a socket to reuse old addresses */ grpc_error* grpc_set_socket_reuse_port(int fd, int reuse) { #ifndef SO_REUSEPORT return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "SO_REUSEPORT unavailable on compiling system"); #else int val = (reuse != 0); int newval; socklen_t intlen = sizeof(newval); if (0 != setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val))) { return GRPC_OS_ERROR(errno, "setsockopt(SO_REUSEPORT)"); } if (0 != getsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &newval, &intlen)) { return GRPC_OS_ERROR(errno, "getsockopt(SO_REUSEPORT)"); } if ((newval != 0) != val) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_REUSEPORT"); } return GRPC_ERROR_NONE; #endif } static gpr_once g_probe_so_reuesport_once = GPR_ONCE_INIT; static int g_support_so_reuseport = false; void probe_so_reuseport_once(void) { #ifndef GPR_MANYLINUX1 int s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { /* This might be an ipv6-only environment in which case 'socket(AF_INET,..)' call would fail. Try creating IPv6 socket in that case */ s = socket(AF_INET6, SOCK_STREAM, 0); } if (s >= 0) { g_support_so_reuseport = GRPC_LOG_IF_ERROR("check for SO_REUSEPORT", grpc_set_socket_reuse_port(s, 1)); close(s); } #endif } bool grpc_is_socket_reuse_port_supported() { gpr_once_init(&g_probe_so_reuesport_once, probe_so_reuseport_once); return g_support_so_reuseport; } /* disable nagle */ grpc_error* grpc_set_socket_low_latency(int fd, int low_latency) { int val = (low_latency != 0); int newval; socklen_t intlen = sizeof(newval); if (0 != setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val))) { return GRPC_OS_ERROR(errno, "setsockopt(TCP_NODELAY)"); } if (0 != getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &newval, &intlen)) { return GRPC_OS_ERROR(errno, "getsockopt(TCP_NODELAY)"); } if ((newval != 0) != val) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set TCP_NODELAY"); } return GRPC_ERROR_NONE; } /* set a socket using a grpc_socket_mutator */ grpc_error* grpc_set_socket_with_mutator(int fd, grpc_socket_mutator* mutator) { GPR_ASSERT(mutator); if (!grpc_socket_mutator_mutate_fd(mutator, fd)) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("grpc_socket_mutator failed."); } return GRPC_ERROR_NONE; } static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT; static int g_ipv6_loopback_available; static void probe_ipv6_once(void) { int fd = socket(AF_INET6, SOCK_STREAM, 0); g_ipv6_loopback_available = 0; if (fd < 0) { gpr_log(GPR_INFO, "Disabling AF_INET6 sockets because socket() failed."); } else { grpc_sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr.s6_addr[15] = 1; /* [::1]:0 */ if (bind(fd, reinterpret_cast<grpc_sockaddr*>(&addr), sizeof(addr)) == 0) { g_ipv6_loopback_available = 1; } else { gpr_log(GPR_INFO, "Disabling AF_INET6 sockets because ::1 is not available."); } close(fd); } } int grpc_ipv6_loopback_available(void) { gpr_once_init(&g_probe_ipv6_once, probe_ipv6_once); return g_ipv6_loopback_available; } /* This should be 0 in production, but it may be enabled for testing or debugging purposes, to simulate an environment where IPv6 sockets can't also speak IPv4. */ int grpc_forbid_dualstack_sockets_for_testing = 0; static int set_socket_dualstack(int fd) { if (!grpc_forbid_dualstack_sockets_for_testing) { const int off = 0; return 0 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof(off)); } else { /* Force an IPv6-only socket, for testing purposes. */ const int on = 1; setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)); return 0; } } static grpc_error* error_for_fd(int fd, const grpc_resolved_address* addr) { if (fd >= 0) return GRPC_ERROR_NONE; char* addr_str; grpc_sockaddr_to_string(&addr_str, addr, 0); grpc_error* err = grpc_error_set_str(GRPC_OS_ERROR(errno, "socket"), GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(addr_str)); gpr_free(addr_str); return err; } grpc_error* grpc_create_dualstack_socket( const grpc_resolved_address* resolved_addr, int type, int protocol, grpc_dualstack_mode* dsmode, int* newfd) { return grpc_create_dualstack_socket_using_factory( nullptr, resolved_addr, type, protocol, dsmode, newfd); } static int create_socket(grpc_socket_factory* factory, int domain, int type, int protocol) { return (factory != nullptr) ? grpc_socket_factory_socket(factory, domain, type, protocol) : socket(domain, type, protocol); } grpc_error* grpc_create_dualstack_socket_using_factory( grpc_socket_factory* factory, const grpc_resolved_address* resolved_addr, int type, int protocol, grpc_dualstack_mode* dsmode, int* newfd) { const grpc_sockaddr* addr = reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr); int family = addr->sa_family; if (family == AF_INET6) { if (grpc_ipv6_loopback_available()) { *newfd = create_socket(factory, family, type, protocol); } else { *newfd = -1; errno = EAFNOSUPPORT; } /* Check if we've got a valid dualstack socket. */ if (*newfd >= 0 && set_socket_dualstack(*newfd)) { *dsmode = GRPC_DSMODE_DUALSTACK; return GRPC_ERROR_NONE; } /* If this isn't an IPv4 address, then return whatever we've got. */ if (!grpc_sockaddr_is_v4mapped(resolved_addr, nullptr)) { *dsmode = GRPC_DSMODE_IPV6; return error_for_fd(*newfd, resolved_addr); } /* Fall back to AF_INET. */ if (*newfd >= 0) { close(*newfd); } family = AF_INET; } *dsmode = family == AF_INET ? GRPC_DSMODE_IPV4 : GRPC_DSMODE_NONE; *newfd = create_socket(factory, family, type, protocol); return error_for_fd(*newfd, resolved_addr); } uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); } uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); } int grpc_inet_pton(int af, const char* src, void* dst) { return inet_pton(af, src, dst); } const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) { GPR_ASSERT(size <= (socklen_t)-1); return inet_ntop(af, src, dst, static_cast<socklen_t>(size)); } #endif <commit_msg>format<commit_after>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/iomgr/port.h" #ifdef GRPC_POSIX_SOCKET #include "src/core/lib/iomgr/socket_utils.h" #include "src/core/lib/iomgr/socket_utils_posix.h" #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include "src/core/lib/gpr/host_port.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/iomgr/sockaddr.h" #include "src/core/lib/iomgr/sockaddr_utils.h" /* set a socket to non blocking mode */ grpc_error* grpc_set_socket_nonblocking(int fd, int non_blocking) { int oldflags = fcntl(fd, F_GETFL, 0); if (oldflags < 0) { return GRPC_OS_ERROR(errno, "fcntl"); } if (non_blocking) { oldflags |= O_NONBLOCK; } else { oldflags &= ~O_NONBLOCK; } if (fcntl(fd, F_SETFL, oldflags) != 0) { return GRPC_OS_ERROR(errno, "fcntl"); } return GRPC_ERROR_NONE; } grpc_error* grpc_set_socket_no_sigpipe_if_possible(int fd) { #ifdef GRPC_HAVE_SO_NOSIGPIPE int val = 1; int newval; socklen_t intlen = sizeof(newval); if (0 != setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &val, sizeof(val))) { return GRPC_OS_ERROR(errno, "setsockopt(SO_NOSIGPIPE)"); } if (0 != getsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &newval, &intlen)) { return GRPC_OS_ERROR(errno, "getsockopt(SO_NOSIGPIPE)"); } if ((newval != 0) != (val != 0)) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_NOSIGPIPE"); } #endif return GRPC_ERROR_NONE; } grpc_error* grpc_set_socket_ip_pktinfo_if_possible(int fd) { #ifdef GRPC_HAVE_IP_PKTINFO int get_local_ip = 1; if (0 != setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &get_local_ip, sizeof(get_local_ip))) { return GRPC_OS_ERROR(errno, "setsockopt(IP_PKTINFO)"); } #endif return GRPC_ERROR_NONE; } grpc_error* grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd) { #ifdef GRPC_HAVE_IPV6_RECVPKTINFO int get_local_ip = 1; if (0 != setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &get_local_ip, sizeof(get_local_ip))) { return GRPC_OS_ERROR(errno, "setsockopt(IPV6_RECVPKTINFO)"); } #endif return GRPC_ERROR_NONE; } grpc_error* grpc_set_socket_sndbuf(int fd, int buffer_size_bytes) { return 0 == setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffer_size_bytes, sizeof(buffer_size_bytes)) ? GRPC_ERROR_NONE : GRPC_OS_ERROR(errno, "setsockopt(SO_SNDBUF)"); } grpc_error* grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes) { return 0 == setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buffer_size_bytes, sizeof(buffer_size_bytes)) ? GRPC_ERROR_NONE : GRPC_OS_ERROR(errno, "setsockopt(SO_RCVBUF)"); } /* set a socket to close on exec */ grpc_error* grpc_set_socket_cloexec(int fd, int close_on_exec) { int oldflags = fcntl(fd, F_GETFD, 0); if (oldflags < 0) { return GRPC_OS_ERROR(errno, "fcntl"); } if (close_on_exec) { oldflags |= FD_CLOEXEC; } else { oldflags &= ~FD_CLOEXEC; } if (fcntl(fd, F_SETFD, oldflags) != 0) { return GRPC_OS_ERROR(errno, "fcntl"); } return GRPC_ERROR_NONE; } /* set a socket to reuse old addresses */ grpc_error* grpc_set_socket_reuse_addr(int fd, int reuse) { int val = (reuse != 0); int newval; socklen_t intlen = sizeof(newval); if (0 != setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) { return GRPC_OS_ERROR(errno, "setsockopt(SO_REUSEADDR)"); } if (0 != getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &newval, &intlen)) { return GRPC_OS_ERROR(errno, "getsockopt(SO_REUSEADDR)"); } if ((newval != 0) != val) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_REUSEADDR"); } return GRPC_ERROR_NONE; } /* set a socket to reuse old addresses */ grpc_error* grpc_set_socket_reuse_port(int fd, int reuse) { #ifndef SO_REUSEPORT return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "SO_REUSEPORT unavailable on compiling system"); #else int val = (reuse != 0); int newval; socklen_t intlen = sizeof(newval); if (0 != setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val))) { return GRPC_OS_ERROR(errno, "setsockopt(SO_REUSEPORT)"); } if (0 != getsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &newval, &intlen)) { return GRPC_OS_ERROR(errno, "getsockopt(SO_REUSEPORT)"); } if ((newval != 0) != val) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_REUSEPORT"); } return GRPC_ERROR_NONE; #endif } static gpr_once g_probe_so_reuesport_once = GPR_ONCE_INIT; static int g_support_so_reuseport = false; void probe_so_reuseport_once(void) { #ifndef GPR_MANYLINUX1 int s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { /* This might be an ipv6-only environment in which case 'socket(AF_INET,..)' call would fail. Try creating IPv6 socket in that case */ s = socket(AF_INET6, SOCK_STREAM, 0); } if (s >= 0) { g_support_so_reuseport = GRPC_LOG_IF_ERROR( "check for SO_REUSEPORT", grpc_set_socket_reuse_port(s, 1)); close(s); } #endif } bool grpc_is_socket_reuse_port_supported() { gpr_once_init(&g_probe_so_reuesport_once, probe_so_reuseport_once); return g_support_so_reuseport; } /* disable nagle */ grpc_error* grpc_set_socket_low_latency(int fd, int low_latency) { int val = (low_latency != 0); int newval; socklen_t intlen = sizeof(newval); if (0 != setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val))) { return GRPC_OS_ERROR(errno, "setsockopt(TCP_NODELAY)"); } if (0 != getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &newval, &intlen)) { return GRPC_OS_ERROR(errno, "getsockopt(TCP_NODELAY)"); } if ((newval != 0) != val) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set TCP_NODELAY"); } return GRPC_ERROR_NONE; } /* set a socket using a grpc_socket_mutator */ grpc_error* grpc_set_socket_with_mutator(int fd, grpc_socket_mutator* mutator) { GPR_ASSERT(mutator); if (!grpc_socket_mutator_mutate_fd(mutator, fd)) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("grpc_socket_mutator failed."); } return GRPC_ERROR_NONE; } static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT; static int g_ipv6_loopback_available; static void probe_ipv6_once(void) { int fd = socket(AF_INET6, SOCK_STREAM, 0); g_ipv6_loopback_available = 0; if (fd < 0) { gpr_log(GPR_INFO, "Disabling AF_INET6 sockets because socket() failed."); } else { grpc_sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr.s6_addr[15] = 1; /* [::1]:0 */ if (bind(fd, reinterpret_cast<grpc_sockaddr*>(&addr), sizeof(addr)) == 0) { g_ipv6_loopback_available = 1; } else { gpr_log(GPR_INFO, "Disabling AF_INET6 sockets because ::1 is not available."); } close(fd); } } int grpc_ipv6_loopback_available(void) { gpr_once_init(&g_probe_ipv6_once, probe_ipv6_once); return g_ipv6_loopback_available; } /* This should be 0 in production, but it may be enabled for testing or debugging purposes, to simulate an environment where IPv6 sockets can't also speak IPv4. */ int grpc_forbid_dualstack_sockets_for_testing = 0; static int set_socket_dualstack(int fd) { if (!grpc_forbid_dualstack_sockets_for_testing) { const int off = 0; return 0 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof(off)); } else { /* Force an IPv6-only socket, for testing purposes. */ const int on = 1; setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)); return 0; } } static grpc_error* error_for_fd(int fd, const grpc_resolved_address* addr) { if (fd >= 0) return GRPC_ERROR_NONE; char* addr_str; grpc_sockaddr_to_string(&addr_str, addr, 0); grpc_error* err = grpc_error_set_str(GRPC_OS_ERROR(errno, "socket"), GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(addr_str)); gpr_free(addr_str); return err; } grpc_error* grpc_create_dualstack_socket( const grpc_resolved_address* resolved_addr, int type, int protocol, grpc_dualstack_mode* dsmode, int* newfd) { return grpc_create_dualstack_socket_using_factory( nullptr, resolved_addr, type, protocol, dsmode, newfd); } static int create_socket(grpc_socket_factory* factory, int domain, int type, int protocol) { return (factory != nullptr) ? grpc_socket_factory_socket(factory, domain, type, protocol) : socket(domain, type, protocol); } grpc_error* grpc_create_dualstack_socket_using_factory( grpc_socket_factory* factory, const grpc_resolved_address* resolved_addr, int type, int protocol, grpc_dualstack_mode* dsmode, int* newfd) { const grpc_sockaddr* addr = reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr); int family = addr->sa_family; if (family == AF_INET6) { if (grpc_ipv6_loopback_available()) { *newfd = create_socket(factory, family, type, protocol); } else { *newfd = -1; errno = EAFNOSUPPORT; } /* Check if we've got a valid dualstack socket. */ if (*newfd >= 0 && set_socket_dualstack(*newfd)) { *dsmode = GRPC_DSMODE_DUALSTACK; return GRPC_ERROR_NONE; } /* If this isn't an IPv4 address, then return whatever we've got. */ if (!grpc_sockaddr_is_v4mapped(resolved_addr, nullptr)) { *dsmode = GRPC_DSMODE_IPV6; return error_for_fd(*newfd, resolved_addr); } /* Fall back to AF_INET. */ if (*newfd >= 0) { close(*newfd); } family = AF_INET; } *dsmode = family == AF_INET ? GRPC_DSMODE_IPV4 : GRPC_DSMODE_NONE; *newfd = create_socket(factory, family, type, protocol); return error_for_fd(*newfd, resolved_addr); } uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); } uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); } int grpc_inet_pton(int af, const char* src, void* dst) { return inet_pton(af, src, dst); } const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) { GPR_ASSERT(size <= (socklen_t)-1); return inet_ntop(af, src, dst, static_cast<socklen_t>(size)); } #endif <|endoftext|>
<commit_before>/* * ShinyAsyncJob.cpp * * Copyright (C) 2009-19 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #define kShinyAppStarted "Shiny started; listening on URL: " #include "ShinyAsyncJob.hpp" #include "../SessionShinyViewer.hpp" #include <session/jobs/JobsApi.hpp> #include <session/SessionUrlPorts.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace shiny { ShinyAsyncJob::ShinyAsyncJob(const std::string& name, const FilePath& path, const std::string& viewerType, const std::string& runCmd): AsyncRJob(name), path_(path), viewerType_(viewerType), runCmd_(runCmd) { } void ShinyAsyncJob::start() { // set a status before we start R jobs::setJobStatus(job_, "Starting"); // create the string to send to R std::string cmd( "options(shiny.launch.browser = function(url) { " " cat(\"" kShinyAppStarted "\", url)" "}); " + runCmd_); // start the R process core::system::Options environment; async_r::AsyncRProcess::start(cmd.c_str(), environment, path_.getParent(), async_r::AsyncRProcessOptions::R_PROCESS_NO_RDATA); // echo the command we submitted to R onStdout("=> " + runCmd_ + "\n\n"); } void ShinyAsyncJob::enqueueStateEvent(const std::string& state) { json::Object dataJson; dataJson["url"] = url_ports::mapUrlPorts(url_); dataJson["path"] = module_context::createAliasedPath(path_); dataJson["state"] = state; dataJson["viewer"] = viewerType_; dataJson["options"] = shiny_viewer::SHINY_VIEWER_OPTIONS_NONE; dataJson["id"] = job_->id(); ClientEvent event(client_events::kShinyViewer, dataJson); module_context::enqueClientEvent(event); } void ShinyAsyncJob::onStdout(const std::string& output) { size_t pos = output.find(kShinyAppStarted); if (pos != std::string::npos) { // extract the URL, which is the portion of the output string following the start token url_ = output.substr(pos); // create an event to let the client know to start viewing the running application enqueueStateEvent("started"); // set the job state so the Jobs tab will show the app jobs::setJobStatus(job_, "Running"); setJobState(job_, jobs::JobState::JobRunning); // no need to echo this to the user return; } // forward output to base class so it can be emitted to the client AsyncRJob::onStdout(output); } void ShinyAsyncJob::onCompleted(int exitStatus) { if (exitStatus == 0) { setJobState(job_, jobs::JobState::JobSucceeded); onStdout("\nShiny application finished running.\n\n"); } else { if (cancelled_) { // typically the only way Shiny applications exit is by being stopped, so don't treat that // as a failure setJobState(job_, jobs::JobState::JobSucceeded); onStdout("\nShiny application successfully stopped.\n\n"); } else { setJobState(job_, jobs::JobState::JobFailed); onStdout("\nShiny application failed.\n\n"); } } AsyncRJob::onCompleted(exitStatus); } } // namespace shiny } // namespace modules } // namespace session } // namespace rstudio <commit_msg>correct offset of shiny background job URL<commit_after>/* * ShinyAsyncJob.cpp * * Copyright (C) 2009-19 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #define kShinyAppStarted "Shiny started; listening on URL: " #include "ShinyAsyncJob.hpp" #include "../SessionShinyViewer.hpp" #include <session/jobs/JobsApi.hpp> #include <session/SessionUrlPorts.hpp> #include <session/SessionModuleContext.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace shiny { ShinyAsyncJob::ShinyAsyncJob(const std::string& name, const FilePath& path, const std::string& viewerType, const std::string& runCmd): AsyncRJob(name), path_(path), viewerType_(viewerType), runCmd_(runCmd) { } void ShinyAsyncJob::start() { // set a status before we start R jobs::setJobStatus(job_, "Starting"); // create the string to send to R std::string cmd( "options(shiny.launch.browser = function(url) { " " cat(\"" kShinyAppStarted "\", url)" "}); " + runCmd_); // start the R process core::system::Options environment; async_r::AsyncRProcess::start(cmd.c_str(), environment, path_.getParent(), async_r::AsyncRProcessOptions::R_PROCESS_NO_RDATA); // echo the command we submitted to R onStdout("=> " + runCmd_ + "\n\n"); } void ShinyAsyncJob::enqueueStateEvent(const std::string& state) { json::Object dataJson; dataJson["url"] = url_ports::mapUrlPorts(url_); dataJson["path"] = module_context::createAliasedPath(path_); dataJson["state"] = state; dataJson["viewer"] = viewerType_; dataJson["options"] = shiny_viewer::SHINY_VIEWER_OPTIONS_NONE; dataJson["id"] = job_->id(); ClientEvent event(client_events::kShinyViewer, dataJson); module_context::enqueClientEvent(event); } void ShinyAsyncJob::onStdout(const std::string& output) { size_t pos = output.find(kShinyAppStarted); if (pos != std::string::npos) { // extract the URL, which is the portion of the output string following the start token url_ = output.substr(pos + std::string(kShinyAppStarted).size() + 1); // create an event to let the client know to start viewing the running application enqueueStateEvent("started"); // set the job state so the Jobs tab will show the app jobs::setJobStatus(job_, "Running"); setJobState(job_, jobs::JobState::JobRunning); // no need to echo this to the user return; } // forward output to base class so it can be emitted to the client AsyncRJob::onStdout(output); } void ShinyAsyncJob::onCompleted(int exitStatus) { if (exitStatus == 0) { setJobState(job_, jobs::JobState::JobSucceeded); onStdout("\nShiny application finished running.\n\n"); } else { if (cancelled_) { // typically the only way Shiny applications exit is by being stopped, so don't treat that // as a failure setJobState(job_, jobs::JobState::JobSucceeded); onStdout("\nShiny application successfully stopped.\n\n"); } else { setJobState(job_, jobs::JobState::JobFailed); onStdout("\nShiny application failed.\n\n"); } } AsyncRJob::onCompleted(exitStatus); } } // namespace shiny } // namespace modules } // namespace session } // namespace rstudio <|endoftext|>
<commit_before>// Licensed under the Apache License, Version 2.0. // Author: Jin Qing (http://blog.csdn.net/jq0123) #include "client_async_reader_helper.h" #include <cassert> // for assert() #include <grpc_cb/impl/client/client_async_read_handler.h> // for HandleMsg() #include "client_reader_async_read_cqtag.h" // for ClientReaderAsyncReadCqTag namespace grpc_cb { ClientAsyncReaderHelper::ClientAsyncReaderHelper( CompletionQueueSptr cq_sptr, CallSptr call_sptr, const ClientAsyncReadHandlerSptr& read_handler_sptr, const OnEnd& on_end) : cq_sptr_(cq_sptr), // XXX DEL call_sptr_(call_sptr), read_handler_sptr_(read_handler_sptr), on_end_(on_end) { assert(cq_sptr); assert(call_sptr); assert(read_handler_sptr); assert(on_end); } ClientAsyncReaderHelper::~ClientAsyncReaderHelper() {} // Setup to read each. void ClientAsyncReaderHelper::Start() { if (started_) return; started_ = true; Next(); } // Setup next async read. void ClientAsyncReaderHelper::Next() { assert(started_); if (aborted_) // Maybe writer failed. return; auto sptr = shared_from_this(); auto* tag = new ClientReaderAsyncReadCqTag(sptr); if (tag->Start()) return; delete tag; status_.SetInternalError("Failed to async read server stream."); on_end_(); } void ClientAsyncReaderHelper::OnRead(ClientReaderAsyncReadCqTag& tag) { if (aborted_) // Maybe writer failed. return; assert(status_.ok()); assert(on_end_); if (!tag.HasGotMsg()) { // End of read. Do not recv status in Reader. Do it after all reading and writing. on_end_(); return; } status_ = tag.GetResultMsg(read_handler_sptr_->GetMsg()); if (!status_.ok()) { on_end_(); return; } read_handler_sptr_->HandleMsg(); Next(); } // DEL //void ClientAsyncReaderHelper::AsyncRecvStatus() { // assert(status_sptr_->ok()); // // // input status_sptr_ to CqTag? To abort writing? // auto* tag = new ClientReaderAsyncRecvStatusCqTag(call_sptr_, on_status_); // if (tag->Start()) return; // // delete tag; // status_sptr_->SetInternalError("Failed to receive status."); // if (on_status_) on_status_(*status_sptr_); //} #if 0 template <class Response> inline void OnReadEach(const Response& msg, const ClientReaderDataSptr<Response>& data_sptr) { Status& status = data_sptr->status; assert(status.ok()); std::function<void(const Response&)>& on_msg = data_sptr->on_msg; if (on_msg) on_msg(msg); AsyncReadNext(data_sptr); // Old tag will be deleted after return in BlockingRun(). } template <class Response> inline void OnEnd(const Status& status, const ClientReaderDataSptr<Response>& data_sptr) { StatusCallback& on_status = data_sptr->on_status; if (status.ok()) { AsyncRecvStatus(data_sptr->call_sptr, data_sptr->status, on_status); return; } if (on_status) on_status(status); } #endif } // namespace grpc_cb <commit_msg>cleanup.<commit_after>// Licensed under the Apache License, Version 2.0. // Author: Jin Qing (http://blog.csdn.net/jq0123) #include "client_async_reader_helper.h" #include <cassert> // for assert() #include <grpc_cb/impl/client/client_async_read_handler.h> // for HandleMsg() #include "client_reader_async_read_cqtag.h" // for ClientReaderAsyncReadCqTag namespace grpc_cb { ClientAsyncReaderHelper::ClientAsyncReaderHelper( CompletionQueueSptr cq_sptr, CallSptr call_sptr, const ClientAsyncReadHandlerSptr& read_handler_sptr, const OnEnd& on_end) : cq_sptr_(cq_sptr), // XXX DEL call_sptr_(call_sptr), read_handler_sptr_(read_handler_sptr), on_end_(on_end) { assert(cq_sptr); assert(call_sptr); assert(read_handler_sptr); assert(on_end); } ClientAsyncReaderHelper::~ClientAsyncReaderHelper() {} // Setup to read each. void ClientAsyncReaderHelper::Start() { if (started_) return; started_ = true; Next(); } // Setup next async read. void ClientAsyncReaderHelper::Next() { assert(started_); if (aborted_) // Maybe writer failed. return; auto sptr = shared_from_this(); auto* tag = new ClientReaderAsyncReadCqTag(sptr); if (tag->Start()) return; delete tag; status_.SetInternalError("Failed to async read server stream."); on_end_(); } void ClientAsyncReaderHelper::OnRead(ClientReaderAsyncReadCqTag& tag) { if (aborted_) // Maybe writer failed. return; assert(status_.ok()); assert(on_end_); if (!tag.HasGotMsg()) { // End of read. Do not recv status in Reader. Do it after all reading and writing. on_end_(); return; } status_ = tag.GetResultMsg(read_handler_sptr_->GetMsg()); if (!status_.ok()) { on_end_(); return; } read_handler_sptr_->HandleMsg(); Next(); } } // namespace grpc_cb <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 3.0 Module * ------------------------------------------------- * * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*! * \file * \brief Multiview tests. * Tests functionality provided by the three multiview extensions. * Note that this file is formatted using external/openglcts/.clang-format */ /*--------------------------------------------------------------------*/ #include "es3fMultiviewTests.hpp" #include "deString.h" #include "deStringUtil.hpp" #include "gluContextInfo.hpp" #include "gluPixelTransfer.hpp" #include "gluShaderProgram.hpp" #include "glw.h" #include "glwEnums.hpp" #include "glwFunctions.hpp" #include "tcuRenderTarget.hpp" #include "tcuSurface.hpp" #include "tcuTestLog.hpp" #include "tcuVector.hpp" using tcu::TestLog; using tcu::Vec4; namespace deqp { namespace gles3 { namespace Functional { static const int NUM_CASE_ITERATIONS = 1; static const float UNIT_SQUARE[16] = { 1.0f, 1.0f, 0.05f, 1.0f, // Vertex 0 1.0f, -1.0f, 0.05f, 1.0f, // Vertex 1 -1.0f, 1.0f, 0.05f, 1.0f, // Vertex 2 -1.0f, -1.0f, 0.05f, 1.0f // Vertex 3 }; static const float COLOR_VALUES[] = { 1, 0, 0, 1, // Red for level 0 0, 1, 0, 1, // Green for level 1 }; class MultiviewCase : public TestCase { public: MultiviewCase(Context& context, const char* name, const char* description, int numSamples); ~MultiviewCase(); void init(); void deinit(); IterateResult iterate(); private: MultiviewCase(const MultiviewCase& other); MultiviewCase& operator=(const MultiviewCase& other); void setupFramebufferObjects(); void deleteFramebufferObjects(); glu::ShaderProgram* m_multiviewProgram; deUint32 m_multiviewFbo; deUint32 m_arrayTexture; glu::ShaderProgram* m_finalProgram; int m_caseIndex; const int m_numSamples; const int m_width; const int m_height; }; MultiviewCase::MultiviewCase(Context& context, const char* name, const char* description, int numSamples) : TestCase(context, name, description) , m_multiviewProgram(DE_NULL) , m_multiviewFbo(0) , m_arrayTexture(0) , m_finalProgram(DE_NULL) , m_caseIndex(0) , m_numSamples(numSamples) , m_width(512) , m_height(512) { } MultiviewCase::~MultiviewCase() { MultiviewCase::deinit(); } void MultiviewCase::setupFramebufferObjects() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); // First create the array texture and multiview FBO. gl.genTextures(1, &m_arrayTexture); gl.bindTexture(GL_TEXTURE_2D_ARRAY, m_arrayTexture); gl.texStorage3D(GL_TEXTURE_2D_ARRAY, 1 /* num mipmaps */, GL_RGBA8, m_width / 2, m_height, 2 /* num levels */); gl.texParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST); gl.texParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); GLU_EXPECT_NO_ERROR(gl.getError(), "Create array texture"); gl.genFramebuffers(1, &m_multiviewFbo); gl.bindFramebuffer(GL_FRAMEBUFFER, m_multiviewFbo); if (m_numSamples == 1) { gl.framebufferTextureMultiviewOVR(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_arrayTexture, 0 /* mip level */, 0 /* base view index */, 2 /* num views */); } else { gl.framebufferTextureMultisampleMultiviewOVR(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_arrayTexture, 0 /* mip level */, m_numSamples /* samples */, 0 /* base view index */, 2 /* num views */); } GLU_EXPECT_NO_ERROR(gl.getError(), "Create multiview FBO"); deUint32 fboStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (fboStatus == GL_FRAMEBUFFER_UNSUPPORTED) { throw tcu::NotSupportedError("Framebuffer unsupported", "", __FILE__, __LINE__); } else if (fboStatus != GL_FRAMEBUFFER_COMPLETE) { throw tcu::TestError("Failed to create framebuffer object", "", __FILE__, __LINE__); } } void MultiviewCase::deleteFramebufferObjects() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.deleteTextures(1, &m_arrayTexture); gl.deleteFramebuffers(1, &m_multiviewFbo); } void MultiviewCase::init() { const glu::ContextInfo& contextInfo = m_context.getContextInfo(); bool mvsupported = contextInfo.isExtensionSupported("GL_OVR_multiview"); if (!mvsupported) { TCU_THROW(NotSupportedError, "Multiview is not supported"); } if (m_numSamples > 1) { bool msaasupported = contextInfo.isExtensionSupported("GL_OVR_multiview_multisampled_render_to_texture"); if (!msaasupported) { TCU_THROW(NotSupportedError, "Implicit MSAA multiview is not supported"); } } const char* multiviewVertexShader = "#version 300 es\n" "#extension GL_OVR_multiview : enable\n" "layout(num_views=2) in;\n" "layout(location = 0) in mediump vec4 a_position;\n" "uniform mediump vec4 uColor[2];\n" "out mediump vec4 vColor;\n" "void main() {\n" " vColor = uColor[gl_ViewID_OVR];\n" " gl_Position = a_position;\n" "}\n"; const char* multiviewFragmentShader = "#version 300 es\n" "layout(location = 0) out mediump vec4 dEQP_FragColor;\n" "in mediump vec4 vColor;\n" "void main() {\n" " dEQP_FragColor = vColor;\n" "}\n"; m_multiviewProgram = new glu::ShaderProgram( m_context.getRenderContext(), glu::makeVtxFragSources(multiviewVertexShader, multiviewFragmentShader)); DE_ASSERT(m_multiviewProgram); if (!m_multiviewProgram->isOk()) { m_testCtx.getLog() << *m_multiviewProgram; TCU_FAIL("Failed to compile multiview shader"); } // Draw the first layer on the left half of the screen and the second layer // on the right half. const char* finalVertexShader = "#version 300 es\n" "layout(location = 0) in mediump vec4 a_position;\n" "out highp vec3 vTexCoord;\n" "void main() {\n" " vTexCoord.x = fract(a_position.x + 1.0);\n" " vTexCoord.y = .5 * (a_position.y + 1.0);\n" " vTexCoord.z = a_position.x;\n" " gl_Position = a_position;\n" "}\n"; const char* finalFragmentShader = "#version 300 es\n" "layout(location = 0) out mediump vec4 dEQP_FragColor;\n" "uniform sampler2DArray uArrayTexture;\n" "in highp vec3 vTexCoord;\n" "void main() {\n" " vec3 uvw = vTexCoord;\n" " uvw.z = floor(vTexCoord.z + 1.0);\n" " dEQP_FragColor = texture(uArrayTexture, uvw);\n" "}\n"; m_finalProgram = new glu::ShaderProgram(m_context.getRenderContext(), glu::makeVtxFragSources(finalVertexShader, finalFragmentShader)); DE_ASSERT(m_finalProgram); if (!m_finalProgram->isOk()) { m_testCtx.getLog() << *m_finalProgram; TCU_FAIL("Failed to compile final shader"); } m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); GLU_CHECK_MSG("Case initialization finished"); } void MultiviewCase::deinit() { deleteFramebufferObjects(); delete m_multiviewProgram; m_multiviewProgram = DE_NULL; delete m_finalProgram; m_finalProgram = DE_NULL; } MultiviewCase::IterateResult MultiviewCase::iterate() { TestLog& log = m_testCtx.getLog(); deUint32 colorUniform = glGetUniformLocation(m_multiviewProgram->getProgram(), "uColor"); std::string header = "Case iteration " + de::toString(m_caseIndex + 1) + " / " + de::toString(NUM_CASE_ITERATIONS); log << TestLog::Section(header, header); DE_ASSERT(m_multiviewProgram); // Create and bind the multiview FBO. try { setupFramebufferObjects(); } catch (tcu::NotSupportedError& e) { log << TestLog::Message << "ERROR: " << e.what() << "." << TestLog::EndMessage << TestLog::EndSection; m_testCtx.setTestResult(QP_TEST_RESULT_NOT_SUPPORTED, "Not supported"); return STOP; } catch (tcu::InternalError& e) { log << TestLog::Message << "ERROR: " << e.what() << "." << TestLog::EndMessage << TestLog::EndSection; m_testCtx.setTestResult(QP_TEST_RESULT_INTERNAL_ERROR, "Error"); return STOP; } log << TestLog::EndSection; // Draw full screen quad into the multiview framebuffer. // The quad should be instanced into both layers of the array texture. const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.bindFramebuffer(GL_FRAMEBUFFER, m_multiviewFbo); gl.viewport(0, 0, m_width / 2, m_height); gl.useProgram(m_multiviewProgram->getProgram()); gl.uniform4fv(colorUniform, 2, COLOR_VALUES); gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, &UNIT_SQUARE[0]); gl.drawArrays(GL_TRIANGLE_STRIP, 0, 4); // Sample from the array texture to draw a quad into the backbuffer. const int backbufferWidth = m_context.getRenderTarget().getWidth(); const int backbufferHeight = m_context.getRenderTarget().getHeight(); gl.bindFramebuffer(GL_FRAMEBUFFER, 0); gl.viewport(0, 0, backbufferWidth, backbufferHeight); gl.useProgram(m_finalProgram->getProgram()); gl.bindTexture(GL_TEXTURE_2D_ARRAY, m_arrayTexture); gl.drawArrays(GL_TRIANGLE_STRIP, 0, 4); // Read back the framebuffer, ensure that the left half is red and the // right half is green. tcu::Surface pixels(backbufferWidth, backbufferHeight); glu::readPixels(m_context.getRenderContext(), 0, 0, pixels.getAccess()); bool failed = false; for (int y = 0; y < backbufferHeight; y++) { for (int x = 0; x < backbufferWidth; x++) { tcu::RGBA pixel = pixels.getPixel(x, y); if (x < backbufferWidth / 2) { if (pixel.getRed() != 255 || pixel.getGreen() != 0 || pixel.getBlue() != 0) { failed = true; } } else { if (pixel.getRed() != 0 || pixel.getGreen() != 255 || pixel.getBlue() != 0) { failed = true; } } if (failed) { break; } } } deleteFramebufferObjects(); if (failed) { log << TestLog::Image("Result image", "Result image", pixels); } log << TestLog::Message << "Test result: " << (failed ? "Failed!" : "Passed!") << TestLog::EndMessage; if (failed) { m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } return (++m_caseIndex < NUM_CASE_ITERATIONS) ? CONTINUE : STOP; } MultiviewTests::MultiviewTests(Context& context) : TestCaseGroup(context, "multiview", "Multiview Tests") { } MultiviewTests::~MultiviewTests() { } void MultiviewTests::init() { addChild(new MultiviewCase(m_context, "samples_1", "Multiview test without multisampling", 1)); addChild(new MultiviewCase(m_context, "samples_2", "Multiview test with MSAAx2", 2)); addChild(new MultiviewCase(m_context, "samples_4", "Multiview test without MSAAx4", 4)); } } // namespace Functional } // namespace gles3 } // namespace deqp <commit_msg>Fix missing precision qualifiers in multiview tests<commit_after>/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 3.0 Module * ------------------------------------------------- * * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*! * \file * \brief Multiview tests. * Tests functionality provided by the three multiview extensions. * Note that this file is formatted using external/openglcts/.clang-format */ /*--------------------------------------------------------------------*/ #include "es3fMultiviewTests.hpp" #include "deString.h" #include "deStringUtil.hpp" #include "gluContextInfo.hpp" #include "gluPixelTransfer.hpp" #include "gluShaderProgram.hpp" #include "glw.h" #include "glwEnums.hpp" #include "glwFunctions.hpp" #include "tcuRenderTarget.hpp" #include "tcuSurface.hpp" #include "tcuTestLog.hpp" #include "tcuVector.hpp" using tcu::TestLog; using tcu::Vec4; namespace deqp { namespace gles3 { namespace Functional { static const int NUM_CASE_ITERATIONS = 1; static const float UNIT_SQUARE[16] = { 1.0f, 1.0f, 0.05f, 1.0f, // Vertex 0 1.0f, -1.0f, 0.05f, 1.0f, // Vertex 1 -1.0f, 1.0f, 0.05f, 1.0f, // Vertex 2 -1.0f, -1.0f, 0.05f, 1.0f // Vertex 3 }; static const float COLOR_VALUES[] = { 1, 0, 0, 1, // Red for level 0 0, 1, 0, 1, // Green for level 1 }; class MultiviewCase : public TestCase { public: MultiviewCase(Context& context, const char* name, const char* description, int numSamples); ~MultiviewCase(); void init(); void deinit(); IterateResult iterate(); private: MultiviewCase(const MultiviewCase& other); MultiviewCase& operator=(const MultiviewCase& other); void setupFramebufferObjects(); void deleteFramebufferObjects(); glu::ShaderProgram* m_multiviewProgram; deUint32 m_multiviewFbo; deUint32 m_arrayTexture; glu::ShaderProgram* m_finalProgram; int m_caseIndex; const int m_numSamples; const int m_width; const int m_height; }; MultiviewCase::MultiviewCase(Context& context, const char* name, const char* description, int numSamples) : TestCase(context, name, description) , m_multiviewProgram(DE_NULL) , m_multiviewFbo(0) , m_arrayTexture(0) , m_finalProgram(DE_NULL) , m_caseIndex(0) , m_numSamples(numSamples) , m_width(512) , m_height(512) { } MultiviewCase::~MultiviewCase() { MultiviewCase::deinit(); } void MultiviewCase::setupFramebufferObjects() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); // First create the array texture and multiview FBO. gl.genTextures(1, &m_arrayTexture); gl.bindTexture(GL_TEXTURE_2D_ARRAY, m_arrayTexture); gl.texStorage3D(GL_TEXTURE_2D_ARRAY, 1 /* num mipmaps */, GL_RGBA8, m_width / 2, m_height, 2 /* num levels */); gl.texParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST); gl.texParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); GLU_EXPECT_NO_ERROR(gl.getError(), "Create array texture"); gl.genFramebuffers(1, &m_multiviewFbo); gl.bindFramebuffer(GL_FRAMEBUFFER, m_multiviewFbo); if (m_numSamples == 1) { gl.framebufferTextureMultiviewOVR(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_arrayTexture, 0 /* mip level */, 0 /* base view index */, 2 /* num views */); } else { gl.framebufferTextureMultisampleMultiviewOVR(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_arrayTexture, 0 /* mip level */, m_numSamples /* samples */, 0 /* base view index */, 2 /* num views */); } GLU_EXPECT_NO_ERROR(gl.getError(), "Create multiview FBO"); deUint32 fboStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (fboStatus == GL_FRAMEBUFFER_UNSUPPORTED) { throw tcu::NotSupportedError("Framebuffer unsupported", "", __FILE__, __LINE__); } else if (fboStatus != GL_FRAMEBUFFER_COMPLETE) { throw tcu::TestError("Failed to create framebuffer object", "", __FILE__, __LINE__); } } void MultiviewCase::deleteFramebufferObjects() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.deleteTextures(1, &m_arrayTexture); gl.deleteFramebuffers(1, &m_multiviewFbo); } void MultiviewCase::init() { const glu::ContextInfo& contextInfo = m_context.getContextInfo(); bool mvsupported = contextInfo.isExtensionSupported("GL_OVR_multiview"); if (!mvsupported) { TCU_THROW(NotSupportedError, "Multiview is not supported"); } if (m_numSamples > 1) { bool msaasupported = contextInfo.isExtensionSupported("GL_OVR_multiview_multisampled_render_to_texture"); if (!msaasupported) { TCU_THROW(NotSupportedError, "Implicit MSAA multiview is not supported"); } } const char* multiviewVertexShader = "#version 300 es\n" "#extension GL_OVR_multiview : enable\n" "layout(num_views=2) in;\n" "layout(location = 0) in mediump vec4 a_position;\n" "uniform mediump vec4 uColor[2];\n" "out mediump vec4 vColor;\n" "void main() {\n" " vColor = uColor[gl_ViewID_OVR];\n" " gl_Position = a_position;\n" "}\n"; const char* multiviewFragmentShader = "#version 300 es\n" "layout(location = 0) out mediump vec4 dEQP_FragColor;\n" "in mediump vec4 vColor;\n" "void main() {\n" " dEQP_FragColor = vColor;\n" "}\n"; m_multiviewProgram = new glu::ShaderProgram( m_context.getRenderContext(), glu::makeVtxFragSources(multiviewVertexShader, multiviewFragmentShader)); DE_ASSERT(m_multiviewProgram); if (!m_multiviewProgram->isOk()) { m_testCtx.getLog() << *m_multiviewProgram; TCU_FAIL("Failed to compile multiview shader"); } // Draw the first layer on the left half of the screen and the second layer // on the right half. const char* finalVertexShader = "#version 300 es\n" "layout(location = 0) in mediump vec4 a_position;\n" "out highp vec3 vTexCoord;\n" "void main() {\n" " vTexCoord.x = fract(a_position.x + 1.0);\n" " vTexCoord.y = .5 * (a_position.y + 1.0);\n" " vTexCoord.z = a_position.x;\n" " gl_Position = a_position;\n" "}\n"; const char* finalFragmentShader = "#version 300 es\n" "layout(location = 0) out mediump vec4 dEQP_FragColor;\n" "uniform lowp sampler2DArray uArrayTexture;\n" "in highp vec3 vTexCoord;\n" "void main() {\n" " highp vec3 uvw = vTexCoord;\n" " uvw.z = floor(vTexCoord.z + 1.0);\n" " dEQP_FragColor = texture(uArrayTexture, uvw);\n" "}\n"; m_finalProgram = new glu::ShaderProgram(m_context.getRenderContext(), glu::makeVtxFragSources(finalVertexShader, finalFragmentShader)); DE_ASSERT(m_finalProgram); if (!m_finalProgram->isOk()) { m_testCtx.getLog() << *m_finalProgram; TCU_FAIL("Failed to compile final shader"); } m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); GLU_CHECK_MSG("Case initialization finished"); } void MultiviewCase::deinit() { deleteFramebufferObjects(); delete m_multiviewProgram; m_multiviewProgram = DE_NULL; delete m_finalProgram; m_finalProgram = DE_NULL; } MultiviewCase::IterateResult MultiviewCase::iterate() { TestLog& log = m_testCtx.getLog(); deUint32 colorUniform = glGetUniformLocation(m_multiviewProgram->getProgram(), "uColor"); std::string header = "Case iteration " + de::toString(m_caseIndex + 1) + " / " + de::toString(NUM_CASE_ITERATIONS); log << TestLog::Section(header, header); DE_ASSERT(m_multiviewProgram); // Create and bind the multiview FBO. try { setupFramebufferObjects(); } catch (tcu::NotSupportedError& e) { log << TestLog::Message << "ERROR: " << e.what() << "." << TestLog::EndMessage << TestLog::EndSection; m_testCtx.setTestResult(QP_TEST_RESULT_NOT_SUPPORTED, "Not supported"); return STOP; } catch (tcu::InternalError& e) { log << TestLog::Message << "ERROR: " << e.what() << "." << TestLog::EndMessage << TestLog::EndSection; m_testCtx.setTestResult(QP_TEST_RESULT_INTERNAL_ERROR, "Error"); return STOP; } log << TestLog::EndSection; // Draw full screen quad into the multiview framebuffer. // The quad should be instanced into both layers of the array texture. const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.bindFramebuffer(GL_FRAMEBUFFER, m_multiviewFbo); gl.viewport(0, 0, m_width / 2, m_height); gl.useProgram(m_multiviewProgram->getProgram()); gl.uniform4fv(colorUniform, 2, COLOR_VALUES); gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, &UNIT_SQUARE[0]); gl.drawArrays(GL_TRIANGLE_STRIP, 0, 4); // Sample from the array texture to draw a quad into the backbuffer. const int backbufferWidth = m_context.getRenderTarget().getWidth(); const int backbufferHeight = m_context.getRenderTarget().getHeight(); gl.bindFramebuffer(GL_FRAMEBUFFER, 0); gl.viewport(0, 0, backbufferWidth, backbufferHeight); gl.useProgram(m_finalProgram->getProgram()); gl.bindTexture(GL_TEXTURE_2D_ARRAY, m_arrayTexture); gl.drawArrays(GL_TRIANGLE_STRIP, 0, 4); // Read back the framebuffer, ensure that the left half is red and the // right half is green. tcu::Surface pixels(backbufferWidth, backbufferHeight); glu::readPixels(m_context.getRenderContext(), 0, 0, pixels.getAccess()); bool failed = false; for (int y = 0; y < backbufferHeight; y++) { for (int x = 0; x < backbufferWidth; x++) { tcu::RGBA pixel = pixels.getPixel(x, y); if (x < backbufferWidth / 2) { if (pixel.getRed() != 255 || pixel.getGreen() != 0 || pixel.getBlue() != 0) { failed = true; } } else { if (pixel.getRed() != 0 || pixel.getGreen() != 255 || pixel.getBlue() != 0) { failed = true; } } if (failed) { break; } } } deleteFramebufferObjects(); if (failed) { log << TestLog::Image("Result image", "Result image", pixels); } log << TestLog::Message << "Test result: " << (failed ? "Failed!" : "Passed!") << TestLog::EndMessage; if (failed) { m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } return (++m_caseIndex < NUM_CASE_ITERATIONS) ? CONTINUE : STOP; } MultiviewTests::MultiviewTests(Context& context) : TestCaseGroup(context, "multiview", "Multiview Tests") { } MultiviewTests::~MultiviewTests() { } void MultiviewTests::init() { addChild(new MultiviewCase(m_context, "samples_1", "Multiview test without multisampling", 1)); addChild(new MultiviewCase(m_context, "samples_2", "Multiview test with MSAAx2", 2)); addChild(new MultiviewCase(m_context, "samples_4", "Multiview test without MSAAx4", 4)); } } // namespace Functional } // namespace gles3 } // namespace deqp <|endoftext|>
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <gadget/gadgetConfig.h> #include <gadget/Util/Debug.h> #include <cluster/Packets/DataPacket.h> #include <cluster/Plugins/RemoteInputManager/RemoteInputManager.h> #include <cluster/ClusterManager.h> #include <cluster/ClusterNetwork/ClusterNode.h> #include <cluster/Plugins/ApplicationDataManager/ApplicationDataManager.h> #include <cluster/Plugins/ApplicationDataManager/ApplicationData.h> //#include <gadget/RemoteInputManager/VirtualDevice.h> #include <gadget/Type/Input.h> #include <vpr/System.h> #include <vpr/Util/Assert.h> namespace cluster { DataPacket::DataPacket(Header* packet_head, vpr::SocketStream* stream) { recv(packet_head,stream); parse(); } DataPacket::DataPacket() { // Given the input, create the packet and then serialize the packet(which includes the header) // - Set member variables // - Create the correct packet header // - Serialize the packet //vprASSERT(mDeviceData == NULL && "Device data vector can't equal NULL"); // Header vars (Create Header) mHeader = new Header(Header::RIM_PACKET, Header::RIM_DATA_PACKET, Header::RIM_PACKET_HEAD_SIZE + 16 /* GUID */ + 0 /*mDeviceData->size()*/, 0/* Frame ID*/); serialize(); } vpr::ReturnStatus DataPacket::send(vpr::SocketStream* socket) { vprASSERT("YOU SHOULD NOT BE USING THIS SEND FUNCTION"); return(vpr::ReturnStatus::Fail); } void DataPacket::send(vpr::SocketStream* socket, vpr::GUID device_id, std::vector<vpr::Uint8>* device_data) { // - Send header data // - Send Device ID // - Send Device Data // - Send packet data vprASSERT(socket != NULL && "SocketStream can't be NULL"); vprASSERT(device_data != NULL && "Device Data can't be NULL"); vpr::Uint32 bytes_written; mHeader->setPacketLength(Header::RIM_PACKET_HEAD_SIZE + 16 /* GUID*/ + device_data->size()); mHeader->serializeHeader(); mHeader->send(socket); // Send the device ID //////////////////////////////// mId = device_id; vpr::BufferObjectWriter temp_writer; mId.writeObject((vpr::ObjectWriter*)&temp_writer); ///// // std::vector<vpr::Uint8> val(2); // vpr::Uint16 nw_val = vpr::System::Htons(device_id); // val[0] = ((vpr::Uint8*)&nw_val)[0]; // val[1] = ((vpr::Uint8*)&nw_val)[1]; ///////////////////////////////// //socket->send(val,2,bytes_written); socket->send(*temp_writer.getData(),16,bytes_written); socket->send(*device_data,mHeader->getPacketLength()-Header::RIM_PACKET_HEAD_SIZE-16,bytes_written); } void DataPacket::serialize() { // Create the header information mHeader->serializeHeader(); } void DataPacket::parse() { //mVirtualId = mPacketReader->readUint16(); mId.readObject(mPacketReader); // WE MUST KEEP IN MIND THAT mData is not simply the device data but the device data with the // Virtual Device Data ID at the beginning //std::cout << "Size before shrink: " << mPacketReader->mData->size() << std::endl; //std::vector<vpr::Uint8>::iterator i; //i = mPacketReader->mData->begin(); //i = mPacketReader->mData->erase(i); //i = mPacketReader->mData->begin(); //i = mPacketReader->mData->erase(i); //std::cout << "Size after shrink: " << mPacketReader->mData->size() << std::endl; } bool DataPacket::action(ClusterNode* node) { if (node == NULL) { return false; } gadget::Input* virtual_device = RemoteInputManager::instance()->getVirtualDevice(mId); if (virtual_device != NULL) { mPacketReader->setAttrib("rim.timestamp.delta", node->getDelta()); virtual_device->readObject(mPacketReader); return true; } ApplicationData* user_data = ApplicationDataManager::instance()->getRemoteApplicationData(mId); if (user_data != NULL) { user_data->readObject(mPacketReader); return true; } return false; } void DataPacket::printData(int debug_level) { vprDEBUG_BEGIN(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrYELLOW,"==== Device Data Packet ====\n") << vprDEBUG_FLUSH; Packet::printData(vprDBG_VERB_LVL); vprDEBUG(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrYELLOW, "Virtual ID: ") << mId.toString() << std::endl << vprDEBUG_FLUSH; vprDEBUG_END(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrYELLOW,"============================\n") << vprDEBUG_FLUSH; /* Packet::printData(); vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << clrOutBOLD(clrCYAN,"\n==== Device Request Packet Data ====") //<< "\nVirtual(Remote) ID: " << mVirtualId //<< "\nDevice Name: " << mDeviceName //<< "\nData Size: " << mDeviceData->size() << std::endl << vprDEBUG_FLUSH; */ } } // end namespace gadget <commit_msg>Silence a MIPSpro warning.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2003 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <gadget/gadgetConfig.h> #include <gadget/Util/Debug.h> #include <cluster/Packets/DataPacket.h> #include <cluster/Plugins/RemoteInputManager/RemoteInputManager.h> #include <cluster/ClusterManager.h> #include <cluster/ClusterNetwork/ClusterNode.h> #include <cluster/Plugins/ApplicationDataManager/ApplicationDataManager.h> #include <cluster/Plugins/ApplicationDataManager/ApplicationData.h> //#include <gadget/RemoteInputManager/VirtualDevice.h> #include <gadget/Type/Input.h> #include <vpr/System.h> #include <vpr/Util/Assert.h> namespace cluster { DataPacket::DataPacket(Header* packet_head, vpr::SocketStream* stream) { recv(packet_head,stream); parse(); } DataPacket::DataPacket() { // Given the input, create the packet and then serialize the packet(which includes the header) // - Set member variables // - Create the correct packet header // - Serialize the packet //vprASSERT(mDeviceData == NULL && "Device data vector can't equal NULL"); // Header vars (Create Header) mHeader = new Header(Header::RIM_PACKET, Header::RIM_DATA_PACKET, Header::RIM_PACKET_HEAD_SIZE + 16 /* GUID */ + 0 /*mDeviceData->size()*/, 0/* Frame ID*/); serialize(); } vpr::ReturnStatus DataPacket::send(vpr::SocketStream* socket) { vprASSERT(false && "YOU SHOULD NOT BE USING THIS SEND FUNCTION"); return(vpr::ReturnStatus::Fail); } void DataPacket::send(vpr::SocketStream* socket, vpr::GUID device_id, std::vector<vpr::Uint8>* device_data) { // - Send header data // - Send Device ID // - Send Device Data // - Send packet data vprASSERT(socket != NULL && "SocketStream can't be NULL"); vprASSERT(device_data != NULL && "Device Data can't be NULL"); vpr::Uint32 bytes_written; mHeader->setPacketLength(Header::RIM_PACKET_HEAD_SIZE + 16 /* GUID*/ + device_data->size()); mHeader->serializeHeader(); mHeader->send(socket); // Send the device ID //////////////////////////////// mId = device_id; vpr::BufferObjectWriter temp_writer; mId.writeObject((vpr::ObjectWriter*)&temp_writer); ///// // std::vector<vpr::Uint8> val(2); // vpr::Uint16 nw_val = vpr::System::Htons(device_id); // val[0] = ((vpr::Uint8*)&nw_val)[0]; // val[1] = ((vpr::Uint8*)&nw_val)[1]; ///////////////////////////////// //socket->send(val,2,bytes_written); socket->send(*temp_writer.getData(),16,bytes_written); socket->send(*device_data,mHeader->getPacketLength()-Header::RIM_PACKET_HEAD_SIZE-16,bytes_written); } void DataPacket::serialize() { // Create the header information mHeader->serializeHeader(); } void DataPacket::parse() { //mVirtualId = mPacketReader->readUint16(); mId.readObject(mPacketReader); // WE MUST KEEP IN MIND THAT mData is not simply the device data but the device data with the // Virtual Device Data ID at the beginning //std::cout << "Size before shrink: " << mPacketReader->mData->size() << std::endl; //std::vector<vpr::Uint8>::iterator i; //i = mPacketReader->mData->begin(); //i = mPacketReader->mData->erase(i); //i = mPacketReader->mData->begin(); //i = mPacketReader->mData->erase(i); //std::cout << "Size after shrink: " << mPacketReader->mData->size() << std::endl; } bool DataPacket::action(ClusterNode* node) { if (node == NULL) { return false; } gadget::Input* virtual_device = RemoteInputManager::instance()->getVirtualDevice(mId); if (virtual_device != NULL) { mPacketReader->setAttrib("rim.timestamp.delta", node->getDelta()); virtual_device->readObject(mPacketReader); return true; } ApplicationData* user_data = ApplicationDataManager::instance()->getRemoteApplicationData(mId); if (user_data != NULL) { user_data->readObject(mPacketReader); return true; } return false; } void DataPacket::printData(int debug_level) { vprDEBUG_BEGIN(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrYELLOW,"==== Device Data Packet ====\n") << vprDEBUG_FLUSH; Packet::printData(vprDBG_VERB_LVL); vprDEBUG(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrYELLOW, "Virtual ID: ") << mId.toString() << std::endl << vprDEBUG_FLUSH; vprDEBUG_END(gadgetDBG_RIM,vprDBG_VERB_LVL) << clrOutBOLD(clrYELLOW,"============================\n") << vprDEBUG_FLUSH; /* Packet::printData(); vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << clrOutBOLD(clrCYAN,"\n==== Device Request Packet Data ====") //<< "\nVirtual(Remote) ID: " << mVirtualId //<< "\nDevice Name: " << mDeviceName //<< "\nData Size: " << mDeviceData->size() << std::endl << vprDEBUG_FLUSH; */ } } // end namespace gadget <|endoftext|>
<commit_before>/***************************************************************************** * Controller_widget.cpp : Controller Widget for the controllers **************************************************************************** * Copyright (C) 2006-2008 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <jb@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _CONTROLLER_WIDGET_H_ #define _CONTROLLER_WIDGET_H_ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "qt4.hpp" #include <QWidget> #include <QFrame> #include <QToolButton> #define I_PLAY_TOOLTIP N_("Play\nIf the playlist is empty, open a media") class QLabel; class QSpinBox; class QAbstractSlider; /** * SPECIAL Widgets that are a bit more than just a ToolButton * and have an icon/behaviour that changes depending on the context: * - playButton * - A->B Button * - Teletext group buttons * - Sound Widget group **/ class PlayButton : public QToolButton { Q_OBJECT private slots: void updateButton( bool ); }; class AtoB_Button : public QToolButton { Q_OBJECT private slots: void setIcons( bool, bool ); }; #define VOLUME_MAX 200 class VolumeClickHandler; class SoundWidget : public QWidget { Q_OBJECT public: SoundWidget( QWidget *parent, intf_thread_t *_p_i, bool, bool b_special = false ); private: intf_thread_t *p_intf; QLabel *volMuteLabel; QAbstractSlider *volumeSlider; bool b_my_volume; QMenu *volumeMenu; virtual bool eventFilter( QObject *obj, QEvent *e ); protected slots: void updateVolume( int ); void updateVolume( void ); void showVolumeMenu( QPoint pos ); }; #endif <commit_msg>Qt: remove reference to a dead class.<commit_after>/***************************************************************************** * Controller_widget.cpp : Controller Widget for the controllers **************************************************************************** * Copyright (C) 2006-2008 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <jb@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _CONTROLLER_WIDGET_H_ #define _CONTROLLER_WIDGET_H_ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "qt4.hpp" #include <QWidget> #include <QFrame> #include <QToolButton> #define I_PLAY_TOOLTIP N_("Play\nIf the playlist is empty, open a media") class QLabel; class QSpinBox; class QAbstractSlider; /** * SPECIAL Widgets that are a bit more than just a ToolButton * and have an icon/behaviour that changes depending on the context: * - playButton * - A->B Button * - Teletext group buttons * - Sound Widget group **/ class PlayButton : public QToolButton { Q_OBJECT private slots: void updateButton( bool ); }; class AtoB_Button : public QToolButton { Q_OBJECT private slots: void setIcons( bool, bool ); }; #define VOLUME_MAX 200 class SoundWidget : public QWidget { Q_OBJECT public: SoundWidget( QWidget *parent, intf_thread_t *_p_i, bool, bool b_special = false ); private: intf_thread_t *p_intf; QLabel *volMuteLabel; QAbstractSlider *volumeSlider; bool b_my_volume; QMenu *volumeMenu; virtual bool eventFilter( QObject *obj, QEvent *e ); protected slots: void updateVolume( int ); void updateVolume( void ); void showVolumeMenu( QPoint pos ); }; #endif <|endoftext|>
<commit_before>#include "OneDEnergyWallHeating.h" #include "EquationOfState.h" template<> InputParameters validParams<OneDEnergyWallHeating>() { InputParameters params = validParams<Kernel>(); params.addRequiredCoupledVar("rho", "density"); // _rho_var_number params.addRequiredCoupledVar("rhou", "momentum"); // _rho_var_number // params.addRequiredCoupledVar("u", ""); // params.addRequiredCoupledVar("pressure", ""); params.addRequiredCoupledVar("temperature", ""); // Required parameters //params.addRequiredParam<Real>("Hw", "Convective heat transfer coefficient"); params.addRequiredParam<Real>("aw", "heat transfer area density, m^2 / m^3"); params.addRequiredParam<Real>("Tw", "Wall temperature, K"); params.addRequiredParam<UserObjectName>("eos", "The name of equation of state object to use."); return params; } OneDEnergyWallHeating::OneDEnergyWallHeating(const std::string & name, InputParameters parameters) : Kernel(name, parameters), _rho(coupledValue("rho")), _rhou(coupledValue("rhou")), //_u_vel(coupledValue("u")), //_pressure(coupledValue("pressure")), _temperature(coupledValue("temperature")), _rho_var_number(coupled("rho")), //_Hw(getParam<Real>("Hw")), _aw(getParam<Real>("aw")), _Tw(getParam<Real>("Tw")), _HTC(getMaterialProperty<Real>("HeatTransferCoefficient")), _eos(getUserObject<EquationOfState>("eos")) {} Real OneDEnergyWallHeating::computeQpResidual() { /* //time ramp up Real t1 = 0.55; Real t2 = 1.0; Real _Hw_time = 0.; if(_t < t1) { _Hw_time = 0.; } else if(_t < t2) { _Hw_time = _Hw * (_t - t1) / (t2 - t1); } else { _Hw_time = _Hw; } */ // heat transfer term: Hw * aw * (T-Tw) * psi //return _Hw * _aw * (_temperature[_qp]-_Tw) * _test[_i][_qp]; return _HTC[_qp]* _aw * (_temperature[_qp]-_Tw) * _test[_i][_qp]; } Real OneDEnergyWallHeating::computeQpJacobian() { // Derivatives wrt rho*E // d(Res)/d(rhoE) = Hw * aw * (dT/drhoE) * phi_j * test return _HTC[_qp]* _aw * _eos.dT_drhoE(_rho[_qp], _rhou[_qp], _u[_qp]) * _phi[_j][_qp] * _test[_i][_qp]; } Real OneDEnergyWallHeating::computeQpOffDiagJacobian(unsigned int jvar) { if (jvar == _rho_var_number) { // Derivatives wrt rho*E // TODO: Add dT_drho, dT_drhou, dT_drhoE to EOS object return 0.; } else return 0.; } <commit_msg>Working on Jacobians for SUPG terms.<commit_after>#include "OneDEnergyWallHeating.h" #include "EquationOfState.h" template<> InputParameters validParams<OneDEnergyWallHeating>() { InputParameters params = validParams<Kernel>(); params.addRequiredCoupledVar("rho", "density"); // _rho_var_number params.addRequiredCoupledVar("rhou", "momentum"); // _rho_var_number // params.addRequiredCoupledVar("u", ""); // params.addRequiredCoupledVar("pressure", ""); params.addRequiredCoupledVar("temperature", ""); // Required parameters //params.addRequiredParam<Real>("Hw", "Convective heat transfer coefficient"); params.addRequiredParam<Real>("aw", "heat transfer area density, m^2 / m^3"); params.addRequiredParam<Real>("Tw", "Wall temperature, K"); params.addRequiredParam<UserObjectName>("eos", "The name of equation of state object to use."); return params; } OneDEnergyWallHeating::OneDEnergyWallHeating(const std::string & name, InputParameters parameters) : Kernel(name, parameters), _rho(coupledValue("rho")), _rhou(coupledValue("rhou")), //_u_vel(coupledValue("u")), //_pressure(coupledValue("pressure")), _temperature(coupledValue("temperature")), _rho_var_number(coupled("rho")), //_Hw(getParam<Real>("Hw")), _aw(getParam<Real>("aw")), _Tw(getParam<Real>("Tw")), _HTC(getMaterialProperty<Real>("HeatTransferCoefficient")), _eos(getUserObject<EquationOfState>("eos")) {} Real OneDEnergyWallHeating::computeQpResidual() { // heat transfer term: Hw * aw * (T-Tw) * psi //return _Hw * _aw * (_temperature[_qp]-_Tw) * _test[_i][_qp]; return _HTC[_qp]* _aw * (_temperature[_qp]-_Tw) * _test[_i][_qp]; } Real OneDEnergyWallHeating::computeQpJacobian() { // Derivatives wrt rho*E // d(Res)/d(rhoE) = Hw * aw * (dT/drhoE) * phi_j * test return _HTC[_qp]* _aw * _eos.dT_drhoE(_rho[_qp], _rhou[_qp], _u[_qp]) * _phi[_j][_qp] * _test[_i][_qp]; } Real OneDEnergyWallHeating::computeQpOffDiagJacobian(unsigned int jvar) { if (jvar == _rho_var_number) { // Derivatives wrt rho*E // TODO: Add dT_drho, dT_drhou, dT_drhoE to EOS object return 0.; } else return 0.; } <|endoftext|>
<commit_before>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2005 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <sstream> #include <vector> #if defined(VPR_OS_Windows) # include <winsock2.h> # include <ws2tcpip.h> #else # include <sys/types.h> # include <sys/socket.h> # if defined(HAVE_GETIFADDRS) # include <ifaddrs.h> # else # include <sys/ioctl.h> # include <net/if.h> # endif # include <netinet/in.h> # include <arpa/inet.h> # include <errno.h> #endif #include <vpr/Util/Exception.h> #include <vpr/IO/Socket/InetAddr.h> namespace vpr { /** * Retrieves all the IPv4 addresses associated with the local machine, * including the loopback address (127.0.0.1) if so indicated. This is an * internal function that is not part of the public VPR interface. * * This function exists in this form primarily because NSPR does not provide * any wrapper that offerrs this functionality. Since the WinSock2 use of * WSAIoctl() so closely mimics the use of ioctl(2) to get the interface * addresses, much code duplication would be required between vpr::InetAddrBSD * and vpr::InetAddrNSPR. Instead of duplicating complicated code, those * classes call into this function. * * @post \p hostAddrs contains vpr::InetAddr objetcs holding all the local * IPv4 addresses for the local machine. * * @param hostAddrs Storage for the discovered local IPv4 addresses. The * vector is cleared before the addresses are added, so * any objects currently in the vector are lost. * @param withLoopback A flag indicating whether to include the loopback * address (127.0.0.1) in \p hostAddrs. * * @note This method currently supports only IPv4. * * @throw vpr::Exception is thrown if a fatal error occurs that prevents * discovery of the local machine's addresses. */ void getIfAddrs(std::vector<vpr::InetAddr>& hostAddrs, const bool withLoopback) { const in_addr_t loop = ntohl(INADDR_LOOPBACK); // Make sure hostAddrs is empty so that we can use push_back() below. hostAddrs.clear(); #if defined(HAVE_GETIFADDRS) ifaddrs* addrs(NULL); int result = getifaddrs(&addrs); if ( result < 0 ) { std::ostringstream msg_stream; msg_stream << "Failed to query interface addresses: " << strerror(errno); throw vpr::Exception(msg_stream.str(), VPR_LOCATION); } else { for ( ifaddrs* a = addrs; a != NULL; a = a->ifa_next ) { sockaddr_in* addr_in = (sockaddr_in*) a->ifa_addr; // We only handle IPv4 addresses. if ( addr_in->sin_family != AF_INET ) { continue; } // If we have the loopback address and withLoopback is false, then we // skip this address. if ( addr_in->sin_addr.s_addr == loop && ! withLoopback ) { continue; } char netaddr[18]; const char* temp_addr = inet_ntop(addr_in->sin_family, &addr_in->sin_addr, netaddr, sizeof(netaddr)); if ( NULL != temp_addr ) { vpr::InetAddr vpr_addr; vpr_addr.setAddress(netaddr, 0); hostAddrs.push_back(vpr_addr); } } } freeifaddrs(addrs); #else /* ! HAVE_GETIFADDRS */ // While the implementation of this method is long and rather complex // looking, the idea is simple: // // 1. Create an IPv4 socket. // 2. Use ioctl(2) or WSAIoctl() on the socket handle to query all the // network interfaces. // 3. Iterate over the returned interface request objects and extract // the valid IPv4 addresses. // 4. Store each IPv4 address in a new vpr::InetAddr object. #if defined(VPR_OS_Windows) typedef INTERFACE_INFO ifreq_t; SOCKET sock = WSASocket(AF_INET, SOCK_DGRAM, 0); // Socket creation failed, so we cannot proceed. if ( sock == SOCKET_ERROR ) { std::ostringstream msg_stream; msg_stream << "Socket creation failed (error code " << WSAGetLastError() << ")"; throw vpr::Exception(msg_stream.str(), VPR_LOCATION); } #else typedef ifreq ifreq_t; int sock = socket(AF_INET, SOCK_DGRAM, 0); // Socket creation failed, so we cannot proceed. if ( sock < 0 ) { std::ostringstream msg_stream; msg_stream << "Socket creation failed: " << strerror(errno); throw vpr::Exception(msg_stream.str(), VPR_LOCATION); } #endif // Initial guess on the size of the buffer that will be returned by // ioctl(2) or WSAIoctl(). size_t len = sizeof(ifreq_t) * 32; size_t lastlen(0); unsigned long bytes_returned(0); #if ! defined(VPR_OS_Windows) ifconf ifc; #endif ifreq_t* if_list(NULL); // Call ioctl(2) or WSAIoctl() iteratively to ensure that we get back all // the interface addresses. This is based on code from NSPR. for ( ; ; ) { // Allocate storage for the data returned by ioctl(2) or WSAIoctl(). if_list = new ifreq_t[len]; if ( NULL == if_list ) { #if defined(VPR_OS_Windows) closesocket(sock); #else close(sock); #endif throw vpr::Exception("Out of memory", VPR_LOCATION); } #if defined(VPR_OS_Windows) int result = WSAIoctl(sock, SIO_GET_INTERFACE_LIST, 0, 0, &if_list, len, &bytes_returned, 0, 0); #else ifc.ifc_len = len; ifc.ifc_req = if_list; int result = ioctl(sock, SIOCGIFCONF, &ifc); bytes_returned = ifc.ifc_len; #endif // Ask the kernel for all the network interfaces to which sock could be // bound. #if defined(VPR_OS_Windows) if ( result == SOCKET_ERROR ) #else if ( result < 0 ) #endif { #if defined(VPR_OS_Windows) const int inval_err(WSAEINVAL); const int err_code(WSAGetLastError()); #else const int inval_err(EINVAL); const int err_code(errno); #endif // If ioctl(2) or WSAIoctl() failed for reasons other than our buffer // being too small, then we cannot continue. We need to clean up after // ourselves before we throw the exception explaining what went // wrong. if ( err_code != inval_err || lastlen != 0 ) { #if defined(VPR_OS_Windows) closesocket(sock); #else close(sock); #endif delete[] if_list; std::ostringstream msg_stream; #if defined(VPR_OS_Windows) msg_stream << "Bad ioctl (error code " << err_code << ")"; #else msg_stream << "Bad ioctl: " << strerror(errno); #endif throw vpr::Exception(msg_stream.str(), VPR_LOCATION); } } // If ioctl(2) or WSAIoctl() returned successfully, check the size of // the buffer that it returned. else { // If lastlen is the same as the size of the buffer returned by // ioctl(2) or WSAIoctl(), then we are done. If the size of the buffer // returned by ioctl(2) or WASIoctl() is no larger than what we // allocated, then we are done. if ( bytes_returned == lastlen || bytes_returned <= len ) { break; } // Otherwise, we continue iterating. else { lastlen = bytes_returned; } } // Increment the size of the returned buffer. len += 10 * sizeof(ifreq_t); delete[] if_list; } // We are done with the socket. #if defined(VPR_OS_Windows) closesocket(sock); #else close(sock); #endif // Figure out how many interfaces were returned. const size_t num = bytes_returned / sizeof(ifreq_t); // Iterate over the returned ifreq objects and pull out the valid IPv4 // addresses. for ( size_t i = 0; i < num; ++i ) { #if defined(VPR_OS_Windows) sockaddr_in* addr = (sockaddr_in*) &if_list[i].iiAddress; #else sockaddr_in* addr = (sockaddr_in*) &ifc.ifc_req[i].ifr_addr; #endif // Skip addresses that are not IPv4. // XXX: We should support IPv6 at some point. if ( addr->sin_family != AF_INET ) { continue; } // If we have the loopback address and withLoopback is false, then we // skip this address. if ( addr->sin_addr.s_addr == loop && ! withLoopback ) { continue; } char netaddr[18]; const char* temp_addr = inet_ntop(addr->sin_family, &addr->sin_addr, netaddr, sizeof(netaddr)); if ( NULL != temp_addr ) { vpr::InetAddr vpr_addr; vpr_addr.setAddress(netaddr, 0); hostAddrs.push_back(vpr_addr); } } // All done. delete[] if_list; #endif /* defined(HAVE_GETIFADDRS) */ } } <commit_msg>Fixed Windows compile errors.<commit_after>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2005 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * 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; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <sstream> #include <vector> #if defined(VPR_OS_Windows) # include <winsock2.h> # include <ws2tcpip.h> #else # include <sys/types.h> # include <sys/socket.h> # if defined(HAVE_GETIFADDRS) # include <ifaddrs.h> # else # include <sys/ioctl.h> # include <net/if.h> # endif # include <netinet/in.h> # include <arpa/inet.h> # include <errno.h> #endif #include <vpr/Util/Exception.h> #include <vpr/IO/Socket/InetAddr.h> namespace vpr { /** * Retrieves all the IPv4 addresses associated with the local machine, * including the loopback address (127.0.0.1) if so indicated. This is an * internal function that is not part of the public VPR interface. * * This function exists in this form primarily because NSPR does not provide * any wrapper that offerrs this functionality. Since the WinSock2 use of * WSAIoctl() so closely mimics the use of ioctl(2) to get the interface * addresses, much code duplication would be required between vpr::InetAddrBSD * and vpr::InetAddrNSPR. Instead of duplicating complicated code, those * classes call into this function. * * @post \p hostAddrs contains vpr::InetAddr objetcs holding all the local * IPv4 addresses for the local machine. * * @param hostAddrs Storage for the discovered local IPv4 addresses. The * vector is cleared before the addresses are added, so * any objects currently in the vector are lost. * @param withLoopback A flag indicating whether to include the loopback * address (127.0.0.1) in \p hostAddrs. * * @note This method currently supports only IPv4. * * @throw vpr::Exception is thrown if a fatal error occurs that prevents * discovery of the local machine's addresses. */ void getIfAddrs(std::vector<vpr::InetAddr>& hostAddrs, const bool withLoopback) { #if defined(VPR_OS_Windows) const unsigned long loop = ntohl(INADDR_LOOPBACK); #else const in_addr_t loop = ntohl(INADDR_LOOPBACK); #endif // Make sure hostAddrs is empty so that we can use push_back() below. hostAddrs.clear(); #if defined(HAVE_GETIFADDRS) ifaddrs* addrs(NULL); int result = getifaddrs(&addrs); if ( result < 0 ) { std::ostringstream msg_stream; msg_stream << "Failed to query interface addresses: " << strerror(errno); throw vpr::Exception(msg_stream.str(), VPR_LOCATION); } else { for ( ifaddrs* a = addrs; a != NULL; a = a->ifa_next ) { sockaddr_in* addr_in = (sockaddr_in*) a->ifa_addr; // We only handle IPv4 addresses. if ( addr_in->sin_family != AF_INET ) { continue; } // If we have the loopback address and withLoopback is false, then we // skip this address. if ( addr_in->sin_addr.s_addr == loop && ! withLoopback ) { continue; } char netaddr[18]; const char* temp_addr = inet_ntop(addr_in->sin_family, &addr_in->sin_addr, netaddr, sizeof(netaddr)); if ( NULL != temp_addr ) { vpr::InetAddr vpr_addr; vpr_addr.setAddress(netaddr, 0); hostAddrs.push_back(vpr_addr); } } } freeifaddrs(addrs); #else /* ! HAVE_GETIFADDRS */ // While the implementation of this method is long and rather complex // looking, the idea is simple: // // 1. Create an IPv4 socket. // 2. Use ioctl(2) or WSAIoctl() on the socket handle to query all the // network interfaces. // 3. Iterate over the returned interface request objects and extract // the valid IPv4 addresses. // 4. Store each IPv4 address in a new vpr::InetAddr object. #if defined(VPR_OS_Windows) typedef INTERFACE_INFO ifreq_t; SOCKET sock = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0); // Socket creation failed, so we cannot proceed. if ( sock == SOCKET_ERROR ) { std::ostringstream msg_stream; msg_stream << "Socket creation failed (error code " << WSAGetLastError() << ")"; throw vpr::Exception(msg_stream.str(), VPR_LOCATION); } #else typedef ifreq ifreq_t; int sock = socket(AF_INET, SOCK_DGRAM, 0); // Socket creation failed, so we cannot proceed. if ( sock < 0 ) { std::ostringstream msg_stream; msg_stream << "Socket creation failed: " << strerror(errno); throw vpr::Exception(msg_stream.str(), VPR_LOCATION); } #endif // Initial guess on the size of the buffer that will be returned by // ioctl(2) or WSAIoctl(). size_t len = sizeof(ifreq_t) * 32; size_t lastlen(0); unsigned long bytes_returned(0); #if ! defined(VPR_OS_Windows) ifconf ifc; #endif ifreq_t* if_list(NULL); // Call ioctl(2) or WSAIoctl() iteratively to ensure that we get back all // the interface addresses. This is based on code from NSPR. for ( ; ; ) { // Allocate storage for the data returned by ioctl(2) or WSAIoctl(). if_list = new ifreq_t[len]; if ( NULL == if_list ) { #if defined(VPR_OS_Windows) closesocket(sock); #else close(sock); #endif throw vpr::Exception("Out of memory", VPR_LOCATION); } #if defined(VPR_OS_Windows) int result = WSAIoctl(sock, SIO_GET_INTERFACE_LIST, 0, 0, &if_list, len, &bytes_returned, 0, 0); #else ifc.ifc_len = len; ifc.ifc_req = if_list; int result = ioctl(sock, SIOCGIFCONF, &ifc); bytes_returned = ifc.ifc_len; #endif // Ask the kernel for all the network interfaces to which sock could be // bound. #if defined(VPR_OS_Windows) if ( result == SOCKET_ERROR ) #else if ( result < 0 ) #endif { #if defined(VPR_OS_Windows) const int inval_err(WSAEINVAL); const int err_code(WSAGetLastError()); #else const int inval_err(EINVAL); const int err_code(errno); #endif // If ioctl(2) or WSAIoctl() failed for reasons other than our buffer // being too small, then we cannot continue. We need to clean up after // ourselves before we throw the exception explaining what went // wrong. if ( err_code != inval_err || lastlen != 0 ) { #if defined(VPR_OS_Windows) closesocket(sock); #else close(sock); #endif delete[] if_list; std::ostringstream msg_stream; #if defined(VPR_OS_Windows) msg_stream << "Bad ioctl (error code " << err_code << ")"; #else msg_stream << "Bad ioctl: " << strerror(errno); #endif throw vpr::Exception(msg_stream.str(), VPR_LOCATION); } } // If ioctl(2) or WSAIoctl() returned successfully, check the size of // the buffer that it returned. else { // If lastlen is the same as the size of the buffer returned by // ioctl(2) or WSAIoctl(), then we are done. If the size of the buffer // returned by ioctl(2) or WASIoctl() is no larger than what we // allocated, then we are done. if ( bytes_returned == lastlen || bytes_returned <= len ) { break; } // Otherwise, we continue iterating. else { lastlen = bytes_returned; } } // Increment the size of the returned buffer. len += 10 * sizeof(ifreq_t); delete[] if_list; } // We are done with the socket. #if defined(VPR_OS_Windows) closesocket(sock); #else close(sock); #endif // Figure out how many interfaces were returned. const size_t num = bytes_returned / sizeof(ifreq_t); // Iterate over the returned ifreq objects and pull out the valid IPv4 // addresses. for ( size_t i = 0; i < num; ++i ) { #if defined(VPR_OS_Windows) sockaddr_in* addr = (sockaddr_in*) &if_list[i].iiAddress; #else sockaddr_in* addr = (sockaddr_in*) &ifc.ifc_req[i].ifr_addr; #endif // Skip addresses that are not IPv4. // XXX: We should support IPv6 at some point. if ( addr->sin_family != AF_INET ) { continue; } // If we have the loopback address and withLoopback is false, then we // skip this address. if ( addr->sin_addr.s_addr == loop && ! withLoopback ) { continue; } char netaddr[18]; #if defined(VPR_OS_Windows) // inet_ntoa() returns a pointer to static memory, which means that // it is not reentrant. There is a race condition here between the // time of the return from inet_ntoa() and the time that strcpy() // actually copies the memory. Unfortunately, WinSock2 does not // provide inet_ntop(). strcpy(netaddr, inet_ntoa(addr->sin_addr)); char* temp_addr = netaddr; #else const char* temp_addr = inet_ntop(addr->sin_family, &addr->sin_addr, netaddr, sizeof(netaddr)); #endif if ( NULL != temp_addr ) { vpr::InetAddr vpr_addr; vpr_addr.setAddress(netaddr, 0); hostAddrs.push_back(vpr_addr); } } // All done. delete[] if_list; #endif /* defined(HAVE_GETIFADDRS) */ } } <|endoftext|>
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <configuration.hpp> #include <CommandLine.hpp> #include <Kernels.hpp> #include <Memory.hpp> #include <Pipeline.hpp> int main(int argc, char *argv[]) { // Command line options Options options{}; DeviceOptions deviceOptions{}; DataOptions dataOptions{}; GeneratorOptions generatorOptions{}; // Memory HostMemory hostMemory{}; DeviceMemory deviceMemory{}; HostMemoryDumpFiles hostMemoryDumpFiles{}; // OpenCL kernels OpenCLRunTime openclRunTime{}; KernelConfigurations kernelConfigurations{}; Kernels kernels{}; KernelRunTimeConfigurations kernelRunTimeConfigurations{}; // Timers Timers timers{}; // Observation AstroData::Observation observation; // Process command line arguments isa::utils::ArgumentList args(argc, argv); try { processCommandLineOptions(args, options, deviceOptions, dataOptions, hostMemoryDumpFiles, kernelConfigurations, generatorOptions, observation); } catch (std::exception &err) { return 1; } // Load or generate input data try { hostMemory.input.resize(observation.getNrBeams()); if (dataOptions.dataLOFAR || dataOptions.dataSIGPROC || dataOptions.dataPSRDADA) { loadInput(observation, deviceOptions, dataOptions, hostMemory, timers); } else { for (unsigned int beam = 0; beam < observation.getNrBeams(); beam++) { // TODO: if there are multiple synthesized beams, the generated data should take this into account hostMemory.input.at(beam) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches()); AstroData::generateSinglePulse(generatorOptions.width, generatorOptions.DM, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(beam)), inputBits, generatorOptions.random); } } try { hostMemory.zappedChannels.resize(observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); } catch (std::out_of_range &err) { std::cerr << "No padding specified for " << deviceOptions.deviceName << "." << std::endl; return 1; } try { AstroData::readZappedChannels(observation, dataOptions.channelsFile, hostMemory.zappedChannels); AstroData::readIntegrationSteps(observation, dataOptions.integrationFile, hostMemory.integrationSteps); } catch (AstroData::FileError &err) { std::cerr << err.what() << std::endl; return 1; } } catch (std::exception &err) { std::cerr << err.what() << std::endl; return 1; } // Print message with observation and search information if (options.print) { std::cout << "Device: " << deviceOptions.deviceName << " (" + std::to_string(deviceOptions.platformID) + ", "; std::cout << std::to_string(deviceOptions.deviceID) + ")" << std::endl; std::cout << "Padding: " << deviceOptions.padding[deviceOptions.deviceName] << " bytes" << std::endl; std::cout << std::endl; std::cout << "Beams: " << observation.getNrBeams() << std::endl; std::cout << "Synthesized Beams: " << observation.getNrSynthesizedBeams() << std::endl; std::cout << "Batches: " << observation.getNrBatches() << std::endl; std::cout << "Samples: " << observation.getNrSamplesPerBatch() << std::endl; std::cout << "Sampling time: " << observation.getSamplingTime() << std::endl; std::cout << "Frequency range: " << observation.getMinFreq() << " MHz, " << observation.getMaxFreq() << " MHz"; std::cout << std::endl; std::cout << "Subbands: " << observation.getNrSubbands() << " (" << observation.getSubbandBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Channels: " << observation.getNrChannels() << " (" << observation.getChannelBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Zapped Channels: " << observation.getNrZappedChannels() << std::endl; std::cout << "Integration steps: " << hostMemory.integrationSteps.size() << std::endl; if (options.subbandDedispersion) { std::cout << "Subbanding DMs: " << observation.getNrDMs(true) << " (" << observation.getFirstDM(true) << ", "; std::cout << observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true)); std::cout << ")" << std::endl; } std::cout << "DMs: " << observation.getNrDMs() << " (" << observation.getFirstDM() << ", "; std::cout << observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()) << ")"; std::cout << std::endl; std::cout << std::endl; } // Initialize OpenCL openclRunTime.context = new cl::Context(); openclRunTime.platforms = new std::vector<cl::Platform>(); openclRunTime.devices = new std::vector<cl::Device>(); openclRunTime.queues = new std::vector<std::vector<cl::CommandQueue>>(); try { isa::OpenCL::initializeOpenCL(deviceOptions.platformID, 1, openclRunTime.platforms, openclRunTime.context, openclRunTime.devices, openclRunTime.queues); } catch (isa::OpenCL::OpenCLError &err) { std::cerr << err.what() << std::endl; return 1; } // Memory allocation allocateHostMemory(observation, options, deviceOptions, dataOptions, kernelConfigurations, hostMemory); if (observation.getNrDelayBatches() > observation.getNrBatches()) { std::cerr << "Not enough input batches for the specified search." << std::endl; return 1; } try { allocateDeviceMemory(observation, openclRunTime, options, deviceOptions, hostMemory, deviceMemory); } catch (cl::Error &err) { std::cerr << "Memory error: " << err.what() << " " << err.err() << std::endl; return 1; } // Generate OpenCL kernels try { generateOpenCLKernels(openclRunTime, observation, options, deviceOptions, kernelConfigurations, hostMemory, deviceMemory, kernels); } catch (std::exception &err) { std::cerr << "OpenCL code generation error: " << err.what() << std::endl; return 1; } // Generate run time configurations for the OpenCL kernels generateOpenCLRunTimeConfigurations(observation, options, deviceOptions, kernelConfigurations, hostMemory, kernelRunTimeConfigurations); // Search loop pipeline(openclRunTime, observation, options, deviceOptions, dataOptions, timers, kernels, kernelRunTimeConfigurations, hostMemory, deviceMemory, hostMemoryDumpFiles); // Store performance statistics before shutting down std::ofstream outputStats; outputStats.open(dataOptions.outputFile + ".stats"); outputStats << std::fixed << std::setprecision(6); outputStats << "# nrDMs" << std::endl; if (options.subbandDedispersion) { outputStats << observation.getNrDMs(true) * observation.getNrDMs() << std::endl; } else { outputStats << observation.getNrDMs() << std::endl; } outputStats << "# timers.inputLoad" << std::endl; outputStats << timers.inputLoad.getTotalTime() << std::endl; outputStats << "# timers.search" << std::endl; outputStats << timers.search.getTotalTime() << std::endl; outputStats << "# inputHandlingTotal inputHandlingAvg err" << std::endl; outputStats << timers.inputHandling.getTotalTime() << " " << timers.inputHandling.getAverageTime() << " "; outputStats << timers.inputHandling.getStandardDeviation() << std::endl; outputStats << "# inputCopyTotal inputCopyAvg err" << std::endl; outputStats << timers.inputCopy.getTotalTime() << " " << timers.inputCopy.getAverageTime() << " "; outputStats << timers.inputCopy.getStandardDeviation() << std::endl; if (!options.subbandDedispersion) { outputStats << "# dedispersionSingleStepTotal dedispersionSingleStepAvg err" << std::endl; outputStats << timers.dedispersionSingleStep.getTotalTime() << " "; outputStats << timers.dedispersionSingleStep.getAverageTime() << " "; outputStats << timers.dedispersionSingleStep.getStandardDeviation() << std::endl; } else { outputStats << "# dedispersionStepOneTotal dedispersionStepOneAvg err" << std::endl; outputStats << timers.dedispersionStepOne.getTotalTime() << " "; outputStats << timers.dedispersionStepOne.getAverageTime() << " "; outputStats << timers.dedispersionStepOne.getStandardDeviation() << std::endl; outputStats << "# dedispersionStepTwoTotal dedispersionStepTwoAvg err" << std::endl; outputStats << timers.dedispersionStepTwo.getTotalTime() << " "; outputStats << timers.dedispersionStepTwo.getAverageTime() << " "; outputStats << timers.dedispersionStepTwo.getStandardDeviation() << std::endl; } outputStats << "# integrationTotal integrationAvg err" << std::endl; outputStats << timers.integration.getTotalTime() << " " << timers.integration.getAverageTime() << " "; outputStats << timers.integration.getStandardDeviation() << std::endl; if (options.snrMode == SNRMode::Standard) { outputStats << "# snrTotal snrAvg err" << std::endl; outputStats << timers.snr.getTotalTime() << " " << timers.snr.getAverageTime() << " "; outputStats << timers.snr.getStandardDeviation() << std::endl; } else if (options.snrMode == SNRMode::Momad) { outputStats << "# maxTotal maxAvg err" << std::endl; outputStats << timers.max.getTotalTime() << " " << timers.max.getAverageTime() << " "; outputStats << timers.max.getStandardDeviation() << std::endl; outputStats << "# medianOfMediansStepOneTotal medianOfMediansStepOneAvg err" << std::endl; outputStats << timers.medianOfMediansStepOne.getTotalTime() << " " << timers.medianOfMediansStepOne.getAverageTime() << " "; outputStats << timers.medianOfMediansStepOne.getStandardDeviation() << std::endl; outputStats << "# medianOfMediansStepTwoTotal medianOfMediansStepTwoAvg err" << std::endl; outputStats << timers.medianOfMediansStepTwo.getTotalTime() << " " << timers.medianOfMediansStepTwo.getAverageTime() << " "; outputStats << timers.medianOfMediansStepTwo.getStandardDeviation() << std::endl; outputStats << "# medianOfMediansAbsoluteDeviationStepOneTotal medianOfMediansAbsoluteDeviationStepOneAvg err" << std::endl; outputStats << timers.medianOfMediansAbsoluteDeviationStepOne.getTotalTime() << " " << timers.medianOfMediansAbsoluteDeviationStepOne.getAverageTime() << " "; outputStats << timers.medianOfMediansAbsoluteDeviationStepOne.getStandardDeviation() << std::endl; outputStats << "# medianOfMediansAbsoluteDeviationStepTwoTotal medianOfMediansAbsoluteDeviationStepTwoAvg err" << std::endl; outputStats << timers.medianOfMediansAbsoluteDeviationStepTwo.getTotalTime() << " " << timers.medianOfMediansAbsoluteDeviationStepTwo.getAverageTime() << " "; outputStats << timers.medianOfMediansAbsoluteDeviationStepTwo.getStandardDeviation() << std::endl; } outputStats << "# outputCopyTotal outputCopyAvg err" << std::endl; outputStats << timers.outputCopy.getTotalTime() << " " << timers.outputCopy.getAverageTime() << " "; outputStats << timers.outputCopy.getStandardDeviation() << std::endl; outputStats << "# triggerTimeTotal triggerTimeAvg err" << std::endl; outputStats << timers.trigger.getTotalTime() << " " << timers.trigger.getAverageTime() << " "; outputStats << timers.trigger.getStandardDeviation() << std::endl; outputStats.close(); return 0; } <commit_msg>Print downsampling factor.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <configuration.hpp> #include <CommandLine.hpp> #include <Kernels.hpp> #include <Memory.hpp> #include <Pipeline.hpp> int main(int argc, char *argv[]) { // Command line options Options options{}; DeviceOptions deviceOptions{}; DataOptions dataOptions{}; GeneratorOptions generatorOptions{}; // Memory HostMemory hostMemory{}; DeviceMemory deviceMemory{}; HostMemoryDumpFiles hostMemoryDumpFiles{}; // OpenCL kernels OpenCLRunTime openclRunTime{}; KernelConfigurations kernelConfigurations{}; Kernels kernels{}; KernelRunTimeConfigurations kernelRunTimeConfigurations{}; // Timers Timers timers{}; // Observation AstroData::Observation observation; // Process command line arguments isa::utils::ArgumentList args(argc, argv); try { processCommandLineOptions(args, options, deviceOptions, dataOptions, hostMemoryDumpFiles, kernelConfigurations, generatorOptions, observation); } catch (std::exception &err) { return 1; } // Load or generate input data try { hostMemory.input.resize(observation.getNrBeams()); if (dataOptions.dataLOFAR || dataOptions.dataSIGPROC || dataOptions.dataPSRDADA) { loadInput(observation, deviceOptions, dataOptions, hostMemory, timers); } else { for (unsigned int beam = 0; beam < observation.getNrBeams(); beam++) { // TODO: if there are multiple synthesized beams, the generated data should take this into account hostMemory.input.at(beam) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches()); AstroData::generateSinglePulse(generatorOptions.width, generatorOptions.DM, observation, deviceOptions.padding.at(deviceOptions.deviceName), *(hostMemory.input.at(beam)), inputBits, generatorOptions.random); } } try { hostMemory.zappedChannels.resize(observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName) / sizeof(unsigned int))); } catch (std::out_of_range &err) { std::cerr << "No padding specified for " << deviceOptions.deviceName << "." << std::endl; return 1; } try { AstroData::readZappedChannels(observation, dataOptions.channelsFile, hostMemory.zappedChannels); AstroData::readIntegrationSteps(observation, dataOptions.integrationFile, hostMemory.integrationSteps); } catch (AstroData::FileError &err) { std::cerr << err.what() << std::endl; return 1; } } catch (std::exception &err) { std::cerr << err.what() << std::endl; return 1; } // Print message with observation and search information if (options.print) { std::cout << "Device: " << deviceOptions.deviceName << " (" + std::to_string(deviceOptions.platformID) + ", "; std::cout << std::to_string(deviceOptions.deviceID) + ")" << std::endl; std::cout << "Padding: " << deviceOptions.padding[deviceOptions.deviceName] << " bytes" << std::endl; std::cout << std::endl; std::cout << "Beams: " << observation.getNrBeams() << std::endl; std::cout << "Synthesized Beams: " << observation.getNrSynthesizedBeams() << std::endl; std::cout << "Batches: " << observation.getNrBatches() << std::endl; std::cout << "Samples: " << observation.getNrSamplesPerBatch() << std::endl; std::cout << "Sampling time: " << observation.getSamplingTime() << std::endl; if ( options.downsampling ) { std::cout << "Downsampling factor: " << observation.getDownsampling() << std::endl; } std::cout << "Frequency range: " << observation.getMinFreq() << " MHz, " << observation.getMaxFreq() << " MHz"; std::cout << std::endl; std::cout << "Subbands: " << observation.getNrSubbands() << " (" << observation.getSubbandBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Channels: " << observation.getNrChannels() << " (" << observation.getChannelBandwidth() << " MHz)"; std::cout << std::endl; std::cout << "Zapped Channels: " << observation.getNrZappedChannels() << std::endl; std::cout << "Integration steps: " << hostMemory.integrationSteps.size() << std::endl; if (options.subbandDedispersion) { std::cout << "Subbanding DMs: " << observation.getNrDMs(true) << " (" << observation.getFirstDM(true) << ", "; std::cout << observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true)); std::cout << ")" << std::endl; } std::cout << "DMs: " << observation.getNrDMs() << " (" << observation.getFirstDM() << ", "; std::cout << observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()) << ")"; std::cout << std::endl; std::cout << std::endl; } // Initialize OpenCL openclRunTime.context = new cl::Context(); openclRunTime.platforms = new std::vector<cl::Platform>(); openclRunTime.devices = new std::vector<cl::Device>(); openclRunTime.queues = new std::vector<std::vector<cl::CommandQueue>>(); try { isa::OpenCL::initializeOpenCL(deviceOptions.platformID, 1, openclRunTime.platforms, openclRunTime.context, openclRunTime.devices, openclRunTime.queues); } catch (isa::OpenCL::OpenCLError &err) { std::cerr << err.what() << std::endl; return 1; } // Memory allocation allocateHostMemory(observation, options, deviceOptions, dataOptions, kernelConfigurations, hostMemory); if (observation.getNrDelayBatches() > observation.getNrBatches()) { std::cerr << "Not enough input batches for the specified search." << std::endl; return 1; } try { allocateDeviceMemory(observation, openclRunTime, options, deviceOptions, hostMemory, deviceMemory); } catch (cl::Error &err) { std::cerr << "Memory error: " << err.what() << " " << err.err() << std::endl; return 1; } // Generate OpenCL kernels try { generateOpenCLKernels(openclRunTime, observation, options, deviceOptions, kernelConfigurations, hostMemory, deviceMemory, kernels); } catch (std::exception &err) { std::cerr << "OpenCL code generation error: " << err.what() << std::endl; return 1; } // Generate run time configurations for the OpenCL kernels generateOpenCLRunTimeConfigurations(observation, options, deviceOptions, kernelConfigurations, hostMemory, kernelRunTimeConfigurations); // Search loop pipeline(openclRunTime, observation, options, deviceOptions, dataOptions, timers, kernels, kernelRunTimeConfigurations, hostMemory, deviceMemory, hostMemoryDumpFiles); // Store performance statistics before shutting down std::ofstream outputStats; outputStats.open(dataOptions.outputFile + ".stats"); outputStats << std::fixed << std::setprecision(6); outputStats << "# nrDMs" << std::endl; if (options.subbandDedispersion) { outputStats << observation.getNrDMs(true) * observation.getNrDMs() << std::endl; } else { outputStats << observation.getNrDMs() << std::endl; } outputStats << "# timers.inputLoad" << std::endl; outputStats << timers.inputLoad.getTotalTime() << std::endl; outputStats << "# timers.search" << std::endl; outputStats << timers.search.getTotalTime() << std::endl; outputStats << "# inputHandlingTotal inputHandlingAvg err" << std::endl; outputStats << timers.inputHandling.getTotalTime() << " " << timers.inputHandling.getAverageTime() << " "; outputStats << timers.inputHandling.getStandardDeviation() << std::endl; outputStats << "# inputCopyTotal inputCopyAvg err" << std::endl; outputStats << timers.inputCopy.getTotalTime() << " " << timers.inputCopy.getAverageTime() << " "; outputStats << timers.inputCopy.getStandardDeviation() << std::endl; if (!options.subbandDedispersion) { outputStats << "# dedispersionSingleStepTotal dedispersionSingleStepAvg err" << std::endl; outputStats << timers.dedispersionSingleStep.getTotalTime() << " "; outputStats << timers.dedispersionSingleStep.getAverageTime() << " "; outputStats << timers.dedispersionSingleStep.getStandardDeviation() << std::endl; } else { outputStats << "# dedispersionStepOneTotal dedispersionStepOneAvg err" << std::endl; outputStats << timers.dedispersionStepOne.getTotalTime() << " "; outputStats << timers.dedispersionStepOne.getAverageTime() << " "; outputStats << timers.dedispersionStepOne.getStandardDeviation() << std::endl; outputStats << "# dedispersionStepTwoTotal dedispersionStepTwoAvg err" << std::endl; outputStats << timers.dedispersionStepTwo.getTotalTime() << " "; outputStats << timers.dedispersionStepTwo.getAverageTime() << " "; outputStats << timers.dedispersionStepTwo.getStandardDeviation() << std::endl; } outputStats << "# integrationTotal integrationAvg err" << std::endl; outputStats << timers.integration.getTotalTime() << " " << timers.integration.getAverageTime() << " "; outputStats << timers.integration.getStandardDeviation() << std::endl; if (options.snrMode == SNRMode::Standard) { outputStats << "# snrTotal snrAvg err" << std::endl; outputStats << timers.snr.getTotalTime() << " " << timers.snr.getAverageTime() << " "; outputStats << timers.snr.getStandardDeviation() << std::endl; } else if (options.snrMode == SNRMode::Momad) { outputStats << "# maxTotal maxAvg err" << std::endl; outputStats << timers.max.getTotalTime() << " " << timers.max.getAverageTime() << " "; outputStats << timers.max.getStandardDeviation() << std::endl; outputStats << "# medianOfMediansStepOneTotal medianOfMediansStepOneAvg err" << std::endl; outputStats << timers.medianOfMediansStepOne.getTotalTime() << " " << timers.medianOfMediansStepOne.getAverageTime() << " "; outputStats << timers.medianOfMediansStepOne.getStandardDeviation() << std::endl; outputStats << "# medianOfMediansStepTwoTotal medianOfMediansStepTwoAvg err" << std::endl; outputStats << timers.medianOfMediansStepTwo.getTotalTime() << " " << timers.medianOfMediansStepTwo.getAverageTime() << " "; outputStats << timers.medianOfMediansStepTwo.getStandardDeviation() << std::endl; outputStats << "# medianOfMediansAbsoluteDeviationStepOneTotal medianOfMediansAbsoluteDeviationStepOneAvg err" << std::endl; outputStats << timers.medianOfMediansAbsoluteDeviationStepOne.getTotalTime() << " " << timers.medianOfMediansAbsoluteDeviationStepOne.getAverageTime() << " "; outputStats << timers.medianOfMediansAbsoluteDeviationStepOne.getStandardDeviation() << std::endl; outputStats << "# medianOfMediansAbsoluteDeviationStepTwoTotal medianOfMediansAbsoluteDeviationStepTwoAvg err" << std::endl; outputStats << timers.medianOfMediansAbsoluteDeviationStepTwo.getTotalTime() << " " << timers.medianOfMediansAbsoluteDeviationStepTwo.getAverageTime() << " "; outputStats << timers.medianOfMediansAbsoluteDeviationStepTwo.getStandardDeviation() << std::endl; } outputStats << "# outputCopyTotal outputCopyAvg err" << std::endl; outputStats << timers.outputCopy.getTotalTime() << " " << timers.outputCopy.getAverageTime() << " "; outputStats << timers.outputCopy.getStandardDeviation() << std::endl; outputStats << "# triggerTimeTotal triggerTimeAvg err" << std::endl; outputStats << timers.trigger.getTotalTime() << " " << timers.trigger.getAverageTime() << " "; outputStats << timers.trigger.getStandardDeviation() << std::endl; outputStats.close(); return 0; } <|endoftext|>
<commit_before>#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "guiutil.h" #include <QPixmap> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include <QDebug> #include <qrencode.h> #define EXPORT_IMAGE_SIZE 256 QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); setAttribute(Qt::WA_DeleteOnClose); ui->chkReqPayment->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lblBTC->setVisible(enableReq); ui->lnLabel->setText(label); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::genCode() { QString uri = getURI(); if(uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if(!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for(int y = 0; y < code->width; y++) { for(int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); } else ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); } QString QRCodeDialog::getURI() { QString ret = QString("slimcoin:%1").arg(address); int paramCount = 0; if(ui->chkReqPayment->isChecked() && !ui->lnReqAmount->text().isEmpty()) { bool ok = false; ui->lnReqAmount->text().toDouble(&ok); if(ok) { ret += QString("?amount=%1").arg(ui->lnReqAmount->text()); paramCount++; } } if(!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if(!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to 255 chars, to prevent a DoS against the QR-Code dialog if(ret.length() < 256) return ret; else return QString(""); } void QRCodeDialog::on_lnReqAmount_textChanged(const QString &arg1) { genCode(); } void QRCodeDialog::on_lnLabel_textChanged(const QString &arg1) { genCode(); } void QRCodeDialog::on_lnMessage_textChanged(const QString &arg1) { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save Image..."), QString(), tr("PNG Images (*.png)")); if(!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool) { genCode(); } <commit_msg>gardening<commit_after>#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "guiutil.h" #include <QPixmap> #include <QUrl> #include <QDebug> #include <qrencode.h> #define EXPORT_IMAGE_SIZE 256 QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); setAttribute(Qt::WA_DeleteOnClose); ui->chkReqPayment->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lblBTC->setVisible(enableReq); ui->lnLabel->setText(label); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::genCode() { QString uri = getURI(); if(uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if(!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for(int y = 0; y < code->width; y++) { for(int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); } else ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); } QString QRCodeDialog::getURI() { QString ret = QString("slimcoin:%1").arg(address); int paramCount = 0; if(ui->chkReqPayment->isChecked() && !ui->lnReqAmount->text().isEmpty()) { bool ok = false; ui->lnReqAmount->text().toDouble(&ok); if(ok) { ret += QString("?amount=%1").arg(ui->lnReqAmount->text()); paramCount++; } } if(!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if(!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to 255 chars, to prevent a DoS against the QR-Code dialog if(ret.length() < 256) return ret; else return QString(""); } void QRCodeDialog::on_lnReqAmount_textChanged(const QString &arg1) { genCode(); } void QRCodeDialog::on_lnLabel_textChanged(const QString &arg1) { genCode(); } void QRCodeDialog::on_lnMessage_textChanged(const QString &arg1) { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save Image..."), QString(), tr("PNG Images (*.png)")); if(!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool) { genCode(); } <|endoftext|>
<commit_before>#include "splashscreen.h" #include "clientversion.h" #include "util.h" #include "chainparams.h" #include <QApplication> #include <QPainter> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers")); QString testnetAddText = QString(tr("[testnet]")); // define text to place as single text object QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(TestNet()) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(100,100,100)); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10*fontFactor)); pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); // draw testnet string if -testnet is on if(QApplication::applicationName().contains(QString("-testnet"))) { // draw copyright stuff QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int testnetAddTextWidth = fm.width(testnetAddText); pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText); } pixPaint.end(); this->setPixmap(newPixmap); } <commit_msg>splashscreen: use TestNet() instead of unneeded string processing<commit_after>#include "splashscreen.h" #include "clientversion.h" #include "util.h" #include "chainparams.h" #include <QApplication> #include <QPainter> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers")); QString testnetAddText = QString(tr("[testnet]")); // define text to place as single text object QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(TestNet()) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(100,100,100)); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10*fontFactor)); pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); // draw testnet string if testnet is on if(TestNet()) { QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int testnetAddTextWidth = fm.width(testnetAddText); pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText); } pixPaint.end(); this->setPixmap(newPixmap); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "splashscreen.h" #include "networkstyle.h" #include "clientversion.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "version.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> #include <QRadialGradient> SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) : QWidget(0, f), curAlignment(0) { // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; float devicePixelRatio = 1.0; #if QT_VERSION > 0x050100 devicePixelRatio = ((QGuiApplication*)QCoreApplication::instance())->devicePixelRatio(); #endif // define text to place QString titleText = tr(PACKAGE_NAME); QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QChar(0xA9)+QString(" %1-%2 ").arg(2009).arg(COPYRIGHT_YEAR) + QString::fromStdString(CopyrightHolders()); QString titleAddText = networkStyle->getTitleAddText(); QString font = QApplication::font().toString(); // create a bitmap according to device pixelratio QSize splashSize(480*devicePixelRatio,320*devicePixelRatio); pixmap = QPixmap(splashSize); #if QT_VERSION > 0x050100 // change to HiDPI if it makes sense pixmap.setDevicePixelRatio(devicePixelRatio); #endif QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100,100,100)); // draw a slightly radial gradient QRadialGradient gradient(QPoint(0,0), splashSize.width()/devicePixelRatio); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, QColor(247,247,247)); QRect rGradient(QPoint(0,0), splashSize); pixPaint.fillRect(rGradient, gradient); // draw the bitcoin icon, expected size of PNG: 1024x1024 QRect rectIcon(QPoint(-150,-122), QSize(430,430)); const QSize requiredSize(1024,1024); QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize)); pixPaint.drawPixmap(rectIcon, icon); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10*fontFactor)); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); // draw additional text if special network if(!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleAddTextWidth-10,15,titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), QSize(pixmap.size().width()/devicePixelRatio,pixmap.size().height()/devicePixelRatio)); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget *mainWin) { Q_UNUSED(mainWin); hide(); } static void InitMessage(SplashScreen *splash, const std::string &message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter), Q_ARG(QColor, QColor(55,55,55))); } static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen *splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET if(pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color) { curMessage = message; curAlignment = alignment; curColor = color; update(); } void SplashScreen::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.drawPixmap(0, 0, pixmap); QRect r = rect().adjusted(5, 5, -5, -5); painter.setPen(curColor); painter.drawText(r, curAlignment, curMessage); } void SplashScreen::closeEvent(QCloseEvent *event) { StartShutdown(); // allows an "emergency" shutdown during startup event->ignore(); } <commit_msg>splashscreen: Resize text to fit exactly<commit_after>// Copyright (c) 2011-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "splashscreen.h" #include "networkstyle.h" #include "clientversion.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "version.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> #include <QRadialGradient> SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) : QWidget(0, f), curAlignment(0) { // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; float devicePixelRatio = 1.0; #if QT_VERSION > 0x050100 devicePixelRatio = ((QGuiApplication*)QCoreApplication::instance())->devicePixelRatio(); #endif // define text to place QString titleText = tr(PACKAGE_NAME); QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QChar(0xA9)+QString(" %1-%2 ").arg(2009).arg(COPYRIGHT_YEAR) + QString::fromStdString(CopyrightHolders()); QString titleAddText = networkStyle->getTitleAddText(); QString font = QApplication::font().toString(); // create a bitmap according to device pixelratio QSize splashSize(480*devicePixelRatio,320*devicePixelRatio); pixmap = QPixmap(splashSize); #if QT_VERSION > 0x050100 // change to HiDPI if it makes sense pixmap.setDevicePixelRatio(devicePixelRatio); #endif QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100,100,100)); // draw a slightly radial gradient QRadialGradient gradient(QPoint(0,0), splashSize.width()/devicePixelRatio); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, QColor(247,247,247)); QRect rGradient(QPoint(0,0), splashSize); pixPaint.fillRect(rGradient, gradient); // draw the bitcoin icon, expected size of PNG: 1024x1024 QRect rectIcon(QPoint(-150,-122), QSize(430,430)); const QSize requiredSize(1024,1024); QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize)); pixPaint.drawPixmap(rectIcon, icon); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if (titleTextWidth > 176) { fontFactor = fontFactor * 176 / titleTextWidth; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10*fontFactor)); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); // draw additional text if special network if(!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleAddTextWidth-10,15,titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), QSize(pixmap.size().width()/devicePixelRatio,pixmap.size().height()/devicePixelRatio)); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget *mainWin) { Q_UNUSED(mainWin); hide(); } static void InitMessage(SplashScreen *splash, const std::string &message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter), Q_ARG(QColor, QColor(55,55,55))); } static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen *splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET if(pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color) { curMessage = message; curAlignment = alignment; curColor = color; update(); } void SplashScreen::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.drawPixmap(0, 0, pixmap); QRect r = rect().adjusted(5, 5, -5, -5); painter.setPen(curColor); painter.drawText(r, curAlignment, curMessage); } void SplashScreen::closeEvent(QCloseEvent *event) { StartShutdown(); // allows an "emergency" shutdown during startup event->ignore(); } <|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "libcef/browser/scheme_handler.h" #include <string> #include "libcef/browser/chrome_scheme_handler.h" #include "libcef/browser/devtools_scheme_handler.h" #include "libcef/common/scheme_registration.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/url_constants.h" #include "net/url_request/data_protocol_handler.h" #include "net/url_request/file_protocol_handler.h" #include "net/url_request/ftp_protocol_handler.h" #include "net/url_request/url_request_job_factory_impl.h" namespace scheme { void InstallInternalProtectedHandlers( net::URLRequestJobFactoryImpl* job_factory, content::ProtocolHandlerMap* protocol_handlers, net::FtpTransactionFactory* ftp_transaction_factory) { protocol_handlers->insert( std::make_pair(chrome::kDataScheme, new net::DataProtocolHandler)); protocol_handlers->insert( std::make_pair(chrome::kFileScheme, new net::FileProtocolHandler( content::BrowserThread::GetBlockingPool()-> GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)))); #if !defined(DISABLE_FTP_SUPPORT) protocol_handlers->insert( std::make_pair(chrome::kFtpScheme, new net::FtpProtocolHandler(ftp_transaction_factory))); #endif for (content::ProtocolHandlerMap::iterator it = protocol_handlers->begin(); it != protocol_handlers->end(); ++it) { const std::string& scheme = it->first; scoped_ptr<net::URLRequestJobFactory::ProtocolHandler> protocol_handler; if (scheme == chrome::kChromeDevToolsScheme) { // Don't use the default "chrome-devtools" handler. continue; } else if (scheme == chrome::kChromeUIScheme) { // Filter the URLs that are passed to the default "chrome" handler so as // not to interfere with CEF's "chrome" handler. protocol_handler.reset( scheme::WrapChromeProtocolHandler( make_scoped_ptr(it->second.release())).release()); } else { protocol_handler.reset(it->second.release()); } // Make sure IsInternalProtectedScheme() stays synchronized with what // Chromium is actually giving us. DCHECK(IsInternalProtectedScheme(scheme)); bool set_protocol = job_factory->SetProtocolHandler( scheme, protocol_handler.release()); DCHECK(set_protocol); } } void RegisterInternalHandlers() { scheme::RegisterChromeHandler(); scheme::RegisterChromeDevToolsHandler(); } void DidFinishLoad(CefRefPtr<CefFrame> frame, const GURL& validated_url) { if (validated_url.scheme() == chrome::kChromeUIScheme) scheme::DidFinishChromeLoad(frame, validated_url); } } // namespace scheme <commit_msg>Fix compile error (issue #1064).<commit_after>// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "libcef/browser/scheme_handler.h" #include <string> #include "libcef/browser/chrome_scheme_handler.h" #include "libcef/browser/devtools_scheme_handler.h" #include "libcef/common/scheme_registration.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/url_constants.h" #include "net/url_request/data_protocol_handler.h" #include "net/url_request/file_protocol_handler.h" #include "net/url_request/ftp_protocol_handler.h" #include "net/url_request/url_request_job_factory_impl.h" namespace scheme { void InstallInternalProtectedHandlers( net::URLRequestJobFactoryImpl* job_factory, content::ProtocolHandlerMap* protocol_handlers, net::FtpTransactionFactory* ftp_transaction_factory) { protocol_handlers->insert( std::make_pair(chrome::kDataScheme, new net::DataProtocolHandler)); protocol_handlers->insert( std::make_pair(chrome::kFileScheme, new net::FileProtocolHandler( content::BrowserThread::GetBlockingPool()-> GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)))); #if !defined(DISABLE_FTP_SUPPORT) protocol_handlers->insert( std::make_pair(chrome::kFtpScheme, new net::FtpProtocolHandler(ftp_transaction_factory))); #endif for (content::ProtocolHandlerMap::iterator it = protocol_handlers->begin(); it != protocol_handlers->end(); ++it) { const std::string& scheme = it->first; scoped_ptr<net::URLRequestJobFactory::ProtocolHandler> protocol_handler; if (scheme == chrome::kChromeDevToolsScheme) { // Don't use the default "chrome-devtools" handler. continue; } else if (scheme == chrome::kChromeUIScheme) { // Filter the URLs that are passed to the default "chrome" handler so as // not to interfere with CEF's "chrome" handler. protocol_handler.reset( scheme::WrapChromeProtocolHandler( make_scoped_ptr(it->second.release())).release()); } else { protocol_handler.reset(it->second.release()); } // Make sure IsInternalProtectedScheme() stays synchronized with what // Chromium is actually giving us. DCHECK(IsInternalProtectedScheme(scheme)); bool set_protocol = job_factory->SetProtocolHandler( scheme, protocol_handler.release()); DCHECK(set_protocol); } } void RegisterInternalHandlers() { scheme::RegisterChromeHandler(); scheme::RegisterChromeDevToolsHandler(); } void DidFinishLoad(CefRefPtr<CefFrame> frame, const GURL& validated_url) { if (validated_url.scheme() == chrome::kChromeUIScheme) scheme::DidFinishChromeLoad(frame, validated_url); } } // namespace scheme <|endoftext|>
<commit_before>/***************************************************************************** * Copyright (C) 2011-2013 Michael Krufky * * Author: Michael Krufky <mkrufky@linuxtv.org> * * 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 * *****************************************************************************/ #define DBG 0 #include <stdio.h> #include <stdlib.h> #include <string.h> #include "functions.h" #include "log.h" #define CLASS_MODULE "desc" #include "dvbpsi/dr_0a.h" /* ISO639 language descriptor */ #include "dvbpsi/dr_48.h" /* service descriptor */ #include "dvbpsi/dr_4d.h" /* short event descriptor */ #include "dvbpsi/dr_62.h" /* frequency list descriptor */ #include "dvbpsi/dr_83.h" /* LCN descriptor */ #include "dvbpsi/dr_86.h" /* caption service descriptor */ #include "dvbpsi/dr_a0.h" /* extended channel name descriptor */ #include "dvbpsi/dr_a1.h" /* service location descriptor */ #include "desc.h" #define dprintf(fmt, arg...) __dprintf(DBG_DESC, fmt, ##arg) #define DT_ISO639Language 0x0a #define DT_Service 0x48 #define DT_ShortEvent 0x4d #define DT_Teletext 0x56 #define DT_FrequencyList 0x62 #define DT_LogicalChannelNumber 0x83 #define DT_CaptionService 0x86 #define DT_ExtendedChannelName 0xa0 #define DT_ServiceLocation 0xa1 #define desc_dr_failed(dr) \ ({ \ bool __ret = !dr; \ if (__ret) dprintf("decoder failed!"); \ __ret; \ }) desc::desc() // : f_kill_thread(false) { dprintf("()"); } desc::~desc() { dprintf("()"); } bool desc::iso639language(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_ISO639Language) return false; dvbpsi_iso639_dr_t* dr = dvbpsi_DecodeISO639Dr(p_descriptor); if (desc_dr_failed(dr)) return false; for (int i = 0; i < dr->i_code_count; ++i) dprintf("%c%c%c %x", dr->code[i].iso_639_code[0], dr->code[i].iso_639_code[1], dr->code[i].iso_639_code[2], dr->code[i].i_audio_type); return true; } bool desc::service(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_Service) return false; dvbpsi_service_dr_t* dr = dvbpsi_DecodeServiceDr(p_descriptor); if (desc_dr_failed(dr)) return false; get_descriptor_text(dr->i_service_provider_name, dr->i_service_provider_name_length, provider_name); get_descriptor_text(dr->i_service_name, dr->i_service_name_length, service_name); dprintf("%s, %s", provider_name, service_name); return true; } bool desc::short_event(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_ShortEvent) return false; dvbpsi_short_event_dr_t* dr = dvbpsi_DecodeShortEventDr(p_descriptor); if (desc_dr_failed(dr)) return false; memcpy(_4d.lang, dr->i_iso_639_code, 3); get_descriptor_text(dr->i_event_name, dr->i_event_name_length, _4d.name); get_descriptor_text(dr->i_text, dr->i_text_length, _4d.text); dprintf("%s, %s, %s", _4d.lang, _4d.name, _4d.text); return true; } bool desc::freq_list(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_FrequencyList) return false; dvbpsi_frequency_list_dr_t* dr = dvbpsi_DecodeFrequencyListDr(p_descriptor); if (desc_dr_failed(dr)) return false; for (int i = 0; i < dr->i_number_of_frequencies; ++i) { #if 0 = dr->p_center_frequencies[i] #else dprintf("%d", dr->p_center_frequencies[i]); #endif } return true; } bool desc::_lcn(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_LogicalChannelNumber) return false; dvbpsi_lcn_dr_t* dr = dvbpsi_DecodeLCNDr(p_descriptor); if (desc_dr_failed(dr)) return false; for (int i = 0; i < dr->i_number_of_entries; i ++) { #if 0 = lcn->p_entries[i].i_service_id; = lcn->p_entries[i].i_logical_channel_number; #else lcn[dr->p_entries[i].i_service_id] = dr->p_entries[i].i_logical_channel_number; dprintf("%d, %d", dr->p_entries[i].i_service_id, lcn[dr->p_entries[i].i_service_id]); #endif } return true; } bool desc::caption_service(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_CaptionService) return false; dvbpsi_caption_service_dr_t* dr = dvbpsi_DecodeCaptionServiceDr(p_descriptor); if (desc_dr_failed(dr)) return false; dvbpsi_caption_service_t *service = dr->p_first_service; for (int i = 0; i < dr->i_number_of_services; i ++) { if (!service) { dprintf("error!"); break; } dprintf("%d / %04x, %s line21 field: %d %d %s%s%c%c%c", service->i_caption_service_number, service->i_caption_service_number, (service->b_digital_cc) ? "708" : "608", service->b_line21_field, (service->b_digital_cc) ? service->i_caption_service_number : 0, (service->b_easy_reader) ? "easy reader " : "", (service->b_wide_aspect_ratio) ? "wide aspect ratio " : "", service->i_iso_639_code[0], service->i_iso_639_code[1], service->i_iso_639_code[2]); service = service->p_next; } return true; } bool desc::extended_channel_name(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_ExtendedChannelName) return false; dvbpsi_extended_channel_name_dr_t *dr = dvbpsi_ExtendedChannelNameeDr(p_descriptor); if (desc_dr_failed(dr)) return false; unsigned char name[256]; memset(name, 0, sizeof(name)); decode_multiple_string(dr->i_long_channel_name, dr->i_long_channel_name_length, name); dprintf("%s", name); return true; } bool desc::service_location(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_ServiceLocation) return false; dvbpsi_service_location_dr_t* dr = dvbpsi_DecodeServiceLocationDr(p_descriptor); if (desc_dr_failed(dr)) return false; dvbpsi_service_location_element_t *element = dr->p_first_element; for (int i = 0; i < dr->i_number_elements; i ++) { if (!element) { dprintf("error!"); break; } _a1[element->i_elementary_pid].elementary_pid = element->i_elementary_pid; _a1[element->i_elementary_pid].stream_type = element->i_stream_type; memcpy(_a1[element->i_elementary_pid].iso_639_code, element->i_iso_639_code, 3); dprintf("%d, %02x, %c%c%c", element->i_elementary_pid, element->i_stream_type, element->i_iso_639_code[0], element->i_iso_639_code[1], element->i_iso_639_code[2]); element = element->p_next; } return true; } void desc::decode(dvbpsi_descriptor_t* p_descriptor) { while (p_descriptor) { switch (p_descriptor->i_tag) { case DT_ISO639Language: iso639language(p_descriptor); break; case DT_Service: service(p_descriptor); break; case DT_ShortEvent: short_event(p_descriptor); break; case DT_FrequencyList: freq_list(p_descriptor); break; case DT_LogicalChannelNumber: _lcn(p_descriptor); break; case DT_CaptionService: caption_service(p_descriptor); break; case DT_ExtendedChannelName: extended_channel_name(p_descriptor); break; case DT_ServiceLocation: service_location(p_descriptor); break; default: dprintf("unknown descriptor tag: %02x", p_descriptor->i_tag); break; } p_descriptor = p_descriptor->p_next; } } <commit_msg>desc: convert descriptors 0x86 & 0xa1 from linked lists to arrays<commit_after>/***************************************************************************** * Copyright (C) 2011-2013 Michael Krufky * * Author: Michael Krufky <mkrufky@linuxtv.org> * * 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 * *****************************************************************************/ #define DBG 0 #include <stdio.h> #include <stdlib.h> #include <string.h> #include "functions.h" #include "log.h" #define CLASS_MODULE "desc" #include "dvbpsi/dr_0a.h" /* ISO639 language descriptor */ #include "dvbpsi/dr_48.h" /* service descriptor */ #include "dvbpsi/dr_4d.h" /* short event descriptor */ #include "dvbpsi/dr_62.h" /* frequency list descriptor */ #include "dvbpsi/dr_83.h" /* LCN descriptor */ #include "dvbpsi/dr_86.h" /* caption service descriptor */ #include "dvbpsi/dr_a0.h" /* extended channel name descriptor */ #include "dvbpsi/dr_a1.h" /* service location descriptor */ #include "desc.h" #define dprintf(fmt, arg...) __dprintf(DBG_DESC, fmt, ##arg) #define DT_ISO639Language 0x0a #define DT_Service 0x48 #define DT_ShortEvent 0x4d #define DT_Teletext 0x56 #define DT_FrequencyList 0x62 #define DT_LogicalChannelNumber 0x83 #define DT_CaptionService 0x86 #define DT_ExtendedChannelName 0xa0 #define DT_ServiceLocation 0xa1 #define desc_dr_failed(dr) \ ({ \ bool __ret = !dr; \ if (__ret) dprintf("decoder failed!"); \ __ret; \ }) desc::desc() // : f_kill_thread(false) { dprintf("()"); } desc::~desc() { dprintf("()"); } bool desc::iso639language(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_ISO639Language) return false; dvbpsi_iso639_dr_t* dr = dvbpsi_DecodeISO639Dr(p_descriptor); if (desc_dr_failed(dr)) return false; for (int i = 0; i < dr->i_code_count; ++i) dprintf("%c%c%c %x", dr->code[i].iso_639_code[0], dr->code[i].iso_639_code[1], dr->code[i].iso_639_code[2], dr->code[i].i_audio_type); return true; } bool desc::service(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_Service) return false; dvbpsi_service_dr_t* dr = dvbpsi_DecodeServiceDr(p_descriptor); if (desc_dr_failed(dr)) return false; get_descriptor_text(dr->i_service_provider_name, dr->i_service_provider_name_length, provider_name); get_descriptor_text(dr->i_service_name, dr->i_service_name_length, service_name); dprintf("%s, %s", provider_name, service_name); return true; } bool desc::short_event(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_ShortEvent) return false; dvbpsi_short_event_dr_t* dr = dvbpsi_DecodeShortEventDr(p_descriptor); if (desc_dr_failed(dr)) return false; memcpy(_4d.lang, dr->i_iso_639_code, 3); get_descriptor_text(dr->i_event_name, dr->i_event_name_length, _4d.name); get_descriptor_text(dr->i_text, dr->i_text_length, _4d.text); dprintf("%s, %s, %s", _4d.lang, _4d.name, _4d.text); return true; } bool desc::freq_list(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_FrequencyList) return false; dvbpsi_frequency_list_dr_t* dr = dvbpsi_DecodeFrequencyListDr(p_descriptor); if (desc_dr_failed(dr)) return false; for (int i = 0; i < dr->i_number_of_frequencies; ++i) { #if 0 = dr->p_center_frequencies[i] #else dprintf("%d", dr->p_center_frequencies[i]); #endif } return true; } bool desc::_lcn(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_LogicalChannelNumber) return false; dvbpsi_lcn_dr_t* dr = dvbpsi_DecodeLCNDr(p_descriptor); if (desc_dr_failed(dr)) return false; for (int i = 0; i < dr->i_number_of_entries; i ++) { #if 0 = lcn->p_entries[i].i_service_id; = lcn->p_entries[i].i_logical_channel_number; #else lcn[dr->p_entries[i].i_service_id] = dr->p_entries[i].i_logical_channel_number; dprintf("%d, %d", dr->p_entries[i].i_service_id, lcn[dr->p_entries[i].i_service_id]); #endif } return true; } bool desc::caption_service(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_CaptionService) return false; dvbpsi_caption_service_dr_t* dr = dvbpsi_DecodeCaptionServiceDr(p_descriptor); if (desc_dr_failed(dr)) return false; for (int i = 0; i < dr->i_number_of_services; i ++) { dvbpsi_caption_service_t *service = &dr->services[0]; if (!service) { dprintf("error!"); break; } dprintf("%d / %04x, %s line21 field: %d %d %s%s%c%c%c", service->i_caption_service_number, service->i_caption_service_number, (service->b_digital_cc) ? "708" : "608", service->b_line21_field, (service->b_digital_cc) ? service->i_caption_service_number : 0, (service->b_easy_reader) ? "easy reader " : "", (service->b_wide_aspect_ratio) ? "wide aspect ratio " : "", service->i_iso_639_code[0], service->i_iso_639_code[1], service->i_iso_639_code[2]); } return true; } bool desc::extended_channel_name(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_ExtendedChannelName) return false; dvbpsi_extended_channel_name_dr_t *dr = dvbpsi_ExtendedChannelNameeDr(p_descriptor); if (desc_dr_failed(dr)) return false; unsigned char name[256]; memset(name, 0, sizeof(name)); decode_multiple_string(dr->i_long_channel_name, dr->i_long_channel_name_length, name); dprintf("%s", name); return true; } bool desc::service_location(dvbpsi_descriptor_t* p_descriptor) { if (p_descriptor->i_tag != DT_ServiceLocation) return false; dvbpsi_service_location_dr_t* dr = dvbpsi_DecodeServiceLocationDr(p_descriptor); if (desc_dr_failed(dr)) return false; for (int i = 0; i < dr->i_number_elements; i ++) { dvbpsi_service_location_element_t *element = &dr->elements[i]; if (!element) { dprintf("error!"); break; } _a1[element->i_elementary_pid].elementary_pid = element->i_elementary_pid; _a1[element->i_elementary_pid].stream_type = element->i_stream_type; memcpy(_a1[element->i_elementary_pid].iso_639_code, element->i_iso_639_code, 3); dprintf("%d, %02x, %c%c%c", element->i_elementary_pid, element->i_stream_type, element->i_iso_639_code[0], element->i_iso_639_code[1], element->i_iso_639_code[2]); } return true; } void desc::decode(dvbpsi_descriptor_t* p_descriptor) { while (p_descriptor) { switch (p_descriptor->i_tag) { case DT_ISO639Language: iso639language(p_descriptor); break; case DT_Service: service(p_descriptor); break; case DT_ShortEvent: short_event(p_descriptor); break; case DT_FrequencyList: freq_list(p_descriptor); break; case DT_LogicalChannelNumber: _lcn(p_descriptor); break; case DT_CaptionService: caption_service(p_descriptor); break; case DT_ExtendedChannelName: extended_channel_name(p_descriptor); break; case DT_ServiceLocation: service_location(p_descriptor); break; default: dprintf("unknown descriptor tag: %02x", p_descriptor->i_tag); break; } p_descriptor = p_descriptor->p_next; } } <|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/>. */ // SmartVM is only available if EVM JIT is enabled #if ETH_EVMJIT #include "SmartVM.h" #include <unordered_map> #include <thread> #include <libdevcore/concurrent_queue.h> #include <libdevcore/Log.h> #include <libdevcore/SHA3.h> #include <libdevcore/Guards.h> #include <evmjit/JIT.h> #include <evmjit/libevmjit-cpp/Utils.h> #include "VMFactory.h" namespace dev { namespace eth { namespace { struct JitInfo: LogChannel { static const char* name() { return "JIT"; }; static const int verbosity = 11; }; using HitMap = std::unordered_map<h256, uint64_t>; HitMap& getHitMap() { static HitMap s_hitMap; return s_hitMap; } struct JitTask { bytes code; h256 codeHash; static JitTask createStopSentinel() { return JitTask(); } bool isStopSentinel() { assert((!code.empty() || !codeHash) && "'empty code => empty hash' invariand failed"); return code.empty(); } }; class JitWorker { std::thread m_worker; concurrent_queue<JitTask> m_queue; void work() { clog(JitInfo) << "JIT worker started."; JitTask task; while (!(task = m_queue.pop()).isStopSentinel()) { clog(JitInfo) << "Compilation... " << task.codeHash; evmjit::JIT::compile(task.code.data(), task.code.size(), eth2jit(task.codeHash)); clog(JitInfo) << " ...finished " << task.codeHash; } clog(JitInfo) << "JIT worker finished."; } public: JitWorker() noexcept: m_worker([this]{ work(); }) {} ~JitWorker() { push(JitTask::createStopSentinel()); m_worker.join(); } void push(JitTask&& _task) { m_queue.push(std::move(_task)); } }; } bytesConstRef SmartVM::execImpl(u256& io_gas, ExtVMFace& _ext, OnOpFunc const& _onOp) { auto codeHash = _ext.codeHash; auto vmKind = VMKind::Interpreter; // default VM // Jitted EVM code already in memory? if (evmjit::JIT::isCodeReady(eth2jit(codeHash))) { clog(JitInfo) << "JIT: " << codeHash; vmKind = VMKind::JIT; } else { static JitWorker s_worker; // Check EVM code hit count static const uint64_t c_hitTreshold = 2; auto& hits = getHitMap()[codeHash]; ++hits; if (hits == c_hitTreshold) { clog(JitInfo) << "Schedule: " << codeHash; s_worker.push({_ext.code, codeHash}); } clog(JitInfo) << "Interpreter: " << codeHash; } // TODO: Selected VM must be kept only because it returns reference to its internal memory. // VM implementations should be stateless, without escaping memory reference. m_selectedVM = VMFactory::create(vmKind); return m_selectedVM->execImpl(io_gas, _ext, _onOp); } } } #endif <commit_msg>Fix empty EVM code in SmartVM.<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/>. */ // SmartVM is only available if EVM JIT is enabled #if ETH_EVMJIT #include "SmartVM.h" #include <unordered_map> #include <thread> #include <libdevcore/concurrent_queue.h> #include <libdevcore/Log.h> #include <libdevcore/SHA3.h> #include <libdevcore/Guards.h> #include <evmjit/JIT.h> #include <evmjit/libevmjit-cpp/Utils.h> #include "VMFactory.h" namespace dev { namespace eth { namespace { struct JitInfo: LogChannel { static const char* name() { return "JIT"; }; static const int verbosity = 11; }; using HitMap = std::unordered_map<h256, uint64_t>; HitMap& getHitMap() { static HitMap s_hitMap; return s_hitMap; } struct JitTask { bytes code; h256 codeHash; static JitTask createStopSentinel() { return JitTask(); } bool isStopSentinel() { assert((!code.empty() || !codeHash) && "'empty code => empty hash' invariant failed"); return code.empty(); } }; class JitWorker { std::thread m_worker; concurrent_queue<JitTask> m_queue; void work() { clog(JitInfo) << "JIT worker started."; JitTask task; while (!(task = m_queue.pop()).isStopSentinel()) { clog(JitInfo) << "Compilation... " << task.codeHash; evmjit::JIT::compile(task.code.data(), task.code.size(), eth2jit(task.codeHash)); clog(JitInfo) << " ...finished " << task.codeHash; } clog(JitInfo) << "JIT worker finished."; } public: JitWorker() noexcept: m_worker([this]{ work(); }) {} ~JitWorker() { push(JitTask::createStopSentinel()); m_worker.join(); } void push(JitTask&& _task) { m_queue.push(std::move(_task)); } }; } bytesConstRef SmartVM::execImpl(u256& io_gas, ExtVMFace& _ext, OnOpFunc const& _onOp) { auto codeHash = _ext.codeHash; auto vmKind = VMKind::Interpreter; // default VM // Jitted EVM code already in memory? if (evmjit::JIT::isCodeReady(eth2jit(codeHash))) { clog(JitInfo) << "JIT: " << codeHash; vmKind = VMKind::JIT; } else if (!_ext.code.empty()) // This check is needed for VM tests { static JitWorker s_worker; // Check EVM code hit count static const uint64_t c_hitTreshold = 2; auto& hits = getHitMap()[codeHash]; ++hits; if (hits == c_hitTreshold) { clog(JitInfo) << "Schedule: " << codeHash; s_worker.push({_ext.code, codeHash}); } clog(JitInfo) << "Interpreter: " << codeHash; } // TODO: Selected VM must be kept only because it returns reference to its internal memory. // VM implementations should be stateless, without escaping memory reference. m_selectedVM = VMFactory::create(vmKind); return m_selectedVM->execImpl(io_gas, _ext, _onOp); } } } #endif <|endoftext|>
<commit_before>#include "reactor_facility.h" namespace reactor { ReactorFacility::ReactorFacility(cyclus::Context* ctx) : cyclus::Facility(ctx) { cycle_end_ = ctx->time(); }; std::string ReactorFacility::str() { return Facility::str(); } void ReactorFacility::Tick() { if(fuel_library_.name.size() == 0){ std::ifstream inf(libraries[0] +"/manifest.txt"); std::string line; std::string iso_name; fuel_library_.name = libraries[0]; while(getline(inf, line)){ std::istringstream iss(line); isoInformation iso; iss >> iso_name; iso.name = atoi(iso_name.c_str()); iso.region = 0; iso.fraction.push_back(0); fuel_library_.iso.push_back(iso); } fuel_library_.base_flux = flux_finder(fuel_library_.name); fuel_library_.base_mass = core_mass; fuel_library_.base_power = generated_power; fuel_library_.batch_fluence = 0; if (libraries.size() == 1){ DataReader2(fuel_library_.name, fuel_library_.iso); } else { ///interpolation stuff } core_ = std::vector<fuelBundle>(batches); for(int i = 0; i < core_.size(); i++){ core_[i] = fuel_library_; } } } void ReactorFacility::Tock() { cyclus::Context* ctx = context(); if (ctx->time() != cycle_end_) return; // Pop materials out of inventory std::vector<cyclus::Material::Ptr> manifest; manifest = cyclus::ResCast<cyclus::Material>(inventory.PopN(inventory.count())); // convert materials into fuel bundles cyclus::CompMap comp; cyclus::CompMap::iterator it; while(core_.size() < batches){ fuelBundle bundle; bundle = fuel_library_; core_.push_back(bundle); } /*for(int i = 0; i < core_.size(); i++){ int j = 0; while (core_[i].iso[0].fluence[j] < core_[i].batch_fluence){ j++; } std::cout << intpol(core_[i].iso[0].iso_vector[1].mass[j], core_[i].iso[0].iso_vector[1].mass[j+1], core_[i].iso[0].fluence[j], core_[i].iso[0].fluence[j+1], core_[i].batch_fluence)*core_[i].iso[0].fraction[0] << std::endl; }*/ for(int i = 0; i < manifest.size(); i++){ comp = manifest[i]->comp()->mass(); int j = 0; int fl_iso = core_[i].iso[j].name; int comp_iso; for (it = comp.begin(); it != comp.end(); ++it){ comp_iso = pyne::nucname::zzaaam(it->first); if(fl_iso < comp_iso) { while(fl_iso < comp_iso && j < core_[i].iso.size()-1){ fl_iso = core_[i].iso[j++].name; } } if(fl_iso == comp_iso){ if (core_[i].batch_fluence == 0){ core_[i].iso[j].fraction[0] = it->second; std::cout << fl_iso << " " << it->second <<std::endl; } j+=1; fl_iso = core_[i].iso[j].name; } } } /// reorder fuelBundles. std::vector<fuelBundle> temp_core; k_test = 0 for (int i = 0; i < batches; i++){ for (int j = 0; j < batches-i; j++){ } } /// pass fuel bundles to burn-up calc std::vector<fuelInfo> reactor_return; reactor_return = burnupcalc(core_, nonleakage, 0.0001); /// convert fuel bundles into materials int i = 0; for(int i = 0; i < reactor_return.size(); i++){ core_[i].batch_fluence = reactor_return[i].fluence; cyclus::CompMap out_comp; for(std::map<int, double>::iterator c = reactor_return[i].burnup_info.begin(); c != reactor_return[i].burnup_info.end(); ++c){ if(c->second < 0){ out_comp[pyne::nucname::zzaaam_to_id(c->first)] = 0; } else { out_comp[pyne::nucname::zzaaam_to_id(c->first)] = c->second; } } manifest[i]->Transmute(cyclus::Composition::CreateFromMass(out_comp)); inventory.Push(manifest[i]); } /*for(int i = 0; i < core_.size(); i++){ int j = 0; while (core_[i].iso[0].fluence[j] < core_[i].batch_fluence){ j++; } std::cout << intpol(core_[i].iso[0].iso_vector[1].mass[j], core_[i].iso[0].iso_vector[1].mass[j+1], core_[i].iso[0].fluence[j], core_[i].iso[0].fluence[j+1], core_[i].batch_fluence)*core_[i].iso[0].fraction[0] << std::endl; }*/ // cycle end update cycle_end_ = ctx->time() + ceil(reactor_return[reactor_return.size()-1].fluence/(86400*fuel_library_.base_flux*28)); std::cout << "Time :: " <<reactor_return[reactor_return.size()-1].fluence/(86400*fuel_library_.base_flux) << std::endl; } std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr> ReactorFacility::GetMatlRequests() { using cyclus::RequestPortfolio; using cyclus::Material; using cyclus::Composition; using cyclus::CompMap; using cyclus::CapacityConstraint; std::set<RequestPortfolio<Material>::Ptr> ports; cyclus::Context* ctx = context(); if (ctx->time() != cycle_end_){ return ports; } CompMap cm; Material::Ptr target = Material::CreateUntracked(core_mass/batches, Composition::CreateFromAtom(cm)); RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>()); double qty; if(inventory.count() == 0){ for(int i = 0; i < batches; i++){ port->AddRequest(target, this, in_commods[i+1]); } qty = core_mass; } else { port->AddRequest(target, this, in_commods[0]); qty = core_mass/batches; } CapacityConstraint<Material> cc(qty); port->AddConstraint(cc); ports.insert(port); return ports; } // MatlBids // std::set<cyclus::BidPortfolio<cyclus::Material>::Ptr> ReactorFacility::GetMatlBids( cyclus::CommodMap<cyclus::Material>::type& commod_requests) { using cyclus::BidPortfolio; using cyclus::CapacityConstraint; using cyclus::Converter; using cyclus::Material; using cyclus::Request; cyclus::Context* ctx = context(); std::set<BidPortfolio<Material>::Ptr> ports; if (ctx->time() != cycle_end_){ return ports; } // respond to all requests of my commodity if (inventory.count() == 0){return ports;} std::vector<cyclus::Material::Ptr> manifest; manifest = cyclus::ResCast<Material>(inventory.PopN(inventory.count())); BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>()); std::vector<Request<Material>*>& requests = commod_requests[out_commod]; std::vector<Request<Material>*>::iterator it; for (it = requests.begin(); it != requests.end(); ++it) { Request<Material>* req = *it; if (req->commodity() == out_commod) { Material::Ptr offer = Material::CreateUntracked(core_mass/batches, manifest[0]->comp()); port->AddBid(req, offer, this); } } inventory.PushAll(manifest); CapacityConstraint<Material> cc(core_mass/batches); port->AddConstraint(cc); ports.insert(port); return ports; } void ReactorFacility::AcceptMatlTrades( const std::vector< std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >& responses) { std::vector<std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >::const_iterator it; for (it = responses.begin(); it != responses.end(); ++it) { inventory.Push(it->second); } } void ReactorFacility::GetMatlTrades( const std::vector< cyclus::Trade<cyclus::Material> >& trades, std::vector<std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >& responses) { using cyclus::Material; using cyclus::Trade; std::vector< cyclus::Trade<cyclus::Material> >::const_iterator it; cyclus::Material::Ptr discharge = cyclus::ResCast<Material>(inventory.Pop()); core_.erase(core_.begin()); for (it = trades.begin(); it != trades.end(); ++it) { responses.push_back(std::make_pair(*it, discharge)); } } extern "C" cyclus::Agent* ConstructReactorFacility(cyclus::Context* ctx) { return new ReactorFacility(ctx); } } <commit_msg>new branch<commit_after>#include "reactor_facility.h" namespace reactor { ReactorFacility::ReactorFacility(cyclus::Context* ctx) : cyclus::Facility(ctx) { cycle_end_ = ctx->time(); }; std::string ReactorFacility::str() { return Facility::str(); } void ReactorFacility::Tick() { if(fuel_library_.name.size() == 0){ std::ifstream inf(libraries[0] +"/manifest.txt"); std::string line; std::string iso_name; fuel_library_.name = libraries[0]; while(getline(inf, line)){ std::istringstream iss(line); isoInformation iso; iss >> iso_name; iso.name = atoi(iso_name.c_str()); iso.region = 0; iso.fraction.push_back(0); fuel_library_.iso.push_back(iso); } fuel_library_.base_flux = flux_finder(fuel_library_.name); fuel_library_.base_mass = core_mass; fuel_library_.base_power = generated_power; fuel_library_.batch_fluence = 0; if (libraries.size() == 1){ DataReader2(fuel_library_.name, fuel_library_.iso); } else { ///interpolation stuff } core_ = std::vector<fuelBundle>(batches); for(int i = 0; i < core_.size(); i++){ core_[i] = fuel_library_; } } } void ReactorFacility::Tock() { cyclus::Context* ctx = context(); if (ctx->time() != cycle_end_) return; // Pop materials out of inventory std::vector<cyclus::Material::Ptr> manifest; manifest = cyclus::ResCast<cyclus::Material>(inventory.PopN(inventory.count())); // convert materials into fuel bundles cyclus::CompMap comp; cyclus::CompMap::iterator it; while(core_.size() < batches){ fuelBundle bundle; bundle = fuel_library_; core_.push_back(bundle); } /*for(int i = 0; i < core_.size(); i++){ int j = 0; while (core_[i].iso[0].fluence[j] < core_[i].batch_fluence){ j++; } std::cout << intpol(core_[i].iso[0].iso_vector[1].mass[j], core_[i].iso[0].iso_vector[1].mass[j+1], core_[i].iso[0].fluence[j], core_[i].iso[0].fluence[j+1], core_[i].batch_fluence)*core_[i].iso[0].fraction[0] << std::endl; }*/ for(int i = 0; i < manifest.size(); i++){ comp = manifest[i]->comp()->mass(); int j = 0; int fl_iso = core_[i].iso[j].name; int comp_iso; for (it = comp.begin(); it != comp.end(); ++it){ comp_iso = pyne::nucname::zzaaam(it->first); if(fl_iso < comp_iso) { while(fl_iso < comp_iso && j < core_[i].iso.size()-1){ fl_iso = core_[i].iso[j++].name; } } if(fl_iso == comp_iso){ if (core_[i].batch_fluence == 0){ core_[i].iso[j].fraction[0] = it->second; std::cout << fl_iso << " " << it->second <<std::endl; } j+=1; fl_iso = core_[i].iso[j].name; } } } /// reorder fuelBundles. std::vector<fuelBundle> temp_core(batch); std::vector<isoInformation> temp_isos(batches); k_test = 0 for (int i = 0; i < batches; i++){ temp_isos.push_back(regioncollapse(core_[i], 1)); } for(int j = 0; j < batches; j++){ for (int i = 0; i < temp_isos; i++){ if (k_test < temp_isos[i].neutron_prod[1]/temp_isos[i].neutron_dest[1]){ k_test = temp_isos[i].neutron_prod[1]/temp_isos[i].neutron_dest[1]; temp_core[i] = core_[i] } } } /// pass fuel bundles to burn-up calc std::vector<fuelInfo> reactor_return; reactor_return = burnupcalc(core_, nonleakage, 0.0001); /// convert fuel bundles into materials int i = 0; for(int i = 0; i < reactor_return.size(); i++){ core_[i].batch_fluence = reactor_return[i].fluence; cyclus::CompMap out_comp; for(std::map<int, double>::iterator c = reactor_return[i].burnup_info.begin(); c != reactor_return[i].burnup_info.end(); ++c){ if(c->second < 0){ out_comp[pyne::nucname::zzaaam_to_id(c->first)] = 0; } else { out_comp[pyne::nucname::zzaaam_to_id(c->first)] = c->second; } } manifest[i]->Transmute(cyclus::Composition::CreateFromMass(out_comp)); inventory.Push(manifest[i]); } /*for(int i = 0; i < core_.size(); i++){ int j = 0; while (core_[i].iso[0].fluence[j] < core_[i].batch_fluence){ j++; } std::cout << intpol(core_[i].iso[0].iso_vector[1].mass[j], core_[i].iso[0].iso_vector[1].mass[j+1], core_[i].iso[0].fluence[j], core_[i].iso[0].fluence[j+1], core_[i].batch_fluence)*core_[i].iso[0].fraction[0] << std::endl; }*/ // cycle end update cycle_end_ = ctx->time() + ceil(reactor_return[reactor_return.size()-1].fluence/(86400*fuel_library_.base_flux*28)); std::cout << "Time :: " <<reactor_return[reactor_return.size()-1].fluence/(86400*fuel_library_.base_flux) << std::endl; } std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr> ReactorFacility::GetMatlRequests() { using cyclus::RequestPortfolio; using cyclus::Material; using cyclus::Composition; using cyclus::CompMap; using cyclus::CapacityConstraint; std::set<RequestPortfolio<Material>::Ptr> ports; cyclus::Context* ctx = context(); if (ctx->time() != cycle_end_){ return ports; } CompMap cm; Material::Ptr target = Material::CreateUntracked(core_mass/batches, Composition::CreateFromAtom(cm)); RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>()); double qty; if(inventory.count() == 0){ for(int i = 0; i < batches; i++){ port->AddRequest(target, this, in_commods[i+1]); } qty = core_mass; } else { port->AddRequest(target, this, in_commods[0]); qty = core_mass/batches; } CapacityConstraint<Material> cc(qty); port->AddConstraint(cc); ports.insert(port); return ports; } // MatlBids // std::set<cyclus::BidPortfolio<cyclus::Material>::Ptr> ReactorFacility::GetMatlBids( cyclus::CommodMap<cyclus::Material>::type& commod_requests) { using cyclus::BidPortfolio; using cyclus::CapacityConstraint; using cyclus::Converter; using cyclus::Material; using cyclus::Request; cyclus::Context* ctx = context(); std::set<BidPortfolio<Material>::Ptr> ports; if (ctx->time() != cycle_end_){ return ports; } // respond to all requests of my commodity if (inventory.count() == 0){return ports;} std::vector<cyclus::Material::Ptr> manifest; manifest = cyclus::ResCast<Material>(inventory.PopN(inventory.count())); BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>()); std::vector<Request<Material>*>& requests = commod_requests[out_commod]; std::vector<Request<Material>*>::iterator it; for (it = requests.begin(); it != requests.end(); ++it) { Request<Material>* req = *it; if (req->commodity() == out_commod) { Material::Ptr offer = Material::CreateUntracked(core_mass/batches, manifest[0]->comp()); port->AddBid(req, offer, this); } } inventory.PushAll(manifest); CapacityConstraint<Material> cc(core_mass/batches); port->AddConstraint(cc); ports.insert(port); return ports; } void ReactorFacility::AcceptMatlTrades( const std::vector< std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >& responses) { std::vector<std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >::const_iterator it; for (it = responses.begin(); it != responses.end(); ++it) { inventory.Push(it->second); } } void ReactorFacility::GetMatlTrades( const std::vector< cyclus::Trade<cyclus::Material> >& trades, std::vector<std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >& responses) { using cyclus::Material; using cyclus::Trade; std::vector< cyclus::Trade<cyclus::Material> >::const_iterator it; cyclus::Material::Ptr discharge = cyclus::ResCast<Material>(inventory.Pop()); core_.erase(core_.begin()); for (it = trades.begin(); it != trades.end(); ++it) { responses.push_back(std::make_pair(*it, discharge)); } } extern "C" cyclus::Agent* ConstructReactorFacility(cyclus::Context* ctx) { return new ReactorFacility(ctx); } } <|endoftext|>
<commit_before>// Module: Log4CPLUS // File: hierarchy.cxx // Created: 6/2001 // Author: Tad E. Smith // // // Copyright 2001-2010 Tad E. Smith // // 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 <log4cplus/hierarchy.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/spi/loggerimpl.h> #include <log4cplus/spi/rootlogger.h> #include <log4cplus/thread/syncprims-pub-impl.h> #include <utility> namespace log4cplus { ////////////////////////////////////////////////////////////////////////////// // File "Local" methods ////////////////////////////////////////////////////////////////////////////// namespace { static bool startsWith(tstring const & teststr, tstring const & substr) { bool val = false; tstring::size_type const len = substr.length(); if (teststr.length() > len) val = teststr.compare (0, len, substr) == 0; return val; } } ////////////////////////////////////////////////////////////////////////////// // Hierarchy static declarations ////////////////////////////////////////////////////////////////////////////// const LogLevel Hierarchy::DISABLE_OFF = -1; const LogLevel Hierarchy::DISABLE_OVERRIDE = -2; ////////////////////////////////////////////////////////////////////////////// // Hierarchy ctor and dtor ////////////////////////////////////////////////////////////////////////////// Hierarchy::Hierarchy() : defaultFactory(new DefaultLoggerFactory()) , root(NULL) // Don't disable any LogLevel level by default. , disableValue(DISABLE_OFF) , emittedNoAppenderWarning(false) { root = Logger( new spi::RootLogger(*this, DEBUG_LOG_LEVEL) ); } Hierarchy::~Hierarchy() { shutdown(); } ////////////////////////////////////////////////////////////////////////////// // Hierarchy public methods ////////////////////////////////////////////////////////////////////////////// void Hierarchy::clear() { thread::MutexGuard guard (hashtable_mutex); provisionNodes.erase(provisionNodes.begin(), provisionNodes.end()); loggerPtrs.erase(loggerPtrs.begin(), loggerPtrs.end()); } bool Hierarchy::exists(const tstring& name) { thread::MutexGuard guard (hashtable_mutex); LoggerMap::iterator it = loggerPtrs.find(name); return it != loggerPtrs.end(); } void Hierarchy::disable(const tstring& loglevelStr) { if(disableValue != DISABLE_OVERRIDE) { disableValue = getLogLevelManager().fromString(loglevelStr); } } void Hierarchy::disable(LogLevel ll) { if(disableValue != DISABLE_OVERRIDE) { disableValue = ll; } } void Hierarchy::disableAll() { disable(FATAL_LOG_LEVEL); } void Hierarchy::disableDebug() { disable(DEBUG_LOG_LEVEL); } void Hierarchy::disableInfo() { disable(INFO_LOG_LEVEL); } void Hierarchy::enableAll() { disableValue = DISABLE_OFF; } Logger Hierarchy::getInstance(const tstring& name) { return getInstance(name, *defaultFactory); } Logger Hierarchy::getInstance(const tstring& name, spi::LoggerFactory& factory) { thread::MutexGuard guard (hashtable_mutex); return getInstanceImpl(name, factory); } LoggerList Hierarchy::getCurrentLoggers() { LoggerList ret; { thread::MutexGuard guard (hashtable_mutex); initializeLoggerList(ret); } return ret; } bool Hierarchy::isDisabled(LogLevel level) { return disableValue >= level; } Logger Hierarchy::getRoot() const { return root; } void Hierarchy::resetConfiguration() { getRoot().setLogLevel(DEBUG_LOG_LEVEL); disableValue = DISABLE_OFF; shutdown(); LoggerList loggers = getCurrentLoggers(); for (LoggerList::iterator it = loggers.begin (); it != loggers.end(); ++it) { Logger & logger = *it; logger.setLogLevel(NOT_SET_LOG_LEVEL); logger.setAdditivity(true); } } void Hierarchy::setLoggerFactory(std::auto_ptr<spi::LoggerFactory> factory) { defaultFactory = factory; } spi::LoggerFactory * Hierarchy::getLoggerFactory() { return defaultFactory.get(); } void Hierarchy::shutdown() { LoggerList loggers = getCurrentLoggers(); // begin by closing nested appenders // then, remove all appenders root.closeNestedAppenders(); root.removeAllAppenders(); // repeat for (LoggerList::iterator it = loggers.begin(); it != loggers.end(); ++it) { Logger & logger = *it; logger.closeNestedAppenders(); logger.removeAllAppenders(); } } ////////////////////////////////////////////////////////////////////////////// // Hierarchy private methods ////////////////////////////////////////////////////////////////////////////// Logger Hierarchy::getInstanceImpl(const tstring& name, spi::LoggerFactory& factory) { if (name.empty ()) return root; Logger logger; LoggerMap::iterator lm_it = loggerPtrs.find(name); if (lm_it != loggerPtrs.end()) logger = lm_it->second; else { // Need to create a new logger logger = factory.makeNewLoggerInstance(name, *this); bool inserted = loggerPtrs.insert(std::make_pair(name, logger)).second; if (! inserted) { helpers::getLogLog().error( LOG4CPLUS_TEXT("Hierarchy::getInstanceImpl()- Insert failed"), true); } ProvisionNodeMap::iterator pnm_it = provisionNodes.find(name); if (pnm_it != provisionNodes.end()) { updateChildren(pnm_it->second, logger); bool deleted = (provisionNodes.erase(name) > 0); if (! deleted) { helpers::getLogLog().error( LOG4CPLUS_TEXT("Hierarchy::getInstanceImpl()- Delete failed"), true); } } updateParents(logger); } return logger; } void Hierarchy::initializeLoggerList(LoggerList& list) const { for(LoggerMap::const_iterator it=loggerPtrs.begin(); it!= loggerPtrs.end(); ++it) { list.push_back((*it).second); } } void Hierarchy::updateParents(Logger const & logger) { tstring const & name = logger.getName(); std::size_t const length = name.length(); bool parentFound = false; tstring substr; // if name = "w.x.y.z", loop thourgh "w.x.y", "w.x" and "w", but not "w.x.y.z" for(std::size_t i=name.find_last_of(LOG4CPLUS_TEXT('.'), length-1); i != tstring::npos && i > 0; i = name.find_last_of(LOG4CPLUS_TEXT('.'), i-1)) { substr.assign (name, 0, i); LoggerMap::iterator it = loggerPtrs.find(substr); if(it != loggerPtrs.end()) { parentFound = true; logger.value->parent = it->second.value; break; // no need to update the ancestors of the closest ancestor } else { ProvisionNodeMap::iterator it2 = provisionNodes.find(substr); if(it2 != provisionNodes.end()) { it2->second.push_back(logger); } else { ProvisionNode node; node.push_back(logger); std::pair<ProvisionNodeMap::iterator, bool> tmp = provisionNodes.insert(std::make_pair(substr, node)); //bool inserted = provisionNodes.insert(std::make_pair(substr, node)).second; if(!tmp.second) { helpers::getLogLog().error( LOG4CPLUS_TEXT("Hierarchy::updateParents()- Insert failed"), true); } } } // end if Logger found } // end for loop if(!parentFound) { logger.value->parent = root.value; } } void Hierarchy::updateChildren(ProvisionNode& pn, Logger const & logger) { for(ProvisionNode::iterator it=pn.begin(); it!=pn.end(); ++it) { Logger& c = *it; // Unless this child already points to a correct (lower) parent, // make logger.parent point to c.parent and c.parent to logger. if( !startsWith(c.value->parent->getName(), logger.getName()) ) { logger.value->parent = c.value->parent; c.value->parent = logger.value; } } } } // namespace log4cplus <commit_msg>hierarchy.cxx: Rework last patch to allow NRVO.<commit_after>// Module: Log4CPLUS // File: hierarchy.cxx // Created: 6/2001 // Author: Tad E. Smith // // // Copyright 2001-2010 Tad E. Smith // // 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 <log4cplus/hierarchy.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/spi/loggerimpl.h> #include <log4cplus/spi/rootlogger.h> #include <log4cplus/thread/syncprims-pub-impl.h> #include <utility> namespace log4cplus { ////////////////////////////////////////////////////////////////////////////// // File "Local" methods ////////////////////////////////////////////////////////////////////////////// namespace { static bool startsWith(tstring const & teststr, tstring const & substr) { bool val = false; tstring::size_type const len = substr.length(); if (teststr.length() > len) val = teststr.compare (0, len, substr) == 0; return val; } } ////////////////////////////////////////////////////////////////////////////// // Hierarchy static declarations ////////////////////////////////////////////////////////////////////////////// const LogLevel Hierarchy::DISABLE_OFF = -1; const LogLevel Hierarchy::DISABLE_OVERRIDE = -2; ////////////////////////////////////////////////////////////////////////////// // Hierarchy ctor and dtor ////////////////////////////////////////////////////////////////////////////// Hierarchy::Hierarchy() : defaultFactory(new DefaultLoggerFactory()) , root(NULL) // Don't disable any LogLevel level by default. , disableValue(DISABLE_OFF) , emittedNoAppenderWarning(false) { root = Logger( new spi::RootLogger(*this, DEBUG_LOG_LEVEL) ); } Hierarchy::~Hierarchy() { shutdown(); } ////////////////////////////////////////////////////////////////////////////// // Hierarchy public methods ////////////////////////////////////////////////////////////////////////////// void Hierarchy::clear() { thread::MutexGuard guard (hashtable_mutex); provisionNodes.erase(provisionNodes.begin(), provisionNodes.end()); loggerPtrs.erase(loggerPtrs.begin(), loggerPtrs.end()); } bool Hierarchy::exists(const tstring& name) { thread::MutexGuard guard (hashtable_mutex); LoggerMap::iterator it = loggerPtrs.find(name); return it != loggerPtrs.end(); } void Hierarchy::disable(const tstring& loglevelStr) { if(disableValue != DISABLE_OVERRIDE) { disableValue = getLogLevelManager().fromString(loglevelStr); } } void Hierarchy::disable(LogLevel ll) { if(disableValue != DISABLE_OVERRIDE) { disableValue = ll; } } void Hierarchy::disableAll() { disable(FATAL_LOG_LEVEL); } void Hierarchy::disableDebug() { disable(DEBUG_LOG_LEVEL); } void Hierarchy::disableInfo() { disable(INFO_LOG_LEVEL); } void Hierarchy::enableAll() { disableValue = DISABLE_OFF; } Logger Hierarchy::getInstance(const tstring& name) { return getInstance(name, *defaultFactory); } Logger Hierarchy::getInstance(const tstring& name, spi::LoggerFactory& factory) { thread::MutexGuard guard (hashtable_mutex); return getInstanceImpl(name, factory); } LoggerList Hierarchy::getCurrentLoggers() { LoggerList ret; { thread::MutexGuard guard (hashtable_mutex); initializeLoggerList(ret); } return ret; } bool Hierarchy::isDisabled(LogLevel level) { return disableValue >= level; } Logger Hierarchy::getRoot() const { return root; } void Hierarchy::resetConfiguration() { getRoot().setLogLevel(DEBUG_LOG_LEVEL); disableValue = DISABLE_OFF; shutdown(); LoggerList loggers = getCurrentLoggers(); for (LoggerList::iterator it = loggers.begin (); it != loggers.end(); ++it) { Logger & logger = *it; logger.setLogLevel(NOT_SET_LOG_LEVEL); logger.setAdditivity(true); } } void Hierarchy::setLoggerFactory(std::auto_ptr<spi::LoggerFactory> factory) { defaultFactory = factory; } spi::LoggerFactory * Hierarchy::getLoggerFactory() { return defaultFactory.get(); } void Hierarchy::shutdown() { LoggerList loggers = getCurrentLoggers(); // begin by closing nested appenders // then, remove all appenders root.closeNestedAppenders(); root.removeAllAppenders(); // repeat for (LoggerList::iterator it = loggers.begin(); it != loggers.end(); ++it) { Logger & logger = *it; logger.closeNestedAppenders(); logger.removeAllAppenders(); } } ////////////////////////////////////////////////////////////////////////////// // Hierarchy private methods ////////////////////////////////////////////////////////////////////////////// Logger Hierarchy::getInstanceImpl(const tstring& name, spi::LoggerFactory& factory) { Logger logger; LoggerMap::iterator lm_it; if (name.empty ()) logger = root; else if ((lm_it = loggerPtrs.find(name)) != loggerPtrs.end()) logger = lm_it->second; else { // Need to create a new logger logger = factory.makeNewLoggerInstance(name, *this); bool inserted = loggerPtrs.insert(std::make_pair(name, logger)).second; if (! inserted) { helpers::getLogLog().error( LOG4CPLUS_TEXT("Hierarchy::getInstanceImpl()- Insert failed"), true); } ProvisionNodeMap::iterator pnm_it = provisionNodes.find(name); if (pnm_it != provisionNodes.end()) { updateChildren(pnm_it->second, logger); bool deleted = (provisionNodes.erase(name) > 0); if (! deleted) { helpers::getLogLog().error( LOG4CPLUS_TEXT("Hierarchy::getInstanceImpl()- Delete failed"), true); } } updateParents(logger); } return logger; } void Hierarchy::initializeLoggerList(LoggerList& list) const { for(LoggerMap::const_iterator it=loggerPtrs.begin(); it!= loggerPtrs.end(); ++it) { list.push_back((*it).second); } } void Hierarchy::updateParents(Logger const & logger) { tstring const & name = logger.getName(); std::size_t const length = name.length(); bool parentFound = false; tstring substr; // if name = "w.x.y.z", loop thourgh "w.x.y", "w.x" and "w", but not "w.x.y.z" for(std::size_t i=name.find_last_of(LOG4CPLUS_TEXT('.'), length-1); i != tstring::npos && i > 0; i = name.find_last_of(LOG4CPLUS_TEXT('.'), i-1)) { substr.assign (name, 0, i); LoggerMap::iterator it = loggerPtrs.find(substr); if(it != loggerPtrs.end()) { parentFound = true; logger.value->parent = it->second.value; break; // no need to update the ancestors of the closest ancestor } else { ProvisionNodeMap::iterator it2 = provisionNodes.find(substr); if(it2 != provisionNodes.end()) { it2->second.push_back(logger); } else { ProvisionNode node; node.push_back(logger); std::pair<ProvisionNodeMap::iterator, bool> tmp = provisionNodes.insert(std::make_pair(substr, node)); //bool inserted = provisionNodes.insert(std::make_pair(substr, node)).second; if(!tmp.second) { helpers::getLogLog().error( LOG4CPLUS_TEXT("Hierarchy::updateParents()- Insert failed"), true); } } } // end if Logger found } // end for loop if(!parentFound) { logger.value->parent = root.value; } } void Hierarchy::updateChildren(ProvisionNode& pn, Logger const & logger) { for(ProvisionNode::iterator it=pn.begin(); it!=pn.end(); ++it) { Logger& c = *it; // Unless this child already points to a correct (lower) parent, // make logger.parent point to c.parent and c.parent to logger. if( !startsWith(c.value->parent->getName(), logger.getName()) ) { logger.value->parent = c.value->parent; c.value->parent = logger.value; } } } } // namespace log4cplus <|endoftext|>
<commit_before>#include "highlight.hpp" #include "CgStr.hpp" #include "config.hpp" #include "debug.hpp" #include <cstring> #include <iostream> using namespace synth; unsigned const kMaxRefRecursion = 16; bool synth::isTypeAliasCursorKind(CXCursorKind k) { return k == CXCursor_TypeAliasDecl || k == CXCursor_TypeAliasTemplateDecl || k == CXCursor_TypedefDecl; } bool synth::isTypeCursorKind(CXCursorKind k) { SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum") switch (k) { case CXCursor_ClassDecl: case CXCursor_ClassTemplate: case CXCursor_ClassTemplatePartialSpecialization: case CXCursor_StructDecl: case CXCursor_UnionDecl: case CXCursor_EnumDecl: case CXCursor_ObjCInterfaceDecl: case CXCursor_ObjCCategoryDecl: case CXCursor_ObjCProtocolDecl: case CXCursor_ObjCImplementationDecl: case CXCursor_TemplateTypeParameter: case CXCursor_TemplateTemplateParameter: case CXCursor_TypeRef: case CXCursor_ObjCSuperClassRef: case CXCursor_ObjCProtocolRef: case CXCursor_ObjCClassRef: case CXCursor_CXXBaseSpecifier: return true; default: return isTypeAliasCursorKind(k); } SYNTH_DISCLANGWARN_END } bool synth::isFunctionCursorKind(CXCursorKind k) { SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum") switch (k) { case CXCursor_FunctionDecl: case CXCursor_ObjCInstanceMethodDecl: case CXCursor_ObjCClassMethodDecl: case CXCursor_CXXMethod: case CXCursor_FunctionTemplate: case CXCursor_Constructor: case CXCursor_Destructor: case CXCursor_ConversionFunction: case CXCursor_OverloadedDeclRef: return true; default: return false; } SYNTH_DISCLANGWARN_END } static TokenAttributes getVarTokenAttributes(CXCursor cur) { if (clang_getCursorLinkage(cur) == CXLinkage_NoLinkage) return TokenAttributes::varLocal; if (clang_getCXXAccessSpecifier(cur) == CX_CXXInvalidAccessSpecifier) return TokenAttributes::varGlobal; if (clang_Cursor_getStorageClass(cur) == CX_SC_Static) return TokenAttributes::varStaticMember; return TokenAttributes::varNonstaticMember; } static TokenAttributes getIntTokenAttributes(boost::string_ref sp) { if (!sp.empty()) { if (sp.size() >= 2 && sp[0] == '0') { if (sp[1] == 'x' || sp[1] == 'X') return TokenAttributes::litNumIntHex; if (sp[1] == 'b' || sp[1] == 'B') return TokenAttributes::litNumIntBin; return TokenAttributes::litNumIntOct; } char suffix = sp[sp.size() - 1]; if (suffix == 'l' || suffix == 'L') return TokenAttributes::litNumIntDecLong; } return TokenAttributes::litNum; } static bool isBuiltinTypeKw(boost::string_ref t) { return t.starts_with("unsigned ") || t == "unsigned" || t.starts_with("signed ") || t == "signed" || t.starts_with("short ") || t == "short" || t.starts_with("long ") || t == "long" || t == "int" || t == "float" || t == "double" || t == "bool" || t == "char" || t == "char16_t" || t == "char32_t" || t == "wchar_t" || t == "void"; } static TokenAttributes getTokenAttributesImpl( CXToken tok, CXCursor cur, boost::string_ref sp, // token spelling CXTranslationUnit tu, unsigned recursionDepth) { CXCursorKind k = clang_getCursorKind(cur); CXTokenKind tk = clang_getTokenKind(tok); if (clang_isPreprocessing(k)) { if (k == CXCursor_InclusionDirective && sp != "include" && sp != "#") return TokenAttributes::preIncludeFile; return TokenAttributes::pre; } switch (tk) { case CXToken_Punctuation: if (k == CXCursor_BinaryOperator || k == CXCursor_UnaryOperator) return TokenAttributes::op; return TokenAttributes::punct; case CXToken_Comment: return TokenAttributes::cmmt; case CXToken_Literal: SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum") switch (k) { case CXCursor_ObjCStringLiteral: case CXCursor_StringLiteral: return TokenAttributes::litStr; case CXCursor_CharacterLiteral: return TokenAttributes::litChr; case CXCursor_FloatingLiteral: return TokenAttributes::litNumFlt; case CXCursor_IntegerLiteral: return getIntTokenAttributes(sp); case CXCursor_ImaginaryLiteral: return TokenAttributes::litNum; default: return TokenAttributes::lit; } SYNTH_DISCLANGWARN_END case CXToken_Keyword: { if (k == CXCursor_BinaryOperator || k == CXCursor_UnaryOperator) return TokenAttributes::opWord; if (k == CXCursor_CXXNullPtrLiteralExpr || k == CXCursor_CXXBoolLiteralExpr || k == CXCursor_ObjCBoolLiteralExpr ) { return TokenAttributes::litKw; } if (k == CXCursor_TypeRef || isBuiltinTypeKw(sp)) return TokenAttributes::tyBuiltin; if (clang_isDeclaration(k) || k == CXCursor_DeclStmt) return TokenAttributes::kwDecl; if (sp == "sizeof" || sp == "alignof") return TokenAttributes::opWord; if (sp == "this") return TokenAttributes::litKw; return TokenAttributes::kw; } case CXToken_Identifier: if (isTypeCursorKind(k)) return TokenAttributes::ty; if (isFunctionCursorKind(k)) return TokenAttributes::func; SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum") switch (k) { case CXCursor_MemberRef: case CXCursor_DeclRefExpr: case CXCursor_MemberRefExpr: case CXCursor_UsingDeclaration: case CXCursor_TemplateRef: { CXCursor refd = clang_getCursorReferenced(cur); bool recErr = recursionDepth > kMaxRefRecursion; if (recErr) { CgStr kindSp(clang_getCursorKindSpelling(k)); CgStr rKindSp(clang_getCursorKindSpelling( clang_getCursorKind(refd))); std::clog << "When trying to highlight token " << clang_getTokenExtent(tu, tok) << " " << sp << ":\n" << " Cursor " << clang_getCursorExtent(cur) << " " << kindSp << " references " << clang_getCursorExtent(refd) << " " << rKindSp << " Maximum depth exceeded with " << recursionDepth << ".\n"; return TokenAttributes::none; } if (clang_equalCursors(cur, refd)) return TokenAttributes::none; return getTokenAttributesImpl( tok, refd, sp, tu, recursionDepth + 1); } case CXCursor_ObjCPropertyDecl: return TokenAttributes::varNonstaticMember; // Sorta right. case CXCursor_ObjCIvarDecl: case CXCursor_FieldDecl: return TokenAttributes::varNonstaticMember; // TODO case CXCursor_EnumConstantDecl: case CXCursor_NonTypeTemplateParameter: return TokenAttributes::constant; case CXCursor_VarDecl: return getVarTokenAttributes(cur); case CXCursor_ParmDecl: return TokenAttributes::varLocal; case CXCursor_Namespace: case CXCursor_NamespaceAlias: case CXCursor_UsingDirective: case CXCursor_NamespaceRef: return TokenAttributes::namesp; case CXCursor_LabelStmt: return TokenAttributes::lbl; default: if (clang_isAttribute(k)) return TokenAttributes::attr; return TokenAttributes::none; } } SYNTH_DISCLANGWARN_END assert("unreachable" && false); return TokenAttributes::none; } TokenAttributes synth::getTokenAttributes( CXToken tok, CXCursor cur, boost::string_ref tokSpelling) { return getTokenAttributesImpl( tok, cur, tokSpelling, clang_Cursor_getTranslationUnit(cur), 0); } <commit_msg>highlight: More agressively highlight all references.<commit_after>#include "highlight.hpp" #include "CgStr.hpp" #include "config.hpp" #include "debug.hpp" #include <cstring> #include <iostream> using namespace synth; unsigned const kMaxRefRecursion = 16; bool synth::isTypeAliasCursorKind(CXCursorKind k) { return k == CXCursor_TypeAliasDecl || k == CXCursor_TypeAliasTemplateDecl || k == CXCursor_TypedefDecl; } bool synth::isTypeCursorKind(CXCursorKind k) { SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum") switch (k) { case CXCursor_ClassDecl: case CXCursor_ClassTemplate: case CXCursor_ClassTemplatePartialSpecialization: case CXCursor_StructDecl: case CXCursor_UnionDecl: case CXCursor_EnumDecl: case CXCursor_ObjCInterfaceDecl: case CXCursor_ObjCCategoryDecl: case CXCursor_ObjCProtocolDecl: case CXCursor_ObjCImplementationDecl: case CXCursor_TemplateTypeParameter: case CXCursor_TemplateTemplateParameter: case CXCursor_TypeRef: case CXCursor_ObjCSuperClassRef: case CXCursor_ObjCProtocolRef: case CXCursor_ObjCClassRef: case CXCursor_CXXBaseSpecifier: return true; default: return isTypeAliasCursorKind(k); } SYNTH_DISCLANGWARN_END } bool synth::isFunctionCursorKind(CXCursorKind k) { SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum") switch (k) { case CXCursor_FunctionDecl: case CXCursor_ObjCInstanceMethodDecl: case CXCursor_ObjCClassMethodDecl: case CXCursor_CXXMethod: case CXCursor_FunctionTemplate: case CXCursor_Constructor: case CXCursor_Destructor: case CXCursor_ConversionFunction: case CXCursor_OverloadedDeclRef: return true; default: return false; } SYNTH_DISCLANGWARN_END } static TokenAttributes getVarTokenAttributes(CXCursor cur) { if (clang_getCursorLinkage(cur) == CXLinkage_NoLinkage) return TokenAttributes::varLocal; if (clang_getCXXAccessSpecifier(cur) == CX_CXXInvalidAccessSpecifier) return TokenAttributes::varGlobal; if (clang_Cursor_getStorageClass(cur) == CX_SC_Static) return TokenAttributes::varStaticMember; return TokenAttributes::varNonstaticMember; } static TokenAttributes getIntTokenAttributes(boost::string_ref sp) { if (!sp.empty()) { if (sp.size() >= 2 && sp[0] == '0') { if (sp[1] == 'x' || sp[1] == 'X') return TokenAttributes::litNumIntHex; if (sp[1] == 'b' || sp[1] == 'B') return TokenAttributes::litNumIntBin; return TokenAttributes::litNumIntOct; } char suffix = sp[sp.size() - 1]; if (suffix == 'l' || suffix == 'L') return TokenAttributes::litNumIntDecLong; } return TokenAttributes::litNum; } static bool isBuiltinTypeKw(boost::string_ref t) { return t.starts_with("unsigned ") || t == "unsigned" || t.starts_with("signed ") || t == "signed" || t.starts_with("short ") || t == "short" || t.starts_with("long ") || t == "long" || t == "int" || t == "float" || t == "double" || t == "bool" || t == "char" || t == "char16_t" || t == "char32_t" || t == "wchar_t" || t == "void"; } static TokenAttributes getTokenAttributesImpl( CXToken tok, CXCursor cur, boost::string_ref sp, // token spelling CXTranslationUnit tu, unsigned recursionDepth) { CXCursorKind k = clang_getCursorKind(cur); CXTokenKind tk = clang_getTokenKind(tok); if (clang_isPreprocessing(k)) { if (k == CXCursor_InclusionDirective && sp != "include" && sp != "#") return TokenAttributes::preIncludeFile; return TokenAttributes::pre; } switch (tk) { case CXToken_Punctuation: if (k == CXCursor_BinaryOperator || k == CXCursor_UnaryOperator) return TokenAttributes::op; return TokenAttributes::punct; case CXToken_Comment: return TokenAttributes::cmmt; case CXToken_Literal: SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum") switch (k) { case CXCursor_ObjCStringLiteral: case CXCursor_StringLiteral: return TokenAttributes::litStr; case CXCursor_CharacterLiteral: return TokenAttributes::litChr; case CXCursor_FloatingLiteral: return TokenAttributes::litNumFlt; case CXCursor_IntegerLiteral: return getIntTokenAttributes(sp); case CXCursor_ImaginaryLiteral: return TokenAttributes::litNum; default: return TokenAttributes::lit; } SYNTH_DISCLANGWARN_END case CXToken_Keyword: { if (k == CXCursor_BinaryOperator || k == CXCursor_UnaryOperator) return TokenAttributes::opWord; if (k == CXCursor_CXXNullPtrLiteralExpr || k == CXCursor_CXXBoolLiteralExpr || k == CXCursor_ObjCBoolLiteralExpr ) { return TokenAttributes::litKw; } if (k == CXCursor_TypeRef || isBuiltinTypeKw(sp)) return TokenAttributes::tyBuiltin; if (clang_isDeclaration(k) || k == CXCursor_DeclStmt) return TokenAttributes::kwDecl; if (sp == "sizeof" || sp == "alignof") return TokenAttributes::opWord; if (sp == "this") return TokenAttributes::litKw; return TokenAttributes::kw; } case CXToken_Identifier: if (isTypeCursorKind(k)) return TokenAttributes::ty; if (isFunctionCursorKind(k)) return TokenAttributes::func; SYNTH_DISCLANGWARN_BEGIN("-Wswitch-enum") switch (k) { case CXCursor_ObjCPropertyDecl: return TokenAttributes::varNonstaticMember; // Sorta right. case CXCursor_ObjCIvarDecl: case CXCursor_FieldDecl: return TokenAttributes::varNonstaticMember; // TODO case CXCursor_EnumConstantDecl: case CXCursor_NonTypeTemplateParameter: return TokenAttributes::constant; case CXCursor_VarDecl: return getVarTokenAttributes(cur); case CXCursor_ParmDecl: return TokenAttributes::varLocal; case CXCursor_Namespace: case CXCursor_NamespaceAlias: case CXCursor_UsingDirective: case CXCursor_NamespaceRef: return TokenAttributes::namesp; case CXCursor_LabelStmt: return TokenAttributes::lbl; default: { if (clang_isAttribute(k)) return TokenAttributes::attr; CXCursor refd = clang_getCursorReferenced(cur); bool recErr = recursionDepth > kMaxRefRecursion; if (recErr) { CgStr kindSp(clang_getCursorKindSpelling(k)); CgStr rKindSp(clang_getCursorKindSpelling( clang_getCursorKind(refd))); std::clog << "When trying to highlight token " << clang_getTokenExtent(tu, tok) << " " << sp << ":\n" << " Cursor " << clang_getCursorExtent(cur) << " " << kindSp << " references " << clang_getCursorExtent(refd) << " " << rKindSp << " Maximum depth exceeded with " << recursionDepth << ".\n"; return TokenAttributes::none; } if (clang_equalCursors(cur, refd)) return TokenAttributes::none; return getTokenAttributesImpl( tok, refd, sp, tu, recursionDepth + 1); } } } SYNTH_DISCLANGWARN_END assert("unreachable" && false); return TokenAttributes::none; } TokenAttributes synth::getTokenAttributes( CXToken tok, CXCursor cur, boost::string_ref tokSpelling) { return getTokenAttributesImpl( tok, cur, tokSpelling, clang_Cursor_getTranslationUnit(cur), 0); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // 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 "DeclCollector.h" #include "IncrementalParser.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/Lex/Token.h" using namespace clang; namespace { static bool shouldIgnore(const Decl* D) { // This function is called for all "deserialized" decls, where the // "deserialized" decl either really comes from an AST file or from // a header that's loaded to import the AST for a library with a dictionary // (the non-PCM case). // // Functions that are inlined must be sent to CodeGen - they will not have a // symbol in the library. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) { if (D->isFromASTFile()) { return !FD->hasBody(); } else { // If the decl must be emitted then it will be in the library. // If not, we must expose it to CodeGen now because it might // not be in the library. Does this correspond to a weak symbol // by definition? return !(FD->isInlined() || FD->isTemplateInstantiation()); } } // Don't codegen statics coming in from a module; they are already part of // the library. // We do need to expose static variables from template instantiations. if (const VarDecl* VD = dyn_cast<VarDecl>(D)) if (VD->hasGlobalStorage() && !VD->getType().isConstQualified() && VD->getTemplateSpecializationKind() == TSK_Undeclared) return true; return false; } } namespace cling { bool DeclCollector::comesFromASTReader(DeclGroupRef DGR) const { assert(!DGR.isNull() && "DeclGroupRef is Null!"); assert(m_CurTransaction && "No current transaction when deserializing"); if (m_CurTransaction->getCompilationOpts().CodeGenerationForModule) return true; // Take the first/only decl in the group. Decl* D = *DGR.begin(); return D->isFromASTFile(); } bool DeclCollector::comesFromASTReader(const Decl* D) const { // The operation is const but clang::DeclGroupRef doesn't allow us to // express it. return comesFromASTReader(DeclGroupRef(const_cast<Decl*>(D))); } // pin the vtable here. DeclCollector::~DeclCollector() { } void DeclCollector::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { assert(D->isImplicit()); // We need to mark the decls coming from the modules if (comesFromASTReader(RD) || comesFromASTReader(D)) { Decl* implicitD = const_cast<Decl*>(D); implicitD->addAttr(UsedAttr::CreateImplicit(implicitD->getASTContext())); } } ASTTransformer::Result DeclCollector::TransformDecl(Decl* D) const { // We are sure it's safe to pipe it through the transformers // Consume late transformers init for (size_t i = 0; D && i < m_TransactionTransformers.size(); ++i) { ASTTransformer::Result NewDecl = m_TransactionTransformers[i]->Transform(D, m_CurTransaction); if (!NewDecl.getInt()) { m_CurTransaction->setIssuedDiags(Transaction::kErrors); return NewDecl; } D = NewDecl.getPointer(); } if (FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D)) { if (utils::Analyze::IsWrapper(FD)) { for (size_t i = 0; D && i < m_WrapperTransformers.size(); ++i) { ASTTransformer::Result NewDecl = m_WrapperTransformers[i]->Transform(D, m_CurTransaction); if (!NewDecl.getInt()) { m_CurTransaction->setIssuedDiags(Transaction::kErrors); return NewDecl; } D = NewDecl.getPointer(); } } } return ASTTransformer::Result(D, true); } bool DeclCollector::Transform(DeclGroupRef& DGR) const { struct CommitTransactionRAII_t { IncrementalParser* m_IncrParser; Transaction* m_Transaction; CommitTransactionRAII_t(IncrementalParser* IP, CompilationOptions CO): m_IncrParser(IP) { m_Transaction = IP->beginTransaction(CO); } ~CommitTransactionRAII_t() { IncrementalParser::ParseResultTransaction PRT = m_IncrParser->endTransaction(m_Transaction); if (PRT.getInt() != IncrementalParser::kFailed) { if (Transaction* T = PRT.getPointer()) { assert(T == m_Transaction && "Ended different transaction?"); m_IncrParser->commitTransaction(T); } } } } CommitTransactionRAII(m_IncrParser, m_CurTransaction->getCompilationOpts()); llvm::SmallVector<Decl*, 4> ReplacedDecls; bool HaveReplacement = false; for (Decl* D: DGR) { ASTTransformer::Result NewDecl = TransformDecl(D); if (!NewDecl.getInt()) return false; HaveReplacement |= (NewDecl.getPointer() != D); if (NewDecl.getPointer()) ReplacedDecls.push_back(NewDecl.getPointer()); } if (HaveReplacement) DGR = DeclGroupRef::Create((*DGR.begin())->getASTContext(), ReplacedDecls.data(), ReplacedDecls.size()); return true; } bool DeclCollector::HandleTopLevelDecl(DeclGroupRef DGR) { if (!Transform(DGR)) return false; if (DGR.isNull()) return true; Transaction::DelayCallInfo DCI(DGR, Transaction::kCCIHandleTopLevelDecl); m_CurTransaction->append(DCI); if (!m_Consumer) return true; if (comesFromASTReader(DGR)) { for (DeclGroupRef::iterator DI = DGR.begin(), DE = DGR.end(); DI != DE; ++DI) { DeclGroupRef SplitDGR(*DI); // FIXME: The special namespace treatment (not sending itself to // CodeGen, but only its content - if the contained decl should be // emitted) works around issue with the static initialization when // having a PCH and loading a library. We don't want to generate // code for the static that will come through the library. // // This will be fixed with the clang::Modules. Make sure we remember. // assert(!getCI()->getLangOpts().Modules && "Please revisit!"); if (NamespaceDecl* ND = dyn_cast<NamespaceDecl>(*DI)) { for (NamespaceDecl::decl_iterator NDI = ND->decls_begin(), EN = ND->decls_end(); NDI != EN; ++NDI) { // Recurse over decls inside the namespace, like // CodeGenModule::EmitNamespace() does. if (!shouldIgnore(*NDI)) m_Consumer->HandleTopLevelDecl(DeclGroupRef(*NDI)); } } else if (!shouldIgnore(*DI)) { m_Consumer->HandleTopLevelDecl(DeclGroupRef(*DI)); } continue; } } else { m_Consumer->HandleTopLevelDecl(DGR); } return true; } void DeclCollector::HandleInterestingDecl(DeclGroupRef DGR) { Transaction::DelayCallInfo DCI(DGR, Transaction::kCCIHandleInterestingDecl); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DGR) || !shouldIgnore(*DGR.begin()))) m_Consumer->HandleTopLevelDecl(DGR); } void DeclCollector::HandleTagDeclDefinition(TagDecl* TD) { Transaction::DelayCallInfo DCI(DeclGroupRef(TD), Transaction::kCCIHandleTagDeclDefinition); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(TD)) || !shouldIgnore(TD))) m_Consumer->HandleTagDeclDefinition(TD); } void DeclCollector::HandleVTable(CXXRecordDecl* RD) { Transaction::DelayCallInfo DCI(DeclGroupRef(RD), Transaction::kCCIHandleVTable); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(RD)) || !shouldIgnore(RD))) m_Consumer->HandleVTable(RD); // 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) { // C has tentative definitions which we might need to deal with when running // in C mode. Transaction::DelayCallInfo DCI(DeclGroupRef(VD), Transaction::kCCICompleteTentativeDefinition); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(VD)) || !shouldIgnore(VD))) m_Consumer->CompleteTentativeDefinition(VD); } void DeclCollector::HandleTranslationUnit(ASTContext& Ctx) { //if (m_Consumer) // m_Consumer->HandleTranslationUnit(Ctx); } void DeclCollector::HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) { Transaction::DelayCallInfo DCI(DeclGroupRef(D), Transaction::kCCIHandleCXXImplicitFunctionInstantiation); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(D)) || !shouldIgnore(D))) m_Consumer->HandleCXXImplicitFunctionInstantiation(D); } void DeclCollector::HandleCXXStaticMemberVarInstantiation(VarDecl *D) { Transaction::DelayCallInfo DCI(DeclGroupRef(D), Transaction::kCCIHandleCXXStaticMemberVarInstantiation); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(D)) || !shouldIgnore(D))) m_Consumer->HandleCXXStaticMemberVarInstantiation(D); } void DeclCollector::MacroDefined(const clang::Token &MacroNameTok, const clang::MacroDirective *MD) { Transaction::MacroDirectiveInfo MDE(MacroNameTok.getIdentifierInfo(), MD); m_CurTransaction->append(MDE); } } // namespace cling <commit_msg>Do not emit if there are parse or trnasformation errors.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // 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 "DeclCollector.h" #include "IncrementalParser.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/Lex/Token.h" using namespace clang; namespace { static bool shouldIgnore(const Decl* D) { // This function is called for all "deserialized" decls, where the // "deserialized" decl either really comes from an AST file or from // a header that's loaded to import the AST for a library with a dictionary // (the non-PCM case). // // Functions that are inlined must be sent to CodeGen - they will not have a // symbol in the library. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) { if (D->isFromASTFile()) { return !FD->hasBody(); } else { // If the decl must be emitted then it will be in the library. // If not, we must expose it to CodeGen now because it might // not be in the library. Does this correspond to a weak symbol // by definition? return !(FD->isInlined() || FD->isTemplateInstantiation()); } } // Don't codegen statics coming in from a module; they are already part of // the library. // We do need to expose static variables from template instantiations. if (const VarDecl* VD = dyn_cast<VarDecl>(D)) if (VD->hasGlobalStorage() && !VD->getType().isConstQualified() && VD->getTemplateSpecializationKind() == TSK_Undeclared) return true; return false; } } namespace cling { bool DeclCollector::comesFromASTReader(DeclGroupRef DGR) const { assert(!DGR.isNull() && "DeclGroupRef is Null!"); assert(m_CurTransaction && "No current transaction when deserializing"); if (m_CurTransaction->getCompilationOpts().CodeGenerationForModule) return true; // Take the first/only decl in the group. Decl* D = *DGR.begin(); return D->isFromASTFile(); } bool DeclCollector::comesFromASTReader(const Decl* D) const { // The operation is const but clang::DeclGroupRef doesn't allow us to // express it. return comesFromASTReader(DeclGroupRef(const_cast<Decl*>(D))); } // pin the vtable here. DeclCollector::~DeclCollector() { } void DeclCollector::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { assert(D->isImplicit()); // We need to mark the decls coming from the modules if (comesFromASTReader(RD) || comesFromASTReader(D)) { Decl* implicitD = const_cast<Decl*>(D); implicitD->addAttr(UsedAttr::CreateImplicit(implicitD->getASTContext())); } } ASTTransformer::Result DeclCollector::TransformDecl(Decl* D) const { // We are sure it's safe to pipe it through the transformers // Consume late transformers init for (size_t i = 0; D && i < m_TransactionTransformers.size(); ++i) { ASTTransformer::Result NewDecl = m_TransactionTransformers[i]->Transform(D, m_CurTransaction); if (!NewDecl.getInt()) { m_CurTransaction->setIssuedDiags(Transaction::kErrors); return NewDecl; } D = NewDecl.getPointer(); } if (FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D)) { if (utils::Analyze::IsWrapper(FD)) { for (size_t i = 0; D && i < m_WrapperTransformers.size(); ++i) { ASTTransformer::Result NewDecl = m_WrapperTransformers[i]->Transform(D, m_CurTransaction); if (!NewDecl.getInt()) { m_CurTransaction->setIssuedDiags(Transaction::kErrors); return NewDecl; } D = NewDecl.getPointer(); } } } return ASTTransformer::Result(D, true); } bool DeclCollector::Transform(DeclGroupRef& DGR) const { struct CommitTransactionRAII_t { IncrementalParser* m_IncrParser; Transaction* m_Transaction; CommitTransactionRAII_t(IncrementalParser* IP, CompilationOptions CO): m_IncrParser(IP) { m_Transaction = IP->beginTransaction(CO); } ~CommitTransactionRAII_t() { IncrementalParser::ParseResultTransaction PRT = m_IncrParser->endTransaction(m_Transaction); if (PRT.getInt() != IncrementalParser::kFailed) { if (Transaction* T = PRT.getPointer()) { assert(T == m_Transaction && "Ended different transaction?"); m_IncrParser->commitTransaction(T); } } } } CommitTransactionRAII(m_IncrParser, m_CurTransaction->getCompilationOpts()); llvm::SmallVector<Decl*, 4> ReplacedDecls; bool HaveReplacement = false; for (Decl* D: DGR) { ASTTransformer::Result NewDecl = TransformDecl(D); if (!NewDecl.getInt()) return false; HaveReplacement |= (NewDecl.getPointer() != D); if (NewDecl.getPointer()) ReplacedDecls.push_back(NewDecl.getPointer()); } if (HaveReplacement) DGR = DeclGroupRef::Create((*DGR.begin())->getASTContext(), ReplacedDecls.data(), ReplacedDecls.size()); return true; } bool DeclCollector::HandleTopLevelDecl(DeclGroupRef DGR) { if (!Transform(DGR)) return false; if (DGR.isNull()) return true; Transaction::DelayCallInfo DCI(DGR, Transaction::kCCIHandleTopLevelDecl); m_CurTransaction->append(DCI); if (!m_Consumer || getTransaction()->getIssuedDiags() == Transaction::kErrors) return true; if (comesFromASTReader(DGR)) { for (DeclGroupRef::iterator DI = DGR.begin(), DE = DGR.end(); DI != DE; ++DI) { DeclGroupRef SplitDGR(*DI); // FIXME: The special namespace treatment (not sending itself to // CodeGen, but only its content - if the contained decl should be // emitted) works around issue with the static initialization when // having a PCH and loading a library. We don't want to generate // code for the static that will come through the library. // // This will be fixed with the clang::Modules. Make sure we remember. // assert(!getCI()->getLangOpts().Modules && "Please revisit!"); if (NamespaceDecl* ND = dyn_cast<NamespaceDecl>(*DI)) { for (NamespaceDecl::decl_iterator NDI = ND->decls_begin(), EN = ND->decls_end(); NDI != EN; ++NDI) { // Recurse over decls inside the namespace, like // CodeGenModule::EmitNamespace() does. if (!shouldIgnore(*NDI)) m_Consumer->HandleTopLevelDecl(DeclGroupRef(*NDI)); } } else if (!shouldIgnore(*DI)) { m_Consumer->HandleTopLevelDecl(DeclGroupRef(*DI)); } continue; } } else { m_Consumer->HandleTopLevelDecl(DGR); } return true; } void DeclCollector::HandleInterestingDecl(DeclGroupRef DGR) { Transaction::DelayCallInfo DCI(DGR, Transaction::kCCIHandleInterestingDecl); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DGR) || !shouldIgnore(*DGR.begin()))) m_Consumer->HandleTopLevelDecl(DGR); } void DeclCollector::HandleTagDeclDefinition(TagDecl* TD) { Transaction::DelayCallInfo DCI(DeclGroupRef(TD), Transaction::kCCIHandleTagDeclDefinition); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(TD)) || !shouldIgnore(TD))) m_Consumer->HandleTagDeclDefinition(TD); } void DeclCollector::HandleVTable(CXXRecordDecl* RD) { Transaction::DelayCallInfo DCI(DeclGroupRef(RD), Transaction::kCCIHandleVTable); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(RD)) || !shouldIgnore(RD))) m_Consumer->HandleVTable(RD); // 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) { // C has tentative definitions which we might need to deal with when running // in C mode. Transaction::DelayCallInfo DCI(DeclGroupRef(VD), Transaction::kCCICompleteTentativeDefinition); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(VD)) || !shouldIgnore(VD))) m_Consumer->CompleteTentativeDefinition(VD); } void DeclCollector::HandleTranslationUnit(ASTContext& Ctx) { //if (m_Consumer) // m_Consumer->HandleTranslationUnit(Ctx); } void DeclCollector::HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) { Transaction::DelayCallInfo DCI(DeclGroupRef(D), Transaction::kCCIHandleCXXImplicitFunctionInstantiation); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(D)) || !shouldIgnore(D))) m_Consumer->HandleCXXImplicitFunctionInstantiation(D); } void DeclCollector::HandleCXXStaticMemberVarInstantiation(VarDecl *D) { Transaction::DelayCallInfo DCI(DeclGroupRef(D), Transaction::kCCIHandleCXXStaticMemberVarInstantiation); m_CurTransaction->append(DCI); if (m_Consumer && (!comesFromASTReader(DeclGroupRef(D)) || !shouldIgnore(D))) m_Consumer->HandleCXXStaticMemberVarInstantiation(D); } void DeclCollector::MacroDefined(const clang::Token &MacroNameTok, const clang::MacroDirective *MD) { Transaction::MacroDirectiveInfo MDE(MacroNameTok.getIdentifierInfo(), MD); m_CurTransaction->append(MDE); } } // namespace cling <|endoftext|>
<commit_before>#include "idmanager.hpp" #include <iostream> using namespace std; IdManager::IdManager() { cout << "Available IDs: " << MAX_IDS << ", IdManager memory footprint: " << MAX_IDS * sizeof(ID) / 1048576 << "MB" << endl; for(unsigned int freeId = MAX_IDS-1; freeId > 0; freeId--) { freeIds.push(freeId); } } unsigned int IdManager::acquireId() { if(freeIds.empty()) { cout << "Error: Ran out of free ids (idmanager.cpp). Either increase the amount of freeIds or reduce entities in world." << endl; } const auto acquiredId = freeIds.top(); freeIds.pop(); return acquiredId; } void IdManager::releaseId(unsigned int releasedId) { freeIds.push(releasedId); } <commit_msg>reduced work done by idmanager during startup<commit_after>#include "idmanager.hpp" #include <iostream> using namespace std; IdManager::IdManager() { cout << "Available IDs: " << MAX_IDS << ", IdManager memory footprint: " << MAX_IDS * sizeof(ID) / 1048576 << "MB" << endl; } unsigned int IdManager::acquireId() { //If any ID has been returned, reuse it if(!freeIds.empty()) { const ID recycledId = freeIds.top(); freeIds.pop(); return recycledId; } //Else get next free id; static ID id = 0; id += 1; if(id == MAX_IDS) { cout << "Error: Ran out of free ids (idmanager.cpp). Either increase the amount of freeIds or reduce entities in world." << endl; } return id; } void IdManager::releaseId(unsigned int releasedId) { freeIds.push(releasedId); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "ProgramOptions/Parameters.h" #include <regex> namespace { std::regex const removeComments("(^[ \t]+|[ \t]*(#.*)?$)", std::regex::nosubs | std::regex::ECMAScript); } namespace arangodb { namespace options { std::string removeCommentsFromNumber(std::string const& value) { // replace leading spaces, replace trailing spaces & comments return std::regex_replace(value, ::removeComments, ""); } } } <commit_msg>use two simple regexes to workaround macos compilers producing endless loops (#9281)<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "ProgramOptions/Parameters.h" #include <regex> namespace { std::regex const removeComments("#.*$", std::regex::ECMAScript); std::regex const removeTabs("^[ \t]+|[ \t]+$", std::regex::ECMAScript); } namespace arangodb { namespace options { std::string removeCommentsFromNumber(std::string const& value) { // replace trailing comments auto noComment = std::regex_replace(value, ::removeComments, ""); // replace leading spaces, replace trailing spaces return std::regex_replace(noComment, ::removeTabs, ""); } } } <|endoftext|>
<commit_before>/************************************************************************* * Copyright (C) 2011-2012 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of TeapotNet. * * * * TeapotNet 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. * * * * TeapotNet is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with TeapotNet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "interface.h" #include "html.h" #include "user.h" #include "store.h" #include "splicer.h" #include "config.h" #include "directory.h" #include "mime.h" namespace tpot { Interface *Interface::Instance = NULL; Interface::Interface(int port) : Http::Server(port) { } Interface::~Interface(void) { } void Interface::add(const String &prefix, HttpInterfaceable *interfaceable) { Assert(interfaceable != NULL); String cprefix(prefix); if(cprefix.empty() || cprefix[0] != '/') cprefix = "/" + cprefix; mMutex.lock(); if(mPrefixes.contains(cprefix)) { mMutex.unlock(); throw Exception("URL prefix \""+cprefix+"\" is already registered"); } mPrefixes.insert(cprefix, interfaceable); mMutex.unlock(); } void Interface::remove(const String &prefix, HttpInterfaceable *interfaceable) { mMutex.lock(); HttpInterfaceable *test = NULL; if(mPrefixes.get(prefix, test) && (!interfaceable || test == interfaceable)) mPrefixes.erase(prefix); mMutex.unlock(); } void Interface::process(Http::Request &request) { Address remoteAddr = request.sock->getRemoteAddress(); //Log("Interface", "Request for URL \""+request.url+"\""); // URL must begin with / if(request.url.empty() || request.url[0] != '/') throw 404; User *user = NULL; String auth; if(request.headers.get("Authorization", auth)) { String tmp = auth.cut(' '); auth.trim(); tmp.trim(); if(auth != "Basic") throw 400; String name = tmp.base64Decode(); String password = name.cut(':'); user = User::Authenticate(name, password); } if(request.url == "/") { if(user) { Http::Response response(request, 303); response.headers["Location"] = "/" + user->name(); response.send(); return; } else if(User::Count() == 0) { if(remoteAddr.isLocal() || remoteAddr.isPrivate()) { if(request.method == "POST") { if(request.post.contains("name")) { String name = request.post["name"]; String password = request.post["password"]; try { if(!name.empty() && !password.empty()) { User *user = new User(name, password); user->start(); } } catch(const Exception &e) { Http::Response response(request, 200); response.send(); Html page(response.sock); page.header("Error", false, "/"); page.text(e.what()); page.footer(); return; } } Http::Response response(request,303); response.send(); Html page(response.sock); page.header("Account created", false, "/"); page.open("h1"); page.text("Your account has been created."); page.close("h1"); page.open("p"); page.text("Please enter your username and password when prompted to log in."); page.close("p"); page.footer(); return; } Http::Response response(request, 200); response.send(); Html page(response.sock); page.header(); page.open("h1"); page.text("Welcome to TeapotNet !"); page.close("h1"); page.open("p"); page.text("No user has been configured yet, please enter your new username and password."); page.close("p"); page.openForm("/","post"); page.openFieldset("New user"); page.label("name","Name"); page.input("text","name"); page.br(); page.label("password","Password"); page.input("password","password"); page.br(); page.label("add"); page.button("add","OK"); page.closeFieldset(); page.closeForm(); page.footer(); return; } else { Http::Response response(request, 200); response.send(); Html page(response.sock); page.header(); page.open("h1"); page.text("Welcome to TeapotNet !"); page.close("h1"); page.text("No user has been configured yet."); page.footer(); return; } } } List<String> list; request.url.explode(list,'/'); list.pop_front(); // first element is empty because url begin with '/' if(list.empty()) throw 500; if(list.size() == 1 && list.front().contains('.') && request.url[request.url.size()-1] != '/') { String fileName = Config::Get("static_dir") + Directory::Separator + list.front(); if(File::Exist(fileName)) { Http::RespondWithFile(request, fileName); return; } if(!User::Exist(list.front())) throw 404; } if(list.front().empty() || User::Exist(list.front()) || (!remoteAddr.isLocal() && !remoteAddr.isPrivate())) { if(!user || list.front() != user->name()) { String realm = "TeapotNet"; Http::Response response(request, 401); response.headers.insert("WWW-Authenticate", "Basic realm=\""+realm+"\""); response.send(); Html page(response.sock); page.header("Authentication required"); page.footer(); return; } while(!list.empty()) { String prefix; prefix.implode(list,'/'); prefix = "/" + prefix; list.pop_back(); mMutex.lock(); HttpInterfaceable *interfaceable; if(mPrefixes.get(prefix,interfaceable)) { mMutex.unlock(); request.url.ignore(prefix.size()); //Log("Interface", "Matched prefix \""+prefix+"\""); if(prefix != "/" && request.url.empty()) { Http::Response response(request, 301); // Moved Permanently response.headers["Location"] = prefix+"/"; response.send(); return; } interfaceable->http(prefix, request); return; } mMutex.unlock(); } } else { if(list.size() != 1) throw 404; try { ByteString digest; String tmp = list.front(); try { tmp >> digest; } catch(...) { throw 404; } Store::Entry entry; if(Store::GetResource(digest, entry) && !entry.path.empty()) { File file(entry.path); Http::Response response(request, 200); response.headers["Content-Disposition"] = "inline; filename=\"" + entry.name + "\""; response.headers["Content-Type"] = Mime::GetType(entry.name); response.headers["Content-Length"] << entry.size; response.headers["Last-Modified"] = entry.time.toHttpDate(); response.headers["Content-SHA512"] = entry.digest.toString(); response.send(); response.sock->write(file); return; } else { size_t blockSize = 128*1024; // TODO String filename = File::TempName(); // TODO size_t firstBlock = 0; size_t firstOffset = 0; int64_t rangeBegin = 0; int64_t rangeEnd = 0; bool hasRange = request.extractRange(rangeBegin, rangeEnd); if(hasRange) { firstBlock = size_t(rangeBegin / blockSize); firstOffset = size_t(rangeBegin % blockSize); } try { Splicer splicer(digest, filename, blockSize, firstBlock); File file(filename, File::Read); uint64_t contentLength = splicer.size(); int code = 200; rangeBegin = 0; rangeEnd = contentLength-1; if(hasRange) { Assert(request.extractRange(rangeBegin, rangeEnd, contentLength)); if(rangeBegin >= contentLength || rangeEnd >= contentLength || rangeBegin > rangeEnd) throw 416; contentLength = uint64_t(rangeEnd - rangeBegin + 1); code = 206; } Http::Response response(request, code); response.headers["Content-Disposition"] = "inline; filename=\"" + splicer.name() + "\""; response.headers["Content-Type"] = Mime::GetType(splicer.name()); response.headers["Content-Length"] << contentLength; response.headers["Accept-Ranges"] = "bytes"; if(hasRange) response.headers["Content-Range"] << rangeBegin << '-' << rangeEnd << '/' << contentLength; else response.headers["Content-SHA512"] = digest.toString(); // TODO: Missing headers response.send(); file.seekRead(firstBlock*blockSize); uint64_t total = 0; size_t current = firstBlock; while(total < contentLength && !splicer.finished()) { msleep(100); splicer.process(); size_t finished = splicer.finishedBlocks(); while(total < contentLength && current < finished) { if(current == firstBlock && firstOffset) file.ignore(firstOffset); size_t size = size_t(std::min(uint64_t(blockSize), contentLength - total)); Assert(size = file.read(*response.sock, size)); total+= size; ++current; } } splicer.close(); if(total < contentLength) total+= file.read(*response.sock, contentLength - total); if(total == contentLength) { if(rangeBegin == 0 && contentLength == file.size()) { // TODO: copy in incoming } } else Log("Interface::http", String("Warning: Splicer downloaded ") + String::number(total) + " bytes whereas size was " + String::number(contentLength)); } catch(const NetException &e) { // nothing to do } catch(const Exception &e) { Log("Interface::process", String("Error during file transfer: ") + e.what()); } if(File::Exist(filename)) File::Remove(filename); return; } } catch(const NetException &e) { return; // nothing to do } catch(const std::exception &e) { Log("Interface::process", String("Error: ") + e.what()); throw 404; } } throw 404; } } <commit_msg>Fixed size in Content-Range<commit_after>/************************************************************************* * Copyright (C) 2011-2012 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of TeapotNet. * * * * TeapotNet 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. * * * * TeapotNet is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with TeapotNet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "interface.h" #include "html.h" #include "user.h" #include "store.h" #include "splicer.h" #include "config.h" #include "directory.h" #include "mime.h" namespace tpot { Interface *Interface::Instance = NULL; Interface::Interface(int port) : Http::Server(port) { } Interface::~Interface(void) { } void Interface::add(const String &prefix, HttpInterfaceable *interfaceable) { Assert(interfaceable != NULL); String cprefix(prefix); if(cprefix.empty() || cprefix[0] != '/') cprefix = "/" + cprefix; mMutex.lock(); if(mPrefixes.contains(cprefix)) { mMutex.unlock(); throw Exception("URL prefix \""+cprefix+"\" is already registered"); } mPrefixes.insert(cprefix, interfaceable); mMutex.unlock(); } void Interface::remove(const String &prefix, HttpInterfaceable *interfaceable) { mMutex.lock(); HttpInterfaceable *test = NULL; if(mPrefixes.get(prefix, test) && (!interfaceable || test == interfaceable)) mPrefixes.erase(prefix); mMutex.unlock(); } void Interface::process(Http::Request &request) { Address remoteAddr = request.sock->getRemoteAddress(); //Log("Interface", "Request for URL \""+request.url+"\""); // URL must begin with / if(request.url.empty() || request.url[0] != '/') throw 404; User *user = NULL; String auth; if(request.headers.get("Authorization", auth)) { String tmp = auth.cut(' '); auth.trim(); tmp.trim(); if(auth != "Basic") throw 400; String name = tmp.base64Decode(); String password = name.cut(':'); user = User::Authenticate(name, password); } if(request.url == "/") { if(user) { Http::Response response(request, 303); response.headers["Location"] = "/" + user->name(); response.send(); return; } else if(User::Count() == 0) { if(remoteAddr.isLocal() || remoteAddr.isPrivate()) { if(request.method == "POST") { if(request.post.contains("name")) { String name = request.post["name"]; String password = request.post["password"]; try { if(!name.empty() && !password.empty()) { User *user = new User(name, password); user->start(); } } catch(const Exception &e) { Http::Response response(request, 200); response.send(); Html page(response.sock); page.header("Error", false, "/"); page.text(e.what()); page.footer(); return; } } Http::Response response(request,303); response.send(); Html page(response.sock); page.header("Account created", false, "/"); page.open("h1"); page.text("Your account has been created."); page.close("h1"); page.open("p"); page.text("Please enter your username and password when prompted to log in."); page.close("p"); page.footer(); return; } Http::Response response(request, 200); response.send(); Html page(response.sock); page.header(); page.open("h1"); page.text("Welcome to TeapotNet !"); page.close("h1"); page.open("p"); page.text("No user has been configured yet, please enter your new username and password."); page.close("p"); page.openForm("/","post"); page.openFieldset("New user"); page.label("name","Name"); page.input("text","name"); page.br(); page.label("password","Password"); page.input("password","password"); page.br(); page.label("add"); page.button("add","OK"); page.closeFieldset(); page.closeForm(); page.footer(); return; } else { Http::Response response(request, 200); response.send(); Html page(response.sock); page.header(); page.open("h1"); page.text("Welcome to TeapotNet !"); page.close("h1"); page.text("No user has been configured yet."); page.footer(); return; } } } List<String> list; request.url.explode(list,'/'); list.pop_front(); // first element is empty because url begin with '/' if(list.empty()) throw 500; if(list.size() == 1 && list.front().contains('.') && request.url[request.url.size()-1] != '/') { String fileName = Config::Get("static_dir") + Directory::Separator + list.front(); if(File::Exist(fileName)) { Http::RespondWithFile(request, fileName); return; } if(!User::Exist(list.front())) throw 404; } if(list.front().empty() || User::Exist(list.front()) || (!remoteAddr.isLocal() && !remoteAddr.isPrivate())) { if(!user || list.front() != user->name()) { String realm = "TeapotNet"; Http::Response response(request, 401); response.headers.insert("WWW-Authenticate", "Basic realm=\""+realm+"\""); response.send(); Html page(response.sock); page.header("Authentication required"); page.footer(); return; } while(!list.empty()) { String prefix; prefix.implode(list,'/'); prefix = "/" + prefix; list.pop_back(); mMutex.lock(); HttpInterfaceable *interfaceable; if(mPrefixes.get(prefix,interfaceable)) { mMutex.unlock(); request.url.ignore(prefix.size()); //Log("Interface", "Matched prefix \""+prefix+"\""); if(prefix != "/" && request.url.empty()) { Http::Response response(request, 301); // Moved Permanently response.headers["Location"] = prefix+"/"; response.send(); return; } interfaceable->http(prefix, request); return; } mMutex.unlock(); } } else { if(list.size() != 1) throw 404; try { ByteString digest; String tmp = list.front(); try { tmp >> digest; } catch(...) { throw 404; } Store::Entry entry; if(Store::GetResource(digest, entry) && !entry.path.empty()) { File file(entry.path); Http::Response response(request, 200); response.headers["Content-Disposition"] = "inline; filename=\"" + entry.name + "\""; response.headers["Content-Type"] = Mime::GetType(entry.name); response.headers["Content-Length"] << entry.size; response.headers["Last-Modified"] = entry.time.toHttpDate(); response.headers["Content-SHA512"] = entry.digest.toString(); response.send(); response.sock->write(file); return; } else { size_t blockSize = 128*1024; // TODO String filename = File::TempName(); // TODO size_t firstBlock = 0; size_t firstOffset = 0; int64_t rangeBegin = 0; int64_t rangeEnd = 0; bool hasRange = request.extractRange(rangeBegin, rangeEnd); if(hasRange) { firstBlock = size_t(rangeBegin / blockSize); firstOffset = size_t(rangeBegin % blockSize); } try { Splicer splicer(digest, filename, blockSize, firstBlock); File file(filename, File::Read); uint64_t contentLength = splicer.size(); int code = 200; rangeBegin = 0; rangeEnd = contentLength-1; if(hasRange) { Assert(request.extractRange(rangeBegin, rangeEnd, contentLength)); if(rangeBegin >= contentLength || rangeEnd >= contentLength || rangeBegin > rangeEnd) throw 416; contentLength = uint64_t(rangeEnd - rangeBegin + 1); code = 206; } Http::Response response(request, code); response.headers["Content-Disposition"] = "inline; filename=\"" + splicer.name() + "\""; response.headers["Content-Type"] = Mime::GetType(splicer.name()); response.headers["Content-Length"] << contentLength; response.headers["Accept-Ranges"] = "bytes"; if(hasRange) response.headers["Content-Range"] << rangeBegin << '-' << rangeEnd << '/' << splicer.size(); else response.headers["Content-SHA512"] = digest.toString(); // TODO: Missing headers response.send(); file.seekRead(firstBlock*blockSize); uint64_t total = 0; size_t current = firstBlock; while(total < contentLength && !splicer.finished()) { msleep(100); splicer.process(); size_t finished = splicer.finishedBlocks(); while(total < contentLength && current < finished) { if(current == firstBlock && firstOffset) file.ignore(firstOffset); size_t size = size_t(std::min(uint64_t(blockSize), contentLength - total)); Assert(size = file.read(*response.sock, size)); total+= size; ++current; } } splicer.close(); if(total < contentLength) total+= file.read(*response.sock, contentLength - total); if(total == contentLength) { if(rangeBegin == 0 && contentLength == file.size()) { // TODO: copy in incoming } } else Log("Interface::http", String("Warning: Splicer downloaded ") + String::number(total) + " bytes whereas size was " + String::number(contentLength)); } catch(const NetException &e) { // nothing to do } catch(const Exception &e) { Log("Interface::process", String("Error during file transfer: ") + e.what()); } if(File::Exist(filename)) File::Remove(filename); return; } } catch(const NetException &e) { return; // nothing to do } catch(const std::exception &e) { Log("Interface::process", String("Error: ") + e.what()); throw 404; } } throw 404; } } <|endoftext|>
<commit_before>//===-- ARMMCInstLower.cpp - Convert ARM MachineInstr to an MCInst --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains code to lower ARM MachineInstrs to their corresponding // MCInst records. // //===----------------------------------------------------------------------===// #include "ARM.h" #include "ARMMCInstLower.h" //#include "llvm/CodeGen/MachineModuleInfoImpls.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/Constants.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInst.h" //#include "llvm/MC/MCStreamer.h" #include "llvm/Target/Mangler.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/SmallString.h" using namespace llvm; #if 0 const ARMSubtarget &ARMMCInstLower::getSubtarget() const { return AsmPrinter.getSubtarget(); } MachineModuleInfoMachO &ARMMCInstLower::getMachOMMI() const { assert(getSubtarget().isTargetDarwin() &&"Can only get MachO info on darwin"); return AsmPrinter.MMI->getObjFileInfo<MachineModuleInfoMachO>(); } #endif MCSymbol *ARMMCInstLower::GetGlobalAddressSymbol(const GlobalValue *GV) const { return Printer.Mang->getSymbol(GV); } const MCSymbolRefExpr *ARMMCInstLower:: GetSymbolRef(const MachineOperand &MO) const { assert(MO.isGlobal() && "Isn't a global address reference?"); // FIXME: HANDLE PLT references how?? const MCSymbolRefExpr *SymRef; const MCSymbol *Symbol = GetGlobalAddressSymbol(MO.getGlobal()); switch (MO.getTargetFlags()) { default: assert(0 && "Unknown target flag on GV operand"); case 0: SymRef = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None, Ctx); break; case ARMII::MO_LO16: SymRef = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_ARM_LO16, Ctx); break; case ARMII::MO_HI16: SymRef = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_ARM_HI16, Ctx); break; } return SymRef; } MCSymbol *ARMMCInstLower:: GetExternalSymbolSymbol(const MachineOperand &MO) const { // FIXME: HANDLE PLT references how?? // FIXME: This probably needs to be merged with the above SymbolRef stuff // to handle :lower16: and :upper16: (?) switch (MO.getTargetFlags()) { default: assert(0 && "Unknown target flag on GV operand"); case 0: break; } return Printer.GetExternalSymbolSymbol(MO.getSymbolName()); } MCSymbol *ARMMCInstLower:: GetJumpTableSymbol(const MachineOperand &MO) const { SmallString<256> Name; raw_svector_ostream(Name) << Printer.MAI->getPrivateGlobalPrefix() << "JTI" << Printer.getFunctionNumber() << '_' << MO.getIndex(); #if 0 switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); } #endif // Create a symbol for the name. return Ctx.GetOrCreateSymbol(Name.str()); } MCSymbol *ARMMCInstLower:: GetConstantPoolIndexSymbol(const MachineOperand &MO) const { SmallString<256> Name; raw_svector_ostream(Name) << Printer.MAI->getPrivateGlobalPrefix() << "CPI" << Printer.getFunctionNumber() << '_' << MO.getIndex(); #if 0 switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); } #endif // Create a symbol for the name. return Ctx.GetOrCreateSymbol(Name.str()); } MCOperand ARMMCInstLower:: LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const { // FIXME: We would like an efficient form for this, so we don't have to do a // lot of extra uniquing. const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, Ctx); #if 0 switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); } #endif if (!MO.isJTI() && MO.getOffset()) Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(MO.getOffset(), Ctx), Ctx); return MCOperand::CreateExpr(Expr); } MCOperand ARMMCInstLower:: LowerSymbolRefOperand(const MachineOperand &MO, const MCSymbolRefExpr *Sym) const { const MCExpr *Expr = Sym; if (!MO.isJTI() && MO.getOffset()) Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(MO.getOffset(), Ctx), Ctx); return MCOperand::CreateExpr(Expr); } void ARMMCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const { OutMI.setOpcode(MI->getOpcode()); for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); MCOperand MCOp; switch (MO.getType()) { default: MI->dump(); assert(0 && "unknown operand type"); case MachineOperand::MO_Register: // Ignore all non-CPSR implicit register operands. if (MO.isImplicit() && MO.getReg() != ARM::CPSR) continue; assert(!MO.getSubReg() && "Subregs should be eliminated!"); MCOp = MCOperand::CreateReg(MO.getReg()); break; case MachineOperand::MO_Immediate: MCOp = MCOperand::CreateImm(MO.getImm()); break; case MachineOperand::MO_MachineBasicBlock: MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create( MO.getMBB()->getSymbol(), Ctx)); break; case MachineOperand::MO_GlobalAddress: MCOp = LowerSymbolRefOperand(MO, GetSymbolRef(MO)); break; case MachineOperand::MO_ExternalSymbol: MCOp = LowerSymbolOperand(MO, GetExternalSymbolSymbol(MO)); break; case MachineOperand::MO_JumpTableIndex: MCOp = LowerSymbolOperand(MO, GetJumpTableSymbol(MO)); break; case MachineOperand::MO_ConstantPoolIndex: MCOp = LowerSymbolOperand(MO, GetConstantPoolIndexSymbol(MO)); break; case MachineOperand::MO_BlockAddress: MCOp = LowerSymbolOperand(MO, Printer.GetBlockAddressSymbol( MO.getBlockAddress())); break; case MachineOperand::MO_FPImmediate: APFloat Val = MO.getFPImm()->getValueAPF(); bool ignored; Val.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored); MCOp = MCOperand::CreateFPImm(Val.convertToDouble()); break; } OutMI.addOperand(MCOp); } } <commit_msg>Remove a few commented out bits<commit_after>//===-- ARMMCInstLower.cpp - Convert ARM MachineInstr to an MCInst --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains code to lower ARM MachineInstrs to their corresponding // MCInst records. // //===----------------------------------------------------------------------===// #include "ARM.h" #include "ARMMCInstLower.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/Constants.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInst.h" #include "llvm/Target/Mangler.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/SmallString.h" using namespace llvm; MCSymbol *ARMMCInstLower::GetGlobalAddressSymbol(const GlobalValue *GV) const { return Printer.Mang->getSymbol(GV); } const MCSymbolRefExpr *ARMMCInstLower:: GetSymbolRef(const MachineOperand &MO) const { assert(MO.isGlobal() && "Isn't a global address reference?"); // FIXME: HANDLE PLT references how?? const MCSymbolRefExpr *SymRef; const MCSymbol *Symbol = GetGlobalAddressSymbol(MO.getGlobal()); switch (MO.getTargetFlags()) { default: assert(0 && "Unknown target flag on GV operand"); case 0: SymRef = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None, Ctx); break; case ARMII::MO_LO16: SymRef = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_ARM_LO16, Ctx); break; case ARMII::MO_HI16: SymRef = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_ARM_HI16, Ctx); break; } return SymRef; } MCSymbol *ARMMCInstLower:: GetExternalSymbolSymbol(const MachineOperand &MO) const { // FIXME: HANDLE PLT references how?? // FIXME: This probably needs to be merged with the above SymbolRef stuff // to handle :lower16: and :upper16: (?) switch (MO.getTargetFlags()) { default: assert(0 && "Unknown target flag on GV operand"); case 0: break; } return Printer.GetExternalSymbolSymbol(MO.getSymbolName()); } MCSymbol *ARMMCInstLower:: GetJumpTableSymbol(const MachineOperand &MO) const { SmallString<256> Name; raw_svector_ostream(Name) << Printer.MAI->getPrivateGlobalPrefix() << "JTI" << Printer.getFunctionNumber() << '_' << MO.getIndex(); #if 0 switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); } #endif // Create a symbol for the name. return Ctx.GetOrCreateSymbol(Name.str()); } MCSymbol *ARMMCInstLower:: GetConstantPoolIndexSymbol(const MachineOperand &MO) const { SmallString<256> Name; raw_svector_ostream(Name) << Printer.MAI->getPrivateGlobalPrefix() << "CPI" << Printer.getFunctionNumber() << '_' << MO.getIndex(); #if 0 switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); } #endif // Create a symbol for the name. return Ctx.GetOrCreateSymbol(Name.str()); } MCOperand ARMMCInstLower:: LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const { // FIXME: We would like an efficient form for this, so we don't have to do a // lot of extra uniquing. const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, Ctx); #if 0 switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); } #endif if (!MO.isJTI() && MO.getOffset()) Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(MO.getOffset(), Ctx), Ctx); return MCOperand::CreateExpr(Expr); } MCOperand ARMMCInstLower:: LowerSymbolRefOperand(const MachineOperand &MO, const MCSymbolRefExpr *Sym) const { const MCExpr *Expr = Sym; if (!MO.isJTI() && MO.getOffset()) Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(MO.getOffset(), Ctx), Ctx); return MCOperand::CreateExpr(Expr); } void ARMMCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const { OutMI.setOpcode(MI->getOpcode()); for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); MCOperand MCOp; switch (MO.getType()) { default: MI->dump(); assert(0 && "unknown operand type"); case MachineOperand::MO_Register: // Ignore all non-CPSR implicit register operands. if (MO.isImplicit() && MO.getReg() != ARM::CPSR) continue; assert(!MO.getSubReg() && "Subregs should be eliminated!"); MCOp = MCOperand::CreateReg(MO.getReg()); break; case MachineOperand::MO_Immediate: MCOp = MCOperand::CreateImm(MO.getImm()); break; case MachineOperand::MO_MachineBasicBlock: MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create( MO.getMBB()->getSymbol(), Ctx)); break; case MachineOperand::MO_GlobalAddress: MCOp = LowerSymbolRefOperand(MO, GetSymbolRef(MO)); break; case MachineOperand::MO_ExternalSymbol: MCOp = LowerSymbolOperand(MO, GetExternalSymbolSymbol(MO)); break; case MachineOperand::MO_JumpTableIndex: MCOp = LowerSymbolOperand(MO, GetJumpTableSymbol(MO)); break; case MachineOperand::MO_ConstantPoolIndex: MCOp = LowerSymbolOperand(MO, GetConstantPoolIndexSymbol(MO)); break; case MachineOperand::MO_BlockAddress: MCOp = LowerSymbolOperand(MO, Printer.GetBlockAddressSymbol( MO.getBlockAddress())); break; case MachineOperand::MO_FPImmediate: APFloat Val = MO.getFPImm()->getValueAPF(); bool ignored; Val.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored); MCOp = MCOperand::CreateFPImm(Val.convertToDouble()); break; } OutMI.addOperand(MCOp); } } <|endoftext|>
<commit_before>// This code implements the ability to interrupt executing Python code using // the standard R interrupt handling mechanism. // // Since execution of Python code occurs within native C++ code the normal R // interpeter checking for interrupts that occurs during do_eval does not have // a chance to execute. Typically within Rcpp packages long running user code // will call Rcpp::checkForInterrupts periodically to check for an interrupt // and exit via an exception if there is one. However there is no opportunity // to do this during Python execution, so we need to find a way to get periodic // callbacks during the Python interpeter's processing to perform this check. // // This is provided for via the Py_AddPendingCall function, which enables the // scheduling of a C callabck on the main interpeter thread *during* the // execution of Python code. Unfortunately this call occurs very eagerly, so we // can't just schedule a callback and have the callback reschedule itself (this // completely swamps the interpeteter). Rather, we need to have a background // thread that will perform the Py_AddPendingCall on a throttled basis (both // time wise and in terms of only scheduling an additional callback while the // Python interpeter remains running). // // Having arranged for callbacks during Python interpretation at the // appropriate rate, we then need to interact with R to check for a user // interrupt, then interact with Python to notify it of any interrupt. We poll // for interrupts in R using the same technique as Rcpp::checkForException. If // we determine that an interrupt has occurred we call PyErr_SetInterrupt, // which signals Python that an interrupt has been requested, which will // ultimately result in a KeyboardInterrupt error being raised. #include "interrupt.h" #include "libpython.h" using namespace libpython; #include "tinythread.h" using namespace tthread; #include <Rinternals.h> namespace { // Class that is used to signal the need to poll for interrupts between // threads. The function called by the Python interpreter during execution // (pollForInterrupts) always calls requestPolling to keep polling alive. The // background thread periodically attmeps to "collect" this request and if // successful re-schedules the pollForInterrupts function using // Py_AddPendingCall. This allows us to prevent the background thread from // continually scheduling pollForInterrupts even when the Python interpreter is // not running (because once pollForInterrupts is no longer being called by the // Python interpreter no additonal calls to pollForInterrupts will be // scheduled) class InterruptPollingSignal { public: InterruptPollingSignal() : pollingRequested_(true) {} void requestPolling() { lock_guard<mutex> lock(mutex_); pollingRequested_ = true; } bool collectRequest() { lock_guard<mutex> lock(mutex_); bool requested = pollingRequested_; pollingRequested_ = false; return requested; } private: InterruptPollingSignal(const InterruptPollingSignal& other); InterruptPollingSignal& operator=(const InterruptPollingSignal&); private: mutex mutex_; bool pollingRequested_; }; InterruptPollingSignal s_pollingSignal; extern "C" { // Forward declarations int pollForInterrupts(void*); void checkUserInterrupt(void*); // Background thread which re-schedules pollForInterrupts on the main Python // interpreter thread every 100ms so long as the Python interpeter is still // running (when it stops running it will stop calling pollForInterrupts and // the polling signal will not be set). void interruptPollingWorker(void *) { while(true) { // Throttle via sleep this_thread::sleep_for(chrono::milliseconds(1000)); // Schedule polling on the main thread if the interpeter is still running // Note that Py_AddPendingCall is documented to be callable from a background // thread: "This function doesn’t need a current thread state to run, and it // doesn’t need the global interpreter lock." // (see: https://docs.python.org/3/c-api/init.html#c.Py_AddPendingCall) if (s_pollingSignal.collectRequest()) Py_AddPendingCall(pollForInterrupts, NULL); } } // Callback function scheduled to run on the main Python interpreter loop. This // is scheduled using Py_AddPendingCall, which ensures that it is run on the // main thread while the interpreter is executing. Note that we can't just have // this function keep reschedulding itself or the interpreter would be swamped // with just calling and re-calling this function. Rather, we need to throttle // the scheduling of the function by using a background thread + a sleep timer. int pollForInterrupts(void*) { // Check whether an interrupt has been requested by the user. If one // has then set the Python interrupt flag (which will soon after result // in a KeyboardInterrupt error being thrown). if (R_ToplevelExec(checkUserInterrupt, NULL) == FALSE) PyErr_SetInterrupt(); // Request that the background thread schedule us to be called again // (this is delegated to a background thread so that these requests // can be throttled) s_pollingSignal.requestPolling(); // Success return 0; } // Wrapper for calling R_CheckUserInterrupt within R_TolevelExec. Note that // this call will result in R calling it's internal R_ProcessEvents function // which will allow front-ends to pump events, set the interrupt pending flag, // etc. This function may also jump_to_top, but these jumps are caught by // R_ToplevelExec and results in a return value of FALSE. void checkUserInterrupt(void*) { R_CheckUserInterrupt(); } } // extern "C" } // anonymous namespace // Initialize interrupt polling background thread void initialize_interrupt_polling() { thread t(interruptPollingWorker, NULL); t.detach(); } <commit_msg>Revert "check for interrupt every 1000ms rather than 100ms"<commit_after>// This code implements the ability to interrupt executing Python code using // the standard R interrupt handling mechanism. // // Since execution of Python code occurs within native C++ code the normal R // interpeter checking for interrupts that occurs during do_eval does not have // a chance to execute. Typically within Rcpp packages long running user code // will call Rcpp::checkForInterrupts periodically to check for an interrupt // and exit via an exception if there is one. However there is no opportunity // to do this during Python execution, so we need to find a way to get periodic // callbacks during the Python interpeter's processing to perform this check. // // This is provided for via the Py_AddPendingCall function, which enables the // scheduling of a C callabck on the main interpeter thread *during* the // execution of Python code. Unfortunately this call occurs very eagerly, so we // can't just schedule a callback and have the callback reschedule itself (this // completely swamps the interpeteter). Rather, we need to have a background // thread that will perform the Py_AddPendingCall on a throttled basis (both // time wise and in terms of only scheduling an additional callback while the // Python interpeter remains running). // // Having arranged for callbacks during Python interpretation at the // appropriate rate, we then need to interact with R to check for a user // interrupt, then interact with Python to notify it of any interrupt. We poll // for interrupts in R using the same technique as Rcpp::checkForException. If // we determine that an interrupt has occurred we call PyErr_SetInterrupt, // which signals Python that an interrupt has been requested, which will // ultimately result in a KeyboardInterrupt error being raised. #include "interrupt.h" #include "libpython.h" using namespace libpython; #include "tinythread.h" using namespace tthread; #include <Rinternals.h> namespace { // Class that is used to signal the need to poll for interrupts between // threads. The function called by the Python interpreter during execution // (pollForInterrupts) always calls requestPolling to keep polling alive. The // background thread periodically attmeps to "collect" this request and if // successful re-schedules the pollForInterrupts function using // Py_AddPendingCall. This allows us to prevent the background thread from // continually scheduling pollForInterrupts even when the Python interpreter is // not running (because once pollForInterrupts is no longer being called by the // Python interpreter no additonal calls to pollForInterrupts will be // scheduled) class InterruptPollingSignal { public: InterruptPollingSignal() : pollingRequested_(true) {} void requestPolling() { lock_guard<mutex> lock(mutex_); pollingRequested_ = true; } bool collectRequest() { lock_guard<mutex> lock(mutex_); bool requested = pollingRequested_; pollingRequested_ = false; return requested; } private: InterruptPollingSignal(const InterruptPollingSignal& other); InterruptPollingSignal& operator=(const InterruptPollingSignal&); private: mutex mutex_; bool pollingRequested_; }; InterruptPollingSignal s_pollingSignal; extern "C" { // Forward declarations int pollForInterrupts(void*); void checkUserInterrupt(void*); // Background thread which re-schedules pollForInterrupts on the main Python // interpreter thread every 100ms so long as the Python interpeter is still // running (when it stops running it will stop calling pollForInterrupts and // the polling signal will not be set). void interruptPollingWorker(void *) { while(true) { // Throttle via sleep this_thread::sleep_for(chrono::milliseconds(100)); // Schedule polling on the main thread if the interpeter is still running // Note that Py_AddPendingCall is documented to be callable from a background // thread: "This function doesn’t need a current thread state to run, and it // doesn’t need the global interpreter lock." // (see: https://docs.python.org/3/c-api/init.html#c.Py_AddPendingCall) if (s_pollingSignal.collectRequest()) Py_AddPendingCall(pollForInterrupts, NULL); } } // Callback function scheduled to run on the main Python interpreter loop. This // is scheduled using Py_AddPendingCall, which ensures that it is run on the // main thread while the interpreter is executing. Note that we can't just have // this function keep reschedulding itself or the interpreter would be swamped // with just calling and re-calling this function. Rather, we need to throttle // the scheduling of the function by using a background thread + a sleep timer. int pollForInterrupts(void*) { // Check whether an interrupt has been requested by the user. If one // has then set the Python interrupt flag (which will soon after result // in a KeyboardInterrupt error being thrown). if (R_ToplevelExec(checkUserInterrupt, NULL) == FALSE) PyErr_SetInterrupt(); // Request that the background thread schedule us to be called again // (this is delegated to a background thread so that these requests // can be throttled) s_pollingSignal.requestPolling(); // Success return 0; } // Wrapper for calling R_CheckUserInterrupt within R_TolevelExec. Note that // this call will result in R calling it's internal R_ProcessEvents function // which will allow front-ends to pump events, set the interrupt pending flag, // etc. This function may also jump_to_top, but these jumps are caught by // R_ToplevelExec and results in a return value of FALSE. void checkUserInterrupt(void*) { R_CheckUserInterrupt(); } } // extern "C" } // anonymous namespace // Initialize interrupt polling background thread void initialize_interrupt_polling() { thread t(interruptPollingWorker, NULL); t.detach(); } <|endoftext|>
<commit_before>#include <znc/main.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Modules.h> #include <znc/Nick.h> #include <znc/Chan.h> #include <znc/IRCSock.h> #include <znc/version.h> #include <mutex> #include <limits> #include "twitchtmi.h" #include "jload.h" #if (VERSION_MAJOR < 1) || (VERSION_MAJOR == 1 && VERSION_MINOR < 7) #error This module needs at least ZNC 1.7.0 or later. #endif TwitchTMI::~TwitchTMI() { } bool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage) { OnBoot(); if(GetNetwork()) { std::list<CString> channels; for(CChan *ch: GetNetwork()->GetChans()) { ch->SetTopic(CString()); channels.push_back(ch->GetName().substr(1)); } CThreadPool::Get().addJob(new TwitchTMIJob(this, channels)); } if(GetArgs().Token(0) != "FrankerZ") lastFrankerZ = std::numeric_limits<decltype(lastFrankerZ)>::max(); PutIRC("CAP REQ :twitch.tv/membership"); PutIRC("CAP REQ :twitch.tv/commands"); PutIRC("CAP REQ :twitch.tv/tags"); return true; } bool TwitchTMI::OnBoot() { initCurl(); timer = new TwitchTMIUpdateTimer(this); AddTimer(timer); return true; } void TwitchTMI::OnIRCConnected() { PutIRC("CAP REQ :twitch.tv/membership"); PutIRC("CAP REQ :twitch.tv/commands"); PutIRC("CAP REQ :twitch.tv/tags"); } CModule::EModRet TwitchTMI::OnUserRaw(CString &sLine) { if(sLine.Left(5).Equals("WHO #")) return CModule::HALT; if(sLine.Left(5).Equals("AWAY ")) return CModule::HALT; if(sLine.Left(12).Equals("TWITCHCLIENT")) return CModule::HALT; if(sLine.Left(9).Equals("JTVCLIENT")) return CModule::HALT; return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnRawMessage(CMessage &msg) { if(msg.GetCommand().Equals("HOSTTARGET")) { return CModule::HALT; } else if(msg.GetCommand().Equals("CLEARCHAT")) { msg.SetCommand("NOTICE"); if(msg.GetParam(1) != "") { msg.SetParam(1, msg.GetParam(1) + " was timed out."); } else { msg.SetParam(1, "Chat was cleared by a moderator."); } } else if(msg.GetCommand().Equals("USERSTATE")) { return CModule::HALT; } else if(msg.GetCommand().Equals("ROOMSTATE")) { return CModule::HALT; } else if(msg.GetCommand().Equals("RECONNECT")) { return CModule::HALT; } else if(msg.GetCommand().Equals("GLOBALUSERSTATE")) { return CModule::HALT; } else if(msg.GetCommand().Equals("WHISPER")) { msg.SetCommand("PRIVMSG"); } else if(msg.GetCommand().Equals("USERNOTICE")) { //TODO: Translate Tags to useful message msg.SetCommand("PRIVMSG"); msg.SetParam(1, "<<<RESUB>>> " + msg.GetParam(1)); } CString realNick = msg.GetTag("display-name").Trim_n(); if(realNick != "") msg.GetNick().SetNick(realNick); return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey) { return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnPrivTextMessage(CTextMessage &Message) { if(Message.GetNick().GetNick().Equals("jtv")) return CModule::HALT; return CModule::CONTINUE; } void TwitchTMI::PutUserChanMessage(CChan *chan, const CString &from, const CString &msg) { std::stringstream ss; ss << ":" << from << " PRIVMSG " << chan->GetName() << " :"; CString s = ss.str(); PutUser(s + msg); if(!chan->AutoClearChanBuffer() || !GetNetwork()->IsUserOnline() || chan->IsDetached()) chan->AddBuffer(s + "{text}", msg); } CModule::EModRet TwitchTMI::OnChanTextMessage(CTextMessage &Message) { if(Message.GetNick().GetNick().Equals("jtv")) return CModule::HALT; if(Message.GetText() == "FrankerZ" && std::time(nullptr) - lastFrankerZ > 10) { std::stringstream ss; CString mynick = GetNetwork()->GetIRCNick().GetNickMask(); CChan *chan = Message.GetChan(); ss << "PRIVMSG " << chan->GetName() << " :FrankerZ"; PutIRC(ss.str()); CThreadPool::Get().addJob(new GenericJob([]() {}, [this, chan, mynick]() { PutUserChanMessage(chan, mynick, "FrankerZ"); })); lastFrankerZ = std::time(nullptr); } return CModule::CONTINUE; } bool TwitchTMI::OnServerCapAvailable(const CString &sCap) { if(sCap == "twitch.tv/membership") return true; else if(sCap == "twitch.tv/tags") return true; else if(sCap == "twitch.tv/commands") return true; return false; } CModule::EModRet TwitchTMI::OnUserTextMessage(CTextMessage &msg) { if(msg.GetTarget().Left(1).Equals("#")) return CModule::CONTINUE; msg.SetText(msg.GetText().insert(0, " ").insert(0, msg.GetTarget()).insert(0, "/w ")); msg.SetTarget("#jtv"); return CModule::CONTINUE; } TwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod) :CTimer(tmod, 30, 0, "TwitchTMIUpdateTimer", "Downloads Twitch information") ,mod(tmod) { } void TwitchTMIUpdateTimer::RunJob() { if(!mod->GetNetwork()) return; std::list<CString> channels; for(CChan *chan: mod->GetNetwork()->GetChans()) { channels.push_back(chan->GetName().substr(1)); } CThreadPool::Get().addJob(new TwitchTMIJob(mod, channels)); } static std::mutex job_thread_lock; void TwitchTMIJob::runThread() { std::unique_lock<std::mutex> lock_guard(job_thread_lock, std::try_to_lock); if(!lock_guard.owns_lock()) { channels.clear(); return; } titles.resize(channels.size()); lives.resize(channels.size()); int i = -1; for(const CString &channel: channels) { i++; std::stringstream ss, ss2; ss << "https://api.twitch.tv/kraken/channels/" << channel; ss2 << "https://api.twitch.tv/kraken/streams/" << channel; CString url = ss.str(); CString url2 = ss2.str(); Json::Value root = getJsonFromUrl(url.c_str(), "Accept: application/vnd.twitchtv.v3+json"); Json::Value root2 = getJsonFromUrl(url2.c_str(), "Accept: application/vnd.twitchtv.v3+json"); if(!root.isNull()) { Json::Value &titleVal = root["status"]; titles[i] = CString(); if(!titleVal.isString()) titleVal = root["title"]; if(titleVal.isString()) { titles[i] = titleVal.asString(); titles[i].Trim(); } } lives[i] = false; if(!root2.isNull()) { Json::Value &streamVal = root2["stream"]; if(!streamVal.isNull()) lives[i] = true; } } } void TwitchTMIJob::runMain() { int i = -1; for(const CString &channel: channels) { i++; CChan *chan = mod->GetNetwork()->FindChan(CString("#") + channel); if(!chan) continue; if(!titles[i].empty() && chan->GetTopic() != titles[i]) { chan->SetTopic(titles[i]); chan->SetTopicOwner("jtv"); chan->SetTopicDate((unsigned long)time(nullptr)); std::stringstream ss; ss << ":jtv TOPIC #" << channel << " :" << titles[i]; mod->PutUser(ss.str()); } auto it = mod->liveChannels.find(channel); if(it != mod->liveChannels.end()) { if(!lives[i]) { mod->liveChannels.erase(it); mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went offline! <<<"); } } else { if(lives[i]) { mod->liveChannels.insert(channel); mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went live! <<<"); } } } } template<> void TModInfo<TwitchTMI>(CModInfo &info) { info.SetWikiPage("Twitch"); info.SetHasArgs(true); } NETWORKMODULEDEFS(TwitchTMI, "Twitch IRC helper module") <commit_msg>Store topic and its time as NV<commit_after>#include <znc/main.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Modules.h> #include <znc/Nick.h> #include <znc/Chan.h> #include <znc/IRCSock.h> #include <znc/version.h> #include <mutex> #include <limits> #include "twitchtmi.h" #include "jload.h" #if (VERSION_MAJOR < 1) || (VERSION_MAJOR == 1 && VERSION_MINOR < 7) #error This module needs at least ZNC 1.7.0 or later. #endif TwitchTMI::~TwitchTMI() { } bool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage) { OnBoot(); if(GetNetwork()) { std::list<CString> channels; for(CChan *ch: GetNetwork()->GetChans()) { CString sname = ch->GetName().substr(1); channels.push_back(sname); ch->SetTopic(GetNV("tmi_topic_" + sname)); ch->SetTopicOwner("jtv"); ch->SetTopicDate(GetNV("tmi_topic_time_" + sname).ToULong()); } CThreadPool::Get().addJob(new TwitchTMIJob(this, channels)); } if(GetArgs().Token(0) != "FrankerZ") lastFrankerZ = std::numeric_limits<decltype(lastFrankerZ)>::max(); PutIRC("CAP REQ :twitch.tv/membership"); PutIRC("CAP REQ :twitch.tv/commands"); PutIRC("CAP REQ :twitch.tv/tags"); return true; } bool TwitchTMI::OnBoot() { initCurl(); timer = new TwitchTMIUpdateTimer(this); AddTimer(timer); return true; } void TwitchTMI::OnIRCConnected() { PutIRC("CAP REQ :twitch.tv/membership"); PutIRC("CAP REQ :twitch.tv/commands"); PutIRC("CAP REQ :twitch.tv/tags"); } CModule::EModRet TwitchTMI::OnUserRaw(CString &sLine) { if(sLine.Left(5).Equals("WHO #")) return CModule::HALT; if(sLine.Left(5).Equals("AWAY ")) return CModule::HALT; if(sLine.Left(12).Equals("TWITCHCLIENT")) return CModule::HALT; if(sLine.Left(9).Equals("JTVCLIENT")) return CModule::HALT; return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnRawMessage(CMessage &msg) { if(msg.GetCommand().Equals("HOSTTARGET")) { return CModule::HALT; } else if(msg.GetCommand().Equals("CLEARCHAT")) { msg.SetCommand("NOTICE"); if(msg.GetParam(1) != "") { msg.SetParam(1, msg.GetParam(1) + " was timed out."); } else { msg.SetParam(1, "Chat was cleared by a moderator."); } } else if(msg.GetCommand().Equals("USERSTATE")) { return CModule::HALT; } else if(msg.GetCommand().Equals("ROOMSTATE")) { return CModule::HALT; } else if(msg.GetCommand().Equals("RECONNECT")) { return CModule::HALT; } else if(msg.GetCommand().Equals("GLOBALUSERSTATE")) { return CModule::HALT; } else if(msg.GetCommand().Equals("WHISPER")) { msg.SetCommand("PRIVMSG"); } else if(msg.GetCommand().Equals("USERNOTICE")) { //TODO: Translate Tags to useful message msg.SetCommand("PRIVMSG"); msg.SetParam(1, "<<<RESUB>>> " + msg.GetParam(1)); } CString realNick = msg.GetTag("display-name").Trim_n(); if(realNick != "") msg.GetNick().SetNick(realNick); return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey) { return CModule::CONTINUE; } CModule::EModRet TwitchTMI::OnPrivTextMessage(CTextMessage &Message) { if(Message.GetNick().GetNick().Equals("jtv")) return CModule::HALT; return CModule::CONTINUE; } void TwitchTMI::PutUserChanMessage(CChan *chan, const CString &from, const CString &msg) { std::stringstream ss; ss << ":" << from << " PRIVMSG " << chan->GetName() << " :"; CString s = ss.str(); PutUser(s + msg); if(!chan->AutoClearChanBuffer() || !GetNetwork()->IsUserOnline() || chan->IsDetached()) chan->AddBuffer(s + "{text}", msg); } CModule::EModRet TwitchTMI::OnChanTextMessage(CTextMessage &Message) { if(Message.GetNick().GetNick().Equals("jtv")) return CModule::HALT; if(Message.GetText() == "FrankerZ" && std::time(nullptr) - lastFrankerZ > 10) { std::stringstream ss; CString mynick = GetNetwork()->GetIRCNick().GetNickMask(); CChan *chan = Message.GetChan(); ss << "PRIVMSG " << chan->GetName() << " :FrankerZ"; PutIRC(ss.str()); CThreadPool::Get().addJob(new GenericJob([]() {}, [this, chan, mynick]() { PutUserChanMessage(chan, mynick, "FrankerZ"); })); lastFrankerZ = std::time(nullptr); } return CModule::CONTINUE; } bool TwitchTMI::OnServerCapAvailable(const CString &sCap) { if(sCap == "twitch.tv/membership") return true; else if(sCap == "twitch.tv/tags") return true; else if(sCap == "twitch.tv/commands") return true; return false; } CModule::EModRet TwitchTMI::OnUserTextMessage(CTextMessage &msg) { if(msg.GetTarget().Left(1).Equals("#")) return CModule::CONTINUE; msg.SetText(msg.GetText().insert(0, " ").insert(0, msg.GetTarget()).insert(0, "/w ")); msg.SetTarget("#jtv"); return CModule::CONTINUE; } TwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod) :CTimer(tmod, 30, 0, "TwitchTMIUpdateTimer", "Downloads Twitch information") ,mod(tmod) { } void TwitchTMIUpdateTimer::RunJob() { if(!mod->GetNetwork()) return; std::list<CString> channels; for(CChan *chan: mod->GetNetwork()->GetChans()) { channels.push_back(chan->GetName().substr(1)); } CThreadPool::Get().addJob(new TwitchTMIJob(mod, channels)); } static std::mutex job_thread_lock; void TwitchTMIJob::runThread() { std::unique_lock<std::mutex> lock_guard(job_thread_lock, std::try_to_lock); if(!lock_guard.owns_lock()) { channels.clear(); return; } titles.resize(channels.size()); lives.resize(channels.size()); int i = -1; for(const CString &channel: channels) { i++; std::stringstream ss, ss2; ss << "https://api.twitch.tv/kraken/channels/" << channel; ss2 << "https://api.twitch.tv/kraken/streams/" << channel; CString url = ss.str(); CString url2 = ss2.str(); Json::Value root = getJsonFromUrl(url.c_str(), "Accept: application/vnd.twitchtv.v3+json"); Json::Value root2 = getJsonFromUrl(url2.c_str(), "Accept: application/vnd.twitchtv.v3+json"); if(!root.isNull()) { Json::Value &titleVal = root["status"]; titles[i] = CString(); if(!titleVal.isString()) titleVal = root["title"]; if(titleVal.isString()) { titles[i] = titleVal.asString(); titles[i].Trim(); } } lives[i] = false; if(!root2.isNull()) { Json::Value &streamVal = root2["stream"]; if(!streamVal.isNull()) lives[i] = true; } } } void TwitchTMIJob::runMain() { int i = -1; for(const CString &channel: channels) { i++; CChan *chan = mod->GetNetwork()->FindChan(CString("#") + channel); if(!chan) continue; if(!titles[i].empty() && chan->GetTopic() != titles[i]) { unsigned long topic_time = (unsigned long)time(nullptr); chan->SetTopic(titles[i]); chan->SetTopicOwner("jtv"); chan->SetTopicDate(topic_time); std::stringstream ss; ss << ":jtv TOPIC #" << channel << " :" << titles[i]; mod->PutUser(ss.str()); mod->SetNV("tmi_topic_" + channel, titles[i], true); mod->SetNV("tmi_topic_time_" + channel, CString(topic_time), true); } auto it = mod->liveChannels.find(channel); if(it != mod->liveChannels.end()) { if(!lives[i]) { mod->liveChannels.erase(it); mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went offline! <<<"); } } else { if(lives[i]) { mod->liveChannels.insert(channel); mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went live! <<<"); } } } } template<> void TModInfo<TwitchTMI>(CModInfo &info) { info.SetWikiPage("Twitch"); info.SetHasArgs(true); } NETWORKMODULEDEFS(TwitchTMI, "Twitch IRC helper module") <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2013 Daniel Mansfield 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. */ #ifndef INVENTORY_HPP #define INVENTORY_HPP #include "item.hpp" #include "weapon.hpp" #include "armour.hpp" #include <list> #include <utility> #include <iostream> #include "JsonBox.h" class Inventory { public: // Whilst weapons and armour are also items, they have their own // specific properties and so cannot be stored inside the same // list as the items. We use a list and not a vector as inventories // are highly mutable. This way they can also be efficiently sorted // The first element of the pair stores a pointer to the item in // the item/weapon/armour atlas, defined in main(), and the second // element stores the quantity of the item std::list<std::pair<Item*, int>> items; std::list<std::pair<Weapon*, int>> weapons; std::list<std::pair<Armour*, int>> armour; Inventory() { } // Load the inventory from a JSON value Inventory(JsonBox::Value o, std::map<std::string, Item>& itemAtlas, std::map<std::string, Weapon>& weaponAtlas, std::map<std::string, Armour>& armourAtlas) { for(auto item : o["items"].getArray()) { std::string itemName = item.getArray()[0].getString(); int itemQuantity = item.getArray()[1].getInteger(); this->items.push_back(std::make_pair(&itemAtlas[itemName], itemQuantity)); } for(auto weapon : o["weapons"].getArray()) { std::string weaponName = weapon.getArray()[0].getString(); int weaponQuantity = weapon.getArray()[1].getInteger(); this->weapons.push_back(std::make_pair(&weaponAtlas[weaponName], weaponQuantity)); } for(auto armour : o["armour"].getArray()) { std::string armourName = armour.getArray()[0].getString(); int armourQuantity = armour.getArray()[1].getInteger(); this->armour.push_back(std::make_pair(&armourAtlas[armourName], armourQuantity)); } } Inventory(std::list<std::pair<Item*, int>> items, std::list<std::pair<Weapon*, int>> weapons, std::list<std::pair<Armour*, int>> armour) { this->items = items; this->weapons = weapons; this->armour = armour; } // Remove all items from the inventory, destroying them in the process // (They remain in the atlas though) void clear() { this->items.clear(); this->weapons.clear(); this->armour.clear(); } // Add an item to the inventory, specified by a pointer to it // from the item atlas (technically does not need to point there, // but it should anyway) void add_item(Item* item, int count) { // Perform the same operation as merging, but for a single item for(auto& it : this->items) { if(it.first == item) { it.second += count; return; } } // If the item doesn't already exist in the inventory, then a // pair must be created too this->items.push_back(std::make_pair(item, count)); } // Same as for items void add_weapon(Weapon* weapon, int count) { for(auto& it : this->weapons) { if(it.first == weapon) { it.second += count; return; } } this->weapons.push_back(std::make_pair(weapon, count)); } // Same as for items void add_armour(Armour* armour, int count) { for(auto& it : this->armour) { if(it.first == armour) { it.second += count; return; } } this->armour.push_back(std::make_pair(armour, count)); } // Remove the specified number of items from the inventory void remove_item(Item* item, int count) { // Iterate through the items, and if they are found then decrease // the quantity by the quantity removed for(auto& it : this->items) { if(it.first == item) { it.second -= count; break; } } // Iterate through the list again, and remove any elements from // the list that have zero or less for their quantity // We do this in two passes because removing an element from // a list during a for loop invalidates the iterators, and the // loop stops working this->items.remove_if([](std::pair<Item*, int>& element) { return element.second < 1; }); } // Same as for items void remove_weapon(Weapon* weapon, int count) { for(auto& it : this->weapons) { if(it.first == weapon) { it.second -= count; break; } } this->weapons.remove_if([](std::pair<Weapon*, int>& element) { return element.second < 1; }); } // Same as for items void remove_armour(Armour* armour, int count) { for(auto& it : this->armour) { if(it.first == armour) { it.second -= count; break; } } this->armour.remove_if([](std::pair<Armour*, int>& element) { return element.second < 1; }); } // Returns the count of the specified item unsigned int has_item(Item* item) { unsigned int count = 0; for(auto it : this->items) { if(it.first == item) ++count; } return count; } // Same for weapon unsigned int has_weapon(Weapon* weapon) { unsigned int count = 0; for(auto it : this->weapons) { if(it.first == weapon) ++count; } return count; } // Same for armour unsigned int has_armour(Armour* armour) { unsigned int count = 0; for(auto it : this->armour) { if(it.first == armour) ++count; } return count; } // Merge the specified inventory with the current one, adding // item quantities together if they already exist and adding the item // into a new slot if they do not void merge(Inventory* inventory) { // You can't merge an inventory with itself! if(inventory == this) return; // Loop through the items to be added, and add them. Our addition // function will take care of everything else for us for(auto it : inventory->items) { this->add_item(it.first, it.second); } // Do the same for the weapons for(auto it : inventory->weapons) { this->add_weapon(it.first, it.second); } // Do the same for the armour for(auto it : inventory->armour) { this->add_armour(it.first, it.second); } return; } // Output a list of the items onto stdout, formatted nicely and // numbered if required int print_items(bool label = false) { unsigned int i = 1; for(auto it : this->items) { // Number the items if asked if(label) std::cout << i++ << ": "; // Output the item name, quantity and description, e.g. // Gold Piece (29) - Glimmering discs of wealth std::cout << it.first->name << " (" << it.second << ") - "; std::cout << it.first->description << std::endl; } // Return the number of items outputted, for convenience return this->items.size(); } // Same as for items int print_weapons(bool label = false) { unsigned int i = 1; for(auto it : this->weapons) { if(label) std::cout << i++ << ": "; std::cout << it.first->name << " (" << it.second << ") - "; std::cout << it.first->description << std::endl; } return this->weapons.size(); } // Same as for items int print_armour(bool label = false) { unsigned int i = 1; for(auto it : this->armour) { if(label) std::cout << i++ << ": "; std::cout << it.first->name << " (" << it.second << ") - "; std::cout << it.first->description << std::endl; } return this->armour.size(); } // Print the entire inventory; items, then weapons, then armour, // but if the inventory is empty then output "Nothing" void print(bool label = false) { if(this->items.size() == 0 && this->weapons.size() == 0 && this->armour.size() == 0) { std::cout << "Nothing" << std::endl; } else { this->print_items(label); this->print_weapons(label); this->print_armour(label); } return; } JsonBox::Object to_json() { JsonBox::Object o; JsonBox::Array a; for(auto item : this->items) { JsonBox::Array pair; pair.push_back(JsonBox::Value(item.first->id)); pair.push_back(JsonBox::Value(item.second)); a.push_back(JsonBox::Value(pair)); } o["items"] = JsonBox::Value(a); a.clear(); for(auto weapon : this->weapons) { JsonBox::Array pair; pair.push_back(JsonBox::Value(weapon.first->id)); pair.push_back(JsonBox::Value(weapon.second)); a.push_back(JsonBox::Value(pair)); } o["weapons"] = a; a.clear(); for(auto armour : this->armour) { JsonBox::Array pair; pair.push_back(JsonBox::Value(armour.first->id)); pair.push_back(JsonBox::Value(armour.second)); a.push_back(JsonBox::Value(pair)); } o["armour"] = a; return o; } }; #endif /* INVENTORY_HPP */ <commit_msg>Fixed JSON weirdness<commit_after>/* The MIT License (MIT) Copyright (c) 2013 Daniel Mansfield 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. */ #ifndef INVENTORY_HPP #define INVENTORY_HPP #include "item.hpp" #include "weapon.hpp" #include "armour.hpp" #include <list> #include <utility> #include <iostream> #include "JsonBox.h" class Inventory { public: // Whilst weapons and armour are also items, they have their own // specific properties and so cannot be stored inside the same // list as the items. We use a list and not a vector as inventories // are highly mutable. This way they can also be efficiently sorted // The first element of the pair stores a pointer to the item in // the item/weapon/armour atlas, defined in main(), and the second // element stores the quantity of the item std::list<std::pair<Item*, int>> items; std::list<std::pair<Weapon*, int>> weapons; std::list<std::pair<Armour*, int>> armour; Inventory() { } // Load the inventory from a JSON value Inventory(JsonBox::Value v, std::map<std::string, Item>& itemAtlas, std::map<std::string, Weapon>& weaponAtlas, std::map<std::string, Armour>& armourAtlas) { JsonBox::Object o = v.getObject(); for(auto item : o["items"].getArray()) { std::string itemName = item.getArray()[0].getString(); int itemQuantity = item.getArray()[1].getInteger(); this->items.push_back(std::make_pair(&itemAtlas[itemName], itemQuantity)); } for(auto weapon : o["weapons"].getArray()) { std::string weaponName = weapon.getArray()[0].getString(); int weaponQuantity = weapon.getArray()[1].getInteger(); this->weapons.push_back(std::make_pair(&weaponAtlas[weaponName], weaponQuantity)); } for(auto armour : o["armour"].getArray()) { std::string armourName = armour.getArray()[0].getString(); int armourQuantity = armour.getArray()[1].getInteger(); this->armour.push_back(std::make_pair(&armourAtlas[armourName], armourQuantity)); } } Inventory(std::list<std::pair<Item*, int>> items, std::list<std::pair<Weapon*, int>> weapons, std::list<std::pair<Armour*, int>> armour) { this->items = items; this->weapons = weapons; this->armour = armour; } // Remove all items from the inventory, destroying them in the process // (They remain in the atlas though) void clear() { this->items.clear(); this->weapons.clear(); this->armour.clear(); } // Add an item to the inventory, specified by a pointer to it // from the item atlas (technically does not need to point there, // but it should anyway) void add_item(Item* item, int count) { // Perform the same operation as merging, but for a single item for(auto& it : this->items) { if(it.first == item) { it.second += count; return; } } // If the item doesn't already exist in the inventory, then a // pair must be created too this->items.push_back(std::make_pair(item, count)); } // Same as for items void add_weapon(Weapon* weapon, int count) { for(auto& it : this->weapons) { if(it.first == weapon) { it.second += count; return; } } this->weapons.push_back(std::make_pair(weapon, count)); } // Same as for items void add_armour(Armour* armour, int count) { for(auto& it : this->armour) { if(it.first == armour) { it.second += count; return; } } this->armour.push_back(std::make_pair(armour, count)); } // Remove the specified number of items from the inventory void remove_item(Item* item, int count) { // Iterate through the items, and if they are found then decrease // the quantity by the quantity removed for(auto& it : this->items) { if(it.first == item) { it.second -= count; break; } } // Iterate through the list again, and remove any elements from // the list that have zero or less for their quantity // We do this in two passes because removing an element from // a list during a for loop invalidates the iterators, and the // loop stops working this->items.remove_if([](std::pair<Item*, int>& element) { return element.second < 1; }); } // Same as for items void remove_weapon(Weapon* weapon, int count) { for(auto& it : this->weapons) { if(it.first == weapon) { it.second -= count; break; } } this->weapons.remove_if([](std::pair<Weapon*, int>& element) { return element.second < 1; }); } // Same as for items void remove_armour(Armour* armour, int count) { for(auto& it : this->armour) { if(it.first == armour) { it.second -= count; break; } } this->armour.remove_if([](std::pair<Armour*, int>& element) { return element.second < 1; }); } // Returns the count of the specified item unsigned int has_item(Item* item) { unsigned int count = 0; for(auto it : this->items) { if(it.first == item) ++count; } return count; } // Same for weapon unsigned int has_weapon(Weapon* weapon) { unsigned int count = 0; for(auto it : this->weapons) { if(it.first == weapon) ++count; } return count; } // Same for armour unsigned int has_armour(Armour* armour) { unsigned int count = 0; for(auto it : this->armour) { if(it.first == armour) ++count; } return count; } // Merge the specified inventory with the current one, adding // item quantities together if they already exist and adding the item // into a new slot if they do not void merge(Inventory* inventory) { // You can't merge an inventory with itself! if(inventory == this) return; // Loop through the items to be added, and add them. Our addition // function will take care of everything else for us for(auto it : inventory->items) { this->add_item(it.first, it.second); } // Do the same for the weapons for(auto it : inventory->weapons) { this->add_weapon(it.first, it.second); } // Do the same for the armour for(auto it : inventory->armour) { this->add_armour(it.first, it.second); } return; } // Output a list of the items onto stdout, formatted nicely and // numbered if required int print_items(bool label = false) { unsigned int i = 1; for(auto it : this->items) { // Number the items if asked if(label) std::cout << i++ << ": "; // Output the item name, quantity and description, e.g. // Gold Piece (29) - Glimmering discs of wealth std::cout << it.first->name << " (" << it.second << ") - "; std::cout << it.first->description << std::endl; } // Return the number of items outputted, for convenience return this->items.size(); } // Same as for items int print_weapons(bool label = false) { unsigned int i = 1; for(auto it : this->weapons) { if(label) std::cout << i++ << ": "; std::cout << it.first->name << " (" << it.second << ") - "; std::cout << it.first->description << std::endl; } return this->weapons.size(); } // Same as for items int print_armour(bool label = false) { unsigned int i = 1; for(auto it : this->armour) { if(label) std::cout << i++ << ": "; std::cout << it.first->name << " (" << it.second << ") - "; std::cout << it.first->description << std::endl; } return this->armour.size(); } // Print the entire inventory; items, then weapons, then armour, // but if the inventory is empty then output "Nothing" void print(bool label = false) { if(this->items.size() == 0 && this->weapons.size() == 0 && this->armour.size() == 0) { std::cout << "Nothing" << std::endl; } else { this->print_items(label); this->print_weapons(label); this->print_armour(label); } return; } JsonBox::Object to_json() { JsonBox::Object o; JsonBox::Array a; for(auto item : this->items) { JsonBox::Array pair; pair.push_back(JsonBox::Value(item.first->id)); pair.push_back(JsonBox::Value(item.second)); a.push_back(JsonBox::Value(pair)); } o["items"] = JsonBox::Value(a); a.clear(); for(auto weapon : this->weapons) { JsonBox::Array pair; pair.push_back(JsonBox::Value(weapon.first->id)); pair.push_back(JsonBox::Value(weapon.second)); a.push_back(JsonBox::Value(pair)); } o["weapons"] = a; a.clear(); for(auto armour : this->armour) { JsonBox::Array pair; pair.push_back(JsonBox::Value(armour.first->id)); pair.push_back(JsonBox::Value(armour.second)); a.push_back(JsonBox::Value(pair)); } o["armour"] = a; return o; } }; #endif /* INVENTORY_HPP */ <|endoftext|>
<commit_before>#include"all_defines.hpp" #include"aio.hpp" #include<unistd.h> #include<errno.h> #include<signal.h> #include<fcntl.h> // used for error reporting before aborting #include<iostream> /* POSIX-based asynchronous I/O and signal handling Note that we don't program to the letter of the POSIX specs: AFAIK no actual OS conforms perfectly to POSIX. Preferably we try to be somewhat more resilient and try to be more defensive when making system calls. */ /*self-pipe trick with SIGCHLD*/ int sigchld_wr, sigchld_rd; /*PLANNED (not yet implemented) When compiled single_threaded, signal handlers also write to sigchld_wr, in order to (hopefully!) interrupt pending select()/poll()'s. We don't depend on this too much, because we will still raise flags somewhere - we only depend on it to interrupt our calls. When compiled without single_threaded, signals are blocked on all threads, then at initialization we start a "hidden" thread whose sole purpose is to wait for signals. */ /*SIGCHLD Known issues: On Linux < 2.4, each thread's child processes belonged only to that thread; this meant (1) SIGCHLD gets sent exactly to the thread which launched that process, and nobody else, and (2) a thread couldn't waitpid() on any other thread's child process. Both behaviors are not POSIX compliant. I also can't think of a way to handle those properly, at least not with the fact that the events system in `hl` may be launched from any of N worker threads. For Linux >= 2.4, a thread could now waitpid() on other thread's child processes. However, AFAIK (can't find references regarding exact behavior) SIGCHLD is still sent to the launching thread. For Linux >= 2.6, we have NPTL, which is supposedly correctly POSIX. The code here *should* work on Linux 2.4, assuming that write() from multiple threads simultaneously gets properly handled (locked!!) by the OS. */ static void sigchld_handler(int) { ssize_t rv; char buf[1]; /*exact data doesn't matter*/ do { errno = 0; rv = write(sigchld_wr, buf, 1); /*our signal installer actually masks out all other signals for this handler, so we shouldn't get EINTR, but better safe than sorry... */ } while(rv < 0 && errno == EINTR); /*All other errors get ignored!*/ /*Errors: EAGAIN - we *shouldn't* mark sigchld_wr as nonblocking EBADF - pretty bad problem, means we failed to init, but we *do* check the pipe FD's at init time before we even install this sighandler. EFAULT - nasty, means buf is segfaultable, meaning we probably can't return anyway. EFBIG - not writing to a file, just a pipe. EINTR - handled by restarting the call. EINVAL - pretty bad problem, means we failed to init EIO - not writing to a file, just a pipe. ENOSPC - that's OK, we only care that there's data on the pipe to wake up the select() call EPIPE - will only happen when we're cleaning up and closing everything, so won't matter if signal is lost, we're already exiting. */ } /*FD_CLOEXEC Known Issues: Normally FD's will remain open across fork() and exec() calls. This is useful when piping. Unfortunately, we rarely even want to use piping; almost definitely we will pipe only a few FD's. Thus, in the general case, when acquiring FD's from the OS, we must very soon force them to FD_CLOEXEC. However, this has problems in a multithreaded implementation which fork()s. It's possible for one thread to fork()+exec() while another thread has just, say, called socket(). In this case the returned socket will *not* have FD_CLOEXEC and will remain open in the child process, reducing the number of useable FD's in the process, as well as other weird stuff like tape drives not rewinding... This can be solved in many ways: 1. Ignore CLOEXEC. After fork() and before exec(), close everything except for any redirections we want. This means about sysconf(_SC_OPEN_MAX) calls to close(). Now suppose _SC_OPEN_MAX is 65,536... 2. Like above. But we just keep closing until we get N consecutive EBADF failures for close(), where N is some big number. Hackish solution which depends on the probability that FD numbers will skip at most N consecutive values. 3. Keep track of the largest ever FD we ever see from any source. Just loop up to that instead of sysconf(_SC_OPEN_MAX), which should be faster because the largest FD will be much smaller than _SC_OPEN_MAX. However when multithreaded we have to rely on locks to keep track of the largest seen FD anyway, so.... 4. Protect all open()+fcntl()/socket()+fcntl/pipe()+fcntl(), as well as fork(), with a mutex. While fork() will also duplicate the mutex in the child, we do an exec() soon anwyay, so the child's mutex copy gets implicitly deleted. #4 above seems the best solution but it *might* mean that some LIBC and other third-party library routines can't be safely used (since they would internally open some FD's, which we can't protect with a mutex). */ static void force_cloexec(int fd) { int flag; do { errno = 0; flag = fcntl(fd, F_GETFD); } while(flag < 0 && errno == EINTR); if(flag < 0) { std::cerr << "cloexec: error during getting of flag" << std::endl; exit(1); } long lflag = ((long) (flag)) | FD_CLOEXEC; int rv; do { errno = 0; rv = fcntl(fd, F_SETFD, lflag); } while(rv < 0 && errno == EINTR); if(flag < 0) { std::cerr << "cloexec: error during setting of flag" << std::endl; exit(1); } } <commit_msg>src/ios_posix.cpp: Made variables static<commit_after>#include"all_defines.hpp" #include"aio.hpp" #include<unistd.h> #include<errno.h> #include<signal.h> #include<fcntl.h> // used for error reporting before aborting #include<iostream> /* POSIX-based asynchronous I/O and signal handling Note that we don't program to the letter of the POSIX specs: AFAIK no actual OS conforms perfectly to POSIX. Preferably we try to be somewhat more resilient and try to be more defensive when making system calls. */ /*self-pipe trick with SIGCHLD*/ static int sigchld_wr, sigchld_rd; /*PLANNED (not yet implemented) When compiled single_threaded, signal handlers also write to sigchld_wr, in order to (hopefully!) interrupt pending select()/poll()'s. We don't depend on this too much, because we will still raise flags somewhere - we only depend on it to interrupt our calls. When compiled without single_threaded, signals are blocked on all threads, then at initialization we start a "hidden" thread whose sole purpose is to wait for signals. */ /*SIGCHLD Known issues: On Linux < 2.4, each thread's child processes belonged only to that thread; this meant (1) SIGCHLD gets sent exactly to the thread which launched that process, and nobody else, and (2) a thread couldn't waitpid() on any other thread's child process. Both behaviors are not POSIX compliant. I also can't think of a way to handle those properly, at least not with the fact that the events system in `hl` may be launched from any of N worker threads. For Linux >= 2.4, a thread could now waitpid() on other thread's child processes. However, AFAIK (can't find references regarding exact behavior) SIGCHLD is still sent to the launching thread. For Linux >= 2.6, we have NPTL, which is supposedly correctly POSIX. The code here *should* work on Linux 2.4, assuming that write() from multiple threads simultaneously gets properly handled (locked!!) by the OS. */ static void sigchld_handler(int) { ssize_t rv; char buf[1]; /*exact data doesn't matter*/ do { errno = 0; rv = write(sigchld_wr, buf, 1); /*our signal installer actually masks out all other signals for this handler, so we shouldn't get EINTR, but better safe than sorry... */ } while(rv < 0 && errno == EINTR); /*All other errors get ignored!*/ /*Errors: EAGAIN - we *shouldn't* mark sigchld_wr as nonblocking EBADF - pretty bad problem, means we failed to init, but we *do* check the pipe FD's at init time before we even install this sighandler. EFAULT - nasty, means buf is segfaultable, meaning we probably can't return anyway. EFBIG - not writing to a file, just a pipe. EINTR - handled by restarting the call. EINVAL - pretty bad problem, means we failed to init EIO - not writing to a file, just a pipe. ENOSPC - that's OK, we only care that there's data on the pipe to wake up the select() call EPIPE - will only happen when we're cleaning up and closing everything, so won't matter if signal is lost, we're already exiting. */ } /*FD_CLOEXEC Known Issues: Normally FD's will remain open across fork() and exec() calls. This is useful when piping. Unfortunately, we rarely even want to use piping; almost definitely we will pipe only a few FD's. Thus, in the general case, when acquiring FD's from the OS, we must very soon force them to FD_CLOEXEC. However, this has problems in a multithreaded implementation which fork()s. It's possible for one thread to fork()+exec() while another thread has just, say, called socket(). In this case the returned socket will *not* have FD_CLOEXEC and will remain open in the child process, reducing the number of useable FD's in the process, as well as other weird stuff like tape drives not rewinding... This can be solved in many ways: 1. Ignore CLOEXEC. After fork() and before exec(), close everything except for any redirections we want. This means about sysconf(_SC_OPEN_MAX) calls to close(). Now suppose _SC_OPEN_MAX is 65,536... 2. Like above. But we just keep closing until we get N consecutive EBADF failures for close(), where N is some big number. Hackish solution which depends on the probability that FD numbers will skip at most N consecutive values. 3. Keep track of the largest ever FD we ever see from any source. Just loop up to that instead of sysconf(_SC_OPEN_MAX), which should be faster because the largest FD will be much smaller than _SC_OPEN_MAX. However when multithreaded we have to rely on locks to keep track of the largest seen FD anyway, so.... 4. Protect all open()+fcntl()/socket()+fcntl/pipe()+fcntl(), as well as fork(), with a mutex. While fork() will also duplicate the mutex in the child, we do an exec() soon anwyay, so the child's mutex copy gets implicitly deleted. #4 above seems the best solution but it *might* mean that some LIBC and other third-party library routines can't be safely used (since they would internally open some FD's, which we can't protect with a mutex). */ static void force_cloexec(int fd) { int flag; do { errno = 0; flag = fcntl(fd, F_GETFD); } while(flag < 0 && errno == EINTR); if(flag < 0) { std::cerr << "cloexec: error during getting of flag" << std::endl; exit(1); } long lflag = ((long) (flag)) | FD_CLOEXEC; int rv; do { errno = 0; rv = fcntl(fd, F_SETFD, lflag); } while(rv < 0 && errno == EINTR); if(flag < 0) { std::cerr << "cloexec: error during setting of flag" << std::endl; exit(1); } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Copyright (c) 2018-2018 The VERGE Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/standard.h> #include <pubkey.h> #include <script/script.h> #include <util/system.h> #include <util/strencodings.h> #include <stealth.h> typedef std::vector<unsigned char> valtype; bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} const char* GetTxnOutputType(txnouttype t) { switch (t) { case TX_NONSTANDARD: return "nonstandard"; case TX_PUBKEY: return "pubkey"; case TX_PUBKEYHASH: return "pubkeyhash"; case TX_SCRIPTHASH: return "scripthash"; case TX_MULTISIG: return "multisig"; case TX_NULL_DATA: return "nulldata"; case TX_WITNESS_V0_KEYHASH: return "witness_v0_keyhash"; case TX_WITNESS_V0_SCRIPTHASH: return "witness_v0_scripthash"; case TX_WITNESS_UNKNOWN: return "witness_unknown"; } return nullptr; } static bool MatchPayToPubkey(const CScript& script, valtype& pubkey) { if (script.size() == CPubKey::PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } if (script.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } return false; } static bool MatchPayToPubkeyHash(const CScript& script, valtype& pubkeyhash) { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { pubkeyhash = valtype(script.begin () + 3, script.begin() + 23); return true; } return false; } /** Test for "small positive integer" script opcodes - OP_1 through OP_16. */ static constexpr bool IsSmallInteger(opcodetype opcode) { return opcode >= OP_1 && opcode <= OP_16; } static bool MatchMultisig(const CScript& script, unsigned int& required, std::vector<valtype>& pubkeys) { opcodetype opcode; valtype data; CScript::const_iterator it = script.begin(); if (script.size() < 1 || script.back() != OP_CHECKMULTISIG) return false; if (!script.GetOp(it, opcode, data) || !IsSmallInteger(opcode)) return false; required = CScript::DecodeOP_N(opcode); while (script.GetOp(it, opcode, data) && CPubKey::ValidSize(data)) { pubkeys.emplace_back(std::move(data)); } if (!IsSmallInteger(opcode)) return false; unsigned int keys = CScript::DecodeOP_N(opcode); if (pubkeys.size() != keys || keys < required) return false; return (it + 1 == script.end()); } bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet) { vSolutionsRet.clear(); // Shortcut for pay-to-script-hash, which are more constrained than the other types: // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL if (scriptPubKey.IsPayToScriptHash()) { typeRet = TX_SCRIPTHASH; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } int witnessversion; std::vector<unsigned char> witnessprogram; if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_KEYHASH_SIZE) { typeRet = TX_WITNESS_V0_KEYHASH; vSolutionsRet.push_back(witnessprogram); return true; } if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) { typeRet = TX_WITNESS_V0_SCRIPTHASH; vSolutionsRet.push_back(witnessprogram); return true; } if (witnessversion != 0) { typeRet = TX_WITNESS_UNKNOWN; vSolutionsRet.push_back(std::vector<unsigned char>{(unsigned char)witnessversion}); vSolutionsRet.push_back(std::move(witnessprogram)); return true; } typeRet = TX_NONSTANDARD; return false; } // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } std::vector<unsigned char> data; if (MatchPayToPubkey(scriptPubKey, data)) { typeRet = TX_PUBKEY; vSolutionsRet.push_back(std::move(data)); return true; } if (MatchPayToPubkeyHash(scriptPubKey, data)) { typeRet = TX_PUBKEYHASH; vSolutionsRet.push_back(std::move(data)); return true; } unsigned int required; std::vector<std::vector<unsigned char>> keys; if (MatchMultisig(scriptPubKey, required, keys)) { typeRet = TX_MULTISIG; vSolutionsRet.push_back({static_cast<unsigned char>(required)}); // safe as required is in range 1..16 vSolutionsRet.insert(vSolutionsRet.end(), keys.begin(), keys.end()); vSolutionsRet.push_back({static_cast<unsigned char>(keys.size())}); // safe as size is in range 1..16 return true; } vSolutionsRet.clear(); typeRet = TX_NONSTANDARD; return false; } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) { std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } else if (whichType == TX_WITNESS_V0_KEYHASH) { WitnessV0KeyHash hash; std::copy(vSolutions[0].begin(), vSolutions[0].end(), hash.begin()); addressRet = hash; return true; } else if (whichType == TX_WITNESS_V0_SCRIPTHASH) { WitnessV0ScriptHash hash; std::copy(vSolutions[0].begin(), vSolutions[0].end(), hash.begin()); addressRet = hash; return true; } else if (whichType == TX_WITNESS_UNKNOWN) { WitnessUnknown unk; unk.version = vSolutions[0][0]; std::copy(vSolutions[1].begin(), vSolutions[1].end(), unk.program); unk.length = vSolutions[1].size(); addressRet = unk; return true; } // Multisig txns have more than one address... return false; } bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; } namespace { class CScriptVisitor : public boost::static_visitor<bool> { private: CScript *script; bool shouldStealth; public: explicit CScriptVisitor(CScript *scriptin) { script = scriptin; } CScriptVisitor(CScript *scriptin, bool shouldStealthIn) { script = scriptin; shouldStealth = shouldStealthIn; } bool operator()(const CNoDestination &dest) const { script->clear(); return false; } bool operator()(const CKeyID &keyID) const { script->clear(); *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; return true; } bool operator()(const CStealthAddress &stealthID) const { script->clear(); ec_secret ephem_secret; ec_secret secretShared; ec_point pkSendTo; ec_point ephem_pubkey; if (GenerateRandomSecret(ephem_secret) != 0) { return false; }; if (StealthSecret(ephem_secret, stealthID.scan_pubkey, stealthID.spend_pubkey, secretShared, pkSendTo) != 0) { return false; }; CPubKey cpkTo(pkSendTo); if (!cpkTo.IsValid()) { return false; }; *script << OP_RETURN << std::vector<unsigned char>(cpkTo.begin(), cpkTo.end()); return false; } bool operator()(const CScriptID &scriptID) const { script->clear(); *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; return true; } bool operator()(const WitnessV0KeyHash& id) const { script->clear(); *script << OP_0 << ToByteVector(id); return true; } bool operator()(const WitnessV0ScriptHash& id) const { script->clear(); *script << OP_0 << ToByteVector(id); return true; } bool operator()(const WitnessUnknown& id) const { script->clear(); *script << CScript::EncodeOP_N(id.version) << std::vector<unsigned char>(id.program, id.program + id.length); return true; } }; } // namespace CScript GetScriptForDestination(const CTxDestination& dest) { CScript script; boost::apply_visitor(CScriptVisitor(&script), dest); return script; } CScript GetScriptForStealthPubKey(const CPubKey& pubKey) { return CScript() << OP_RETURN << std::vector<unsigned char>(pubKey.begin(), pubKey.end()); } CScript GetScriptForRawPubKey(const CPubKey& pubKey) { return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG; } CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) { CScript script; script << CScript::EncodeOP_N(nRequired); for (const CPubKey& key : keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; } CScript GetScriptForWitness(const CScript& redeemscript) { CScript ret; txnouttype typ; std::vector<std::vector<unsigned char> > vSolutions; if (Solver(redeemscript, typ, vSolutions)) { if (typ == TX_PUBKEY) { return GetScriptForDestination(WitnessV0KeyHash(Hash160(vSolutions[0].begin(), vSolutions[0].end()))); } else if (typ == TX_PUBKEYHASH) { return GetScriptForDestination(WitnessV0KeyHash(vSolutions[0])); } } uint256 hash; CSHA256().Write(&redeemscript[0], redeemscript.size()).Finalize(hash.begin()); return GetScriptForDestination(WitnessV0ScriptHash(hash)); } bool IsValidDestination(const CTxDestination& dest) { return dest.which() != 0; } <commit_msg>Remove unused boolean for stealth in standard visitor<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Copyright (c) 2018-2018 The VERGE Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/standard.h> #include <pubkey.h> #include <script/script.h> #include <util/system.h> #include <util/strencodings.h> #include <stealth.h> typedef std::vector<unsigned char> valtype; bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} const char* GetTxnOutputType(txnouttype t) { switch (t) { case TX_NONSTANDARD: return "nonstandard"; case TX_PUBKEY: return "pubkey"; case TX_PUBKEYHASH: return "pubkeyhash"; case TX_SCRIPTHASH: return "scripthash"; case TX_MULTISIG: return "multisig"; case TX_NULL_DATA: return "nulldata"; case TX_WITNESS_V0_KEYHASH: return "witness_v0_keyhash"; case TX_WITNESS_V0_SCRIPTHASH: return "witness_v0_scripthash"; case TX_WITNESS_UNKNOWN: return "witness_unknown"; } return nullptr; } static bool MatchPayToPubkey(const CScript& script, valtype& pubkey) { if (script.size() == CPubKey::PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } if (script.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } return false; } static bool MatchPayToPubkeyHash(const CScript& script, valtype& pubkeyhash) { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { pubkeyhash = valtype(script.begin () + 3, script.begin() + 23); return true; } return false; } /** Test for "small positive integer" script opcodes - OP_1 through OP_16. */ static constexpr bool IsSmallInteger(opcodetype opcode) { return opcode >= OP_1 && opcode <= OP_16; } static bool MatchMultisig(const CScript& script, unsigned int& required, std::vector<valtype>& pubkeys) { opcodetype opcode; valtype data; CScript::const_iterator it = script.begin(); if (script.size() < 1 || script.back() != OP_CHECKMULTISIG) return false; if (!script.GetOp(it, opcode, data) || !IsSmallInteger(opcode)) return false; required = CScript::DecodeOP_N(opcode); while (script.GetOp(it, opcode, data) && CPubKey::ValidSize(data)) { pubkeys.emplace_back(std::move(data)); } if (!IsSmallInteger(opcode)) return false; unsigned int keys = CScript::DecodeOP_N(opcode); if (pubkeys.size() != keys || keys < required) return false; return (it + 1 == script.end()); } bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet) { vSolutionsRet.clear(); // Shortcut for pay-to-script-hash, which are more constrained than the other types: // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL if (scriptPubKey.IsPayToScriptHash()) { typeRet = TX_SCRIPTHASH; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } int witnessversion; std::vector<unsigned char> witnessprogram; if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_KEYHASH_SIZE) { typeRet = TX_WITNESS_V0_KEYHASH; vSolutionsRet.push_back(witnessprogram); return true; } if (witnessversion == 0 && witnessprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE) { typeRet = TX_WITNESS_V0_SCRIPTHASH; vSolutionsRet.push_back(witnessprogram); return true; } if (witnessversion != 0) { typeRet = TX_WITNESS_UNKNOWN; vSolutionsRet.push_back(std::vector<unsigned char>{(unsigned char)witnessversion}); vSolutionsRet.push_back(std::move(witnessprogram)); return true; } typeRet = TX_NONSTANDARD; return false; } // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } std::vector<unsigned char> data; if (MatchPayToPubkey(scriptPubKey, data)) { typeRet = TX_PUBKEY; vSolutionsRet.push_back(std::move(data)); return true; } if (MatchPayToPubkeyHash(scriptPubKey, data)) { typeRet = TX_PUBKEYHASH; vSolutionsRet.push_back(std::move(data)); return true; } unsigned int required; std::vector<std::vector<unsigned char>> keys; if (MatchMultisig(scriptPubKey, required, keys)) { typeRet = TX_MULTISIG; vSolutionsRet.push_back({static_cast<unsigned char>(required)}); // safe as required is in range 1..16 vSolutionsRet.insert(vSolutionsRet.end(), keys.begin(), keys.end()); vSolutionsRet.push_back({static_cast<unsigned char>(keys.size())}); // safe as size is in range 1..16 return true; } vSolutionsRet.clear(); typeRet = TX_NONSTANDARD; return false; } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) { std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } else if (whichType == TX_WITNESS_V0_KEYHASH) { WitnessV0KeyHash hash; std::copy(vSolutions[0].begin(), vSolutions[0].end(), hash.begin()); addressRet = hash; return true; } else if (whichType == TX_WITNESS_V0_SCRIPTHASH) { WitnessV0ScriptHash hash; std::copy(vSolutions[0].begin(), vSolutions[0].end(), hash.begin()); addressRet = hash; return true; } else if (whichType == TX_WITNESS_UNKNOWN) { WitnessUnknown unk; unk.version = vSolutions[0][0]; std::copy(vSolutions[1].begin(), vSolutions[1].end(), unk.program); unk.length = vSolutions[1].size(); addressRet = unk; return true; } // Multisig txns have more than one address... return false; } bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; } namespace { class CScriptVisitor : public boost::static_visitor<bool> { private: CScript *script; public: explicit CScriptVisitor(CScript *scriptin) { script = scriptin; } CScriptVisitor(CScript *scriptin, bool shouldStealthIn) { script = scriptin; } bool operator()(const CNoDestination &dest) const { script->clear(); return false; } bool operator()(const CKeyID &keyID) const { script->clear(); *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; return true; } bool operator()(const CStealthAddress &stealthID) const { script->clear(); ec_secret ephem_secret; ec_secret secretShared; ec_point pkSendTo; ec_point ephem_pubkey; if (GenerateRandomSecret(ephem_secret) != 0) { return false; }; if (StealthSecret(ephem_secret, stealthID.scan_pubkey, stealthID.spend_pubkey, secretShared, pkSendTo) != 0) { return false; }; CPubKey cpkTo(pkSendTo); if (!cpkTo.IsValid()) { return false; }; *script << OP_RETURN << std::vector<unsigned char>(cpkTo.begin(), cpkTo.end()); return false; } bool operator()(const CScriptID &scriptID) const { script->clear(); *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; return true; } bool operator()(const WitnessV0KeyHash& id) const { script->clear(); *script << OP_0 << ToByteVector(id); return true; } bool operator()(const WitnessV0ScriptHash& id) const { script->clear(); *script << OP_0 << ToByteVector(id); return true; } bool operator()(const WitnessUnknown& id) const { script->clear(); *script << CScript::EncodeOP_N(id.version) << std::vector<unsigned char>(id.program, id.program + id.length); return true; } }; } // namespace CScript GetScriptForDestination(const CTxDestination& dest) { CScript script; boost::apply_visitor(CScriptVisitor(&script), dest); return script; } CScript GetScriptForStealthPubKey(const CPubKey& pubKey) { return CScript() << OP_RETURN << std::vector<unsigned char>(pubKey.begin(), pubKey.end()); } CScript GetScriptForRawPubKey(const CPubKey& pubKey) { return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG; } CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) { CScript script; script << CScript::EncodeOP_N(nRequired); for (const CPubKey& key : keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; } CScript GetScriptForWitness(const CScript& redeemscript) { CScript ret; txnouttype typ; std::vector<std::vector<unsigned char> > vSolutions; if (Solver(redeemscript, typ, vSolutions)) { if (typ == TX_PUBKEY) { return GetScriptForDestination(WitnessV0KeyHash(Hash160(vSolutions[0].begin(), vSolutions[0].end()))); } else if (typ == TX_PUBKEYHASH) { return GetScriptForDestination(WitnessV0KeyHash(vSolutions[0])); } } uint256 hash; CSHA256().Write(&redeemscript[0], redeemscript.size()).Finalize(hash.begin()); return GetScriptForDestination(WitnessV0ScriptHash(hash)); } bool IsValidDestination(const CTxDestination& dest) { return dest.which() != 0; } <|endoftext|>
<commit_before>#include "iotsaUser.h" #include "iotsaConfigFile.h" #undef PASSWORD_DEBUGGING // Enables admin1/admin1 to always log in String &defaultPassword() { static String dftPwd; if (dftPwd == "") { #ifdef ESP32 randomSeed(ESP.getEfuseMac()); #else randomSeed(ESP.getChipId()); #endif dftPwd = String("password") + String(random(1000)); } return dftPwd; } IotsaUserMod::IotsaUserMod(IotsaApplication &_app, const char *_username, const char *_password) : username(_username), password(_password), IotsaAuthMod(_app) { configLoad(); } void IotsaUserMod::handler() { bool anyChanged = false; String pwold, pw1, pw2; bool passwordChanged = false; bool oldPasswordCorrect = false; bool newPasswordsMatch = false; String newUsername; for (uint8_t i=0; i<server.args(); i++){ if( server.argName(i) == "username") { newUsername = server.arg(i); if (newUsername == username) { newUsername = ""; anyChanged = false; } else { if (needsAuthentication("users")) return; anyChanged = true; } } if( server.argName(i) == "old") { // password authentication is checked later. pwold = server.arg(i); oldPasswordCorrect = pwold == password; } if( server.argName(i) == "password") { // password authentication is checked later. pw1 = server.arg(i); passwordChanged = true; } if( server.argName(i) == "again") { pw2 = server.arg(i); passwordChanged = true; } } if (passwordChanged) { newPasswordsMatch = pw1 == pw2; if (newPasswordsMatch && oldPasswordCorrect) { password = pw1; anyChanged = true; } else { anyChanged = false; } } if (anyChanged && newUsername != "") { username = newUsername; } if (anyChanged) configSave(); String message = "<html><head><title>Edit users and passwords</title></head><body><h1>Edit users and passwords</h1>"; if (anyChanged && newUsername != "") { message += "<p><em>Username changed.</e,></p>"; } if (passwordChanged && anyChanged) { message += "<p><em>Password has been changed.</em></p>"; } else if (passwordChanged && !oldPasswordCorrect) { message += "<p><em>Old password incorrect.</em></p>"; } else if (passwordChanged && !newPasswordsMatch) { message += "<p><em>Passwords do not match, not changed.</em></p>"; } message += "<form method='get'>Username: <input name='username' value='"; message += htmlEncode(username); message += "'>"; if (password != "") { message += "<br>Old Password: <input type='password' name='old' value=''"; message += "empty1"; message += "'>"; } else if (configurationMode == TMPC_CONFIG) { message += "<br>Password not set, default is '"; message += defaultPassword(); message += "'."; } else { message += "<br>Password not set, reboot in configuration mode to see default password."; } message += "<br>New Password: <input type='password' name='password' value='"; message += "empty2"; message += "'><br>Repeat New Password: <input type='password' name='again' value='"; message += "empty3"; message += "'><br><input type='submit'></form>"; server.send(200, "text/html", message); } void IotsaUserMod::setup() { configLoad(); } void IotsaUserMod::serverSetup() { server.on("/users", std::bind(&IotsaUserMod::handler, this)); } void IotsaUserMod::configLoad() { IotsaConfigFileLoad cf("/config/users.cfg"); cf.get("user0", username, username); cf.get("password0", password, password); IotsaSerial.print("Loaded users.cfg. Username="); IotsaSerial.print(username); IotsaSerial.print(", password length="); IotsaSerial.println(password.length()); } void IotsaUserMod::configSave() { IotsaConfigFileSave cf("/config/users.cfg"); cf.put("user0", username); cf.put("password0", password); IotsaSerial.print("Saved users.cfg. Username="); IotsaSerial.print(username); IotsaSerial.print(", password length="); IotsaSerial.println(password.length()); } void IotsaUserMod::loop() { } String IotsaUserMod::info() { String message = "<p>Usernames/passwords enabled."; message += " See <a href=\"/users\">/users</a> to change."; if (configurationMode && password == "") { message += "<br>Username and password are the defaults: '"; message += htmlEncode(username); message += "' and '"; String &dfp = defaultPassword(); message += dfp; message += "'."; } message += "</p>"; return message; } bool IotsaUserMod::needsAuthentication(const char *right) { // We ignore "right", username/password grants all rights. String &curPassword = password; if (curPassword == "") curPassword = defaultPassword(); if (!server.authenticate(username.c_str(), curPassword.c_str()) #ifdef PASSWORD_DEBUGGING && !server.authenticate("admin1", "admin1") #endif ) { server.sendHeader("WWW-Authenticate", "Basic realm=\"Login Required\""); server.send(401, "text/plain", "401 Unauthorized\n"); IotsaSerial.print("Return 401 Unauthorized for right="); IotsaSerial.println(right); return true; } return false; } <commit_msg>Fixed bug in handling of passwords.<commit_after>#include "iotsaUser.h" #include "iotsaConfigFile.h" #undef PASSWORD_DEBUGGING // Enables admin1/admin1 to always log in String &defaultPassword() { static String dftPwd; if (dftPwd == "") { #ifdef ESP32 randomSeed(ESP.getEfuseMac()); #else randomSeed(ESP.getChipId()); #endif dftPwd = String("password") + String(random(1000)); } return dftPwd; } IotsaUserMod::IotsaUserMod(IotsaApplication &_app, const char *_username, const char *_password) : username(_username), password(_password), IotsaAuthMod(_app) { configLoad(); } void IotsaUserMod::handler() { bool anyChanged = false; String pwold, pw1, pw2; bool passwordChanged = false; bool oldPasswordCorrect = false; bool newPasswordsMatch = false; String newUsername; for (uint8_t i=0; i<server.args(); i++){ if( server.argName(i) == "username") { newUsername = server.arg(i); if (newUsername == username) { newUsername = ""; anyChanged = false; } else { if (needsAuthentication("users")) return; anyChanged = true; } } if( server.argName(i) == "old") { // password authentication is checked later. pwold = server.arg(i); oldPasswordCorrect = pwold == password; } if( server.argName(i) == "password") { // password authentication is checked later. pw1 = server.arg(i); passwordChanged = true; } if( server.argName(i) == "again") { pw2 = server.arg(i); passwordChanged = true; } } if (passwordChanged) { newPasswordsMatch = pw1 == pw2; if (newPasswordsMatch && oldPasswordCorrect) { password = pw1; anyChanged = true; } else { anyChanged = false; } } if (anyChanged && newUsername != "") { username = newUsername; } if (anyChanged) configSave(); String message = "<html><head><title>Edit users and passwords</title></head><body><h1>Edit users and passwords</h1>"; if (anyChanged && newUsername != "") { message += "<p><em>Username changed.</e,></p>"; } if (passwordChanged && anyChanged) { message += "<p><em>Password has been changed.</em></p>"; } else if (passwordChanged && !oldPasswordCorrect) { message += "<p><em>Old password incorrect.</em></p>"; } else if (passwordChanged && !newPasswordsMatch) { message += "<p><em>Passwords do not match, not changed.</em></p>"; } message += "<form method='get'>Username: <input name='username' value='"; message += htmlEncode(username); message += "'>"; message += "<br>Old Password: <input type='password' name='old' value=''"; message += "empty1"; message += "'>"; if (password == "") { if (configurationMode == TMPC_CONFIG) { message += "<br><i>(Password not set, default is '"; message += defaultPassword(); message += "')</i>"; } else { message += "<br><i>(Password not set, reboot in configuration mode to see default password)</i>)"; } } message += "<br>New Password: <input type='password' name='password' value='"; message += "empty2"; message += "'><br>Repeat New Password: <input type='password' name='again' value='"; message += "empty3"; message += "'><br><input type='submit'></form>"; server.send(200, "text/html", message); } void IotsaUserMod::setup() { configLoad(); } void IotsaUserMod::serverSetup() { server.on("/users", std::bind(&IotsaUserMod::handler, this)); } void IotsaUserMod::configLoad() { IotsaConfigFileLoad cf("/config/users.cfg"); cf.get("user0", username, username); cf.get("password0", password, password); IotsaSerial.print("Loaded users.cfg. Username="); IotsaSerial.print(username); IotsaSerial.print(", password length="); IotsaSerial.println(password.length()); } void IotsaUserMod::configSave() { IotsaConfigFileSave cf("/config/users.cfg"); cf.put("user0", username); cf.put("password0", password); IotsaSerial.print("Saved users.cfg. Username="); IotsaSerial.print(username); IotsaSerial.print(", password length="); IotsaSerial.println(password.length()); } void IotsaUserMod::loop() { } String IotsaUserMod::info() { String message = "<p>Usernames/passwords enabled."; message += " See <a href=\"/users\">/users</a> to change."; if (configurationMode && password == "") { message += "<br>Username and password are the defaults: '"; message += htmlEncode(username); message += "' and '"; String &dfp = defaultPassword(); message += dfp; message += "'."; } message += "</p>"; return message; } bool IotsaUserMod::needsAuthentication(const char *right) { // We ignore "right", username/password grants all rights. String &curPassword = password; if (curPassword == "") curPassword = defaultPassword(); if (!server.authenticate(username.c_str(), curPassword.c_str()) #ifdef PASSWORD_DEBUGGING && !server.authenticate("admin1", "admin1") #endif ) { server.sendHeader("WWW-Authenticate", "Basic realm=\"Login Required\""); server.send(401, "text/plain", "401 Unauthorized\n"); IotsaSerial.print("Return 401 Unauthorized for right="); IotsaSerial.println(right); return true; } return false; } <|endoftext|>
<commit_before>/* Copyright (C) 2018 Michal Kosciesza <michal@mkiol.net> * * 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 "itemmodel.h" #include <QDebug> ItemWorker::ItemWorker(ItemModel *model, const QString &data) : data{data}, model{model} {} ItemWorker::~ItemWorker() { requestInterruption(); wait(); } void ItemWorker::run() { if (model->m_delayedStart) QThread::msleep(startDelay); if (!isInterruptionRequested()) items = model->makeItems(); if (!isInterruptionRequested()) model->postMakeItems(items); } ItemModel::ItemModel(ListItem *prototype, QObject *parent) : ListModel{prototype, parent} {} void ItemModel::updateModel(const QString &data) { if (m_worker && m_worker->isRunning()) { m_worker->requestInterruption(); return; } setBusy(true); m_worker = std::make_unique<ItemWorker>(this, data); connect(m_worker.get(), &QThread::finished, this, &ItemModel::workerDone); m_worker->start(QThread::IdlePriority); } void ItemModel::postMakeItems(const QList<ListItem *> &) {} void ItemModel::clear() { if (m_list.length() == 0) return; removeRows(0, rowCount()); emit countChanged(); } void ItemModel::workerDone() { auto *worker = qobject_cast<ItemWorker *>(sender()); if (worker) { int old_l = m_list.length(); if (m_list.length() != 0) removeRows(0, rowCount()); if (!worker->items.isEmpty()) appendRows(worker->items); if (old_l != m_list.length()) emit countChanged(); m_worker.reset(); } setBusy(false); } void ItemModel::setBusy(bool busy) { if (busy != m_busy) { m_busy = busy; emit busyChanged(); } } void SelectableItem::setSelected(bool value) { if (m_selected != value) { m_selected = value; emit dataChanged(); } } SelectableItemModel::SelectableItemModel(SelectableItem *prototype, bool delayedStart, QObject *parent) : ItemModel{prototype, parent} { m_delayedStart = delayedStart; } void SelectableItemModel::clear() { ItemModel::clear(); m_selectedCount = 0; emit selectedCountChanged(); } void SelectableItemModel::postMakeItems(const QList<ListItem *> &items) { int selectable_count = 0; int selected_count = 0; for (const auto *item : items) { const auto *si = qobject_cast<const SelectableItem *>(item); if (si->selectable()) selectable_count++; if (si->selected()) selected_count++; } if (selectable_count != m_selectableCount) { m_selectableCount = selectable_count; emit selectableCountChanged(); } if (selected_count != m_selectedCount) { m_selectedCount = selected_count; emit selectedCountChanged(); } } void SelectableItemModel::setFilter(const QString &filter) { if (m_filter != filter) { m_filter = filter; emit filterChanged(); updateModel(); } } void SelectableItemModel::setFilterNoUpdate(const QString &filter) { if (m_filter != filter) { m_filter = filter; emit filterChanged(); } } void SelectableItemModel::setSelected(int index, bool value) { if (index >= m_list.length()) { qWarning() << "index is invalid"; return; } auto *item = qobject_cast<SelectableItem *>(m_list.at(index)); if (item->selectable()) { bool cvalue = item->selected(); if (cvalue != value) { item->setSelected(value); if (value) m_selectedCount++; else m_selectedCount--; emit selectedCountChanged(); } } } void SelectableItemModel::setAllSelected(bool value) { if (m_list.isEmpty()) return; int c = m_selectedCount; foreach (auto *li, m_list) { auto *item = qobject_cast<SelectableItem *>(li); if (item->selectable()) { bool cvalue = item->selected(); if (cvalue != value) { item->setSelected(value); if (value) m_selectedCount++; else m_selectedCount--; } } } if (c != m_selectedCount) emit selectedCountChanged(); } QVariantList SelectableItemModel::selectedItems() { return {}; } void SelectableItemModel::workerDone() { if (m_worker && m_worker->data != m_filter) { updateModel(m_filter); } else { ItemModel::workerDone(); } } void SelectableItemModel::updateModel(const QString &) { setAllSelected(false); ItemModel::updateModel(m_filter); } <commit_msg>fix: files model couldn't be updated<commit_after>/* Copyright (C) 2018 Michal Kosciesza <michal@mkiol.net> * * 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 "itemmodel.h" #include <QDebug> ItemWorker::ItemWorker(ItemModel *model, const QString &data) : data{data}, model{model} {} ItemWorker::~ItemWorker() { requestInterruption(); wait(); } void ItemWorker::run() { if (model->m_delayedStart) QThread::msleep(startDelay); if (!isInterruptionRequested()) items = model->makeItems(); if (!isInterruptionRequested()) model->postMakeItems(items); } ItemModel::ItemModel(ListItem *prototype, QObject *parent) : ListModel{prototype, parent} {} void ItemModel::updateModel(const QString &data) { if (m_worker && m_worker->isRunning()) { if (m_delayedStart) m_worker->requestInterruption(); return; } setBusy(true); m_worker = std::make_unique<ItemWorker>(this, data); connect(m_worker.get(), &QThread::finished, this, &ItemModel::workerDone); m_worker->start(QThread::IdlePriority); } void ItemModel::postMakeItems(const QList<ListItem *> &) {} void ItemModel::clear() { if (m_list.length() == 0) return; removeRows(0, rowCount()); emit countChanged(); } void ItemModel::workerDone() { auto *worker = qobject_cast<ItemWorker *>(sender()); if (worker) { int old_l = m_list.length(); if (m_list.length() != 0) removeRows(0, rowCount()); if (!worker->items.isEmpty()) appendRows(worker->items); if (old_l != m_list.length()) emit countChanged(); m_worker.reset(); } setBusy(false); } void ItemModel::setBusy(bool busy) { if (busy != m_busy) { m_busy = busy; emit busyChanged(); } } void SelectableItem::setSelected(bool value) { if (m_selected != value) { m_selected = value; emit dataChanged(); } } SelectableItemModel::SelectableItemModel(SelectableItem *prototype, bool delayedStart, QObject *parent) : ItemModel{prototype, parent} { m_delayedStart = delayedStart; } void SelectableItemModel::clear() { ItemModel::clear(); m_selectedCount = 0; emit selectedCountChanged(); } void SelectableItemModel::postMakeItems(const QList<ListItem *> &items) { int selectable_count = 0; int selected_count = 0; for (const auto *item : items) { const auto *si = qobject_cast<const SelectableItem *>(item); if (si->selectable()) selectable_count++; if (si->selected()) selected_count++; } if (selectable_count != m_selectableCount) { m_selectableCount = selectable_count; emit selectableCountChanged(); } if (selected_count != m_selectedCount) { m_selectedCount = selected_count; emit selectedCountChanged(); } } void SelectableItemModel::setFilter(const QString &filter) { if (m_filter != filter) { m_filter = filter; emit filterChanged(); updateModel(); } } void SelectableItemModel::setFilterNoUpdate(const QString &filter) { if (m_filter != filter) { m_filter = filter; emit filterChanged(); } } void SelectableItemModel::setSelected(int index, bool value) { if (index >= m_list.length()) { qWarning() << "index is invalid"; return; } auto *item = qobject_cast<SelectableItem *>(m_list.at(index)); if (item->selectable()) { bool cvalue = item->selected(); if (cvalue != value) { item->setSelected(value); if (value) m_selectedCount++; else m_selectedCount--; emit selectedCountChanged(); } } } void SelectableItemModel::setAllSelected(bool value) { if (m_list.isEmpty()) return; int c = m_selectedCount; foreach (auto *li, m_list) { auto *item = qobject_cast<SelectableItem *>(li); if (item->selectable()) { bool cvalue = item->selected(); if (cvalue != value) { item->setSelected(value); if (value) m_selectedCount++; else m_selectedCount--; } } } if (c != m_selectedCount) emit selectedCountChanged(); } QVariantList SelectableItemModel::selectedItems() { return {}; } void SelectableItemModel::workerDone() { if (m_worker && m_worker->data != m_filter) { updateModel(m_filter); } else { ItemModel::workerDone(); } } void SelectableItemModel::updateModel(const QString &) { setAllSelected(false); ItemModel::updateModel(m_filter); } <|endoftext|>
<commit_before>#include "settingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include "utils/logoutput.h" #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingContainer::SettingContainer(std::string key, std::string label) : key(key) , label(label) { } SettingConfig* SettingContainer::addChild(std::string key, std::string label) { children.emplace_back(key, label, nullptr); return &children.back(); } SettingConfig::SettingConfig(std::string key, std::string label, SettingContainer* parent) : SettingContainer(key, label) , parent(parent) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } bool SettingRegistry::settingExists(std::string key) const { return settings.find(key) != settings.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) { auto it = settings.find(key); if (it == settings.end()) return nullptr; return it->second; } SettingContainer* SettingRegistry::getCategory(std::string key) { for (SettingContainer& cat : categories) if (cat.getKey().compare(key) == 0) return &cat; return nullptr; } SettingRegistry::SettingRegistry() { } bool SettingRegistry::settingsLoaded() { return settings.size() > 0; } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } int SettingRegistry::loadJSONsettings(std::string filename) { rapidjson::Document json_document; int err = loadJSON(filename, json_document); if (err) { return err; } if (json_document.HasMember("inherits")) { std::string filename_copy = std::string(filename.c_str()); // copy the string because dirname(.) changes the input string!!! char* filename_cstr = (char*)filename_copy.c_str(); int err = loadJSONsettings(std::string(dirname(filename_cstr)) + std::string("/") + json_document["inherits"].GetString()); if (err) { return err; } return loadJSONsettingsFromDoc(json_document, false); } else { return loadJSONsettingsFromDoc(json_document, true); } } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } if (json_document.HasMember("machine_extruder_trains")) { categories.emplace_back("machine_extruder_trains", "Extruder Trains Settings Objects"); SettingContainer* category_trains = &categories.back(); const rapidjson::Value& trains = json_document["machine_extruder_trains"]; if (trains.IsArray()) { if (trains.Size() > 0 && trains[0].IsObject()) { unsigned int idx = 0; for (auto it = trains.Begin(); it != trains.End(); ++it) { SettingConfig* child = category_trains->addChild(std::to_string(idx), std::to_string(idx)); for (rapidjson::Value::ConstMemberIterator setting_iterator = it->MemberBegin(); setting_iterator != it->MemberEnd(); ++setting_iterator) { _addSettingToContainer(child, setting_iterator, warn_duplicates, false); } idx++; } } } else { logError("Error: JSON machine_extruder_trains is not an array!\n"); } } if (json_document.HasMember("machine_settings")) { categories.emplace_back("machine_settings", "Machine Settings"); SettingContainer* category_machine_settings = &categories.back(); const rapidjson::Value& json_object_container = json_document["machine_settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(category_machine_settings, setting_iterator, warn_duplicates); } } if (json_document.HasMember("categories")) { for (rapidjson::Value::ConstMemberIterator category_iterator = json_document["categories"].MemberBegin(); category_iterator != json_document["categories"].MemberEnd(); ++category_iterator) { if (!category_iterator->value.IsObject()) { continue; } if (!category_iterator->value.HasMember("label") || !category_iterator->value["label"].IsString()) { continue; } if (!category_iterator->value.HasMember("settings") || !category_iterator->value["settings"].IsObject()) { continue; } categories.emplace_back(category_iterator->name.GetString(), category_iterator->value["label"].GetString()); SettingContainer* category = &categories.back(); const rapidjson::Value& json_object_container = category_iterator->value["settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(category, setting_iterator, warn_duplicates); } } } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); logError("%s\n", setting.c_str()); SettingConfig* conf = getSettingConfig(setting); _loadSettingValues(conf, override_iterator, false); } } return 0; } void SettingRegistry::_addSettingToContainer(SettingContainer* parent, rapidjson::Value::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; if (data.HasMember("type") && data["type"].IsString() && (data["type"].GetString() == std::string("polygon") || data["type"].GetString() == std::string("polygons"))) { logWarning("Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); /// When this setting has children, add those children to the parent setting. if (data.HasMember("children") && data["children"].IsObject()) { const rapidjson::Value& json_object_container = data["children"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(parent, setting_iterator, warn_duplicates, add_to_settings); } } return; } std::string label; if (!json_object_it->value.HasMember("label") || !data["label"].IsString()) { label = "N/A"; } else { label = data["label"].GetString(); } /// Create the new setting config object. SettingConfig* config = parent->addChild(json_object_it->name.GetString(), label); _loadSettingValues(config, json_object_it, warn_duplicates, add_to_settings); } void SettingRegistry::_loadSettingValues(SettingConfig* config, rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (data.HasMember("default")) { const rapidjson::Value& dflt = data["default"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { logError("Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } /// Register the setting in the settings map lookup. if (warn_duplicates && settingExists(config->getKey())) { cura::logError("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", config->getKey().c_str(), config->getLabel().c_str(), getSettingConfig(config->getKey())->getLabel().c_str()); } if (add_to_settings) { settings[config->getKey()] = config; } /// When this setting has children, add those children to this setting. if (data.HasMember("children") && data["children"].IsObject()) { const rapidjson::Value& json_object_container = data["children"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(config, setting_iterator, warn_duplicates, add_to_settings); } } } }//namespace cura<commit_msg>Fix more indenting<commit_after>#include "settingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include "utils/logoutput.h" #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingContainer::SettingContainer(std::string key, std::string label) : key(key) , label(label) { } SettingConfig* SettingContainer::addChild(std::string key, std::string label) { children.emplace_back(key, label, nullptr); return &children.back(); } SettingConfig::SettingConfig(std::string key, std::string label, SettingContainer* parent) : SettingContainer(key, label) , parent(parent) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } bool SettingRegistry::settingExists(std::string key) const { return settings.find(key) != settings.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) { auto it = settings.find(key); if (it == settings.end()) return nullptr; return it->second; } SettingContainer* SettingRegistry::getCategory(std::string key) { for (SettingContainer& cat : categories) if (cat.getKey().compare(key) == 0) return &cat; return nullptr; } SettingRegistry::SettingRegistry() { } bool SettingRegistry::settingsLoaded() { return settings.size() > 0; } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } int SettingRegistry::loadJSONsettings(std::string filename) { rapidjson::Document json_document; int err = loadJSON(filename, json_document); if (err) { return err; } if (json_document.HasMember("inherits")) { std::string filename_copy = std::string(filename.c_str()); // copy the string because dirname(.) changes the input string!!! char* filename_cstr = (char*)filename_copy.c_str(); int err = loadJSONsettings(std::string(dirname(filename_cstr)) + std::string("/") + json_document["inherits"].GetString()); if (err) { return err; } return loadJSONsettingsFromDoc(json_document, false); } else { return loadJSONsettingsFromDoc(json_document, true); } } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } if (json_document.HasMember("machine_extruder_trains")) { categories.emplace_back("machine_extruder_trains", "Extruder Trains Settings Objects"); SettingContainer* category_trains = &categories.back(); const rapidjson::Value& trains = json_document["machine_extruder_trains"]; if (trains.IsArray()) { if (trains.Size() > 0 && trains[0].IsObject()) { unsigned int idx = 0; for (auto it = trains.Begin(); it != trains.End(); ++it) { SettingConfig* child = category_trains->addChild(std::to_string(idx), std::to_string(idx)); for (rapidjson::Value::ConstMemberIterator setting_iterator = it->MemberBegin(); setting_iterator != it->MemberEnd(); ++setting_iterator) { _addSettingToContainer(child, setting_iterator, warn_duplicates, false); } idx++; } } } else { logError("Error: JSON machine_extruder_trains is not an array!\n"); } } if (json_document.HasMember("machine_settings")) { categories.emplace_back("machine_settings", "Machine Settings"); SettingContainer* category_machine_settings = &categories.back(); const rapidjson::Value& json_object_container = json_document["machine_settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(category_machine_settings, setting_iterator, warn_duplicates); } } if (json_document.HasMember("categories")) { for (rapidjson::Value::ConstMemberIterator category_iterator = json_document["categories"].MemberBegin(); category_iterator != json_document["categories"].MemberEnd(); ++category_iterator) { if (!category_iterator->value.IsObject()) { continue; } if (!category_iterator->value.HasMember("label") || !category_iterator->value["label"].IsString()) { continue; } if (!category_iterator->value.HasMember("settings") || !category_iterator->value["settings"].IsObject()) { continue; } categories.emplace_back(category_iterator->name.GetString(), category_iterator->value["label"].GetString()); SettingContainer* category = &categories.back(); const rapidjson::Value& json_object_container = category_iterator->value["settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(category, setting_iterator, warn_duplicates); } } } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); logError("%s\n", setting.c_str()); SettingConfig* conf = getSettingConfig(setting); _loadSettingValues(conf, override_iterator, false); } } return 0; } void SettingRegistry::_addSettingToContainer(SettingContainer* parent, rapidjson::Value::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; if (data.HasMember("type") && data["type"].IsString() && (data["type"].GetString() == std::string("polygon") || data["type"].GetString() == std::string("polygons"))) { logWarning("Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); /// When this setting has children, add those children to the parent setting. if (data.HasMember("children") && data["children"].IsObject()) { const rapidjson::Value& json_object_container = data["children"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(parent, setting_iterator, warn_duplicates, add_to_settings); } } return; } std::string label; if (!json_object_it->value.HasMember("label") || !data["label"].IsString()) { label = "N/A"; } else { label = data["label"].GetString(); } /// Create the new setting config object. SettingConfig* config = parent->addChild(json_object_it->name.GetString(), label); _loadSettingValues(config, json_object_it, warn_duplicates, add_to_settings); } void SettingRegistry::_loadSettingValues(SettingConfig* config, rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (data.HasMember("default")) { const rapidjson::Value& dflt = data["default"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { logError("Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } /// Register the setting in the settings map lookup. if (warn_duplicates && settingExists(config->getKey())) { cura::logError("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", config->getKey().c_str(), config->getLabel().c_str(), getSettingConfig(config->getKey())->getLabel().c_str()); } if (add_to_settings) { settings[config->getKey()] = config; } /// When this setting has children, add those children to this setting. if (data.HasMember("children") && data["children"].IsObject()) { const rapidjson::Value& json_object_container = data["children"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(config, setting_iterator, warn_duplicates, add_to_settings); } } } }//namespace cura<|endoftext|>
<commit_before>/* * bonjour.cpp * * Copyright (C) 2014 William Markezana <william.markezana@me.com> * */ #include "bonjour.h" #include "strings-helper.h" #include <muduo/base/Logging.h> #include <signal.h> void *avahi_service(void *arg); /* * constructor * */ bonjour::bonjour() { mIniFile = new ini_parser((string) CONFIGURATION_DIRECTORY + "config.cfg"); hostname = mIniFile->get<string>("PIXEL_STYLES", "Hostname", "Pixel Styles"); avahi_publish_service_pid = 0; mAvahiThread = 0; pthread_create(&mAvahiThread, NULL, avahi_service, this); delete mIniFile; } /* * destructor * */ bonjour::~bonjour() { if (kill(avahi_publish_service_pid, SIGINT) == -1) { LOG_INFO << "Unable to kill avahi-publish-service process!"; } LOG_INFO << "Closed Service " << hostname; } /* * private callbacks * */ void *avahi_service(void *arg) { bonjour *mBonjour = (bonjour*) arg; pid_t pid; pid = fork(); if (pid < 0) return (void*) (1); else if (pid == 0) { /* if (execlp("avahi-publish-service", "avahi-publish-service", mBonjour->hostname.c_str(), "_PixelStyles._tcp", to_string(TCP_CONNECTION_PORT).c_str(), strcat((char*) "kLivePreviewUdpPort=", to_string(UDP_BROADCAST_PORT).c_str()), NULL) == -1) { */ if( execlp("avahi-publish-service", "avahi-publish-service", mBonjour->hostname.c_str(), "_PixelStyles._tcp", to_string(TCP_CONNECTION_PORT).c_str(), ((string)"kLivePreviewUdpPort="+to_string(UDP_BROADCAST_PORT)).c_str(), NULL) == -1 ) { LOG_INFO << "Bad error... couldn't find or failed to run: avahi-publish-service OR dns-sd OR mDNSPublish"; return (void*) (1); } } LOG_INFO << "Started avahi-publish-service with pid " << pid << " hostname '" << mBonjour->hostname << "'"; mBonjour->avahi_publish_service_pid = pid; return (void*) (1); } <commit_msg>[bonjour] useless comments removed.<commit_after>/* * bonjour.cpp * * Copyright (C) 2014 William Markezana <william.markezana@me.com> * */ #include "bonjour.h" #include "strings-helper.h" #include <muduo/base/Logging.h> #include <signal.h> void *avahi_service(void *arg); /* * constructor * */ bonjour::bonjour() { mIniFile = new ini_parser((string) CONFIGURATION_DIRECTORY + "config.cfg"); hostname = mIniFile->get<string>("PIXEL_STYLES", "Hostname", "Pixel Styles"); avahi_publish_service_pid = 0; mAvahiThread = 0; pthread_create(&mAvahiThread, NULL, avahi_service, this); delete mIniFile; } /* * destructor * */ bonjour::~bonjour() { if (kill(avahi_publish_service_pid, SIGINT) == -1) { LOG_INFO << "Unable to kill avahi-publish-service process!"; } LOG_INFO << "Closed Service " << hostname; } /* * private callbacks * */ void *avahi_service(void *arg) { bonjour *mBonjour = (bonjour*) arg; pid_t pid; pid = fork(); if (pid < 0) return (void*) (1); else if (pid == 0) { if( execlp("avahi-publish-service", "avahi-publish-service", mBonjour->hostname.c_str(), "_PixelStyles._tcp", to_string(TCP_CONNECTION_PORT).c_str(), ((string)"kLivePreviewUdpPort="+to_string(UDP_BROADCAST_PORT)).c_str(), NULL) == -1 ) { LOG_INFO << "Bad error... couldn't find or failed to run: avahi-publish-service OR dns-sd OR mDNSPublish"; return (void*) (1); } } LOG_INFO << "Started avahi-publish-service with pid " << pid << " hostname '" << mBonjour->hostname << "'"; mBonjour->avahi_publish_service_pid = pid; return (void*) (1); } <|endoftext|>
<commit_before>#include "stable_vector.h" #include <boost/noncopyable.hpp> #include <boost/container/stable_vector.hpp> #include <gtest/gtest.h> #include <list> #include <vector> #include <chrono> struct A { explicit A(int i) : m_i(i) { } int m_i; }; struct B : A, boost::noncopyable { using A::A; }; TEST(stable_vector, init) { stable_vector<int> v; ASSERT_TRUE(v.empty()); ASSERT_EQ(v.size(), 0); } TEST(stable_vector, ctor_initializer_list) { stable_vector<int> v = {0, 1, 2, 3, 4}; ASSERT_EQ(v.size(), 5); ASSERT_EQ(std::accumulate(v.cbegin(), v.cend(), 0), 0 + 1 + 2 + 3 + 4); } TEST(stable_vector, ctor_element_copies) { stable_vector<int> v(5, 1); ASSERT_EQ(v.size(), 5); ASSERT_EQ(v[0], 1); ASSERT_EQ(std::accumulate(v.cbegin(), v.cend(), 0), 5); } TEST(stable_vector, ctor_count) { stable_vector<int> v(5); ASSERT_EQ(v.size(), 5); ASSERT_EQ(v[0], 0); ASSERT_EQ(std::accumulate(v.cbegin(), v.cend(), 0), 0); } TEST(stable_vector, ctor_input_iterator) { std::list<int> l = {1, 2, 3, 4, 5}; stable_vector<int> v(l.begin(), l.end()); ASSERT_EQ(v.size(), l.size()); ASSERT_EQ(std::accumulate(v.cbegin(), v.cend(), 0), std::accumulate(l.cbegin(), l.cend(), 0)); } TEST(stable_vector, copy_ctor) { stable_vector<int> v1 = {1, 2, 3, 4, 5}; stable_vector<int> v2(v1); ASSERT_TRUE(v1 == v2); v2.push_back(6); ASSERT_EQ(v1.size(), 5); ASSERT_EQ(v2.size(), 6); } TEST(stable_vector, copy_assignment) { stable_vector<int> v1 = {1, 2, 3, 4, 5}; stable_vector<int> v2 = {10, 11}; ASSERT_TRUE(v1 != v2); v2 = v1; ASSERT_TRUE(v1 == v2); v2.push_back(6); ASSERT_EQ(v1.size(), 5); ASSERT_EQ(v2.size(), 6); } TEST(stable_vector, move_ctor) { stable_vector<int> vtmp = {1, 2, 3, 4, 5}; stable_vector<int> v2(std::move(vtmp)); ASSERT_EQ(v2.size(), 5); ASSERT_TRUE(vtmp.empty()); } TEST(stable_vector, move_assignment) { stable_vector<int> v2 = {10, 11}; v2 = stable_vector<int>({1, 2, 3, 4, 5}); ASSERT_EQ(v2.size(), 5); } TEST(stable_vector, push_back) { stable_vector<A> v; A a(1); v.push_back(a); ASSERT_EQ(v.size(), 1); ASSERT_EQ(v[0].m_i, a.m_i); v.push_back(A(2)); ASSERT_EQ(v.size(), 2); ASSERT_EQ(v[0].m_i, a.m_i); ASSERT_EQ(v[1].m_i, 2); } TEST(stable_vector, emplace_back) { stable_vector<B> v; v.emplace_back(1); ASSERT_EQ(v.size(), 1); ASSERT_EQ(v[0].m_i, 1); } TEST(stable_vector, out_of_range) { stable_vector<A> v; ASSERT_THROW(v.at(0), std::out_of_range); } TEST(stable_vector, equal) { stable_vector<int> v1; v1.push_back(0); v1.push_back(1); v1.push_back(2); stable_vector<int> v2; v2.push_back(0); v2.push_back(1); v2.push_back(2); ASSERT_TRUE(v1 == v2); ASSERT_FALSE(v1 != v2); } TEST(stable_vector, not_equal) { stable_vector<int> v1; v1.push_back(0); stable_vector<int> v2; ASSERT_TRUE(v1 != v2); ASSERT_FALSE(v1 == v2); } TEST(stable_vector, front) { stable_vector<int> v; v.push_back(1); ASSERT_EQ(v.front(), 1); v.push_back(2); ASSERT_EQ(v.front(), 1); } TEST(stable_vector, back) { stable_vector<int> v; v.push_back(1); ASSERT_EQ(v.back(), 1); v.push_back(2); ASSERT_EQ(v.back(), 2); } TEST(stable_vector, begin) { stable_vector<int> v; v.push_back(1); ASSERT_EQ(*v.begin(), 1); ASSERT_EQ(*v.cbegin(), 1); v.push_back(2); ASSERT_EQ(*v.begin(), 1); ASSERT_EQ(*v.cbegin(), 1); } TEST(stable_vector, end) { stable_vector<int> v; v.push_back(1); ASSERT_EQ(*(v.end() - 1), 1); ASSERT_EQ(*(v.cend() - 1), 1); v.push_back(2); ASSERT_EQ(*(v.end() - 1), 2); ASSERT_EQ(*(v.cend() - 1), 2); } TEST(stable_vector, capacity) { stable_vector<int, 16> v; ASSERT_EQ(0, v.capacity()); v.emplace_back(1); ASSERT_EQ(16, v.capacity()); stable_vector<int, 16> v2(55); ASSERT_EQ(64, v2.capacity()); } TEST(stable_vector, reserve) { stable_vector<int, 8> v; v.reserve(1); ASSERT_EQ(8, v.capacity()); v.reserve(31); ASSERT_EQ(32, v.capacity()); v.reserve(10); ASSERT_EQ(32, v.capacity()); v.reserve(1); ASSERT_EQ(32, v.capacity()); stable_vector<int, 8> v2; v2.reserve(41); ASSERT_EQ(48, v2.capacity()); } TEST(stable_vector_multiple_chunks, init) { stable_vector<int, 4> v = {1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_EQ(v.size(), 9); } TEST(stable_vector_multiple_chunks, copy) { stable_vector<int, 4> v = {1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_EQ(v.size(), 9); stable_vector<int, 4> v2 = {1}; ASSERT_EQ(v2.size(), 1); v2 = v; ASSERT_EQ(v2.size(), 9); v = {}; ASSERT_TRUE(v.empty()); ASSERT_EQ(v2.size(), 9); ASSERT_EQ(v2[8], 9); } TEST(stable_vector_multiple_chunks, reference) { stable_vector<int, 2> v = {1, 2}; auto* ref = &v[1]; for (int i = 3; i < 10; ++i) v.push_back(i); ASSERT_TRUE(ref == &v[1]); } TEST(stable_vector_multiple_chunks, iterator) { stable_vector<int, 2> v = {1, 2, 3}; auto it = v.begin() + 1; for (int i = 4; i < 10; ++i) v.push_back(i); ASSERT_TRUE(*it == 2); ASSERT_TRUE(it == v.begin() + 1); } TEST(stable_vector_iterator, empty) { stable_vector<int> v; ASSERT_TRUE(v.begin() == v.end()); ASSERT_TRUE(v.begin() == v.cend()); ASSERT_TRUE(v.cbegin() == v.end()); ASSERT_TRUE(v.cbegin() == v.cend()); } TEST(stable_vector_iterator, for_loop) { stable_vector<int> v = {0, 1, 2, 3, 4}; int i = 0; for (auto it = v.cbegin(); it != v.cend(); ++it, ++i) ASSERT_EQ(*it, i); i = 0; for (auto t : v) ASSERT_EQ(t, i++); } TEST(stable_vector_iterator, arithmetic) { stable_vector<int> v = {0, 1, 2, 3, 4}; auto it = v.cbegin() + 3; ASSERT_EQ(*it, 3); it = it - 1; ASSERT_EQ(*it, 2); --it; ASSERT_EQ(*it, 1); it += 4; ASSERT_TRUE(it == v.cend()); ASSERT_TRUE(it == v.end()); it -= 5; ASSERT_TRUE(it == v.cbegin()); ASSERT_TRUE(it == v.begin()); } template <class ContainerT> int sum(const ContainerT& v) { int sum = 0; auto start = std::chrono::high_resolution_clock::now(); for (const auto& i : v) { sum += i; } auto end = std::chrono::high_resolution_clock::now(); std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "ms elapsed" << std::endl; return sum; } static std::size_t ElementsCount = 10000000; TEST(stable_vector_iterator, performance) { stable_vector<int, 4096> v(ElementsCount, 1); int s = sum(v); EXPECT_EQ(ElementsCount, s); } TEST(boost_stable_vector_iterator, performance) { boost::container::stable_vector<int> v(ElementsCount, 1); int s = sum(v); EXPECT_EQ(ElementsCount, s); } TEST(list_iterator, performance) { std::list<int> v(ElementsCount, 1); int s = sum(v); EXPECT_EQ(ElementsCount, s); } TEST(std_vector_iterator, performance) { std::vector<int> v(10000000, 1); int s = sum(v); std::cout << s << std::endl; } <commit_msg>unit tests on move assign<commit_after>#include "stable_vector.h" #include <boost/noncopyable.hpp> #include <boost/container/stable_vector.hpp> #include <gtest/gtest.h> #include <list> #include <vector> #include <chrono> struct A { explicit A(int i) : m_i(i) { } int m_i; }; struct B : A, boost::noncopyable { using A::A; }; template <bool NoExcept = false> class CallCounter { public: CallCounter() { ++constructions; } ~CallCounter() noexcept(true) { ++destructions; } CallCounter(const CallCounter&) { ++copy_constructions; } CallCounter& operator=(const CallCounter&) { ++copy_constructions; return *this; } CallCounter(CallCounter&&) noexcept(NoExcept) { ++move_constructions; } CallCounter& operator=(CallCounter&&) noexcept(NoExcept) { ++move_constructions; return *this; } static void reset_counters() { constructions = 0; copy_constructions = 0; move_constructions = 0; destructions = 0; } static int constructions; static int copy_constructions; static int move_constructions; static int destructions; }; template <bool NoExcept> int CallCounter<NoExcept>::constructions = 0; template <bool NoExcept> int CallCounter<NoExcept>::copy_constructions = 0; template <bool NoExcept> int CallCounter<NoExcept>::move_constructions = 0; template <bool NoExcept> int CallCounter<NoExcept>::destructions = 0; TEST(stable_vector, init) { stable_vector<int> v; ASSERT_TRUE(v.empty()); ASSERT_EQ(v.size(), 0); } TEST(stable_vector, ctor_initializer_list) { stable_vector<int> v = {0, 1, 2, 3, 4}; ASSERT_EQ(v.size(), 5); ASSERT_EQ(std::accumulate(v.cbegin(), v.cend(), 0), 0 + 1 + 2 + 3 + 4); } TEST(stable_vector, ctor_element_copies) { stable_vector<int> v(5, 1); ASSERT_EQ(v.size(), 5); ASSERT_EQ(v[0], 1); ASSERT_EQ(std::accumulate(v.cbegin(), v.cend(), 0), 5); } TEST(stable_vector, ctor_count) { stable_vector<int> v(5); ASSERT_EQ(v.size(), 5); ASSERT_EQ(v[0], 0); ASSERT_EQ(std::accumulate(v.cbegin(), v.cend(), 0), 0); } TEST(stable_vector, ctor_input_iterator) { std::list<int> l = {1, 2, 3, 4, 5}; stable_vector<int> v(l.begin(), l.end()); ASSERT_EQ(v.size(), l.size()); ASSERT_EQ(std::accumulate(v.cbegin(), v.cend(), 0), std::accumulate(l.cbegin(), l.cend(), 0)); } TEST(stable_vector, copy_ctor) { stable_vector<int> v1 = {1, 2, 3, 4, 5}; stable_vector<int> v2(v1); ASSERT_TRUE(v1 == v2); v2.push_back(6); ASSERT_EQ(v1.size(), 5); ASSERT_EQ(v2.size(), 6); } TEST(stable_vector, copy_assignment) { stable_vector<int> v1 = {1, 2, 3, 4, 5}; stable_vector<int> v2 = {10, 11}; ASSERT_TRUE(v1 != v2); v2 = v1; ASSERT_TRUE(v1 == v2); v2.push_back(6); ASSERT_EQ(v1.size(), 5); ASSERT_EQ(v2.size(), 6); } TEST(stable_vector, move_ctor) { stable_vector<int> vtmp = {1, 2, 3, 4, 5}; stable_vector<int> v2(std::move(vtmp)); ASSERT_EQ(v2.size(), 5); ASSERT_TRUE(vtmp.empty()); } TEST(stable_vector, move_assignment) { stable_vector<CallCounter<>, 16> v(10); ASSERT_EQ(v.size(), 10); stable_vector<CallCounter<>, 16> v2(3); CallCounter<>::reset_counters(); v = std::move(v2); ASSERT_EQ(v.size(), 3); EXPECT_EQ(0, CallCounter<>::constructions); EXPECT_EQ(10, CallCounter<>::destructions); EXPECT_EQ(0, CallCounter<>::copy_constructions); EXPECT_EQ(0, CallCounter<>::move_constructions); } TEST(stable_vector, push_back) { stable_vector<A> v; A a(1); v.push_back(a); ASSERT_EQ(v.size(), 1); ASSERT_EQ(v[0].m_i, a.m_i); v.push_back(A(2)); ASSERT_EQ(v.size(), 2); ASSERT_EQ(v[0].m_i, a.m_i); ASSERT_EQ(v[1].m_i, 2); } TEST(stable_vector, emplace_back) { stable_vector<B> v; v.emplace_back(1); ASSERT_EQ(v.size(), 1); ASSERT_EQ(v[0].m_i, 1); } TEST(stable_vector, out_of_range) { stable_vector<A> v; ASSERT_THROW(v.at(0), std::out_of_range); } TEST(stable_vector, equal) { stable_vector<int> v1; v1.push_back(0); v1.push_back(1); v1.push_back(2); stable_vector<int> v2; v2.push_back(0); v2.push_back(1); v2.push_back(2); ASSERT_TRUE(v1 == v2); ASSERT_FALSE(v1 != v2); } TEST(stable_vector, not_equal) { stable_vector<int> v1; v1.push_back(0); stable_vector<int> v2; ASSERT_TRUE(v1 != v2); ASSERT_FALSE(v1 == v2); } TEST(stable_vector, front) { stable_vector<int> v; v.push_back(1); ASSERT_EQ(v.front(), 1); v.push_back(2); ASSERT_EQ(v.front(), 1); } TEST(stable_vector, back) { stable_vector<int> v; v.push_back(1); ASSERT_EQ(v.back(), 1); v.push_back(2); ASSERT_EQ(v.back(), 2); } TEST(stable_vector, begin) { stable_vector<int> v; v.push_back(1); ASSERT_EQ(*v.begin(), 1); ASSERT_EQ(*v.cbegin(), 1); v.push_back(2); ASSERT_EQ(*v.begin(), 1); ASSERT_EQ(*v.cbegin(), 1); } TEST(stable_vector, end) { stable_vector<int> v; v.push_back(1); ASSERT_EQ(*(v.end() - 1), 1); ASSERT_EQ(*(v.cend() - 1), 1); v.push_back(2); ASSERT_EQ(*(v.end() - 1), 2); ASSERT_EQ(*(v.cend() - 1), 2); } TEST(stable_vector, capacity) { stable_vector<int, 16> v; ASSERT_EQ(0, v.capacity()); v.emplace_back(1); ASSERT_EQ(16, v.capacity()); stable_vector<int, 16> v2(55); ASSERT_EQ(64, v2.capacity()); } TEST(stable_vector, reserve) { stable_vector<int, 8> v; v.reserve(1); ASSERT_EQ(8, v.capacity()); v.reserve(31); ASSERT_EQ(32, v.capacity()); v.reserve(10); ASSERT_EQ(32, v.capacity()); v.reserve(1); ASSERT_EQ(32, v.capacity()); stable_vector<int, 8> v2; v2.reserve(41); ASSERT_EQ(48, v2.capacity()); } TEST(stable_vector_multiple_chunks, init) { stable_vector<int, 4> v = {1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_EQ(v.size(), 9); } TEST(stable_vector_multiple_chunks, copy) { stable_vector<int, 4> v = {1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_EQ(v.size(), 9); stable_vector<int, 4> v2 = {1}; ASSERT_EQ(v2.size(), 1); v2 = v; ASSERT_EQ(v2.size(), 9); v = {}; ASSERT_TRUE(v.empty()); ASSERT_EQ(v2.size(), 9); ASSERT_EQ(v2[8], 9); } TEST(stable_vector_multiple_chunks, reference) { stable_vector<int, 2> v = {1, 2}; auto* ref = &v[1]; for (int i = 3; i < 10; ++i) v.push_back(i); ASSERT_TRUE(ref == &v[1]); } TEST(stable_vector_multiple_chunks, iterator) { stable_vector<int, 2> v = {1, 2, 3}; auto it = v.begin() + 1; for (int i = 4; i < 10; ++i) v.push_back(i); ASSERT_TRUE(*it == 2); ASSERT_TRUE(it == v.begin() + 1); } TEST(stable_vector_iterator, empty) { stable_vector<int> v; ASSERT_TRUE(v.begin() == v.end()); ASSERT_TRUE(v.begin() == v.cend()); ASSERT_TRUE(v.cbegin() == v.end()); ASSERT_TRUE(v.cbegin() == v.cend()); } TEST(stable_vector_iterator, for_loop) { stable_vector<int> v = {0, 1, 2, 3, 4}; int i = 0; for (auto it = v.cbegin(); it != v.cend(); ++it, ++i) ASSERT_EQ(*it, i); i = 0; for (auto t : v) ASSERT_EQ(t, i++); } TEST(stable_vector_iterator, arithmetic) { stable_vector<int> v = {0, 1, 2, 3, 4}; auto it = v.cbegin() + 3; ASSERT_EQ(*it, 3); it = it - 1; ASSERT_EQ(*it, 2); --it; ASSERT_EQ(*it, 1); it += 4; ASSERT_TRUE(it == v.cend()); ASSERT_TRUE(it == v.end()); it -= 5; ASSERT_TRUE(it == v.cbegin()); ASSERT_TRUE(it == v.begin()); } template <class ContainerT> int sum(const ContainerT& v) { int sum = 0; auto start = std::chrono::high_resolution_clock::now(); for (const auto& i : v) { sum += i; } auto end = std::chrono::high_resolution_clock::now(); std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "ms elapsed" << std::endl; return sum; } static std::size_t ElementsCount = 10000000; TEST(stable_vector_iterator, performance) { stable_vector<int, 4096> v(ElementsCount, 1); int s = sum(v); EXPECT_EQ(ElementsCount, s); } TEST(boost_stable_vector_iterator, performance) { boost::container::stable_vector<int> v(ElementsCount, 1); int s = sum(v); EXPECT_EQ(ElementsCount, s); } TEST(list_iterator, performance) { std::list<int> v(ElementsCount, 1); int s = sum(v); EXPECT_EQ(ElementsCount, s); } TEST(std_vector_iterator, performance) { std::vector<int> v(10000000, 1); int s = sum(v); std::cout << s << std::endl; } <|endoftext|>
<commit_before>#include "starlight_input.h" #define NUM_KEYBOARD_KEYS 0x100 #define NUM_MOUSE_BUTTONS 5 // Keyboard static bool prev[NUM_KEYBOARD_KEYS]; static bool keys[NUM_KEYBOARD_KEYS]; static bool down[NUM_KEYBOARD_KEYS]; static bool up[NUM_KEYBOARD_KEYS]; // Mouse static bool mousePrev[NUM_MOUSE_BUTTONS]; static bool mouseButtons[NUM_MOUSE_BUTTONS]; static bool mouseDown[NUM_MOUSE_BUTTONS]; static bool mouseUp[NUM_MOUSE_BUTTONS]; static bool isMouseGrabbed; static float2 lastMousePos; static float2 mouseDelta; static float2 mousePos; bool input::GetKey(int key) { return keys[key]; } bool input::GetKeyDown(int key) { return down[key]; } bool input::GetKeyUp(int key) { return up[key]; } bool input::GetMouse(int button) { return mouseButtons[button]; } bool input::GetMouseDown(int button) { return mouseDown[button]; } bool input::GetMouseUp(int button) { return mouseUp[button]; } bool input::IsMouseGrabbed() { return isMouseGrabbed; } // In pixels. Origin is top-left float2 input::GetMouseDelta() { return mouseDelta; } // In pixels. Origin is top-left float2 input::GetMousePosition() { return mousePos; } void input::SetMouseButton(int button, bool pressed) { mouseButtons[button] = pressed; } void input::SetKey(int key, bool pressed) { keys[key] = pressed; } void input::SetMousePosition(float2 pos) { mousePos = pos; mouseDelta += pos - lastMousePos; } void input::Init() { // Keyboard memset(prev, int(false), NUM_KEYBOARD_KEYS * sizeof(bool)); memset(keys, int(false), NUM_KEYBOARD_KEYS * sizeof(bool)); memset(down, int(false), NUM_KEYBOARD_KEYS * sizeof(bool)); memset(up, int(false), NUM_KEYBOARD_KEYS * sizeof(bool)); // Mouse memset(mousePrev, int(false), NUM_MOUSE_BUTTONS * sizeof(bool)); memset(mouseButtons, int(false), NUM_MOUSE_BUTTONS * sizeof(bool)); memset(mouseDown, int(false), NUM_MOUSE_BUTTONS * sizeof(bool)); memset(mouseUp, int(false), NUM_MOUSE_BUTTONS * sizeof(bool)); isMouseGrabbed = false; mouseDelta = { 0, 0 }; } void input::BeginFrame() { // Keyboard { bool changes[NUM_KEYBOARD_KEYS]; for (unsigned int i = 0; i < NUM_KEYBOARD_KEYS; i++) { changes[i] = keys[i] ^ prev[i]; down[i] = changes[i] & keys[i]; up[i] = changes[i] & !keys[i]; } } // Mouse { bool changes[NUM_MOUSE_BUTTONS]; for (unsigned int i = 0; i < NUM_MOUSE_BUTTONS; i++) { changes[i] = mouseButtons[i] ^ mousePrev[i]; mouseDown[i] = changes[i] & mouseButtons[i]; mouseUp[i] = changes[i] & !mouseButtons[i]; } } } void input::EndFrame() { memcpy(prev, keys, NUM_KEYBOARD_KEYS * sizeof(bool)); memcpy(mousePrev, mouseButtons, NUM_MOUSE_BUTTONS * sizeof(bool)); mouseDelta = { 0, 0 }; lastMousePos = mousePos; } void input::SetMouseGrabbed(bool grabMouse) { // TODO #if 0 isMouseGrabbed = grabMouse; if (isMouseGrabbed) { glfwSetInputMode(mj::Application::GetWindow(), GLFW_CURSOR, GLFW_CURSOR_DISABLED); } else { glfwSetInputMode(mj::Application::GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL); } #endif } <commit_msg>Fix build error<commit_after>#include "starlight_input.h" #include <string.h> #define NUM_KEYBOARD_KEYS 0x100 #define NUM_MOUSE_BUTTONS 5 // Keyboard static bool prev[NUM_KEYBOARD_KEYS]; static bool keys[NUM_KEYBOARD_KEYS]; static bool down[NUM_KEYBOARD_KEYS]; static bool up[NUM_KEYBOARD_KEYS]; // Mouse static bool mousePrev[NUM_MOUSE_BUTTONS]; static bool mouseButtons[NUM_MOUSE_BUTTONS]; static bool mouseDown[NUM_MOUSE_BUTTONS]; static bool mouseUp[NUM_MOUSE_BUTTONS]; static bool isMouseGrabbed; static float2 lastMousePos; static float2 mouseDelta; static float2 mousePos; bool input::GetKey(int key) { return keys[key]; } bool input::GetKeyDown(int key) { return down[key]; } bool input::GetKeyUp(int key) { return up[key]; } bool input::GetMouse(int button) { return mouseButtons[button]; } bool input::GetMouseDown(int button) { return mouseDown[button]; } bool input::GetMouseUp(int button) { return mouseUp[button]; } bool input::IsMouseGrabbed() { return isMouseGrabbed; } // In pixels. Origin is top-left float2 input::GetMouseDelta() { return mouseDelta; } // In pixels. Origin is top-left float2 input::GetMousePosition() { return mousePos; } void input::SetMouseButton(int button, bool pressed) { mouseButtons[button] = pressed; } void input::SetKey(int key, bool pressed) { keys[key] = pressed; } void input::SetMousePosition(float2 pos) { mousePos = pos; mouseDelta += pos - lastMousePos; } void input::Init() { // Keyboard memset(prev, int(false), NUM_KEYBOARD_KEYS * sizeof(bool)); memset(keys, int(false), NUM_KEYBOARD_KEYS * sizeof(bool)); memset(down, int(false), NUM_KEYBOARD_KEYS * sizeof(bool)); memset(up, int(false), NUM_KEYBOARD_KEYS * sizeof(bool)); // Mouse memset(mousePrev, int(false), NUM_MOUSE_BUTTONS * sizeof(bool)); memset(mouseButtons, int(false), NUM_MOUSE_BUTTONS * sizeof(bool)); memset(mouseDown, int(false), NUM_MOUSE_BUTTONS * sizeof(bool)); memset(mouseUp, int(false), NUM_MOUSE_BUTTONS * sizeof(bool)); isMouseGrabbed = false; mouseDelta = { 0, 0 }; } void input::BeginFrame() { // Keyboard { bool changes[NUM_KEYBOARD_KEYS]; for (unsigned int i = 0; i < NUM_KEYBOARD_KEYS; i++) { changes[i] = keys[i] ^ prev[i]; down[i] = changes[i] & keys[i]; up[i] = changes[i] & !keys[i]; } } // Mouse { bool changes[NUM_MOUSE_BUTTONS]; for (unsigned int i = 0; i < NUM_MOUSE_BUTTONS; i++) { changes[i] = mouseButtons[i] ^ mousePrev[i]; mouseDown[i] = changes[i] & mouseButtons[i]; mouseUp[i] = changes[i] & !mouseButtons[i]; } } } void input::EndFrame() { memcpy(prev, keys, NUM_KEYBOARD_KEYS * sizeof(bool)); memcpy(mousePrev, mouseButtons, NUM_MOUSE_BUTTONS * sizeof(bool)); mouseDelta = { 0, 0 }; lastMousePos = mousePos; } void input::SetMouseGrabbed(bool grabMouse) { // TODO #if 0 isMouseGrabbed = grabMouse; if (isMouseGrabbed) { glfwSetInputMode(mj::Application::GetWindow(), GLFW_CURSOR, GLFW_CURSOR_DISABLED); } else { glfwSetInputMode(mj::Application::GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL); } #endif } <|endoftext|>
<commit_before><commit_msg>coverity#1019326 Unchecked dynamic_cast<commit_after><|endoftext|>
<commit_before>#include "Board.h" #include "Pipe.h" #include "Log.h" const int Board::x_offset = 227; const int Board::y_offset = 35; const int Board::slotSize = 48; const int Board::lines = BOARD_LINES; const int Board::columns = BOARD_COLUMNS; Board::Board (SDL_Surface* s, SDL_Rect* c, SDL_Surface* back, SDL_Surface* pipe1, SDL_Surface* pipe2) { screen = s; coordinates = c; background = back; pipes_sprite1 = pipe1; pipes_sprite2 = pipe2; starting_time = SDL_GetTicks(); flow_started = false; game_in_progress = true; for (int line = 0; line < lines; line++) { for (int column = 0; column < columns; column++) { slots[line][column] = NULL; } } for (int p = 0; p < POOL_SIZE; p++) { pool[p] = new Pipe(pipes_sprite1, pipes_sprite2); } } void Board::mouseClick (int x, int y) { int x_min = x_offset, x_max = x_min + (lines * slotSize); int y_min = y_offset, y_max = y_min + (columns * slotSize); // Check limits if (x >= x_min && x <= x_max && y >= y_min && y <= y_max) { int line = (x - x_min) / slotSize; int column = (y - y_min) / slotSize; Pipe **pipe = &slots[line][column]; if (*pipe) { if ((*pipe)->isBlocked()) return; delete *pipe; } // Get top of the pool *pipe = pool[0]; rotatePool(); } } void Board::rotatePool (void) { for (int p = 0; p < POOL_SIZE - 1; p++) { pool[p] = pool[p + 1]; } pool[POOL_SIZE - 1] = new Pipe(pipes_sprite1, pipes_sprite2); } SDL_Rect Board::getSlotScreenPosition (int line, int column) { SDL_Rect pos; pos.x = (line * slotSize) + x_offset; pos.y = (column * slotSize) + y_offset; return pos; } Pipe* Board::getPipe(int column, int line) { if(column >= BOARD_COLUMNS || column < 0 || line >= BOARD_LINES || line < 0) { return NULL; } else { return slots[column][line]; } } Pipe* Board::getCurrentPipe() { return getPipe(current_pipe_column, current_pipe_line); } void Board::getNextPipe(const int direction, int *column, int *line, int *flow) { *column = current_pipe_column; *line = current_pipe_line; switch(direction) { case FLOW_TOP: *line -= 1; *flow = FLOW_DOWN; break; case FLOW_RIGHT: *column += 1; *flow = FLOW_LEFT; break; case FLOW_DOWN: *line += 1; *flow = FLOW_TOP; break; case FLOW_LEFT: *column -= 1; *flow = FLOW_RIGHT; break; }; } void Board::Update() { if(game_in_progress) { updatePipes(); updateStartingFlow(); updateNextPipe(); } } void Board::updatePipes() { for (int l = 0; l < lines; l++) { for (int c = 0; c < columns; c++) { if (slots[l][c] != NULL) { slots[l][c]->Update(); } } } } void Board::updateStartingFlow() { if (flow_started == false && SDL_GetTicks() - starting_time > INITIAL_DELAY) { if (slots[INITIAL_COLUMN][INITIAL_LINE] != NULL) { current_pipe_column = INITIAL_COLUMN; current_pipe_line = INITIAL_LINE; getCurrentPipe()->StartFlow(FLOW_LEFT); flow_started = true; } else { gameOver(); } } } void Board::updateNextPipe() { if (flow_started == true && getCurrentPipe()->isFlowFinished()) { int flow_direction = getCurrentPipe()->getFlowTurnPosition(); int next_flow; int column, line, flow; getNextPipe(flow_direction, &column, &line, &flow); current_pipe_column = column; current_pipe_line = line; next_flow = flow; // game over if has no next pipe or the next pipe does not have the next_flow entry if (getCurrentPipe() == NULL || !getCurrentPipe()->hasFlowEntry(next_flow)) { gameOver(); } else { getCurrentPipe()->StartFlow(next_flow); } } else if(flow_started == true) { int next_flow_direction = calculateNextFlowDirection(); if(next_flow_direction > 0) { getCurrentPipe()->setFlowTurnPosition(calculateNextFlowDirection()); } else { gameOver(); } } } int Board::calculateNextFlowDirection() { Pipe* pipe = getCurrentPipe(); Pipe* next_pipe; int column, line, flow; // finds the first possible next pipe if(pipe->hasFlowEntry(FLOW_TOP) && !pipe->getFlowStartPosition()) { getNextPipe(FLOW_TOP, &column, &line, &flow); next_pipe = getPipe(column, line); if(next_pipe->hasFlowEntry(FLOW_DOWN)) { return FLOW_TOP; } } if(next_pipe == NULL && pipe->hasFlowEntry(FLOW_RIGHT) && !pipe->getFlowStartPosition()) { getNextPipe(FLOW_RIGHT, &column, &line, &flow); next_pipe = getPipe(column, line); if(next_pipe->hasFlowEntry(FLOW_LEFT)) { return FLOW_RIGHT; } } if(next_pipe == NULL && pipe->hasFlowEntry(FLOW_DOWN) && !pipe->getFlowStartPosition()) { getNextPipe(FLOW_DOWN, &column, &line, &flow); next_pipe = getPipe(column, line); if(next_pipe->hasFlowEntry(FLOW_TOP)) { return FLOW_DOWN; } } if(next_pipe == NULL && pipe->hasFlowEntry(FLOW_LEFT) && !pipe->getFlowStartPosition()) { getNextPipe(FLOW_LEFT, &column, &line, &flow); next_pipe = getPipe(column, line); if(next_pipe->hasFlowEntry(FLOW_RIGHT)) { return FLOW_LEFT; } } // if couldn't find anything, turn to the first possible one if(pipe->hasFlowEntry(FLOW_TOP)) { return FLOW_TOP; } else if(pipe->hasFlowEntry(FLOW_RIGHT)) { return FLOW_RIGHT; } else if(pipe->hasFlowEntry(FLOW_DOWN)) { return FLOW_DOWN; } else if(pipe->hasFlowEntry(FLOW_LEFT)) { return FLOW_LEFT; } return 0; } void Board::Draw () { // Draw background SDL_BlitSurface(background, 0, screen, coordinates); // Draw all board pipes for (int l = 0; l < lines; l++) { for (int c = 0; c < columns; c++) { // if != NULL we have a pipe to draw if (slots[l][c] != NULL) { SDL_Rect pos = getSlotScreenPosition(l, c); slots[l][c]->Draw(screen, &pos); } } } // Draw pool pipes SDL_Rect pos; pos.x = POOL_OFFSET_X; pos.y = POOL_OFFSET_Y; for (int p = POOL_SIZE - 1; p > 0; p--, pos.y += POOL_SPACING) { pool[p]->Draw(screen, &pos); } pos.y = POOL_TOP_Y; pool[0]->Draw(screen, &pos); } void Board::gameOver() { LOG(logINFO) << "Game over !"; game_in_progress = false; } <commit_msg>Fix flow direction.<commit_after>#include "Board.h" #include "Pipe.h" #include "Log.h" const int Board::x_offset = 227; const int Board::y_offset = 35; const int Board::slotSize = 48; const int Board::lines = BOARD_LINES; const int Board::columns = BOARD_COLUMNS; Board::Board (SDL_Surface* s, SDL_Rect* c, SDL_Surface* back, SDL_Surface* pipe1, SDL_Surface* pipe2) { screen = s; coordinates = c; background = back; pipes_sprite1 = pipe1; pipes_sprite2 = pipe2; starting_time = SDL_GetTicks(); flow_started = false; game_in_progress = true; for (int line = 0; line < lines; line++) { for (int column = 0; column < columns; column++) { slots[line][column] = NULL; } } for (int p = 0; p < POOL_SIZE; p++) { pool[p] = new Pipe(pipes_sprite1, pipes_sprite2); } } void Board::mouseClick (int x, int y) { int x_min = x_offset, x_max = x_min + (lines * slotSize); int y_min = y_offset, y_max = y_min + (columns * slotSize); // Check limits if (x >= x_min && x <= x_max && y >= y_min && y <= y_max) { int line = (x - x_min) / slotSize; int column = (y - y_min) / slotSize; Pipe **pipe = &slots[line][column]; if (*pipe) { if ((*pipe)->isBlocked()) return; delete *pipe; } // Get top of the pool *pipe = pool[0]; rotatePool(); } } void Board::rotatePool (void) { for (int p = 0; p < POOL_SIZE - 1; p++) { pool[p] = pool[p + 1]; } pool[POOL_SIZE - 1] = new Pipe(pipes_sprite1, pipes_sprite2); } SDL_Rect Board::getSlotScreenPosition (int line, int column) { SDL_Rect pos; pos.x = (line * slotSize) + x_offset; pos.y = (column * slotSize) + y_offset; return pos; } Pipe* Board::getPipe(int column, int line) { if(column >= BOARD_COLUMNS || column < 0 || line >= BOARD_LINES || line < 0) { return NULL; } else { return slots[column][line]; } } Pipe* Board::getCurrentPipe() { return getPipe(current_pipe_column, current_pipe_line); } void Board::getNextPipe(const int direction, int *column, int *line, int *flow) { *column = current_pipe_column; *line = current_pipe_line; switch(direction) { case FLOW_TOP: *line -= 1; *flow = FLOW_DOWN; break; case FLOW_RIGHT: *column += 1; *flow = FLOW_LEFT; break; case FLOW_DOWN: *line += 1; *flow = FLOW_TOP; break; case FLOW_LEFT: *column -= 1; *flow = FLOW_RIGHT; break; }; } void Board::Update() { if(game_in_progress) { updatePipes(); updateStartingFlow(); updateNextPipe(); } } void Board::updatePipes() { for (int l = 0; l < lines; l++) { for (int c = 0; c < columns; c++) { if (slots[l][c] != NULL) { slots[l][c]->Update(); } } } } void Board::updateStartingFlow() { if (flow_started == false && SDL_GetTicks() - starting_time > INITIAL_DELAY) { if (slots[INITIAL_COLUMN][INITIAL_LINE] != NULL) { current_pipe_column = INITIAL_COLUMN; current_pipe_line = INITIAL_LINE; getCurrentPipe()->StartFlow(FLOW_LEFT); flow_started = true; } else { gameOver(); } } } void Board::updateNextPipe() { if (flow_started == true && getCurrentPipe()->isFlowFinished()) { int flow_direction = getCurrentPipe()->getFlowTurnPosition(); int next_flow; int column, line, flow; getNextPipe(flow_direction, &column, &line, &flow); current_pipe_column = column; current_pipe_line = line; next_flow = flow; // game over if has no next pipe or the next pipe does not have the next_flow entry if (getCurrentPipe() == NULL || !getCurrentPipe()->hasFlowEntry(next_flow)) { gameOver(); } else { getCurrentPipe()->StartFlow(next_flow); } } else if(flow_started == true) { int next_flow_direction = calculateNextFlowDirection(); if(next_flow_direction > 0) { getCurrentPipe()->setFlowTurnPosition(next_flow_direction); } else { gameOver(); } } } int Board::calculateNextFlowDirection() { Pipe* pipe = getCurrentPipe(); Pipe* next_pipe; int column, line, flow; // finds the first possible next pipe if (pipe->hasFlowEntry(FLOW_TOP) && pipe->getFlowStartPosition() != FLOW_TOP) { getNextPipe(FLOW_TOP, &column, &line, &flow); next_pipe = getPipe(column, line); if(next_pipe->hasFlowEntry(FLOW_DOWN)) { return FLOW_TOP; } } if (next_pipe == NULL && pipe->hasFlowEntry(FLOW_RIGHT) && pipe->getFlowStartPosition() != FLOW_RIGHT) { getNextPipe(FLOW_RIGHT, &column, &line, &flow); next_pipe = getPipe(column, line); if(next_pipe->hasFlowEntry(FLOW_LEFT)) { return FLOW_RIGHT; } } if (next_pipe == NULL && pipe->hasFlowEntry(FLOW_DOWN) && pipe->getFlowStartPosition() != FLOW_DOWN) { getNextPipe(FLOW_DOWN, &column, &line, &flow); next_pipe = getPipe(column, line); if(next_pipe->hasFlowEntry(FLOW_TOP)) { return FLOW_DOWN; } } if (next_pipe == NULL && pipe->hasFlowEntry(FLOW_LEFT) && pipe->getFlowStartPosition() != FLOW_LEFT) { getNextPipe(FLOW_LEFT, &column, &line, &flow); next_pipe = getPipe(column, line); if(next_pipe->hasFlowEntry(FLOW_RIGHT)) { return FLOW_LEFT; } } // if couldn't find anything, turn to the first possible one if(pipe->hasFlowEntry(FLOW_TOP) && pipe->getFlowStartPosition() != FLOW_TOP) { return FLOW_TOP; } else if(pipe->hasFlowEntry(FLOW_RIGHT) && pipe->getFlowStartPosition() != FLOW_RIGHT) { return FLOW_RIGHT; } else if(pipe->hasFlowEntry(FLOW_DOWN) && pipe->getFlowStartPosition() != FLOW_DOWN) { return FLOW_DOWN; } else if(pipe->hasFlowEntry(FLOW_LEFT) && pipe->getFlowStartPosition() != FLOW_LEFT) { return FLOW_LEFT; } return 0; } void Board::Draw () { // Draw background SDL_BlitSurface(background, 0, screen, coordinates); // Draw all board pipes for (int l = 0; l < lines; l++) { for (int c = 0; c < columns; c++) { // if != NULL we have a pipe to draw if (slots[l][c] != NULL) { SDL_Rect pos = getSlotScreenPosition(l, c); slots[l][c]->Draw(screen, &pos); } } } // Draw pool pipes SDL_Rect pos; pos.x = POOL_OFFSET_X; pos.y = POOL_OFFSET_Y; for (int p = POOL_SIZE - 1; p > 0; p--, pos.y += POOL_SPACING) { pool[p]->Draw(screen, &pos); } pos.y = POOL_TOP_Y; pool[0]->Draw(screen, &pos); } void Board::gameOver() { LOG(logINFO) << "Game over !"; game_in_progress = false; } <|endoftext|>
<commit_before>#include "Course.h" #include <string> using namespace std; Course::Course(unsigned int _startTime, unsigned int _endTime, string _days, string _courseName, string _courseLoc, unsigned int _courseId){ startTime = _startTime; endTime = _endTime; days = _days; courseName = _courseName; courseLoc = _courseLoc; courseId = _courseId; } int const Course::getEndTime(){ return endTime; } int const Course::getStartTime(){ return startTime; } string const Course::getDays(){ return days; } string const Course::getName(){ return courseName; } string const Course::getLoc(){ return ""; }<commit_msg>Course.it9 - pass: get loc<commit_after>#include "Course.h" #include <string> using namespace std; Course::Course(unsigned int _startTime, unsigned int _endTime, string _days, string _courseName, string _courseLoc, unsigned int _courseId){ startTime = _startTime; endTime = _endTime; days = _days; courseName = _courseName; courseLoc = _courseLoc; courseId = _courseId; } int const Course::getEndTime(){ return endTime; } int const Course::getStartTime(){ return startTime; } string const Course::getDays(){ return days; } string const Course::getName(){ return courseName; } string const Course::getLoc(){ return courseLoc; }<|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/dp_st_speed/dp_st_cost.h" #include <limits> #include "modules/planning/common/speed/st_point.h" namespace apollo { namespace planning { namespace { constexpr double kInf = std::numeric_limits<double>::infinity(); } DpStCost::DpStCost(const DpStSpeedConfig& config, const std::vector<const PathObstacle*>& obstacles, const common::TrajectoryPoint& init_point) : config_(config), obstacles_(obstacles), init_point_(init_point), unit_s_(config_.total_path_length() / config_.matrix_dimension_s()), unit_t_(config_.total_time() / config_.matrix_dimension_t()), unit_v_(unit_s_ / unit_t_) {} double DpStCost::GetObstacleCost(const StGraphPoint& st_graph_point) { const double s = st_graph_point.point().s(); const double t = st_graph_point.point().t(); double cost = 0.0; for (const auto* obstacle : obstacles_) { auto boundary = obstacle->st_boundary(); const double kIgnoreDistance = 200.0; if (boundary.min_s() > kIgnoreDistance) { continue; } if (t < boundary.min_t() || t > boundary.max_t()) { continue; } if (obstacle->IsBlockingObstacle() && boundary.IsPointInBoundary(STPoint(s, t))) { return kInf; } double s_upper = 0.0; double s_lower = 0.0; const auto key = boundary.id() + std::to_string(st_graph_point.index_t()); if (boundary_range_map_.find(key) == boundary_range_map_.end()) { boundary.GetBoundarySRange(t, &s_upper, &s_lower); boundary_range_map_[key] = std::make_pair(s_upper, s_lower); } else { s_upper = boundary_range_map_[key].first; s_lower = boundary_range_map_[key].second; } if (s < s_lower) { constexpr double kSafeTimeBuffer = 3.0; const double len = obstacle->obstacle()->Speed() * kSafeTimeBuffer; if (s + len < s_lower) { continue; } else { cost += config_.obstacle_weight() * config_.default_obstacle_cost() * std::pow((len - s_lower + s), 2); } } else if (s > s_upper) { const double kSafeDistance = 20.0; // or calculated from velocity if (s > s_upper + kSafeDistance) { continue; } else { cost += config_.obstacle_weight() * config_.default_obstacle_cost() * std::pow((kSafeDistance + s_upper - s), 2); } } } return cost * unit_t_; } double DpStCost::GetReferenceCost(const STPoint& point, const STPoint& reference_point) const { return config_.reference_weight() * (point.s() - reference_point.s()) * (point.s() - reference_point.s()) * unit_t_; } double DpStCost::GetSpeedCost(const STPoint& first, const STPoint& second, const double speed_limit) const { double cost = 0.0; const double speed = (second.s() - first.s()) / unit_t_; if (speed < 0) { return kInf; } double det_speed = (speed - speed_limit) / speed_limit; if (det_speed > 0) { cost = config_.exceed_speed_penalty() * config_.default_speed_cost() * fabs(speed * speed) * unit_t_; } else if (det_speed < 0) { cost = config_.low_speed_penalty() * config_.default_speed_cost() * -det_speed * unit_t_; } else { cost = 0.0; } return cost; } double DpStCost::GetAccelCost(const double accel) const { const double accel_sq = accel * accel; double max_acc = config_.max_acceleration(); double max_dec = config_.max_deceleration(); double accel_penalty = config_.accel_penalty(); double decel_penalty = config_.decel_penalty(); double cost = 0.0; if (accel > 0.0) { cost = accel_penalty * accel_sq; } else { cost = decel_penalty * accel_sq; } cost += accel_sq * decel_penalty * decel_penalty / (1 + std::exp(1.0 * (accel - max_dec))) + accel_sq * accel_penalty * accel_penalty / (1 + std::exp(-1.0 * (accel - max_acc))); return cost * unit_t_; } double DpStCost::GetAccelCostByThreePoints(const STPoint& first, const STPoint& second, const STPoint& third) const { double accel = (first.s() + third.s() - 2 * second.s()) / (unit_t_ * unit_t_); return GetAccelCost(accel); } double DpStCost::GetAccelCostByTwoPoints(const double pre_speed, const STPoint& pre_point, const STPoint& curr_point) const { double current_speed = (curr_point.s() - pre_point.s()) / unit_t_; double accel = (current_speed - pre_speed) / unit_t_; return GetAccelCost(accel); } double DpStCost::JerkCost(const double jerk) const { double jerk_sq = jerk * jerk; double cost = 0.0; if (jerk > 0) { cost = config_.positive_jerk_coeff() * jerk_sq * unit_t_; } else { cost = config_.negative_jerk_coeff() * jerk_sq * unit_t_; } return cost; } double DpStCost::GetJerkCostByFourPoints(const STPoint& first, const STPoint& second, const STPoint& third, const STPoint& fourth) const { double jerk = (fourth.s() - 3 * third.s() + 3 * second.s() - first.s()) / (unit_t_ * unit_t_ * unit_t_); return JerkCost(jerk); } double DpStCost::GetJerkCostByTwoPoints(const double pre_speed, const double pre_acc, const STPoint& pre_point, const STPoint& curr_point) const { const double curr_speed = (curr_point.s() - pre_point.s()) / unit_t_; const double curr_accel = (curr_speed - pre_speed) / unit_t_; const double jerk = (curr_accel - pre_acc) / unit_t_; return JerkCost(jerk); } double DpStCost::GetJerkCostByThreePoints(const double first_speed, const STPoint& first, const STPoint& second, const STPoint& third) const { const double pre_speed = (second.s() - first.s()) / unit_t_; const double pre_acc = (pre_speed - first_speed) / unit_t_; const double curr_speed = (third.s() - second.s()) / unit_t_; const double curr_acc = (curr_speed - pre_speed) / unit_t_; const double jerk = (curr_acc - pre_acc) / unit_t_; return JerkCost(jerk); } } // namespace planning } // namespace apollo <commit_msg>Planning: quick fix to avoid key conflict. (#2232)<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/dp_st_speed/dp_st_cost.h" #include <limits> #include "modules/planning/common/speed/st_point.h" namespace apollo { namespace planning { namespace { constexpr double kInf = std::numeric_limits<double>::infinity(); } DpStCost::DpStCost(const DpStSpeedConfig& config, const std::vector<const PathObstacle*>& obstacles, const common::TrajectoryPoint& init_point) : config_(config), obstacles_(obstacles), init_point_(init_point), unit_s_(config_.total_path_length() / config_.matrix_dimension_s()), unit_t_(config_.total_time() / config_.matrix_dimension_t()), unit_v_(unit_s_ / unit_t_) {} double DpStCost::GetObstacleCost(const StGraphPoint& st_graph_point) { const double s = st_graph_point.point().s(); const double t = st_graph_point.point().t(); double cost = 0.0; for (const auto* obstacle : obstacles_) { auto boundary = obstacle->st_boundary(); const double kIgnoreDistance = 200.0; if (boundary.min_s() > kIgnoreDistance) { continue; } if (t < boundary.min_t() || t > boundary.max_t()) { continue; } if (obstacle->IsBlockingObstacle() && boundary.IsPointInBoundary(STPoint(s, t))) { return kInf; } double s_upper = 0.0; double s_lower = 0.0; const auto key = boundary.id() + "#" + std::to_string(st_graph_point.index_t()); if (boundary_range_map_.find(key) == boundary_range_map_.end()) { boundary.GetBoundarySRange(t, &s_upper, &s_lower); boundary_range_map_[key] = std::make_pair(s_upper, s_lower); } else { s_upper = boundary_range_map_[key].first; s_lower = boundary_range_map_[key].second; } if (s < s_lower) { constexpr double kSafeTimeBuffer = 3.0; const double len = obstacle->obstacle()->Speed() * kSafeTimeBuffer; if (s + len < s_lower) { continue; } else { cost += config_.obstacle_weight() * config_.default_obstacle_cost() * std::pow((len - s_lower + s), 2); } } else if (s > s_upper) { const double kSafeDistance = 20.0; // or calculated from velocity if (s > s_upper + kSafeDistance) { continue; } else { cost += config_.obstacle_weight() * config_.default_obstacle_cost() * std::pow((kSafeDistance + s_upper - s), 2); } } } return cost * unit_t_; } double DpStCost::GetReferenceCost(const STPoint& point, const STPoint& reference_point) const { return config_.reference_weight() * (point.s() - reference_point.s()) * (point.s() - reference_point.s()) * unit_t_; } double DpStCost::GetSpeedCost(const STPoint& first, const STPoint& second, const double speed_limit) const { double cost = 0.0; const double speed = (second.s() - first.s()) / unit_t_; if (speed < 0) { return kInf; } double det_speed = (speed - speed_limit) / speed_limit; if (det_speed > 0) { cost = config_.exceed_speed_penalty() * config_.default_speed_cost() * fabs(speed * speed) * unit_t_; } else if (det_speed < 0) { cost = config_.low_speed_penalty() * config_.default_speed_cost() * -det_speed * unit_t_; } else { cost = 0.0; } return cost; } double DpStCost::GetAccelCost(const double accel) const { const double accel_sq = accel * accel; double max_acc = config_.max_acceleration(); double max_dec = config_.max_deceleration(); double accel_penalty = config_.accel_penalty(); double decel_penalty = config_.decel_penalty(); double cost = 0.0; if (accel > 0.0) { cost = accel_penalty * accel_sq; } else { cost = decel_penalty * accel_sq; } cost += accel_sq * decel_penalty * decel_penalty / (1 + std::exp(1.0 * (accel - max_dec))) + accel_sq * accel_penalty * accel_penalty / (1 + std::exp(-1.0 * (accel - max_acc))); return cost * unit_t_; } double DpStCost::GetAccelCostByThreePoints(const STPoint& first, const STPoint& second, const STPoint& third) const { double accel = (first.s() + third.s() - 2 * second.s()) / (unit_t_ * unit_t_); return GetAccelCost(accel); } double DpStCost::GetAccelCostByTwoPoints(const double pre_speed, const STPoint& pre_point, const STPoint& curr_point) const { double current_speed = (curr_point.s() - pre_point.s()) / unit_t_; double accel = (current_speed - pre_speed) / unit_t_; return GetAccelCost(accel); } double DpStCost::JerkCost(const double jerk) const { double jerk_sq = jerk * jerk; double cost = 0.0; if (jerk > 0) { cost = config_.positive_jerk_coeff() * jerk_sq * unit_t_; } else { cost = config_.negative_jerk_coeff() * jerk_sq * unit_t_; } return cost; } double DpStCost::GetJerkCostByFourPoints(const STPoint& first, const STPoint& second, const STPoint& third, const STPoint& fourth) const { double jerk = (fourth.s() - 3 * third.s() + 3 * second.s() - first.s()) / (unit_t_ * unit_t_ * unit_t_); return JerkCost(jerk); } double DpStCost::GetJerkCostByTwoPoints(const double pre_speed, const double pre_acc, const STPoint& pre_point, const STPoint& curr_point) const { const double curr_speed = (curr_point.s() - pre_point.s()) / unit_t_; const double curr_accel = (curr_speed - pre_speed) / unit_t_; const double jerk = (curr_accel - pre_acc) / unit_t_; return JerkCost(jerk); } double DpStCost::GetJerkCostByThreePoints(const double first_speed, const STPoint& first, const STPoint& second, const STPoint& third) const { const double pre_speed = (second.s() - first.s()) / unit_t_; const double pre_acc = (pre_speed - first_speed) / unit_t_; const double curr_speed = (third.s() - second.s()) / unit_t_; const double curr_acc = (curr_speed - pre_speed) / unit_t_; const double jerk = (curr_acc - pre_acc) / unit_t_; return JerkCost(jerk); } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved. */ #include "properties_binding.h" #include <Poco/StringTokenizer.h> #include <Poco/File.h> using namespace kroll; namespace ti { PropertiesBinding::PropertiesBinding(kroll::Host *host) { file_path = FileUtils::GetApplicationDirectory(); file_path += KR_PATH_SEP; file_path += "application.properties"; Poco::File file(file_path); if (!file.exists()) { file.createFile(); } config = new Poco::Util::PropertyFileConfiguration(file_path); SetMethod("getBool", &PropertiesBinding::GetBool); SetMethod("getDouble", &PropertiesBinding::GetDouble); SetMethod("getInt", &PropertiesBinding::GetInt); SetMethod("getString", &PropertiesBinding::GetString); SetMethod("getList", &PropertiesBinding::GetList); SetMethod("setBool", &PropertiesBinding::SetBool); SetMethod("setDouble", &PropertiesBinding::SetDouble); SetMethod("setInt", &PropertiesBinding::SetInt); SetMethod("setString", &PropertiesBinding::SetString); SetMethod("setList", &PropertiesBinding::SetList); SetMethod("hasProperty", &PropertiesBinding::HasProperty); SetMethod("listProperties", &PropertiesBinding::ListProperties); } PropertiesBinding::~PropertiesBinding() { config->save(file_path); } void PropertiesBinding::Getter(const ValueList& args, SharedValue result, Type type) { if (args.size() > 0 && args.at(0)->IsString()) { std::string eprefix = "PropertiesBinding::Get: "; try { std::string property = args.at(0)->ToString(); if (args.size() == 1) { switch (type) { case Bool: result->SetBool(config->getBool(property)); break; case Double: result->SetDouble(config->getDouble(property)); break; case Int: result->SetInt(config->getInt(property)); break; case String: result->SetString(config->getString(property).c_str()); break; default: break; } return; } else if (args.size() >= 2) { switch (type) { case Bool: result->SetBool(config->getBool(property, args.at(1)->ToBool())); break; case Double: result->SetDouble(config->getDouble(property, args.at(1)->ToDouble())); break; case Int: result->SetInt(config->getInt(property, args.at(1)->ToInt())); break; case String: result->SetString(config->getString(property, args.at(1)->ToString()).c_str()); break; default: break; } return; } } catch(Poco::Exception &e) { throw ValueException::FromString(eprefix + e.displayText()); } } } void PropertiesBinding::Setter(const ValueList& args, Type type) { if (args.size() >= 2 && args.at(0)->IsString()) { std::string eprefix = "PropertiesBinding::Set: "; try { std::string property = args.at(0)->ToString(); switch (type) { case Bool: config->setBool(property, args.at(1)->ToBool()); break; case Double: config->setDouble(property, args.at(1)->ToDouble()); break; case Int: config->setInt(property, args.at(1)->ToInt()); break; case String: config->setString(property, args.at(1)->ToString()); break; default: break; } config->save(file_path); } catch(Poco::Exception &e) { throw ValueException::FromString(eprefix + e.displayText()); } } } void PropertiesBinding::GetBool(const ValueList& args, SharedValue result) { Getter(args, result, Bool); } void PropertiesBinding::GetDouble(const ValueList& args, SharedValue result) { Getter(args, result, Double); } void PropertiesBinding::GetInt(const ValueList& args, SharedValue result) { Getter(args, result, Int); } void PropertiesBinding::GetString(const ValueList& args, SharedValue result) { Getter(args, result, String); } void PropertiesBinding::GetList(const ValueList& args, SharedValue result) { SharedValue stringValue = Value::Null; GetString(args, stringValue); if (!stringValue->IsNull()) { SharedPtr<StaticBoundList> list = new StaticBoundList(); std::string string = stringValue->ToString(); Poco::StringTokenizer t(string, ",", Poco::StringTokenizer::TOK_TRIM); for (size_t i = 0; i < t.count(); i++) { SharedValue token = Value::NewString(t[i].c_str()); list->Append(token); } SharedBoundList list2 = list; result->SetList(list2); } } void PropertiesBinding::SetBool(const ValueList& args, SharedValue result) { Setter(args, Bool); } void PropertiesBinding::SetDouble(const ValueList& args, SharedValue result) { Setter(args, Double); } void PropertiesBinding::SetInt(const ValueList& args, SharedValue result) { Setter(args, Int); } void PropertiesBinding::SetString(const ValueList& args, SharedValue result) { Setter(args, String); } void PropertiesBinding::SetList(const ValueList& args, SharedValue result) { if (args.size() >= 2 && args.at(0)->IsString() && args.at(1)->IsList()) { std::string property = args.at(0)->ToString(); SharedBoundList list = args.at(1)->ToList(); std::string value; for (size_t i = 0; i < list->Size(); i++) { value += list->At(i)->ToString(); if (i < list->Size() - 1) { value += ","; } } config->setString(property, value); config->save(file_path); } } void PropertiesBinding::HasProperty(const ValueList& args, SharedValue result) { result->SetBool(false); if (args.size() >= 1 && args.at(0)->IsString()) { std::string property = args.at(0)->ToString(); result->SetBool(config->hasProperty(property)); } } void PropertiesBinding::ListProperties(const ValueList& args, SharedValue result) { std::vector<std::string> keys; config->keys(keys); SharedPtr<StaticBoundList> property_list = new StaticBoundList(); for (int i = 0; i < keys.size(); i++) { std::string property_name = keys.at(i); SharedValue name_value = Value::NewString(property_name.c_str()); property_list->Append(name_value); } result->SetList(property_list); } } <commit_msg>another quick fix for linux .. -Wall is annoying..<commit_after>/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved. */ #include "properties_binding.h" #include <Poco/StringTokenizer.h> #include <Poco/File.h> using namespace kroll; namespace ti { PropertiesBinding::PropertiesBinding(kroll::Host *host) { file_path = FileUtils::GetApplicationDirectory(); file_path += KR_PATH_SEP; file_path += "application.properties"; Poco::File file(file_path); if (!file.exists()) { file.createFile(); } config = new Poco::Util::PropertyFileConfiguration(file_path); SetMethod("getBool", &PropertiesBinding::GetBool); SetMethod("getDouble", &PropertiesBinding::GetDouble); SetMethod("getInt", &PropertiesBinding::GetInt); SetMethod("getString", &PropertiesBinding::GetString); SetMethod("getList", &PropertiesBinding::GetList); SetMethod("setBool", &PropertiesBinding::SetBool); SetMethod("setDouble", &PropertiesBinding::SetDouble); SetMethod("setInt", &PropertiesBinding::SetInt); SetMethod("setString", &PropertiesBinding::SetString); SetMethod("setList", &PropertiesBinding::SetList); SetMethod("hasProperty", &PropertiesBinding::HasProperty); SetMethod("listProperties", &PropertiesBinding::ListProperties); } PropertiesBinding::~PropertiesBinding() { config->save(file_path); } void PropertiesBinding::Getter(const ValueList& args, SharedValue result, Type type) { if (args.size() > 0 && args.at(0)->IsString()) { std::string eprefix = "PropertiesBinding::Get: "; try { std::string property = args.at(0)->ToString(); if (args.size() == 1) { switch (type) { case Bool: result->SetBool(config->getBool(property)); break; case Double: result->SetDouble(config->getDouble(property)); break; case Int: result->SetInt(config->getInt(property)); break; case String: result->SetString(config->getString(property).c_str()); break; default: break; } return; } else if (args.size() >= 2) { switch (type) { case Bool: result->SetBool(config->getBool(property, args.at(1)->ToBool())); break; case Double: result->SetDouble(config->getDouble(property, args.at(1)->ToDouble())); break; case Int: result->SetInt(config->getInt(property, args.at(1)->ToInt())); break; case String: result->SetString(config->getString(property, args.at(1)->ToString()).c_str()); break; default: break; } return; } } catch(Poco::Exception &e) { throw ValueException::FromString(eprefix + e.displayText()); } } } void PropertiesBinding::Setter(const ValueList& args, Type type) { if (args.size() >= 2 && args.at(0)->IsString()) { std::string eprefix = "PropertiesBinding::Set: "; try { std::string property = args.at(0)->ToString(); switch (type) { case Bool: config->setBool(property, args.at(1)->ToBool()); break; case Double: config->setDouble(property, args.at(1)->ToDouble()); break; case Int: config->setInt(property, args.at(1)->ToInt()); break; case String: config->setString(property, args.at(1)->ToString()); break; default: break; } config->save(file_path); } catch(Poco::Exception &e) { throw ValueException::FromString(eprefix + e.displayText()); } } } void PropertiesBinding::GetBool(const ValueList& args, SharedValue result) { Getter(args, result, Bool); } void PropertiesBinding::GetDouble(const ValueList& args, SharedValue result) { Getter(args, result, Double); } void PropertiesBinding::GetInt(const ValueList& args, SharedValue result) { Getter(args, result, Int); } void PropertiesBinding::GetString(const ValueList& args, SharedValue result) { Getter(args, result, String); } void PropertiesBinding::GetList(const ValueList& args, SharedValue result) { SharedValue stringValue = Value::Null; GetString(args, stringValue); if (!stringValue->IsNull()) { SharedPtr<StaticBoundList> list = new StaticBoundList(); std::string string = stringValue->ToString(); Poco::StringTokenizer t(string, ",", Poco::StringTokenizer::TOK_TRIM); for (size_t i = 0; i < t.count(); i++) { SharedValue token = Value::NewString(t[i].c_str()); list->Append(token); } SharedBoundList list2 = list; result->SetList(list2); } } void PropertiesBinding::SetBool(const ValueList& args, SharedValue result) { Setter(args, Bool); } void PropertiesBinding::SetDouble(const ValueList& args, SharedValue result) { Setter(args, Double); } void PropertiesBinding::SetInt(const ValueList& args, SharedValue result) { Setter(args, Int); } void PropertiesBinding::SetString(const ValueList& args, SharedValue result) { Setter(args, String); } void PropertiesBinding::SetList(const ValueList& args, SharedValue result) { if (args.size() >= 2 && args.at(0)->IsString() && args.at(1)->IsList()) { std::string property = args.at(0)->ToString(); SharedBoundList list = args.at(1)->ToList(); std::string value; for (int i = 0; i < list->Size(); i++) { value += list->At(i)->ToString(); if (i < list->Size() - 1) { value += ","; } } config->setString(property, value); config->save(file_path); } } void PropertiesBinding::HasProperty(const ValueList& args, SharedValue result) { result->SetBool(false); if (args.size() >= 1 && args.at(0)->IsString()) { std::string property = args.at(0)->ToString(); result->SetBool(config->hasProperty(property)); } } void PropertiesBinding::ListProperties(const ValueList& args, SharedValue result) { std::vector<std::string> keys; config->keys(keys); SharedPtr<StaticBoundList> property_list = new StaticBoundList(); for (size_t i = 0; i < keys.size(); i++) { std::string property_name = keys.at(i); SharedValue name_value = Value::NewString(property_name.c_str()); property_list->Append(name_value); } result->SetList(property_list); } } <|endoftext|>
<commit_before>//===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Owen Anderson and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a trivial dead store elimination that only considers // basic-block local redundant stores. // // FIXME: This should eventually be extended to be a post-dominator tree // traversal. Doing so would be pretty trivial. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "fdse" #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Pass.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/MemoryDependenceAnalysis.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Support/Compiler.h" using namespace llvm; STATISTIC(NumFastStores, "Number of stores deleted"); STATISTIC(NumFastOther , "Number of other instrs removed"); namespace { struct VISIBILITY_HIDDEN FDSE : public FunctionPass { static char ID; // Pass identification, replacement for typeid FDSE() : FunctionPass((intptr_t)&ID) {} virtual bool runOnFunction(Function &F) { bool Changed = false; for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) Changed |= runOnBasicBlock(*I); return Changed; } bool runOnBasicBlock(BasicBlock &BB); void DeleteDeadInstructionChains(Instruction *I, SetVector<Instruction*> &DeadInsts); // getAnalysisUsage - We require post dominance frontiers (aka Control // Dependence Graph) virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequired<MemoryDependenceAnalysis>(); AU.addPreserved<MemoryDependenceAnalysis>(); } }; char FDSE::ID = 0; RegisterPass<FDSE> X("fdse", "Fast Dead Store Elimination"); } FunctionPass *llvm::createFastDeadStoreEliminationPass() { return new FDSE(); } bool FDSE::runOnBasicBlock(BasicBlock &BB) { MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>(); // Record the last-seen store to this pointer DenseMap<Value*, StoreInst*> lastStore; // Record instructions possibly made dead by deleting a store SetVector<Instruction*> possiblyDead; bool MadeChange = false; // Do a top-down walk on the BB for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ++BBI) { // If we find a store or a free... if (isa<StoreInst>(BBI) || isa<FreeInst>(BBI)) { Value* pointer = 0; if (StoreInst* S = dyn_cast<StoreInst>(BBI)) pointer = S->getPointerOperand(); else if (FreeInst* F = dyn_cast<FreeInst>(BBI)) pointer = F->getPointerOperand(); assert(pointer && "Not a free or a store?"); StoreInst*& last = lastStore[pointer]; // ... to a pointer that has been stored to before... if (last) { // ... and no other memory dependencies are between them.... if (MD.getDependency(BBI) == last) { // Remove it! MD.removeInstruction(last); // DCE instructions only used to calculate that store if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0))) possiblyDead.insert(D); last->eraseFromParent(); NumFastStores++; MadeChange = true; } } // Update our most-recent-store map if (StoreInst* S = dyn_cast<StoreInst>(BBI)) last = S; else last = 0; } } // If this block ends in a return, unwind, unreachable, and eventually // tailcall, then all allocas are dead at its end. if (BB.getTerminator()->getNumSuccessors() == 0) { // Pointers alloca'd in this function are dead in the end block SmallPtrSet<AllocaInst*, 4> deadPointers; // Find all of the alloca'd pointers in the entry block BasicBlock *Entry = BB.getParent()->begin(); for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) deadPointers.insert(AI); // Scan the basic block backwards for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){ --BBI; if (deadPointers.empty()) break; // If we find a store whose pointer is dead... if (StoreInst* S = dyn_cast<StoreInst>(BBI)) { if (deadPointers.count(S->getPointerOperand())){ // Remove it! MD.removeInstruction(S); // DCE instructions only used to calculate that store if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0))) possiblyDead.insert(D); BBI++; S->eraseFromParent(); NumFastStores++; MadeChange = true; } // If we encounter a use of the pointer, it is no longer considered dead } else if (LoadInst* L = dyn_cast<LoadInst>(BBI)) { deadPointers.erase(L->getPointerOperand()); } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) { deadPointers.erase(V->getOperand(0)); } } } // Do a trivial DCE while (!possiblyDead.empty()) { Instruction *I = possiblyDead.back(); possiblyDead.pop_back(); DeleteDeadInstructionChains(I, possiblyDead); } return MadeChange; } void FDSE::DeleteDeadInstructionChains(Instruction *I, SetVector<Instruction*> &DeadInsts) { // Instruction must be dead. if (!I->use_empty() || !isInstructionTriviallyDead(I)) return; // Let the memory dependence know getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I); // See if this made any operands dead. We do it this way in case the // instruction uses the same operand twice. We don't want to delete a // value then reference it. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { if (I->getOperand(i)->hasOneUse()) if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i))) DeadInsts.insert(Op); // Attempt to nuke it later. I->setOperand(i, 0); // Drop from the operand list. } I->eraseFromParent(); ++NumFastOther; } <commit_msg>Handle the case where an entire structure is freed, and its dependency is a store to a field within that structure.<commit_after>//===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Owen Anderson and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a trivial dead store elimination that only considers // basic-block local redundant stores. // // FIXME: This should eventually be extended to be a post-dominator tree // traversal. Doing so would be pretty trivial. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "fdse" #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Pass.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/MemoryDependenceAnalysis.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Support/Compiler.h" using namespace llvm; STATISTIC(NumFastStores, "Number of stores deleted"); STATISTIC(NumFastOther , "Number of other instrs removed"); namespace { struct VISIBILITY_HIDDEN FDSE : public FunctionPass { static char ID; // Pass identification, replacement for typeid FDSE() : FunctionPass((intptr_t)&ID) {} virtual bool runOnFunction(Function &F) { bool Changed = false; for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) Changed |= runOnBasicBlock(*I); return Changed; } bool runOnBasicBlock(BasicBlock &BB); bool handleFreeWithNonTrivialDependency(FreeInst* F, StoreInst* dependency, SetVector<Instruction*>& possiblyDead); bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead); void DeleteDeadInstructionChains(Instruction *I, SetVector<Instruction*> &DeadInsts); // getAnalysisUsage - We require post dominance frontiers (aka Control // Dependence Graph) virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequired<TargetData>(); AU.addRequired<AliasAnalysis>(); AU.addRequired<MemoryDependenceAnalysis>(); AU.addPreserved<AliasAnalysis>(); AU.addPreserved<MemoryDependenceAnalysis>(); } }; char FDSE::ID = 0; RegisterPass<FDSE> X("fdse", "Fast Dead Store Elimination"); } FunctionPass *llvm::createFastDeadStoreEliminationPass() { return new FDSE(); } bool FDSE::runOnBasicBlock(BasicBlock &BB) { AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>(); // Record the last-seen store to this pointer DenseMap<Value*, StoreInst*> lastStore; // Record instructions possibly made dead by deleting a store SetVector<Instruction*> possiblyDead; bool MadeChange = false; // Do a top-down walk on the BB for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ++BBI) { // If we find a store or a free... if (isa<StoreInst>(BBI) || isa<FreeInst>(BBI)) { Value* pointer = 0; if (StoreInst* S = dyn_cast<StoreInst>(BBI)) pointer = S->getPointerOperand(); else if (FreeInst* F = dyn_cast<FreeInst>(BBI)) pointer = F->getPointerOperand(); assert(pointer && "Not a free or a store?"); StoreInst*& last = lastStore[pointer]; // ... to a pointer that has been stored to before... if (last) { // ... and no other memory dependencies are between them.... if (MD.getDependency(BBI) == last) { // Remove it! MD.removeInstruction(last); AA.deleteValue(last); // DCE instructions only used to calculate that store if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0))) possiblyDead.insert(D); last->eraseFromParent(); NumFastStores++; MadeChange = true; // If this is a free, check for a non-trivial dependency } else if (FreeInst* F = dyn_cast<FreeInst>(BBI)) MadeChange |= handleFreeWithNonTrivialDependency(F, last, possiblyDead); } // Update our most-recent-store map if (StoreInst* S = dyn_cast<StoreInst>(BBI)) last = S; else last = 0; } } // If this block ends in a return, unwind, unreachable, and eventually // tailcall, then all allocas are dead at its end. if (BB.getTerminator()->getNumSuccessors() == 0) MadeChange |= handleEndBlock(BB, possiblyDead); // Do a trivial DCE while (!possiblyDead.empty()) { Instruction *I = possiblyDead.back(); possiblyDead.pop_back(); DeleteDeadInstructionChains(I, possiblyDead); } return MadeChange; } /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose /// dependency is a store to a field of that structure bool FDSE::handleFreeWithNonTrivialDependency(FreeInst* F, StoreInst* dependency, SetVector<Instruction*>& possiblyDead) { TargetData &TD = getAnalysis<TargetData>(); AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>(); Value* depPointer = dependency->getPointerOperand(); unsigned depPointerSize = TD.getTypeSize(dependency->getOperand(0)->getType()); // Check for aliasing AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL, depPointer, depPointerSize); if (A == AliasAnalysis::MustAlias) { // Remove it! MD.removeInstruction(dependency); AA.deleteValue(dependency); // DCE instructions only used to calculate that store if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0))) possiblyDead.insert(D); dependency->eraseFromParent(); NumFastStores++; return true; } return false; } /// handleEndBlock - Remove dead stores to stack-allocated locations in the function /// end block bool FDSE::handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead) { AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>(); bool MadeChange = false; // Pointers alloca'd in this function are dead in the end block SmallPtrSet<AllocaInst*, 4> deadPointers; // Find all of the alloca'd pointers in the entry block BasicBlock *Entry = BB.getParent()->begin(); for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I) if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) deadPointers.insert(AI); // Scan the basic block backwards for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){ --BBI; if (deadPointers.empty()) break; // If we find a store whose pointer is dead... if (StoreInst* S = dyn_cast<StoreInst>(BBI)) { if (deadPointers.count(S->getPointerOperand())){ // Remove it! MD.removeInstruction(S); AA.deleteValue(S); // DCE instructions only used to calculate that store if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0))) possiblyDead.insert(D); BBI++; S->eraseFromParent(); NumFastStores++; MadeChange = true; } // If we encounter a use of the pointer, it is no longer considered dead } else if (LoadInst* L = dyn_cast<LoadInst>(BBI)) { deadPointers.erase(L->getPointerOperand()); } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) { deadPointers.erase(V->getOperand(0)); } } return MadeChange; } void FDSE::DeleteDeadInstructionChains(Instruction *I, SetVector<Instruction*> &DeadInsts) { // Instruction must be dead. if (!I->use_empty() || !isInstructionTriviallyDead(I)) return; // Let the memory dependence know getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I); getAnalysis<AliasAnalysis>().deleteValue(I); // See if this made any operands dead. We do it this way in case the // instruction uses the same operand twice. We don't want to delete a // value then reference it. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { if (I->getOperand(i)->hasOneUse()) if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i))) DeadInsts.insert(Op); // Attempt to nuke it later. I->setOperand(i, 0); // Drop from the operand list. } I->eraseFromParent(); ++NumFastOther; } <|endoftext|>
<commit_before>//===-- LowerGC.cpp - Provide GC support for targets that don't -----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements lowering for the llvm.gc* intrinsics for targets that do // not natively support them (which includes the C backend). Note that the code // generated is not as efficient as it would be for targets that natively // support the GC intrinsics, but it is useful for getting new targets // up-and-running quickly. // // This pass implements the code transformation described in this paper: // "Accurate Garbage Collection in an Uncooperative Environment" // Fergus Hendersen, ISMM, 2002 // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "lowergc" #include "llvm/Transforms/Scalar.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Transforms/Utils/Cloning.h" using namespace llvm; namespace { class LowerGC : public FunctionPass { /// GCRootInt, GCReadInt, GCWriteInt - The function prototypes for the /// llvm.gcread/llvm.gcwrite/llvm.gcroot intrinsics. Function *GCRootInt, *GCReadInt, *GCWriteInt; /// GCRead/GCWrite - These are the functions provided by the garbage /// collector for read/write barriers. Function *GCRead, *GCWrite; /// RootChain - This is the global linked-list that contains the chain of GC /// roots. GlobalVariable *RootChain; /// MainRootRecordType - This is the type for a function root entry if it /// had zero roots. const Type *MainRootRecordType; public: LowerGC() : GCRootInt(0), GCReadInt(0), GCWriteInt(0), GCRead(0), GCWrite(0), RootChain(0), MainRootRecordType(0) {} virtual bool doInitialization(Module &M); virtual bool runOnFunction(Function &F); private: const StructType *getRootRecordType(unsigned NumRoots); }; RegisterOpt<LowerGC> X("lowergc", "Lower GC intrinsics, for GCless code generators"); } /// createLowerGCPass - This function returns an instance of the "lowergc" /// pass, which lowers garbage collection intrinsics to normal LLVM code. FunctionPass *llvm::createLowerGCPass() { return new LowerGC(); } /// getRootRecordType - This function creates and returns the type for a root /// record containing 'NumRoots' roots. const StructType *LowerGC::getRootRecordType(unsigned NumRoots) { // Build a struct that is a type used for meta-data/root pairs. std::vector<const Type *> ST; ST.push_back(GCRootInt->getFunctionType()->getParamType(0)); ST.push_back(GCRootInt->getFunctionType()->getParamType(1)); StructType *PairTy = StructType::get(ST); // Build the array of pairs. ArrayType *PairArrTy = ArrayType::get(PairTy, NumRoots); // Now build the recursive list type. PATypeHolder RootListH = MainRootRecordType ? (Type*)MainRootRecordType : (Type*)OpaqueType::get(); ST.clear(); ST.push_back(PointerType::get(RootListH)); // Prev pointer ST.push_back(Type::UIntTy); // NumElements in array ST.push_back(PairArrTy); // The pairs StructType *RootList = StructType::get(ST); if (MainRootRecordType) return RootList; assert(NumRoots == 0 && "The main struct type should have zero entries!"); cast<OpaqueType>((Type*)RootListH.get())->refineAbstractTypeTo(RootList); MainRootRecordType = RootListH; return cast<StructType>(RootListH.get()); } /// doInitialization - If this module uses the GC intrinsics, find them now. If /// not, this pass does not do anything. bool LowerGC::doInitialization(Module &M) { GCRootInt = M.getNamedFunction("llvm.gcroot"); GCReadInt = M.getNamedFunction("llvm.gcread"); GCWriteInt = M.getNamedFunction("llvm.gcwrite"); if (!GCRootInt && !GCReadInt && !GCWriteInt) return false; PointerType *VoidPtr = PointerType::get(Type::SByteTy); PointerType *VoidPtrPtr = PointerType::get(VoidPtr); // If the program is using read/write barriers, find the implementations of // them from the GC runtime library. if (GCReadInt) // Make: sbyte* %llvm_gc_read(sbyte**) GCRead = M.getOrInsertFunction("llvm_gc_read", VoidPtr, VoidPtrPtr, 0); if (GCWriteInt) // Make: void %llvm_gc_write(sbyte*, sbyte**) GCWrite = M.getOrInsertFunction("llvm_gc_write", Type::VoidTy, VoidPtr, VoidPtrPtr, 0); // If the program has GC roots, get or create the global root list. if (GCRootInt) { const StructType *RootListTy = getRootRecordType(0); const Type *PRLTy = PointerType::get(RootListTy); M.addTypeName("llvm_gc_root_ty", RootListTy); // Get the root chain if it already exists. RootChain = M.getGlobalVariable("llvm_gc_root_chain", PRLTy); if (RootChain == 0) { // If the root chain does not exist, insert a new one with linkonce // linkage! RootChain = new GlobalVariable(PRLTy, false, GlobalValue::LinkOnceLinkage, Constant::getNullValue(RootListTy), "llvm_gc_root_chain", &M); } else if (RootChain->hasExternalLinkage() && RootChain->isExternal()) { RootChain->setInitializer(Constant::getNullValue(PRLTy)); RootChain->setLinkage(GlobalValue::LinkOnceLinkage); } } return true; } /// Coerce - If the specified operand number of the specified instruction does /// not have the specified type, insert a cast. static void Coerce(Instruction *I, unsigned OpNum, Type *Ty) { if (I->getOperand(OpNum)->getType() != Ty) { if (Constant *C = dyn_cast<Constant>(I->getOperand(OpNum))) I->setOperand(OpNum, ConstantExpr::getCast(C, Ty)); else { CastInst *C = new CastInst(I->getOperand(OpNum), Ty, "", I); I->setOperand(OpNum, C); } } } /// runOnFunction - If the program is using GC intrinsics, replace any /// read/write intrinsics with the appropriate read/write barrier calls, then /// inline them. Finally, build the data structures for bool LowerGC::runOnFunction(Function &F) { // Quick exit for programs that are not using GC mechanisms. if (!GCRootInt && !GCReadInt && !GCWriteInt) return false; PointerType *VoidPtr = PointerType::get(Type::SByteTy); PointerType *VoidPtrPtr = PointerType::get(VoidPtr); // If there are read/write barriers in the program, perform a quick pass over // the function eliminating them. While we are at it, remember where we see // calls to llvm.gcroot. std::vector<CallInst*> GCRoots; std::vector<CallInst*> NormalCalls; bool MadeChange = false; for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) if (CallInst *CI = dyn_cast<CallInst>(II++)) { if (!CI->getCalledFunction() || !CI->getCalledFunction()->getIntrinsicID()) NormalCalls.push_back(CI); // Remember all normal function calls. if (Function *F = CI->getCalledFunction()) if (F == GCRootInt) GCRoots.push_back(CI); else if (F == GCReadInt || F == GCWriteInt) { if (F == GCWriteInt) { // Change a llvm.gcwrite call to call llvm_gc_write instead. CI->setOperand(0, GCWrite); // Insert casts of the operands as needed. Coerce(CI, 1, VoidPtr); Coerce(CI, 2, VoidPtrPtr); } else { Coerce(CI, 1, VoidPtrPtr); if (CI->getType() == VoidPtr) { CI->setOperand(0, GCRead); } else { // Create a whole new call to replace the old one. CallInst *NC = new CallInst(GCRead, CI->getOperand(1), CI->getName(), CI); Value *NV = new CastInst(NC, CI->getType(), "", CI); CI->replaceAllUsesWith(NV); BB->getInstList().erase(CI); CI = NC; } } // Now that we made the replacement, inline expand the call if // possible, otherwise things will be too horribly expensive. InlineFunction(CI); MadeChange = true; } } // If there are no GC roots in this function, then there is no need to create // a GC list record for it. if (GCRoots.empty()) return MadeChange; // Okay, there are GC roots in this function. On entry to the function, add a // record to the llvm_gc_root_chain, and remove it on exit. // Create the alloca, and zero it out. const StructType *RootListTy = getRootRecordType(GCRoots.size()); AllocaInst *AI = new AllocaInst(RootListTy, 0, "gcroots", F.begin()->begin()); // Insert the memset call after all of the allocas in the function. BasicBlock::iterator IP = AI; while (isa<AllocaInst>(IP)) ++IP; Constant *Zero = ConstantUInt::get(Type::UIntTy, 0); Constant *One = ConstantUInt::get(Type::UIntTy, 1); // Get a pointer to the prev pointer. std::vector<Value*> Par; Par.push_back(Zero); Par.push_back(Zero); Value *PrevPtrPtr = new GetElementPtrInst(AI, Par, "prevptrptr", IP); // Load the previous pointer. Value *PrevPtr = new LoadInst(RootChain, "prevptr", IP); // Store the previous pointer into the prevptrptr new StoreInst(PrevPtr, PrevPtrPtr, IP); // Set the number of elements in this record. Par[1] = ConstantUInt::get(Type::UIntTy, 1); Value *NumEltsPtr = new GetElementPtrInst(AI, Par, "numeltsptr", IP); new StoreInst(ConstantUInt::get(Type::UIntTy, GCRoots.size()), NumEltsPtr,IP); Par[1] = ConstantUInt::get(Type::UIntTy, 2); Par.resize(4); const PointerType *PtrLocTy = cast<PointerType>(GCRootInt->getFunctionType()->getParamType(0)); Constant *Null = ConstantPointerNull::get(PtrLocTy); // Initialize all of the gcroot records now, and eliminate them as we go. for (unsigned i = 0, e = GCRoots.size(); i != e; ++i) { // Initialize the meta-data pointer. Par[2] = ConstantUInt::get(Type::UIntTy, i); Par[3] = One; Value *MetaDataPtr = new GetElementPtrInst(AI, Par, "MetaDataPtr", IP); assert(isa<Constant>(GCRoots[i]->getOperand(2)) || isa<GlobalValue>(GCRoots[i]->getOperand(2))); new StoreInst(GCRoots[i]->getOperand(2), MetaDataPtr, IP); // Initialize the root pointer to null on entry to the function. Par[3] = Zero; Value *RootPtrPtr = new GetElementPtrInst(AI, Par, "RootEntPtr", IP); new StoreInst(Null, RootPtrPtr, IP); // Each occurrance of the llvm.gcroot intrinsic now turns into an // initialization of the slot with the address and a zeroing out of the // address specified. new StoreInst(Constant::getNullValue(PtrLocTy->getElementType()), GCRoots[i]->getOperand(1), GCRoots[i]); new StoreInst(GCRoots[i]->getOperand(1), RootPtrPtr, GCRoots[i]); GCRoots[i]->getParent()->getInstList().erase(GCRoots[i]); } // Now that the record is all initialized, store the pointer into the global // pointer. Value *C = new CastInst(AI, PointerType::get(MainRootRecordType), "", IP); new StoreInst(C, RootChain, IP); // On exit from the function we have to remove the entry from the GC root // chain. Doing this is straight-forward for return and unwind instructions: // just insert the appropriate copy. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) if (isa<UnwindInst>(BB->getTerminator()) || isa<ReturnInst>(BB->getTerminator())) { // We could reuse the PrevPtr loaded on entry to the function, but this // would make the value live for the whole function, which is probably a // bad idea. Just reload the value out of our stack entry. PrevPtr = new LoadInst(PrevPtrPtr, "prevptr", BB->getTerminator()); new StoreInst(PrevPtr, RootChain, BB->getTerminator()); } // If an exception is thrown from a callee we have to make sure to // unconditionally take the record off the stack. For this reason, we turn // all call instructions into invoke whose cleanup pops the entry off the // stack. We only insert one cleanup block, which is shared by all invokes. if (!NormalCalls.empty()) { // Create the shared cleanup block. BasicBlock *Cleanup = new BasicBlock("gc_cleanup", &F); UnwindInst *UI = new UnwindInst(Cleanup); PrevPtr = new LoadInst(PrevPtrPtr, "prevptr", UI); new StoreInst(PrevPtr, RootChain, UI); // Loop over all of the function calls, turning them into invokes. while (!NormalCalls.empty()) { CallInst *CI = NormalCalls.back(); BasicBlock *CBB = CI->getParent(); NormalCalls.pop_back(); // Split the basic block containing the function call. BasicBlock *NewBB = CBB->splitBasicBlock(CI, CBB->getName()+".cont"); // Remove the unconditional branch inserted at the end of the CBB. CBB->getInstList().pop_back(); NewBB->getInstList().remove(CI); // Create a new invoke instruction. Value *II = new InvokeInst(CI->getCalledValue(), NewBB, Cleanup, std::vector<Value*>(CI->op_begin()+1, CI->op_end()), CI->getName(), CBB); CI->replaceAllUsesWith(II); delete CI; } } return true; } <commit_msg>Spelling people's names right is kinda important<commit_after>//===-- LowerGC.cpp - Provide GC support for targets that don't -----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements lowering for the llvm.gc* intrinsics for targets that do // not natively support them (which includes the C backend). Note that the code // generated is not as efficient as it would be for targets that natively // support the GC intrinsics, but it is useful for getting new targets // up-and-running quickly. // // This pass implements the code transformation described in this paper: // "Accurate Garbage Collection in an Uncooperative Environment" // Fergus Henderson, ISMM, 2002 // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "lowergc" #include "llvm/Transforms/Scalar.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Transforms/Utils/Cloning.h" using namespace llvm; namespace { class LowerGC : public FunctionPass { /// GCRootInt, GCReadInt, GCWriteInt - The function prototypes for the /// llvm.gcread/llvm.gcwrite/llvm.gcroot intrinsics. Function *GCRootInt, *GCReadInt, *GCWriteInt; /// GCRead/GCWrite - These are the functions provided by the garbage /// collector for read/write barriers. Function *GCRead, *GCWrite; /// RootChain - This is the global linked-list that contains the chain of GC /// roots. GlobalVariable *RootChain; /// MainRootRecordType - This is the type for a function root entry if it /// had zero roots. const Type *MainRootRecordType; public: LowerGC() : GCRootInt(0), GCReadInt(0), GCWriteInt(0), GCRead(0), GCWrite(0), RootChain(0), MainRootRecordType(0) {} virtual bool doInitialization(Module &M); virtual bool runOnFunction(Function &F); private: const StructType *getRootRecordType(unsigned NumRoots); }; RegisterOpt<LowerGC> X("lowergc", "Lower GC intrinsics, for GCless code generators"); } /// createLowerGCPass - This function returns an instance of the "lowergc" /// pass, which lowers garbage collection intrinsics to normal LLVM code. FunctionPass *llvm::createLowerGCPass() { return new LowerGC(); } /// getRootRecordType - This function creates and returns the type for a root /// record containing 'NumRoots' roots. const StructType *LowerGC::getRootRecordType(unsigned NumRoots) { // Build a struct that is a type used for meta-data/root pairs. std::vector<const Type *> ST; ST.push_back(GCRootInt->getFunctionType()->getParamType(0)); ST.push_back(GCRootInt->getFunctionType()->getParamType(1)); StructType *PairTy = StructType::get(ST); // Build the array of pairs. ArrayType *PairArrTy = ArrayType::get(PairTy, NumRoots); // Now build the recursive list type. PATypeHolder RootListH = MainRootRecordType ? (Type*)MainRootRecordType : (Type*)OpaqueType::get(); ST.clear(); ST.push_back(PointerType::get(RootListH)); // Prev pointer ST.push_back(Type::UIntTy); // NumElements in array ST.push_back(PairArrTy); // The pairs StructType *RootList = StructType::get(ST); if (MainRootRecordType) return RootList; assert(NumRoots == 0 && "The main struct type should have zero entries!"); cast<OpaqueType>((Type*)RootListH.get())->refineAbstractTypeTo(RootList); MainRootRecordType = RootListH; return cast<StructType>(RootListH.get()); } /// doInitialization - If this module uses the GC intrinsics, find them now. If /// not, this pass does not do anything. bool LowerGC::doInitialization(Module &M) { GCRootInt = M.getNamedFunction("llvm.gcroot"); GCReadInt = M.getNamedFunction("llvm.gcread"); GCWriteInt = M.getNamedFunction("llvm.gcwrite"); if (!GCRootInt && !GCReadInt && !GCWriteInt) return false; PointerType *VoidPtr = PointerType::get(Type::SByteTy); PointerType *VoidPtrPtr = PointerType::get(VoidPtr); // If the program is using read/write barriers, find the implementations of // them from the GC runtime library. if (GCReadInt) // Make: sbyte* %llvm_gc_read(sbyte**) GCRead = M.getOrInsertFunction("llvm_gc_read", VoidPtr, VoidPtrPtr, 0); if (GCWriteInt) // Make: void %llvm_gc_write(sbyte*, sbyte**) GCWrite = M.getOrInsertFunction("llvm_gc_write", Type::VoidTy, VoidPtr, VoidPtrPtr, 0); // If the program has GC roots, get or create the global root list. if (GCRootInt) { const StructType *RootListTy = getRootRecordType(0); const Type *PRLTy = PointerType::get(RootListTy); M.addTypeName("llvm_gc_root_ty", RootListTy); // Get the root chain if it already exists. RootChain = M.getGlobalVariable("llvm_gc_root_chain", PRLTy); if (RootChain == 0) { // If the root chain does not exist, insert a new one with linkonce // linkage! RootChain = new GlobalVariable(PRLTy, false, GlobalValue::LinkOnceLinkage, Constant::getNullValue(RootListTy), "llvm_gc_root_chain", &M); } else if (RootChain->hasExternalLinkage() && RootChain->isExternal()) { RootChain->setInitializer(Constant::getNullValue(PRLTy)); RootChain->setLinkage(GlobalValue::LinkOnceLinkage); } } return true; } /// Coerce - If the specified operand number of the specified instruction does /// not have the specified type, insert a cast. static void Coerce(Instruction *I, unsigned OpNum, Type *Ty) { if (I->getOperand(OpNum)->getType() != Ty) { if (Constant *C = dyn_cast<Constant>(I->getOperand(OpNum))) I->setOperand(OpNum, ConstantExpr::getCast(C, Ty)); else { CastInst *C = new CastInst(I->getOperand(OpNum), Ty, "", I); I->setOperand(OpNum, C); } } } /// runOnFunction - If the program is using GC intrinsics, replace any /// read/write intrinsics with the appropriate read/write barrier calls, then /// inline them. Finally, build the data structures for bool LowerGC::runOnFunction(Function &F) { // Quick exit for programs that are not using GC mechanisms. if (!GCRootInt && !GCReadInt && !GCWriteInt) return false; PointerType *VoidPtr = PointerType::get(Type::SByteTy); PointerType *VoidPtrPtr = PointerType::get(VoidPtr); // If there are read/write barriers in the program, perform a quick pass over // the function eliminating them. While we are at it, remember where we see // calls to llvm.gcroot. std::vector<CallInst*> GCRoots; std::vector<CallInst*> NormalCalls; bool MadeChange = false; for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) if (CallInst *CI = dyn_cast<CallInst>(II++)) { if (!CI->getCalledFunction() || !CI->getCalledFunction()->getIntrinsicID()) NormalCalls.push_back(CI); // Remember all normal function calls. if (Function *F = CI->getCalledFunction()) if (F == GCRootInt) GCRoots.push_back(CI); else if (F == GCReadInt || F == GCWriteInt) { if (F == GCWriteInt) { // Change a llvm.gcwrite call to call llvm_gc_write instead. CI->setOperand(0, GCWrite); // Insert casts of the operands as needed. Coerce(CI, 1, VoidPtr); Coerce(CI, 2, VoidPtrPtr); } else { Coerce(CI, 1, VoidPtrPtr); if (CI->getType() == VoidPtr) { CI->setOperand(0, GCRead); } else { // Create a whole new call to replace the old one. CallInst *NC = new CallInst(GCRead, CI->getOperand(1), CI->getName(), CI); Value *NV = new CastInst(NC, CI->getType(), "", CI); CI->replaceAllUsesWith(NV); BB->getInstList().erase(CI); CI = NC; } } // Now that we made the replacement, inline expand the call if // possible, otherwise things will be too horribly expensive. InlineFunction(CI); MadeChange = true; } } // If there are no GC roots in this function, then there is no need to create // a GC list record for it. if (GCRoots.empty()) return MadeChange; // Okay, there are GC roots in this function. On entry to the function, add a // record to the llvm_gc_root_chain, and remove it on exit. // Create the alloca, and zero it out. const StructType *RootListTy = getRootRecordType(GCRoots.size()); AllocaInst *AI = new AllocaInst(RootListTy, 0, "gcroots", F.begin()->begin()); // Insert the memset call after all of the allocas in the function. BasicBlock::iterator IP = AI; while (isa<AllocaInst>(IP)) ++IP; Constant *Zero = ConstantUInt::get(Type::UIntTy, 0); Constant *One = ConstantUInt::get(Type::UIntTy, 1); // Get a pointer to the prev pointer. std::vector<Value*> Par; Par.push_back(Zero); Par.push_back(Zero); Value *PrevPtrPtr = new GetElementPtrInst(AI, Par, "prevptrptr", IP); // Load the previous pointer. Value *PrevPtr = new LoadInst(RootChain, "prevptr", IP); // Store the previous pointer into the prevptrptr new StoreInst(PrevPtr, PrevPtrPtr, IP); // Set the number of elements in this record. Par[1] = ConstantUInt::get(Type::UIntTy, 1); Value *NumEltsPtr = new GetElementPtrInst(AI, Par, "numeltsptr", IP); new StoreInst(ConstantUInt::get(Type::UIntTy, GCRoots.size()), NumEltsPtr,IP); Par[1] = ConstantUInt::get(Type::UIntTy, 2); Par.resize(4); const PointerType *PtrLocTy = cast<PointerType>(GCRootInt->getFunctionType()->getParamType(0)); Constant *Null = ConstantPointerNull::get(PtrLocTy); // Initialize all of the gcroot records now, and eliminate them as we go. for (unsigned i = 0, e = GCRoots.size(); i != e; ++i) { // Initialize the meta-data pointer. Par[2] = ConstantUInt::get(Type::UIntTy, i); Par[3] = One; Value *MetaDataPtr = new GetElementPtrInst(AI, Par, "MetaDataPtr", IP); assert(isa<Constant>(GCRoots[i]->getOperand(2)) || isa<GlobalValue>(GCRoots[i]->getOperand(2))); new StoreInst(GCRoots[i]->getOperand(2), MetaDataPtr, IP); // Initialize the root pointer to null on entry to the function. Par[3] = Zero; Value *RootPtrPtr = new GetElementPtrInst(AI, Par, "RootEntPtr", IP); new StoreInst(Null, RootPtrPtr, IP); // Each occurrance of the llvm.gcroot intrinsic now turns into an // initialization of the slot with the address and a zeroing out of the // address specified. new StoreInst(Constant::getNullValue(PtrLocTy->getElementType()), GCRoots[i]->getOperand(1), GCRoots[i]); new StoreInst(GCRoots[i]->getOperand(1), RootPtrPtr, GCRoots[i]); GCRoots[i]->getParent()->getInstList().erase(GCRoots[i]); } // Now that the record is all initialized, store the pointer into the global // pointer. Value *C = new CastInst(AI, PointerType::get(MainRootRecordType), "", IP); new StoreInst(C, RootChain, IP); // On exit from the function we have to remove the entry from the GC root // chain. Doing this is straight-forward for return and unwind instructions: // just insert the appropriate copy. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) if (isa<UnwindInst>(BB->getTerminator()) || isa<ReturnInst>(BB->getTerminator())) { // We could reuse the PrevPtr loaded on entry to the function, but this // would make the value live for the whole function, which is probably a // bad idea. Just reload the value out of our stack entry. PrevPtr = new LoadInst(PrevPtrPtr, "prevptr", BB->getTerminator()); new StoreInst(PrevPtr, RootChain, BB->getTerminator()); } // If an exception is thrown from a callee we have to make sure to // unconditionally take the record off the stack. For this reason, we turn // all call instructions into invoke whose cleanup pops the entry off the // stack. We only insert one cleanup block, which is shared by all invokes. if (!NormalCalls.empty()) { // Create the shared cleanup block. BasicBlock *Cleanup = new BasicBlock("gc_cleanup", &F); UnwindInst *UI = new UnwindInst(Cleanup); PrevPtr = new LoadInst(PrevPtrPtr, "prevptr", UI); new StoreInst(PrevPtr, RootChain, UI); // Loop over all of the function calls, turning them into invokes. while (!NormalCalls.empty()) { CallInst *CI = NormalCalls.back(); BasicBlock *CBB = CI->getParent(); NormalCalls.pop_back(); // Split the basic block containing the function call. BasicBlock *NewBB = CBB->splitBasicBlock(CI, CBB->getName()+".cont"); // Remove the unconditional branch inserted at the end of the CBB. CBB->getInstList().pop_back(); NewBB->getInstList().remove(CI); // Create a new invoke instruction. Value *II = new InvokeInst(CI->getCalledValue(), NewBB, Cleanup, std::vector<Value*>(CI->op_begin()+1, CI->op_end()), CI->getName(), CBB); CI->replaceAllUsesWith(II); delete CI; } } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/url_request/url_request_throttler_manager.h" #include <list> #include "base/logging.h" #include "base/string_util.h" namespace { // TODO(joi): Remove after crbug.com/71721 is fixed. struct IteratorHistory { // Copy of 'this' pointer at time of access; this helps both because // the this pointer is often obfuscated (at least for this particular // stack trace) in fully optimized builds, and possibly to detect // changes in the this pointer during iteration over the map (e.g. // from another thread overwriting memory). net::URLRequestThrottlerManager* self; // Copy of URL key. char url[256]; // Not a refptr, we don't want to change behavior by keeping it alive. net::URLRequestThrottlerEntryInterface* entry; // Set to true if the entry gets erased. Helpful to verify that entries // with 0 refcount (since we don't take a refcount above) have been // erased from the map. bool was_erased; }; } // namespace namespace net { const unsigned int URLRequestThrottlerManager::kMaximumNumberOfEntries = 1500; const unsigned int URLRequestThrottlerManager::kRequestsBetweenCollecting = 200; URLRequestThrottlerManager* URLRequestThrottlerManager::GetInstance() { return Singleton<URLRequestThrottlerManager>::get(); } scoped_refptr<URLRequestThrottlerEntryInterface> URLRequestThrottlerManager::RegisterRequestUrl(const GURL &url) { CHECK(being_tested_ || thread_checker_.CalledOnValidThread()); // Normalize the url. std::string url_id = GetIdFromUrl(url); // Periodically garbage collect old entries. GarbageCollectEntriesIfNecessary(); // Find the entry in the map or create it. scoped_refptr<URLRequestThrottlerEntry>& entry = url_entries_[url_id]; if (entry.get() == NULL) entry = new URLRequestThrottlerEntry(); // TODO(joi): Demote CHECKs in this file to DCHECKs (or remove them) once // we fully understand crbug.com/71721 CHECK(entry.get()); return entry; } void URLRequestThrottlerManager::OverrideEntryForTests( const GURL& url, URLRequestThrottlerEntry* entry) { // Normalize the url. std::string url_id = GetIdFromUrl(url); // Periodically garbage collect old entries. GarbageCollectEntriesIfNecessary(); url_entries_[url_id] = entry; } void URLRequestThrottlerManager::EraseEntryForTests(const GURL& url) { // Normalize the url. std::string url_id = GetIdFromUrl(url); url_entries_.erase(url_id); } void URLRequestThrottlerManager::InitializeOptions(bool enforce_throttling) { enforce_throttling_ = enforce_throttling; being_tested_ = false; } URLRequestThrottlerManager::URLRequestThrottlerManager() : requests_since_last_gc_(0), enforce_throttling_(true), being_tested_(true) { // Construction/destruction is on main thread (because BrowserMain // retrieves an instance to call InitializeOptions), but is from then on // used on I/O thread. thread_checker_.DetachFromThread(); url_id_replacements_.ClearPassword(); url_id_replacements_.ClearUsername(); url_id_replacements_.ClearQuery(); url_id_replacements_.ClearRef(); // TODO(joi): Remove after crbug.com/71721 is fixed. base::strlcpy(magic_buffer_1_, "MAGICZZ", arraysize(magic_buffer_1_)); base::strlcpy(magic_buffer_2_, "GOOGYZZ", arraysize(magic_buffer_2_)); } URLRequestThrottlerManager::~URLRequestThrottlerManager() { // Destruction is on main thread (AtExit), but real use is on I/O thread. thread_checker_.DetachFromThread(); // Delete all entries. url_entries_.clear(); } std::string URLRequestThrottlerManager::GetIdFromUrl(const GURL& url) const { if (!url.is_valid()) return url.possibly_invalid_spec(); GURL id = url.ReplaceComponents(url_id_replacements_); // TODO(joi): Remove "GOOGY/MONSTA" stuff once crbug.com/71721 is done return StringPrintf("GOOGY%sMONSTA", StringToLowerASCII(id.spec()).c_str()); } void URLRequestThrottlerManager::GarbageCollectEntriesIfNecessary() { requests_since_last_gc_++; if (requests_since_last_gc_ < kRequestsBetweenCollecting) return; requests_since_last_gc_ = 0; GarbageCollectEntries(); } void URLRequestThrottlerManager::GarbageCollectEntries() { // TODO(joi): Remove these crash report aids once crbug.com/71721 // is figured out. IteratorHistory history[32] = { { 0 } }; size_t history_ix = 0; history[history_ix++].self = this; int nulls_found = 0; UrlEntryMap::iterator i = url_entries_.begin(); while (i != url_entries_.end()) { if (i->second == NULL) { ++nulls_found; } // Keep a log of the first 31 items accessed after the first // NULL encountered (hypothesis is there are multiple NULLs, // and we may learn more about pattern of memory overwrite). // We also log when we access the first entry, to get an original // value for our this pointer. if (nulls_found > 0 && history_ix < arraysize(history)) { history[history_ix].self = this; base::strlcpy(history[history_ix].url, i->first.c_str(), arraysize(history[history_ix].url)); history[history_ix].entry = i->second.get(); history[history_ix].was_erased = false; ++history_ix; } // TODO(joi): Remove first i->second check when crbug.com/71721 is fixed. if (i->second == NULL || (i->second)->IsEntryOutdated()) { url_entries_.erase(i++); if (nulls_found > 0 && (history_ix - 1) < arraysize(history)) { history[history_ix - 1].was_erased = true; } } else { ++i; } } // TODO(joi): Make this a CHECK again after M11 branch point. DCHECK(nulls_found == 0); // In case something broke we want to make sure not to grow indefinitely. while (url_entries_.size() > kMaximumNumberOfEntries) { url_entries_.erase(url_entries_.begin()); } } } // namespace net <commit_msg>Revert to CHECK when null entries appear in the throttler map.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/url_request/url_request_throttler_manager.h" #include <list> #include "base/logging.h" #include "base/string_util.h" namespace { // TODO(joi): Remove after crbug.com/71721 is fixed. struct IteratorHistory { // Copy of 'this' pointer at time of access; this helps both because // the this pointer is often obfuscated (at least for this particular // stack trace) in fully optimized builds, and possibly to detect // changes in the this pointer during iteration over the map (e.g. // from another thread overwriting memory). net::URLRequestThrottlerManager* self; // Copy of URL key. char url[256]; // Not a refptr, we don't want to change behavior by keeping it alive. net::URLRequestThrottlerEntryInterface* entry; // Set to true if the entry gets erased. Helpful to verify that entries // with 0 refcount (since we don't take a refcount above) have been // erased from the map. bool was_erased; }; } // namespace namespace net { const unsigned int URLRequestThrottlerManager::kMaximumNumberOfEntries = 1500; const unsigned int URLRequestThrottlerManager::kRequestsBetweenCollecting = 200; URLRequestThrottlerManager* URLRequestThrottlerManager::GetInstance() { return Singleton<URLRequestThrottlerManager>::get(); } scoped_refptr<URLRequestThrottlerEntryInterface> URLRequestThrottlerManager::RegisterRequestUrl(const GURL &url) { CHECK(being_tested_ || thread_checker_.CalledOnValidThread()); // Normalize the url. std::string url_id = GetIdFromUrl(url); // Periodically garbage collect old entries. GarbageCollectEntriesIfNecessary(); // Find the entry in the map or create it. scoped_refptr<URLRequestThrottlerEntry>& entry = url_entries_[url_id]; if (entry.get() == NULL) entry = new URLRequestThrottlerEntry(); // TODO(joi): Demote CHECKs in this file to DCHECKs (or remove them) once // we fully understand crbug.com/71721 CHECK(entry.get()); return entry; } void URLRequestThrottlerManager::OverrideEntryForTests( const GURL& url, URLRequestThrottlerEntry* entry) { // Normalize the url. std::string url_id = GetIdFromUrl(url); // Periodically garbage collect old entries. GarbageCollectEntriesIfNecessary(); url_entries_[url_id] = entry; } void URLRequestThrottlerManager::EraseEntryForTests(const GURL& url) { // Normalize the url. std::string url_id = GetIdFromUrl(url); url_entries_.erase(url_id); } void URLRequestThrottlerManager::InitializeOptions(bool enforce_throttling) { enforce_throttling_ = enforce_throttling; being_tested_ = false; } URLRequestThrottlerManager::URLRequestThrottlerManager() : requests_since_last_gc_(0), enforce_throttling_(true), being_tested_(true) { // Construction/destruction is on main thread (because BrowserMain // retrieves an instance to call InitializeOptions), but is from then on // used on I/O thread. thread_checker_.DetachFromThread(); url_id_replacements_.ClearPassword(); url_id_replacements_.ClearUsername(); url_id_replacements_.ClearQuery(); url_id_replacements_.ClearRef(); // TODO(joi): Remove after crbug.com/71721 is fixed. base::strlcpy(magic_buffer_1_, "MAGICZZ", arraysize(magic_buffer_1_)); base::strlcpy(magic_buffer_2_, "GOOGYZZ", arraysize(magic_buffer_2_)); } URLRequestThrottlerManager::~URLRequestThrottlerManager() { // Destruction is on main thread (AtExit), but real use is on I/O thread. thread_checker_.DetachFromThread(); // Delete all entries. url_entries_.clear(); } std::string URLRequestThrottlerManager::GetIdFromUrl(const GURL& url) const { if (!url.is_valid()) return url.possibly_invalid_spec(); GURL id = url.ReplaceComponents(url_id_replacements_); // TODO(joi): Remove "GOOGY/MONSTA" stuff once crbug.com/71721 is done return StringPrintf("GOOGY%sMONSTA", StringToLowerASCII(id.spec()).c_str()); } void URLRequestThrottlerManager::GarbageCollectEntriesIfNecessary() { requests_since_last_gc_++; if (requests_since_last_gc_ < kRequestsBetweenCollecting) return; requests_since_last_gc_ = 0; GarbageCollectEntries(); } void URLRequestThrottlerManager::GarbageCollectEntries() { // TODO(joi): Remove these crash report aids once crbug.com/71721 // is figured out. IteratorHistory history[32] = { { 0 } }; size_t history_ix = 0; history[history_ix++].self = this; int nulls_found = 0; UrlEntryMap::iterator i = url_entries_.begin(); while (i != url_entries_.end()) { if (i->second == NULL) { ++nulls_found; } // Keep a log of the first 31 items accessed after the first // NULL encountered (hypothesis is there are multiple NULLs, // and we may learn more about pattern of memory overwrite). // We also log when we access the first entry, to get an original // value for our this pointer. if (nulls_found > 0 && history_ix < arraysize(history)) { history[history_ix].self = this; base::strlcpy(history[history_ix].url, i->first.c_str(), arraysize(history[history_ix].url)); history[history_ix].entry = i->second.get(); history[history_ix].was_erased = false; ++history_ix; } // TODO(joi): Remove first i->second check when crbug.com/71721 is fixed. if (i->second == NULL || (i->second)->IsEntryOutdated()) { url_entries_.erase(i++); if (nulls_found > 0 && (history_ix - 1) < arraysize(history)) { history[history_ix - 1].was_erased = true; } } else { ++i; } } CHECK(nulls_found == 0); // In case something broke we want to make sure not to grow indefinitely. while (url_entries_.size() > kMaximumNumberOfEntries) { url_entries_.erase(url_entries_.begin()); } } } // namespace net <|endoftext|>
<commit_before>/* * Copyright (C) 2016 Luke San Antonio * All rights reserved. */ #include <chrono> #include <string> #include "sdl_helper.h" #include "gfx/scene.h" #include "assets/minigltf.h" #include "common/log.h" int main(int argc, char** argv) { redc::Scoped_Log_Init log_raii{}; if(argc < 2) { redc::log_e("usage: % <filename.gltf>", argv[0]); return EXIT_FAILURE; } auto sdl_init = init_sdl("glTF viewer", redc::Vec<int>{1000, 1000}, false, false); auto before = std::chrono::high_resolution_clock::now(); auto desc = redc::load_gltf_file(argv[1]); auto asset = redc::load_asset(desc.value()); auto after = std::chrono::high_resolution_clock::now(); auto dt = std::chrono::duration_cast<std::chrono::milliseconds>(after - before); redc::log_i("Took %s to load", dt.count() / 1000.0); // List materials, shaders, programs and techniques for(auto mat_pair : desc->materials) { redc::log_i("Material: %", mat_pair.first); redc::log_i("\tname: %", mat_pair.second.name); redc::log_i("\ttechnique: %", mat_pair.second.technique); for(auto param_pair : mat_pair.second.values) { redc::log_i("\tParameter: %", param_pair.first); redc::log_i("\t\tstring_value: %", param_pair.second.string_value); std::string number_array = "["; for(auto num : param_pair.second.number_array) { number_array += std::to_string(num) + ", "; } number_array += "]"; redc::log_i("\t\tnumber_array: %", number_array); } } for(auto mesh_pair : desc->meshes) { redc::log_i("Mesh: %", mesh_pair.first); std::size_t i = 0; for(auto prim : mesh_pair.second.primitives) { redc::log_i("\t% material: %", i, prim.material); redc::log_i("\t% indices: %", i, prim.indices); redc::log_i("\t% mode: %", i, prim.mode); for(auto attrib_pair : prim.attributes) { redc::log_i("\t%\tattribute %:%", i, attrib_pair.first, attrib_pair.second); } ++i; } } for(auto shader_pair : desc->shaders) { redc::log_i("Shader: %", shader_pair.first); redc::log_i("\tname: %", shader_pair.second.name); redc::log_i("\ttype: %", shader_pair.second.type); std::string source(shader_pair.second.source.begin(), shader_pair.second.source.end()); redc::log_i("\tsource:\n%", source); } for(auto program_pair : desc->programs) { redc::log_i("Program: %", program_pair.first); redc::log_i("\tvertexShader: %", program_pair.second.vertexShader); redc::log_i("\tfragmentShader: %", program_pair.second.fragmentShader); for(auto attrib : program_pair.second.attributes) { redc::log_i("\tattribute %", attrib); } } for(auto technique_pair : desc->techniques) { redc::log_i("Technique: %", technique_pair.first); redc::log_i("\tname: %", technique_pair.second.name); redc::log_i("\tprogram: %", technique_pair.second.program); for(auto attrib_pair : technique_pair.second.attributes) { redc::log_i("\tattribute %:%", attrib_pair.first, attrib_pair.second); } for(auto uniform_pair : technique_pair.second.uniforms) { redc::log_i("\tuniform %:%", uniform_pair.first, uniform_pair.second); } for(auto parameter_pair : technique_pair.second.parameters) { redc::log_i("\tParameter: %", parameter_pair.first); redc::log_i("\t\tcount: %", parameter_pair.second.count); redc::log_i("\t\tnode: %", parameter_pair.second.node); redc::log_i("\t\ttype: %", parameter_pair.second.type); redc::log_i("\t\tsemantic: %", parameter_pair.second.semantic); redc::log_i("\t\tValue:"); redc::log_i("\t\t\tstring_value: %", parameter_pair.second.value.string_value); std::string number_array = "["; for(auto num : parameter_pair.second.value.number_array) { number_array += std::to_string(num) + ", "; } number_array += "]"; redc::log_i("\t\t\tnumber_array: %", number_array); } } return EXIT_SUCCESS; } <commit_msg>Stop printing information about asset hierarchy<commit_after>/* * Copyright (C) 2016 Luke San Antonio * All rights reserved. */ #include <chrono> #include "sdl_helper.h" #include "gfx/scene.h" #include "assets/minigltf.h" #include "common/log.h" int main(int argc, char** argv) { redc::Scoped_Log_Init log_raii{}; if(argc < 2) { redc::log_e("usage: % <filename.gltf>", argv[0]); return EXIT_FAILURE; } auto sdl_init = init_sdl("glTF viewer", redc::Vec<int>{1000, 1000}, false, false); auto before = std::chrono::high_resolution_clock::now(); auto desc = redc::load_gltf_file(argv[1]); auto asset = redc::load_asset(desc.value()); auto after = std::chrono::high_resolution_clock::now(); auto dt = std::chrono::duration_cast<std::chrono::milliseconds>(after - before); redc::log_i("Took %s to load", dt.count() / 1000.0); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexPS.cxx ** Lexer for PostScript ** ** Written by Nigel Hathaway. **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsASelfDelimitingChar(const int ch) { return (ch == '[' || ch == ']' || ch == '{' || ch == '}' || ch == '/' || ch == '<' || ch == '>' || ch == '(' || ch == ')' || ch == '%'); } static inline bool IsAWhitespaceChar(const int ch) { return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\f' || ch == '\0'); } static bool IsABaseNDigit(const int ch, const int base) { int maxdig = '9'; int letterext = -1; if (base <= 10) maxdig = '0' + base - 1; else letterext = base - 11; return ((ch >= '0' && ch <= maxdig) || (ch >= 'A' && ch <= ('A' + letterext)) || (ch >= 'a' && ch <= ('a' + letterext))); } static inline bool IsABase85Char(const int ch) { return ((ch >= '!' && ch <= 'u') || ch == 'z'); } static void ColourisePSDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords1 = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; StyleContext sc(startPos, length, initStyle, styler); bool tokenizing = styler.GetPropertyInt("ps.tokenize") != 0; int pslevel = styler.GetPropertyInt("ps.level", 3); int lineCurrent = styler.GetLine(startPos); int nestTextCurrent = 0; if (lineCurrent > 0 && initStyle == SCE_PS_TEXT) nestTextCurrent = styler.GetLineState(lineCurrent - 1); int numRadix = 0; bool numHasPoint = false; bool numHasExponent = false; bool numHasSign = false; // Clear out existing tokenization if (tokenizing && length > 0) { styler.StartAt(startPos, static_cast<char>(INDIC2_MASK)); styler.ColourTo(startPos + length-1, 0); styler.Flush(); styler.StartAt(startPos); styler.StartSegment(startPos); } for (; sc.More(); sc.Forward()) { if (sc.atLineStart) lineCurrent = styler.GetLine(sc.currentPos); // Determine if the current state should terminate. if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) { if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_PS_DSC_COMMENT) { if (sc.ch == ':') { sc.Forward(); if (!sc.atLineEnd) sc.SetState(SCE_PS_DSC_VALUE); else sc.SetState(SCE_C_DEFAULT); } else if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } else if (IsAWhitespaceChar(sc.ch)) { sc.ChangeState(SCE_PS_COMMENT); } } else if (sc.state == SCE_PS_NUMBER) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) { if ((sc.chPrev == '+' || sc.chPrev == '-' || sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0) sc.ChangeState(SCE_PS_NAME); sc.SetState(SCE_C_DEFAULT); } else if (sc.ch == '#') { if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) { sc.ChangeState(SCE_PS_NAME); } else { char szradix[5]; sc.GetCurrent(szradix, 4); numRadix = atoi(szradix); if (numRadix < 2 || numRadix > 36) sc.ChangeState(SCE_PS_NAME); } } else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) { if (numHasExponent) { sc.ChangeState(SCE_PS_NAME); } else { numHasExponent = true; if (sc.chNext == '+' || sc.chNext == '-') sc.Forward(); } } else if (sc.ch == '.') { if (numHasPoint || numHasExponent || numRadix != 0) { sc.ChangeState(SCE_PS_NAME); } else { numHasPoint = true; } } else if (numRadix == 0) { if (!IsABaseNDigit(sc.ch, 10)) sc.ChangeState(SCE_PS_NAME); } else { if (!IsABaseNDigit(sc.ch, numRadix)) sc.ChangeState(SCE_PS_NAME); } } else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); if ((pslevel >= 1 && keywords1.InList(s)) || (pslevel >= 2 && keywords2.InList(s)) || (pslevel >= 3 && keywords3.InList(s)) || keywords4.InList(s) || keywords5.InList(s)) { sc.ChangeState(SCE_PS_KEYWORD); } sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT || sc.state == SCE_PS_PAREN_PROC) { sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_PS_TEXT) { if (sc.ch == '(') { nestTextCurrent++; } else if (sc.ch == ')') { if (--nestTextCurrent == 0) sc.ForwardSetState(SCE_PS_DEFAULT); } else if (sc.ch == '\\') { sc.Forward(); } } else if (sc.state == SCE_PS_HEXSTRING) { if (sc.ch == '>') { sc.ForwardSetState(SCE_PS_DEFAULT); } else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_HEXSTRING); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } } else if (sc.state == SCE_PS_BASE85STRING) { if (sc.Match('~', '>')) { sc.Forward(); sc.ForwardSetState(SCE_PS_DEFAULT); } else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_BASE85STRING); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } } // Determine if a new state should be entered. if (sc.state == SCE_C_DEFAULT) { unsigned int tokenpos = sc.currentPos; if (sc.ch == '[' || sc.ch == ']') { sc.SetState(SCE_PS_PAREN_ARRAY); } else if (sc.ch == '{' || sc.ch == '}') { sc.SetState(SCE_PS_PAREN_PROC); } else if (sc.ch == '/') { if (sc.chNext == '/') { sc.SetState(SCE_PS_IMMEVAL); sc.Forward(); } else { sc.SetState(SCE_PS_LITERAL); } } else if (sc.ch == '<') { if (sc.chNext == '<') { sc.SetState(SCE_PS_PAREN_DICT); sc.Forward(); } else if (sc.chNext == '~') { sc.SetState(SCE_PS_BASE85STRING); sc.Forward(); } else { sc.SetState(SCE_PS_HEXSTRING); } } else if (sc.ch == '>' && sc.chNext == '>') { sc.SetState(SCE_PS_PAREN_DICT); sc.Forward(); } else if (sc.ch == '>' || sc.ch == ')') { sc.SetState(SCE_C_DEFAULT); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } else if (sc.ch == '(') { sc.SetState(SCE_PS_TEXT); nestTextCurrent = 1; } else if (sc.ch == '%') { if (sc.chNext == '%' && sc.atLineStart) { sc.SetState(SCE_PS_DSC_COMMENT); sc.Forward(); if (sc.chNext == '+') { sc.Forward(); sc.ForwardSetState(SCE_PS_DSC_VALUE); } } else { sc.SetState(SCE_PS_COMMENT); } } else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') && IsABaseNDigit(sc.chNext, 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = (sc.ch == '.'); numHasExponent = false; numHasSign = (sc.ch == '+' || sc.ch == '-'); } else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' && IsABaseNDigit(sc.GetRelative(2), 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = false; numHasExponent = false; numHasSign = true; } else if (IsABaseNDigit(sc.ch, 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = false; numHasExponent = false; numHasSign = false; } else if (!IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_NAME); } // Mark the start of tokens if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT && sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) { styler.Flush(); styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK)); styler.ColourTo(tokenpos, INDIC2_MASK); styler.Flush(); styler.StartAt(tokenpos); styler.StartSegment(tokenpos); } } if (sc.atLineEnd) styler.SetLineState(lineCurrent, nestTextCurrent); } sc.Complete(); } static void FoldPSDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; int levelMinCurrent = levelCurrent; int levelNext = levelCurrent; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); //mac?? if ((style & 31) == SCE_PS_PAREN_PROC) { if (ch == '{') { // Measure the minimum before a '{' to allow // folding on "} {" if (levelMinCurrent > levelNext) { levelMinCurrent = levelNext; } levelNext++; } else if (ch == '}') { levelNext--; } } if (atEOL) { int levelUse = levelCurrent; if (foldAtElse) { levelUse = levelMinCurrent; } int lev = levelUse | levelNext << 16; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (levelUse < levelNext) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelCurrent = levelNext; levelMinCurrent = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } } static const char * const psWordListDesc[] = { "PS Level 1 operators", "PS Level 2 operators", "PS Level 3 operators", "RIP-specific operators", "User-defined operators", 0 }; LexerModule lmPS(SCLEX_PS, ColourisePSDoc, "ps", FoldPSDoc, psWordListDesc); <commit_msg>Fixed warning from Borland.<commit_after>// Scintilla source code edit control /** @file LexPS.cxx ** Lexer for PostScript ** ** Written by Nigel Hathaway. **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsASelfDelimitingChar(const int ch) { return (ch == '[' || ch == ']' || ch == '{' || ch == '}' || ch == '/' || ch == '<' || ch == '>' || ch == '(' || ch == ')' || ch == '%'); } static inline bool IsAWhitespaceChar(const int ch) { return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\f' || ch == '\0'); } static bool IsABaseNDigit(const int ch, const int base) { int maxdig = '9'; int letterext = -1; if (base <= 10) maxdig = '0' + base - 1; else letterext = base - 11; return ((ch >= '0' && ch <= maxdig) || (ch >= 'A' && ch <= ('A' + letterext)) || (ch >= 'a' && ch <= ('a' + letterext))); } static inline bool IsABase85Char(const int ch) { return ((ch >= '!' && ch <= 'u') || ch == 'z'); } static void ColourisePSDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords1 = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; StyleContext sc(startPos, length, initStyle, styler); bool tokenizing = styler.GetPropertyInt("ps.tokenize") != 0; int pslevel = styler.GetPropertyInt("ps.level", 3); int lineCurrent = styler.GetLine(startPos); int nestTextCurrent = 0; if (lineCurrent > 0 && initStyle == SCE_PS_TEXT) nestTextCurrent = styler.GetLineState(lineCurrent - 1); int numRadix = 0; bool numHasPoint = false; bool numHasExponent = false; bool numHasSign = false; // Clear out existing tokenization if (tokenizing && length > 0) { styler.StartAt(startPos, static_cast<char>(INDIC2_MASK)); styler.ColourTo(startPos + length-1, 0); styler.Flush(); styler.StartAt(startPos); styler.StartSegment(startPos); } for (; sc.More(); sc.Forward()) { if (sc.atLineStart) lineCurrent = styler.GetLine(sc.currentPos); // Determine if the current state should terminate. if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) { if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_PS_DSC_COMMENT) { if (sc.ch == ':') { sc.Forward(); if (!sc.atLineEnd) sc.SetState(SCE_PS_DSC_VALUE); else sc.SetState(SCE_C_DEFAULT); } else if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } else if (IsAWhitespaceChar(sc.ch)) { sc.ChangeState(SCE_PS_COMMENT); } } else if (sc.state == SCE_PS_NUMBER) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) { if ((sc.chPrev == '+' || sc.chPrev == '-' || sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0) sc.ChangeState(SCE_PS_NAME); sc.SetState(SCE_C_DEFAULT); } else if (sc.ch == '#') { if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) { sc.ChangeState(SCE_PS_NAME); } else { char szradix[5]; sc.GetCurrent(szradix, 4); numRadix = atoi(szradix); if (numRadix < 2 || numRadix > 36) sc.ChangeState(SCE_PS_NAME); } } else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) { if (numHasExponent) { sc.ChangeState(SCE_PS_NAME); } else { numHasExponent = true; if (sc.chNext == '+' || sc.chNext == '-') sc.Forward(); } } else if (sc.ch == '.') { if (numHasPoint || numHasExponent || numRadix != 0) { sc.ChangeState(SCE_PS_NAME); } else { numHasPoint = true; } } else if (numRadix == 0) { if (!IsABaseNDigit(sc.ch, 10)) sc.ChangeState(SCE_PS_NAME); } else { if (!IsABaseNDigit(sc.ch, numRadix)) sc.ChangeState(SCE_PS_NAME); } } else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); if ((pslevel >= 1 && keywords1.InList(s)) || (pslevel >= 2 && keywords2.InList(s)) || (pslevel >= 3 && keywords3.InList(s)) || keywords4.InList(s) || keywords5.InList(s)) { sc.ChangeState(SCE_PS_KEYWORD); } sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) { if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT || sc.state == SCE_PS_PAREN_PROC) { sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_PS_TEXT) { if (sc.ch == '(') { nestTextCurrent++; } else if (sc.ch == ')') { if (--nestTextCurrent == 0) sc.ForwardSetState(SCE_PS_DEFAULT); } else if (sc.ch == '\\') { sc.Forward(); } } else if (sc.state == SCE_PS_HEXSTRING) { if (sc.ch == '>') { sc.ForwardSetState(SCE_PS_DEFAULT); } else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_HEXSTRING); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } } else if (sc.state == SCE_PS_BASE85STRING) { if (sc.Match('~', '>')) { sc.Forward(); sc.ForwardSetState(SCE_PS_DEFAULT); } else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_BASE85STRING); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } } // Determine if a new state should be entered. if (sc.state == SCE_C_DEFAULT) { unsigned int tokenpos = sc.currentPos; if (sc.ch == '[' || sc.ch == ']') { sc.SetState(SCE_PS_PAREN_ARRAY); } else if (sc.ch == '{' || sc.ch == '}') { sc.SetState(SCE_PS_PAREN_PROC); } else if (sc.ch == '/') { if (sc.chNext == '/') { sc.SetState(SCE_PS_IMMEVAL); sc.Forward(); } else { sc.SetState(SCE_PS_LITERAL); } } else if (sc.ch == '<') { if (sc.chNext == '<') { sc.SetState(SCE_PS_PAREN_DICT); sc.Forward(); } else if (sc.chNext == '~') { sc.SetState(SCE_PS_BASE85STRING); sc.Forward(); } else { sc.SetState(SCE_PS_HEXSTRING); } } else if (sc.ch == '>' && sc.chNext == '>') { sc.SetState(SCE_PS_PAREN_DICT); sc.Forward(); } else if (sc.ch == '>' || sc.ch == ')') { sc.SetState(SCE_C_DEFAULT); styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR); } else if (sc.ch == '(') { sc.SetState(SCE_PS_TEXT); nestTextCurrent = 1; } else if (sc.ch == '%') { if (sc.chNext == '%' && sc.atLineStart) { sc.SetState(SCE_PS_DSC_COMMENT); sc.Forward(); if (sc.chNext == '+') { sc.Forward(); sc.ForwardSetState(SCE_PS_DSC_VALUE); } } else { sc.SetState(SCE_PS_COMMENT); } } else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') && IsABaseNDigit(sc.chNext, 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = (sc.ch == '.'); numHasExponent = false; numHasSign = (sc.ch == '+' || sc.ch == '-'); } else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' && IsABaseNDigit(sc.GetRelative(2), 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = false; numHasExponent = false; numHasSign = true; } else if (IsABaseNDigit(sc.ch, 10)) { sc.SetState(SCE_PS_NUMBER); numRadix = 0; numHasPoint = false; numHasExponent = false; numHasSign = false; } else if (!IsAWhitespaceChar(sc.ch)) { sc.SetState(SCE_PS_NAME); } // Mark the start of tokens if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT && sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) { styler.Flush(); styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK)); styler.ColourTo(tokenpos, INDIC2_MASK); styler.Flush(); styler.StartAt(tokenpos); styler.StartSegment(tokenpos); } } if (sc.atLineEnd) styler.SetLineState(lineCurrent, nestTextCurrent); } sc.Complete(); } static void FoldPSDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; int levelMinCurrent = levelCurrent; int levelNext = levelCurrent; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); //mac?? if ((style & 31) == SCE_PS_PAREN_PROC) { if (ch == '{') { // Measure the minimum before a '{' to allow // folding on "} {" if (levelMinCurrent > levelNext) { levelMinCurrent = levelNext; } levelNext++; } else if (ch == '}') { levelNext--; } } if (atEOL) { int levelUse = levelCurrent; if (foldAtElse) { levelUse = levelMinCurrent; } int lev = levelUse | levelNext << 16; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (levelUse < levelNext) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelCurrent = levelNext; levelMinCurrent = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } } static const char * const psWordListDesc[] = { "PS Level 1 operators", "PS Level 2 operators", "PS Level 3 operators", "RIP-specific operators", "User-defined operators", 0 }; LexerModule lmPS(SCLEX_PS, ColourisePSDoc, "ps", FoldPSDoc, psWordListDesc); <|endoftext|>
<commit_before>#include <sstream> #include "util/bitmap.h" #include "factory/collector.h" #include "network/network.h" #include "util/token_exception.h" #include "mugen/exception.h" #include "mugen/menu.h" #include "mugen/game.h" #include "music.h" #include "menu/menu.h" #include "menu/menu-exception.h" #include "input/input-manager.h" #include "game/mod.h" #include "exceptions/shutdown_exception.h" #include "exceptions/exception.h" #include "util/timedifference.h" #include "util/funcs.h" #include "util/ftalleg.h" #include "util/file-system.h" #include "util/tokenreader.h" #include "util/token.h" #include "globals.h" #include "network/server.h" #include "configuration.h" #include "init.h" #include "mugen/config.h" #include <string.h> #include <vector> using namespace std; #define NUM_ARGS(d) (sizeof(d)/sizeof(char*)) static const char * WINDOWED_ARG[] = {"-w", "fullscreen", "nowindowed", "no-windowed"}; static const char * DATAPATH_ARG[] = {"-d", "--data", "data", "datapath", "data-path", "path"}; static const char * DEBUG_ARG[] = {"-l", "--debug", "debug"}; static const char * MUSIC_ARG[] = {"-m", "music", "nomusic", "no-music"}; static const char * NETWORK_SERVER_ARG[] = {"server", "network-server"}; static const char * MUGEN_ARG[] = {"mugen", "--mugen"}; static const char * MUGEN_INSTANT_ARG[] = {"mugen:training"}; static const char * JOYSTICK_ARG[] = {"joystick", "nojoystick", "no-joystick"}; static const char * closestMatch(const char * s1, vector<const char *> args){ const char * good = NULL; int minimum = -1; for (vector<const char *>::iterator it = args.begin(); it != args.end(); it++){ const char * compare = *it; if (strlen(compare) > 2){ int distance = Util::levenshtein(s1, compare); if (distance != -1 && (minimum == -1 || distance < minimum)){ minimum = distance; good = compare; } } } return good; } static bool isArg( const char * s1, const char * s2[], int num){ for (int i = 0; i < num; i++){ if (strcasecmp(s1, s2[i]) == 0){ return true; } } return false; } /* {"a", "b", "c"}, 3, ',' => "a, b, c" */ static const char * all(const char * args[], const int num, const char separate = ','){ static char buffer[1<<10]; strcpy(buffer, ""); for (int i = 0; i < num; i++){ char fuz[10]; sprintf(fuz, "%c ", separate); strcat(buffer, args[i]); if (i != num - 1){ strcat(buffer, fuz); } } return buffer; } static void showOptions(){ Global::debug(0) << "Paintown by Jon Rafkind" << endl; Global::debug(0) << "Command line options" << endl; Global::debug(0) << " " << all(WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG), ',') << " : Fullscreen mode" << endl; Global::debug(0) << " " << all(DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG)) << " <path> : Use data path of <path>. Default is " << Util::getDataPath2().path() << endl; Global::debug(0) << " " << all(DEBUG_ARG, NUM_ARGS(DEBUG_ARG)) << " # : Enable debug statements. Higher numbers gives more debugging. Default is 0. Negative numbers are allowed. Example: -l 3" << endl; Global::debug(0) << " " << all(MUSIC_ARG, NUM_ARGS(MUSIC_ARG)) << " : Turn off music" << endl; Global::debug(0) << " " << all(MUGEN_ARG, NUM_ARGS(MUGEN_ARG)) << " : Go directly to the mugen menu" << endl; Global::debug(0) << " " << all(MUGEN_INSTANT_ARG, NUM_ARGS(MUGEN_INSTANT_ARG)) << " <player 1 name>,<player 2 name>,<stage> : Start training game with the specified players and stage" << endl; Global::debug(0) << " " << all(JOYSTICK_ARG, NUM_ARGS(JOYSTICK_ARG)) << " : Disable joystick input" << endl; #ifdef HAVE_NETWORKING Global::debug(0) << " " << all(NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG)) << " : Go straight to the network server" << endl; #endif Global::debug(0) << endl; } static void addArgs(vector<const char *> & args, const char * strings[], int num){ for (int i = 0; i < num; i++){ args.push_back(strings[i]); } } static void setMugenMotif(const Filesystem::AbsolutePath & path){ TokenReader reader; Token * head = reader.readToken(path.path()); const Token * motif = head->findToken("menu/option/mugen/motif"); if (motif != NULL){ string path; motif->view() >> path; Mugen::Data::getInstance().setMotif(Filesystem::RelativePath(path)); } } static Filesystem::AbsolutePath mainMenuPath(){ string menu = Paintown::Mod::getCurrentMod()->getMenu(); return Filesystem::find(Filesystem::RelativePath(menu)); /* string file = Filesystem::find(currentMod()); TokenReader tr(file); Token * head = tr.readToken(); Token * menu = head->findToken("game/menu"); if (menu == NULL){ throw LoadException(file + " does not contain a game/menu token"); } string path; *menu >> path; // string path = "/menu/main.txt" return Filesystem::find(path); */ } /* static void hack(){ Filesystem::AbsolutePath fontsDirectory = Filesystem::find(Filesystem::RelativePath("fonts")); Global::debug(1, "hack") << "Font directory " << fontsDirectory.path() << endl; vector<string> ttfFonts = Util::getFiles(fontsDirectory, "*.ttf"); Global::debug(1, "hack") << "Fonts: " << ttfFonts.size() << endl; } */ static bool parseMugenInstant(string input, string * player1, string * player2, string * stage){ unsigned int comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected three arguments separated by a comma, only 1 was given: " << input << endl; return false; } *player1 = input.substr(0, comma); input.erase(0, comma + 1); comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected three arguments separated by a comma, only 2 were given: " << input << endl; return false; } *player2 = input.substr(0, comma); input.erase(0, comma + 1); *stage = input; return true; } static void runMugenTraining(const string & player1, const string & player2, const string & stage){ Global::debug(0) << "Mugen training mode player 1 '" << player1 << "' player2 '" << player2 << "' stage '" << stage << "'" << endl; Mugen::Game::startTraining(player1, player2, stage); } int paintown_main( int argc, char ** argv ){ /* -1 means use whatever is in the configuration */ int gfx = -1; bool music_on = true; bool joystick_on = true; bool mugen = false; bool just_network_server = false; Collector janitor; struct MugenInstant{ MugenInstant(): enabled(false){ } bool enabled; string player1; string player2; string stage; } mugenInstant; Global::setDebug(0); vector<const char *> all_args; #define ADD_ARGS(args) addArgs(all_args, args, NUM_ARGS(args)) ADD_ARGS(WINDOWED_ARG); ADD_ARGS(DATAPATH_ARG); ADD_ARGS(DEBUG_ARG); ADD_ARGS(MUSIC_ARG); ADD_ARGS(MUGEN_ARG); ADD_ARGS(MUGEN_INSTANT_ARG); #ifdef HAVE_NETWORKING ADD_ARGS(NETWORK_SERVER_ARG); #endif #undef ADD_ARGS for ( int q = 1; q < argc; q++ ){ if (isArg(argv[q], WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG))){ gfx = Global::FULLSCREEN; } else if ( isArg( argv[ q ], DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG) ) ){ q += 1; if ( q < argc ){ Util::setDataPath( argv[ q ] ); } } else if ( isArg( argv[ q ], MUSIC_ARG, NUM_ARGS(MUSIC_ARG) ) ){ music_on = false; } else if (isArg(argv[q], MUGEN_ARG, NUM_ARGS(MUGEN_ARG))){ mugen = true; } else if (isArg(argv[q], JOYSTICK_ARG, NUM_ARGS(JOYSTICK_ARG))){ joystick_on = false; } else if (isArg(argv[q], MUGEN_INSTANT_ARG, NUM_ARGS(MUGEN_INSTANT_ARG))){ q += 1; if (q < argc){ mugenInstant.enabled = parseMugenInstant(argv[q], &mugenInstant.player1, &mugenInstant.player2, &mugenInstant.stage); } else { Global::debug(0) << "Expected an argument. Example: mugen:training kfm,ken,falls" << endl; } } else if ( isArg( argv[ q ], DEBUG_ARG, NUM_ARGS(DEBUG_ARG) ) ){ q += 1; if ( q < argc ){ istringstream i( argv[ q ] ); int f; i >> f; Global::setDebug( f ); } #ifdef HAVE_NETWORKING } else if (isArg(argv[q], NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG))){ just_network_server = true; #endif } else { const char * arg = argv[q]; const char * closest = closestMatch(arg, all_args); if (closest == NULL){ Global::debug(0) << "I don't recognize option '" << arg << "'" << endl; } else { Global::debug(0) << "You gave option '" << arg << "'. Did you mean '" << closest << "'?" << endl; } } } #undef NUM_ARGS showOptions(); Global::debug(0) << "Debug level: " << Global::getDebug() << endl; if (!Filesystem::exists(Util::getDataPath2())){ Global::debug(0) << "Cannot find data path '" << Util::getDataPath2().path() << "'! Either use the -d switch to specify the data directory or find the data directory and move it to that path" << endl; return 1; } /* time how long init takes */ TimeDifference diff; diff.startTime(); /* init initializes practically everything including * graphics * sound * input * network * configuration * ... */ if (! Global::init(gfx)){ Global::debug(0) << "Could not initialize system" << endl; return -1; } else { // Configuration::setFullscreen((gfx == Global::FULLSCREEN ? true : false)); } diff.endTime(); Global::debug(0) << diff.printTime("Init took") << endl; try{ Paintown::Mod::loadPaintownMod(Configuration::getCurrentGame()); } catch (const Filesystem::NotFound & e){ Global::debug(0) << "Could not load mod " << Configuration::getCurrentGame() << ": " << e.getTrace() << endl; Paintown::Mod::loadDefaultMod(); } Configuration::setJoystickEnabled(joystick_on); InputManager input; Music music(music_on); while (true){ try{ /* fadein from white */ //Menu game(true, Bitmap::makeColor(255, 255, 255)); //game.load(mainMenuPath()); if (just_network_server){ #ifdef HAVE_NETWORKING Network::networkServer(); #endif } else if (mugen){ setMugenMotif(mainMenuPath()); Mugen::run(); } else if (mugenInstant.enabled){ setMugenMotif(mainMenuPath()); runMugenTraining(mugenInstant.player1, mugenInstant.player2, mugenInstant.stage); } else { Menu::Menu game(mainMenuPath()); game.run(Menu::Context()); } } catch (const Filesystem::Exception & ex){ Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getTrace() << endl; } catch (const TokenException & ex){ Global::debug(0) << "There was a problem with the token. Error was:\n " << ex.getTrace() << endl; return -1; } catch (const LoadException & ex){ Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getTrace() << endl; return -1; } catch (const Exception::Return & ex){ } catch (const ShutdownException & shutdown){ Global::debug(1) << "Forced a shutdown. Cya!" << endl; } catch (const MugenException & m){ Global::debug(0) << "Mugen exception: " << m.getReason() << endl; } catch (const ReloadMenuException & ex){ Global::debug(1) << "Menu Reload Requested. Restarting...." << endl; continue; } catch (const ftalleg::Exception & ex){ Global::debug(0) << "Freetype exception caught. Error was:\n" << ex.getReason() << endl; } catch (const Exception::Base & base){ // Global::debug(0) << "Freetype exception caught. Error was:\n" << ex.getReason() << endl; Global::debug(0) << "Base exception: " << base.getTrace() << endl; } catch (...){ Global::debug(0) << "Uncaught exception!" << endl; } break; } Configuration::saveConfiguration(); Global::debug(0) << "Bye!" << endl; return 0; } <commit_msg>start memory usage in main<commit_after>#include <sstream> #include "util/bitmap.h" #include "factory/collector.h" #include "network/network.h" #include "util/token_exception.h" #include "util/system.h" #include "mugen/exception.h" #include "mugen/menu.h" #include "mugen/game.h" #include "music.h" #include "menu/menu.h" #include "menu/menu-exception.h" #include "input/input-manager.h" #include "game/mod.h" #include "exceptions/shutdown_exception.h" #include "exceptions/exception.h" #include "util/timedifference.h" #include "util/funcs.h" #include "util/ftalleg.h" #include "util/file-system.h" #include "util/tokenreader.h" #include "util/token.h" #include "globals.h" #include "network/server.h" #include "configuration.h" #include "init.h" #include "mugen/config.h" #include <string.h> #include <vector> using namespace std; #define NUM_ARGS(d) (sizeof(d)/sizeof(char*)) static const char * WINDOWED_ARG[] = {"-w", "fullscreen", "nowindowed", "no-windowed"}; static const char * DATAPATH_ARG[] = {"-d", "--data", "data", "datapath", "data-path", "path"}; static const char * DEBUG_ARG[] = {"-l", "--debug", "debug"}; static const char * MUSIC_ARG[] = {"-m", "music", "nomusic", "no-music"}; static const char * NETWORK_SERVER_ARG[] = {"server", "network-server"}; static const char * MUGEN_ARG[] = {"mugen", "--mugen"}; static const char * MUGEN_INSTANT_ARG[] = {"mugen:training"}; static const char * JOYSTICK_ARG[] = {"joystick", "nojoystick", "no-joystick"}; static const char * closestMatch(const char * s1, vector<const char *> args){ const char * good = NULL; int minimum = -1; for (vector<const char *>::iterator it = args.begin(); it != args.end(); it++){ const char * compare = *it; if (strlen(compare) > 2){ int distance = Util::levenshtein(s1, compare); if (distance != -1 && (minimum == -1 || distance < minimum)){ minimum = distance; good = compare; } } } return good; } static bool isArg( const char * s1, const char * s2[], int num){ for (int i = 0; i < num; i++){ if (strcasecmp(s1, s2[i]) == 0){ return true; } } return false; } /* {"a", "b", "c"}, 3, ',' => "a, b, c" */ static const char * all(const char * args[], const int num, const char separate = ','){ static char buffer[1<<10]; strcpy(buffer, ""); for (int i = 0; i < num; i++){ char fuz[10]; sprintf(fuz, "%c ", separate); strcat(buffer, args[i]); if (i != num - 1){ strcat(buffer, fuz); } } return buffer; } static void showOptions(){ Global::debug(0) << "Paintown by Jon Rafkind" << endl; Global::debug(0) << "Command line options" << endl; Global::debug(0) << " " << all(WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG), ',') << " : Fullscreen mode" << endl; Global::debug(0) << " " << all(DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG)) << " <path> : Use data path of <path>. Default is " << Util::getDataPath2().path() << endl; Global::debug(0) << " " << all(DEBUG_ARG, NUM_ARGS(DEBUG_ARG)) << " # : Enable debug statements. Higher numbers gives more debugging. Default is 0. Negative numbers are allowed. Example: -l 3" << endl; Global::debug(0) << " " << all(MUSIC_ARG, NUM_ARGS(MUSIC_ARG)) << " : Turn off music" << endl; Global::debug(0) << " " << all(MUGEN_ARG, NUM_ARGS(MUGEN_ARG)) << " : Go directly to the mugen menu" << endl; Global::debug(0) << " " << all(MUGEN_INSTANT_ARG, NUM_ARGS(MUGEN_INSTANT_ARG)) << " <player 1 name>,<player 2 name>,<stage> : Start training game with the specified players and stage" << endl; Global::debug(0) << " " << all(JOYSTICK_ARG, NUM_ARGS(JOYSTICK_ARG)) << " : Disable joystick input" << endl; #ifdef HAVE_NETWORKING Global::debug(0) << " " << all(NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG)) << " : Go straight to the network server" << endl; #endif Global::debug(0) << endl; } static void addArgs(vector<const char *> & args, const char * strings[], int num){ for (int i = 0; i < num; i++){ args.push_back(strings[i]); } } static void setMugenMotif(const Filesystem::AbsolutePath & path){ TokenReader reader; Token * head = reader.readToken(path.path()); const Token * motif = head->findToken("menu/option/mugen/motif"); if (motif != NULL){ string path; motif->view() >> path; Mugen::Data::getInstance().setMotif(Filesystem::RelativePath(path)); } } static Filesystem::AbsolutePath mainMenuPath(){ string menu = Paintown::Mod::getCurrentMod()->getMenu(); return Filesystem::find(Filesystem::RelativePath(menu)); /* string file = Filesystem::find(currentMod()); TokenReader tr(file); Token * head = tr.readToken(); Token * menu = head->findToken("game/menu"); if (menu == NULL){ throw LoadException(file + " does not contain a game/menu token"); } string path; *menu >> path; // string path = "/menu/main.txt" return Filesystem::find(path); */ } /* static void hack(){ Filesystem::AbsolutePath fontsDirectory = Filesystem::find(Filesystem::RelativePath("fonts")); Global::debug(1, "hack") << "Font directory " << fontsDirectory.path() << endl; vector<string> ttfFonts = Util::getFiles(fontsDirectory, "*.ttf"); Global::debug(1, "hack") << "Fonts: " << ttfFonts.size() << endl; } */ static bool parseMugenInstant(string input, string * player1, string * player2, string * stage){ unsigned int comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected three arguments separated by a comma, only 1 was given: " << input << endl; return false; } *player1 = input.substr(0, comma); input.erase(0, comma + 1); comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected three arguments separated by a comma, only 2 were given: " << input << endl; return false; } *player2 = input.substr(0, comma); input.erase(0, comma + 1); *stage = input; return true; } static void runMugenTraining(const string & player1, const string & player2, const string & stage){ Global::debug(0) << "Mugen training mode player 1 '" << player1 << "' player2 '" << player2 << "' stage '" << stage << "'" << endl; Mugen::Game::startTraining(player1, player2, stage); } int paintown_main( int argc, char ** argv ){ /* -1 means use whatever is in the configuration */ int gfx = -1; bool music_on = true; bool joystick_on = true; bool mugen = false; bool just_network_server = false; Collector janitor; struct MugenInstant{ MugenInstant(): enabled(false){ } bool enabled; string player1; string player2; string stage; } mugenInstant; System::startMemoryUsage(); Global::setDebug(0); vector<const char *> all_args; #define ADD_ARGS(args) addArgs(all_args, args, NUM_ARGS(args)) ADD_ARGS(WINDOWED_ARG); ADD_ARGS(DATAPATH_ARG); ADD_ARGS(DEBUG_ARG); ADD_ARGS(MUSIC_ARG); ADD_ARGS(MUGEN_ARG); ADD_ARGS(MUGEN_INSTANT_ARG); #ifdef HAVE_NETWORKING ADD_ARGS(NETWORK_SERVER_ARG); #endif #undef ADD_ARGS for ( int q = 1; q < argc; q++ ){ if (isArg(argv[q], WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG))){ gfx = Global::FULLSCREEN; } else if ( isArg( argv[ q ], DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG) ) ){ q += 1; if ( q < argc ){ Util::setDataPath( argv[ q ] ); } } else if ( isArg( argv[ q ], MUSIC_ARG, NUM_ARGS(MUSIC_ARG) ) ){ music_on = false; } else if (isArg(argv[q], MUGEN_ARG, NUM_ARGS(MUGEN_ARG))){ mugen = true; } else if (isArg(argv[q], JOYSTICK_ARG, NUM_ARGS(JOYSTICK_ARG))){ joystick_on = false; } else if (isArg(argv[q], MUGEN_INSTANT_ARG, NUM_ARGS(MUGEN_INSTANT_ARG))){ q += 1; if (q < argc){ mugenInstant.enabled = parseMugenInstant(argv[q], &mugenInstant.player1, &mugenInstant.player2, &mugenInstant.stage); } else { Global::debug(0) << "Expected an argument. Example: mugen:training kfm,ken,falls" << endl; } } else if ( isArg( argv[ q ], DEBUG_ARG, NUM_ARGS(DEBUG_ARG) ) ){ q += 1; if ( q < argc ){ istringstream i( argv[ q ] ); int f; i >> f; Global::setDebug( f ); } #ifdef HAVE_NETWORKING } else if (isArg(argv[q], NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG))){ just_network_server = true; #endif } else { const char * arg = argv[q]; const char * closest = closestMatch(arg, all_args); if (closest == NULL){ Global::debug(0) << "I don't recognize option '" << arg << "'" << endl; } else { Global::debug(0) << "You gave option '" << arg << "'. Did you mean '" << closest << "'?" << endl; } } } #undef NUM_ARGS showOptions(); Global::debug(0) << "Debug level: " << Global::getDebug() << endl; if (!Filesystem::exists(Util::getDataPath2())){ Global::debug(0) << "Cannot find data path '" << Util::getDataPath2().path() << "'! Either use the -d switch to specify the data directory or find the data directory and move it to that path" << endl; return 1; } /* time how long init takes */ TimeDifference diff; diff.startTime(); /* init initializes practically everything including * graphics * sound * input * network * configuration * ... */ if (! Global::init(gfx)){ Global::debug(0) << "Could not initialize system" << endl; return -1; } else { // Configuration::setFullscreen((gfx == Global::FULLSCREEN ? true : false)); } diff.endTime(); Global::debug(0) << diff.printTime("Init took") << endl; try{ Paintown::Mod::loadPaintownMod(Configuration::getCurrentGame()); } catch (const Filesystem::NotFound & e){ Global::debug(0) << "Could not load mod " << Configuration::getCurrentGame() << ": " << e.getTrace() << endl; Paintown::Mod::loadDefaultMod(); } Configuration::setJoystickEnabled(joystick_on); InputManager input; Music music(music_on); while (true){ try{ /* fadein from white */ //Menu game(true, Bitmap::makeColor(255, 255, 255)); //game.load(mainMenuPath()); if (just_network_server){ #ifdef HAVE_NETWORKING Network::networkServer(); #endif } else if (mugen){ setMugenMotif(mainMenuPath()); Mugen::run(); } else if (mugenInstant.enabled){ setMugenMotif(mainMenuPath()); runMugenTraining(mugenInstant.player1, mugenInstant.player2, mugenInstant.stage); } else { Menu::Menu game(mainMenuPath()); game.run(Menu::Context()); } } catch (const Filesystem::Exception & ex){ Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getTrace() << endl; } catch (const TokenException & ex){ Global::debug(0) << "There was a problem with the token. Error was:\n " << ex.getTrace() << endl; return -1; } catch (const LoadException & ex){ Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getTrace() << endl; return -1; } catch (const Exception::Return & ex){ } catch (const ShutdownException & shutdown){ Global::debug(1) << "Forced a shutdown. Cya!" << endl; } catch (const MugenException & m){ Global::debug(0) << "Mugen exception: " << m.getReason() << endl; } catch (const ReloadMenuException & ex){ Global::debug(1) << "Menu Reload Requested. Restarting...." << endl; continue; } catch (const ftalleg::Exception & ex){ Global::debug(0) << "Freetype exception caught. Error was:\n" << ex.getReason() << endl; } catch (const Exception::Base & base){ // Global::debug(0) << "Freetype exception caught. Error was:\n" << ex.getReason() << endl; Global::debug(0) << "Base exception: " << base.getTrace() << endl; } catch (...){ Global::debug(0) << "Uncaught exception!" << endl; } break; } Configuration::saveConfiguration(); Global::debug(0) << "Bye!" << endl; return 0; } <|endoftext|>
<commit_before>// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include <signal.h> #include <string> #include <map> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> #include <boost/bind.hpp> #include <boost/mem_fn.hpp> #include <boost/algorithm/string.hpp> #include "common/logging.h" #include "util/cpu-info.h" #include "util/disk-info.h" #include "util/mem-info.h" #include "util/url-coding.h" #include "util/webserver.h" #include "util/logging.h" #include "util/debug-util.h" #include "util/thrift-util.h" using namespace std; using namespace boost; using namespace google; const char* GetDefaultDocumentRoot(); DEFINE_int32(webserver_port, 25000, "Port to start debug webserver on"); DEFINE_string(webserver_interface, "", "Interface to start debug webserver on. If blank, webserver binds to 0.0.0.0"); DEFINE_string(webserver_doc_root, GetDefaultDocumentRoot(), "Files under <webserver_doc_root>/www are accessible via the debug webserver. " "Defaults to $IMPALA_HOME, or if $IMPALA_HOME is not set, disables the document " "root"); DEFINE_bool(enable_webserver_doc_root, true, "If true, webserver may serve static files from the webserver_doc_root"); // Mongoose requires a non-null return from the callback to signify successful processing static void* PROCESSING_COMPLETE = reinterpret_cast<void*>(1); static const char* DOC_FOLDER = "/www/"; static const int DOC_FOLDER_LEN = strlen(DOC_FOLDER); // Returns $IMPALA_HOME if set, otherwise /tmp/impala_www const char* GetDefaultDocumentRoot() { stringstream ss; char* impala_home = getenv("IMPALA_HOME"); if (impala_home == NULL) { return ""; // Empty document root means don't serve static files } else { ss << impala_home; } // Deliberate memory leak, but this should be called exactly once. string* str = new string(ss.str()); return str->c_str(); } namespace impala { Webserver::Webserver() : context_(NULL) { http_address_ = MakeNetworkAddress( FLAGS_webserver_interface.empty() ? "0.0.0.0" : FLAGS_webserver_interface, FLAGS_webserver_port); } Webserver::Webserver(const int port) : context_(NULL) { http_address_ = MakeNetworkAddress("0.0.0.0", port); } Webserver::~Webserver() { Stop(); } void Webserver::RootHandler(const Webserver::ArgumentMap& args, stringstream* output) { // path_handler_lock_ already held by MongooseCallback (*output) << "<h2>Version</h2>"; (*output) << "<pre>" << GetVersionString() << "</pre>" << endl; (*output) << "<h2>Hardware Info</h2>"; (*output) << "<pre>"; (*output) << CpuInfo::DebugString(); (*output) << MemInfo::DebugString(); (*output) << DiskInfo::DebugString(); (*output) << "</pre>"; (*output) << "<h2>Status Pages</h2>"; BOOST_FOREACH(const PathHandlerMap::value_type& handler, path_handlers_) { if (handler.second.is_on_nav_bar()) { (*output) << "<a href=\"" << handler.first << "\">" << handler.first << "</a><br/>"; } } } void Webserver::BuildArgumentMap(const string& args, ArgumentMap* output) { vector<string> arg_pairs; split(arg_pairs, args, is_any_of("&")); BOOST_FOREACH(const string& arg_pair, arg_pairs) { vector<string> key_value; split(key_value, arg_pair, is_any_of("=")); if (key_value.empty()) continue; string key; if (!UrlDecode(key_value[0], &key)) continue; string value; if (!UrlDecode((key_value.size() >= 2 ? key_value[1] : ""), &value)) continue; to_lower(key); (*output)[key] = value; } } Status Webserver::Start() { LOG(INFO) << "Starting webserver on " << http_address_; stringstream listening_spec; if (IsWildcardAddress(http_address_.hostname)) { listening_spec << http_address_; } else { string port_as_string = lexical_cast<string>(http_address_.port); listening_spec << ":" << port_as_string; } string listening_str = listening_spec.str(); vector<const char*> options; if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) { LOG(INFO) << "Document root: " << FLAGS_webserver_doc_root; options.push_back("document_root"); options.push_back(FLAGS_webserver_doc_root.c_str()); } else { LOG(INFO)<< "Document root disabled"; } options.push_back("listening_ports"); options.push_back(listening_str.c_str()); // Options must be a NULL-terminated list options.push_back(NULL); // mongoose ignores SIGCHLD and we need it to run kinit. This means that since // mongoose does not reap its own children CGI programs must be avoided. // Save the signal handler so we can restore it after mongoose sets it to be ignored. sighandler_t sig_chld = signal(SIGCHLD, SIG_DFL); // To work around not being able to pass member functions as C callbacks, we store a // pointer to this server in the per-server state, and register a static method as the // default callback. That method unpacks the pointer to this and calls the real // callback. context_ = mg_start(&Webserver::MongooseCallbackStatic, reinterpret_cast<void*>(this), &options[0]); // Restore the child signal handler so wait() works properly. signal(SIGCHLD, sig_chld); if (context_ == NULL) { stringstream error_msg; error_msg << "Webserver: Could not start on address " << http_address_; return Status(error_msg.str()); } PathHandlerCallback default_callback = bind<void>(mem_fn(&Webserver::RootHandler), this, _1, _2); RegisterPathHandler("/", default_callback); LOG(INFO) << "Webserver started"; return Status::OK; } void Webserver::Stop() { if (context_ != NULL) mg_stop(context_); } void* Webserver::MongooseCallbackStatic(enum mg_event event, struct mg_connection* connection) { const struct mg_request_info* request_info = mg_get_request_info(connection); Webserver* instance = reinterpret_cast<Webserver*>(mg_get_user_data(connection)); return instance->MongooseCallback(event, connection, request_info); } void* Webserver::MongooseCallback(enum mg_event event, struct mg_connection* connection, const struct mg_request_info* request_info) { if (event == MG_NEW_REQUEST) { if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) { if (strncmp(DOC_FOLDER, request_info->uri, DOC_FOLDER_LEN) == 0) { VLOG(2) << "HTTP File access: " << request_info->uri; // Let Mongoose deal with this request; returning NULL will fall through // to the default handler which will serve files. return NULL; } } mutex::scoped_lock lock(path_handlers_lock_); PathHandlerMap::const_iterator it = path_handlers_.find(request_info->uri); if (it == path_handlers_.end()) { mg_printf(connection, "HTTP/1.1 404 Not Found\r\n" "Content-Type: text/plain\r\n\r\n"); mg_printf(connection, "No handler for URI %s\r\n\r\n", request_info->uri); return PROCESSING_COMPLETE; } // Should we render with css styles? bool use_style = true; map<string, string> arguments; if (request_info->query_string != NULL) { BuildArgumentMap(request_info->query_string, &arguments); } if (!it->second.is_styled() || arguments.find("raw") != arguments.end()) { use_style = false; } stringstream output; if (use_style) BootstrapPageHeader(&output); BOOST_FOREACH(const PathHandlerCallback& callback_, it->second.callbacks()) { callback_(arguments, &output); } if (use_style) BootstrapPageFooter(&output); string str = output.str(); // Without styling, render the page as plain text if (arguments.find("raw") != arguments.end()) { mg_printf(connection, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n", (int)str.length()); } else { mg_printf(connection, "HTTP/1.1 200 OK\r\n" "Content-Type: text/html\r\n" "Content-Length: %d\r\n" "\r\n", (int)str.length()); } // Make sure to use mg_write for printing the body; mg_printf truncates at 8kb mg_write(connection, str.c_str(), str.length()); return PROCESSING_COMPLETE; } else { return NULL; } } void Webserver::RegisterPathHandler(const string& path, const PathHandlerCallback& callback, bool is_styled, bool is_on_nav_bar) { mutex::scoped_lock lock(path_handlers_lock_); PathHandlerMap::iterator it = path_handlers_.find(path); if (it == path_handlers_.end()) { it = path_handlers_.insert( make_pair(path, PathHandler(is_styled, is_on_nav_bar))).first; } it->second.AddCallback(callback); } const string PAGE_HEADER = "<!DOCTYPE html>" " <html>" " <head><title>Cloudera Impala</title>" " <link href='www/bootstrap/css/bootstrap.min.css' rel='stylesheet' media='screen'>" " <style>" " body {" " padding-top: 60px; " " }" " </style>" " </head>" " <body>"; static const string PAGE_FOOTER = "</div></body></html>"; static const string NAVIGATION_BAR_PREFIX = "<div class='navbar navbar-inverse navbar-fixed-top'>" " <div class='navbar-inner'>" " <div class='container'>" " <a class='btn btn-navbar' data-toggle='collapse' data-target='.nav-collapse'>" " <span class='icon-bar'></span>" " <span class='icon-bar'></span>" " <span class='icon-bar'></span>" " </a>" " <a class='brand' href='/'>Impala</a>" " <div class='nav-collapse collapse'>" " <ul class='nav'>"; static const string NAVIGATION_BAR_SUFFIX = " </ul>" " </div>" " </div>" " </div>" " </div>" " <div class='container'>"; void Webserver::BootstrapPageHeader(stringstream* output) { (*output) << PAGE_HEADER; (*output) << NAVIGATION_BAR_PREFIX; BOOST_FOREACH(const PathHandlerMap::value_type& handler, path_handlers_) { if (handler.second.is_on_nav_bar()) { (*output) << "<li><a href=\"" << handler.first << "\">" << handler.first << "</a></li>"; } } (*output) << NAVIGATION_BAR_SUFFIX; } void Webserver::BootstrapPageFooter(stringstream* output) { (*output) << PAGE_FOOTER; } } <commit_msg>IMPALA-86: Authentication and SSL support for debug webserver<commit_after>// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include <signal.h> #include <string> #include <map> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> #include <boost/bind.hpp> #include <boost/mem_fn.hpp> #include <boost/algorithm/string.hpp> #include "common/logging.h" #include "util/cpu-info.h" #include "util/disk-info.h" #include "util/mem-info.h" #include "util/url-coding.h" #include "util/webserver.h" #include "util/logging.h" #include "util/debug-util.h" #include "util/thrift-util.h" using namespace std; using namespace boost; using namespace google; const char* GetDefaultDocumentRoot(); DEFINE_int32(webserver_port, 25000, "Port to start debug webserver on"); DEFINE_string(webserver_interface, "", "Interface to start debug webserver on. If blank, webserver binds to 0.0.0.0"); DEFINE_string(webserver_doc_root, GetDefaultDocumentRoot(), "Files under <webserver_doc_root>/www are accessible via the debug webserver. " "Defaults to $IMPALA_HOME, or if $IMPALA_HOME is not set, disables the document " "root"); DEFINE_bool(enable_webserver_doc_root, true, "If true, webserver may serve static files from the webserver_doc_root"); DEFINE_string(webserver_certificate_file, "", "The location of the debug webserver's SSL certificate file, in .pem format. If " "empty, webserver SSL support is not enabled"); DEFINE_string(webserver_authentication_domain, "", "Domain used for debug webserver authentication"); // Mongoose requires a non-null return from the callback to signify successful processing static void* PROCESSING_COMPLETE = reinterpret_cast<void*>(1); static const char* DOC_FOLDER = "/www/"; static const int DOC_FOLDER_LEN = strlen(DOC_FOLDER); // Returns $IMPALA_HOME if set, otherwise /tmp/impala_www const char* GetDefaultDocumentRoot() { stringstream ss; char* impala_home = getenv("IMPALA_HOME"); if (impala_home == NULL) { return ""; // Empty document root means don't serve static files } else { ss << impala_home; } // Deliberate memory leak, but this should be called exactly once. string* str = new string(ss.str()); return str->c_str(); } namespace impala { Webserver::Webserver() : context_(NULL) { http_address_ = MakeNetworkAddress( FLAGS_webserver_interface.empty() ? "0.0.0.0" : FLAGS_webserver_interface, FLAGS_webserver_port); } Webserver::Webserver(const int port) : context_(NULL) { http_address_ = MakeNetworkAddress("0.0.0.0", port); } Webserver::~Webserver() { Stop(); } void Webserver::RootHandler(const Webserver::ArgumentMap& args, stringstream* output) { // path_handler_lock_ already held by MongooseCallback (*output) << "<h2>Version</h2>"; (*output) << "<pre>" << GetVersionString() << "</pre>" << endl; (*output) << "<h2>Hardware Info</h2>"; (*output) << "<pre>"; (*output) << CpuInfo::DebugString(); (*output) << MemInfo::DebugString(); (*output) << DiskInfo::DebugString(); (*output) << "</pre>"; (*output) << "<h2>Status Pages</h2>"; BOOST_FOREACH(const PathHandlerMap::value_type& handler, path_handlers_) { if (handler.second.is_on_nav_bar()) { (*output) << "<a href=\"" << handler.first << "\">" << handler.first << "</a><br/>"; } } } void Webserver::BuildArgumentMap(const string& args, ArgumentMap* output) { vector<string> arg_pairs; split(arg_pairs, args, is_any_of("&")); BOOST_FOREACH(const string& arg_pair, arg_pairs) { vector<string> key_value; split(key_value, arg_pair, is_any_of("=")); if (key_value.empty()) continue; string key; if (!UrlDecode(key_value[0], &key)) continue; string value; if (!UrlDecode((key_value.size() >= 2 ? key_value[1] : ""), &value)) continue; to_lower(key); (*output)[key] = value; } } Status Webserver::Start() { LOG(INFO) << "Starting webserver on " << http_address_; stringstream listening_spec; if (IsWildcardAddress(http_address_.hostname)) { listening_spec << http_address_; } else { string port_as_string = lexical_cast<string>(http_address_.port); listening_spec << ":" << port_as_string; } bool enable_ssl = !FLAGS_webserver_certificate_file.empty(); if (enable_ssl) { LOG(INFO) << "Webserver: Enabling HTTPS support"; // Mongoose makes sockets with 's' suffixes accept SSL traffic only listening_spec << "s"; } string listening_str = listening_spec.str(); vector<const char*> options; if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) { LOG(INFO) << "Document root: " << FLAGS_webserver_doc_root; options.push_back("document_root"); options.push_back(FLAGS_webserver_doc_root.c_str()); } else { LOG(INFO)<< "Document root disabled"; } if (enable_ssl) { options.push_back("ssl_certificate"); options.push_back(FLAGS_webserver_certificate_file.c_str()); } if (!FLAGS_webserver_authentication_domain.empty()) { options.push_back("authentication_domain"); options.push_back(FLAGS_webserver_authentication_domain.c_str()); } options.push_back("listening_ports"); options.push_back(listening_str.c_str()); // Options must be a NULL-terminated list options.push_back(NULL); // mongoose ignores SIGCHLD and we need it to run kinit. This means that since // mongoose does not reap its own children CGI programs must be avoided. // Save the signal handler so we can restore it after mongoose sets it to be ignored. sighandler_t sig_chld = signal(SIGCHLD, SIG_DFL); // To work around not being able to pass member functions as C callbacks, we store a // pointer to this server in the per-server state, and register a static method as the // default callback. That method unpacks the pointer to this and calls the real // callback. context_ = mg_start(&Webserver::MongooseCallbackStatic, reinterpret_cast<void*>(this), &options[0]); // Restore the child signal handler so wait() works properly. signal(SIGCHLD, sig_chld); if (context_ == NULL) { stringstream error_msg; error_msg << "Webserver: Could not start on address " << http_address_; return Status(error_msg.str()); } PathHandlerCallback default_callback = bind<void>(mem_fn(&Webserver::RootHandler), this, _1, _2); RegisterPathHandler("/", default_callback); LOG(INFO) << "Webserver started"; return Status::OK; } void Webserver::Stop() { if (context_ != NULL) mg_stop(context_); } void* Webserver::MongooseCallbackStatic(enum mg_event event, struct mg_connection* connection) { const struct mg_request_info* request_info = mg_get_request_info(connection); Webserver* instance = reinterpret_cast<Webserver*>(mg_get_user_data(connection)); return instance->MongooseCallback(event, connection, request_info); } void* Webserver::MongooseCallback(enum mg_event event, struct mg_connection* connection, const struct mg_request_info* request_info) { if (event == MG_EVENT_LOG) { const char* msg = mg_get_log_message(connection); if (msg != NULL) { LOG(INFO) << "Webserver: " << msg; } return PROCESSING_COMPLETE; } if (event == MG_NEW_REQUEST) { if (!FLAGS_webserver_doc_root.empty() && FLAGS_enable_webserver_doc_root) { if (strncmp(DOC_FOLDER, request_info->uri, DOC_FOLDER_LEN) == 0) { VLOG(2) << "HTTP File access: " << request_info->uri; // Let Mongoose deal with this request; returning NULL will fall through // to the default handler which will serve files. return NULL; } } mutex::scoped_lock lock(path_handlers_lock_); PathHandlerMap::const_iterator it = path_handlers_.find(request_info->uri); if (it == path_handlers_.end()) { mg_printf(connection, "HTTP/1.1 404 Not Found\r\n" "Content-Type: text/plain\r\n\r\n"); mg_printf(connection, "No handler for URI %s\r\n\r\n", request_info->uri); return PROCESSING_COMPLETE; } // Should we render with css styles? bool use_style = true; map<string, string> arguments; if (request_info->query_string != NULL) { BuildArgumentMap(request_info->query_string, &arguments); } if (!it->second.is_styled() || arguments.find("raw") != arguments.end()) { use_style = false; } stringstream output; if (use_style) BootstrapPageHeader(&output); BOOST_FOREACH(const PathHandlerCallback& callback_, it->second.callbacks()) { callback_(arguments, &output); } if (use_style) BootstrapPageFooter(&output); string str = output.str(); // Without styling, render the page as plain text if (arguments.find("raw") != arguments.end()) { mg_printf(connection, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n", (int)str.length()); } else { mg_printf(connection, "HTTP/1.1 200 OK\r\n" "Content-Type: text/html\r\n" "Content-Length: %d\r\n" "\r\n", (int)str.length()); } // Make sure to use mg_write for printing the body; mg_printf truncates at 8kb mg_write(connection, str.c_str(), str.length()); return PROCESSING_COMPLETE; } else { return NULL; } } void Webserver::RegisterPathHandler(const string& path, const PathHandlerCallback& callback, bool is_styled, bool is_on_nav_bar) { mutex::scoped_lock lock(path_handlers_lock_); PathHandlerMap::iterator it = path_handlers_.find(path); if (it == path_handlers_.end()) { it = path_handlers_.insert( make_pair(path, PathHandler(is_styled, is_on_nav_bar))).first; } it->second.AddCallback(callback); } const string PAGE_HEADER = "<!DOCTYPE html>" " <html>" " <head><title>Cloudera Impala</title>" " <link href='www/bootstrap/css/bootstrap.min.css' rel='stylesheet' media='screen'>" " <style>" " body {" " padding-top: 60px; " " }" " </style>" " </head>" " <body>"; static const string PAGE_FOOTER = "</div></body></html>"; static const string NAVIGATION_BAR_PREFIX = "<div class='navbar navbar-inverse navbar-fixed-top'>" " <div class='navbar-inner'>" " <div class='container'>" " <a class='btn btn-navbar' data-toggle='collapse' data-target='.nav-collapse'>" " <span class='icon-bar'></span>" " <span class='icon-bar'></span>" " <span class='icon-bar'></span>" " </a>" " <a class='brand' href='/'>Impala</a>" " <div class='nav-collapse collapse'>" " <ul class='nav'>"; static const string NAVIGATION_BAR_SUFFIX = " </ul>" " </div>" " </div>" " </div>" " </div>" " <div class='container'>"; void Webserver::BootstrapPageHeader(stringstream* output) { (*output) << PAGE_HEADER; (*output) << NAVIGATION_BAR_PREFIX; BOOST_FOREACH(const PathHandlerMap::value_type& handler, path_handlers_) { if (handler.second.is_on_nav_bar()) { (*output) << "<li><a href=\"" << handler.first << "\">" << handler.first << "</a></li>"; } } (*output) << NAVIGATION_BAR_SUFFIX; } void Webserver::BootstrapPageFooter(stringstream* output) { (*output) << PAGE_FOOTER; } } <|endoftext|>
<commit_before><commit_msg>Use after free error due to CanvasRenderinContext2D::State not unregistering callback<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <string> #include "atom/common/platform_util.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "native_mate/dictionary.h" #if defined(OS_WIN) #include "base/win/shortcut.h" #endif namespace mate { template<> struct Converter<base::win::ShortcutOperation> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, base::win::ShortcutOperation* out) { std::string operation; if (!ConvertFromV8(isolate, val, & operation)) return false; if (operation.empty() || operation == "create") *out = base::win::SHORTCUT_CREATE_ALWAYS; else if (operation == "update") *out = base::win::SHORTCUT_UPDATE_EXISTING; else if (operation == "replace") *out = base::win::SHORTCUT_REPLACE_EXISTING; else return false; return true; } }; } // namespace mate namespace { bool OpenExternal( #if defined(OS_WIN) const base::string16& url, #else const GURL& url, #endif mate::Arguments* args) { bool activate = true; if (args->Length() == 2) { mate::Dictionary options; if (args->GetNext(&options)) { options.Get("activate", &activate); } } return platform_util::OpenExternal(url, activate); } #if defined(OS_WIN) bool WriteShortcutLink(const base::FilePath& shortcut_path, mate::Arguments* args) { base::win::ShortcutOperation operation = base::win::SHORTCUT_CREATE_ALWAYS; args->GetNext(&operation); mate::Dictionary options = mate::Dictionary::CreateEmpty(args->isolate()); if (!args->GetNext(&options)) { args->ThrowError(); return false; } base::win::ShortcutProperties properties; base::FilePath path; base::string16 str; int index; if (options.Get("target", &path)) properties.set_target(path); if (options.Get("cwd", &path)) properties.set_working_dir(path); if (options.Get("args", &str)) properties.set_arguments(str); if (options.Get("description", &str)) properties.set_description(str); if (options.Get("icon", &path) && options.Get("iconIndex", &index)) properties.set_icon(path, index); if (options.Get("appUserModelId", &str)) properties.set_app_id(str); return base::win::CreateOrUpdateShortcutLink( shortcut_path, properties, operation); } mate::Dictionary ReadShortcutLink(v8::Isolate* isolate, const base::FilePath& path) { using base::win::ShortcutProperties; mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate); // We have to call ResolveShortcutProperties one by one for each property // because the API doesn't allow us to only get existing properties. base::win::ShortcutProperties properties; if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_TARGET, &properties)) { options.Set("target", properties.target); } else { // No need to continue if it doesn't even have a target. return options; } if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_WORKING_DIR, &properties)) { options.Set("cwd", properties.working_dir); } if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_ARGUMENTS, &properties)) { options.Set("args", properties.arguments); } if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_DESCRIPTION, &properties)) { options.Set("description", properties.description); } if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_ICON, &properties)) { options.Set("icon", properties.icon); options.Set("iconIndex", properties.icon_index); } if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_ICON, &properties)) { options.Set("appUserModelId", properties.app_id); } return options; } #endif void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("showItemInFolder", &platform_util::ShowItemInFolder); dict.SetMethod("openItem", &platform_util::OpenItem); dict.SetMethod("openExternal", &OpenExternal); dict.SetMethod("moveItemToTrash", &platform_util::MoveItemToTrash); dict.SetMethod("beep", &platform_util::Beep); #if defined(OS_WIN) dict.SetMethod("writeShortcutLink", &WriteShortcutLink); dict.SetMethod("readShortcutLink", &ReadShortcutLink); #endif } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_shell, Initialize) <commit_msg>Initialize COM before using the API<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <string> #include "atom/common/platform_util.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "native_mate/dictionary.h" #if defined(OS_WIN) #include "base/win/scoped_com_initializer.h" #include "base/win/shortcut.h" #endif namespace mate { template<> struct Converter<base::win::ShortcutOperation> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, base::win::ShortcutOperation* out) { std::string operation; if (!ConvertFromV8(isolate, val, & operation)) return false; if (operation.empty() || operation == "create") *out = base::win::SHORTCUT_CREATE_ALWAYS; else if (operation == "update") *out = base::win::SHORTCUT_UPDATE_EXISTING; else if (operation == "replace") *out = base::win::SHORTCUT_REPLACE_EXISTING; else return false; return true; } }; } // namespace mate namespace { bool OpenExternal( #if defined(OS_WIN) const base::string16& url, #else const GURL& url, #endif mate::Arguments* args) { bool activate = true; if (args->Length() == 2) { mate::Dictionary options; if (args->GetNext(&options)) { options.Get("activate", &activate); } } return platform_util::OpenExternal(url, activate); } #if defined(OS_WIN) bool WriteShortcutLink(const base::FilePath& shortcut_path, mate::Arguments* args) { base::win::ShortcutOperation operation = base::win::SHORTCUT_CREATE_ALWAYS; args->GetNext(&operation); mate::Dictionary options = mate::Dictionary::CreateEmpty(args->isolate()); if (!args->GetNext(&options)) { args->ThrowError(); return false; } base::win::ShortcutProperties properties; base::FilePath path; base::string16 str; int index; if (options.Get("target", &path)) properties.set_target(path); if (options.Get("cwd", &path)) properties.set_working_dir(path); if (options.Get("args", &str)) properties.set_arguments(str); if (options.Get("description", &str)) properties.set_description(str); if (options.Get("icon", &path) && options.Get("iconIndex", &index)) properties.set_icon(path, index); if (options.Get("appUserModelId", &str)) properties.set_app_id(str); base::win::ScopedCOMInitializer com_initializer; return base::win::CreateOrUpdateShortcutLink( shortcut_path, properties, operation); } mate::Dictionary ReadShortcutLink(v8::Isolate* isolate, const base::FilePath& path) { using base::win::ShortcutProperties; mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate); base::win::ScopedCOMInitializer com_initializer; // We have to call ResolveShortcutProperties one by one for each property // because the API doesn't allow us to only get existing properties. base::win::ShortcutProperties properties; if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_TARGET, &properties)) { options.Set("target", properties.target); } else { // No need to continue if it doesn't even have a target. return options; } if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_WORKING_DIR, &properties)) { options.Set("cwd", properties.working_dir); } if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_ARGUMENTS, &properties)) { options.Set("args", properties.arguments); } if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_DESCRIPTION, &properties)) { options.Set("description", properties.description); } if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_ICON, &properties)) { options.Set("icon", properties.icon); options.Set("iconIndex", properties.icon_index); } if (base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_ICON, &properties)) { options.Set("appUserModelId", properties.app_id); } return options; } #endif void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("showItemInFolder", &platform_util::ShowItemInFolder); dict.SetMethod("openItem", &platform_util::OpenItem); dict.SetMethod("openExternal", &OpenExternal); dict.SetMethod("moveItemToTrash", &platform_util::MoveItemToTrash); dict.SetMethod("beep", &platform_util::Beep); #if defined(OS_WIN) dict.SetMethod("writeShortcutLink", &WriteShortcutLink); dict.SetMethod("readShortcutLink", &ReadShortcutLink); #endif } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_shell, Initialize) <|endoftext|>
<commit_before>#ifndef IMPLSTORE_HPP # define IMPLSTORE_HPP # pragma once #include <cassert> #include <cstddef> #include <type_traits> #include <utility> namespace generic { template <class U, ::std::size_t N = 64> class implstore { public: static constexpr ::std::size_t const buffer_size = N; using value_type = U; template <typename ...A, typename = typename ::std::enable_if<::std::is_constructible<U, A...>{}>::type> implstore(A&& ...args) { static_assert(sizeof(U) <= sizeof(store_), "impl too large"); new (static_cast<void*>(&store_)) U(::std::forward<A>(args)...); } ~implstore() { get()->~U(); } implstore(implstore const& other) : implstore(other, nullptr) { } implstore(implstore&& other) : implstore(::std::move(other), nullptr) { } template <::std::size_t M, typename K = U> implstore(implstore<U, M> const& other, typename ::std::enable_if< ::std::is_copy_constructible<K>{} >::type* = nullptr) { new (static_cast<void*>(&store_)) U(*other); } template <::std::size_t M, typename K = U> implstore(implstore<U, M>&& other, typename ::std::enable_if< ::std::is_move_constructible<K>{} >::type* = nullptr) { new (static_cast<void*>(&store_)) U(::std::move(*other)); } template <::std::size_t M, typename K = U, typename = typename ::std::enable_if< ::std::is_copy_assignable<K>{} >::type > implstore& operator=(implstore<U, M> const& rhs) { assert(this != &rhs); **this = *rhs; return *this; } template <::std::size_t M, typename K = U, typename = typename ::std::enable_if< ::std::is_move_assignable<K>{} >::type > implstore& operator=(implstore<U, M>&& rhs) { assert(this != &rhs); **this = ::std::move(*rhs); return *this; } U const* operator->() const noexcept { return reinterpret_cast<U const*>(&store_); } U* operator->() noexcept { return reinterpret_cast<U*>(&store_); } U const* get() const noexcept { return reinterpret_cast<U const*>(&store_); } U* get() noexcept { return reinterpret_cast<U*>(&store_); } U const& operator*() const noexcept { return *reinterpret_cast<U const*>(&store_); } U& operator*() noexcept { return *reinterpret_cast<U*>(&store_); } private: typename ::std::aligned_storage<N>::type store_; }; } #endif // IMPLSTORE_HPP <commit_msg>some fixes<commit_after>#ifndef IMPLSTORE_HPP # define IMPLSTORE_HPP # pragma once #include <cassert> #include <cstddef> #include <type_traits> #include <utility> namespace generic { template <class U, ::std::size_t N = 64> class implstore { public: static constexpr ::std::size_t const buffer_size = N; using value_type = U; template <typename ...A, typename = typename ::std::enable_if<::std::is_constructible<U, A...>{}>::type > implstore(A&& ...args) { static_assert(sizeof(U) <= sizeof(store_), "impl too large"); new (static_cast<void*>(&store_)) U(::std::forward<A>(args)...); } ~implstore() { get()->~U(); } implstore(implstore const& other) : implstore(other, nullptr) { } implstore(implstore&& other) : implstore(::std::move(other), nullptr) { } template <::std::size_t M, typename K = U> implstore(implstore<U, M> const& other, typename ::std::enable_if< ::std::is_copy_constructible<K>{} >::type* = nullptr) { new (static_cast<void*>(&store_)) U(*other); } template <::std::size_t M, typename K = U> implstore(implstore<U, M>&& other, typename ::std::enable_if< ::std::is_move_constructible<K>{} >::type* = nullptr) { new (static_cast<void*>(&store_)) U(::std::move(*other)); } template <::std::size_t M, typename K = U, typename = typename ::std::enable_if< ::std::is_copy_assignable<K>{} >::type > implstore& operator=(implstore<U, M> const& rhs) { assert(this != &rhs); **this = *rhs; return *this; } template <::std::size_t M, typename K = U, typename = typename ::std::enable_if< ::std::is_move_assignable<K>{} >::type > implstore& operator=(implstore<U, M>&& rhs) { assert(this != &rhs); **this = ::std::move(*rhs); return *this; } U const* operator->() const noexcept { return reinterpret_cast<U const*>(&store_); } U* operator->() noexcept { return reinterpret_cast<U*>(&store_); } U const* get() const noexcept { return reinterpret_cast<U const*>(&store_); } U* get() noexcept { return reinterpret_cast<U*>(&store_); } U const& operator*() const noexcept { return *reinterpret_cast<U const*>(&store_); } U& operator*() noexcept { return *reinterpret_cast<U*>(&store_); } private: typename ::std::aligned_storage<N>::type store_; }; } #endif // IMPLSTORE_HPP <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <string> #include "atom/common/platform_util.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "native_mate/dictionary.h" #if defined(OS_WIN) #include "base/win/scoped_com_initializer.h" #include "base/win/shortcut.h" #endif namespace mate { template<> struct Converter<base::win::ShortcutOperation> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, base::win::ShortcutOperation* out) { std::string operation; if (!ConvertFromV8(isolate, val, & operation)) return false; if (operation.empty() || operation == "create") *out = base::win::SHORTCUT_CREATE_ALWAYS; else if (operation == "update") *out = base::win::SHORTCUT_UPDATE_EXISTING; else if (operation == "replace") *out = base::win::SHORTCUT_REPLACE_EXISTING; else return false; return true; } }; } // namespace mate namespace { bool OpenExternal( #if defined(OS_WIN) const base::string16& url, #else const GURL& url, #endif mate::Arguments* args) { bool activate = true; if (args->Length() == 2) { mate::Dictionary options; if (args->GetNext(&options)) { options.Get("activate", &activate); } } return platform_util::OpenExternal(url, activate); } #if defined(OS_WIN) bool WriteShortcutLink(const base::FilePath& shortcut_path, mate::Arguments* args) { base::win::ShortcutOperation operation = base::win::SHORTCUT_CREATE_ALWAYS; args->GetNext(&operation); mate::Dictionary options = mate::Dictionary::CreateEmpty(args->isolate()); if (!args->GetNext(&options)) { args->ThrowError(); return false; } base::win::ShortcutProperties properties; base::FilePath path; base::string16 str; int index; if (options.Get("target", &path)) properties.set_target(path); if (options.Get("cwd", &path)) properties.set_working_dir(path); if (options.Get("args", &str)) properties.set_arguments(str); if (options.Get("description", &str)) properties.set_description(str); if (options.Get("icon", &path) && options.Get("iconIndex", &index)) properties.set_icon(path, index); if (options.Get("appUserModelId", &str)) properties.set_app_id(str); base::win::ScopedCOMInitializer com_initializer; return base::win::CreateOrUpdateShortcutLink( shortcut_path, properties, operation); } mate::Dictionary ReadShortcutLink(v8::Isolate* isolate, const base::FilePath& path) { using base::win::ShortcutProperties; mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate); base::win::ScopedCOMInitializer com_initializer; base::win::ShortcutProperties properties; if (!base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_ALL, &properties)) { return options; } options.Set("target", properties.target); options.Set("cwd", properties.working_dir); options.Set("args", properties.arguments); options.Set("description", properties.description); options.Set("icon", properties.icon); options.Set("iconIndex", properties.icon_index); options.Set("appUserModelId", properties.app_id); return options; } #endif void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("showItemInFolder", &platform_util::ShowItemInFolder); dict.SetMethod("openItem", &platform_util::OpenItem); dict.SetMethod("openExternal", &OpenExternal); dict.SetMethod("moveItemToTrash", &platform_util::MoveItemToTrash); dict.SetMethod("beep", &platform_util::Beep); #if defined(OS_WIN) dict.SetMethod("writeShortcutLink", &WriteShortcutLink); dict.SetMethod("readShortcutLink", &ReadShortcutLink); #endif } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_shell, Initialize) <commit_msg>Throw exception when ReadShortcutLink failed<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <string> #include "atom/common/platform_util.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "native_mate/dictionary.h" #if defined(OS_WIN) #include "base/win/scoped_com_initializer.h" #include "base/win/shortcut.h" #endif namespace mate { template<> struct Converter<base::win::ShortcutOperation> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, base::win::ShortcutOperation* out) { std::string operation; if (!ConvertFromV8(isolate, val, & operation)) return false; if (operation.empty() || operation == "create") *out = base::win::SHORTCUT_CREATE_ALWAYS; else if (operation == "update") *out = base::win::SHORTCUT_UPDATE_EXISTING; else if (operation == "replace") *out = base::win::SHORTCUT_REPLACE_EXISTING; else return false; return true; } }; } // namespace mate namespace { bool OpenExternal( #if defined(OS_WIN) const base::string16& url, #else const GURL& url, #endif mate::Arguments* args) { bool activate = true; if (args->Length() == 2) { mate::Dictionary options; if (args->GetNext(&options)) { options.Get("activate", &activate); } } return platform_util::OpenExternal(url, activate); } #if defined(OS_WIN) bool WriteShortcutLink(const base::FilePath& shortcut_path, mate::Arguments* args) { base::win::ShortcutOperation operation = base::win::SHORTCUT_CREATE_ALWAYS; args->GetNext(&operation); mate::Dictionary options = mate::Dictionary::CreateEmpty(args->isolate()); if (!args->GetNext(&options)) { args->ThrowError(); return false; } base::win::ShortcutProperties properties; base::FilePath path; base::string16 str; int index; if (options.Get("target", &path)) properties.set_target(path); if (options.Get("cwd", &path)) properties.set_working_dir(path); if (options.Get("args", &str)) properties.set_arguments(str); if (options.Get("description", &str)) properties.set_description(str); if (options.Get("icon", &path) && options.Get("iconIndex", &index)) properties.set_icon(path, index); if (options.Get("appUserModelId", &str)) properties.set_app_id(str); base::win::ScopedCOMInitializer com_initializer; return base::win::CreateOrUpdateShortcutLink( shortcut_path, properties, operation); } v8::Local<v8::Value> ReadShortcutLink(mate::Arguments* args, const base::FilePath& path) { using base::win::ShortcutProperties; mate::Dictionary options = mate::Dictionary::CreateEmpty(args->isolate()); base::win::ScopedCOMInitializer com_initializer; base::win::ShortcutProperties properties; if (!base::win::ResolveShortcutProperties( path, ShortcutProperties::PROPERTIES_ALL, &properties)) { args->ThrowError("Failed to read shortcut link"); return v8::Null(args->isolate()); } options.Set("target", properties.target); options.Set("cwd", properties.working_dir); options.Set("args", properties.arguments); options.Set("description", properties.description); options.Set("icon", properties.icon); options.Set("iconIndex", properties.icon_index); options.Set("appUserModelId", properties.app_id); return options.GetHandle(); } #endif void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("showItemInFolder", &platform_util::ShowItemInFolder); dict.SetMethod("openItem", &platform_util::OpenItem); dict.SetMethod("openExternal", &OpenExternal); dict.SetMethod("moveItemToTrash", &platform_util::MoveItemToTrash); dict.SetMethod("beep", &platform_util::Beep); #if defined(OS_WIN) dict.SetMethod("writeShortcutLink", &WriteShortcutLink); dict.SetMethod("readShortcutLink", &ReadShortcutLink); #endif } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_shell, Initialize) <|endoftext|>
<commit_before>#include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <mixerr.h> #include <Instrument.h> #include <notetags.h> #include <rt.h> #include <rtdefs.h> #include "MIXN.h" #include <ugens.h> #include "funcs.h" extern int resetval; MIXN::MIXN() : Instrument() { in = NULL; my_aud_locs = aud_locs; my_spk_locs = spk_locs; my_ratefs = ratefs; my_num_rates = num_rates; my_cur_rate = cur_rate; my_cur_point = cur_point; my_num_points = num_points; my_out_chan_amp = new float[MAXBUS]; my_tot_dist = tot_dist; my_n_spk = n_spk; my_use_path = use_path; my_use_rates = use_rates; my_cycle = cycle; } MIXN::~MIXN() { delete [] in; } int MIXN::init(double p[], int n_args) { // p0 = outsk // p1 = insk // p2 = duration (-endtime) // p3 = inchan // p4-n = channel amps // we're (still) stashing the setline info in gen table 1 int i; float dur; if (p[2] < 0.0) p[2] = -p[2] - p[1]; outskip = p[0]; inskip = p[1]; dur = p[2]; if (rtsetoutput(outskip, dur, this) != 0) return DONT_SCHEDULE; if (rtsetinput(inskip, this) != 0) return DONT_SCHEDULE; inchan = p[3]; amp = p[4]; amp_count = 0; for (i=0; i < outputchans; i++) { my_out_chan_amp[i] = 0.0; } // Make sure this works with trajectories, etc... for (i = 0; i < n_args-5; i++) { my_out_chan_amp[i] = p[i+5]; if (i > outputchans) { fprintf(stderr, "You wanted output channel %d, but have only " "specified %d output channels\n", i, outputchans); exit(-1); } } amp_count = i; // Watch out for this one amptable = floc(1); if (amptable) { int amplen = fsize(1); tableset(SR, dur, amplen, tabs); } else printf("Setting phrase curve to all 1's\n"); skip = (int)(SR/(float)resetval); // how often to update amp curve, default 200/sec. // if (inchan >= inputChannels()) // warn("MIXN","You are requesting channel %2.f of a %d channel file.\n",inchan+1,inputChannels()); return(this->mytag); } int MIXN::configure() { in = new float [RTBUFSAMPS * inputChannels()]; return 0; } int MIXN::run() { int i,j,k,outframes; float aamp; int branch; float *outp; float t_out_amp[8]; /* FIXME make this more flexible later */ float t_dur; float sig; int finalsamp; aamp = 0; aud_locs = my_aud_locs; spk_locs = my_spk_locs; ratefs = my_ratefs; num_rates = my_num_rates; cur_rate = my_cur_rate; cur_point = my_cur_point; num_points = my_num_points; out_chan_amp = my_out_chan_amp; tot_dist = my_tot_dist; n_spk = my_n_spk; use_path = my_use_path; use_rates = my_use_rates; cycle = my_cycle; outframes = framesToRun()*inputChannels(); rtgetin(in, this, outframes); outp = outbuf; // Use private pointer to Inst::outbuf branch = 0; for (i = 0; i < outframes; i += inputChannels()) { if (--branch < 0) { #ifdef RTUPDATE if (tags_on) { for (j=0;j<8;j++) { t_out_amp[j] = rtupdate(this->mytag,j+4); if (t_out_amp[j] != NOPUPDATE) { out_chan_amp[j] = t_out_amp[j]; } } } #endif if (amptable) aamp = tablei(cursamp, amptable, tabs) * amp; else aamp = amp; if (use_path) { update_amps(cursamp); } branch = skip; } if (inchan < inputChannels()) sig = in[i + (int)inchan] * aamp; for (j = 0; j < outputchans; j++) { outp[j] = sig * out_chan_amp[j]; } outp += outputchans; cursamp++; } my_cur_rate = cur_rate; my_cur_point = cur_point; return i; } Instrument* makeMIXN() { MIXN *inst; inst = new MIXN(); inst->set_bus_config("MIXN"); #ifdef RTUPDATE inst->set_instnum("MIXN"); #endif return inst; } void rtprofile() { RT_INTRO("MIXN",makeMIXN); } <commit_msg>outputchans -> outputChannels();<commit_after>#include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <mixerr.h> #include <Instrument.h> #include <notetags.h> #include <rt.h> #include <rtdefs.h> #include "MIXN.h" #include <ugens.h> #include "funcs.h" extern int resetval; MIXN::MIXN() : Instrument() { in = NULL; my_aud_locs = aud_locs; my_spk_locs = spk_locs; my_ratefs = ratefs; my_num_rates = num_rates; my_cur_rate = cur_rate; my_cur_point = cur_point; my_num_points = num_points; my_out_chan_amp = new float[MAXBUS]; my_tot_dist = tot_dist; my_n_spk = n_spk; my_use_path = use_path; my_use_rates = use_rates; my_cycle = cycle; } MIXN::~MIXN() { delete [] in; } int MIXN::init(double p[], int n_args) { // p0 = outsk // p1 = insk // p2 = duration (-endtime) // p3 = inchan // p4-n = channel amps // we're (still) stashing the setline info in gen table 1 int i; float dur; if (p[2] < 0.0) p[2] = -p[2] - p[1]; outskip = p[0]; inskip = p[1]; dur = p[2]; if (rtsetoutput(outskip, dur, this) != 0) return DONT_SCHEDULE; if (rtsetinput(inskip, this) != 0) return DONT_SCHEDULE; inchan = p[3]; amp = p[4]; amp_count = 0; outputchans = outputChannels(); for (i=0; i < outputchans; i++) { my_out_chan_amp[i] = 0.0; } // Make sure this works with trajectories, etc... for (i = 0; i < n_args-5; i++) { my_out_chan_amp[i] = p[i+5]; if (i > outputchans) { fprintf(stderr, "You wanted output channel %d, but have only " "specified %d output channels\n", i, outputchans); exit(-1); } } amp_count = i; // Watch out for this one amptable = floc(1); if (amptable) { int amplen = fsize(1); tableset(SR, dur, amplen, tabs); } else printf("Setting phrase curve to all 1's\n"); skip = (int)(SR/(float)resetval); // how often to update amp curve, default 200/sec. // if (inchan >= inputChannels()) // warn("MIXN","You are requesting channel %2.f of a %d channel file.\n",inchan+1,inputChannels()); return(this->mytag); } int MIXN::configure() { in = new float [RTBUFSAMPS * inputChannels()]; return 0; } int MIXN::run() { int i,j,k,outframes; float aamp; int branch; float *outp; float t_out_amp[8]; /* FIXME make this more flexible later */ float t_dur; float sig; int finalsamp; aamp = 0; aud_locs = my_aud_locs; spk_locs = my_spk_locs; ratefs = my_ratefs; num_rates = my_num_rates; cur_rate = my_cur_rate; cur_point = my_cur_point; num_points = my_num_points; out_chan_amp = my_out_chan_amp; tot_dist = my_tot_dist; n_spk = my_n_spk; use_path = my_use_path; use_rates = my_use_rates; cycle = my_cycle; outframes = framesToRun()*inputChannels(); rtgetin(in, this, outframes); outp = outbuf; // Use private pointer to Inst::outbuf branch = 0; for (i = 0; i < outframes; i += inputChannels()) { if (--branch < 0) { #ifdef RTUPDATE if (tags_on) { for (j=0;j<8;j++) { t_out_amp[j] = rtupdate(this->mytag,j+4); if (t_out_amp[j] != NOPUPDATE) { out_chan_amp[j] = t_out_amp[j]; } } } #endif if (amptable) aamp = tablei(cursamp, amptable, tabs) * amp; else aamp = amp; if (use_path) { update_amps(cursamp); } branch = skip; } if (inchan < inputChannels()) sig = in[i + (int)inchan] * aamp; for (j = 0; j < outputchans; j++) { outp[j] = sig * out_chan_amp[j]; } outp += outputchans; cursamp++; } my_cur_rate = cur_rate; my_cur_point = cur_point; return i; } Instrument* makeMIXN() { MIXN *inst; inst = new MIXN(); inst->set_bus_config("MIXN"); #ifdef RTUPDATE inst->set_instnum("MIXN"); #endif return inst; } void rtprofile() { RT_INTRO("MIXN",makeMIXN); } <|endoftext|>
<commit_before>/*! \file system.cpp \brief System management implementation \author Ivan Shynkarenka \date 06.07.2015 \copyright MIT License */ #include "benchmark/system.h" #if defined(__APPLE__) #include <mach/mach.h> #include <mach/mach_time.h> #include <sys/sysctl.h> #include <math.h> #include <pthread.h> #elif defined(unix) || defined(__unix) || defined(__unix__) #include <sys/sysinfo.h> #include <pthread.h> #include <unistd.h> #include <fstream> #include <regex> #if defined(__CYGWIN__) #include <windows.h> #endif #elif defined(_WIN32) || defined(_WIN64) #include <windows.h> #include <memory> #endif namespace CppBenchmark { //! @cond namespace Internals { #if defined(__APPLE__) uint32_t ceilLog2(uint32_t x) { uint32_t result = 0; --x; while (x > 0) { ++result; x >>= 1; } return result; } // This function returns the rational number inside the given interval with // the smallest denominator (and smallest numerator breaks ties; correctness // proof neglects floating-point errors). mach_timebase_info_data_t bestFrac(double a, double b) { if (floor(a) < floor(b)) { mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 }; return rv; } double m = floor(a); mach_timebase_info_data_t next = bestFrac(1 / (b - m), 1 / (a - m)); mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer }; return rv; } // This is just less than the smallest thing we can multiply numer by without // overflowing. ceilLog2(numer) = 64 - number of leading zeros of numer uint64_t getExpressibleSpan(uint32_t numer, uint32_t denom) { uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - ceilLog2(numer))) - 1; return maxDiffWithoutOverflow * numer / denom; } // The clock may run up to 0.1% faster or slower than the "exact" tick count. // However, although the bound on the error is the same as for the pragmatic // answer, the error is actually minimized over the given accuracy bound. uint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb) { tb.numer = 0; tb.denom = 1; kern_return_t mtiStatus = mach_timebase_info(&tb); if (mtiStatus != KERN_SUCCESS) return 0; double frac = (double)tb.numer / tb.denom; uint64_t spanTarget = 315360000000000000llu; if (getExpressibleSpan(tb.numer, tb.denom) >= spanTarget) return 0; for (double errorTarget = 1 / 1024.0; errorTarget > 0.000001;) { mach_timebase_info_data_t newFrac = bestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac); if (getExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget) break; tb = newFrac; errorTarget = fabs((double)tb.numer / tb.denom - frac) / frac / 8; } return mach_absolute_time(); } #endif #if defined(_WIN32) || defined(_WIN64) // Helper function to count set bits in the processor mask DWORD CountSetBits(ULONG_PTR pBitMask) { DWORD dwLeftShift = sizeof(ULONG_PTR) * 8 - 1; DWORD dwBitSetCount = 0; ULONG_PTR pBitTest = (ULONG_PTR)1 << dwLeftShift; for (DWORD i = 0; i <= dwLeftShift; ++i) { dwBitSetCount += ((pBitMask & pBitTest) ? 1 : 0); pBitTest /= 2; } return dwBitSetCount; } #endif } // namespace Internals //! @endcond std::string System::CpuArchitecture() { #if defined(__APPLE__) char result[1024]; size_t size = sizeof(result); if (sysctlbyname("machdep.cpu.brand_string", result, &size, nullptr, 0) == 0) return result; return "<unknown>"; #elif defined(unix) || defined(__unix) || defined(__unix__) static std::regex pattern("model name(.*): (.*)"); std::string line; std::ifstream stream("/proc/cpuinfo"); while (getline(stream, line)) { std::smatch matches; if (std::regex_match(line, matches, pattern)) return matches[2]; } return "<unknown>"; #elif defined(_WIN32) || defined(_WIN64) HKEY hKeyProcessor; LONG lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKeyProcessor); if (lError != ERROR_SUCCESS) return "<unknown>"; // Smart resource deleter pattern auto clear = [](HKEY hKey) { RegCloseKey(hKey); }; auto key = std::unique_ptr<std::remove_pointer<HKEY>::type, decltype(clear)>(hKeyProcessor, clear); CHAR pBuffer[_MAX_PATH] = { 0 }; DWORD dwBufferSize = sizeof(pBuffer); lError = RegQueryValueExA(key.get(), "ProcessorNameString", nullptr, nullptr, (LPBYTE)pBuffer, &dwBufferSize); if (lError != ERROR_SUCCESS) return "<unknown>"; return std::string(pBuffer); #else #error Unsupported platform #endif } int System::CpuLogicalCores() { return CpuTotalCores().first; } int System::CpuPhysicalCores() { return CpuTotalCores().second; } std::pair<int, int> System::CpuTotalCores() { #if defined(__APPLE__) int logical = 0; size_t logical_size = sizeof(logical); if (sysctlbyname("hw.logicalcpu", &logical, &logical_size, nullptr, 0) != 0) logical = -1; int physical = 0; size_t physical_size = sizeof(physical); if (sysctlbyname("hw.physicalcpu", &physical, &physical_size, nullptr, 0) != 0) physical = -1; return std::make_pair(logical, physical); #elif defined(unix) || defined(__unix) || defined(__unix__) long processors = sysconf(_SC_NPROCESSORS_ONLN); return std::make_pair(processors, processors); #elif defined(_WIN32) || defined(_WIN64) BOOL allocated = FALSE; PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pBuffer = nullptr; DWORD dwLength = 0; while (!allocated) { DWORD dwResult = GetLogicalProcessorInformation(pBuffer, &dwLength); if (dwResult == FALSE) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { if (pBuffer != nullptr) free(pBuffer); pBuffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(dwLength); if (pBuffer == nullptr) return std::make_pair(-1, -1); } else return std::make_pair(-1, -1); } else allocated = TRUE; } std::pair<int, int> result(0, 0); PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pCurrent = pBuffer; DWORD dwOffset = 0; while (dwOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= dwLength) { switch (pCurrent->Relationship) { case RelationProcessorCore: result.first += Internals::CountSetBits(pCurrent->ProcessorMask); result.second += 1; break; case RelationNumaNode: case RelationCache: case RelationProcessorPackage: break; default: return std::make_pair(-1, -1); } dwOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); pCurrent++; } free(pBuffer); return result; #else #error Unsupported platform #endif } int64_t System::CpuClockSpeed() { #if defined(__APPLE__) uint64_t frequency = 0; size_t size = sizeof(frequency); if (sysctlbyname("hw.cpufrequency", &frequency, &size, nullptr, 0) == 0) return frequency; return -1; #elif defined(unix) || defined(__unix) || defined(__unix__) static std::regex pattern("cpu MHz(.*): (.*)"); std::string line; std::ifstream stream("/proc/cpuinfo"); while (getline(stream, line)) { std::smatch matches; if (std::regex_match(line, matches, pattern)) return (int64_t)(atof(matches[2].str().c_str()) * 1000 * 1000); } return -1; #elif defined(_WIN32) || defined(_WIN64) HKEY hKeyProcessor; long lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKeyProcessor); if (lError != ERROR_SUCCESS) return -1; // Smart resource deleter pattern auto clear = [](HKEY hKey) { RegCloseKey(hKey); }; auto key = std::unique_ptr<std::remove_pointer<HKEY>::type, decltype(clear)>(hKeyProcessor, clear); DWORD dwMHz = 0; DWORD dwBufferSize = sizeof(DWORD); lError = RegQueryValueExA(key.get(), "~MHz", nullptr, nullptr, (LPBYTE)&dwMHz, &dwBufferSize); if (lError != ERROR_SUCCESS) return -1; return dwMHz * 1000 * 1000; #else #error Unsupported platform #endif } bool System::CpuHyperThreading() { std::pair<int, int> cores = CpuTotalCores(); return (cores.first != cores.second); } int64_t System::RamTotal() { #if defined(__APPLE__) int64_t memsize = 0; size_t size = sizeof(memsize); if (sysctlbyname("hw.memsize", &memsize, &size, nullptr, 0) == 0) return memsize; return -1; #elif defined(linux) || defined(__linux) || defined(__linux__) struct sysinfo si; return (sysinfo(&si) == 0) ? si.totalram : -1; #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx(&status); return status.ullTotalPhys; #else #error Unsupported platform #endif } int64_t System::RamFree() { #if defined(__APPLE__) mach_port_t host_port = mach_host_self(); if (host_port == MACH_PORT_NULL) return -1; vm_size_t page_size = 0; host_page_size(host_port, &page_size); vm_statistics_data_t vmstat; mach_msg_type_number_t count = HOST_VM_INFO_COUNT; kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat, &count); if (kernReturn != KERN_SUCCESS) return -1; int64_t used_mem = (vmstat.active_count + vmstat.inactive_count + vmstat.wire_count) * page_size; int64_t free_mem = vmstat.free_count * page_size; return free_mem; #elif defined(linux) || defined(__linux) || defined(__linux__) struct sysinfo si; return (sysinfo(&si) == 0) ? si.freeram : -1; #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx(&status); return status.ullAvailPhys; #else #error Unsupported platform #endif } uint64_t System::CurrentThreadId() { #if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__) return (uint64_t)pthread_self(); #elif defined(_WIN32) || defined(_WIN64) return GetCurrentThreadId(); #else #error Unsupported platform #endif } uint64_t System::Timestamp() { #if defined(__APPLE__) static mach_timebase_info_data_t info; static uint64_t bias = Internals::PrepareTimebaseInfo(info); return (mach_absolute_time() - bias) * info.numer / info.denom; #elif defined(unix) || defined(__unix) || defined(__unix__) struct timespec timestamp; clock_gettime(CLOCK_MONOTONIC, &timestamp); return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec; #elif defined(_WIN32) || defined(_WIN64) static uint64_t offset = 0; static LARGE_INTEGER first{0}; static LARGE_INTEGER frequency{0}; static bool initialized = false; static bool qpc = true; if (!initialized) { // Calculate timestamp offset FILETIME timestamp; GetSystemTimePreciseAsFileTime(&timestamp); ULARGE_INTEGER result; result.LowPart = timestamp.dwLowDateTime; result.HighPart = timestamp.dwHighDateTime; // Convert 01.01.1601 to 01.01.1970 result.QuadPart -= 116444736000000000ll; offset = result.QuadPart * 100; // Setup performance counter qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first); initialized = true; } if (qpc) { LARGE_INTEGER timestamp{0}; QueryPerformanceCounter(&timestamp); timestamp.QuadPart -= first.QuadPart; return offset + ((timestamp.QuadPart * 1000 * 1000 * 1000) / frequency.QuadPart); } else return offset; #else #error Unsupported platform #endif } } // namespace CppBenchmark <commit_msg>Fix linux build<commit_after>/*! \file system.cpp \brief System management implementation \author Ivan Shynkarenka \date 06.07.2015 \copyright MIT License */ #include "benchmark/system.h" #if defined(__APPLE__) #include <mach/mach.h> #include <mach/mach_time.h> #include <sys/sysctl.h> #include <math.h> #include <pthread.h> #elif defined(unix) || defined(__unix) || defined(__unix__) #include <sys/sysinfo.h> #include <pthread.h> #include <fstream> #include <regex> #if defined(__CYGWIN__) #include <windows.h> #endif #elif defined(_WIN32) || defined(_WIN64) #include <windows.h> #include <memory> #endif namespace CppBenchmark { //! @cond namespace Internals { #if defined(__APPLE__) uint32_t ceilLog2(uint32_t x) { uint32_t result = 0; --x; while (x > 0) { ++result; x >>= 1; } return result; } // This function returns the rational number inside the given interval with // the smallest denominator (and smallest numerator breaks ties; correctness // proof neglects floating-point errors). mach_timebase_info_data_t bestFrac(double a, double b) { if (floor(a) < floor(b)) { mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 }; return rv; } double m = floor(a); mach_timebase_info_data_t next = bestFrac(1 / (b - m), 1 / (a - m)); mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer }; return rv; } // This is just less than the smallest thing we can multiply numer by without // overflowing. ceilLog2(numer) = 64 - number of leading zeros of numer uint64_t getExpressibleSpan(uint32_t numer, uint32_t denom) { uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - ceilLog2(numer))) - 1; return maxDiffWithoutOverflow * numer / denom; } // The clock may run up to 0.1% faster or slower than the "exact" tick count. // However, although the bound on the error is the same as for the pragmatic // answer, the error is actually minimized over the given accuracy bound. uint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb) { tb.numer = 0; tb.denom = 1; kern_return_t mtiStatus = mach_timebase_info(&tb); if (mtiStatus != KERN_SUCCESS) return 0; double frac = (double)tb.numer / tb.denom; uint64_t spanTarget = 315360000000000000llu; if (getExpressibleSpan(tb.numer, tb.denom) >= spanTarget) return 0; for (double errorTarget = 1 / 1024.0; errorTarget > 0.000001;) { mach_timebase_info_data_t newFrac = bestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac); if (getExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget) break; tb = newFrac; errorTarget = fabs((double)tb.numer / tb.denom - frac) / frac / 8; } return mach_absolute_time(); } #endif #if defined(_WIN32) || defined(_WIN64) // Helper function to count set bits in the processor mask DWORD CountSetBits(ULONG_PTR pBitMask) { DWORD dwLeftShift = sizeof(ULONG_PTR) * 8 - 1; DWORD dwBitSetCount = 0; ULONG_PTR pBitTest = (ULONG_PTR)1 << dwLeftShift; for (DWORD i = 0; i <= dwLeftShift; ++i) { dwBitSetCount += ((pBitMask & pBitTest) ? 1 : 0); pBitTest /= 2; } return dwBitSetCount; } #endif } // namespace Internals //! @endcond std::string System::CpuArchitecture() { #if defined(__APPLE__) char result[1024]; size_t size = sizeof(result); if (sysctlbyname("machdep.cpu.brand_string", result, &size, nullptr, 0) == 0) return result; return "<unknown>"; #elif defined(unix) || defined(__unix) || defined(__unix__) static std::regex pattern("model name(.*): (.*)"); std::string line; std::ifstream stream("/proc/cpuinfo"); while (getline(stream, line)) { std::smatch matches; if (std::regex_match(line, matches, pattern)) return matches[2]; } return "<unknown>"; #elif defined(_WIN32) || defined(_WIN64) HKEY hKeyProcessor; LONG lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKeyProcessor); if (lError != ERROR_SUCCESS) return "<unknown>"; // Smart resource deleter pattern auto clear = [](HKEY hKey) { RegCloseKey(hKey); }; auto key = std::unique_ptr<std::remove_pointer<HKEY>::type, decltype(clear)>(hKeyProcessor, clear); CHAR pBuffer[_MAX_PATH] = { 0 }; DWORD dwBufferSize = sizeof(pBuffer); lError = RegQueryValueExA(key.get(), "ProcessorNameString", nullptr, nullptr, (LPBYTE)pBuffer, &dwBufferSize); if (lError != ERROR_SUCCESS) return "<unknown>"; return std::string(pBuffer); #else #error Unsupported platform #endif } int System::CpuLogicalCores() { return CpuTotalCores().first; } int System::CpuPhysicalCores() { return CpuTotalCores().second; } std::pair<int, int> System::CpuTotalCores() { #if defined(__APPLE__) int logical = 0; size_t logical_size = sizeof(logical); if (sysctlbyname("hw.logicalcpu", &logical, &logical_size, nullptr, 0) != 0) logical = -1; int physical = 0; size_t physical_size = sizeof(physical); if (sysctlbyname("hw.physicalcpu", &physical, &physical_size, nullptr, 0) != 0) physical = -1; return std::make_pair(logical, physical); #elif defined(unix) || defined(__unix) || defined(__unix__) long processors = sysconf(_SC_NPROCESSORS_ONLN); return std::make_pair(processors, processors); #elif defined(_WIN32) || defined(_WIN64) BOOL allocated = FALSE; PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pBuffer = nullptr; DWORD dwLength = 0; while (!allocated) { DWORD dwResult = GetLogicalProcessorInformation(pBuffer, &dwLength); if (dwResult == FALSE) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { if (pBuffer != nullptr) free(pBuffer); pBuffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(dwLength); if (pBuffer == nullptr) return std::make_pair(-1, -1); } else return std::make_pair(-1, -1); } else allocated = TRUE; } std::pair<int, int> result(0, 0); PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pCurrent = pBuffer; DWORD dwOffset = 0; while (dwOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= dwLength) { switch (pCurrent->Relationship) { case RelationProcessorCore: result.first += Internals::CountSetBits(pCurrent->ProcessorMask); result.second += 1; break; case RelationNumaNode: case RelationCache: case RelationProcessorPackage: break; default: return std::make_pair(-1, -1); } dwOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); pCurrent++; } free(pBuffer); return result; #else #error Unsupported platform #endif } int64_t System::CpuClockSpeed() { #if defined(__APPLE__) uint64_t frequency = 0; size_t size = sizeof(frequency); if (sysctlbyname("hw.cpufrequency", &frequency, &size, nullptr, 0) == 0) return frequency; return -1; #elif defined(unix) || defined(__unix) || defined(__unix__) static std::regex pattern("cpu MHz(.*): (.*)"); std::string line; std::ifstream stream("/proc/cpuinfo"); while (getline(stream, line)) { std::smatch matches; if (std::regex_match(line, matches, pattern)) return (int64_t)(atof(matches[2].str().c_str()) * 1000 * 1000); } return -1; #elif defined(_WIN32) || defined(_WIN64) HKEY hKeyProcessor; long lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKeyProcessor); if (lError != ERROR_SUCCESS) return -1; // Smart resource deleter pattern auto clear = [](HKEY hKey) { RegCloseKey(hKey); }; auto key = std::unique_ptr<std::remove_pointer<HKEY>::type, decltype(clear)>(hKeyProcessor, clear); DWORD dwMHz = 0; DWORD dwBufferSize = sizeof(DWORD); lError = RegQueryValueExA(key.get(), "~MHz", nullptr, nullptr, (LPBYTE)&dwMHz, &dwBufferSize); if (lError != ERROR_SUCCESS) return -1; return dwMHz * 1000 * 1000; #else #error Unsupported platform #endif } bool System::CpuHyperThreading() { std::pair<int, int> cores = CpuTotalCores(); return (cores.first != cores.second); } int64_t System::RamTotal() { #if defined(__APPLE__) int64_t memsize = 0; size_t size = sizeof(memsize); if (sysctlbyname("hw.memsize", &memsize, &size, nullptr, 0) == 0) return memsize; return -1; #elif defined(linux) || defined(__linux) || defined(__linux__) int64_t pages = sysconf(_SC_PHYS_PAGES); int64_t page_size = sysconf(_SC_PAGESIZE); if ((pages > 0) && (page_size > 0)) return pages * page_size; return -1; #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx(&status); return status.ullTotalPhys; #else #error Unsupported platform #endif } int64_t System::RamFree() { #if defined(__APPLE__) mach_port_t host_port = mach_host_self(); if (host_port == MACH_PORT_NULL) return -1; vm_size_t page_size = 0; host_page_size(host_port, &page_size); vm_statistics_data_t vmstat; mach_msg_type_number_t count = HOST_VM_INFO_COUNT; kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat, &count); if (kernReturn != KERN_SUCCESS) return -1; int64_t used_mem = (vmstat.active_count + vmstat.inactive_count + vmstat.wire_count) * page_size; int64_t free_mem = vmstat.free_count * page_size; return free_mem; #elif defined(linux) || defined(__linux) || defined(__linux__) int64_t pages = sysconf(_SC_AVPHYS_PAGES); int64_t page_size = sysconf(_SC_PAGESIZE); if ((pages > 0) && (page_size > 0)) return pages * page_size; return -1; #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx(&status); return status.ullAvailPhys; #else #error Unsupported platform #endif } uint64_t System::CurrentThreadId() { #if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__) return (uint64_t)pthread_self(); #elif defined(_WIN32) || defined(_WIN64) return GetCurrentThreadId(); #else #error Unsupported platform #endif } uint64_t System::Timestamp() { #if defined(__APPLE__) static mach_timebase_info_data_t info; static uint64_t bias = Internals::PrepareTimebaseInfo(info); return (mach_absolute_time() - bias) * info.numer / info.denom; #elif defined(unix) || defined(__unix) || defined(__unix__) struct timespec timestamp; clock_gettime(CLOCK_MONOTONIC, &timestamp); return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec; #elif defined(_WIN32) || defined(_WIN64) static uint64_t offset = 0; static LARGE_INTEGER first{0}; static LARGE_INTEGER frequency{0}; static bool initialized = false; static bool qpc = true; if (!initialized) { // Calculate timestamp offset FILETIME timestamp; GetSystemTimePreciseAsFileTime(&timestamp); ULARGE_INTEGER result; result.LowPart = timestamp.dwLowDateTime; result.HighPart = timestamp.dwHighDateTime; // Convert 01.01.1601 to 01.01.1970 result.QuadPart -= 116444736000000000ll; offset = result.QuadPart * 100; // Setup performance counter qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first); initialized = true; } if (qpc) { LARGE_INTEGER timestamp{0}; QueryPerformanceCounter(&timestamp); timestamp.QuadPart -= first.QuadPart; return offset + ((timestamp.QuadPart * 1000 * 1000 * 1000) / frequency.QuadPart); } else return offset; #else #error Unsupported platform #endif } } // namespace CppBenchmark <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief application endpoint server feature /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2010-2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "ApplicationEndpointServer.h" #include <openssl/err.h> #include "Basics/delete_object.h" #include "Basics/ssl-helper.h" #include "Basics/Random.h" #include "Dispatcher/ApplicationDispatcher.h" #include "HttpServer/HttpHandlerFactory.h" #include "HttpServer/HttpHandler.h" #include "HttpServer/HttpServer.h" #include "HttpServer/HttpsServer.h" #include "Logger/Logger.h" #include "Scheduler/ApplicationScheduler.h" using namespace triagens::basics; using namespace triagens::rest; using namespace std; // ----------------------------------------------------------------------------- // --SECTION-- private classes // ----------------------------------------------------------------------------- namespace { class BIOGuard { public: BIOGuard(BIO *bio) : _bio(bio) { } ~BIOGuard() { BIO_free(_bio); } public: BIO *_bio; }; } // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Scheduler /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// ApplicationEndpointServer::ApplicationEndpointServer (ApplicationServer* applicationServer, ApplicationScheduler* applicationScheduler, ApplicationDispatcher* applicationDispatcher, std::string const& authenticationRealm, HttpHandlerFactory::auth_fptr checkAuthentication) : ApplicationFeature("HttpServer"), _applicationServer(applicationServer), _applicationScheduler(applicationScheduler), _applicationDispatcher(applicationDispatcher), _authenticationRealm(authenticationRealm), _checkAuthentication(checkAuthentication), _handlerFactory(0), _servers(), _httpsKeyfile(), _cafile(), _sslProtocol(HttpsServer::TLS_V1), _sslCache(false), _sslOptions((uint64_t) (SSL_OP_TLS_ROLLBACK_BUG | SSL_OP_CIPHER_SERVER_PREFERENCE)), _sslCipherList(""), _sslContext(0), _rctx() { } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// ApplicationEndpointServer::~ApplicationEndpointServer () { for_each(_servers.begin(), _servers.end(), DeleteObject()); _servers.clear(); if (_handlerFactory != 0) { delete _handlerFactory; } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Scheduler /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief builds the endpoint server //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::buildServers (const EndpointList* endpointList) { assert(_handlerFactory != 0); assert(_applicationScheduler->scheduler() != 0); HttpServer* server; // unencrypted endpoints if (endpointList->count(Endpoint::PROTOCOL_HTTP, Endpoint::ENCRYPTION_NONE) > 0) { // http server = new HttpServer(_applicationScheduler->scheduler(), _applicationDispatcher->dispatcher(), _handlerFactory); server->setEndpointList(endpointList); _servers.push_back(server); } // ssl endpoints if (endpointList->count(Endpoint::PROTOCOL_HTTP, Endpoint::ENCRYPTION_SSL) > 0) { // https server = new HttpsServer(_applicationScheduler->scheduler(), _applicationDispatcher->dispatcher(), _handlerFactory, _sslContext); server->setEndpointList(endpointList); _servers.push_back(server); } return true; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- ApplicationFeature methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ApplicationServer /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::setupOptions (map<string, ProgramOptionsDescription>& options) { options[ApplicationServer::OPTIONS_SERVER + ":help-ssl"] ("server.keyfile", &_httpsKeyfile, "keyfile for SSL connections") ("server.cafile", &_cafile, "file containing the CA certificates of clients") ("server.ssl-protocol", &_sslProtocol, "1 = SSLv2, 2 = SSLv23, 3 = SSLv3, 4 = TLSv1") ("server.ssl-cache", &_sslCache, "use SSL session caching") ("server.ssl-options", &_sslOptions, "ssl options, see OpenSSL documentation") ("server.ssl-cipher-list", &_sslCipherList, "ssl cipher list, see OpenSSL documentation") ; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::parsePhase2 (ProgramOptions& options) { // create the ssl context (if possible) bool ok = createSslContext(); if (! ok) { return false; } // and return return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::prepare () { _handlerFactory = new HttpHandlerFactory(_authenticationRealm, _checkAuthentication); // check the ssl context if (_sslContext == 0) { LOGGER_FATAL << "no ssl context is known, cannot create https server"; LOGGER_INFO << "please use the --server.keyfile option"; return false; } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::prepare2 () { // scheduler might be created after prepare()!! Scheduler* scheduler = _applicationScheduler->scheduler(); if (scheduler == 0) { LOGGER_FATAL << "no scheduler is known, cannot create http server"; return false; } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::open () { for (vector<HttpServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { HttpServer* server = *i; server->startListening(); } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::close () { // close all open connections for (vector<HttpServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { HttpServer* server = *i; server->shutdownHandlers(); } // close all listen sockets for (vector<HttpServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { HttpServer* server = *i; server->stopListening(); } } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::stop () { for (vector<HttpServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { HttpServer* server = *i; server->stop(); } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup HttpServer /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief creates an ssl context //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::createSslContext () { // check keyfile if (_httpsKeyfile.empty()) { return true; } // validate protocol if (_sslProtocol <= HttpsServer::SSL_UNKNOWN || _sslProtocol >= HttpsServer::SSL_LAST) { LOGGER_ERROR << "invalid SSL protocol version specified."; LOGGER_INFO << "please use a valid value for --server.ssl-protocol."; return false; } LOGGER_INFO << "using SSL protocol version '" << HttpsServer::protocolName((HttpsServer::protocol_e) _sslProtocol) << "'"; // create context _sslContext = HttpsServer::sslContext(HttpsServer::protocol_e(_sslProtocol), _httpsKeyfile); if (_sslContext == 0) { LOGGER_ERROR << "failed to create SSL context, cannot create a HTTPS server"; return false; } // set cache mode SSL_CTX_set_session_cache_mode(_sslContext, _sslCache ? SSL_SESS_CACHE_SERVER : SSL_SESS_CACHE_OFF); if (_sslCache) { LOGGER_INFO << "using SSL session caching"; } // set options SSL_CTX_set_options(_sslContext, _sslOptions); LOGGER_INFO << "using SSL options: " << _sslOptions; if (_sslCipherList.size() > 0) { LOGGER_INFO << "using SSL cipher-list '" << _sslCipherList << "'"; if (SSL_CTX_set_cipher_list(_sslContext, _sslCipherList.c_str()) != 1) { LOGGER_FATAL << "cannot set SSL cipher list '" << _sslCipherList << "'"; LOGGER_ERROR << lastSSLError(); return false; } } // set ssl context Random::UniformCharacter r("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); _rctx = r.random(SSL_MAX_SSL_SESSION_ID_LENGTH); int res = SSL_CTX_set_session_id_context(_sslContext, (unsigned char const*) _rctx.c_str(), _rctx.size()); if (res != 1) { LOGGER_FATAL << "cannot set SSL session id context '" << _rctx << "'"; LOGGER_ERROR << lastSSLError(); return false; } // check CA if (! _cafile.empty()) { LOGGER_TRACE << "trying to load CA certificates from '" << _cafile << "'"; int res = SSL_CTX_load_verify_locations(_sslContext, _cafile.c_str(), 0); if (res == 0) { LOGGER_FATAL << "cannot load CA certificates from '" << _cafile << "'"; LOGGER_ERROR << lastSSLError(); return false; } STACK_OF(X509_NAME) * certNames; certNames = SSL_load_client_CA_file(_cafile.c_str()); if (certNames == 0) { LOGGER_FATAL << "cannot load CA certificates from '" << _cafile << "'"; LOGGER_ERROR << lastSSLError(); return false; } if (TRI_IsTraceLogging(__FILE__)) { for (int i = 0; i < sk_X509_NAME_num(certNames); ++i) { X509_NAME* cert = sk_X509_NAME_value(certNames, i); if (cert) { BIOGuard bout(BIO_new(BIO_s_mem())); X509_NAME_print_ex(bout._bio, cert, 0, (XN_FLAG_SEP_COMMA_PLUS | XN_FLAG_DN_REV | ASN1_STRFLGS_UTF8_CONVERT) & ~ASN1_STRFLGS_ESC_MSB); char* r; long len = BIO_get_mem_data(bout._bio, &r); LOGGER_TRACE << "name: " << string(r, len); } } } SSL_CTX_set_client_CA_list(_sslContext, certNames); } return true; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End: <commit_msg>ssl keyfile was required by mistake<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief application endpoint server feature /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Copyright 2010-2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "ApplicationEndpointServer.h" #include <openssl/err.h> #include "Basics/delete_object.h" #include "Basics/ssl-helper.h" #include "Basics/Random.h" #include "Dispatcher/ApplicationDispatcher.h" #include "HttpServer/HttpHandlerFactory.h" #include "HttpServer/HttpHandler.h" #include "HttpServer/HttpServer.h" #include "HttpServer/HttpsServer.h" #include "Logger/Logger.h" #include "Scheduler/ApplicationScheduler.h" using namespace triagens::basics; using namespace triagens::rest; using namespace std; // ----------------------------------------------------------------------------- // --SECTION-- private classes // ----------------------------------------------------------------------------- namespace { class BIOGuard { public: BIOGuard(BIO *bio) : _bio(bio) { } ~BIOGuard() { BIO_free(_bio); } public: BIO *_bio; }; } // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Scheduler /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// ApplicationEndpointServer::ApplicationEndpointServer (ApplicationServer* applicationServer, ApplicationScheduler* applicationScheduler, ApplicationDispatcher* applicationDispatcher, std::string const& authenticationRealm, HttpHandlerFactory::auth_fptr checkAuthentication) : ApplicationFeature("HttpServer"), _applicationServer(applicationServer), _applicationScheduler(applicationScheduler), _applicationDispatcher(applicationDispatcher), _authenticationRealm(authenticationRealm), _checkAuthentication(checkAuthentication), _handlerFactory(0), _servers(), _httpsKeyfile(), _cafile(), _sslProtocol(HttpsServer::TLS_V1), _sslCache(false), _sslOptions((uint64_t) (SSL_OP_TLS_ROLLBACK_BUG | SSL_OP_CIPHER_SERVER_PREFERENCE)), _sslCipherList(""), _sslContext(0), _rctx() { } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// ApplicationEndpointServer::~ApplicationEndpointServer () { for_each(_servers.begin(), _servers.end(), DeleteObject()); _servers.clear(); if (_handlerFactory != 0) { delete _handlerFactory; } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup Scheduler /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief builds the endpoint server //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::buildServers (const EndpointList* endpointList) { assert(_handlerFactory != 0); assert(_applicationScheduler->scheduler() != 0); HttpServer* server; // unencrypted endpoints if (endpointList->count(Endpoint::PROTOCOL_HTTP, Endpoint::ENCRYPTION_NONE) > 0) { // http server = new HttpServer(_applicationScheduler->scheduler(), _applicationDispatcher->dispatcher(), _handlerFactory); server->setEndpointList(endpointList); _servers.push_back(server); } // ssl endpoints if (endpointList->count(Endpoint::PROTOCOL_HTTP, Endpoint::ENCRYPTION_SSL) > 0) { // check the ssl context if (_sslContext == 0) { LOGGER_FATAL << "no ssl context is known, cannot create https server"; LOGGER_INFO << "please use the --server.keyfile option"; return false; } // https server = new HttpsServer(_applicationScheduler->scheduler(), _applicationDispatcher->dispatcher(), _handlerFactory, _sslContext); server->setEndpointList(endpointList); _servers.push_back(server); } return true; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- ApplicationFeature methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ApplicationServer /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::setupOptions (map<string, ProgramOptionsDescription>& options) { options[ApplicationServer::OPTIONS_SERVER + ":help-ssl"] ("server.keyfile", &_httpsKeyfile, "keyfile for SSL connections") ("server.cafile", &_cafile, "file containing the CA certificates of clients") ("server.ssl-protocol", &_sslProtocol, "1 = SSLv2, 2 = SSLv23, 3 = SSLv3, 4 = TLSv1") ("server.ssl-cache", &_sslCache, "use SSL session caching") ("server.ssl-options", &_sslOptions, "ssl options, see OpenSSL documentation") ("server.ssl-cipher-list", &_sslCipherList, "ssl cipher list, see OpenSSL documentation") ; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::parsePhase2 (ProgramOptions& options) { // create the ssl context (if possible) bool ok = createSslContext(); if (! ok) { return false; } // and return return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::prepare () { _handlerFactory = new HttpHandlerFactory(_authenticationRealm, _checkAuthentication); return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::prepare2 () { // scheduler might be created after prepare()!! Scheduler* scheduler = _applicationScheduler->scheduler(); if (scheduler == 0) { LOGGER_FATAL << "no scheduler is known, cannot create http server"; return false; } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::open () { for (vector<HttpServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { HttpServer* server = *i; server->startListening(); } return true; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::close () { // close all open connections for (vector<HttpServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { HttpServer* server = *i; server->shutdownHandlers(); } // close all listen sockets for (vector<HttpServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { HttpServer* server = *i; server->stopListening(); } } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// void ApplicationEndpointServer::stop () { for (vector<HttpServer*>::iterator i = _servers.begin(); i != _servers.end(); ++i) { HttpServer* server = *i; server->stop(); } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup HttpServer /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief creates an ssl context //////////////////////////////////////////////////////////////////////////////// bool ApplicationEndpointServer::createSslContext () { // check keyfile if (_httpsKeyfile.empty()) { return true; } // validate protocol if (_sslProtocol <= HttpsServer::SSL_UNKNOWN || _sslProtocol >= HttpsServer::SSL_LAST) { LOGGER_ERROR << "invalid SSL protocol version specified."; LOGGER_INFO << "please use a valid value for --server.ssl-protocol."; return false; } LOGGER_INFO << "using SSL protocol version '" << HttpsServer::protocolName((HttpsServer::protocol_e) _sslProtocol) << "'"; // create context _sslContext = HttpsServer::sslContext(HttpsServer::protocol_e(_sslProtocol), _httpsKeyfile); if (_sslContext == 0) { LOGGER_ERROR << "failed to create SSL context, cannot create a HTTPS server"; return false; } // set cache mode SSL_CTX_set_session_cache_mode(_sslContext, _sslCache ? SSL_SESS_CACHE_SERVER : SSL_SESS_CACHE_OFF); if (_sslCache) { LOGGER_INFO << "using SSL session caching"; } // set options SSL_CTX_set_options(_sslContext, _sslOptions); LOGGER_INFO << "using SSL options: " << _sslOptions; if (_sslCipherList.size() > 0) { LOGGER_INFO << "using SSL cipher-list '" << _sslCipherList << "'"; if (SSL_CTX_set_cipher_list(_sslContext, _sslCipherList.c_str()) != 1) { LOGGER_FATAL << "cannot set SSL cipher list '" << _sslCipherList << "'"; LOGGER_ERROR << lastSSLError(); return false; } } // set ssl context Random::UniformCharacter r("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); _rctx = r.random(SSL_MAX_SSL_SESSION_ID_LENGTH); int res = SSL_CTX_set_session_id_context(_sslContext, (unsigned char const*) _rctx.c_str(), _rctx.size()); if (res != 1) { LOGGER_FATAL << "cannot set SSL session id context '" << _rctx << "'"; LOGGER_ERROR << lastSSLError(); return false; } // check CA if (! _cafile.empty()) { LOGGER_TRACE << "trying to load CA certificates from '" << _cafile << "'"; int res = SSL_CTX_load_verify_locations(_sslContext, _cafile.c_str(), 0); if (res == 0) { LOGGER_FATAL << "cannot load CA certificates from '" << _cafile << "'"; LOGGER_ERROR << lastSSLError(); return false; } STACK_OF(X509_NAME) * certNames; certNames = SSL_load_client_CA_file(_cafile.c_str()); if (certNames == 0) { LOGGER_FATAL << "cannot load CA certificates from '" << _cafile << "'"; LOGGER_ERROR << lastSSLError(); return false; } if (TRI_IsTraceLogging(__FILE__)) { for (int i = 0; i < sk_X509_NAME_num(certNames); ++i) { X509_NAME* cert = sk_X509_NAME_value(certNames, i); if (cert) { BIOGuard bout(BIO_new(BIO_s_mem())); X509_NAME_print_ex(bout._bio, cert, 0, (XN_FLAG_SEP_COMMA_PLUS | XN_FLAG_DN_REV | ASN1_STRFLGS_UTF8_CONVERT) & ~ASN1_STRFLGS_ESC_MSB); char* r; long len = BIO_get_mem_data(bout._bio, &r); LOGGER_TRACE << "name: " << string(r, len); } } } SSL_CTX_set_client_CA_list(_sslContext, certNames); } return true; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End: <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: test_plane_intersection.cpp 5686 2012-05-11 20:59:00Z gioia $ */ #include <gtest/gtest.h> #include <pcl/common/common.h> #include <pcl/common/intersections.h> #include <pcl/pcl_tests.h> using namespace pcl; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (PCL, lineWithLineIntersection) { Eigen::Vector4f line_a; Eigen::Vector4f line_b; //case 1 line_a.x() = 0.09100f; line_a.y() = 0.00200f; line_a.z() = 0.00300f; line_a.w() = 0.00400f; line_b.x() = 0.0157f; line_b.y() = 0.0333f; line_b.z() = 0.0678f; line_b.w() = 0.0995f; Eigen::Vector4f p1, p2; lineToLineSegment (line_a, line_b, p1, p2); Eigen::Vector4f point_case_1; bool result_case_1 = lineWithLineIntersection(line_a, line_b, point_case_1); double sqr_dist_case_1 = (p1 - p2).squaredNorm (); double default_sqr_eps = 1e-4; EXPECT_GT(sqr_dist_case_1, default_sqr_eps); Eigen::Vector4f zero(0.0f, 0.0f, 0.0f, 0.0f); EXPECT_EQ(point_case_1, zero); EXPECT_FALSE(result_case_1); pcl::ModelCoefficients line_a_mod; pcl::ModelCoefficients line_b_mod; std::vector<float> values_a_case_1; values_a_case_1.push_back(line_a.x()); values_a_case_1.push_back(line_a.y()); values_a_case_1.push_back(line_a.z()); values_a_case_1.push_back(line_a.w()); std::vector<float> values_b_case_1; values_b_case_1.push_back(line_b.x()); values_b_case_1.push_back(line_b.y()); values_b_case_1.push_back(line_b.z()); values_b_case_1.push_back(line_b.w()); line_a_mod.values = values_a_case_1; line_b_mod.values = values_b_case_1; Eigen::Vector4f point_mod_1; EXPECT_FALSE(lineWithLineIntersection(line_a_mod, line_b_mod, point_mod_1)); EXPECT_EQ(result_case_1, lineWithLineIntersection(line_a_mod, line_b_mod, point_mod_1)); EXPECT_EQ(point_mod_1, zero); //case 2 line_a.x() = 0.09100f; line_a.y() = 0.00200f; line_a.z() = 0.00300f; line_a.w() = 0.00400f; line_b.x() = 0.00157f; line_b.y() = 0.00333f; line_b.z() = 0.00678f; line_b.w() = 0.00995f; lineToLineSegment (line_a, line_b, p1, p2); Eigen::Vector4f point_case_2; double sqr_eps_case_2 = 1e-1; bool result_case_2 = lineWithLineIntersection(line_a, line_b, point_case_2, sqr_eps_case_2); double sqr_dist_case_2 = (p1 - p2).squaredNorm (); EXPECT_LT(sqr_dist_case_2, sqr_eps_case_2); EXPECT_EQ(point_case_2, p1); EXPECT_TRUE(result_case_2); pcl::ModelCoefficients line_a_mod_2; pcl::ModelCoefficients line_b_mod_2; std::vector<float> values_a_case_2; values_a_case_2.push_back(0.1000f); values_a_case_2.push_back(0.2000f); values_a_case_2.push_back(0.3000f); values_a_case_2.push_back(0.4000f); std::vector<float> values_b_case_2; values_b_case_2.push_back(0.1001f); values_b_case_2.push_back(0.2001f); values_b_case_2.push_back(0.3001f); values_b_case_2.push_back(0.4001f); line_a_mod_2.values = values_a_case_2; line_b_mod_2.values = values_b_case_2; Eigen::Vector4f point_mod_2; Eigen::Vector4f point_mod_case_2; double sqr_mod_case_2 = 1e-1; Eigen::Vector4f coeff1 = Eigen::Vector4f::Map (&line_a_mod_2.values[0], line_a_mod_2.values.size ()); Eigen::Vector4f coeff2 = Eigen::Vector4f::Map (&line_b_mod_2.values[0], line_b_mod_2.values.size ()); Eigen::Vector4f p1_mod, p2_mod; lineToLineSegment (coeff1, coeff2, p1_mod, p2_mod); double sqr_mod_act_2 = (p1_mod - p2_mod).squaredNorm (); EXPECT_LT(sqr_mod_act_2, sqr_mod_case_2); EXPECT_EQ(lineWithLineIntersection (coeff1, coeff2, point_mod_case_2, sqr_mod_case_2), lineWithLineIntersection(line_a_mod_2, line_b_mod_2, point_mod_2, sqr_mod_case_2)); EXPECT_TRUE(lineWithLineIntersection(line_a_mod_2, line_b_mod_2, point_mod_2, sqr_mod_case_2)); EXPECT_EQ(point_mod_2, point_mod_case_2); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (PCL, planeWithPlaneIntersection) { //Testing parallel planes const int k = 2; float x = 1.0f; float y = 2.0f; float z = 3.0f; float w = 4.0f; Eigen::Vector4f plane_a; plane_a.x() = x; plane_a.y() = y; plane_a.z() = z; plane_a.w() = w; EXPECT_EQ(1.0f, plane_a.x()); EXPECT_EQ(2.0f, plane_a.y()); EXPECT_EQ(3.0f, plane_a.z()); EXPECT_EQ(4.0f, plane_a.w()); Eigen::Vector4f plane_b; plane_b.x() = x; plane_b.y() = y; plane_b.z() = z; plane_b.w() = w + k; EXPECT_EQ(1.0f, plane_b.x()); EXPECT_EQ(2.0f, plane_b.y()); EXPECT_EQ(3.0f, plane_b.z()); EXPECT_EQ(6.0f, plane_b.w()); Eigen::VectorXf line; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360)); plane_b.x() = k * x; plane_b.y() = k * y; plane_b.z() = k * z; plane_b.w() = k * w; EXPECT_EQ(2.0f, plane_b.x()); EXPECT_EQ(4.0f, plane_b.y()); EXPECT_EQ(6.0f, plane_b.z()); EXPECT_EQ(8.0f, plane_b.w()); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360)); //overlapping planes plane_b.w() = w; EXPECT_EQ(4.0f, plane_b.w()); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360)); //orthogonal planes plane_a.x() = 2.0f; plane_a.y() = 1.0f; plane_a.z() = -5.0f; plane_a.w() = 6.0f; EXPECT_EQ(2.0f, plane_a.x()); EXPECT_EQ(1.0f, plane_a.y()); EXPECT_EQ(-5.0f, plane_a.z()); EXPECT_EQ(6.0f, plane_a.w()); plane_b.x() = 2.0f; plane_b.y() = 1.0f; plane_b.z() = 1.0f; plane_b.w() = 7.0f; EXPECT_EQ(2.0f, plane_b.x()); EXPECT_EQ(1.0f, plane_b.y()); EXPECT_EQ(1.0f, plane_b.z()); EXPECT_EQ(7.0f, plane_b.w()); std::cout << std::endl; EXPECT_TRUE(planeWithPlaneIntersection(plane_a, plane_b, line, 0)); //general planes plane_a.x() = 1.555f; plane_a.y() = 0.894f; plane_a.z() = 1.234f; plane_a.w() = 3.567f; plane_b.x() = 0.743f; plane_b.y() = 1.890f; plane_b.z() = 6.789f; plane_b.w() = 5.432f; std::cout << std::endl; EXPECT_TRUE(planeWithPlaneIntersection(plane_a, plane_b, line, 0)); } //* ---[ */ int main (int argc, char** argv) { testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */ <commit_msg>fixed win32 compilation error on test_plane_intersection<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: test_plane_intersection.cpp 5686 2012-05-11 20:59:00Z gioia $ */ #include <gtest/gtest.h> #include <pcl/common/common.h> #include <pcl/common/intersections.h> #include <pcl/pcl_tests.h> using namespace pcl; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (PCL, lineWithLineIntersection) { Eigen::Vector4f line_a; Eigen::Vector4f line_b; //case 1 line_a.x() = 0.09100f; line_a.y() = 0.00200f; line_a.z() = 0.00300f; line_a.w() = 0.00400f; line_b.x() = 0.0157f; line_b.y() = 0.0333f; line_b.z() = 0.0678f; line_b.w() = 0.0995f; Eigen::Vector4f p1, p2; lineToLineSegment (line_a, line_b, p1, p2); Eigen::Vector4f point_case_1; bool result_case_1 = lineWithLineIntersection(line_a, line_b, point_case_1); double sqr_dist_case_1 = (p1 - p2).squaredNorm (); double default_sqr_eps = 1e-4; EXPECT_GT(sqr_dist_case_1, default_sqr_eps); Eigen::Vector4f zero(0.0f, 0.0f, 0.0f, 0.0f); EXPECT_EQ(point_case_1[0], zero[0]); EXPECT_EQ(point_case_1[1], zero[1]); EXPECT_EQ(point_case_1[2], zero[2]); EXPECT_EQ(point_case_1[3], zero[3]); EXPECT_FALSE(result_case_1); pcl::ModelCoefficients line_a_mod; pcl::ModelCoefficients line_b_mod; std::vector<float> values_a_case_1; values_a_case_1.push_back(line_a.x()); values_a_case_1.push_back(line_a.y()); values_a_case_1.push_back(line_a.z()); values_a_case_1.push_back(line_a.w()); std::vector<float> values_b_case_1; values_b_case_1.push_back(line_b.x()); values_b_case_1.push_back(line_b.y()); values_b_case_1.push_back(line_b.z()); values_b_case_1.push_back(line_b.w()); line_a_mod.values = values_a_case_1; line_b_mod.values = values_b_case_1; Eigen::Vector4f point_mod_1; EXPECT_FALSE(lineWithLineIntersection(line_a_mod, line_b_mod, point_mod_1)); EXPECT_EQ(result_case_1, lineWithLineIntersection(line_a_mod, line_b_mod, point_mod_1)); EXPECT_EQ(point_mod_1[0], zero[0]); EXPECT_EQ(point_mod_1[1], zero[1]); EXPECT_EQ(point_mod_1[2], zero[2]); EXPECT_EQ(point_mod_1[3], zero[3]); //case 2 line_a.x() = 0.09100f; line_a.y() = 0.00200f; line_a.z() = 0.00300f; line_a.w() = 0.00400f; line_b.x() = 0.00157f; line_b.y() = 0.00333f; line_b.z() = 0.00678f; line_b.w() = 0.00995f; lineToLineSegment (line_a, line_b, p1, p2); Eigen::Vector4f point_case_2; double sqr_eps_case_2 = 1e-1; bool result_case_2 = lineWithLineIntersection(line_a, line_b, point_case_2, sqr_eps_case_2); double sqr_dist_case_2 = (p1 - p2).squaredNorm (); EXPECT_LT(sqr_dist_case_2, sqr_eps_case_2); EXPECT_EQ(point_case_2[0], p1[0]); EXPECT_EQ(point_case_2[1], p1[1]); EXPECT_EQ(point_case_2[2], p1[2]); EXPECT_EQ(point_case_2[3], p1[3]); EXPECT_TRUE(result_case_2); pcl::ModelCoefficients line_a_mod_2; pcl::ModelCoefficients line_b_mod_2; std::vector<float> values_a_case_2; values_a_case_2.push_back(0.1000f); values_a_case_2.push_back(0.2000f); values_a_case_2.push_back(0.3000f); values_a_case_2.push_back(0.4000f); std::vector<float> values_b_case_2; values_b_case_2.push_back(0.1001f); values_b_case_2.push_back(0.2001f); values_b_case_2.push_back(0.3001f); values_b_case_2.push_back(0.4001f); line_a_mod_2.values = values_a_case_2; line_b_mod_2.values = values_b_case_2; Eigen::Vector4f point_mod_2; Eigen::Vector4f point_mod_case_2; double sqr_mod_case_2 = 1e-1; Eigen::Vector4f coeff1 = Eigen::Vector4f::Map (&line_a_mod_2.values[0], line_a_mod_2.values.size ()); Eigen::Vector4f coeff2 = Eigen::Vector4f::Map (&line_b_mod_2.values[0], line_b_mod_2.values.size ()); Eigen::Vector4f p1_mod, p2_mod; lineToLineSegment (coeff1, coeff2, p1_mod, p2_mod); double sqr_mod_act_2 = (p1_mod - p2_mod).squaredNorm (); EXPECT_LT(sqr_mod_act_2, sqr_mod_case_2); EXPECT_EQ(lineWithLineIntersection (coeff1, coeff2, point_mod_case_2, sqr_mod_case_2), lineWithLineIntersection(line_a_mod_2, line_b_mod_2, point_mod_2, sqr_mod_case_2)); EXPECT_TRUE(lineWithLineIntersection(line_a_mod_2, line_b_mod_2, point_mod_2, sqr_mod_case_2)); EXPECT_EQ(point_mod_2[0], point_mod_case_2[0]); EXPECT_EQ(point_mod_2[1], point_mod_case_2[1]); EXPECT_EQ(point_mod_2[2], point_mod_case_2[2]); EXPECT_EQ(point_mod_2[3], point_mod_case_2[3]); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (PCL, planeWithPlaneIntersection) { //Testing parallel planes const int k = 2; float x = 1.0f; float y = 2.0f; float z = 3.0f; float w = 4.0f; Eigen::Vector4f plane_a; plane_a.x() = x; plane_a.y() = y; plane_a.z() = z; plane_a.w() = w; EXPECT_EQ(1.0f, plane_a.x()); EXPECT_EQ(2.0f, plane_a.y()); EXPECT_EQ(3.0f, plane_a.z()); EXPECT_EQ(4.0f, plane_a.w()); Eigen::Vector4f plane_b; plane_b.x() = x; plane_b.y() = y; plane_b.z() = z; plane_b.w() = w + k; EXPECT_EQ(1.0f, plane_b.x()); EXPECT_EQ(2.0f, plane_b.y()); EXPECT_EQ(3.0f, plane_b.z()); EXPECT_EQ(6.0f, plane_b.w()); Eigen::VectorXf line; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360)); plane_b.x() = k * x; plane_b.y() = k * y; plane_b.z() = k * z; plane_b.w() = k * w; EXPECT_EQ(2.0f, plane_b.x()); EXPECT_EQ(4.0f, plane_b.y()); EXPECT_EQ(6.0f, plane_b.z()); EXPECT_EQ(8.0f, plane_b.w()); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360)); //overlapping planes plane_b.w() = w; EXPECT_EQ(4.0f, plane_b.w()); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 45)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 90)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 180)); std::cout << std::endl; EXPECT_FALSE(planeWithPlaneIntersection(plane_a, plane_b, line, 360)); //orthogonal planes plane_a.x() = 2.0f; plane_a.y() = 1.0f; plane_a.z() = -5.0f; plane_a.w() = 6.0f; EXPECT_EQ(2.0f, plane_a.x()); EXPECT_EQ(1.0f, plane_a.y()); EXPECT_EQ(-5.0f, plane_a.z()); EXPECT_EQ(6.0f, plane_a.w()); plane_b.x() = 2.0f; plane_b.y() = 1.0f; plane_b.z() = 1.0f; plane_b.w() = 7.0f; EXPECT_EQ(2.0f, plane_b.x()); EXPECT_EQ(1.0f, plane_b.y()); EXPECT_EQ(1.0f, plane_b.z()); EXPECT_EQ(7.0f, plane_b.w()); std::cout << std::endl; EXPECT_TRUE(planeWithPlaneIntersection(plane_a, plane_b, line, 0)); //general planes plane_a.x() = 1.555f; plane_a.y() = 0.894f; plane_a.z() = 1.234f; plane_a.w() = 3.567f; plane_b.x() = 0.743f; plane_b.y() = 1.890f; plane_b.z() = 6.789f; plane_b.w() = 5.432f; std::cout << std::endl; EXPECT_TRUE(planeWithPlaneIntersection(plane_a, plane_b, line, 0)); } //* ---[ */ int main (int argc, char** argv) { testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */ <|endoftext|>
<commit_before>#include "vorbisbuf.h" #include <system_error> #include <cstring> namespace fys { #define ERROR_MESSAGE_FROM_ENUM(e) case e: return #e; std::error_category& vorbisbuf_error_category() { static struct : public std::error_category { const char* name() const noexcept override { return "vorbisbuf"; } std::string message(int e) const override { switch(e) { ERROR_MESSAGE_FROM_ENUM(VORBIS_need_more_data) // not a real error ERROR_MESSAGE_FROM_ENUM(VORBIS_invalid_api_mixing) // can't mix API modes ERROR_MESSAGE_FROM_ENUM(VORBIS_outofmem) // not enough memory ERROR_MESSAGE_FROM_ENUM(VORBIS_feature_not_supported) // uses floor 0 ERROR_MESSAGE_FROM_ENUM(VORBIS_too_many_channels) // STB_VORBIS_MAX_CHANNELS is too small ERROR_MESSAGE_FROM_ENUM(VORBIS_file_open_failure) // fopen() failed ERROR_MESSAGE_FROM_ENUM(VORBIS_seek_without_length) // can't seek in unknown-length file ERROR_MESSAGE_FROM_ENUM(VORBIS_unexpected_eof) // file is truncated? ERROR_MESSAGE_FROM_ENUM(VORBIS_seek_invalid) // seek past EOF // decoding errors (corrupt/invalid stream) -- you probably // don't care about the exact details of these // vorbis errors: ERROR_MESSAGE_FROM_ENUM(VORBIS_invalid_setup) ERROR_MESSAGE_FROM_ENUM(VORBIS_invalid_stream) // ogg errors: ERROR_MESSAGE_FROM_ENUM(VORBIS_missing_capture_pattern) ERROR_MESSAGE_FROM_ENUM(VORBIS_invalid_stream_structure_version) ERROR_MESSAGE_FROM_ENUM(VORBIS_continued_packet_flag_invalid) ERROR_MESSAGE_FROM_ENUM(VORBIS_incorrect_stream_serial_number) ERROR_MESSAGE_FROM_ENUM(VORBIS_invalid_first_page) ERROR_MESSAGE_FROM_ENUM(VORBIS_bad_packet_type) ERROR_MESSAGE_FROM_ENUM(VORBIS_cant_find_last_page) ERROR_MESSAGE_FROM_ENUM(VORBIS_seek_failed) default: return ""; } } } _category; return _category; } vorbisbuf::channelbuf::channelbuf(vorbisbuf& src): m_src(src) {} auto vorbisbuf::channelbuf::underflow() -> int_type { ++m_debug_underflow_count; if(!m_src.decode_next_frame()) return traits_type::eof(); if(m_decoded_buffer.empty()) return traits_type::eof(); return traits_type::not_eof(m_decoded_buffer[0]); } std::streamsize vorbisbuf::channelbuf::xsgetn(char_type* s, std::streamsize count) { size_t data_copied = 0; while(1) { size_t data_to_copy = std::min(static_cast<size_t>(std::distance(gptr(), egptr())), count - data_copied); std::memcpy(s + data_copied, gptr(), data_to_copy); data_copied += data_to_copy; setg(eback(), gptr() + data_to_copy, egptr()); if(data_copied == static_cast<size_t>(count)) { return data_copied; } if(underflow() == traits_type::eof()) return data_copied; } } void vorbisbuf::channelbuf::push_data(char_type const* data_begin, size_t data_size) { ++m_debug_push_data_count; size_t old_data_still_valid = std::distance(gptr(), egptr()); size_t final_size = old_data_still_valid + data_size; if(final_size <= m_decoded_buffer.capacity()) { memmove(m_decoded_buffer.data(), gptr(), old_data_still_valid); m_decoded_buffer.resize(final_size); std::memcpy(m_decoded_buffer.data() + old_data_still_valid, data_begin, data_size); } else { decltype(m_decoded_buffer) new_buffer(final_size); std::memcpy(new_buffer.data(), gptr(), old_data_still_valid); std::memcpy(new_buffer.data() + old_data_still_valid, data_begin, data_size); std::swap(m_decoded_buffer, new_buffer); } setg(&*begin(m_decoded_buffer), &*begin(m_decoded_buffer), &*end(m_decoded_buffer)); } void vorbisbuf::stb_vorbis_deleter::operator()(stb_vorbis* v) { stb_vorbis_close(v); } vorbisbuf::vorbisbuf(std::streambuf* streambuf): m_streambuf(streambuf), m_buffer(32, 0) { //! Remember to open the file like this std::ifstream file("file.ogg", std::ios::in | std::ios::binary); or you might have problem with EOF in the middle of nowhere. auto next = m_buffer.begin(); try_open_vorbis_header: { std::streamsize get_result = m_streambuf->sgetn(&*next, std::distance(next, m_buffer.end())); if(get_result == 0) throw std::system_error(VORBIS_unexpected_eof, vorbisbuf_error_category()); next += get_result; int data_used = 0; int error = 0; m_vorbis.reset(stb_vorbis_open_pushdata(reinterpret_cast<unsigned char*>(m_buffer.data()), std::distance(m_buffer.begin(), next), &data_used, &error, nullptr)); if(error == STBVorbisError::VORBIS_need_more_data) { size_t n = std::distance(m_buffer.begin(), next); m_buffer.resize(m_buffer.size()*2);//Grow by powers of 2 next = m_buffer.begin() + n; goto try_open_vorbis_header; } if(error) throw std::system_error(error, vorbisbuf_error_category()); memmove(&*begin(m_buffer), &*(begin(m_buffer) + data_used), m_buffer.size() - data_used); m_current = begin(m_buffer) + m_buffer.size() - data_used; } stb_vorbis_info infos = stb_vorbis_get_info(m_vorbis.get()); m_sample_rate = infos.sample_rate; for(int i = 0; i < infos.channels; ++i) m_channels.emplace_back(new channelbuf(*this)); } auto vorbisbuf::channel(unsigned int id) -> channelbuf& { return *m_channels.at(id); } unsigned int vorbisbuf::channels_nb() { return m_channels.size(); } unsigned int vorbisbuf::sample_rate() { return m_sample_rate; } auto vorbisbuf::underflow() -> int_type { if(channels_nb() == 0) return traits_type::eof(); ///TODO à refaire, un appel à setg() est nécessaire size_t pcm_current = m_pcm_current_channel; (++m_pcm_current_channel) %= channels_nb(); return m_channels[pcm_current]->sbumpc(); } bool vorbisbuf::decode_next_frame() { auto next = m_current == end(m_buffer) ? begin(m_buffer) : m_current; try_decode_frame: { std::streamsize get_result = m_streambuf->sgetn(&*next, std::distance(next, m_buffer.end())); next += get_result; int data_used = 0; int channels = 0; float** decoded_output = nullptr; int samples = 0; data_used = stb_vorbis_decode_frame_pushdata( m_vorbis.get(), reinterpret_cast<unsigned char*>(m_buffer.data()), std::distance(begin(m_buffer), next), &channels, &decoded_output, &samples ); if(data_used == 0)//(need more data) { int error = stb_vorbis_get_error(m_vorbis.get()); if(error && error != STBVorbisError::VORBIS_need_more_data) throw std::system_error(error, vorbisbuf_error_category()); if(get_result == 0) return false;//EOF size_t n = std::distance(m_buffer.begin(), next); m_buffer.resize(m_buffer.size()*2);//Grow by powers of 2 next = m_buffer.begin() + n; goto try_decode_frame; } size_t data_ready = std::distance(begin(m_buffer) + data_used, next); memmove(&*begin(m_buffer), &*(begin(m_buffer) + data_used), data_ready); m_current = begin(m_buffer) + data_ready; if(samples == 0)//(resynching the stream, keep going) { next = m_current == end(m_buffer) ? begin(m_buffer) : m_current; goto try_decode_frame; } //For each channel output transform float32 to int16 & push it to the corresponding channelbuf buffer for(int channel_id = 0; channel_id < channels; ++channel_id) { char* decoded_buffer_f = reinterpret_cast<char*>(decoded_output[channel_id]); //Rewrite the decoded float buffer with int16_t equivalent { char* write = decoded_buffer_f; float* read = reinterpret_cast<float*>(decoded_buffer_f); for(; write != decoded_buffer_f + samples*sizeof(int16_t); write += sizeof(int16_t), ++read) { //x(s) = x(f)*[max(s) - min(s)]/[max(f) - min(f)] + min(s) - min(f)*[max(s) - min(s)]/[max(f) - min(f)] //For equivalence, we take max(s) = -min(s), so that there are as many + numbers than - numbers //In case x(f) == 1.f, x(s) would be max(s) + 1, so we round it up to max(s) *reinterpret_cast<int16_t*>(write) = (*read) >= 1.f ? 0x7FFF : (*read) < -1.f ? 0x8000 : static_cast<int16_t>((*read)*0x8000); } } m_channels[channel_id]->push_data(decoded_buffer_f, samples*sizeof(int16_t)); } } return true; } } <commit_msg>Correcting previous commit's spaces/tab and std::<commit_after>#include "vorbisbuf.h" #include <system_error> #include <cstring> namespace fys { #define ERROR_MESSAGE_FROM_ENUM(e) case e: return #e; std::error_category& vorbisbuf_error_category() { static struct : public std::error_category { const char* name() const noexcept override { return "vorbisbuf"; } std::string message(int e) const override { switch(e) { ERROR_MESSAGE_FROM_ENUM(VORBIS_need_more_data) // not a real error ERROR_MESSAGE_FROM_ENUM(VORBIS_invalid_api_mixing) // can't mix API modes ERROR_MESSAGE_FROM_ENUM(VORBIS_outofmem) // not enough memory ERROR_MESSAGE_FROM_ENUM(VORBIS_feature_not_supported) // uses floor 0 ERROR_MESSAGE_FROM_ENUM(VORBIS_too_many_channels) // STB_VORBIS_MAX_CHANNELS is too small ERROR_MESSAGE_FROM_ENUM(VORBIS_file_open_failure) // fopen() failed ERROR_MESSAGE_FROM_ENUM(VORBIS_seek_without_length) // can't seek in unknown-length file ERROR_MESSAGE_FROM_ENUM(VORBIS_unexpected_eof) // file is truncated? ERROR_MESSAGE_FROM_ENUM(VORBIS_seek_invalid) // seek past EOF // decoding errors (corrupt/invalid stream) -- you probably // don't care about the exact details of these // vorbis errors: ERROR_MESSAGE_FROM_ENUM(VORBIS_invalid_setup) ERROR_MESSAGE_FROM_ENUM(VORBIS_invalid_stream) // ogg errors: ERROR_MESSAGE_FROM_ENUM(VORBIS_missing_capture_pattern) ERROR_MESSAGE_FROM_ENUM(VORBIS_invalid_stream_structure_version) ERROR_MESSAGE_FROM_ENUM(VORBIS_continued_packet_flag_invalid) ERROR_MESSAGE_FROM_ENUM(VORBIS_incorrect_stream_serial_number) ERROR_MESSAGE_FROM_ENUM(VORBIS_invalid_first_page) ERROR_MESSAGE_FROM_ENUM(VORBIS_bad_packet_type) ERROR_MESSAGE_FROM_ENUM(VORBIS_cant_find_last_page) ERROR_MESSAGE_FROM_ENUM(VORBIS_seek_failed) default: return ""; } } } _category; return _category; } vorbisbuf::channelbuf::channelbuf(vorbisbuf& src): m_src(src) {} auto vorbisbuf::channelbuf::underflow() -> int_type { ++m_debug_underflow_count; if(!m_src.decode_next_frame()) return traits_type::eof(); if(m_decoded_buffer.empty()) return traits_type::eof(); return traits_type::not_eof(m_decoded_buffer[0]); } std::streamsize vorbisbuf::channelbuf::xsgetn(char_type* s, std::streamsize count) { size_t data_copied = 0; while(1) { size_t data_to_copy = std::min(static_cast<size_t>(std::distance(gptr(), egptr())), count - data_copied); std::memcpy(s + data_copied, gptr(), data_to_copy); data_copied += data_to_copy; setg(eback(), gptr() + data_to_copy, egptr()); if(data_copied == static_cast<size_t>(count)) { return data_copied; } if(underflow() == traits_type::eof()) return data_copied; } } void vorbisbuf::channelbuf::push_data(char_type const* data_begin, size_t data_size) { ++m_debug_push_data_count; size_t old_data_still_valid = std::distance(gptr(), egptr()); size_t final_size = old_data_still_valid + data_size; if(final_size <= m_decoded_buffer.capacity()) { std::memmove(m_decoded_buffer.data(), gptr(), old_data_still_valid); m_decoded_buffer.resize(final_size); std::memcpy(m_decoded_buffer.data() + old_data_still_valid, data_begin, data_size); } else { decltype(m_decoded_buffer) new_buffer(final_size); std::memcpy(new_buffer.data(), gptr(), old_data_still_valid); std::memcpy(new_buffer.data() + old_data_still_valid, data_begin, data_size); std::swap(m_decoded_buffer, new_buffer); } setg(&*begin(m_decoded_buffer), &*begin(m_decoded_buffer), &*end(m_decoded_buffer)); } void vorbisbuf::stb_vorbis_deleter::operator()(stb_vorbis* v) { stb_vorbis_close(v); } vorbisbuf::vorbisbuf(std::streambuf* streambuf): m_streambuf(streambuf), m_buffer(32, 0) { //! Remember to open the file like this std::ifstream file("file.ogg", std::ios::in | std::ios::binary); or you might have problem with EOF in the middle of nowhere. auto next = m_buffer.begin(); try_open_vorbis_header: { std::streamsize get_result = m_streambuf->sgetn(&*next, std::distance(next, m_buffer.end())); if(get_result == 0) throw std::system_error(VORBIS_unexpected_eof, vorbisbuf_error_category()); next += get_result; int data_used = 0; int error = 0; m_vorbis.reset(stb_vorbis_open_pushdata(reinterpret_cast<unsigned char*>(m_buffer.data()), std::distance(m_buffer.begin(), next), &data_used, &error, nullptr)); if(error == STBVorbisError::VORBIS_need_more_data) { size_t n = std::distance(m_buffer.begin(), next); m_buffer.resize(m_buffer.size()*2);//Grow by powers of 2 next = m_buffer.begin() + n; goto try_open_vorbis_header; } if(error) throw std::system_error(error, vorbisbuf_error_category()); std::memmove(&*begin(m_buffer), &*(begin(m_buffer) + data_used), m_buffer.size() - data_used); m_current = begin(m_buffer) + m_buffer.size() - data_used; } stb_vorbis_info infos = stb_vorbis_get_info(m_vorbis.get()); m_sample_rate = infos.sample_rate; for(int i = 0; i < infos.channels; ++i) m_channels.emplace_back(new channelbuf(*this)); } auto vorbisbuf::channel(unsigned int id) -> channelbuf& { return *m_channels.at(id); } unsigned int vorbisbuf::channels_nb() { return m_channels.size(); } unsigned int vorbisbuf::sample_rate() { return m_sample_rate; } auto vorbisbuf::underflow() -> int_type { if(channels_nb() == 0) return traits_type::eof(); ///TODO à refaire, un appel à setg() est nécessaire size_t pcm_current = m_pcm_current_channel; (++m_pcm_current_channel) %= channels_nb(); return m_channels[pcm_current]->sbumpc(); } bool vorbisbuf::decode_next_frame() { auto next = m_current == end(m_buffer) ? begin(m_buffer) : m_current; try_decode_frame: { std::streamsize get_result = m_streambuf->sgetn(&*next, std::distance(next, m_buffer.end())); next += get_result; int data_used = 0; int channels = 0; float** decoded_output = nullptr; int samples = 0; data_used = stb_vorbis_decode_frame_pushdata( m_vorbis.get(), reinterpret_cast<unsigned char*>(m_buffer.data()), std::distance(begin(m_buffer), next), &channels, &decoded_output, &samples ); if(data_used == 0)//(need more data) { int error = stb_vorbis_get_error(m_vorbis.get()); if(error && error != STBVorbisError::VORBIS_need_more_data) throw std::system_error(error, vorbisbuf_error_category()); if(get_result == 0) return false;//EOF size_t n = std::distance(m_buffer.begin(), next); m_buffer.resize(m_buffer.size()*2);//Grow by powers of 2 next = m_buffer.begin() + n; goto try_decode_frame; } size_t data_ready = std::distance(begin(m_buffer) + data_used, next); std::memmove(&*begin(m_buffer), &*(begin(m_buffer) + data_used), data_ready); m_current = begin(m_buffer) + data_ready; if(samples == 0)//(resynching the stream, keep going) { next = m_current == end(m_buffer) ? begin(m_buffer) : m_current; goto try_decode_frame; } //For each channel output transform float32 to int16 & push it to the corresponding channelbuf buffer for(int channel_id = 0; channel_id < channels; ++channel_id) { char* decoded_buffer_f = reinterpret_cast<char*>(decoded_output[channel_id]); //Rewrite the decoded float buffer with int16_t equivalent { char* write = decoded_buffer_f; float* read = reinterpret_cast<float*>(decoded_buffer_f); for(; write != decoded_buffer_f + samples*sizeof(int16_t); write += sizeof(int16_t), ++read) { //x(s) = x(f)*[max(s) - min(s)]/[max(f) - min(f)] + min(s) - min(f)*[max(s) - min(s)]/[max(f) - min(f)] //For equivalence, we take max(s) = -min(s), so that there are as many + numbers than - numbers //In case x(f) == 1.f, x(s) would be max(s) + 1, so we round it up to max(s) *reinterpret_cast<int16_t*>(write) = (*read) >= 1.f ? 0x7FFF : (*read) < -1.f ? 0x8000 : static_cast<int16_t>((*read)*0x8000); } } m_channels[channel_id]->push_data(decoded_buffer_f, samples*sizeof(int16_t)); } } return true; } } <|endoftext|>
<commit_before>#include "instanciate.h" using namespace Yuni; namespace Nany { namespace Pass { namespace Instanciate { namespace // anonymous { static inline bool debugResolveListOnlyContainsFunc(const std::vector<std::reference_wrapper<Atom>>& list) { for (auto& atom: list) { if (not atom.get().isFunction()) return true; } return false; } } // anonymous namespace inline bool ProgramBuilder::identify(const IR::ISA::Operand<IR::ISA::Op::identify>& operands) { auto& frame = atomStack.back(); AnyString name = currentProgram.stringrefs[operands.text]; // keeping traces of the code logic frame.lvids[operands.lvid].resolvedName = name; frame.lvids[operands.lvid].referer = operands.self; if (name == '=') // it is an assignment, not a real method call { // remember this special case frame.lvids[operands.lvid].isAssignment = true; // for consistency checks, after transformations on the AST, '=' should be a method call // we should have something like: 'foo.=(rhs)' if (unlikely(0 == operands.self)) return complainInvalidSelfRefForVariableAssignment(operands.lvid); return true; } if (operands.self != 0) { if (not frame.verify(operands.self)) return false; if (frame.lvids[operands.self].isAssignment) { // since self was marked as an 'assignment', we're trying to resolve here '^()' if (unlikely(name != "^()")) { ICE() << "invalid resolve name for assignment (got '" << name << "')"; return false; } // remember this special case frame.lvids[operands.lvid].isAssignment = true; return true; } } auto& cdef = cdeftable.classdef(CLID{frame.atomid, operands.lvid}); // checking if the lvid does not map to a parameter, which must // have already be resolved when instanciating the function assert(cdef.clid.lvid() >= 2 + frame.atom.parameters.size()); if (unlikely(cdef.clid.lvid() < 2 + frame.atom.parameters.size())) { String errmsg; errmsg << CLID{frame.atomid, operands.lvid} << ": should be alreayd resolved"; return complainOperand(reinterpret_cast<const IR::Instruction&>(operands), errmsg); } // list of all possible atoms when resolving 'name' multipleResults.clear(); // Self, if any Atom* selfAtom = nullptr; // local variable ? bool isLocalVariable = false; if (0 == operands.self) { // simple variable, function, namespace... // checking first for builtin identifiers (void, any...) switch (name[0]) { case 'a': { if (name == "any") // any - nothing to resolve { multipleResults.clear(); frame.lvids[operands.lvid].markedAsAny = true; frame.resolvePerCLID[cdef.clid].clear(); cdeftable.substitute(operands.lvid).mutateToAny(); return true; } break; } case 'v': { if (name == "void") { multipleResults.clear(); frame.resolvePerCLID[cdef.clid].clear(); cdeftable.substitute(operands.lvid).mutateToVoid(); return true; } break; } case '_': { if (name[1] == '_') { multipleResults.clear(); frame.resolvePerCLID[cdef.clid].clear(); // just in case if (name == "__false") { auto& opc = cdeftable.substitute(operands.lvid); opc.mutateToBuiltin(nyt_bool); opc.qualifiers.ref = false; out.emitStore_u64(operands.lvid, 0); return true; } if (name == "__true") { auto& opc = cdeftable.substitute(operands.lvid); opc.mutateToBuiltin(nyt_bool); opc.qualifiers.ref = false; out.emitStore_u64(operands.lvid, 1); return true; } else { nytype_t type = nany_cstring_to_type_n(name.c_str(), (uint)name.size()); if (unlikely(type == nyt_void)) return complainUnknownBuiltinType(name); cdeftable.substitute(operands.lvid).mutateToBuiltin(type); return true; } return false; } break; } } // trying for local variables first LVID lvidVar = frame.findLocalVariable(name); if (lvidVar != 0) { // the variable is used, whatever it is (error or not) frame.lvids[lvidVar].hasBeenUsed = true; frame.lvids[operands.lvid].alias = lvidVar; if (not frame.verify(lvidVar)) // suppress spurious errors from previous ones return false; // acquire the variable if (canGenerateCode()) out.emitStore(operands.lvid, lvidVar); auto& varcdef = cdeftable.classdef(CLID{frame.atomid, lvidVar}); if (not varcdef.isBuiltin()) { auto* varAtom = cdeftable.findClassdefAtom(varcdef); if (unlikely(varAtom == nullptr)) { ICE() << "invalid atom for local scope variable. clid: " << CLID{frame.atomid, lvidVar} << ", " << (uint32_t) varcdef.kind; return false; } multipleResults.emplace_back(std::ref(*varAtom)); isLocalVariable = true; } else { // special case - not an atom auto& spare = cdeftable.substitute(cdef.clid.lvid()); spare.mutateToBuiltin(varcdef.kind); spare.qualifiers.ref = false; return true; } } else { if (not frame.atom.performNameLookupOnChildren(multipleResults, name)) { if (frame.atom.parent) frame.atom.parent->performNameLookupFromParent(multipleResults, name); } } } else { // self.<something to identify> if (unlikely(frame.lvids[operands.lvid].markedAsAny)) { ICE() << "can not perform member lookup on 'any'"; return false; } auto& self = cdeftable.classdef(CLID{frame.atomid, operands.self}); if (unlikely(self.isBuiltinOrVoid())) return complainInvalidMemberRequestNonClass(name, self.kind); selfAtom = cdeftable.findClassdefAtom(self); if (selfAtom != nullptr) // the parent has been fully resolved { // since the parent has been fully resolved, no multiple // solution should be available assert(frame.resolvePerCLID[self.clid].empty()); selfAtom->performNameLookupOnChildren(multipleResults, name); } else { auto& selfSolutions = frame.resolvePerCLID[self.clid]; multipleResults.reserve(selfSolutions.size()); for (auto& atomElement: selfSolutions) atomElement.get().performNameLookupOnChildren(multipleResults, name); } } switch (multipleResults.size()) { case 1: // unique match count { auto& atom = multipleResults[0].get(); if (unlikely(atom.hasErrors)) return false; // if the resolution is simple (aka only one solution), it is possible that the // solution is a member variable. In this case, the atom will be the member itself // and not its real type if (atom.isMemberVariable()) { assert(not isLocalVariable and "a member variable cannot be a local variable"); // member variable - the real type is held by 'returnType' auto& cdefvar = cdeftable.classdef(atom.returnType.clid); auto* atomvar = cdeftable.findClassdefAtom(cdefvar); if (unlikely(not (atomvar or cdefvar.isBuiltin()))) return (ICE() << "invalid variable member type for " << atom.printFullname()); auto& spare = cdeftable.substitute(operands.lvid); spare.import(cdefvar); if (atomvar) spare.mutateToAtom(atomvar); auto& origin = frame.lvids[operands.lvid].origin.varMember; origin.self = operands.self; origin.atomid = atom.atomid; origin.field = atom.varinfo.effectiveFieldIndex; if (canGenerateCode()) { // read the address uint32_t self = operands.self; if (self == 0) { // retrieving the local self if (likely(frame.atom.isClassMember())) self = 2; // 1: return type, 2: self parameter else { ICE() << "invalid 'self' object"; return false; } } out.emitFieldget(operands.lvid, self, atom.varinfo.effectiveFieldIndex); tryToAcquireObject(operands.lvid, cdefvar); } } else { // override the typeinfo auto& spare = cdeftable.substitute(cdef.clid.lvid()); spare.import(cdef); spare.mutateToAtom(&atom); if (isLocalVariable) { // disable optimisation to avoid unwanted behavior auto& origin = frame.lvids[operands.lvid].origin; origin.memalloc = false; origin.returnedValue = false; if (canGenerateCode()) acquireObject(operands.lvid); } } // instanciating the type itself, to resolve member variables if (atom.isClass() and not atom.classinfo.isInstanciated) return instanciateAtomClass(atom); return true; } default: // multiple solutions { // checking integrity (debug only) - verifying that all results are functions if (debugmode) { if (unlikely(debugResolveListOnlyContainsFunc(multipleResults))) return complainOperand((const IR::Instruction&) operands, "resolve-list contains something else than functions"); } // multiple solutions are possible (probably for a func call) // keeping the solutions for later resolution by the real func call // (with parameters to find the most appropriate one) frame.resolvePerCLID[cdef.clid].swap(multipleResults); return true; } case 0: // no identifier found from 'atom map' { return complainUnknownIdentifier(selfAtom, frame.atom, name); } } return false; } void ProgramBuilder::visit(const IR::ISA::Operand<IR::ISA::Op::identify>& operands) { assert(not atomStack.empty()); bool ok = identify(operands); if (unlikely(not ok)) atomStack.back().invalidate(operands.lvid); } } // namespace Instanciate } // namespace Pass } // namespace Nany <commit_msg>added keyword 'null'<commit_after>#include "instanciate.h" using namespace Yuni; namespace Nany { namespace Pass { namespace Instanciate { namespace // anonymous { static inline bool debugResolveListOnlyContainsFunc(const std::vector<std::reference_wrapper<Atom>>& list) { for (auto& atom: list) { if (not atom.get().isFunction()) return true; } return false; } } // anonymous namespace inline bool ProgramBuilder::identify(const IR::ISA::Operand<IR::ISA::Op::identify>& operands) { auto& frame = atomStack.back(); AnyString name = currentProgram.stringrefs[operands.text]; // keeping traces of the code logic frame.lvids[operands.lvid].resolvedName = name; frame.lvids[operands.lvid].referer = operands.self; if (name == '=') // it is an assignment, not a real method call { // remember this special case frame.lvids[operands.lvid].isAssignment = true; // for consistency checks, after transformations on the AST, '=' should be a method call // we should have something like: 'foo.=(rhs)' if (unlikely(0 == operands.self)) return complainInvalidSelfRefForVariableAssignment(operands.lvid); return true; } if (operands.self != 0) { if (not frame.verify(operands.self)) return false; if (frame.lvids[operands.self].isAssignment) { // since self was marked as an 'assignment', we're trying to resolve here '^()' if (unlikely(name != "^()")) { ICE() << "invalid resolve name for assignment (got '" << name << "')"; return false; } // remember this special case frame.lvids[operands.lvid].isAssignment = true; return true; } } auto& cdef = cdeftable.classdef(CLID{frame.atomid, operands.lvid}); // checking if the lvid does not map to a parameter, which must // have already be resolved when instanciating the function assert(cdef.clid.lvid() >= 2 + frame.atom.parameters.size()); if (unlikely(cdef.clid.lvid() < 2 + frame.atom.parameters.size())) { String errmsg; errmsg << CLID{frame.atomid, operands.lvid} << ": should be alreayd resolved"; return complainOperand(reinterpret_cast<const IR::Instruction&>(operands), errmsg); } // list of all possible atoms when resolving 'name' multipleResults.clear(); // Self, if any Atom* selfAtom = nullptr; // local variable ? bool isLocalVariable = false; if (0 == operands.self) { // simple variable, function, namespace... // checking first for builtin identifiers (void, any...) switch (name[0]) { case 'a': { if (name == "any") // any - nothing to resolve { multipleResults.clear(); frame.lvids[operands.lvid].markedAsAny = true; frame.resolvePerCLID[cdef.clid].clear(); cdeftable.substitute(operands.lvid).mutateToAny(); return true; } break; } case 'n': { if (name == "null") { multipleResults.clear(); frame.resolvePerCLID[cdef.clid].clear(); // just in case auto& opc = cdeftable.substitute(operands.lvid); opc.mutateToBuiltin(nyt_pointer); opc.qualifiers.ref = false; out.emitStore_u64(operands.lvid, 0); return true; } break; } case 'v': { if (name == "void") { multipleResults.clear(); frame.resolvePerCLID[cdef.clid].clear(); cdeftable.substitute(operands.lvid).mutateToVoid(); return true; } break; } case '_': { if (name[1] == '_') { multipleResults.clear(); frame.resolvePerCLID[cdef.clid].clear(); // just in case if (name == "__false") { auto& opc = cdeftable.substitute(operands.lvid); opc.mutateToBuiltin(nyt_bool); opc.qualifiers.ref = false; out.emitStore_u64(operands.lvid, 0); return true; } if (name == "__true") { auto& opc = cdeftable.substitute(operands.lvid); opc.mutateToBuiltin(nyt_bool); opc.qualifiers.ref = false; out.emitStore_u64(operands.lvid, 1); return true; } else { nytype_t type = nany_cstring_to_type_n(name.c_str(), (uint)name.size()); if (unlikely(type == nyt_void)) return complainUnknownBuiltinType(name); cdeftable.substitute(operands.lvid).mutateToBuiltin(type); return true; } return false; } break; } } // trying for local variables first LVID lvidVar = frame.findLocalVariable(name); if (lvidVar != 0) { // the variable is used, whatever it is (error or not) frame.lvids[lvidVar].hasBeenUsed = true; frame.lvids[operands.lvid].alias = lvidVar; if (not frame.verify(lvidVar)) // suppress spurious errors from previous ones return false; // acquire the variable if (canGenerateCode()) out.emitStore(operands.lvid, lvidVar); auto& varcdef = cdeftable.classdef(CLID{frame.atomid, lvidVar}); if (not varcdef.isBuiltin()) { auto* varAtom = cdeftable.findClassdefAtom(varcdef); if (unlikely(varAtom == nullptr)) { ICE() << "invalid atom for local scope variable. clid: " << CLID{frame.atomid, lvidVar} << ", " << (uint32_t) varcdef.kind; return false; } multipleResults.emplace_back(std::ref(*varAtom)); isLocalVariable = true; } else { // special case - not an atom auto& spare = cdeftable.substitute(cdef.clid.lvid()); spare.mutateToBuiltin(varcdef.kind); spare.qualifiers.ref = false; return true; } } else { if (not frame.atom.performNameLookupOnChildren(multipleResults, name)) { if (frame.atom.parent) frame.atom.parent->performNameLookupFromParent(multipleResults, name); } } } else { // self.<something to identify> if (unlikely(frame.lvids[operands.lvid].markedAsAny)) { ICE() << "can not perform member lookup on 'any'"; return false; } auto& self = cdeftable.classdef(CLID{frame.atomid, operands.self}); if (unlikely(self.isBuiltinOrVoid())) return complainInvalidMemberRequestNonClass(name, self.kind); selfAtom = cdeftable.findClassdefAtom(self); if (selfAtom != nullptr) // the parent has been fully resolved { // since the parent has been fully resolved, no multiple // solution should be available assert(frame.resolvePerCLID[self.clid].empty()); selfAtom->performNameLookupOnChildren(multipleResults, name); } else { auto& selfSolutions = frame.resolvePerCLID[self.clid]; multipleResults.reserve(selfSolutions.size()); for (auto& atomElement: selfSolutions) atomElement.get().performNameLookupOnChildren(multipleResults, name); } } switch (multipleResults.size()) { case 1: // unique match count { auto& atom = multipleResults[0].get(); if (unlikely(atom.hasErrors)) return false; // if the resolution is simple (aka only one solution), it is possible that the // solution is a member variable. In this case, the atom will be the member itself // and not its real type if (atom.isMemberVariable()) { assert(not isLocalVariable and "a member variable cannot be a local variable"); // member variable - the real type is held by 'returnType' auto& cdefvar = cdeftable.classdef(atom.returnType.clid); auto* atomvar = cdeftable.findClassdefAtom(cdefvar); if (unlikely(not (atomvar or cdefvar.isBuiltin()))) return (ICE() << "invalid variable member type for " << atom.printFullname()); auto& spare = cdeftable.substitute(operands.lvid); spare.import(cdefvar); if (atomvar) spare.mutateToAtom(atomvar); auto& origin = frame.lvids[operands.lvid].origin.varMember; origin.self = operands.self; origin.atomid = atom.atomid; origin.field = atom.varinfo.effectiveFieldIndex; if (canGenerateCode()) { // read the address uint32_t self = operands.self; if (self == 0) { // retrieving the local self if (likely(frame.atom.isClassMember())) self = 2; // 1: return type, 2: self parameter else { ICE() << "invalid 'self' object"; return false; } } out.emitFieldget(operands.lvid, self, atom.varinfo.effectiveFieldIndex); tryToAcquireObject(operands.lvid, cdefvar); } } else { // override the typeinfo auto& spare = cdeftable.substitute(cdef.clid.lvid()); spare.import(cdef); spare.mutateToAtom(&atom); if (isLocalVariable) { // disable optimisation to avoid unwanted behavior auto& origin = frame.lvids[operands.lvid].origin; origin.memalloc = false; origin.returnedValue = false; if (canGenerateCode()) acquireObject(operands.lvid); } } // instanciating the type itself, to resolve member variables if (atom.isClass() and not atom.classinfo.isInstanciated) return instanciateAtomClass(atom); return true; } default: // multiple solutions { // checking integrity (debug only) - verifying that all results are functions if (debugmode) { if (unlikely(debugResolveListOnlyContainsFunc(multipleResults))) return complainOperand((const IR::Instruction&) operands, "resolve-list contains something else than functions"); } // multiple solutions are possible (probably for a func call) // keeping the solutions for later resolution by the real func call // (with parameters to find the most appropriate one) frame.resolvePerCLID[cdef.clid].swap(multipleResults); return true; } case 0: // no identifier found from 'atom map' { return complainUnknownIdentifier(selfAtom, frame.atom, name); } } return false; } void ProgramBuilder::visit(const IR::ISA::Operand<IR::ISA::Op::identify>& operands) { assert(not atomStack.empty()); bool ok = identify(operands); if (unlikely(not ok)) atomStack.back().invalidate(operands.lvid); } } // namespace Instanciate } // namespace Pass } // namespace Nany <|endoftext|>
<commit_before>//===-- hwasan_interceptors.cc --------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of HWAddressSanitizer. // // Interceptors for standard library functions. // // FIXME: move as many interceptors as possible into // sanitizer_common/sanitizer_common_interceptors.h //===----------------------------------------------------------------------===// #include "interception/interception.h" #include "hwasan.h" #include "hwasan_allocator.h" #include "hwasan_mapping.h" #include "hwasan_thread.h" #include "hwasan_poisoning.h" #include "hwasan_report.h" #include "sanitizer_common/sanitizer_platform_limits_posix.h" #include "sanitizer_common/sanitizer_allocator.h" #include "sanitizer_common/sanitizer_allocator_interface.h" #include "sanitizer_common/sanitizer_allocator_internal.h" #include "sanitizer_common/sanitizer_atomic.h" #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_errno.h" #include "sanitizer_common/sanitizer_stackdepot.h" #include "sanitizer_common/sanitizer_libc.h" #include "sanitizer_common/sanitizer_linux.h" #include "sanitizer_common/sanitizer_tls_get_addr.h" #include <stdarg.h> // ACHTUNG! No other system header includes in this file. // Ideally, we should get rid of stdarg.h as well. using namespace __hwasan; using __sanitizer::memory_order; using __sanitizer::atomic_load; using __sanitizer::atomic_store; using __sanitizer::atomic_uintptr_t; bool IsInInterceptorScope() { Thread *t = GetCurrentThread(); return t && t->InInterceptorScope(); } struct InterceptorScope { InterceptorScope() { Thread *t = GetCurrentThread(); if (t) t->EnterInterceptorScope(); } ~InterceptorScope() { Thread *t = GetCurrentThread(); if (t) t->LeaveInterceptorScope(); } }; static uptr allocated_for_dlsym; static const uptr kDlsymAllocPoolSize = 1024; static uptr alloc_memory_for_dlsym[kDlsymAllocPoolSize]; static bool IsInDlsymAllocPool(const void *ptr) { uptr off = (uptr)ptr - (uptr)alloc_memory_for_dlsym; return off < sizeof(alloc_memory_for_dlsym); } static void *AllocateFromLocalPool(uptr size_in_bytes) { uptr size_in_words = RoundUpTo(size_in_bytes, kWordSize) / kWordSize; void *mem = (void *)&alloc_memory_for_dlsym[allocated_for_dlsym]; allocated_for_dlsym += size_in_words; CHECK_LT(allocated_for_dlsym, kDlsymAllocPoolSize); return mem; } #define ENSURE_HWASAN_INITED() do { \ CHECK(!hwasan_init_is_running); \ if (!hwasan_inited) { \ __hwasan_init(); \ } \ } while (0) int __sanitizer_posix_memalign(void **memptr, uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; CHECK_NE(memptr, 0); int res = hwasan_posix_memalign(memptr, alignment, size, &stack); return res; } void * __sanitizer_memalign(uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_memalign(alignment, size, &stack); } void * __sanitizer_aligned_alloc(uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_aligned_alloc(alignment, size, &stack); } void * __sanitizer___libc_memalign(uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; void *ptr = hwasan_memalign(alignment, size, &stack); if (ptr) DTLS_on_libc_memalign(ptr, size); return ptr; } void * __sanitizer_valloc(uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_valloc(size, &stack); } void * __sanitizer_pvalloc(uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_pvalloc(size, &stack); } void __sanitizer_free(void *ptr) { GET_MALLOC_STACK_TRACE; if (!ptr || UNLIKELY(IsInDlsymAllocPool(ptr))) return; hwasan_free(ptr, &stack); } void __sanitizer_cfree(void *ptr) { GET_MALLOC_STACK_TRACE; if (!ptr || UNLIKELY(IsInDlsymAllocPool(ptr))) return; hwasan_free(ptr, &stack); } uptr __sanitizer_malloc_usable_size(const void *ptr) { return __sanitizer_get_allocated_size(ptr); } struct __sanitizer_struct_mallinfo __sanitizer_mallinfo() { __sanitizer_struct_mallinfo sret; internal_memset(&sret, 0, sizeof(sret)); return sret; } int __sanitizer_mallopt(int cmd, int value) { return 0; } void __sanitizer_malloc_stats(void) { // FIXME: implement, but don't call REAL(malloc_stats)! } void * __sanitizer_calloc(uptr nmemb, uptr size) { GET_MALLOC_STACK_TRACE; if (UNLIKELY(!hwasan_inited)) // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym. return AllocateFromLocalPool(nmemb * size); return hwasan_calloc(nmemb, size, &stack); } void * __sanitizer_realloc(void *ptr, uptr size) { GET_MALLOC_STACK_TRACE; if (UNLIKELY(IsInDlsymAllocPool(ptr))) { uptr offset = (uptr)ptr - (uptr)alloc_memory_for_dlsym; uptr copy_size = Min(size, kDlsymAllocPoolSize - offset); void *new_ptr; if (UNLIKELY(!hwasan_inited)) { new_ptr = AllocateFromLocalPool(copy_size); } else { copy_size = size; new_ptr = hwasan_malloc(copy_size, &stack); } internal_memcpy(new_ptr, ptr, copy_size); return new_ptr; } return hwasan_realloc(ptr, size, &stack); } void * __sanitizer_malloc(uptr size) { GET_MALLOC_STACK_TRACE; if (UNLIKELY(!hwasan_init_is_running)) ENSURE_HWASAN_INITED(); if (UNLIKELY(!hwasan_inited)) // Hack: dlsym calls malloc before REAL(malloc) is retrieved from dlsym. return AllocateFromLocalPool(size); return hwasan_malloc(size, &stack); } #if HWASAN_WITH_INTERCEPTORS #define INTERCEPTOR_ALIAS(RET, FN, ARGS...) \ extern "C" SANITIZER_INTERFACE_ATTRIBUTE RET WRAP(FN)(ARGS) \ ALIAS("__sanitizer_" #FN); \ extern "C" SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE RET FN( \ ARGS) ALIAS("__sanitizer_" #FN) INTERCEPTOR_ALIAS(int, posix_memalign, void **memptr, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, aligned_alloc, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, __libc_memalign, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, valloc, SIZE_T size); INTERCEPTOR_ALIAS(void, free, void *ptr); INTERCEPTOR_ALIAS(uptr, malloc_usable_size, const void *ptr); INTERCEPTOR_ALIAS(void *, calloc, SIZE_T nmemb, SIZE_T size); INTERCEPTOR_ALIAS(void *, realloc, void *ptr, SIZE_T size); INTERCEPTOR_ALIAS(void *, malloc, SIZE_T size); #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR_ALIAS(void *, memalign, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, pvalloc, SIZE_T size); INTERCEPTOR_ALIAS(void, cfree, void *ptr); INTERCEPTOR_ALIAS(__sanitizer_struct_mallinfo, mallinfo); INTERCEPTOR_ALIAS(int, mallopt, int cmd, int value); INTERCEPTOR_ALIAS(void, malloc_stats, void); #endif #endif // HWASAN_WITH_INTERCEPTORS static void BeforeFork() { StackDepotLockAll(); } static void AfterFork() { StackDepotUnlockAll(); } INTERCEPTOR(int, fork, void) { ENSURE_HWASAN_INITED(); BeforeFork(); int pid = REAL(fork)(); AfterFork(); return pid; } struct HwasanInterceptorContext { bool in_interceptor_scope; }; namespace __hwasan { int OnExit() { // FIXME: ask frontend whether we need to return failure. return 0; } } // namespace __hwasan namespace __hwasan { void InitializeInterceptors() { static int inited = 0; CHECK_EQ(inited, 0); INTERCEPT_FUNCTION(fork); #if HWASAN_WITH_INTERCEPTORS INTERCEPT_FUNCTION(realloc); INTERCEPT_FUNCTION(free); #endif inited = 1; } } // namespace __hwasan <commit_msg>Bring back the pthread_create interceptor, but only on non-aarch64.<commit_after>//===-- hwasan_interceptors.cc --------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of HWAddressSanitizer. // // Interceptors for standard library functions. // // FIXME: move as many interceptors as possible into // sanitizer_common/sanitizer_common_interceptors.h //===----------------------------------------------------------------------===// #include "interception/interception.h" #include "hwasan.h" #include "hwasan_allocator.h" #include "hwasan_mapping.h" #include "hwasan_thread.h" #include "hwasan_poisoning.h" #include "hwasan_report.h" #include "sanitizer_common/sanitizer_platform_limits_posix.h" #include "sanitizer_common/sanitizer_allocator.h" #include "sanitizer_common/sanitizer_allocator_interface.h" #include "sanitizer_common/sanitizer_allocator_internal.h" #include "sanitizer_common/sanitizer_atomic.h" #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_errno.h" #include "sanitizer_common/sanitizer_stackdepot.h" #include "sanitizer_common/sanitizer_libc.h" #include "sanitizer_common/sanitizer_linux.h" #include "sanitizer_common/sanitizer_tls_get_addr.h" #include <stdarg.h> // ACHTUNG! No other system header includes in this file. // Ideally, we should get rid of stdarg.h as well. using namespace __hwasan; using __sanitizer::memory_order; using __sanitizer::atomic_load; using __sanitizer::atomic_store; using __sanitizer::atomic_uintptr_t; bool IsInInterceptorScope() { Thread *t = GetCurrentThread(); return t && t->InInterceptorScope(); } struct InterceptorScope { InterceptorScope() { Thread *t = GetCurrentThread(); if (t) t->EnterInterceptorScope(); } ~InterceptorScope() { Thread *t = GetCurrentThread(); if (t) t->LeaveInterceptorScope(); } }; static uptr allocated_for_dlsym; static const uptr kDlsymAllocPoolSize = 1024; static uptr alloc_memory_for_dlsym[kDlsymAllocPoolSize]; static bool IsInDlsymAllocPool(const void *ptr) { uptr off = (uptr)ptr - (uptr)alloc_memory_for_dlsym; return off < sizeof(alloc_memory_for_dlsym); } static void *AllocateFromLocalPool(uptr size_in_bytes) { uptr size_in_words = RoundUpTo(size_in_bytes, kWordSize) / kWordSize; void *mem = (void *)&alloc_memory_for_dlsym[allocated_for_dlsym]; allocated_for_dlsym += size_in_words; CHECK_LT(allocated_for_dlsym, kDlsymAllocPoolSize); return mem; } #define ENSURE_HWASAN_INITED() do { \ CHECK(!hwasan_init_is_running); \ if (!hwasan_inited) { \ __hwasan_init(); \ } \ } while (0) int __sanitizer_posix_memalign(void **memptr, uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; CHECK_NE(memptr, 0); int res = hwasan_posix_memalign(memptr, alignment, size, &stack); return res; } void * __sanitizer_memalign(uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_memalign(alignment, size, &stack); } void * __sanitizer_aligned_alloc(uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_aligned_alloc(alignment, size, &stack); } void * __sanitizer___libc_memalign(uptr alignment, uptr size) { GET_MALLOC_STACK_TRACE; void *ptr = hwasan_memalign(alignment, size, &stack); if (ptr) DTLS_on_libc_memalign(ptr, size); return ptr; } void * __sanitizer_valloc(uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_valloc(size, &stack); } void * __sanitizer_pvalloc(uptr size) { GET_MALLOC_STACK_TRACE; return hwasan_pvalloc(size, &stack); } void __sanitizer_free(void *ptr) { GET_MALLOC_STACK_TRACE; if (!ptr || UNLIKELY(IsInDlsymAllocPool(ptr))) return; hwasan_free(ptr, &stack); } void __sanitizer_cfree(void *ptr) { GET_MALLOC_STACK_TRACE; if (!ptr || UNLIKELY(IsInDlsymAllocPool(ptr))) return; hwasan_free(ptr, &stack); } uptr __sanitizer_malloc_usable_size(const void *ptr) { return __sanitizer_get_allocated_size(ptr); } struct __sanitizer_struct_mallinfo __sanitizer_mallinfo() { __sanitizer_struct_mallinfo sret; internal_memset(&sret, 0, sizeof(sret)); return sret; } int __sanitizer_mallopt(int cmd, int value) { return 0; } void __sanitizer_malloc_stats(void) { // FIXME: implement, but don't call REAL(malloc_stats)! } void * __sanitizer_calloc(uptr nmemb, uptr size) { GET_MALLOC_STACK_TRACE; if (UNLIKELY(!hwasan_inited)) // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym. return AllocateFromLocalPool(nmemb * size); return hwasan_calloc(nmemb, size, &stack); } void * __sanitizer_realloc(void *ptr, uptr size) { GET_MALLOC_STACK_TRACE; if (UNLIKELY(IsInDlsymAllocPool(ptr))) { uptr offset = (uptr)ptr - (uptr)alloc_memory_for_dlsym; uptr copy_size = Min(size, kDlsymAllocPoolSize - offset); void *new_ptr; if (UNLIKELY(!hwasan_inited)) { new_ptr = AllocateFromLocalPool(copy_size); } else { copy_size = size; new_ptr = hwasan_malloc(copy_size, &stack); } internal_memcpy(new_ptr, ptr, copy_size); return new_ptr; } return hwasan_realloc(ptr, size, &stack); } void * __sanitizer_malloc(uptr size) { GET_MALLOC_STACK_TRACE; if (UNLIKELY(!hwasan_init_is_running)) ENSURE_HWASAN_INITED(); if (UNLIKELY(!hwasan_inited)) // Hack: dlsym calls malloc before REAL(malloc) is retrieved from dlsym. return AllocateFromLocalPool(size); return hwasan_malloc(size, &stack); } #if HWASAN_WITH_INTERCEPTORS #define INTERCEPTOR_ALIAS(RET, FN, ARGS...) \ extern "C" SANITIZER_INTERFACE_ATTRIBUTE RET WRAP(FN)(ARGS) \ ALIAS("__sanitizer_" #FN); \ extern "C" SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE RET FN( \ ARGS) ALIAS("__sanitizer_" #FN) INTERCEPTOR_ALIAS(int, posix_memalign, void **memptr, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, aligned_alloc, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, __libc_memalign, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, valloc, SIZE_T size); INTERCEPTOR_ALIAS(void, free, void *ptr); INTERCEPTOR_ALIAS(uptr, malloc_usable_size, const void *ptr); INTERCEPTOR_ALIAS(void *, calloc, SIZE_T nmemb, SIZE_T size); INTERCEPTOR_ALIAS(void *, realloc, void *ptr, SIZE_T size); INTERCEPTOR_ALIAS(void *, malloc, SIZE_T size); #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR_ALIAS(void *, memalign, SIZE_T alignment, SIZE_T size); INTERCEPTOR_ALIAS(void *, pvalloc, SIZE_T size); INTERCEPTOR_ALIAS(void, cfree, void *ptr); INTERCEPTOR_ALIAS(__sanitizer_struct_mallinfo, mallinfo); INTERCEPTOR_ALIAS(int, mallopt, int cmd, int value); INTERCEPTOR_ALIAS(void, malloc_stats, void); #endif #endif // HWASAN_WITH_INTERCEPTORS #if HWASAN_WITH_INTERCEPTORS && !defined(__aarch64__) INTERCEPTOR(int, pthread_create, void *th, void *attr, void *(*callback)(void *), void *param) { ScopedTaggingDisabler disabler; int res = REAL(pthread_create)(UntagPtr(th), UntagPtr(attr), callback, param); return res; } #endif static void BeforeFork() { StackDepotLockAll(); } static void AfterFork() { StackDepotUnlockAll(); } INTERCEPTOR(int, fork, void) { ENSURE_HWASAN_INITED(); BeforeFork(); int pid = REAL(fork)(); AfterFork(); return pid; } struct HwasanInterceptorContext { bool in_interceptor_scope; }; namespace __hwasan { int OnExit() { // FIXME: ask frontend whether we need to return failure. return 0; } } // namespace __hwasan namespace __hwasan { void InitializeInterceptors() { static int inited = 0; CHECK_EQ(inited, 0); INTERCEPT_FUNCTION(fork); #if HWASAN_WITH_INTERCEPTORS #if !defined(__aarch64__) INTERCEPT_FUNCTION(pthread_create); #endif INTERCEPT_FUNCTION(realloc); INTERCEPT_FUNCTION(free); #endif inited = 1; } } // namespace __hwasan <|endoftext|>
<commit_before>/* * Copyright (c) 2017, Ford Motor Company * 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 Ford Motor Company 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "transport_manager/iap2_emulation/iap2_transport_adapter.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include "utils/threads/thread.h" #include "utils/file_system.h" namespace { static const mode_t mode = 0666; static const auto in_signals_channel = "iap_signals_in"; static const auto out_signals_channel = "iap_signals_out"; } // namespace namespace transport_manager { namespace transport_adapter { CREATE_LOGGERPTR_GLOBAL(logger_, "IAP2Emulation"); IAP2BluetoothEmulationTransportAdapter::IAP2BluetoothEmulationTransportAdapter( const uint16_t port, resumption::LastState& last_state, const TransportManagerSettings& settings) : TcpTransportAdapter(port, last_state, settings) {} void IAP2BluetoothEmulationTransportAdapter::DeviceSwitched( const DeviceUID& device_handle) { LOG4CXX_AUTO_TRACE(logger_); UNUSED(device_handle); DCHECK(!"Switching for iAP2 Bluetooth is not supported."); } DeviceType IAP2BluetoothEmulationTransportAdapter::GetDeviceType() const { return IOS_BT; } IAP2USBEmulationTransportAdapter::IAP2USBEmulationTransportAdapter( const uint16_t port, resumption::LastState& last_state, const TransportManagerSettings& settings) : TcpTransportAdapter(port, last_state, settings), out_(0) { auto delegate = new IAPSignalHandlerDelegate(*this); signal_handler_ = threads::CreateThread("iAP signal handler", delegate); signal_handler_->start(); const auto result = mkfifo(out_signals_channel, mode); LOG4CXX_DEBUG(logger_, "Out signals channel creation result: " << result); } IAP2USBEmulationTransportAdapter::~IAP2USBEmulationTransportAdapter() { signal_handler_->join(); threads::DeleteThread(signal_handler_); LOG4CXX_DEBUG(logger_, "Out close result: " << close(out_)); LOG4CXX_DEBUG(logger_, "Out unlink result: " << unlink(out_signals_channel)); } void IAP2USBEmulationTransportAdapter::DeviceSwitched( const DeviceUID& device_handle) { LOG4CXX_AUTO_TRACE(logger_); UNUSED(device_handle); const auto switch_signal_ack = std::string("SDL_TRANSPORT_SWITCH_ACK\n"); auto out_ = open(out_signals_channel, O_WRONLY); LOG4CXX_DEBUG(logger_, "Out channel descriptor: " << out_); const auto bytes = write(out_, switch_signal_ack.c_str(), switch_signal_ack.size()); LOG4CXX_DEBUG(logger_, "Written bytes to out: " << bytes); LOG4CXX_DEBUG(logger_, "Switching signal ACK is sent"); LOG4CXX_DEBUG(logger_, "iAP2 USB device is switched with iAP2 Bluetooth"); } DeviceType IAP2USBEmulationTransportAdapter::GetDeviceType() const { return IOS_USB; } IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate:: IAPSignalHandlerDelegate(IAP2USBEmulationTransportAdapter& adapter) : adapter_(adapter), run_flag_(true), in_(0) { const auto result = mkfifo(in_signals_channel, mode); LOG4CXX_DEBUG(logger_, "In signals channel creation result: " << result); } void IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate::threadMain() { LOG4CXX_AUTO_TRACE(logger_); LOG4CXX_DEBUG(logger_, "Signal handling is started"); const auto switch_signal = "SDL_TRANSPORT_SWITCH"; LOG4CXX_DEBUG(logger_, "Waiting for signal: " << switch_signal); in_ = open(in_signals_channel, O_RDONLY); LOG4CXX_DEBUG(logger_, "In channel descriptor: " << in_); const auto size = 32; while (run_flag_) { char buffer[size]; auto bytes = read(in_, &buffer, size); if (!bytes) { continue; } LOG4CXX_DEBUG(logger_, "Read in bytes: " << bytes); std::string str(buffer); if (std::string::npos != str.find(switch_signal)) { LOG4CXX_DEBUG(logger_, "Switch signal received."); adapter_.DoTransportSwitch(); } } } void IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate:: exitThreadMain() { LOG4CXX_AUTO_TRACE(logger_); LOG4CXX_DEBUG(logger_, "Stopping signal handling."); run_flag_ = false; LOG4CXX_DEBUG(logger_, "In close result: " << close(in_)); LOG4CXX_DEBUG(logger_, "In unlink result: " << unlink(in_signals_channel)); } } } // namespace transport_manager::transport_adapter <commit_msg>Fixes thread stopping in case no one connected to the pipe<commit_after>/* * Copyright (c) 2017, Ford Motor Company * 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 Ford Motor Company 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "transport_manager/iap2_emulation/iap2_transport_adapter.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include "utils/threads/thread.h" #include "utils/file_system.h" namespace { static const mode_t mode = 0666; static const auto in_signals_channel = "iap_signals_in"; static const auto out_signals_channel = "iap_signals_out"; } // namespace namespace transport_manager { namespace transport_adapter { CREATE_LOGGERPTR_GLOBAL(logger_, "IAP2Emulation"); IAP2BluetoothEmulationTransportAdapter::IAP2BluetoothEmulationTransportAdapter( const uint16_t port, resumption::LastState& last_state, const TransportManagerSettings& settings) : TcpTransportAdapter(port, last_state, settings) {} void IAP2BluetoothEmulationTransportAdapter::DeviceSwitched( const DeviceUID& device_handle) { LOG4CXX_AUTO_TRACE(logger_); UNUSED(device_handle); DCHECK(!"Switching for iAP2 Bluetooth is not supported."); } DeviceType IAP2BluetoothEmulationTransportAdapter::GetDeviceType() const { return IOS_BT; } IAP2USBEmulationTransportAdapter::IAP2USBEmulationTransportAdapter( const uint16_t port, resumption::LastState& last_state, const TransportManagerSettings& settings) : TcpTransportAdapter(port, last_state, settings), out_(0) { auto delegate = new IAPSignalHandlerDelegate(*this); signal_handler_ = threads::CreateThread("iAP signal handler", delegate); signal_handler_->start(); const auto result = mkfifo(out_signals_channel, mode); LOG4CXX_DEBUG(logger_, "Out signals channel creation result: " << result); } IAP2USBEmulationTransportAdapter::~IAP2USBEmulationTransportAdapter() { signal_handler_->join(); auto delegate = signal_handler_->delegate(); signal_handler_->set_delegate(NULL); delete delegate; threads::DeleteThread(signal_handler_); LOG4CXX_DEBUG(logger_, "Out close result: " << close(out_)); LOG4CXX_DEBUG(logger_, "Out unlink result: " << unlink(out_signals_channel)); } void IAP2USBEmulationTransportAdapter::DeviceSwitched( const DeviceUID& device_handle) { LOG4CXX_AUTO_TRACE(logger_); UNUSED(device_handle); const auto switch_signal_ack = std::string("SDL_TRANSPORT_SWITCH_ACK\n"); auto out_ = open(out_signals_channel, O_WRONLY); LOG4CXX_DEBUG(logger_, "Out channel descriptor: " << out_); const auto bytes = write(out_, switch_signal_ack.c_str(), switch_signal_ack.size()); LOG4CXX_DEBUG(logger_, "Written bytes to out: " << bytes); LOG4CXX_DEBUG(logger_, "Switching signal ACK is sent"); LOG4CXX_DEBUG(logger_, "iAP2 USB device is switched with iAP2 Bluetooth"); } DeviceType IAP2USBEmulationTransportAdapter::GetDeviceType() const { return IOS_USB; } IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate:: IAPSignalHandlerDelegate(IAP2USBEmulationTransportAdapter& adapter) : adapter_(adapter), run_flag_(true), in_(0) { const auto result = mkfifo(in_signals_channel, mode); LOG4CXX_DEBUG(logger_, "In signals channel creation result: " << result); } void IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate::threadMain() { LOG4CXX_AUTO_TRACE(logger_); LOG4CXX_DEBUG(logger_, "Signal handling is started"); const auto switch_signal = "SDL_TRANSPORT_SWITCH"; LOG4CXX_DEBUG(logger_, "Waiting for signal: " << switch_signal); in_ = open(in_signals_channel, O_RDONLY); LOG4CXX_DEBUG(logger_, "In channel descriptor: " << in_); const auto size = 32; while (run_flag_) { char buffer[size]; auto bytes = read(in_, &buffer, size); if (!bytes) { continue; } LOG4CXX_DEBUG(logger_, "Read in bytes: " << bytes); std::string str(buffer); if (std::string::npos != str.find(switch_signal)) { LOG4CXX_DEBUG(logger_, "Switch signal received."); adapter_.DoTransportSwitch(); } } LOG4CXX_DEBUG(logger_, "In close result: " << close(in_)); LOG4CXX_DEBUG(logger_, "In unlink result: " << unlink(in_signals_channel)); } void IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate:: exitThreadMain() { LOG4CXX_AUTO_TRACE(logger_); LOG4CXX_DEBUG(logger_, "Stopping signal handling."); run_flag_ = false; if (!in_) { // To stop thread gracefully in case of no one has connected to pipe before auto in = open(in_signals_channel, O_WRONLY); UNUSED(in); } } } } // namespace transport_manager::transport_adapter <|endoftext|>
<commit_before>// Copyright (c) 2021 midnightBITS // This code is licensed under MIT license (see LICENSE for details) #include "flask-app.hh" #include <stdlib.h> #include <chrono> #include "flask-app-dir.hh" #ifdef _WIN32 #include <Windows.h> #undef max #undef min #endif using namespace std::literals; namespace tangle::http::flask { app::app() = default; app::~app() { stop(); } void app::start() { stop(); th_ = std::thread{[](app* self) { self->run(); }, this}; stage_ = 2; cv_.notify_one(); std::unique_lock lck{m_}; auto self = this; cv_.wait(lck, [&] { return self->stage_ == 3; }); } void app::stop() { if (process_) { fprintf(stderr, "Stopping flask\n"); process_->kill(); } if (th_.joinable()) th_.join(); th_ = std::thread{}; process_.reset(); stage_ = 0; } #ifdef _WIN32 inline void setenv(char const* name, char const* value, int) { SetEnvironmentVariableA(name, value); } #endif void app::run() { setenv("FLASK_APP", FLASK_APP, 1); fprintf(stderr, "Starting flask\n"); process_ = std::make_unique<Process>("flask run", std::string{}); fprintf(stderr, "Started flask\n"); std::this_thread::sleep_for(1s); { std::unique_lock lck{m_}; auto self = this; cv_.wait(lck, [&] { return self->stage_ == 2; }); } stage_ = 3; cv_.notify_one(); auto result = process_->get_exit_status(); } } // namespace tangle::http::flask <commit_msg>Add warning if Flask cannot be run<commit_after>// Copyright (c) 2021 midnightBITS // This code is licensed under MIT license (see LICENSE for details) #include "flask-app.hh" #include <stdlib.h> #include <chrono> #include "flask-app-dir.hh" #ifdef _WIN32 #include <Windows.h> #undef max #undef min #endif using namespace std::literals; namespace tangle::http::flask { app::app() = default; app::~app() { stop(); } void app::start() { stop(); th_ = std::thread{[](app* self) { self->run(); }, this}; stage_ = 2; cv_.notify_one(); std::unique_lock lck{m_}; auto self = this; cv_.wait(lck, [&] { return self->stage_ == 3; }); } void app::stop() { if (process_) { fprintf(stderr, "Stopping flask\n"); process_->kill(); } if (th_.joinable()) th_.join(); th_ = std::thread{}; process_.reset(); stage_ = 0; } #ifdef _WIN32 inline void setenv(char const* name, char const* value, int) { SetEnvironmentVariableA(name, value); } #endif void app::run() { setenv("FLASK_APP", FLASK_APP, 1); fprintf(stderr, "Starting flask\n"); process_ = std::make_unique<Process>("flask run", std::string{}); if (!process_->get_id()) { fprintf( stderr, "Flask could not be started. These tests need it to run. " "Use\n\n sudo python3 -m pip install --upgrade flask\n\n"); } else { fprintf(stderr, "Started flask\n"); std::this_thread::sleep_for(1s); } { std::unique_lock lck{m_}; auto self = this; cv_.wait(lck, [&] { return self->stage_ == 2; }); } stage_ = 3; cv_.notify_one(); auto result = process_->get_exit_status(); } } // namespace tangle::http::flask <|endoftext|>
<commit_before>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "HTTPFile.h" #include "MIMEType.h" #include "IndexFiles.h" #include "../Interface/Server.h" #include "../Interface/File.h" #include "../Interface/Pipe.h" #include "../stringtools.h" #define FP_READ_SIZE 8192 CHTTPFile::CHTTPFile(std::string pFilename, IPipe *pOutput) { filename=pFilename; output=pOutput; } std::string CHTTPFile::getContentType(void) { std::string ext=findextension(filename); return MIMEType::getMIMEType(ext); } void CHTTPFile::operator ()(void) { IFile *fp=Server->openFile(filename); if( fp==NULL ) { const std::vector<std::string> idxf=IndexFiles::getIndexFiles(); for(size_t i=0;i<idxf.size();++i) { std::string fn=filename+"/"+idxf[i]; fp=Server->openFile(fn); if( fp!=NULL ) { filename=fn; break; } } } std::string ct=getContentType(); if( fp==NULL ) { output->Write("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\nContent-Length: 22\r\n\r\nSorry. File not found."); return; } std::string status="HTTP/1.1 200 ok\r\n"; std::string header="Server: CS\r\nContent-Type: "+ct+"\r\nCache-Control: max-age=3600\r\nConnection: Keep-Alive\r\nKeep-Alive: timeout=15, max=95\r\nContent-Length: "+nconvert(fp->Size())+"\r\n\r\n"; Server->Log("Sending file: "+filename, LL_INFO); output->Write(status+header); size_t bytes=0; std::string buf; while( (buf=fp->Read(FP_READ_SIZE)).size()>0 ) { bytes+=buf.size(); output->Write(buf); } Server->Log("Sending file: "+filename+" done", LL_INFO); Server->destroy(fp); } <commit_msg>Log accessed file in HTTP server<commit_after>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "HTTPFile.h" #include "MIMEType.h" #include "IndexFiles.h" #include "../Interface/Server.h" #include "../Interface/File.h" #include "../Interface/Pipe.h" #include "../stringtools.h" #define FP_READ_SIZE 8192 CHTTPFile::CHTTPFile(std::string pFilename, IPipe *pOutput) { filename=pFilename; output=pOutput; } std::string CHTTPFile::getContentType(void) { std::string ext=findextension(filename); return MIMEType::getMIMEType(ext); } void CHTTPFile::operator ()(void) { Server->Log("Sending file \""+filename+"\"", LL_DEBUG); IFile *fp=Server->openFile(filename); if( fp==NULL ) { const std::vector<std::string> idxf=IndexFiles::getIndexFiles(); for(size_t i=0;i<idxf.size();++i) { std::string fn=filename+"/"+idxf[i]; fp=Server->openFile(fn); if( fp!=NULL ) { filename=fn; break; } } } std::string ct=getContentType(); if( fp==NULL ) { output->Write("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\nContent-Length: 22\r\n\r\nSorry. File not found."); return; } std::string status="HTTP/1.1 200 ok\r\n"; std::string header="Server: CS\r\nContent-Type: "+ct+"\r\nCache-Control: max-age=3600\r\nConnection: Keep-Alive\r\nKeep-Alive: timeout=15, max=95\r\nContent-Length: "+nconvert(fp->Size())+"\r\n\r\n"; Server->Log("Sending file: "+filename, LL_INFO); output->Write(status+header); size_t bytes=0; std::string buf; while( (buf=fp->Read(FP_READ_SIZE)).size()>0 ) { bytes+=buf.size(); output->Write(buf); } Server->Log("Sending file: "+filename+" done", LL_INFO); Server->destroy(fp); } <|endoftext|>
<commit_before>#include "mainwidget.h" #include "ui_mainwidget.h" MainWidget::MainWidget(QWidget *parent) : QWidget(parent), ui(new Ui::MainWidget) { ui->setupUi(this); // setup createAction(); createTrayIcon(); // set echomode ui->passEdit->setEchoMode( QLineEdit::Password ); // create manager manager = new QNetworkAccessManager( this ); // setting ( if you ) setting = new QSettings( "conf.ini", QSettings::IniFormat, this ); // load setting loadConfigSlot(); // connect timer connect( &statusTimer, SIGNAL(timeout()), SLOT(updateStatusSlot()) ); connect( &timer, SIGNAL(timeout()), this, SLOT(loginSlot()) ); // class no zikkenn public toka } MainWidget::~MainWidget() { delete ui; } void MainWidget::on_loginButton_clicked() { // login button // clear status clearStatusSlot(); // stop all timer timer.stop(); statusTimer.stop(); // disable stop button ui->stopTimerButton->setEnabled( false ); if ( ui->repeatCheckBox->isChecked() ) { // repeat login timer.setInterval( ui->repatSpinBox->value() * 60 * 1000 ); // set progress ui->progressBar->setMaximum( ui->repatSpinBox->value() ); ui->progressBar->setValue( ui->repatSpinBox->value() ); // set status timer statusTimer.setInterval( 1000 * 60 ); statusTimer.start(); // start timer timer.start(); // button enable ui->stopTimerButton->setEnabled( true ); } // login loginSlot(); } void MainWidget::loginSlot() { // login slot QString send_data; // AccessManager mode QNetworkRequest request; // clear counter ui->progressBar->setValue( timer.interval() / 1000 / 60 ); ui->progressBar->setMaximum( timer.interval() / 1000 / 60 ); send_data = "uid=" + ui->idEdit->text() + "&pwd=" + ui->passEdit->text() + "&Submit1=%E3%83%AD%E3%82%B0%E3%82%A4%E3%83%B3"; // set url request.setUrl( QUrl( ui->serverNameEdit->text() + "cgi-bin/Login.cgi" ) ); request.setRawHeader( "Content-type", "application/x-www-form-urlencoded" ); // get QNetworkReply *reply = manager->post( request, send_data.toUtf8() ); // connect connect( reply, SIGNAL(finished()), this, SLOT(readyReadSlot()) ); connect( reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorSlot(QList<QSslError>)) ); connect( reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkErrorSlot(QNetworkReply::NetworkError)) ); } void MainWidget::logoutSlot() { // logout slot QString send_data; // AccessManager mode QNetworkRequest request; send_data = "Submit2=%E3%83%AD%E3%82%B0%E3%82%A2%E3%82%A6%E3%83%88"; // set url request.setUrl( QUrl( ui->serverNameEdit->text() + "cgi-bin/Logout.cgi" ) ); request.setRawHeader( "Content-type", "application/x-www-form-urlencoded" ); // get QNetworkReply *reply = manager->post( request, send_data.toUtf8() ); // connect connect( reply, SIGNAL(finished()), this, SLOT(readyReadSlot()) ); connect( reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorSlot(QList<QSslError>)) ); connect( reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkErrorSlot(QNetworkReply::NetworkError)) ); } void MainWidget::readyReadSlot() { // ready read slot QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() ); // バッファに読み込み QByteArray buffer( reply->readAll() ); // パーサー作成 QXmlStreamReader reader( buffer ); // analyze html QString loginTime; QString logoutTime; LoginStatus stat = lsFailed; while ( !reader.atEnd() ) { // 次の要素を読む reader.readNext(); // タグ開始 if ( reader.isStartElement() ) { if ( reader.name() == "span" && reader.attributes().value( "id" ).toString() == "loginTime" ) { // ログイン時間取得 loginTime = reader.readElementText(); // ログイン成功 stat = lsLogin; } else if ( reader.name() == "span" && reader.attributes().value( "id" ).toString() == "logoutTime" ) { // ログアウト時間取得 logoutTime = reader.readElementText(); } else if ( reader.name() == "p" && reader.attributes().value( "class" ).toString() == "subcaption" ) { // ログインかログアウトか判別 QString mode = reader.readElementText(); if ( mode == "Logout" || mode == "ログアウト" ) { stat = lsLogout; } } } } // メッセージ作成 QString info; QString title; if ( stat == lsLogin ) { // ログイン成功 title = tr( "Login" ); info = QString() + tr( "Login time\t : " ) + loginTime + tr( "\nLogout time\t : " ) + logoutTime; if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info ); } } else if ( stat == lsLogout ) { // logout complete title = tr( "Logout" ); info = tr( "Logout succeeded" ); if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info ); } } else { // error title = tr( "Error" ); info = tr( "Some errors occurred" ); if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info, QSystemTrayIcon::Warning ); } } // ラベルに表示 ui->messageLabel->setText( title + "\n" + info ); // delete reply reply->deleteLater(); } void MainWidget::saveConfigSlot() { // save config // save check setting->setValue( "Repeat", ui->repeatCheckBox->isChecked() ); setting->setValue( "AutoMinimize", ui->autoToTrayCheckBox->isChecked() ); setting->setValue( "AutoStart", ui->autoStartCheckBox->isChecked() ); setting->setValue( "ConfigId", ui->saveIdCheckBox->isChecked() ); setting->setValue( "ConfigPass", ui->savePassCheckBox->isChecked() ); setting->setValue( "RepeatMin", ui->repatSpinBox->value() ); setting->setValue( "Auth", ui->serverNameEdit->text() ); // if need id,pass if ( ui->saveIdCheckBox->isChecked() ) { setting->setValue( "ID", ui->idEdit->text() ); } if ( ui->savePassCheckBox->isChecked() ) { setting->setValue( "Pass", ui->passEdit->text() ); } } void MainWidget::loadConfigSlot() { // load config // load check ui->repeatCheckBox->setChecked( setting->value( "Repeat" ).toBool() ); ui->autoToTrayCheckBox->setChecked( setting->value( "AutoMinimize" ).toBool() ); ui->autoStartCheckBox->setChecked( setting->value( "AutoStart" ).toBool() ); ui->saveIdCheckBox->setChecked( setting->value( "ConfigId" ).toBool() ); ui->savePassCheckBox->setChecked( setting->value( "ConfigPass" ).toBool() ); ui->repatSpinBox->setValue( setting->value( "RepeatMin" ).toInt() ); ui->serverNameEdit->setText( setting->value( "Auth" ).toString() ); // if need id,pass if ( ui->saveIdCheckBox->isChecked() ) { ui->idEdit->setText( setting->value( "ID" ).toString() ); } if ( ui->savePassCheckBox->isChecked() ) { ui->passEdit->setText( setting->value( "Pass" ).toString() ); } // do setting if ( ui->autoStartCheckBox->isChecked() ) { // Auto Login on_loginButton_clicked(); } if ( ui->autoToTrayCheckBox->isChecked() ) { // minimize to tray QTimer::singleShot( 100, this, SLOT(minimizeSlot()) ); } } void MainWidget::minimizeSlot() { // minimize to tray trayIcon->show(); /* trayIcon->showMessage( tr( "Minimize to tray" ), tr( "This application is still running. To quit please click this icon and select Close" ) ); */ hide(); } void MainWidget::updateStatusSlot() { // update status // update progress bar if ( timer.isActive() ) { ui->progressBar->setValue( ui->progressBar->value() - 1 ); } } void MainWidget::clearStatusSlot() { // clearStatus ui->progressBar->setValue( 0 ); } void MainWidget::sslErrorSlot(const QList<QSslError> &errors) { // sslError Slot QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() ); QString errString; // iOSでは不完全型となっているため直接アクセスしない #ifndef Q_OS_IOS foreach ( QSslError err, errors ) { errString += err.errorString() + "\n"; } #endif // 全エラー無視(本来は確認すべき) reply->ignoreSslErrors(); // view ssl error if ( isVisible() ) { QMessageBox::warning( this, tr( "Ssl warning" ), errString + tr( "\n\nThese \"SslError\" are ignored." ) ); } } void MainWidget::trayIconClickSlot( QSystemTrayIcon::ActivationReason reason ) { // tray icon clicked if ( reason == QSystemTrayIcon::Trigger ) { // Macの場合ここでhideすると落ちるためなにもしない #ifdef Q_OS_MAC return; #endif trayIcon->hide(); this->show(); } } void MainWidget::networkErrorSlot( QNetworkReply::NetworkError code ) { // network error Q_UNUSED( code ) if ( isVisible() ) { QMessageBox::warning( this, tr( "Network error" ), tr( "Some network error occurred" ) ); } } void MainWidget::checkIpSlot() { // check ip foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) ui->ipEdit->setText( address.toString() ); } } void MainWidget::on_aboutButton_clicked() { // aboutQt QMessageBox::aboutQt( this ); } void MainWidget::on_closeButton_clicked() { close(); } void MainWidget::on_stopTimerButton_clicked() { // stop timer timer.stop(); statusTimer.stop(); ui->stopTimerButton->setEnabled( false ); } void MainWidget::createTrayIcon() { // create tray icon // create menu trayMenu = new QMenu( this ); trayMenu->addAction( showAction ); trayMenu->addSeparator(); trayMenu->addAction( connectAction ); trayMenu->addAction( disconnectAction ); trayMenu->addSeparator(); trayMenu->addAction( closeAction ); // setup icon trayIcon = new QSystemTrayIcon( this ); trayIcon->setContextMenu( trayMenu ); trayIcon->setIcon( QIcon( ":/image/icon.png" ) ); trayIcon->setToolTip( tr( "QAutoLogin" ) ); // connect connect( trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconClickSlot(QSystemTrayIcon::ActivationReason)) ); } void MainWidget::createAction() { // create actions closeAction = new QAction( tr( "&Close" ), this ); connectAction = new QAction( tr( "&Login" ), this ); disconnectAction = new QAction( tr( "Log&out" ), this ); showAction = new QAction( tr( "&Show" ), this ); connect( closeAction, SIGNAL(triggered()), this, SLOT(close()) ); connect( connectAction, SIGNAL(triggered()), this, SLOT(on_loginButton_clicked()) ); connect( disconnectAction, SIGNAL(triggered()), this, SLOT(on_logoutButton_clicked()) ); connect( showAction, SIGNAL(triggered()), SLOT(show()) ); } void MainWidget::closeEvent(QCloseEvent *) { // close event if ( trayIcon->isVisible() ) { trayIcon->hide(); } } void MainWidget::on_saveConfigButton_clicked() { // save config button saveConfigSlot(); } void MainWidget::on_logoutButton_clicked() { // logout logoutSlot(); // disable timer timer.stop(); statusTimer.stop(); ui->stopTimerButton->setEnabled( false ); } void MainWidget::on_minimizePushButton_clicked() { minimizeSlot(); } void MainWidget::on_checkIpButton_clicked() { // check ip checkIpSlot(); } <commit_msg>MacOSでのQSettingの保存先を変更<commit_after>#include "mainwidget.h" #include "ui_mainwidget.h" MainWidget::MainWidget(QWidget *parent) : QWidget(parent), ui(new Ui::MainWidget) { ui->setupUi(this); // setup createAction(); createTrayIcon(); // set echomode ui->passEdit->setEchoMode( QLineEdit::Password ); // create manager manager = new QNetworkAccessManager( this ); // setting #ifdef Q_OS_MAC setting = new QSettings( QSettings::IniFormat, QSettings::UserScope, "futr", "QAutoLogin" ); setting->setFallbacksEnabled( false ); #else setting = new QSettings( "conf.ini", QSettings::IniFormat, this ); #endif // load setting loadConfigSlot(); // connect timer connect( &statusTimer, SIGNAL(timeout()), SLOT(updateStatusSlot()) ); connect( &timer, SIGNAL(timeout()), this, SLOT(loginSlot()) ); // class no zikkenn public toka } MainWidget::~MainWidget() { delete ui; } void MainWidget::on_loginButton_clicked() { // login button // clear status clearStatusSlot(); // stop all timer timer.stop(); statusTimer.stop(); // disable stop button ui->stopTimerButton->setEnabled( false ); if ( ui->repeatCheckBox->isChecked() ) { // repeat login timer.setInterval( ui->repatSpinBox->value() * 60 * 1000 ); // set progress ui->progressBar->setMaximum( ui->repatSpinBox->value() ); ui->progressBar->setValue( ui->repatSpinBox->value() ); // set status timer statusTimer.setInterval( 1000 * 60 ); statusTimer.start(); // start timer timer.start(); // button enable ui->stopTimerButton->setEnabled( true ); } // login loginSlot(); } void MainWidget::loginSlot() { // login slot QString send_data; // AccessManager mode QNetworkRequest request; // clear counter ui->progressBar->setValue( timer.interval() / 1000 / 60 ); ui->progressBar->setMaximum( timer.interval() / 1000 / 60 ); send_data = "uid=" + ui->idEdit->text() + "&pwd=" + ui->passEdit->text() + "&Submit1=%E3%83%AD%E3%82%B0%E3%82%A4%E3%83%B3"; // set url request.setUrl( QUrl( ui->serverNameEdit->text() + "cgi-bin/Login.cgi" ) ); request.setRawHeader( "Content-type", "application/x-www-form-urlencoded" ); // get QNetworkReply *reply = manager->post( request, send_data.toUtf8() ); // connect connect( reply, SIGNAL(finished()), this, SLOT(readyReadSlot()) ); connect( reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorSlot(QList<QSslError>)) ); connect( reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkErrorSlot(QNetworkReply::NetworkError)) ); } void MainWidget::logoutSlot() { // logout slot QString send_data; // AccessManager mode QNetworkRequest request; send_data = "Submit2=%E3%83%AD%E3%82%B0%E3%82%A2%E3%82%A6%E3%83%88"; // set url request.setUrl( QUrl( ui->serverNameEdit->text() + "cgi-bin/Logout.cgi" ) ); request.setRawHeader( "Content-type", "application/x-www-form-urlencoded" ); // get QNetworkReply *reply = manager->post( request, send_data.toUtf8() ); // connect connect( reply, SIGNAL(finished()), this, SLOT(readyReadSlot()) ); connect( reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorSlot(QList<QSslError>)) ); connect( reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkErrorSlot(QNetworkReply::NetworkError)) ); } void MainWidget::readyReadSlot() { // ready read slot QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() ); // バッファに読み込み QByteArray buffer( reply->readAll() ); // パーサー作成 QXmlStreamReader reader( buffer ); // analyze html QString loginTime; QString logoutTime; LoginStatus stat = lsFailed; while ( !reader.atEnd() ) { // 次の要素を読む reader.readNext(); // タグ開始 if ( reader.isStartElement() ) { if ( reader.name() == "span" && reader.attributes().value( "id" ).toString() == "loginTime" ) { // ログイン時間取得 loginTime = reader.readElementText(); // ログイン成功 stat = lsLogin; } else if ( reader.name() == "span" && reader.attributes().value( "id" ).toString() == "logoutTime" ) { // ログアウト時間取得 logoutTime = reader.readElementText(); } else if ( reader.name() == "p" && reader.attributes().value( "class" ).toString() == "subcaption" ) { // ログインかログアウトか判別 QString mode = reader.readElementText(); if ( mode == "Logout" || mode == "ログアウト" ) { stat = lsLogout; } } } } // メッセージ作成 QString info; QString title; if ( stat == lsLogin ) { // ログイン成功 title = tr( "Login" ); info = QString() + tr( "Login time\t : " ) + loginTime + tr( "\nLogout time\t : " ) + logoutTime; if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info ); } } else if ( stat == lsLogout ) { // logout complete title = tr( "Logout" ); info = tr( "Logout succeeded" ); if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info ); } } else { // error title = tr( "Error" ); info = tr( "Some errors occurred" ); if ( trayIcon->isVisible() ) { trayIcon->showMessage( title, info, QSystemTrayIcon::Warning ); } } // ラベルに表示 ui->messageLabel->setText( title + "\n" + info ); // delete reply reply->deleteLater(); } void MainWidget::saveConfigSlot() { // save config // save check setting->setValue( "Repeat", ui->repeatCheckBox->isChecked() ); setting->setValue( "AutoMinimize", ui->autoToTrayCheckBox->isChecked() ); setting->setValue( "AutoStart", ui->autoStartCheckBox->isChecked() ); setting->setValue( "ConfigId", ui->saveIdCheckBox->isChecked() ); setting->setValue( "ConfigPass", ui->savePassCheckBox->isChecked() ); setting->setValue( "RepeatMin", ui->repatSpinBox->value() ); setting->setValue( "Auth", ui->serverNameEdit->text() ); // if need id,pass if ( ui->saveIdCheckBox->isChecked() ) { setting->setValue( "ID", ui->idEdit->text() ); } if ( ui->savePassCheckBox->isChecked() ) { setting->setValue( "Pass", ui->passEdit->text() ); } } void MainWidget::loadConfigSlot() { // load config // load check ui->repeatCheckBox->setChecked( setting->value( "Repeat" ).toBool() ); ui->autoToTrayCheckBox->setChecked( setting->value( "AutoMinimize" ).toBool() ); ui->autoStartCheckBox->setChecked( setting->value( "AutoStart" ).toBool() ); ui->saveIdCheckBox->setChecked( setting->value( "ConfigId" ).toBool() ); ui->savePassCheckBox->setChecked( setting->value( "ConfigPass" ).toBool() ); ui->repatSpinBox->setValue( setting->value( "RepeatMin" ).toInt() ); ui->serverNameEdit->setText( setting->value( "Auth" ).toString() ); // if need id,pass if ( ui->saveIdCheckBox->isChecked() ) { ui->idEdit->setText( setting->value( "ID" ).toString() ); } if ( ui->savePassCheckBox->isChecked() ) { ui->passEdit->setText( setting->value( "Pass" ).toString() ); } // do setting if ( ui->autoStartCheckBox->isChecked() ) { // Auto Login on_loginButton_clicked(); } if ( ui->autoToTrayCheckBox->isChecked() ) { // minimize to tray QTimer::singleShot( 100, this, SLOT(minimizeSlot()) ); } } void MainWidget::minimizeSlot() { // minimize to tray trayIcon->show(); /* trayIcon->showMessage( tr( "Minimize to tray" ), tr( "This application is still running. To quit please click this icon and select Close" ) ); */ hide(); } void MainWidget::updateStatusSlot() { // update status // update progress bar if ( timer.isActive() ) { ui->progressBar->setValue( ui->progressBar->value() - 1 ); } } void MainWidget::clearStatusSlot() { // clearStatus ui->progressBar->setValue( 0 ); } void MainWidget::sslErrorSlot(const QList<QSslError> &errors) { // sslError Slot QNetworkReply *reply = qobject_cast< QNetworkReply *>( sender() ); QString errString; // iOSでは不完全型となっているため直接アクセスしない #ifndef Q_OS_IOS foreach ( QSslError err, errors ) { errString += err.errorString() + "\n"; } #endif // 全エラー無視(本来は確認すべき) reply->ignoreSslErrors(); // view ssl error if ( isVisible() ) { QMessageBox::warning( this, tr( "Ssl warning" ), errString + tr( "\n\nThese \"SslError\" are ignored." ) ); } } void MainWidget::trayIconClickSlot( QSystemTrayIcon::ActivationReason reason ) { // tray icon clicked if ( reason == QSystemTrayIcon::Trigger ) { // Macの場合ここでhideすると落ちるためなにもしない #ifdef Q_OS_MAC return; #endif trayIcon->hide(); this->show(); } } void MainWidget::networkErrorSlot( QNetworkReply::NetworkError code ) { // network error Q_UNUSED( code ) if ( isVisible() ) { QMessageBox::warning( this, tr( "Network error" ), tr( "Some network error occurred" ) ); } } void MainWidget::checkIpSlot() { // check ip foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) ui->ipEdit->setText( address.toString() ); } } void MainWidget::on_aboutButton_clicked() { // aboutQt QMessageBox::aboutQt( this ); } void MainWidget::on_closeButton_clicked() { close(); } void MainWidget::on_stopTimerButton_clicked() { // stop timer timer.stop(); statusTimer.stop(); ui->stopTimerButton->setEnabled( false ); } void MainWidget::createTrayIcon() { // create tray icon // create menu trayMenu = new QMenu( this ); trayMenu->addAction( showAction ); trayMenu->addSeparator(); trayMenu->addAction( connectAction ); trayMenu->addAction( disconnectAction ); trayMenu->addSeparator(); trayMenu->addAction( closeAction ); // setup icon trayIcon = new QSystemTrayIcon( this ); trayIcon->setContextMenu( trayMenu ); trayIcon->setIcon( QIcon( ":/image/icon.png" ) ); trayIcon->setToolTip( tr( "QAutoLogin" ) ); // connect connect( trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconClickSlot(QSystemTrayIcon::ActivationReason)) ); } void MainWidget::createAction() { // create actions closeAction = new QAction( tr( "&Close" ), this ); connectAction = new QAction( tr( "&Login" ), this ); disconnectAction = new QAction( tr( "Log&out" ), this ); showAction = new QAction( tr( "&Show" ), this ); connect( closeAction, SIGNAL(triggered()), this, SLOT(close()) ); connect( connectAction, SIGNAL(triggered()), this, SLOT(on_loginButton_clicked()) ); connect( disconnectAction, SIGNAL(triggered()), this, SLOT(on_logoutButton_clicked()) ); connect( showAction, SIGNAL(triggered()), SLOT(show()) ); } void MainWidget::closeEvent(QCloseEvent *) { // close event if ( trayIcon->isVisible() ) { trayIcon->hide(); } } void MainWidget::on_saveConfigButton_clicked() { // save config button saveConfigSlot(); } void MainWidget::on_logoutButton_clicked() { // logout logoutSlot(); // disable timer timer.stop(); statusTimer.stop(); ui->stopTimerButton->setEnabled( false ); } void MainWidget::on_minimizePushButton_clicked() { minimizeSlot(); } void MainWidget::on_checkIpButton_clicked() { // check ip checkIpSlot(); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QStatusBar> //#include "" //#include "" #include <QMessageBox> using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QStatusBar *statusBar = this->statusBar(); ui->statusBar->showMessage("Scientist successfully added", 4000); currentScientistSortColumn = "Name"; statusBarMessage = new QLabel(); ui->statusBar->addPermanentWidget(statusBarMessage,1); ui->input_dropdown_sort_s->addItem("Name"); ui->input_dropdown_sort_s->addItem("Gender"); ui->input_dropdown_sort_s->addItem("Birth"); ui->input_dropdown_sort_s->addItem("Death"); ui->input_keyword_s->setPlaceholderText("search scientists..."); currentComputerSortColumn = "Name"; ui->statusBar->addPermanentWidget(statusBarMessage,1); ui->input_dropdown_sort_c->addItem("Name"); ui->input_dropdown_sort_c->addItem("Year built"); ui->input_dropdown_sort_c->addItem("Type"); ui->input_dropdown_sort_c->addItem("Built"); ui->input_keyword_c->setPlaceholderText("search computers..."); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_button_add_scientist_clicked() { AddStudentDialog addstudentdialog; int addStudentReturnValue = addstudentdialog.exec(); if(addStudentReturnValue == 1) { ui->statusBar->showMessage("Scientist successfully added", 4000); } else if(addStudentReturnValue == 0) { ui->statusBar->showMessage("Scientist added was canceled", 4000); } else { ui->statusBar->showMessage("Something went wery wery wrong", 4000); } } void MainWindow::getAllScientist() { currentScientist = _service.getScientistVector(); displayAllScientists(); } void MainWindow::displayAllScientists() { ui->table_s->clearContents(); ui->table_s->setRowCount(_service.getSize()); //currentlyDisplayedScientist.clear(); for(unsigned int row = 0; row < currentScientist.size(); row++) { Scientist currentScientist = _service.getScientist(row); string searchString = ui->input_keyword_s->text().toStdString(); //if(currentScientist.contains(searchString)) { ui->table_s->setItem(row,0,new QTableWidgetItem(QString::fromStdString(currentScientist.getName()))); ui->table_s->setItem(row,1,new QTableWidgetItem(QString::fromStdString(currentScientist.getGender()))); ui->table_s->setItem(row,2,new QTableWidgetItem(currentScientist.getYearOfBirth())); ui->table_s->setItem(row,3,new QTableWidgetItem(currentScientist.getYearOfDeath())); //ui->table_s->addItem(QString::fromStdString(currentScientist.toString())); currentlyDisplayedScientist.push_back(currentScientist); } //currentlyDisplayedScientist = _service; } ui->table_s->setRowCount(currentlyDisplayedScientist.size()); } <commit_msg>edit design<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QStatusBar> //#include "" //#include "" #include <QMessageBox> using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QStatusBar *statusBar = this->statusBar(); ui->statusBar->showMessage("Scientist successfully added", 4000); currentScientistSortColumn = "Name"; statusBarMessage = new QLabel(); ui->statusBar->addPermanentWidget(statusBarMessage,1); ui->input_dropdown_sort_s->addItem("Name"); ui->input_dropdown_sort_s->addItem("Gender"); ui->input_dropdown_sort_s->addItem("Birth"); ui->input_dropdown_sort_s->addItem("Death"); ui->input_keyword_s->setPlaceholderText("search scientists..."); currentComputerSortColumn = "Name"; ui->statusBar->addPermanentWidget(statusBarMessage,1); ui->input_dropdown_sort_c->addItem("Name"); ui->input_dropdown_sort_c->addItem("Year built"); ui->input_dropdown_sort_c->addItem("Type"); ui->input_dropdown_sort_c->addItem("Built"); ui->input_keyword_c->setPlaceholderText("search computers..."); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_button_add_scientist_clicked() { AddStudentDialog addstudentdialog; int addStudentReturnValue = addstudentdialog.exec(); if(addStudentReturnValue == 1) { ui->statusBar->showMessage("Scientist successfully added", 4000); } else if(addStudentReturnValue == 0) { ui->statusBar->showMessage("Scientist added was canceled", 4000); } else { ui->statusBar->showMessage("Something went wery wery wrong", 4000); } } void MainWindow::getAllScientist() { currentScientist = _service.getScientistVector(); displayAllScientists(); } void MainWindow::displayAllScientists() { ui->table_s->clearContents(); ui->table_s->setRowCount(_service.getSize()); //currentlyDisplayedScientist.clear(); for(unsigned int row = 0; row < currentScientist.size(); row++) { Scientist currentScientist = _service.getScientist(row); string searchString = ui->input_keyword_s->text().toStdString(); //if(currentScientist.contains(searchString)) { ui->table_s->setItem(row,0,new QTableWidgetItem(QString::fromStdString(currentScientist.getName()))); ui->table_s->setItem(row,1,new QTableWidgetItem(QString::fromStdString(currentScientist.getGender()))); ui->table_s->setItem(row,2,new QTableWidgetItem(currentScientist.getYearOfBirth())); ui->table_s->setItem(row,3,new QTableWidgetItem(currentScientist.getYearOfDeath())); //ui->table_s->addItem(QString::fromStdString(currentScientist.toString())); currentlyDisplayedScientist.push_back(currentScientist); } //currentlyDisplayedScientist = _service; } ui->table_s->setRowCount(currentlyDisplayedScientist.size()); } <|endoftext|>
<commit_before>#include "repo_log.h" #if BOOST_VERSION > 105700 #include <boost/core/null_deleter.hpp> #else #include <boost/utility/empty_deleter.hpp> #endif #include <boost/iostreams/stream.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks/sync_frontend.hpp> #include <boost/log/sinks/text_ostream_backend.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/support/date_time.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> #include <ctime> using namespace repo::lib; using text_sink = boost::log::sinks::synchronous_sink < boost::log::sinks::text_ostream_backend >; RepoLog::RepoLog() { } RepoLog::~RepoLog() { } void RepoLog::log( const RepoLogLevel &severity, const std::string &msg) { switch (severity) { case RepoLogLevel::TRACE: repoTrace << msg; break; case RepoLogLevel::DEBUG: repoDebug << msg; break; case RepoLogLevel::INFO: repoInfo << msg; break; case RepoLogLevel::WARNING: repoWarning << msg; break; case RepoLogLevel::ERR: repoError << msg; break; case RepoLogLevel::FATAL: repoFatal << msg; } } BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "TimeStamp", boost::posix_time::ptime) BOOST_LOG_ATTRIBUTE_KEYWORD(threadid, "ThreadID", boost::log::attributes::current_thread_id::value_type) static std::string getTimeAsString() { time_t rawtime; struct tm * timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, "%d-%m-%Y_%Hh%Mm%S", timeinfo); return std::string(buffer); } void RepoLog::logToFile(const std::string &filePath) { boost::filesystem::path logPath(filePath); std::string fileName; // a directory is given std::string name = getTimeAsString() + "_%N.log"; fileName = (logPath / name).string(); boost::log::add_file_log ( boost::log::keywords::file_name = fileName, boost::log::keywords::rotation_size = 10 * 1024 * 1024, boost::log::keywords::time_based_rotation = boost::log::sinks::file::rotation_at_time_point(0, 0, 0), boost::log::keywords::auto_flush = true, boost::log::keywords::format = ( boost::log::expressions::stream << "[" << boost::log::expressions::format_date_time(timestamp, "%Y-%m-%d %H:%M:%S") << "]" << "(" << threadid << ") <" << boost::log::trivial::severity << ">" << ": " << boost::log::expressions::smessage )); boost::log::add_common_attributes(); repoInfo << "Log file registered: " << filePath; } void RepoLog::setLoggingLevel(const RepoLogLevel &level) { boost::log::trivial::severity_level loggingLevel; switch (level) { case repo::lib::RepoLog::RepoLogLevel::TRACE: loggingLevel = boost::log::trivial::trace; break; case repo::lib::RepoLog::RepoLogLevel::DEBUG: loggingLevel = boost::log::trivial::debug; break; case repo::lib::RepoLog::RepoLogLevel::INFO: loggingLevel = boost::log::trivial::info; break; case repo::lib::RepoLog::RepoLogLevel::WARNING: loggingLevel = boost::log::trivial::warning; break; case repo::lib::RepoLog::RepoLogLevel::ERR: loggingLevel = boost::log::trivial::error; break; case repo::lib::RepoLog::RepoLogLevel::FATAL: loggingLevel = boost::log::trivial::fatal; break; default: repoError << "Unknown log level: " << (int)level; return; } boost::log::core::get()->set_filter( boost::log::trivial::severity >= loggingLevel); } void RepoLog::subscribeBroadcaster(RepoBroadcaster *broadcaster) { boost::iostreams::stream<RepoBroadcaster> *streamptr = new boost::iostreams::stream<RepoBroadcaster>(*broadcaster); #if BOOST_VERSION > 105700 boost::shared_ptr< std::ostream > stream( streamptr, boost::null_deleter()); #else boost::shared_ptr< std::ostream > stream( streamptr, boost::empty_deleter()); #endif boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >(); sink->set_filter(boost::log::trivial::severity >= boost::log::trivial::trace); //FIXME: better format! sink->set_formatter ( boost::log::expressions::stream << "%" << boost::log::trivial::severity << "%" << boost::log::expressions::smessage); sink->locked_backend()->add_stream(stream); sink->locked_backend()->auto_flush(true); // Register the sink in the logging core boost::log::core::get()->add_sink(sink); } void RepoLog::subscribeListeners( const std::vector<RepoAbstractListener*> &listeners) { /* FIXME: ideally, we should have a single broadcaster for the application and you should only need to add the listeners when you subscribe But the whole hackery of making a broadcaster to be a ostream to tap into the boost logger made this really difficult so for now, instantiate a new broadcaster everytime. And I will review this on a braver day... */ RepoBroadcaster *broadcaster = new RepoBroadcaster(); for (auto listener : listeners) broadcaster->subscribe(listener); subscribeBroadcaster(broadcaster); }<commit_msg>ISSUE #428 swap day/year<commit_after>#include "repo_log.h" #if BOOST_VERSION > 105700 #include <boost/core/null_deleter.hpp> #else #include <boost/utility/empty_deleter.hpp> #endif #include <boost/iostreams/stream.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks/sync_frontend.hpp> #include <boost/log/sinks/text_ostream_backend.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/support/date_time.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> #include <ctime> using namespace repo::lib; using text_sink = boost::log::sinks::synchronous_sink < boost::log::sinks::text_ostream_backend >; RepoLog::RepoLog() { } RepoLog::~RepoLog() { } void RepoLog::log( const RepoLogLevel &severity, const std::string &msg) { switch (severity) { case RepoLogLevel::TRACE: repoTrace << msg; break; case RepoLogLevel::DEBUG: repoDebug << msg; break; case RepoLogLevel::INFO: repoInfo << msg; break; case RepoLogLevel::WARNING: repoWarning << msg; break; case RepoLogLevel::ERR: repoError << msg; break; case RepoLogLevel::FATAL: repoFatal << msg; } } BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "TimeStamp", boost::posix_time::ptime) BOOST_LOG_ATTRIBUTE_KEYWORD(threadid, "ThreadID", boost::log::attributes::current_thread_id::value_type) static std::string getTimeAsString() { time_t rawtime; struct tm * timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, "%Y-%m-%d_%Hh%Mm%S", timeinfo); return std::string(buffer); } void RepoLog::logToFile(const std::string &filePath) { boost::filesystem::path logPath(filePath); std::string fileName; // a directory is given std::string name = getTimeAsString() + "_%N.log"; fileName = (logPath / name).string(); boost::log::add_file_log ( boost::log::keywords::file_name = fileName, boost::log::keywords::rotation_size = 10 * 1024 * 1024, boost::log::keywords::time_based_rotation = boost::log::sinks::file::rotation_at_time_point(0, 0, 0), boost::log::keywords::auto_flush = true, boost::log::keywords::format = ( boost::log::expressions::stream << "[" << boost::log::expressions::format_date_time(timestamp, "%Y-%m-%d %H:%M:%S") << "]" << "(" << threadid << ") <" << boost::log::trivial::severity << ">" << ": " << boost::log::expressions::smessage )); boost::log::add_common_attributes(); repoInfo << "Log file registered: " << filePath; } void RepoLog::setLoggingLevel(const RepoLogLevel &level) { boost::log::trivial::severity_level loggingLevel; switch (level) { case repo::lib::RepoLog::RepoLogLevel::TRACE: loggingLevel = boost::log::trivial::trace; break; case repo::lib::RepoLog::RepoLogLevel::DEBUG: loggingLevel = boost::log::trivial::debug; break; case repo::lib::RepoLog::RepoLogLevel::INFO: loggingLevel = boost::log::trivial::info; break; case repo::lib::RepoLog::RepoLogLevel::WARNING: loggingLevel = boost::log::trivial::warning; break; case repo::lib::RepoLog::RepoLogLevel::ERR: loggingLevel = boost::log::trivial::error; break; case repo::lib::RepoLog::RepoLogLevel::FATAL: loggingLevel = boost::log::trivial::fatal; break; default: repoError << "Unknown log level: " << (int)level; return; } boost::log::core::get()->set_filter( boost::log::trivial::severity >= loggingLevel); } void RepoLog::subscribeBroadcaster(RepoBroadcaster *broadcaster) { boost::iostreams::stream<RepoBroadcaster> *streamptr = new boost::iostreams::stream<RepoBroadcaster>(*broadcaster); #if BOOST_VERSION > 105700 boost::shared_ptr< std::ostream > stream( streamptr, boost::null_deleter()); #else boost::shared_ptr< std::ostream > stream( streamptr, boost::empty_deleter()); #endif boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >(); sink->set_filter(boost::log::trivial::severity >= boost::log::trivial::trace); //FIXME: better format! sink->set_formatter ( boost::log::expressions::stream << "%" << boost::log::trivial::severity << "%" << boost::log::expressions::smessage); sink->locked_backend()->add_stream(stream); sink->locked_backend()->auto_flush(true); // Register the sink in the logging core boost::log::core::get()->add_sink(sink); } void RepoLog::subscribeListeners( const std::vector<RepoAbstractListener*> &listeners) { /* FIXME: ideally, we should have a single broadcaster for the application and you should only need to add the listeners when you subscribe But the whole hackery of making a broadcaster to be a ostream to tap into the boost logger made this really difficult so for now, instantiate a new broadcaster everytime. And I will review this on a braver day... */ RepoBroadcaster *broadcaster = new RepoBroadcaster(); for (auto listener : listeners) broadcaster->subscribe(listener); subscribeBroadcaster(broadcaster); }<|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright 2008 Kevin Ottens <ervin@kde.org> Copyright 2008, 2009 Mario Bensi <nef@ipsquad.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mainwindow.h" #include <akonadi/control.h> #include <akonadi/collectionfetchjob.h> #include <KDE/KAction> #include <KDE/KActionCollection> #include <KDE/KConfigGroup> #include <KDE/KIcon> #include <KDE/KLocale> #include <QtGui/QDockWidget> #include <QtGui/QHeaderView> #include "actionlisteditor.h" #include "actionlistview.h" #include "configdialog.h" #include "globalmodel.h" #include "globalsettings.h" #include "todoflatmodel.h" #include "sidebar.h" MainWindow::MainWindow(QWidget *parent) : KXmlGuiWindow(parent) { Akonadi::Control::start(); setupSideBar(); setupCentralWidget(); setupActions(); setupGUI(); restoreColumnState(); applySettings(); actionCollection()->action("project_mode")->trigger(); } void MainWindow::setupCentralWidget() { m_editor = new ActionListEditor(this, actionCollection()); connect(m_sidebar, SIGNAL(noProjectInboxActivated()), m_editor, SLOT(showNoProjectInbox())); connect(m_sidebar, SIGNAL(projectActivated(QModelIndex)), m_editor, SLOT(focusOnProject(QModelIndex))); connect(m_sidebar, SIGNAL(noContextInboxActivated()), m_editor, SLOT(showNoContextInbox())); connect(m_sidebar, SIGNAL(contextActivated(QModelIndex)), m_editor, SLOT(focusOnContext(QModelIndex))); setCentralWidget(m_editor); } void MainWindow::setupSideBar() { m_sidebar = new SideBar(this, actionCollection()); QDockWidget *dock = new QDockWidget(this); dock->setObjectName("SideBar"); dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable); dock->setWidget(m_sidebar); addDockWidget(Qt::LeftDockWidgetArea, dock); } void MainWindow::setupActions() { KActionCollection *ac = actionCollection(); QActionGroup *modeGroup = new QActionGroup(this); modeGroup->setExclusive(true); KAction *action = ac->addAction("project_mode", m_sidebar, SLOT(switchToProjectMode())); action->setText(i18n("Project Mode")); action->setIcon(KIcon("view-pim-tasks")); action->setCheckable(true); modeGroup->addAction(action); action = ac->addAction("context_mode", m_sidebar, SLOT(switchToContextMode())); action->setText(i18n("Context Mode")); action->setIcon(KIcon("view-pim-notes")); action->setCheckable(true); modeGroup->addAction(action); ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog())); ac->addAction(KStandardAction::Quit, this, SLOT(close())); } void MainWindow::closeEvent(QCloseEvent *event) { saveColumnsState(); KXmlGuiWindow::closeEvent(event); } void MainWindow::saveAutoSaveSettings() { saveColumnsState(); KXmlGuiWindow::saveAutoSaveSettings(); } void MainWindow::saveColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); QByteArray state = m_editor->view()->header()->saveState(); cg.writeEntry("MainHeaderState", state.toBase64()); } void MainWindow::restoreColumnState() { KConfigGroup cg = autoSaveConfigGroup(); QByteArray state; if (cg.hasKey("MainHeaderState")) { state = cg.readEntry("MainHeaderState", state); m_editor->view()->header()->restoreState(QByteArray::fromBase64(state)); } } void MainWindow::showConfigDialog() { if (KConfigDialog::showDialog("settings")) { return; } ConfigDialog *dialog = new ConfigDialog(this, "settings", GlobalSettings::self()); connect(dialog, SIGNAL(settingsChanged(const QString&)), this, SLOT(applySettings())); dialog->show(); } void MainWindow::applySettings() { Akonadi::Collection collection(GlobalSettings::collectionId()); if (!collection.isValid()) return; Akonadi::CollectionFetchJob *job = new Akonadi::CollectionFetchJob(collection, Akonadi::CollectionFetchJob::Base); job->exec(); GlobalModel::todoFlat()->setCollection(job->collections().first()); } <commit_msg>Make sure the collection was really fetched.<commit_after>/* This file is part of Zanshin Todo. Copyright 2008 Kevin Ottens <ervin@kde.org> Copyright 2008, 2009 Mario Bensi <nef@ipsquad.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mainwindow.h" #include <akonadi/control.h> #include <akonadi/collectionfetchjob.h> #include <KDE/KAction> #include <KDE/KActionCollection> #include <KDE/KConfigGroup> #include <KDE/KIcon> #include <KDE/KLocale> #include <QtGui/QDockWidget> #include <QtGui/QHeaderView> #include "actionlisteditor.h" #include "actionlistview.h" #include "configdialog.h" #include "globalmodel.h" #include "globalsettings.h" #include "todoflatmodel.h" #include "sidebar.h" MainWindow::MainWindow(QWidget *parent) : KXmlGuiWindow(parent) { Akonadi::Control::start(); setupSideBar(); setupCentralWidget(); setupActions(); setupGUI(); restoreColumnState(); applySettings(); actionCollection()->action("project_mode")->trigger(); } void MainWindow::setupCentralWidget() { m_editor = new ActionListEditor(this, actionCollection()); connect(m_sidebar, SIGNAL(noProjectInboxActivated()), m_editor, SLOT(showNoProjectInbox())); connect(m_sidebar, SIGNAL(projectActivated(QModelIndex)), m_editor, SLOT(focusOnProject(QModelIndex))); connect(m_sidebar, SIGNAL(noContextInboxActivated()), m_editor, SLOT(showNoContextInbox())); connect(m_sidebar, SIGNAL(contextActivated(QModelIndex)), m_editor, SLOT(focusOnContext(QModelIndex))); setCentralWidget(m_editor); } void MainWindow::setupSideBar() { m_sidebar = new SideBar(this, actionCollection()); QDockWidget *dock = new QDockWidget(this); dock->setObjectName("SideBar"); dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable); dock->setWidget(m_sidebar); addDockWidget(Qt::LeftDockWidgetArea, dock); } void MainWindow::setupActions() { KActionCollection *ac = actionCollection(); QActionGroup *modeGroup = new QActionGroup(this); modeGroup->setExclusive(true); KAction *action = ac->addAction("project_mode", m_sidebar, SLOT(switchToProjectMode())); action->setText(i18n("Project Mode")); action->setIcon(KIcon("view-pim-tasks")); action->setCheckable(true); modeGroup->addAction(action); action = ac->addAction("context_mode", m_sidebar, SLOT(switchToContextMode())); action->setText(i18n("Context Mode")); action->setIcon(KIcon("view-pim-notes")); action->setCheckable(true); modeGroup->addAction(action); ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog())); ac->addAction(KStandardAction::Quit, this, SLOT(close())); } void MainWindow::closeEvent(QCloseEvent *event) { saveColumnsState(); KXmlGuiWindow::closeEvent(event); } void MainWindow::saveAutoSaveSettings() { saveColumnsState(); KXmlGuiWindow::saveAutoSaveSettings(); } void MainWindow::saveColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); QByteArray state = m_editor->view()->header()->saveState(); cg.writeEntry("MainHeaderState", state.toBase64()); } void MainWindow::restoreColumnState() { KConfigGroup cg = autoSaveConfigGroup(); QByteArray state; if (cg.hasKey("MainHeaderState")) { state = cg.readEntry("MainHeaderState", state); m_editor->view()->header()->restoreState(QByteArray::fromBase64(state)); } } void MainWindow::showConfigDialog() { if (KConfigDialog::showDialog("settings")) { return; } ConfigDialog *dialog = new ConfigDialog(this, "settings", GlobalSettings::self()); connect(dialog, SIGNAL(settingsChanged(const QString&)), this, SLOT(applySettings())); dialog->show(); } void MainWindow::applySettings() { Akonadi::Collection collection(GlobalSettings::collectionId()); if (!collection.isValid()) return; Akonadi::CollectionFetchJob *job = new Akonadi::CollectionFetchJob(collection, Akonadi::CollectionFetchJob::Base); job->exec(); if (job->collections().isEmpty()) return; GlobalModel::todoFlat()->setCollection(job->collections().first()); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include <KActionCollection> #include <QFileDialog> #include <KMessageBox> #include <KService> #include <KStandardAction> #include <QUrl> #include <KToolBar> #include <QApplication> #include <QTemporaryDir> #include <QTemporaryFile> #include <QFile> #include <iostream> #include <QtCore/QDebug> #undef QT_NO_DEBUG #include <kdebug.h> void MainWindow::textChanged(KTextEditor::Document *document) { (void)document; refreshTimer->start(1000); } void MainWindow::render() { render(display->getScale()); } void MainWindow::gotoNextImage() { if(currentDoc && currentPage < currentDoc->numPages()) { currentPage++; render(); } } void MainWindow::gotoPreviousImage() { if(currentPage > 0) { currentPage--; render(); } } void MainWindow::render(double scale) { if (currentDoc && display) { if(currentPage >= currentDoc->numPages()) { currentPage = currentDoc->numPages() - 1; } if(currentPage < 0) { currentPage = 0; } prevImage->setVisible(currentDoc->numPages() > 1); nextImage->setVisible(currentDoc->numPages() > 1); QImage image = currentDoc->page(currentPage)->renderToImage(scale * physicalDpiX(), scale * physicalDpiY()); display->setImage(image); } } void MainWindow::compile() { QSettings settings; QString program = settings.value("compiler", "pdflatex").toString(); QStringList arguments; QTemporaryDir tmpdir; tmpdir.setAutoRemove(true); if (program == "pdflatex") { arguments << "-halt-on-error"; } if(dir->path() == "") { return; } if(texdir.absolutePath() == "") { std::cout << "need a temporary directory" << std::endl; texdir = QFileInfo(tmpdir.path()); } arguments << dir->filePath("_livetikz_preview.tex"); std::cout << "Arguments: " << dir->filePath("_livetikz_preview.tex").toStdString() << std::endl; std::cout << "WD: " << texdir.absolutePath().toStdString() << std::endl; renderProcess = new QProcess(this); renderProcess->setWorkingDirectory(texdir.absolutePath()); renderProcess->start(program, arguments); log->setText("Compiling..."); renderOutput = ""; connect(renderProcess, SIGNAL(finished(int)), this, SLOT(renderFinished(int))); connect(renderProcess, SIGNAL(readyReadStandardError()), this, SLOT(updateLog())); connect(renderProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(updateLog())); connect(killButton, SIGNAL(clicked()), renderProcess, SLOT(kill())); killButton->setVisible(true); } void MainWindow::refresh() { if(!dir) { dir = new QTemporaryDir(); dir->setAutoRemove(false); } if (dir->isValid()) { QFile file(dir->filePath("_livetikz_preview.tex")); if (file.open(QIODevice::ReadWrite | QIODevice::Text)) { QTextStream out(&file); QFile inputFile(templateFile.url(QUrl::PreferLocalFile)); if (inputFile.exists() && inputFile.open(QIODevice::ReadOnly)) { QTextStream in(&inputFile); while (!in.atEnd()) { QString line = in.readLine(); if (line.trimmed() == "<>") { out << doc->text() << "\n"; } else { out << line << "\n"; } } inputFile.close(); } else { out << "\\documentclass{article}\n" << "\\usepackage{tikz}\n" << "\\usepackage{color}\n" << "\\usepackage{amssymb}\n" << "\\usepackage{pgfplots}\n" << "\\usetikzlibrary{pgfplots.groupplots}\n" << "\\usetikzlibrary{arrows}\n" << "\\usetikzlibrary{patterns}\n" << "\\usetikzlibrary{positioning}\n" << "\\usetikzlibrary{decorations.pathreplacing}\n" << "\\usetikzlibrary{shapes.arrows}\n" << "\\usetikzlibrary{pgfplots.groupplots}\n" << "\\pgfplotsset{compat=1.13}\n"; out << "\\begin{document}\n"; out << doc->text() << "\n"; out << "\\end{document}\n"; } out.flush(); file.flush(); file.close(); if (renderProcess != NULL) { refreshTimer->start(1000); // wait for old rendering to finish } compile(); } } } void MainWindow::appendLog(QString str) { renderOutput += str; log->setText(renderOutput); log->verticalScrollBar()->setValue(log->verticalScrollBar()->maximum()); QTextCursor c = log->textCursor(); c.movePosition(QTextCursor::End); log->setTextCursor(c); } void MainWindow::updateLog() { if (renderProcess) { appendLog(renderProcess->readAllStandardOutput()); } } void MainWindow::renderFinished(int code) { if (code == 0) { appendLog("Done!"); } else { appendLog("Error!"); } killButton->setVisible(false); if(!dir) return; delete currentDoc; currentDoc = NULL; QFile pdf_file(QDir::cleanPath(texdir.absolutePath() + QDir::separator() + "_livetikz_preview.pdf")); if (pdf_file.exists()) { QFile::rename(QDir::cleanPath(texdir.absolutePath() + QDir::separator() + "_livetikz_preview.pdf"), dir->filePath("_livetikz_preview.pdf")); currentDoc = Poppler::Document::load(dir->filePath("_livetikz_preview.pdf")); if (currentDoc) { currentDoc->setRenderHint(Poppler::Document::TextAntialiasing); currentDoc->setRenderHint(Poppler::Document::Antialiasing); currentDoc->setRenderHint(Poppler::Document::TextHinting); currentDoc->setRenderHint(Poppler::Document::TextSlightHinting); currentDoc->setRenderHint(Poppler::Document::ThinLineSolid); render(); } } dir->remove(); delete dir; dir = NULL; renderProcess = NULL; } MainWindow::MainWindow() : currentDoc(NULL), renderProcess(NULL), currentPage(0) { QSettings settings; setupEditor(); setupActions(); setupMenu(); setupUI(); dir = NULL; templateFile = QUrl(settings.value("template", "").toString()); templateLabel->setText(templateFile.url(QUrl::PreferLocalFile)); doc->setHighlightingMode("Latex"); refreshTimer = new QTimer(this); refreshTimer->setSingleShot(true); connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refresh())); refreshTimer->start(1000); connect(display, SIGNAL(zoomChanged(double)), this, SLOT(render(double))); connect(browseButton, SIGNAL(clicked()), SLOT(browse())); connect(prevImage, SIGNAL(triggered()), this, SLOT(gotoPreviousImage())); connect(nextImage, SIGNAL(triggered()), this, SLOT(gotoNextImage())); connect((QObject *)doc, SIGNAL(textChanged(KTextEditor::Document *)), this, SLOT(textChanged(KTextEditor::Document *))); connect(templateLabel, SIGNAL(textEdited(const QString&)), this, SLOT(updateTemplate(const QString&))); } void MainWindow::showCompilerSelection() { QStringList items; items << tr("pdflatex") << tr("latexrun"); bool ok; QString item = QInputDialog::getItem(this, tr("LaTeX compiler"), tr("Compiler:"), items, 0, false, &ok); if (ok && !item.isEmpty()) { QSettings settings; settings.setValue("compiler", item); } } MainWindow::~MainWindow() {} void MainWindow::load(const QUrl &url) { texdir = QFileInfo(url.toLocalFile()); katePart->openUrl(url); } void MainWindow::setupActions() { KStandardAction::open(this, SLOT(load()), actionCollection()); KStandardAction::quit(qApp, SLOT(closeAllWindows()), actionCollection()); } void MainWindow::setupMenu() { QMenu *tikzMenu = new QMenu(tr("LiveTikZ"), this); QAction *compiler = tikzMenu->addAction(tr("&Compiler")); connect(compiler, SIGNAL(triggered()), this, SLOT(showCompilerSelection())); menuBar()->addMenu(tikzMenu); } void MainWindow::setupUI() { window = new QWidget; mainLayout = new QHBoxLayout; splitView = new QSplitter(window); templateLabel = new QLineEdit("Select template..."); browseButton = new QPushButton("Browse"); templateLayout = new QHBoxLayout; templateLayout->addWidget(templateLabel); templateLayout->addWidget(browseButton); leftLayout = new QVBoxLayout; leftLayout->addLayout(templateLayout); splitView->addWidget(view); display = new ZoomScrollImage; log = new QTextEdit(window); log->setReadOnly(true); log->ensureCursorVisible(); QFontMetrics m(log->font()); log->setFixedHeight(5 * m.lineSpacing()); logLayout = new QHBoxLayout; splitView->addWidget(display); leftLayout->addWidget(splitView); logLayout->addWidget(log); killButton = new QPushButton("Kill pdflatex"); killButton->setVisible(false); logLayout->addWidget(killButton); leftLayout->addLayout(logLayout); mainLayout->addLayout(leftLayout); window->setLayout(mainLayout); setCentralWidget(window); setupGUI(ToolBar | Keys | StatusBar | Save); createGUI(katePart); toolBar()->addSeparator(); prevImage = toolBar()->addAction(QIcon::fromTheme("go-previous"), "Previous image"); nextImage = toolBar()->addAction(QIcon::fromTheme("go-next"), "Next image"); prevImage->setVisible(false); nextImage->setVisible(false); QDesktopWidget widget; QRect mainScreenSize = widget.availableGeometry(widget.primaryScreen()); this->resize(mainScreenSize.width() * 0.7, mainScreenSize.height() * 0.7); log->resize(mainScreenSize.width() * 0.7, mainScreenSize.height() * 0.7 * 0.1); display->resize(mainScreenSize.width() * 0.7 * 0.5, mainScreenSize.height() * 0.7 * 1); view->resize(mainScreenSize.width() * 0.7 * 0.5, mainScreenSize.height() * 0.7 * 0.9); setWindowIcon(QIcon(":/logo.png")); } void MainWindow::setupEditor() { KService::Ptr service = KService::serviceByDesktopName("katepart"); if (service) { katePart = service->createInstance<KParts::ReadWritePart>(0); if (katePart) { view = ((KTextEditor::View *)katePart->widget()); doc = view->document(); } else { KMessageBox::error(this, "Could not create editor"); qApp->quit(); } } else { KMessageBox::error(this, "Service katepart not found - please install kate"); qApp->quit(); } } void MainWindow::load() { load(QFileDialog::getOpenFileUrl()); } void MainWindow::updateTemplate(const QString& filename) { QSettings settings; templateFile = QUrl::fromUserInput(filename); settings.setValue("template", filename); refresh(); } void MainWindow::browse() { QUrl newTemplateFile = QFileDialog::getOpenFileUrl(this, QString("Open template")); if (newTemplateFile.fileName() != "") { QString filename = newTemplateFile.url(QUrl::PreferLocalFile); templateLabel->setText(filename); updateTemplate(filename); } } <commit_msg>fixed race condition<commit_after>#include "mainwindow.h" #include <KActionCollection> #include <QFileDialog> #include <KMessageBox> #include <KService> #include <KStandardAction> #include <QUrl> #include <KToolBar> #include <QApplication> #include <QTemporaryDir> #include <QTemporaryFile> #include <QFile> #include <iostream> #include <QtCore/QDebug> #undef QT_NO_DEBUG #include <kdebug.h> void MainWindow::textChanged(KTextEditor::Document *document) { (void)document; refreshTimer->start(1000); } void MainWindow::render() { render(display->getScale()); } void MainWindow::gotoNextImage() { if(currentDoc && currentPage < currentDoc->numPages()) { currentPage++; render(); } } void MainWindow::gotoPreviousImage() { if(currentPage > 0) { currentPage--; render(); } } void MainWindow::render(double scale) { if (currentDoc && display) { if(currentPage >= currentDoc->numPages()) { currentPage = currentDoc->numPages() - 1; } if(currentPage < 0) { currentPage = 0; } prevImage->setVisible(currentDoc->numPages() > 1); nextImage->setVisible(currentDoc->numPages() > 1); QImage image = currentDoc->page(currentPage)->renderToImage(scale * physicalDpiX(), scale * physicalDpiY()); display->setImage(image); } } void MainWindow::compile() { QSettings settings; QString program = settings.value("compiler", "pdflatex").toString(); QStringList arguments; QTemporaryDir tmpdir; tmpdir.setAutoRemove(true); if (program == "pdflatex") { arguments << "-halt-on-error"; } if(dir->path() == "") { return; } if(texdir.absolutePath() == "") { std::cout << "need a temporary directory" << std::endl; texdir = QFileInfo(tmpdir.path()); } arguments << dir->filePath("_livetikz_preview.tex"); std::cout << "Arguments: " << dir->filePath("_livetikz_preview.tex").toStdString() << std::endl; std::cout << "WD: " << texdir.absolutePath().toStdString() << std::endl; renderProcess = new QProcess(this); renderProcess->setWorkingDirectory(texdir.absolutePath()); renderProcess->start(program, arguments); log->setText("Compiling..."); renderOutput = ""; connect(renderProcess, SIGNAL(finished(int)), this, SLOT(renderFinished(int))); connect(renderProcess, SIGNAL(readyReadStandardError()), this, SLOT(updateLog())); connect(renderProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(updateLog())); connect(killButton, SIGNAL(clicked()), renderProcess, SLOT(kill())); killButton->setVisible(true); } void MainWindow::refresh() { if(!dir) { dir = new QTemporaryDir(); dir->setAutoRemove(false); } if (dir->isValid()) { QFile file(dir->filePath("_livetikz_preview.tex")); if (file.open(QIODevice::ReadWrite | QIODevice::Text)) { QTextStream out(&file); QFile inputFile(templateFile.url(QUrl::PreferLocalFile)); if (inputFile.exists() && inputFile.open(QIODevice::ReadOnly)) { QTextStream in(&inputFile); while (!in.atEnd()) { QString line = in.readLine(); if (line.trimmed() == "<>") { out << doc->text() << "\n"; } else { out << line << "\n"; } } inputFile.close(); } else { out << "\\documentclass{article}\n" << "\\usepackage{tikz}\n" << "\\usepackage{color}\n" << "\\usepackage{amssymb}\n" << "\\usepackage{pgfplots}\n" << "\\usetikzlibrary{pgfplots.groupplots}\n" << "\\usetikzlibrary{arrows}\n" << "\\usetikzlibrary{patterns}\n" << "\\usetikzlibrary{positioning}\n" << "\\usetikzlibrary{decorations.pathreplacing}\n" << "\\usetikzlibrary{shapes.arrows}\n" << "\\usetikzlibrary{pgfplots.groupplots}\n" << "\\pgfplotsset{compat=1.13}\n"; out << "\\begin{document}\n"; out << doc->text() << "\n"; out << "\\end{document}\n"; } out.flush(); file.flush(); file.close(); if (renderProcess != NULL) { refreshTimer->start(1000); // wait for old rendering to finish } else { compile(); } } } } void MainWindow::appendLog(QString str) { renderOutput += str; log->setText(renderOutput); log->verticalScrollBar()->setValue(log->verticalScrollBar()->maximum()); QTextCursor c = log->textCursor(); c.movePosition(QTextCursor::End); log->setTextCursor(c); } void MainWindow::updateLog() { if (renderProcess) { appendLog(renderProcess->readAllStandardOutput()); } } void MainWindow::renderFinished(int code) { if (code == 0) { appendLog("Done!"); } else { appendLog("Error!"); } killButton->setVisible(false); if(!dir) return; delete currentDoc; currentDoc = NULL; QFile pdf_file(QDir::cleanPath(texdir.absolutePath() + QDir::separator() + "_livetikz_preview.pdf")); if (pdf_file.exists()) { QFile::rename(QDir::cleanPath(texdir.absolutePath() + QDir::separator() + "_livetikz_preview.pdf"), dir->filePath("_livetikz_preview.pdf")); currentDoc = Poppler::Document::load(dir->filePath("_livetikz_preview.pdf")); if (currentDoc) { currentDoc->setRenderHint(Poppler::Document::TextAntialiasing); currentDoc->setRenderHint(Poppler::Document::Antialiasing); currentDoc->setRenderHint(Poppler::Document::TextHinting); currentDoc->setRenderHint(Poppler::Document::TextSlightHinting); currentDoc->setRenderHint(Poppler::Document::ThinLineSolid); render(); } } dir->remove(); delete dir; dir = NULL; renderProcess = NULL; } MainWindow::MainWindow() : currentDoc(NULL), renderProcess(NULL), currentPage(0) { QSettings settings; setupEditor(); setupActions(); setupMenu(); setupUI(); dir = NULL; templateFile = QUrl(settings.value("template", "").toString()); templateLabel->setText(templateFile.url(QUrl::PreferLocalFile)); doc->setHighlightingMode("Latex"); refreshTimer = new QTimer(this); refreshTimer->setSingleShot(true); connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refresh())); refreshTimer->start(1000); connect(display, SIGNAL(zoomChanged(double)), this, SLOT(render(double))); connect(browseButton, SIGNAL(clicked()), SLOT(browse())); connect(prevImage, SIGNAL(triggered()), this, SLOT(gotoPreviousImage())); connect(nextImage, SIGNAL(triggered()), this, SLOT(gotoNextImage())); connect((QObject *)doc, SIGNAL(textChanged(KTextEditor::Document *)), this, SLOT(textChanged(KTextEditor::Document *))); connect(templateLabel, SIGNAL(textEdited(const QString&)), this, SLOT(updateTemplate(const QString&))); } void MainWindow::showCompilerSelection() { QStringList items; items << tr("pdflatex") << tr("latexrun"); bool ok; QString item = QInputDialog::getItem(this, tr("LaTeX compiler"), tr("Compiler:"), items, 0, false, &ok); if (ok && !item.isEmpty()) { QSettings settings; settings.setValue("compiler", item); } } MainWindow::~MainWindow() {} void MainWindow::load(const QUrl &url) { texdir = QFileInfo(url.toLocalFile()); katePart->openUrl(url); } void MainWindow::setupActions() { KStandardAction::open(this, SLOT(load()), actionCollection()); KStandardAction::quit(qApp, SLOT(closeAllWindows()), actionCollection()); } void MainWindow::setupMenu() { QMenu *tikzMenu = new QMenu(tr("LiveTikZ"), this); QAction *compiler = tikzMenu->addAction(tr("&Compiler")); connect(compiler, SIGNAL(triggered()), this, SLOT(showCompilerSelection())); menuBar()->addMenu(tikzMenu); } void MainWindow::setupUI() { window = new QWidget; mainLayout = new QHBoxLayout; splitView = new QSplitter(window); templateLabel = new QLineEdit("Select template..."); browseButton = new QPushButton("Browse"); templateLayout = new QHBoxLayout; templateLayout->addWidget(templateLabel); templateLayout->addWidget(browseButton); leftLayout = new QVBoxLayout; leftLayout->addLayout(templateLayout); splitView->addWidget(view); display = new ZoomScrollImage; log = new QTextEdit(window); log->setReadOnly(true); log->ensureCursorVisible(); QFontMetrics m(log->font()); log->setFixedHeight(5 * m.lineSpacing()); logLayout = new QHBoxLayout; splitView->addWidget(display); leftLayout->addWidget(splitView); logLayout->addWidget(log); killButton = new QPushButton("Kill pdflatex"); killButton->setVisible(false); logLayout->addWidget(killButton); leftLayout->addLayout(logLayout); mainLayout->addLayout(leftLayout); window->setLayout(mainLayout); setCentralWidget(window); setupGUI(ToolBar | Keys | StatusBar | Save); createGUI(katePart); toolBar()->addSeparator(); prevImage = toolBar()->addAction(QIcon::fromTheme("go-previous"), "Previous image"); nextImage = toolBar()->addAction(QIcon::fromTheme("go-next"), "Next image"); prevImage->setVisible(false); nextImage->setVisible(false); QDesktopWidget widget; QRect mainScreenSize = widget.availableGeometry(widget.primaryScreen()); this->resize(mainScreenSize.width() * 0.7, mainScreenSize.height() * 0.7); log->resize(mainScreenSize.width() * 0.7, mainScreenSize.height() * 0.7 * 0.1); display->resize(mainScreenSize.width() * 0.7 * 0.5, mainScreenSize.height() * 0.7 * 1); view->resize(mainScreenSize.width() * 0.7 * 0.5, mainScreenSize.height() * 0.7 * 0.9); setWindowIcon(QIcon(":/logo.png")); } void MainWindow::setupEditor() { KService::Ptr service = KService::serviceByDesktopName("katepart"); if (service) { katePart = service->createInstance<KParts::ReadWritePart>(0); if (katePart) { view = ((KTextEditor::View *)katePart->widget()); doc = view->document(); } else { KMessageBox::error(this, "Could not create editor"); qApp->quit(); } } else { KMessageBox::error(this, "Service katepart not found - please install kate"); qApp->quit(); } } void MainWindow::load() { load(QFileDialog::getOpenFileUrl()); } void MainWindow::updateTemplate(const QString& filename) { QSettings settings; templateFile = QUrl::fromUserInput(filename); settings.setValue("template", filename); refresh(); } void MainWindow::browse() { QUrl newTemplateFile = QFileDialog::getOpenFileUrl(this, QString("Open template")); if (newTemplateFile.fileName() != "") { QString filename = newTemplateFile.url(QUrl::PreferLocalFile); templateLabel->setText(filename); updateTemplate(filename); } } <|endoftext|>
<commit_before>/* * Main Send File Transfer Window * * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mainwindow.h" #include "ui_mainwindow.h" #include <KFileItem> #include <KFileItemList> #include <KIO/PreviewJob> #include <KApplication> #include <KCmdLineArgs> #include <KMimeType> #include <KDebug> #include <KMessageBox> #include <KPixmapSequence> #include <KPixmapSequenceOverlayPainter> #include <KDE/KIO/PreviewJob> #include <QAbstractItemDelegate> #include <QPainter> #include <QRect> #include <QStyle> #include <QDebug> #include <QAbstractButton> #include <TelepathyQt/AccountManager> #include <TelepathyQt/PendingChannelRequest> #include <TelepathyQt/PendingReady> #include "flat-model-proxy.h" #include <KTp/Models/accounts-model.h> #include <KTp/Models/accounts-filter-model.h> #include <KTp/Models/contact-model-item.h> //FIXME, copy and paste the approver code for loading this from a config file into this, the contact list and the chat handler. #define PREFERRED_FILETRANSFER_HANDLER "org.freedesktop.Telepathy.Client.KDE.FileTransfer" class ContactGridDelegate : public QAbstractItemDelegate { public: ContactGridDelegate(QObject *parent); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; }; ContactGridDelegate::ContactGridDelegate(QObject *parent) : QAbstractItemDelegate(parent) { } void ContactGridDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyle *style = QApplication::style(); int textHeight = option.fontMetrics.height()*2; style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter); QRect avatarRect = option.rect.adjusted(0,0,0,-textHeight); QRect textRect = option.rect.adjusted(0,option.rect.height()-textHeight,0,-3); QPixmap avatar = index.data(Qt::DecorationRole).value<QPixmap>(); if (avatar.isNull()) { avatar = KIcon("im-user-online").pixmap(QSize(70,70)); } //resize larger avatars if (avatar.width() > 80 || avatar.height()> 80) { avatar = avatar.scaled(QSize(80,80), Qt::KeepAspectRatio); //draw leaving paddings on smaller (or non square) avatars } style->drawItemPixmap(painter, avatarRect, Qt::AlignCenter, avatar); QTextOption textOption; textOption.setAlignment(Qt::AlignCenter); textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); painter->drawText(textRect, index.data().toString(), textOption); } QSize ContactGridDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index); int textHeight = option.fontMetrics.height()*2; return QSize(84, 80 + textHeight + 3); } MainWindow::MainWindow(const KUrl &url, QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow), m_accountsModel(0) { Tp::registerTypes(); ui->setupUi(this); setWindowTitle(i18n("Send file - %1", url.fileName())); kDebug() << KApplication::arguments(); ui->fileNameLabel->setText(url.fileName()); m_busyOverlay = new KPixmapSequenceOverlayPainter(this); m_busyOverlay->setSequence(KPixmapSequence("process-working", 22)); m_busyOverlay->setWidget(ui->filePreview); m_busyOverlay->start(); KFileItem file(KFileItem::Unknown, KFileItem::Unknown, url); QStringList availablePlugins = KIO::PreviewJob::availablePlugins(); KIO::PreviewJob* job = KIO::filePreview(KFileItemList() << file, QSize(280, 280), &availablePlugins); job->setOverlayIconAlpha(0); job->setScaleType(KIO::PreviewJob::Unscaled); connect(job, SIGNAL(gotPreview(KFileItem,QPixmap)), this, SLOT(onPreviewLoaded(KFileItem,QPixmap))); connect(job, SIGNAL(failed(KFileItem)), this, SLOT(onPreviewFailed(KFileItem))); Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar << Tp::Account::FeatureProtocolInfo << Tp::Account::FeatureProfile); Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureRosterGroups << Tp::Connection::FeatureRoster << Tp::Connection::FeatureSelfContact); Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias << Tp::Contact::FeatureAvatarData << Tp::Contact::FeatureSimplePresence << Tp::Contact::FeatureCapabilities); Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus()); m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(), accountFactory, connectionFactory, channelFactory, contactFactory); connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady())); connect(ui->buttonBox, SIGNAL(accepted()), SLOT(onDialogAccepted())); connect(ui->buttonBox, SIGNAL(rejected()), SLOT(close())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::onAccountManagerReady() { m_accountsModel = new AccountsModel(m_accountManager, this); AccountsFilterModel *filterModel = new AccountsFilterModel(this); filterModel->setSourceModel(m_accountsModel); filterModel->setShowOfflineUsers(false); filterModel->setFilterByFileTransferCapability(true); connect(ui->filterBar, SIGNAL(textChanged(QString)), filterModel, SLOT(setFilterString(QString))); FlatModelProxy *flatProxyModel = new FlatModelProxy(filterModel); ui->listView->setModel(flatProxyModel); ui->listView->setItemDelegate(new ContactGridDelegate(this)); } void MainWindow::onDialogAccepted() { // don't do anytghing if no contact has been selected if (!ui->listView->currentIndex().isValid()) { // show message box? return; } ContactModelItem *contactModelItem = ui->listView->currentIndex().data(AccountsModel::ItemRole).value<ContactModelItem*>(); Tp::ContactPtr contact = contactModelItem->contact(); Tp::AccountPtr sendingAccount = m_accountsModel->accountForContactItem(contactModelItem); if (sendingAccount.isNull()) { kDebug() << "sending account: NULL"; } else { kDebug() << "Account is: " << sendingAccount->displayName(); kDebug() << "sending to: " << contact->alias(); } // start sending file QString filePath (KCmdLineArgs::parsedArgs()->arg(0)); qDebug() << "FILE TO SEND: " << filePath; Tp::FileTransferChannelCreationProperties fileTransferProperties(filePath, KMimeType::findByFileContent(filePath)->name()); Tp::PendingChannelRequest* channelRequest = sendingAccount->createFileTransfer(contact, fileTransferProperties, QDateTime::currentDateTime(), PREFERRED_FILETRANSFER_HANDLER); connect(channelRequest, SIGNAL(finished(Tp::PendingOperation*)), SLOT(slotFileTransferFinished(Tp::PendingOperation*))); //disable the buttons foreach(QAbstractButton* button, ui->buttonBox->buttons()) { button->setEnabled(false); } } void MainWindow::slotFileTransferFinished(Tp::PendingOperation* op) { if (op->isError()) { //FIXME map to human readable strings. QString errorMsg(op->errorName() + ": " + op->errorMessage()); kDebug() << "ERROR!: " << errorMsg; KMessageBox::error(this, i18n("Failed to send file"), i18n("File Transfer Failed")); close(); } else { kDebug() << "Transfer started"; // now I can close the dialog close(); } } void MainWindow::onPreviewLoaded(const KFileItem& item, const QPixmap& preview) { Q_UNUSED(item); ui->filePreview->setPixmap(preview); m_busyOverlay->stop(); } void MainWindow::onPreviewFailed(const KFileItem& item) { kWarning() << "Loading thumb failed" << item.name(); ui->filePreview->setPixmap(KIconLoader::global()->loadIcon(item.iconName(), KIconLoader::Desktop, 128)); m_busyOverlay->stop(); } <commit_msg>Update to use aysnc setting of account manager in account model creation.<commit_after>/* * Main Send File Transfer Window * * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mainwindow.h" #include "ui_mainwindow.h" #include <KFileItem> #include <KFileItemList> #include <KIO/PreviewJob> #include <KApplication> #include <KCmdLineArgs> #include <KMimeType> #include <KDebug> #include <KMessageBox> #include <KPixmapSequence> #include <KPixmapSequenceOverlayPainter> #include <KDE/KIO/PreviewJob> #include <QAbstractItemDelegate> #include <QPainter> #include <QRect> #include <QStyle> #include <QDebug> #include <QAbstractButton> #include <TelepathyQt/AccountManager> #include <TelepathyQt/PendingChannelRequest> #include <TelepathyQt/PendingReady> #include "flat-model-proxy.h" #include <KTp/Models/accounts-model.h> #include <KTp/Models/accounts-filter-model.h> #include <KTp/Models/contact-model-item.h> //FIXME, copy and paste the approver code for loading this from a config file into this, the contact list and the chat handler. #define PREFERRED_FILETRANSFER_HANDLER "org.freedesktop.Telepathy.Client.KDE.FileTransfer" class ContactGridDelegate : public QAbstractItemDelegate { public: ContactGridDelegate(QObject *parent); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; }; ContactGridDelegate::ContactGridDelegate(QObject *parent) : QAbstractItemDelegate(parent) { } void ContactGridDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyle *style = QApplication::style(); int textHeight = option.fontMetrics.height()*2; style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter); QRect avatarRect = option.rect.adjusted(0,0,0,-textHeight); QRect textRect = option.rect.adjusted(0,option.rect.height()-textHeight,0,-3); QPixmap avatar = index.data(Qt::DecorationRole).value<QPixmap>(); if (avatar.isNull()) { avatar = KIcon("im-user-online").pixmap(QSize(70,70)); } //resize larger avatars if (avatar.width() > 80 || avatar.height()> 80) { avatar = avatar.scaled(QSize(80,80), Qt::KeepAspectRatio); //draw leaving paddings on smaller (or non square) avatars } style->drawItemPixmap(painter, avatarRect, Qt::AlignCenter, avatar); QTextOption textOption; textOption.setAlignment(Qt::AlignCenter); textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); painter->drawText(textRect, index.data().toString(), textOption); } QSize ContactGridDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index); int textHeight = option.fontMetrics.height()*2; return QSize(84, 80 + textHeight + 3); } MainWindow::MainWindow(const KUrl &url, QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow), m_accountsModel(0) { Tp::registerTypes(); ui->setupUi(this); setWindowTitle(i18n("Send file - %1", url.fileName())); kDebug() << KApplication::arguments(); ui->fileNameLabel->setText(url.fileName()); m_busyOverlay = new KPixmapSequenceOverlayPainter(this); m_busyOverlay->setSequence(KPixmapSequence("process-working", 22)); m_busyOverlay->setWidget(ui->filePreview); m_busyOverlay->start(); KFileItem file(KFileItem::Unknown, KFileItem::Unknown, url); QStringList availablePlugins = KIO::PreviewJob::availablePlugins(); KIO::PreviewJob* job = KIO::filePreview(KFileItemList() << file, QSize(280, 280), &availablePlugins); job->setOverlayIconAlpha(0); job->setScaleType(KIO::PreviewJob::Unscaled); connect(job, SIGNAL(gotPreview(KFileItem,QPixmap)), this, SLOT(onPreviewLoaded(KFileItem,QPixmap))); connect(job, SIGNAL(failed(KFileItem)), this, SLOT(onPreviewFailed(KFileItem))); Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar << Tp::Account::FeatureProtocolInfo << Tp::Account::FeatureProfile); Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureRosterGroups << Tp::Connection::FeatureRoster << Tp::Connection::FeatureSelfContact); Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias << Tp::Contact::FeatureAvatarData << Tp::Contact::FeatureSimplePresence << Tp::Contact::FeatureCapabilities); Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus()); m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(), accountFactory, connectionFactory, channelFactory, contactFactory); m_accountsModel = new AccountsModel(this); AccountsFilterModel *filterModel = new AccountsFilterModel(this); filterModel->setSourceModel(m_accountsModel); filterModel->setShowOfflineUsers(false); filterModel->setFilterByFileTransferCapability(true); connect(ui->filterBar, SIGNAL(textChanged(QString)), filterModel, SLOT(setFilterString(QString))); FlatModelProxy *flatProxyModel = new FlatModelProxy(filterModel); ui->listView->setModel(flatProxyModel); ui->listView->setItemDelegate(new ContactGridDelegate(this)); connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady())); connect(ui->buttonBox, SIGNAL(accepted()), SLOT(onDialogAccepted())); connect(ui->buttonBox, SIGNAL(rejected()), SLOT(close())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::onAccountManagerReady() { m_accountsModel->setAccountManager(m_accountManager); } void MainWindow::onDialogAccepted() { // don't do anytghing if no contact has been selected if (!ui->listView->currentIndex().isValid()) { // show message box? return; } ContactModelItem *contactModelItem = ui->listView->currentIndex().data(AccountsModel::ItemRole).value<ContactModelItem*>(); Tp::ContactPtr contact = contactModelItem->contact(); Tp::AccountPtr sendingAccount = m_accountsModel->accountForContactItem(contactModelItem); if (sendingAccount.isNull()) { kDebug() << "sending account: NULL"; } else { kDebug() << "Account is: " << sendingAccount->displayName(); kDebug() << "sending to: " << contact->alias(); } // start sending file QString filePath (KCmdLineArgs::parsedArgs()->arg(0)); qDebug() << "FILE TO SEND: " << filePath; Tp::FileTransferChannelCreationProperties fileTransferProperties(filePath, KMimeType::findByFileContent(filePath)->name()); Tp::PendingChannelRequest* channelRequest = sendingAccount->createFileTransfer(contact, fileTransferProperties, QDateTime::currentDateTime(), PREFERRED_FILETRANSFER_HANDLER); connect(channelRequest, SIGNAL(finished(Tp::PendingOperation*)), SLOT(slotFileTransferFinished(Tp::PendingOperation*))); //disable the buttons foreach(QAbstractButton* button, ui->buttonBox->buttons()) { button->setEnabled(false); } } void MainWindow::slotFileTransferFinished(Tp::PendingOperation* op) { if (op->isError()) { //FIXME map to human readable strings. QString errorMsg(op->errorName() + ": " + op->errorMessage()); kDebug() << "ERROR!: " << errorMsg; KMessageBox::error(this, i18n("Failed to send file"), i18n("File Transfer Failed")); close(); } else { kDebug() << "Transfer started"; // now I can close the dialog close(); } } void MainWindow::onPreviewLoaded(const KFileItem& item, const QPixmap& preview) { Q_UNUSED(item); ui->filePreview->setPixmap(preview); m_busyOverlay->stop(); } void MainWindow::onPreviewFailed(const KFileItem& item) { kWarning() << "Loading thumb failed" << item.name(); ui->filePreview->setPixmap(KIconLoader::global()->loadIcon(item.iconName(), KIconLoader::Desktop, 128)); m_busyOverlay->stop(); } <|endoftext|>
<commit_before>#ifndef ERASED_HPP #define ERASED_HPP #include <functional> #include <memory> // value semantic type erasure via base types template<typename T> class erased final { public: // alias for unique_ptr with a deleter function template<typename U> using ptr = std::unique_ptr<U, std::function<void (U*)>>; // construct with perfect forwarding to T template<typename... Args> erased(Args... args) : cloner(create_cloner<T>()), deleter(create_deleter<T>()), value(new T(std::forward<Args>(args)...), deleter) {} // construct from type that inherits T template<typename U> erased(U const & value) : cloner(create_cloner<U>()), deleter(create_deleter<U>()), value(new U(value), deleter) { static_assert(std::is_base_of<T, U>::value, "the given value does not inherit the erasure type"); static_assert(std::is_copy_constructible<U>::value, "the given value is not copy constructible"); } // copy constructor erased(erased const & other) : cloner(other.cloner), deleter(other.deleter), value(cloner(&*other.value), deleter) {} // construct from erased<U> where U inherits T template<typename U> erased(erased<U> const & other) : cloner(create_cloner<U>(other.cloner)), deleter(create_deleter<U>(other.deleter)), value(other.cloner(&*other.value), deleter) { static_throw_assert(std::is_base_of<T, U>::value, "the given value does not inherit the erasure type"); } // assignment operator erased & operator =(erased const & other) { cloner = other.cloner; deleter = other.deleter; ptr<T> newPtr(cloner(&*other.value), deleter); value.swap(newPtr); return *this; } // assignment operator from erased<U> where U inherits T template<typename U> erased & operator =(erased<U> const & other) { static_throw_assert(std::is_base_of<T, U>::value, "the given value does not inherit the erasure type"); cloner = create_cloner<U>(other.cloner); deleter = create_deleter<U>(other.deleter); ptr<T> newu_p(other.cloner(&*other.value), deleter); value.swap(std::move(newu_p)); return *this; } // assignment from U where U inherits T, and U is not erased<U> template<typename U, typename std::enable_if_t<std::is_base_of_v<T, U>, int> = 0> erased & operator =(U const & newValue) { cloner = create_cloner<U>(); deleter = create_deleter<U>(); ptr<T> newu_p(new U(newValue), deleter); value.swap(std::move(newu_p)); return *this; } // assignment from U where T can be assigned by U, and U is not an inheritor of T template<typename U, typename std::enable_if_t<!std::is_base_of_v<T, U> && !std::is_same_v<U, erased>, int> = 0> erased & operator =(U const & newValue) { *value = newValue; return *this; } std::unique_ptr<T> clone() const { return std::unique_ptr<T>(cloner(value.get())); } T & operator *() { return *value; } T * operator ->() { return &*value; } T const & operator *() const { return *value; } T const * operator ->() const { return &*value; } private: template<typename U> std::function<T* (T*)> create_cloner() { return [](T * original) { return (T*)new U(*static_cast<U*>(original)); }; } // create a cloner function of a multiply-erased value by wrapping the cloner of the source erased<U> template<typename U> std::function<T* (T*)> create_cloner(std::function<U* (U*)> underlying) { return [underlying](T * original) { return (T*)underlying(static_cast<U*>(original)); }; } template<typename U> std::function<void (T*)> create_deleter() { return [](T * p) { delete (U*)p; }; } // create a deleter function of a multiply-erased value by wrapping the cloner of the source erased<U> template<typename U> std::function<void (T*)> create_deleter(std::function<void (U*)> underlying) { return [underlying](T * p) { underlying(static_cast<U*>(p)); }; } template<typename U> friend class erased; std::function<T* (T*)> cloner; std::function<void(T*)> deleter; ptr<T> value; }; #endif //ERASED_HPP <commit_msg>Optimize erased.<commit_after>#ifndef ERASED_HPP #define ERASED_HPP #include <functional> #include <memory> // value semantic type erasure via base types template <typename T> class erased { template<typename... Us> struct subclass_argument { static constexpr bool value = false; }; template<typename U> struct subclass_argument<U> { static constexpr bool value = std::is_base_of<T, U>::value; }; public: typedef T type; // construct with perfect forwarding to T template <typename... Args, typename std::enable_if<std::is_constructible<T, Args...>::value && !subclass_argument<Args...>::value, int>::type = 0> erased(Args&&... args) : op_ptr(&op<T>), downcast_offset(0), value(new T(std::forward<Args>(args)...)) {} // construct from type that inherits T template <typename U> // ReSharper disable once CppNonExplicitConvertingConstructor erased(U const & value) : op_ptr(&op<U>), downcast_offset(compute_downcast_offset<U>()), value(new U(value)) { static_assert(std::is_base_of<T, U>::value, "the given value does not inherit the erasure type"); static_assert(std::is_copy_constructible<U>::value, "the given value is not copy constructible"); } // copy constructor erased(erased const & other) : op_ptr(other.op_ptr), downcast_offset(other.downcast_offset), value(other.do_clone()) {} // construct from erased<U> where U inherits T template <typename U> erased(erased<U> const & other) : op_ptr(other.op_ptr), downcast_offset(other.downcast_offset + compute_downcast_offset<U>()), value(other.do_clone()) { static_assert(std::is_base_of<T, U>::value, "the given value does not inherit the erasure type"); } ~erased() { do_delete(); } // assignment operator erased & operator =(erased const & other) { do_delete(); op_ptr = other.op_ptr; downcast_offset = other.downcast_offset; value = other.do_clone(); return *this; } // assignment operator from erased<U> where U inherits T template <typename U> erased & operator =(erased<U> const & other) { static_assert(std::is_base_of<T, U>::value, "the given value does not inherit the erasure type"); do_delete(); op_ptr = other.op_ptr; downcast_offset = other.downcast_offset + compute_downcast_offset<U>(); value = other.clone(); return *this; } // assignment from U where U inherits T template <typename U, typename std::enable_if<std::is_base_of<T, U>::value, int>::type = 0> erased & operator =(U const & newValue) { do_delete(); op_ptr = &op<U>; downcast_offset = compute_downcast_offset<U>(); value = new U(newValue); return *this; } // assignment from U where T can be assigned by U, and U is not an inheritor of T template <typename U, typename std::enable_if<!std::is_base_of<T, U>::value && !std::is_same<U, erased>::value, int>::type = 0> erased & operator =(U const & newValue) { *value = newValue; return *this; } std::unique_ptr<T> clone() const { T * temp = do_clone(); return std::unique_ptr<T>(temp); } T & operator *() { return *value; } T * operator ->() { return &*value; } T const & operator *() const { return *value; } T const * operator ->() const { return &*value; } private: template <typename U> static constexpr intptr_t compute_downcast_offset() { return reinterpret_cast<intptr_t>(static_cast<U*>(reinterpret_cast<T*>(static_cast<void*>(nullptr)))); } template <typename U> static void * op(void const * value, bool doDelete) { if (doDelete) { delete reinterpret_cast<U*>(const_cast<void *>(value)); return nullptr; } else { return reinterpret_cast<void *>(new U(*reinterpret_cast<U const *>(value))); } } void * downcast(void * p) const { return reinterpret_cast<int8_t *>(p) + downcast_offset; } void * upcast(void * p) const { return reinterpret_cast<int8_t *>(p) - downcast_offset; } T * do_clone() const { return reinterpret_cast<T*>(upcast(op_ptr(downcast(value), false))); } void do_delete() { op_ptr(downcast(value), true); } template <typename U> friend class erased; void * (*op_ptr)(void const *, bool); size_t downcast_offset; T * value; }; #endif //ERASED_HPP <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <math.h> #include <stdio.h> // FIXME(brettw) eraseme. #include <algorithm> #include "ppapi/c/pp_event.h" #include "ppapi/c/pp_rect.h" #include "ppapi/cpp/device_context_2d.h" #include "ppapi/cpp/image_data.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/scriptable_object.h" #include "ppapi/cpp/var.h" void FlushCallback(PP_Resource context, void* data); void FillRect(pp::ImageData* image, int left, int top, int width, int height, uint32_t color) { for (int y = std::max(0, top); y < std::min(image->height() - 1, top + height); y++) { for (int x = std::max(0, left); x < std::min(image->width() - 1, left + width); x++) *image->GetAddr32(x, y) = color; } } class MyScriptableObject : public pp::ScriptableObject { public: virtual bool HasMethod(const pp::Var& method, pp::Var* exception) { return method.AsString() == "toString"; } virtual bool HasProperty(const pp::Var& name, pp::Var* exception) { if (name.is_string() && name.AsString() == "blah") return true; return false; } virtual pp::Var GetProperty(const pp::Var& name, pp::Var* exception) { if (name.is_string() && name.AsString() == "blah") return new MyScriptableObject(); return pp::Var(); } virtual void GetAllPropertyNames(std::vector<pp::Var>* names, pp::Var* exception) { names->push_back("blah"); } virtual pp::Var Call(const pp::Var& method, const std::vector<pp::Var>& args, pp::Var* exception) { if (method.AsString() == "toString") return pp::Var("hello world"); return pp::Var(); } }; class MyInstance : public pp::Instance { public: MyInstance(PP_Instance instance) : pp::Instance(instance), width_(0), height_(0), animation_counter_(0) {} virtual ~MyInstance() {} virtual bool Init(size_t argc, const char* argn[], const char* argv[]) { return true; } virtual bool HandleEvent(const PP_Event& event) { switch (event.type) { case PP_Event_Type_MouseDown: printf("Mouse down\n"); SayHello(); return true; case PP_Event_Type_MouseMove: printf("Mouse move\n"); return true; case PP_Event_Type_KeyDown: printf("Key down\n"); return true; default: return false; } } virtual pp::Var GetInstanceObject() { return new MyScriptableObject(); } void Paint() { pp::ImageData image(PP_IMAGEDATAFORMAT_BGRA_PREMUL, width_, height_, false); if (image.is_null()) { printf("Couldn't allocate the image data\n"); return; } // Fill with semitransparent gradient. for (int y = 0; y < image.height(); y++) { char* row = &static_cast<char*>(image.data())[y * image.stride()]; for (int x = 0; x < image.width(); x++) { row[x * 4 + 0] = y; row[x * 4 + 1] = y; row[x * 4 + 2] = 0; row[x * 4 + 3] = y; } } const int kStepsPerCircle = 800; float radians = static_cast<float>(animation_counter_) / kStepsPerCircle * 2 * M_PI; float radius = std::min(width_, height_) / 2 - 3; int x = static_cast<int>(cos(radians) * radius) + radius + 2; int y = static_cast<int>(sin(radians) * radius) + radius + 2; FillRect(&image, x - 3, y - 3, 7, 7, 0x80000000); device_context_.ReplaceContents(&image); device_context_.Flush(&FlushCallback, this); } virtual void ViewChanged(const PP_Rect& position, const PP_Rect& clip) { printf("ViewChanged %d,%d,%d,%d\n", position.point.x, position.point.y, position.size.width, position.size.height); if (position.size.width == width_ || position.size.height == height_) return; // We don't care about the position, only the size. width_ = position.size.width; height_ = position.size.height; device_context_ = pp::DeviceContext2D(width_, height_, false); if (!BindGraphicsDeviceContext(device_context_)) { printf("Couldn't bind the device context\n"); return; } Paint(); } void OnFlush() { animation_counter_++; Paint(); } private: void Log(const pp::Var& var) { pp::Var doc = GetWindowObject().GetProperty("document"); if (console_.is_void()) { pp::Var body = doc.GetProperty("body"); console_ = doc.Call("createElement", "pre"); console_.GetProperty("style").SetProperty("backgroundColor", "lightgray"); body.Call("appendChild", console_); } console_.Call("appendChild", doc.Call("createTextNode", var)); console_.Call("appendChild", doc.Call("createTextNode", "\n")); } void SayHello() { pp::Var window = GetWindowObject(); pp::Var doc = window.GetProperty("document"); pp::Var body = doc.GetProperty("body"); pp::Var obj(new MyScriptableObject()); // Our object should have its toString method called. Log("Testing MyScriptableObject::toString():"); Log(obj); // body.appendChild(body) should throw an exception Log("\nCalling body.appendChild(body):"); pp::Var exception; body.Call("appendChild", body, &exception); Log(exception); Log("\nEnumeration of window properties:"); std::vector<pp::Var> props; window.GetAllPropertyNames(&props); for (size_t i = 0; i < props.size(); ++i) Log(props[i]); } pp::Var console_; pp::DeviceContext2D device_context_; int width_; int height_; // Incremented for each flush we get. int animation_counter_; }; void FlushCallback(PP_Resource context, void* data) { static_cast<MyInstance*>(data)->OnFlush(); } class MyModule : public pp::Module { public: MyModule() : pp::Module() {} virtual ~MyModule() {} virtual pp::Instance* CreateInstance(PP_Instance instance) { return new MyInstance(instance); } }; namespace pp { Module* CreateModule() { return new MyModule(); } } // namespace pp <commit_msg>Fix some warnings in the example plugin.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <math.h> #include <stdio.h> // FIXME(brettw) eraseme. #include <algorithm> #include "ppapi/c/pp_event.h" #include "ppapi/c/pp_rect.h" #include "ppapi/cpp/device_context_2d.h" #include "ppapi/cpp/image_data.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/scriptable_object.h" #include "ppapi/cpp/var.h" void FlushCallback(PP_Resource context, void* data); void FillRect(pp::ImageData* image, int left, int top, int width, int height, uint32_t color) { for (int y = std::max(0, top); y < std::min(image->height() - 1, top + height); y++) { for (int x = std::max(0, left); x < std::min(image->width() - 1, left + width); x++) *image->GetAddr32(x, y) = color; } } class MyScriptableObject : public pp::ScriptableObject { public: virtual bool HasMethod(const pp::Var& method, pp::Var* exception) { return method.AsString() == "toString"; } virtual bool HasProperty(const pp::Var& name, pp::Var* exception) { if (name.is_string() && name.AsString() == "blah") return true; return false; } virtual pp::Var GetProperty(const pp::Var& name, pp::Var* exception) { if (name.is_string() && name.AsString() == "blah") return new MyScriptableObject(); return pp::Var(); } virtual void GetAllPropertyNames(std::vector<pp::Var>* names, pp::Var* exception) { names->push_back("blah"); } virtual pp::Var Call(const pp::Var& method, const std::vector<pp::Var>& args, pp::Var* exception) { if (method.AsString() == "toString") return pp::Var("hello world"); return pp::Var(); } }; class MyInstance : public pp::Instance { public: MyInstance(PP_Instance instance) : pp::Instance(instance), width_(0), height_(0), animation_counter_(0) {} virtual ~MyInstance() {} virtual bool Init(size_t argc, const char* argn[], const char* argv[]) { return true; } virtual bool HandleEvent(const PP_Event& event) { switch (event.type) { case PP_Event_Type_MouseDown: printf("Mouse down\n"); SayHello(); return true; case PP_Event_Type_MouseMove: printf("Mouse move\n"); return true; case PP_Event_Type_KeyDown: printf("Key down\n"); return true; default: return false; } } virtual pp::Var GetInstanceObject() { return new MyScriptableObject(); } void Paint() { pp::ImageData image(PP_IMAGEDATAFORMAT_BGRA_PREMUL, width_, height_, false); if (image.is_null()) { printf("Couldn't allocate the image data\n"); return; } // Fill with semitransparent gradient. for (int y = 0; y < image.height(); y++) { char* row = &static_cast<char*>(image.data())[y * image.stride()]; for (int x = 0; x < image.width(); x++) { row[x * 4 + 0] = y; row[x * 4 + 1] = y; row[x * 4 + 2] = 0; row[x * 4 + 3] = y; } } const int kStepsPerCircle = 800; float radians = static_cast<float>(animation_counter_) / kStepsPerCircle * 2 * 3.14159265358979; float radius = static_cast<float>(std::min(width_, height_)) / 2.0f - 3.0f; int x = static_cast<int>(cos(radians) * radius + radius + 2); int y = static_cast<int>(sin(radians) * radius + radius + 2); FillRect(&image, x - 3, y - 3, 7, 7, 0x80000000); device_context_.ReplaceContents(&image); device_context_.Flush(&FlushCallback, this); } virtual void ViewChanged(const PP_Rect& position, const PP_Rect& clip) { printf("ViewChanged %d,%d,%d,%d\n", position.point.x, position.point.y, position.size.width, position.size.height); if (position.size.width == width_ || position.size.height == height_) return; // We don't care about the position, only the size. width_ = position.size.width; height_ = position.size.height; device_context_ = pp::DeviceContext2D(width_, height_, false); if (!BindGraphicsDeviceContext(device_context_)) { printf("Couldn't bind the device context\n"); return; } Paint(); } void OnFlush() { animation_counter_++; Paint(); } private: void Log(const pp::Var& var) { pp::Var doc = GetWindowObject().GetProperty("document"); if (console_.is_void()) { pp::Var body = doc.GetProperty("body"); console_ = doc.Call("createElement", "pre"); console_.GetProperty("style").SetProperty("backgroundColor", "lightgray"); body.Call("appendChild", console_); } console_.Call("appendChild", doc.Call("createTextNode", var)); console_.Call("appendChild", doc.Call("createTextNode", "\n")); } void SayHello() { pp::Var window = GetWindowObject(); pp::Var doc = window.GetProperty("document"); pp::Var body = doc.GetProperty("body"); pp::Var obj(new MyScriptableObject()); // Our object should have its toString method called. Log("Testing MyScriptableObject::toString():"); Log(obj); // body.appendChild(body) should throw an exception Log("\nCalling body.appendChild(body):"); pp::Var exception; body.Call("appendChild", body, &exception); Log(exception); Log("\nEnumeration of window properties:"); std::vector<pp::Var> props; window.GetAllPropertyNames(&props); for (size_t i = 0; i < props.size(); ++i) Log(props[i]); } pp::Var console_; pp::DeviceContext2D device_context_; int width_; int height_; // Incremented for each flush we get. int animation_counter_; }; void FlushCallback(PP_Resource context, void* data) { static_cast<MyInstance*>(data)->OnFlush(); } class MyModule : public pp::Module { public: MyModule() : pp::Module() {} virtual ~MyModule() {} virtual pp::Instance* CreateInstance(PP_Instance instance) { return new MyInstance(instance); } }; namespace pp { Module* CreateModule() { return new MyModule(); } } // namespace pp <|endoftext|>
<commit_before><commit_msg>ch-49: add the 1-st example from chapter 49<commit_after><|endoftext|>
<commit_before>//#include "utilities.h" #include "new_mapper.hpp" Realm::Logger log_solver_mapper("solver_mapper"); SolverMapper::SolverMapper(Machine machine, Runtime *rt, Processor local, std::vector<Processor>* _procs_list, std::vector<Memory>* _sysmems_list, std::map<Memory, std::vector<Processor> >* _sysmem_local_procs, std::map<Processor, Memory>* _proc_sysmems, std::map<Processor, Memory>* _proc_regmems) : DefaultMapper(rt->get_mapper_runtime(), machine, local), procs_list(*_procs_list), sysmems_list(*_sysmems_list), sysmem_local_procs(*_sysmem_local_procs), proc_sysmems(*_proc_sysmems), proc_regmems(*_proc_regmems) {} void SolverMapper::slice_task(const MapperContext ctx, const Task& task, const SliceTaskInput& input, SliceTaskOutput& output) { default_slice_task(task, local_cpus, remote_cpus, input, output, cpu_slices_cache); } void SolverMapper::default_slice_task(const Task &task, const std::vector<Processor> &local, const std::vector<Processor> &remote, const SliceTaskInput& input, SliceTaskOutput &output, std::map<Domain,std::vector<TaskSlice> > &cached_slices) const { // Before we do anything else, see if it is in the cache std::map<Domain,std::vector<TaskSlice> >::const_iterator finder = cached_slices.find(input.domain); if (finder != cached_slices.end()) { output.slices = finder->second; return; } assert(input.domain.get_dim() == 1); Rect<1> point_rect = input.domain.get_rect<1>(); Point<1> num_blocks(local.size()); default_decompose_points<1>(point_rect, local, num_blocks, false/*recurse*/, stealing_enabled, output.slices); } <commit_msg>small tweak to namespace inclusion for support for dependent partitioning<commit_after>//#include "utilities.h" #include "new_mapper.hpp" using namespace LegionRuntime::Arrays; Realm::Logger log_solver_mapper("solver_mapper"); SolverMapper::SolverMapper(Machine machine, Runtime *rt, Processor local, std::vector<Processor>* _procs_list, std::vector<Memory>* _sysmems_list, std::map<Memory, std::vector<Processor> >* _sysmem_local_procs, std::map<Processor, Memory>* _proc_sysmems, std::map<Processor, Memory>* _proc_regmems) : DefaultMapper(rt->get_mapper_runtime(), machine, local), procs_list(*_procs_list), sysmems_list(*_sysmems_list), sysmem_local_procs(*_sysmem_local_procs), proc_sysmems(*_proc_sysmems), proc_regmems(*_proc_regmems) {} void SolverMapper::slice_task(const MapperContext ctx, const Task& task, const SliceTaskInput& input, SliceTaskOutput& output) { default_slice_task(task, local_cpus, remote_cpus, input, output, cpu_slices_cache); } void SolverMapper::default_slice_task(const Task &task, const std::vector<Processor> &local, const std::vector<Processor> &remote, const SliceTaskInput& input, SliceTaskOutput &output, std::map<Domain,std::vector<TaskSlice> > &cached_slices) const { // Before we do anything else, see if it is in the cache std::map<Domain,std::vector<TaskSlice> >::const_iterator finder = cached_slices.find(input.domain); if (finder != cached_slices.end()) { output.slices = finder->second; return; } assert(input.domain.get_dim() == 1); Rect<1> point_rect = input.domain.get_rect<1>(); Point<1> num_blocks(local.size()); default_decompose_points<1>(point_rect, local, num_blocks, false/*recurse*/, stealing_enabled, output.slices); } <|endoftext|>
<commit_before>// Copyright (c) 2015 The Brick Authors. #include "brick/indicator/unity_launcher.h" #include "brick/brick_app.h" #include "include/base/cef_logging.h" void UnityLauncher::Init() { handler_ = unity_launcher_entry_get_for_desktop_id(APP_COMMON_NAME ".desktop"); RegisterEventListeners(); } void UnityLauncher::onEvent(const DownloadProgressEvent& event) { if (event.getTotal() <= 0) return; if (event.getPercent() >= 100 && downloads_.count(event.getId())) { downloads_.erase(event.getId()); } downloads_[event.getId()] = event.getPercent(); Update(); } void UnityLauncher::onEvent(const DownloadCompleteEvent& event) { if (downloads_.count(event.getId())) { downloads_.erase(event.getId()); } Update(); } void UnityLauncher::Update() { int badges = badges_ + static_cast<int>(downloads_.size()); if (badges > 0) { unity_launcher_entry_set_count(handler_, badges); unity_launcher_entry_set_count_visible(handler_, true); if (!downloads_.empty()) { unity_launcher_entry_set_progress_visible(handler_, true); double progress = 0; for (const auto &download: downloads_) { progress += download.second; } unity_launcher_entry_set_progress(handler_, progress / downloads_.size() / 100); } } else { unity_launcher_entry_set_count(handler_, 0); unity_launcher_entry_set_count_visible(handler_, false); unity_launcher_entry_set_progress(handler_, 0); unity_launcher_entry_set_progress_visible(handler_, false); } } void UnityLauncher::SetBadge(int badge) { badges_ = badge; Update(); } void UnityLauncher::RegisterEventListeners() { EventBus::AddHandler<DownloadProgressEvent>(*this); EventBus::AddHandler<DownloadCompleteEvent>(*this); } <commit_msg>Fixed UnityLauncher event-handlers<commit_after>// Copyright (c) 2015 The Brick Authors. #include "brick/indicator/unity_launcher.h" #include "brick/brick_app.h" #include "include/base/cef_logging.h" void UnityLauncher::Init() { handler_ = unity_launcher_entry_get_for_desktop_id(APP_COMMON_NAME ".desktop"); RegisterEventListeners(); } void UnityLauncher::OnEvent(const DownloadProgressEvent& event) { if (event.getTotal() <= 0) return; if (event.getPercent() >= 100 && downloads_.count(event.getId())) { downloads_.erase(event.getId()); } downloads_[event.getId()] = event.getPercent(); Update(); } void UnityLauncher::OnEvent(const DownloadCompleteEvent& event) { if (downloads_.count(event.getId())) { downloads_.erase(event.getId()); } Update(); } void UnityLauncher::Update() { int badges = badges_ + static_cast<int>(downloads_.size()); if (badges > 0) { unity_launcher_entry_set_count(handler_, badges); unity_launcher_entry_set_count_visible(handler_, true); if (!downloads_.empty()) { unity_launcher_entry_set_progress_visible(handler_, true); double progress = 0; for (const auto &download: downloads_) { progress += download.second; } unity_launcher_entry_set_progress(handler_, progress / downloads_.size() / 100); } } else { unity_launcher_entry_set_count(handler_, 0); unity_launcher_entry_set_count_visible(handler_, false); unity_launcher_entry_set_progress(handler_, 0); unity_launcher_entry_set_progress_visible(handler_, false); } } void UnityLauncher::SetBadge(int badge) { badges_ = badge; Update(); } void UnityLauncher::RegisterEventListeners() { EventBus::AddHandler<DownloadProgressEvent>(*this); EventBus::AddHandler<DownloadCompleteEvent>(*this); } <|endoftext|>
<commit_before>// Copyright (c) 2019 - 2021 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 - 2022 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/runtime/posh_runtime.hpp" #include "iceoryx_hoofs/cxx/helplets.hpp" #include "iceoryx_posh/internal/log/posh_logging.hpp" #include "iceoryx_posh/internal/runtime/posh_runtime_impl.hpp" #include <cstdint> #include <new> #include <type_traits> namespace iox { namespace runtime { // A refcount for use in getLifetimeParticipant(). static int refcount; // Track whether the refcount lifetime mechanism is used by this particular // implementation of the abstract PoshRuntime class. static bool manual_lifetime_management = false; PoshRuntime::factory_t& PoshRuntime::getRuntimeFactory() noexcept { static factory_t runtimeFactory = PoshRuntimeImpl::defaultRuntimeFactory; return runtimeFactory; } void PoshRuntime::setRuntimeFactory(const factory_t& factory) noexcept { if (factory) { PoshRuntime::getRuntimeFactory() = factory; } else { LogFatal() << "Cannot set runtime factory. Passed factory must not be empty!"; errorHandler(PoshError::POSH__RUNTIME_FACTORY_IS_NOT_SET); } } PoshRuntime& PoshRuntime::defaultRuntimeFactory(cxx::optional<const RuntimeName_t*> name) noexcept { static typename std::aligned_storage<sizeof(PoshRuntimeImpl), alignof(PoshRuntimeImpl)>::type buf; static cxx::ScopeGuard ltp = [](auto name){ new(&buf) PoshRuntimeImpl(name); manual_lifetime_management = true; return getLifetimeParticipant(); }(name); return reinterpret_cast<PoshRuntimeImpl&>(buf); } // singleton access PoshRuntime& PoshRuntime::getInstance() noexcept { return getInstance(cxx::nullopt); } PoshRuntime& PoshRuntime::initRuntime(const RuntimeName_t& name) noexcept { return getInstance(cxx::make_optional<const RuntimeName_t*>(&name)); } PoshRuntime& PoshRuntime::getInstance(cxx::optional<const RuntimeName_t*> name) noexcept { return getRuntimeFactory()(name); } cxx::ScopeGuard PoshRuntime::getLifetimeParticipant() noexcept { return cxx::ScopeGuard( [](){ ++refcount; }, [](){ if (0 == --refcount && manual_lifetime_management) { getInstance().~PoshRuntime(); } } ); } PoshRuntime::PoshRuntime(cxx::optional<const RuntimeName_t*> name) noexcept : m_appName(verifyInstanceName(name)) { if (cxx::isCompiledOn32BitSystem()) { LogWarn() << "Running applications on 32-bit architectures is not supported! Use at your own risk!"; } } const RuntimeName_t& PoshRuntime::verifyInstanceName(cxx::optional<const RuntimeName_t*> name) noexcept { if (!name.has_value()) { LogFatal() << "Cannot initialize runtime. Application name has not been specified!"; errorHandler(PoshError::POSH__RUNTIME_NO_NAME_PROVIDED, ErrorLevel::FATAL); } else if (!cxx::isValidFileName(**name)) { LogFatal() << "Cannot initialize runtime. The application name \"" << **name << "\" is not a valid platform-independent file name."; errorHandler(PoshError::POSH__RUNTIME_NAME_NOT_VALID_FILE_NAME); } return *name.value(); } RuntimeName_t PoshRuntime::getInstanceName() const noexcept { return m_appName; } void PoshRuntime::shutdown() noexcept { m_shutdownRequested.store(true, std::memory_order_relaxed); } } // namespace runtime } // namespace iox <commit_msg>iox-#1725 Make variables atomic and capture buf<commit_after>// Copyright (c) 2019 - 2021 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 - 2022 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/runtime/posh_runtime.hpp" #include "iceoryx_hoofs/cxx/helplets.hpp" #include "iceoryx_posh/internal/log/posh_logging.hpp" #include "iceoryx_posh/internal/runtime/posh_runtime_impl.hpp" #include <atomic> #include <cstdint> #include <new> #include <type_traits> namespace iox { namespace runtime { // A refcount for use in getLifetimeParticipant(). static std::atomic<uint64_t> s_refcount{0U}; // Track whether the refcount lifetime mechanism is used by this particular // implementation of the abstract PoshRuntime class. static std::atomic<bool> manual_lifetime_management{false}; PoshRuntime::factory_t& PoshRuntime::getRuntimeFactory() noexcept { static factory_t runtimeFactory = PoshRuntimeImpl::defaultRuntimeFactory; return runtimeFactory; } void PoshRuntime::setRuntimeFactory(const factory_t& factory) noexcept { if (factory) { PoshRuntime::getRuntimeFactory() = factory; } else { LogFatal() << "Cannot set runtime factory. Passed factory must not be empty!"; errorHandler(PoshError::POSH__RUNTIME_FACTORY_IS_NOT_SET); } } PoshRuntime& PoshRuntime::defaultRuntimeFactory(cxx::optional<const RuntimeName_t*> name) noexcept { static typename std::aligned_storage<sizeof(PoshRuntimeImpl), alignof(PoshRuntimeImpl)>::type buf; static cxx::ScopeGuard ltp = [&buf](auto name) { new (&buf) PoshRuntimeImpl(name); manual_lifetime_management = true; return getLifetimeParticipant(); }(name); return reinterpret_cast<PoshRuntimeImpl&>(buf); } // singleton access PoshRuntime& PoshRuntime::getInstance() noexcept { return getInstance(cxx::nullopt); } PoshRuntime& PoshRuntime::initRuntime(const RuntimeName_t& name) noexcept { return getInstance(cxx::make_optional<const RuntimeName_t*>(&name)); } PoshRuntime& PoshRuntime::getInstance(cxx::optional<const RuntimeName_t*> name) noexcept { return getRuntimeFactory()(name); } cxx::ScopeGuard PoshRuntime::getLifetimeParticipant() noexcept { return cxx::ScopeGuard([]() { ++s_refcount; }, []() { if (0 == --s_refcount && manual_lifetime_management) { getInstance().~PoshRuntime(); } }); } PoshRuntime::PoshRuntime(cxx::optional<const RuntimeName_t*> name) noexcept : m_appName(verifyInstanceName(name)) { if (cxx::isCompiledOn32BitSystem()) { LogWarn() << "Running applications on 32-bit architectures is not supported! Use at your own risk!"; } } const RuntimeName_t& PoshRuntime::verifyInstanceName(cxx::optional<const RuntimeName_t*> name) noexcept { if (!name.has_value()) { LogFatal() << "Cannot initialize runtime. Application name has not been specified!"; errorHandler(PoshError::POSH__RUNTIME_NO_NAME_PROVIDED, ErrorLevel::FATAL); } else if (!cxx::isValidFileName(**name)) { LogFatal() << "Cannot initialize runtime. The application name \"" << **name << "\" is not a valid platform-independent file name."; errorHandler(PoshError::POSH__RUNTIME_NAME_NOT_VALID_FILE_NAME); } return *name.value(); } RuntimeName_t PoshRuntime::getInstanceName() const noexcept { return m_appName; } void PoshRuntime::shutdown() noexcept { m_shutdownRequested.store(true, std::memory_order_relaxed); } } // namespace runtime } // namespace iox <|endoftext|>
<commit_before>/* Copyright 2017 Stanford University, NVIDIA Corporation * * 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 "inst_impl.h" #include "event_impl.h" #include "mem_impl.h" #include "logging.h" #include "runtime_impl.h" namespace Realm { Logger log_inst("inst"); //////////////////////////////////////////////////////////////////////// // // class DeferredInstDestroy // class DeferredInstDestroy : public EventWaiter { public: DeferredInstDestroy(RegionInstanceImpl *i) : impl(i) { } virtual ~DeferredInstDestroy(void) { } public: virtual bool event_triggered(Event e, bool poisoned) { // if input event is poisoned, do not attempt to destroy the lock // we don't have an output event here, so this may result in a leak if nobody is // paying attention if(poisoned) { log_poison.info() << "poisoned deferred instance destruction skipped - POSSIBLE LEAK - inst=" << impl->me; } else { log_inst.info("instance destroyed: space=" IDFMT " id=" IDFMT "", impl->metadata.is.id, impl->me.id); get_runtime()->get_memory_impl(impl->memory)->destroy_instance(impl->me, true); } return true; } virtual void print(std::ostream& os) const { os << "deferred instance destruction"; } virtual Event get_finish_event(void) const { return Event::NO_EVENT; } protected: RegionInstanceImpl *impl; }; //////////////////////////////////////////////////////////////////////// // // class RegionInstance // AddressSpace RegionInstance::address_space(void) const { return ID(id).instance.owner_node; } Memory RegionInstance::get_location(void) const { RegionInstanceImpl *i_impl = get_runtime()->get_instance_impl(*this); return i_impl->memory; } void RegionInstance::destroy(Event wait_on /*= Event::NO_EVENT*/) const { DetailedTimer::ScopedPush sp(TIME_LOW_LEVEL); RegionInstanceImpl *i_impl = get_runtime()->get_instance_impl(*this); if (!wait_on.has_triggered()) { EventImpl::add_waiter(wait_on, new DeferredInstDestroy(i_impl)); return; } log_inst.info("instance destroyed: space=" IDFMT " id=" IDFMT "", i_impl->metadata.is.id, this->id); get_runtime()->get_memory_impl(i_impl->memory)->destroy_instance(*this, true); } void RegionInstance::destroy(const std::vector<DestroyedField>& destroyed_fields, Event wait_on /*= Event::NO_EVENT*/) const { // TODO: actually call destructor assert(destroyed_fields.empty()); destroy(wait_on); } /*static*/ const RegionInstance RegionInstance::NO_INST = { 0 }; // a generic accessor just holds a pointer to the impl and passes all // requests through LegionRuntime::Accessor::RegionAccessor<LegionRuntime::Accessor::AccessorType::Generic> RegionInstance::get_accessor(void) const { // request metadata (if needed), but don't block on it yet RegionInstanceImpl *i_impl = get_runtime()->get_instance_impl(*this); Event e = i_impl->metadata.request_data(ID(id).instance.owner_node, id); if(!e.has_triggered()) log_inst.info("requested metadata in accessor creation: " IDFMT, id); return LegionRuntime::Accessor::RegionAccessor<LegionRuntime::Accessor::AccessorType::Generic>(LegionRuntime::Accessor::AccessorType::Generic::Untyped((void *)i_impl)); } void RegionInstance::report_instance_fault(int reason, const void *reason_data, size_t reason_size) const { assert(0); } //////////////////////////////////////////////////////////////////////// // // class RegionInstanceImpl // RegionInstanceImpl::RegionInstanceImpl(RegionInstance _me, IndexSpace _is, Memory _memory, off_t _offset, size_t _size, ReductionOpID _redopid, const DomainLinearization& _linear, size_t _block_size, size_t _elmt_size, const std::vector<size_t>& _field_sizes, const ProfilingRequestSet &reqs, off_t _count_offset /*= 0*/, off_t _red_list_size /*= 0*/, RegionInstance _parent_inst /*= NO_INST*/) : me(_me), memory(_memory) { metadata.linearization = _linear; metadata.block_size = _block_size; metadata.elmt_size = _elmt_size; metadata.field_sizes = _field_sizes; metadata.is = _is; metadata.alloc_offset = _offset; //metadata.access_offset = _offset + _adjust; metadata.size = _size; //StaticAccess<IndexSpaceImpl> rdata(_is.impl()); //locked_data.first_elmt = rdata->first_elmt; //locked_data.last_elmt = rdata->last_elmt; metadata.redopid = _redopid; metadata.count_offset = _count_offset; metadata.red_list_size = _red_list_size; metadata.parent_inst = _parent_inst; metadata.mark_valid(); lock.init(ID(me).convert<Reservation>(), ID(me).instance.owner_node); lock.in_use = true; if (!reqs.empty()) { requests = reqs; measurements.import_requests(requests); if (measurements.wants_measurement< ProfilingMeasurements::InstanceTimeline>()) { timeline.record_create_time(); } } } // when we auto-create a remote instance, we don't know region/offset RegionInstanceImpl::RegionInstanceImpl(RegionInstance _me, Memory _memory) : me(_me), memory(_memory) { lock.init(ID(me).convert<Reservation>(), ID(me).instance.owner_node); lock.in_use = true; } RegionInstanceImpl::~RegionInstanceImpl(void) {} // helper function to figure out which field we're in void find_field_start(const std::vector<size_t>& field_sizes, off_t byte_offset, size_t size, off_t& field_start, int& field_size) { off_t start = 0; for(std::vector<size_t>::const_iterator it = field_sizes.begin(); it != field_sizes.end(); it++) { assert((*it) > 0); if(byte_offset < (off_t)(*it)) { if ((off_t)(byte_offset + size) > (off_t)(*it)) { log_inst.error(REQUESTED_FIELD_NOTMATCH.id(), "Requested field does not match the expected field size"); assert(false); } field_start = start; field_size = (*it); return; } start += (*it); byte_offset -= (*it); } assert(0); } void RegionInstanceImpl::record_instance_usage(void) { // can't do this in the constructor because our ID isn't right yet... if(measurements.wants_measurement<ProfilingMeasurements::InstanceMemoryUsage>()) { ProfilingMeasurements::InstanceMemoryUsage usage; usage.instance = me; usage.memory = memory; usage.bytes = metadata.size; measurements.add_measurement(usage); } } bool RegionInstanceImpl::get_strided_parameters(void *&base, size_t &stride, off_t field_offset) { MemoryImpl *mem = get_runtime()->get_memory_impl(memory); // must have valid data by now - block if we have to metadata.await_data(); off_t offset = metadata.alloc_offset; size_t elmt_stride; if (metadata.block_size == 1) { offset += field_offset; elmt_stride = metadata.elmt_size; } else { off_t field_start=0; int field_size=0; find_field_start(metadata.field_sizes, field_offset, 1, field_start, field_size); offset += (field_start * metadata.block_size) + (field_offset - field_start); elmt_stride = field_size; } base = mem->get_direct_ptr(offset, 0); if (!base) return false; // if the caller wants a particular stride and we differ (and have more // than one element), fail if(stride != 0) { if((stride != elmt_stride) && (metadata.size > metadata.elmt_size)) return false; } else { stride = elmt_stride; } // if there's a per-element offset, apply it after we've agreed with the caller on // what we're pretending the stride is const DomainLinearization& dl = metadata.linearization; if(dl.get_dim() > 0) { // make sure this instance uses a 1-D linearization assert(dl.get_dim() == 1); LegionRuntime::Arrays::Mapping<1, 1> *mapping = dl.get_mapping<1>(); LegionRuntime::Arrays::Rect<1> preimage = mapping->preimage((coord_t)0); assert(preimage.lo == preimage.hi); // double-check that whole range maps densely preimage.hi.x[0] += 1; // not perfect, but at least detects non-unit-stride case assert(mapping->image_is_dense(preimage)); coord_t inst_first_elmt = preimage.lo[0]; //printf("adjusting base by %d * %zd\n", inst_first_elmt, stride); base = ((char *)base) - inst_first_elmt * stride; } return true; } void RegionInstanceImpl::finalize_instance(void) { if (!requests.empty()) { if (measurements.wants_measurement< ProfilingMeasurements::InstanceTimeline>()) { // set the instance ID correctly now - it wasn't available at construction time timeline.instance = me; timeline.record_delete_time(); measurements.add_measurement(timeline); } measurements.send_responses(requests); requests.clear(); } } void *RegionInstanceImpl::Metadata::serialize(size_t& out_size) const { // figure out how much space we need out_size = (sizeof(IndexSpace) + sizeof(off_t) + sizeof(size_t) + sizeof(ReductionOpID) + sizeof(off_t) + sizeof(off_t) + sizeof(size_t) + sizeof(size_t) + sizeof(size_t) + (field_sizes.size() * sizeof(size_t)) + sizeof(RegionInstance) + (MAX_LINEARIZATION_LEN * sizeof(int))); void *data = malloc(out_size); char *pos = (char *)data; #define S(val) do { memcpy(pos, &(val), sizeof(val)); pos += sizeof(val); } while(0) S(is); S(alloc_offset); S(size); S(redopid); S(count_offset); S(red_list_size); S(block_size); S(elmt_size); size_t l = field_sizes.size(); S(l); for(size_t i = 0; i < l; i++) S(field_sizes[i]); S(parent_inst); linearization.serialize((int *)pos); #undef S return data; } void RegionInstanceImpl::Metadata::deserialize(const void *in_data, size_t in_size) { const char *pos = (const char *)in_data; #define S(val) do { memcpy(&(val), pos, sizeof(val)); pos += sizeof(val); } while(0) S(is); S(alloc_offset); S(size); S(redopid); S(count_offset); S(red_list_size); S(block_size); S(elmt_size); size_t l; S(l); field_sizes.resize(l); for(size_t i = 0; i < l; i++) S(field_sizes[i]); S(parent_inst); linearization.deserialize((const int *)pos); #undef S } #ifdef POINTER_CHECKS void RegionInstanceImpl::verify_access(unsigned ptr) { StaticAccess<RegionInstanceImpl> data(this); const ElementMask &mask = data->is.get_valid_mask(); if (!mask.is_set(ptr)) { fprintf(stderr,"ERROR: Accessing invalid pointer %d in logical region " IDFMT "\n",ptr,data->is.id); assert(false); } } #endif static inline off_t calc_mem_loc(off_t alloc_offset, off_t field_start, int field_size, int elmt_size, int block_size, int index) { return (alloc_offset + // start address ((index / block_size) * block_size * elmt_size) + // full blocks (field_start * block_size) + // skip other fields ((index % block_size) * field_size)); // some some of our fields within our block } void RegionInstanceImpl::get_bytes(int index, off_t byte_offset, void *dst, size_t size) { // must have valid data by now - block if we have to metadata.await_data(); off_t o; if(metadata.block_size == 1) { // no blocking - don't need to know about field boundaries o = metadata.alloc_offset + (index * metadata.elmt_size) + byte_offset; } else { off_t field_start=0; int field_size=0; find_field_start(metadata.field_sizes, byte_offset, size, field_start, field_size); o = calc_mem_loc(metadata.alloc_offset, field_start, field_size, metadata.elmt_size, metadata.block_size, index); } MemoryImpl *m = get_runtime()->get_memory_impl(memory); m->get_bytes(o, dst, size); } void RegionInstanceImpl::put_bytes(int index, off_t byte_offset, const void *src, size_t size) { // must have valid data by now - block if we have to metadata.await_data(); off_t o; if(metadata.block_size == 1) { // no blocking - don't need to know about field boundaries o = metadata.alloc_offset + (index * metadata.elmt_size) + byte_offset; } else { off_t field_start=0; int field_size=0; find_field_start(metadata.field_sizes, byte_offset, size, field_start, field_size); o = calc_mem_loc(metadata.alloc_offset, field_start, field_size, metadata.elmt_size, metadata.block_size, index); } MemoryImpl *m = get_runtime()->get_memory_impl(memory); m->put_bytes(o, src, size); } }; // namespace Realm <commit_msg>fixing a small merge error<commit_after>/* Copyright 2017 Stanford University, NVIDIA Corporation * * 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 "inst_impl.h" #include "event_impl.h" #include "mem_impl.h" #include "logging.h" #include "runtime_impl.h" namespace Realm { Logger log_inst("inst"); //////////////////////////////////////////////////////////////////////// // // class DeferredInstDestroy // class DeferredInstDestroy : public EventWaiter { public: DeferredInstDestroy(RegionInstanceImpl *i) : impl(i) { } virtual ~DeferredInstDestroy(void) { } public: virtual bool event_triggered(Event e, bool poisoned) { // if input event is poisoned, do not attempt to destroy the lock // we don't have an output event here, so this may result in a leak if nobody is // paying attention if(poisoned) { log_poison.info() << "poisoned deferred instance destruction skipped - POSSIBLE LEAK - inst=" << impl->me; } else { log_inst.info("instance destroyed: space=" IDFMT " id=" IDFMT "", impl->metadata.is.id, impl->me.id); get_runtime()->get_memory_impl(impl->memory)->destroy_instance(impl->me, true); } return true; } virtual void print(std::ostream& os) const { os << "deferred instance destruction"; } virtual Event get_finish_event(void) const { return Event::NO_EVENT; } protected: RegionInstanceImpl *impl; }; //////////////////////////////////////////////////////////////////////// // // class RegionInstance // AddressSpace RegionInstance::address_space(void) const { return ID(id).instance.owner_node; } Memory RegionInstance::get_location(void) const { RegionInstanceImpl *i_impl = get_runtime()->get_instance_impl(*this); return i_impl->memory; } void RegionInstance::destroy(Event wait_on /*= Event::NO_EVENT*/) const { DetailedTimer::ScopedPush sp(TIME_LOW_LEVEL); RegionInstanceImpl *i_impl = get_runtime()->get_instance_impl(*this); if (!wait_on.has_triggered()) { EventImpl::add_waiter(wait_on, new DeferredInstDestroy(i_impl)); return; } log_inst.info("instance destroyed: space=" IDFMT " id=" IDFMT "", i_impl->metadata.is.id, this->id); get_runtime()->get_memory_impl(i_impl->memory)->destroy_instance(*this, true); } void RegionInstance::destroy(const std::vector<DestroyedField>& destroyed_fields, Event wait_on /*= Event::NO_EVENT*/) const { // TODO: actually call destructor assert(destroyed_fields.empty()); destroy(wait_on); } /*static*/ const RegionInstance RegionInstance::NO_INST = { 0 }; // a generic accessor just holds a pointer to the impl and passes all // requests through LegionRuntime::Accessor::RegionAccessor<LegionRuntime::Accessor::AccessorType::Generic> RegionInstance::get_accessor(void) const { // request metadata (if needed), but don't block on it yet RegionInstanceImpl *i_impl = get_runtime()->get_instance_impl(*this); Event e = i_impl->metadata.request_data(ID(id).instance.owner_node, id); if(!e.has_triggered()) log_inst.info("requested metadata in accessor creation: " IDFMT, id); return LegionRuntime::Accessor::RegionAccessor<LegionRuntime::Accessor::AccessorType::Generic>(LegionRuntime::Accessor::AccessorType::Generic::Untyped((void *)i_impl)); } void RegionInstance::report_instance_fault(int reason, const void *reason_data, size_t reason_size) const { assert(0); } //////////////////////////////////////////////////////////////////////// // // class RegionInstanceImpl // RegionInstanceImpl::RegionInstanceImpl(RegionInstance _me, IndexSpace _is, Memory _memory, off_t _offset, size_t _size, ReductionOpID _redopid, const DomainLinearization& _linear, size_t _block_size, size_t _elmt_size, const std::vector<size_t>& _field_sizes, const ProfilingRequestSet &reqs, off_t _count_offset /*= 0*/, off_t _red_list_size /*= 0*/, RegionInstance _parent_inst /*= NO_INST*/) : me(_me), memory(_memory) { metadata.linearization = _linear; metadata.block_size = _block_size; metadata.elmt_size = _elmt_size; metadata.field_sizes = _field_sizes; metadata.is = _is; metadata.alloc_offset = _offset; //metadata.access_offset = _offset + _adjust; metadata.size = _size; //StaticAccess<IndexSpaceImpl> rdata(_is.impl()); //locked_data.first_elmt = rdata->first_elmt; //locked_data.last_elmt = rdata->last_elmt; metadata.redopid = _redopid; metadata.count_offset = _count_offset; metadata.red_list_size = _red_list_size; metadata.parent_inst = _parent_inst; metadata.mark_valid(); lock.init(ID(me).convert<Reservation>(), ID(me).instance.owner_node); lock.in_use = true; if (!reqs.empty()) { requests = reqs; measurements.import_requests(requests); if (measurements.wants_measurement< ProfilingMeasurements::InstanceTimeline>()) { timeline.record_create_time(); } } } // when we auto-create a remote instance, we don't know region/offset RegionInstanceImpl::RegionInstanceImpl(RegionInstance _me, Memory _memory) : me(_me), memory(_memory) { lock.init(ID(me).convert<Reservation>(), ID(me).instance.owner_node); lock.in_use = true; } RegionInstanceImpl::~RegionInstanceImpl(void) {} // helper function to figure out which field we're in void find_field_start(const std::vector<size_t>& field_sizes, off_t byte_offset, size_t size, off_t& field_start, int& field_size) { off_t start = 0; for(std::vector<size_t>::const_iterator it = field_sizes.begin(); it != field_sizes.end(); it++) { assert((*it) > 0); if(byte_offset < (off_t)(*it)) { if ((off_t)(byte_offset + size) > (off_t)(*it)) { log_inst.error("Requested field does not match the expected field size"); assert(false); } field_start = start; field_size = (*it); return; } start += (*it); byte_offset -= (*it); } assert(0); } void RegionInstanceImpl::record_instance_usage(void) { // can't do this in the constructor because our ID isn't right yet... if(measurements.wants_measurement<ProfilingMeasurements::InstanceMemoryUsage>()) { ProfilingMeasurements::InstanceMemoryUsage usage; usage.instance = me; usage.memory = memory; usage.bytes = metadata.size; measurements.add_measurement(usage); } } bool RegionInstanceImpl::get_strided_parameters(void *&base, size_t &stride, off_t field_offset) { MemoryImpl *mem = get_runtime()->get_memory_impl(memory); // must have valid data by now - block if we have to metadata.await_data(); off_t offset = metadata.alloc_offset; size_t elmt_stride; if (metadata.block_size == 1) { offset += field_offset; elmt_stride = metadata.elmt_size; } else { off_t field_start=0; int field_size=0; find_field_start(metadata.field_sizes, field_offset, 1, field_start, field_size); offset += (field_start * metadata.block_size) + (field_offset - field_start); elmt_stride = field_size; } base = mem->get_direct_ptr(offset, 0); if (!base) return false; // if the caller wants a particular stride and we differ (and have more // than one element), fail if(stride != 0) { if((stride != elmt_stride) && (metadata.size > metadata.elmt_size)) return false; } else { stride = elmt_stride; } // if there's a per-element offset, apply it after we've agreed with the caller on // what we're pretending the stride is const DomainLinearization& dl = metadata.linearization; if(dl.get_dim() > 0) { // make sure this instance uses a 1-D linearization assert(dl.get_dim() == 1); LegionRuntime::Arrays::Mapping<1, 1> *mapping = dl.get_mapping<1>(); LegionRuntime::Arrays::Rect<1> preimage = mapping->preimage((coord_t)0); assert(preimage.lo == preimage.hi); // double-check that whole range maps densely preimage.hi.x[0] += 1; // not perfect, but at least detects non-unit-stride case assert(mapping->image_is_dense(preimage)); coord_t inst_first_elmt = preimage.lo[0]; //printf("adjusting base by %d * %zd\n", inst_first_elmt, stride); base = ((char *)base) - inst_first_elmt * stride; } return true; } void RegionInstanceImpl::finalize_instance(void) { if (!requests.empty()) { if (measurements.wants_measurement< ProfilingMeasurements::InstanceTimeline>()) { // set the instance ID correctly now - it wasn't available at construction time timeline.instance = me; timeline.record_delete_time(); measurements.add_measurement(timeline); } measurements.send_responses(requests); requests.clear(); } } void *RegionInstanceImpl::Metadata::serialize(size_t& out_size) const { // figure out how much space we need out_size = (sizeof(IndexSpace) + sizeof(off_t) + sizeof(size_t) + sizeof(ReductionOpID) + sizeof(off_t) + sizeof(off_t) + sizeof(size_t) + sizeof(size_t) + sizeof(size_t) + (field_sizes.size() * sizeof(size_t)) + sizeof(RegionInstance) + (MAX_LINEARIZATION_LEN * sizeof(int))); void *data = malloc(out_size); char *pos = (char *)data; #define S(val) do { memcpy(pos, &(val), sizeof(val)); pos += sizeof(val); } while(0) S(is); S(alloc_offset); S(size); S(redopid); S(count_offset); S(red_list_size); S(block_size); S(elmt_size); size_t l = field_sizes.size(); S(l); for(size_t i = 0; i < l; i++) S(field_sizes[i]); S(parent_inst); linearization.serialize((int *)pos); #undef S return data; } void RegionInstanceImpl::Metadata::deserialize(const void *in_data, size_t in_size) { const char *pos = (const char *)in_data; #define S(val) do { memcpy(&(val), pos, sizeof(val)); pos += sizeof(val); } while(0) S(is); S(alloc_offset); S(size); S(redopid); S(count_offset); S(red_list_size); S(block_size); S(elmt_size); size_t l; S(l); field_sizes.resize(l); for(size_t i = 0; i < l; i++) S(field_sizes[i]); S(parent_inst); linearization.deserialize((const int *)pos); #undef S } #ifdef POINTER_CHECKS void RegionInstanceImpl::verify_access(unsigned ptr) { StaticAccess<RegionInstanceImpl> data(this); const ElementMask &mask = data->is.get_valid_mask(); if (!mask.is_set(ptr)) { fprintf(stderr,"ERROR: Accessing invalid pointer %d in logical region " IDFMT "\n",ptr,data->is.id); assert(false); } } #endif static inline off_t calc_mem_loc(off_t alloc_offset, off_t field_start, int field_size, int elmt_size, int block_size, int index) { return (alloc_offset + // start address ((index / block_size) * block_size * elmt_size) + // full blocks (field_start * block_size) + // skip other fields ((index % block_size) * field_size)); // some some of our fields within our block } void RegionInstanceImpl::get_bytes(int index, off_t byte_offset, void *dst, size_t size) { // must have valid data by now - block if we have to metadata.await_data(); off_t o; if(metadata.block_size == 1) { // no blocking - don't need to know about field boundaries o = metadata.alloc_offset + (index * metadata.elmt_size) + byte_offset; } else { off_t field_start=0; int field_size=0; find_field_start(metadata.field_sizes, byte_offset, size, field_start, field_size); o = calc_mem_loc(metadata.alloc_offset, field_start, field_size, metadata.elmt_size, metadata.block_size, index); } MemoryImpl *m = get_runtime()->get_memory_impl(memory); m->get_bytes(o, dst, size); } void RegionInstanceImpl::put_bytes(int index, off_t byte_offset, const void *src, size_t size) { // must have valid data by now - block if we have to metadata.await_data(); off_t o; if(metadata.block_size == 1) { // no blocking - don't need to know about field boundaries o = metadata.alloc_offset + (index * metadata.elmt_size) + byte_offset; } else { off_t field_start=0; int field_size=0; find_field_start(metadata.field_sizes, byte_offset, size, field_start, field_size); o = calc_mem_loc(metadata.alloc_offset, field_start, field_size, metadata.elmt_size, metadata.block_size, index); } MemoryImpl *m = get_runtime()->get_memory_impl(memory); m->put_bytes(o, src, size); } }; // namespace Realm <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1784 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1143576 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/04/23 03:00:53<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1785 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2947 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1968803 by chui@ocl-promo-incrementor on 2019/07/17 03:00:12<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2948 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2174 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1294684 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/07/24 03:00:09<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2175 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2538 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1482174 by johtaylo@johtaylo-jtincrementor2-increment on 2017/11/14 03:00:05<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2539 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3064 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 2048321 by chui@ocl-promo-incrementor on 2019/12/19 03:00:07<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3065 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_IO_JSON_HH__ #define ALEPH_PERSISTENCE_DIAGRAMS_IO_JSON_HH__ #include <fstream> #include <ostream> #include <string> namespace aleph { namespace io { /** Writes a persistence diagram to an output stream, using the JSON format. The diagram will be serialized such that its points will be stored in the field ``data`` as a two-dimensional array. Note that infinite values will be encoded as strings. Additional data about the diagram, e.g. its dimension, are stored in name--value pairs. */ template <class Diagram> void writeJSON( std::ostream& o, const Diagram& D, const std::string& name = std::string() ) { std::string level = " "; o << "{\n"; o << level << "\"betti\": " << D.betti() << ",\n" << level << "\"dimension\": " << D.dimension() << ",\n"; if( !name.empty() ) o << level << "\"name\": " << "\"" << name << "\",\n"; o << level << "\"size\": " << D.size() << ",\n" << level << "\"diagram\": " << "[\n"; for( auto it = D.begin(); it != D.end(); ++it ) { if( it != D.begin() ) o << ",\n"; o << level << level << "[" << "\"" << it->x() << "\"" << "," << "\"" << it->y() << "\"" << "]"; } o << "\n" << level << "]\n" << "}"; } } // namespace io } // namespace aleph #endif <commit_msg>Implemented JSON reading for persistence diagrams<commit_after>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_IO_JSON_HH__ #define ALEPH_PERSISTENCE_DIAGRAMS_IO_JSON_HH__ #include <aleph/config/RapidJSON.hh> #include <aleph/persistenceDiagrams/PersistenceDiagram.hh> #include <aleph/utilities/String.hh> #include <fstream> #include <istream> #include <ostream> #include <string> #ifdef ALEPH_WITH_RAPID_JSON #include <rapidjson/document.h> #include <rapidjson/istreamwrapper.h> #endif namespace aleph { namespace io { /** Writes a persistence diagram to an output stream, using the JSON format. The diagram will be serialized such that its points will be stored in the field ``data`` as a two-dimensional array. Note that infinite values will be encoded as strings. Additional data about the diagram, e.g. its dimension, are stored in name--value pairs. */ template <class Diagram> void writeJSON( std::ostream& o, const Diagram& D, const std::string& name = std::string() ) { std::string level = " "; o << "{\n"; o << level << "\"betti\": " << D.betti() << ",\n" << level << "\"dimension\": " << D.dimension() << ",\n"; if( !name.empty() ) o << level << "\"name\": " << "\"" << name << "\",\n"; o << level << "\"size\": " << D.size() << ",\n" << level << "\"diagram\": " << "[\n"; for( auto it = D.begin(); it != D.end(); ++it ) { if( it != D.begin() ) o << ",\n"; o << level << level << "[" << "\"" << it->x() << "\"" << "," << "\"" << it->y() << "\"" << "]"; } o << "\n" << level << "]\n" << "}"; } /** Convenience function for writing a persistence diagram to a file in JSON format. */ template <class Diagram> void writeJSON( const std::string& filename, const Diagram& D, const std::string& name = std::string() ) { std::ofstream out( filename ); if( !out ) throw std::runtime_error( "Unable to open output file" ); writeJSON( out, D, name ); } /** Reads multiple persistence diagrams from an input stream in JSON format. The stream is checked for consistency; appropriate error messages will be raised if necessary. */ template <class T> std::vector< aleph::PersistenceDiagram<T> > readJSON( std::istream& in ) { #ifdef ALEPH_WITH_RAPID_JSON rapidjson::Document document; { rapidjson::IStreamWrapper isw( in ); document.ParseStream( isw ); } using PersistenceDiagram = aleph::PersistenceDiagram<T>; std::vector<PersistenceDiagram> persistenceDiagrams; if( !document.HasMember( "diagrams" ) ) throw std::runtime_error( "Unable to find array of persistence diagrams" ); for( auto&& diagram : document["diagrams"].GetArray() ) { auto dimension = diagram["dimension"].GetUint(); auto betti = diagram["betti"].GetUint(); auto size = diagram["size"].GetUint(); PersistenceDiagram persistenceDiagram; persistenceDiagram.setDimension( dimension ); for( auto&& point : diagram["diagram"].GetArray() ) { auto x = aleph::utilities::convert<T>( point[0].GetString() ); auto y = aleph::utilities::convert<T>( point[1].GetString() ); persistenceDiagram.add( x,y ); } if( persistenceDiagram.size() != size ) throw std::runtime_error( "Stored number of points does not match number of points in persistence diagram" ); if( persistenceDiagram.betti() != betti ) throw std::runtime_error( "Stored Betti number does not match Betti number of persistence diagram" ); persistenceDiagrams.emplace_back( persistenceDiagram ); } return persistenceDiagrams; #else return {}; #endif } /** Reads multiple persistence diagrams from a JSON input file. This is only a convenience unction provided to call the other reading routine defined above. */ template <class T> std::vector< aleph::PersistenceDiagram<T> > readJSON( const std::string& filename ) { std::ifstream in( filename ); if( !in ) throw std::runtime_error( "Unable to read input file" ); return readJSON<T>( in ); } } // namespace io } // namespace aleph #endif <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "<WebSig>" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, Institute for * Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>. * The development of this software was partly funded by the European * Commission in the <WebSig> project in the ISIS Programme. * For more information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * XSEC * * Configuration file for Windows platform * * Needs to be modified by hand * * Author(s): Berin Lautenbach * * $Id$ * */ #include <xercesc/util/XercesVersion.hpp> #define XSEC_VERSION "1.0.0" #define XSEC_VERSION_MAJOR 1 #define XSEC_VERSION_MEDIUM 0 #define XSEC_VERSION_MINOR 0 /* * Because we don't have a configure script, we need to rely on version * numbers to understand library idiosycracies */ #if (XERCES_VERSION_MAJOR >= 2) && (XERCES_VERSION_MINOR >= 3) /* * As of version 2.3, xerces requires a version parameter in XMLFormatter * constructors */ # define XSEC_XERCES_FORMATTER_REQUIRES_VERSION 1 #else /* * In version 2.2, the XMLUri class was broken for relative URI de-referencing */ # define XSEC_XERCES_BROKEN_XMLURI 1 #endif /* * The following defines whether Xalan integration is required. * * Xalan is used for XSLT and complex XPath processing. * Activate this #define if Xalan is not required (or desired) */ #define XSEC_NO_XALAN /* * Define presence of cryptographic providers */ #define HAVE_OPENSSL 1 /* #define HAVE_WINCAPI 1 */ /* * Macros used to determine what header files exist on this * system */ /* Posix unistd.h */ /* #define HAVE_UNISTD_H */ /* Windows direct.h */ #define HAVE_DIRECT_H 1 <commit_msg>Set for Xalan build<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "<WebSig>" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, Institute for * Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>. * The development of this software was partly funded by the European * Commission in the <WebSig> project in the ISIS Programme. * For more information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * XSEC * * Configuration file for Windows platform * * Needs to be modified by hand * * Author(s): Berin Lautenbach * * $Id$ * */ #include <xercesc/util/XercesVersion.hpp> #define XSEC_VERSION "1.0.0" #define XSEC_VERSION_MAJOR 1 #define XSEC_VERSION_MEDIUM 0 #define XSEC_VERSION_MINOR 0 /* * Because we don't have a configure script, we need to rely on version * numbers to understand library idiosycracies */ #if (XERCES_VERSION_MAJOR >= 2) && (XERCES_VERSION_MINOR >= 3) /* * As of version 2.3, xerces requires a version parameter in XMLFormatter * constructors */ # define XSEC_XERCES_FORMATTER_REQUIRES_VERSION 1 #else /* * In version 2.2, the XMLUri class was broken for relative URI de-referencing */ # define XSEC_XERCES_BROKEN_XMLURI 1 #endif /* * The following defines whether Xalan integration is required. * * Xalan is used for XSLT and complex XPath processing. * Activate this #define if Xalan is not required (or desired) */ /* #define XSEC_NO_XALAN */ /* * Define presence of cryptographic providers */ #define HAVE_OPENSSL 1 /* #define HAVE_WINCAPI 1 */ /* * Macros used to determine what header files exist on this * system */ /* Posix unistd.h */ /* #define HAVE_UNISTD_H */ /* Windows direct.h */ #define HAVE_DIRECT_H 1 <|endoftext|>
<commit_before>//! //! @author Yue Wang //! @date 26.11.2014 //! //! @brief Implementation for Listing 4.13 //! #include <../include/utilities.hpp> #include <iostream> #include <list> #include <algorithm> #include <future> namespace para { template<typename T> std::list<T> parallel_functional_quick_sort(std::list<T> l) { using std::list; using std::partition; using std::move; using std::future; using std::async; if(l.empty()) return l; //trivial case list<T> ret; ret.splice(ret.end(),l,l.begin()); T const& pivot = ret.front(); auto divide_point = partition(l.begin(),l.end(),[&](T const& t) { return t < pivot; }); list<T> lower; lower.splice(lower.end(),l,l.begin(),divide_point); future<list<T>> sorted_lower = async(&parallel_functional_quick_sort<T>,move(lower)); list<T> sorted_higher = parallel_functional_quick_sort(move(l)); ret.splice(ret.end(), sorted_higher); ret.splice(ret.begin(), sorted_lower.get()); return ret; } }//namespace int main() { std::list<int> l {6,3,2,5,1,4}; para::println_range(l); l = para::parallel_functional_quick_sort(l); para::println_range(l); return 0; } <commit_msg>commented modified: ch04/functional_quick_sort_parallel_version.cpp<commit_after>//! //! @author Yue Wang //! @date 26.11.2014 //! //! @brief Implementation for Listing 4.13 //! #include <../include/utilities.hpp> #include <iostream> #include <list> #include <algorithm> #include <future> namespace para { /** * @brief parallel_functional_quick_sort * @param list * @return sorted list * * @concept for T : operator < * * using platform dependent number of threads. */ template<typename T> std::list<T> parallel_functional_quick_sort(std::list<T> l) { using std::list; using std::partition; using std::move; using std::future; using std::async; if(l.empty()) return l; //trivial case //! use the first element as pivot. list<T> ret; ret.splice(ret.end(),l,l.begin()); T pivot = ret.front(); auto divide_point = partition(l.begin(),l.end(),[&](T const& t) { return t < pivot; }); //!build the unsorted lower part list<T> lower; lower.splice(lower.end(),l,l.begin(),divide_point); //! @brief recursion //! @attention since futrue and async are used here, std library will decide if new //! thread is needed for sorted_lower. As a result, threads number will differ //! on different platform. future<list<T>> sorted_lower = async(&parallel_functional_quick_sort<T>,move(lower)); list<T> sorted_higher = parallel_functional_quick_sort(move(l)); //! merge by splicing ret.splice(ret.end(), sorted_higher); ret.splice(ret.begin(), sorted_lower.get()); return ret; } }//namespace int main() { std::list<int> l {6,3,2,5,1,4}; para::println_range(l); l = para::parallel_functional_quick_sort(l); para::println_range(l); return 0; } //! output //para> 6 3 2 5 1 4 //para> 1 2 3 4 5 6 <|endoftext|>
<commit_before>#include "../common/init.h" #include "../common/timer.h" #include <iostream> #include <vector> #include "util/stretch-bitmap.h" #include "util/font.h" #include "util/debug.h" #include "util/load_exception.h" #include "util/token_exception.h" #include "util/stretch-bitmap.h" #include "util/input/input.h" #include "util/input/input-manager.h" #include "util/sound.h" #include "util/exceptions/exception.h" #include "util/network/network.h" #include "util/thread.h" #include "mugen/util.h" #include "mugen/search.h" #include "mugen/exception.h" #include "mugen/options.h" #include "mugen/widgets.h" #include <queue> static void sendMessage(std::string message, Network::Socket socket){ int size = message.size()+1 + sizeof(uint16_t); char * buffer = new char[size]; char * position = buffer; position = Network::dump16(position, size); position = Network::dumpStr(position, message); Network::sendBytes(socket, (uint8_t*) buffer, size + sizeof(uint16_t)); delete[] buffer; } static std::string readMessage(Network::Socket socket){ int16_t size = Network::read16(socket); char * buffer = new char[size]; Network::readBytes(socket, (uint8_t*) buffer, size); char * position = buffer; std::string message; position = Network::parseString(position, &message, size + 1); delete[] buffer; return message; } class Logic: public PaintownUtil::Logic, public Mugen::Widgets::ChatPanel::ClassListener{ public: Logic(Mugen::Widgets::ChatPanel & panel): panel(panel), escaped(false){ } Mugen::Widgets::ChatPanel & panel; bool escaped; Network::Socket socket; std::queue<std::string> sendable; std::queue<std::string> messages; ::Util::Thread::LockObject lock; ::Util::Thread::Id thread; double ticks(double system){ return system; } void run(){ try { panel.act(); sendMessages(); processMessages(); } catch (const Exception::Return & ex){ escaped = true; ::Util::Thread::joinThread(thread); throw ex; } } bool done(){ return escaped; } void sendMessages(){ lock.acquire(); while (!sendable.empty()){ sendMessage(sendable.front(), socket); sendable.pop(); } lock.release(); } void processMessages(){ lock.acquire(); while (!messages.empty()){ panel.addMessage("remote", messages.front()); messages.pop(); } lock.release(); } void pollMessages(){ try{ while (!escaped){ std::string message = readMessage(socket); lock.acquire(); messages.push(message); lock.signal(); lock.release(); } } catch (const Network::NetworkException & fail){ } } void listen(const std::string & message){ lock.acquire(); sendable.push(message); lock.release(); } }; class Draw: public PaintownUtil::Draw { public: Draw(Mugen::Widgets::ChatPanel & panel): panel(panel){ } Mugen::Widgets::ChatPanel & panel; void draw(const Graphics::Bitmap & screen){ Graphics::StretchedBitmap stretch(320, 240, screen); stretch.start(); stretch.fill(Graphics::makeColor(255,255,255)); panel.draw(stretch); stretch.finish(); screen.BlitToScreen(); } }; static void * do_thread(void * arg){ Logic * logic = (Logic*) arg; logic->pollMessages(); return NULL; } static void doServer(int port){ Mugen::Widgets::ChatPanel chat(10, 20, 300, 200); std::vector< PaintownUtil::ReferenceCount<Gui::ScrollItem> > list; Mugen::OptionMenu menu(list); chat.setFont(menu.getFont()); chat.setClient("You"); Logic logic(chat); chat.connectClassListener(&logic); Draw draw(chat); Network::Socket remote = Network::open(port); Network::listen(remote); Global::debug(0) << "Waiting for a connection on port " << port << std::endl; logic.socket = Network::accept(remote); Network::close(remote); Global::debug(0) << "Got a connection" << std::endl; ::Util::Thread::createThread(&logic.thread, NULL, (::Util::Thread::ThreadFunction) do_thread, &logic); PaintownUtil::standardLoop(logic, draw); } static void doClient(const std::string & host, int port){ Mugen::Widgets::ChatPanel chat(10, 20, 300, 200); std::vector< PaintownUtil::ReferenceCount<Gui::ScrollItem> > list; Mugen::OptionMenu menu(list); chat.setFont(menu.getFont()); chat.setClient("You"); Logic logic(chat); chat.connectClassListener(&logic); Draw draw(chat); Global::debug(0) << "Connecting to " << host << " on port " << port << std::endl; logic.socket = Network::connect(host, port); Global::debug(0) << "Connected" << std::endl; ::Util::Thread::createThread(&logic.thread, NULL, (::Util::Thread::ThreadFunction) do_thread, &logic); PaintownUtil::standardLoop(logic, draw); } static void arguments(const std::string & application, int status){ std::cout << "Usage: ./" << application << " server port" << std::endl; std::cout << " ./" << application << " client port [host]" << std::endl; exit(status); } int main(int argc, char ** argv){ if (argc > 2){ bool server = (strcmp(argv[1],"server")==0) ? true : false; bool client = (strcmp(argv[1],"client")==0) ? true : false; if (!server && !client){ arguments(argv[0], 1); } int port = atoi(argv[2]); std::string hostname = "127.0.0.1"; if (client && argc == 4){ hostname = argv[3]; } Screen::realInit(); atexit(Screen::realFinish); Common::startTimers(); Sound::initialize(); Global::setDebug(2); Graphics::Bitmap screen(*Graphics::getScreenBuffer()); Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, &screen); Keyboard::pushRepeatState(true); InputManager manager; Network::init(); try { if (server){ doServer(port); } else { doClient(hostname, port); } } catch (const Exception::Return & ex){ } catch (const Network::NetworkException & ex){ Global::debug(0) << "Network Exception: " << ex.getMessage() << std::endl; } Network::shutdown(); } else { arguments(argv[0],0); } return 0; } #ifdef USE_ALLEGRO END_OF_MAIN() #endif <commit_msg>[mugen] Use ScopedLock.<commit_after>#include "../common/init.h" #include "../common/timer.h" #include <iostream> #include <vector> #include "util/stretch-bitmap.h" #include "util/font.h" #include "util/debug.h" #include "util/load_exception.h" #include "util/token_exception.h" #include "util/stretch-bitmap.h" #include "util/input/input.h" #include "util/input/input-manager.h" #include "util/sound.h" #include "util/exceptions/exception.h" #include "util/network/network.h" #include "util/thread.h" #include "mugen/util.h" #include "mugen/search.h" #include "mugen/exception.h" #include "mugen/options.h" #include "mugen/widgets.h" #include <queue> static void sendMessage(std::string message, Network::Socket socket){ int size = message.size()+1 + sizeof(uint16_t); char * buffer = new char[size]; char * position = buffer; position = Network::dump16(position, size); position = Network::dumpStr(position, message); Network::sendBytes(socket, (uint8_t*) buffer, size + sizeof(uint16_t)); delete[] buffer; } static std::string readMessage(Network::Socket socket){ int16_t size = Network::read16(socket); char * buffer = new char[size]; Network::readBytes(socket, (uint8_t*) buffer, size); char * position = buffer; std::string message; position = Network::parseString(position, &message, size + 1); delete[] buffer; return message; } class Logic: public PaintownUtil::Logic, public Mugen::Widgets::ChatPanel::ClassListener{ public: Logic(Mugen::Widgets::ChatPanel & panel): panel(panel), escaped(false){ } Mugen::Widgets::ChatPanel & panel; bool escaped; Network::Socket socket; std::queue<std::string> sendable; std::queue<std::string> messages; ::Util::Thread::LockObject lock; ::Util::Thread::Id thread; double ticks(double system){ return system; } void run(){ try { panel.act(); sendMessages(); processMessages(); } catch (const Exception::Return & ex){ escaped = true; ::Util::Thread::joinThread(thread); throw ex; } } bool done(){ return escaped; } void sendMessages(){ while (!sendable.empty()){ ::Util::Thread::ScopedLock scope(lock); sendMessage(sendable.front(), socket); sendable.pop(); } } void processMessages(){ while (!messages.empty()){ ::Util::Thread::ScopedLock scope(lock); panel.addMessage("remote", messages.front()); messages.pop(); } } void pollMessages(){ try{ while (!escaped){ std::string message = readMessage(socket); lock.acquire(); messages.push(message); lock.signal(); lock.release(); } } catch (const Network::NetworkException & fail){ } } void listen(const std::string & message){ sendable.push(message); } }; class Draw: public PaintownUtil::Draw { public: Draw(Mugen::Widgets::ChatPanel & panel): panel(panel){ } Mugen::Widgets::ChatPanel & panel; void draw(const Graphics::Bitmap & screen){ Graphics::StretchedBitmap stretch(320, 240, screen); stretch.start(); stretch.fill(Graphics::makeColor(255,255,255)); panel.draw(stretch); stretch.finish(); screen.BlitToScreen(); } }; static void * do_thread(void * arg){ Logic * logic = (Logic*) arg; logic->pollMessages(); return NULL; } static void doServer(int port){ Mugen::Widgets::ChatPanel chat(10, 20, 300, 200); std::vector< PaintownUtil::ReferenceCount<Gui::ScrollItem> > list; Mugen::OptionMenu menu(list); chat.setFont(menu.getFont()); chat.setClient("You"); Logic logic(chat); chat.connectClassListener(&logic); Draw draw(chat); Network::Socket remote = Network::open(port); Network::listen(remote); Global::debug(0) << "Waiting for a connection on port " << port << std::endl; logic.socket = Network::accept(remote); Network::close(remote); Global::debug(0) << "Got a connection" << std::endl; ::Util::Thread::createThread(&logic.thread, NULL, (::Util::Thread::ThreadFunction) do_thread, &logic); PaintownUtil::standardLoop(logic, draw); } static void doClient(const std::string & host, int port){ Mugen::Widgets::ChatPanel chat(10, 20, 300, 200); std::vector< PaintownUtil::ReferenceCount<Gui::ScrollItem> > list; Mugen::OptionMenu menu(list); chat.setFont(menu.getFont()); chat.setClient("You"); Logic logic(chat); chat.connectClassListener(&logic); Draw draw(chat); Global::debug(0) << "Connecting to " << host << " on port " << port << std::endl; logic.socket = Network::connect(host, port); Global::debug(0) << "Connected" << std::endl; ::Util::Thread::createThread(&logic.thread, NULL, (::Util::Thread::ThreadFunction) do_thread, &logic); PaintownUtil::standardLoop(logic, draw); } static void arguments(const std::string & application, int status){ std::cout << "Usage: ./" << application << " server port" << std::endl; std::cout << " ./" << application << " client port [host]" << std::endl; exit(status); } int main(int argc, char ** argv){ if (argc > 2){ bool server = (strcmp(argv[1],"server")==0) ? true : false; bool client = (strcmp(argv[1],"client")==0) ? true : false; if (!server && !client){ arguments(argv[0], 1); } int port = atoi(argv[2]); std::string hostname = "127.0.0.1"; if (client && argc == 4){ hostname = argv[3]; } Screen::realInit(); atexit(Screen::realFinish); Common::startTimers(); Sound::initialize(); Global::setDebug(2); Graphics::Bitmap screen(*Graphics::getScreenBuffer()); Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, &screen); Keyboard::pushRepeatState(true); InputManager manager; Network::init(); try { if (server){ doServer(port); } else { doClient(hostname, port); } } catch (const Exception::Return & ex){ } catch (const Network::NetworkException & ex){ Global::debug(0) << "Network Exception: " << ex.getMessage() << std::endl; } Network::shutdown(); } else { arguments(argv[0],0); } return 0; } #ifdef USE_ALLEGRO END_OF_MAIN() #endif <|endoftext|>
<commit_before>/* * (C) 2016 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "tests.h" #if defined(BOTAN_HAS_OCSP) #include <botan/ocsp.h> #include <botan/x509path.h> #include <botan/certstor.h> #include <botan/calendar.h> #endif namespace Botan_Tests { #if defined(BOTAN_HAS_OCSP) class OCSP_Tests : public Test { private: std::vector<uint8_t> slurp_data_file(const std::string& path) { const std::string fsname = Test::data_file(path); std::ifstream file(fsname.c_str(), std::ios::binary); if(!file.good()) throw Test_Error("Error reading from " + fsname); std::vector<uint8_t> contents; while(file.good()) { std::vector<uint8_t> buf(4096); file.read(reinterpret_cast<char*>(buf.data()), buf.size()); size_t got = file.gcount(); if(got == 0 && file.eof()) break; contents.insert(contents.end(), buf.data(), buf.data() + got); } return contents; } std::shared_ptr<const Botan::X509_Certificate> load_test_X509_cert(const std::string& path) { return std::make_shared<const Botan::X509_Certificate>(Test::data_file(path)); } std::shared_ptr<const Botan::OCSP::Response> load_test_OCSP_resp(const std::string& path) { return std::make_shared<const Botan::OCSP::Response>(slurp_data_file(path)); } Test::Result test_response_parsing() { Test::Result result("OCSP response parsing"); // Simple parsing tests const std::vector<std::string> ocsp_input_paths = { "ocsp/resp1.der", "ocsp/resp2.der", "ocsp/resp3.der" }; for(std::string ocsp_input_path : ocsp_input_paths) { try { Botan::OCSP::Response resp(slurp_data_file(ocsp_input_path)); result.test_success("Parsed input " + ocsp_input_path); } catch(Botan::Exception& e) { result.test_failure("Parsing failed", e.what()); } } return result; } Test::Result test_request_encoding() { Test::Result result("OCSP request encoding"); const Botan::X509_Certificate end_entity(Test::data_file("ocsp/gmail.pem")); const Botan::X509_Certificate issuer(Test::data_file("ocsp/google_g2.pem")); try { const Botan::OCSP::Request bogus(end_entity, issuer); result.test_failure("Bad arguments (swapped end entity, issuer) accepted"); } catch(Botan::Invalid_Argument&) { result.test_success("Bad arguments rejected"); } const Botan::OCSP::Request req(issuer, end_entity); const std::string expected_request = "ME4wTKADAgEAMEUwQzBBMAkGBSsOAwIaBQAEFPLgavmFih2NcJtJGSN6qbUaKH5kBBRK3QYWG7z2aLV29YG2u2IaulqBLwIIQkg+DF+RYMY="; result.test_eq("Encoded OCSP request", req.base64_encode(), expected_request); return result; } Test::Result test_response_verification() { Test::Result result("OCSP request check"); std::shared_ptr<const Botan::X509_Certificate> ee = load_test_X509_cert("ocsp/randombit.pem"); std::shared_ptr<const Botan::X509_Certificate> ca = load_test_X509_cert("ocsp/letsencrypt.pem"); std::shared_ptr<const Botan::X509_Certificate> trust_root = load_test_X509_cert("ocsp/geotrust.pem"); const std::vector<std::shared_ptr<const Botan::X509_Certificate>> cert_path = { ee, ca, trust_root }; std::shared_ptr<const Botan::OCSP::Response> ocsp = load_test_OCSP_resp("ocsp/randombit_ocsp.der"); Botan::Certificate_Store_In_Memory certstore; certstore.add_certificate(trust_root); // Some arbitrary time within the validity period of the test certs const auto valid_time = Botan::calendar_point(2016,11,20,8,30,0).to_std_timepoint(); std::vector<std::set<Botan::Certificate_Status_Code>> ocsp_status = Botan::PKIX::check_ocsp( cert_path, { ocsp }, { &certstore }, valid_time); if(result.test_eq("Expected size of ocsp_status", ocsp_status.size(), 1)) { if(result.test_eq("Expected size of ocsp_status[0]", ocsp_status[0].size(), 1)) { result.confirm("Status good", ocsp_status[0].count(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD)); } } return result; } #if defined(BOTAN_HAS_ONLINE_REVOCATION_CHECKS) Test::Result test_online_request() { Test::Result result("OCSP online check"); std::shared_ptr<const Botan::X509_Certificate> ee = load_test_X509_cert("ocsp/randombit.pem"); std::shared_ptr<const Botan::X509_Certificate> ca = load_test_X509_cert("ocsp/letsencrypt.pem"); std::shared_ptr<const Botan::X509_Certificate> trust_root = load_test_X509_cert("ocsp/identrust.pem"); const std::vector<std::shared_ptr<const Botan::X509_Certificate>> cert_path = { ee, ca, trust_root }; Botan::Certificate_Store_In_Memory certstore; certstore.add_certificate(trust_root); std::vector<std::set<Botan::Certificate_Status_Code>> ocsp_status = Botan::PKIX::check_ocsp_online( cert_path, { &certstore }, std::chrono::system_clock::now(), std::chrono::milliseconds(3000), true); if(result.test_eq("Expected size of ocsp_status", ocsp_status.size(), 2)) { if(result.test_eq("Expected size of ocsp_status[0]", ocsp_status[0].size(), 1)) { result.confirm("Status good", ocsp_status[0].count(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD)); } if(result.test_eq("Expected size of ocsp_status[1]", ocsp_status[1].size(), 1)) { result.confirm("Status good", ocsp_status[1].count(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD)); } } return result; } #endif public: std::vector<Test::Result> run() override { std::vector<Test::Result> results; results.push_back(test_request_encoding()); results.push_back(test_response_parsing()); results.push_back(test_response_verification()); #if defined(BOTAN_HAS_ONLINE_REVOCATION_CHECKS) if(Test::run_online_tests()) results.push_back(test_online_request()); #endif return results; } }; BOTAN_REGISTER_TEST("ocsp", OCSP_Tests); #endif } <commit_msg>The certificate being tested by the OCSP online test has expired.<commit_after>/* * (C) 2016 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "tests.h" #if defined(BOTAN_HAS_OCSP) #include <botan/ocsp.h> #include <botan/x509path.h> #include <botan/certstor.h> #include <botan/calendar.h> #endif namespace Botan_Tests { #if defined(BOTAN_HAS_OCSP) class OCSP_Tests : public Test { private: std::vector<uint8_t> slurp_data_file(const std::string& path) { const std::string fsname = Test::data_file(path); std::ifstream file(fsname.c_str(), std::ios::binary); if(!file.good()) throw Test_Error("Error reading from " + fsname); std::vector<uint8_t> contents; while(file.good()) { std::vector<uint8_t> buf(4096); file.read(reinterpret_cast<char*>(buf.data()), buf.size()); size_t got = file.gcount(); if(got == 0 && file.eof()) break; contents.insert(contents.end(), buf.data(), buf.data() + got); } return contents; } std::shared_ptr<const Botan::X509_Certificate> load_test_X509_cert(const std::string& path) { return std::make_shared<const Botan::X509_Certificate>(Test::data_file(path)); } std::shared_ptr<const Botan::OCSP::Response> load_test_OCSP_resp(const std::string& path) { return std::make_shared<const Botan::OCSP::Response>(slurp_data_file(path)); } Test::Result test_response_parsing() { Test::Result result("OCSP response parsing"); // Simple parsing tests const std::vector<std::string> ocsp_input_paths = { "ocsp/resp1.der", "ocsp/resp2.der", "ocsp/resp3.der" }; for(std::string ocsp_input_path : ocsp_input_paths) { try { Botan::OCSP::Response resp(slurp_data_file(ocsp_input_path)); result.test_success("Parsed input " + ocsp_input_path); } catch(Botan::Exception& e) { result.test_failure("Parsing failed", e.what()); } } return result; } Test::Result test_request_encoding() { Test::Result result("OCSP request encoding"); const Botan::X509_Certificate end_entity(Test::data_file("ocsp/gmail.pem")); const Botan::X509_Certificate issuer(Test::data_file("ocsp/google_g2.pem")); try { const Botan::OCSP::Request bogus(end_entity, issuer); result.test_failure("Bad arguments (swapped end entity, issuer) accepted"); } catch(Botan::Invalid_Argument&) { result.test_success("Bad arguments rejected"); } const Botan::OCSP::Request req(issuer, end_entity); const std::string expected_request = "ME4wTKADAgEAMEUwQzBBMAkGBSsOAwIaBQAEFPLgavmFih2NcJtJGSN6qbUaKH5kBBRK3QYWG7z2aLV29YG2u2IaulqBLwIIQkg+DF+RYMY="; result.test_eq("Encoded OCSP request", req.base64_encode(), expected_request); return result; } Test::Result test_response_verification() { Test::Result result("OCSP request check"); std::shared_ptr<const Botan::X509_Certificate> ee = load_test_X509_cert("ocsp/randombit.pem"); std::shared_ptr<const Botan::X509_Certificate> ca = load_test_X509_cert("ocsp/letsencrypt.pem"); std::shared_ptr<const Botan::X509_Certificate> trust_root = load_test_X509_cert("ocsp/geotrust.pem"); const std::vector<std::shared_ptr<const Botan::X509_Certificate>> cert_path = { ee, ca, trust_root }; std::shared_ptr<const Botan::OCSP::Response> ocsp = load_test_OCSP_resp("ocsp/randombit_ocsp.der"); Botan::Certificate_Store_In_Memory certstore; certstore.add_certificate(trust_root); // Some arbitrary time within the validity period of the test certs const auto valid_time = Botan::calendar_point(2016,11,20,8,30,0).to_std_timepoint(); std::vector<std::set<Botan::Certificate_Status_Code>> ocsp_status = Botan::PKIX::check_ocsp( cert_path, { ocsp }, { &certstore }, valid_time); if(result.test_eq("Expected size of ocsp_status", ocsp_status.size(), 1)) { if(result.test_eq("Expected size of ocsp_status[0]", ocsp_status[0].size(), 1)) { result.confirm("Status good", ocsp_status[0].count(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD)); } } return result; } #if defined(BOTAN_HAS_ONLINE_REVOCATION_CHECKS) Test::Result test_online_request() { Test::Result result("OCSP online check"); // Expired end-entity certificate: std::shared_ptr<const Botan::X509_Certificate> ee = load_test_X509_cert("ocsp/randombit.pem"); std::shared_ptr<const Botan::X509_Certificate> ca = load_test_X509_cert("ocsp/letsencrypt.pem"); std::shared_ptr<const Botan::X509_Certificate> trust_root = load_test_X509_cert("ocsp/identrust.pem"); const std::vector<std::shared_ptr<const Botan::X509_Certificate>> cert_path = { ee, ca, trust_root }; Botan::Certificate_Store_In_Memory certstore; certstore.add_certificate(trust_root); std::vector<std::set<Botan::Certificate_Status_Code>> ocsp_status = Botan::PKIX::check_ocsp_online( cert_path, { &certstore }, std::chrono::system_clock::now(), std::chrono::milliseconds(3000), true); if(result.test_eq("Expected size of ocsp_status", ocsp_status.size(), 2)) { if(result.test_eq("Expected size of ocsp_status[0]", ocsp_status[0].size(), 1)) { result.confirm("Status expired", ocsp_status[0].count(Botan::Certificate_Status_Code::OCSP_HAS_EXPIRED)); } if(result.test_eq("Expected size of ocsp_status[1]", ocsp_status[1].size(), 1)) { result.confirm("Status good", ocsp_status[1].count(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD)); } } return result; } #endif public: std::vector<Test::Result> run() override { std::vector<Test::Result> results; results.push_back(test_request_encoding()); results.push_back(test_response_parsing()); results.push_back(test_response_verification()); #if defined(BOTAN_HAS_ONLINE_REVOCATION_CHECKS) if(Test::run_online_tests()) results.push_back(test_online_request()); #endif return results; } }; BOTAN_REGISTER_TEST("ocsp", OCSP_Tests); #endif } <|endoftext|>
<commit_before>/** * \file * * \brief source file of mount command * * \copyright BSD License (see doc/COPYING or http://www.libelektra.org) * */ #include <mount.hpp> #include <backend.hpp> #include <backends.hpp> #include <cmdline.hpp> #include <iostream> #include <iterator> #include <fstream> #include <vector> #include <string> #include <kdbprivate.h> #include <kdbmodule.h> using namespace std; using namespace kdb; using namespace kdb::tools; MountCommand::MountCommand() {} /** * @brief Output what currently is mounted */ void MountCommand::outputMtab(Cmdline const& cl) { Backends::BackendInfoVector mtab = Backends::getBackendInfo(mountConf); bool all = cl.first && cl.second && cl.third; char delim = '\n'; if (cl.null) delim = '\0'; for (Backends::BackendInfoVector::const_iterator it=mtab.begin(); it!=mtab.end(); ++it) { if (cl.first) { std::cout << it->path; if (all) std::cout << " on "; else std::cout << delim << std::flush; } if (cl.second) { std::cout << it->mountpoint; if (all) std::cout << " with name "; else std::cout << delim << std::flush; } // TODO: remove next version if (cl.third) { std::cout << it->name; std::cout << delim << std::flush; } } } void MountCommand::processArguments(Cmdline const& cl) { if (!cl.interactive && cl.arguments.size() == 1) { throw invalid_argument("wrong number of arguments, 0 or more then 1 needed"); } if (cl.interactive) { cout << "Welcome to interactive mounting" << endl; cout << "Note that nothing will be made persistent" << endl; cout << "until you say y at the very end of the mounting process" << endl; cout << endl; cout << "Please provide a unique name." << endl; } } void MountCommand::buildBackend(Cmdline const& cl) { Backend backend; Key mpk(mp, KEY_CASCADING_NAME, KEY_END); if (!mpk.isValid()) { throw invalid_argument(mp + " is not a valid mountpoint"); } backend.setMountpoint(mpk, mountConf); backend.setBackendConfig(cl.getPluginsConfig("system/")); if (cl.debug) { cout << "Trying to load the resolver plugin " << cl.resolver << endl; } backend.addPlugin (cl.resolver); if (cl.interactive) { cout << endl; cout << "Enter a path to a file in the filesystem." << endl; cout << "The path must either not exist or be a file." << endl; cout << "For user or cascading mountpoints it must be a relative path." << endl; cout << "Then, the path will be resolved dynamically." << endl; cout << "Path: "; cin >> path; } else { path = cl.arguments[0]; } backend.useConfigFile(path); istringstream sstream(cl.plugins); std::string plugin; while (std::getline (sstream, plugin, ' ')) { if (cl.debug) { cout << "Trying to add default plugin " << plugin << endl; } backend.addPlugin (plugin); } if (cl.interactive) { cout << "Now enter a sequence of plugins you want in the backend" << endl; } appendPlugins(cl, backend); backend.serialize(mountConf); } bool MountCommand::readPluginConfig(Cmdline const& cl, size_t current_token, KeySet & pluginConfig) { string keyName; string value; if (cl.interactive) { cout << "Enter the plugin configuration" << endl; cout << "Use '.' as Key name to finish" << endl; while (true) { cout << "Enter the Key name: "; cin >> keyName; if (keyName == ".") break; cout << "Enter the Key value: "; cin >> value; pluginConfig.append(Key("user/"+keyName, KEY_VALUE, value.c_str(), KEY_END)); } } else { // check if there is a further token (which might be the config of the current plugin) if (current_token + 1 >= cl.arguments.size ()) return false; string configString = cl.arguments[current_token + 1]; // check if the next argument is a config (otherwise it is treated as plugin name) // only a token with a '=' is treated as config if (configString.find ('=') == string::npos) return false; istringstream sstream(configString); // read until the next '=', this will be the keyname while (std::getline (sstream, keyName, '=')) { // read until a ',' or the end of line // if nothing is read because the '=' is the last character // in the config string, consider the value empty if (!std::getline (sstream, value, ',')) value = ""; pluginConfig.append(Key("user/"+keyName, KEY_VALUE, value.c_str(), KEY_END)); } } return true; } void MountCommand::appendPlugins(Cmdline const& cl, Backend & backend) { std::string pname; size_t current_plugin = 2; KeySet pluginConfig; if (cl.interactive) { cout << "First Plugin: "; cin >> pname; readPluginConfig (cl, current_plugin, pluginConfig); } else { if (current_plugin >= cl.arguments.size()) { pname = "dump"; } else { pname = cl.arguments[current_plugin]; if (readPluginConfig (cl, current_plugin, pluginConfig)) { current_plugin ++; } } current_plugin ++; } while (pname != "." || !backend.validated()) { try { backend.addPlugin (pname, pluginConfig); pluginConfig.clear(); } catch (PluginCheckException const& e) { if (!cl.interactive) { // do not allow errors in non-interactive mode throw; } else { cerr << "Could not add that plugin" << endl; cerr << e.what() << endl; } } if (cl.interactive) { if (!backend.validated()) cout << "Not validated, try to add another plugin (. to abort)" << endl; else cout << "Enter . to finish entering plugins" << endl; } if (cl.interactive) { cout << endl; cout << "Next Plugin: "; cin >> pname; if (pname != ".") { readPluginConfig (cl, current_plugin, pluginConfig); } } else { if (current_plugin >= cl.arguments.size()) { pname = "."; } else { pname = cl.arguments[current_plugin]; if (readPluginConfig (cl, current_plugin, pluginConfig)) { current_plugin ++; } } current_plugin ++; } if (pname == "." && !backend.validated()) { std::cerr << backend << std::endl; throw CommandAbortException(); } } } /** * @brief Its quite linear whats going on, but there are many steps involved * * @param cl the commandline * * @retval 0 on success (otherwise exception) */ int MountCommand::execute(Cmdline const& cl) { readMountConf(cl); if (!cl.interactive && cl.arguments.empty()) { // no interactive mode, so lets output the mtab outputMtab(cl); return 0; } processArguments(cl); getMountpoint(cl); buildBackend(cl); askForConfirmation(cl); doIt(); return 0; } MountCommand::~MountCommand() {} <commit_msg>kdb: make mounting fool-proof (hopefully)<commit_after>/** * \file * * \brief source file of mount command * * \copyright BSD License (see doc/COPYING or http://www.libelektra.org) * */ #include <mount.hpp> #include <backend.hpp> #include <backends.hpp> #include <cmdline.hpp> #include <iostream> #include <iterator> #include <fstream> #include <vector> #include <string> #include <kdbprivate.h> #include <kdbmodule.h> using namespace std; using namespace kdb; using namespace kdb::tools; class KDBMountException : public KDBException { std::string msg; public: KDBMountException(std::string const & e) : KDBException (Key()) { msg = e; } virtual const char* what() const noexcept { return msg.c_str(); } }; MountCommand::MountCommand() {} /** * @brief Output what currently is mounted */ void MountCommand::outputMtab(Cmdline const& cl) { Backends::BackendInfoVector mtab = Backends::getBackendInfo(mountConf); bool all = cl.first && cl.second && cl.third; char delim = '\n'; if (cl.null) delim = '\0'; for (Backends::BackendInfoVector::const_iterator it=mtab.begin(); it!=mtab.end(); ++it) { if (cl.first) { std::cout << it->path; if (all) std::cout << " on "; else std::cout << delim << std::flush; } if (cl.second) { std::cout << it->mountpoint; if (all) std::cout << " with name "; else std::cout << delim << std::flush; } // TODO: remove next version if (cl.third) { std::cout << it->name; std::cout << delim << std::flush; } } } void MountCommand::processArguments(Cmdline const& cl) { if (!cl.interactive && cl.arguments.size() == 1) { throw invalid_argument("wrong number of arguments, 0 or more then 1 needed"); } if (cl.interactive) { cout << "Welcome to interactive mounting" << endl; cout << "Note that nothing will be made persistent" << endl; cout << "until you say y at the very end of the mounting process" << endl; cout << endl; cout << "Please provide a unique name." << endl; } } void MountCommand::buildBackend(Cmdline const& cl) { Backend backend; Key mpk(mp, KEY_CASCADING_NAME, KEY_END); if (!mpk.isValid()) { throw invalid_argument(mp + " is not a valid mountpoint"); } backend.setMountpoint(mpk, mountConf); backend.setBackendConfig(cl.getPluginsConfig("system/")); if (cl.debug) { cout << "Trying to load the resolver plugin " << cl.resolver << endl; } backend.addPlugin (cl.resolver); if (cl.interactive) { cout << endl; cout << "Enter a path to a file in the filesystem." << endl; cout << "The path must either not exist or be a file." << endl; cout << "For user or cascading mountpoints it must be a relative path." << endl; cout << "Then, the path will be resolved dynamically." << endl; cout << "Path: "; cin >> path; } else { path = cl.arguments[0]; } backend.useConfigFile(path); istringstream sstream(cl.plugins); std::string plugin; while (std::getline (sstream, plugin, ' ')) { if (cl.debug) { cout << "Trying to add default plugin " << plugin << endl; } backend.addPlugin (plugin); } if (cl.interactive) { cout << "Now enter a sequence of plugins you want in the backend" << endl; } appendPlugins(cl, backend); backend.serialize(mountConf); } bool MountCommand::readPluginConfig(Cmdline const& cl, size_t current_token, KeySet & pluginConfig) { string keyName; string value; if (cl.interactive) { cout << "Enter the plugin configuration" << endl; cout << "Use '.' as Key name to finish" << endl; while (true) { cout << "Enter the Key name: "; cin >> keyName; if (keyName == ".") break; cout << "Enter the Key value: "; cin >> value; pluginConfig.append(Key("user/"+keyName, KEY_VALUE, value.c_str(), KEY_END)); } } else { // check if there is a further token (which might be the config of the current plugin) if (current_token + 1 >= cl.arguments.size ()) return false; string configString = cl.arguments[current_token + 1]; // check if the next argument is a config (otherwise it is treated as plugin name) // only a token with a '=' is treated as config if (configString.find ('=') == string::npos) return false; istringstream sstream(configString); // read until the next '=', this will be the keyname while (std::getline (sstream, keyName, '=')) { // read until a ',' or the end of line // if nothing is read because the '=' is the last character // in the config string, consider the value empty if (!std::getline (sstream, value, ',')) value = ""; pluginConfig.append(Key("user/"+keyName, KEY_VALUE, value.c_str(), KEY_END)); } } return true; } void MountCommand::appendPlugins(Cmdline const& cl, Backend & backend) { std::string pname; size_t current_plugin = 2; KeySet pluginConfig; if (cl.interactive) { cout << "First Plugin: "; cin >> pname; readPluginConfig (cl, current_plugin, pluginConfig); } else { if (current_plugin >= cl.arguments.size()) { pname = "dump"; } else { pname = cl.arguments[current_plugin]; if (readPluginConfig (cl, current_plugin, pluginConfig)) { current_plugin ++; } } current_plugin ++; } while (pname != "." || !backend.validated()) { try { backend.addPlugin (pname, pluginConfig); pluginConfig.clear(); } catch (PluginCheckException const& e) { if (!cl.interactive) { // do not allow errors in non-interactive mode throw; } else { cerr << "Could not add that plugin" << endl; cerr << e.what() << endl; } } if (cl.interactive) { if (!backend.validated()) cout << "Not validated, try to add another plugin (. to abort)" << endl; else cout << "Enter . to finish entering plugins" << endl; } if (cl.interactive) { cout << endl; cout << "Next Plugin: "; cin >> pname; if (pname != ".") { readPluginConfig (cl, current_plugin, pluginConfig); } } else { if (current_plugin >= cl.arguments.size()) { pname = "."; } else { pname = cl.arguments[current_plugin]; if (readPluginConfig (cl, current_plugin, pluginConfig)) { current_plugin ++; } } current_plugin ++; } if (pname == "." && !backend.validated()) { std::cerr << backend << std::endl; throw CommandAbortException(); } } } /** * @brief Its quite linear whats going on, but there are many steps involved * * @param cl the commandline * * @retval 0 on success (otherwise exception) */ int MountCommand::execute(Cmdline const& cl) { readMountConf(cl); if (!cl.interactive && cl.arguments.empty()) { // no interactive mode, so lets output the mtab outputMtab(cl); return 0; } processArguments(cl); getMountpoint(cl); buildBackend(cl); askForConfirmation(cl); try { doIt(); } catch (KDBException const & e) { throw KDBMountException(std::string(e.what())+"\n\n" "IMPORTANT: Make sure you can write to system namespace\n" " Usually you need to be root for that!"); } return 0; } MountCommand::~MountCommand() {} <|endoftext|>
<commit_before><commit_msg>* notify theme loading with --load-extension * fix crasher in theme parsing with no images<commit_after><|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 "TransitionView.h" #include "OverView.h" #include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkTime.h" #include "SkInterpolator.h" static const char gIsTransitionQuery[] = "is-transition"; static const char gReplaceTransitionEvt[] = "replace-transition-view"; bool is_transition(SkView* view) { SkEvent isTransition(gIsTransitionQuery); return view->doQuery(&isTransition); } class TransitionView : public SampleView { enum { // kDurationMS = 500 kDurationMS = 1 }; public: TransitionView(SkView* prev, SkView* next, int direction) : fInterp(4, 2){ fAnimationDirection = (Direction)(1 << (direction % 8)); fPrev = prev; fPrev->setClipToBounds(false); fPrev->setVisibleP(true); (void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState); //Not calling unref because fPrev is assumed to have been created, so //this will result in a transfer of ownership this->attachChildToBack(fPrev); fNext = next; fNext->setClipToBounds(true); fNext->setVisibleP(true); (void)SampleView::SetUsePipe(fNext, SkOSMenu::kOffState); //Calling unref because next is a newly created view and TransitionView //is now the sole owner of fNext this->attachChildToFront(fNext)->unref(); fDone = false; //SkDebugf("--created transition\n"); } ~TransitionView(){ //SkDebugf("--deleted transition\n"); } virtual void requestMenu(SkOSMenu* menu) { if (SampleView::IsSampleView(fNext)) ((SampleView*)fNext)->requestMenu(menu); } protected: virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SkString title; if (SampleCode::RequestTitle(fNext, &title)) { SampleCode::TitleR(evt, title.c_str()); return true; } return false; } if (evt->isType(gIsTransitionQuery)) { return true; } return this->INHERITED::onQuery(evt); } virtual bool onEvent(const SkEvent& evt) { if (evt.isType(gReplaceTransitionEvt)) { fPrev->detachFromParent(); fPrev = (SkView*)SkEventSink::FindSink(evt.getFast32()); (void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState); //attach the new fPrev and call unref to balance the ref in onDraw this->attachChildToBack(fPrev)->unref(); this->inval(NULL); return true; } if (evt.isType("transition-done")) { fNext->setLoc(0, 0); fNext->setClipToBounds(false); SkEvent* evt = new SkEvent(gReplaceTransitionEvt, this->getParent()->getSinkID()); evt->setFast32(fNext->getSinkID()); //increate ref count of fNext so it survives detachAllChildren fNext->ref(); this->detachAllChildren(); evt->post(); return true; } return this->INHERITED::onEvent(evt); } virtual void onDrawBackground(SkCanvas* canvas) {} virtual void onDrawContent(SkCanvas* canvas) { if (fDone) return; if (is_overview(fNext) || is_overview(fPrev)) { fPipeState = SkOSMenu::kOffState; } SkScalar values[4]; SkInterpolator::Result result = fInterp.timeToValues(SkTime::GetMSecs(), values); //SkDebugf("transition %x %d pipe:%d\n", this, result, fUsePipe); //SkDebugf("%f %f %f %f %d\n", values[0], values[1], values[2], values[3], result); if (SkInterpolator::kNormal_Result == result) { fPrev->setLocX(values[kPrevX]); fPrev->setLocY(values[kPrevY]); fNext->setLocX(values[kNextX]); fNext->setLocY(values[kNextY]); this->inval(NULL); } else { (new SkEvent("transition-done", this->getSinkID()))->post(); fDone = true; } } virtual void onSizeChange() { this->INHERITED::onSizeChange(); fNext->setSize(this->width(), this->height()); fPrev->setSize(this->width(), this->height()); SkScalar lr = 0, ud = 0; if (fAnimationDirection & (kLeftDirection|kULDirection|kDLDirection)) lr = this->width(); if (fAnimationDirection & (kRightDirection|kURDirection|kDRDirection)) lr = -this->width(); if (fAnimationDirection & (kUpDirection|kULDirection|kURDirection)) ud = this->height(); if (fAnimationDirection & (kDownDirection|kDLDirection|kDRDirection)) ud = -this->height(); fBegin[kPrevX] = fBegin[kPrevY] = 0; fBegin[kNextX] = lr; fBegin[kNextY] = ud; fNext->setLocX(lr); fNext->setLocY(ud); if (is_transition(fPrev)) lr = ud = 0; fEnd[kPrevX] = -lr; fEnd[kPrevY] = -ud; fEnd[kNextX] = fEnd[kNextY] = 0; SkScalar blend[] = { SkFloatToScalar(0.8f), SkFloatToScalar(0.0f), SkFloatToScalar(0.0f), SK_Scalar1 }; fInterp.setKeyFrame(0, SkTime::GetMSecs(), fBegin, blend); fInterp.setKeyFrame(1, SkTime::GetMSecs()+kDurationMS, fEnd, blend); } private: enum { kPrevX = 0, kPrevY = 1, kNextX = 2, kNextY = 3 }; SkView* fPrev; SkView* fNext; bool fDone; SkInterpolator fInterp; enum Direction{ kUpDirection = 1, kURDirection = 1 << 1, kRightDirection = 1 << 2, kDRDirection = 1 << 3, kDownDirection = 1 << 4, kDLDirection = 1 << 5, kLeftDirection = 1 << 6, kULDirection = 1 << 7 }; Direction fAnimationDirection; SkScalar fBegin[4]; SkScalar fEnd[4]; typedef SampleView INHERITED; }; SkView* create_transition(SkView* prev, SkView* next, int direction) { return SkNEW_ARGS(TransitionView, (prev, next, direction)); } <commit_msg>Disable transitions for the Android SampleApp.<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 "TransitionView.h" #include "OverView.h" #include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkTime.h" #include "SkInterpolator.h" static const char gIsTransitionQuery[] = "is-transition"; static const char gReplaceTransitionEvt[] = "replace-transition-view"; bool is_transition(SkView* view) { SkEvent isTransition(gIsTransitionQuery); return view->doQuery(&isTransition); } class TransitionView : public SampleView { enum { // kDurationMS = 500 kDurationMS = 1 }; public: TransitionView(SkView* prev, SkView* next, int direction) : fInterp(4, 2){ fAnimationDirection = (Direction)(1 << (direction % 8)); fPrev = prev; fPrev->setClipToBounds(false); fPrev->setVisibleP(true); (void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState); //Not calling unref because fPrev is assumed to have been created, so //this will result in a transfer of ownership this->attachChildToBack(fPrev); fNext = next; fNext->setClipToBounds(true); fNext->setVisibleP(true); (void)SampleView::SetUsePipe(fNext, SkOSMenu::kOffState); //Calling unref because next is a newly created view and TransitionView //is now the sole owner of fNext this->attachChildToFront(fNext)->unref(); fDone = false; //SkDebugf("--created transition\n"); } ~TransitionView(){ //SkDebugf("--deleted transition\n"); } virtual void requestMenu(SkOSMenu* menu) { if (SampleView::IsSampleView(fNext)) ((SampleView*)fNext)->requestMenu(menu); } protected: virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SkString title; if (SampleCode::RequestTitle(fNext, &title)) { SampleCode::TitleR(evt, title.c_str()); return true; } return false; } if (evt->isType(gIsTransitionQuery)) { return true; } return this->INHERITED::onQuery(evt); } virtual bool onEvent(const SkEvent& evt) { if (evt.isType(gReplaceTransitionEvt)) { fPrev->detachFromParent(); fPrev = (SkView*)SkEventSink::FindSink(evt.getFast32()); (void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState); //attach the new fPrev and call unref to balance the ref in onDraw this->attachChildToBack(fPrev)->unref(); this->inval(NULL); return true; } if (evt.isType("transition-done")) { fNext->setLoc(0, 0); fNext->setClipToBounds(false); SkEvent* evt = new SkEvent(gReplaceTransitionEvt, this->getParent()->getSinkID()); evt->setFast32(fNext->getSinkID()); //increate ref count of fNext so it survives detachAllChildren fNext->ref(); this->detachAllChildren(); evt->post(); return true; } return this->INHERITED::onEvent(evt); } virtual void onDrawBackground(SkCanvas* canvas) {} virtual void onDrawContent(SkCanvas* canvas) { if (fDone) return; if (is_overview(fNext) || is_overview(fPrev)) { fPipeState = SkOSMenu::kOffState; } SkScalar values[4]; SkInterpolator::Result result = fInterp.timeToValues(SkTime::GetMSecs(), values); //SkDebugf("transition %x %d pipe:%d\n", this, result, fUsePipe); //SkDebugf("%f %f %f %f %d\n", values[0], values[1], values[2], values[3], result); if (SkInterpolator::kNormal_Result == result) { fPrev->setLocX(values[kPrevX]); fPrev->setLocY(values[kPrevY]); fNext->setLocX(values[kNextX]); fNext->setLocY(values[kNextY]); this->inval(NULL); } else { (new SkEvent("transition-done", this->getSinkID()))->post(); fDone = true; } } virtual void onSizeChange() { this->INHERITED::onSizeChange(); fNext->setSize(this->width(), this->height()); fPrev->setSize(this->width(), this->height()); SkScalar lr = 0, ud = 0; if (fAnimationDirection & (kLeftDirection|kULDirection|kDLDirection)) lr = this->width(); if (fAnimationDirection & (kRightDirection|kURDirection|kDRDirection)) lr = -this->width(); if (fAnimationDirection & (kUpDirection|kULDirection|kURDirection)) ud = this->height(); if (fAnimationDirection & (kDownDirection|kDLDirection|kDRDirection)) ud = -this->height(); fBegin[kPrevX] = fBegin[kPrevY] = 0; fBegin[kNextX] = lr; fBegin[kNextY] = ud; fNext->setLocX(lr); fNext->setLocY(ud); if (is_transition(fPrev)) lr = ud = 0; fEnd[kPrevX] = -lr; fEnd[kPrevY] = -ud; fEnd[kNextX] = fEnd[kNextY] = 0; SkScalar blend[] = { SkFloatToScalar(0.8f), SkFloatToScalar(0.0f), SkFloatToScalar(0.0f), SK_Scalar1 }; fInterp.setKeyFrame(0, SkTime::GetMSecs(), fBegin, blend); fInterp.setKeyFrame(1, SkTime::GetMSecs()+kDurationMS, fEnd, blend); } private: enum { kPrevX = 0, kPrevY = 1, kNextX = 2, kNextY = 3 }; SkView* fPrev; SkView* fNext; bool fDone; SkInterpolator fInterp; enum Direction{ kUpDirection = 1, kURDirection = 1 << 1, kRightDirection = 1 << 2, kDRDirection = 1 << 3, kDownDirection = 1 << 4, kDLDirection = 1 << 5, kLeftDirection = 1 << 6, kULDirection = 1 << 7 }; Direction fAnimationDirection; SkScalar fBegin[4]; SkScalar fEnd[4]; typedef SampleView INHERITED; }; SkView* create_transition(SkView* prev, SkView* next, int direction) { #ifdef SK_BUILD_FOR_ANDROID // Disable transitions for Android return next; #else return SkNEW_ARGS(TransitionView, (prev, next, direction)); #endif } <|endoftext|>
<commit_before>#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <aleph/containers/PointCloud.hh> #include <aleph/config/FLANN.hh> #include <aleph/geometry/BruteForce.hh> #include <aleph/geometry/FLANN.hh> #include <aleph/geometry/VietorisRipsComplex.hh> #include <aleph/geometry/distances/Euclidean.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <aleph/topology/io/SimplicialComplexReader.hh> #include <aleph/persistenceDiagrams/PersistenceDiagram.hh> #include <aleph/persistenceDiagrams/MultiScaleKernel.hh> #include <aleph/persistenceDiagrams/distances/Bottleneck.hh> #include <aleph/persistenceDiagrams/distances/Hausdorff.hh> #include <aleph/persistenceDiagrams/distances/Wasserstein.hh> #include <aleph/persistentHomology/Calculation.hh> #include <stdexcept> namespace py = pybind11; using DataType = double; using VertexType = unsigned; using PointCloud = aleph::containers::PointCloud<DataType>; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; #ifdef ALEPH_WITH_FLANN template <class Distance> using NearestNeighbours = aleph::geometry::FLANN<PointCloud, Distance>; #else template <class Distance> using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>; #endif void wrapSimplex( py::module& m ) { py::class_<Simplex>(m, "Simplex") .def( py::init<>() ) .def( py::init<VertexType, DataType>() ) .def( py::init<Simplex, DataType>() ) .def( "__init__", [] ( Simplex& instance, py::list vertices_ ) { std::vector<VertexType> vertices; for( auto handle : vertices_ ) vertices.push_back( py::cast<VertexType>( handle ) ); new (&instance) Simplex( vertices.begin(), vertices.end() ); } ) .def( "__init__", [] ( Simplex& instance, py::list vertices_, DataType dataType ) { std::vector<VertexType> vertices; for( auto handle : vertices_ ) vertices.push_back( py::cast<VertexType>( handle ) ); new (&instance) Simplex( vertices.begin(), vertices.end(), dataType ); } ) .def( "__bool__", [] ( const Simplex& simplex ) { return !simplex.empty(); } ) .def( "__contains__", [] ( const Simplex& simplex, VertexType v ) { return simplex.contains(v); } ) .def( "__getitem__", [] ( const Simplex& simplex, VertexType i ) { return simplex[i]; } ) .def( "__iter__", [] ( const Simplex& simplex ) { return py::make_iterator( simplex.begin(), simplex.end() ); }, py::keep_alive<0,1>() ) .def( "__eq__" , &Simplex::operator== ) .def( "__ne__" , &Simplex::operator!= ) .def( "__lt__" , &Simplex::operator< ) .def( "__len__", &Simplex::size ) .def( "__repr__", [] ( const Simplex& simplex ) { std::ostringstream stream; stream << simplex; return stream.str(); } ) .def( "__reversed__", [] ( const Simplex& simplex ) { return py::make_iterator( simplex.rbegin(), simplex.rend() ); }, py::keep_alive<0,1>() ) .def_property_readonly( "boundary", [] ( const Simplex& simplex ) { return py::make_iterator( simplex.begin_boundary(), simplex.end_boundary() ); }, py::keep_alive<0,1>() ) .def_property_readonly( "dimension", &Simplex::dimension ) .def_property_readonly( "empty" , &Simplex::empty ) .def_property("data" , &Simplex::data, &Simplex::setData ) .def_property("weight", &Simplex::data, &Simplex::setData ); } void wrapSimplicialComplex( py::module& m ) { py::class_<SimplicialComplex>(m, "SimplicialComplex") .def( py::init<>() ) .def( "__init__", [] ( SimplicialComplex& instance, py::list simplices_ ) { std::vector<Simplex> simplices; for( auto simplexHandle : simplices_ ) { // Let us first try to obtain a simplex from each handle // in order to rapidly build a complex. try { auto simplex = py::cast<Simplex>( simplexHandle ); simplices.push_back( simplex ); } // Assume that the list contains only lists of vertices // and convert them directly to simplices. catch( py::cast_error& ) { std::vector<VertexType> vertices; DataType data = DataType(); try { auto&& vertices_ = py::cast<py::list>( simplexHandle ); for( auto vertexHandle : vertices_ ) vertices.push_back( py::cast<VertexType>( vertexHandle ) ); } catch( py::cast_error& ) { auto&& tuple_ = py::cast<py::tuple>( simplexHandle ); if( tuple_.size() != 2 ) throw std::runtime_error( "Unsupported number of tuple elements" ); auto&& vertices_ = py::cast<py::list>( tuple_[0] ); data = py::cast<DataType>( tuple_[1] ); for( auto vertexHandle : vertices_ ) vertices.push_back( py::cast<VertexType>( vertexHandle ) ); } simplices.push_back( Simplex( vertices.begin(), vertices.end(), data ) ); } } new (&instance) SimplicialComplex( simplices.begin(), simplices.end() ); } ) .def( "__bool__", [] ( const SimplicialComplex& K ) { return !K.empty(); } ) .def( "__contains__", &SimplicialComplex::contains ) .def( "__getitem__", &SimplicialComplex::operator[] ) // FIXME: might want to handle negative indices? .def( "__iter__", [] ( const SimplicialComplex& K ) { return py::make_iterator( K.begin(), K.end() ); }, py::keep_alive<0,1>() ) .def( "__len__", &SimplicialComplex::size ) .def( "__repr__", [] ( const SimplicialComplex& K ) { std::ostringstream stream; stream << K; return stream.str(); } ) .def( "append", &SimplicialComplex::push_back ) .def( "append", [] ( SimplicialComplex& K, py::list vertices_ ) { std::vector<VertexType> vertices; for( auto vertexHandle : vertices_ ) vertices.push_back( py::cast<VertexType>( vertexHandle ) ); K.push_back( Simplex( vertices.begin(), vertices.end() ) ); } ) .def( "sort", [] ( SimplicialComplex& K ) { K.sort(); return K; } ) .def( "sort", [] ( SimplicialComplex& K, py::function functor ) { K.sort( [&functor] ( const Simplex& s, const Simplex& t ) { return py::cast<bool>( functor(s,t) ); } ); return K; } ) .def_property_readonly( "dimension", &SimplicialComplex::dimension ); } void wrapPersistenceDiagram( py::module& m ) { py::class_<PersistenceDiagram>(m, "PersistenceDiagram") .def( py::init<>() ) .def( "__bool__", [] ( const PersistenceDiagram& D ) { return !D.empty(); } ) .def( "__eq__", &PersistenceDiagram::operator== ) .def( "__ne__", &PersistenceDiagram::operator!= ) .def( "__len__", &PersistenceDiagram::size ) .def( "__repr__", [] ( const PersistenceDiagram& D ) { std::ostringstream stream; stream << D; return stream.str(); } ) .def( "removeDiagonal", &PersistenceDiagram::removeDiagonal ) .def( "removeUnpaired", &PersistenceDiagram::removeUnpaired ) .def_property( "dimension", &PersistenceDiagram::setDimension, &PersistenceDiagram::dimension ) .def_property_readonly( "betti", &PersistenceDiagram::betti ); } void wrapPersistentHomologyCalculation( py::module& m ) { using namespace pybind11::literals; m.def( "calculatePersistenceDiagrams", [] ( const SimplicialComplex& K ) { return aleph::calculatePersistenceDiagrams( K ); } ); m.def( "calculatePersistenceDiagrams", [] ( py::buffer buffer, DataType epsilon, unsigned dimension ) { py::buffer_info bufferInfo = buffer.request(); if( bufferInfo.ndim != 2 || bufferInfo.shape.size() != 2 ) throw std::runtime_error( "Only two-dimensional buffers are supported" ); if( bufferInfo.format != py::format_descriptor<DataType>::format() ) throw std::runtime_error( "Unexpected format" ); auto n = bufferInfo.shape[0]; auto d = bufferInfo.shape[1]; PointCloud pointCloud(n,d); DataType* target = pointCloud.data(); DataType* source = reinterpret_cast<DataType*>( bufferInfo.ptr ); std::copy( source, source + n*d, target ); using Distance = aleph::distances::Euclidean<DataType>; dimension = dimension > 0 ? dimension : static_cast<unsigned>( pointCloud.dimension() + 1 ); auto K = aleph::geometry::buildVietorisRipsComplex( NearestNeighbours<Distance>( pointCloud ), epsilon, dimension ); return aleph::calculatePersistenceDiagrams( K ); }, "buffer"_a, "epsilon"_a = DataType(), "dimension"_a = 0 ); } void wrapDistanceCalculations( py::module& m ) { using namespace pybind11::literals; m.def( "bottleneckDistance", [] (const PersistenceDiagram& D1, const PersistenceDiagram& D2 ) { return aleph::distances::bottleneckDistance( D1, D2 ); } ); m.def( "hausdorffDistances", [] ( const PersistenceDiagram& D1, const PersistenceDiagram& D2 ) { return aleph::distances::hausdorffDistance( D1, D2 ); } ); m.def( "wassersteinDistance", [] ( const PersistenceDiagram& D1, const PersistenceDiagram& D2, DataType p ) { return aleph::distances::wassersteinDistance( D1, D2, p ); }, "D1"_a, "D2"_a, "p"_a = DataType(1) ); } void wrapKernelCalculations( py::module& m ) { using namespace pybind11::literals; m.def( "multiScaleKernel", [] ( const PersistenceDiagram& D1, const PersistenceDiagram& D2, double sigma ) { return aleph::multiScaleKernel( D1, D2, sigma ); } ); m.def( "multiScalePseudoMetric", [] ( const PersistenceDiagram& D1, const PersistenceDiagram& D2, double sigma ) { return aleph::multiScalePseudoMetric( D1, D2, sigma ); } ); } void wrapInputFunctions( py::module& m ) { m.def( "load", [] ( py::object object ) { std::string filename = py::cast<std::string>( object ); SimplicialComplex K; aleph::topology::io::SimplicialComplexReader reader; reader( filename, K); return K; } ); m.def( "load", [] ( py::object object, py::function functor ) { std::string filename = py::cast<std::string>( object ); SimplicialComplex K; aleph::topology::io::SimplicialComplexReader reader; reader( filename, K, [&functor] ( DataType a, DataType b ) { return py::cast<bool>( functor(a,b) ); } ); } ); } PYBIND11_PLUGIN(aleph) { py::module m("aleph", "Python bindings for Aleph, a library for exploring persistent homology"); wrapSimplex(m); wrapSimplicialComplex(m); wrapPersistenceDiagram(m); wrapPersistentHomologyCalculation(m); wrapInputFunctions(m); return m.ptr(); } <commit_msg>Added persistence diagram iterator support for Python bindings<commit_after>#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <aleph/containers/PointCloud.hh> #include <aleph/config/FLANN.hh> #include <aleph/geometry/BruteForce.hh> #include <aleph/geometry/FLANN.hh> #include <aleph/geometry/VietorisRipsComplex.hh> #include <aleph/geometry/distances/Euclidean.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <aleph/topology/io/SimplicialComplexReader.hh> #include <aleph/persistenceDiagrams/PersistenceDiagram.hh> #include <aleph/persistenceDiagrams/MultiScaleKernel.hh> #include <aleph/persistenceDiagrams/distances/Bottleneck.hh> #include <aleph/persistenceDiagrams/distances/Hausdorff.hh> #include <aleph/persistenceDiagrams/distances/Wasserstein.hh> #include <aleph/persistentHomology/Calculation.hh> #include <stdexcept> namespace py = pybind11; using DataType = double; using VertexType = unsigned; using PointCloud = aleph::containers::PointCloud<DataType>; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; #ifdef ALEPH_WITH_FLANN template <class Distance> using NearestNeighbours = aleph::geometry::FLANN<PointCloud, Distance>; #else template <class Distance> using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>; #endif void wrapSimplex( py::module& m ) { py::class_<Simplex>(m, "Simplex") .def( py::init<>() ) .def( py::init<VertexType, DataType>() ) .def( py::init<Simplex, DataType>() ) .def( "__init__", [] ( Simplex& instance, py::list vertices_ ) { std::vector<VertexType> vertices; for( auto handle : vertices_ ) vertices.push_back( py::cast<VertexType>( handle ) ); new (&instance) Simplex( vertices.begin(), vertices.end() ); } ) .def( "__init__", [] ( Simplex& instance, py::list vertices_, DataType dataType ) { std::vector<VertexType> vertices; for( auto handle : vertices_ ) vertices.push_back( py::cast<VertexType>( handle ) ); new (&instance) Simplex( vertices.begin(), vertices.end(), dataType ); } ) .def( "__bool__", [] ( const Simplex& simplex ) { return !simplex.empty(); } ) .def( "__contains__", [] ( const Simplex& simplex, VertexType v ) { return simplex.contains(v); } ) .def( "__getitem__", [] ( const Simplex& simplex, VertexType i ) { return simplex[i]; } ) .def( "__iter__", [] ( const Simplex& simplex ) { return py::make_iterator( simplex.begin(), simplex.end() ); }, py::keep_alive<0,1>() ) .def( "__eq__" , &Simplex::operator== ) .def( "__ne__" , &Simplex::operator!= ) .def( "__lt__" , &Simplex::operator< ) .def( "__len__", &Simplex::size ) .def( "__repr__", [] ( const Simplex& simplex ) { std::ostringstream stream; stream << simplex; return stream.str(); } ) .def( "__reversed__", [] ( const Simplex& simplex ) { return py::make_iterator( simplex.rbegin(), simplex.rend() ); }, py::keep_alive<0,1>() ) .def_property_readonly( "boundary", [] ( const Simplex& simplex ) { return py::make_iterator( simplex.begin_boundary(), simplex.end_boundary() ); }, py::keep_alive<0,1>() ) .def_property_readonly( "dimension", &Simplex::dimension ) .def_property_readonly( "empty" , &Simplex::empty ) .def_property("data" , &Simplex::data, &Simplex::setData ) .def_property("weight", &Simplex::data, &Simplex::setData ); } void wrapSimplicialComplex( py::module& m ) { py::class_<SimplicialComplex>(m, "SimplicialComplex") .def( py::init<>() ) .def( "__init__", [] ( SimplicialComplex& instance, py::list simplices_ ) { std::vector<Simplex> simplices; for( auto simplexHandle : simplices_ ) { // Let us first try to obtain a simplex from each handle // in order to rapidly build a complex. try { auto simplex = py::cast<Simplex>( simplexHandle ); simplices.push_back( simplex ); } // Assume that the list contains only lists of vertices // and convert them directly to simplices. catch( py::cast_error& ) { std::vector<VertexType> vertices; DataType data = DataType(); try { auto&& vertices_ = py::cast<py::list>( simplexHandle ); for( auto vertexHandle : vertices_ ) vertices.push_back( py::cast<VertexType>( vertexHandle ) ); } catch( py::cast_error& ) { auto&& tuple_ = py::cast<py::tuple>( simplexHandle ); if( tuple_.size() != 2 ) throw std::runtime_error( "Unsupported number of tuple elements" ); auto&& vertices_ = py::cast<py::list>( tuple_[0] ); data = py::cast<DataType>( tuple_[1] ); for( auto vertexHandle : vertices_ ) vertices.push_back( py::cast<VertexType>( vertexHandle ) ); } simplices.push_back( Simplex( vertices.begin(), vertices.end(), data ) ); } } new (&instance) SimplicialComplex( simplices.begin(), simplices.end() ); } ) .def( "__bool__", [] ( const SimplicialComplex& K ) { return !K.empty(); } ) .def( "__contains__", &SimplicialComplex::contains ) .def( "__getitem__", &SimplicialComplex::operator[] ) // FIXME: might want to handle negative indices? .def( "__iter__", [] ( const SimplicialComplex& K ) { return py::make_iterator( K.begin(), K.end() ); }, py::keep_alive<0,1>() ) .def( "__len__", &SimplicialComplex::size ) .def( "__repr__", [] ( const SimplicialComplex& K ) { std::ostringstream stream; stream << K; return stream.str(); } ) .def( "append", &SimplicialComplex::push_back ) .def( "append", [] ( SimplicialComplex& K, py::list vertices_ ) { std::vector<VertexType> vertices; for( auto vertexHandle : vertices_ ) vertices.push_back( py::cast<VertexType>( vertexHandle ) ); K.push_back( Simplex( vertices.begin(), vertices.end() ) ); } ) .def( "sort", [] ( SimplicialComplex& K ) { K.sort(); return K; } ) .def( "sort", [] ( SimplicialComplex& K, py::function functor ) { K.sort( [&functor] ( const Simplex& s, const Simplex& t ) { return py::cast<bool>( functor(s,t) ); } ); return K; } ) .def_property_readonly( "dimension", &SimplicialComplex::dimension ); } void wrapPersistenceDiagram( py::module& m ) { py::class_<PersistenceDiagram>(m, "PersistenceDiagram") .def( py::init<>() ) .def( "__bool__", [] ( const PersistenceDiagram& D ) { return !D.empty(); } ) .def( "__eq__", &PersistenceDiagram::operator== ) .def( "__ne__", &PersistenceDiagram::operator!= ) .def( "__len__", &PersistenceDiagram::size ) .def( "__iter__", [] ( const PersistenceDiagram& D ) { return py::make_iterator( D.begin(), D.end() ); }, py::keep_alive<0,1>() ) .def( "__repr__", [] ( const PersistenceDiagram& D ) { std::ostringstream stream; stream << D; return stream.str(); } ) .def( "removeDiagonal", &PersistenceDiagram::removeDiagonal ) .def( "removeUnpaired", &PersistenceDiagram::removeUnpaired ) .def_property( "dimension", &PersistenceDiagram::setDimension, &PersistenceDiagram::dimension ) .def_property_readonly( "betti", &PersistenceDiagram::betti ); using Point = typename PersistenceDiagram::Point; py::class_<Point>(m, "PersistenceDiagram.Point" ) .def( py::init<DataType>() ) .def( py::init<DataType, DataType>() ) .def( "__eq__", &Point::operator== ) .def( "__ne__", &Point::operator!= ) .def( "__repr__", [] ( const Point& p ) { return "<" + std::to_string( p.x() ) + "," + std::to_string( p.y() ) + ">"; } ) .def_property_readonly( "x", &Point::x ) .def_property_readonly( "y", &Point::y ) .def_property_readonly( "persistence", &Point::persistence ) .def_property_readonly( "unpaired" , &Point::isUnpaired ); } void wrapPersistentHomologyCalculation( py::module& m ) { using namespace pybind11::literals; m.def( "calculatePersistenceDiagrams", [] ( const SimplicialComplex& K ) { return aleph::calculatePersistenceDiagrams( K ); } ); m.def( "calculatePersistenceDiagrams", [] ( py::buffer buffer, DataType epsilon, unsigned dimension ) { py::buffer_info bufferInfo = buffer.request(); if( bufferInfo.ndim != 2 || bufferInfo.shape.size() != 2 ) throw std::runtime_error( "Only two-dimensional buffers are supported" ); if( bufferInfo.format != py::format_descriptor<DataType>::format() ) throw std::runtime_error( "Unexpected format" ); auto n = bufferInfo.shape[0]; auto d = bufferInfo.shape[1]; PointCloud pointCloud(n,d); DataType* target = pointCloud.data(); DataType* source = reinterpret_cast<DataType*>( bufferInfo.ptr ); std::copy( source, source + n*d, target ); using Distance = aleph::distances::Euclidean<DataType>; dimension = dimension > 0 ? dimension : static_cast<unsigned>( pointCloud.dimension() + 1 ); auto K = aleph::geometry::buildVietorisRipsComplex( NearestNeighbours<Distance>( pointCloud ), epsilon, dimension ); return aleph::calculatePersistenceDiagrams( K ); }, "buffer"_a, "epsilon"_a = DataType(), "dimension"_a = 0 ); } void wrapDistanceCalculations( py::module& m ) { using namespace pybind11::literals; m.def( "bottleneckDistance", [] (const PersistenceDiagram& D1, const PersistenceDiagram& D2 ) { return aleph::distances::bottleneckDistance( D1, D2 ); } ); m.def( "hausdorffDistances", [] ( const PersistenceDiagram& D1, const PersistenceDiagram& D2 ) { return aleph::distances::hausdorffDistance( D1, D2 ); } ); m.def( "wassersteinDistance", [] ( const PersistenceDiagram& D1, const PersistenceDiagram& D2, DataType p ) { return aleph::distances::wassersteinDistance( D1, D2, p ); }, "D1"_a, "D2"_a, "p"_a = DataType(1) ); } void wrapKernelCalculations( py::module& m ) { using namespace pybind11::literals; m.def( "multiScaleKernel", [] ( const PersistenceDiagram& D1, const PersistenceDiagram& D2, double sigma ) { return aleph::multiScaleKernel( D1, D2, sigma ); } ); m.def( "multiScalePseudoMetric", [] ( const PersistenceDiagram& D1, const PersistenceDiagram& D2, double sigma ) { return aleph::multiScalePseudoMetric( D1, D2, sigma ); } ); } void wrapInputFunctions( py::module& m ) { m.def( "load", [] ( py::object object ) { std::string filename = py::cast<std::string>( object ); SimplicialComplex K; aleph::topology::io::SimplicialComplexReader reader; reader( filename, K); return K; } ); m.def( "load", [] ( py::object object, py::function functor ) { std::string filename = py::cast<std::string>( object ); SimplicialComplex K; aleph::topology::io::SimplicialComplexReader reader; reader( filename, K, [&functor] ( DataType a, DataType b ) { return py::cast<bool>( functor(a,b) ); } ); } ); } PYBIND11_PLUGIN(aleph) { py::module m("aleph", "Python bindings for Aleph, a library for exploring persistent homology"); wrapSimplex(m); wrapSimplicialComplex(m); wrapPersistenceDiagram(m); wrapPersistentHomologyCalculation(m); wrapInputFunctions(m); return m.ptr(); } <|endoftext|>
<commit_before><commit_msg>Some followup cleanup now that these methods are in the formula cell only.<commit_after><|endoftext|>
<commit_before><commit_msg>surely this check should preceed deref of pActiveViewSh<commit_after><|endoftext|>
<commit_before><commit_msg>fdo#56098 Paste Special options after cut incorrect<commit_after><|endoftext|>
<commit_before>#include "mastercard.h" #include "glodec.h" #include "conarray.h" bool luhn_test(int card_number)//verify mastercard { int s1; int s2; int s3; std::vector<int> card_vector; std::vector<int> card_reverse; std::vector<int> even_digits; conarray::conarray(13, card_number, card_vector, card_reverse); for (int i = 0; i < card_reverse.max_size; i = i + 2) { //getting sum of all the odd digits s1 += card_reverse.at(i); } even_digits.resize(card_vector.size / 2); for (int i = 1; i < card_reverse.size; i=+2) { //doubling the even digits int n = 0; //this is the position for the vector even_digits.at(n) = (card_reverse.at(i) * 2); } for (int i = even_digits.size; i >= 0; i++) { s2 += even_digits.at(i); } s3 = s1 + s2; if (s3 % 10 == 0) { return true; } else { return false; } } <commit_msg>update mastercard.cpp<commit_after>#include "mastercard.h" #include "glodec.h" #include "conarray.h" bool luhn_test(int card_number)//verify mastercard { int s1; int s2; int s3; std::vector<int> card_vector; std::vector<int> card_reverse; std::vector<int> even_digits; conarray::conarray(13, card_number, card_vector, card_reverse); for (int i = 0; i < card_reverse.max_size; i = i + 2) { //getting sum of all the odd digits s1 += card_reverse.at(i); } even_digits.resize(card_vector.size / 2); for (int i = 1; i < card_reverse.size; i=+2) { //doubling the even digits int n = 0; //this is the position for the vector n++; even_digits.at(n) = (card_reverse.at(i) * 2); } for (int i = even_digits.size; i >= 0; i++) { s2 += even_digits.at(i); } s3 = s1 + s2; if (s3 % 10 == 0) { return true; } else { return false; } } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/memory/scoped_vector.h" #include "base/synchronization/condition_variable.h" #include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/perf/perf_test.h" #if defined(OS_POSIX) #include <pthread.h> #endif namespace base { namespace { const int kNumRuns = 100000; // Base class for a threading perf-test. This sets up some threads for the // test and measures the clock-time in addition to time spent on each thread. class ThreadPerfTest : public testing::Test { public: ThreadPerfTest() : done_(false, false) { // Disable the task profiler as it adds significant cost! CommandLine::Init(0, NULL); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kProfilerTiming, switches::kProfilerTimingDisabledValue); } // To be implemented by each test. Subclass must uses threads_ such that // their cpu-time can be measured. Test must return from PingPong() _and_ // call FinishMeasurement from any thread to complete the test. virtual void Init() {} virtual void PingPong(int hops) = 0; virtual void Reset() {} void TimeOnThread(base::TimeTicks* ticks, base::WaitableEvent* done) { *ticks = base::TimeTicks::ThreadNow(); done->Signal(); } base::TimeTicks ThreadNow(base::Thread* thread) { base::WaitableEvent done(false, false); base::TimeTicks ticks; thread->message_loop_proxy()->PostTask( FROM_HERE, base::Bind(&ThreadPerfTest::TimeOnThread, base::Unretained(this), &ticks, &done)); done.Wait(); return ticks; } void RunPingPongTest(const std::string& name, unsigned num_threads) { // Create threads and collect starting cpu-time for each thread. std::vector<base::TimeTicks> thread_starts; while (threads_.size() < num_threads) { threads_.push_back(new base::Thread("PingPonger")); threads_.back()->Start(); if (base::TimeTicks::IsThreadNowSupported()) thread_starts.push_back(ThreadNow(threads_.back())); } Init(); base::TimeTicks start = base::TimeTicks::HighResNow(); PingPong(kNumRuns); done_.Wait(); base::TimeTicks end = base::TimeTicks::HighResNow(); // Gather the cpu-time spent on each thread. This does one extra tasks, // but that should be in the noise given enough runs. base::TimeDelta thread_time; while (threads_.size()) { if (base::TimeTicks::IsThreadNowSupported()) { thread_time += ThreadNow(threads_.back()) - thread_starts.back(); thread_starts.pop_back(); } threads_.pop_back(); } Reset(); double num_runs = static_cast<double>(kNumRuns); double us_per_task_clock = (end - start).InMicroseconds() / num_runs; double us_per_task_cpu = thread_time.InMicroseconds() / num_runs; // Clock time per task. perf_test::PrintResult( "task", "", name + "_time ", us_per_task_clock, "us/hop", true); // Total utilization across threads if available (likely higher). if (base::TimeTicks::IsThreadNowSupported()) { perf_test::PrintResult( "task", "", name + "_cpu ", us_per_task_cpu, "us/hop", true); } } protected: void FinishMeasurement() { done_.Signal(); } ScopedVector<base::Thread> threads_; private: base::WaitableEvent done_; }; // Class to test task performance by posting empty tasks back and forth. class TaskPerfTest : public ThreadPerfTest { base::Thread* NextThread(int count) { return threads_[count % threads_.size()]; } virtual void PingPong(int hops) OVERRIDE { if (!hops) { FinishMeasurement(); return; } NextThread(hops)->message_loop_proxy()->PostTask( FROM_HERE, base::Bind( &ThreadPerfTest::PingPong, base::Unretained(this), hops - 1)); } }; // This tries to test the 'best-case' as well as the 'worst-case' task posting // performance. The best-case keeps one thread alive such that it never yeilds, // while the worse-case forces a context switch for every task. Four threads are // used to ensure the threads do yeild (with just two it might be possible for // both threads to stay awake if they can signal each other fast enough). TEST_F(TaskPerfTest, TaskPingPong) { RunPingPongTest("1_Task_Threads", 1); RunPingPongTest("4_Task_Threads", 4); } // Class to test our WaitableEvent performance by signaling back and fort. // WaitableEvent is templated so we can also compare with other versions. template <typename WaitableEventType> class EventPerfTest : public ThreadPerfTest { public: virtual void Init() OVERRIDE { for (size_t i = 0; i < threads_.size(); i++) events_.push_back(new WaitableEventType(false, false)); } virtual void Reset() OVERRIDE { events_.clear(); } void WaitAndSignalOnThread(size_t event) { size_t next_event = (event + 1) % events_.size(); int my_hops = 0; do { events_[event]->Wait(); my_hops = --remaining_hops_; // We own 'hops' between Wait and Signal. events_[next_event]->Signal(); } while (my_hops > 0); // Once we are done, all threads will signal as hops passes zero. // We only signal completion once, on the thread that reaches zero. if (!my_hops) FinishMeasurement(); } virtual void PingPong(int hops) OVERRIDE { remaining_hops_ = hops; for (size_t i = 0; i < threads_.size(); i++) { threads_[i]->message_loop_proxy()->PostTask( FROM_HERE, base::Bind(&EventPerfTest::WaitAndSignalOnThread, base::Unretained(this), i)); } // Kick off the Signal ping-ponging. events_.front()->Signal(); } int remaining_hops_; ScopedVector<WaitableEventType> events_; }; // Similar to the task posting test, this just tests similar functionality // using WaitableEvents. We only test four threads (worst-case), but we // might want to craft a way to test the best-case (where the thread doesn't // end up blocking because the event is already signalled). typedef EventPerfTest<base::WaitableEvent> WaitableEventPerfTest; TEST_F(WaitableEventPerfTest, EventPingPong) { RunPingPongTest("4_WaitableEvent_Threads", 4); } // Build a minimal event using ConditionVariable. class ConditionVariableEvent { public: ConditionVariableEvent(bool manual_reset, bool initially_signaled) : cond_(&lock_), signaled_(false) { DCHECK(!manual_reset); DCHECK(!initially_signaled); } void Signal() { { base::AutoLock scoped_lock(lock_); signaled_ = true; } cond_.Signal(); } void Wait() { base::AutoLock scoped_lock(lock_); while (!signaled_) cond_.Wait(); signaled_ = false; } private: base::Lock lock_; base::ConditionVariable cond_; bool signaled_; }; // This is meant to test the absolute minimal context switching time // using our own base synchronization code. typedef EventPerfTest<ConditionVariableEvent> ConditionVariablePerfTest; TEST_F(ConditionVariablePerfTest, EventPingPong) { RunPingPongTest("4_ConditionVariable_Threads", 4); } #if defined(OS_POSIX) // Absolutely 100% minimal posix waitable event. If there is a better/faster // way to force a context switch, we should use that instead. class PthreadEvent { public: PthreadEvent(bool manual_reset, bool initially_signaled) { DCHECK(!manual_reset); DCHECK(!initially_signaled); pthread_mutex_init(&mutex_, 0); pthread_cond_init(&cond_, 0); signaled_ = false; } ~PthreadEvent() { pthread_cond_destroy(&cond_); pthread_mutex_destroy(&mutex_); } void Signal() { pthread_mutex_lock(&mutex_); signaled_ = true; pthread_mutex_unlock(&mutex_); pthread_cond_signal(&cond_); } void Wait() { pthread_mutex_lock(&mutex_); while (!signaled_) pthread_cond_wait(&cond_, &mutex_); signaled_ = false; pthread_mutex_unlock(&mutex_); } private: bool signaled_; pthread_mutex_t mutex_; pthread_cond_t cond_; }; // This is meant to test the absolute minimal context switching time. // If there is any faster way to do this we should substitute it in. typedef EventPerfTest<PthreadEvent> PthreadEventPerfTest; TEST_F(PthreadEventPerfTest, EventPingPong) { RunPingPongTest("4_PthreadCondVar_Threads", 4); } #endif } // namespace } // namespace base <commit_msg>base: Test the cost of adding observers on message loops.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/memory/scoped_vector.h" #include "base/synchronization/condition_variable.h" #include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/perf/perf_test.h" #if defined(OS_POSIX) #include <pthread.h> #endif namespace base { namespace { const int kNumRuns = 100000; // Base class for a threading perf-test. This sets up some threads for the // test and measures the clock-time in addition to time spent on each thread. class ThreadPerfTest : public testing::Test { public: ThreadPerfTest() : done_(false, false) { // Disable the task profiler as it adds significant cost! CommandLine::Init(0, NULL); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kProfilerTiming, switches::kProfilerTimingDisabledValue); } // To be implemented by each test. Subclass must uses threads_ such that // their cpu-time can be measured. Test must return from PingPong() _and_ // call FinishMeasurement from any thread to complete the test. virtual void Init() {} virtual void PingPong(int hops) = 0; virtual void Reset() {} void TimeOnThread(base::TimeTicks* ticks, base::WaitableEvent* done) { *ticks = base::TimeTicks::ThreadNow(); done->Signal(); } base::TimeTicks ThreadNow(base::Thread* thread) { base::WaitableEvent done(false, false); base::TimeTicks ticks; thread->message_loop_proxy()->PostTask( FROM_HERE, base::Bind(&ThreadPerfTest::TimeOnThread, base::Unretained(this), &ticks, &done)); done.Wait(); return ticks; } void RunPingPongTest(const std::string& name, unsigned num_threads) { // Create threads and collect starting cpu-time for each thread. std::vector<base::TimeTicks> thread_starts; while (threads_.size() < num_threads) { threads_.push_back(new base::Thread("PingPonger")); threads_.back()->Start(); if (base::TimeTicks::IsThreadNowSupported()) thread_starts.push_back(ThreadNow(threads_.back())); } Init(); base::TimeTicks start = base::TimeTicks::HighResNow(); PingPong(kNumRuns); done_.Wait(); base::TimeTicks end = base::TimeTicks::HighResNow(); // Gather the cpu-time spent on each thread. This does one extra tasks, // but that should be in the noise given enough runs. base::TimeDelta thread_time; while (threads_.size()) { if (base::TimeTicks::IsThreadNowSupported()) { thread_time += ThreadNow(threads_.back()) - thread_starts.back(); thread_starts.pop_back(); } threads_.pop_back(); } Reset(); double num_runs = static_cast<double>(kNumRuns); double us_per_task_clock = (end - start).InMicroseconds() / num_runs; double us_per_task_cpu = thread_time.InMicroseconds() / num_runs; // Clock time per task. perf_test::PrintResult( "task", "", name + "_time ", us_per_task_clock, "us/hop", true); // Total utilization across threads if available (likely higher). if (base::TimeTicks::IsThreadNowSupported()) { perf_test::PrintResult( "task", "", name + "_cpu ", us_per_task_cpu, "us/hop", true); } } protected: void FinishMeasurement() { done_.Signal(); } ScopedVector<base::Thread> threads_; private: base::WaitableEvent done_; }; // Class to test task performance by posting empty tasks back and forth. class TaskPerfTest : public ThreadPerfTest { base::Thread* NextThread(int count) { return threads_[count % threads_.size()]; } virtual void PingPong(int hops) OVERRIDE { if (!hops) { FinishMeasurement(); return; } NextThread(hops)->message_loop_proxy()->PostTask( FROM_HERE, base::Bind( &ThreadPerfTest::PingPong, base::Unretained(this), hops - 1)); } }; // This tries to test the 'best-case' as well as the 'worst-case' task posting // performance. The best-case keeps one thread alive such that it never yeilds, // while the worse-case forces a context switch for every task. Four threads are // used to ensure the threads do yeild (with just two it might be possible for // both threads to stay awake if they can signal each other fast enough). TEST_F(TaskPerfTest, TaskPingPong) { RunPingPongTest("1_Task_Threads", 1); RunPingPongTest("4_Task_Threads", 4); } // Same as above, but add observers to test their perf impact. class MessageLoopObserver : public base::MessageLoop::TaskObserver { public: virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE { } virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE { } }; MessageLoopObserver message_loop_observer; class TaskObserverPerfTest : public TaskPerfTest { public: virtual void Init() OVERRIDE { TaskPerfTest::Init(); for (size_t i = 0; i < threads_.size(); i++) { threads_[i]->message_loop()->AddTaskObserver(&message_loop_observer); } } }; TEST_F(TaskObserverPerfTest, TaskPingPong) { RunPingPongTest("1_Task_Threads_With_Observer", 1); RunPingPongTest("4_Task_Threads_With_Observer", 4); } // Class to test our WaitableEvent performance by signaling back and fort. // WaitableEvent is templated so we can also compare with other versions. template <typename WaitableEventType> class EventPerfTest : public ThreadPerfTest { public: virtual void Init() OVERRIDE { for (size_t i = 0; i < threads_.size(); i++) events_.push_back(new WaitableEventType(false, false)); } virtual void Reset() OVERRIDE { events_.clear(); } void WaitAndSignalOnThread(size_t event) { size_t next_event = (event + 1) % events_.size(); int my_hops = 0; do { events_[event]->Wait(); my_hops = --remaining_hops_; // We own 'hops' between Wait and Signal. events_[next_event]->Signal(); } while (my_hops > 0); // Once we are done, all threads will signal as hops passes zero. // We only signal completion once, on the thread that reaches zero. if (!my_hops) FinishMeasurement(); } virtual void PingPong(int hops) OVERRIDE { remaining_hops_ = hops; for (size_t i = 0; i < threads_.size(); i++) { threads_[i]->message_loop_proxy()->PostTask( FROM_HERE, base::Bind(&EventPerfTest::WaitAndSignalOnThread, base::Unretained(this), i)); } // Kick off the Signal ping-ponging. events_.front()->Signal(); } int remaining_hops_; ScopedVector<WaitableEventType> events_; }; // Similar to the task posting test, this just tests similar functionality // using WaitableEvents. We only test four threads (worst-case), but we // might want to craft a way to test the best-case (where the thread doesn't // end up blocking because the event is already signalled). typedef EventPerfTest<base::WaitableEvent> WaitableEventPerfTest; TEST_F(WaitableEventPerfTest, EventPingPong) { RunPingPongTest("4_WaitableEvent_Threads", 4); } // Build a minimal event using ConditionVariable. class ConditionVariableEvent { public: ConditionVariableEvent(bool manual_reset, bool initially_signaled) : cond_(&lock_), signaled_(false) { DCHECK(!manual_reset); DCHECK(!initially_signaled); } void Signal() { { base::AutoLock scoped_lock(lock_); signaled_ = true; } cond_.Signal(); } void Wait() { base::AutoLock scoped_lock(lock_); while (!signaled_) cond_.Wait(); signaled_ = false; } private: base::Lock lock_; base::ConditionVariable cond_; bool signaled_; }; // This is meant to test the absolute minimal context switching time // using our own base synchronization code. typedef EventPerfTest<ConditionVariableEvent> ConditionVariablePerfTest; TEST_F(ConditionVariablePerfTest, EventPingPong) { RunPingPongTest("4_ConditionVariable_Threads", 4); } #if defined(OS_POSIX) // Absolutely 100% minimal posix waitable event. If there is a better/faster // way to force a context switch, we should use that instead. class PthreadEvent { public: PthreadEvent(bool manual_reset, bool initially_signaled) { DCHECK(!manual_reset); DCHECK(!initially_signaled); pthread_mutex_init(&mutex_, 0); pthread_cond_init(&cond_, 0); signaled_ = false; } ~PthreadEvent() { pthread_cond_destroy(&cond_); pthread_mutex_destroy(&mutex_); } void Signal() { pthread_mutex_lock(&mutex_); signaled_ = true; pthread_mutex_unlock(&mutex_); pthread_cond_signal(&cond_); } void Wait() { pthread_mutex_lock(&mutex_); while (!signaled_) pthread_cond_wait(&cond_, &mutex_); signaled_ = false; pthread_mutex_unlock(&mutex_); } private: bool signaled_; pthread_mutex_t mutex_; pthread_cond_t cond_; }; // This is meant to test the absolute minimal context switching time. // If there is any faster way to do this we should substitute it in. typedef EventPerfTest<PthreadEvent> PthreadEventPerfTest; TEST_F(PthreadEventPerfTest, EventPingPong) { RunPingPongTest("4_PthreadCondVar_Threads", 4); } #endif } // namespace } // namespace base <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <map> #include "base/command_line.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_number_conversions.h" #include "base/test/test_timeouts.h" #include "base/test/trace_event_analyzer.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/automation_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/javascript_test_util.h" #include "chrome/test/ui/ui_perf_test.h" #include "net/base/net_util.h" #include "ui/gfx/gl/gl_implementation.h" #include "ui/gfx/gl/gl_switches.h" namespace { enum FrameRateTestFlags { kUseGpu = 1 << 0, // Only execute test if --enable-gpu, and verify // that test ran on GPU. This is required for // tests that run on GPU. kForceGpuComposited = 1 << 1, // Force the test to use the compositor. kDisableVsync = 1 << 2, // Do not limit framerate to vertical refresh. // when on GPU, nor to 60hz when not on GPU. kUseReferenceBuild = 1 << 3, // Run test using the reference chrome build. kInternal = 1 << 4, // Test uses internal test data. kHasRedirect = 1 << 5, // Test page contains an HTML redirect. }; class FrameRateTest : public UIPerfTest , public ::testing::WithParamInterface<int> { public: FrameRateTest() { show_window_ = true; dom_automation_enabled_ = true; } bool HasFlag(FrameRateTestFlags flag) const { return (GetParam() & flag) == flag; } bool IsGpuAvailable() const { return CommandLine::ForCurrentProcess()->HasSwitch("enable-gpu"); } std::string GetSuffixForTestFlags() { std::string suffix; if (HasFlag(kForceGpuComposited)) suffix += "_comp"; if (HasFlag(kUseGpu)) suffix += "_gpu"; if (HasFlag(kDisableVsync)) suffix += "_novsync"; if (HasFlag(kUseReferenceBuild)) suffix += "_ref"; return suffix; } virtual FilePath GetDataPath(const std::string& name) { // Make sure the test data is checked out. FilePath test_path; PathService::Get(chrome::DIR_TEST_DATA, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("perf")); test_path = test_path.Append(FILE_PATH_LITERAL("frame_rate")); if (HasFlag(kInternal)) { test_path = test_path.Append(FILE_PATH_LITERAL("private")); } else { test_path = test_path.Append(FILE_PATH_LITERAL("content")); } test_path = test_path.AppendASCII(name); return test_path; } virtual void SetUp() { if (HasFlag(kUseReferenceBuild)) UseReferenceBuild(); // Turn on chrome.Interval to get higher-resolution timestamps on frames. launch_arguments_.AppendSwitch(switches::kEnableBenchmarking); // Required additional argument to make the kEnableBenchmarking switch work. launch_arguments_.AppendSwitch(switches::kEnableStatsTable); // UI tests boot up render views starting from about:blank. This causes // the renderer to start up thinking it cannot use the GPU. To work // around that, and allow the frame rate test to use the GPU, we must // pass kAllowWebUICompositing. launch_arguments_.AppendSwitch(switches::kAllowWebUICompositing); // Some of the tests may launch http requests through JSON or AJAX // which causes a security error (cross domain request) when the page // is loaded from the local file system ( file:// ). The following switch // fixes that error. launch_arguments_.AppendSwitch(switches::kAllowFileAccessFromFiles); if (!HasFlag(kUseGpu)) { launch_arguments_.AppendSwitch(switches::kDisableAcceleratedCompositing); launch_arguments_.AppendSwitch(switches::kDisableExperimentalWebGL); launch_arguments_.AppendSwitch(switches::kDisableAccelerated2dCanvas); } else { // This switch is required for enabling the accelerated 2d canvas on // Chrome versions prior to Chrome 15, which may be the case for the // reference build. launch_arguments_.AppendSwitch(switches::kEnableAccelerated2dCanvas); } if (HasFlag(kDisableVsync)) launch_arguments_.AppendSwitch(switches::kDisableGpuVsync); UIPerfTest::SetUp(); } bool DidRunOnGpu(const std::string& json_events) { using namespace trace_analyzer; // Check trace for GPU accleration. scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events)); gfx::GLImplementation gl_impl = gfx::kGLImplementationNone; const TraceEvent* gpu_event = analyzer->FindOneEvent( Query(EVENT_NAME) == Query::String("SwapBuffers") && Query(EVENT_HAS_NUMBER_ARG, "GLImpl")); if (gpu_event) gl_impl = static_cast<gfx::GLImplementation>( gpu_event->GetKnownArgAsInt("GLImpl")); return (gl_impl == gfx::kGLImplementationDesktopGL || gl_impl == gfx::kGLImplementationEGLGLES2); } void RunTest(const std::string& name) { if (HasFlag(kUseGpu) && !IsGpuAvailable()) { printf("Test skipped: requires gpu. Pass --enable-gpu on the command " "line if use of GPU is desired.\n"); return; } // Verify flag combinations. ASSERT_TRUE(HasFlag(kUseGpu) || !HasFlag(kForceGpuComposited)); ASSERT_TRUE(!HasFlag(kUseGpu) || IsGpuAvailable()); FilePath test_path = GetDataPath(name); ASSERT_TRUE(file_util::DirectoryExists(test_path)) << "Missing test directory: " << test_path.value(); test_path = test_path.Append(FILE_PATH_LITERAL("test.html")); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); // TODO(jbates): remove this check when ref builds are updated. if (!HasFlag(kUseReferenceBuild)) ASSERT_TRUE(automation()->BeginTracing("test_gpu")); if (HasFlag(kHasRedirect)) { // If the test file is known to contain an html redirect, we must block // until the second navigation is complete and reacquire the active tab // in order to avoid a race condition. // If the following assertion is triggered due to a timeout, it is // possible that the current test does not re-direct and therefore should // not have the kHasRedirect flag turned on. ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURLBlockUntilNavigationsComplete( net::FilePathToFileURL(test_path), 2)); tab = GetActiveTab(); ASSERT_TRUE(tab.get()); } else { ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(net::FilePathToFileURL(test_path))); } // Block until initialization completes // If the following assertion fails intermittently, it could be due to a // race condition caused by an html redirect. If that is the case, verify // that flag kHasRedirect is enabled for the current test. ASSERT_TRUE(WaitUntilJavaScriptCondition( tab, L"", L"window.domAutomationController.send(__initialized);", TestTimeouts::large_test_timeout_ms())); if (HasFlag(kForceGpuComposited)) { ASSERT_TRUE(tab->NavigateToURLAsync( GURL("javascript:__make_body_composited();"))); } // Start the tests. ASSERT_TRUE(tab->NavigateToURLAsync(GURL("javascript:__start_all();"))); // Block until the tests completes. ASSERT_TRUE(WaitUntilJavaScriptCondition( tab, L"", L"window.domAutomationController.send(!__running_all);", TestTimeouts::large_test_timeout_ms())); // TODO(jbates): remove this check when ref builds are updated. if (!HasFlag(kUseReferenceBuild)) { std::string json_events; ASSERT_TRUE(automation()->EndTracing(&json_events)); bool did_run_on_gpu = DidRunOnGpu(json_events); bool expect_gpu = HasFlag(kUseGpu); EXPECT_EQ(expect_gpu, did_run_on_gpu); } // Read out the results. std::wstring json; ASSERT_TRUE(tab->ExecuteAndExtractString( L"", L"window.domAutomationController.send(" L"JSON.stringify(__calc_results_total()));", &json)); std::map<std::string, std::string> results; ASSERT_TRUE(JsonDictionaryToMap(WideToUTF8(json), &results)); ASSERT_TRUE(results.find("mean") != results.end()); ASSERT_TRUE(results.find("sigma") != results.end()); ASSERT_TRUE(results.find("gestures") != results.end()); ASSERT_TRUE(results.find("means") != results.end()); ASSERT_TRUE(results.find("sigmas") != results.end()); std::string trace_name = "interval" + GetSuffixForTestFlags(); printf("GESTURES %s: %s= [%s] [%s] [%s]\n", name.c_str(), trace_name.c_str(), results["gestures"].c_str(), results["means"].c_str(), results["sigmas"].c_str()); std::string mean_and_error = results["mean"] + "," + results["sigma"]; PrintResultMeanAndError(name, "", trace_name, mean_and_error, "frames-per-second", true); } }; // Must use a different class name to avoid test instantiation conflicts // with FrameRateTest. An alias is good enough. The alias names must match // the pattern FrameRate*Test* for them to get picked up by the test bots. typedef FrameRateTest FrameRateCompositingTest; // Tests that trigger compositing with a -webkit-translateZ(0) #define FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(content) \ TEST_P(FrameRateCompositingTest, content) { \ RunTest(#content); \ } INSTANTIATE_TEST_CASE_P(, FrameRateCompositingTest, ::testing::Values( 0, kUseGpu | kForceGpuComposited, kUseReferenceBuild, kUseReferenceBuild | kUseGpu | kForceGpuComposited)); FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(blank); FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(googleblog); typedef FrameRateTest FrameRateNoVsyncCanvasInternalTest; // Tests for animated 2D canvas content with and without disabling vsync #define INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(content) \ TEST_P(FrameRateNoVsyncCanvasInternalTest, content) { \ RunTest(#content); \ } INSTANTIATE_TEST_CASE_P(, FrameRateNoVsyncCanvasInternalTest, ::testing::Values( kInternal | kHasRedirect, kInternal | kHasRedirect | kUseGpu, kInternal | kHasRedirect | kUseGpu | kDisableVsync, kUseReferenceBuild | kInternal | kHasRedirect, kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu, kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu | kDisableVsync)); INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(fishbowl) typedef FrameRateTest FrameRateGpuCanvasInternalTest; // Tests for animated 2D canvas content to be tested only with GPU // acceleration. // tests are run with and without Vsync #define INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(content) \ TEST_P(FrameRateGpuCanvasInternalTest, content) { \ RunTest(#content); \ } INSTANTIATE_TEST_CASE_P(, FrameRateGpuCanvasInternalTest, ::testing::Values( kInternal | kHasRedirect | kUseGpu, kInternal | kHasRedirect | kUseGpu | kDisableVsync, kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu, kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu | kDisableVsync)); INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(fireflies) INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(FishIE) INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(speedreading) } // namespace <commit_msg>Disable fishbowl framerate test to turn GPU bots green.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <map> #include "base/command_line.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_number_conversions.h" #include "base/test/test_timeouts.h" #include "base/test/trace_event_analyzer.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/automation_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/javascript_test_util.h" #include "chrome/test/ui/ui_perf_test.h" #include "net/base/net_util.h" #include "ui/gfx/gl/gl_implementation.h" #include "ui/gfx/gl/gl_switches.h" namespace { enum FrameRateTestFlags { kUseGpu = 1 << 0, // Only execute test if --enable-gpu, and verify // that test ran on GPU. This is required for // tests that run on GPU. kForceGpuComposited = 1 << 1, // Force the test to use the compositor. kDisableVsync = 1 << 2, // Do not limit framerate to vertical refresh. // when on GPU, nor to 60hz when not on GPU. kUseReferenceBuild = 1 << 3, // Run test using the reference chrome build. kInternal = 1 << 4, // Test uses internal test data. kHasRedirect = 1 << 5, // Test page contains an HTML redirect. }; class FrameRateTest : public UIPerfTest , public ::testing::WithParamInterface<int> { public: FrameRateTest() { show_window_ = true; dom_automation_enabled_ = true; } bool HasFlag(FrameRateTestFlags flag) const { return (GetParam() & flag) == flag; } bool IsGpuAvailable() const { return CommandLine::ForCurrentProcess()->HasSwitch("enable-gpu"); } std::string GetSuffixForTestFlags() { std::string suffix; if (HasFlag(kForceGpuComposited)) suffix += "_comp"; if (HasFlag(kUseGpu)) suffix += "_gpu"; if (HasFlag(kDisableVsync)) suffix += "_novsync"; if (HasFlag(kUseReferenceBuild)) suffix += "_ref"; return suffix; } virtual FilePath GetDataPath(const std::string& name) { // Make sure the test data is checked out. FilePath test_path; PathService::Get(chrome::DIR_TEST_DATA, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("perf")); test_path = test_path.Append(FILE_PATH_LITERAL("frame_rate")); if (HasFlag(kInternal)) { test_path = test_path.Append(FILE_PATH_LITERAL("private")); } else { test_path = test_path.Append(FILE_PATH_LITERAL("content")); } test_path = test_path.AppendASCII(name); return test_path; } virtual void SetUp() { if (HasFlag(kUseReferenceBuild)) UseReferenceBuild(); // Turn on chrome.Interval to get higher-resolution timestamps on frames. launch_arguments_.AppendSwitch(switches::kEnableBenchmarking); // Required additional argument to make the kEnableBenchmarking switch work. launch_arguments_.AppendSwitch(switches::kEnableStatsTable); // UI tests boot up render views starting from about:blank. This causes // the renderer to start up thinking it cannot use the GPU. To work // around that, and allow the frame rate test to use the GPU, we must // pass kAllowWebUICompositing. launch_arguments_.AppendSwitch(switches::kAllowWebUICompositing); // Some of the tests may launch http requests through JSON or AJAX // which causes a security error (cross domain request) when the page // is loaded from the local file system ( file:// ). The following switch // fixes that error. launch_arguments_.AppendSwitch(switches::kAllowFileAccessFromFiles); if (!HasFlag(kUseGpu)) { launch_arguments_.AppendSwitch(switches::kDisableAcceleratedCompositing); launch_arguments_.AppendSwitch(switches::kDisableExperimentalWebGL); launch_arguments_.AppendSwitch(switches::kDisableAccelerated2dCanvas); } else { // This switch is required for enabling the accelerated 2d canvas on // Chrome versions prior to Chrome 15, which may be the case for the // reference build. launch_arguments_.AppendSwitch(switches::kEnableAccelerated2dCanvas); } if (HasFlag(kDisableVsync)) launch_arguments_.AppendSwitch(switches::kDisableGpuVsync); UIPerfTest::SetUp(); } bool DidRunOnGpu(const std::string& json_events) { using namespace trace_analyzer; // Check trace for GPU accleration. scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events)); gfx::GLImplementation gl_impl = gfx::kGLImplementationNone; const TraceEvent* gpu_event = analyzer->FindOneEvent( Query(EVENT_NAME) == Query::String("SwapBuffers") && Query(EVENT_HAS_NUMBER_ARG, "GLImpl")); if (gpu_event) gl_impl = static_cast<gfx::GLImplementation>( gpu_event->GetKnownArgAsInt("GLImpl")); return (gl_impl == gfx::kGLImplementationDesktopGL || gl_impl == gfx::kGLImplementationEGLGLES2); } void RunTest(const std::string& name) { if (HasFlag(kUseGpu) && !IsGpuAvailable()) { printf("Test skipped: requires gpu. Pass --enable-gpu on the command " "line if use of GPU is desired.\n"); return; } // Verify flag combinations. ASSERT_TRUE(HasFlag(kUseGpu) || !HasFlag(kForceGpuComposited)); ASSERT_TRUE(!HasFlag(kUseGpu) || IsGpuAvailable()); FilePath test_path = GetDataPath(name); ASSERT_TRUE(file_util::DirectoryExists(test_path)) << "Missing test directory: " << test_path.value(); test_path = test_path.Append(FILE_PATH_LITERAL("test.html")); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); // TODO(jbates): remove this check when ref builds are updated. if (!HasFlag(kUseReferenceBuild)) ASSERT_TRUE(automation()->BeginTracing("test_gpu")); if (HasFlag(kHasRedirect)) { // If the test file is known to contain an html redirect, we must block // until the second navigation is complete and reacquire the active tab // in order to avoid a race condition. // If the following assertion is triggered due to a timeout, it is // possible that the current test does not re-direct and therefore should // not have the kHasRedirect flag turned on. ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURLBlockUntilNavigationsComplete( net::FilePathToFileURL(test_path), 2)); tab = GetActiveTab(); ASSERT_TRUE(tab.get()); } else { ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(net::FilePathToFileURL(test_path))); } // Block until initialization completes // If the following assertion fails intermittently, it could be due to a // race condition caused by an html redirect. If that is the case, verify // that flag kHasRedirect is enabled for the current test. ASSERT_TRUE(WaitUntilJavaScriptCondition( tab, L"", L"window.domAutomationController.send(__initialized);", TestTimeouts::large_test_timeout_ms())); if (HasFlag(kForceGpuComposited)) { ASSERT_TRUE(tab->NavigateToURLAsync( GURL("javascript:__make_body_composited();"))); } // Start the tests. ASSERT_TRUE(tab->NavigateToURLAsync(GURL("javascript:__start_all();"))); // Block until the tests completes. ASSERT_TRUE(WaitUntilJavaScriptCondition( tab, L"", L"window.domAutomationController.send(!__running_all);", TestTimeouts::large_test_timeout_ms())); // TODO(jbates): remove this check when ref builds are updated. if (!HasFlag(kUseReferenceBuild)) { std::string json_events; ASSERT_TRUE(automation()->EndTracing(&json_events)); bool did_run_on_gpu = DidRunOnGpu(json_events); bool expect_gpu = HasFlag(kUseGpu); EXPECT_EQ(expect_gpu, did_run_on_gpu); } // Read out the results. std::wstring json; ASSERT_TRUE(tab->ExecuteAndExtractString( L"", L"window.domAutomationController.send(" L"JSON.stringify(__calc_results_total()));", &json)); std::map<std::string, std::string> results; ASSERT_TRUE(JsonDictionaryToMap(WideToUTF8(json), &results)); ASSERT_TRUE(results.find("mean") != results.end()); ASSERT_TRUE(results.find("sigma") != results.end()); ASSERT_TRUE(results.find("gestures") != results.end()); ASSERT_TRUE(results.find("means") != results.end()); ASSERT_TRUE(results.find("sigmas") != results.end()); std::string trace_name = "interval" + GetSuffixForTestFlags(); printf("GESTURES %s: %s= [%s] [%s] [%s]\n", name.c_str(), trace_name.c_str(), results["gestures"].c_str(), results["means"].c_str(), results["sigmas"].c_str()); std::string mean_and_error = results["mean"] + "," + results["sigma"]; PrintResultMeanAndError(name, "", trace_name, mean_and_error, "frames-per-second", true); } }; // Must use a different class name to avoid test instantiation conflicts // with FrameRateTest. An alias is good enough. The alias names must match // the pattern FrameRate*Test* for them to get picked up by the test bots. typedef FrameRateTest FrameRateCompositingTest; // Tests that trigger compositing with a -webkit-translateZ(0) #define FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(content) \ TEST_P(FrameRateCompositingTest, content) { \ RunTest(#content); \ } INSTANTIATE_TEST_CASE_P(, FrameRateCompositingTest, ::testing::Values( 0, kUseGpu | kForceGpuComposited, kUseReferenceBuild, kUseReferenceBuild | kUseGpu | kForceGpuComposited)); FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(blank); FRAME_RATE_TEST_WITH_AND_WITHOUT_ACCELERATED_COMPOSITING(googleblog); typedef FrameRateTest FrameRateNoVsyncCanvasInternalTest; // Tests for animated 2D canvas content with and without disabling vsync #define INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(content) \ TEST_P(FrameRateNoVsyncCanvasInternalTest, content) { \ RunTest(#content); \ } INSTANTIATE_TEST_CASE_P(, FrameRateNoVsyncCanvasInternalTest, ::testing::Values( kInternal | kHasRedirect, kInternal | kHasRedirect | kUseGpu, kInternal | kHasRedirect | kUseGpu | kDisableVsync, kUseReferenceBuild | kInternal | kHasRedirect, kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu, kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu | kDisableVsync)); INTERNAL_FRAME_RATE_TEST_CANVAS_WITH_AND_WITHOUT_NOVSYNC(DISABLED_fishbowl) typedef FrameRateTest FrameRateGpuCanvasInternalTest; // Tests for animated 2D canvas content to be tested only with GPU // acceleration. // tests are run with and without Vsync #define INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(content) \ TEST_P(FrameRateGpuCanvasInternalTest, content) { \ RunTest(#content); \ } INSTANTIATE_TEST_CASE_P(, FrameRateGpuCanvasInternalTest, ::testing::Values( kInternal | kHasRedirect | kUseGpu, kInternal | kHasRedirect | kUseGpu | kDisableVsync, kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu, kUseReferenceBuild | kInternal | kHasRedirect | kUseGpu | kDisableVsync)); INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(fireflies) INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(FishIE) INTERNAL_FRAME_RATE_TEST_CANVAS_GPU(speedreading) } // namespace <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/openglqt/canvasqopenglwidget.h> #include <inviwo/core/datastructures/image/layerram.h> #include <inviwo/core/common/inviwoapplication.h> #include <modules/opengl/openglcapabilities.h> #include <warn/push> #include <warn/ignore/all> #include <QOpenGLContext> #include <QResizeEvent> #include <QApplication> #include <warn/pop> namespace inviwo { CanvasQOpenGLWidget::CanvasQOpenGLWidget(QWidget* parent, size2_t dim) : QOpenGLWidget(parent), CanvasGL(dim) { setFocusPolicy(Qt::StrongFocus); grabGesture(Qt::PanGesture); grabGesture(Qt::PinchGesture); // Needed in order for initializeGL to be called and we rely on // the context being initialized after construction. QResizeEvent event(QSize(dim.x, dim.y), QSize(width(), height())); QOpenGLWidget::resizeEvent(&event); } void CanvasQOpenGLWidget::defineDefaultContextFormat() { if (QOpenGLContext::globalShareContext()) { std::string preferProfile = OpenGLCapabilities::getPreferredProfile(); auto gsc = QOpenGLContext::globalShareContext(); if (preferProfile == "core") { gsc->format().setProfile(QSurfaceFormat::CoreProfile); } else if (preferProfile == "compatibility") { gsc->format().setProfile(QSurfaceFormat::CompatibilityProfile); } } } void CanvasQOpenGLWidget::activate() { makeCurrent(); } void CanvasQOpenGLWidget::initializeGL() { OpenGLCapabilities::initializeGLEW(); // QOpenGLWidget docs: // There is no need to call makeCurrent() because this has already been done // when this function is called. // Note however that the framebuffer is not yet available at this stage, // so do not issue draw calls from here. // Defer such calls to paintGL() instead. QOpenGLWidget::initializeGL(); } void CanvasQOpenGLWidget::glSwapBuffers() { // Do nothing: // QOpenGLWidget will swap buffers after paintGL and we are calling this from CanvasGL::update() // QOpenGLWidget docs: // triggering a buffer swap just for the QOpenGLWidget is not possible since there is no real, // onscreen native surface for it. // Instead, it is up to the widget stack to manage composition and buffer swaps on the gui thread. // When a thread is done updating the framebuffer, call update() on the GUI/main thread to schedule composition. } void CanvasQOpenGLWidget::update() { QOpenGLWidget::update(); // this will trigger a paint event. } void CanvasQOpenGLWidget::paintGL() { CanvasGL::update(); } void CanvasQOpenGLWidget::resize(size2_t size) { // this should trigger a resize event. QOpenGLWidget::resize(size.x, size.y); } Canvas::ContextID CanvasQOpenGLWidget::activeContext() const { return static_cast<ContextID>(QOpenGLContext::currentContext()); } Canvas::ContextID CanvasQOpenGLWidget::contextId() const { return static_cast<ContextID>(context()); } void CanvasQOpenGLWidget::resizeEvent(QResizeEvent* event) { if (event->spontaneous()) { return; } setUpdatesEnabled(false); util::OnScopeExit enable([&]() { setUpdatesEnabled(true); }); CanvasGL::resize(uvec2(event->size().width(), event->size().height())); QOpenGLWidget::resizeEvent(event); } void CanvasQOpenGLWidget::releaseContext() { doneCurrent(); context()->create(); context()->moveToThread(QApplication::instance()->thread()); } } // namespace inviwo<commit_msg>OpenGLQt: Use latest GL version<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/openglqt/canvasqopenglwidget.h> #include <inviwo/core/datastructures/image/layerram.h> #include <inviwo/core/common/inviwoapplication.h> #include <modules/opengl/openglcapabilities.h> #include <warn/push> #include <warn/ignore/all> #include <QOpenGLContext> #include <QResizeEvent> #include <QApplication> #include <warn/pop> namespace inviwo { CanvasQOpenGLWidget::CanvasQOpenGLWidget(QWidget* parent, size2_t dim) : QOpenGLWidget(parent), CanvasGL(dim) { setFocusPolicy(Qt::StrongFocus); grabGesture(Qt::PanGesture); grabGesture(Qt::PinchGesture); // Needed in order for initializeGL to be called and we rely on // the context being initialized after construction. QResizeEvent event(QSize(dim.x, dim.y), QSize(width(), height())); QOpenGLWidget::resizeEvent(&event); } void CanvasQOpenGLWidget::defineDefaultContextFormat() { if (QOpenGLContext::globalShareContext()) { std::string preferProfile = OpenGLCapabilities::getPreferredProfile(); auto gsc = QOpenGLContext::globalShareContext(); // We want the latest possible version gsc->format().setMajorVersion(10); if (preferProfile == "core") { gsc->format().setProfile(QSurfaceFormat::CoreProfile); } else if (preferProfile == "compatibility") { gsc->format().setProfile(QSurfaceFormat::CompatibilityProfile); } } } void CanvasQOpenGLWidget::activate() { makeCurrent(); } void CanvasQOpenGLWidget::initializeGL() { OpenGLCapabilities::initializeGLEW(); // QOpenGLWidget docs: // There is no need to call makeCurrent() because this has already been done // when this function is called. // Note however that the framebuffer is not yet available at this stage, // so do not issue draw calls from here. // Defer such calls to paintGL() instead. QOpenGLWidget::initializeGL(); } void CanvasQOpenGLWidget::glSwapBuffers() { // Do nothing: // QOpenGLWidget will swap buffers after paintGL and we are calling this from CanvasGL::update() // QOpenGLWidget docs: // triggering a buffer swap just for the QOpenGLWidget is not possible since there is no real, // onscreen native surface for it. // Instead, it is up to the widget stack to manage composition and buffer swaps on the gui thread. // When a thread is done updating the framebuffer, call update() on the GUI/main thread to schedule composition. } void CanvasQOpenGLWidget::update() { QOpenGLWidget::update(); // this will trigger a paint event. } void CanvasQOpenGLWidget::paintGL() { CanvasGL::update(); } void CanvasQOpenGLWidget::resize(size2_t size) { // this should trigger a resize event. QOpenGLWidget::resize(size.x, size.y); } Canvas::ContextID CanvasQOpenGLWidget::activeContext() const { return static_cast<ContextID>(QOpenGLContext::currentContext()); } Canvas::ContextID CanvasQOpenGLWidget::contextId() const { return static_cast<ContextID>(context()); } void CanvasQOpenGLWidget::resizeEvent(QResizeEvent* event) { if (event->spontaneous()) { return; } setUpdatesEnabled(false); util::OnScopeExit enable([&]() { setUpdatesEnabled(true); }); CanvasGL::resize(uvec2(event->size().width(), event->size().height())); QOpenGLWidget::resizeEvent(event); } void CanvasQOpenGLWidget::releaseContext() { doneCurrent(); context()->create(); context()->moveToThread(QApplication::instance()->thread()); } } // namespace inviwo<|endoftext|>